Upload full round2 9000-step checkpoint
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +8 -0
- checkpoints/r2/shuffle/baseline/step9000/README.md +49 -0
- checkpoints/r2/shuffle/baseline/step9000/_CHECKPOINT_METADATA +1 -0
- checkpoints/r2/shuffle/baseline/step9000/assets/franka/norm_stats.json +88 -0
- checkpoints/r2/shuffle/baseline/step9000/assets/policy_metadata.json +49 -0
- checkpoints/r2/shuffle/baseline/step9000/checkpoint_info.json +8 -0
- checkpoints/r2/shuffle/baseline/step9000/code/LICENSE +201 -0
- checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/examples/robomme/picmem_phase_a_rollout.py +1018 -0
- checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_baseline.py +625 -0
- checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_execution.py +113 -0
- checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_history.py +258 -0
- checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_matrix.py +114 -0
- checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_partial.py +226 -0
- checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_release.py +420 -0
- checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_round.py +103 -0
- checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_round_evaluate.py +147 -0
- checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_round_finish.py +97 -0
- checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_round_run.py +249 -0
- checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_status_data.py +227 -0
- checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_status_labels.py +48 -0
- checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_status_review.py +55 -0
- checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/manifest.json +182 -0
- checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/scripts/picmem_phase_a_checkpoint_probe.py +528 -0
- checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/scripts/picmem_phase_a_dataset_smoke.py +536 -0
- checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/scripts/picmem_phase_a_full_state_smoke.py +919 -0
- checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/scripts/picmem_phase_a_full_state_train.py +347 -0
- checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/models/config/robomme/perceptual-picmem-phase-a-modul.yaml +53 -0
- checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/models/config/robomme/perceptual-picmem-transition-v1-modul.yaml +73 -0
- checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/models/config/robomme/perceptual-picmem-v2-stage4-hybrid-modul.yaml +54 -0
- checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/models/representation/phase_a_reader.py +328 -0
- checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/models/representation/transition_status.py +288 -0
- checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/policies/picmem_phase_a_rollout.py +563 -0
- checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/policies/semantic_transition_runtime.py +1236 -0
- checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/shared/mem_buffer.py +635 -0
- checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/training/dataset.py +501 -0
- checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/training/picmem_phase_a.py +201 -0
- checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/training/picmem_phase_a_full_state.py +1936 -0
- checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/training/picmem_phase_a_reader.py +717 -0
- checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/training/picmem_phase_a_runtime.py +176 -0
- checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/training/semantic_transition_reader.py +260 -0
- checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/transition_status_manifest.json +67 -0
- checkpoints/r2/shuffle/baseline/step9000/code/pyproject.toml +128 -0
- checkpoints/r2/shuffle/baseline/step9000/code/robomme/LICENSE +201 -0
- checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/__init__.py +1 -0
- checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/action_chunk_broker.py +50 -0
- checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/base_policy.py +12 -0
- checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/image_tools.py +58 -0
- checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/image_tools_test.py +37 -0
- checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/msgpack_numpy.py +57 -0
- checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/msgpack_numpy_test.py +45 -0
.gitattributes
CHANGED
|
@@ -720,3 +720,11 @@ checkpoints/r2/shuffle/baseline/step8000/resume_state/ocdbt.process_0/d/36f39fcd
|
|
| 720 |
checkpoints/r2/shuffle/baseline/step8000/resume_state/ocdbt.process_0/d/4bbd32adf2b7336cadcb18bb52047a5c filter=lfs diff=lfs merge=lfs -text
|
| 721 |
checkpoints/r2/shuffle/baseline/step8000/resume_state/ocdbt.process_0/d/8e1c9a3cea3f74fc1d20691e046245a0 filter=lfs diff=lfs merge=lfs -text
|
| 722 |
checkpoints/r2/shuffle/baseline/step8000/resume_state/ocdbt.process_0/d/e43002d36ecc20bd162287f94d990f41 filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 720 |
checkpoints/r2/shuffle/baseline/step8000/resume_state/ocdbt.process_0/d/4bbd32adf2b7336cadcb18bb52047a5c filter=lfs diff=lfs merge=lfs -text
|
| 721 |
checkpoints/r2/shuffle/baseline/step8000/resume_state/ocdbt.process_0/d/8e1c9a3cea3f74fc1d20691e046245a0 filter=lfs diff=lfs merge=lfs -text
|
| 722 |
checkpoints/r2/shuffle/baseline/step8000/resume_state/ocdbt.process_0/d/e43002d36ecc20bd162287f94d990f41 filter=lfs diff=lfs merge=lfs -text
|
| 723 |
+
checkpoints/r2/shuffle/baseline/step9000/params/ocdbt.process_0/d/63d7385a0282182e209c36f5009987ac filter=lfs diff=lfs merge=lfs -text
|
| 724 |
+
checkpoints/r2/shuffle/baseline/step9000/params/ocdbt.process_0/d/a06069890aa4d04c31c910f8f5f67227 filter=lfs diff=lfs merge=lfs -text
|
| 725 |
+
checkpoints/r2/shuffle/baseline/step9000/params/ocdbt.process_0/d/aa7bed65eb2f1580ba7e32c788dbcba6 filter=lfs diff=lfs merge=lfs -text
|
| 726 |
+
checkpoints/r2/shuffle/baseline/step9000/resume_state/ocdbt.process_0/d/0e636c96c48077912e928b8466b48ebe filter=lfs diff=lfs merge=lfs -text
|
| 727 |
+
checkpoints/r2/shuffle/baseline/step9000/resume_state/ocdbt.process_0/d/2c882f98deed4eb7646b550ec4454166 filter=lfs diff=lfs merge=lfs -text
|
| 728 |
+
checkpoints/r2/shuffle/baseline/step9000/resume_state/ocdbt.process_0/d/7e7c067be6fc3ab0c386dcca415e7c32 filter=lfs diff=lfs merge=lfs -text
|
| 729 |
+
checkpoints/r2/shuffle/baseline/step9000/resume_state/ocdbt.process_0/d/b03ff5c988ddc142ab70b736239ecb93 filter=lfs diff=lfs merge=lfs -text
|
| 730 |
+
checkpoints/r2/shuffle/baseline/step9000/resume_state/ocdbt.process_0/d/e9dbd5f3c1ed092c0df1a8580e8520f2 filter=lfs diff=lfs merge=lfs -text
|
checkpoints/r2/shuffle/baseline/step9000/README.md
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
tags: [robotics, pi05, franka, lora]
|
| 3 |
+
---
|
| 4 |
+
|
| 5 |
+
# pi05-shuffle-baseline-lora-gbs4-pgb1-gpu4-r2-step9000
|
| 6 |
+
|
| 7 |
+
Second-round π0.5 LoRA fine-tuning for **shuffle**, checkpoint **9,000**.
|
| 8 |
+
Trained locally on **4 RTX A6000 GPUs**, **global batch 4**, **per-GPU batch 1**,
|
| 9 |
+
without gradient accumulation. This checkpoint represents **36,000 sample exposures**;
|
| 10 |
+
the run targets **12,500 optimizer updates / 50,000 sample exposures**.
|
| 11 |
+
Checkpoints are saved every **1,000** updates and at the final **12,500**.
|
| 12 |
+
Steps **5,000**, **10,000**, and **12,500** have standalone model repositories.
|
| 13 |
+
Other complete checkpoints are retained in the
|
| 14 |
+
[backup archive](https://huggingface.co/datasets/fm-dev/pi05-checkpoint-backups/tree/main/checkpoints/r2)
|
| 15 |
+
under `task/method/stepN/` with the same loading files and full resume state.
|
| 16 |
+
`r2` keeps these artifacts separate from the original 6,250-step experiment.
|
| 17 |
+
|
| 18 |
+
Warmup: **250** updates to **5e-5**; cosine decay to **5e-6** at step **12,500**.
|
| 19 |
+
EMA: **0.999^4 = 0.996005996001**. AdamW, LoRA rank32, seed42.
|
| 20 |
+
Full settings are in `training_config.json`.
|
| 21 |
+
|
| 22 |
+
No-history baseline: current base/wrist images, state and task instruction.
|
| 23 |
+
|
| 24 |
+
Only robot execution rows supervise actions. Demonstration images, features and
|
| 25 |
+
original episode/frame coordinates remain available as history; execution start
|
| 26 |
+
does not reset the visual history. Episode splits and normalization use the
|
| 27 |
+
training split only. The recorded Cartesian end-effector/tool pose convention
|
| 28 |
+
must match the collection controller; do not apply an extra tool/flange offset.
|
| 29 |
+
Outputs have shape `(20,8)`: absolute xyz, unit XYZW quaternion in the positive-qx
|
| 30 |
+
chart, and gripper command in [0,1]. Numeric state/actions use STD normalization;
|
| 31 |
+
state tokens use a separate bounded train-q01/q99 view.
|
| 32 |
+
|
| 33 |
+
Unknown action components remain NaN/false in the training dataset and are masked
|
| 34 |
+
in both flow conditioning and loss. Entirely unsupervised components:
|
| 35 |
+
**[7]**. In particular, Shuffle's
|
| 36 |
+
gripper output has no command supervision and must not be interpreted as learned
|
| 37 |
+
gripper control. Button Order has only limited verified closed-command labels.
|
| 38 |
+
|
| 39 |
+
This repository includes EMA serving weights, normalization/history assets,
|
| 40 |
+
inference source, exact dependency versions, and full non-EMA/optimizer/RNG/sampler
|
| 41 |
+
resume state. Intermediate publication is not a policy-quality evaluation.
|
| 42 |
+
Offline evaluation, when included, does not establish real-robot success rate.
|
| 43 |
+
|
| 44 |
+
Load with `from load_model import load, observe; policy = load()` from this bundle.
|
| 45 |
+
For history models call `observe(policy, base_rgb, state)` for every observed frame,
|
| 46 |
+
including demonstrations, and reset between episodes. Status-D additionally requires
|
| 47 |
+
explicit `history_keyframe_index` (an observed frame or None), `current_subgoal`,
|
| 48 |
+
and causal `transition_context_*` inputs in `policy.infer(...)`; its output includes
|
| 49 |
+
`transition_status`. Use the exported Writer schedule and matching control frame.
|
checkpoints/r2/shuffle/baseline/step9000/_CHECKPOINT_METADATA
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 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": {}}
|
checkpoints/r2/shuffle/baseline/step9000/assets/franka/norm_stats.json
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"norm_stats": {
|
| 3 |
+
"state": {
|
| 4 |
+
"mean": [
|
| 5 |
+
0.43004271388053894,
|
| 6 |
+
0.01438639685511589,
|
| 7 |
+
0.15972454845905304,
|
| 8 |
+
0.8642361760139465,
|
| 9 |
+
-0.4695635437965393,
|
| 10 |
+
-0.005614287685602903,
|
| 11 |
+
0.003596301656216383,
|
| 12 |
+
0.0026823587249964476
|
| 13 |
+
],
|
| 14 |
+
"std": [
|
| 15 |
+
0.025760769844055176,
|
| 16 |
+
0.13458988070487976,
|
| 17 |
+
0.09128014743328094,
|
| 18 |
+
0.08076709508895874,
|
| 19 |
+
0.14975696802139282,
|
| 20 |
+
0.04439425468444824,
|
| 21 |
+
0.04049962759017944,
|
| 22 |
+
0.000042953066440531984
|
| 23 |
+
],
|
| 24 |
+
"q01": [
|
| 25 |
+
0.35660686701536176,
|
| 26 |
+
-0.19194583505392074,
|
| 27 |
+
0.04546925485134125,
|
| 28 |
+
0.6543013167381286,
|
| 29 |
+
-0.7548727107048034,
|
| 30 |
+
-0.11300075851380825,
|
| 31 |
+
-0.06998954810202122,
|
| 32 |
+
0.0026348750106990337
|
| 33 |
+
],
|
| 34 |
+
"q99": [
|
| 35 |
+
0.49797759830951693,
|
| 36 |
+
0.2586104992032051,
|
| 37 |
+
0.3494038268923759,
|
| 38 |
+
0.9951327449083328,
|
| 39 |
+
-0.07059624232351777,
|
| 40 |
+
0.07216263540089134,
|
| 41 |
+
0.09449841350317002,
|
| 42 |
+
0.002790587111376226
|
| 43 |
+
]
|
| 44 |
+
},
|
| 45 |
+
"actions": {
|
| 46 |
+
"mean": [
|
| 47 |
+
0.42990756034851074,
|
| 48 |
+
0.015801655128598213,
|
| 49 |
+
0.1326005756855011,
|
| 50 |
+
0.8696262240409851,
|
| 51 |
+
-0.4551904797554016,
|
| 52 |
+
0.0005095235537737608,
|
| 53 |
+
0.0030130352824926376,
|
| 54 |
+
0.0
|
| 55 |
+
],
|
| 56 |
+
"std": [
|
| 57 |
+
0.02352166548371315,
|
| 58 |
+
0.14162100851535797,
|
| 59 |
+
0.07555239647626877,
|
| 60 |
+
0.08528122305870056,
|
| 61 |
+
0.15965595841407776,
|
| 62 |
+
0.04530269280076027,
|
| 63 |
+
0.041560959070920944,
|
| 64 |
+
1.0
|
| 65 |
+
],
|
| 66 |
+
"q01": [
|
| 67 |
+
0.3335464817285538,
|
| 68 |
+
-0.19901523888111114,
|
| 69 |
+
0.0370797111839056,
|
| 70 |
+
0.6137884080410003,
|
| 71 |
+
-0.7878426039218902,
|
| 72 |
+
-0.24762430131435395,
|
| 73 |
+
-0.08285837218165397,
|
| 74 |
+
0.0
|
| 75 |
+
],
|
| 76 |
+
"q99": [
|
| 77 |
+
0.4879460096359252,
|
| 78 |
+
0.25839828968048095,
|
| 79 |
+
0.337459173798561,
|
| 80 |
+
0.9956820118427276,
|
| 81 |
+
-0.06469799026846947,
|
| 82 |
+
0.08956875860691063,
|
| 83 |
+
0.2402494329214096,
|
| 84 |
+
0.0
|
| 85 |
+
]
|
| 86 |
+
}
|
| 87 |
+
}
|
| 88 |
+
}
|
checkpoints/r2/shuffle/baseline/step9000/assets/policy_metadata.json
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"dataset": "/data/benchmarks/franka-demos/status-d-training/datasets/shuffle",
|
| 3 |
+
"representation": "absolute recorded end-effector xyz, unit xyzw with qx positive, commanded gripper open in [0,1]",
|
| 4 |
+
"gripper": "full-rate Joy edges matched to saved server requests; unknown=NaN/mask false; no bootstrap",
|
| 5 |
+
"run_purpose": "fine-tuning",
|
| 6 |
+
"target_steps": 12500,
|
| 7 |
+
"save_interval": 1000,
|
| 8 |
+
"task": "shuffle",
|
| 9 |
+
"prompt": "After the cups are shuffled, press the button next to the cup hiding the cube.",
|
| 10 |
+
"partial_action_supervision": true,
|
| 11 |
+
"unsupervised_action_components": [
|
| 12 |
+
7
|
| 13 |
+
],
|
| 14 |
+
"current_state_tokens": "train q01/q99 bounded [-1,1], constant spans map to zero",
|
| 15 |
+
"training_recipe": {
|
| 16 |
+
"method": "LoRA + Cartesian projections + optional history modules",
|
| 17 |
+
"gpus": 4,
|
| 18 |
+
"global_batch_size": 4,
|
| 19 |
+
"fsdp_devices": 1,
|
| 20 |
+
"gradient_accumulation": 1,
|
| 21 |
+
"action_dim": 8,
|
| 22 |
+
"action_horizon": 20,
|
| 23 |
+
"max_token_len": 128,
|
| 24 |
+
"ema_decay": 0.996005996001,
|
| 25 |
+
"reference_steps": 50000,
|
| 26 |
+
"reference_global_batch": 1,
|
| 27 |
+
"reference_ema_decay": 0.999,
|
| 28 |
+
"reference_warmup_steps": 1000,
|
| 29 |
+
"sample_exposures": 50000,
|
| 30 |
+
"warmup_steps": 250,
|
| 31 |
+
"decay_steps": 12500,
|
| 32 |
+
"peak_lr": 5e-05,
|
| 33 |
+
"decay_lr": 5e-06
|
| 34 |
+
},
|
| 35 |
+
"training_round": 2,
|
| 36 |
+
"training_setting": "baseline",
|
| 37 |
+
"action_supervision": "execution frames only; demonstration frames retained as visual history",
|
| 38 |
+
"checkpoint_retention": {
|
| 39 |
+
"save_interval": 1000,
|
| 40 |
+
"local_latest": 3,
|
| 41 |
+
"milestones": [
|
| 42 |
+
5000,
|
| 43 |
+
10000,
|
| 44 |
+
12500
|
| 45 |
+
],
|
| 46 |
+
"remote": "all"
|
| 47 |
+
},
|
| 48 |
+
"gpu_allocator": "platform"
|
| 49 |
+
}
|
checkpoints/r2/shuffle/baseline/step9000/checkpoint_info.json
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"optimizer_step": 9000,
|
| 3 |
+
"target_steps": 12500,
|
| 4 |
+
"sample_expos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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Apache License
|
| 2 |
+
Version 2.0, January 2004
|
| 3 |
+
http://www.apache.org/licenses/
|
| 4 |
+
|
| 5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 6 |
+
|
| 7 |
+
1. Definitions.
|
| 8 |
+
|
| 9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 11 |
+
|
| 12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 13 |
+
the copyright owner that is granting the License.
|
| 14 |
+
|
| 15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 16 |
+
other entities that control, are controlled by, or are under common
|
| 17 |
+
control with that entity. For the purposes of this definition,
|
| 18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 19 |
+
direction or management of such entity, whether by contract or
|
| 20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 22 |
+
|
| 23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 24 |
+
exercising permissions granted by this License.
|
| 25 |
+
|
| 26 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 27 |
+
including but not limited to software source code, documentation
|
| 28 |
+
source, and configuration files.
|
| 29 |
+
|
| 30 |
+
"Object" form shall mean any form resulting from mechanical
|
| 31 |
+
transformation or translation of a Source form, including but
|
| 32 |
+
not limited to compiled object code, generated documentation,
|
| 33 |
+
and conversions to other media types.
|
| 34 |
+
|
| 35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 36 |
+
Object form, made available under the License, as indicated by a
|
| 37 |
+
copyright notice that is included in or attached to the work
|
| 38 |
+
(an example is provided in the Appendix below).
|
| 39 |
+
|
| 40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 41 |
+
form, that is based on (or derived from) the Work and for which the
|
| 42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 44 |
+
of this License, Derivative Works shall not include works that remain
|
| 45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 46 |
+
the Work and Derivative Works thereof.
|
| 47 |
+
|
| 48 |
+
"Contribution" shall mean any work of authorship, including
|
| 49 |
+
the original version of the Work and any modifications or additions
|
| 50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 54 |
+
means any form of electronic, verbal, or written communication sent
|
| 55 |
+
to the Licensor or its representatives, including but not limited to
|
| 56 |
+
communication on electronic mailing lists, source code control systems,
|
| 57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 59 |
+
excluding communication that is conspicuously marked or otherwise
|
| 60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 61 |
+
|
| 62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 64 |
+
subsequently incorporated within the Work.
|
| 65 |
+
|
| 66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 71 |
+
Work and such Derivative Works in Source or Object form.
|
| 72 |
+
|
| 73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 76 |
+
(except as stated in this section) patent license to make, have made,
|
| 77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 78 |
+
where such license applies only to those patent claims licensable
|
| 79 |
+
by such Contributor that are necessarily infringed by their
|
| 80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 82 |
+
institute patent litigation against any entity (including a
|
| 83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 84 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 85 |
+
or contributory patent infringement, then any patent licenses
|
| 86 |
+
granted to You under this License for that Work shall terminate
|
| 87 |
+
as of the date such litigation is filed.
|
| 88 |
+
|
| 89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 90 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 91 |
+
modifications, and in Source or Object form, provided that You
|
| 92 |
+
meet the following conditions:
|
| 93 |
+
|
| 94 |
+
(a) You must give any other recipients of the Work or
|
| 95 |
+
Derivative Works a copy of this License; and
|
| 96 |
+
|
| 97 |
+
(b) You must cause any modified files to carry prominent notices
|
| 98 |
+
stating that You changed the files; and
|
| 99 |
+
|
| 100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 101 |
+
that You distribute, all copyright, patent, trademark, and
|
| 102 |
+
attribution notices from the Source form of the Work,
|
| 103 |
+
excluding those notices that do not pertain to any part of
|
| 104 |
+
the Derivative Works; and
|
| 105 |
+
|
| 106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 107 |
+
distribution, then any Derivative Works that You distribute must
|
| 108 |
+
include a readable copy of the attribution notices contained
|
| 109 |
+
within such NOTICE file, excluding those notices that do not
|
| 110 |
+
pertain to any part of the Derivative Works, in at least one
|
| 111 |
+
of the following places: within a NOTICE text file distributed
|
| 112 |
+
as part of the Derivative Works; within the Source form or
|
| 113 |
+
documentation, if provided along with the Derivative Works; or,
|
| 114 |
+
within a display generated by the Derivative Works, if and
|
| 115 |
+
wherever such third-party notices normally appear. The contents
|
| 116 |
+
of the NOTICE file are for informational purposes only and
|
| 117 |
+
do not modify the License. You may add Your own attribution
|
| 118 |
+
notices within Derivative Works that You distribute, alongside
|
| 119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 120 |
+
that such additional attribution notices cannot be construed
|
| 121 |
+
as modifying the License.
|
| 122 |
+
|
| 123 |
+
You may add Your own copyright statement to Your modifications and
|
| 124 |
+
may provide additional or different license terms and conditions
|
| 125 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 126 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 127 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 128 |
+
the conditions stated in this License.
|
| 129 |
+
|
| 130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 132 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 133 |
+
this License, without any additional terms or conditions.
|
| 134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 135 |
+
the terms of any separate license agreement you may have executed
|
| 136 |
+
with Licensor regarding such Contributions.
|
| 137 |
+
|
| 138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 140 |
+
except as required for reasonable and customary use in describing the
|
| 141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 142 |
+
|
| 143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 144 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 147 |
+
implied, including, without limitation, any warranties or conditions
|
| 148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 150 |
+
appropriateness of using or redistributing the Work and assume any
|
| 151 |
+
risks associated with Your exercise of permissions under this License.
|
| 152 |
+
|
| 153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 154 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 155 |
+
unless required by applicable law (such as deliberate and grossly
|
| 156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 157 |
+
liable to You for damages, including any direct, indirect, special,
|
| 158 |
+
incidental, or consequential damages of any character arising as a
|
| 159 |
+
result of this License or out of the use or inability to use the
|
| 160 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 161 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 162 |
+
other commercial damages or losses), even if such Contributor
|
| 163 |
+
has been advised of the possibility of such damages.
|
| 164 |
+
|
| 165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 168 |
+
or other liability obligations and/or rights consistent with this
|
| 169 |
+
License. However, in accepting such obligations, You may act only
|
| 170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 171 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 172 |
+
defend, and hold each Contributor harmless for any liability
|
| 173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 174 |
+
of your accepting any such warranty or additional liability.
|
| 175 |
+
|
| 176 |
+
END OF TERMS AND CONDITIONS
|
| 177 |
+
|
| 178 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 179 |
+
|
| 180 |
+
To apply the Apache License to your work, attach the following
|
| 181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 182 |
+
replaced with your own identifying information. (Don't include
|
| 183 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 184 |
+
comment syntax for the file format. We also recommend that a
|
| 185 |
+
file or class name and description of purpose be included on the
|
| 186 |
+
same "printed page" as the copyright notice for easier
|
| 187 |
+
identification within third-party archives.
|
| 188 |
+
|
| 189 |
+
Copyright [yyyy] [name of copyright owner]
|
| 190 |
+
|
| 191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 192 |
+
you may not use this file except in compliance with the License.
|
| 193 |
+
You may obtain a copy of the License at
|
| 194 |
+
|
| 195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 196 |
+
|
| 197 |
+
Unless required by applicable law or agreed to in writing, software
|
| 198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 200 |
+
See the License for the specific language governing permissions and
|
| 201 |
+
limitations under the License.
|
checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/examples/robomme/picmem_phase_a_rollout.py
ADDED
|
@@ -0,0 +1,1018 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""RoboMME simulator-side producer for the Phase-A evolving-memory rollout.
|
| 2 |
+
|
| 3 |
+
The standard evaluator runs the simulator in a process separate from the
|
| 4 |
+
policy server. This module derives one strict runtime reset from the real
|
| 5 |
+
reset demonstration and emits only newly arrived events from the current
|
| 6 |
+
simulator trajectory. The reset/event envelopes travel inside the existing
|
| 7 |
+
``add_buffer`` request; images and robot states continue to use RoboMME's
|
| 8 |
+
normal buffer wire.
|
| 9 |
+
|
| 10 |
+
This is an explicitly privileged oracle producer for the Phase-A upper bound.
|
| 11 |
+
It does not read a completed Run084 sidecar or any future rollout state.
|
| 12 |
+
Training remains bound to the corrected full Run084 artifact; evaluation is
|
| 13 |
+
bound instead to the pinned simulator episode identity and the exact live
|
| 14 |
+
demonstration prefix.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import math
|
| 20 |
+
from collections.abc import Mapping, Sequence
|
| 21 |
+
from copy import deepcopy
|
| 22 |
+
from dataclasses import dataclass
|
| 23 |
+
from typing import Any
|
| 24 |
+
|
| 25 |
+
import numpy as np
|
| 26 |
+
|
| 27 |
+
from picmem.annotations import annotate_episode_from_steps
|
| 28 |
+
from picmem.memory.contracts import ManagerMode
|
| 29 |
+
from picmem.memory.manager import task_schema_for
|
| 30 |
+
from picmem.provenance.run084 import events_from_sidecar
|
| 31 |
+
from picmem.provenance.runtime_reader import (
|
| 32 |
+
RuntimeReadError,
|
| 33 |
+
build_runtime_event,
|
| 34 |
+
build_runtime_reset,
|
| 35 |
+
build_runtime_source_contract,
|
| 36 |
+
canonical_json_sha256,
|
| 37 |
+
runtime_state_sha256,
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
RUNTIME_BATCH_SCHEMA_VERSION = "picmem_phase_a_rollout_batch_v2"
|
| 41 |
+
RUNTIME_START_SCHEMA_VERSION = "picmem_phase_a_rollout_start_v1"
|
| 42 |
+
RUNTIME_ENVELOPE_SCHEMA_VERSION = "picmem_phase_a_rollout_event_envelope_v1"
|
| 43 |
+
RUNTIME_ACK_SCHEMA_VERSION = "picmem_phase_a_rollout_batch_ack_v1"
|
| 44 |
+
RUNTIME_RECEIPT_SCHEMA_VERSION = "picmem_phase_a_runtime_read_receipt_v3"
|
| 45 |
+
PRODUCER_SCHEMA_VERSION = "picmem_phase_a_robomme_oracle_producer_v1"
|
| 46 |
+
|
| 47 |
+
SUPPORTED_TASKS = frozenset({"MoveCube", "PickXtimes", "VideoPlaceButton", "VideoUnmask"})
|
| 48 |
+
TERMINAL_STATUSES = frozenset({"success", "fail", "timeout", "unknown"})
|
| 49 |
+
GENESIS_BATCH_SHA256 = "0" * 64
|
| 50 |
+
_ACK_FIELDS = frozenset(
|
| 51 |
+
{
|
| 52 |
+
"schema_version",
|
| 53 |
+
"batch_sequence",
|
| 54 |
+
"batch_sha256",
|
| 55 |
+
"duplicate",
|
| 56 |
+
"runtime_receipt",
|
| 57 |
+
}
|
| 58 |
+
)
|
| 59 |
+
_TERMINAL_OUTCOME_FIELDS = frozenset({"stop", "status"})
|
| 60 |
+
_RUNTIME_EVENT_RECEIPT_BINDING_FIELDS = (
|
| 61 |
+
"event_id",
|
| 62 |
+
"runtime_step",
|
| 63 |
+
"event_sha256",
|
| 64 |
+
"source_state_sha256",
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
@dataclass(frozen=True, slots=True)
|
| 69 |
+
class RuntimeEpisodeBinding:
|
| 70 |
+
"""The exact reset authorization sent once to the policy server."""
|
| 71 |
+
|
| 72 |
+
start: Mapping[str, Any]
|
| 73 |
+
source_identity_sha256: str
|
| 74 |
+
source_contract_sha256: str
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class RoboMMEPhaseAOracleProducer:
|
| 78 |
+
"""Produce causal Phase-A runtime messages from one live RoboMME env."""
|
| 79 |
+
|
| 80 |
+
def __init__(
|
| 81 |
+
self,
|
| 82 |
+
*,
|
| 83 |
+
manager_mode: ManagerMode | str,
|
| 84 |
+
metadata_seed: int,
|
| 85 |
+
max_execution_steps: int,
|
| 86 |
+
) -> None:
|
| 87 |
+
try:
|
| 88 |
+
self._manager_mode = ManagerMode(manager_mode)
|
| 89 |
+
except ValueError as exc:
|
| 90 |
+
raise RuntimeReadError(f"unsupported rollout manager_mode {manager_mode!r}") from exc
|
| 91 |
+
self._metadata_seed = _nat(metadata_seed, "metadata_seed")
|
| 92 |
+
self._max_execution_steps = _pos(max_execution_steps, "max_execution_steps")
|
| 93 |
+
self._task_env: Any | None = None
|
| 94 |
+
self._task_id: str | None = None
|
| 95 |
+
self._episode_id: int | None = None
|
| 96 |
+
self._identity_sha256: str | None = None
|
| 97 |
+
self._start: dict[str, Any] | None = None
|
| 98 |
+
self._start_sent = False
|
| 99 |
+
self._pending: list[dict[str, Any]] = []
|
| 100 |
+
self._next_batch_sequence = 0
|
| 101 |
+
self._last_acked_batch_sha256 = GENESIS_BATCH_SHA256
|
| 102 |
+
self._inflight: dict[str, Any] | None = None
|
| 103 |
+
self._inflight_event_count = 0
|
| 104 |
+
self._last_acked_runtime_receipt: dict[str, Any] | None = None
|
| 105 |
+
self._initial_event_ids: tuple[str, ...] = ()
|
| 106 |
+
self._revision = 0
|
| 107 |
+
self._event_ordinal = 0
|
| 108 |
+
self._last_runtime_step = -1
|
| 109 |
+
self._terminal_outcome: dict[str, Any] | None = None
|
| 110 |
+
self._last_task_timestep: int | None = None
|
| 111 |
+
self._target_cycles: int | None = None
|
| 112 |
+
self._cycle_start_step: int | None = None
|
| 113 |
+
self._last_move_subgoal: str | None = None
|
| 114 |
+
self._move_completions = 0
|
| 115 |
+
self._move_step_count = 0
|
| 116 |
+
|
| 117 |
+
@property
|
| 118 |
+
def manager_mode(self) -> ManagerMode:
|
| 119 |
+
return self._manager_mode
|
| 120 |
+
|
| 121 |
+
def begin_episode(
|
| 122 |
+
self,
|
| 123 |
+
env_runner: Any,
|
| 124 |
+
pretrajectory: Mapping[str, Any],
|
| 125 |
+
) -> RuntimeEpisodeBinding:
|
| 126 |
+
"""Bind and reset the producer from the real simulator reset result."""
|
| 127 |
+
|
| 128 |
+
self._clear_episode()
|
| 129 |
+
if not isinstance(pretrajectory, Mapping):
|
| 130 |
+
raise RuntimeReadError("RoboMME pretrajectory must be a mapping")
|
| 131 |
+
task_id = getattr(env_runner, "env_id", None)
|
| 132 |
+
if task_id not in SUPPORTED_TASKS:
|
| 133 |
+
raise RuntimeReadError(f"unsupported Phase-A rollout task {task_id!r}")
|
| 134 |
+
episode_id = _nat(getattr(env_runner, "episode_id", None), "episode_id")
|
| 135 |
+
env = getattr(env_runner, "env", None)
|
| 136 |
+
if env is None:
|
| 137 |
+
raise RuntimeReadError("RoboMME env_runner has no active environment")
|
| 138 |
+
task_env = _unwrapped(env)
|
| 139 |
+
|
| 140 |
+
images = pretrajectory.get("images")
|
| 141 |
+
if not isinstance(images, Sequence) or isinstance(images, (str, bytes)) or not images:
|
| 142 |
+
raise RuntimeReadError("RoboMME pretrajectory images must be a non-empty sequence")
|
| 143 |
+
exec_start_step = len(images) - 1
|
| 144 |
+
if task_id == "PickXtimes" and exec_start_step != 0:
|
| 145 |
+
raise RuntimeReadError("PickXtimes Phase-A rollout must begin execution at step zero")
|
| 146 |
+
if task_id != "PickXtimes" and exec_start_step <= 0:
|
| 147 |
+
raise RuntimeReadError(f"{task_id} Phase-A rollout requires a real demonstration prefix")
|
| 148 |
+
episode_end_step = exec_start_step + self._max_execution_steps
|
| 149 |
+
instruction = _canonical_instruction(pretrajectory.get("task_goal"))
|
| 150 |
+
reset_steps = _reset_steps_from_env(env, exec_start_step=exec_start_step, task_id=task_id)
|
| 151 |
+
source_path = f"robomme://test/{task_id}/{episode_id}"
|
| 152 |
+
dataset_version = "robomme_simulator_phase_a_runtime_v1"
|
| 153 |
+
|
| 154 |
+
full_contract = _build_full_source_contract(
|
| 155 |
+
task_id=task_id,
|
| 156 |
+
episode_id=episode_id,
|
| 157 |
+
instruction=instruction,
|
| 158 |
+
dataset_version=dataset_version,
|
| 159 |
+
source_path=source_path,
|
| 160 |
+
reset_steps=reset_steps,
|
| 161 |
+
exec_start_step=exec_start_step,
|
| 162 |
+
episode_end_step=episode_end_step,
|
| 163 |
+
task_env=task_env,
|
| 164 |
+
first_images=images,
|
| 165 |
+
)
|
| 166 |
+
source_contract = build_runtime_source_contract(
|
| 167 |
+
task_id=task_id,
|
| 168 |
+
source_contract=full_contract,
|
| 169 |
+
exec_start_step=exec_start_step,
|
| 170 |
+
episode_end_step=episode_end_step,
|
| 171 |
+
)
|
| 172 |
+
source_contract_sha256 = canonical_json_sha256(source_contract)
|
| 173 |
+
source_identity = _simulator_source_identity(
|
| 174 |
+
task_env,
|
| 175 |
+
task_id=task_id,
|
| 176 |
+
episode_id=episode_id,
|
| 177 |
+
instruction=instruction,
|
| 178 |
+
source_path=source_path,
|
| 179 |
+
exec_start_step=exec_start_step,
|
| 180 |
+
episode_end_step=episode_end_step,
|
| 181 |
+
)
|
| 182 |
+
source_identity_sha256 = canonical_json_sha256(source_identity)
|
| 183 |
+
reset = build_runtime_reset(
|
| 184 |
+
task_id=task_id,
|
| 185 |
+
episode_id=episode_id,
|
| 186 |
+
instruction=instruction,
|
| 187 |
+
dataset_version=dataset_version,
|
| 188 |
+
split="test",
|
| 189 |
+
source_path=source_path,
|
| 190 |
+
exec_start_step=exec_start_step,
|
| 191 |
+
episode_end_step=episode_end_step,
|
| 192 |
+
use_intervals=source_contract["use_intervals"],
|
| 193 |
+
source_identity_sha256=source_identity_sha256,
|
| 194 |
+
source_contract=source_contract,
|
| 195 |
+
reset_steps=reset_steps,
|
| 196 |
+
)
|
| 197 |
+
start = {
|
| 198 |
+
"schema_version": RUNTIME_START_SCHEMA_VERSION,
|
| 199 |
+
"reset": reset,
|
| 200 |
+
"expected_identity_sha256": reset["identity_sha256"],
|
| 201 |
+
"expected_source_identity_sha256": source_identity_sha256,
|
| 202 |
+
"expected_source_contract_sha256": source_contract_sha256,
|
| 203 |
+
"manager_mode": self._manager_mode.value,
|
| 204 |
+
"metadata_seed": self._metadata_seed,
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
initial_events = _initial_candidates(
|
| 208 |
+
task_id=task_id,
|
| 209 |
+
episode_id=episode_id,
|
| 210 |
+
instruction=instruction,
|
| 211 |
+
episode_end_step=episode_end_step,
|
| 212 |
+
exec_start_step=exec_start_step,
|
| 213 |
+
source_contract=full_contract,
|
| 214 |
+
)
|
| 215 |
+
self._task_env = task_env
|
| 216 |
+
self._task_id = task_id
|
| 217 |
+
self._episode_id = episode_id
|
| 218 |
+
self._identity_sha256 = reset["identity_sha256"]
|
| 219 |
+
self._start = start
|
| 220 |
+
self._initial_event_ids = tuple(event.event_id for event in initial_events)
|
| 221 |
+
self._event_ordinal = len(initial_events)
|
| 222 |
+
self._last_runtime_step = exec_start_step
|
| 223 |
+
if task_id == "PickXtimes":
|
| 224 |
+
timestep = _nat(_required_attr(task_env, "timestep"), "PickXtimes.timestep")
|
| 225 |
+
target = _pos(_required_attr(task_env, "num_repeats"), "PickXtimes.num_repeats")
|
| 226 |
+
if timestep != 0:
|
| 227 |
+
raise RuntimeReadError("PickXtimes simulator did not reset to cycle zero")
|
| 228 |
+
self._last_task_timestep = timestep
|
| 229 |
+
self._target_cycles = target
|
| 230 |
+
self._cycle_start_step = exec_start_step
|
| 231 |
+
elif task_id == "MoveCube":
|
| 232 |
+
self._move_step_count = sum(1 for event in initial_events if event.kind == "demo_step")
|
| 233 |
+
if self._move_step_count <= 0:
|
| 234 |
+
raise RuntimeReadError("MoveCube reset did not produce demonstrated procedure steps")
|
| 235 |
+
self._last_move_subgoal = _online_subgoal(getattr(env_runner, "info", {}))
|
| 236 |
+
return RuntimeEpisodeBinding(
|
| 237 |
+
start=deepcopy(start),
|
| 238 |
+
source_identity_sha256=source_identity_sha256,
|
| 239 |
+
source_contract_sha256=source_contract_sha256,
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
def observe_after_step(
|
| 243 |
+
self,
|
| 244 |
+
env_runner: Any,
|
| 245 |
+
*,
|
| 246 |
+
runtime_step: int,
|
| 247 |
+
terminal_outcome: Mapping[str, Any] | None = None,
|
| 248 |
+
) -> tuple[Mapping[str, Any], ...]:
|
| 249 |
+
"""Observe one returned simulator state and enqueue only causal events.
|
| 250 |
+
|
| 251 |
+
A terminal outcome describes the result of the action that produced
|
| 252 |
+
this exact state. Successful PickXtimes and video tasks emit a final
|
| 253 |
+
``task_complete`` event. MoveCube completion remains the real final
|
| 254 |
+
``step_complete`` transition, while failed/timeout/unknown outcomes
|
| 255 |
+
only cause the already-observed events to be delivered.
|
| 256 |
+
"""
|
| 257 |
+
|
| 258 |
+
if self._task_env is None or self._task_id is None or self._episode_id is None:
|
| 259 |
+
raise RuntimeReadError("begin_episode must succeed before observe_after_step")
|
| 260 |
+
if self._terminal_outcome is not None:
|
| 261 |
+
raise RuntimeReadError("rollout already observed a terminal outcome")
|
| 262 |
+
runtime_step = _nat(runtime_step, "runtime_step")
|
| 263 |
+
if runtime_step <= self._last_runtime_step:
|
| 264 |
+
raise RuntimeReadError("rollout runtime_step must increase after env.step")
|
| 265 |
+
env = getattr(env_runner, "env", None)
|
| 266 |
+
if env is None or _unwrapped(env) is not self._task_env:
|
| 267 |
+
raise RuntimeReadError("RoboMME environment instance changed within an episode")
|
| 268 |
+
|
| 269 |
+
emitted: list[dict[str, Any]] = []
|
| 270 |
+
if self._task_id == "PickXtimes":
|
| 271 |
+
emitted.extend(self._observe_pick(runtime_step))
|
| 272 |
+
elif self._task_id == "MoveCube":
|
| 273 |
+
emitted.extend(self._observe_move(getattr(env_runner, "info", {}), runtime_step))
|
| 274 |
+
outcome = _terminal_outcome(terminal_outcome)
|
| 275 |
+
if outcome is not None:
|
| 276 |
+
if outcome["status"] == "success":
|
| 277 |
+
if self._task_id == "MoveCube":
|
| 278 |
+
if (
|
| 279 |
+
self._last_move_subgoal != "all tasks completed"
|
| 280 |
+
or self._move_completions != self._move_step_count
|
| 281 |
+
):
|
| 282 |
+
raise RuntimeReadError("successful MoveCube terminal state did not complete its live procedure")
|
| 283 |
+
else:
|
| 284 |
+
if self._task_id == "PickXtimes":
|
| 285 |
+
assert self._last_task_timestep is not None
|
| 286 |
+
assert self._target_cycles is not None
|
| 287 |
+
if self._last_task_timestep < 2 * self._target_cycles:
|
| 288 |
+
raise RuntimeReadError("successful PickXtimes terminal state precedes its target cycles")
|
| 289 |
+
emitted.append(self._terminal_completion(runtime_step, outcome))
|
| 290 |
+
self._terminal_outcome = deepcopy(outcome)
|
| 291 |
+
self._pending.extend(emitted)
|
| 292 |
+
self._last_runtime_step = runtime_step
|
| 293 |
+
return tuple(deepcopy(emitted))
|
| 294 |
+
|
| 295 |
+
def peek_add_buffer_payload(self) -> dict[str, Any]:
|
| 296 |
+
"""Return the current delivery without committing any producer state.
|
| 297 |
+
|
| 298 |
+
Until an exact ACK arrives, every call returns a byte-equivalent deep
|
| 299 |
+
copy of the same in-flight batch. Events observed after the batch was
|
| 300 |
+
formed remain queued for the next sequence and cannot be removed by
|
| 301 |
+
acknowledgement of the older delivery.
|
| 302 |
+
"""
|
| 303 |
+
|
| 304 |
+
if self._start is None:
|
| 305 |
+
raise RuntimeReadError("Phase-A producer has no active episode")
|
| 306 |
+
if self._inflight is None:
|
| 307 |
+
body = {
|
| 308 |
+
"schema_version": RUNTIME_BATCH_SCHEMA_VERSION,
|
| 309 |
+
"batch_sequence": self._next_batch_sequence,
|
| 310 |
+
"previous_batch_sha256": self._last_acked_batch_sha256,
|
| 311 |
+
"start": None if self._start_sent else deepcopy(self._start),
|
| 312 |
+
"events": deepcopy(self._pending),
|
| 313 |
+
}
|
| 314 |
+
self._inflight = {**body, "batch_sha256": canonical_json_sha256(body)}
|
| 315 |
+
self._inflight_event_count = len(self._pending)
|
| 316 |
+
return deepcopy(self._inflight)
|
| 317 |
+
|
| 318 |
+
def acknowledge_add_buffer_payload(self, raw: Mapping[str, Any]) -> dict[str, Any]:
|
| 319 |
+
"""Commit exactly the currently in-flight delivery after server ACK."""
|
| 320 |
+
|
| 321 |
+
if not isinstance(raw, Mapping) or set(raw) != _ACK_FIELDS:
|
| 322 |
+
raise RuntimeReadError("Phase-A rollout ACK fields mismatch")
|
| 323 |
+
if raw["schema_version"] != RUNTIME_ACK_SCHEMA_VERSION:
|
| 324 |
+
raise RuntimeReadError("Phase-A rollout ACK schema_version mismatch")
|
| 325 |
+
sequence = _nat(raw["batch_sequence"], "ack.batch_sequence")
|
| 326 |
+
batch_sha256 = _sha256(raw["batch_sha256"], "ack.batch_sha256")
|
| 327 |
+
if not isinstance(raw["duplicate"], bool):
|
| 328 |
+
raise RuntimeReadError("Phase-A rollout ACK duplicate must be boolean")
|
| 329 |
+
receipt = raw["runtime_receipt"]
|
| 330 |
+
receipt = _validated_runtime_receipt(receipt)
|
| 331 |
+
if self._inflight is None:
|
| 332 |
+
raise RuntimeReadError("Phase-A rollout ACK arrived without an in-flight batch")
|
| 333 |
+
if sequence != self._inflight["batch_sequence"]:
|
| 334 |
+
raise RuntimeReadError("Phase-A rollout ACK batch_sequence differs from in-flight")
|
| 335 |
+
if batch_sha256 != self._inflight["batch_sha256"]:
|
| 336 |
+
raise RuntimeReadError("Phase-A rollout ACK batch_sha256 differs from in-flight")
|
| 337 |
+
if self._inflight_event_count > len(self._pending):
|
| 338 |
+
raise RuntimeReadError("Phase-A rollout pending queue regressed before ACK")
|
| 339 |
+
if self._pending[: self._inflight_event_count] != self._inflight["events"]:
|
| 340 |
+
raise RuntimeReadError("Phase-A rollout pending prefix drifted before ACK")
|
| 341 |
+
if receipt.get("identity_sha256") != self._identity_sha256:
|
| 342 |
+
raise RuntimeReadError("Phase-A rollout ACK receipt identity differs from the episode")
|
| 343 |
+
if receipt.get("task_id") != self._task_id or receipt.get("episode_id") != self._episode_id:
|
| 344 |
+
raise RuntimeReadError("Phase-A rollout ACK receipt episode binding mismatch")
|
| 345 |
+
if receipt.get("manager_mode") != self._manager_mode.value:
|
| 346 |
+
raise RuntimeReadError("Phase-A rollout ACK receipt manager_mode mismatch")
|
| 347 |
+
self._validate_ack_receipt_progression(receipt)
|
| 348 |
+
|
| 349 |
+
del self._pending[: self._inflight_event_count]
|
| 350 |
+
if self._inflight["start"] is not None:
|
| 351 |
+
self._start_sent = True
|
| 352 |
+
self._last_acked_batch_sha256 = batch_sha256
|
| 353 |
+
self._next_batch_sequence += 1
|
| 354 |
+
self._last_acked_runtime_receipt = deepcopy(receipt)
|
| 355 |
+
self._inflight = None
|
| 356 |
+
self._inflight_event_count = 0
|
| 357 |
+
return deepcopy(dict(raw))
|
| 358 |
+
|
| 359 |
+
def _validate_ack_receipt_progression(self, receipt: Mapping[str, Any]) -> None:
|
| 360 |
+
"""Bind one valid receipt to exactly the current in-flight event suffix."""
|
| 361 |
+
|
| 362 |
+
if self._inflight is None:
|
| 363 |
+
raise RuntimeReadError("Phase-A rollout ACK has no in-flight lineage")
|
| 364 |
+
previous = self._last_acked_runtime_receipt
|
| 365 |
+
previous_event_ids = [] if previous is None else _receipt_event_ids(previous, "previous runtime_receipt")
|
| 366 |
+
previous_events = [] if previous is None else _receipt_runtime_events(previous, "previous runtime_receipt")
|
| 367 |
+
base_revision = 0 if previous is None else _receipt_nat(previous, "next_revision", "previous runtime_receipt")
|
| 368 |
+
base_ordinal = (
|
| 369 |
+
len(self._initial_event_ids)
|
| 370 |
+
if previous is None
|
| 371 |
+
else _receipt_nat(previous, "next_event_ordinal", "previous runtime_receipt")
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
initial_event_ids = _receipt_event_ids(
|
| 375 |
+
receipt,
|
| 376 |
+
"runtime_receipt",
|
| 377 |
+
field="initial_event_ids",
|
| 378 |
+
)
|
| 379 |
+
if initial_event_ids != list(self._initial_event_ids):
|
| 380 |
+
raise RuntimeReadError("Phase-A rollout ACK initial_event_ids mismatch")
|
| 381 |
+
|
| 382 |
+
inflight_event_ids: list[str] = []
|
| 383 |
+
inflight_bindings: list[dict[str, Any]] = []
|
| 384 |
+
for index, raw_envelope in enumerate(self._inflight["events"]):
|
| 385 |
+
if not isinstance(raw_envelope, Mapping):
|
| 386 |
+
raise RuntimeReadError("Phase-A in-flight event envelope is not a mapping")
|
| 387 |
+
event = raw_envelope.get("event")
|
| 388 |
+
if not isinstance(event, Mapping):
|
| 389 |
+
raise RuntimeReadError("Phase-A in-flight runtime event is not a mapping")
|
| 390 |
+
event_id = _text(event.get("event_id"), f"inflight.events[{index}].event_id")
|
| 391 |
+
revision = _nat(event.get("revision"), f"inflight.events[{index}].revision")
|
| 392 |
+
ordinal = _nat(event.get("event_ordinal"), f"inflight.events[{index}].event_ordinal")
|
| 393 |
+
if revision != base_revision + index:
|
| 394 |
+
raise RuntimeReadError("Phase-A in-flight event revision is not contiguous with its ACK base")
|
| 395 |
+
if ordinal != base_ordinal + index:
|
| 396 |
+
raise RuntimeReadError("Phase-A in-flight event ordinal is not contiguous with its ACK base")
|
| 397 |
+
inflight_event_ids.append(event_id)
|
| 398 |
+
inflight_bindings.append(
|
| 399 |
+
{
|
| 400 |
+
"event_id": event_id,
|
| 401 |
+
"runtime_step": _nat(
|
| 402 |
+
event.get("runtime_step"),
|
| 403 |
+
f"inflight.events[{index}].runtime_step",
|
| 404 |
+
),
|
| 405 |
+
"event_sha256": _sha256(
|
| 406 |
+
event.get("event_sha256"),
|
| 407 |
+
f"inflight.events[{index}].event_sha256",
|
| 408 |
+
),
|
| 409 |
+
"source_state_sha256": _sha256(
|
| 410 |
+
event.get("source_state_sha256"),
|
| 411 |
+
f"inflight.events[{index}].source_state_sha256",
|
| 412 |
+
),
|
| 413 |
+
}
|
| 414 |
+
)
|
| 415 |
+
|
| 416 |
+
event_ids = _receipt_event_ids(receipt, "runtime_receipt")
|
| 417 |
+
expected_event_ids = [*previous_event_ids, *inflight_event_ids]
|
| 418 |
+
if event_ids != expected_event_ids:
|
| 419 |
+
raise RuntimeReadError("Phase-A rollout ACK runtime_event_ids do not match its batch lineage")
|
| 420 |
+
|
| 421 |
+
runtime_events = _receipt_runtime_events(receipt, "runtime_receipt")
|
| 422 |
+
if runtime_events[: len(previous_events)] != previous_events:
|
| 423 |
+
raise RuntimeReadError("Phase-A rollout ACK runtime_events changed its committed prefix")
|
| 424 |
+
suffix = runtime_events[len(previous_events) :]
|
| 425 |
+
if len(suffix) != len(inflight_bindings):
|
| 426 |
+
raise RuntimeReadError("Phase-A rollout ACK runtime_events length does not match its batch")
|
| 427 |
+
for index, (event_receipt, expected) in enumerate(zip(suffix, inflight_bindings, strict=True)):
|
| 428 |
+
actual = {field: event_receipt.get(field) for field in _RUNTIME_EVENT_RECEIPT_BINDING_FIELDS}
|
| 429 |
+
if actual != expected:
|
| 430 |
+
raise RuntimeReadError(f"Phase-A rollout ACK runtime_events[{index}] is not bound to its batch event")
|
| 431 |
+
|
| 432 |
+
expected_revision = base_revision + len(inflight_event_ids)
|
| 433 |
+
if _receipt_nat(receipt, "next_revision", "runtime_receipt") != expected_revision:
|
| 434 |
+
raise RuntimeReadError("Phase-A rollout ACK next_revision does not match its batch lineage")
|
| 435 |
+
expected_ordinal = base_ordinal + len(inflight_event_ids)
|
| 436 |
+
if _receipt_nat(receipt, "next_event_ordinal", "runtime_receipt") != expected_ordinal:
|
| 437 |
+
raise RuntimeReadError("Phase-A rollout ACK next_event_ordinal does not match its batch lineage")
|
| 438 |
+
|
| 439 |
+
def _terminal_completion(
|
| 440 |
+
self,
|
| 441 |
+
runtime_step: int,
|
| 442 |
+
outcome: Mapping[str, Any],
|
| 443 |
+
) -> dict[str, Any]:
|
| 444 |
+
assert self._task_id is not None
|
| 445 |
+
assert self._episode_id is not None
|
| 446 |
+
observed_state = {
|
| 447 |
+
"schema_version": PRODUCER_SCHEMA_VERSION,
|
| 448 |
+
"task_id": self._task_id,
|
| 449 |
+
"episode_id": self._episode_id,
|
| 450 |
+
"runtime_step": runtime_step,
|
| 451 |
+
"terminal_outcome": deepcopy(dict(outcome)),
|
| 452 |
+
}
|
| 453 |
+
return self._envelope(
|
| 454 |
+
runtime_step=runtime_step,
|
| 455 |
+
event_id=f"{self._episode_id}:runtime:task-complete",
|
| 456 |
+
kind="task_complete",
|
| 457 |
+
evidence=None,
|
| 458 |
+
observed_state=observed_state,
|
| 459 |
+
)
|
| 460 |
+
|
| 461 |
+
def _observe_pick(self, runtime_step: int) -> list[dict[str, Any]]:
|
| 462 |
+
assert self._task_env is not None
|
| 463 |
+
assert self._last_task_timestep is not None
|
| 464 |
+
assert self._target_cycles is not None
|
| 465 |
+
timestep = _nat(_required_attr(self._task_env, "timestep"), "PickXtimes.timestep")
|
| 466 |
+
if timestep < self._last_task_timestep:
|
| 467 |
+
raise RuntimeReadError("PickXtimes simulator timestep regressed")
|
| 468 |
+
if timestep > 2 * self._target_cycles + 1:
|
| 469 |
+
raise RuntimeReadError("PickXtimes simulator timestep exceeds target-cycle protocol")
|
| 470 |
+
result: list[dict[str, Any]] = []
|
| 471 |
+
for edge in range(self._last_task_timestep + 1, timestep + 1):
|
| 472 |
+
if edge > 2 * self._target_cycles:
|
| 473 |
+
continue
|
| 474 |
+
if edge % 2 == 1:
|
| 475 |
+
self._cycle_start_step = runtime_step
|
| 476 |
+
continue
|
| 477 |
+
cycle = edge // 2
|
| 478 |
+
start = self._cycle_start_step if self._cycle_start_step is not None else runtime_step
|
| 479 |
+
observed_state = {
|
| 480 |
+
"schema_version": PRODUCER_SCHEMA_VERSION,
|
| 481 |
+
"task_id": "PickXtimes",
|
| 482 |
+
"episode_id": self._episode_id,
|
| 483 |
+
"runtime_step": runtime_step,
|
| 484 |
+
"task_timestep": timestep,
|
| 485 |
+
"target_cycles": self._target_cycles,
|
| 486 |
+
"completed_cycle": cycle,
|
| 487 |
+
}
|
| 488 |
+
result.append(
|
| 489 |
+
self._envelope(
|
| 490 |
+
runtime_step=runtime_step,
|
| 491 |
+
event_id=f"{self._episode_id}:runtime:cycle:{cycle}",
|
| 492 |
+
kind="cycle_complete",
|
| 493 |
+
evidence=(min(start, runtime_step), runtime_step),
|
| 494 |
+
observed_state=observed_state,
|
| 495 |
+
)
|
| 496 |
+
)
|
| 497 |
+
self._cycle_start_step = runtime_step
|
| 498 |
+
self._last_task_timestep = timestep
|
| 499 |
+
return result
|
| 500 |
+
|
| 501 |
+
def _observe_move(self, info: Any, runtime_step: int) -> list[dict[str, Any]]:
|
| 502 |
+
current = _online_subgoal(info)
|
| 503 |
+
previous = self._last_move_subgoal
|
| 504 |
+
self._last_move_subgoal = current
|
| 505 |
+
if previous is None or current is None or current == previous:
|
| 506 |
+
return []
|
| 507 |
+
if previous in {"", "static", "no record", "all tasks completed"}:
|
| 508 |
+
return []
|
| 509 |
+
if self._move_completions >= self._move_step_count:
|
| 510 |
+
return []
|
| 511 |
+
self._move_completions += 1
|
| 512 |
+
observed_state = {
|
| 513 |
+
"schema_version": PRODUCER_SCHEMA_VERSION,
|
| 514 |
+
"task_id": "MoveCube",
|
| 515 |
+
"episode_id": self._episode_id,
|
| 516 |
+
"runtime_step": runtime_step,
|
| 517 |
+
"completed_subgoal": previous,
|
| 518 |
+
"next_subgoal": current,
|
| 519 |
+
"completed_step_index": self._move_completions,
|
| 520 |
+
}
|
| 521 |
+
return [
|
| 522 |
+
self._envelope(
|
| 523 |
+
runtime_step=runtime_step,
|
| 524 |
+
event_id=f"{self._episode_id}:runtime:step:{self._move_completions}",
|
| 525 |
+
kind="step_complete",
|
| 526 |
+
evidence=None,
|
| 527 |
+
observed_state=observed_state,
|
| 528 |
+
)
|
| 529 |
+
]
|
| 530 |
+
|
| 531 |
+
def _envelope(
|
| 532 |
+
self,
|
| 533 |
+
*,
|
| 534 |
+
runtime_step: int,
|
| 535 |
+
event_id: str,
|
| 536 |
+
kind: str,
|
| 537 |
+
evidence: tuple[int, int] | None,
|
| 538 |
+
observed_state: Mapping[str, Any],
|
| 539 |
+
) -> dict[str, Any]:
|
| 540 |
+
assert self._identity_sha256 is not None
|
| 541 |
+
assert self._task_id is not None
|
| 542 |
+
assert self._episode_id is not None
|
| 543 |
+
wire = build_runtime_event(
|
| 544 |
+
identity_sha256=self._identity_sha256,
|
| 545 |
+
task_id=self._task_id,
|
| 546 |
+
episode_id=self._episode_id,
|
| 547 |
+
runtime_step=runtime_step,
|
| 548 |
+
revision=self._revision,
|
| 549 |
+
event_id=event_id,
|
| 550 |
+
event_ordinal=self._event_ordinal,
|
| 551 |
+
kind=kind,
|
| 552 |
+
evidence=evidence,
|
| 553 |
+
value=None,
|
| 554 |
+
bindings=None,
|
| 555 |
+
confidence=1.0,
|
| 556 |
+
source_state_sha256=runtime_state_sha256(observed_state),
|
| 557 |
+
)
|
| 558 |
+
self._revision += 1
|
| 559 |
+
self._event_ordinal += 1
|
| 560 |
+
return {
|
| 561 |
+
"schema_version": RUNTIME_ENVELOPE_SCHEMA_VERSION,
|
| 562 |
+
"event": wire,
|
| 563 |
+
"observed_source_state": deepcopy(dict(observed_state)),
|
| 564 |
+
}
|
| 565 |
+
|
| 566 |
+
def _clear_episode(self) -> None:
|
| 567 |
+
self._task_env = None
|
| 568 |
+
self._task_id = None
|
| 569 |
+
self._episode_id = None
|
| 570 |
+
self._identity_sha256 = None
|
| 571 |
+
self._start = None
|
| 572 |
+
self._start_sent = False
|
| 573 |
+
self._pending.clear()
|
| 574 |
+
self._next_batch_sequence = 0
|
| 575 |
+
self._last_acked_batch_sha256 = GENESIS_BATCH_SHA256
|
| 576 |
+
self._inflight = None
|
| 577 |
+
self._inflight_event_count = 0
|
| 578 |
+
self._last_acked_runtime_receipt = None
|
| 579 |
+
self._initial_event_ids = ()
|
| 580 |
+
self._revision = 0
|
| 581 |
+
self._event_ordinal = 0
|
| 582 |
+
self._last_runtime_step = -1
|
| 583 |
+
self._terminal_outcome = None
|
| 584 |
+
self._last_task_timestep = None
|
| 585 |
+
self._target_cycles = None
|
| 586 |
+
self._cycle_start_step = None
|
| 587 |
+
self._last_move_subgoal = None
|
| 588 |
+
self._move_completions = 0
|
| 589 |
+
self._move_step_count = 0
|
| 590 |
+
|
| 591 |
+
|
| 592 |
+
def attach_runtime_to_buffer(
|
| 593 |
+
buffer_payload: Mapping[str, Any],
|
| 594 |
+
producer: RoboMMEPhaseAOracleProducer,
|
| 595 |
+
) -> dict[str, Any]:
|
| 596 |
+
"""Copy a normal RoboMME buffer request and attach the strict runtime batch."""
|
| 597 |
+
|
| 598 |
+
if not isinstance(buffer_payload, Mapping) or buffer_payload.get("add_buffer") is not True:
|
| 599 |
+
raise RuntimeReadError("Phase-A runtime can attach only to an add_buffer request")
|
| 600 |
+
if "picmem_phase_a_runtime" in buffer_payload:
|
| 601 |
+
raise RuntimeReadError("add_buffer already contains a Phase-A runtime payload")
|
| 602 |
+
return {**dict(buffer_payload), "picmem_phase_a_runtime": producer.peek_add_buffer_payload()}
|
| 603 |
+
|
| 604 |
+
|
| 605 |
+
def acknowledge_runtime_buffer(
|
| 606 |
+
buffer_payload: Mapping[str, Any],
|
| 607 |
+
response: Mapping[str, Any],
|
| 608 |
+
producer: RoboMMEPhaseAOracleProducer,
|
| 609 |
+
) -> dict[str, Any]:
|
| 610 |
+
"""Validate one completed host response and commit its producer delivery."""
|
| 611 |
+
|
| 612 |
+
if not isinstance(buffer_payload, Mapping):
|
| 613 |
+
raise RuntimeReadError("Phase-A ACK requires the original add_buffer request")
|
| 614 |
+
batch = buffer_payload.get("picmem_phase_a_runtime")
|
| 615 |
+
if not isinstance(batch, Mapping):
|
| 616 |
+
raise RuntimeReadError("Phase-A ACK request is missing its runtime batch")
|
| 617 |
+
if not isinstance(response, Mapping) or response.get("add_buffer_finished") is not True:
|
| 618 |
+
raise RuntimeReadError("Phase-A add_buffer response is not complete")
|
| 619 |
+
ack = response.get("picmem_phase_a_runtime_ack")
|
| 620 |
+
if not isinstance(ack, Mapping):
|
| 621 |
+
raise RuntimeReadError("Phase-A add_buffer response is missing its runtime ACK")
|
| 622 |
+
if ack.get("batch_sequence") != batch.get("batch_sequence"):
|
| 623 |
+
raise RuntimeReadError("Phase-A response ACK sequence differs from its request")
|
| 624 |
+
if ack.get("batch_sha256") != batch.get("batch_sha256"):
|
| 625 |
+
raise RuntimeReadError("Phase-A response ACK hash differs from its request")
|
| 626 |
+
return producer.acknowledge_add_buffer_payload(ack)
|
| 627 |
+
|
| 628 |
+
|
| 629 |
+
def _build_full_source_contract(
|
| 630 |
+
*,
|
| 631 |
+
task_id: str,
|
| 632 |
+
episode_id: int,
|
| 633 |
+
instruction: str,
|
| 634 |
+
dataset_version: str,
|
| 635 |
+
source_path: str,
|
| 636 |
+
reset_steps: list[dict[str, Any]],
|
| 637 |
+
exec_start_step: int,
|
| 638 |
+
episode_end_step: int,
|
| 639 |
+
task_env: Any,
|
| 640 |
+
first_images: Sequence[Any],
|
| 641 |
+
) -> dict[str, Any]:
|
| 642 |
+
contract_spec = task_schema_for(task_id, instruction).contracts[0]
|
| 643 |
+
timeline: list[dict[str, Any]] = []
|
| 644 |
+
if task_id in {"MoveCube", "VideoPlaceButton"}:
|
| 645 |
+
sentinel = {
|
| 646 |
+
"step": exec_start_step,
|
| 647 |
+
"simple_subgoal": "no record",
|
| 648 |
+
"grounded_subgoal": "no record",
|
| 649 |
+
"is_video_demo": False,
|
| 650 |
+
"is_subgoal_boundary": False,
|
| 651 |
+
"is_completed": False,
|
| 652 |
+
}
|
| 653 |
+
annotation = annotate_episode_from_steps(
|
| 654 |
+
task_id=task_id,
|
| 655 |
+
episode_id=episode_id,
|
| 656 |
+
steps=[*deepcopy(reset_steps), sentinel],
|
| 657 |
+
instruction=instruction,
|
| 658 |
+
dataset_version=dataset_version,
|
| 659 |
+
split="test",
|
| 660 |
+
source_path=source_path,
|
| 661 |
+
contract_source="runtime_reset_simulator",
|
| 662 |
+
policy_input_fields=["runtime visual history only"],
|
| 663 |
+
contract_variant="coarse",
|
| 664 |
+
).to_json()
|
| 665 |
+
matches = [
|
| 666 |
+
value for value in annotation.get("contracts", []) if value.get("contract_id") == contract_spec.contract_id
|
| 667 |
+
]
|
| 668 |
+
if len(matches) != 1:
|
| 669 |
+
raise RuntimeReadError(f"{task_id} reset did not derive one exact primary contract")
|
| 670 |
+
timeline = deepcopy(matches[0].get("value_timeline", []))
|
| 671 |
+
if not timeline:
|
| 672 |
+
raise RuntimeReadError(f"{task_id} reset did not derive initial oracle evidence")
|
| 673 |
+
elif task_id == "VideoUnmask":
|
| 674 |
+
actor = _required_attr(task_env, "bin_0")
|
| 675 |
+
point = _project_actor(task_env, actor, first_images)
|
| 676 |
+
timeline = [
|
| 677 |
+
{
|
| 678 |
+
"step": exec_start_step - 1,
|
| 679 |
+
"evidence_interval": [0, exec_start_step - 1],
|
| 680 |
+
"value": point,
|
| 681 |
+
"confidence": 1.0,
|
| 682 |
+
"source": "runtime_simulator_oracle",
|
| 683 |
+
"update_kind": "set_once_from_reveal_or_grounded_subgoal",
|
| 684 |
+
}
|
| 685 |
+
]
|
| 686 |
+
return {
|
| 687 |
+
"contract_id": contract_spec.contract_id,
|
| 688 |
+
"query": contract_spec.query,
|
| 689 |
+
"semantic_type": contract_spec.semantic_type.value,
|
| 690 |
+
"reducer_type": contract_spec.reducer_type.value,
|
| 691 |
+
"open_step": contract_spec.open_step,
|
| 692 |
+
"use_intervals": [[exec_start_step, episode_end_step]],
|
| 693 |
+
"value_timeline": timeline,
|
| 694 |
+
}
|
| 695 |
+
|
| 696 |
+
|
| 697 |
+
def _initial_candidates(
|
| 698 |
+
*,
|
| 699 |
+
task_id: str,
|
| 700 |
+
episode_id: int,
|
| 701 |
+
instruction: str,
|
| 702 |
+
episode_end_step: int,
|
| 703 |
+
exec_start_step: int,
|
| 704 |
+
source_contract: Mapping[str, Any],
|
| 705 |
+
) -> tuple[Any, ...]:
|
| 706 |
+
annotation = {
|
| 707 |
+
"task_id": task_id,
|
| 708 |
+
"episode_id": episode_id,
|
| 709 |
+
"task_instruction": instruction,
|
| 710 |
+
"num_steps": episode_end_step + 1,
|
| 711 |
+
"exec_start_step": exec_start_step,
|
| 712 |
+
"contracts": [deepcopy(dict(source_contract))],
|
| 713 |
+
"ordered_subgoals": [],
|
| 714 |
+
}
|
| 715 |
+
return tuple(events_from_sidecar(annotation))
|
| 716 |
+
|
| 717 |
+
|
| 718 |
+
def _reset_steps_from_env(env: Any, *, exec_start_step: int, task_id: str) -> list[dict[str, Any]]:
|
| 719 |
+
if exec_start_step == 0:
|
| 720 |
+
return []
|
| 721 |
+
wrapper = env
|
| 722 |
+
seen: set[int] = set()
|
| 723 |
+
demonstration_data: Any | None = None
|
| 724 |
+
while wrapper is not None and id(wrapper) not in seen:
|
| 725 |
+
seen.add(id(wrapper))
|
| 726 |
+
values = getattr(wrapper, "__dict__", None)
|
| 727 |
+
if isinstance(values, dict) and "demonstration_data" in values:
|
| 728 |
+
demonstration_data = values["demonstration_data"]
|
| 729 |
+
break
|
| 730 |
+
wrapper = values.get("env") if isinstance(values, dict) else None
|
| 731 |
+
if not isinstance(demonstration_data, tuple) or len(demonstration_data) != 5:
|
| 732 |
+
raise RuntimeReadError(f"{task_id} runtime demonstration_data is unavailable")
|
| 733 |
+
info = demonstration_data[4]
|
| 734 |
+
if not isinstance(info, Mapping):
|
| 735 |
+
raise RuntimeReadError("RoboMME runtime demonstration info batch is unavailable")
|
| 736 |
+
fields = (
|
| 737 |
+
"simple_subgoal",
|
| 738 |
+
"grounded_subgoal",
|
| 739 |
+
"is_video_demo",
|
| 740 |
+
"is_subgoal_boundary",
|
| 741 |
+
"is_completed",
|
| 742 |
+
)
|
| 743 |
+
columns = {name: info.get(name) for name in fields}
|
| 744 |
+
if any(not isinstance(value, Sequence) or isinstance(value, (str, bytes)) for value in columns.values()):
|
| 745 |
+
raise RuntimeReadError("RoboMME reset is missing exact demonstration annotation columns")
|
| 746 |
+
if any(len(value) != exec_start_step + 1 for value in columns.values()):
|
| 747 |
+
raise RuntimeReadError("RoboMME demonstration columns do not align with reset images")
|
| 748 |
+
result: list[dict[str, Any]] = []
|
| 749 |
+
for step in range(exec_start_step):
|
| 750 |
+
simple = _canonical_subgoal(columns["simple_subgoal"][step])
|
| 751 |
+
grounded = _canonical_subgoal(columns["grounded_subgoal"][step])
|
| 752 |
+
row = {
|
| 753 |
+
"step": step,
|
| 754 |
+
"simple_subgoal": simple,
|
| 755 |
+
"grounded_subgoal": grounded,
|
| 756 |
+
"is_video_demo": _bool(columns["is_video_demo"][step], "is_video_demo"),
|
| 757 |
+
"is_subgoal_boundary": _bool(columns["is_subgoal_boundary"][step], "is_subgoal_boundary"),
|
| 758 |
+
"is_completed": _bool(columns["is_completed"][step], "is_completed"),
|
| 759 |
+
}
|
| 760 |
+
if not row["is_video_demo"] or row["is_completed"]:
|
| 761 |
+
raise RuntimeReadError("RoboMME reset prefix is not a pure uncompleted demonstration")
|
| 762 |
+
result.append(row)
|
| 763 |
+
if _bool(columns["is_video_demo"][exec_start_step], "execution is_video_demo"):
|
| 764 |
+
raise RuntimeReadError("RoboMME execution boundary is still marked as video demonstration")
|
| 765 |
+
return result
|
| 766 |
+
|
| 767 |
+
|
| 768 |
+
def _simulator_source_identity(
|
| 769 |
+
task_env: Any,
|
| 770 |
+
*,
|
| 771 |
+
task_id: str,
|
| 772 |
+
episode_id: int,
|
| 773 |
+
instruction: str,
|
| 774 |
+
source_path: str,
|
| 775 |
+
exec_start_step: int,
|
| 776 |
+
episode_end_step: int,
|
| 777 |
+
) -> dict[str, Any]:
|
| 778 |
+
seed = getattr(task_env, "seed", 0)
|
| 779 |
+
if isinstance(seed, bool) or not isinstance(seed, (int, np.integer)):
|
| 780 |
+
raise RuntimeReadError("RoboMME simulator seed must be an integer")
|
| 781 |
+
difficulty = getattr(task_env, "difficulty", "unknown")
|
| 782 |
+
if not isinstance(difficulty, str) or not difficulty:
|
| 783 |
+
raise RuntimeReadError("RoboMME simulator difficulty must be non-empty")
|
| 784 |
+
spec = getattr(task_env, "task_spec", getattr(task_env, "spec", {}))
|
| 785 |
+
spec_sha256 = canonical_json_sha256(_plain_json(spec))
|
| 786 |
+
return {
|
| 787 |
+
"schema_version": PRODUCER_SCHEMA_VERSION,
|
| 788 |
+
"task_id": task_id,
|
| 789 |
+
"episode_id": episode_id,
|
| 790 |
+
"instruction": instruction,
|
| 791 |
+
"source_path": source_path,
|
| 792 |
+
"seed": int(seed),
|
| 793 |
+
"difficulty": difficulty,
|
| 794 |
+
"simulator_spec_sha256": spec_sha256,
|
| 795 |
+
"exec_start_step": exec_start_step,
|
| 796 |
+
"episode_end_step": episode_end_step,
|
| 797 |
+
}
|
| 798 |
+
|
| 799 |
+
|
| 800 |
+
def _project_actor(task_env: Any, actor: Any, images: Sequence[Any]) -> dict[str, Any]:
|
| 801 |
+
image = np.asarray(images[-1])
|
| 802 |
+
if image.ndim != 3 or image.shape[-1] not in (3, 4):
|
| 803 |
+
raise RuntimeReadError("RoboMME front image must have shape [H,W,3|4]")
|
| 804 |
+
camera = getattr(task_env, "front_camera", getattr(task_env, "camera", None))
|
| 805 |
+
if camera is None:
|
| 806 |
+
raise RuntimeReadError("VideoUnmask simulator has no front camera")
|
| 807 |
+
intrinsic = _camera_matrix(camera, "get_intrinsic_matrix", "intrinsic_matrix")
|
| 808 |
+
if intrinsic.shape != (3, 3):
|
| 809 |
+
raise RuntimeReadError("RoboMME camera intrinsic matrix must be 3x3")
|
| 810 |
+
try:
|
| 811 |
+
extrinsic = _camera_matrix(camera, "get_extrinsic_matrix", "extrinsic_matrix")
|
| 812 |
+
except RuntimeReadError as exc:
|
| 813 |
+
model = _camera_matrix(camera, "get_model_matrix", "model_matrix")
|
| 814 |
+
if model.shape != (4, 4):
|
| 815 |
+
raise RuntimeReadError("RoboMME camera model matrix must be 4x4") from exc
|
| 816 |
+
try:
|
| 817 |
+
extrinsic = np.linalg.inv(model)
|
| 818 |
+
except np.linalg.LinAlgError as exc:
|
| 819 |
+
raise RuntimeReadError("RoboMME camera model matrix is singular") from exc
|
| 820 |
+
if extrinsic.shape not in {(3, 4), (4, 4)}:
|
| 821 |
+
raise RuntimeReadError("RoboMME camera extrinsic matrix must be 3x4 or 4x4")
|
| 822 |
+
position = _actor_position(actor)
|
| 823 |
+
world = np.concatenate((position, np.ones(1, dtype=np.float64)))
|
| 824 |
+
camera_point = extrinsic @ world
|
| 825 |
+
camera_xyz = camera_point[:3]
|
| 826 |
+
if not np.isfinite(camera_xyz).all() or camera_xyz[2] <= 0:
|
| 827 |
+
raise RuntimeReadError("VideoUnmask actor projects behind the front camera")
|
| 828 |
+
pixel = intrinsic @ camera_xyz
|
| 829 |
+
x = math.floor(float(pixel[0] / pixel[2]) + 0.5)
|
| 830 |
+
y = math.floor(float(pixel[1] / pixel[2]) + 0.5)
|
| 831 |
+
if not (0 <= x < image.shape[1] and 0 <= y < image.shape[0]):
|
| 832 |
+
raise RuntimeReadError("VideoUnmask actor projection is outside the front image")
|
| 833 |
+
return {"kind": "image_point", "x": x, "y": y}
|
| 834 |
+
|
| 835 |
+
|
| 836 |
+
def _camera_matrix(camera: Any, method: str, attribute: str) -> np.ndarray:
|
| 837 |
+
getter = getattr(camera, method, None)
|
| 838 |
+
raw = getter() if callable(getter) else getattr(camera, attribute, None)
|
| 839 |
+
if raw is None:
|
| 840 |
+
raise RuntimeReadError(f"RoboMME camera is missing {method}")
|
| 841 |
+
result = np.asarray(raw, dtype=np.float64)
|
| 842 |
+
if not np.isfinite(result).all():
|
| 843 |
+
raise RuntimeReadError("RoboMME camera matrix must be finite")
|
| 844 |
+
return result
|
| 845 |
+
|
| 846 |
+
|
| 847 |
+
def _actor_position(actor: Any) -> np.ndarray:
|
| 848 |
+
if isinstance(actor, (np.ndarray, list, tuple)):
|
| 849 |
+
raw = actor
|
| 850 |
+
else:
|
| 851 |
+
pose = actor.get_pose() if callable(getattr(actor, "get_pose", None)) else getattr(actor, "pose", None)
|
| 852 |
+
raw = getattr(pose, "p", None)
|
| 853 |
+
result = np.asarray(raw, dtype=np.float64)
|
| 854 |
+
if result.shape == (1, 3):
|
| 855 |
+
result = result[0]
|
| 856 |
+
if result.shape != (3,) or not np.isfinite(result).all():
|
| 857 |
+
raise RuntimeReadError("RoboMME actor position must be finite xyz")
|
| 858 |
+
return result
|
| 859 |
+
|
| 860 |
+
|
| 861 |
+
def _online_subgoal(info: Any) -> str | None:
|
| 862 |
+
if not isinstance(info, Mapping):
|
| 863 |
+
return None
|
| 864 |
+
raw = info.get("simple_subgoal_online", info.get("simple_subgoal"))
|
| 865 |
+
if isinstance(raw, Sequence) and not isinstance(raw, (str, bytes)):
|
| 866 |
+
raw = raw[-1] if raw else None
|
| 867 |
+
return _canonical_subgoal(raw) if isinstance(raw, str) else None
|
| 868 |
+
|
| 869 |
+
|
| 870 |
+
def _plain_json(value: Any) -> Any:
|
| 871 |
+
if value is None or isinstance(value, (str, bool, int)):
|
| 872 |
+
return value
|
| 873 |
+
if isinstance(value, (float, np.floating)):
|
| 874 |
+
result = float(value)
|
| 875 |
+
if not math.isfinite(result):
|
| 876 |
+
raise RuntimeReadError("simulator identity contains non-finite values")
|
| 877 |
+
return result
|
| 878 |
+
if isinstance(value, np.integer):
|
| 879 |
+
return int(value)
|
| 880 |
+
if isinstance(value, np.ndarray):
|
| 881 |
+
return _plain_json(value.tolist())
|
| 882 |
+
if isinstance(value, Mapping):
|
| 883 |
+
return {str(key): _plain_json(child) for key, child in value.items()}
|
| 884 |
+
if isinstance(value, Sequence) and not isinstance(value, (str, bytes)):
|
| 885 |
+
return [_plain_json(child) for child in value]
|
| 886 |
+
# Gym specs are objects; bind their stable public identifier rather than a
|
| 887 |
+
# repr that can contain an address.
|
| 888 |
+
identifier = getattr(value, "id", None)
|
| 889 |
+
if isinstance(identifier, str) and identifier:
|
| 890 |
+
return {"id": identifier}
|
| 891 |
+
raise RuntimeReadError(f"simulator identity contains unsupported {type(value).__name__}")
|
| 892 |
+
|
| 893 |
+
|
| 894 |
+
def _unwrapped(env: Any) -> Any:
|
| 895 |
+
value = getattr(env, "unwrapped", None)
|
| 896 |
+
if value is None:
|
| 897 |
+
raise RuntimeReadError("RoboMME environment has no unwrapped task instance")
|
| 898 |
+
return value
|
| 899 |
+
|
| 900 |
+
|
| 901 |
+
def _required_attr(value: Any, name: str) -> Any:
|
| 902 |
+
if not hasattr(value, name):
|
| 903 |
+
raise RuntimeReadError(f"RoboMME simulator is missing required current field {name!r}")
|
| 904 |
+
return getattr(value, name)
|
| 905 |
+
|
| 906 |
+
|
| 907 |
+
def _canonical_instruction(value: Any) -> str:
|
| 908 |
+
if not isinstance(value, str) or not value.strip():
|
| 909 |
+
raise RuntimeReadError("RoboMME task_goal must be a non-empty string")
|
| 910 |
+
return " ".join(value.strip().lower().split())
|
| 911 |
+
|
| 912 |
+
|
| 913 |
+
def _canonical_subgoal(value: Any) -> str:
|
| 914 |
+
if not isinstance(value, str):
|
| 915 |
+
raise RuntimeReadError("RoboMME subgoal must be a string")
|
| 916 |
+
return " ".join(value.strip().lower().split())
|
| 917 |
+
|
| 918 |
+
|
| 919 |
+
def _bool(value: Any, name: str) -> bool:
|
| 920 |
+
if not isinstance(value, (bool, np.bool_)):
|
| 921 |
+
raise RuntimeReadError(f"RoboMME {name} must be boolean")
|
| 922 |
+
return bool(value)
|
| 923 |
+
|
| 924 |
+
|
| 925 |
+
def _terminal_outcome(value: Mapping[str, Any] | None) -> dict[str, Any] | None:
|
| 926 |
+
if value is None:
|
| 927 |
+
return None
|
| 928 |
+
if not isinstance(value, Mapping) or set(value) != _TERMINAL_OUTCOME_FIELDS:
|
| 929 |
+
raise RuntimeReadError("terminal_outcome fields mismatch")
|
| 930 |
+
if not isinstance(value["stop"], (bool, np.bool_)) or not bool(value["stop"]):
|
| 931 |
+
raise RuntimeReadError("terminal_outcome.stop must be true")
|
| 932 |
+
status = value["status"]
|
| 933 |
+
if not isinstance(status, str) or status not in TERMINAL_STATUSES:
|
| 934 |
+
raise RuntimeReadError("terminal_outcome.status is unsupported")
|
| 935 |
+
return {"stop": True, "status": status}
|
| 936 |
+
|
| 937 |
+
|
| 938 |
+
def _receipt_event_ids(
|
| 939 |
+
receipt: Mapping[str, Any],
|
| 940 |
+
name: str,
|
| 941 |
+
*,
|
| 942 |
+
field: str = "runtime_event_ids",
|
| 943 |
+
) -> list[str]:
|
| 944 |
+
raw = receipt.get(field)
|
| 945 |
+
if not isinstance(raw, list) or any(not isinstance(value, str) or not value or "\0" in value for value in raw):
|
| 946 |
+
raise RuntimeReadError(f"Phase-A rollout ACK {name}.{field} must be a list of event IDs")
|
| 947 |
+
return list(raw)
|
| 948 |
+
|
| 949 |
+
|
| 950 |
+
def _receipt_runtime_events(receipt: Mapping[str, Any], name: str) -> list[dict[str, Any]]:
|
| 951 |
+
raw = receipt.get("runtime_events")
|
| 952 |
+
if not isinstance(raw, list) or any(not isinstance(value, Mapping) for value in raw):
|
| 953 |
+
raise RuntimeReadError(f"Phase-A rollout ACK {name}.runtime_events must be a list of mappings")
|
| 954 |
+
return [deepcopy(dict(value)) for value in raw]
|
| 955 |
+
|
| 956 |
+
|
| 957 |
+
def _receipt_nat(receipt: Mapping[str, Any], field: str, name: str) -> int:
|
| 958 |
+
return _nat(receipt.get(field), f"ACK {name}.{field}")
|
| 959 |
+
|
| 960 |
+
|
| 961 |
+
def _text(value: Any, name: str) -> str:
|
| 962 |
+
if not isinstance(value, str) or not value or "\0" in value:
|
| 963 |
+
raise RuntimeReadError(f"{name} must be a non-empty string without NUL")
|
| 964 |
+
return value
|
| 965 |
+
|
| 966 |
+
|
| 967 |
+
def _validated_runtime_receipt(value: Any) -> dict[str, Any]:
|
| 968 |
+
if not isinstance(value, Mapping):
|
| 969 |
+
raise RuntimeReadError("Phase-A rollout ACK runtime_receipt must be a mapping")
|
| 970 |
+
receipt = deepcopy(dict(value))
|
| 971 |
+
if receipt.get("schema_version") != RUNTIME_RECEIPT_SCHEMA_VERSION:
|
| 972 |
+
raise RuntimeReadError("Phase-A rollout ACK runtime_receipt schema_version mismatch")
|
| 973 |
+
receipt_sha256 = _sha256(
|
| 974 |
+
receipt.get("receipt_sha256"),
|
| 975 |
+
"ack.runtime_receipt.receipt_sha256",
|
| 976 |
+
)
|
| 977 |
+
body = {name: child for name, child in receipt.items() if name != "receipt_sha256"}
|
| 978 |
+
if canonical_json_sha256(body) != receipt_sha256:
|
| 979 |
+
raise RuntimeReadError("Phase-A rollout ACK runtime_receipt hash mismatch")
|
| 980 |
+
return receipt
|
| 981 |
+
|
| 982 |
+
|
| 983 |
+
def _sha256(value: Any, name: str) -> str:
|
| 984 |
+
if (
|
| 985 |
+
not isinstance(value, str)
|
| 986 |
+
or len(value) != 64
|
| 987 |
+
or any(character not in "0123456789abcdef" for character in value)
|
| 988 |
+
):
|
| 989 |
+
raise RuntimeReadError(f"{name} must be lowercase SHA-256")
|
| 990 |
+
return value
|
| 991 |
+
|
| 992 |
+
|
| 993 |
+
def _nat(value: Any, name: str) -> int:
|
| 994 |
+
if isinstance(value, bool) or not isinstance(value, (int, np.integer)) or int(value) < 0:
|
| 995 |
+
raise RuntimeReadError(f"{name} must be a non-negative integer")
|
| 996 |
+
return int(value)
|
| 997 |
+
|
| 998 |
+
|
| 999 |
+
def _pos(value: Any, name: str) -> int:
|
| 1000 |
+
result = _nat(value, name)
|
| 1001 |
+
if result <= 0:
|
| 1002 |
+
raise RuntimeReadError(f"{name} must be positive")
|
| 1003 |
+
return result
|
| 1004 |
+
|
| 1005 |
+
|
| 1006 |
+
__all__ = [
|
| 1007 |
+
"GENESIS_BATCH_SHA256",
|
| 1008 |
+
"PRODUCER_SCHEMA_VERSION",
|
| 1009 |
+
"RUNTIME_ACK_SCHEMA_VERSION",
|
| 1010 |
+
"RUNTIME_BATCH_SCHEMA_VERSION",
|
| 1011 |
+
"RUNTIME_ENVELOPE_SCHEMA_VERSION",
|
| 1012 |
+
"RUNTIME_RECEIPT_SCHEMA_VERSION",
|
| 1013 |
+
"RUNTIME_START_SCHEMA_VERSION",
|
| 1014 |
+
"RoboMMEPhaseAOracleProducer",
|
| 1015 |
+
"RuntimeEpisodeBinding",
|
| 1016 |
+
"acknowledge_runtime_buffer",
|
| 1017 |
+
"attach_runtime_to_buffer",
|
| 1018 |
+
]
|
checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_baseline.py
ADDED
|
@@ -0,0 +1,625 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Franka converted HDF5 to the existing pi05 baseline training pipeline.
|
| 2 |
+
|
| 3 |
+
Run with the robomme environment and the checkout root and robomme/src on PYTHONPATH.
|
| 4 |
+
Only converted HDF5 is read. No ROS runtime or raw bags are needed.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import argparse
|
| 10 |
+
import dataclasses
|
| 11 |
+
import json
|
| 12 |
+
import pickle
|
| 13 |
+
from concurrent.futures import ProcessPoolExecutor
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
import cv2
|
| 17 |
+
import h5py
|
| 18 |
+
import numpy as np
|
| 19 |
+
|
| 20 |
+
BASE = "_cam_base_camera_color_image_raw_compressed"
|
| 21 |
+
WRIST = "_cam_hand_camera_color_image_raw_compressed"
|
| 22 |
+
POSE = "_franka_robot_state_broadcaster_current_pose"
|
| 23 |
+
PROMPTS = {
|
| 24 |
+
"pick3": "Pick up the cube and place it on the plate exactly three times, lifting it clear between placements, then press the blue button.",
|
| 25 |
+
"button_order": "Press the buttons in the same order as shown in the demonstration.",
|
| 26 |
+
"shuffle": "Track the cup hiding the cube during the shuffle, then press the button next to that cup.",
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def canonical_pose(pose):
|
| 31 |
+
"""Cartesian xyz + unit xyzw, in the qx-positive chart used by these demos."""
|
| 32 |
+
pose = np.array(pose, dtype=np.float32, copy=True)
|
| 33 |
+
quaternion = pose[..., 3:7]
|
| 34 |
+
norm = np.linalg.norm(quaternion, axis=-1, keepdims=True)
|
| 35 |
+
if np.any(norm < 1e-6) or not np.isfinite(pose).all():
|
| 36 |
+
raise ValueError("Pose must be finite with a nonzero quaternion")
|
| 37 |
+
quaternion /= norm
|
| 38 |
+
# This dataset keeps the tool facing down. Reject a crossing of this chart
|
| 39 |
+
# instead of introducing a discontinuity; other workspaces need another chart.
|
| 40 |
+
if np.any(np.abs(quaternion[..., 0]) < 0.1):
|
| 41 |
+
raise ValueError("Quaternion is outside this dataset's qx-positive chart")
|
| 42 |
+
quaternion *= np.where(quaternion[..., :1] < 0, -1, 1)
|
| 43 |
+
return pose
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def command_targets(timestamps, joy_timestamps, buttons, initial_open):
|
| 47 |
+
"""14=open, 15=close; pressed command persists after button release.
|
| 48 |
+
|
| 49 |
+
Use the recorded Joy event time, not the nearest RGB frame, so a future
|
| 50 |
+
command cannot enter an earlier target. Simultaneous commands are unknown.
|
| 51 |
+
"""
|
| 52 |
+
order = np.argsort(joy_timestamps, kind="stable")
|
| 53 |
+
result = np.empty(len(timestamps), dtype=np.float32)
|
| 54 |
+
latch = initial_open
|
| 55 |
+
cursor = 0
|
| 56 |
+
for i, stamp in enumerate(timestamps):
|
| 57 |
+
while cursor < len(order) and joy_timestamps[order[cursor]] <= stamp:
|
| 58 |
+
opened, closed = buttons[order[cursor], 14:16] != 0
|
| 59 |
+
if opened or closed:
|
| 60 |
+
latch = np.nan if opened and closed else float(opened)
|
| 61 |
+
cursor += 1
|
| 62 |
+
result[i] = latch
|
| 63 |
+
return result
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def window_starts(timestamps, valid, horizon):
|
| 67 |
+
"""Complete windows on the original ~15 Hz clock, never across a data gap."""
|
| 68 |
+
if horizon <= 0:
|
| 69 |
+
raise ValueError("action horizon must be positive")
|
| 70 |
+
if len(timestamps) < horizon:
|
| 71 |
+
return np.empty(0, dtype=np.int64)
|
| 72 |
+
good = np.lib.stride_tricks.sliding_window_view(valid, horizon).all(axis=1)
|
| 73 |
+
if horizon > 1:
|
| 74 |
+
dt = np.diff(timestamps)
|
| 75 |
+
gaps_ok = (dt > 0) & (dt <= 100_000_000)
|
| 76 |
+
good &= np.lib.stride_tricks.sliding_window_view(gaps_ok, horizon - 1).all(axis=1)
|
| 77 |
+
return np.flatnonzero(good)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def initial_target(timestamps, joy_timestamps, buttons, widths):
|
| 81 |
+
"""Infer a recording-start command only from its uninterrupted endpoint.
|
| 82 |
+
|
| 83 |
+
A gripper can still be moving when recording starts. The first measured
|
| 84 |
+
width is therefore not its target. This uses the pre-command response as
|
| 85 |
+
offline supervision only; no future measurements become model inputs.
|
| 86 |
+
"""
|
| 87 |
+
events = joy_timestamps[np.any(buttons[:, 14:16], axis=1)]
|
| 88 |
+
prefix = widths[timestamps < events.min()] if len(events) else widths
|
| 89 |
+
prefix = prefix[np.isfinite(prefix)]
|
| 90 |
+
if len(prefix) < 5 or np.ptp(prefix[-5:]) > 0.05:
|
| 91 |
+
return np.nan
|
| 92 |
+
if np.all(prefix[-5:] >= 0.9) and np.all(np.diff(prefix) >= -0.05):
|
| 93 |
+
return 1.0
|
| 94 |
+
if np.all(prefix[-5:] <= 0.1) and np.all(np.diff(prefix) <= 0.05):
|
| 95 |
+
return 0.0
|
| 96 |
+
return np.nan
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def decode_image(dataset):
|
| 100 |
+
image = cv2.imdecode(dataset[:], cv2.IMREAD_COLOR)
|
| 101 |
+
if image is None:
|
| 102 |
+
raise ValueError(f"Invalid JPEG: {dataset.name}")
|
| 103 |
+
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
| 104 |
+
return prepare_rgb(image)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def prepare_rgb(image):
|
| 108 |
+
"""The same RGB resize/padding for converted data and online inference."""
|
| 109 |
+
image = np.asarray(image)
|
| 110 |
+
if image.shape[:2] == (224, 224):
|
| 111 |
+
return image
|
| 112 |
+
h, w = image.shape[:2]
|
| 113 |
+
scale = 224 / max(h, w)
|
| 114 |
+
image = cv2.resize(image, (int(w * scale), int(h * scale)), interpolation=cv2.INTER_LINEAR)
|
| 115 |
+
result = np.zeros((224, 224, 3), dtype=np.uint8)
|
| 116 |
+
y, x = (224 - image.shape[0]) // 2, (224 - image.shape[1]) // 2
|
| 117 |
+
result[y : y + image.shape[0], x : x + image.shape[1]] = image
|
| 118 |
+
return result
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def convert_episode(args):
|
| 122 |
+
path, output, episode_id, horizon = args
|
| 123 |
+
cv2.setNumThreads(1)
|
| 124 |
+
with h5py.File(path, "r") as source:
|
| 125 |
+
keys = sorted(source)
|
| 126 |
+
n = len(keys)
|
| 127 |
+
timestamps = np.zeros(n, dtype=np.int64)
|
| 128 |
+
joy_timestamps = np.zeros(n, dtype=np.int64)
|
| 129 |
+
buttons = np.zeros((n, 16), dtype=np.int32)
|
| 130 |
+
state = np.full((n, 8), np.nan, dtype=np.float32)
|
| 131 |
+
actions = np.full((n, 8), np.nan, dtype=np.float32)
|
| 132 |
+
valid = np.zeros(n, dtype=bool)
|
| 133 |
+
action_synced = np.zeros(n, dtype=bool)
|
| 134 |
+
missing_wrist = 0
|
| 135 |
+
required = [
|
| 136 |
+
BASE,
|
| 137 |
+
WRIST,
|
| 138 |
+
POSE + "_position",
|
| 139 |
+
POSE + "_orientation",
|
| 140 |
+
"_target_pose_position",
|
| 141 |
+
"_target_pose_orientation",
|
| 142 |
+
"_franka_gripper_joint_states/position",
|
| 143 |
+
]
|
| 144 |
+
for i, key in enumerate(keys):
|
| 145 |
+
frame = source[key]
|
| 146 |
+
timestamps[i] = frame.attrs["timestamp"]
|
| 147 |
+
joy_timestamps[i] = frame["original_timestamps"].attrs.get("_spacenav_joy", timestamps[i])
|
| 148 |
+
if "_spacenav_joy_buttons" in frame:
|
| 149 |
+
values = frame["_spacenav_joy_buttons"][:]
|
| 150 |
+
buttons[i, : min(16, len(values))] = values[:16]
|
| 151 |
+
if "_franka_gripper_joint_states/position" in frame:
|
| 152 |
+
gripper = frame["_franka_gripper_joint_states"]
|
| 153 |
+
names = [name.decode() for name in gripper["joint_names"][:]]
|
| 154 |
+
if len(names) != 2 or not all("finger_joint" in name for name in names):
|
| 155 |
+
raise ValueError(f"Unexpected gripper joints: {names}")
|
| 156 |
+
state[i, 7] = np.sum(gripper["position"][:]) / 0.08
|
| 157 |
+
if "_target_pose_position" in frame and "_target_pose_orientation" in frame:
|
| 158 |
+
actions[i, :7] = canonical_pose(
|
| 159 |
+
np.r_[frame["_target_pose_position"][:], frame["_target_pose_orientation"][:]]
|
| 160 |
+
)
|
| 161 |
+
action_synced[i] = abs(frame["sync_quality"].attrs.get("_target_pose", np.inf)) <= 40_000_000
|
| 162 |
+
missing_wrist += WRIST not in frame
|
| 163 |
+
if not all(k in frame for k in required):
|
| 164 |
+
continue
|
| 165 |
+
state[i, :7] = canonical_pose(np.r_[frame[POSE + "_position"][:], frame[POSE + "_orientation"][:]])
|
| 166 |
+
sync = frame["sync_quality"].attrs
|
| 167 |
+
valid[i] = all(
|
| 168 |
+
abs(sync.get(k, np.inf)) <= 40_000_000 for k in [WRIST, POSE, "_franka_gripper_joint_states"]
|
| 169 |
+
)
|
| 170 |
+
initial_open = initial_target(timestamps, joy_timestamps, buttons, state[:, 7])
|
| 171 |
+
actions[:, 7] = command_targets(timestamps, joy_timestamps, buttons, initial_open)
|
| 172 |
+
valid &= np.isfinite(state).all(axis=1)
|
| 173 |
+
# Only the observation at the start of a chunk is a model input.
|
| 174 |
+
# Future action targets need synchronized commands, not future images.
|
| 175 |
+
action_valid = action_synced & np.isfinite(actions).all(axis=1)
|
| 176 |
+
starts = window_starts(timestamps, action_valid, horizon)
|
| 177 |
+
starts = starts[valid[starts]]
|
| 178 |
+
output.mkdir(parents=True, exist_ok=False)
|
| 179 |
+
for local_index, i in enumerate(starts):
|
| 180 |
+
frame = source[keys[i]]
|
| 181 |
+
sample = {
|
| 182 |
+
"image": decode_image(frame[BASE]),
|
| 183 |
+
"wrist_image": decode_image(frame[WRIST]),
|
| 184 |
+
"state": state[i],
|
| 185 |
+
"actions": actions[i : i + horizon],
|
| 186 |
+
"prompt": PROMPTS[path.parent.name],
|
| 187 |
+
"epis_idx": np.asarray(episode_id),
|
| 188 |
+
"step_idx": np.asarray(i),
|
| 189 |
+
"timestamp_ns": timestamps[i],
|
| 190 |
+
}
|
| 191 |
+
with (output / f"{local_index}.pkl").open("xb") as handle:
|
| 192 |
+
pickle.dump(sample, handle, protocol=pickle.HIGHEST_PROTOCOL)
|
| 193 |
+
summary = {
|
| 194 |
+
"episode": path.stem,
|
| 195 |
+
"task": path.parent.name,
|
| 196 |
+
"frames": n,
|
| 197 |
+
"samples": len(starts),
|
| 198 |
+
"missing_wrist": int(missing_wrist),
|
| 199 |
+
"invalid_frames": int((~valid).sum()),
|
| 200 |
+
"initial_gripper_open": float(initial_open) if np.isfinite(initial_open) else None,
|
| 201 |
+
"fps": float(1e9 / np.median(np.diff(timestamps))),
|
| 202 |
+
}
|
| 203 |
+
return summary, state[starts], actions[starts[:, None] + np.arange(horizon)]
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def prepare(source, output, horizon=20, workers=8):
|
| 207 |
+
from openpi.shared import normalize
|
| 208 |
+
|
| 209 |
+
files = sorted(Path(source).glob("*/*.h5"))
|
| 210 |
+
if not files:
|
| 211 |
+
raise ValueError("No converted HDF5 episodes found")
|
| 212 |
+
output = Path(output)
|
| 213 |
+
output.mkdir(parents=True, exist_ok=False)
|
| 214 |
+
splits = {"train": [], "validation": []}
|
| 215 |
+
# Split whole episodes, independently within each task, with a fixed seed.
|
| 216 |
+
rng = np.random.default_rng(42)
|
| 217 |
+
for task in sorted({p.parent.name for p in files}):
|
| 218 |
+
group = [p for p in files if p.parent.name == task]
|
| 219 |
+
order = rng.permutation(len(group))
|
| 220 |
+
held_out = set(order[: max(1, round(len(group) * 0.1))])
|
| 221 |
+
for i, path in enumerate(group):
|
| 222 |
+
splits["validation" if i in held_out else "train"].append(path)
|
| 223 |
+
stats = {key: normalize.RunningStats() for key in ["state", "actions"]}
|
| 224 |
+
summaries = []
|
| 225 |
+
with ProcessPoolExecutor(workers) as pool:
|
| 226 |
+
for split, paths in splits.items():
|
| 227 |
+
data_dir = output / split / "data"
|
| 228 |
+
data_dir.mkdir(parents=True)
|
| 229 |
+
jobs = [(path, output / "episodes" / path.stem, files.index(path), horizon) for path in paths]
|
| 230 |
+
count = 0
|
| 231 |
+
for (summary, states, actions), job in zip(pool.map(convert_episode, jobs), jobs, strict=True):
|
| 232 |
+
summary["split"] = split
|
| 233 |
+
summaries.append(summary)
|
| 234 |
+
for i in range(summary["samples"]):
|
| 235 |
+
(job[1] / f"{i}.pkl").rename(data_dir / f"{count + i}.pkl")
|
| 236 |
+
job[1].rmdir()
|
| 237 |
+
count += summary["samples"]
|
| 238 |
+
if split == "train" and len(states):
|
| 239 |
+
stats["state"].update(states)
|
| 240 |
+
stats["actions"].update(actions)
|
| 241 |
+
print(json.dumps(summary), flush=True)
|
| 242 |
+
(output / split / "meta").mkdir()
|
| 243 |
+
(output / split / "meta" / "stats.json").write_text(json.dumps({"total_samples": count}))
|
| 244 |
+
normalize.save(output / "assets" / "franka", {key: value.get_statistics() for key, value in stats.items()})
|
| 245 |
+
(output / "episodes").rmdir()
|
| 246 |
+
(output / "dataset.json").write_text(
|
| 247 |
+
json.dumps(
|
| 248 |
+
{
|
| 249 |
+
"source": str(Path(source).resolve()),
|
| 250 |
+
"action_horizon": horizon,
|
| 251 |
+
"representation": "absolute flange xyz, unit xyzw with qx positive, gripper open in [0,1]",
|
| 252 |
+
"gripper": (
|
| 253 |
+
"Joy 14 open / 15 close, latched at original event timestamps; initial stable measured endpoint"
|
| 254 |
+
),
|
| 255 |
+
"image_processing": "JPEG decode to RGB, aspect-preserving 224x224 bilinear resize with black padding",
|
| 256 |
+
"sync_tolerance_ms": 40,
|
| 257 |
+
"max_window_gap_ms": 100,
|
| 258 |
+
"prompts": PROMPTS,
|
| 259 |
+
"episodes": summaries,
|
| 260 |
+
},
|
| 261 |
+
indent=2,
|
| 262 |
+
)
|
| 263 |
+
)
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
@dataclasses.dataclass(frozen=True)
|
| 267 |
+
class FrankaInputs:
|
| 268 |
+
disable_context_gripper_command: bool = False
|
| 269 |
+
|
| 270 |
+
def __call__(self, data):
|
| 271 |
+
result = {
|
| 272 |
+
"image": {"base_0_rgb": data["image"], "left_wrist_0_rgb": data["wrist_image"]},
|
| 273 |
+
"image_mask": {"base_0_rgb": np.True_, "left_wrist_0_rgb": np.True_},
|
| 274 |
+
"state": np.r_[canonical_pose(data["state"][:7]), data["state"][7]].astype(np.float32),
|
| 275 |
+
"prompt": data["prompt"],
|
| 276 |
+
"simple_subgoal": None,
|
| 277 |
+
"grounded_subgoal": None,
|
| 278 |
+
}
|
| 279 |
+
if "actions" in data:
|
| 280 |
+
result["actions"] = data["actions"]
|
| 281 |
+
if "action_component_valid_mask" in data:
|
| 282 |
+
result["action_component_valid_mask"] = data["action_component_valid_mask"]
|
| 283 |
+
for key in [
|
| 284 |
+
"static_image_emb", "static_pos_emb", "static_state_emb", "static_mask",
|
| 285 |
+
"current_subgoal", "transition_context_action_delta", "transition_context_state_delta",
|
| 286 |
+
"transition_context_relative_age", "transition_context_valid_mask",
|
| 287 |
+
"transition_span_target", "transition_last_span_target", "transition_status_valid",
|
| 288 |
+
"transition_last_span_valid",
|
| 289 |
+
]:
|
| 290 |
+
if data.get(key) is not None:
|
| 291 |
+
result[key] = data[key]
|
| 292 |
+
if self.disable_context_gripper_command and "transition_context_action_delta" in result:
|
| 293 |
+
context = np.asarray(result["transition_context_action_delta"]).copy()
|
| 294 |
+
context[..., 7] = 0
|
| 295 |
+
result["transition_context_action_delta"] = context
|
| 296 |
+
return result
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
@dataclasses.dataclass(frozen=True)
|
| 300 |
+
class FrankaOutputs:
|
| 301 |
+
def __call__(self, data):
|
| 302 |
+
actions = np.asarray(data["actions"])[..., :8].copy()
|
| 303 |
+
actions[..., :7] = canonical_pose(actions[..., :7])
|
| 304 |
+
actions[..., 7] = np.clip(actions[..., 7], 0, 1)
|
| 305 |
+
return {"actions": actions}
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
@dataclasses.dataclass(frozen=True)
|
| 309 |
+
class ResizeOnlyWhenNeeded:
|
| 310 |
+
def __call__(self, data):
|
| 311 |
+
if all(image.shape[:2] == (224, 224) for image in data["image"].values()):
|
| 312 |
+
return data
|
| 313 |
+
return {**data, "image": {key: prepare_rgb(image) for key, image in data["image"].items()}}
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
@dataclasses.dataclass(frozen=True)
|
| 317 |
+
class FrankaDataConfig:
|
| 318 |
+
assets_path: str
|
| 319 |
+
partial_supervision: bool = False
|
| 320 |
+
disable_context_gripper_command: bool = False
|
| 321 |
+
|
| 322 |
+
def create(self, assets_dirs, model_config):
|
| 323 |
+
from mme_vla_suite.training import config
|
| 324 |
+
from openpi import transforms
|
| 325 |
+
from openpi.shared import normalize
|
| 326 |
+
|
| 327 |
+
stats = normalize.load(Path(self.assets_path))
|
| 328 |
+
data_inputs = [FrankaInputs(self.disable_context_gripper_command)]
|
| 329 |
+
model_transforms = config.ModelTransformFactory()(model_config)
|
| 330 |
+
model_inputs = list(model_transforms.inputs)
|
| 331 |
+
if self.partial_supervision:
|
| 332 |
+
from integrations.robomme.franka_partial import BoundedStateForTokenization
|
| 333 |
+
|
| 334 |
+
data_inputs.append(BoundedStateForTokenization(stats["state"]))
|
| 335 |
+
model_inputs = [
|
| 336 |
+
dataclasses.replace(
|
| 337 |
+
transform,
|
| 338 |
+
tokenizer=config.PaligemmaTokenizer(model_config.max_token_len, reject_truncation=True),
|
| 339 |
+
state_input_key="state_for_tokenization",
|
| 340 |
+
) if isinstance(transform, config.TokenizePromptWithMemory) else transform
|
| 341 |
+
for transform in model_inputs
|
| 342 |
+
]
|
| 343 |
+
model_transforms = transforms.Group(
|
| 344 |
+
inputs=[ResizeOnlyWhenNeeded() if isinstance(transform, transforms.ResizeImages) else transform
|
| 345 |
+
for transform in model_inputs],
|
| 346 |
+
outputs=model_transforms.outputs,
|
| 347 |
+
)
|
| 348 |
+
return config.DataConfig(
|
| 349 |
+
repo_id="franka",
|
| 350 |
+
asset_id="franka",
|
| 351 |
+
norm_stats=stats,
|
| 352 |
+
use_quantile_norm=not self.partial_supervision,
|
| 353 |
+
data_transforms=transforms.Group(inputs=data_inputs, outputs=[FrankaOutputs()]),
|
| 354 |
+
model_transforms=model_transforms,
|
| 355 |
+
)
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
def equivalent_step_budget(reference_steps=25000, reference_batch=1, global_batch=4):
|
| 359 |
+
"""Preserve example count and sample-based warmup/EMA timescales."""
|
| 360 |
+
if min(reference_steps, reference_batch, global_batch) <= 0:
|
| 361 |
+
raise ValueError("Steps and batch sizes must be positive")
|
| 362 |
+
return {
|
| 363 |
+
"reference_steps": reference_steps, "reference_global_batch": reference_batch,
|
| 364 |
+
"global_batch": global_batch, "sample_exposures": reference_steps * reference_batch,
|
| 365 |
+
"steps": (reference_steps * reference_batch + global_batch - 1) // global_batch,
|
| 366 |
+
"warmup_steps": (1000 * reference_batch + global_batch - 1) // global_batch,
|
| 367 |
+
"ema_decay": .999 ** (global_batch / reference_batch),
|
| 368 |
+
}
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
FORMAL_BUDGET = equivalent_step_budget()
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
def model_repo_id(task, history_frames, step):
|
| 375 |
+
"""User-facing names explicitly identify global/per-GPU batch and checkpoint."""
|
| 376 |
+
variant = f"uniform{history_frames}" if history_frames else "baseline"
|
| 377 |
+
return f"fm-dev/pi05-{task.replace('_', '-')}-{variant}-lora-gbs4-pgb1-gpu4-step{step}"
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
def make_train_config(
|
| 381 |
+
dataset, run_root, steps=FORMAL_BUDGET["steps"], resume=False, uniform_history=False,
|
| 382 |
+
save_interval=5000, warmup_steps=FORMAL_BUDGET["warmup_steps"], decay_steps=FORMAL_BUDGET["steps"],
|
| 383 |
+
exp_name="button-order", log_interval=100, history_frames=32,
|
| 384 |
+
):
|
| 385 |
+
from mme_vla_suite.training import config
|
| 386 |
+
from openpi.training import optimizer, weight_loaders
|
| 387 |
+
|
| 388 |
+
dataset, run_root = Path(dataset).resolve(), Path(run_root).resolve()
|
| 389 |
+
spec = json.loads((dataset / "dataset.json").read_text())
|
| 390 |
+
partial = spec.get("partial_action_supervision", False)
|
| 391 |
+
cfg = config.get_config("pi05_baseline")
|
| 392 |
+
cfg = dataclasses.replace(
|
| 393 |
+
cfg,
|
| 394 |
+
name="pi05_franka_baseline",
|
| 395 |
+
exp_name=exp_name,
|
| 396 |
+
model=dataclasses.replace(
|
| 397 |
+
cfg.model, action_horizon=spec["action_horizon"], discrete_state_input=True, max_token_len=128
|
| 398 |
+
),
|
| 399 |
+
data=FrankaDataConfig(str(dataset / "assets" / "franka"), partial_supervision=partial),
|
| 400 |
+
dataset_path=str(dataset / "train"),
|
| 401 |
+
batch_size=4 if partial else 8,
|
| 402 |
+
fsdp_devices=1 if partial else 4,
|
| 403 |
+
num_workers=4 if partial else 0,
|
| 404 |
+
ema_decay=FORMAL_BUDGET["ema_decay"] if partial else 0.99,
|
| 405 |
+
num_train_steps=steps,
|
| 406 |
+
full_state_checkpoints=True,
|
| 407 |
+
lr_schedule=optimizer.CosineDecaySchedule(
|
| 408 |
+
warmup_steps=warmup_steps, peak_lr=5e-5 if partial else 2.5e-5,
|
| 409 |
+
decay_steps=decay_steps, decay_lr=5e-6 if partial else 2.5e-6,
|
| 410 |
+
),
|
| 411 |
+
checkpoint_base_dir=str(run_root / "checkpoints"),
|
| 412 |
+
weight_loader=weight_loaders.CheckpointWeightLoader(
|
| 413 |
+
"/data/robomme/models/openpi/openpi-assets/checkpoints/pi05_base/params"
|
| 414 |
+
),
|
| 415 |
+
save_interval=save_interval,
|
| 416 |
+
keep_period=save_interval,
|
| 417 |
+
log_interval=log_interval,
|
| 418 |
+
wandb_enabled=False,
|
| 419 |
+
resume=resume,
|
| 420 |
+
policy_metadata={
|
| 421 |
+
"dataset": str(dataset),
|
| 422 |
+
"representation": spec["representation"],
|
| 423 |
+
"gripper": spec["gripper"],
|
| 424 |
+
"run_purpose": "fine-tuning" if steps > 110 else "local training pipeline validation",
|
| 425 |
+
"target_steps": steps,
|
| 426 |
+
"save_interval": save_interval,
|
| 427 |
+
"task": spec.get("task", "pick3 + button_order"),
|
| 428 |
+
"prompt": spec.get("prompts", {}).get(spec.get("task")),
|
| 429 |
+
"partial_action_supervision": partial,
|
| 430 |
+
"unsupervised_action_components": spec.get("unsupervised_action_components", []),
|
| 431 |
+
"current_state_tokens": spec.get("current_state_tokens", "legacy quantile input"),
|
| 432 |
+
},
|
| 433 |
+
metrics_path=str(run_root / "metrics.tsv"),
|
| 434 |
+
)
|
| 435 |
+
if uniform_history:
|
| 436 |
+
from mme_vla_suite.models.config.utils import resolve_history_config_path
|
| 437 |
+
|
| 438 |
+
if history_frames not in (16, 32):
|
| 439 |
+
raise ValueError("Franka uniform history supports 16 or 32 frames")
|
| 440 |
+
history_path = resolve_history_config_path(f"perceptual-franka-uniform{history_frames}-modul.yaml")
|
| 441 |
+
cfg = dataclasses.replace(
|
| 442 |
+
cfg,
|
| 443 |
+
name=f"pi05_franka_uniform{history_frames}_baseline",
|
| 444 |
+
model=dataclasses.replace(cfg.model, use_history=True, history_config=str(history_path)),
|
| 445 |
+
policy_metadata={
|
| 446 |
+
**cfg.policy_metadata,
|
| 447 |
+
"history": {
|
| 448 |
+
"sampling": "uniform over [0,t], inclusive",
|
| 449 |
+
"frames": history_frames,
|
| 450 |
+
"camera": "base",
|
| 451 |
+
"tokens_per_frame": 16,
|
| 452 |
+
"integration": "FrameSamp modulation",
|
| 453 |
+
},
|
| 454 |
+
},
|
| 455 |
+
)
|
| 456 |
+
if partial:
|
| 457 |
+
from flax import nnx
|
| 458 |
+
from openpi.shared import nnx_utils
|
| 459 |
+
from integrations.robomme.franka_partial import CartesianWeightLoader
|
| 460 |
+
|
| 461 |
+
model = dataclasses.replace(
|
| 462 |
+
cfg.model, action_dim=8, paligemma_variant="gemma_2b_lora", action_expert_variant="gemma_300m_lora"
|
| 463 |
+
)
|
| 464 |
+
cfg = dataclasses.replace(
|
| 465 |
+
cfg, model=model,
|
| 466 |
+
freeze_filter=nnx.Any(model.get_freeze_filter(), nnx_utils.PathRegex("time_mlp_.*")),
|
| 467 |
+
weight_loader=CartesianWeightLoader(cfg.weight_loader.params_path),
|
| 468 |
+
policy_metadata={**cfg.policy_metadata, "training_recipe": {
|
| 469 |
+
"method": "LoRA + Cartesian projections + optional history modules",
|
| 470 |
+
"gpus": 4, "global_batch_size": 4, "fsdp_devices": 1,
|
| 471 |
+
"gradient_accumulation": 1, "action_dim": 8, "action_horizon": 20,
|
| 472 |
+
"max_token_len": 128, "ema_decay": FORMAL_BUDGET["ema_decay"],
|
| 473 |
+
"reference_steps": 25000, "reference_global_batch": 1,
|
| 474 |
+
"reference_ema_decay": .999, "reference_warmup_steps": 1000,
|
| 475 |
+
"sample_exposures": steps * 4,
|
| 476 |
+
"warmup_steps": warmup_steps, "decay_steps": decay_steps,
|
| 477 |
+
"peak_lr": 5e-5, "decay_lr": 5e-6,
|
| 478 |
+
}},
|
| 479 |
+
)
|
| 480 |
+
return cfg
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
def train(dataset, run_root, steps=FORMAL_BUDGET["steps"], resume=False, uniform_history=False, **training_options):
|
| 484 |
+
import os
|
| 485 |
+
import sys
|
| 486 |
+
|
| 487 |
+
if uniform_history:
|
| 488 |
+
# Free temporary initialization buffers so concurrent policy servers
|
| 489 |
+
# can share the four GPUs. The model/batch/optimizer are unchanged.
|
| 490 |
+
os.environ.setdefault("XLA_PYTHON_CLIENT_ALLOCATOR", "platform")
|
| 491 |
+
root = Path(__file__).resolve().parents[2]
|
| 492 |
+
sys.path.insert(0, str(root / "robomme" / "scripts"))
|
| 493 |
+
import train as trainer
|
| 494 |
+
|
| 495 |
+
config = make_train_config(dataset, run_root, steps, resume, uniform_history, **training_options)
|
| 496 |
+
config = dataclasses.replace(config, policy_metadata={
|
| 497 |
+
**config.policy_metadata, "gpu_allocator": os.environ.get("XLA_PYTHON_CLIENT_ALLOCATOR", "default"),
|
| 498 |
+
})
|
| 499 |
+
trainer.main(config)
|
| 500 |
+
assets = config.checkpoint_dir / str(steps) / "assets"
|
| 501 |
+
if uniform_history:
|
| 502 |
+
(assets / "history_config.yaml").write_text(Path(config.model.history_config).read_text())
|
| 503 |
+
(assets / "policy_metadata.json").write_text(json.dumps(config.policy_metadata, indent=2))
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
def replay(dataset, checkpoint, output, uniform_history=False, history_frames=32):
|
| 507 |
+
"""Reload a serving checkpoint and run one held-out observation per episode."""
|
| 508 |
+
from mme_vla_suite.policies.policy_config import create_trained_policy
|
| 509 |
+
|
| 510 |
+
dataset, checkpoint = Path(dataset), Path(checkpoint)
|
| 511 |
+
config = make_train_config(dataset, checkpoint.parents[3], uniform_history=uniform_history, history_frames=history_frames)
|
| 512 |
+
policy = create_trained_policy(config, checkpoint)
|
| 513 |
+
spec = json.loads((dataset / "dataset.json").read_text())
|
| 514 |
+
results = []
|
| 515 |
+
offset = 0
|
| 516 |
+
for episode in spec["episodes"]:
|
| 517 |
+
if episode["split"] != "validation":
|
| 518 |
+
continue
|
| 519 |
+
count = episode["samples"]
|
| 520 |
+
if count:
|
| 521 |
+
with (dataset / "validation" / "data" / f"{offset + count // 2}.pkl").open("rb") as handle:
|
| 522 |
+
sample = pickle.load(handle)
|
| 523 |
+
if uniform_history:
|
| 524 |
+
from picmem.data.semantic_transition.sampling import even_sampling_indices
|
| 525 |
+
|
| 526 |
+
policy.reset()
|
| 527 |
+
step = int(sample["step_idx"])
|
| 528 |
+
episode_id = int(sample["epis_idx"])
|
| 529 |
+
for index in even_sampling_indices(step, policy._metadata["history"]["frames"]):
|
| 530 |
+
feature = dataset / "features" / f"episode_{episode_id}" / f"token_emb_{index}.npy"
|
| 531 |
+
policy.mem_buffer._history_feats[index] = np.load(feature, allow_pickle=True).item()
|
| 532 |
+
policy.step_idx = step
|
| 533 |
+
prediction = policy.infer({key: sample[key] for key in ["image", "wrist_image", "state", "prompt"]})
|
| 534 |
+
actions = prediction["actions"]
|
| 535 |
+
if actions.shape != (spec["action_horizon"], 8) or not np.isfinite(actions).all():
|
| 536 |
+
raise ValueError(f"Invalid policy output for {episode['episode']}")
|
| 537 |
+
results.append(
|
| 538 |
+
{
|
| 539 |
+
"episode": episode["episode"],
|
| 540 |
+
"task": episode["task"],
|
| 541 |
+
"shape": list(actions.shape),
|
| 542 |
+
"all_finite": True,
|
| 543 |
+
"gripper_range": [float(actions[:, 7].min()), float(actions[:, 7].max())],
|
| 544 |
+
"infer_time_ms": float(prediction["infer_time_ms"]),
|
| 545 |
+
}
|
| 546 |
+
)
|
| 547 |
+
print(json.dumps(results[-1]), flush=True)
|
| 548 |
+
offset += count
|
| 549 |
+
Path(output).write_text(
|
| 550 |
+
json.dumps(
|
| 551 |
+
{
|
| 552 |
+
"checkpoint": str(checkpoint),
|
| 553 |
+
"observations": results,
|
| 554 |
+
"scope": "offline checkpoint load and finite-output check; no robot rollout",
|
| 555 |
+
},
|
| 556 |
+
indent=2,
|
| 557 |
+
)
|
| 558 |
+
)
|
| 559 |
+
|
| 560 |
+
|
| 561 |
+
def load_policy(checkpoint):
|
| 562 |
+
"""Load either formal model using only its exported checkpoint directory."""
|
| 563 |
+
from mme_vla_suite.training import config as training_config
|
| 564 |
+
from mme_vla_suite.policies.policy_config import create_trained_policy
|
| 565 |
+
|
| 566 |
+
checkpoint = Path(checkpoint).resolve()
|
| 567 |
+
metadata = json.loads((checkpoint / "assets/policy_metadata.json").read_text())
|
| 568 |
+
if not metadata.get("partial_action_supervision"):
|
| 569 |
+
raise ValueError("This entrypoint expects the verified partial Cartesian8 training recipe")
|
| 570 |
+
cfg = training_config.get_config("pi05_baseline")
|
| 571 |
+
history_path = checkpoint / "assets/history_config.yaml"
|
| 572 |
+
cfg = dataclasses.replace(
|
| 573 |
+
cfg,
|
| 574 |
+
model=dataclasses.replace(
|
| 575 |
+
cfg.model, action_dim=8, action_horizon=20,
|
| 576 |
+
max_token_len=metadata.get("training_recipe", {}).get("max_token_len", 128), discrete_state_input=True,
|
| 577 |
+
paligemma_variant="gemma_2b_lora", action_expert_variant="gemma_300m_lora",
|
| 578 |
+
use_history=history_path.exists(), history_config=str(history_path) if history_path.exists() else None,
|
| 579 |
+
),
|
| 580 |
+
data=FrankaDataConfig(
|
| 581 |
+
str(checkpoint / "assets/franka"), partial_supervision=True,
|
| 582 |
+
disable_context_gripper_command=metadata.get("disable_context_gripper_command", False),
|
| 583 |
+
),
|
| 584 |
+
policy_metadata=metadata,
|
| 585 |
+
)
|
| 586 |
+
return create_trained_policy(cfg, checkpoint)
|
| 587 |
+
|
| 588 |
+
|
| 589 |
+
def observe(policy, base_rgb, state):
|
| 590 |
+
"""Append each observed source frame, including current, before uniform-history inference."""
|
| 591 |
+
if policy.mem_buffer is None:
|
| 592 |
+
return
|
| 593 |
+
state = np.r_[canonical_pose(np.asarray(state)[:7]), np.asarray(state)[7]].astype(np.float32)
|
| 594 |
+
policy.add_buffer({"images": prepare_rgb(base_rgb)[None, None], "state": state[None]})
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
if __name__ == "__main__":
|
| 598 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 599 |
+
commands = parser.add_subparsers(dest="command", required=True)
|
| 600 |
+
prep = commands.add_parser("prepare")
|
| 601 |
+
prep.add_argument("--source", type=Path, required=True)
|
| 602 |
+
prep.add_argument("--output", type=Path, required=True)
|
| 603 |
+
prep.add_argument("--horizon", type=int, default=20)
|
| 604 |
+
prep.add_argument("--workers", type=int, default=8)
|
| 605 |
+
training = commands.add_parser("train")
|
| 606 |
+
training.add_argument("--dataset", type=Path, required=True)
|
| 607 |
+
training.add_argument("--run-root", type=Path, required=True)
|
| 608 |
+
training.add_argument("--steps", type=int, default=FORMAL_BUDGET["steps"])
|
| 609 |
+
training.add_argument("--resume", action="store_true")
|
| 610 |
+
training.add_argument("--uniform-history", action="store_true")
|
| 611 |
+
training.add_argument("--history-frames", type=int, choices=[16, 32], default=32)
|
| 612 |
+
training.add_argument("--save-interval", type=int, default=5000)
|
| 613 |
+
training.add_argument("--warmup-steps", type=int, default=FORMAL_BUDGET["warmup_steps"])
|
| 614 |
+
training.add_argument("--decay-steps", type=int, default=FORMAL_BUDGET["steps"])
|
| 615 |
+
training.add_argument("--exp-name", default="button-order")
|
| 616 |
+
training.add_argument("--log-interval", type=int, default=100)
|
| 617 |
+
replay_parser = commands.add_parser("replay")
|
| 618 |
+
replay_parser.add_argument("--dataset", type=Path, required=True)
|
| 619 |
+
replay_parser.add_argument("--checkpoint", type=Path, required=True)
|
| 620 |
+
replay_parser.add_argument("--output", type=Path, required=True)
|
| 621 |
+
replay_parser.add_argument("--uniform-history", action="store_true")
|
| 622 |
+
replay_parser.add_argument("--history-frames", type=int, choices=[16, 32], default=32)
|
| 623 |
+
args = vars(parser.parse_args())
|
| 624 |
+
command = args.pop("command")
|
| 625 |
+
{"prepare": prepare, "train": train, "replay": replay}[command](**args)
|
checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_execution.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Select execution action rows while retaining each episode's complete visual history."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
from collections import Counter
|
| 6 |
+
import copy
|
| 7 |
+
import json
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
import pickle
|
| 10 |
+
import tempfile
|
| 11 |
+
|
| 12 |
+
import numpy as np
|
| 13 |
+
|
| 14 |
+
from integrations.robomme.franka_partial import validate_actions
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def prepare(dataset, annotations, output):
|
| 18 |
+
from openpi.shared import normalize
|
| 19 |
+
|
| 20 |
+
dataset, annotations, output = map(Path, (dataset, annotations, output))
|
| 21 |
+
if output.exists():
|
| 22 |
+
raise FileExistsError(f"Preserve the existing dataset: {output}")
|
| 23 |
+
spec = copy.deepcopy(json.loads((dataset / "dataset.json").read_text()))
|
| 24 |
+
task = spec["task"]
|
| 25 |
+
candidates = {}
|
| 26 |
+
for path in (annotations / "events-candidates-v1" / task).glob("*.json"):
|
| 27 |
+
record = json.loads(path.read_text())
|
| 28 |
+
if "raw_episode_id" in record:
|
| 29 |
+
candidates[record["raw_episode_id"]] = record
|
| 30 |
+
writer_version = "writer-astra-real-v2" if task == "button_order" else "writer-astra-real-v1"
|
| 31 |
+
episodes = {record["episode_id"]: record for record in spec["episodes"]}
|
| 32 |
+
source_offsets, cursor = {}, 0
|
| 33 |
+
for episode in spec["episodes"]:
|
| 34 |
+
source_offsets[episode["episode_id"]] = cursor
|
| 35 |
+
cursor += episode["frames"]
|
| 36 |
+
if episode["split"] == "excluded":
|
| 37 |
+
continue
|
| 38 |
+
annotation = candidates[episode["episode"]]
|
| 39 |
+
if annotation["total_frames"] != episode["frames"]:
|
| 40 |
+
raise ValueError(f"Annotation/frame count mismatch: {episode['episode']}")
|
| 41 |
+
writer = json.loads((annotations / writer_version / task / f"episode_{annotation['episode_id']:06d}.json").read_text())
|
| 42 |
+
if writer["total_frames"] != episode["frames"] or writer["first_decision_frame"] != annotation["execution_start"]:
|
| 43 |
+
raise ValueError(f"Writer/phase boundary mismatch: {episode['episode']}")
|
| 44 |
+
episode.update(execution_start=annotation["execution_start"], writer_episode_id=annotation["episode_id"])
|
| 45 |
+
spec["prompts"][task] = writer["task_instruction"]
|
| 46 |
+
output.parent.mkdir(parents=True, exist_ok=True)
|
| 47 |
+
states, actions, counts, episode_counts = {}, {}, {}, Counter()
|
| 48 |
+
with tempfile.TemporaryDirectory(prefix=f".{output.name}-", dir=output.parent) as temporary:
|
| 49 |
+
build = Path(temporary)
|
| 50 |
+
(build / "features").symlink_to((dataset / "features").resolve(), target_is_directory=True)
|
| 51 |
+
for split in ("train", "validation", "test"):
|
| 52 |
+
(build / split / "data").mkdir(parents=True)
|
| 53 |
+
(build / split / "meta").mkdir()
|
| 54 |
+
(build / split / "features").symlink_to("../features", target_is_directory=True)
|
| 55 |
+
count = 0
|
| 56 |
+
paths = sorted((dataset / split / "data").glob("*.pkl"), key=lambda p: int(p.stem))
|
| 57 |
+
for path in paths:
|
| 58 |
+
with path.open("rb") as stream:
|
| 59 |
+
row = pickle.load(stream)
|
| 60 |
+
episode_id, frame = int(row["epis_idx"]), int(row["step_idx"])
|
| 61 |
+
episode = episodes[episode_id]
|
| 62 |
+
if frame < episode["execution_start"]:
|
| 63 |
+
continue
|
| 64 |
+
validate_actions(row["actions"], row["action_component_valid_mask"])
|
| 65 |
+
row.update(exec_start_idx=np.asarray(episode["execution_start"]), is_demo=np.asarray(False),
|
| 66 |
+
global_episode_id=np.asarray(episode_id), task_id=f"franka_{task}",
|
| 67 |
+
source_index=np.asarray(source_offsets[episode_id] + frame), prompt=spec["prompts"][task])
|
| 68 |
+
with (build / split / "data" / f"{count}.pkl").open("xb") as stream:
|
| 69 |
+
pickle.dump(row, stream, protocol=pickle.HIGHEST_PROTOCOL)
|
| 70 |
+
count += 1
|
| 71 |
+
episode_counts[episode_id] += 1
|
| 72 |
+
if split == "train":
|
| 73 |
+
states[episode_id, frame] = row["state"]
|
| 74 |
+
for offset, action in enumerate(row["actions"]):
|
| 75 |
+
key = episode_id, frame + offset
|
| 76 |
+
if key in actions and not np.array_equal(actions[key], action, equal_nan=True):
|
| 77 |
+
raise ValueError(f"Overlapping action windows disagree: {key}")
|
| 78 |
+
actions[key] = action
|
| 79 |
+
counts[split] = count
|
| 80 |
+
(build / split / "meta/stats.json").write_text(json.dumps({"total_samples": count, "execution_samples": count}))
|
| 81 |
+
norms, valid_counts = {}, {}
|
| 82 |
+
for field, rows in (("state", states), ("actions", actions)):
|
| 83 |
+
matrix = np.stack(list(rows.values()))
|
| 84 |
+
columns = [v[np.isfinite(v)] for v in matrix.T]
|
| 85 |
+
if any(not len(v) for v in columns[:7]) or field == "state" and not len(columns[7]):
|
| 86 |
+
raise ValueError(f"Missing required normalization evidence: {field}")
|
| 87 |
+
norms[field] = normalize.NormStats(
|
| 88 |
+
mean=np.array([v.mean() if len(v) else 0 for v in columns]),
|
| 89 |
+
std=np.array([v.std() if len(v) else 1 for v in columns]),
|
| 90 |
+
q01=np.array([np.quantile(v, .01) if len(v) else 0 for v in columns]),
|
| 91 |
+
q99=np.array([np.quantile(v, .99) if len(v) else 0 for v in columns]),
|
| 92 |
+
)
|
| 93 |
+
valid_counts[field] = [len(v) for v in columns]
|
| 94 |
+
normalize.save(build / "assets/franka", norms)
|
| 95 |
+
for episode in spec["episodes"]:
|
| 96 |
+
episode["samples"] = episode_counts[episode["episode_id"]]
|
| 97 |
+
spec.update(counts=counts, normalization_valid_counts=valid_counts,
|
| 98 |
+
normalization="train-only known-component STD; unique frames used in execution training windows",
|
| 99 |
+
action_supervision="execution frames only; demonstration frames retained as visual history",
|
| 100 |
+
frame_coordinates="original episode/frame IDs, never shifted at execution start",
|
| 101 |
+
representation="absolute recorded end-effector xyz, unit xyzw with qx positive, commanded gripper open in [0,1]",
|
| 102 |
+
previous_dataset=str(dataset.resolve()), annotation_source=str(annotations.resolve()),
|
| 103 |
+
unsupervised_action_components=[i for i, count in enumerate(valid_counts["actions"]) if not count])
|
| 104 |
+
(build / "dataset.json").write_text(json.dumps(spec, indent=2))
|
| 105 |
+
build.rename(output)
|
| 106 |
+
return {"task": task, "counts": counts, "output": str(output), "history_start_frame": 0}
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
if __name__ == "__main__":
|
| 110 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 111 |
+
for name in ("dataset", "annotations", "output"):
|
| 112 |
+
parser.add_argument("--" + name, type=Path, required=True)
|
| 113 |
+
print(json.dumps(prepare(**vars(parser.parse_args()))), flush=True)
|
checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_history.py
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Cache frozen base-camera features for the existing Uniform16 FrameSamp loader."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import json
|
| 7 |
+
import multiprocessing
|
| 8 |
+
import os
|
| 9 |
+
import pickle
|
| 10 |
+
import shutil
|
| 11 |
+
from concurrent.futures import ProcessPoolExecutor
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
import cv2
|
| 15 |
+
import h5py
|
| 16 |
+
import numpy as np
|
| 17 |
+
|
| 18 |
+
from integrations.robomme.franka_baseline import BASE, POSE, canonical_pose, decode_image
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def decode_episode(path):
|
| 22 |
+
cv2.setNumThreads(1)
|
| 23 |
+
with h5py.File(path, "r") as source:
|
| 24 |
+
keys = sorted(source)
|
| 25 |
+
images = np.empty((len(keys), 224, 224, 3), dtype=np.uint8)
|
| 26 |
+
states = np.zeros((len(keys), 8), dtype=np.float32)
|
| 27 |
+
state_valid = np.zeros(len(keys), dtype=bool)
|
| 28 |
+
for i, key in enumerate(keys):
|
| 29 |
+
frame = source[key]
|
| 30 |
+
images[i] = decode_image(frame[BASE])
|
| 31 |
+
required = [POSE + "_position", POSE + "_orientation", "_franka_gripper_joint_states/position"]
|
| 32 |
+
if all(name in frame for name in required):
|
| 33 |
+
states[i, :7] = canonical_pose(np.r_[frame[required[0]][:], frame[required[1]][:]])
|
| 34 |
+
states[i, 7] = frame[required[2]][:].sum() / 0.08
|
| 35 |
+
state_valid[i] = True
|
| 36 |
+
# The recipe uses visual/position history only. Missing historical state
|
| 37 |
+
# remains a finite placeholder and is recorded, never used by the encoder.
|
| 38 |
+
return images, states, state_valid
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def frozen_encoder():
|
| 42 |
+
import flax.nnx as nnx
|
| 43 |
+
import flax.nnx.bridge as bridge
|
| 44 |
+
import jax
|
| 45 |
+
import jax.numpy as jnp
|
| 46 |
+
from openpi.models import model, siglip
|
| 47 |
+
|
| 48 |
+
params = model.restore_params(
|
| 49 |
+
"/data/robomme/models/openpi/openpi-assets/checkpoints/pi05_base/params",
|
| 50 |
+
restore_type=np.ndarray,
|
| 51 |
+
)["PaliGemma"]["img"]
|
| 52 |
+
encoder = bridge.ToNNX(
|
| 53 |
+
siglip.Module(
|
| 54 |
+
num_classes=2048,
|
| 55 |
+
variant="So400m/14",
|
| 56 |
+
pool_type="none",
|
| 57 |
+
scan=True,
|
| 58 |
+
dtype_mm="bfloat16",
|
| 59 |
+
)
|
| 60 |
+
)
|
| 61 |
+
encoder.lazy_init(jnp.zeros((1, 224, 224, 3)), train=False, rngs=nnx.Rngs(0))
|
| 62 |
+
graph, state = nnx.split(encoder)
|
| 63 |
+
# Match init_train_state's frozen-parameter dtype and checkpoint exactly.
|
| 64 |
+
state.replace_by_pure_dict(jax.tree.map(lambda x: jnp.asarray(x, dtype=jnp.bfloat16), params))
|
| 65 |
+
return nnx.merge(graph, state)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def prepare(dataset, output, workers=8, batch_size=32):
|
| 69 |
+
import flax.nnx as nnx
|
| 70 |
+
import jax
|
| 71 |
+
import jax.numpy as jnp
|
| 72 |
+
from mme_vla_suite.shared.data_utils import pool_tokens_to_size
|
| 73 |
+
from mme_vla_suite.shared.posemb_3d import PosEmb3D
|
| 74 |
+
|
| 75 |
+
dataset, output = Path(dataset).resolve(), Path(output).resolve()
|
| 76 |
+
spec = json.loads((dataset / "dataset.json").read_text())
|
| 77 |
+
paths = sorted(Path(spec["source"]).glob("*/*.h5"))
|
| 78 |
+
output.mkdir(parents=True, exist_ok=False)
|
| 79 |
+
features = output / "features"
|
| 80 |
+
features.mkdir()
|
| 81 |
+
encoder = frozen_encoder()
|
| 82 |
+
position_encoder = PosEmb3D(768)
|
| 83 |
+
|
| 84 |
+
@nnx.jit
|
| 85 |
+
def encode(module, images):
|
| 86 |
+
tokens, _ = module(images, train=False)
|
| 87 |
+
return pool_tokens_to_size(tokens, 16)
|
| 88 |
+
|
| 89 |
+
summaries = []
|
| 90 |
+
with ProcessPoolExecutor(workers, mp_context=multiprocessing.get_context("spawn")) as pool:
|
| 91 |
+
for episode_id, (path, decoded) in enumerate(zip(paths, pool.map(decode_episode, paths), strict=True)):
|
| 92 |
+
images, states, state_valid = decoded
|
| 93 |
+
destination = features / f"episode_{episode_id}"
|
| 94 |
+
destination.mkdir()
|
| 95 |
+
positions = np.asarray(position_encoder(jnp.arange(len(images)), 4), dtype=np.float32)
|
| 96 |
+
for start in range(0, len(images), batch_size):
|
| 97 |
+
batch = images[start : start + batch_size]
|
| 98 |
+
length = len(batch)
|
| 99 |
+
# A fixed batch shape avoids recompiling for every episode tail.
|
| 100 |
+
if length < batch_size:
|
| 101 |
+
batch = np.pad(batch, ((0, batch_size - length), (0, 0), (0, 0), (0, 0)))
|
| 102 |
+
embeddings = np.asarray(
|
| 103 |
+
encode(encoder, jnp.asarray(batch, dtype=jnp.float32) / 127.5 - 1), dtype=np.float32
|
| 104 |
+
)
|
| 105 |
+
for offset in range(length):
|
| 106 |
+
i = start + offset
|
| 107 |
+
np.save(
|
| 108 |
+
destination / f"token_emb_{i}.npy",
|
| 109 |
+
{
|
| 110 |
+
"image_emb_4x4": embeddings[offset : offset + 1],
|
| 111 |
+
"pos_emb_4x4": positions[i : i + 1],
|
| 112 |
+
"state_emb": states[i],
|
| 113 |
+
},
|
| 114 |
+
)
|
| 115 |
+
summary = {
|
| 116 |
+
"episode": path.stem,
|
| 117 |
+
"episode_id": episode_id,
|
| 118 |
+
"frames": len(images),
|
| 119 |
+
"missing_unused_state_frames": int((~state_valid).sum()),
|
| 120 |
+
}
|
| 121 |
+
summaries.append(summary)
|
| 122 |
+
print(json.dumps(summary), flush=True)
|
| 123 |
+
del encoder
|
| 124 |
+
jax.clear_caches()
|
| 125 |
+
|
| 126 |
+
for split in ["train", "validation"]:
|
| 127 |
+
destination = output / split
|
| 128 |
+
(destination / "data").mkdir(parents=True)
|
| 129 |
+
shutil.copytree(dataset / split / "meta", destination / "meta")
|
| 130 |
+
(destination / "features").symlink_to("../features", target_is_directory=True)
|
| 131 |
+
count = json.loads((destination / "meta" / "stats.json").read_text())["total_samples"]
|
| 132 |
+
for i in range(count):
|
| 133 |
+
with (dataset / split / "data" / f"{i}.pkl").open("rb") as handle:
|
| 134 |
+
row = pickle.load(handle)
|
| 135 |
+
# FrameSamp samples the whole observed prefix and does not use this
|
| 136 |
+
# recurrent/Status compatibility field to select its history.
|
| 137 |
+
row["exec_start_idx"] = np.asarray(0)
|
| 138 |
+
with (destination / "data" / f"{i}.pkl").open("xb") as handle:
|
| 139 |
+
pickle.dump(row, handle, protocol=pickle.HIGHEST_PROTOCOL)
|
| 140 |
+
shutil.copytree(dataset / "assets", output / "assets")
|
| 141 |
+
spec["baseline_dataset"] = str(dataset)
|
| 142 |
+
spec["history"] = {
|
| 143 |
+
"frames": 16,
|
| 144 |
+
"sampling": "even_sampling_indices(t,16), inclusive [0,t]",
|
| 145 |
+
"camera": "base",
|
| 146 |
+
"tokens_per_frame": 16,
|
| 147 |
+
"tokens": 256,
|
| 148 |
+
"use_historical_state": False,
|
| 149 |
+
"position": "absolute source-frame index and 4x4 spatial position",
|
| 150 |
+
"vision_checkpoint": "/data/robomme/models/openpi/openpi-assets/checkpoints/pi05_base/params",
|
| 151 |
+
"vision_dtype": "bfloat16",
|
| 152 |
+
"cache_dtype": "float32",
|
| 153 |
+
}
|
| 154 |
+
(output / "dataset.json").write_text(json.dumps(spec, indent=2))
|
| 155 |
+
(output / "feature-summary.json").write_text(json.dumps(summaries, indent=2))
|
| 156 |
+
print(f"Completed: {len(summaries)} episodes, {sum(row['frames'] for row in summaries)} frame features", flush=True)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def select_task(dataset, output, task):
|
| 160 |
+
"""Reuse source rows and cached features; fit normalization on one task's train split."""
|
| 161 |
+
from openpi.shared import normalize
|
| 162 |
+
|
| 163 |
+
dataset, output = Path(dataset).resolve(), Path(output).resolve()
|
| 164 |
+
spec = json.loads((dataset / "dataset.json").read_text())
|
| 165 |
+
selected = [episode for episode in spec["episodes"] if episode["task"] == task]
|
| 166 |
+
if not selected:
|
| 167 |
+
raise ValueError(f"No episodes for task {task}")
|
| 168 |
+
output.mkdir(parents=True, exist_ok=False)
|
| 169 |
+
(output / "features").symlink_to(dataset / "features", target_is_directory=True)
|
| 170 |
+
statistics = {key: normalize.RunningStats() for key in ["state", "actions"]}
|
| 171 |
+
counts = {"train": 0, "validation": 0}
|
| 172 |
+
offsets = dict(counts)
|
| 173 |
+
for split in counts:
|
| 174 |
+
(output / split / "data").mkdir(parents=True)
|
| 175 |
+
(output / split / "meta").mkdir()
|
| 176 |
+
(output / split / "features").symlink_to("../features", target_is_directory=True)
|
| 177 |
+
for episode in spec["episodes"]:
|
| 178 |
+
split, count = episode["split"], episode["samples"]
|
| 179 |
+
start = offsets[split]
|
| 180 |
+
offsets[split] += count
|
| 181 |
+
if episode["task"] != task:
|
| 182 |
+
continue
|
| 183 |
+
for index in range(start, start + count):
|
| 184 |
+
source = dataset / split / "data" / f"{index}.pkl"
|
| 185 |
+
os.link(source, output / split / "data" / f"{counts[split]}.pkl")
|
| 186 |
+
counts[split] += 1
|
| 187 |
+
if split == "train":
|
| 188 |
+
with source.open("rb") as handle:
|
| 189 |
+
row = pickle.load(handle)
|
| 190 |
+
for key in statistics:
|
| 191 |
+
statistics[key].update(row[key][None])
|
| 192 |
+
for split, count in counts.items():
|
| 193 |
+
(output / split / "meta" / "stats.json").write_text(json.dumps({"total_samples": count}))
|
| 194 |
+
normalize.save(output / "assets" / "franka", {key: value.get_statistics() for key, value in statistics.items()})
|
| 195 |
+
spec.update({"episodes": selected, "task": task, "parent_dataset": str(dataset),
|
| 196 |
+
"normalization_source": f"{task} training episodes only"})
|
| 197 |
+
(output / "dataset.json").write_text(json.dumps(spec, indent=2))
|
| 198 |
+
print(json.dumps({"task": task, "episodes": len(selected), "samples": counts}), flush=True)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def cache_task(source, output, task, batch_size=8):
|
| 202 |
+
"""Cache every original frame for an additional task using the frozen encoder."""
|
| 203 |
+
import flax.nnx as nnx
|
| 204 |
+
import jax.numpy as jnp
|
| 205 |
+
from mme_vla_suite.shared.data_utils import pool_tokens_to_size
|
| 206 |
+
from mme_vla_suite.shared.posemb_3d import PosEmb3D
|
| 207 |
+
|
| 208 |
+
source, output = Path(source), Path(output)
|
| 209 |
+
paths = sorted(source.glob("*/*.h5"))
|
| 210 |
+
selected = [(i,p) for i,p in enumerate(paths) if p.parent.name == task]
|
| 211 |
+
if not selected:
|
| 212 |
+
raise ValueError(f"No converted episodes for {task}")
|
| 213 |
+
output.mkdir(parents=True, exist_ok=True)
|
| 214 |
+
encoder = frozen_encoder()
|
| 215 |
+
position_encoder = PosEmb3D(768)
|
| 216 |
+
|
| 217 |
+
@nnx.jit
|
| 218 |
+
def encode(module, images):
|
| 219 |
+
tokens, _ = module(images, train=False)
|
| 220 |
+
return pool_tokens_to_size(tokens, 16)
|
| 221 |
+
|
| 222 |
+
records = []
|
| 223 |
+
for episode_id, path in selected:
|
| 224 |
+
images, states, state_valid = decode_episode(path)
|
| 225 |
+
destination = output / f"episode_{episode_id}"
|
| 226 |
+
destination.mkdir(exist_ok=True)
|
| 227 |
+
positions = np.asarray(position_encoder(jnp.arange(len(images)), 4), dtype=np.float32)
|
| 228 |
+
for start in range(0, len(images), batch_size):
|
| 229 |
+
batch = images[start:start + batch_size]
|
| 230 |
+
length = len(batch)
|
| 231 |
+
batch = np.pad(batch, ((0,batch_size-length),(0,0),(0,0),(0,0)))
|
| 232 |
+
embeddings = np.asarray(encode(encoder, jnp.asarray(batch, dtype=jnp.float32) / 127.5 - 1), dtype=np.float32)
|
| 233 |
+
for offset in range(length):
|
| 234 |
+
i = start + offset
|
| 235 |
+
np.save(destination / f"token_emb_{i}.npy", {
|
| 236 |
+
"image_emb_4x4": embeddings[offset:offset + 1],
|
| 237 |
+
"pos_emb_4x4": positions[i:i + 1], "state_emb": states[i],
|
| 238 |
+
})
|
| 239 |
+
record = {"episode":path.stem,"episode_id":episode_id,"frames":len(images),
|
| 240 |
+
"missing_unused_state_frames":int((~state_valid).sum())}
|
| 241 |
+
records.append(record)
|
| 242 |
+
print(json.dumps(record),flush=True)
|
| 243 |
+
(output / "feature-summary.json").write_text(json.dumps(records,indent=2))
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
if __name__ == "__main__":
|
| 247 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 248 |
+
parser.add_argument("--dataset", type=Path, required=True)
|
| 249 |
+
parser.add_argument("--output", type=Path, required=True)
|
| 250 |
+
parser.add_argument("--workers", type=int, default=8)
|
| 251 |
+
parser.add_argument("--batch-size", type=int, default=32)
|
| 252 |
+
parser.add_argument("--task", help="Select one task from an already cached dataset instead of encoding features")
|
| 253 |
+
args = vars(parser.parse_args())
|
| 254 |
+
task = args.pop("task")
|
| 255 |
+
if task:
|
| 256 |
+
select_task(args["dataset"], args["output"], task)
|
| 257 |
+
else:
|
| 258 |
+
prepare(**args)
|
checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_matrix.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run the remaining real-robot tasks and archive every complete checkpoint."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import subprocess
|
| 8 |
+
import sys
|
| 9 |
+
import time
|
| 10 |
+
|
| 11 |
+
from integrations.robomme.franka_baseline import FORMAL_BUDGET, model_repo_id
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def checkpoint_jobs(matrix):
|
| 15 |
+
for task in matrix["tasks"]:
|
| 16 |
+
slug = task["task"].replace("_", "-")
|
| 17 |
+
for variant in ("baseline", "uniform32"):
|
| 18 |
+
config = "pi05_franka_baseline" if variant == "baseline" else "pi05_franka_uniform32_baseline"
|
| 19 |
+
for step in (5000, FORMAL_BUDGET["steps"]):
|
| 20 |
+
yield {
|
| 21 |
+
"task": task["task"], "variant": variant, "step": step,
|
| 22 |
+
"checkpoint": str(Path(task["run_root"]) / variant / "checkpoints" / config / slug / str(step)),
|
| 23 |
+
"repo_id": model_repo_id(task["task"], 32 if variant == "uniform32" else 0, step),
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def archive(matrix_path):
|
| 28 |
+
from huggingface_hub import HfApi
|
| 29 |
+
|
| 30 |
+
matrix_path = Path(matrix_path)
|
| 31 |
+
tasks = json.loads(matrix_path.read_text())
|
| 32 |
+
jobs = list(checkpoint_jobs(tasks))
|
| 33 |
+
receipts = matrix_path.parent / "checkpoint-uploads"
|
| 34 |
+
receipts.mkdir(exist_ok=True)
|
| 35 |
+
api = HfApi()
|
| 36 |
+
while jobs:
|
| 37 |
+
for job in jobs[:]:
|
| 38 |
+
source = Path(job["checkpoint"])
|
| 39 |
+
receipt = receipts / f"{job['task']}-{job['variant']}-{job['step']}.json"
|
| 40 |
+
if receipt.exists():
|
| 41 |
+
jobs.remove(job)
|
| 42 |
+
continue
|
| 43 |
+
if not (source / "_CHECKPOINT_METADATA").exists():
|
| 44 |
+
continue
|
| 45 |
+
if not (source / "resume_state").is_dir():
|
| 46 |
+
raise ValueError(f"Complete training state is missing: {source}")
|
| 47 |
+
print(f"Uploading complete checkpoint {job['task']}/{job['variant']}/{job['step']}", flush=True)
|
| 48 |
+
api.create_repo(job["repo_id"], repo_type="model", private=False, exist_ok=True)
|
| 49 |
+
commit = api.upload_folder(
|
| 50 |
+
repo_id=job["repo_id"], repo_type="model", folder_path=source,
|
| 51 |
+
commit_message=f"Archive complete {job['step']}-step checkpoint including optimizer and sampler",
|
| 52 |
+
)
|
| 53 |
+
remote = {f.path: f.size for f in api.list_repo_tree(job["repo_id"], recursive=True)
|
| 54 |
+
if hasattr(f, "size")}
|
| 55 |
+
files = [p for p in source.rglob("*") if p.is_file()]
|
| 56 |
+
for path in files:
|
| 57 |
+
name = path.relative_to(source).as_posix()
|
| 58 |
+
if remote.get(name) != path.stat().st_size:
|
| 59 |
+
raise RuntimeError(f"Remote checkpoint file missing or wrong size: {job['repo_id']}/{name}")
|
| 60 |
+
receipt.write_text(json.dumps({
|
| 61 |
+
**job, "commit": commit.oid, "complete_checkpoint_verified": True,
|
| 62 |
+
"files": len(files), "bytes": sum(p.stat().st_size for p in files),
|
| 63 |
+
}, indent=2))
|
| 64 |
+
jobs.remove(job)
|
| 65 |
+
print(f"Verified complete checkpoint: {job['repo_id']}", flush=True)
|
| 66 |
+
if jobs:
|
| 67 |
+
time.sleep(10)
|
| 68 |
+
print("All formal checkpoints uploaded with full resume state", flush=True)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def train_remaining(matrix_path, wait_pid):
|
| 72 |
+
import psutil
|
| 73 |
+
|
| 74 |
+
matrix_path = Path(matrix_path)
|
| 75 |
+
matrix = json.loads(matrix_path.read_text())
|
| 76 |
+
if wait_pid:
|
| 77 |
+
print(f"Waiting for current button_order controller PID {wait_pid}", flush=True)
|
| 78 |
+
try:
|
| 79 |
+
psutil.Process(wait_pid).wait()
|
| 80 |
+
except psutil.NoSuchProcess:
|
| 81 |
+
pass
|
| 82 |
+
button = next(t for t in matrix["tasks"] if t["task"] == "button_order")
|
| 83 |
+
button_root = Path(button["run_root"])
|
| 84 |
+
final = button_root / "uniform32/checkpoints/pi05_franka_uniform32_baseline/button-order" / str(FORMAL_BUDGET["steps"])
|
| 85 |
+
evaluation = button_root / "uniform32-evaluation.json"
|
| 86 |
+
if not (final / "_CHECKPOINT_METADATA").exists() or not evaluation.exists():
|
| 87 |
+
raise RuntimeError("button_order training/evaluation must finish before the remaining tasks start")
|
| 88 |
+
if not json.loads(evaluation.read_text())["all_outputs_finite"]:
|
| 89 |
+
raise RuntimeError("button_order final evaluation failed")
|
| 90 |
+
for task in matrix["tasks"]:
|
| 91 |
+
if task["task"] == "button_order":
|
| 92 |
+
continue
|
| 93 |
+
dataset = Path(task["dataset"])
|
| 94 |
+
if not (dataset / "dataset.json").exists():
|
| 95 |
+
raise RuntimeError(f"Prepared dataset is not ready: {dataset}")
|
| 96 |
+
print(f"Starting both settings for {task['task']}", flush=True)
|
| 97 |
+
with (matrix_path.parent / f"{task['task']}-controller.log").open("a") as log:
|
| 98 |
+
subprocess.run([
|
| 99 |
+
sys.executable, "-m", "integrations.robomme.franka_release", "run",
|
| 100 |
+
"--dataset", str(dataset), "--run-root", task["run_root"],
|
| 101 |
+
], stdout=log, stderr=subprocess.STDOUT, check=True)
|
| 102 |
+
print("All task/settings finished training and evaluation; check upload receipts separately", flush=True)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
if __name__ == "__main__":
|
| 106 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 107 |
+
parser.add_argument("command", choices=["archive", "train-remaining"])
|
| 108 |
+
parser.add_argument("--matrix-path", type=Path, required=True)
|
| 109 |
+
parser.add_argument("--wait-pid", type=int, default=0)
|
| 110 |
+
args = parser.parse_args()
|
| 111 |
+
if args.command == "archive":
|
| 112 |
+
archive(args.matrix_path)
|
| 113 |
+
else:
|
| 114 |
+
train_remaining(args.matrix_path, args.wait_pid)
|
checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_partial.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Verified partial Cartesian supervision and the local four-GPU Franka recipe.
|
| 2 |
+
|
| 3 |
+
Preparation reads converted HDF5 plus the saved Joy-edge/server evidence from
|
| 4 |
+
fm-dev/shulin_ws. It never reads ROS bags or infers commands from finger width.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import argparse
|
| 9 |
+
import dataclasses
|
| 10 |
+
import importlib.util
|
| 11 |
+
import json
|
| 12 |
+
import pickle
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
import h5py
|
| 16 |
+
import numpy as np
|
| 17 |
+
|
| 18 |
+
from integrations.robomme.franka_baseline import BASE, WRIST, POSE, PROMPTS, canonical_pose, decode_image, window_starts
|
| 19 |
+
|
| 20 |
+
PROMPT = PROMPTS["button_order"]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@dataclasses.dataclass(frozen=True)
|
| 24 |
+
class BoundedStateForTokenization:
|
| 25 |
+
stats: object
|
| 26 |
+
|
| 27 |
+
def __call__(self, data):
|
| 28 |
+
low, high = np.asarray(self.stats.q01), np.asarray(self.stats.q99)
|
| 29 |
+
span = high - low
|
| 30 |
+
state = np.asarray(data["state"], dtype=np.float32)
|
| 31 |
+
bounded = 2 * (state - low) / np.where(span > 1e-6, span, 1) - 1
|
| 32 |
+
return {**data, "state_for_tokenization": np.where(
|
| 33 |
+
span > 1e-6, np.clip(bounded, -1, 1), 0
|
| 34 |
+
).astype(np.float32)}
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@dataclasses.dataclass(frozen=True)
|
| 38 |
+
class CartesianWeightLoader:
|
| 39 |
+
params_path: str
|
| 40 |
+
|
| 41 |
+
def load(self, params):
|
| 42 |
+
from flax import traverse_util
|
| 43 |
+
from openpi.models import model
|
| 44 |
+
from openpi.training.weight_loaders import _merge_params
|
| 45 |
+
|
| 46 |
+
loaded = model.restore_params(self.params_path, restore_type=np.ndarray)
|
| 47 |
+
# The base's padded joint-space heads do not represent Cartesian D8.
|
| 48 |
+
for key in ("action_in_proj", "action_out_proj", "state_proj"):
|
| 49 |
+
loaded.pop(key, None)
|
| 50 |
+
reference = traverse_util.flatten_dict(params, sep="/")
|
| 51 |
+
for key, value in traverse_util.flatten_dict(loaded, sep="/").items():
|
| 52 |
+
if key in reference and value is not None and value.shape != reference[key].shape:
|
| 53 |
+
raise ValueError(f"Unexpected pretrained shape mismatch: {key}")
|
| 54 |
+
return _merge_params(loaded, params, missing_regex=".*")
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def validate_actions(actions, mask):
|
| 58 |
+
if actions.shape != mask.shape or actions.shape[-1] != 8 or mask.dtype != bool:
|
| 59 |
+
raise ValueError("Partial action arrays require matching [H,8] targets and boolean masks")
|
| 60 |
+
if not np.isfinite(actions[mask]).all() or not np.isnan(actions[~mask]).all():
|
| 61 |
+
raise ValueError("Known actions must be finite; unknown disk targets must be NaN")
|
| 62 |
+
if np.any(mask[..., 3:7] != mask[..., 3:4]):
|
| 63 |
+
raise ValueError("Quaternion validity must be all-or-none")
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def read_h5_signals(path):
|
| 67 |
+
"""Numeric signals from converted HDF5, with missing measurements left unknown."""
|
| 68 |
+
with h5py.File(path, "r") as source:
|
| 69 |
+
keys = sorted(source)
|
| 70 |
+
stamps = np.array([source[k].attrs["timestamp"] for k in keys], dtype=np.int64)
|
| 71 |
+
state_pose = np.full((len(keys), 7), np.nan)
|
| 72 |
+
target_pose = np.full((len(keys), 7), np.nan)
|
| 73 |
+
width = np.full(len(keys), np.nan)
|
| 74 |
+
for i, key in enumerate(keys):
|
| 75 |
+
frame = source[key]
|
| 76 |
+
if POSE + "_position" in frame and POSE + "_orientation" in frame:
|
| 77 |
+
state_pose[i] = np.r_[frame[POSE + "_position"][:], frame[POSE + "_orientation"][:]]
|
| 78 |
+
if "_target_pose_position" in frame and "_target_pose_orientation" in frame:
|
| 79 |
+
target_pose[i] = np.r_[frame["_target_pose_position"][:], frame["_target_pose_orientation"][:]]
|
| 80 |
+
if "_franka_gripper_joint_states/position" in frame:
|
| 81 |
+
width[i] = frame["_franka_gripper_joint_states/position"][:].sum() / .08
|
| 82 |
+
return stamps, state_pose, target_pose, width
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def prepare(source, reference, split_manifest, output, features, task="button_order"):
|
| 86 |
+
from openpi.shared import normalize
|
| 87 |
+
|
| 88 |
+
source, reference, output = Path(source), Path(reference), Path(output)
|
| 89 |
+
manifest = json.loads(Path(split_manifest).read_text())
|
| 90 |
+
entries = manifest["episodes"]
|
| 91 |
+
available = {p.stem: p for p in (source / task).glob("*.h5")}
|
| 92 |
+
if {e["raw_episode_id"] for e in entries} != set(available):
|
| 93 |
+
raise ValueError(f"Split must cover exactly the converted {task} episodes")
|
| 94 |
+
# Reuse the user's reviewed event/clock logic, never its older bootstrap.
|
| 95 |
+
evidence_source = reference / "scripts/build_franka_baseline_dataset.py"
|
| 96 |
+
module_spec = importlib.util.spec_from_file_location("franka_evidence", evidence_source)
|
| 97 |
+
evidence = importlib.util.module_from_spec(module_spec)
|
| 98 |
+
module_spec.loader.exec_module(evidence)
|
| 99 |
+
commands, server_counts = evidence.parse_server_commands(reference / "evidence/remote_gripper_server_events.log")
|
| 100 |
+
output.mkdir(parents=True, exist_ok=False)
|
| 101 |
+
(output / "features").symlink_to(Path(features).resolve(), target_is_directory=True)
|
| 102 |
+
counts = {"train": 0, "validation": 0, "test": 0}
|
| 103 |
+
for split in counts:
|
| 104 |
+
(output / split / "data").mkdir(parents=True)
|
| 105 |
+
(output / split / "meta").mkdir()
|
| 106 |
+
(output / split / "features").symlink_to("../features", target_is_directory=True)
|
| 107 |
+
# Feature IDs follow the original sorted converted inventory, not split order.
|
| 108 |
+
all_files = sorted(source.glob("*/*.h5"))
|
| 109 |
+
records, state_rows, action_rows = [], [], []
|
| 110 |
+
for entry in entries:
|
| 111 |
+
name, split = entry["raw_episode_id"], entry["split"]
|
| 112 |
+
path = available[name]
|
| 113 |
+
episode_id = all_files.index(path)
|
| 114 |
+
qc_path = reference / "data/qc_state" / f"{task}__{name}.npz"
|
| 115 |
+
if qc_path.exists():
|
| 116 |
+
with np.load(qc_path) as qc:
|
| 117 |
+
stamps = qc["ts"].copy()
|
| 118 |
+
state_pose = np.c_[qc["ee_pos"], qc["ee_quat"]]
|
| 119 |
+
target_pose = np.c_[qc["tgt_pos"], qc["tgt_quat"]]
|
| 120 |
+
width = qc["grip_pos"].sum(axis=1) / 0.08
|
| 121 |
+
else:
|
| 122 |
+
stamps, state_pose, target_pose, width = read_h5_signals(path)
|
| 123 |
+
n = len(stamps)
|
| 124 |
+
state = np.full((n, 8), np.nan, dtype=np.float32)
|
| 125 |
+
actions = np.full((n, 8), np.nan, dtype=np.float32)
|
| 126 |
+
state_finite = np.isfinite(state_pose).all(axis=1) & np.isfinite(width)
|
| 127 |
+
pose_finite = np.isfinite(target_pose).all(axis=1)
|
| 128 |
+
state[state_finite, :7] = canonical_pose(state_pose[state_finite])
|
| 129 |
+
state[state_finite, 7] = width[state_finite]
|
| 130 |
+
actions[pose_finite, :7] = canonical_pose(target_pose[pose_finite])
|
| 131 |
+
joy_path = reference / "evidence/joy_edges" / task / f"{name}.json"
|
| 132 |
+
verified = []
|
| 133 |
+
if joy_path.exists():
|
| 134 |
+
verified, _ = evidence.verified_commands(json.loads(joy_path.read_text()), commands)
|
| 135 |
+
actions[:, 7] = [np.nan if (v := evidence.command_at(int(t), verified)) is None else v for t in stamps]
|
| 136 |
+
mask = np.isfinite(actions)
|
| 137 |
+
# Keep the local 40 ms stream tolerance and 100 ms gap filter. Missing
|
| 138 |
+
# command evidence removes one component, not the known pose targets.
|
| 139 |
+
obs_valid = state_finite.copy()
|
| 140 |
+
target_synced = np.zeros(n, dtype=bool)
|
| 141 |
+
with h5py.File(path, "r") as h5:
|
| 142 |
+
keys = sorted(h5)
|
| 143 |
+
if len(keys) != n:
|
| 144 |
+
raise ValueError(f"QC/HDF5 frame count differs: {name}")
|
| 145 |
+
for i, key in enumerate(keys):
|
| 146 |
+
frame = h5[key]
|
| 147 |
+
if int(frame.attrs["timestamp"]) != int(stamps[i]):
|
| 148 |
+
raise ValueError(f"QC/HDF5 timestamp differs: {name}/{key}")
|
| 149 |
+
if POSE + "_position" in frame:
|
| 150 |
+
np.testing.assert_array_equal(frame[POSE + "_position"][:], state_pose[i, :3])
|
| 151 |
+
sync = frame["sync_quality"].attrs
|
| 152 |
+
obs_valid[i] &= BASE in frame and WRIST in frame and all(
|
| 153 |
+
abs(sync.get(k, np.inf)) <= 40_000_000
|
| 154 |
+
for k in (WRIST, POSE, "_franka_gripper_joint_states")
|
| 155 |
+
)
|
| 156 |
+
target_synced[i] = abs(sync.get("_target_pose", np.inf)) <= 40_000_000
|
| 157 |
+
starts = window_starts(stamps, pose_finite & target_synced, 20)
|
| 158 |
+
starts = starts[obs_valid[starts]]
|
| 159 |
+
if entry.get("exclude_reason"):
|
| 160 |
+
starts = starts[:0]
|
| 161 |
+
for i in starts:
|
| 162 |
+
frame = h5[keys[i]]
|
| 163 |
+
row = {
|
| 164 |
+
"image": decode_image(frame[BASE]), "wrist_image": decode_image(frame[WRIST]),
|
| 165 |
+
"state": state[i], "actions": actions[i:i + 20],
|
| 166 |
+
"action_component_valid_mask": mask[i:i + 20], "prompt": PROMPTS[task],
|
| 167 |
+
"epis_idx": np.asarray(episode_id), "step_idx": np.asarray(i),
|
| 168 |
+
"exec_start_idx": np.asarray(0), "timestamp_ns": stamps[i],
|
| 169 |
+
}
|
| 170 |
+
validate_actions(row["actions"], row["action_component_valid_mask"])
|
| 171 |
+
with (output / split / "data" / f"{counts[split]}.pkl").open("xb") as stream:
|
| 172 |
+
pickle.dump(row, stream, protocol=pickle.HIGHEST_PROTOCOL)
|
| 173 |
+
counts[split] += 1
|
| 174 |
+
if split == "train" and not entry.get("exclude_reason"):
|
| 175 |
+
state_rows.append(state[obs_valid])
|
| 176 |
+
# Fit once per original known source frame, avoiding window overlap weighting.
|
| 177 |
+
action_rows.append(actions[pose_finite & target_synced])
|
| 178 |
+
records.append({
|
| 179 |
+
"episode": name, "episode_id": episode_id, "task": task, "split": split,
|
| 180 |
+
"frames": n, "samples": len(starts), "known_gripper_frames": int(mask[:, 7].sum()),
|
| 181 |
+
"verified_commands": len(verified),
|
| 182 |
+
"exclude_reason": entry.get("exclude_reason"),
|
| 183 |
+
})
|
| 184 |
+
print(json.dumps(records[-1]), flush=True)
|
| 185 |
+
stats, valid_counts = {}, {}
|
| 186 |
+
for key, arrays in (("state", state_rows), ("actions", action_rows)):
|
| 187 |
+
values = np.concatenate(arrays).astype(np.float64)
|
| 188 |
+
known = [v[np.isfinite(v)] for v in values.T]
|
| 189 |
+
valid_counts[key] = [len(v) for v in known]
|
| 190 |
+
if any(len(v) == 0 for v in known[:7]) or (key == "state" and not len(known[7])):
|
| 191 |
+
raise ValueError(f"No training evidence for one or more {key} components")
|
| 192 |
+
# A wholly unobserved action-gripper dimension uses the physical unit
|
| 193 |
+
# coordinate (identity normalization), not invented fitted statistics.
|
| 194 |
+
# Its labels stay NaN/false and its output is explicitly unsupervised.
|
| 195 |
+
stats[key] = normalize.NormStats(
|
| 196 |
+
mean=np.array([v.mean() if len(v) else 0 for v in known]),
|
| 197 |
+
std=np.array([v.std() if len(v) else 1 for v in known]),
|
| 198 |
+
q01=np.array([np.quantile(v, .01) if len(v) else 0 for v in known]),
|
| 199 |
+
q99=np.array([np.quantile(v, .99) if len(v) else 1 for v in known]),
|
| 200 |
+
)
|
| 201 |
+
normalize.save(output / "assets/franka", stats)
|
| 202 |
+
for split, count in counts.items():
|
| 203 |
+
(output / split / "meta/stats.json").write_text(json.dumps({"total_samples": count}))
|
| 204 |
+
spec = {
|
| 205 |
+
"source": str(source), "task": task, "action_horizon": 20,
|
| 206 |
+
"prompts": {task: PROMPTS[task]},
|
| 207 |
+
"partial_action_supervision": True, "normalization": "train-only known-component STD",
|
| 208 |
+
"representation": "absolute flange xyz, unit xyzw with qx positive, commanded gripper open in [0,1]",
|
| 209 |
+
"gripper": "full-rate Joy edges matched to saved server requests; unknown=NaN/mask false; no bootstrap",
|
| 210 |
+
"split_manifest": str(split_manifest), "command_evidence_source": str(evidence_source),
|
| 211 |
+
"sync_tolerance_ms": 40, "max_window_gap_ms": 100,
|
| 212 |
+
"current_state_tokens": "train q01/q99 bounded [-1,1], constant spans map to zero",
|
| 213 |
+
"server_evidence_counts": server_counts, "episodes": records, "counts": counts,
|
| 214 |
+
"normalization_valid_counts": valid_counts,
|
| 215 |
+
"unsupervised_action_components": [i for i,n in enumerate(valid_counts["actions"]) if n == 0],
|
| 216 |
+
}
|
| 217 |
+
(output / "dataset.json").write_text(json.dumps(spec, indent=2))
|
| 218 |
+
print(json.dumps(counts), flush=True)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
if __name__ == "__main__":
|
| 222 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 223 |
+
for name in ("source", "reference", "split-manifest", "output", "features"):
|
| 224 |
+
parser.add_argument("--" + name, type=Path, required=True)
|
| 225 |
+
parser.add_argument("--task", choices=list(PROMPTS), default="button_order")
|
| 226 |
+
prepare(**vars(parser.parse_args()))
|
checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_release.py
ADDED
|
@@ -0,0 +1,420 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Evaluate final Franka policies and publish portable model bundles to fm-dev."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import importlib.metadata
|
| 6 |
+
import json
|
| 7 |
+
import os
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
import pickle
|
| 10 |
+
import shutil
|
| 11 |
+
import subprocess
|
| 12 |
+
import sys
|
| 13 |
+
import time
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
|
| 17 |
+
from integrations.robomme.franka_baseline import FORMAL_BUDGET, load_policy, model_repo_id
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def training_settings(metadata, spec, checkpoint_step):
|
| 21 |
+
recipe = metadata["training_recipe"]
|
| 22 |
+
history = metadata.get("history", {})
|
| 23 |
+
return {
|
| 24 |
+
"model": "pi0.5", "task": spec["task"], "fine_tuning": "LoRA",
|
| 25 |
+
"setting": f"uniform{history['frames']}" if history else "baseline",
|
| 26 |
+
"checkpoint_step": checkpoint_step, "target_steps": metadata["target_steps"],
|
| 27 |
+
"global_batch_size": recipe["global_batch_size"],
|
| 28 |
+
"per_gpu_batch_size": recipe["global_batch_size"] // recipe["gpus"],
|
| 29 |
+
"num_gpus": recipe["gpus"], "gpu_model": "NVIDIA RTX A6000",
|
| 30 |
+
"gradient_accumulation_steps": recipe["gradient_accumulation"],
|
| 31 |
+
"parallelism": "JAX data parallel", "fsdp_devices": recipe["fsdp_devices"],
|
| 32 |
+
"samples_seen": checkpoint_step * recipe["global_batch_size"],
|
| 33 |
+
"reference_budget": {"batch_size": recipe["reference_global_batch"], "steps": recipe["reference_steps"]},
|
| 34 |
+
"optimizer": {"name": "AdamW", "beta1": .9, "beta2": .95, "epsilon": 1e-8,
|
| 35 |
+
"weight_decay": 1e-10, "clip_gradient_norm": 1.0},
|
| 36 |
+
"lr_schedule": {"name": "cosine", "warmup_steps": recipe["warmup_steps"],
|
| 37 |
+
"peak_lr": recipe["peak_lr"], "decay_steps": recipe["decay_steps"],
|
| 38 |
+
"final_lr": recipe["decay_lr"]},
|
| 39 |
+
"ema_decay": recipe["ema_decay"], "seed": 42, "data_loader_workers": 4,
|
| 40 |
+
"lora_backbones": ["gemma_2b_lora", "gemma_300m_lora"], "lora_rank": 32,
|
| 41 |
+
"trainable": recipe["method"],
|
| 42 |
+
"compute_dtype": "bfloat16", "trainable_parameter_dtype": "float32",
|
| 43 |
+
"action_dim": recipe["action_dim"], "action_horizon": recipe["action_horizon"],
|
| 44 |
+
"state_tokens": {"enabled": True, "max_token_len": recipe["max_token_len"],
|
| 45 |
+
"normalization": "bounded train q01/q99; constant spans map to0"},
|
| 46 |
+
"history": {**history, "history_tokens": history.get("frames", 0) * history.get("tokens_per_frame", 0)},
|
| 47 |
+
"normalization": "train-only known-component STD", "dataset_sample_counts": spec["counts"],
|
| 48 |
+
"checkpoint_save_steps": [5000, metadata["target_steps"]],
|
| 49 |
+
"full_resume_state_included": True,
|
| 50 |
+
"unsupervised_action_components": spec.get("unsupervised_action_components", []),
|
| 51 |
+
"gpu_allocator": metadata.get("gpu_allocator", "default"),
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def evaluate(dataset, checkpoint, output, per_episode=25):
|
| 56 |
+
from picmem.data.semantic_transition.sampling import even_sampling_indices
|
| 57 |
+
|
| 58 |
+
dataset, checkpoint = Path(dataset), Path(checkpoint)
|
| 59 |
+
spec = json.loads((dataset / "dataset.json").read_text())
|
| 60 |
+
policy = load_policy(checkpoint)
|
| 61 |
+
history = (checkpoint / "assets/history_config.yaml").exists()
|
| 62 |
+
offsets = {"validation": 0, "test": 0}
|
| 63 |
+
collected = {split: {"position_l2_m": [], "quaternion_angle_rad": [], "gripper_mae": []} for split in offsets}
|
| 64 |
+
records = []
|
| 65 |
+
for episode in spec["episodes"]:
|
| 66 |
+
split = episode["split"]
|
| 67 |
+
if split not in offsets:
|
| 68 |
+
continue
|
| 69 |
+
count = episode["samples"]
|
| 70 |
+
indices = np.unique(np.linspace(0, count - 1, min(count, per_episode), dtype=int)) if count else []
|
| 71 |
+
for local_index in indices:
|
| 72 |
+
with (dataset / split / "data" / f"{offsets[split] + local_index}.pkl").open("rb") as stream:
|
| 73 |
+
sample = pickle.load(stream)
|
| 74 |
+
if history:
|
| 75 |
+
# Offline samples provide their own complete frame features and
|
| 76 |
+
# sample key. Keep the encoder/position tables, clear only history.
|
| 77 |
+
policy.mem_buffer._history_feats.clear()
|
| 78 |
+
step, episode_id = int(sample["step_idx"]), int(sample["epis_idx"])
|
| 79 |
+
for index in even_sampling_indices(step, policy._metadata["history"]["frames"]):
|
| 80 |
+
feature = dataset / "features" / f"episode_{episode_id}" / f"token_emb_{index}.npy"
|
| 81 |
+
policy.mem_buffer._history_feats[index] = np.load(feature, allow_pickle=True).item()
|
| 82 |
+
policy.step_idx = step
|
| 83 |
+
obs = {key: sample[key] for key in ("image", "wrist_image", "state", "prompt")}
|
| 84 |
+
obs["sample_key"] = [split, episode["episode"], int(sample["step_idx"]), 42]
|
| 85 |
+
pred = policy.infer(obs)["actions"]
|
| 86 |
+
if pred.shape != (20, 8) or not np.isfinite(pred).all():
|
| 87 |
+
raise ValueError("Invalid restored policy output")
|
| 88 |
+
target, mask = sample["actions"], sample["action_component_valid_mask"]
|
| 89 |
+
position_mask, quat_mask = mask[:, :3].all(-1), mask[:, 3:7].all(-1)
|
| 90 |
+
position = np.linalg.norm(pred[position_mask, :3] - target[position_mask, :3], axis=-1)
|
| 91 |
+
dot = np.sum(pred[quat_mask, 3:7] * target[quat_mask, 3:7], axis=-1)
|
| 92 |
+
angle = 2 * np.arccos(np.clip(np.abs(dot), 0, 1))
|
| 93 |
+
gripper = np.abs(pred[mask[:, 7], 7] - target[mask[:, 7], 7])
|
| 94 |
+
for name, values in zip(collected[split], (position, angle, gripper), strict=True):
|
| 95 |
+
collected[split][name].extend(values.tolist())
|
| 96 |
+
records.append({"split": split, "episode": episode["episode"], "frame": int(sample["step_idx"])})
|
| 97 |
+
offsets[split] += count
|
| 98 |
+
print(f"Evaluated {split}/{episode['episode']}: {len(indices)} observations", flush=True)
|
| 99 |
+
report = {
|
| 100 |
+
"checkpoint": str(checkpoint.resolve()), "optimizer_step": int(checkpoint.name),
|
| 101 |
+
"all_outputs_finite": True, "action_shape": [20, 8], "per_episode": per_episode,
|
| 102 |
+
"scope": "Held-out offline H20 action error; no physical robot rollout or success-rate claim",
|
| 103 |
+
"splits": {split: {name: {"count": len(v), "mean": float(np.mean(v)) if v else None}
|
| 104 |
+
for name, v in metrics.items()} for split, metrics in collected.items()},
|
| 105 |
+
"observations": records,
|
| 106 |
+
}
|
| 107 |
+
Path(output).write_text(json.dumps(report, indent=2, allow_nan=False))
|
| 108 |
+
print(json.dumps(report["splits"]), flush=True)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def publish(dataset, checkpoint, evaluation, output, repo_id, intermediate=False):
|
| 112 |
+
from huggingface_hub import HfApi
|
| 113 |
+
|
| 114 |
+
dataset, checkpoint, output = Path(dataset), Path(checkpoint), Path(output)
|
| 115 |
+
metadata = json.loads((checkpoint / "assets/policy_metadata.json").read_text())
|
| 116 |
+
report = json.loads(Path(evaluation).read_text()) if evaluation is not None else None
|
| 117 |
+
target_steps = FORMAL_BUDGET["steps"]
|
| 118 |
+
checkpoint_step = int(checkpoint.name)
|
| 119 |
+
if intermediate:
|
| 120 |
+
if (checkpoint_step != 5000 or metadata["target_steps"] != target_steps
|
| 121 |
+
or not (checkpoint / "_CHECKPOINT_METADATA").exists()):
|
| 122 |
+
raise ValueError("Intermediate upload requires the completed 5,000-step checkpoint")
|
| 123 |
+
elif (checkpoint_step != target_steps or metadata["target_steps"] != target_steps
|
| 124 |
+
or report is None or report["optimizer_step"] != target_steps or not report["all_outputs_finite"]
|
| 125 |
+
or Path(report["checkpoint"]).resolve() != checkpoint.resolve()):
|
| 126 |
+
raise ValueError(f"Only the evaluated {target_steps}-update model can be published")
|
| 127 |
+
if not repo_id.startswith("fm-dev/"):
|
| 128 |
+
raise ValueError("This task publishes only to the authorized fm-dev namespace")
|
| 129 |
+
# Controllers started before the user's rename request still pass legacy IDs.
|
| 130 |
+
# Resolve those IDs before any Hub write, preserving running trainers.
|
| 131 |
+
history_frames = metadata.get("history", {}).get("frames", 0)
|
| 132 |
+
task_slug = metadata["task"].replace("_", "-")
|
| 133 |
+
legacy = f"fm-dev/pi05-{task_slug}-{'uniform32-' if history_frames else ''}lora{'-5000' if intermediate else ''}"
|
| 134 |
+
destination = model_repo_id(metadata["task"], history_frames, checkpoint_step)
|
| 135 |
+
if repo_id not in {legacy, destination}:
|
| 136 |
+
raise ValueError(f"Model name must identify this task, setting and checkpoint: {destination}")
|
| 137 |
+
repo_id = destination
|
| 138 |
+
output.mkdir(parents=True, exist_ok=True)
|
| 139 |
+
shutil.copyfile(dataset / "dataset.json", output / "dataset_manifest.json")
|
| 140 |
+
# Publish serving weights and the complete optimizer/RNG/sampler resume state.
|
| 141 |
+
for directory in ("params", "assets", "resume_state"):
|
| 142 |
+
if not (output / directory).exists():
|
| 143 |
+
shutil.copytree(checkpoint / directory, output / directory, copy_function=os.link)
|
| 144 |
+
shutil.copyfile(checkpoint / "_CHECKPOINT_METADATA", output / "_CHECKPOINT_METADATA")
|
| 145 |
+
if evaluation is not None:
|
| 146 |
+
shutil.copyfile(evaluation, output / "evaluation.json")
|
| 147 |
+
(output / "checkpoint_info.json").write_text(json.dumps({
|
| 148 |
+
"optimizer_step": checkpoint_step, "target_steps": target_steps,
|
| 149 |
+
"sample_exposures": checkpoint_step * 4,
|
| 150 |
+
"evaluation_status": "pending" if intermediate else "completed",
|
| 151 |
+
"resume_state_included": True,
|
| 152 |
+
}, indent=2))
|
| 153 |
+
root = Path(__file__).resolve().parents[2]
|
| 154 |
+
for directory in ("integrations", "src", "robomme/src", "robomme/packages/openpi-client/src"):
|
| 155 |
+
for source in (root / directory).rglob("*"):
|
| 156 |
+
if source.is_file() and source.suffix in {".py", ".yaml", ".yml", ".json"}:
|
| 157 |
+
dest = output / "code" / source.relative_to(root)
|
| 158 |
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
| 159 |
+
shutil.copyfile(source, dest)
|
| 160 |
+
for directory in ("", "robomme"):
|
| 161 |
+
for name in ("LICENSE", "pyproject.toml"):
|
| 162 |
+
source = root / directory / name
|
| 163 |
+
if source.exists():
|
| 164 |
+
dest = output / "code" / directory / name
|
| 165 |
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
| 166 |
+
shutil.copyfile(source, dest)
|
| 167 |
+
requirements = []
|
| 168 |
+
for dist in importlib.metadata.distributions():
|
| 169 |
+
name = dist.metadata["Name"]
|
| 170 |
+
if name.lower().replace("_", "-") in {"picmem-dev", "openpi", "openpi-client", "flash-attn-jax"}:
|
| 171 |
+
continue
|
| 172 |
+
requirements.append(f"{name}=={dist.version}")
|
| 173 |
+
(output / "requirements.txt").write_text(
|
| 174 |
+
"--extra-index-url https://download.pytorch.org/whl/cu126\n" + "\n".join(sorted(set(requirements))) + "\n"
|
| 175 |
+
)
|
| 176 |
+
(output / "load_model.py").write_text(
|
| 177 |
+
'from pathlib import Path\nimport sys\n'
|
| 178 |
+
'ROOT = Path(__file__).resolve().parent\n'
|
| 179 |
+
'for path in ("code", "code/src", "code/robomme/src", "code/robomme/packages/openpi-client/src"):\n'
|
| 180 |
+
' sys.path.insert(0, str(ROOT / path))\n'
|
| 181 |
+
'from integrations.robomme.franka_baseline import load_policy, observe\n'
|
| 182 |
+
'def load():\n return load_policy(ROOT)\n'
|
| 183 |
+
)
|
| 184 |
+
spec = json.loads((dataset / "dataset.json").read_text())
|
| 185 |
+
uniform = "history" in metadata
|
| 186 |
+
(output / "training_config.json").write_text(json.dumps(training_settings(metadata, spec, checkpoint_step), indent=2))
|
| 187 |
+
frames = metadata.get("history", {}).get("frames", 0)
|
| 188 |
+
task = spec["task"]
|
| 189 |
+
instruction = metadata.get("prompt") or spec["prompts"][task]
|
| 190 |
+
split_episodes = {s: sum(e["split"] == s for e in spec["episodes"]) for s in ("train", "validation", "test")}
|
| 191 |
+
gripper_evidence = {s: sum(e["known_gripper_frames"] for e in spec["episodes"] if e["split"] == s)
|
| 192 |
+
for s in split_episodes}
|
| 193 |
+
(output / "README.md").write_text(f'''---
|
| 194 |
+
base_model: physical-intelligence/pi05_base
|
| 195 |
+
tags: [robotics, pi05, franka, lora]
|
| 196 |
+
---
|
| 197 |
+
|
| 198 |
+
# {repo_id.split('/')[-1]}
|
| 199 |
+
|
| 200 |
+
Trained locally for **{checkpoint_step:,} optimizer updates** on four NVIDIA RTX A6000s.
|
| 201 |
+
Global batch4 ×{checkpoint_step:,}updates ={checkpoint_step * 4:,} training examples.
|
| 202 |
+
The complete run targets6,250updates =25,000examples, matching the sample
|
| 203 |
+
budget of the reference single-GPU batch1 ×25,000-update experiment.
|
| 204 |
+
{'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.'}
|
| 205 |
+
This repository contains full EMA serving weights, normalization and history
|
| 206 |
+
assets, inference source and exact installed dependency versions.
|
| 207 |
+
{'An offline evaluation report is included.' if not intermediate else 'No policy-quality evaluation is claimed for this intermediate upload.'}
|
| 208 |
+
The complete optimizer, non-EMA parameters, RNG and sampler cursor are included
|
| 209 |
+
under `resume_state/`; `params/` contains EMA serving weights. This is a
|
| 210 |
+
Cartesian8 LoRA adaptation of π0.5.
|
| 211 |
+
|
| 212 |
+
Input: base and wrist RGB images, current flange xyz + unit XYZW quaternion
|
| 213 |
+
(positive qx chart), measured finger opening divided by0.08, and task text.
|
| 214 |
+
Output:20 absolute target flange poses and gripper commands (0closed,1open).
|
| 215 |
+
Numeric state/actions use train-only STD normalization. Current-state tokens
|
| 216 |
+
use a separate train-q01/q99 bounded view, max128tokens. Task prompt:
|
| 217 |
+
`{instruction}`
|
| 218 |
+
|
| 219 |
+
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.'}
|
| 220 |
+
No Writer, Status head, subgoal, or semantic-memory inputs are used.
|
| 221 |
+
|
| 222 |
+
Training: LoRA Gemma2B and300M; fresh Cartesian projections and optional history
|
| 223 |
+
modules trainable; pretrained backbones and time MLPs frozen. AdamW, global
|
| 224 |
+
batch4 (one/GPU), no accumulation,250-step warmup, cosine5e-5→5e-6 through
|
| 225 |
+
step6,250. EMA0.999^4 =0.996005996001 preserves the reference per-sample
|
| 226 |
+
smoothing timescale. Checkpoints saved at5,000 and6,250updates.
|
| 227 |
+
Episode splits:{split_episodes}; accepted train/validation/test windows:{spec['counts']}.
|
| 228 |
+
The original40ms synchronization and100ms maximum-gap filters are retained.
|
| 229 |
+
|
| 230 |
+
Gripper command labels require saved full-rate Joy edges matched to server
|
| 231 |
+
requests and clock bounds. Unknown targets are NaN/false on disk and masked
|
| 232 |
+
in both flow conditioning and loss. Measured width is state only. Source-frame
|
| 233 |
+
gripper evidence counts by split:{gripper_evidence}. Entirely unsupervised
|
| 234 |
+
action components:{spec.get('unsupervised_action_components', [])}.
|
| 235 |
+
{'Button Order has only closed training gripper targets; this does not establish a learned open/close policy.' if task == 'button_order' else ''}
|
| 236 |
+
{'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 ''}
|
| 237 |
+
Metrics with no known labels are null, not zero.
|
| 238 |
+
Evaluation reports known-component offline errors, not robot success rates.
|
| 239 |
+
|
| 240 |
+
## Load
|
| 241 |
+
|
| 242 |
+
Use Python3.10 and a CUDA12 GPU environment. Download this repository, then:
|
| 243 |
+
|
| 244 |
+
```bash
|
| 245 |
+
python -m pip install -r requirements.txt
|
| 246 |
+
```
|
| 247 |
+
|
| 248 |
+
```python
|
| 249 |
+
from load_model import load, observe
|
| 250 |
+
policy = load()
|
| 251 |
+
# Arrays: RGB uint8 images, float32 state[8]. Resized to224 with aspect padding.
|
| 252 |
+
observe(policy, base_rgb, state) # Append every observed frame for the history model.
|
| 253 |
+
result = policy.infer({{
|
| 254 |
+
"image": base_rgb, "wrist_image": wrist_rgb, "state": state,
|
| 255 |
+
"prompt": {instruction!r},
|
| 256 |
+
}})
|
| 257 |
+
actions = result["actions"] # (20,8)
|
| 258 |
+
```
|
| 259 |
+
|
| 260 |
+
For the history model, call `observe(policy, base_rgb, state)` for every original
|
| 261 |
+
observation frame, including the current one, and `policy.reset()` between
|
| 262 |
+
episodes. It uses the checkpoint's frozen vision encoder and appends frame
|
| 263 |
+
indices in order; the policy samples{frames} across the full prefix. `observe` is a
|
| 264 |
+
no-op for the model without history. The offline evaluator in
|
| 265 |
+
`code/integrations/robomme/franka_release.py` demonstrates this with cached
|
| 266 |
+
features. This bundle does not include demonstration images or private raw
|
| 267 |
+
workspace evidence. Robot control must use the same Cartesian frame and tool
|
| 268 |
+
convention as the training data.
|
| 269 |
+
''')
|
| 270 |
+
# Exercise the packaged source and online history path before publishing.
|
| 271 |
+
# A separate process avoids retaining GPU allocations in the upload worker.
|
| 272 |
+
if not intermediate:
|
| 273 |
+
check_packaged_inference(output)
|
| 274 |
+
api = HfApi()
|
| 275 |
+
api.create_repo(repo_id, repo_type="model", private=False, exist_ok=True)
|
| 276 |
+
commit = api.upload_folder(repo_id=repo_id, repo_type="model", folder_path=output,
|
| 277 |
+
commit_message=f"Upload {'intermediate' if intermediate else 'evaluated'} {checkpoint_step}-step Franka pi05 model")
|
| 278 |
+
remote = {f.path: f.size for f in api.list_repo_tree(repo_id, repo_type="model", recursive=True)
|
| 279 |
+
if hasattr(f, "size")}
|
| 280 |
+
for local in output.rglob("*"):
|
| 281 |
+
if local.is_file() and ".cache" not in local.relative_to(output).parts:
|
| 282 |
+
name = local.relative_to(output).as_posix()
|
| 283 |
+
if remote.get(name) != local.stat().st_size:
|
| 284 |
+
raise RuntimeError(f"Remote model file missing or wrong size: {name}")
|
| 285 |
+
receipt = {"repo_id": repo_id, "optimizer_step": checkpoint_step, "commit": commit.oid,
|
| 286 |
+
"verified_files": len(remote)}
|
| 287 |
+
print(json.dumps(receipt), flush=True)
|
| 288 |
+
return receipt
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def check_packaged_inference(output):
|
| 292 |
+
smoke = subprocess.run(
|
| 293 |
+
[sys.executable, "-c", '''
|
| 294 |
+
import json
|
| 295 |
+
import numpy as np
|
| 296 |
+
from load_model import load, observe
|
| 297 |
+
policy = load()
|
| 298 |
+
image = np.zeros((224, 224, 3), dtype=np.uint8)
|
| 299 |
+
state = np.array([.45, 0, .15, .7, -.7, 0, 0, 0], dtype=np.float32)
|
| 300 |
+
observe(policy, image, state)
|
| 301 |
+
actions = policy.infer({"image": image, "wrist_image": image, "state": state,
|
| 302 |
+
"prompt": policy._metadata["prompt"]})["actions"]
|
| 303 |
+
assert actions.shape == (20, 8) and np.isfinite(actions).all()
|
| 304 |
+
print(json.dumps({"packaged_inference": "passed", "shape": list(actions.shape)}))
|
| 305 |
+
'''], cwd=output, capture_output=True, text=True, check=True,
|
| 306 |
+
env={**os.environ, "PYTHONPATH": str(output), "JAX_PLATFORMS": "cuda", "CUDA_VISIBLE_DEVICES": "0"},
|
| 307 |
+
)
|
| 308 |
+
(output / "packaged-inference-check.txt").write_text(smoke.stdout.splitlines()[-1] + "\n")
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def upload_5k(dataset, run_root):
|
| 312 |
+
"""Upload each 5k model as soon as Orbax finishes saving, without using GPUs."""
|
| 313 |
+
root = Path(run_root)
|
| 314 |
+
task = json.loads((Path(dataset) / "dataset.json").read_text())["task"]
|
| 315 |
+
slug = task.replace("_", "-")
|
| 316 |
+
for variant, name in (("baseline", "pi05_franka_baseline"), ("uniform32", "pi05_franka_uniform32_baseline")):
|
| 317 |
+
checkpoint = root / variant / "checkpoints" / name / slug / "5000"
|
| 318 |
+
receipt_path = root / f"{variant}-5000-upload.json"
|
| 319 |
+
if receipt_path.exists():
|
| 320 |
+
continue
|
| 321 |
+
print(f"Waiting for committed checkpoint: {checkpoint}", flush=True)
|
| 322 |
+
while not (checkpoint / "_CHECKPOINT_METADATA").exists():
|
| 323 |
+
time.sleep(5)
|
| 324 |
+
repo_id = model_repo_id(task, 32 if variant == "uniform32" else 0, 5000)
|
| 325 |
+
print(f"Uploading 5k checkpoint to {repo_id}", flush=True)
|
| 326 |
+
receipt = publish(dataset, checkpoint, None, root / f"{variant}-5000-export", repo_id, intermediate=True)
|
| 327 |
+
receipt_path.write_text(json.dumps(receipt, indent=2))
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def wait_for_baseline(pid, root):
|
| 331 |
+
"""Attach a new controller to a baseline trainer that is already running."""
|
| 332 |
+
import psutil
|
| 333 |
+
|
| 334 |
+
root = Path(root).resolve()
|
| 335 |
+
final = root / "baseline/checkpoints/pi05_franka_baseline/button-order" / str(FORMAL_BUDGET["steps"])
|
| 336 |
+
try:
|
| 337 |
+
process = psutil.Process(pid)
|
| 338 |
+
command = process.cmdline()
|
| 339 |
+
if ("integrations.robomme.franka_baseline" not in command
|
| 340 |
+
or str(root / "baseline") not in command):
|
| 341 |
+
raise ValueError("The existing process is not this run's baseline trainer")
|
| 342 |
+
print(f"Waiting for existing baseline trainer PID {pid}; next model is Uniform32", flush=True)
|
| 343 |
+
process.wait()
|
| 344 |
+
except psutil.NoSuchProcess:
|
| 345 |
+
pass
|
| 346 |
+
if not (final / "_CHECKPOINT_METADATA").exists():
|
| 347 |
+
raise RuntimeError("Existing baseline trainer exited without its final complete checkpoint")
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
def run(dataset, run_root, wait_baseline_pid=0):
|
| 351 |
+
"""Durable sequential train → evaluate → publish, each model uses all four GPUs."""
|
| 352 |
+
root = Path(run_root)
|
| 353 |
+
root.mkdir(parents=True, exist_ok=True)
|
| 354 |
+
task = json.loads((Path(dataset) / "dataset.json").read_text())["task"]
|
| 355 |
+
slug = task.replace("_", "-")
|
| 356 |
+
if wait_baseline_pid:
|
| 357 |
+
wait_for_baseline(wait_baseline_pid, root)
|
| 358 |
+
for history, variant in ((False, "baseline"), (True, "uniform32")):
|
| 359 |
+
run = root / variant
|
| 360 |
+
name = "pi05_franka_uniform32_baseline" if history else "pi05_franka_baseline"
|
| 361 |
+
checkpoints = run / "checkpoints" / name / slug
|
| 362 |
+
final = checkpoints / str(FORMAL_BUDGET["steps"])
|
| 363 |
+
command = [sys.executable, "-m", "integrations.robomme.franka_baseline", "train",
|
| 364 |
+
"--dataset", str(dataset), "--run-root", str(run), "--exp-name", slug]
|
| 365 |
+
if history:
|
| 366 |
+
command.extend(["--uniform-history", "--history-frames", "32"])
|
| 367 |
+
if checkpoints.exists() and any(p.is_dir() and p.name.isdigit() for p in checkpoints.iterdir()):
|
| 368 |
+
command.append("--resume")
|
| 369 |
+
if not final.exists():
|
| 370 |
+
with (root / f"{variant}-train.log").open("a") as log:
|
| 371 |
+
subprocess.run(command, stdout=log, stderr=subprocess.STDOUT, check=True)
|
| 372 |
+
report = root / f"{variant}-evaluation.json"
|
| 373 |
+
with (root / f"{variant}-evaluation.log").open("a") as log:
|
| 374 |
+
subprocess.run([sys.executable, "-m", "integrations.robomme.franka_release", "evaluate",
|
| 375 |
+
"--dataset", str(dataset), "--checkpoint", str(final), "--output", str(report)],
|
| 376 |
+
stdout=log, stderr=subprocess.STDOUT, check=True,
|
| 377 |
+
env={**os.environ, "CUDA_VISIBLE_DEVICES": "0"})
|
| 378 |
+
repo_id = model_repo_id(task, 32 if history else 0, FORMAL_BUDGET["steps"])
|
| 379 |
+
(root / f"{variant}-trained.json").write_text(json.dumps({
|
| 380 |
+
"steps": FORMAL_BUDGET["steps"], "evaluation": str(report), "repo_id": repo_id,
|
| 381 |
+
}))
|
| 382 |
+
with (root / f"{variant}-upload.log").open("a") as log:
|
| 383 |
+
publication = subprocess.run([
|
| 384 |
+
sys.executable, "-m", "integrations.robomme.franka_release", "publish",
|
| 385 |
+
"--dataset", str(dataset), "--checkpoint", str(final), "--evaluation", str(report),
|
| 386 |
+
"--output", str(root / f"{variant}-export"), "--repo-id", repo_id,
|
| 387 |
+
], stdout=log, stderr=subprocess.STDOUT, check=False,
|
| 388 |
+
env={**os.environ, "JAX_PLATFORMS": "cpu"})
|
| 389 |
+
if publication.returncode:
|
| 390 |
+
print(f"Upload pending for {repo_id}; training queue continues. See {variant}-upload.log", flush=True)
|
| 391 |
+
continue
|
| 392 |
+
(root / f"{variant}-complete.json").write_text(json.dumps({
|
| 393 |
+
"steps": FORMAL_BUDGET["steps"], "sample_exposures": FORMAL_BUDGET["sample_exposures"],
|
| 394 |
+
"repo_id": repo_id,
|
| 395 |
+
}))
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
if __name__ == "__main__":
|
| 399 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 400 |
+
commands = parser.add_subparsers(dest="command", required=True)
|
| 401 |
+
evaluation = commands.add_parser("evaluate")
|
| 402 |
+
for name in ("dataset", "checkpoint", "output"):
|
| 403 |
+
evaluation.add_argument("--" + name, type=Path, required=True)
|
| 404 |
+
evaluation.add_argument("--per-episode", type=int, default=25)
|
| 405 |
+
publication = commands.add_parser("publish")
|
| 406 |
+
for name in ("dataset", "checkpoint", "output"):
|
| 407 |
+
publication.add_argument("--" + name, type=Path, required=True)
|
| 408 |
+
publication.add_argument("--evaluation", type=Path)
|
| 409 |
+
publication.add_argument("--repo-id", required=True)
|
| 410 |
+
publication.add_argument("--intermediate", action="store_true")
|
| 411 |
+
early = commands.add_parser("upload-5k")
|
| 412 |
+
early.add_argument("--dataset", type=Path, required=True)
|
| 413 |
+
early.add_argument("--run-root", type=Path, required=True)
|
| 414 |
+
runner = commands.add_parser("run")
|
| 415 |
+
runner.add_argument("--dataset", type=Path, required=True)
|
| 416 |
+
runner.add_argument("--run-root", type=Path, required=True)
|
| 417 |
+
runner.add_argument("--wait-baseline-pid", type=int, default=int(os.environ.get("FRANKA_WAIT_BASELINE_PID", "0")))
|
| 418 |
+
args = vars(parser.parse_args())
|
| 419 |
+
command = args.pop("command")
|
| 420 |
+
{"evaluate": evaluate, "publish": publish, "run": run, "upload-5k": upload_5k}[command](**args)
|
checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_round.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Settings and upload-aware local retention for the second Franka training round."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import json
|
| 5 |
+
import dataclasses
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import shutil
|
| 8 |
+
|
| 9 |
+
TARGET_STEPS = 12_500
|
| 10 |
+
SAVE_INTERVAL = 1_000
|
| 11 |
+
MILESTONE_STEPS = (5_000, 10_000, TARGET_STEPS)
|
| 12 |
+
BACKUP_REPO_ID = "fm-dev/pi05-checkpoint-backups"
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def training_options():
|
| 16 |
+
# Keep every periodic checkpoint until the uploader verifies its remote copy.
|
| 17 |
+
# make_train_config sets keep_period to save_interval; pruning happens below.
|
| 18 |
+
return {"steps": TARGET_STEPS, "save_interval": SAVE_INTERVAL,
|
| 19 |
+
"warmup_steps": 250, "decay_steps": TARGET_STEPS}
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def checkpoint_steps():
|
| 23 |
+
return [*range(SAVE_INTERVAL, TARGET_STEPS, SAVE_INTERVAL), TARGET_STEPS]
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def model_repo_id(task, setting, step):
|
| 27 |
+
if setting not in {"status_d", "baseline", "uniform32"} or step not in checkpoint_steps():
|
| 28 |
+
raise ValueError("Unknown second-round model setting or checkpoint step")
|
| 29 |
+
return f"fm-dev/pi05-{task.replace('_', '-')}-{setting.replace('_', '-')}-lora-gbs4-pgb1-gpu4-r2-step{step}"
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def checkpoint_storage(task, setting, step):
|
| 33 |
+
"""Keep milestones as models and other full checkpoints in archive folders."""
|
| 34 |
+
model_id = model_repo_id(task, setting, step)
|
| 35 |
+
if step in MILESTONE_STEPS:
|
| 36 |
+
return model_id, "model", ""
|
| 37 |
+
return BACKUP_REPO_ID, "dataset", f"checkpoints/r2/{task}/{setting}/step{step}"
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def make_config(dataset, run_root, setting, **overrides):
|
| 41 |
+
from integrations.robomme.franka_baseline import make_train_config
|
| 42 |
+
|
| 43 |
+
if setting not in {"status_d", "baseline", "uniform32"}:
|
| 44 |
+
raise ValueError(f"Unsupported setting: {setting}")
|
| 45 |
+
dataset = Path(dataset).resolve()
|
| 46 |
+
spec = json.loads((dataset / "dataset.json").read_text())
|
| 47 |
+
cfg = make_train_config(dataset, run_root, uniform_history=setting != "baseline",
|
| 48 |
+
history_frames=32, exp_name=spec["task"].replace("_", "-"),
|
| 49 |
+
**(training_options() | overrides))
|
| 50 |
+
metadata = {**cfg.policy_metadata, "training_round": 2, "training_setting": setting,
|
| 51 |
+
"action_supervision": spec["action_supervision"],
|
| 52 |
+
"checkpoint_retention": {"save_interval": SAVE_INTERVAL, "local_latest": 3,
|
| 53 |
+
"milestones": [5000, 10000, TARGET_STEPS], "remote": "all"},
|
| 54 |
+
"training_recipe": {**cfg.policy_metadata["training_recipe"],
|
| 55 |
+
"reference_steps": TARGET_STEPS * 4,
|
| 56 |
+
"reference_global_batch": 1}}
|
| 57 |
+
if setting == "status_d":
|
| 58 |
+
history = dataset / "assets/history_status_d.yaml"
|
| 59 |
+
if not history.is_file():
|
| 60 |
+
raise FileNotFoundError(f"Prepare the Status/Writer data before training: {history}")
|
| 61 |
+
cfg = dataclasses.replace(
|
| 62 |
+
cfg, name="pi05_franka_status_d",
|
| 63 |
+
model=dataclasses.replace(cfg.model, history_config=str(history), max_token_len=256),
|
| 64 |
+
data=dataclasses.replace(cfg.data, disable_context_gripper_command=True),
|
| 65 |
+
aux_dataset_path=str(dataset / "status/train"), aux_dataset_fraction=.10,
|
| 66 |
+
)
|
| 67 |
+
metadata.update(
|
| 68 |
+
disable_context_gripper_command=True,
|
| 69 |
+
status_context="48-step causal pose-command and measured-state context; command-gripper feature disabled",
|
| 70 |
+
writer_schedule=json.loads((dataset / "writer/dataset-index.json").read_text())["writer_schedule"],
|
| 71 |
+
history={**metadata["history"], "keyframe_slots": 1, "tokens": 528, "use_historical_state": False},
|
| 72 |
+
)
|
| 73 |
+
metadata["training_recipe"]["max_token_len"] = 256
|
| 74 |
+
metadata["training_recipe"]["status_auxiliary_fraction"] = .10
|
| 75 |
+
return dataclasses.replace(cfg, policy_metadata=metadata)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def prune_uploaded_checkpoints(checkpoint_root, export_root, receipt_root):
|
| 79 |
+
"""Keep the newest three and milestones; never delete an unverified upload."""
|
| 80 |
+
checkpoint_root, export_root, receipt_root = map(Path, (checkpoint_root, export_root, receipt_root))
|
| 81 |
+
committed = sorted(
|
| 82 |
+
(p for p in checkpoint_root.iterdir()
|
| 83 |
+
if p.name.isdigit() and not p.is_symlink() and (p / "_CHECKPOINT_METADATA").is_file()),
|
| 84 |
+
key=lambda p: int(p.name),
|
| 85 |
+
)
|
| 86 |
+
protected = {p.name for p in committed[-3:]} | {"5000", "10000", str(TARGET_STEPS)}
|
| 87 |
+
removed = []
|
| 88 |
+
for checkpoint in committed:
|
| 89 |
+
receipt = receipt_root / f"{checkpoint.name}.json"
|
| 90 |
+
if checkpoint.name in protected or not receipt.is_file():
|
| 91 |
+
continue
|
| 92 |
+
record = json.loads(receipt.read_text())
|
| 93 |
+
if (record.get("full_bundle_verified") is not True
|
| 94 |
+
or record.get("checkpoint") != str(checkpoint.resolve())):
|
| 95 |
+
continue
|
| 96 |
+
export = export_root / checkpoint.name
|
| 97 |
+
if export.is_symlink():
|
| 98 |
+
raise ValueError(f"Export directory must not be a symlink: {export}")
|
| 99 |
+
if export.exists():
|
| 100 |
+
shutil.rmtree(export)
|
| 101 |
+
shutil.rmtree(checkpoint)
|
| 102 |
+
removed.append(int(checkpoint.name))
|
| 103 |
+
return removed
|
checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_round_evaluate.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Offline action/Status checks with the exported model's real Writer and history inputs."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
from collections import defaultdict
|
| 6 |
+
import json
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import pickle
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
|
| 12 |
+
from integrations.robomme.franka_baseline import canonical_pose, load_policy
|
| 13 |
+
from integrations.robomme.franka_partial import read_h5_signals
|
| 14 |
+
from integrations.robomme.franka_status_data import causal_context
|
| 15 |
+
from picmem.data.semantic_transition.sampling import even_sampling_indices
|
| 16 |
+
from picmem.data.semantic_transition.scheduled_writer import ScheduledWriterReader
|
| 17 |
+
from picmem.training.transition_metrics import evaluate_transition_predictions
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def status_metrics(rows):
|
| 21 |
+
metrics = {}
|
| 22 |
+
for name, target, probability in (
|
| 23 |
+
("span", "span_target", "p_transition_span"),
|
| 24 |
+
("conditional_last_span", "last_span_target", "p_transition_last_given_span"),
|
| 25 |
+
):
|
| 26 |
+
valid = np.array([name == "span" or (r["span_target"] == 1 and r["last_span_valid"]) for r in rows])
|
| 27 |
+
metrics[name] = evaluate_transition_predictions(
|
| 28 |
+
span_target=np.array([r[target] for r in rows]), status_valid=valid,
|
| 29 |
+
span_probability=np.array([r[probability] for r in rows]),
|
| 30 |
+
) if valid.any() else None
|
| 31 |
+
return metrics
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def evaluate(dataset, checkpoint, output, per_episode=25):
|
| 35 |
+
dataset, checkpoint, output = map(Path, (dataset, checkpoint, output))
|
| 36 |
+
spec = json.loads((dataset / "dataset.json").read_text())
|
| 37 |
+
policy = load_policy(checkpoint)
|
| 38 |
+
status = policy.metadata.get("training_setting") == "status_d"
|
| 39 |
+
writer = ScheduledWriterReader(dataset / "writer", expected_schedule="status") if status else None
|
| 40 |
+
offsets = {"validation": 0, "test": 0}
|
| 41 |
+
labels, status_paths = {}, defaultdict(list)
|
| 42 |
+
status_predictions = {split: [] for split in offsets}
|
| 43 |
+
if status:
|
| 44 |
+
labels = {(r["global_episode_id"], r["step_idx"]): r
|
| 45 |
+
for r in json.loads((dataset / "status/labels.json").read_text())}
|
| 46 |
+
for split in offsets:
|
| 47 |
+
for path in sorted((dataset / "status" / split / "data").glob("*.pkl")):
|
| 48 |
+
with path.open("rb") as stream:
|
| 49 |
+
row = pickle.load(stream)
|
| 50 |
+
status_paths[int(row["epis_idx"])].append(path.resolve())
|
| 51 |
+
errors = {s: {"position_l2_m": [], "quaternion_angle_rad": [], "gripper_mae": []} for s in offsets}
|
| 52 |
+
horizon_errors = {s: [] for s in offsets}
|
| 53 |
+
observations, predictions = [], []
|
| 54 |
+
for episode in spec["episodes"]:
|
| 55 |
+
split = episode["split"]
|
| 56 |
+
if split not in offsets:
|
| 57 |
+
continue
|
| 58 |
+
count = episode["samples"]
|
| 59 |
+
indices = np.unique(np.linspace(0, count - 1, min(count, per_episode), dtype=int)) if count else []
|
| 60 |
+
action_paths = [(dataset / split / "data" / f"{offsets[split] + index}.pkl").resolve() for index in indices]
|
| 61 |
+
paths = list(dict.fromkeys([*action_paths, *status_paths[episode["episode_id"]]]))
|
| 62 |
+
if status and paths:
|
| 63 |
+
stamps, state_pose, target_pose, widths = read_h5_signals(Path(spec["source"]) / spec["task"] / f"{episode['episode']}.h5")
|
| 64 |
+
states = np.c_[state_pose, widths].astype(np.float32)
|
| 65 |
+
finite = np.isfinite(states[:, :7]).all(-1)
|
| 66 |
+
states[finite, :7] = canonical_pose(states[finite, :7])
|
| 67 |
+
poses = target_pose.astype(np.float32)
|
| 68 |
+
finite = np.isfinite(poses).all(-1)
|
| 69 |
+
poses[finite] = canonical_pose(poses[finite])
|
| 70 |
+
for path in paths:
|
| 71 |
+
with path.open("rb") as stream:
|
| 72 |
+
row = pickle.load(stream)
|
| 73 |
+
frame, episode_id = int(row["step_idx"]), int(row["epis_idx"])
|
| 74 |
+
obs = {k: row[k] for k in ("image", "wrist_image", "state", "prompt")}
|
| 75 |
+
if policy.mem_buffer is not None:
|
| 76 |
+
selected = even_sampling_indices(frame, 32)
|
| 77 |
+
if writer is not None:
|
| 78 |
+
snapshot = writer.snapshot_for(global_episode_id=episode_id, frame_index=frame, task_instruction=row["prompt"])
|
| 79 |
+
obs.update(history_keyframe_index=snapshot.keyframe_frame_index, current_subgoal=snapshot.current_subgoal)
|
| 80 |
+
if snapshot.keyframe_frame_index is not None:
|
| 81 |
+
selected.append(snapshot.keyframe_frame_index)
|
| 82 |
+
obs.update(causal_context(stamps, states, poses, frame).as_numpy())
|
| 83 |
+
policy.mem_buffer._history_feats.clear()
|
| 84 |
+
for selected_frame in set(selected):
|
| 85 |
+
feature_path = dataset / "features" / f"episode_{episode_id}" / f"token_emb_{selected_frame}.npy"
|
| 86 |
+
policy.mem_buffer._history_feats[selected_frame] = np.load(feature_path, allow_pickle=True).item()
|
| 87 |
+
policy.step_idx = frame
|
| 88 |
+
obs["sample_key"] = [split, episode["episode"], frame, 42]
|
| 89 |
+
result = policy.infer(obs)
|
| 90 |
+
actions = result["actions"]
|
| 91 |
+
if actions.shape != (20, 8) or not np.isfinite(actions).all():
|
| 92 |
+
raise ValueError("Restored model produced invalid actions")
|
| 93 |
+
target, mask = row["actions"], row["action_component_valid_mask"]
|
| 94 |
+
position = np.linalg.norm(actions[:, :3] - target[:, :3], axis=-1)
|
| 95 |
+
angle = 2 * np.arccos(np.clip(np.abs(np.sum(actions[:, 3:7] * target[:, 3:7], axis=-1)), 0, 1))
|
| 96 |
+
if path in action_paths:
|
| 97 |
+
errors[split]["position_l2_m"].extend(position[mask[:, :3].all(-1)].tolist())
|
| 98 |
+
errors[split]["quaternion_angle_rad"].extend(angle[mask[:, 3:7].all(-1)].tolist())
|
| 99 |
+
errors[split]["gripper_mae"].extend(np.abs(actions[mask[:, 7], 7] - target[mask[:, 7], 7]).tolist())
|
| 100 |
+
horizon_errors[split].append(position)
|
| 101 |
+
observations.append({"split": split, "episode": episode["episode"], "frame": frame})
|
| 102 |
+
predictions.append({"split": split, "episode": episode["episode"], "frame": frame,
|
| 103 |
+
"actions": actions.tolist(), "position_l2_m": position.tolist(),
|
| 104 |
+
"action_evaluation_sample": path in action_paths,
|
| 105 |
+
"transition_status": result.get("transition_status")})
|
| 106 |
+
if status and any(not np.isfinite(v) or not 0 <= v <= 1 for v in result["transition_status"].values()):
|
| 107 |
+
raise ValueError("Restored model produced invalid Status probabilities")
|
| 108 |
+
label = labels.get((episode_id, frame))
|
| 109 |
+
if label is not None:
|
| 110 |
+
if label["split"] != split:
|
| 111 |
+
raise ValueError("Status label split does not match its observation")
|
| 112 |
+
status_predictions[split].append({**label, **result["transition_status"]})
|
| 113 |
+
offsets[split] += count
|
| 114 |
+
print(f"Evaluated {split}/{episode['episode']}: {len(indices)} action samples, {len(paths)} total observations", flush=True)
|
| 115 |
+
report = {
|
| 116 |
+
"checkpoint": str(checkpoint.resolve()), "optimizer_step": int(checkpoint.name),
|
| 117 |
+
"all_outputs_finite": True, "action_shape": [20, 8], "per_episode": per_episode,
|
| 118 |
+
"scope": "Held-out offline action error; Status-D uses causal expert-history Writer projections, not a physical or closed-loop success-rate evaluation",
|
| 119 |
+
"splits": {s: {k: {"count": len(v), "mean": float(np.mean(v)) if v else None,
|
| 120 |
+
"p90": float(np.quantile(v, .9)) if v else None} for k, v in metrics.items()}
|
| 121 |
+
for s, metrics in errors.items()},
|
| 122 |
+
"position_by_horizon": {s: {str(n): {"mean_m": float(np.mean(np.stack(v)[:, :n])),
|
| 123 |
+
"p90_m": float(np.quantile(np.stack(v)[:, :n], .9))}
|
| 124 |
+
for n in (1, 4, 16, 20)} for s, v in horizon_errors.items() if v},
|
| 125 |
+
"observations": observations,
|
| 126 |
+
}
|
| 127 |
+
if status:
|
| 128 |
+
report["status_evaluation"] = {
|
| 129 |
+
"scope": "All labeled held-out windows; agent/model-reviewed labels, not human ground truth. "
|
| 130 |
+
"Unreviewed endpoints stay masked. Small, positive-enriched label sets do not establish "
|
| 131 |
+
"online trigger reliability. A split with no negatives cannot estimate false-positive rate.",
|
| 132 |
+
"splits": {split: status_metrics(rows) for split, rows in status_predictions.items()},
|
| 133 |
+
"predictions": status_predictions,
|
| 134 |
+
}
|
| 135 |
+
output.parent.mkdir(parents=True, exist_ok=True)
|
| 136 |
+
output.write_text(json.dumps(report, indent=2, allow_nan=False))
|
| 137 |
+
output.with_name(output.stem + "-predictions.json").write_text(json.dumps(predictions, allow_nan=False))
|
| 138 |
+
print(json.dumps(report["splits"]), flush=True)
|
| 139 |
+
return report
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
if __name__ == "__main__":
|
| 143 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 144 |
+
for name in ("dataset", "checkpoint", "output"):
|
| 145 |
+
parser.add_argument("--" + name, type=Path, required=True)
|
| 146 |
+
parser.add_argument("--per-episode", type=int, default=25)
|
| 147 |
+
evaluate(**vars(parser.parse_args()))
|
checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_round_finish.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Evaluate a completed round-two model and attach its reports to the public final checkpoint."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import shutil
|
| 9 |
+
import subprocess
|
| 10 |
+
import sys
|
| 11 |
+
import time
|
| 12 |
+
|
| 13 |
+
from integrations.robomme.franka_round import TARGET_STEPS, model_repo_id
|
| 14 |
+
from integrations.robomme.franka_round_evaluate import evaluate
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def finish(round_root, task, setting):
|
| 18 |
+
from huggingface_hub import HfApi
|
| 19 |
+
|
| 20 |
+
root = Path(round_root)
|
| 21 |
+
run = root / "runs" / task / setting
|
| 22 |
+
name = {"status_d": "pi05_franka_status_d", "baseline": "pi05_franka_baseline", "uniform32": "pi05_franka_uniform32_baseline"}[setting]
|
| 23 |
+
checkpoint = run / "checkpoints" / name / task.replace("_", "-") / str(TARGET_STEPS)
|
| 24 |
+
while not (checkpoint / "_CHECKPOINT_METADATA").is_file():
|
| 25 |
+
time.sleep(10)
|
| 26 |
+
report = run / "evaluation.json"
|
| 27 |
+
if not report.exists():
|
| 28 |
+
evaluate(root / "datasets" / task, checkpoint, report)
|
| 29 |
+
import gc
|
| 30 |
+
import jax
|
| 31 |
+
|
| 32 |
+
jax.clear_caches()
|
| 33 |
+
gc.collect()
|
| 34 |
+
result = json.loads(report.read_text())
|
| 35 |
+
if (result["optimizer_step"] != TARGET_STEPS or not result["all_outputs_finite"]
|
| 36 |
+
or Path(result["checkpoint"]).resolve() != checkpoint.resolve()):
|
| 37 |
+
raise ValueError("Final checkpoint evaluation did not pass")
|
| 38 |
+
receipt = run / "receipts" / f"{TARGET_STEPS}.json"
|
| 39 |
+
while not receipt.exists():
|
| 40 |
+
time.sleep(10)
|
| 41 |
+
exported = run / "exports" / str(TARGET_STEPS)
|
| 42 |
+
check = exported / "packaged-inference-check.txt"
|
| 43 |
+
if not check.exists():
|
| 44 |
+
code = '''
|
| 45 |
+
import json
|
| 46 |
+
import numpy as np
|
| 47 |
+
from load_model import load, observe
|
| 48 |
+
policy = load()
|
| 49 |
+
image = np.zeros((224,224,3),dtype=np.uint8)
|
| 50 |
+
state = np.array([.45,0,.15,.7,-.7,0,0,0],dtype=np.float32)
|
| 51 |
+
observe(policy,image,state)
|
| 52 |
+
obs = {"image":image,"wrist_image":image,"state":state,"prompt":policy.metadata["prompt"]}
|
| 53 |
+
if policy.metadata.get("training_setting")=="status_d":
|
| 54 |
+
from mme_vla_suite.training.semantic_transition_reader import runtime_only_zero_transition_metadata
|
| 55 |
+
obs.update({k:v for k,v in runtime_only_zero_transition_metadata().items() if k.startswith("transition_context_")})
|
| 56 |
+
obs.update(history_keyframe_index=None,current_subgoal=None)
|
| 57 |
+
result = policy.infer(obs)
|
| 58 |
+
assert result["actions"].shape==(20,8) and np.isfinite(result["actions"]).all()
|
| 59 |
+
print(json.dumps({"packaged_inference":"passed","shape":[20,8],"status":result.get("transition_status")}))
|
| 60 |
+
'''
|
| 61 |
+
smoke = subprocess.run([sys.executable, "-c", code], cwd=exported, capture_output=True, text=True, check=True,
|
| 62 |
+
env={**os.environ, "PYTHONPATH": str(exported), "CUDA_VISIBLE_DEVICES": "0"})
|
| 63 |
+
check.write_text(smoke.stdout.splitlines()[-1] + "\n")
|
| 64 |
+
shutil.copyfile(report, exported / "evaluation.json")
|
| 65 |
+
info_path = exported / "checkpoint_info.json"
|
| 66 |
+
info = json.loads(info_path.read_text())
|
| 67 |
+
info["evaluation_status"] = "completed"
|
| 68 |
+
info_path.write_text(json.dumps(info, indent=2))
|
| 69 |
+
card_path = exported / "README.md"
|
| 70 |
+
card = card_path.read_text()
|
| 71 |
+
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"
|
| 72 |
+
card = card.replace("Final checkpoint validation: held-out offline evaluation and packaged-source inference passed.",
|
| 73 |
+
"Final checkpoint checks: offline evaluation completed; packaged-source inference and finite-output checks passed.")
|
| 74 |
+
if note not in card:
|
| 75 |
+
card += note
|
| 76 |
+
card_path.write_text(card)
|
| 77 |
+
repo = model_repo_id(task, setting, TARGET_STEPS)
|
| 78 |
+
api = HfApi()
|
| 79 |
+
commit = api.upload_folder(repo_id=repo, folder_path=exported, repo_type="model",
|
| 80 |
+
allow_patterns=["evaluation.json", "checkpoint_info.json", "packaged-inference-check.txt", "README.md"],
|
| 81 |
+
commit_message="Add final offline evaluation and packaged inference validation")
|
| 82 |
+
remote = {f.rfilename: f.size for f in api.model_info(repo, files_metadata=True).siblings}
|
| 83 |
+
for filename in ("evaluation.json", "checkpoint_info.json", "packaged-inference-check.txt", "README.md"):
|
| 84 |
+
if remote.get(filename) != (exported / filename).stat().st_size:
|
| 85 |
+
raise RuntimeError(f"Final report missing or wrong size on Hub: {filename}")
|
| 86 |
+
complete = {"task": task, "setting": setting, "steps": TARGET_STEPS, "sample_exposures": TARGET_STEPS * 4,
|
| 87 |
+
"repo_id": repo, "evaluation": str(report), "packaged_inference": "passed", "commit": commit.oid}
|
| 88 |
+
(run / "complete.json").write_text(json.dumps(complete, indent=2))
|
| 89 |
+
print(json.dumps(complete), flush=True)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
if __name__ == "__main__":
|
| 93 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 94 |
+
parser.add_argument("--round-root", type=Path, required=True)
|
| 95 |
+
parser.add_argument("--task", choices=("button_order", "pick3", "shuffle"), required=True)
|
| 96 |
+
parser.add_argument("--setting", choices=("status_d", "baseline", "uniform32"), required=True)
|
| 97 |
+
finish(**vars(parser.parse_args()))
|
checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_round_run.py
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Train and archive the second Franka round, preserving every uploaded 1k checkpoint."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import dataclasses
|
| 6 |
+
import importlib.metadata
|
| 7 |
+
import json
|
| 8 |
+
import os
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
import shutil
|
| 11 |
+
import sys
|
| 12 |
+
import time
|
| 13 |
+
|
| 14 |
+
from integrations.robomme.franka_round import TARGET_STEPS, checkpoint_steps, checkpoint_storage, make_config, model_repo_id, prune_uploaded_checkpoints
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def train(dataset, run_root, setting, resume=False):
|
| 18 |
+
os.environ.setdefault("XLA_PYTHON_CLIENT_ALLOCATOR", "platform")
|
| 19 |
+
cfg = make_config(dataset, run_root, setting, resume=resume)
|
| 20 |
+
cfg = dataclasses.replace(cfg, policy_metadata={**cfg.policy_metadata, "gpu_allocator": "platform"})
|
| 21 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "robomme/scripts"))
|
| 22 |
+
import train as trainer
|
| 23 |
+
|
| 24 |
+
trainer.main(cfg)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def export_bundle(dataset, checkpoint, output, setting):
|
| 28 |
+
from integrations.robomme.franka_release import training_settings
|
| 29 |
+
|
| 30 |
+
dataset, checkpoint, output = map(Path, (dataset, checkpoint, output))
|
| 31 |
+
metadata = json.loads((checkpoint / "assets/policy_metadata.json").read_text())
|
| 32 |
+
spec = json.loads((dataset / "dataset.json").read_text())
|
| 33 |
+
if (metadata.get("training_round") != 2 or metadata.get("training_setting") != setting
|
| 34 |
+
or metadata.get("target_steps") != TARGET_STEPS or metadata.get("task") != spec["task"]):
|
| 35 |
+
raise ValueError("Only the matching formal second-round run may use this model name")
|
| 36 |
+
if setting == "status_d" and "pinned_writer" not in metadata:
|
| 37 |
+
raise ValueError("Status-D serving export requires the actual Writer provenance")
|
| 38 |
+
step = int(checkpoint.name)
|
| 39 |
+
repo = model_repo_id(spec["task"], setting, step)
|
| 40 |
+
output.mkdir(parents=True, exist_ok=True)
|
| 41 |
+
for folder in ("params", "assets", "resume_state"):
|
| 42 |
+
for source in (checkpoint / folder).rglob("*"):
|
| 43 |
+
if not source.is_file():
|
| 44 |
+
continue
|
| 45 |
+
target = output / source.relative_to(checkpoint)
|
| 46 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 47 |
+
if target.exists() and target.stat().st_size != source.stat().st_size:
|
| 48 |
+
target.unlink()
|
| 49 |
+
if not target.exists():
|
| 50 |
+
os.link(source, target)
|
| 51 |
+
shutil.copyfile(checkpoint / "_CHECKPOINT_METADATA", output / "_CHECKPOINT_METADATA")
|
| 52 |
+
shutil.copyfile(dataset / "dataset.json", output / "dataset_manifest.json")
|
| 53 |
+
config = training_settings(metadata, spec, step)
|
| 54 |
+
config.update(setting=setting, checkpoint_save_steps=checkpoint_steps(), training_round=2,
|
| 55 |
+
action_supervision=spec["action_supervision"], frame_coordinates=spec["frame_coordinates"],
|
| 56 |
+
checkpoint_retention=metadata["checkpoint_retention"])
|
| 57 |
+
if setting == "status_d":
|
| 58 |
+
config["history"]["history_tokens"] = 528
|
| 59 |
+
config["status_context"] = metadata["status_context"]
|
| 60 |
+
config["writer_schedule"] = metadata["writer_schedule"]
|
| 61 |
+
shutil.copyfile(dataset / "status/summary.json", output / "status_supervision_summary.json")
|
| 62 |
+
projection = json.loads((dataset / "writer/dataset-index.json").read_text())
|
| 63 |
+
original_writer = json.loads((Path(projection["source_annotations"]) / "dataset-index.json").read_text())
|
| 64 |
+
fields = ("writer_model", "writer_models_by_context", "writer_prompt_version", "writer_system_prompt",
|
| 65 |
+
"writer_evidence", "writer_api", "sampling_parameters", "dataset_version")
|
| 66 |
+
provenance = {k: original_writer[k] for k in fields if k in original_writer}
|
| 67 |
+
provenance.update(writer_schedule=projection["writer_schedule"], deployment_writer_model=projection["deployment_writer_model"])
|
| 68 |
+
if "task_definition_correction" in projection:
|
| 69 |
+
provenance["task_definition_correction"] = projection["task_definition_correction"]
|
| 70 |
+
(output / "writer_provenance.json").write_text(json.dumps(provenance, indent=2))
|
| 71 |
+
(output / "training_config.json").write_text(json.dumps(config, indent=2))
|
| 72 |
+
(output / "checkpoint_info.json").write_text(json.dumps({
|
| 73 |
+
"optimizer_step": step, "target_steps": TARGET_STEPS, "sample_exposures": step * 4,
|
| 74 |
+
"full_resume_state_included": True, "evaluation_status": "pending", "training_round": 2,
|
| 75 |
+
}, indent=2))
|
| 76 |
+
code_root = Path(__file__).resolve().parents[2]
|
| 77 |
+
for directory in ("integrations", "src", "robomme/src", "robomme/packages/openpi-client/src"):
|
| 78 |
+
for source in (code_root / directory).rglob("*"):
|
| 79 |
+
if source.is_file() and source.suffix in {".py", ".yaml", ".yml", ".json"}:
|
| 80 |
+
target = output / "code" / source.relative_to(code_root)
|
| 81 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 82 |
+
shutil.copyfile(source, target)
|
| 83 |
+
for directory in ("", "robomme"):
|
| 84 |
+
for filename in ("LICENSE", "pyproject.toml"):
|
| 85 |
+
source = code_root / directory / filename
|
| 86 |
+
if source.is_file():
|
| 87 |
+
target = output / "code" / directory / filename
|
| 88 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 89 |
+
shutil.copyfile(source, target)
|
| 90 |
+
excluded = {"picmem-dev", "openpi", "openpi-client", "flash-attn-jax"}
|
| 91 |
+
requirements = sorted({f"{d.metadata['Name']}=={d.version}" for d in importlib.metadata.distributions()
|
| 92 |
+
if d.metadata["Name"].lower().replace("_", "-") not in excluded})
|
| 93 |
+
(output / "requirements.txt").write_text("--extra-index-url https://download.pytorch.org/whl/cu126\n" + "\n".join(requirements) + "\n")
|
| 94 |
+
(output / "load_model.py").write_text(
|
| 95 |
+
'from pathlib import Path\nimport sys\nROOT = Path(__file__).resolve().parent\n'
|
| 96 |
+
'for path in ("code", "code/src", "code/robomme/src", "code/robomme/packages/openpi-client/src"):\n'
|
| 97 |
+
' sys.path.insert(0, str(ROOT / path))\n'
|
| 98 |
+
'from integrations.robomme.franka_baseline import load_policy, observe\n'
|
| 99 |
+
'def load():\n return load_policy(ROOT)\n'
|
| 100 |
+
)
|
| 101 |
+
method = (
|
| 102 |
+
"Status-D: 32 uniformly sampled frames over the complete observed episode prefix [0,t], "
|
| 103 |
+
"plus one nullable Writer keyframe (528 visual tokens total), and a held Writer current subgoal. "
|
| 104 |
+
"The Writer initializes at execution start and subsequently updates at Status events. "
|
| 105 |
+
"Offline Writer timing is projected using coarse event estimates; this is teacher conditioning, "
|
| 106 |
+
"not a claim of an online predicted-Status rollout. Status span positives use supported event brackets; "
|
| 107 |
+
"endpoint and negative supervision comes only from explicitly reviewed windows. Unreviewed labels "
|
| 108 |
+
"remain masked. Review provenance is agent/model review, not human ground truth. "
|
| 109 |
+
"The 48-step Status context uses recorded pose commands and measured state. Its command-gripper "
|
| 110 |
+
"feature is disabled consistently in training and inference; no missing gripper command is invented. "
|
| 111 |
+
"Historical state embeddings are disabled."
|
| 112 |
+
if setting == "status_d" else
|
| 113 |
+
"Uniform32: 32 uniformly sampled frames over the complete observed episode prefix [0,t], "
|
| 114 |
+
"512 visual tokens, including demonstration history. Historical state embeddings are disabled."
|
| 115 |
+
if setting == "uniform32" else "No-history baseline: current base/wrist images, state and task instruction."
|
| 116 |
+
)
|
| 117 |
+
(output / "README.md").write_text(f'''---
|
| 118 |
+
tags: [robotics, pi05, franka, lora]
|
| 119 |
+
---
|
| 120 |
+
|
| 121 |
+
# {repo.split('/')[-1]}
|
| 122 |
+
|
| 123 |
+
Second-round π0.5 LoRA fine-tuning for **{spec['task']}**, checkpoint **{step:,}**.
|
| 124 |
+
Trained locally on **4 RTX A6000 GPUs**, **global batch 4**, **per-GPU batch 1**,
|
| 125 |
+
without gradient accumulation. This checkpoint represents **{step * 4:,} sample exposures**;
|
| 126 |
+
the run targets **12,500 optimizer updates / 50,000 sample exposures**.
|
| 127 |
+
Checkpoints are saved every **1,000** updates and at the final **12,500**.
|
| 128 |
+
Steps **5,000**, **10,000**, and **12,500** have standalone model repositories.
|
| 129 |
+
Other complete checkpoints are retained in the
|
| 130 |
+
[backup archive](https://huggingface.co/datasets/fm-dev/pi05-checkpoint-backups/tree/main/checkpoints/r2)
|
| 131 |
+
under `task/method/stepN/` with the same loading files and full resume state.
|
| 132 |
+
`r2` keeps these artifacts separate from the original 6,250-step experiment.
|
| 133 |
+
|
| 134 |
+
Warmup: **250** updates to **5e-5**; cosine decay to **5e-6** at step **12,500**.
|
| 135 |
+
EMA: **0.999^4 = 0.996005996001**. AdamW, LoRA rank32, seed42.
|
| 136 |
+
Full settings are in `training_config.json`.
|
| 137 |
+
|
| 138 |
+
{method}
|
| 139 |
+
|
| 140 |
+
Only robot execution rows supervise actions. Demonstration images, features and
|
| 141 |
+
original episode/frame coordinates remain available as history; execution start
|
| 142 |
+
does not reset the visual history. Episode splits and normalization use the
|
| 143 |
+
training split only. The recorded Cartesian end-effector/tool pose convention
|
| 144 |
+
must match the collection controller; do not apply an extra tool/flange offset.
|
| 145 |
+
Outputs have shape `(20,8)`: absolute xyz, unit XYZW quaternion in the positive-qx
|
| 146 |
+
chart, and gripper command in [0,1]. Numeric state/actions use STD normalization;
|
| 147 |
+
state tokens use a separate bounded train-q01/q99 view.
|
| 148 |
+
|
| 149 |
+
Unknown action components remain NaN/false in the training dataset and are masked
|
| 150 |
+
in both flow conditioning and loss. Entirely unsupervised components:
|
| 151 |
+
**{spec.get('unsupervised_action_components', [])}**. In particular, Shuffle's
|
| 152 |
+
gripper output has no command supervision and must not be interpreted as learned
|
| 153 |
+
gripper control. Button Order has only limited verified closed-command labels.
|
| 154 |
+
|
| 155 |
+
This repository includes EMA serving weights, normalization/history assets,
|
| 156 |
+
inference source, exact dependency versions, and full non-EMA/optimizer/RNG/sampler
|
| 157 |
+
resume state. Intermediate publication is not a policy-quality evaluation.
|
| 158 |
+
Offline evaluation, when included, does not establish real-robot success rate.
|
| 159 |
+
|
| 160 |
+
Load with `from load_model import load, observe; policy = load()` from this bundle.
|
| 161 |
+
For history models call `observe(policy, base_rgb, state)` for every observed frame,
|
| 162 |
+
including demonstrations, and reset between episodes. Status-D additionally requires
|
| 163 |
+
explicit `history_keyframe_index` (an observed frame or None), `current_subgoal`,
|
| 164 |
+
and causal `transition_context_*` inputs in `policy.infer(...)`; its output includes
|
| 165 |
+
`transition_status`. Use the exported Writer schedule and matching control frame.
|
| 166 |
+
''')
|
| 167 |
+
return repo
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def archive(round_root, settings):
|
| 171 |
+
from huggingface_hub import HfApi
|
| 172 |
+
from huggingface_hub.hf_api import RepoFile
|
| 173 |
+
|
| 174 |
+
root = Path(round_root)
|
| 175 |
+
names = {"status_d": "pi05_franka_status_d", "baseline": "pi05_franka_baseline", "uniform32": "pi05_franka_uniform32_baseline"}
|
| 176 |
+
jobs = [(task, setting, step) for setting in settings for task in ("button_order", "pick3", "shuffle") for step in checkpoint_steps()]
|
| 177 |
+
api = HfApi()
|
| 178 |
+
while jobs:
|
| 179 |
+
for task, setting, step in jobs[:]:
|
| 180 |
+
run = root / "runs" / task / setting
|
| 181 |
+
checkpoints = run / "checkpoints" / names[setting] / task.replace("_", "-")
|
| 182 |
+
checkpoint, export = checkpoints / str(step), run / "exports" / str(step)
|
| 183 |
+
receipts = run / "receipts"
|
| 184 |
+
receipt = receipts / f"{step}.json"
|
| 185 |
+
if receipt.exists():
|
| 186 |
+
record = json.loads(receipt.read_text())
|
| 187 |
+
if record.get("full_bundle_verified") is not True:
|
| 188 |
+
raise ValueError(f"Incomplete upload receipt: {receipt}")
|
| 189 |
+
jobs.remove((task, setting, step))
|
| 190 |
+
continue
|
| 191 |
+
if not (checkpoint / "_CHECKPOINT_METADATA").is_file():
|
| 192 |
+
continue
|
| 193 |
+
model_id = export_bundle(root / "datasets" / task, checkpoint, export, setting)
|
| 194 |
+
repo, repo_type, path_in_repo = checkpoint_storage(task, setting, step)
|
| 195 |
+
prefix = f"{path_in_repo}/" if path_in_repo else ""
|
| 196 |
+
try:
|
| 197 |
+
api.create_repo(repo, private=False, repo_type=repo_type, exist_ok=True)
|
| 198 |
+
commit = api.upload_folder(repo_id=repo, folder_path=export, repo_type=repo_type,
|
| 199 |
+
path_in_repo=path_in_repo or None,
|
| 200 |
+
ignore_patterns=[".cache/**", "**/__pycache__/**"],
|
| 201 |
+
commit_message=f"Upload full round2 {step}-step checkpoint")
|
| 202 |
+
info = api.repo_info(repo, repo_type=repo_type)
|
| 203 |
+
if info.private:
|
| 204 |
+
api.update_repo_settings(repo_id=repo, repo_type=repo_type, private=False)
|
| 205 |
+
info = api.repo_info(repo, repo_type=repo_type)
|
| 206 |
+
remote = {f.path: f.size for f in api.list_repo_tree(
|
| 207 |
+
repo, repo_type=repo_type, path_in_repo=path_in_repo or None, recursive=True
|
| 208 |
+
) if isinstance(f, RepoFile)}
|
| 209 |
+
for path in checkpoint.rglob("*"):
|
| 210 |
+
if path.is_file() and remote.get(prefix + path.relative_to(checkpoint).as_posix()) != path.stat().st_size:
|
| 211 |
+
raise RuntimeError(f"Source checkpoint file missing remotely: {repo}/{path.relative_to(checkpoint)}")
|
| 212 |
+
files = [p for p in export.rglob("*") if p.is_file() and not {".cache", "__pycache__"}.intersection(p.relative_to(export).parts)]
|
| 213 |
+
for path in files:
|
| 214 |
+
if remote.get(prefix + path.relative_to(export).as_posix()) != path.stat().st_size:
|
| 215 |
+
raise RuntimeError(f"Remote file missing or wrong size: {repo}/{path.relative_to(export)}")
|
| 216 |
+
receipts.mkdir(parents=True, exist_ok=True)
|
| 217 |
+
temporary = receipt.with_suffix(".tmp")
|
| 218 |
+
temporary.write_text(json.dumps({"checkpoint": str(checkpoint.resolve()), "repo_id": repo,
|
| 219 |
+
"repo_type": repo_type, "path_in_repo": path_in_repo,
|
| 220 |
+
"model_id": model_id,
|
| 221 |
+
"step": step, "full_bundle_verified": True, "commit": commit.oid,
|
| 222 |
+
"files": len(files), "public": not info.private}, indent=2))
|
| 223 |
+
temporary.replace(receipt)
|
| 224 |
+
jobs.remove((task, setting, step))
|
| 225 |
+
print(f"Verified {repo_type}:{repo}/{path_in_repo}", flush=True)
|
| 226 |
+
removed = prune_uploaded_checkpoints(checkpoints, run / "exports", receipts)
|
| 227 |
+
if removed:
|
| 228 |
+
print(f"Pruned verified local checkpoints {task}/{setting}: {removed}", flush=True)
|
| 229 |
+
except Exception as error:
|
| 230 |
+
print(f"Upload retry pending {repo}: {type(error).__name__}: {error}", flush=True)
|
| 231 |
+
time.sleep(30)
|
| 232 |
+
if jobs:
|
| 233 |
+
time.sleep(10)
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
if __name__ == "__main__":
|
| 237 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 238 |
+
commands = parser.add_subparsers(dest="command", required=True)
|
| 239 |
+
training = commands.add_parser("train")
|
| 240 |
+
training.add_argument("--dataset", type=Path, required=True)
|
| 241 |
+
training.add_argument("--run-root", type=Path, required=True)
|
| 242 |
+
training.add_argument("--setting", choices=("status_d", "baseline", "uniform32"), required=True)
|
| 243 |
+
training.add_argument("--resume", action="store_true")
|
| 244 |
+
uploading = commands.add_parser("archive")
|
| 245 |
+
uploading.add_argument("--round-root", type=Path, required=True)
|
| 246 |
+
uploading.add_argument("--settings", nargs="+", choices=("status_d", "baseline", "uniform32"), default=["status_d"])
|
| 247 |
+
args = vars(parser.parse_args())
|
| 248 |
+
command = args.pop("command")
|
| 249 |
+
{"train": train, "archive": archive}[command](**args)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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Bind real Franka observations, partial Status labels, and causal Writer projections."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from collections import Counter
|
| 5 |
+
import hashlib
|
| 6 |
+
import json
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import pickle
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
import polars as pl
|
| 12 |
+
import yaml
|
| 13 |
+
|
| 14 |
+
from integrations.robomme.franka_baseline import canonical_pose
|
| 15 |
+
from integrations.robomme.franka_partial import read_h5_signals
|
| 16 |
+
from picmem.data.semantic_transition.canonical import canonical_json_sha256
|
| 17 |
+
from picmem.data.semantic_transition.pinned_keyframe import parse_pinned_episode
|
| 18 |
+
from picmem.data.semantic_transition.scheduled_writer import EVIDENCE_POLICY, INDEX_SCHEMA_VERSION, project_writer_episode, teacher_status_triggers
|
| 19 |
+
from picmem.data.semantic_transition.sequence_targets import (
|
| 20 |
+
TransitionRowKey, TransitionSequence, TransitionSequenceManifest, TransitionSourceRow,
|
| 21 |
+
TransitionStatusRowTarget, _sequence_identity_payload, write_transition_sequence_manifest,
|
| 22 |
+
)
|
| 23 |
+
from picmem.data.semantic_transition.training_materializer import build_realized_transition_context
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def event_records(annotations, task):
|
| 27 |
+
result = {}
|
| 28 |
+
for version in ("events-astra-v2", "events-astra-refinements-v3"):
|
| 29 |
+
for path in sorted((Path(annotations) / version / task).glob("episode_*/candidate_*/annotation.json")):
|
| 30 |
+
record = json.loads(path.read_text())
|
| 31 |
+
result[record["raw_episode_id"], record["candidate_id"]] = record
|
| 32 |
+
return list(result.values())
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def prepare_writer(dataset, annotations):
|
| 36 |
+
dataset, annotations = Path(dataset), Path(annotations)
|
| 37 |
+
spec = json.loads((dataset / "dataset.json").read_text())
|
| 38 |
+
output = dataset / "writer"
|
| 39 |
+
if output.exists():
|
| 40 |
+
return json.loads((output / "dataset-index.json").read_text())
|
| 41 |
+
output.mkdir()
|
| 42 |
+
records = event_records(annotations, spec["task"])
|
| 43 |
+
version = "writer-astra-real-v2" if spec["task"] == "button_order" else "writer-astra-real-v1"
|
| 44 |
+
source_root = annotations / version / spec["task"]
|
| 45 |
+
source_index = json.loads((source_root / "dataset-index.json").read_text())
|
| 46 |
+
schedule = {"mode": "status", "initialization": "episode_start", "period_frames": None,
|
| 47 |
+
"evidence": EVIDENCE_POLICY}
|
| 48 |
+
selected, summaries = [], []
|
| 49 |
+
for episode in spec["episodes"]:
|
| 50 |
+
if episode["split"] == "excluded":
|
| 51 |
+
continue
|
| 52 |
+
source_path = source_root / f"episode_{episode['writer_episode_id']:06d}.json"
|
| 53 |
+
source = json.loads(source_path.read_text())
|
| 54 |
+
for name in ("inference_backend", "native_backend"):
|
| 55 |
+
source.pop(name, None)
|
| 56 |
+
source["episode_id"] = episode["episode_id"]
|
| 57 |
+
parse_pinned_episode(source)
|
| 58 |
+
events = [r["event"] for r in records if r["raw_episode_id"] == episode["episode"]
|
| 59 |
+
and r["result"]["verdict"] == "observed" and r.get("event") is not None]
|
| 60 |
+
mapping = {"episode_id": str(episode["episode_id"]), "total_frames": episode["frames"],
|
| 61 |
+
"unit_mappings": [{"unit_id": e["event_id"], "phase": "execution", "semantic_transition": True,
|
| 62 |
+
"action_start_frame": e["action_start_frame"], "action_end_frame": e["action_end_frame"]}
|
| 63 |
+
for e in events]}
|
| 64 |
+
triggers, queries = teacher_status_triggers(mapping, execution_start_frame=episode["execution_start"],
|
| 65 |
+
task_name=f"franka_{spec['task']}")
|
| 66 |
+
for trigger in triggers:
|
| 67 |
+
trigger["trigger_source"] = "franka_coarse_event_teacher_controller"
|
| 68 |
+
projected = project_writer_episode(source, triggers, schedule=schedule,
|
| 69 |
+
dataset_version=f"franka-{spec['task']}-status-d-r2")
|
| 70 |
+
(output / f"episode_{episode['episode_id']:06d}.json").write_text(json.dumps(projected, indent=2))
|
| 71 |
+
trace = {"source_episode": str(source_path), "global_episode_id": episode["episode_id"],
|
| 72 |
+
"source_episode_id": episode["writer_episode_id"], "raw_episode_id": episode["episode"],
|
| 73 |
+
"teacher_scope": "coarse event estimates used only for Writer timing; not certified negative Status labels",
|
| 74 |
+
"queries": queries, "triggers": triggers}
|
| 75 |
+
(output / f"teacher-{episode['episode_id']:06d}.json").write_text(json.dumps(trace, indent=2))
|
| 76 |
+
selected.append(episode["episode_id"])
|
| 77 |
+
summaries.append({"episode_id": episode["episode_id"], "updates": len(projected["updates"])})
|
| 78 |
+
index = {"schema_version": INDEX_SCHEMA_VERSION, "complete": True, "selected_episode_ids": sorted(selected),
|
| 79 |
+
"episode_count": len(selected), "dataset_version": f"franka-{spec['task']}-status-d-r2",
|
| 80 |
+
"writer_schedule": schedule, "source_annotations": str(source_root.resolve()),
|
| 81 |
+
"source_dataset_version": source_index["dataset_version"],
|
| 82 |
+
"annotation_writer": {k: source_index[k] for k in ("writer_model", "writer_models_by_context", "writer_prompt_version", "writer_evidence")},
|
| 83 |
+
"deployment_writer_model": "gemini-3.7-flash", "episodes": summaries,
|
| 84 |
+
"teacher_scope": "coarse interval teacher projection; source own-bank labels may differ from sparse online Writer"}
|
| 85 |
+
(output / "dataset-index.json").write_text(json.dumps(index, indent=2))
|
| 86 |
+
return index
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def causal_context(stamps, states, poses, target):
|
| 90 |
+
"""Use the last contiguous observed history; the command-gripper feature is disabled."""
|
| 91 |
+
first = target
|
| 92 |
+
for previous in range(target - 1, max(-1, target - 49), -1):
|
| 93 |
+
if (not np.isfinite(states[previous:previous + 2]).all() or not np.isfinite(poses[previous]).all()
|
| 94 |
+
or not 0 < stamps[previous + 1] - stamps[previous] <= 100_000_000):
|
| 95 |
+
break
|
| 96 |
+
first = previous
|
| 97 |
+
command_features = np.zeros((target - first + 1, 8), dtype=np.float32)
|
| 98 |
+
command_features[:-1, :7] = poses[first:target]
|
| 99 |
+
return build_realized_transition_context(actions=command_features, states=states[first:target + 1],
|
| 100 |
+
target_index=target - first)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def prepare_status(dataset, canonical, reviews, version="v1"):
|
| 104 |
+
dataset, canonical, reviews = map(Path, (dataset, canonical, reviews))
|
| 105 |
+
spec = json.loads((dataset / "dataset.json").read_text())
|
| 106 |
+
output = dataset / f"status-{version}"
|
| 107 |
+
output.mkdir(exist_ok=False)
|
| 108 |
+
episodes = {e["episode_id"]: e for e in spec["episodes"]}
|
| 109 |
+
labels = {(r["global_episode_id"], r["step_idx"]): r
|
| 110 |
+
for r in json.loads((reviews / f"{spec['task']}-coarse-positive-spans.json").read_text())["labels"]}
|
| 111 |
+
for path in reviews.rglob("*-reviewed.json"):
|
| 112 |
+
record = json.loads(path.read_text())
|
| 113 |
+
if record.get("task") != spec["task"]:
|
| 114 |
+
continue
|
| 115 |
+
for label in record["labels"]:
|
| 116 |
+
key = record["global_episode_id"], label["step_idx"]
|
| 117 |
+
if not set(range(key[1], key[1] + 17)) <= set(label["observed_frames"]):
|
| 118 |
+
raise ValueError(f"Reviewed labels require complete consecutive observations: {key}")
|
| 119 |
+
if key in labels and labels[key]["span_target"] != label["span_target"]:
|
| 120 |
+
raise ValueError(f"Review contradicts a coarse-positive target; resolve explicitly: {key}")
|
| 121 |
+
labels[key] = {**label, "global_episode_id": key[0], "split": episodes[key[0]]["split"],
|
| 122 |
+
"source_review": str(path.resolve())}
|
| 123 |
+
inputs, input_values = {}, {}
|
| 124 |
+
for split in ("train", "validation", "test"):
|
| 125 |
+
for path in (dataset / split / "data").glob("*.pkl"):
|
| 126 |
+
with path.open("rb") as stream:
|
| 127 |
+
row = pickle.load(stream)
|
| 128 |
+
key = int(row["epis_idx"]), int(row["step_idx"])
|
| 129 |
+
inputs[key], input_values[key] = path, row
|
| 130 |
+
sequences, bindings, context_rows = {s: [] for s in ("train", "validation", "test")}, [], []
|
| 131 |
+
for split in sequences:
|
| 132 |
+
(output / split / "data").mkdir(parents=True)
|
| 133 |
+
(output / split / "meta").mkdir()
|
| 134 |
+
(output / split / "features").symlink_to(dataset / "features", target_is_directory=True)
|
| 135 |
+
current_episode, frames, signals = None, None, None
|
| 136 |
+
source_rows = {}
|
| 137 |
+
for key, label in sorted(labels.items()):
|
| 138 |
+
episode_id, step = key
|
| 139 |
+
episode = episodes[episode_id]
|
| 140 |
+
split = episode["split"]
|
| 141 |
+
if key not in inputs:
|
| 142 |
+
raise ValueError(f"Status query lacks an accepted model input: {key}")
|
| 143 |
+
if current_episode != episode_id:
|
| 144 |
+
frames = pl.read_parquet(canonical / "data/chunk-000" / f"episode_{episode['writer_episode_id']:06d}.parquet")
|
| 145 |
+
stamps, state_pose, target_pose, widths = read_h5_signals(Path(spec["source"]) / spec["task"] / f"{episode['episode']}.h5")
|
| 146 |
+
states = np.c_[state_pose, widths].astype(np.float32)
|
| 147 |
+
finite = np.isfinite(states[:, :7]).all(-1)
|
| 148 |
+
states[finite, :7] = canonical_pose(states[finite, :7])
|
| 149 |
+
poses = target_pose.astype(np.float32)
|
| 150 |
+
finite = np.isfinite(poses).all(-1)
|
| 151 |
+
poses[finite] = canonical_pose(poses[finite])
|
| 152 |
+
signals = stamps, states, poses
|
| 153 |
+
current_episode = episode_id
|
| 154 |
+
context = causal_context(*signals, step)
|
| 155 |
+
bound = []
|
| 156 |
+
for frame in range(step, step + 17):
|
| 157 |
+
source_key = episode_id, frame
|
| 158 |
+
if source_key not in source_rows:
|
| 159 |
+
if source_key in inputs:
|
| 160 |
+
path = inputs[source_key]
|
| 161 |
+
data = path.read_bytes()
|
| 162 |
+
kind = "accepted_model_input"
|
| 163 |
+
else:
|
| 164 |
+
observation = frames.row(frame, named=True)
|
| 165 |
+
if int(observation["frame_index"]) != frame:
|
| 166 |
+
raise ValueError("Canonical observation/frame index mismatch")
|
| 167 |
+
data = pickle.dumps(observation, protocol=pickle.HIGHEST_PROTOCOL)
|
| 168 |
+
path = output / "observations" / f"{episode_id}-{frame}.pkl"
|
| 169 |
+
path.parent.mkdir(exist_ok=True)
|
| 170 |
+
path.write_bytes(data)
|
| 171 |
+
kind = "canonical_result_observation_only"
|
| 172 |
+
source_rows[source_key] = TransitionSourceRow(
|
| 173 |
+
TransitionRowKey(f"franka_{spec['task']}", episode_id, frame), hashlib.sha256(data).hexdigest())
|
| 174 |
+
bindings.append({"key": source_rows[source_key].key.to_dict(), "file": str(path.resolve()),
|
| 175 |
+
"kind": kind, "sha256": source_rows[source_key].row_sha256})
|
| 176 |
+
bound.append(source_rows[source_key])
|
| 177 |
+
target = TransitionStatusRowTarget(
|
| 178 |
+
source_row=bound[0], chunk_index=0, candidate_observation_steps=tuple(range(step + 1, step + 17)),
|
| 179 |
+
candidate_observation_row_sha256=tuple(r.row_sha256 for r in bound[1:]),
|
| 180 |
+
transition_span_target=label["span_target"], transition_last_span_target=label["last_span_target"],
|
| 181 |
+
transition_status_valid=True, transition_last_span_valid=label["last_span_valid"],
|
| 182 |
+
realized_transition_context=context,
|
| 183 |
+
)
|
| 184 |
+
annotation_sha = canonical_json_sha256(label)
|
| 185 |
+
identity = _sequence_identity_payload(start_key=target.source_row.key, annotation_sha256=annotation_sha,
|
| 186 |
+
reviewed_through_step=step + 16, rows=[target])
|
| 187 |
+
sequence = TransitionSequence(canonical_json_sha256(identity), target.source_row.key, annotation_sha,
|
| 188 |
+
tuple(range(step + 1, step + 49)), step + 16, (target,))
|
| 189 |
+
index = len(sequences[split])
|
| 190 |
+
(output / split / "data" / f"{index}.pkl").symlink_to(inputs[key].resolve())
|
| 191 |
+
sequences[split].append(sequence)
|
| 192 |
+
if split == "train":
|
| 193 |
+
values = context.as_numpy()
|
| 194 |
+
array = np.c_[values["transition_context_action_delta"], values["transition_context_state_delta"], values["transition_context_relative_age"]]
|
| 195 |
+
context_rows.extend(array[values["transition_context_valid_mask"]])
|
| 196 |
+
summary = {"task": spec["task"], "counts": {}, "manifest_sha256": {}, "context_disabled_action_components": [7]}
|
| 197 |
+
for split, values in sequences.items():
|
| 198 |
+
manifest = TransitionSequenceManifest(canonical_json_sha256(bindings), canonical_json_sha256(list(labels.values())), tuple(values))
|
| 199 |
+
digest = write_transition_sequence_manifest(output / split / "transition-sequence-manifest.json", manifest)
|
| 200 |
+
(output / split / "meta/stats.json").write_text(json.dumps({"total_samples": len(values)}))
|
| 201 |
+
summary["manifest_sha256"][split] = digest
|
| 202 |
+
summary["counts"][split] = dict(Counter(
|
| 203 |
+
"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"
|
| 204 |
+
for s in values))
|
| 205 |
+
context_matrix = np.stack(context_rows)
|
| 206 |
+
mean, std = context_matrix.mean(0), context_matrix.std(0)
|
| 207 |
+
mean[7], std[7] = 0, 1
|
| 208 |
+
std = np.where(std > 1e-6, std, 1)
|
| 209 |
+
summary["context_input_mean"], summary["context_input_std"] = mean.tolist(), std.tolist()
|
| 210 |
+
(output / "source-bindings.json").write_text(json.dumps(bindings, indent=2))
|
| 211 |
+
(output / "labels.json").write_text(json.dumps(list(labels.values()), indent=2))
|
| 212 |
+
(output / "summary.json").write_text(json.dumps(summary, indent=2))
|
| 213 |
+
history_source = Path(__file__).resolve().parents[2] / "robomme/src/mme_vla_suite/models/config/robomme/perceptual-uniform32-status-d-modul.yaml"
|
| 214 |
+
history = yaml.safe_load(history_source.read_text())
|
| 215 |
+
history["use_state_emb"] = False
|
| 216 |
+
history["pinned_keyframe"]["annotation_dir"] = str((dataset / "writer").resolve())
|
| 217 |
+
history["transition_status"].update(
|
| 218 |
+
training_manifest_path=str((output / "train/transition-sequence-manifest.json").resolve()),
|
| 219 |
+
training_manifest_sha256=summary["manifest_sha256"]["train"],
|
| 220 |
+
context_input_mean=mean.tolist(), context_input_std=std.tolist(),
|
| 221 |
+
)
|
| 222 |
+
(dataset / "assets/history_status_d.yaml").write_text(yaml.safe_dump(history, sort_keys=False))
|
| 223 |
+
status_link = dataset / "status"
|
| 224 |
+
if status_link.is_symlink():
|
| 225 |
+
status_link.unlink()
|
| 226 |
+
status_link.symlink_to(output.name, target_is_directory=True)
|
| 227 |
+
return summary
|
checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_status_labels.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Use accepted coarse events only as certain positive spans; leave endpoint/negative targets unknown."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import json
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import pickle
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def positive_span_labels(dataset, annotations):
|
| 10 |
+
dataset, annotations = Path(dataset), Path(annotations)
|
| 11 |
+
spec = json.loads((dataset / "dataset.json").read_text())
|
| 12 |
+
episodes = {e["episode"]: e for e in spec["episodes"]}
|
| 13 |
+
available = {}
|
| 14 |
+
for split in ("train", "validation", "test"):
|
| 15 |
+
for path in (dataset / split / "data").glob("*.pkl"):
|
| 16 |
+
with path.open("rb") as stream:
|
| 17 |
+
row = pickle.load(stream)
|
| 18 |
+
available.setdefault(int(row["epis_idx"]), []).append(int(row["step_idx"]))
|
| 19 |
+
events = {}
|
| 20 |
+
for version in ("events-astra-v2", "events-astra-refinements-v3"):
|
| 21 |
+
for path in sorted((annotations / version / spec["task"]).glob("episode_*/candidate_*/annotation.json")):
|
| 22 |
+
record = json.loads(path.read_text())
|
| 23 |
+
events[record["raw_episode_id"], record["candidate_id"]] = (path, record)
|
| 24 |
+
labels, omitted = [], []
|
| 25 |
+
for (raw_episode, candidate), (path, record) in sorted(events.items()):
|
| 26 |
+
if record["result"]["verdict"] != "observed" or record.get("event") is None:
|
| 27 |
+
continue
|
| 28 |
+
episode = episodes[raw_episode]
|
| 29 |
+
window = record["event"]["observable_window"]
|
| 30 |
+
earliest, latest = window["earliest_frame"], window["latest_frame"]
|
| 31 |
+
# A whole supported change bracket must lie among this chunk's resulting
|
| 32 |
+
# observations. No exact action endpoint or negative coverage is inferred.
|
| 33 |
+
starts = [t for t in available.get(episode["episode_id"], []) if t < earliest <= latest <= t + 16]
|
| 34 |
+
if not starts:
|
| 35 |
+
omitted.append({"episode": raw_episode, "candidate_id": candidate,
|
| 36 |
+
"reason": "No valid policy input window contains the full observable bracket"})
|
| 37 |
+
continue
|
| 38 |
+
start = min(starts, key=lambda t: (abs(t - ((earliest + latest) / 2 - 8)), t))
|
| 39 |
+
labels.append({
|
| 40 |
+
"task": spec["task"], "global_episode_id": episode["episode_id"],
|
| 41 |
+
"raw_episode_id": raw_episode, "split": episode["split"], "step_idx": start,
|
| 42 |
+
"span_target": 1, "last_span_target": 0, "last_span_valid": False,
|
| 43 |
+
"source_annotation": str(path.resolve()), "candidate_id": candidate,
|
| 44 |
+
"observable_bracket": [earliest, latest],
|
| 45 |
+
"supervision_scope": "accepted coarse positive span only; endpoint and negatives unsupervised",
|
| 46 |
+
"human_ground_truth": False,
|
| 47 |
+
})
|
| 48 |
+
return {"task": spec["task"], "labels": labels, "omitted": omitted}
|
checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_status_review.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Render consecutive observed frames for targeted Status review; never assign labels automatically."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import io
|
| 6 |
+
import json
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
from PIL import Image, ImageDraw, ImageOps
|
| 10 |
+
import polars as pl
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def render(canonical, output, episode_id, starts):
|
| 14 |
+
canonical, output = Path(canonical), Path(output)
|
| 15 |
+
source = canonical / "data/chunk-000" / f"episode_{episode_id:06d}.parquet"
|
| 16 |
+
indices = sorted({i for start in starts for i in range(max(0, start - 2), start + 19)})
|
| 17 |
+
frames = pl.read_parquet(source, columns=["frame_index", "image", "wrist_image"])
|
| 18 |
+
if min(starts) < 0 or max(starts) + 16 >= frames.height:
|
| 19 |
+
raise ValueError("Each review must include all 16 resulting observations")
|
| 20 |
+
selected = frames.filter(pl.col("frame_index").is_in(indices)).sort("frame_index")
|
| 21 |
+
tiles = []
|
| 22 |
+
for row in selected.iter_rows(named=True):
|
| 23 |
+
for column, label in (("image", "FRONT DETAIL"), ("wrist_image", "WRIST")):
|
| 24 |
+
tile = Image.new("RGB", (256, 280), "black")
|
| 25 |
+
draw = ImageDraw.Draw(tile)
|
| 26 |
+
draw.text((5, 5), f"TP {row['frame_index']} {label}", fill="white")
|
| 27 |
+
value = row[column]
|
| 28 |
+
if value is None or not value.get("bytes"):
|
| 29 |
+
draw.text((20, 120), "MISSING VIEW", fill="red")
|
| 30 |
+
else:
|
| 31 |
+
image = Image.open(io.BytesIO(value["bytes"])).convert("RGB")
|
| 32 |
+
if column == "image":
|
| 33 |
+
image = image.crop((560, 0, min(1280, image.width), min(720, image.height)))
|
| 34 |
+
image = ImageOps.contain(image, (256, 256))
|
| 35 |
+
tile.paste(image, ((256 - image.width) // 2, 24 + (256 - image.height) // 2))
|
| 36 |
+
tiles.append(tile)
|
| 37 |
+
sheet = Image.new("RGB", (2048, ((len(tiles) + 7) // 8) * 280), "black")
|
| 38 |
+
for i, tile in enumerate(tiles):
|
| 39 |
+
sheet.paste(tile, ((i % 8) * 256, (i // 8) * 280))
|
| 40 |
+
output.parent.mkdir(parents=True, exist_ok=True)
|
| 41 |
+
sheet.save(output, quality=92)
|
| 42 |
+
metadata = {"source": str(source), "episode_id": episode_id, "query_starts": starts,
|
| 43 |
+
"observed_frames": selected["frame_index"].to_list(), "review_status": "pending",
|
| 44 |
+
"image_size": list(sheet.size)}
|
| 45 |
+
output.with_suffix(".json").write_text(json.dumps(metadata, indent=2))
|
| 46 |
+
return metadata
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
if __name__ == "__main__":
|
| 50 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 51 |
+
parser.add_argument("--canonical", type=Path, required=True)
|
| 52 |
+
parser.add_argument("--output", type=Path, required=True)
|
| 53 |
+
parser.add_argument("--episode-id", type=int, required=True)
|
| 54 |
+
parser.add_argument("--starts", type=int, nargs="+", required=True)
|
| 55 |
+
print(json.dumps(render(**vars(parser.parse_args()))))
|
checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/manifest.json
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema_version": "picmem_robomme_phase_a_overlay_v6",
|
| 3 |
+
"base": {
|
| 4 |
+
"repository": "git@github.com:shulin16/wam_dev.git",
|
| 5 |
+
"branch": "main",
|
| 6 |
+
"commit": "8b1a6f7512c839b67449254535fc564db0876593",
|
| 7 |
+
"source_root": "robomme_policy_learning",
|
| 8 |
+
"source_files": {
|
| 9 |
+
"src/mme_vla_suite/shared/mem_buffer.py": {
|
| 10 |
+
"path": "robomme_policy_learning/src/mme_vla_suite/shared/mem_buffer.py",
|
| 11 |
+
"sha256": "ed37406c663cc9be9035cbadb2b961ad2babcc26d7fb8883535aaff1698efef7"
|
| 12 |
+
},
|
| 13 |
+
"src/mme_vla_suite/training/dataset.py": {
|
| 14 |
+
"path": "robomme_policy_learning/src/mme_vla_suite/training/dataset.py",
|
| 15 |
+
"sha256": "435df6266d4fbc3c1c8ca1c3e7b72c7f53f398f929a62f7488daa64cdcecfa48"
|
| 16 |
+
}
|
| 17 |
+
}
|
| 18 |
+
},
|
| 19 |
+
"target": {
|
| 20 |
+
"repository": "git@github.com:shulin16/wam_dev.git",
|
| 21 |
+
"branch": "feat/robomme-mme-vla-pipeline",
|
| 22 |
+
"commit": "8aeb20dc5be051606618aae4b379f97af8cc407d",
|
| 23 |
+
"workspace_root": "picmem"
|
| 24 |
+
},
|
| 25 |
+
"paths": [
|
| 26 |
+
{
|
| 27 |
+
"path": "src/mme_vla_suite/shared/mem_buffer.py",
|
| 28 |
+
"base_sha256": "ed37406c663cc9be9035cbadb2b961ad2babcc26d7fb8883535aaff1698efef7",
|
| 29 |
+
"target_preimage_sha256": "ed37406c663cc9be9035cbadb2b961ad2babcc26d7fb8883535aaff1698efef7",
|
| 30 |
+
"overlay_sha256": "f1f3eb94b9423eb39065322cb1751a176a2bca7778bf2e4cb878b892119e088b"
|
| 31 |
+
},
|
| 32 |
+
{
|
| 33 |
+
"path": "src/mme_vla_suite/training/picmem_phase_a.py",
|
| 34 |
+
"base_sha256": null,
|
| 35 |
+
"target_preimage_sha256": null,
|
| 36 |
+
"overlay_sha256": "771b71fbcf5e7f7482ab40fc1acbba2a19c24c6259a081f467e0dc946eb6062b"
|
| 37 |
+
},
|
| 38 |
+
{
|
| 39 |
+
"path": "src/mme_vla_suite/training/picmem_phase_a_full_state.py",
|
| 40 |
+
"base_sha256": null,
|
| 41 |
+
"target_preimage_sha256": null,
|
| 42 |
+
"overlay_sha256": "e8b165aeec8d023b9df72a956ee6b1c227a44e71e2dc7114fd383ecfc9e7fe30"
|
| 43 |
+
},
|
| 44 |
+
{
|
| 45 |
+
"path": "src/mme_vla_suite/training/picmem_phase_a_reader.py",
|
| 46 |
+
"base_sha256": null,
|
| 47 |
+
"target_preimage_sha256": null,
|
| 48 |
+
"overlay_sha256": "75015051b775c12e07f8d6f8b893108cba1951ecbe4a445f33a3e490d524a4aa"
|
| 49 |
+
},
|
| 50 |
+
{
|
| 51 |
+
"path": "src/mme_vla_suite/training/picmem_phase_a_runtime.py",
|
| 52 |
+
"base_sha256": null,
|
| 53 |
+
"target_preimage_sha256": null,
|
| 54 |
+
"overlay_sha256": "5b218f15545dd1ee75ccb7271300ef985a2b46fcaaedaf74170f638c702ae43c"
|
| 55 |
+
},
|
| 56 |
+
{
|
| 57 |
+
"path": "src/mme_vla_suite/training/dataset.py",
|
| 58 |
+
"base_sha256": "435df6266d4fbc3c1c8ca1c3e7b72c7f53f398f929a62f7488daa64cdcecfa48",
|
| 59 |
+
"target_preimage_sha256": "62f867c89b0073f484ba15ff1e3a5f5554ec520bcae00b06cdcff3f19fbf0d3b",
|
| 60 |
+
"overlay_sha256": "e60d8f245dc20c1c805014690297a2a00f5a4fb6e18f09280d743847edab2c68"
|
| 61 |
+
},
|
| 62 |
+
{
|
| 63 |
+
"path": "src/mme_vla_suite/models/representation/phase_a_reader.py",
|
| 64 |
+
"base_sha256": null,
|
| 65 |
+
"target_preimage_sha256": null,
|
| 66 |
+
"overlay_sha256": "1bf7794d8acc8c478b39654894b36d6451669283f261aac41461ea034cfe8ad9"
|
| 67 |
+
},
|
| 68 |
+
{
|
| 69 |
+
"path": "src/mme_vla_suite/models/config/robomme/perceptual-picmem-phase-a-modul.yaml",
|
| 70 |
+
"base_sha256": null,
|
| 71 |
+
"target_preimage_sha256": null,
|
| 72 |
+
"overlay_sha256": "735b2c4f49a7b94c460153a8b72177a07d72dd8b224200a93c7867e8abebe286"
|
| 73 |
+
},
|
| 74 |
+
{
|
| 75 |
+
"path": "scripts/picmem_phase_a_dataset_smoke.py",
|
| 76 |
+
"base_sha256": null,
|
| 77 |
+
"target_preimage_sha256": null,
|
| 78 |
+
"overlay_sha256": "44b3c7e6eb99c322b76f84c121ebc8954b665a84100894049b18bf24a32a3a54"
|
| 79 |
+
},
|
| 80 |
+
{
|
| 81 |
+
"path": "scripts/picmem_phase_a_checkpoint_probe.py",
|
| 82 |
+
"base_sha256": null,
|
| 83 |
+
"target_preimage_sha256": null,
|
| 84 |
+
"overlay_sha256": "bf21aea49ca166db2e2c0fa788725a0bf1a52025594363d56467d3ef665012fe"
|
| 85 |
+
},
|
| 86 |
+
{
|
| 87 |
+
"path": "scripts/picmem_phase_a_full_state_train.py",
|
| 88 |
+
"base_sha256": null,
|
| 89 |
+
"target_preimage_sha256": null,
|
| 90 |
+
"overlay_sha256": "8aea4aa5d8a7540e42003ceceeb5a696a8f78bd8795dbee13ffba825ae764cea"
|
| 91 |
+
},
|
| 92 |
+
{
|
| 93 |
+
"path": "scripts/picmem_phase_a_full_state_smoke.py",
|
| 94 |
+
"base_sha256": null,
|
| 95 |
+
"target_preimage_sha256": null,
|
| 96 |
+
"overlay_sha256": "cd6e16b048b5ff1f11fa358fd571956d57d45ca78a7303dc859eb9943a4b640b"
|
| 97 |
+
},
|
| 98 |
+
{
|
| 99 |
+
"path": "scripts/run_20260731_picmem_phase_a_8gpu.sh",
|
| 100 |
+
"base_sha256": null,
|
| 101 |
+
"target_preimage_sha256": null,
|
| 102 |
+
"overlay_sha256": "b5ef128664eb1c480afb30c5b10678a1dcc5bcdc9d19e6c5c300abfa9b09170b"
|
| 103 |
+
},
|
| 104 |
+
{
|
| 105 |
+
"path": "scripts/run_20260731_picmem_phase_a_h200.sh",
|
| 106 |
+
"base_sha256": null,
|
| 107 |
+
"target_preimage_sha256": null,
|
| 108 |
+
"overlay_sha256": "b2ea492ea5e847270888a33887e560fce82474a70bf6d6ea1ce78321090f394b"
|
| 109 |
+
},
|
| 110 |
+
{
|
| 111 |
+
"path": "src/mme_vla_suite/policies/picmem_phase_a_rollout.py",
|
| 112 |
+
"base_sha256": null,
|
| 113 |
+
"target_preimage_sha256": null,
|
| 114 |
+
"overlay_sha256": "b429681ec30d6bf68d419bfc3ef401362656e543cec6b9d5d38b584ece09d18b"
|
| 115 |
+
},
|
| 116 |
+
{
|
| 117 |
+
"path": "examples/robomme/picmem_phase_a_rollout.py",
|
| 118 |
+
"base_sha256": null,
|
| 119 |
+
"target_preimage_sha256": null,
|
| 120 |
+
"overlay_sha256": "ecc19b94db23699eb4143fab50349c43196e2528bda2cd4724580ef77de48b8e"
|
| 121 |
+
}
|
| 122 |
+
],
|
| 123 |
+
"patches": [
|
| 124 |
+
{
|
| 125 |
+
"path": "patches/phase_a_reader_host.patch",
|
| 126 |
+
"sha256": "eb00053c9db76e980f04a1d243ac2a68785535f05fa0b8034c5dd976236de31c",
|
| 127 |
+
"files": [
|
| 128 |
+
{
|
| 129 |
+
"path": "src/mme_vla_suite/models/integration/history_observation.py",
|
| 130 |
+
"target_preimage_sha256": "e510f75496770d418d770f3e2a56f6ddc9d972a5ff68b6cd14b7a15665ec39a8",
|
| 131 |
+
"patched_sha256": "1823a44a223e648dee481ca0c625d21ac77117cfb70da2ebd118789a515c8087"
|
| 132 |
+
},
|
| 133 |
+
{
|
| 134 |
+
"path": "src/mme_vla_suite/models/integration/history_pi0.py",
|
| 135 |
+
"target_preimage_sha256": "9192bfc229ac1386a3d36835c6d1e220617431d44b462016b062bc3df07a337f",
|
| 136 |
+
"patched_sha256": "2f7a490ac70cddcbaefb721d9ff83d52266adcb61bb01d4691cc739b2824a524"
|
| 137 |
+
},
|
| 138 |
+
{
|
| 139 |
+
"path": "src/mme_vla_suite/models/representation/percep_mem.py",
|
| 140 |
+
"target_preimage_sha256": "39ef28ef3ee30f302b57a306351be9ae6f8cc18100a460d2e61a4f5dd1dc986f",
|
| 141 |
+
"patched_sha256": "a70618d50a65fcd5f50c5bccd11806e8170c0f207fab449252b367c447ed833c"
|
| 142 |
+
},
|
| 143 |
+
{
|
| 144 |
+
"path": "src/mme_vla_suite/policies/robomme_policy.py",
|
| 145 |
+
"target_preimage_sha256": "78dbf3393bac91a16096d02b17239ca0e14c38be7ce32042d88f96b1e89e35e2",
|
| 146 |
+
"patched_sha256": "747a2ed2ebb7dfa83d8dd255c3b77e0367ef5dec82c041e0f1c6427c9103c12b"
|
| 147 |
+
},
|
| 148 |
+
{
|
| 149 |
+
"path": "src/mme_vla_suite/training/config.py",
|
| 150 |
+
"target_preimage_sha256": "47041573dae2c48b99b56035763f4fd611f6cc5395e7875849dd6017227ce247",
|
| 151 |
+
"patched_sha256": "75580e400a350ab6535840ed2a8d99d25767c7955bd1fd2abdadde25399d9097"
|
| 152 |
+
},
|
| 153 |
+
{
|
| 154 |
+
"path": "src/mme_vla_suite/training/dataloader.py",
|
| 155 |
+
"target_preimage_sha256": "48d7c121120bddd98f37733924519eb40c9bd7375e9dc38815f9e68c435e7cb7",
|
| 156 |
+
"patched_sha256": "be402665224b060e4ff762b65e27cb42658b5dfa3b717169a2c9f288d9481139"
|
| 157 |
+
}
|
| 158 |
+
]
|
| 159 |
+
},
|
| 160 |
+
{
|
| 161 |
+
"path": "patches/phase_a_rollout_host.patch",
|
| 162 |
+
"sha256": "859d80ccdaaf297975902182968d6881b45b942a2cea7e40b585180790ec6ca2",
|
| 163 |
+
"files": [
|
| 164 |
+
{
|
| 165 |
+
"path": "examples/robomme/eval.py",
|
| 166 |
+
"target_preimage_sha256": "2b51b942af18f7a3412814b66eca67a0fc4ff374794bceac5f44d87e1e367c41",
|
| 167 |
+
"patched_sha256": "90b846c40da2593d5985c3c22fa915ba7e9f2d104f0463547193a7413e16dd28"
|
| 168 |
+
},
|
| 169 |
+
{
|
| 170 |
+
"path": "src/mme_vla_suite/policies/policy.py",
|
| 171 |
+
"target_preimage_sha256": "dc31fce752172e1861de4840445b6c300dfa2a675a797dedbee1b108f7f4e20d",
|
| 172 |
+
"patched_sha256": "dae90802dcb7e14b2a5de58b636439ad7228a1289462f2e03812d26e89ddae83"
|
| 173 |
+
},
|
| 174 |
+
{
|
| 175 |
+
"path": "src/mme_vla_suite/serving/websocket_policy_server.py",
|
| 176 |
+
"target_preimage_sha256": "7f145fb4633a0f10fc6f545e0104d2c4aeffecfd86689983ce7ddd691f89a107",
|
| 177 |
+
"patched_sha256": "8a8de436fe8a8c8f3664223687f1e3211035d9fee38651eed5774d41e6839c7a"
|
| 178 |
+
}
|
| 179 |
+
]
|
| 180 |
+
}
|
| 181 |
+
]
|
| 182 |
+
}
|
checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/scripts/picmem_phase_a_checkpoint_probe.py
ADDED
|
@@ -0,0 +1,528 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import dataclasses
|
| 8 |
+
import hashlib
|
| 9 |
+
import json
|
| 10 |
+
import os
|
| 11 |
+
import pickle
|
| 12 |
+
import re
|
| 13 |
+
from collections.abc import Mapping
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
from typing import Any
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def require(condition: bool, message: str) -> None:
|
| 21 |
+
if not condition:
|
| 22 |
+
raise RuntimeError(message)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def load_json(path: Path, label: str) -> dict[str, Any]:
|
| 26 |
+
require(path.is_file(), f"missing {label}: {path}")
|
| 27 |
+
value = json.loads(path.read_text(encoding="utf-8"))
|
| 28 |
+
require(isinstance(value, dict), f"{label} must be a JSON object")
|
| 29 |
+
return value
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def scalar_int(value: Any, name: str) -> int:
|
| 33 |
+
value = value.item() if hasattr(value, "item") else value
|
| 34 |
+
require(not isinstance(value, bool) and isinstance(value, int) and value >= 0, f"bad {name}: {value!r}")
|
| 35 |
+
return int(value)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def array_hash(value: Any) -> str:
|
| 39 |
+
array = np.ascontiguousarray(np.asarray(value))
|
| 40 |
+
digest = hashlib.sha256(f"{array.dtype}:{array.shape}".encode())
|
| 41 |
+
digest.update(array.tobytes())
|
| 42 |
+
return digest.hexdigest()
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def byte_exact(left: Any, right: Any) -> bool:
|
| 46 |
+
left_array = np.ascontiguousarray(np.asarray(left))
|
| 47 |
+
right_array = np.ascontiguousarray(np.asarray(right))
|
| 48 |
+
return bool(
|
| 49 |
+
left_array.dtype == right_array.dtype
|
| 50 |
+
and left_array.shape == right_array.shape
|
| 51 |
+
and left_array.tobytes() == right_array.tobytes()
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def observation_hashes(observation: Any, jax: Any) -> dict[str, str | None]:
|
| 56 |
+
result: dict[str, str | None] = {}
|
| 57 |
+
|
| 58 |
+
def visit(name: str, value: Any) -> None:
|
| 59 |
+
if value is None:
|
| 60 |
+
result[name] = None
|
| 61 |
+
elif isinstance(value, Mapping):
|
| 62 |
+
for key in sorted(value):
|
| 63 |
+
visit(f"{name}.{key}", value[key])
|
| 64 |
+
else:
|
| 65 |
+
result[name] = array_hash(jax.device_get(value))
|
| 66 |
+
|
| 67 |
+
for field in dataclasses.fields(observation):
|
| 68 |
+
if field.name != "static_image_emb":
|
| 69 |
+
visit(field.name, getattr(observation, field.name))
|
| 70 |
+
return result
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def load_frame(dataset: Path, episode: int, frame: int, token_per_image: int) -> tuple[Path, np.ndarray]:
|
| 74 |
+
path = dataset / "features" / f"episode_{episode}" / f"token_emb_{frame}.npy"
|
| 75 |
+
require(path.is_file(), f"missing frame feature: {path}")
|
| 76 |
+
payload = np.load(path, allow_pickle=True).item()
|
| 77 |
+
tokens = np.asarray(payload["image_emb_4x4"])
|
| 78 |
+
require(tokens.shape == (1, token_per_image, 2048), f"bad feature shape: {tokens.shape}")
|
| 79 |
+
return path, tokens.reshape(token_per_image, 2048)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def parse_args() -> argparse.Namespace:
|
| 83 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 84 |
+
parser.add_argument("--checkpoint", required=True, type=Path)
|
| 85 |
+
parser.add_argument("--dataset", required=True, type=Path)
|
| 86 |
+
parser.add_argument("--sidecar-dir", required=True, type=Path)
|
| 87 |
+
parser.add_argument("--history-config", required=True, type=Path)
|
| 88 |
+
parser.add_argument("--cohort", required=True, type=Path)
|
| 89 |
+
parser.add_argument("--output", required=True, type=Path)
|
| 90 |
+
parser.add_argument("--subset-manifest", required=True, type=Path)
|
| 91 |
+
parser.add_argument("--subset-manifest-sha256", required=True)
|
| 92 |
+
parser.add_argument("--replacement-manifest", required=True, type=Path)
|
| 93 |
+
parser.add_argument("--replacement-manifest-sha256", required=True)
|
| 94 |
+
parser.add_argument("--best-visible-manifest", required=True, type=Path)
|
| 95 |
+
parser.add_argument("--best-visible-manifest-sha256", required=True)
|
| 96 |
+
args = parser.parse_args()
|
| 97 |
+
for name in (
|
| 98 |
+
"checkpoint",
|
| 99 |
+
"dataset",
|
| 100 |
+
"sidecar_dir",
|
| 101 |
+
"history_config",
|
| 102 |
+
"cohort",
|
| 103 |
+
"output",
|
| 104 |
+
"subset_manifest",
|
| 105 |
+
):
|
| 106 |
+
setattr(args, name, getattr(args, name).expanduser().resolve())
|
| 107 |
+
for name in ("replacement_manifest", "best_visible_manifest"):
|
| 108 |
+
# Preserve the final component so package-root symlinks fail closed.
|
| 109 |
+
setattr(args, name, getattr(args, name).expanduser().absolute())
|
| 110 |
+
for name in (
|
| 111 |
+
"subset_manifest_sha256",
|
| 112 |
+
"replacement_manifest_sha256",
|
| 113 |
+
"best_visible_manifest_sha256",
|
| 114 |
+
):
|
| 115 |
+
require(
|
| 116 |
+
re.fullmatch(r"[0-9a-f]{64}", getattr(args, name)) is not None,
|
| 117 |
+
f"{name} must be a lowercase SHA-256 digest",
|
| 118 |
+
)
|
| 119 |
+
return args
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def main() -> int:
|
| 123 |
+
args = parse_args()
|
| 124 |
+
require(
|
| 125 |
+
args.subset_manifest.is_file() and not args.subset_manifest.is_symlink(),
|
| 126 |
+
f"missing regular subset manifest: {args.subset_manifest}",
|
| 127 |
+
)
|
| 128 |
+
for path in (args.replacement_manifest, args.best_visible_manifest):
|
| 129 |
+
require(
|
| 130 |
+
path.is_dir() and not path.is_symlink(),
|
| 131 |
+
f"missing completed frozen package root: {path}",
|
| 132 |
+
)
|
| 133 |
+
cohort = load_json(args.cohort, "probe cohort")
|
| 134 |
+
require(
|
| 135 |
+
cohort.get("schema_version") == "picmem_phase_a_run084_checkpoint_probe_cohort_v1",
|
| 136 |
+
"unsupported probe cohort schema",
|
| 137 |
+
)
|
| 138 |
+
geometry = cohort["memory_geometry"]
|
| 139 |
+
token_budget = scalar_int(geometry["token_budget"], "token budget")
|
| 140 |
+
token_per_image = scalar_int(geometry["token_per_image"], "token_per_image")
|
| 141 |
+
frame_budget = scalar_int(geometry["frame_capacity"], "frame capacity")
|
| 142 |
+
require((token_budget, token_per_image, frame_budget) == (512, 16, 32), "cohort geometry drift")
|
| 143 |
+
|
| 144 |
+
batch_size = 64
|
| 145 |
+
task = cohort["task"]
|
| 146 |
+
episode = scalar_int(cohort["target"]["episode"], "target episode")
|
| 147 |
+
step = scalar_int(cohort["target"]["step"], "target step")
|
| 148 |
+
cohort_evidence_frame = scalar_int(
|
| 149 |
+
cohort["target"]["evidence_frame"],
|
| 150 |
+
"cohort evidence frame",
|
| 151 |
+
)
|
| 152 |
+
donor_episode = scalar_int(cohort["donor"]["episode"], "donor episode")
|
| 153 |
+
donor_frame = scalar_int(cohort["donor"]["frame"], "donor frame")
|
| 154 |
+
instruction = cohort["instruction"]
|
| 155 |
+
seed = scalar_int(cohort["sampling"]["seed"], "seed")
|
| 156 |
+
noise_seed = scalar_int(cohort["sampling"]["noise_seed"], "noise seed")
|
| 157 |
+
num_steps = scalar_int(cohort["sampling"]["num_steps"], "sampling steps")
|
| 158 |
+
action_tolerance = float(cohort["acceptance"]["action_tolerance"])
|
| 159 |
+
margin = float(cohort["acceptance"]["margin"])
|
| 160 |
+
require(
|
| 161 |
+
num_steps > 0,
|
| 162 |
+
"invalid cohort batch/sampling values",
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
os.environ["PICMEM_PHASE_A_SIDECAR_DIR"] = str(args.sidecar_dir)
|
| 166 |
+
os.environ["PICMEM_PHASE_A_SUBSET_MANIFEST"] = str(args.subset_manifest)
|
| 167 |
+
os.environ["PICMEM_PHASE_A_SUBSET_MANIFEST_SHA256"] = args.subset_manifest_sha256
|
| 168 |
+
os.environ["PICMEM_PHASE_A_REPLACEMENT_MANIFEST"] = str(args.replacement_manifest)
|
| 169 |
+
os.environ["PICMEM_PHASE_A_REPLACEMENT_MANIFEST_SHA256"] = args.replacement_manifest_sha256
|
| 170 |
+
os.environ["PICMEM_PHASE_A_BEST_VISIBLE_MANIFEST"] = str(args.best_visible_manifest)
|
| 171 |
+
os.environ["PICMEM_PHASE_A_BEST_VISIBLE_MANIFEST_SHA256"] = args.best_visible_manifest_sha256
|
| 172 |
+
|
| 173 |
+
import jax
|
| 174 |
+
import jax.numpy as jnp
|
| 175 |
+
import openpi.models.model as openpi_model
|
| 176 |
+
import openpi.shared.nnx_utils as nnx_utils
|
| 177 |
+
from mme_vla_suite.training import config as train_config
|
| 178 |
+
from mme_vla_suite.training.dataloader import create_data_loader
|
| 179 |
+
from mme_vla_suite.training.picmem_phase_a import load_episode_sidecar, selected_frame_read
|
| 180 |
+
from omegaconf import OmegaConf
|
| 181 |
+
|
| 182 |
+
from picmem.memory.causal import paired_action_effect
|
| 183 |
+
from picmem.provenance.frozen_reader import FrozenSelectionReader
|
| 184 |
+
from picmem.provenance.run084 import replay_sidecar
|
| 185 |
+
from picmem.sampling.run084_sampler import Run084TaskBalancedSampler
|
| 186 |
+
|
| 187 |
+
reader = FrozenSelectionReader.load_formal(
|
| 188 |
+
subset_manifest_path=args.subset_manifest,
|
| 189 |
+
subset_manifest_sha256=args.subset_manifest_sha256,
|
| 190 |
+
replacement_manifest_path=args.replacement_manifest,
|
| 191 |
+
replacement_manifest_sha256=args.replacement_manifest_sha256,
|
| 192 |
+
best_visible_manifest_path=args.best_visible_manifest,
|
| 193 |
+
best_visible_manifest_sha256=args.best_visible_manifest_sha256,
|
| 194 |
+
)
|
| 195 |
+
candidates = tuple(
|
| 196 |
+
row
|
| 197 |
+
for row in reader.subset.records
|
| 198 |
+
if (
|
| 199 |
+
row.task_id,
|
| 200 |
+
row.global_episode_id,
|
| 201 |
+
row.step_idx,
|
| 202 |
+
row.instruction,
|
| 203 |
+
)
|
| 204 |
+
== (task, episode, step, instruction)
|
| 205 |
+
)
|
| 206 |
+
require(
|
| 207 |
+
len(candidates) == 1,
|
| 208 |
+
f"cohort must resolve exactly one corrected sample identity, got {len(candidates)}",
|
| 209 |
+
)
|
| 210 |
+
frozen_row = candidates[0]
|
| 211 |
+
dataset_index = frozen_row.new_sample_idx
|
| 212 |
+
loader_seed = int(reader.replacements.seed)
|
| 213 |
+
locator = Run084TaskBalancedSampler(
|
| 214 |
+
reader.subset,
|
| 215 |
+
batch_size=batch_size,
|
| 216 |
+
seed=loader_seed,
|
| 217 |
+
auto_advance=False,
|
| 218 |
+
)
|
| 219 |
+
sampler_epoch, batch_cursor, batch_row = locator.locate_sample_identity(
|
| 220 |
+
frozen_row.sample_identity_sha256
|
| 221 |
+
)
|
| 222 |
+
locator.set_position(epoch=sampler_epoch, batch_cursor=batch_cursor)
|
| 223 |
+
sampler_state = locator.state_dict()
|
| 224 |
+
require(
|
| 225 |
+
locator.next_batch_indices()[batch_row] == dataset_index
|
| 226 |
+
and locator.next_batch_sample_ids()[batch_row] == frozen_row.sample_identity_sha256,
|
| 227 |
+
"sampler locator did not bind the exact corrected sample identity",
|
| 228 |
+
)
|
| 229 |
+
|
| 230 |
+
params_dir = args.checkpoint / "params"
|
| 231 |
+
assets_dir = args.checkpoint / "assets"
|
| 232 |
+
norm_stats = assets_dir / "robomme" / "norm_stats.json"
|
| 233 |
+
raw_path = args.dataset / "data" / f"{dataset_index}.pkl"
|
| 234 |
+
for path in (params_dir, norm_stats, raw_path, args.history_config):
|
| 235 |
+
require(path.exists(), f"missing probe input: {path}")
|
| 236 |
+
|
| 237 |
+
with raw_path.open("rb") as stream:
|
| 238 |
+
raw = pickle.load(stream)
|
| 239 |
+
raw_episode = scalar_int(raw.get("epis_idx"), "raw episode")
|
| 240 |
+
raw_step = scalar_int(raw.get("step_idx"), "raw step")
|
| 241 |
+
raw_exec_start = scalar_int(raw.get("exec_start_idx"), "raw exec start")
|
| 242 |
+
require((raw_episode, raw_step, raw.get("prompt")) == (episode, step, instruction), "cohort row drift")
|
| 243 |
+
reader.subset.validate_raw_sample(dataset_index, raw)
|
| 244 |
+
|
| 245 |
+
target_sidecar_path, _ = load_episode_sidecar(
|
| 246 |
+
args.sidecar_dir,
|
| 247 |
+
episode_id=episode,
|
| 248 |
+
instruction=instruction,
|
| 249 |
+
)
|
| 250 |
+
read = selected_frame_read(
|
| 251 |
+
args.sidecar_dir,
|
| 252 |
+
episode_id=episode,
|
| 253 |
+
step=step,
|
| 254 |
+
raw_exec_start=raw_exec_start,
|
| 255 |
+
instruction=instruction,
|
| 256 |
+
frame_budget=frame_budget,
|
| 257 |
+
recent_anchor_count=4,
|
| 258 |
+
expected_task_id=frozen_row.task_id,
|
| 259 |
+
expected_sidecar_sha256=frozen_row.sidecar_sha256,
|
| 260 |
+
)
|
| 261 |
+
replacement = reader.record_for(frozen_row, current_step=step)
|
| 262 |
+
|
| 263 |
+
donor_sidecar_path, donor_sidecar = load_episode_sidecar(
|
| 264 |
+
args.sidecar_dir,
|
| 265 |
+
episode_id=donor_episode,
|
| 266 |
+
instruction=instruction,
|
| 267 |
+
)
|
| 268 |
+
donor_exec_start = scalar_int(donor_sidecar.get("exec_start_step"), "donor exec start")
|
| 269 |
+
donor_read = replay_sidecar(
|
| 270 |
+
donor_sidecar,
|
| 271 |
+
donor_exec_start,
|
| 272 |
+
budget=frame_budget,
|
| 273 |
+
recent=4,
|
| 274 |
+
)
|
| 275 |
+
require(donor_read.contract_id == read.contract_id, "donor contract mismatch")
|
| 276 |
+
require(donor_frame in donor_read.valid_indices(), "donor frame is not retained evidence")
|
| 277 |
+
require(donor_read.value != read.value, "donor and target memory values are equal")
|
| 278 |
+
|
| 279 |
+
history = OmegaConf.load(args.history_config)
|
| 280 |
+
require(
|
| 281 |
+
(
|
| 282 |
+
str(history.representation_type),
|
| 283 |
+
str(history.perceptual_memory.type),
|
| 284 |
+
str(history.perceptual_memory.frame_selection.type),
|
| 285 |
+
int(history.budget),
|
| 286 |
+
int(history.token_per_image),
|
| 287 |
+
int(history.num_views),
|
| 288 |
+
int(history.streaming_obs_horizon),
|
| 289 |
+
str(history.pool_type),
|
| 290 |
+
bool(history.use_pos_emb),
|
| 291 |
+
bool(history.use_state_emb),
|
| 292 |
+
str(history.memory_feature.img.net),
|
| 293 |
+
int(history.memory_feature.img.input_dim),
|
| 294 |
+
int(history.memory_feature.pos.input_dim),
|
| 295 |
+
int(history.memory_feature.pos.hidden_dim),
|
| 296 |
+
int(history.memory_feature.state.input_dim),
|
| 297 |
+
int(history.memory_feature.state.hidden_dim),
|
| 298 |
+
str(history.integration_type),
|
| 299 |
+
int(history.memory_token_dim),
|
| 300 |
+
int(history.perceptual_memory.frame_selection.frame_budget),
|
| 301 |
+
int(history.perceptual_memory.frame_selection.recent_anchor_count),
|
| 302 |
+
str(history.perceptual_memory.frame_selection.selection_mode),
|
| 303 |
+
str(history.perceptual_memory.frame_selection.metadata_mode),
|
| 304 |
+
str(history.perceptual_memory.frame_selection.reader_mode),
|
| 305 |
+
str(history.perceptual_memory.frame_selection.manager_mode),
|
| 306 |
+
)
|
| 307 |
+
== (
|
| 308 |
+
"perceptual",
|
| 309 |
+
"frame_sampling",
|
| 310 |
+
"picmem_phase_a",
|
| 311 |
+
token_budget,
|
| 312 |
+
token_per_image,
|
| 313 |
+
1,
|
| 314 |
+
16,
|
| 315 |
+
"mean",
|
| 316 |
+
True,
|
| 317 |
+
False,
|
| 318 |
+
"identity",
|
| 319 |
+
2048,
|
| 320 |
+
768,
|
| 321 |
+
768,
|
| 322 |
+
8,
|
| 323 |
+
512,
|
| 324 |
+
"modulation",
|
| 325 |
+
1024,
|
| 326 |
+
frame_budget,
|
| 327 |
+
4,
|
| 328 |
+
"relevant",
|
| 329 |
+
"correct",
|
| 330 |
+
"fixed16",
|
| 331 |
+
"full_evolving",
|
| 332 |
+
),
|
| 333 |
+
"history config drift",
|
| 334 |
+
)
|
| 335 |
+
read = reader.render(
|
| 336 |
+
read,
|
| 337 |
+
replacement,
|
| 338 |
+
str(history.perceptual_memory.frame_selection.selection_mode),
|
| 339 |
+
)
|
| 340 |
+
selected_frames = tuple(read.valid_indices())
|
| 341 |
+
evidence_slots = tuple(read.evidence_slots)
|
| 342 |
+
require(
|
| 343 |
+
len(evidence_slots) == 1,
|
| 344 |
+
f"the pinned relevant checkpoint cohort requires one evidence slot, got {evidence_slots}",
|
| 345 |
+
)
|
| 346 |
+
evidence_slot = evidence_slots[0]
|
| 347 |
+
evidence_frame = int(read.frame_indices[evidence_slot])
|
| 348 |
+
require(
|
| 349 |
+
evidence_frame == cohort_evidence_frame,
|
| 350 |
+
"frozen relevant manifest changed the pinned semantic evidence frame",
|
| 351 |
+
)
|
| 352 |
+
|
| 353 |
+
target_feature, target_tokens = load_frame(
|
| 354 |
+
args.dataset,
|
| 355 |
+
episode,
|
| 356 |
+
evidence_frame,
|
| 357 |
+
token_per_image,
|
| 358 |
+
)
|
| 359 |
+
donor_feature, donor_tokens = load_frame(
|
| 360 |
+
args.dataset,
|
| 361 |
+
donor_episode,
|
| 362 |
+
donor_frame,
|
| 363 |
+
token_per_image,
|
| 364 |
+
)
|
| 365 |
+
require(target_tokens.dtype == donor_tokens.dtype, "target/donor feature dtype mismatch")
|
| 366 |
+
require(not np.array_equal(target_tokens, donor_tokens), "target/donor visual evidence is identical")
|
| 367 |
+
|
| 368 |
+
base = train_config.get_config("mme_vla_suite")
|
| 369 |
+
data_factory = dataclasses.replace(
|
| 370 |
+
base.data,
|
| 371 |
+
assets=dataclasses.replace(base.data.assets, assets_dir=str(assets_dir)),
|
| 372 |
+
)
|
| 373 |
+
config = dataclasses.replace(
|
| 374 |
+
base,
|
| 375 |
+
exp_name="picmem_phase_a_checkpoint_probe",
|
| 376 |
+
model=dataclasses.replace(base.model, history_config=history),
|
| 377 |
+
data=data_factory,
|
| 378 |
+
dataset_path=str(args.dataset),
|
| 379 |
+
batch_size=batch_size,
|
| 380 |
+
num_workers=0,
|
| 381 |
+
seed=seed,
|
| 382 |
+
sampler_seed=loader_seed,
|
| 383 |
+
wandb_enabled=False,
|
| 384 |
+
)
|
| 385 |
+
data_config = config.data.create(config.assets_dirs, config.model)
|
| 386 |
+
require(data_config.norm_stats is not None, "checkpoint norm stats were not loaded")
|
| 387 |
+
loader = create_data_loader(
|
| 388 |
+
config.dataset_path,
|
| 389 |
+
data_config,
|
| 390 |
+
history_config=history,
|
| 391 |
+
action_horizon=config.model.action_horizon,
|
| 392 |
+
batch_size=batch_size,
|
| 393 |
+
shuffle=False,
|
| 394 |
+
num_batches=1,
|
| 395 |
+
num_workers=0,
|
| 396 |
+
seed=loader_seed,
|
| 397 |
+
sampler_epoch=sampler_epoch,
|
| 398 |
+
)
|
| 399 |
+
loader.load_sampler_state_dict(sampler_state)
|
| 400 |
+
require(
|
| 401 |
+
loader.sampler_state_dict()["next_sample_ids"] == sampler_state["next_sample_ids"],
|
| 402 |
+
"host loader changed the restored next sample identities",
|
| 403 |
+
)
|
| 404 |
+
observation, targets = next(iter(loader))
|
| 405 |
+
require(observation is not None and targets is not None, "cohort batch is unavailable")
|
| 406 |
+
require(int(config.model.action_horizon) == 20, "action horizon drift")
|
| 407 |
+
require(int(config.model.action_dim) == 32, "action dimension drift")
|
| 408 |
+
require(tuple(targets.shape) == (batch_size, 20, 32), "action target shape drift")
|
| 409 |
+
require(tuple(observation.static_image_emb.shape) == (batch_size, token_budget, 2048), "memory shape drift")
|
| 410 |
+
require(tuple(observation.static_mask.shape) == (batch_size, token_budget), "memory mask shape drift")
|
| 411 |
+
|
| 412 |
+
correct_static = np.array(jax.device_get(observation.static_image_emb), copy=True)
|
| 413 |
+
correct_mask = np.array(jax.device_get(observation.static_mask), copy=True)
|
| 414 |
+
selected = correct_static[batch_row].reshape(frame_budget, token_per_image, 2048)
|
| 415 |
+
frame_mask = correct_mask[batch_row].reshape(frame_budget, token_per_image)
|
| 416 |
+
require(np.all(frame_mask == frame_mask[:, :1]), "one frame has a partial token mask")
|
| 417 |
+
require(np.array_equal(frame_mask[:, 0], np.asarray(read.valid_mask)), "loader/Read mask mismatch")
|
| 418 |
+
require(np.array_equal(selected[evidence_slot], target_tokens), "loader/Read evidence mismatch")
|
| 419 |
+
shared_hashes = observation_hashes(observation, jax)
|
| 420 |
+
|
| 421 |
+
params = openpi_model.restore_params(params_dir, dtype=jnp.bfloat16)
|
| 422 |
+
model = config.model.load(params)
|
| 423 |
+
model.eval()
|
| 424 |
+
sample_actions = nnx_utils.module_jit(model.sample_actions)
|
| 425 |
+
noise = jax.random.normal(jax.random.key(noise_seed), tuple(targets.shape))
|
| 426 |
+
full_actions: list[np.ndarray] = []
|
| 427 |
+
|
| 428 |
+
def policy(request: Mapping[str, Any], policy_seed: int) -> np.ndarray:
|
| 429 |
+
visual = np.asarray(request["memory_visual"])
|
| 430 |
+
mask = np.asarray(request["memory_mask"])
|
| 431 |
+
require(visual.shape == (frame_budget, token_per_image, 2048), "probe visual shape drift")
|
| 432 |
+
require(mask.shape == (frame_budget,) and mask.dtype == np.bool_, "probe frame mask drift")
|
| 433 |
+
require(
|
| 434 |
+
np.array_equal(np.repeat(mask, token_per_image), correct_mask[batch_row]),
|
| 435 |
+
"probe attempted to change the memory mask",
|
| 436 |
+
)
|
| 437 |
+
static = correct_static.copy()
|
| 438 |
+
static[batch_row] = visual.reshape(token_budget, 2048)
|
| 439 |
+
arm = observation.replace(static_image_emb=jnp.asarray(static))
|
| 440 |
+
require(shared_hashes == observation_hashes(arm, jax), "a non-memory observation field changed")
|
| 441 |
+
actions = sample_actions(
|
| 442 |
+
jax.random.key(policy_seed),
|
| 443 |
+
arm,
|
| 444 |
+
num_steps=num_steps,
|
| 445 |
+
noise=noise,
|
| 446 |
+
)
|
| 447 |
+
actions.block_until_ready()
|
| 448 |
+
full_actions.append(np.array(jax.device_get(actions), copy=True))
|
| 449 |
+
return np.array(full_actions[-1][batch_row], dtype=np.float64, copy=True)
|
| 450 |
+
|
| 451 |
+
effect = paired_action_effect(
|
| 452 |
+
policy,
|
| 453 |
+
observation={},
|
| 454 |
+
read=read,
|
| 455 |
+
selected_visual=selected,
|
| 456 |
+
counterfactual_evidence=donor_tokens[None],
|
| 457 |
+
ground_truth_actions=np.asarray(jax.device_get(targets[batch_row])),
|
| 458 |
+
seed=seed,
|
| 459 |
+
margin=margin,
|
| 460 |
+
action_tolerance=action_tolerance,
|
| 461 |
+
)
|
| 462 |
+
require(len(full_actions) == 2, f"paired probe made {len(full_actions)} full-batch policy calls")
|
| 463 |
+
unaffected_rows = tuple(row for row in range(batch_size) if row != batch_row)
|
| 464 |
+
unaffected_rows_byte_exact = all(
|
| 465 |
+
byte_exact(full_actions[0][row], full_actions[1][row]) for row in unaffected_rows
|
| 466 |
+
)
|
| 467 |
+
mse_delta = effect.action_mse_delta
|
| 468 |
+
passed = bool(
|
| 469 |
+
effect.applicable
|
| 470 |
+
and effect.input_changed
|
| 471 |
+
and effect.action_changed
|
| 472 |
+
and effect.policy_calls == 2
|
| 473 |
+
and effect.changed_slots == (evidence_slot,)
|
| 474 |
+
and unaffected_rows_byte_exact
|
| 475 |
+
and mse_delta is not None
|
| 476 |
+
and mse_delta > 0.0
|
| 477 |
+
)
|
| 478 |
+
report = {
|
| 479 |
+
"schema_version": "picmem_phase_a_checkpoint_probe_v2",
|
| 480 |
+
"status": "PASS" if passed else "FAIL",
|
| 481 |
+
"passed": passed,
|
| 482 |
+
"checkpoint": str(args.checkpoint),
|
| 483 |
+
"checkpoint_assets": str(assets_dir),
|
| 484 |
+
"cohort": str(args.cohort),
|
| 485 |
+
"dataset_index": dataset_index,
|
| 486 |
+
"target_sidecar": str(target_sidecar_path),
|
| 487 |
+
"donor_sidecar": str(donor_sidecar_path),
|
| 488 |
+
"target_feature": str(target_feature),
|
| 489 |
+
"donor_feature": str(donor_feature),
|
| 490 |
+
"changed_slots": list(effect.changed_slots),
|
| 491 |
+
"selected_frames": list(selected_frames),
|
| 492 |
+
"sample_identity_sha256": frozen_row.sample_identity_sha256,
|
| 493 |
+
"replacement_record_sha256": replacement.sha256,
|
| 494 |
+
"action_changed": effect.action_changed,
|
| 495 |
+
"action_l2": effect.action_l2,
|
| 496 |
+
"intervened_batch_row": batch_row,
|
| 497 |
+
"unaffected_rows": list(unaffected_rows),
|
| 498 |
+
"unaffected_rows_byte_exact": unaffected_rows_byte_exact,
|
| 499 |
+
"correct_action_mse": effect.correct_action_mse,
|
| 500 |
+
"negative_action_mse": effect.negative_action_mse,
|
| 501 |
+
"negative_minus_correct_mse": mse_delta,
|
| 502 |
+
"margin": margin,
|
| 503 |
+
"margin_loss": effect.margin_loss,
|
| 504 |
+
"target_visual_sha256": array_hash(target_tokens),
|
| 505 |
+
"donor_visual_sha256": array_hash(donor_tokens),
|
| 506 |
+
"action_sha256": list(effect.action_sha256 or ()),
|
| 507 |
+
"full_batch_action_sha256": [array_hash(value) for value in full_actions],
|
| 508 |
+
"noise_sha256": array_hash(jax.device_get(noise)),
|
| 509 |
+
"sampling": {
|
| 510 |
+
"policy_seed": seed,
|
| 511 |
+
"noise_seed": noise_seed,
|
| 512 |
+
"loader_seed": loader_seed,
|
| 513 |
+
"sampler_epoch": sampler_epoch,
|
| 514 |
+
"batch_cursor": batch_cursor,
|
| 515 |
+
"batch_row": batch_row,
|
| 516 |
+
"next_sample_ids": sampler_state["next_sample_ids"],
|
| 517 |
+
"diffusion_steps": num_steps,
|
| 518 |
+
},
|
| 519 |
+
"shared_observation_field_hashes": shared_hashes,
|
| 520 |
+
}
|
| 521 |
+
args.output.parent.mkdir(parents=True, exist_ok=True)
|
| 522 |
+
args.output.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
| 523 |
+
print(json.dumps(report, sort_keys=True))
|
| 524 |
+
return 0 if passed else 3
|
| 525 |
+
|
| 526 |
+
|
| 527 |
+
if __name__ == "__main__":
|
| 528 |
+
raise SystemExit(main())
|
checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/scripts/picmem_phase_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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""CPU smoke for the real RoboMME Phase-A dataset/config contract."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import hashlib
|
| 8 |
+
import json
|
| 9 |
+
import os
|
| 10 |
+
import re
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from types import SimpleNamespace
|
| 13 |
+
from typing import Any
|
| 14 |
+
|
| 15 |
+
TOKEN_BUDGET = 512
|
| 16 |
+
TOKEN_PER_IMAGE = 16
|
| 17 |
+
FRAME_BUDGET = 32
|
| 18 |
+
NEUTRAL_HOST_FIELDS = (
|
| 19 |
+
"picmem_token_features",
|
| 20 |
+
"picmem_token_mask",
|
| 21 |
+
"picmem_typed_role_ids",
|
| 22 |
+
"picmem_typed_categorical_ids",
|
| 23 |
+
"picmem_typed_numeric_values",
|
| 24 |
+
"picmem_typed_numeric_mask",
|
| 25 |
+
"picmem_typed_age_confidence",
|
| 26 |
+
"picmem_typed_contract_indices",
|
| 27 |
+
"picmem_typed_token_mask",
|
| 28 |
+
"_picmem_typed_task_index",
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def require(condition: bool, message: str) -> None:
|
| 33 |
+
if not condition:
|
| 34 |
+
raise RuntimeError(message)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def scalar_int(value: Any, name: str) -> int:
|
| 38 |
+
value = value.item() if hasattr(value, "item") else value
|
| 39 |
+
require(not isinstance(value, bool) and isinstance(value, int) and value >= 0, f"bad {name}: {value!r}")
|
| 40 |
+
return int(value)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def load_object(path: Path, label: str) -> dict[str, Any]:
|
| 44 |
+
require(path.is_file(), f"missing {label}: {path}")
|
| 45 |
+
|
| 46 |
+
def reject_duplicates(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
| 47 |
+
value: dict[str, Any] = {}
|
| 48 |
+
for key, item in pairs:
|
| 49 |
+
require(key not in value, f"duplicate {label} key: {key}")
|
| 50 |
+
value[key] = item
|
| 51 |
+
return value
|
| 52 |
+
|
| 53 |
+
value = json.loads(path.read_text(encoding="utf-8"), object_pairs_hook=reject_duplicates)
|
| 54 |
+
require(isinstance(value, dict), f"{label} must be a JSON object: {path}")
|
| 55 |
+
return value
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def fake_data_config(np: Any) -> Any:
|
| 59 |
+
def stats(dim: int) -> Any:
|
| 60 |
+
return SimpleNamespace(
|
| 61 |
+
mean=np.zeros(dim, dtype=np.float32),
|
| 62 |
+
std=np.ones(dim, dtype=np.float32),
|
| 63 |
+
q01=-np.ones(dim, dtype=np.float32),
|
| 64 |
+
q99=np.ones(dim, dtype=np.float32),
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
return SimpleNamespace(
|
| 68 |
+
norm_stats={"state": stats(8), "actions": stats(32)},
|
| 69 |
+
use_quantile_norm=False,
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def parse_args() -> argparse.Namespace:
|
| 74 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 75 |
+
parser.add_argument("--dataset", required=True, type=Path)
|
| 76 |
+
parser.add_argument("--sidecar-dir", required=True, type=Path)
|
| 77 |
+
parser.add_argument("--config", required=True, type=Path)
|
| 78 |
+
parser.add_argument("--cohort", required=True, type=Path)
|
| 79 |
+
parser.add_argument("--subset-manifest", required=True, type=Path)
|
| 80 |
+
parser.add_argument("--subset-manifest-sha256", required=True)
|
| 81 |
+
parser.add_argument("--replacement-manifest", required=True, type=Path)
|
| 82 |
+
parser.add_argument("--replacement-manifest-sha256", required=True)
|
| 83 |
+
parser.add_argument("--best-visible-manifest", required=True, type=Path)
|
| 84 |
+
parser.add_argument("--best-visible-manifest-sha256", required=True)
|
| 85 |
+
parser.add_argument("--arm-manifest", type=Path)
|
| 86 |
+
parser.add_argument("--arm-manifest-sha256")
|
| 87 |
+
parser.add_argument("--calibration-manifest", type=Path)
|
| 88 |
+
parser.add_argument("--calibration-manifest-sha256")
|
| 89 |
+
args = parser.parse_args()
|
| 90 |
+
for name in (
|
| 91 |
+
"dataset",
|
| 92 |
+
"sidecar_dir",
|
| 93 |
+
"config",
|
| 94 |
+
"cohort",
|
| 95 |
+
"subset_manifest",
|
| 96 |
+
):
|
| 97 |
+
setattr(args, name, getattr(args, name).expanduser().resolve())
|
| 98 |
+
for name in ("replacement_manifest", "best_visible_manifest"):
|
| 99 |
+
# Preserve the final component so package-root symlinks fail closed.
|
| 100 |
+
setattr(args, name, getattr(args, name).expanduser().absolute())
|
| 101 |
+
for name in ("arm_manifest", "calibration_manifest"):
|
| 102 |
+
value = getattr(args, name)
|
| 103 |
+
if value is not None:
|
| 104 |
+
# Preserve the final component so a manifest symlink cannot be
|
| 105 |
+
# hidden by Path.resolve() before the trust-boundary check.
|
| 106 |
+
setattr(args, name, value.expanduser().absolute())
|
| 107 |
+
for name in (
|
| 108 |
+
"subset_manifest_sha256",
|
| 109 |
+
"replacement_manifest_sha256",
|
| 110 |
+
"best_visible_manifest_sha256",
|
| 111 |
+
"arm_manifest_sha256",
|
| 112 |
+
"calibration_manifest_sha256",
|
| 113 |
+
):
|
| 114 |
+
if getattr(args, name) is None:
|
| 115 |
+
continue
|
| 116 |
+
require(
|
| 117 |
+
re.fullmatch(r"[0-9a-f]{64}", getattr(args, name)) is not None,
|
| 118 |
+
f"{name} must be a lowercase SHA-256 digest",
|
| 119 |
+
)
|
| 120 |
+
return args
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def main() -> int:
|
| 124 |
+
args = parse_args()
|
| 125 |
+
require(args.dataset.is_dir(), f"missing dataset: {args.dataset}")
|
| 126 |
+
require(args.sidecar_dir.is_dir(), f"missing sidecar directory: {args.sidecar_dir}")
|
| 127 |
+
require(
|
| 128 |
+
args.subset_manifest.is_file() and not args.subset_manifest.is_symlink(),
|
| 129 |
+
f"missing regular subset manifest: {args.subset_manifest}",
|
| 130 |
+
)
|
| 131 |
+
for path in (args.replacement_manifest, args.best_visible_manifest):
|
| 132 |
+
require(
|
| 133 |
+
path.is_dir() and not path.is_symlink(),
|
| 134 |
+
f"missing completed frozen package root: {path}",
|
| 135 |
+
)
|
| 136 |
+
cohort = load_object(args.cohort, "checkpoint cohort")
|
| 137 |
+
require(
|
| 138 |
+
cohort.get("schema_version") == "picmem_phase_a_run084_checkpoint_probe_cohort_v1",
|
| 139 |
+
"unsupported checkpoint cohort schema",
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
os.environ["PICMEM_PHASE_A_SIDECAR_DIR"] = str(args.sidecar_dir)
|
| 143 |
+
os.environ["PICMEM_PHASE_A_SUBSET_MANIFEST"] = str(args.subset_manifest)
|
| 144 |
+
os.environ["PICMEM_PHASE_A_SUBSET_MANIFEST_SHA256"] = args.subset_manifest_sha256
|
| 145 |
+
os.environ["PICMEM_PHASE_A_REPLACEMENT_MANIFEST"] = str(args.replacement_manifest)
|
| 146 |
+
os.environ["PICMEM_PHASE_A_REPLACEMENT_MANIFEST_SHA256"] = args.replacement_manifest_sha256
|
| 147 |
+
os.environ["PICMEM_PHASE_A_BEST_VISIBLE_MANIFEST"] = str(args.best_visible_manifest)
|
| 148 |
+
os.environ["PICMEM_PHASE_A_BEST_VISIBLE_MANIFEST_SHA256"] = args.best_visible_manifest_sha256
|
| 149 |
+
|
| 150 |
+
import numpy as np
|
| 151 |
+
from mme_vla_suite.training.dataset import RoboMMEDataset
|
| 152 |
+
from mme_vla_suite.training.picmem_phase_a import (
|
| 153 |
+
MemoryInvariantError,
|
| 154 |
+
load_episode_sidecar,
|
| 155 |
+
selected_frame_read,
|
| 156 |
+
)
|
| 157 |
+
from mme_vla_suite.training.picmem_phase_a_reader import (
|
| 158 |
+
OBSERVATION_FIELDS,
|
| 159 |
+
PhaseATokenMetadata,
|
| 160 |
+
materialize_phase_a_read,
|
| 161 |
+
)
|
| 162 |
+
from omegaconf import OmegaConf
|
| 163 |
+
|
| 164 |
+
from picmem.memory.contracts import ArmManifest
|
| 165 |
+
from picmem.ops.calibration_manifest import load_calibration_manifest
|
| 166 |
+
from picmem.provenance.manifest_builder import iter_formal_read_requirements
|
| 167 |
+
|
| 168 |
+
history = OmegaConf.load(args.config)
|
| 169 |
+
geometry = cohort.get("memory_geometry", {})
|
| 170 |
+
require(str(history.representation_type) == "perceptual", "Phase-A must use perceptual memory")
|
| 171 |
+
require(str(history.perceptual_memory.type) == "frame_sampling", "Phase-A must retain frame_sampling")
|
| 172 |
+
selection = history.perceptual_memory.frame_selection
|
| 173 |
+
require(str(selection.type) == "picmem_phase_a", "wrong Phase-A frame selector")
|
| 174 |
+
require(bool(selection.require_explicit_factors), "formal Phase-A factors must be explicit")
|
| 175 |
+
actual_factors = (
|
| 176 |
+
str(selection.selection_mode),
|
| 177 |
+
str(selection.metadata_mode),
|
| 178 |
+
str(selection.reader_mode),
|
| 179 |
+
str(selection.manager_mode),
|
| 180 |
+
)
|
| 181 |
+
launch_kind = os.environ.get("PICMEM_PHASE_A_LAUNCH_KIND", "")
|
| 182 |
+
training_manifest_kind = os.environ.get("PICMEM_TRAINING_MANIFEST_KIND", "")
|
| 183 |
+
arm_pair = (args.arm_manifest is not None, args.arm_manifest_sha256 is not None)
|
| 184 |
+
calibration_pair = (
|
| 185 |
+
args.calibration_manifest is not None,
|
| 186 |
+
args.calibration_manifest_sha256 is not None,
|
| 187 |
+
)
|
| 188 |
+
require(arm_pair[0] == arm_pair[1], "arm manifest path/hash must be supplied together")
|
| 189 |
+
require(
|
| 190 |
+
calibration_pair[0] == calibration_pair[1],
|
| 191 |
+
"calibration manifest path/hash must be supplied together",
|
| 192 |
+
)
|
| 193 |
+
if launch_kind in {"formal", "sku_smoke"}:
|
| 194 |
+
require(
|
| 195 |
+
arm_pair[0] != calibration_pair[0],
|
| 196 |
+
"formal/sku-smoke dataset validation requires exactly one training manifest path/hash",
|
| 197 |
+
)
|
| 198 |
+
expected_kind = "arm_v3" if launch_kind == "formal" else "sku_calibration_v1"
|
| 199 |
+
require(
|
| 200 |
+
training_manifest_kind == expected_kind,
|
| 201 |
+
"training manifest kind disagrees with the Phase-A launch kind",
|
| 202 |
+
)
|
| 203 |
+
else:
|
| 204 |
+
require(
|
| 205 |
+
not arm_pair[0] and not calibration_pair[0] and not training_manifest_kind,
|
| 206 |
+
"non-training dataset smoke cannot carry a training manifest",
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
training_manifest_id = "diagnostic-smoke"
|
| 210 |
+
training_manifest_sha256 = ""
|
| 211 |
+
expected_global_batch = None
|
| 212 |
+
if training_manifest_kind == "arm_v3":
|
| 213 |
+
require(arm_pair[0] and not calibration_pair[0], "arm_v3 requires only the arm manifest path/hash")
|
| 214 |
+
assert args.arm_manifest is not None and args.arm_manifest_sha256 is not None
|
| 215 |
+
require(
|
| 216 |
+
args.arm_manifest.is_file() and not args.arm_manifest.is_symlink(),
|
| 217 |
+
f"missing regular arm manifest: {args.arm_manifest}",
|
| 218 |
+
)
|
| 219 |
+
require(
|
| 220 |
+
hashlib.sha256(args.arm_manifest.read_bytes()).hexdigest() == args.arm_manifest_sha256,
|
| 221 |
+
"arm manifest content hash drift",
|
| 222 |
+
)
|
| 223 |
+
arm = ArmManifest.from_mapping(load_object(args.arm_manifest, "arm manifest"))
|
| 224 |
+
training_manifest_id = arm.arm_id
|
| 225 |
+
training_manifest_sha256 = args.arm_manifest_sha256
|
| 226 |
+
expected_factors = (
|
| 227 |
+
arm.selection_mode.value,
|
| 228 |
+
arm.metadata_mode.value,
|
| 229 |
+
arm.reader_mode.value,
|
| 230 |
+
arm.manager_mode.value,
|
| 231 |
+
)
|
| 232 |
+
require(arm.global_batch == 64 and arm.gpu_count == 8, "arm launch geometry drift")
|
| 233 |
+
expected_global_batch = arm.global_batch
|
| 234 |
+
elif training_manifest_kind == "sku_calibration_v1":
|
| 235 |
+
require(
|
| 236 |
+
calibration_pair[0] and not arm_pair[0],
|
| 237 |
+
"sku_calibration_v1 requires only the calibration manifest path/hash",
|
| 238 |
+
)
|
| 239 |
+
assert args.calibration_manifest is not None and args.calibration_manifest_sha256 is not None
|
| 240 |
+
require(
|
| 241 |
+
args.calibration_manifest.is_file() and not args.calibration_manifest.is_symlink(),
|
| 242 |
+
f"missing regular calibration manifest: {args.calibration_manifest}",
|
| 243 |
+
)
|
| 244 |
+
calibration = load_calibration_manifest(
|
| 245 |
+
args.calibration_manifest,
|
| 246 |
+
expected_sha256=args.calibration_manifest_sha256,
|
| 247 |
+
).manifest
|
| 248 |
+
training_manifest_id = calibration.calibration_id
|
| 249 |
+
training_manifest_sha256 = args.calibration_manifest_sha256
|
| 250 |
+
expected_factors = (
|
| 251 |
+
calibration.factors.selection_mode.value,
|
| 252 |
+
calibration.factors.metadata_mode.value,
|
| 253 |
+
calibration.factors.reader_mode.value,
|
| 254 |
+
calibration.factors.manager_mode.value,
|
| 255 |
+
)
|
| 256 |
+
require(
|
| 257 |
+
calibration.runtime.gpu_count == 8
|
| 258 |
+
and calibration.runtime.world_size == 8
|
| 259 |
+
and calibration.sample_order.global_batch == calibration.runtime.global_batch,
|
| 260 |
+
"calibration launch geometry drift",
|
| 261 |
+
)
|
| 262 |
+
require(
|
| 263 |
+
calibration.lineage.artifact_schema_version == "picmem_run084_artifact_hashes_v2"
|
| 264 |
+
and calibration.lineage.dataset_version == "run084-phasea-identity-v2-source-digest-platform-v9-20260801"
|
| 265 |
+
and calibration.lineage.source_digest_rows == 104_046
|
| 266 |
+
and calibration.lineage.source_digest_bytes == 41_155_470_172,
|
| 267 |
+
"calibration manifest does not bind the full build_c Run084-v2 artifact",
|
| 268 |
+
)
|
| 269 |
+
calibration_environment = {
|
| 270 |
+
"source_digest_manifest_sha256": "PICMEM_SOURCE_DIGEST_SHA256",
|
| 271 |
+
"source_digest_tree_sha256": "PICMEM_SOURCE_DIGEST_TREE_SHA256",
|
| 272 |
+
"source_digest_rows": "PICMEM_SOURCE_DIGEST_ROWS",
|
| 273 |
+
"source_digest_bytes": "PICMEM_SOURCE_DIGEST_BYTES",
|
| 274 |
+
}
|
| 275 |
+
for field, environment_name in calibration_environment.items():
|
| 276 |
+
require(
|
| 277 |
+
str(getattr(calibration.lineage, field)) == os.environ.get(environment_name),
|
| 278 |
+
f"calibration {field} differs from {environment_name}",
|
| 279 |
+
)
|
| 280 |
+
require(
|
| 281 |
+
calibration.runtime.gpu_class.value == os.environ.get("PICMEM_EXPECTED_GPU_CLASS")
|
| 282 |
+
and calibration.runtime.profile_id == os.environ.get("PICMEM_RUNTIME_PROFILE_ID")
|
| 283 |
+
and calibration.runtime.candidate_id == os.environ.get("PICMEM_RUNTIME_CANDIDATE_ID")
|
| 284 |
+
and calibration.runtime.policy_sha256 == os.environ.get("PICMEM_RUNTIME_POLICY_SHA256")
|
| 285 |
+
and calibration.runtime.plan_sha256 == os.environ.get("PICMEM_RUNTIME_PLAN_SHA256"),
|
| 286 |
+
"calibration runtime identity differs from the reviewed process environment",
|
| 287 |
+
)
|
| 288 |
+
require(
|
| 289 |
+
calibration.sample_order.manifest_path == os.environ.get("PICMEM_SAMPLE_ORDER_MANIFEST")
|
| 290 |
+
and calibration.sample_order.manifest_sha256 == os.environ.get("PICMEM_SAMPLE_ORDER_MANIFEST_SHA256")
|
| 291 |
+
and calibration.sample_order.sample_order_sha256 == os.environ.get("PICMEM_SAMPLE_ORDER_SHA256"),
|
| 292 |
+
"calibration sample-order lineage differs from the process environment",
|
| 293 |
+
)
|
| 294 |
+
expected_global_batch = calibration.runtime.global_batch
|
| 295 |
+
else:
|
| 296 |
+
require(
|
| 297 |
+
not os.environ.get("PICMEM_FORMAL_LAUNCH") and launch_kind not in {"formal", "sku_smoke"},
|
| 298 |
+
"formal/sku-smoke dataset validation requires a training manifest",
|
| 299 |
+
)
|
| 300 |
+
expected_factors = actual_factors
|
| 301 |
+
if expected_global_batch is not None:
|
| 302 |
+
require(
|
| 303 |
+
os.environ.get("BATCH_SIZE") == str(expected_global_batch),
|
| 304 |
+
"training manifest global batch differs from BATCH_SIZE",
|
| 305 |
+
)
|
| 306 |
+
require(
|
| 307 |
+
actual_factors == expected_factors,
|
| 308 |
+
f"formal Phase-A factor drift: config={actual_factors}, manifest={expected_factors}",
|
| 309 |
+
)
|
| 310 |
+
require(
|
| 311 |
+
(
|
| 312 |
+
int(history.budget),
|
| 313 |
+
int(history.token_per_image),
|
| 314 |
+
int(history.num_views),
|
| 315 |
+
int(selection.frame_budget),
|
| 316 |
+
int(selection.recent_anchor_count),
|
| 317 |
+
)
|
| 318 |
+
== (TOKEN_BUDGET, TOKEN_PER_IMAGE, 1, FRAME_BUDGET, 4),
|
| 319 |
+
"Phase-A config geometry drift",
|
| 320 |
+
)
|
| 321 |
+
require(
|
| 322 |
+
(
|
| 323 |
+
int(geometry.get("token_budget", -1)),
|
| 324 |
+
int(geometry.get("token_per_image", -1)),
|
| 325 |
+
int(geometry.get("num_views", -1)),
|
| 326 |
+
int(geometry.get("frame_capacity", -1)),
|
| 327 |
+
)
|
| 328 |
+
== (TOKEN_BUDGET, TOKEN_PER_IMAGE, 1, FRAME_BUDGET),
|
| 329 |
+
"cohort/config geometry mismatch",
|
| 330 |
+
)
|
| 331 |
+
|
| 332 |
+
dataset = RoboMMEDataset(
|
| 333 |
+
str(args.dataset),
|
| 334 |
+
fake_data_config(np),
|
| 335 |
+
history,
|
| 336 |
+
action_horizon=20,
|
| 337 |
+
)
|
| 338 |
+
require(dataset.phase_a_enabled, "dataset did not enable the Phase-A selector")
|
| 339 |
+
require(dataset.phase_a_sidecar_dir == args.sidecar_dir, "dataset did not bind the requested sidecars")
|
| 340 |
+
reader = dataset.phase_a_selection_reader
|
| 341 |
+
require(reader is not None, "dataset did not bind the frozen selection manifests")
|
| 342 |
+
require(
|
| 343 |
+
reader.subset.manifest_sha256 == args.subset_manifest_sha256
|
| 344 |
+
and reader.replacements.sha256 == args.replacement_manifest_sha256
|
| 345 |
+
and reader.best_visible.sha256 == args.best_visible_manifest_sha256,
|
| 346 |
+
"dataset frozen-manifest lineage drift",
|
| 347 |
+
)
|
| 348 |
+
completeness = reader.validate_formal_completeness(
|
| 349 |
+
iter_formal_read_requirements(
|
| 350 |
+
reader=reader,
|
| 351 |
+
dataset_root=args.dataset,
|
| 352 |
+
sidecar_dir=args.sidecar_dir,
|
| 353 |
+
manager_mode=reader.replacements.manager_mode,
|
| 354 |
+
)
|
| 355 |
+
)
|
| 356 |
+
|
| 357 |
+
dataset_index = scalar_int(cohort.get("dataset", {}).get("index"), "cohort dataset index")
|
| 358 |
+
require(dataset_index < len(dataset), f"cohort index {dataset_index} is outside the dataset")
|
| 359 |
+
raw = dataset.dataset[dataset_index]
|
| 360 |
+
episode = scalar_int(raw.get("epis_idx"), "epis_idx")
|
| 361 |
+
step = scalar_int(raw.get("step_idx"), "step_idx")
|
| 362 |
+
exec_start = scalar_int(raw.get("exec_start_idx"), "exec_start_idx")
|
| 363 |
+
instruction = raw.get("prompt")
|
| 364 |
+
require(
|
| 365 |
+
(episode, step, instruction)
|
| 366 |
+
== (
|
| 367 |
+
scalar_int(cohort.get("target", {}).get("episode"), "cohort target episode"),
|
| 368 |
+
scalar_int(cohort.get("target", {}).get("step"), "cohort target step"),
|
| 369 |
+
cohort.get("instruction"),
|
| 370 |
+
),
|
| 371 |
+
"cohort/raw sample identity drift",
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
sidecar_path, annotation = load_episode_sidecar(
|
| 375 |
+
args.sidecar_dir,
|
| 376 |
+
episode_id=episode,
|
| 377 |
+
instruction=instruction,
|
| 378 |
+
)
|
| 379 |
+
frozen_row = reader.subset.validate_raw_sample(dataset_index, raw)
|
| 380 |
+
base_read = selected_frame_read(
|
| 381 |
+
args.sidecar_dir,
|
| 382 |
+
episode_id=episode,
|
| 383 |
+
step=step,
|
| 384 |
+
raw_exec_start=exec_start,
|
| 385 |
+
instruction=instruction,
|
| 386 |
+
expected_task_id=frozen_row.task_id,
|
| 387 |
+
expected_sidecar_sha256=frozen_row.sidecar_sha256,
|
| 388 |
+
)
|
| 389 |
+
replacement = reader.record_for(
|
| 390 |
+
frozen_row,
|
| 391 |
+
current_step=step,
|
| 392 |
+
)
|
| 393 |
+
read = reader.render(base_read, replacement, dataset.phase_a_factors.selection_mode)
|
| 394 |
+
plan = materialize_phase_a_read(
|
| 395 |
+
read,
|
| 396 |
+
dataset.phase_a_factors,
|
| 397 |
+
metadata_seed=dataset.phase_a_metadata_seed,
|
| 398 |
+
selection_applied=dataset.phase_a_factors.selection_mode,
|
| 399 |
+
)
|
| 400 |
+
indices = tuple(read.valid_indices())
|
| 401 |
+
require(tuple(read.valid_indices()) == indices, "Read metadata/frame-plan drift")
|
| 402 |
+
require(indices == tuple(sorted(set(indices))), "adapter returned a non-canonical frame plan")
|
| 403 |
+
require(
|
| 404 |
+
indices and indices[-1] <= step and len(indices) == min(FRAME_BUDGET, step + 1),
|
| 405 |
+
"adapter returned a non-causal or short frame plan",
|
| 406 |
+
)
|
| 407 |
+
|
| 408 |
+
sample = dataset[dataset_index]
|
| 409 |
+
for name in NEUTRAL_HOST_FIELDS:
|
| 410 |
+
require(name in sample and sample[name] is None, f"non-neutral host compatibility field: {name}")
|
| 411 |
+
for name in OBSERVATION_FIELDS:
|
| 412 |
+
require(name in sample and sample[name] is not None, f"missing Phase-A observation field: {name}")
|
| 413 |
+
arrays = {
|
| 414 |
+
"static_image_emb": np.asarray(sample["static_image_emb"]),
|
| 415 |
+
"static_pos_emb": np.asarray(sample["static_pos_emb"]),
|
| 416 |
+
"static_state_emb": np.asarray(sample["static_state_emb"]),
|
| 417 |
+
"static_mask": np.asarray(sample["static_mask"]),
|
| 418 |
+
}
|
| 419 |
+
expected_shapes = {
|
| 420 |
+
"static_image_emb": (512, 2048),
|
| 421 |
+
"static_pos_emb": (512, 768),
|
| 422 |
+
"static_state_emb": (512, 8),
|
| 423 |
+
"static_mask": (512,),
|
| 424 |
+
}
|
| 425 |
+
for name, value in arrays.items():
|
| 426 |
+
require(value.shape == expected_shapes[name], f"{name} shape drift: {value.shape}")
|
| 427 |
+
require(np.isfinite(value).all(), f"{name} contains NaN/Inf")
|
| 428 |
+
require(arrays["static_mask"].dtype == np.bool_, "static_mask must be boolean")
|
| 429 |
+
expected_observation = plan.metadata.to_observation()
|
| 430 |
+
expected_mask = expected_observation["phase_a_valid_mask"]
|
| 431 |
+
require(np.array_equal(arrays["static_mask"], expected_mask), "token mask does not match Phase-A Read")
|
| 432 |
+
metadata = {name: np.asarray(sample[name]) for name in OBSERVATION_FIELDS}
|
| 433 |
+
recovered_metadata = PhaseATokenMetadata.from_observation(
|
| 434 |
+
metadata,
|
| 435 |
+
metadata_mode=str(selection.metadata_mode),
|
| 436 |
+
)
|
| 437 |
+
for name, value in recovered_metadata.to_observation().items():
|
| 438 |
+
require(np.array_equal(value, metadata[name]), f"observation roundtrip drift: {name}")
|
| 439 |
+
require(metadata["phase_a_frame_indices"].shape == (TOKEN_BUDGET,), "frame-index shape drift")
|
| 440 |
+
require(metadata["phase_a_capture_steps"].shape == (TOKEN_BUDGET,), "capture-step shape drift")
|
| 441 |
+
require(metadata["phase_a_time_values"].shape == (TOKEN_BUDGET, 3), "time shape drift")
|
| 442 |
+
require(metadata["phase_a_time_mask"].shape == (TOKEN_BUDGET, 3), "time-mask shape drift")
|
| 443 |
+
for name in OBSERVATION_FIELDS:
|
| 444 |
+
require(np.isfinite(metadata[name]).all(), f"{name} contains NaN/Inf")
|
| 445 |
+
require(
|
| 446 |
+
np.array_equal(metadata["phase_a_valid_mask"], arrays["static_mask"]),
|
| 447 |
+
"visual/metadata valid-mask drift",
|
| 448 |
+
)
|
| 449 |
+
for name in OBSERVATION_FIELDS:
|
| 450 |
+
require(
|
| 451 |
+
np.array_equal(metadata[name], expected_observation[name]),
|
| 452 |
+
f"{name} differs from the arm-aware reader plan",
|
| 453 |
+
)
|
| 454 |
+
|
| 455 |
+
spatial_keys = {4: "2x2", 16: "4x4", 64: "8x8"}
|
| 456 |
+
token_offset = 0
|
| 457 |
+
for frame, is_valid, token_count in zip(read.frame_indices, read.valid_mask, plan.token_counts, strict=True):
|
| 458 |
+
token_count = int(token_count)
|
| 459 |
+
if not is_valid:
|
| 460 |
+
token_offset += token_count
|
| 461 |
+
continue
|
| 462 |
+
feature_path = args.dataset / "features" / f"episode_{episode}" / f"token_emb_{frame}.npy"
|
| 463 |
+
require(feature_path.is_file(), f"missing selected feature: {feature_path}")
|
| 464 |
+
feature = np.load(feature_path, allow_pickle=True).item()
|
| 465 |
+
expected = np.asarray(feature[f"image_emb_{spatial_keys[token_count]}"]).reshape(token_count, 2048)
|
| 466 |
+
start = token_offset
|
| 467 |
+
require(
|
| 468 |
+
np.array_equal(arrays["static_image_emb"][start : start + token_count], expected),
|
| 469 |
+
f"loader/Read mismatch at frame {frame}",
|
| 470 |
+
)
|
| 471 |
+
token_offset += token_count
|
| 472 |
+
require(token_offset == TOKEN_BUDGET, "arm reader token budget is not exactly 512")
|
| 473 |
+
|
| 474 |
+
try:
|
| 475 |
+
selected_frame_read(
|
| 476 |
+
args.sidecar_dir,
|
| 477 |
+
episode_id=episode,
|
| 478 |
+
step=step,
|
| 479 |
+
raw_exec_start=exec_start,
|
| 480 |
+
instruction=f"{instruction} [wrong]",
|
| 481 |
+
expected_task_id=frozen_row.task_id,
|
| 482 |
+
expected_sidecar_sha256=frozen_row.sidecar_sha256,
|
| 483 |
+
)
|
| 484 |
+
except MemoryInvariantError:
|
| 485 |
+
pass
|
| 486 |
+
else:
|
| 487 |
+
raise RuntimeError("instruction mismatch did not fail closed")
|
| 488 |
+
|
| 489 |
+
sidecar_exec_start = scalar_int(annotation.get("exec_start_step"), "sidecar exec_start_step")
|
| 490 |
+
if sidecar_exec_start > 0:
|
| 491 |
+
try:
|
| 492 |
+
selected_frame_read(
|
| 493 |
+
args.sidecar_dir,
|
| 494 |
+
episode_id=episode,
|
| 495 |
+
step=step,
|
| 496 |
+
raw_exec_start=sidecar_exec_start - 1,
|
| 497 |
+
instruction=instruction,
|
| 498 |
+
expected_task_id=frozen_row.task_id,
|
| 499 |
+
expected_sidecar_sha256=frozen_row.sidecar_sha256,
|
| 500 |
+
)
|
| 501 |
+
except MemoryInvariantError:
|
| 502 |
+
pass
|
| 503 |
+
else:
|
| 504 |
+
raise RuntimeError("negative alignment offset did not fail closed")
|
| 505 |
+
|
| 506 |
+
print(
|
| 507 |
+
json.dumps(
|
| 508 |
+
{
|
| 509 |
+
"schema_version": "picmem_phase_a_dataset_smoke_v2",
|
| 510 |
+
"status": "PASS",
|
| 511 |
+
"training_manifest_kind": training_manifest_kind or "none",
|
| 512 |
+
"training_manifest_id": training_manifest_id,
|
| 513 |
+
"training_manifest_sha256": training_manifest_sha256,
|
| 514 |
+
"dataset_index": dataset_index,
|
| 515 |
+
"sample_identity_sha256": frozen_row.sample_identity_sha256,
|
| 516 |
+
"episode": episode,
|
| 517 |
+
"step": step,
|
| 518 |
+
"sidecar": str(sidecar_path),
|
| 519 |
+
"replacement_record_sha256": replacement.sha256,
|
| 520 |
+
"selection_mode": dataset.phase_a_factors.selection_mode.value,
|
| 521 |
+
"metadata_mode": dataset.phase_a_factors.metadata_mode.value,
|
| 522 |
+
"reader_mode": dataset.phase_a_factors.reader_mode.value,
|
| 523 |
+
"manager_mode": dataset.phase_a_factors.manager_mode.value,
|
| 524 |
+
"token_counts": [int(value) for value in plan.token_counts],
|
| 525 |
+
"selected_frames": list(indices),
|
| 526 |
+
"valid_tokens": int(arrays["static_mask"].sum()),
|
| 527 |
+
"frozen_completeness": completeness,
|
| 528 |
+
},
|
| 529 |
+
sort_keys=True,
|
| 530 |
+
)
|
| 531 |
+
)
|
| 532 |
+
return 0
|
| 533 |
+
|
| 534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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""CPU Orbax round-trip smoke for the Phase-A full-state host contract."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import dataclasses
|
| 8 |
+
import hashlib
|
| 9 |
+
import json
|
| 10 |
+
import multiprocessing
|
| 11 |
+
import os
|
| 12 |
+
import shutil
|
| 13 |
+
import signal
|
| 14 |
+
import tempfile
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
from types import SimpleNamespace
|
| 17 |
+
from typing import Any
|
| 18 |
+
|
| 19 |
+
import jax
|
| 20 |
+
import jax.numpy as jnp
|
| 21 |
+
import numpy as np
|
| 22 |
+
from mme_vla_suite.training.picmem_phase_a_full_state import (
|
| 23 |
+
SMOKE_SUBSET_SHA256,
|
| 24 |
+
ContinuityEmitter,
|
| 25 |
+
PhaseAContract,
|
| 26 |
+
PhaseASmokeRandomSampler,
|
| 27 |
+
_validate_bound_arm,
|
| 28 |
+
_validate_bound_training_manifest,
|
| 29 |
+
_validate_phase_a_factor_contract,
|
| 30 |
+
initialize_phase_a_checkpoint_dir,
|
| 31 |
+
materialize_phase_a_contract,
|
| 32 |
+
restore_phase_a_checkpoint,
|
| 33 |
+
save_phase_a_checkpoint,
|
| 34 |
+
validate_phase_a_topology,
|
| 35 |
+
)
|
| 36 |
+
from openpi.shared import normalize as _normalize
|
| 37 |
+
|
| 38 |
+
from picmem.ops.checkpoint import CheckpointError, path_sha256, validate_checkpoint
|
| 39 |
+
from picmem.ops.registry import RUN084_BUILD_C_LINEAGE
|
| 40 |
+
from picmem.ops.watchdog import (
|
| 41 |
+
FailureOrigin,
|
| 42 |
+
RemoteState,
|
| 43 |
+
RemoteStatus,
|
| 44 |
+
WatchAction,
|
| 45 |
+
run_once,
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
_DIGESTS = {
|
| 49 |
+
"config_sha256": "11" * 32,
|
| 50 |
+
"dataset_sha256": SMOKE_SUBSET_SHA256,
|
| 51 |
+
"cohort_sha256": "33" * 32,
|
| 52 |
+
"sidecar_sha256": "44" * 32,
|
| 53 |
+
"feature_sha256": "55" * 32,
|
| 54 |
+
"source_metadata_sha256": "66" * 32,
|
| 55 |
+
"source_digest_sha256": RUN084_BUILD_C_LINEAGE["source_digest_manifest_sha256"],
|
| 56 |
+
"artifact_identity_sha256": "77" * 32,
|
| 57 |
+
"artifact_hashes_sha256": "88" * 32,
|
| 58 |
+
"replacement_manifest_sha256": "aa" * 32,
|
| 59 |
+
"best_visible_manifest_sha256": "bb" * 32,
|
| 60 |
+
"sample_order_manifest_sha256": "dd" * 32,
|
| 61 |
+
"sample_order_sha256": "ee" * 32,
|
| 62 |
+
"training_manifest_sha256": "cc" * 32,
|
| 63 |
+
"overlay_sha256": "99" * 32,
|
| 64 |
+
"runtime_policy_sha256": "12" * 32,
|
| 65 |
+
"runtime_plan_sha256": "13" * 32,
|
| 66 |
+
"runtime_matrix_sha256": "14" * 32,
|
| 67 |
+
"runtime_calibration_sha256": "15" * 32,
|
| 68 |
+
"optimizer_sha256": "16" * 32,
|
| 69 |
+
"learning_rate_schedule_sha256": "17" * 32,
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
@dataclasses.dataclass(frozen=True)
|
| 74 |
+
class TinyState:
|
| 75 |
+
step: Any
|
| 76 |
+
params: Any
|
| 77 |
+
ema_params: Any
|
| 78 |
+
opt_state: Any
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class TinyLoader:
|
| 82 |
+
def __init__(self, sampler: PhaseASmokeRandomSampler):
|
| 83 |
+
self.sampler = sampler
|
| 84 |
+
stats = _normalize.NormStats(
|
| 85 |
+
mean=np.asarray([0.0], dtype=np.float32),
|
| 86 |
+
std=np.asarray([1.0], dtype=np.float32),
|
| 87 |
+
q01=np.asarray([-1.0], dtype=np.float32),
|
| 88 |
+
q99=np.asarray([1.0], dtype=np.float32),
|
| 89 |
+
)
|
| 90 |
+
self._data_config = SimpleNamespace(norm_stats={"actions": stats}, asset_id="robomme")
|
| 91 |
+
|
| 92 |
+
def data_config(self) -> Any:
|
| 93 |
+
return self._data_config
|
| 94 |
+
|
| 95 |
+
def sampler_state_dict(self) -> dict[str, Any]:
|
| 96 |
+
return self.sampler.state_dict()
|
| 97 |
+
|
| 98 |
+
def load_sampler_state_dict(self, state: dict[str, Any]) -> None:
|
| 99 |
+
self.sampler.load_state_dict(state)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def _contract(
|
| 103 |
+
root: Path,
|
| 104 |
+
*,
|
| 105 |
+
generation: int,
|
| 106 |
+
parent: str | None,
|
| 107 |
+
) -> PhaseAContract:
|
| 108 |
+
continuity_request_id = "initial-g0" if generation == 0 else "d" * 64
|
| 109 |
+
return PhaseAContract(
|
| 110 |
+
launch_kind="synthetic_smoke",
|
| 111 |
+
experiment="phase-a-smoke",
|
| 112 |
+
job="phase-a-smoke-job",
|
| 113 |
+
run_id="phase-a-smoke-r1",
|
| 114 |
+
generation=generation,
|
| 115 |
+
gpu_class="h200",
|
| 116 |
+
checkpoint_root=root,
|
| 117 |
+
interface_commit="a" * 40,
|
| 118 |
+
code_commit="b" * 40,
|
| 119 |
+
sample_order_path=Path(__file__).resolve(),
|
| 120 |
+
training_manifest_kind="synthetic_smoke_v1",
|
| 121 |
+
runtime_profile_id="synthetic-smoke-profile",
|
| 122 |
+
runtime_candidate_id="synthetic-smoke-candidate",
|
| 123 |
+
global_batch_size=64,
|
| 124 |
+
micro_batch_per_device=8,
|
| 125 |
+
gradient_accumulation_steps=1,
|
| 126 |
+
dataloader_workers=1,
|
| 127 |
+
prefetch_factor=2,
|
| 128 |
+
xla_preallocate=True,
|
| 129 |
+
xla_memory_fraction="0.9",
|
| 130 |
+
nccl_collective_channel_cap=32,
|
| 131 |
+
nccl_p2p_channel_cap=32,
|
| 132 |
+
xla_flags="--xla_gpu_nccl_p2p_max_nchannels=32",
|
| 133 |
+
runtime_checkpoint_interval=250,
|
| 134 |
+
parent_metadata_sha256=parent,
|
| 135 |
+
continuity_mode="initial" if generation == 0 else "checkpoint_resume",
|
| 136 |
+
continuity_request_id=continuity_request_id,
|
| 137 |
+
watch_state_dir=root.parent / "watch",
|
| 138 |
+
continuity_path=root.parent / "watch" / f"continuity-{continuity_request_id}.json",
|
| 139 |
+
metrics_path=root.parent / "attempts" / f"generation-{generation}" / "metrics.tsv",
|
| 140 |
+
**_DIGESTS,
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def _config(root: Path) -> Any:
|
| 145 |
+
return SimpleNamespace(
|
| 146 |
+
checkpoint_dir=root,
|
| 147 |
+
exp_name="phase-a-smoke",
|
| 148 |
+
optimizer="tiny-adam",
|
| 149 |
+
lr_schedule="tiny-positive-schedule",
|
| 150 |
+
ema_decay=0.99,
|
| 151 |
+
seed=17,
|
| 152 |
+
sampler_seed=(1 << 40) + 9,
|
| 153 |
+
save_interval=250,
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def _schedule(step: Any) -> Any:
|
| 158 |
+
return jnp.asarray(1e-3 / (jnp.asarray(step, dtype=jnp.float32) + 1.0), dtype=jnp.float32)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def _state(step: int, offset: float) -> TinyState:
|
| 162 |
+
return TinyState(
|
| 163 |
+
step=jnp.asarray(step, dtype=jnp.int32),
|
| 164 |
+
params={"weight": jnp.asarray([offset + 1.0, offset + 2.0], dtype=jnp.float32)},
|
| 165 |
+
ema_params={"weight": jnp.asarray([offset + 3.0, offset + 4.0], dtype=jnp.float32)},
|
| 166 |
+
opt_state={
|
| 167 |
+
"count": jnp.asarray(step, dtype=jnp.int32),
|
| 168 |
+
"moment": jnp.asarray([offset + 5.0, offset + 6.0], dtype=jnp.float32),
|
| 169 |
+
},
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def _tree_equal(left: Any, right: Any) -> bool:
|
| 174 |
+
if jax.tree_util.tree_structure(left) != jax.tree_util.tree_structure(right):
|
| 175 |
+
return False
|
| 176 |
+
return all(
|
| 177 |
+
np.array_equal(np.asarray(jax.device_get(a)), np.asarray(jax.device_get(b)))
|
| 178 |
+
for a, b in zip(jax.tree_util.tree_leaves(left), jax.tree_util.tree_leaves(right), strict=True)
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def _expect_rejected(action: Any, label: str) -> None:
|
| 183 |
+
try:
|
| 184 |
+
action()
|
| 185 |
+
except (CheckpointError, ValueError):
|
| 186 |
+
return
|
| 187 |
+
raise AssertionError(f"unsafe smoke case was accepted: {label}")
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def _expect_checkpoint_reopen_rejected(root: Path, label: str) -> None:
|
| 191 |
+
try:
|
| 192 |
+
unexpected_manager, _ = initialize_phase_a_checkpoint_dir(
|
| 193 |
+
root,
|
| 194 |
+
overwrite=False,
|
| 195 |
+
resume=True,
|
| 196 |
+
launch_kind="synthetic_smoke",
|
| 197 |
+
)
|
| 198 |
+
except (CheckpointError, ValueError):
|
| 199 |
+
return
|
| 200 |
+
unexpected_manager.close()
|
| 201 |
+
raise AssertionError(f"unsafe cold checkpoint reopen was accepted: {label}")
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def _topology_checks() -> None:
|
| 205 |
+
valid = {
|
| 206 |
+
"gpu_class": "h200",
|
| 207 |
+
"world_size": 8,
|
| 208 |
+
"local_device_count": 8,
|
| 209 |
+
"process_count": 1,
|
| 210 |
+
"fsdp_devices": 8,
|
| 211 |
+
"batch_size": 64,
|
| 212 |
+
"device_kinds": ("NVIDIA H200",) * 8,
|
| 213 |
+
}
|
| 214 |
+
validate_phase_a_topology(**valid)
|
| 215 |
+
validate_phase_a_topology(**(valid | {"gpu_class": "a100_40g", "batch_size": 8, "device_kinds": ("A100",) * 8}))
|
| 216 |
+
for label, replacement in (
|
| 217 |
+
("world", {"world_size": 4}),
|
| 218 |
+
("fsdp", {"fsdp_devices": 4}),
|
| 219 |
+
("batch", {"batch_size": 6}),
|
| 220 |
+
("boolean-batch", {"batch_size": True}),
|
| 221 |
+
("sku", {"device_kinds": ("NVIDIA A100",) * 8}),
|
| 222 |
+
):
|
| 223 |
+
_expect_rejected(lambda replacement=replacement: validate_phase_a_topology(**(valid | replacement)), label)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def _mutate_state(checkpoint: Path) -> None:
|
| 227 |
+
candidates = [
|
| 228 |
+
path for path in checkpoint.joinpath("resume_state").rglob("*") if path.is_file() and path.name != "_METADATA"
|
| 229 |
+
]
|
| 230 |
+
if not candidates:
|
| 231 |
+
raise AssertionError("Orbax smoke checkpoint contains no mutable resume-state payload")
|
| 232 |
+
with candidates[0].open("ab") as stream:
|
| 233 |
+
stream.write(b"corruption")
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def _arm_binding_checks(work_dir: Path) -> None:
|
| 237 |
+
arm_path = work_dir / "arm.json"
|
| 238 |
+
contract = dataclasses.replace(
|
| 239 |
+
_contract(work_dir / "arm-checkpoints", generation=0, parent=None),
|
| 240 |
+
launch_kind="formal",
|
| 241 |
+
training_manifest_kind="arm_v3",
|
| 242 |
+
)
|
| 243 |
+
arm = {
|
| 244 |
+
"schema_version": "picmem_phase_a_arm_v3",
|
| 245 |
+
"arm_id": contract.job,
|
| 246 |
+
"parent_commit": contract.code_commit,
|
| 247 |
+
"parent_tree": "d" * 40,
|
| 248 |
+
"host_overlay_sha256": contract.overlay_sha256,
|
| 249 |
+
"dataset_sha256": contract.dataset_sha256,
|
| 250 |
+
"sidecar_sha256": contract.sidecar_sha256,
|
| 251 |
+
"feature_sha256": contract.feature_sha256,
|
| 252 |
+
"source_metadata_sha256": contract.source_metadata_sha256,
|
| 253 |
+
"artifact_identity_sha256": contract.artifact_identity_sha256,
|
| 254 |
+
"artifact_hashes_sha256": contract.artifact_hashes_sha256,
|
| 255 |
+
"replacement_manifest_sha256": contract.replacement_manifest_sha256,
|
| 256 |
+
"best_visible_manifest_sha256": contract.best_visible_manifest_sha256,
|
| 257 |
+
"sample_order_manifest_sha256": contract.sample_order_manifest_sha256,
|
| 258 |
+
"sample_order_sha256": contract.sample_order_sha256,
|
| 259 |
+
"selection_mode": "relevant",
|
| 260 |
+
"metadata_mode": "correct",
|
| 261 |
+
"reader_mode": "fixed16",
|
| 262 |
+
"manager_mode": "full_evolving",
|
| 263 |
+
"gpu_sku": "H200-141GB",
|
| 264 |
+
"gpu_count": 8,
|
| 265 |
+
"global_batch": 64,
|
| 266 |
+
"seed": 17,
|
| 267 |
+
"checkpoint_interval": 250,
|
| 268 |
+
"resume_lineage": "phase-a/arm-smoke",
|
| 269 |
+
"evaluation_cohort_sha256": contract.cohort_sha256,
|
| 270 |
+
}
|
| 271 |
+
raw = (json.dumps(arm, sort_keys=True, separators=(",", ":")) + "\n").encode()
|
| 272 |
+
arm_path.write_bytes(raw)
|
| 273 |
+
contract = dataclasses.replace(
|
| 274 |
+
contract,
|
| 275 |
+
training_manifest_sha256=hashlib.sha256(raw).hexdigest(),
|
| 276 |
+
)
|
| 277 |
+
config = SimpleNamespace(seed=17, sampler_seed=17, save_interval=250)
|
| 278 |
+
environment = {
|
| 279 |
+
"PICMEM_PHASE_A_LAUNCH_KIND": "formal",
|
| 280 |
+
"PICMEM_TRAINING_MANIFEST_KIND": "arm_v3",
|
| 281 |
+
"PICMEM_ARM_MANIFEST": str(arm_path),
|
| 282 |
+
"PICMEM_ARM_MANIFEST_SHA256": contract.training_manifest_sha256,
|
| 283 |
+
"PICMEM_SOURCE_DIGEST_SHA256": contract.source_digest_sha256,
|
| 284 |
+
"PICMEM_CODE_TREE": arm["parent_tree"],
|
| 285 |
+
"PICMEM_RESUME_LINEAGE": arm["resume_lineage"],
|
| 286 |
+
"PICMEM_PHASE_A_SELECTION_MODE": arm["selection_mode"],
|
| 287 |
+
"PICMEM_PHASE_A_METADATA_MODE": arm["metadata_mode"],
|
| 288 |
+
"PICMEM_PHASE_A_READER_MODE": arm["reader_mode"],
|
| 289 |
+
"PICMEM_PHASE_A_MANAGER_MODE": arm["manager_mode"],
|
| 290 |
+
}
|
| 291 |
+
previous = {
|
| 292 |
+
name: os.environ.get(name)
|
| 293 |
+
for name in (
|
| 294 |
+
*environment,
|
| 295 |
+
"PICMEM_CALIBRATION_MANIFEST",
|
| 296 |
+
"PICMEM_CALIBRATION_MANIFEST_SHA256",
|
| 297 |
+
)
|
| 298 |
+
}
|
| 299 |
+
try:
|
| 300 |
+
os.environ.update({name: str(value) for name, value in environment.items()})
|
| 301 |
+
os.environ.pop("PICMEM_CALIBRATION_MANIFEST", None)
|
| 302 |
+
os.environ.pop("PICMEM_CALIBRATION_MANIFEST_SHA256", None)
|
| 303 |
+
_validate_bound_arm(contract, config)
|
| 304 |
+
factors = {
|
| 305 |
+
"require_explicit_factors": True,
|
| 306 |
+
"selection_mode": arm["selection_mode"],
|
| 307 |
+
"metadata_mode": arm["metadata_mode"],
|
| 308 |
+
"reader_mode": arm["reader_mode"],
|
| 309 |
+
"manager_mode": arm["manager_mode"],
|
| 310 |
+
}
|
| 311 |
+
_validate_phase_a_factor_contract(factors)
|
| 312 |
+
alternatives = {
|
| 313 |
+
"selection_mode": "uniform",
|
| 314 |
+
"metadata_mode": "neutral",
|
| 315 |
+
"reader_mode": "variable64",
|
| 316 |
+
"manager_mode": "fifo",
|
| 317 |
+
}
|
| 318 |
+
for name, alternative in alternatives.items():
|
| 319 |
+
drifted_factors = dict(factors)
|
| 320 |
+
drifted_factors[name] = alternative
|
| 321 |
+
_expect_rejected(
|
| 322 |
+
lambda drifted_factors=drifted_factors: _validate_phase_a_factor_contract(drifted_factors),
|
| 323 |
+
f"YAML {name} masquerade",
|
| 324 |
+
)
|
| 325 |
+
missing_factors = dict(factors)
|
| 326 |
+
del missing_factors["reader_mode"]
|
| 327 |
+
_expect_rejected(
|
| 328 |
+
lambda: _validate_phase_a_factor_contract(missing_factors),
|
| 329 |
+
"YAML missing factor",
|
| 330 |
+
)
|
| 331 |
+
unknown_factors = dict(factors)
|
| 332 |
+
unknown_factors["selection_mode"] = "unknown"
|
| 333 |
+
_expect_rejected(
|
| 334 |
+
lambda: _validate_phase_a_factor_contract(unknown_factors),
|
| 335 |
+
"YAML unknown factor",
|
| 336 |
+
)
|
| 337 |
+
legacy_factors = dict(factors)
|
| 338 |
+
legacy_factors["require_explicit_factors"] = False
|
| 339 |
+
_expect_rejected(
|
| 340 |
+
lambda: _validate_phase_a_factor_contract(legacy_factors),
|
| 341 |
+
"YAML legacy factor defaults",
|
| 342 |
+
)
|
| 343 |
+
|
| 344 |
+
drifted = dict(arm)
|
| 345 |
+
drifted["seed"] = 18
|
| 346 |
+
drifted_raw = (json.dumps(drifted, sort_keys=True, separators=(",", ":")) + "\n").encode()
|
| 347 |
+
arm_path.write_bytes(drifted_raw)
|
| 348 |
+
drifted_contract = dataclasses.replace(
|
| 349 |
+
contract,
|
| 350 |
+
training_manifest_sha256=hashlib.sha256(drifted_raw).hexdigest(),
|
| 351 |
+
)
|
| 352 |
+
os.environ["PICMEM_ARM_MANIFEST_SHA256"] = drifted_contract.training_manifest_sha256
|
| 353 |
+
_expect_rejected(
|
| 354 |
+
lambda: _validate_bound_arm(drifted_contract, config),
|
| 355 |
+
"training-process arm factor drift",
|
| 356 |
+
)
|
| 357 |
+
|
| 358 |
+
duplicate_raw = b'{"arm_id":"duplicate",' + raw[1:]
|
| 359 |
+
arm_path.write_bytes(duplicate_raw)
|
| 360 |
+
duplicate_contract = dataclasses.replace(
|
| 361 |
+
contract,
|
| 362 |
+
training_manifest_sha256=hashlib.sha256(duplicate_raw).hexdigest(),
|
| 363 |
+
)
|
| 364 |
+
os.environ["PICMEM_ARM_MANIFEST_SHA256"] = duplicate_contract.training_manifest_sha256
|
| 365 |
+
_expect_rejected(
|
| 366 |
+
lambda: _validate_bound_arm(duplicate_contract, config),
|
| 367 |
+
"training-process duplicate arm key",
|
| 368 |
+
)
|
| 369 |
+
finally:
|
| 370 |
+
for name, value in previous.items():
|
| 371 |
+
if value is None:
|
| 372 |
+
os.environ.pop(name, None)
|
| 373 |
+
else:
|
| 374 |
+
os.environ[name] = value
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
def _calibration_binding_checks(work_dir: Path) -> None:
|
| 378 |
+
manifest_path = work_dir / "calibration.json"
|
| 379 |
+
contract = dataclasses.replace(
|
| 380 |
+
_contract(work_dir / "calibration-checkpoints", generation=0, parent=None),
|
| 381 |
+
launch_kind="sku_smoke",
|
| 382 |
+
gpu_class="a100_40g",
|
| 383 |
+
training_manifest_kind="sku_calibration_v1",
|
| 384 |
+
runtime_profile_id="a100-40g-calibration-v1",
|
| 385 |
+
runtime_candidate_id="a100-40g-batch8-v1",
|
| 386 |
+
global_batch_size=8,
|
| 387 |
+
micro_batch_per_device=1,
|
| 388 |
+
runtime_checkpoint_interval=25,
|
| 389 |
+
)
|
| 390 |
+
parent_tree = "d" * 40
|
| 391 |
+
source_digest_tree = "18" * 32
|
| 392 |
+
resume_lineage = "phase-a/calibration-smoke"
|
| 393 |
+
manifest = {
|
| 394 |
+
"schema_version": "picmem_phase_a_sku_calibration_manifest_v1",
|
| 395 |
+
"calibration_id": contract.job,
|
| 396 |
+
"purpose": "sku_runtime_calibration",
|
| 397 |
+
"scientific_eligible": False,
|
| 398 |
+
"formal_qualifying": False,
|
| 399 |
+
"lineage": {
|
| 400 |
+
"parent_commit": contract.code_commit,
|
| 401 |
+
"parent_tree": parent_tree,
|
| 402 |
+
"host_overlay_sha256": contract.overlay_sha256,
|
| 403 |
+
"artifact_schema_version": "picmem_run084_artifact_hashes_v2",
|
| 404 |
+
"dataset_version": "run084-v2-smoke",
|
| 405 |
+
"artifact_hashes_sha256": contract.artifact_hashes_sha256,
|
| 406 |
+
"dataset_sha256": contract.dataset_sha256,
|
| 407 |
+
"sidecar_sha256": contract.sidecar_sha256,
|
| 408 |
+
"feature_sha256": contract.feature_sha256,
|
| 409 |
+
"source_metadata_sha256": contract.source_metadata_sha256,
|
| 410 |
+
"source_digest_manifest_sha256": contract.source_digest_sha256,
|
| 411 |
+
"source_digest_tree_sha256": source_digest_tree,
|
| 412 |
+
"source_digest_rows": 104_046,
|
| 413 |
+
"source_digest_bytes": 41_155_470_172,
|
| 414 |
+
"artifact_identity_sha256": contract.artifact_identity_sha256,
|
| 415 |
+
"replacement_manifest_sha256": contract.replacement_manifest_sha256,
|
| 416 |
+
"best_visible_manifest_sha256": contract.best_visible_manifest_sha256,
|
| 417 |
+
"evaluation_cohort_sha256": contract.cohort_sha256,
|
| 418 |
+
},
|
| 419 |
+
"sample_order": {
|
| 420 |
+
"binding_id": "run084-seed17-batch8",
|
| 421 |
+
"dataset_sha256": contract.dataset_sha256,
|
| 422 |
+
"seed": 17,
|
| 423 |
+
"global_batch": 8,
|
| 424 |
+
"manifest_path": str(contract.sample_order_path),
|
| 425 |
+
"manifest_sha256": contract.sample_order_manifest_sha256,
|
| 426 |
+
"sample_order_sha256": contract.sample_order_sha256,
|
| 427 |
+
},
|
| 428 |
+
"factors": {
|
| 429 |
+
"selection_mode": "relevant",
|
| 430 |
+
"metadata_mode": "correct",
|
| 431 |
+
"reader_mode": "fixed16",
|
| 432 |
+
"manager_mode": "full_evolving",
|
| 433 |
+
},
|
| 434 |
+
"runtime": {
|
| 435 |
+
"gpu_class": contract.gpu_class,
|
| 436 |
+
"gpu_sku": "A100-40GB",
|
| 437 |
+
"gpu_count": 8,
|
| 438 |
+
"profile_id": contract.runtime_profile_id,
|
| 439 |
+
"candidate_id": contract.runtime_candidate_id,
|
| 440 |
+
"policy_sha256": contract.runtime_policy_sha256,
|
| 441 |
+
"plan_sha256": contract.runtime_plan_sha256,
|
| 442 |
+
"world_size": 8,
|
| 443 |
+
"global_batch": contract.global_batch_size,
|
| 444 |
+
"micro_batch_per_device": contract.micro_batch_per_device,
|
| 445 |
+
"gradient_accumulation_steps": contract.gradient_accumulation_steps,
|
| 446 |
+
"dataloader_workers": contract.dataloader_workers,
|
| 447 |
+
"prefetch_factor": contract.prefetch_factor,
|
| 448 |
+
"xla_preallocate": contract.xla_preallocate,
|
| 449 |
+
"xla_memory_fraction": contract.xla_memory_fraction,
|
| 450 |
+
"xla_base_flags": [],
|
| 451 |
+
"nccl_collective_channel_cap": contract.nccl_collective_channel_cap,
|
| 452 |
+
"nccl_p2p_channel_cap": contract.nccl_p2p_channel_cap,
|
| 453 |
+
"checkpoint_interval": contract.runtime_checkpoint_interval,
|
| 454 |
+
"train_steps": 100,
|
| 455 |
+
},
|
| 456 |
+
"resume_lineage": resume_lineage,
|
| 457 |
+
}
|
| 458 |
+
raw = (json.dumps(manifest, allow_nan=False, sort_keys=True, separators=(",", ":")) + "\n").encode()
|
| 459 |
+
manifest_path.write_bytes(raw)
|
| 460 |
+
contract = dataclasses.replace(
|
| 461 |
+
contract,
|
| 462 |
+
training_manifest_sha256=hashlib.sha256(raw).hexdigest(),
|
| 463 |
+
)
|
| 464 |
+
config = SimpleNamespace(
|
| 465 |
+
seed=17,
|
| 466 |
+
sampler_seed=17,
|
| 467 |
+
save_interval=25,
|
| 468 |
+
num_train_steps=100,
|
| 469 |
+
)
|
| 470 |
+
environment = {
|
| 471 |
+
"PICMEM_PHASE_A_LAUNCH_KIND": "sku_smoke",
|
| 472 |
+
"PICMEM_TRAINING_MANIFEST_KIND": "sku_calibration_v1",
|
| 473 |
+
"PICMEM_CALIBRATION_MANIFEST": str(manifest_path),
|
| 474 |
+
"PICMEM_CALIBRATION_MANIFEST_SHA256": contract.training_manifest_sha256,
|
| 475 |
+
"PICMEM_CODE_TREE": parent_tree,
|
| 476 |
+
"PICMEM_RESUME_LINEAGE": resume_lineage,
|
| 477 |
+
"PICMEM_ARTIFACT_SCHEMA_VERSION": manifest["lineage"]["artifact_schema_version"],
|
| 478 |
+
"PICMEM_DATASET_VERSION": manifest["lineage"]["dataset_version"],
|
| 479 |
+
"PICMEM_SOURCE_DIGEST_TREE_SHA256": source_digest_tree,
|
| 480 |
+
"PICMEM_SOURCE_DIGEST_ROWS": str(manifest["lineage"]["source_digest_rows"]),
|
| 481 |
+
"PICMEM_SOURCE_DIGEST_BYTES": str(manifest["lineage"]["source_digest_bytes"]),
|
| 482 |
+
"PICMEM_PHASE_A_SELECTION_MODE": "relevant",
|
| 483 |
+
"PICMEM_PHASE_A_METADATA_MODE": "correct",
|
| 484 |
+
"PICMEM_PHASE_A_READER_MODE": "fixed16",
|
| 485 |
+
"PICMEM_PHASE_A_MANAGER_MODE": "full_evolving",
|
| 486 |
+
}
|
| 487 |
+
previous = {
|
| 488 |
+
name: os.environ.get(name) for name in (*environment, "PICMEM_ARM_MANIFEST", "PICMEM_ARM_MANIFEST_SHA256")
|
| 489 |
+
}
|
| 490 |
+
try:
|
| 491 |
+
os.environ.update(environment)
|
| 492 |
+
os.environ.pop("PICMEM_ARM_MANIFEST", None)
|
| 493 |
+
os.environ.pop("PICMEM_ARM_MANIFEST_SHA256", None)
|
| 494 |
+
_validate_bound_training_manifest(contract, config)
|
| 495 |
+
drifted = dict(manifest)
|
| 496 |
+
drifted["runtime"] = dict(manifest["runtime"])
|
| 497 |
+
drifted["runtime"]["global_batch"] = 64
|
| 498 |
+
drifted_raw = (json.dumps(drifted, allow_nan=False, sort_keys=True, separators=(",", ":")) + "\n").encode()
|
| 499 |
+
manifest_path.write_bytes(drifted_raw)
|
| 500 |
+
drifted_contract = dataclasses.replace(
|
| 501 |
+
contract,
|
| 502 |
+
training_manifest_sha256=hashlib.sha256(drifted_raw).hexdigest(),
|
| 503 |
+
)
|
| 504 |
+
os.environ["PICMEM_CALIBRATION_MANIFEST_SHA256"] = drifted_contract.training_manifest_sha256
|
| 505 |
+
_expect_rejected(
|
| 506 |
+
lambda: _validate_bound_training_manifest(drifted_contract, config),
|
| 507 |
+
"calibration runtime batch drift",
|
| 508 |
+
)
|
| 509 |
+
finally:
|
| 510 |
+
for name, value in previous.items():
|
| 511 |
+
if value is None:
|
| 512 |
+
os.environ.pop(name, None)
|
| 513 |
+
else:
|
| 514 |
+
os.environ[name] = value
|
| 515 |
+
|
| 516 |
+
|
| 517 |
+
def _paused_resume_worker(
|
| 518 |
+
contract: PhaseAContract,
|
| 519 |
+
ready_queue: Any,
|
| 520 |
+
resume_gate: Any,
|
| 521 |
+
result_queue: Any,
|
| 522 |
+
) -> None:
|
| 523 |
+
"""Exercise the real host continuity producer in one long-lived process."""
|
| 524 |
+
|
| 525 |
+
ready_sent = False
|
| 526 |
+
try:
|
| 527 |
+
contract.metrics_path.parent.mkdir(parents=True, exist_ok=True)
|
| 528 |
+
contract.metrics_path.write_text("step\n37\n", encoding="utf-8")
|
| 529 |
+
sampler = PhaseASmokeRandomSampler(
|
| 530 |
+
256,
|
| 531 |
+
batch_size=64,
|
| 532 |
+
seed=(1 << 40) + 91,
|
| 533 |
+
epoch=2,
|
| 534 |
+
batch_cursor=3,
|
| 535 |
+
)
|
| 536 |
+
train_rng = jax.random.key(321)
|
| 537 |
+
emitter = ContinuityEmitter(contract, contract.metrics_path)
|
| 538 |
+
emitter.capture_pending(
|
| 539 |
+
current_step=37,
|
| 540 |
+
sampler_state=sampler.state_dict(),
|
| 541 |
+
train_rng=train_rng,
|
| 542 |
+
)
|
| 543 |
+
ready_queue.put({"pid": os.getpid(), "sampler": sampler.state_dict()})
|
| 544 |
+
ready_sent = True
|
| 545 |
+
if not resume_gate.wait(timeout=30):
|
| 546 |
+
raise TimeoutError("paused-resume smoke did not receive the in-place resume signal")
|
| 547 |
+
|
| 548 |
+
# This is the same process, RNG, sampler cursor, and live step that was
|
| 549 |
+
# suspended. The request did not exist at process startup.
|
| 550 |
+
emitter.capture_pending(
|
| 551 |
+
current_step=37,
|
| 552 |
+
sampler_state=sampler.state_dict(),
|
| 553 |
+
train_rng=train_rng,
|
| 554 |
+
)
|
| 555 |
+
pending = emitter.pending
|
| 556 |
+
if pending is None:
|
| 557 |
+
raise AssertionError("live trainer did not capture the paused-resume request")
|
| 558 |
+
request_id = pending.request_id
|
| 559 |
+
report_path = emitter._report_path(pending)
|
| 560 |
+
with contract.metrics_path.open("a", encoding="utf-8") as stream:
|
| 561 |
+
stream.write("38\n")
|
| 562 |
+
stream.flush()
|
| 563 |
+
os.fsync(stream.fileno())
|
| 564 |
+
emitter.after_metric(first_metric_step=38, learning_rate=1e-4)
|
| 565 |
+
if emitter.pending is not None:
|
| 566 |
+
raise AssertionError("continuity producer did not re-arm after the completed request")
|
| 567 |
+
emitter.capture_pending(
|
| 568 |
+
current_step=38,
|
| 569 |
+
sampler_state=sampler.state_dict(),
|
| 570 |
+
train_rng=train_rng,
|
| 571 |
+
)
|
| 572 |
+
if emitter.pending is not None:
|
| 573 |
+
raise AssertionError("completed continuity request was captured a second time")
|
| 574 |
+
result_queue.put(
|
| 575 |
+
{
|
| 576 |
+
"pid": os.getpid(),
|
| 577 |
+
"request_id": request_id,
|
| 578 |
+
"report": str(report_path),
|
| 579 |
+
}
|
| 580 |
+
)
|
| 581 |
+
except BaseException as exc: # propagated to the controlling smoke process
|
| 582 |
+
failure = {"error": f"{type(exc).__name__}: {exc}", "pid": os.getpid()}
|
| 583 |
+
if not ready_sent:
|
| 584 |
+
ready_queue.put(failure)
|
| 585 |
+
result_queue.put(failure)
|
| 586 |
+
raise
|
| 587 |
+
|
| 588 |
+
|
| 589 |
+
def _paused_resume_continuity_checks(work_dir: Path) -> dict[str, Any]:
|
| 590 |
+
checkpoint_root = work_dir / "pause-checkpoints"
|
| 591 |
+
checkpoint_root.mkdir()
|
| 592 |
+
contract = _contract(checkpoint_root, generation=0, parent=None)
|
| 593 |
+
contract.watch_state_dir.mkdir(parents=True)
|
| 594 |
+
|
| 595 |
+
context = multiprocessing.get_context("spawn")
|
| 596 |
+
ready_queue = context.Queue()
|
| 597 |
+
result_queue = context.Queue()
|
| 598 |
+
resume_gate = context.Event()
|
| 599 |
+
process = context.Process(
|
| 600 |
+
target=_paused_resume_worker,
|
| 601 |
+
args=(contract, ready_queue, resume_gate, result_queue),
|
| 602 |
+
name="picmem-paused-resume-smoke",
|
| 603 |
+
)
|
| 604 |
+
process.start()
|
| 605 |
+
stopped = False
|
| 606 |
+
try:
|
| 607 |
+
ready = ready_queue.get(timeout=30)
|
| 608 |
+
if "error" in ready:
|
| 609 |
+
raise AssertionError(f"paused-resume worker failed before ready: {ready['error']}")
|
| 610 |
+
if ready.get("pid") != process.pid:
|
| 611 |
+
raise AssertionError("paused-resume worker PID changed before suspension")
|
| 612 |
+
os.kill(process.pid, signal.SIGSTOP)
|
| 613 |
+
waited_pid, wait_status = os.waitpid(process.pid, os.WUNTRACED)
|
| 614 |
+
if waited_pid != process.pid or not os.WIFSTOPPED(wait_status):
|
| 615 |
+
raise AssertionError("long-lived trainer did not enter a suspended state")
|
| 616 |
+
stopped = True
|
| 617 |
+
|
| 618 |
+
def resume_in_place(_decision: Any, experiment: str, job: str) -> None:
|
| 619 |
+
state = json.loads(contract.watch_state_dir.joinpath("state.json").read_text(encoding="utf-8"))
|
| 620 |
+
pending = state.get("pending_continuity")
|
| 621 |
+
if (experiment, job) != (contract.experiment, contract.job):
|
| 622 |
+
raise AssertionError("resume callback identity drifted")
|
| 623 |
+
if state.get("generation") != 0 or not isinstance(pending, dict):
|
| 624 |
+
raise AssertionError("paused handoff was not durable before resume")
|
| 625 |
+
if pending.get("mode") != "paused_resume":
|
| 626 |
+
raise AssertionError("paused handoff used the wrong continuity mode")
|
| 627 |
+
if pending.get("resume_step") is not None or pending.get("expected_sampler") is not None:
|
| 628 |
+
raise AssertionError("watchdog guessed a lagging paused checkpoint boundary")
|
| 629 |
+
os.kill(process.pid, signal.SIGCONT)
|
| 630 |
+
resume_gate.set()
|
| 631 |
+
|
| 632 |
+
paused = RemoteStatus(
|
| 633 |
+
contract.experiment,
|
| 634 |
+
contract.job,
|
| 635 |
+
RemoteState.PAUSED,
|
| 636 |
+
FailureOrigin.NONE,
|
| 637 |
+
"",
|
| 638 |
+
5, # deliberately lags the authoritative in-process live step 37
|
| 639 |
+
"",
|
| 640 |
+
)
|
| 641 |
+
first = run_once(
|
| 642 |
+
experiment=contract.experiment,
|
| 643 |
+
job=contract.job,
|
| 644 |
+
status=paused,
|
| 645 |
+
state_dir=contract.watch_state_dir,
|
| 646 |
+
checkpoint_root=checkpoint_root,
|
| 647 |
+
execute=resume_in_place,
|
| 648 |
+
admission_check=lambda _decision: {
|
| 649 |
+
"allowed": True,
|
| 650 |
+
"observed_at": "2026-08-01T00:00:00+00:00",
|
| 651 |
+
"reasons": [],
|
| 652 |
+
},
|
| 653 |
+
)
|
| 654 |
+
stopped = False
|
| 655 |
+
if first.action is not WatchAction.RESUME or first.next_state.generation != 0:
|
| 656 |
+
raise AssertionError("paused job did not resume in place at the same generation")
|
| 657 |
+
|
| 658 |
+
result = result_queue.get(timeout=30)
|
| 659 |
+
if "error" in result:
|
| 660 |
+
raise AssertionError(result["error"])
|
| 661 |
+
process.join(timeout=30)
|
| 662 |
+
if process.exitcode != 0:
|
| 663 |
+
raise AssertionError(f"paused-resume worker exited {process.exitcode}")
|
| 664 |
+
if result.get("pid") != ready.get("pid"):
|
| 665 |
+
raise AssertionError("resume launched a replacement process")
|
| 666 |
+
|
| 667 |
+
report_path = Path(result["report"])
|
| 668 |
+
report = json.loads(report_path.read_text(encoding="utf-8"))
|
| 669 |
+
if report["request_id"] != result["request_id"]:
|
| 670 |
+
raise AssertionError("continuity report was not request-bound")
|
| 671 |
+
if (report["resume_step"], report["first_metric_step"]) != (37, 38):
|
| 672 |
+
raise AssertionError("continuity report did not use the authoritative live next step")
|
| 673 |
+
if report["sampler"] != ready["sampler"] or len(report["rng_sha256"]) != 64:
|
| 674 |
+
raise AssertionError("continuity report omitted sampler/RNG evidence")
|
| 675 |
+
if report["prior_metrics_reused"] is not False:
|
| 676 |
+
raise AssertionError("paused-resume report marked the prior trajectory as reused")
|
| 677 |
+
if contract.metrics_path.read_text(encoding="utf-8").splitlines() != ["step", "37", "38"]:
|
| 678 |
+
raise AssertionError("paused-resume smoke replayed or skipped the metric trajectory")
|
| 679 |
+
|
| 680 |
+
running = RemoteStatus(contract.experiment, contract.job, RemoteState.RUNNING)
|
| 681 |
+
second = run_once(
|
| 682 |
+
experiment=contract.experiment,
|
| 683 |
+
job=contract.job,
|
| 684 |
+
status=running,
|
| 685 |
+
state_dir=contract.watch_state_dir,
|
| 686 |
+
checkpoint_root=checkpoint_root,
|
| 687 |
+
)
|
| 688 |
+
if second.action is not WatchAction.NONE:
|
| 689 |
+
raise AssertionError("verified paused-resume continuity did not return to monitoring")
|
| 690 |
+
if second.next_state.pending_continuity is not None:
|
| 691 |
+
raise AssertionError("verified paused-resume continuity remained pending")
|
| 692 |
+
if second.next_state.last_resume_step != 37:
|
| 693 |
+
raise AssertionError("watchdog did not retain the authoritative live resume step")
|
| 694 |
+
return {
|
| 695 |
+
"pid": result["pid"],
|
| 696 |
+
"generation": second.next_state.generation,
|
| 697 |
+
"resume_step": report["resume_step"],
|
| 698 |
+
"first_metric_step": report["first_metric_step"],
|
| 699 |
+
"request_id": report["request_id"],
|
| 700 |
+
}
|
| 701 |
+
finally:
|
| 702 |
+
if process.is_alive():
|
| 703 |
+
if stopped:
|
| 704 |
+
os.kill(process.pid, signal.SIGCONT)
|
| 705 |
+
resume_gate.set()
|
| 706 |
+
process.terminate()
|
| 707 |
+
process.join(timeout=10)
|
| 708 |
+
|
| 709 |
+
|
| 710 |
+
def run(work_dir: Path) -> dict[str, Any]:
|
| 711 |
+
_topology_checks()
|
| 712 |
+
_arm_binding_checks(work_dir)
|
| 713 |
+
_calibration_binding_checks(work_dir)
|
| 714 |
+
paused_resume = _paused_resume_continuity_checks(work_dir)
|
| 715 |
+
checkpoint_root = work_dir / "checkpoints"
|
| 716 |
+
save_manager, resuming = initialize_phase_a_checkpoint_dir(
|
| 717 |
+
checkpoint_root,
|
| 718 |
+
overwrite=False,
|
| 719 |
+
resume=False,
|
| 720 |
+
launch_kind="synthetic_smoke",
|
| 721 |
+
)
|
| 722 |
+
if resuming:
|
| 723 |
+
raise AssertionError("fresh smoke checkpoint manager unexpectedly resumed")
|
| 724 |
+
|
| 725 |
+
save_contract = _contract(checkpoint_root, generation=0, parent=None)
|
| 726 |
+
contract_path = materialize_phase_a_contract(save_contract, _config(checkpoint_root))
|
| 727 |
+
sampler = PhaseASmokeRandomSampler(
|
| 728 |
+
256,
|
| 729 |
+
batch_size=64,
|
| 730 |
+
seed=(1 << 40) + 9,
|
| 731 |
+
epoch=3,
|
| 732 |
+
batch_cursor=1,
|
| 733 |
+
)
|
| 734 |
+
loader = TinyLoader(sampler)
|
| 735 |
+
train_rng = jax.random.key(123)
|
| 736 |
+
state500 = _state(500, 10.0)
|
| 737 |
+
info500 = save_phase_a_checkpoint(
|
| 738 |
+
save_manager,
|
| 739 |
+
state500,
|
| 740 |
+
loader,
|
| 741 |
+
500,
|
| 742 |
+
contract=save_contract,
|
| 743 |
+
contract_path=contract_path,
|
| 744 |
+
train_rng=train_rng,
|
| 745 |
+
schedule=_schedule,
|
| 746 |
+
)
|
| 747 |
+
sampler.mark_batch_consumed()
|
| 748 |
+
state501 = _state(501, 20.0)
|
| 749 |
+
info501 = save_phase_a_checkpoint(
|
| 750 |
+
save_manager,
|
| 751 |
+
state501,
|
| 752 |
+
loader,
|
| 753 |
+
501,
|
| 754 |
+
contract=save_contract,
|
| 755 |
+
contract_path=contract_path,
|
| 756 |
+
train_rng=train_rng,
|
| 757 |
+
schedule=_schedule,
|
| 758 |
+
)
|
| 759 |
+
sampler.mark_batch_consumed()
|
| 760 |
+
state502 = _state(502, 30.0)
|
| 761 |
+
info502 = save_phase_a_checkpoint(
|
| 762 |
+
save_manager,
|
| 763 |
+
state502,
|
| 764 |
+
loader,
|
| 765 |
+
502,
|
| 766 |
+
contract=save_contract,
|
| 767 |
+
contract_path=contract_path,
|
| 768 |
+
train_rng=train_rng,
|
| 769 |
+
schedule=_schedule,
|
| 770 |
+
)
|
| 771 |
+
save_manager.close()
|
| 772 |
+
if not all((info.path / "_COMPLETE").is_file() for info in (info500, info501, info502)):
|
| 773 |
+
raise AssertionError("full-state smoke did not publish _COMPLETE")
|
| 774 |
+
if not info500.path.is_dir():
|
| 775 |
+
raise AssertionError("explicit Phase-A policy did not retain step 500")
|
| 776 |
+
if not info501.path.is_dir() or not info502.path.is_dir():
|
| 777 |
+
raise AssertionError("explicit Phase-A policy did not retain the latest two checkpoints")
|
| 778 |
+
asset_component = info502.state_manifest.components.get("assets")
|
| 779 |
+
if asset_component is None or asset_component.path != "assets":
|
| 780 |
+
raise AssertionError("full-state smoke did not bind the complete assets tree")
|
| 781 |
+
if asset_component.sha256 != path_sha256(info502.path / "assets"):
|
| 782 |
+
raise AssertionError("full-state smoke assets digest drifted")
|
| 783 |
+
for relative in (
|
| 784 |
+
Path("robomme/norm_stats.json"),
|
| 785 |
+
Path("picmem_phase_a_full_state_contract.json"),
|
| 786 |
+
):
|
| 787 |
+
if not (info502.path / "assets" / relative).is_file():
|
| 788 |
+
raise AssertionError(f"full-state smoke is missing immutable asset {relative}")
|
| 789 |
+
|
| 790 |
+
cold_discovery_root = work_dir / "cold-discovery-negative"
|
| 791 |
+
shutil.copytree(checkpoint_root, cold_discovery_root)
|
| 792 |
+
incomplete_newest = cold_discovery_root / "502"
|
| 793 |
+
(incomplete_newest / "_COMPLETE").unlink()
|
| 794 |
+
_expect_checkpoint_reopen_rejected(cold_discovery_root, "incomplete newest numeric checkpoint")
|
| 795 |
+
|
| 796 |
+
restore_manager, cold_resuming = initialize_phase_a_checkpoint_dir(
|
| 797 |
+
checkpoint_root,
|
| 798 |
+
overwrite=False,
|
| 799 |
+
resume=True,
|
| 800 |
+
launch_kind="synthetic_smoke",
|
| 801 |
+
)
|
| 802 |
+
if not cold_resuming:
|
| 803 |
+
restore_manager.close()
|
| 804 |
+
raise AssertionError("freshly reopened checkpoint manager did not discover finalized state")
|
| 805 |
+
|
| 806 |
+
restore_sampler = PhaseASmokeRandomSampler(256, batch_size=64, seed=(1 << 40) + 9)
|
| 807 |
+
restore_loader = TinyLoader(restore_sampler)
|
| 808 |
+
restore_contract = _contract(
|
| 809 |
+
checkpoint_root,
|
| 810 |
+
generation=1,
|
| 811 |
+
parent=info502.metadata_sha256,
|
| 812 |
+
)
|
| 813 |
+
try:
|
| 814 |
+
restored, restored_rng, restored_sampler_state, restored_info = restore_phase_a_checkpoint(
|
| 815 |
+
restore_manager,
|
| 816 |
+
_state(0, -100.0),
|
| 817 |
+
restore_loader,
|
| 818 |
+
contract=restore_contract,
|
| 819 |
+
train_rng=jax.random.key(999),
|
| 820 |
+
schedule=_schedule,
|
| 821 |
+
step=502,
|
| 822 |
+
)
|
| 823 |
+
finally:
|
| 824 |
+
restore_manager.close()
|
| 825 |
+
if int(np.asarray(jax.device_get(restored.step))) != 502:
|
| 826 |
+
raise AssertionError("authoritative step did not round-trip")
|
| 827 |
+
for name in ("params", "ema_params", "opt_state"):
|
| 828 |
+
if not _tree_equal(getattr(restored, name), getattr(state502, name)):
|
| 829 |
+
raise AssertionError(f"{name} did not round-trip")
|
| 830 |
+
if not np.array_equal(jax.random.key_data(restored_rng), jax.random.key_data(train_rng)):
|
| 831 |
+
raise AssertionError("JAX train RNG did not round-trip")
|
| 832 |
+
if restored_sampler_state != loader.sampler_state_dict():
|
| 833 |
+
raise AssertionError("sampler state did not round-trip")
|
| 834 |
+
if restore_loader.sampler_state_dict() != loader.sampler_state_dict():
|
| 835 |
+
raise AssertionError("restored sampler was not installed in the loader")
|
| 836 |
+
if restored_info.metadata_sha256 != info502.metadata_sha256:
|
| 837 |
+
raise AssertionError("restored checkpoint identity drifted")
|
| 838 |
+
|
| 839 |
+
variants = work_dir / "negative"
|
| 840 |
+
missing_complete = variants / "missing-complete"
|
| 841 |
+
corrupt_metadata = variants / "corrupt-metadata"
|
| 842 |
+
mutated_state = variants / "mutated-state"
|
| 843 |
+
mutated_asset = variants / "mutated-asset"
|
| 844 |
+
added_asset = variants / "added-asset"
|
| 845 |
+
for destination in (
|
| 846 |
+
missing_complete,
|
| 847 |
+
corrupt_metadata,
|
| 848 |
+
mutated_state,
|
| 849 |
+
mutated_asset,
|
| 850 |
+
added_asset,
|
| 851 |
+
):
|
| 852 |
+
shutil.copytree(info502.path, destination)
|
| 853 |
+
(missing_complete / "_COMPLETE").unlink()
|
| 854 |
+
(corrupt_metadata / "picmem_full_state.json").write_text("not-json\n", encoding="utf-8")
|
| 855 |
+
_mutate_state(mutated_state)
|
| 856 |
+
with (mutated_asset / "assets" / "picmem_phase_a_full_state_contract.json").open("ab") as stream:
|
| 857 |
+
stream.write(b"corruption")
|
| 858 |
+
(added_asset / "assets" / "unexpected-runtime-asset.json").write_text(
|
| 859 |
+
"{}\n",
|
| 860 |
+
encoding="utf-8",
|
| 861 |
+
)
|
| 862 |
+
_expect_rejected(lambda: validate_checkpoint(missing_complete), "missing _COMPLETE")
|
| 863 |
+
_expect_rejected(lambda: validate_checkpoint(corrupt_metadata), "corrupt metadata")
|
| 864 |
+
_expect_rejected(lambda: validate_checkpoint(mutated_state), "post-finalization state mutation")
|
| 865 |
+
_expect_rejected(lambda: validate_checkpoint(mutated_asset), "immutable asset mutation")
|
| 866 |
+
_expect_rejected(lambda: validate_checkpoint(added_asset), "unmanifested asset addition")
|
| 867 |
+
return {
|
| 868 |
+
"schema_version": "picmem_phase_a_full_state_smoke_v1",
|
| 869 |
+
"status": "PASS",
|
| 870 |
+
"saved_steps": [500, 501, 502],
|
| 871 |
+
"restored_step": 502,
|
| 872 |
+
"sampler": restored_sampler_state,
|
| 873 |
+
"milestone_retained": True,
|
| 874 |
+
"cold_reopen_restore": True,
|
| 875 |
+
"arm_binding_revalidated": True,
|
| 876 |
+
"paused_resume_continuity": paused_resume,
|
| 877 |
+
"negative_cases": [
|
| 878 |
+
"missing_complete",
|
| 879 |
+
"corrupt_metadata",
|
| 880 |
+
"mutated_state",
|
| 881 |
+
"mutated_asset",
|
| 882 |
+
"added_asset",
|
| 883 |
+
"cold_reopen_incomplete_newest",
|
| 884 |
+
"wrong_world",
|
| 885 |
+
"wrong_fsdp",
|
| 886 |
+
"wrong_batch",
|
| 887 |
+
"wrong_sku",
|
| 888 |
+
"arm_factor_drift",
|
| 889 |
+
"duplicate_arm_key",
|
| 890 |
+
"yaml_selection_mode_drift",
|
| 891 |
+
"yaml_metadata_mode_drift",
|
| 892 |
+
"yaml_reader_mode_drift",
|
| 893 |
+
"yaml_manager_mode_drift",
|
| 894 |
+
"yaml_missing_factor",
|
| 895 |
+
"yaml_unknown_factor",
|
| 896 |
+
"yaml_legacy_defaults",
|
| 897 |
+
],
|
| 898 |
+
}
|
| 899 |
+
|
| 900 |
+
|
| 901 |
+
def main() -> int:
|
| 902 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 903 |
+
parser.add_argument("--work-dir", type=Path)
|
| 904 |
+
args = parser.parse_args()
|
| 905 |
+
if args.work_dir is None:
|
| 906 |
+
with tempfile.TemporaryDirectory(prefix="picmem-phase-a-full-state-") as temporary:
|
| 907 |
+
report = run(Path(temporary))
|
| 908 |
+
else:
|
| 909 |
+
work_dir = args.work_dir.expanduser().resolve()
|
| 910 |
+
if work_dir.exists() or work_dir.is_symlink():
|
| 911 |
+
raise FileExistsError(f"refusing to reuse smoke work directory: {work_dir}")
|
| 912 |
+
work_dir.mkdir(parents=True)
|
| 913 |
+
report = run(work_dir)
|
| 914 |
+
print(json.dumps(report, sort_keys=True))
|
| 915 |
+
return 0
|
| 916 |
+
|
| 917 |
+
|
| 918 |
+
if __name__ == "__main__":
|
| 919 |
+
raise SystemExit(main())
|
checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/scripts/picmem_phase_a_full_state_train.py
ADDED
|
@@ -0,0 +1,347 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Dedicated eight-GPU Phase-A trainer with trajectory-complete resume."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import dataclasses
|
| 7 |
+
import functools
|
| 8 |
+
import importlib.util
|
| 9 |
+
import json
|
| 10 |
+
import logging
|
| 11 |
+
import math
|
| 12 |
+
import os
|
| 13 |
+
import sys
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
from typing import Any
|
| 16 |
+
|
| 17 |
+
import jax
|
| 18 |
+
import jax.numpy as jnp
|
| 19 |
+
import mme_vla_suite.training.config as _config
|
| 20 |
+
import numpy as np
|
| 21 |
+
import openpi.training.sharding as sharding
|
| 22 |
+
import openpi.training.utils as training_utils
|
| 23 |
+
from flax.training import common_utils
|
| 24 |
+
from mme_vla_suite.training.picmem_phase_a_full_state import (
|
| 25 |
+
PHASE_A_HISTORY_CONFIG,
|
| 26 |
+
ContinuityEmitter,
|
| 27 |
+
PhaseAContract,
|
| 28 |
+
PhaseAMetricWriter,
|
| 29 |
+
create_phase_a_data_loader,
|
| 30 |
+
initialize_phase_a_checkpoint_dir,
|
| 31 |
+
materialize_phase_a_contract,
|
| 32 |
+
restore_phase_a_checkpoint,
|
| 33 |
+
save_phase_a_checkpoint,
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
CANONICAL_TRAIN_STEPS = 80_000
|
| 37 |
+
SKU_SMOKE_TRAIN_STEPS = 100
|
| 38 |
+
SKU_SMOKE_SAVE_INTERVAL = 25
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _load_host_train_module() -> Any:
|
| 42 |
+
path = Path(__file__).resolve().with_name("train.py")
|
| 43 |
+
spec = importlib.util.spec_from_file_location("picmem_phase_a_pinned_host_train", path)
|
| 44 |
+
if spec is None or spec.loader is None:
|
| 45 |
+
raise RuntimeError(f"cannot import pinned host trainer: {path}")
|
| 46 |
+
module = importlib.util.module_from_spec(spec)
|
| 47 |
+
spec.loader.exec_module(module)
|
| 48 |
+
return module
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
_host_train = _load_host_train_module()
|
| 52 |
+
_ORIGINAL_POST_INIT = _config.TrainConfig.__post_init__
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _is_phase_a_config(config: _config.TrainConfig) -> bool:
|
| 56 |
+
history = config.model.history_config
|
| 57 |
+
return (
|
| 58 |
+
config.name == "mme_vla_suite"
|
| 59 |
+
and isinstance(history, str)
|
| 60 |
+
and Path(history).name == PHASE_A_HISTORY_CONFIG
|
| 61 |
+
and config.typed_stage is None
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _launch_kind() -> str:
|
| 66 |
+
value = os.environ.get("PICMEM_PHASE_A_LAUNCH_KIND", "")
|
| 67 |
+
if value not in {"formal", "sku_smoke"}:
|
| 68 |
+
raise ValueError("PICMEM_PHASE_A_LAUNCH_KIND must be formal or sku_smoke")
|
| 69 |
+
return value
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def _runtime_positive_int(name: str) -> int:
|
| 73 |
+
value = os.environ.get(name, "")
|
| 74 |
+
if not value.isascii() or not value.isdigit() or value == "0" or str(int(value)) != value:
|
| 75 |
+
raise ValueError(f"{name} must be a canonical positive integer")
|
| 76 |
+
return int(value)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _runtime_batch_size() -> int:
|
| 80 |
+
batch_size = _runtime_positive_int("BATCH_SIZE")
|
| 81 |
+
if batch_size % 4:
|
| 82 |
+
raise ValueError("BATCH_SIZE must be divisible by the four Run084 tasks")
|
| 83 |
+
return batch_size
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def _validate_phase_a_config(
|
| 87 |
+
config: _config.TrainConfig,
|
| 88 |
+
*,
|
| 89 |
+
launch_kind: str | None = None,
|
| 90 |
+
) -> None:
|
| 91 |
+
launch_kind = _launch_kind() if launch_kind is None else launch_kind
|
| 92 |
+
if launch_kind not in {"formal", "sku_smoke"}:
|
| 93 |
+
raise ValueError("Phase-A launch_kind is unsupported")
|
| 94 |
+
if not _is_phase_a_config(config):
|
| 95 |
+
raise ValueError("dedicated Phase-A entry accepts only mme_vla_suite with the reviewed history config")
|
| 96 |
+
if not config.full_state_checkpoints:
|
| 97 |
+
raise ValueError("Phase-A training requires full_state_checkpoints")
|
| 98 |
+
runtime_batch_size = _runtime_batch_size()
|
| 99 |
+
if config.batch_size != runtime_batch_size:
|
| 100 |
+
raise ValueError(f"Phase-A TrainConfig batch differs from runtime BATCH_SIZE={runtime_batch_size}")
|
| 101 |
+
if config.fsdp_devices != 8:
|
| 102 |
+
raise ValueError("Phase-A training requires exactly eight FSDP devices")
|
| 103 |
+
expected_steps = CANONICAL_TRAIN_STEPS if launch_kind == "formal" else SKU_SMOKE_TRAIN_STEPS
|
| 104 |
+
if config.num_train_steps != expected_steps:
|
| 105 |
+
raise ValueError(f"Phase-A {launch_kind} must end at step {expected_steps}")
|
| 106 |
+
if config.ema_decay is None:
|
| 107 |
+
raise ValueError("Phase-A trajectory-complete state requires EMA parameters")
|
| 108 |
+
if config.overwrite or config.warm_start_checkpoint is not None:
|
| 109 |
+
raise ValueError("Phase-A formal training forbids overwrite and params-only warm start")
|
| 110 |
+
if config.resume != (config.resum_ckpt_id is not None):
|
| 111 |
+
raise ValueError("Phase-A resume and resum_ckpt_id must be supplied together")
|
| 112 |
+
if config.resum_ckpt_id is not None and not 0 < config.resum_ckpt_id < expected_steps:
|
| 113 |
+
raise ValueError("Phase-A resume checkpoint step must be within the selected launch kind")
|
| 114 |
+
if config.save_interval <= 0:
|
| 115 |
+
raise ValueError("Phase-A save_interval must be positive")
|
| 116 |
+
if config.keep_period != 5_000:
|
| 117 |
+
raise ValueError("Phase-A requires the reviewed 5,000-step milestone period")
|
| 118 |
+
if launch_kind == "formal" and any(step % config.save_interval for step in (500, 1_000, 2_000, 5_000, 10_000)):
|
| 119 |
+
raise ValueError("Phase-A save_interval must materialize every required early milestone")
|
| 120 |
+
if launch_kind == "sku_smoke" and config.save_interval != SKU_SMOKE_SAVE_INTERVAL:
|
| 121 |
+
raise ValueError(f"Phase-A sku_smoke save_interval must equal {SKU_SMOKE_SAVE_INTERVAL}")
|
| 122 |
+
if config.log_interval <= 0:
|
| 123 |
+
raise ValueError("Phase-A log_interval must be positive")
|
| 124 |
+
if config.metrics_path is None:
|
| 125 |
+
raise ValueError("Phase-A requires one exclusive generation metrics path")
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def _phase_a_post_init(config: _config.TrainConfig) -> None:
|
| 129 |
+
bypass_typed_only_gate = _is_phase_a_config(config) and config.full_state_checkpoints
|
| 130 |
+
if not bypass_typed_only_gate:
|
| 131 |
+
_ORIGINAL_POST_INIT(config)
|
| 132 |
+
return
|
| 133 |
+
object.__setattr__(config, "full_state_checkpoints", False)
|
| 134 |
+
try:
|
| 135 |
+
_ORIGINAL_POST_INIT(config)
|
| 136 |
+
finally:
|
| 137 |
+
object.__setattr__(config, "full_state_checkpoints", True)
|
| 138 |
+
_validate_phase_a_config(config)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def _install_phase_a_config_gate() -> None:
|
| 142 |
+
if _config.TrainConfig.__post_init__ is not _phase_a_post_init:
|
| 143 |
+
_config.TrainConfig.__post_init__ = _phase_a_post_init
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def _learning_rate(schedule: Any, step: int) -> float:
|
| 147 |
+
value = float(np.asarray(jax.device_get(schedule(step))))
|
| 148 |
+
if not math.isfinite(value) or value <= 0:
|
| 149 |
+
raise ValueError(f"Phase-A learning rate must be finite and positive, got {value}")
|
| 150 |
+
return value
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def capability_probe() -> int:
|
| 154 |
+
_install_phase_a_config_gate()
|
| 155 |
+
base = _config.get_config("mme_vla_suite")
|
| 156 |
+
model = dataclasses.replace(base.model, history_config=PHASE_A_HISTORY_CONFIG)
|
| 157 |
+
launch_kind = _launch_kind()
|
| 158 |
+
batch_size = _runtime_batch_size()
|
| 159 |
+
steps = CANONICAL_TRAIN_STEPS if launch_kind == "formal" else SKU_SMOKE_TRAIN_STEPS
|
| 160 |
+
save_interval = _runtime_positive_int("SAVE_INTERVAL")
|
| 161 |
+
candidate = dataclasses.replace(
|
| 162 |
+
base,
|
| 163 |
+
model=model,
|
| 164 |
+
exp_name=f"phase-a-{launch_kind}-capability-probe",
|
| 165 |
+
batch_size=batch_size,
|
| 166 |
+
fsdp_devices=8,
|
| 167 |
+
full_state_checkpoints=True,
|
| 168 |
+
num_train_steps=steps,
|
| 169 |
+
save_interval=save_interval,
|
| 170 |
+
keep_period=5_000,
|
| 171 |
+
metrics_path=f"probe/{launch_kind}/attempts/generation-0/metrics.tsv",
|
| 172 |
+
)
|
| 173 |
+
_validate_phase_a_config(candidate, launch_kind=launch_kind)
|
| 174 |
+
print(
|
| 175 |
+
json.dumps(
|
| 176 |
+
{
|
| 177 |
+
"schema_version": "picmem_phase_a_host_capability_v2",
|
| 178 |
+
"status": "PASS",
|
| 179 |
+
"launch_kind": launch_kind,
|
| 180 |
+
"batch_size": batch_size,
|
| 181 |
+
"fsdp_devices": 8,
|
| 182 |
+
"full_state_checkpoints": True,
|
| 183 |
+
"num_train_steps": candidate.num_train_steps,
|
| 184 |
+
"save_interval": candidate.save_interval,
|
| 185 |
+
},
|
| 186 |
+
sort_keys=True,
|
| 187 |
+
)
|
| 188 |
+
)
|
| 189 |
+
return 0
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def run(config: _config.TrainConfig) -> None:
|
| 193 |
+
launch_kind = _launch_kind()
|
| 194 |
+
if launch_kind == "formal" and os.environ.get("PICMEM_FORMAL_LAUNCH") != "1":
|
| 195 |
+
raise ValueError("formal Phase-A training requires PICMEM_FORMAL_LAUNCH=1")
|
| 196 |
+
if launch_kind == "sku_smoke" and os.environ.get("PICMEM_FORMAL_LAUNCH"):
|
| 197 |
+
raise ValueError("sku_smoke cannot carry the formal-launch authorization marker")
|
| 198 |
+
_validate_phase_a_config(config, launch_kind=launch_kind)
|
| 199 |
+
_host_train.init_logging()
|
| 200 |
+
logging.info("Phase-A TrainConfig: %s", config)
|
| 201 |
+
|
| 202 |
+
jax.config.update(
|
| 203 |
+
"jax_compilation_cache_dir",
|
| 204 |
+
str(Path(f"~/.cache/jax_{config.exp_name}").expanduser()),
|
| 205 |
+
)
|
| 206 |
+
rng = jax.random.key(config.seed)
|
| 207 |
+
train_rng, init_rng = jax.random.split(rng)
|
| 208 |
+
mesh = sharding.make_mesh(config.fsdp_devices)
|
| 209 |
+
data_sharding = jax.sharding.NamedSharding(
|
| 210 |
+
mesh,
|
| 211 |
+
jax.sharding.PartitionSpec(sharding.DATA_AXIS),
|
| 212 |
+
)
|
| 213 |
+
replicated_sharding = jax.sharding.NamedSharding(mesh, jax.sharding.PartitionSpec())
|
| 214 |
+
|
| 215 |
+
checkpoint_manager, resuming = initialize_phase_a_checkpoint_dir(
|
| 216 |
+
config.checkpoint_dir,
|
| 217 |
+
overwrite=False,
|
| 218 |
+
resume=config.resume,
|
| 219 |
+
launch_kind=launch_kind,
|
| 220 |
+
)
|
| 221 |
+
if resuming != config.resume:
|
| 222 |
+
raise ValueError("Phase-A requested resume state differs from the checkpoint manager")
|
| 223 |
+
contract = PhaseAContract.from_environment(config)
|
| 224 |
+
contract_path = materialize_phase_a_contract(contract, config)
|
| 225 |
+
_host_train.init_wandb(config, resuming=resuming, enabled=config.wandb_enabled)
|
| 226 |
+
|
| 227 |
+
data_config = config.data.create(config.assets_dirs, config.model)
|
| 228 |
+
data_loader = create_phase_a_data_loader(
|
| 229 |
+
config.dataset_path,
|
| 230 |
+
data_config,
|
| 231 |
+
config.model.history_config,
|
| 232 |
+
config.model.action_horizon,
|
| 233 |
+
config.batch_size,
|
| 234 |
+
sharding=data_sharding,
|
| 235 |
+
num_workers=config.num_workers,
|
| 236 |
+
prefetch_factor=contract.prefetch_factor,
|
| 237 |
+
seed=config.sampler_seed if config.sampler_seed is not None else config.seed,
|
| 238 |
+
subset_manifest_sha256=contract.dataset_sha256,
|
| 239 |
+
sidecar_sha256=contract.sidecar_sha256,
|
| 240 |
+
sample_order_path=contract.sample_order_path,
|
| 241 |
+
sample_order_manifest_sha256=contract.sample_order_manifest_sha256,
|
| 242 |
+
sample_order_sha256=contract.sample_order_sha256,
|
| 243 |
+
)
|
| 244 |
+
train_state, train_state_sharding = _host_train.init_train_state(
|
| 245 |
+
config,
|
| 246 |
+
init_rng,
|
| 247 |
+
mesh,
|
| 248 |
+
resume=False,
|
| 249 |
+
)
|
| 250 |
+
schedule = config.lr_schedule.create()
|
| 251 |
+
if resuming:
|
| 252 |
+
train_state, train_rng, _, _ = restore_phase_a_checkpoint(
|
| 253 |
+
checkpoint_manager,
|
| 254 |
+
train_state,
|
| 255 |
+
data_loader,
|
| 256 |
+
contract=contract,
|
| 257 |
+
train_rng=train_rng,
|
| 258 |
+
schedule=schedule,
|
| 259 |
+
step=int(config.resum_ckpt_id),
|
| 260 |
+
)
|
| 261 |
+
jax.block_until_ready(train_state)
|
| 262 |
+
start_step = int(np.asarray(jax.device_get(train_state.step)))
|
| 263 |
+
if start_step >= config.num_train_steps:
|
| 264 |
+
raise ValueError("Phase-A checkpoint is already at or beyond the canonical final step")
|
| 265 |
+
|
| 266 |
+
continuity = ContinuityEmitter(contract, contract.metrics_path)
|
| 267 |
+
continuity.capture_pending(
|
| 268 |
+
current_step=start_step,
|
| 269 |
+
sampler_state=data_loader.sampler_state_dict(),
|
| 270 |
+
train_rng=train_rng,
|
| 271 |
+
)
|
| 272 |
+
ptrain_step = jax.jit(
|
| 273 |
+
functools.partial(_host_train.train_step, config),
|
| 274 |
+
in_shardings=(replicated_sharding, train_state_sharding, data_sharding),
|
| 275 |
+
out_shardings=(train_state_sharding, replicated_sharding, replicated_sharding),
|
| 276 |
+
donate_argnums=(1,),
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
data_iter = iter(data_loader)
|
| 280 |
+
with PhaseAMetricWriter(contract.metrics_path) as metric_writer:
|
| 281 |
+
while int(np.asarray(jax.device_get(train_state.step))) < config.num_train_steps:
|
| 282 |
+
continuity.capture_pending(
|
| 283 |
+
current_step=int(np.asarray(jax.device_get(train_state.step))),
|
| 284 |
+
sampler_state=data_loader.sampler_state_dict(),
|
| 285 |
+
train_rng=train_rng,
|
| 286 |
+
)
|
| 287 |
+
batch = next(data_iter)
|
| 288 |
+
previous_step = int(np.asarray(jax.device_get(train_state.step)))
|
| 289 |
+
with sharding.set_mesh(mesh):
|
| 290 |
+
train_state, info, stats = ptrain_step(train_rng, train_state, batch)
|
| 291 |
+
authoritative_step = int(np.asarray(jax.device_get(train_state.step)))
|
| 292 |
+
if authoritative_step != previous_step + 1:
|
| 293 |
+
raise RuntimeError("Phase-A train step did not advance exactly once")
|
| 294 |
+
learning_rate = _learning_rate(schedule, previous_step)
|
| 295 |
+
scalar_info = jax.device_get(jax.tree.map(jnp.mean, info))
|
| 296 |
+
metric_writer.write(
|
| 297 |
+
step=authoritative_step,
|
| 298 |
+
learning_rate=learning_rate,
|
| 299 |
+
metrics=scalar_info,
|
| 300 |
+
)
|
| 301 |
+
continuity.after_metric(
|
| 302 |
+
first_metric_step=authoritative_step,
|
| 303 |
+
learning_rate=learning_rate,
|
| 304 |
+
)
|
| 305 |
+
if authoritative_step == start_step + 1 or authoritative_step % config.log_interval == 0:
|
| 306 |
+
_host_train.wandb.log(scalar_info, step=authoritative_step)
|
| 307 |
+
logging.info(
|
| 308 |
+
"Phase-A step=%d metrics=%s",
|
| 309 |
+
authoritative_step,
|
| 310 |
+
common_utils.stack_forest([scalar_info]),
|
| 311 |
+
)
|
| 312 |
+
if stats:
|
| 313 |
+
jax.block_until_ready(stats)
|
| 314 |
+
if authoritative_step % config.save_interval == 0 or authoritative_step == config.num_train_steps:
|
| 315 |
+
logging.info("PICMEM_CHECKPOINT_SAVE_START step=%d", authoritative_step)
|
| 316 |
+
save_phase_a_checkpoint(
|
| 317 |
+
checkpoint_manager,
|
| 318 |
+
train_state,
|
| 319 |
+
data_loader,
|
| 320 |
+
authoritative_step,
|
| 321 |
+
contract=contract,
|
| 322 |
+
contract_path=contract_path,
|
| 323 |
+
train_rng=train_rng,
|
| 324 |
+
schedule=schedule,
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
checkpoint_manager.wait_until_finished()
|
| 328 |
+
final_step = int(np.asarray(jax.device_get(train_state.step)))
|
| 329 |
+
expected_final = CANONICAL_TRAIN_STEPS if launch_kind == "formal" else SKU_SMOKE_TRAIN_STEPS
|
| 330 |
+
if final_step != expected_final:
|
| 331 |
+
raise RuntimeError(f"Phase-A {launch_kind} stopped at unexpected step {final_step}")
|
| 332 |
+
logging.info("PICMEM_PHASE_A_TRAIN_COMPLETE kind=%s step=%d", launch_kind, final_step)
|
| 333 |
+
logging.info("Final state: %s", training_utils.array_tree_to_info(train_state.params))
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def main() -> int:
|
| 337 |
+
if sys.argv[1:] == ["--phase-a-capability-probe"]:
|
| 338 |
+
return capability_probe()
|
| 339 |
+
if "--phase-a-capability-probe" in sys.argv[1:]:
|
| 340 |
+
raise SystemExit("--phase-a-capability-probe cannot be combined with training arguments")
|
| 341 |
+
_install_phase_a_config_gate()
|
| 342 |
+
run(_config.cli())
|
| 343 |
+
return 0
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
if __name__ == "__main__":
|
| 347 |
+
raise SystemExit(main())
|
checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/models/config/robomme/perceptual-picmem-phase-a-modul.yaml
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Phase-A: task/status-conditioned evidence retention with the unchanged
|
| 2 |
+
# FrameSamp+Modul feature encoder. Structured memory remains control-plane
|
| 3 |
+
# only; the policy sees exactly 512 visual/position/state tokens.
|
| 4 |
+
budget: 512
|
| 5 |
+
num_views: 1
|
| 6 |
+
token_per_image: 16
|
| 7 |
+
streaming_obs_horizon: 16
|
| 8 |
+
pool_type: mean
|
| 9 |
+
use_pos_emb: true
|
| 10 |
+
use_state_emb: false
|
| 11 |
+
memory_feature:
|
| 12 |
+
img:
|
| 13 |
+
net: identity
|
| 14 |
+
input_dim: 2048
|
| 15 |
+
pos:
|
| 16 |
+
input_dim: 768
|
| 17 |
+
hidden_dim: 768
|
| 18 |
+
state:
|
| 19 |
+
input_dim: 8
|
| 20 |
+
hidden_dim: 512
|
| 21 |
+
integration_type: modulation
|
| 22 |
+
memory_token_dim: 1024
|
| 23 |
+
representation_type: perceptual
|
| 24 |
+
perceptual_memory:
|
| 25 |
+
type: frame_sampling
|
| 26 |
+
frame_selection:
|
| 27 |
+
type: picmem_phase_a
|
| 28 |
+
sidecar_dir: ${oc.env:PICMEM_PHASE_A_SIDECAR_DIR}
|
| 29 |
+
subset_manifest_path: ${oc.env:PICMEM_PHASE_A_SUBSET_MANIFEST}
|
| 30 |
+
subset_manifest_sha256: ${oc.env:PICMEM_PHASE_A_SUBSET_MANIFEST_SHA256}
|
| 31 |
+
replacement_manifest_path: ${oc.env:PICMEM_PHASE_A_REPLACEMENT_MANIFEST}
|
| 32 |
+
replacement_manifest_sha256: ${oc.env:PICMEM_PHASE_A_REPLACEMENT_MANIFEST_SHA256}
|
| 33 |
+
best_visible_manifest_path: ${oc.env:PICMEM_PHASE_A_BEST_VISIBLE_MANIFEST}
|
| 34 |
+
best_visible_manifest_sha256: ${oc.env:PICMEM_PHASE_A_BEST_VISIBLE_MANIFEST_SHA256}
|
| 35 |
+
frame_budget: 32
|
| 36 |
+
recent_anchor_count: 4
|
| 37 |
+
# Formal factors are supplied by the hash-bound ArmManifest launcher. There
|
| 38 |
+
# are deliberately no defaults: missing environment bindings fail config
|
| 39 |
+
# resolution before dataset construction.
|
| 40 |
+
require_explicit_factors: true
|
| 41 |
+
selection_mode: ${oc.env:PICMEM_PHASE_A_SELECTION_MODE}
|
| 42 |
+
metadata_mode: ${oc.env:PICMEM_PHASE_A_METADATA_MODE}
|
| 43 |
+
reader_mode: ${oc.env:PICMEM_PHASE_A_READER_MODE}
|
| 44 |
+
manager_mode: ${oc.env:PICMEM_PHASE_A_MANAGER_MODE}
|
| 45 |
+
metadata_seed: 0
|
| 46 |
+
phase_a_reader:
|
| 47 |
+
event_vocab_size: 4096
|
| 48 |
+
event_ordinal_vocab_size: 128
|
| 49 |
+
contract_vocab_size: 128
|
| 50 |
+
status_vocab_size: 32
|
| 51 |
+
categorical_embed_dim: 32
|
| 52 |
+
numeric_hidden_dim: 128
|
| 53 |
+
fusion_hidden_dim: 256
|
checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/models/config/robomme/perceptual-picmem-transition-v1-modul.yaml
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# PIC-Mem + conditional final-span semantic-transition Status Head (v2).
|
| 2 |
+
#
|
| 3 |
+
# Action proposal horizon remains 20 in HistoryPi0. The Status Head sees only
|
| 4 |
+
# the first 16 actions that the evaluator can actually execute. Its learned
|
| 5 |
+
# history is a single masked pooling operation over the latest 48 realized
|
| 6 |
+
# action/state deltas; it never changes the Action Head input.
|
| 7 |
+
budget: 64
|
| 8 |
+
num_views: 1
|
| 9 |
+
token_per_image: 16
|
| 10 |
+
streaming_obs_horizon: 16
|
| 11 |
+
pool_type: mean
|
| 12 |
+
use_pos_emb: false
|
| 13 |
+
use_state_emb: false
|
| 14 |
+
memory_feature:
|
| 15 |
+
img:
|
| 16 |
+
net: identity
|
| 17 |
+
input_dim: 2048
|
| 18 |
+
pos:
|
| 19 |
+
input_dim: 768
|
| 20 |
+
hidden_dim: 768
|
| 21 |
+
state:
|
| 22 |
+
input_dim: 8
|
| 23 |
+
hidden_dim: 512
|
| 24 |
+
integration_type: modulation
|
| 25 |
+
memory_token_dim: 1024
|
| 26 |
+
representation_type: perceptual
|
| 27 |
+
perceptual_memory:
|
| 28 |
+
type: picmem
|
| 29 |
+
hidden_dim: 256
|
| 30 |
+
token_feature_dim: 12
|
| 31 |
+
max_contracts: 8
|
| 32 |
+
annotation_dir: ${oc.env:PICMEM_ANNOTATION_DIR,null}
|
| 33 |
+
# The launcher must validate a real sidecar root before training starts.
|
| 34 |
+
# Once that root is present, rows outside the four run084 prototypes may
|
| 35 |
+
# legitimately have no sidecar and receive an empty-memory tensor.
|
| 36 |
+
allow_missing_annotations: true
|
| 37 |
+
include_values: false
|
| 38 |
+
include_write_metadata: false
|
| 39 |
+
|
| 40 |
+
static_semantic_memory:
|
| 41 |
+
enabled: true
|
| 42 |
+
annotation_dir: ${oc.env:PICMEM_STAGE4_ROOT,null}
|
| 43 |
+
|
| 44 |
+
transition_status:
|
| 45 |
+
# v2 changes the checkpoint parameter tree from span_out[1] to status_out[2].
|
| 46 |
+
# It must never be loaded as a v1 Status Head checkpoint.
|
| 47 |
+
schema_version: picmem_transition_status_v2
|
| 48 |
+
enabled: true
|
| 49 |
+
# Stage-3 v1 provides reviewed coarse action intervals and their endpoints.
|
| 50 |
+
# The primary target remains chunk-level span membership; a small conditional
|
| 51 |
+
# endpoint loss lets the controller verify immediately after the final span.
|
| 52 |
+
objective: coarse_span_with_conditional_last
|
| 53 |
+
action_proposal_horizon: 20
|
| 54 |
+
execution_horizon: 16
|
| 55 |
+
context_horizon: 48
|
| 56 |
+
robot_vector_dim: 8
|
| 57 |
+
context_hidden_dim: 128
|
| 58 |
+
span_loss_weight: 1.0
|
| 59 |
+
last_span_loss_weight: 0.5
|
| 60 |
+
# Shadow-mode identity calibration. Replace this with the held-out fitted
|
| 61 |
+
# temperature before authorizing writer commits.
|
| 62 |
+
status_temperature: 1.0
|
| 63 |
+
# This is a shadow-mode default only. Before enabling Gemini commits, fit a
|
| 64 |
+
# temperature and choose the lowest held-out threshold reaching >=90%
|
| 65 |
+
# precision. If that precision is unreachable, remain in shadow mode.
|
| 66 |
+
span_threshold: 0.5
|
| 67 |
+
last_span_threshold: 0.5
|
| 68 |
+
confirmation_tail: 4
|
| 69 |
+
cooldown_chunks: 1
|
| 70 |
+
# Required by the training dataset only. The policy server is stateless and
|
| 71 |
+
# receives realized context arrays with each request.
|
| 72 |
+
training_manifest_path: ${oc.env:PICMEM_TRANSITION_MANIFEST,null}
|
| 73 |
+
training_manifest_sha256: ${oc.env:PICMEM_TRANSITION_MANIFEST_SHA256,null}
|
checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/models/config/robomme/perceptual-picmem-v2-stage4-hybrid-modul.yaml
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# PICMem v2: Stage4-guided selection over the validated Hybrid-512 memory.
|
| 2 |
+
budget: 512
|
| 3 |
+
num_views: 1
|
| 4 |
+
token_per_image: 16
|
| 5 |
+
streaming_obs_horizon: 16
|
| 6 |
+
pool_type: mean
|
| 7 |
+
use_pos_emb: true
|
| 8 |
+
use_state_emb: true
|
| 9 |
+
|
| 10 |
+
memory_feature:
|
| 11 |
+
img:
|
| 12 |
+
net: identity
|
| 13 |
+
input_dim: 2048
|
| 14 |
+
pos:
|
| 15 |
+
input_dim: 768
|
| 16 |
+
hidden_dim: 768
|
| 17 |
+
state:
|
| 18 |
+
input_dim: 8
|
| 19 |
+
hidden_dim: 512
|
| 20 |
+
|
| 21 |
+
integration_type: modulation
|
| 22 |
+
memory_token_dim: 1024
|
| 23 |
+
representation_type: perceptual
|
| 24 |
+
|
| 25 |
+
perceptual_memory:
|
| 26 |
+
type: hybrid
|
| 27 |
+
|
| 28 |
+
latent_memory:
|
| 29 |
+
mode: hybrid
|
| 30 |
+
use_temporal_emb: true
|
| 31 |
+
|
| 32 |
+
static_semantic_memory:
|
| 33 |
+
enabled: true
|
| 34 |
+
annotation_dir: ${oc.env:PICMEM_STAGE4_ROOT,null}
|
| 35 |
+
mode: ${oc.env:PICMEM_STAGE4_MEMORY_MODE,text_anchors}
|
| 36 |
+
|
| 37 |
+
transition_status:
|
| 38 |
+
schema_version: picmem_transition_status_v2
|
| 39 |
+
enabled: true
|
| 40 |
+
objective: coarse_span_with_conditional_last
|
| 41 |
+
action_proposal_horizon: 20
|
| 42 |
+
execution_horizon: 16
|
| 43 |
+
context_horizon: 48
|
| 44 |
+
robot_vector_dim: 8
|
| 45 |
+
context_hidden_dim: 128
|
| 46 |
+
span_loss_weight: 1.0
|
| 47 |
+
last_span_loss_weight: 0.5
|
| 48 |
+
status_temperature: 1.0
|
| 49 |
+
span_threshold: 0.5
|
| 50 |
+
last_span_threshold: 0.5
|
| 51 |
+
confirmation_tail: 4
|
| 52 |
+
cooldown_chunks: 1
|
| 53 |
+
training_manifest_path: ${oc.env:PICMEM_TRANSITION_MANIFEST,null}
|
| 54 |
+
training_manifest_sha256: ${oc.env:PICMEM_TRANSITION_MANIFEST_SHA256,null}
|
checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/models/representation/phase_a_reader.py
ADDED
|
@@ -0,0 +1,328 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Task-aware temporal/role residual for Phase-A visual memory tokens."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from typing import Any
|
| 6 |
+
|
| 7 |
+
import flax.nnx as nnx
|
| 8 |
+
import jax
|
| 9 |
+
import jax.numpy as jnp
|
| 10 |
+
import numpy as np
|
| 11 |
+
import openpi.shared.array_typing as at
|
| 12 |
+
from mme_vla_suite.models.representation.utils import kernel_init
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class PhaseAMetadataReader(nnx.Module):
|
| 16 |
+
"""Fuse selected-frame metadata into already encoded visual tokens.
|
| 17 |
+
|
| 18 |
+
The residual is explicitly gated by the intervention masks. A ``neutral``
|
| 19 |
+
observation therefore returns the visual tokens bit-for-bit, independent
|
| 20 |
+
of the newly initialized reader parameters.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
def __init__(
|
| 24 |
+
self,
|
| 25 |
+
*,
|
| 26 |
+
memory_token_dim: int,
|
| 27 |
+
event_vocab_size: int,
|
| 28 |
+
event_ordinal_vocab_size: int,
|
| 29 |
+
contract_vocab_size: int,
|
| 30 |
+
status_vocab_size: int,
|
| 31 |
+
categorical_embed_dim: int,
|
| 32 |
+
numeric_hidden_dim: int,
|
| 33 |
+
fusion_hidden_dim: int,
|
| 34 |
+
rngs: nnx.Rngs,
|
| 35 |
+
dtype: at.DTypeLike = jnp.float32,
|
| 36 |
+
):
|
| 37 |
+
sizes = {
|
| 38 |
+
"memory_token_dim": memory_token_dim,
|
| 39 |
+
"event_vocab_size": event_vocab_size,
|
| 40 |
+
"event_ordinal_vocab_size": event_ordinal_vocab_size,
|
| 41 |
+
"contract_vocab_size": contract_vocab_size,
|
| 42 |
+
"status_vocab_size": status_vocab_size,
|
| 43 |
+
"categorical_embed_dim": categorical_embed_dim,
|
| 44 |
+
"numeric_hidden_dim": numeric_hidden_dim,
|
| 45 |
+
"fusion_hidden_dim": fusion_hidden_dim,
|
| 46 |
+
}
|
| 47 |
+
if any(value <= 1 for name, value in sizes.items() if name.endswith("vocab_size")):
|
| 48 |
+
raise ValueError("Phase-A categorical vocabularies must reserve neutral index zero")
|
| 49 |
+
if any(value <= 0 for name, value in sizes.items() if not name.endswith("vocab_size")):
|
| 50 |
+
raise ValueError("Phase-A reader dimensions must be positive")
|
| 51 |
+
|
| 52 |
+
self.dtype = dtype
|
| 53 |
+
self.event_vocab_size = event_vocab_size
|
| 54 |
+
self.event_ordinal_vocab_size = event_ordinal_vocab_size
|
| 55 |
+
self.contract_vocab_size = contract_vocab_size
|
| 56 |
+
self.status_vocab_size = status_vocab_size
|
| 57 |
+
self.role_embed = nnx.Embed(4, categorical_embed_dim, rngs=rngs, dtype=dtype)
|
| 58 |
+
self.event_embed = nnx.Embed(
|
| 59 |
+
event_vocab_size,
|
| 60 |
+
categorical_embed_dim,
|
| 61 |
+
rngs=rngs,
|
| 62 |
+
dtype=dtype,
|
| 63 |
+
)
|
| 64 |
+
self.ordinal_embed = nnx.Embed(
|
| 65 |
+
event_ordinal_vocab_size,
|
| 66 |
+
categorical_embed_dim,
|
| 67 |
+
rngs=rngs,
|
| 68 |
+
dtype=dtype,
|
| 69 |
+
)
|
| 70 |
+
self.contract_embed = nnx.Embed(
|
| 71 |
+
contract_vocab_size,
|
| 72 |
+
categorical_embed_dim,
|
| 73 |
+
rngs=rngs,
|
| 74 |
+
dtype=dtype,
|
| 75 |
+
)
|
| 76 |
+
self.status_embed = nnx.Embed(
|
| 77 |
+
status_vocab_size,
|
| 78 |
+
categorical_embed_dim,
|
| 79 |
+
rngs=rngs,
|
| 80 |
+
dtype=dtype,
|
| 81 |
+
)
|
| 82 |
+
# [absolute_time, relative_age, delta_prev, confidence, evidence,
|
| 83 |
+
# three time masks, role mask, categorical mask]
|
| 84 |
+
self.numeric_in = nnx.Linear(
|
| 85 |
+
10,
|
| 86 |
+
numeric_hidden_dim,
|
| 87 |
+
rngs=rngs,
|
| 88 |
+
dtype=dtype,
|
| 89 |
+
kernel_init=kernel_init,
|
| 90 |
+
)
|
| 91 |
+
self.numeric_out = nnx.Linear(
|
| 92 |
+
numeric_hidden_dim,
|
| 93 |
+
numeric_hidden_dim,
|
| 94 |
+
rngs=rngs,
|
| 95 |
+
dtype=dtype,
|
| 96 |
+
kernel_init=kernel_init,
|
| 97 |
+
)
|
| 98 |
+
fused_dim = 5 * categorical_embed_dim + numeric_hidden_dim
|
| 99 |
+
self.fuse_norm = nnx.LayerNorm(fused_dim, rngs=rngs, dtype=dtype)
|
| 100 |
+
self.fuse_in = nnx.Linear(
|
| 101 |
+
fused_dim,
|
| 102 |
+
fusion_hidden_dim,
|
| 103 |
+
rngs=rngs,
|
| 104 |
+
dtype=dtype,
|
| 105 |
+
kernel_init=kernel_init,
|
| 106 |
+
)
|
| 107 |
+
self.out_proj = nnx.Linear(
|
| 108 |
+
fusion_hidden_dim,
|
| 109 |
+
memory_token_dim,
|
| 110 |
+
rngs=rngs,
|
| 111 |
+
dtype=dtype,
|
| 112 |
+
kernel_init=kernel_init,
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
def __call__(
|
| 116 |
+
self,
|
| 117 |
+
visual_tokens: at.Float[at.Array, "b l d"],
|
| 118 |
+
static_mask: at.Bool[at.Array, "b l"],
|
| 119 |
+
phase_a_frame_indices: at.Int[at.Array, "b l"],
|
| 120 |
+
phase_a_capture_steps: at.Int[at.Array, "b l"],
|
| 121 |
+
phase_a_time_values: at.Float[at.Array, "b l 3"],
|
| 122 |
+
phase_a_time_mask: at.Bool[at.Array, "b l 3"],
|
| 123 |
+
phase_a_role_ids: at.Int[at.Array, "b l"],
|
| 124 |
+
phase_a_role_mask: at.Bool[at.Array, "b l"],
|
| 125 |
+
phase_a_event_ids: at.Int[at.Array, "b l"],
|
| 126 |
+
phase_a_event_ordinals: at.Int[at.Array, "b l"],
|
| 127 |
+
phase_a_contract_ids: at.Int[at.Array, "b l"],
|
| 128 |
+
phase_a_status_ids: at.Int[at.Array, "b l"],
|
| 129 |
+
phase_a_categorical_mask: at.Bool[at.Array, "b l"],
|
| 130 |
+
phase_a_confidence: at.Float[at.Array, "b l"],
|
| 131 |
+
phase_a_evidence_mask: at.Bool[at.Array, "b l"],
|
| 132 |
+
phase_a_valid_mask: at.Bool[at.Array, "b l"],
|
| 133 |
+
) -> tuple[at.Float[at.Array, "b l d"], dict[str, Any]]:
|
| 134 |
+
batch, length, _ = visual_tokens.shape
|
| 135 |
+
bl = (batch, length)
|
| 136 |
+
vectors = {
|
| 137 |
+
"static_mask": static_mask,
|
| 138 |
+
"frame_indices": phase_a_frame_indices,
|
| 139 |
+
"capture_steps": phase_a_capture_steps,
|
| 140 |
+
"role_ids": phase_a_role_ids,
|
| 141 |
+
"role_mask": phase_a_role_mask,
|
| 142 |
+
"event_ids": phase_a_event_ids,
|
| 143 |
+
"event_ordinals": phase_a_event_ordinals,
|
| 144 |
+
"contract_ids": phase_a_contract_ids,
|
| 145 |
+
"status_ids": phase_a_status_ids,
|
| 146 |
+
"categorical_mask": phase_a_categorical_mask,
|
| 147 |
+
"confidence": phase_a_confidence,
|
| 148 |
+
"evidence_mask": phase_a_evidence_mask,
|
| 149 |
+
"valid_mask": phase_a_valid_mask,
|
| 150 |
+
}
|
| 151 |
+
for name, value in vectors.items():
|
| 152 |
+
if value.shape != bl:
|
| 153 |
+
raise ValueError(f"Phase-A {name} shape {value.shape} != {bl}")
|
| 154 |
+
if phase_a_time_values.shape != (*bl, 3):
|
| 155 |
+
raise ValueError("Phase-A time_values must have three channels")
|
| 156 |
+
if phase_a_time_mask.shape != (*bl, 3):
|
| 157 |
+
raise ValueError("Phase-A time_mask must have three channels")
|
| 158 |
+
for name in (
|
| 159 |
+
"static_mask",
|
| 160 |
+
"role_mask",
|
| 161 |
+
"categorical_mask",
|
| 162 |
+
"evidence_mask",
|
| 163 |
+
"valid_mask",
|
| 164 |
+
):
|
| 165 |
+
if vectors[name].dtype != jnp.bool_:
|
| 166 |
+
raise ValueError(f"Phase-A {name} must be boolean")
|
| 167 |
+
if phase_a_time_mask.dtype != jnp.bool_:
|
| 168 |
+
raise ValueError("Phase-A time_mask must be boolean")
|
| 169 |
+
for name in (
|
| 170 |
+
"frame_indices",
|
| 171 |
+
"capture_steps",
|
| 172 |
+
"role_ids",
|
| 173 |
+
"event_ids",
|
| 174 |
+
"event_ordinals",
|
| 175 |
+
"contract_ids",
|
| 176 |
+
"status_ids",
|
| 177 |
+
):
|
| 178 |
+
if not jnp.issubdtype(vectors[name].dtype, jnp.integer):
|
| 179 |
+
raise ValueError(f"Phase-A {name} must be integer")
|
| 180 |
+
if not jnp.issubdtype(phase_a_time_values.dtype, jnp.floating):
|
| 181 |
+
raise ValueError("Phase-A time_values must be floating point")
|
| 182 |
+
if not jnp.issubdtype(phase_a_confidence.dtype, jnp.floating):
|
| 183 |
+
raise ValueError("Phase-A confidence must be floating point")
|
| 184 |
+
if _is_concrete(static_mask, phase_a_valid_mask) and not np.array_equal(
|
| 185 |
+
np.asarray(static_mask),
|
| 186 |
+
np.asarray(phase_a_valid_mask),
|
| 187 |
+
):
|
| 188 |
+
raise ValueError("Phase-A valid mask must equal the visual token mask")
|
| 189 |
+
if _is_concrete(
|
| 190 |
+
phase_a_frame_indices,
|
| 191 |
+
phase_a_capture_steps,
|
| 192 |
+
phase_a_valid_mask,
|
| 193 |
+
phase_a_time_values,
|
| 194 |
+
phase_a_time_mask,
|
| 195 |
+
phase_a_role_ids,
|
| 196 |
+
phase_a_role_mask,
|
| 197 |
+
phase_a_event_ids,
|
| 198 |
+
phase_a_event_ordinals,
|
| 199 |
+
phase_a_contract_ids,
|
| 200 |
+
phase_a_status_ids,
|
| 201 |
+
phase_a_categorical_mask,
|
| 202 |
+
phase_a_confidence,
|
| 203 |
+
phase_a_evidence_mask,
|
| 204 |
+
):
|
| 205 |
+
frame_indices = np.asarray(phase_a_frame_indices)
|
| 206 |
+
capture_steps = np.asarray(phase_a_capture_steps)
|
| 207 |
+
valid_mask = np.asarray(phase_a_valid_mask)
|
| 208 |
+
invalid_mask = ~valid_mask
|
| 209 |
+
if np.any(frame_indices < 0) or np.any(capture_steps < 0):
|
| 210 |
+
raise ValueError("Phase-A frame indices and capture steps must be non-negative")
|
| 211 |
+
if np.any(frame_indices[invalid_mask]) or np.any(capture_steps[invalid_mask]):
|
| 212 |
+
raise ValueError("Phase-A padding provenance must be canonical zeros")
|
| 213 |
+
if np.any(np.asarray(phase_a_time_mask)[invalid_mask]):
|
| 214 |
+
raise ValueError("Phase-A padding cannot expose temporal metadata")
|
| 215 |
+
for name, mask in (
|
| 216 |
+
("role_mask", phase_a_role_mask),
|
| 217 |
+
("categorical_mask", phase_a_categorical_mask),
|
| 218 |
+
("evidence_mask", phase_a_evidence_mask),
|
| 219 |
+
):
|
| 220 |
+
if np.any(np.asarray(mask) & invalid_mask):
|
| 221 |
+
raise ValueError(f"Phase-A {name} cannot mark padding")
|
| 222 |
+
|
| 223 |
+
time_mask = np.asarray(phase_a_time_mask)
|
| 224 |
+
categorical_mask = np.asarray(phase_a_categorical_mask)
|
| 225 |
+
role_mask = np.asarray(phase_a_role_mask)
|
| 226 |
+
evidence_mask = np.asarray(phase_a_evidence_mask)
|
| 227 |
+
if not np.array_equal(role_mask, evidence_mask):
|
| 228 |
+
raise ValueError("Phase-A role mask must equal evidence mask")
|
| 229 |
+
if not np.array_equal(categorical_mask, evidence_mask):
|
| 230 |
+
raise ValueError("Phase-A categorical mask must equal evidence mask")
|
| 231 |
+
if not np.array_equal(
|
| 232 |
+
time_mask,
|
| 233 |
+
np.repeat(time_mask[..., :1], 3, axis=-1),
|
| 234 |
+
):
|
| 235 |
+
raise ValueError("Phase-A time channels must share one token gate")
|
| 236 |
+
if np.any(np.asarray(phase_a_time_values)[~time_mask]):
|
| 237 |
+
raise ValueError("masked Phase-A time values must be neutral zeros")
|
| 238 |
+
if np.any(capture_steps[~np.any(time_mask, axis=-1)]):
|
| 239 |
+
raise ValueError("masked Phase-A capture steps must be neutral zeros")
|
| 240 |
+
if np.any(np.asarray(phase_a_role_ids)[~role_mask]):
|
| 241 |
+
raise ValueError("masked Phase-A role IDs must be neutral zeros")
|
| 242 |
+
for name, value in (
|
| 243 |
+
("event_ids", phase_a_event_ids),
|
| 244 |
+
("event_ordinals", phase_a_event_ordinals),
|
| 245 |
+
("contract_ids", phase_a_contract_ids),
|
| 246 |
+
("status_ids", phase_a_status_ids),
|
| 247 |
+
("confidence", phase_a_confidence),
|
| 248 |
+
):
|
| 249 |
+
if np.any(np.asarray(value)[~categorical_mask]):
|
| 250 |
+
raise ValueError(f"masked Phase-A {name} must contain neutral zeros")
|
| 251 |
+
if np.any(np.asarray(phase_a_role_ids)[evidence_mask] == 0):
|
| 252 |
+
raise ValueError("Phase-A evidence tokens require a non-background role")
|
| 253 |
+
for name, value in (
|
| 254 |
+
("event_ids", phase_a_event_ids),
|
| 255 |
+
("event_ordinals", phase_a_event_ordinals),
|
| 256 |
+
("contract_ids", phase_a_contract_ids),
|
| 257 |
+
("status_ids", phase_a_status_ids),
|
| 258 |
+
):
|
| 259 |
+
if np.any(np.asarray(value)[evidence_mask] == 0):
|
| 260 |
+
raise ValueError(f"Phase-A evidence tokens require nonzero {name}")
|
| 261 |
+
|
| 262 |
+
role = self._strict_ids(phase_a_role_ids, 4, "role_ids")
|
| 263 |
+
event = self._strict_ids(phase_a_event_ids, self.event_vocab_size, "event_ids")
|
| 264 |
+
ordinal = self._strict_ids(
|
| 265 |
+
phase_a_event_ordinals,
|
| 266 |
+
self.event_ordinal_vocab_size,
|
| 267 |
+
"event_ordinals",
|
| 268 |
+
)
|
| 269 |
+
contract = self._strict_ids(
|
| 270 |
+
phase_a_contract_ids,
|
| 271 |
+
self.contract_vocab_size,
|
| 272 |
+
"contract_ids",
|
| 273 |
+
)
|
| 274 |
+
status = self._strict_ids(phase_a_status_ids, self.status_vocab_size, "status_ids")
|
| 275 |
+
|
| 276 |
+
role_gate = phase_a_role_mask[..., None].astype(self.dtype)
|
| 277 |
+
categorical_gate = phase_a_categorical_mask[..., None].astype(self.dtype)
|
| 278 |
+
categorical = [
|
| 279 |
+
self.role_embed(role) * role_gate,
|
| 280 |
+
self.event_embed(event) * categorical_gate,
|
| 281 |
+
self.ordinal_embed(ordinal) * categorical_gate,
|
| 282 |
+
self.contract_embed(contract) * categorical_gate,
|
| 283 |
+
self.status_embed(status) * categorical_gate,
|
| 284 |
+
]
|
| 285 |
+
time_mask_f = phase_a_time_mask.astype(self.dtype)
|
| 286 |
+
numeric = jnp.concatenate(
|
| 287 |
+
[
|
| 288 |
+
phase_a_time_values.astype(self.dtype) * time_mask_f,
|
| 289 |
+
phase_a_confidence[..., None].astype(self.dtype) * categorical_gate,
|
| 290 |
+
phase_a_evidence_mask[..., None].astype(self.dtype),
|
| 291 |
+
time_mask_f,
|
| 292 |
+
role_gate,
|
| 293 |
+
categorical_gate,
|
| 294 |
+
],
|
| 295 |
+
axis=-1,
|
| 296 |
+
)
|
| 297 |
+
numeric = self.numeric_out(nnx.silu(self.numeric_in(numeric)))
|
| 298 |
+
fused = self.fuse_norm(jnp.concatenate([*categorical, numeric], axis=-1))
|
| 299 |
+
delta = self.out_proj(nnx.silu(self.fuse_in(fused)))
|
| 300 |
+
metadata_active = (
|
| 301 |
+
phase_a_role_mask | phase_a_categorical_mask | jnp.any(phase_a_time_mask, axis=-1)
|
| 302 |
+
) & static_mask
|
| 303 |
+
output = visual_tokens + jnp.where(
|
| 304 |
+
metadata_active[..., None],
|
| 305 |
+
delta,
|
| 306 |
+
jnp.zeros_like(delta),
|
| 307 |
+
)
|
| 308 |
+
stats = {
|
| 309 |
+
"phase_a_metadata_active_fraction": jnp.mean(metadata_active.astype(jnp.float32)),
|
| 310 |
+
"phase_a_evidence_token_fraction": jnp.mean((phase_a_evidence_mask & static_mask).astype(jnp.float32)),
|
| 311 |
+
}
|
| 312 |
+
return output, stats
|
| 313 |
+
|
| 314 |
+
@staticmethod
|
| 315 |
+
def _strict_ids(values: jax.Array, size: int, name: str) -> jax.Array:
|
| 316 |
+
values = values.astype(jnp.int32)
|
| 317 |
+
if _is_concrete(values):
|
| 318 |
+
host = np.asarray(values)
|
| 319 |
+
if host.size and (int(host.min()) < 0 or int(host.max()) >= size):
|
| 320 |
+
raise ValueError(f"Phase-A {name} must be in [0, {size})")
|
| 321 |
+
return jnp.where((values >= 0) & (values < size), values, 0)
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def _is_concrete(*values: jax.Array) -> bool:
|
| 325 |
+
return all(not isinstance(value, jax.core.Tracer) for value in values)
|
| 326 |
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Low-cost coarse semantic-transition span head for HistoryPi0.
|
| 2 |
+
|
| 3 |
+
The head consumes the 16 executable action-token features and emits two logits:
|
| 4 |
+
whether the chunk overlaps a reviewed transition interval, and whether a
|
| 5 |
+
positive chunk is the final chunk of that interval. It does not predict an
|
| 6 |
+
exact onset token.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
from typing import Any
|
| 12 |
+
|
| 13 |
+
import flax.nnx as nnx
|
| 14 |
+
import jax
|
| 15 |
+
import jax.numpy as jnp
|
| 16 |
+
import openpi.shared.array_typing as at
|
| 17 |
+
from mme_vla_suite.models.representation.utils import kernel_init
|
| 18 |
+
|
| 19 |
+
STATUS_EXECUTION_HORIZON = 16
|
| 20 |
+
SEMANTIC_CONTEXT_HORIZON = 48
|
| 21 |
+
ROBOT_VECTOR_DIM = 8
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def span_binary_loss(
|
| 25 |
+
span_logit: at.Float[at.Array, " b"],
|
| 26 |
+
span_target: at.Float[at.Array, " b"],
|
| 27 |
+
status_valid: at.Bool[at.Array, " b"],
|
| 28 |
+
) -> at.Float[at.Array, " b"]:
|
| 29 |
+
"""Per-row ``BCEWithLogits`` for the coarse span target."""
|
| 30 |
+
|
| 31 |
+
logits = span_logit.astype(jnp.float32)
|
| 32 |
+
target = span_target.astype(jnp.float32)
|
| 33 |
+
loss = jax.nn.softplus(logits) - target * logits
|
| 34 |
+
return jnp.where(status_valid, loss, 0.0)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def last_span_valid_mask(
|
| 38 |
+
span_target: at.Float[at.Array, " b"],
|
| 39 |
+
last_span_valid: at.Bool[at.Array, " b"],
|
| 40 |
+
) -> at.Bool[at.Array, " b"]:
|
| 41 |
+
"""Rows the conditional endpoint loss actually scores."""
|
| 42 |
+
|
| 43 |
+
return last_span_valid & (span_target.astype(jnp.float32) > 0.5)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def valid_row_rescale(valid: at.Bool[at.Array, " b"]) -> at.Float[at.Array, ""]:
|
| 47 |
+
"""Turn a mean over all rows into a mean over participating rows."""
|
| 48 |
+
|
| 49 |
+
n_valid = jnp.sum(valid.astype(jnp.float32))
|
| 50 |
+
return jnp.asarray(valid.shape[0], jnp.float32) / jnp.maximum(n_valid, 1.0)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def last_span_binary_loss(
|
| 54 |
+
last_span_logit: at.Float[at.Array, " b"],
|
| 55 |
+
last_span_target: at.Float[at.Array, " b"],
|
| 56 |
+
span_target: at.Float[at.Array, " b"],
|
| 57 |
+
last_span_valid: at.Bool[at.Array, " b"],
|
| 58 |
+
) -> at.Float[at.Array, " b"]:
|
| 59 |
+
"""Conditional endpoint BCE, evaluated only for known positive spans."""
|
| 60 |
+
|
| 61 |
+
logits = last_span_logit.astype(jnp.float32)
|
| 62 |
+
target = last_span_target.astype(jnp.float32)
|
| 63 |
+
loss = jax.nn.softplus(logits) - target * logits
|
| 64 |
+
valid = last_span_valid_mask(span_target, last_span_valid)
|
| 65 |
+
return jnp.where(valid, loss, 0.0)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def weighted_status_loss_components(
|
| 69 |
+
*,
|
| 70 |
+
span_loss: at.Float[at.Array, " b"],
|
| 71 |
+
last_span_loss: at.Float[at.Array, " b"],
|
| 72 |
+
status_valid: at.Bool[at.Array, " b"],
|
| 73 |
+
span_target: at.Float[at.Array, " b"],
|
| 74 |
+
last_span_valid: at.Bool[at.Array, " b"],
|
| 75 |
+
span_loss_weight: float,
|
| 76 |
+
last_span_loss_weight: float,
|
| 77 |
+
) -> tuple[
|
| 78 |
+
at.Float[at.Array, " b"],
|
| 79 |
+
at.Float[at.Array, " b"],
|
| 80 |
+
dict[str, at.Array],
|
| 81 |
+
]:
|
| 82 |
+
"""Build the two rescaled Status terms and their effective metrics."""
|
| 83 |
+
|
| 84 |
+
endpoint_valid = last_span_valid_mask(span_target, last_span_valid)
|
| 85 |
+
span_rescale = valid_row_rescale(status_valid)
|
| 86 |
+
last_span_rescale = valid_row_rescale(endpoint_valid)
|
| 87 |
+
span_component = span_loss_weight * span_rescale * span_loss
|
| 88 |
+
last_span_component = (
|
| 89 |
+
last_span_loss_weight * last_span_rescale * last_span_loss
|
| 90 |
+
)
|
| 91 |
+
span_contribution = jnp.mean(span_component)
|
| 92 |
+
last_span_contribution = jnp.mean(last_span_component)
|
| 93 |
+
batch_size = jnp.asarray(status_valid.shape[0], dtype=jnp.float32)
|
| 94 |
+
status_valid_rows = jnp.sum(status_valid.astype(jnp.float32))
|
| 95 |
+
last_span_valid_rows = jnp.sum(endpoint_valid.astype(jnp.float32))
|
| 96 |
+
metrics = {
|
| 97 |
+
"transition_span_loss_weight": jnp.asarray(
|
| 98 |
+
span_loss_weight, dtype=jnp.float32
|
| 99 |
+
),
|
| 100 |
+
"transition_last_span_loss_weight": jnp.asarray(
|
| 101 |
+
last_span_loss_weight, dtype=jnp.float32
|
| 102 |
+
),
|
| 103 |
+
"transition_span_rescale": span_rescale,
|
| 104 |
+
"transition_last_span_rescale": last_span_rescale,
|
| 105 |
+
"transition_status_valid_rows": status_valid_rows,
|
| 106 |
+
"transition_last_span_valid_rows": last_span_valid_rows,
|
| 107 |
+
"transition_status_valid_fraction": status_valid_rows / batch_size,
|
| 108 |
+
"transition_last_span_valid_fraction": last_span_valid_rows / batch_size,
|
| 109 |
+
"transition_span_loss_contribution": span_contribution,
|
| 110 |
+
"transition_last_span_loss_contribution": last_span_contribution,
|
| 111 |
+
"transition_status_loss": span_contribution + last_span_contribution,
|
| 112 |
+
}
|
| 113 |
+
return span_component, last_span_component, metrics
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class RealizedTransitionContextEncoder(nnx.Module):
|
| 117 |
+
"""Pool up to 48 causal realized action/state deltas with one query."""
|
| 118 |
+
|
| 119 |
+
def __init__(
|
| 120 |
+
self,
|
| 121 |
+
*,
|
| 122 |
+
action_expert_width: int,
|
| 123 |
+
hidden_dim: int = 128,
|
| 124 |
+
rngs: nnx.Rngs,
|
| 125 |
+
dtype: at.DTypeLike = jnp.float32,
|
| 126 |
+
) -> None:
|
| 127 |
+
if action_expert_width <= 0 or hidden_dim <= 0:
|
| 128 |
+
raise ValueError("transition context dimensions must be positive")
|
| 129 |
+
self.dtype = dtype
|
| 130 |
+
self.hidden_dim = hidden_dim
|
| 131 |
+
self.row_in = nnx.Linear(
|
| 132 |
+
2 * ROBOT_VECTOR_DIM + 1,
|
| 133 |
+
hidden_dim,
|
| 134 |
+
rngs=rngs,
|
| 135 |
+
dtype=dtype,
|
| 136 |
+
kernel_init=kernel_init,
|
| 137 |
+
)
|
| 138 |
+
self.row_out = nnx.Linear(
|
| 139 |
+
hidden_dim,
|
| 140 |
+
hidden_dim,
|
| 141 |
+
rngs=rngs,
|
| 142 |
+
dtype=dtype,
|
| 143 |
+
kernel_init=kernel_init,
|
| 144 |
+
)
|
| 145 |
+
self.query = nnx.Param(
|
| 146 |
+
jax.random.normal(rngs.params(), (hidden_dim,), dtype=jnp.float32)
|
| 147 |
+
/ jnp.sqrt(jnp.asarray(hidden_dim, jnp.float32))
|
| 148 |
+
)
|
| 149 |
+
# No bias is important: an all-masked history must be an exact zero
|
| 150 |
+
# residual, reproducing the context-free Status Head path.
|
| 151 |
+
self.out_proj = nnx.Linear(
|
| 152 |
+
hidden_dim,
|
| 153 |
+
action_expert_width,
|
| 154 |
+
use_bias=False,
|
| 155 |
+
rngs=rngs,
|
| 156 |
+
dtype=dtype,
|
| 157 |
+
kernel_init=kernel_init,
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
def __call__(
|
| 161 |
+
self,
|
| 162 |
+
action_delta: at.Float[at.Array, "b 48 8"],
|
| 163 |
+
state_delta: at.Float[at.Array, "b 48 8"],
|
| 164 |
+
relative_age: at.Float[at.Array, "b 48"],
|
| 165 |
+
valid_mask: at.Bool[at.Array, "b 48"],
|
| 166 |
+
) -> at.Float[at.Array, "b d"]:
|
| 167 |
+
expected_rows = action_delta.shape[:2]
|
| 168 |
+
if action_delta.shape != (*expected_rows, ROBOT_VECTOR_DIM):
|
| 169 |
+
raise ValueError("transition action_delta must end in dimension 8")
|
| 170 |
+
if state_delta.shape != action_delta.shape:
|
| 171 |
+
raise ValueError("transition state_delta must match action_delta")
|
| 172 |
+
if expected_rows[1] != SEMANTIC_CONTEXT_HORIZON:
|
| 173 |
+
raise ValueError("transition context must contain exactly 48 rows")
|
| 174 |
+
if relative_age.shape != expected_rows or valid_mask.shape != expected_rows:
|
| 175 |
+
raise ValueError("transition age/mask shapes must match context rows")
|
| 176 |
+
|
| 177 |
+
rows = jnp.concatenate(
|
| 178 |
+
[
|
| 179 |
+
action_delta.astype(self.dtype),
|
| 180 |
+
state_delta.astype(self.dtype),
|
| 181 |
+
relative_age[..., None].astype(self.dtype),
|
| 182 |
+
],
|
| 183 |
+
axis=-1,
|
| 184 |
+
)
|
| 185 |
+
rows = self.row_out(nnx.silu(self.row_in(rows)))
|
| 186 |
+
scores = jnp.einsum(
|
| 187 |
+
"btd,d->bt",
|
| 188 |
+
rows.astype(jnp.float32),
|
| 189 |
+
self.query.value.astype(jnp.float32),
|
| 190 |
+
) / jnp.sqrt(jnp.asarray(self.hidden_dim, jnp.float32))
|
| 191 |
+
mask_f = valid_mask.astype(jnp.float32)
|
| 192 |
+
masked_scores = jnp.where(valid_mask, scores, -1e30)
|
| 193 |
+
max_score = jnp.max(masked_scores, axis=-1, keepdims=True)
|
| 194 |
+
weights = jnp.exp(masked_scores - max_score) * mask_f
|
| 195 |
+
weights = weights / jnp.maximum(jnp.sum(weights, axis=-1, keepdims=True), 1e-8)
|
| 196 |
+
pooled = jnp.einsum("bt,btd->bd", weights.astype(rows.dtype), rows)
|
| 197 |
+
pooled = jnp.where(jnp.any(valid_mask, axis=-1, keepdims=True), pooled, 0.0)
|
| 198 |
+
return self.out_proj(pooled)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
class TransitionStatusHead(nnx.Module):
|
| 202 |
+
"""Pool executable action features into shared span and final-span logits."""
|
| 203 |
+
|
| 204 |
+
def __init__(
|
| 205 |
+
self,
|
| 206 |
+
*,
|
| 207 |
+
action_expert_width: int,
|
| 208 |
+
context_hidden_dim: int = 128,
|
| 209 |
+
rngs: nnx.Rngs,
|
| 210 |
+
dtype: at.DTypeLike = jnp.float32,
|
| 211 |
+
) -> None:
|
| 212 |
+
self.dtype = dtype
|
| 213 |
+
self.context = RealizedTransitionContextEncoder(
|
| 214 |
+
action_expert_width=action_expert_width,
|
| 215 |
+
hidden_dim=context_hidden_dim,
|
| 216 |
+
rngs=rngs,
|
| 217 |
+
dtype=dtype,
|
| 218 |
+
)
|
| 219 |
+
self.span_norm = nnx.LayerNorm(action_expert_width, rngs=rngs, dtype=dtype)
|
| 220 |
+
self.status_out = nnx.Linear(
|
| 221 |
+
action_expert_width,
|
| 222 |
+
2,
|
| 223 |
+
rngs=rngs,
|
| 224 |
+
dtype=dtype,
|
| 225 |
+
kernel_init=kernel_init,
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
def __call__(
|
| 229 |
+
self,
|
| 230 |
+
action_hidden: at.Float[at.Array, "b 16 d"],
|
| 231 |
+
*,
|
| 232 |
+
action_delta: at.Float[at.Array, "b 48 8"],
|
| 233 |
+
state_delta: at.Float[at.Array, "b 48 8"],
|
| 234 |
+
relative_age: at.Float[at.Array, "b 48"],
|
| 235 |
+
valid_mask: at.Bool[at.Array, "b 48"],
|
| 236 |
+
) -> tuple[at.Float[at.Array, " b"], at.Float[at.Array, " b"]]:
|
| 237 |
+
if action_hidden.shape[1] != STATUS_EXECUTION_HORIZON:
|
| 238 |
+
raise ValueError("Status Head requires exactly 16 executable action slots")
|
| 239 |
+
context = self.context(action_delta, state_delta, relative_age, valid_mask)
|
| 240 |
+
status_action_hidden = jax.lax.stop_gradient(action_hidden)
|
| 241 |
+
features = status_action_hidden + context[:, None, :].astype(action_hidden.dtype)
|
| 242 |
+
status_features = self.span_norm(jnp.mean(features, axis=1))
|
| 243 |
+
logits = self.status_out(status_features)
|
| 244 |
+
return logits[..., 0], logits[..., 1]
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def transition_training_stats(
|
| 248 |
+
*,
|
| 249 |
+
span_logit: at.Float[at.Array, " b"],
|
| 250 |
+
span_target: at.Float[at.Array, " b"],
|
| 251 |
+
status_valid: at.Bool[at.Array, " b"],
|
| 252 |
+
span_loss: at.Float[at.Array, " b"],
|
| 253 |
+
last_span_logit: at.Float[at.Array, " b"],
|
| 254 |
+
last_span_target: at.Float[at.Array, " b"],
|
| 255 |
+
last_span_valid: at.Bool[at.Array, " b"],
|
| 256 |
+
last_span_loss: at.Float[at.Array, " b"],
|
| 257 |
+
) -> dict[str, Any]:
|
| 258 |
+
valid_f = status_valid.astype(jnp.float32)
|
| 259 |
+
denom = jnp.maximum(jnp.sum(valid_f), 1.0)
|
| 260 |
+
endpoint_valid = last_span_valid & (span_target > 0.5)
|
| 261 |
+
endpoint_valid_f = endpoint_valid.astype(jnp.float32)
|
| 262 |
+
endpoint_denom = jnp.maximum(jnp.sum(endpoint_valid_f), 1.0)
|
| 263 |
+
return {
|
| 264 |
+
"transition_span_loss": jnp.sum(span_loss * valid_f) / denom,
|
| 265 |
+
"transition_span_probability": jnp.sum(jax.nn.sigmoid(span_logit) * valid_f) / denom,
|
| 266 |
+
"transition_span_positive_rate": jnp.sum(span_target.astype(jnp.float32) * valid_f) / denom,
|
| 267 |
+
"transition_last_span_loss": jnp.sum(last_span_loss * endpoint_valid_f) / endpoint_denom,
|
| 268 |
+
"transition_last_span_probability": (
|
| 269 |
+
jnp.sum(jax.nn.sigmoid(last_span_logit) * endpoint_valid_f) / endpoint_denom
|
| 270 |
+
),
|
| 271 |
+
"transition_last_span_positive_rate": (
|
| 272 |
+
jnp.sum(last_span_target.astype(jnp.float32) * endpoint_valid_f) / endpoint_denom
|
| 273 |
+
),
|
| 274 |
+
}
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
__all__ = [
|
| 278 |
+
"ROBOT_VECTOR_DIM",
|
| 279 |
+
"SEMANTIC_CONTEXT_HORIZON",
|
| 280 |
+
"STATUS_EXECUTION_HORIZON",
|
| 281 |
+
"RealizedTransitionContextEncoder",
|
| 282 |
+
"TransitionStatusHead",
|
| 283 |
+
"last_span_binary_loss",
|
| 284 |
+
"span_binary_loss",
|
| 285 |
+
"transition_training_stats",
|
| 286 |
+
"valid_row_rescale",
|
| 287 |
+
"weighted_status_loss_components",
|
| 288 |
+
]
|
checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/policies/picmem_phase_a_rollout.py
ADDED
|
@@ -0,0 +1,563 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fail-closed Phase-A runtime controller for RoboMME policy serving.
|
| 2 |
+
|
| 3 |
+
The simulator and policy run in different processes during the standard
|
| 4 |
+
RoboMME evaluation. The simulator therefore sends one identity-bound reset
|
| 5 |
+
and a stream of event envelopes through the existing ``add_buffer`` request.
|
| 6 |
+
This module is the policy-side authority for that wire. It owns no task
|
| 7 |
+
semantics: it validates the transport, applies every event through
|
| 8 |
+
``RuntimeReadSession.ingest_event``, and materializes the resulting evolving
|
| 9 |
+
read through the exact host ``MemoryBuffer`` before ``model.sample_actions``.
|
| 10 |
+
|
| 11 |
+
There is deliberately no legacy frame-sampling fallback once a Phase-A model
|
| 12 |
+
is loaded. A missing reset, a manager-mode mismatch, an event ahead of the
|
| 13 |
+
buffered visual history, or an incomplete 32-frame/512-token materialization
|
| 14 |
+
all fail the action request.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
from collections.abc import Callable, Mapping, Sequence
|
| 20 |
+
from copy import deepcopy
|
| 21 |
+
from dataclasses import dataclass, field
|
| 22 |
+
from typing import Any, TypedDict
|
| 23 |
+
|
| 24 |
+
import numpy as np
|
| 25 |
+
from mme_vla_suite.training.picmem_phase_a_reader import (
|
| 26 |
+
FACTOR_FIELDS,
|
| 27 |
+
FRAME_BUDGET,
|
| 28 |
+
OBSERVATION_FIELDS,
|
| 29 |
+
TOKEN_BUDGET,
|
| 30 |
+
PhaseAFactors,
|
| 31 |
+
)
|
| 32 |
+
from mme_vla_suite.training.picmem_phase_a_runtime import (
|
| 33 |
+
RuntimePhaseAObservation,
|
| 34 |
+
materialize_runtime_observation,
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
from picmem.memory.contracts import SelectionMode
|
| 38 |
+
from picmem.provenance.runtime_reader import (
|
| 39 |
+
RuntimeReadError,
|
| 40 |
+
RuntimeReadSession,
|
| 41 |
+
canonical_json_sha256,
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
RUNTIME_BATCH_SCHEMA_VERSION = "picmem_phase_a_rollout_batch_v2"
|
| 45 |
+
RUNTIME_BATCH_ACK_SCHEMA_VERSION = "picmem_phase_a_rollout_batch_ack_v1"
|
| 46 |
+
RUNTIME_START_SCHEMA_VERSION = "picmem_phase_a_rollout_start_v1"
|
| 47 |
+
RUNTIME_ENVELOPE_SCHEMA_VERSION = "picmem_phase_a_rollout_event_envelope_v1"
|
| 48 |
+
GENESIS_BATCH_SHA256 = "0" * 64
|
| 49 |
+
|
| 50 |
+
_BATCH_FIELDS = frozenset(
|
| 51 |
+
{
|
| 52 |
+
"schema_version",
|
| 53 |
+
"batch_sequence",
|
| 54 |
+
"previous_batch_sha256",
|
| 55 |
+
"batch_sha256",
|
| 56 |
+
"start",
|
| 57 |
+
"events",
|
| 58 |
+
}
|
| 59 |
+
)
|
| 60 |
+
_BATCH_HASH_FIELDS = (
|
| 61 |
+
"schema_version",
|
| 62 |
+
"batch_sequence",
|
| 63 |
+
"previous_batch_sha256",
|
| 64 |
+
"start",
|
| 65 |
+
"events",
|
| 66 |
+
)
|
| 67 |
+
_START_FIELDS = frozenset(
|
| 68 |
+
{
|
| 69 |
+
"schema_version",
|
| 70 |
+
"reset",
|
| 71 |
+
"expected_identity_sha256",
|
| 72 |
+
"expected_source_identity_sha256",
|
| 73 |
+
"expected_source_contract_sha256",
|
| 74 |
+
"manager_mode",
|
| 75 |
+
"metadata_seed",
|
| 76 |
+
}
|
| 77 |
+
)
|
| 78 |
+
_ENVELOPE_FIELDS = frozenset({"schema_version", "event", "observed_source_state"})
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
@dataclass(frozen=True, slots=True)
|
| 82 |
+
class PhaseARolloutMaterialization:
|
| 83 |
+
"""One policy-visible runtime observation and its model input fields."""
|
| 84 |
+
|
| 85 |
+
runtime: RuntimePhaseAObservation
|
| 86 |
+
model_inputs: Mapping[str, np.ndarray]
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class PhaseARolloutBatchAck(TypedDict):
|
| 90 |
+
"""Strict policy-server acknowledgement for one committed batch."""
|
| 91 |
+
|
| 92 |
+
schema_version: str
|
| 93 |
+
batch_sequence: int
|
| 94 |
+
batch_sha256: str
|
| 95 |
+
duplicate: bool
|
| 96 |
+
runtime_receipt: dict[str, Any]
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
@dataclass(frozen=True, slots=True)
|
| 100 |
+
class PhaseARolloutPreparedBatch:
|
| 101 |
+
"""Opaque one-shot result of validating a prospective host append."""
|
| 102 |
+
|
| 103 |
+
batch_sequence: int
|
| 104 |
+
batch_sha256: str
|
| 105 |
+
duplicate: bool
|
| 106 |
+
_controller_token: object = field(repr=False, compare=False)
|
| 107 |
+
_preparation_token: object = field(repr=False, compare=False)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
@dataclass(frozen=True, slots=True)
|
| 111 |
+
class _PreparedState:
|
| 112 |
+
prepared: PhaseARolloutPreparedBatch
|
| 113 |
+
base_session: RuntimeReadSession | None
|
| 114 |
+
base_receipt_sha256: str | None
|
| 115 |
+
base_batch_sequence: int | None
|
| 116 |
+
base_batch_sha256: str | None
|
| 117 |
+
candidate_session: RuntimeReadSession | None
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class PhaseARolloutController:
|
| 121 |
+
"""Bind one formal Phase-A config to one live RoboMME episode at a time."""
|
| 122 |
+
|
| 123 |
+
def __init__(self, *, factors: PhaseAFactors, metadata_seed: int) -> None:
|
| 124 |
+
if type(factors) is not PhaseAFactors:
|
| 125 |
+
raise RuntimeReadError("rollout controller requires the exact PhaseAFactors class")
|
| 126 |
+
# Online mutation plans for non-relevant selectors are not frozen. The
|
| 127 |
+
# runtime bridge must never silently turn those arms into relevant.
|
| 128 |
+
factors.validate_implemented_path(selection_applied=SelectionMode.RELEVANT)
|
| 129 |
+
self._factors = factors
|
| 130 |
+
self._metadata_seed = _nat(metadata_seed, "metadata_seed")
|
| 131 |
+
self._session: RuntimeReadSession | None = None
|
| 132 |
+
self._last_batch_sequence: int | None = None
|
| 133 |
+
self._last_batch_sha256: str | None = None
|
| 134 |
+
self._controller_token = object()
|
| 135 |
+
self._prepared_state: _PreparedState | None = None
|
| 136 |
+
|
| 137 |
+
@property
|
| 138 |
+
def factors(self) -> PhaseAFactors:
|
| 139 |
+
return self._factors
|
| 140 |
+
|
| 141 |
+
@property
|
| 142 |
+
def metadata_seed(self) -> int:
|
| 143 |
+
return self._metadata_seed
|
| 144 |
+
|
| 145 |
+
@property
|
| 146 |
+
def session(self) -> RuntimeReadSession | None:
|
| 147 |
+
return self._session
|
| 148 |
+
|
| 149 |
+
@property
|
| 150 |
+
def last_batch_sequence(self) -> int | None:
|
| 151 |
+
return self._last_batch_sequence
|
| 152 |
+
|
| 153 |
+
@property
|
| 154 |
+
def last_batch_sha256(self) -> str | None:
|
| 155 |
+
return self._last_batch_sha256
|
| 156 |
+
|
| 157 |
+
def reset(self) -> None:
|
| 158 |
+
"""Drop all episode state when the outer policy receives ``reset``."""
|
| 159 |
+
|
| 160 |
+
self._session = None
|
| 161 |
+
self._last_batch_sequence = None
|
| 162 |
+
self._last_batch_sha256 = None
|
| 163 |
+
self._prepared_state = None
|
| 164 |
+
|
| 165 |
+
def accept_add_buffer_payload(
|
| 166 |
+
self,
|
| 167 |
+
raw: Any,
|
| 168 |
+
*,
|
| 169 |
+
buffered_step: int,
|
| 170 |
+
) -> PhaseARolloutBatchAck:
|
| 171 |
+
"""Validate and immediately commit one batch without a host transaction.
|
| 172 |
+
|
| 173 |
+
Production serving should use :meth:`prepare_add_buffer_payload`,
|
| 174 |
+
append the host ``MemoryBuffer`` only for a non-duplicate preparation,
|
| 175 |
+
and then call :meth:`commit_prepared_batch`. This convenience method
|
| 176 |
+
remains useful when no separate host mutation is part of the call.
|
| 177 |
+
"""
|
| 178 |
+
|
| 179 |
+
prepared = self.prepare_add_buffer_payload(
|
| 180 |
+
raw,
|
| 181 |
+
prospective_buffered_step=buffered_step,
|
| 182 |
+
)
|
| 183 |
+
return self.commit_prepared_batch(prepared)
|
| 184 |
+
|
| 185 |
+
def prepare_add_buffer_payload(
|
| 186 |
+
self,
|
| 187 |
+
raw: Any,
|
| 188 |
+
*,
|
| 189 |
+
prospective_buffered_step: int,
|
| 190 |
+
) -> PhaseARolloutPreparedBatch:
|
| 191 |
+
"""Validate one batch against a prospective buffer append.
|
| 192 |
+
|
| 193 |
+
``prospective_buffered_step`` is the highest step that will exist only
|
| 194 |
+
after the host append succeeds. This method never publishes a
|
| 195 |
+
session or advances the batch-chain cursor. Instead it returns one
|
| 196 |
+
opaque, one-shot preparation that can be committed after the host
|
| 197 |
+
mutation succeeds. Exact retries are marked ``duplicate`` so the
|
| 198 |
+
host must skip appending the same visual history a second time.
|
| 199 |
+
|
| 200 |
+
All start and event work happens on an unpublished candidate session,
|
| 201 |
+
so a bad later event cannot leave an earlier event partially accepted.
|
| 202 |
+
"""
|
| 203 |
+
|
| 204 |
+
prospective_buffered_step = _nat(
|
| 205 |
+
prospective_buffered_step,
|
| 206 |
+
"prospective_buffered_step",
|
| 207 |
+
)
|
| 208 |
+
batch = _exact_mapping(raw, _BATCH_FIELDS, "Phase-A rollout batch")
|
| 209 |
+
if batch["schema_version"] != RUNTIME_BATCH_SCHEMA_VERSION:
|
| 210 |
+
raise RuntimeReadError("Phase-A rollout batch schema_version mismatch")
|
| 211 |
+
|
| 212 |
+
batch_sequence = _nat(batch["batch_sequence"], "batch_sequence")
|
| 213 |
+
previous_batch_sha256 = _sha256(
|
| 214 |
+
batch["previous_batch_sha256"],
|
| 215 |
+
"previous_batch_sha256",
|
| 216 |
+
)
|
| 217 |
+
batch_sha256 = _sha256(batch["batch_sha256"], "batch_sha256")
|
| 218 |
+
batch_payload = {name: batch[name] for name in _BATCH_HASH_FIELDS}
|
| 219 |
+
if canonical_json_sha256(batch_payload) != batch_sha256:
|
| 220 |
+
raise RuntimeReadError("Phase-A rollout batch_sha256 mismatch")
|
| 221 |
+
|
| 222 |
+
if self._last_batch_sequence is not None and batch_sequence == self._last_batch_sequence:
|
| 223 |
+
if batch_sha256 != self._last_batch_sha256:
|
| 224 |
+
raise RuntimeReadError("Phase-A rollout batch retry hash mismatch")
|
| 225 |
+
return self._issue_prepared(
|
| 226 |
+
batch_sequence=batch_sequence,
|
| 227 |
+
batch_sha256=batch_sha256,
|
| 228 |
+
duplicate=True,
|
| 229 |
+
candidate_session=None,
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
if self._last_batch_sequence is None:
|
| 233 |
+
if batch_sequence != 0:
|
| 234 |
+
raise RuntimeReadError("first Phase-A rollout batch_sequence must be zero")
|
| 235 |
+
if previous_batch_sha256 != GENESIS_BATCH_SHA256:
|
| 236 |
+
raise RuntimeReadError("first Phase-A rollout batch must name the genesis hash")
|
| 237 |
+
if batch["start"] is None:
|
| 238 |
+
raise RuntimeReadError("first Phase-A rollout batch requires a runtime start")
|
| 239 |
+
else:
|
| 240 |
+
if batch_sequence != self._last_batch_sequence + 1:
|
| 241 |
+
raise RuntimeReadError("Phase-A rollout batch_sequence must be contiguous")
|
| 242 |
+
if previous_batch_sha256 != self._last_batch_sha256:
|
| 243 |
+
raise RuntimeReadError("Phase-A rollout previous_batch_sha256 mismatch")
|
| 244 |
+
|
| 245 |
+
start = batch["start"]
|
| 246 |
+
if start is not None:
|
| 247 |
+
if self._session is not None:
|
| 248 |
+
raise RuntimeReadError("Phase-A rollout session was already started")
|
| 249 |
+
candidate = self._start_session(start)
|
| 250 |
+
if candidate.current_step > prospective_buffered_step:
|
| 251 |
+
raise RuntimeReadError("Phase-A runtime start is ahead of buffered visual history")
|
| 252 |
+
elif self._session is None:
|
| 253 |
+
raise RuntimeReadError("Phase-A add_buffer arrived before an identity-bound runtime start")
|
| 254 |
+
else:
|
| 255 |
+
candidate = deepcopy(self._session)
|
| 256 |
+
|
| 257 |
+
events = batch["events"]
|
| 258 |
+
if not isinstance(events, Sequence) or isinstance(events, (str, bytes)):
|
| 259 |
+
raise RuntimeReadError("Phase-A rollout events must be a sequence")
|
| 260 |
+
assert candidate is not None
|
| 261 |
+
for index, raw_envelope in enumerate(events):
|
| 262 |
+
envelope = _exact_mapping(
|
| 263 |
+
raw_envelope,
|
| 264 |
+
_ENVELOPE_FIELDS,
|
| 265 |
+
f"Phase-A rollout event envelope[{index}]",
|
| 266 |
+
)
|
| 267 |
+
if envelope["schema_version"] != RUNTIME_ENVELOPE_SCHEMA_VERSION:
|
| 268 |
+
raise RuntimeReadError("Phase-A rollout event envelope schema_version mismatch")
|
| 269 |
+
event = envelope["event"]
|
| 270 |
+
if not isinstance(event, Mapping):
|
| 271 |
+
raise RuntimeReadError("Phase-A rollout envelope event must be a mapping")
|
| 272 |
+
runtime_step = _nat(event.get("runtime_step"), "event.runtime_step")
|
| 273 |
+
if runtime_step > prospective_buffered_step:
|
| 274 |
+
raise RuntimeReadError("Phase-A runtime event is ahead of buffered visual history")
|
| 275 |
+
candidate.ingest_event(
|
| 276 |
+
event,
|
| 277 |
+
observed_source_state=deepcopy(envelope["observed_source_state"]),
|
| 278 |
+
)
|
| 279 |
+
if candidate.current_step > prospective_buffered_step:
|
| 280 |
+
raise RuntimeReadError("Phase-A runtime session advanced beyond buffered visual history")
|
| 281 |
+
|
| 282 |
+
return self._issue_prepared(
|
| 283 |
+
batch_sequence=batch_sequence,
|
| 284 |
+
batch_sha256=batch_sha256,
|
| 285 |
+
duplicate=False,
|
| 286 |
+
candidate_session=candidate,
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
def commit_prepared_batch(
|
| 290 |
+
self,
|
| 291 |
+
prepared: PhaseARolloutPreparedBatch,
|
| 292 |
+
) -> PhaseARolloutBatchAck:
|
| 293 |
+
"""Publish one current preparation after the host append succeeds."""
|
| 294 |
+
|
| 295 |
+
if type(prepared) is not PhaseARolloutPreparedBatch:
|
| 296 |
+
raise RuntimeReadError("prepared rollout batch has the wrong type")
|
| 297 |
+
state = self._prepared_state
|
| 298 |
+
if (
|
| 299 |
+
state is None
|
| 300 |
+
or prepared._controller_token is not self._controller_token
|
| 301 |
+
or prepared._preparation_token is not state.prepared._preparation_token
|
| 302 |
+
or prepared.batch_sequence != state.prepared.batch_sequence
|
| 303 |
+
or prepared.batch_sha256 != state.prepared.batch_sha256
|
| 304 |
+
or prepared.duplicate is not state.prepared.duplicate
|
| 305 |
+
):
|
| 306 |
+
raise RuntimeReadError("prepared rollout batch is stale, foreign, or already consumed")
|
| 307 |
+
|
| 308 |
+
# A commit attempt consumes the preparation even when its base has
|
| 309 |
+
# drifted. Retrying an ambiguous host transaction must re-prepare
|
| 310 |
+
# from the current controller state rather than reuse an old token.
|
| 311 |
+
self._prepared_state = None
|
| 312 |
+
if (
|
| 313 |
+
self._session is not state.base_session
|
| 314 |
+
or self._last_batch_sequence != state.base_batch_sequence
|
| 315 |
+
or self._last_batch_sha256 != state.base_batch_sha256
|
| 316 |
+
or self._session_receipt_sha256(self._session) != state.base_receipt_sha256
|
| 317 |
+
):
|
| 318 |
+
raise RuntimeReadError("prepared rollout batch base state drifted before commit")
|
| 319 |
+
|
| 320 |
+
if prepared.duplicate:
|
| 321 |
+
if state.candidate_session is not None:
|
| 322 |
+
raise RuntimeReadError("duplicate rollout preparation unexpectedly has a candidate")
|
| 323 |
+
else:
|
| 324 |
+
if state.candidate_session is None:
|
| 325 |
+
raise RuntimeReadError("new rollout preparation has no candidate session")
|
| 326 |
+
self._session = state.candidate_session
|
| 327 |
+
self._last_batch_sequence = prepared.batch_sequence
|
| 328 |
+
self._last_batch_sha256 = prepared.batch_sha256
|
| 329 |
+
|
| 330 |
+
return self._ack(
|
| 331 |
+
batch_sequence=prepared.batch_sequence,
|
| 332 |
+
batch_sha256=prepared.batch_sha256,
|
| 333 |
+
duplicate=prepared.duplicate,
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
def materialize_for_action(
|
| 337 |
+
self,
|
| 338 |
+
memory_buffer: Any,
|
| 339 |
+
*,
|
| 340 |
+
step: int,
|
| 341 |
+
normalize_state: Callable[[np.ndarray], Any],
|
| 342 |
+
) -> PhaseARolloutMaterialization:
|
| 343 |
+
"""Materialize evolving memory immediately before action sampling."""
|
| 344 |
+
|
| 345 |
+
step = _nat(step, "step")
|
| 346 |
+
if self._session is None:
|
| 347 |
+
raise RuntimeReadError("Phase-A action request has no identity-bound runtime session")
|
| 348 |
+
if not callable(normalize_state):
|
| 349 |
+
raise RuntimeReadError("Phase-A rollout requires the host state normalizer")
|
| 350 |
+
runtime = materialize_runtime_observation(
|
| 351 |
+
self._session,
|
| 352 |
+
memory_buffer,
|
| 353 |
+
step=step,
|
| 354 |
+
factors=self._factors,
|
| 355 |
+
metadata_seed=self._metadata_seed,
|
| 356 |
+
)
|
| 357 |
+
if runtime.plan.frame_indices.shape != (FRAME_BUDGET,):
|
| 358 |
+
raise RuntimeReadError("Phase-A rollout frame budget drift")
|
| 359 |
+
if runtime.image.shape[0] != TOKEN_BUDGET or runtime.mask.shape != (TOKEN_BUDGET,):
|
| 360 |
+
raise RuntimeReadError("Phase-A rollout token budget drift")
|
| 361 |
+
|
| 362 |
+
normalized_state = np.asarray(normalize_state(runtime.state))
|
| 363 |
+
if normalized_state.shape != runtime.state.shape:
|
| 364 |
+
raise RuntimeReadError("Phase-A rollout normalized state geometry drift")
|
| 365 |
+
if normalized_state.dtype != np.float32:
|
| 366 |
+
raise RuntimeReadError("Phase-A rollout normalized state must be float32")
|
| 367 |
+
if not bool(np.isfinite(normalized_state).all()):
|
| 368 |
+
raise RuntimeReadError("Phase-A rollout normalized state must be finite")
|
| 369 |
+
normalized_state.setflags(write=False)
|
| 370 |
+
|
| 371 |
+
model_inputs: dict[str, np.ndarray] = {
|
| 372 |
+
"static_image_emb": runtime.image,
|
| 373 |
+
"static_pos_emb": runtime.position,
|
| 374 |
+
"static_state_emb": normalized_state,
|
| 375 |
+
"static_mask": runtime.mask,
|
| 376 |
+
**runtime.metadata.to_observation(),
|
| 377 |
+
}
|
| 378 |
+
expected = {
|
| 379 |
+
"static_image_emb",
|
| 380 |
+
"static_pos_emb",
|
| 381 |
+
"static_state_emb",
|
| 382 |
+
"static_mask",
|
| 383 |
+
*OBSERVATION_FIELDS,
|
| 384 |
+
}
|
| 385 |
+
if set(model_inputs) != expected:
|
| 386 |
+
raise RuntimeReadError("Phase-A rollout model input fields drifted")
|
| 387 |
+
return PhaseARolloutMaterialization(runtime=runtime, model_inputs=model_inputs)
|
| 388 |
+
|
| 389 |
+
def receipt(self) -> dict[str, Any]:
|
| 390 |
+
if self._session is None:
|
| 391 |
+
raise RuntimeReadError("Phase-A rollout has no session receipt")
|
| 392 |
+
receipt = self._session.receipt()
|
| 393 |
+
if receipt.get("manager_mode") != self._factors.manager_mode.value:
|
| 394 |
+
raise RuntimeReadError("Phase-A rollout receipt manager_mode drift")
|
| 395 |
+
return receipt
|
| 396 |
+
|
| 397 |
+
def _start_session(self, raw: Any) -> RuntimeReadSession:
|
| 398 |
+
start = _exact_mapping(raw, _START_FIELDS, "Phase-A rollout start")
|
| 399 |
+
if start["schema_version"] != RUNTIME_START_SCHEMA_VERSION:
|
| 400 |
+
raise RuntimeReadError("Phase-A rollout start schema_version mismatch")
|
| 401 |
+
if start["manager_mode"] != self._factors.manager_mode.value:
|
| 402 |
+
raise RuntimeReadError("Phase-A rollout start manager_mode differs from the loaded policy config")
|
| 403 |
+
if _nat(start["metadata_seed"], "start.metadata_seed") != self._metadata_seed:
|
| 404 |
+
raise RuntimeReadError("Phase-A rollout start metadata_seed differs from policy config")
|
| 405 |
+
return RuntimeReadSession.from_reset(
|
| 406 |
+
start["reset"],
|
| 407 |
+
expected_identity_sha256=_sha256(
|
| 408 |
+
start["expected_identity_sha256"],
|
| 409 |
+
"expected_identity_sha256",
|
| 410 |
+
),
|
| 411 |
+
expected_source_identity_sha256=_sha256(
|
| 412 |
+
start["expected_source_identity_sha256"],
|
| 413 |
+
"expected_source_identity_sha256",
|
| 414 |
+
),
|
| 415 |
+
expected_source_contract_sha256=_sha256(
|
| 416 |
+
start["expected_source_contract_sha256"],
|
| 417 |
+
"expected_source_contract_sha256",
|
| 418 |
+
),
|
| 419 |
+
manager_mode=self._factors.manager_mode,
|
| 420 |
+
)
|
| 421 |
+
|
| 422 |
+
def _ack(
|
| 423 |
+
self,
|
| 424 |
+
*,
|
| 425 |
+
batch_sequence: int,
|
| 426 |
+
batch_sha256: str,
|
| 427 |
+
duplicate: bool,
|
| 428 |
+
) -> PhaseARolloutBatchAck:
|
| 429 |
+
return {
|
| 430 |
+
"schema_version": RUNTIME_BATCH_ACK_SCHEMA_VERSION,
|
| 431 |
+
"batch_sequence": batch_sequence,
|
| 432 |
+
"batch_sha256": batch_sha256,
|
| 433 |
+
"duplicate": duplicate,
|
| 434 |
+
"runtime_receipt": self.receipt(),
|
| 435 |
+
}
|
| 436 |
+
|
| 437 |
+
def _issue_prepared(
|
| 438 |
+
self,
|
| 439 |
+
*,
|
| 440 |
+
batch_sequence: int,
|
| 441 |
+
batch_sha256: str,
|
| 442 |
+
duplicate: bool,
|
| 443 |
+
candidate_session: RuntimeReadSession | None,
|
| 444 |
+
) -> PhaseARolloutPreparedBatch:
|
| 445 |
+
preparation_token = object()
|
| 446 |
+
prepared = PhaseARolloutPreparedBatch(
|
| 447 |
+
batch_sequence=batch_sequence,
|
| 448 |
+
batch_sha256=batch_sha256,
|
| 449 |
+
duplicate=duplicate,
|
| 450 |
+
_controller_token=self._controller_token,
|
| 451 |
+
_preparation_token=preparation_token,
|
| 452 |
+
)
|
| 453 |
+
self._prepared_state = _PreparedState(
|
| 454 |
+
prepared=prepared,
|
| 455 |
+
base_session=self._session,
|
| 456 |
+
base_receipt_sha256=self._session_receipt_sha256(self._session),
|
| 457 |
+
base_batch_sequence=self._last_batch_sequence,
|
| 458 |
+
base_batch_sha256=self._last_batch_sha256,
|
| 459 |
+
candidate_session=candidate_session,
|
| 460 |
+
)
|
| 461 |
+
return prepared
|
| 462 |
+
|
| 463 |
+
@staticmethod
|
| 464 |
+
def _session_receipt_sha256(session: RuntimeReadSession | None) -> str | None:
|
| 465 |
+
if session is None:
|
| 466 |
+
return None
|
| 467 |
+
value = session.receipt().get("receipt_sha256")
|
| 468 |
+
return _sha256(value, "runtime receipt_sha256")
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
def controller_from_history_config(history_config: Any) -> PhaseARolloutController | None:
|
| 472 |
+
"""Create the controller iff the loaded model is exactly Phase-A.
|
| 473 |
+
|
| 474 |
+
OmegaConf nodes and plain mappings both provide ``get``. Any malformed
|
| 475 |
+
Phase-A declaration fails instead of returning ``None`` and re-enabling
|
| 476 |
+
legacy FrameSamp.
|
| 477 |
+
"""
|
| 478 |
+
|
| 479 |
+
if history_config is None:
|
| 480 |
+
return None
|
| 481 |
+
perceptual = _optional_config_get(history_config, "perceptual_memory")
|
| 482 |
+
if perceptual is None:
|
| 483 |
+
return None
|
| 484 |
+
frame_selection = _optional_config_get(perceptual, "frame_selection")
|
| 485 |
+
if frame_selection is None:
|
| 486 |
+
return None
|
| 487 |
+
if _optional_config_get(frame_selection, "type") != "picmem_phase_a":
|
| 488 |
+
return None
|
| 489 |
+
if _config_get(history_config, "representation_type") != "perceptual":
|
| 490 |
+
raise RuntimeReadError("picmem_phase_a rollout requires perceptual representation")
|
| 491 |
+
if _config_get(perceptual, "type") != "frame_sampling":
|
| 492 |
+
raise RuntimeReadError("picmem_phase_a rollout requires frame_sampling host memory")
|
| 493 |
+
geometry = (
|
| 494 |
+
int(_config_get(history_config, "budget")),
|
| 495 |
+
int(_config_get(history_config, "token_per_image")),
|
| 496 |
+
int(_config_get(history_config, "num_views")),
|
| 497 |
+
int(_config_get(frame_selection, "frame_budget")),
|
| 498 |
+
int(_config_get(frame_selection, "recent_anchor_count")),
|
| 499 |
+
)
|
| 500 |
+
if geometry != (TOKEN_BUDGET, 16, 1, FRAME_BUDGET, 4):
|
| 501 |
+
raise RuntimeReadError("picmem_phase_a rollout requires 32 frames and exactly 512 visual tokens")
|
| 502 |
+
factors = PhaseAFactors.from_mapping(
|
| 503 |
+
{name: _config_get(frame_selection, name) for name in FACTOR_FIELDS},
|
| 504 |
+
require_explicit=True,
|
| 505 |
+
)
|
| 506 |
+
return PhaseARolloutController(
|
| 507 |
+
factors=factors,
|
| 508 |
+
metadata_seed=_config_get(frame_selection, "metadata_seed"),
|
| 509 |
+
)
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
def _config_get(value: Any, name: str) -> Any:
|
| 513 |
+
result = _optional_config_get(value, name)
|
| 514 |
+
if result is None:
|
| 515 |
+
raise RuntimeReadError(f"Phase-A config is missing {name!r}")
|
| 516 |
+
return result
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
def _optional_config_get(value: Any, name: str) -> Any:
|
| 520 |
+
getter = getattr(value, "get", None)
|
| 521 |
+
if not callable(getter):
|
| 522 |
+
raise RuntimeReadError(f"Phase-A config node {name!r} is not mapping-like")
|
| 523 |
+
return getter(name)
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
def _exact_mapping(raw: Any, fields: frozenset[str], name: str) -> dict[str, Any]:
|
| 527 |
+
if not isinstance(raw, Mapping):
|
| 528 |
+
raise RuntimeReadError(f"{name} must be a mapping")
|
| 529 |
+
missing = fields - set(raw)
|
| 530 |
+
unknown = set(raw) - fields
|
| 531 |
+
if missing or unknown:
|
| 532 |
+
raise RuntimeReadError(f"{name} fields mismatch; missing={sorted(missing)}, unknown={sorted(unknown)}")
|
| 533 |
+
return dict(raw)
|
| 534 |
+
|
| 535 |
+
|
| 536 |
+
def _nat(value: Any, name: str) -> int:
|
| 537 |
+
if isinstance(value, bool) or not isinstance(value, (int, np.integer)) or int(value) < 0:
|
| 538 |
+
raise RuntimeReadError(f"{name} must be a non-negative integer")
|
| 539 |
+
return int(value)
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
def _sha256(value: Any, name: str) -> str:
|
| 543 |
+
if (
|
| 544 |
+
not isinstance(value, str)
|
| 545 |
+
or len(value) != 64
|
| 546 |
+
or any(character not in "0123456789abcdef" for character in value)
|
| 547 |
+
):
|
| 548 |
+
raise RuntimeReadError(f"{name} must be lowercase SHA-256")
|
| 549 |
+
return value
|
| 550 |
+
|
| 551 |
+
|
| 552 |
+
__all__ = [
|
| 553 |
+
"GENESIS_BATCH_SHA256",
|
| 554 |
+
"RUNTIME_BATCH_ACK_SCHEMA_VERSION",
|
| 555 |
+
"RUNTIME_BATCH_SCHEMA_VERSION",
|
| 556 |
+
"RUNTIME_ENVELOPE_SCHEMA_VERSION",
|
| 557 |
+
"RUNTIME_START_SCHEMA_VERSION",
|
| 558 |
+
"PhaseARolloutBatchAck",
|
| 559 |
+
"PhaseARolloutController",
|
| 560 |
+
"PhaseARolloutMaterialization",
|
| 561 |
+
"PhaseARolloutPreparedBatch",
|
| 562 |
+
"controller_from_history_config",
|
| 563 |
+
]
|
checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/policies/semantic_transition_runtime.py
ADDED
|
@@ -0,0 +1,1236 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Thin RoboMME rollout facade for semantic-transition status and memory updates.
|
| 2 |
+
|
| 3 |
+
The adapter owns episode-local state in the evaluator process. It keeps the
|
| 4 |
+
policy server stateless, records only the prefix that actually executes, and
|
| 5 |
+
delegates semantic-window, evidence, writer, and task-context semantics to the
|
| 6 |
+
PIC-Mem runtime contracts.
|
| 7 |
+
|
| 8 |
+
No simulator-private state enters this API. The only observation inputs are
|
| 9 |
+
the normal front/wrist images and the observable eight-value robot state that
|
| 10 |
+
the policy already consumes.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
from collections import deque
|
| 16 |
+
from dataclasses import dataclass, field
|
| 17 |
+
from typing import Any
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
|
| 21 |
+
try:
|
| 22 |
+
from picmem.runtime.grounded_writer import (
|
| 23 |
+
GroundedWriterRequest,
|
| 24 |
+
ValidatedWriterResult,
|
| 25 |
+
WriterDecision,
|
| 26 |
+
WriterRequestPurpose,
|
| 27 |
+
)
|
| 28 |
+
from picmem.runtime.online_stage4 import (
|
| 29 |
+
OnlineStage4MemoryReference,
|
| 30 |
+
OnlineStage4MemoryStore,
|
| 31 |
+
OnlineStage4ValidatedWriterResult,
|
| 32 |
+
OnlineStage4WriterRequest,
|
| 33 |
+
)
|
| 34 |
+
from picmem.runtime.semantic_evidence import (
|
| 35 |
+
RealizedObservation,
|
| 36 |
+
sample_uniform_observations,
|
| 37 |
+
)
|
| 38 |
+
from picmem.runtime.semantic_window import (
|
| 39 |
+
ChunkIngestResult,
|
| 40 |
+
ChunkTransitionStatus,
|
| 41 |
+
SemanticWindowController,
|
| 42 |
+
SemanticWindowPhase,
|
| 43 |
+
SemanticWindowState,
|
| 44 |
+
WindowResolution,
|
| 45 |
+
)
|
| 46 |
+
from picmem.runtime.task_context import (
|
| 47 |
+
OriginalTaskAnchor,
|
| 48 |
+
RenderedPolicyPrompt,
|
| 49 |
+
TaskContextCommit,
|
| 50 |
+
TaskContextStore,
|
| 51 |
+
)
|
| 52 |
+
except ImportError as exc: # pragma: no cover - exercised only in an incorrectly installed host.
|
| 53 |
+
raise ImportError(
|
| 54 |
+
"RoboMME semantic-transition rollout requires the PIC-Mem runtime package"
|
| 55 |
+
) from exc
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
STATUS_HORIZON = 16
|
| 59 |
+
CONTEXT_HORIZON = 48
|
| 60 |
+
ROBOT_VECTOR_DIM = 8
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class SemanticTransitionRolloutError(ValueError):
|
| 64 |
+
"""The host called the rollout adapter out of order or with invalid data."""
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _nonempty(value: object, field_name: str) -> str:
|
| 68 |
+
if not isinstance(value, str) or not value.strip():
|
| 69 |
+
raise SemanticTransitionRolloutError(f"{field_name} must be a non-empty string")
|
| 70 |
+
return value
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _natural(value: object, field_name: str) -> int:
|
| 74 |
+
if isinstance(value, bool) or not isinstance(value, int) or value < 0:
|
| 75 |
+
raise SemanticTransitionRolloutError(f"{field_name} must be a non-negative integer")
|
| 76 |
+
return value
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _readonly_float32(value: Any, *, shape: tuple[int, ...], field_name: str) -> np.ndarray:
|
| 80 |
+
try:
|
| 81 |
+
result = np.asarray(value, dtype=np.float32)
|
| 82 |
+
except (TypeError, ValueError) as exc:
|
| 83 |
+
raise SemanticTransitionRolloutError(f"{field_name} must be a numeric array") from exc
|
| 84 |
+
if result.shape != shape:
|
| 85 |
+
raise SemanticTransitionRolloutError(f"{field_name} must have shape {shape}")
|
| 86 |
+
if not np.isfinite(result).all():
|
| 87 |
+
raise SemanticTransitionRolloutError(f"{field_name} must contain only finite values")
|
| 88 |
+
result = np.array(result, dtype=np.float32, copy=True)
|
| 89 |
+
result.flags.writeable = False
|
| 90 |
+
return result
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def _readonly_bool(value: Any, *, shape: tuple[int, ...], field_name: str) -> np.ndarray:
|
| 94 |
+
result = np.asarray(value)
|
| 95 |
+
if result.dtype != np.bool_ or result.shape != shape:
|
| 96 |
+
raise SemanticTransitionRolloutError(f"{field_name} must be a boolean array with shape {shape}")
|
| 97 |
+
result = np.array(result, dtype=np.bool_, copy=True)
|
| 98 |
+
result.flags.writeable = False
|
| 99 |
+
return result
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
@dataclass(frozen=True, slots=True)
|
| 103 |
+
class SemanticPolicyRequest:
|
| 104 |
+
"""Prompt plus the cheap causal context supplied to one policy call."""
|
| 105 |
+
|
| 106 |
+
step: int
|
| 107 |
+
observation_id: str
|
| 108 |
+
rendered_prompt: RenderedPolicyPrompt
|
| 109 |
+
transition_context_action_delta: np.ndarray = field(repr=False, compare=False)
|
| 110 |
+
transition_context_state_delta: np.ndarray = field(repr=False, compare=False)
|
| 111 |
+
transition_context_relative_age: np.ndarray = field(repr=False, compare=False)
|
| 112 |
+
transition_context_valid_mask: np.ndarray = field(repr=False, compare=False)
|
| 113 |
+
history_required_indices: tuple[int, ...] = ()
|
| 114 |
+
|
| 115 |
+
def __post_init__(self) -> None:
|
| 116 |
+
_natural(self.step, "step")
|
| 117 |
+
_nonempty(self.observation_id, "observation_id")
|
| 118 |
+
if not isinstance(self.rendered_prompt, RenderedPolicyPrompt):
|
| 119 |
+
raise TypeError("rendered_prompt must be RenderedPolicyPrompt")
|
| 120 |
+
object.__setattr__(
|
| 121 |
+
self,
|
| 122 |
+
"transition_context_action_delta",
|
| 123 |
+
_readonly_float32(
|
| 124 |
+
self.transition_context_action_delta,
|
| 125 |
+
shape=(CONTEXT_HORIZON, ROBOT_VECTOR_DIM),
|
| 126 |
+
field_name="transition_context_action_delta",
|
| 127 |
+
),
|
| 128 |
+
)
|
| 129 |
+
object.__setattr__(
|
| 130 |
+
self,
|
| 131 |
+
"transition_context_state_delta",
|
| 132 |
+
_readonly_float32(
|
| 133 |
+
self.transition_context_state_delta,
|
| 134 |
+
shape=(CONTEXT_HORIZON, ROBOT_VECTOR_DIM),
|
| 135 |
+
field_name="transition_context_state_delta",
|
| 136 |
+
),
|
| 137 |
+
)
|
| 138 |
+
object.__setattr__(
|
| 139 |
+
self,
|
| 140 |
+
"transition_context_relative_age",
|
| 141 |
+
_readonly_float32(
|
| 142 |
+
self.transition_context_relative_age,
|
| 143 |
+
shape=(CONTEXT_HORIZON,),
|
| 144 |
+
field_name="transition_context_relative_age",
|
| 145 |
+
),
|
| 146 |
+
)
|
| 147 |
+
object.__setattr__(
|
| 148 |
+
self,
|
| 149 |
+
"transition_context_valid_mask",
|
| 150 |
+
_readonly_bool(
|
| 151 |
+
self.transition_context_valid_mask,
|
| 152 |
+
shape=(CONTEXT_HORIZON,),
|
| 153 |
+
field_name="transition_context_valid_mask",
|
| 154 |
+
),
|
| 155 |
+
)
|
| 156 |
+
history_required_indices = tuple(self.history_required_indices)
|
| 157 |
+
if any(
|
| 158 |
+
isinstance(index, bool) or not isinstance(index, int) or index < 0
|
| 159 |
+
for index in history_required_indices
|
| 160 |
+
):
|
| 161 |
+
raise SemanticTransitionRolloutError(
|
| 162 |
+
"history_required_indices must contain non-negative integers"
|
| 163 |
+
)
|
| 164 |
+
if (
|
| 165 |
+
len(set(history_required_indices)) != len(history_required_indices)
|
| 166 |
+
or history_required_indices != tuple(sorted(history_required_indices))
|
| 167 |
+
):
|
| 168 |
+
raise SemanticTransitionRolloutError(
|
| 169 |
+
"history_required_indices must be unique and sorted"
|
| 170 |
+
)
|
| 171 |
+
object.__setattr__(self, "history_required_indices", history_required_indices)
|
| 172 |
+
|
| 173 |
+
@property
|
| 174 |
+
def prompt(self) -> str:
|
| 175 |
+
return self.rendered_prompt.text
|
| 176 |
+
|
| 177 |
+
def transition_model_inputs(self) -> dict[str, np.ndarray]:
|
| 178 |
+
"""Return unbatched arrays using the Status Head's public input names."""
|
| 179 |
+
|
| 180 |
+
return {
|
| 181 |
+
"transition_context_action_delta": self.transition_context_action_delta,
|
| 182 |
+
"transition_context_state_delta": self.transition_context_state_delta,
|
| 183 |
+
"transition_context_relative_age": self.transition_context_relative_age,
|
| 184 |
+
"transition_context_valid_mask": self.transition_context_valid_mask,
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
@dataclass(frozen=True, slots=True)
|
| 189 |
+
class OnlineStage4PolicyRequest:
|
| 190 |
+
"""One policy call with the same task/memory channels used during training."""
|
| 191 |
+
|
| 192 |
+
step: int
|
| 193 |
+
observation_id: str
|
| 194 |
+
prompt: str
|
| 195 |
+
static_semantic_memory: str
|
| 196 |
+
memory_revision: int
|
| 197 |
+
transition_context_action_delta: np.ndarray = field(repr=False, compare=False)
|
| 198 |
+
transition_context_state_delta: np.ndarray = field(repr=False, compare=False)
|
| 199 |
+
transition_context_relative_age: np.ndarray = field(repr=False, compare=False)
|
| 200 |
+
transition_context_valid_mask: np.ndarray = field(repr=False, compare=False)
|
| 201 |
+
history_required_indices: tuple[int, ...] = ()
|
| 202 |
+
|
| 203 |
+
def __post_init__(self) -> None:
|
| 204 |
+
_natural(self.step, "step")
|
| 205 |
+
_nonempty(self.observation_id, "observation_id")
|
| 206 |
+
_nonempty(self.prompt, "prompt")
|
| 207 |
+
_nonempty(self.static_semantic_memory, "static_semantic_memory")
|
| 208 |
+
_natural(self.memory_revision, "memory_revision")
|
| 209 |
+
object.__setattr__(
|
| 210 |
+
self,
|
| 211 |
+
"transition_context_action_delta",
|
| 212 |
+
_readonly_float32(
|
| 213 |
+
self.transition_context_action_delta,
|
| 214 |
+
shape=(CONTEXT_HORIZON, ROBOT_VECTOR_DIM),
|
| 215 |
+
field_name="transition_context_action_delta",
|
| 216 |
+
),
|
| 217 |
+
)
|
| 218 |
+
object.__setattr__(
|
| 219 |
+
self,
|
| 220 |
+
"transition_context_state_delta",
|
| 221 |
+
_readonly_float32(
|
| 222 |
+
self.transition_context_state_delta,
|
| 223 |
+
shape=(CONTEXT_HORIZON, ROBOT_VECTOR_DIM),
|
| 224 |
+
field_name="transition_context_state_delta",
|
| 225 |
+
),
|
| 226 |
+
)
|
| 227 |
+
object.__setattr__(
|
| 228 |
+
self,
|
| 229 |
+
"transition_context_relative_age",
|
| 230 |
+
_readonly_float32(
|
| 231 |
+
self.transition_context_relative_age,
|
| 232 |
+
shape=(CONTEXT_HORIZON,),
|
| 233 |
+
field_name="transition_context_relative_age",
|
| 234 |
+
),
|
| 235 |
+
)
|
| 236 |
+
object.__setattr__(
|
| 237 |
+
self,
|
| 238 |
+
"transition_context_valid_mask",
|
| 239 |
+
_readonly_bool(
|
| 240 |
+
self.transition_context_valid_mask,
|
| 241 |
+
shape=(CONTEXT_HORIZON,),
|
| 242 |
+
field_name="transition_context_valid_mask",
|
| 243 |
+
),
|
| 244 |
+
)
|
| 245 |
+
required = tuple(self.history_required_indices)
|
| 246 |
+
if any(
|
| 247 |
+
isinstance(index, bool) or not isinstance(index, int) or index < 0
|
| 248 |
+
for index in required
|
| 249 |
+
):
|
| 250 |
+
raise SemanticTransitionRolloutError(
|
| 251 |
+
"history_required_indices must contain non-negative integers"
|
| 252 |
+
)
|
| 253 |
+
if required != tuple(sorted(set(required))):
|
| 254 |
+
raise SemanticTransitionRolloutError(
|
| 255 |
+
"history_required_indices must be unique and sorted"
|
| 256 |
+
)
|
| 257 |
+
object.__setattr__(self, "history_required_indices", required)
|
| 258 |
+
|
| 259 |
+
def transition_model_inputs(self) -> dict[str, np.ndarray]:
|
| 260 |
+
return {
|
| 261 |
+
"transition_context_action_delta": self.transition_context_action_delta,
|
| 262 |
+
"transition_context_state_delta": self.transition_context_state_delta,
|
| 263 |
+
"transition_context_relative_age": self.transition_context_relative_age,
|
| 264 |
+
"transition_context_valid_mask": self.transition_context_valid_mask,
|
| 265 |
+
}
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
@dataclass(frozen=True, slots=True)
|
| 269 |
+
class RealizedRobotDelta:
|
| 270 |
+
"""One actually executed action and its resulting observable state delta."""
|
| 271 |
+
|
| 272 |
+
step: int
|
| 273 |
+
action_delta: np.ndarray = field(repr=False, compare=False)
|
| 274 |
+
state_delta: np.ndarray = field(repr=False, compare=False)
|
| 275 |
+
|
| 276 |
+
def __post_init__(self) -> None:
|
| 277 |
+
_natural(self.step, "step")
|
| 278 |
+
object.__setattr__(
|
| 279 |
+
self,
|
| 280 |
+
"action_delta",
|
| 281 |
+
_readonly_float32(
|
| 282 |
+
self.action_delta,
|
| 283 |
+
shape=(ROBOT_VECTOR_DIM,),
|
| 284 |
+
field_name="action_delta",
|
| 285 |
+
),
|
| 286 |
+
)
|
| 287 |
+
object.__setattr__(
|
| 288 |
+
self,
|
| 289 |
+
"state_delta",
|
| 290 |
+
_readonly_float32(
|
| 291 |
+
self.state_delta,
|
| 292 |
+
shape=(ROBOT_VECTOR_DIM,),
|
| 293 |
+
field_name="state_delta",
|
| 294 |
+
),
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
class RealizedTransitionContext:
|
| 299 |
+
"""Causal Status-Head inputs built only from actions executed in the simulator."""
|
| 300 |
+
|
| 301 |
+
def __init__(self, *, initial_step: int, initial_state: Any) -> None:
|
| 302 |
+
self._current_step = _natural(initial_step, "initial_step")
|
| 303 |
+
self._current_state = _readonly_float32(
|
| 304 |
+
initial_state,
|
| 305 |
+
shape=(ROBOT_VECTOR_DIM,),
|
| 306 |
+
field_name="initial_state",
|
| 307 |
+
)
|
| 308 |
+
self._history: deque[RealizedRobotDelta] = deque(maxlen=CONTEXT_HORIZON)
|
| 309 |
+
|
| 310 |
+
@property
|
| 311 |
+
def history(self) -> tuple[RealizedRobotDelta, ...]:
|
| 312 |
+
return tuple(self._history)
|
| 313 |
+
|
| 314 |
+
def record(
|
| 315 |
+
self,
|
| 316 |
+
*,
|
| 317 |
+
step: int,
|
| 318 |
+
action: Any,
|
| 319 |
+
resulting_state: Any,
|
| 320 |
+
) -> RealizedRobotDelta:
|
| 321 |
+
step = _natural(step, "step")
|
| 322 |
+
if step != self._current_step + 1:
|
| 323 |
+
raise SemanticTransitionRolloutError(
|
| 324 |
+
f"realized context steps must be contiguous; expected {self._current_step + 1}, got {step}"
|
| 325 |
+
)
|
| 326 |
+
executed_action = _readonly_float32(
|
| 327 |
+
action,
|
| 328 |
+
shape=(ROBOT_VECTOR_DIM,),
|
| 329 |
+
field_name="action",
|
| 330 |
+
)
|
| 331 |
+
post_state = _readonly_float32(
|
| 332 |
+
resulting_state,
|
| 333 |
+
shape=(ROBOT_VECTOR_DIM,),
|
| 334 |
+
field_name="resulting_state",
|
| 335 |
+
)
|
| 336 |
+
action_delta = np.empty(ROBOT_VECTOR_DIM, dtype=np.float32)
|
| 337 |
+
action_delta[:7] = executed_action[:7] - self._current_state[:7]
|
| 338 |
+
action_delta[7] = executed_action[7]
|
| 339 |
+
realized = RealizedRobotDelta(
|
| 340 |
+
step=step,
|
| 341 |
+
action_delta=action_delta,
|
| 342 |
+
state_delta=post_state - self._current_state,
|
| 343 |
+
)
|
| 344 |
+
self._history.append(realized)
|
| 345 |
+
self._current_step = step
|
| 346 |
+
self._current_state = post_state
|
| 347 |
+
return realized
|
| 348 |
+
|
| 349 |
+
def model_inputs(self) -> dict[str, np.ndarray]:
|
| 350 |
+
action_delta = np.zeros((CONTEXT_HORIZON, ROBOT_VECTOR_DIM), dtype=np.float32)
|
| 351 |
+
state_delta = np.zeros((CONTEXT_HORIZON, ROBOT_VECTOR_DIM), dtype=np.float32)
|
| 352 |
+
relative_age = np.zeros(CONTEXT_HORIZON, dtype=np.float32)
|
| 353 |
+
valid_mask = np.zeros(CONTEXT_HORIZON, dtype=np.bool_)
|
| 354 |
+
history = tuple(self._history)
|
| 355 |
+
left_padding = CONTEXT_HORIZON - len(history)
|
| 356 |
+
for index, item in enumerate(history):
|
| 357 |
+
row = left_padding + index
|
| 358 |
+
action_delta[row] = item.action_delta
|
| 359 |
+
state_delta[row] = item.state_delta
|
| 360 |
+
relative_age[row] = (len(history) - index) / CONTEXT_HORIZON
|
| 361 |
+
valid_mask[row] = True
|
| 362 |
+
return {
|
| 363 |
+
"transition_context_action_delta": action_delta,
|
| 364 |
+
"transition_context_state_delta": state_delta,
|
| 365 |
+
"transition_context_relative_age": relative_age,
|
| 366 |
+
"transition_context_valid_mask": valid_mask,
|
| 367 |
+
}
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
@dataclass(frozen=True, slots=True)
|
| 371 |
+
class WriterApplication:
|
| 372 |
+
"""One locally validated writer result applied at a chunk boundary."""
|
| 373 |
+
|
| 374 |
+
request_id: str
|
| 375 |
+
decision: WriterDecision
|
| 376 |
+
context_commit: TaskContextCommit | None
|
| 377 |
+
window_resolution_applied: bool
|
| 378 |
+
rendered_prompt: RenderedPolicyPrompt
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
@dataclass(frozen=True, slots=True)
|
| 382 |
+
class OnlineStage4WriterApplication:
|
| 383 |
+
"""One operation resolved at a boundary, with the resulting policy memory."""
|
| 384 |
+
|
| 385 |
+
request_id: str
|
| 386 |
+
operation: str
|
| 387 |
+
memory_committed: bool
|
| 388 |
+
memory_before_revision: int
|
| 389 |
+
memory_after_revision: int
|
| 390 |
+
window_resolution_applied: bool
|
| 391 |
+
static_semantic_memory: str
|
| 392 |
+
history_required_indices: tuple[int, ...]
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
@dataclass(slots=True)
|
| 396 |
+
class _PendingActionChunk:
|
| 397 |
+
chunk_id: str
|
| 398 |
+
start_step: int
|
| 399 |
+
executable_actions: np.ndarray
|
| 400 |
+
executed_count: int = 0
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
class SemanticTransitionRolloutAdapter:
|
| 404 |
+
"""Episode-local bridge from RoboMME rollout calls to PIC-Mem runtime state."""
|
| 405 |
+
|
| 406 |
+
def __init__(
|
| 407 |
+
self,
|
| 408 |
+
*,
|
| 409 |
+
episode_nonce: str,
|
| 410 |
+
original_instruction: str,
|
| 411 |
+
initial_step: int,
|
| 412 |
+
initial_state: Any,
|
| 413 |
+
initial_front_image: Any,
|
| 414 |
+
initial_wrist_image: Any | None = None,
|
| 415 |
+
initial_observation_id: str | None = None,
|
| 416 |
+
initial_subgoal: str | None = None,
|
| 417 |
+
confirmation_tail: int = 4,
|
| 418 |
+
span_threshold: float = 0.5,
|
| 419 |
+
last_span_threshold: float = 0.5,
|
| 420 |
+
cooldown_chunks: int = 1,
|
| 421 |
+
) -> None:
|
| 422 |
+
nonce = _nonempty(episode_nonce, "episode_nonce")
|
| 423 |
+
step = _natural(initial_step, "initial_step")
|
| 424 |
+
anchor = OriginalTaskAnchor(original_instruction)
|
| 425 |
+
self._task_context = TaskContextStore(anchor, active_subgoal=initial_subgoal)
|
| 426 |
+
self._window = SemanticWindowController(
|
| 427 |
+
nonce,
|
| 428 |
+
status_horizon=STATUS_HORIZON,
|
| 429 |
+
max_realized_steps=CONTEXT_HORIZON,
|
| 430 |
+
confirmation_tail=confirmation_tail,
|
| 431 |
+
span_threshold=span_threshold,
|
| 432 |
+
last_span_threshold=last_span_threshold,
|
| 433 |
+
cooldown_chunks=cooldown_chunks,
|
| 434 |
+
)
|
| 435 |
+
initial_robot_state = _readonly_float32(
|
| 436 |
+
initial_state,
|
| 437 |
+
shape=(ROBOT_VECTOR_DIM,),
|
| 438 |
+
field_name="initial_state",
|
| 439 |
+
)
|
| 440 |
+
self._realized_context = RealizedTransitionContext(
|
| 441 |
+
initial_step=step,
|
| 442 |
+
initial_state=initial_robot_state,
|
| 443 |
+
)
|
| 444 |
+
self._current_observation = RealizedObservation(
|
| 445 |
+
observation_id=(
|
| 446 |
+
initial_observation_id
|
| 447 |
+
if initial_observation_id is not None
|
| 448 |
+
else f"{nonce}:observation:{step}"
|
| 449 |
+
),
|
| 450 |
+
step=step,
|
| 451 |
+
front_image=initial_front_image,
|
| 452 |
+
wrist_image=initial_wrist_image,
|
| 453 |
+
robot_state=initial_robot_state,
|
| 454 |
+
)
|
| 455 |
+
self._awaiting_policy_response: SemanticPolicyRequest | None = None
|
| 456 |
+
self._pending_chunk: _PendingActionChunk | None = None
|
| 457 |
+
self._preempted_chunk_result: ChunkIngestResult | None = None
|
| 458 |
+
self._writer_request: GroundedWriterRequest | None = None
|
| 459 |
+
self._writer_applications: dict[
|
| 460 |
+
str,
|
| 461 |
+
tuple[ValidatedWriterResult, bool, WriterApplication],
|
| 462 |
+
] = {}
|
| 463 |
+
self._initial_writer_prepared = False
|
| 464 |
+
self._history_required_indices: tuple[int, ...] = ()
|
| 465 |
+
|
| 466 |
+
@property
|
| 467 |
+
def original_task(self) -> OriginalTaskAnchor:
|
| 468 |
+
return self._task_context.anchor
|
| 469 |
+
|
| 470 |
+
@property
|
| 471 |
+
def rendered_prompt(self) -> RenderedPolicyPrompt:
|
| 472 |
+
return self._task_context.render()
|
| 473 |
+
|
| 474 |
+
@property
|
| 475 |
+
def current_step(self) -> int:
|
| 476 |
+
return self._current_observation.step
|
| 477 |
+
|
| 478 |
+
@property
|
| 479 |
+
def phase(self) -> SemanticWindowPhase:
|
| 480 |
+
return self._window.phase
|
| 481 |
+
|
| 482 |
+
@property
|
| 483 |
+
def history(self) -> tuple[RealizedRobotDelta, ...]:
|
| 484 |
+
return self._realized_context.history
|
| 485 |
+
|
| 486 |
+
@property
|
| 487 |
+
def pending_chunk_id(self) -> str | None:
|
| 488 |
+
return self._pending_chunk.chunk_id if self._pending_chunk is not None else None
|
| 489 |
+
|
| 490 |
+
@property
|
| 491 |
+
def preempted_chunk_result(self) -> ChunkIngestResult | None:
|
| 492 |
+
"""Return the latest proposal canceled before action execution, if any."""
|
| 493 |
+
|
| 494 |
+
return self._preempted_chunk_result
|
| 495 |
+
|
| 496 |
+
def prepare_policy_request(self) -> SemanticPolicyRequest:
|
| 497 |
+
"""Open one policy call with the immutable anchor plus current context."""
|
| 498 |
+
|
| 499 |
+
if self._awaiting_policy_response is not None:
|
| 500 |
+
raise SemanticTransitionRolloutError("a policy response is already pending")
|
| 501 |
+
if self._pending_chunk is not None:
|
| 502 |
+
raise SemanticTransitionRolloutError("finish the current action chunk before the next policy call")
|
| 503 |
+
if self._window.ready_window is not None or self._writer_request is not None:
|
| 504 |
+
raise SemanticTransitionRolloutError("resolve the writer-ready window before the next policy call")
|
| 505 |
+
transition_context = self._realized_context.model_inputs()
|
| 506 |
+
request = SemanticPolicyRequest(
|
| 507 |
+
step=self.current_step,
|
| 508 |
+
observation_id=self._current_observation.observation_id,
|
| 509 |
+
rendered_prompt=self.rendered_prompt,
|
| 510 |
+
history_required_indices=self._history_required_indices,
|
| 511 |
+
**transition_context,
|
| 512 |
+
)
|
| 513 |
+
self._awaiting_policy_response = request
|
| 514 |
+
return request
|
| 515 |
+
|
| 516 |
+
def prepare_initial_writer_request(
|
| 517 |
+
self,
|
| 518 |
+
*,
|
| 519 |
+
front_images: tuple[Any, ...] | list[Any],
|
| 520 |
+
wrist_images: tuple[Any | None, ...] | list[Any | None],
|
| 521 |
+
) -> GroundedWriterRequest:
|
| 522 |
+
"""Build one pre-action request from demonstration history plus execution start."""
|
| 523 |
+
|
| 524 |
+
if self._initial_writer_prepared:
|
| 525 |
+
raise SemanticTransitionRolloutError("initial writer request was already prepared")
|
| 526 |
+
if (
|
| 527 |
+
self._awaiting_policy_response is not None
|
| 528 |
+
or self._pending_chunk is not None
|
| 529 |
+
or self._writer_request is not None
|
| 530 |
+
or self._window.phase is not SemanticWindowPhase.CLOSED
|
| 531 |
+
or self._realized_context.history
|
| 532 |
+
):
|
| 533 |
+
raise SemanticTransitionRolloutError(
|
| 534 |
+
"initial writer request must precede every policy call and executed action"
|
| 535 |
+
)
|
| 536 |
+
fronts = tuple(front_images)
|
| 537 |
+
wrists = tuple(wrist_images)
|
| 538 |
+
if len(fronts) < 2 or len(fronts) != len(wrists):
|
| 539 |
+
raise SemanticTransitionRolloutError(
|
| 540 |
+
"pre-action evidence requires aligned demonstration and execution-start images"
|
| 541 |
+
)
|
| 542 |
+
source_observations = tuple(
|
| 543 |
+
RealizedObservation(
|
| 544 |
+
observation_id=f"{self._window.episode_nonce}:history:{index}",
|
| 545 |
+
step=index,
|
| 546 |
+
front_image=front,
|
| 547 |
+
wrist_image=wrists[index],
|
| 548 |
+
)
|
| 549 |
+
for index, front in enumerate(fronts)
|
| 550 |
+
)
|
| 551 |
+
selected = sample_uniform_observations(source_observations, max_timepoints=16)
|
| 552 |
+
history_indices = tuple(observation.step for observation in selected)
|
| 553 |
+
evidence = tuple(
|
| 554 |
+
RealizedObservation(
|
| 555 |
+
observation_id=observation.observation_id,
|
| 556 |
+
step=timepoint_id,
|
| 557 |
+
front_image=observation.front_image,
|
| 558 |
+
wrist_image=observation.wrist_image,
|
| 559 |
+
)
|
| 560 |
+
for timepoint_id, observation in enumerate(selected)
|
| 561 |
+
)
|
| 562 |
+
window = SemanticWindowState(
|
| 563 |
+
window_id=f"{self._window.episode_nonce}:initial-memory:1",
|
| 564 |
+
episode_nonce=self._window.episode_nonce,
|
| 565 |
+
start_step=0,
|
| 566 |
+
current_step=len(evidence) - 1,
|
| 567 |
+
max_end_step=len(evidence) - 1,
|
| 568 |
+
observations=evidence,
|
| 569 |
+
chunk_ids=(f"{self._window.episode_nonce}:pre-action-demonstration",),
|
| 570 |
+
phase=SemanticWindowPhase.READY,
|
| 571 |
+
)
|
| 572 |
+
request = GroundedWriterRequest(
|
| 573 |
+
original_task=self._task_context.anchor,
|
| 574 |
+
task_context=self._task_context.current,
|
| 575 |
+
window=window,
|
| 576 |
+
evidence=evidence,
|
| 577 |
+
purpose=WriterRequestPurpose.PRE_ACTION_DEMONSTRATION,
|
| 578 |
+
history_indices=history_indices,
|
| 579 |
+
)
|
| 580 |
+
self._initial_writer_prepared = True
|
| 581 |
+
self._writer_request = request
|
| 582 |
+
return request
|
| 583 |
+
|
| 584 |
+
def cancel_policy_request(self) -> None:
|
| 585 |
+
"""Release a failed/aborted policy call without changing episode state."""
|
| 586 |
+
|
| 587 |
+
if self._awaiting_policy_response is None:
|
| 588 |
+
raise SemanticTransitionRolloutError("no policy response is pending")
|
| 589 |
+
self._awaiting_policy_response = None
|
| 590 |
+
|
| 591 |
+
def accept_policy_response(
|
| 592 |
+
self,
|
| 593 |
+
*,
|
| 594 |
+
chunk_id: str,
|
| 595 |
+
actions: Any,
|
| 596 |
+
p_transition_span: float,
|
| 597 |
+
p_transition_last_given_span: float = 0.0,
|
| 598 |
+
) -> np.ndarray:
|
| 599 |
+
"""Bind a response and return its safe read-only executable prefix.
|
| 600 |
+
|
| 601 |
+
An active window followed by a negative span proposal returns an empty
|
| 602 |
+
prefix: all 16 proposed actions are canceled before environment execution
|
| 603 |
+
while the realized positive window is sent to the writer.
|
| 604 |
+
"""
|
| 605 |
+
|
| 606 |
+
request = self._awaiting_policy_response
|
| 607 |
+
if request is None:
|
| 608 |
+
raise SemanticTransitionRolloutError("accept_policy_response requires an open policy call")
|
| 609 |
+
if self._pending_chunk is not None:
|
| 610 |
+
raise SemanticTransitionRolloutError("an action chunk is already pending")
|
| 611 |
+
chunk_id = _nonempty(chunk_id, "chunk_id")
|
| 612 |
+
try:
|
| 613 |
+
proposed = np.asarray(actions, dtype=np.float32)
|
| 614 |
+
except (TypeError, ValueError) as exc:
|
| 615 |
+
raise SemanticTransitionRolloutError("actions must be a numeric matrix") from exc
|
| 616 |
+
if proposed.ndim != 2 or proposed.shape[0] < STATUS_HORIZON or proposed.shape[1] != ROBOT_VECTOR_DIM:
|
| 617 |
+
raise SemanticTransitionRolloutError(
|
| 618 |
+
f"actions must have shape [N, {ROBOT_VECTOR_DIM}] with N >= {STATUS_HORIZON}"
|
| 619 |
+
)
|
| 620 |
+
if not np.isfinite(proposed).all():
|
| 621 |
+
raise SemanticTransitionRolloutError("actions must contain only finite values")
|
| 622 |
+
executable = np.array(proposed[:STATUS_HORIZON], dtype=np.float32, copy=True)
|
| 623 |
+
executable.flags.writeable = False
|
| 624 |
+
try:
|
| 625 |
+
raw_span = np.asarray(p_transition_span)
|
| 626 |
+
except (TypeError, ValueError) as exc:
|
| 627 |
+
raise SemanticTransitionRolloutError("p_transition_span must be numeric") from exc
|
| 628 |
+
if (
|
| 629 |
+
raw_span.shape != ()
|
| 630 |
+
or not np.issubdtype(raw_span.dtype, np.number)
|
| 631 |
+
or np.issubdtype(raw_span.dtype, np.bool_)
|
| 632 |
+
):
|
| 633 |
+
raise SemanticTransitionRolloutError("p_transition_span must be a numeric scalar")
|
| 634 |
+
try:
|
| 635 |
+
raw_last_span = np.asarray(p_transition_last_given_span)
|
| 636 |
+
except (TypeError, ValueError) as exc:
|
| 637 |
+
raise SemanticTransitionRolloutError(
|
| 638 |
+
"p_transition_last_given_span must be numeric"
|
| 639 |
+
) from exc
|
| 640 |
+
if (
|
| 641 |
+
raw_last_span.shape != ()
|
| 642 |
+
or not np.issubdtype(raw_last_span.dtype, np.number)
|
| 643 |
+
or np.issubdtype(raw_last_span.dtype, np.bool_)
|
| 644 |
+
):
|
| 645 |
+
raise SemanticTransitionRolloutError(
|
| 646 |
+
"p_transition_last_given_span must be a numeric scalar"
|
| 647 |
+
)
|
| 648 |
+
status = ChunkTransitionStatus(
|
| 649 |
+
p_transition_span=float(raw_span),
|
| 650 |
+
p_transition_last_given_span=float(raw_last_span),
|
| 651 |
+
)
|
| 652 |
+
preempted = self._window.start_chunk(
|
| 653 |
+
chunk_id=chunk_id,
|
| 654 |
+
start_step=request.step,
|
| 655 |
+
pre_observation=self._current_observation,
|
| 656 |
+
status=status,
|
| 657 |
+
)
|
| 658 |
+
if preempted is not None:
|
| 659 |
+
if not preempted.preempted or not preempted.ready:
|
| 660 |
+
raise AssertionError("proposal-boundary result must be a ready preemption")
|
| 661 |
+
self._preempted_chunk_result = preempted
|
| 662 |
+
self._awaiting_policy_response = None
|
| 663 |
+
self._cache_writer_request()
|
| 664 |
+
canceled = np.empty((0, ROBOT_VECTOR_DIM), dtype=np.float32)
|
| 665 |
+
canceled.flags.writeable = False
|
| 666 |
+
return canceled
|
| 667 |
+
execution_limit = self._window.pending_execution_limit
|
| 668 |
+
if execution_limit is None:
|
| 669 |
+
raise AssertionError("accepted action proposal has no controller execution limit")
|
| 670 |
+
executable = np.array(executable[:execution_limit], dtype=np.float32, copy=True)
|
| 671 |
+
executable.flags.writeable = False
|
| 672 |
+
self._pending_chunk = _PendingActionChunk(
|
| 673 |
+
chunk_id=chunk_id,
|
| 674 |
+
start_step=request.step,
|
| 675 |
+
executable_actions=executable,
|
| 676 |
+
)
|
| 677 |
+
self._awaiting_policy_response = None
|
| 678 |
+
return executable
|
| 679 |
+
|
| 680 |
+
def record_executed_offset(
|
| 681 |
+
self,
|
| 682 |
+
*,
|
| 683 |
+
chunk_id: str,
|
| 684 |
+
offset: int,
|
| 685 |
+
resulting_state: Any,
|
| 686 |
+
front_image: Any,
|
| 687 |
+
wrist_image: Any | None = None,
|
| 688 |
+
observation_id: str | None = None,
|
| 689 |
+
) -> RealizedRobotDelta:
|
| 690 |
+
"""Record one sequential action only after its real observation exists."""
|
| 691 |
+
|
| 692 |
+
pending = self._require_pending_chunk(chunk_id)
|
| 693 |
+
if isinstance(offset, bool) or not isinstance(offset, int):
|
| 694 |
+
raise SemanticTransitionRolloutError("offset must be an integer")
|
| 695 |
+
expected_offset = pending.executed_count + 1
|
| 696 |
+
if offset != expected_offset:
|
| 697 |
+
raise SemanticTransitionRolloutError(
|
| 698 |
+
f"executed offsets must be contiguous; expected {expected_offset}, got {offset}"
|
| 699 |
+
)
|
| 700 |
+
if offset > len(pending.executable_actions):
|
| 701 |
+
raise SemanticTransitionRolloutError(
|
| 702 |
+
"offset exceeds the controller-bounded executable prefix"
|
| 703 |
+
)
|
| 704 |
+
post_state = _readonly_float32(
|
| 705 |
+
resulting_state,
|
| 706 |
+
shape=(ROBOT_VECTOR_DIM,),
|
| 707 |
+
field_name="resulting_state",
|
| 708 |
+
)
|
| 709 |
+
resulting_step = pending.start_step + offset
|
| 710 |
+
observation = RealizedObservation(
|
| 711 |
+
observation_id=(
|
| 712 |
+
observation_id
|
| 713 |
+
if observation_id is not None
|
| 714 |
+
else f"{self._window.episode_nonce}:observation:{resulting_step}"
|
| 715 |
+
),
|
| 716 |
+
step=resulting_step,
|
| 717 |
+
front_image=front_image,
|
| 718 |
+
wrist_image=wrist_image,
|
| 719 |
+
robot_state=post_state,
|
| 720 |
+
)
|
| 721 |
+
realized = self._realized_context.record(
|
| 722 |
+
step=resulting_step,
|
| 723 |
+
action=pending.executable_actions[offset - 1],
|
| 724 |
+
resulting_state=post_state,
|
| 725 |
+
)
|
| 726 |
+
|
| 727 |
+
self._window.record_executed_offset(
|
| 728 |
+
chunk_id=chunk_id,
|
| 729 |
+
offset=offset,
|
| 730 |
+
observation=observation,
|
| 731 |
+
)
|
| 732 |
+
self._current_observation = observation
|
| 733 |
+
pending.executed_count += 1
|
| 734 |
+
return realized
|
| 735 |
+
|
| 736 |
+
def finish_chunk(self, *, chunk_id: str) -> ChunkIngestResult:
|
| 737 |
+
"""Close the chunk and cancel every unexecuted action."""
|
| 738 |
+
|
| 739 |
+
self._require_pending_chunk(chunk_id)
|
| 740 |
+
result = self._window.finish_chunk(chunk_id=chunk_id)
|
| 741 |
+
self._pending_chunk = None
|
| 742 |
+
if result.ready:
|
| 743 |
+
self._cache_writer_request()
|
| 744 |
+
return result
|
| 745 |
+
|
| 746 |
+
def writer_request_if_ready(self) -> GroundedWriterRequest | None:
|
| 747 |
+
"""Return the cached uniform evidence request without doing image packaging."""
|
| 748 |
+
|
| 749 |
+
return self._writer_request
|
| 750 |
+
|
| 751 |
+
def require_writer_request(self) -> GroundedWriterRequest:
|
| 752 |
+
request = self._writer_request
|
| 753 |
+
if request is None:
|
| 754 |
+
raise SemanticTransitionRolloutError("no semantic window is writer-ready")
|
| 755 |
+
return request
|
| 756 |
+
|
| 757 |
+
def apply_writer_result(
|
| 758 |
+
self,
|
| 759 |
+
result: ValidatedWriterResult,
|
| 760 |
+
*,
|
| 761 |
+
commit_context: bool = True,
|
| 762 |
+
) -> WriterApplication:
|
| 763 |
+
"""Resolve one writer result at a policy boundary.
|
| 764 |
+
|
| 765 |
+
``commit_context=False`` is the shadow-mode path: the real Gemini
|
| 766 |
+
decision remains auditable and resolves the ready window, but an
|
| 767 |
+
``update`` proposal cannot mutate the task-context revision.
|
| 768 |
+
"""
|
| 769 |
+
|
| 770 |
+
if self._awaiting_policy_response is not None or self._pending_chunk is not None:
|
| 771 |
+
raise SemanticTransitionRolloutError("writer results may be applied only between policy calls")
|
| 772 |
+
if not isinstance(result, ValidatedWriterResult):
|
| 773 |
+
raise TypeError("result must be ValidatedWriterResult")
|
| 774 |
+
if type(commit_context) is not bool:
|
| 775 |
+
raise TypeError("commit_context must be bool")
|
| 776 |
+
previous = self._writer_applications.get(result.request_id)
|
| 777 |
+
if previous is not None:
|
| 778 |
+
previous_result, previous_commit_context, application = previous
|
| 779 |
+
if previous_result != result:
|
| 780 |
+
raise SemanticTransitionRolloutError("writer request id was reused with different content")
|
| 781 |
+
if previous_commit_context is not commit_context:
|
| 782 |
+
raise SemanticTransitionRolloutError(
|
| 783 |
+
"writer request retry cannot change commit_context mode"
|
| 784 |
+
)
|
| 785 |
+
return application
|
| 786 |
+
request = self._writer_request
|
| 787 |
+
if request is None:
|
| 788 |
+
raise SemanticTransitionRolloutError("no writer-ready request is awaiting a result")
|
| 789 |
+
if result.request_id != request.request_id or result.window_id != request.window.window_id:
|
| 790 |
+
raise SemanticTransitionRolloutError("writer result does not match the current request/window")
|
| 791 |
+
if request.purpose is WriterRequestPurpose.PRE_ACTION_DEMONSTRATION:
|
| 792 |
+
context_commit = None
|
| 793 |
+
if result.decision is WriterDecision.UPDATE and commit_context:
|
| 794 |
+
if result.context_delta is None:
|
| 795 |
+
raise SemanticTransitionRolloutError(
|
| 796 |
+
"update result is missing its CAS context delta"
|
| 797 |
+
)
|
| 798 |
+
context_commit = self._task_context.commit(result.context_delta)
|
| 799 |
+
self._history_required_indices = tuple(
|
| 800 |
+
request.history_indices[timepoint_id]
|
| 801 |
+
for timepoint_id in result.proposal.evidence_timepoint_ids
|
| 802 |
+
)
|
| 803 |
+
elif result.decision is not WriterDecision.UPDATE and result.context_delta is not None:
|
| 804 |
+
raise SemanticTransitionRolloutError(
|
| 805 |
+
"non-update result must not contain a context delta"
|
| 806 |
+
)
|
| 807 |
+
application = WriterApplication(
|
| 808 |
+
request_id=result.request_id,
|
| 809 |
+
decision=result.decision,
|
| 810 |
+
context_commit=context_commit,
|
| 811 |
+
window_resolution_applied=False,
|
| 812 |
+
rendered_prompt=self.rendered_prompt,
|
| 813 |
+
)
|
| 814 |
+
self._writer_applications[result.request_id] = (
|
| 815 |
+
result,
|
| 816 |
+
commit_context,
|
| 817 |
+
application,
|
| 818 |
+
)
|
| 819 |
+
self._writer_request = None
|
| 820 |
+
return application
|
| 821 |
+
ready = self._window.ready_window
|
| 822 |
+
if ready is None or ready.window_id != result.window_id:
|
| 823 |
+
raise SemanticTransitionRolloutError("writer result window is no longer ready")
|
| 824 |
+
|
| 825 |
+
context_commit = None
|
| 826 |
+
if result.decision is WriterDecision.UPDATE and commit_context:
|
| 827 |
+
if result.context_delta is None:
|
| 828 |
+
raise SemanticTransitionRolloutError("update result is missing its CAS context delta")
|
| 829 |
+
context_commit = self._task_context.commit(result.context_delta)
|
| 830 |
+
elif result.decision is not WriterDecision.UPDATE and result.context_delta is not None:
|
| 831 |
+
raise SemanticTransitionRolloutError("non-update result must not contain a context delta")
|
| 832 |
+
|
| 833 |
+
resolution = WindowResolution(result.decision.value)
|
| 834 |
+
resolution_applied = self._window.resolve_ready_window(
|
| 835 |
+
window_id=result.window_id,
|
| 836 |
+
decision=resolution,
|
| 837 |
+
)
|
| 838 |
+
application = WriterApplication(
|
| 839 |
+
request_id=result.request_id,
|
| 840 |
+
decision=result.decision,
|
| 841 |
+
context_commit=context_commit,
|
| 842 |
+
window_resolution_applied=resolution_applied,
|
| 843 |
+
rendered_prompt=self.rendered_prompt,
|
| 844 |
+
)
|
| 845 |
+
self._writer_applications[result.request_id] = (result, commit_context, application)
|
| 846 |
+
self._writer_request = None
|
| 847 |
+
self._preempted_chunk_result = None
|
| 848 |
+
return application
|
| 849 |
+
|
| 850 |
+
def _cache_writer_request(self) -> None:
|
| 851 |
+
ready = self._window.ready_window
|
| 852 |
+
if ready is None:
|
| 853 |
+
raise AssertionError("writer request requires a ready semantic window")
|
| 854 |
+
evidence = sample_uniform_observations(ready.observations, max_timepoints=16)
|
| 855 |
+
self._writer_request = GroundedWriterRequest(
|
| 856 |
+
original_task=self._task_context.anchor,
|
| 857 |
+
task_context=self._task_context.current,
|
| 858 |
+
window=ready,
|
| 859 |
+
evidence=evidence,
|
| 860 |
+
)
|
| 861 |
+
|
| 862 |
+
def _require_pending_chunk(self, chunk_id: str) -> _PendingActionChunk:
|
| 863 |
+
pending = self._pending_chunk
|
| 864 |
+
if pending is None:
|
| 865 |
+
raise SemanticTransitionRolloutError("no action chunk is pending")
|
| 866 |
+
if chunk_id != pending.chunk_id:
|
| 867 |
+
raise SemanticTransitionRolloutError(
|
| 868 |
+
f"pending chunk is {pending.chunk_id!r}, not {chunk_id!r}"
|
| 869 |
+
)
|
| 870 |
+
return pending
|
| 871 |
+
|
| 872 |
+
|
| 873 |
+
class OnlineStage4SemanticTransitionRolloutAdapter(SemanticTransitionRolloutAdapter):
|
| 874 |
+
"""Status-window adapter whose writer mutates Stage4 memory, not task text."""
|
| 875 |
+
|
| 876 |
+
def __init__(
|
| 877 |
+
self,
|
| 878 |
+
*,
|
| 879 |
+
episode_nonce: str,
|
| 880 |
+
memory_episode_id: str,
|
| 881 |
+
original_instruction: str,
|
| 882 |
+
initial_step: int,
|
| 883 |
+
history_frame_offset: int,
|
| 884 |
+
episode_frame_limit: int,
|
| 885 |
+
episode_fps: float,
|
| 886 |
+
initial_state: Any,
|
| 887 |
+
initial_front_image: Any,
|
| 888 |
+
initial_wrist_image: Any | None = None,
|
| 889 |
+
initial_observation_id: str | None = None,
|
| 890 |
+
confirmation_tail: int = 4,
|
| 891 |
+
span_threshold: float = 0.5,
|
| 892 |
+
last_span_threshold: float = 0.5,
|
| 893 |
+
cooldown_chunks: int = 1,
|
| 894 |
+
) -> None:
|
| 895 |
+
super().__init__(
|
| 896 |
+
episode_nonce=episode_nonce,
|
| 897 |
+
original_instruction=original_instruction,
|
| 898 |
+
initial_step=initial_step,
|
| 899 |
+
initial_state=initial_state,
|
| 900 |
+
initial_front_image=initial_front_image,
|
| 901 |
+
initial_wrist_image=initial_wrist_image,
|
| 902 |
+
initial_observation_id=initial_observation_id,
|
| 903 |
+
initial_subgoal=None,
|
| 904 |
+
confirmation_tail=confirmation_tail,
|
| 905 |
+
span_threshold=span_threshold,
|
| 906 |
+
last_span_threshold=last_span_threshold,
|
| 907 |
+
cooldown_chunks=cooldown_chunks,
|
| 908 |
+
)
|
| 909 |
+
self._online_memory = OnlineStage4MemoryStore(episode_id=memory_episode_id)
|
| 910 |
+
self._history_frame_offset = _natural(history_frame_offset, "history_frame_offset")
|
| 911 |
+
self._episode_frame_limit = _natural(episode_frame_limit, "episode_frame_limit")
|
| 912 |
+
if initial_step > self._episode_frame_limit:
|
| 913 |
+
raise SemanticTransitionRolloutError(
|
| 914 |
+
"initial_step cannot exceed episode_frame_limit"
|
| 915 |
+
)
|
| 916 |
+
if (
|
| 917 |
+
isinstance(episode_fps, bool)
|
| 918 |
+
or not isinstance(episode_fps, int | float)
|
| 919 |
+
or not np.isfinite(episode_fps)
|
| 920 |
+
or episode_fps <= 0
|
| 921 |
+
):
|
| 922 |
+
raise SemanticTransitionRolloutError(
|
| 923 |
+
"episode_fps must be a positive finite number"
|
| 924 |
+
)
|
| 925 |
+
self._episode_fps = float(episode_fps)
|
| 926 |
+
self._initial_writer_prefixes: list[tuple[RealizedObservation, ...]] = []
|
| 927 |
+
self._initial_writer_sequence = 0
|
| 928 |
+
self._previous_online_writer_transition_end_frame: int | None = None
|
| 929 |
+
self._online_writer_applications: dict[
|
| 930 |
+
str,
|
| 931 |
+
tuple[
|
| 932 |
+
OnlineStage4ValidatedWriterResult,
|
| 933 |
+
bool,
|
| 934 |
+
OnlineStage4WriterApplication,
|
| 935 |
+
],
|
| 936 |
+
] = {}
|
| 937 |
+
self._retained_writer_observations: dict[int, RealizedObservation] = {
|
| 938 |
+
self._history_frame_offset + initial_step: self._current_observation
|
| 939 |
+
}
|
| 940 |
+
|
| 941 |
+
@property
|
| 942 |
+
def memory_snapshot(self):
|
| 943 |
+
return self._online_memory.snapshot
|
| 944 |
+
|
| 945 |
+
@property
|
| 946 |
+
def static_semantic_memory(self) -> str:
|
| 947 |
+
return self._online_memory.policy_memory_text
|
| 948 |
+
|
| 949 |
+
def prepare_policy_request(self) -> OnlineStage4PolicyRequest:
|
| 950 |
+
if self._awaiting_policy_response is not None:
|
| 951 |
+
raise SemanticTransitionRolloutError("a policy response is already pending")
|
| 952 |
+
if self._pending_chunk is not None:
|
| 953 |
+
raise SemanticTransitionRolloutError(
|
| 954 |
+
"finish the current action chunk before the next policy call"
|
| 955 |
+
)
|
| 956 |
+
if self._window.ready_window is not None or self._writer_request is not None:
|
| 957 |
+
raise SemanticTransitionRolloutError(
|
| 958 |
+
"resolve the writer-ready window before the next policy call"
|
| 959 |
+
)
|
| 960 |
+
request = OnlineStage4PolicyRequest(
|
| 961 |
+
step=self.current_step,
|
| 962 |
+
observation_id=self._current_observation.observation_id,
|
| 963 |
+
prompt=self.original_task.instruction,
|
| 964 |
+
static_semantic_memory=self._online_memory.policy_memory_text,
|
| 965 |
+
memory_revision=self._online_memory.revision,
|
| 966 |
+
history_required_indices=self._online_memory.history_required_indices,
|
| 967 |
+
**self._realized_context.model_inputs(),
|
| 968 |
+
)
|
| 969 |
+
self._awaiting_policy_response = request
|
| 970 |
+
return request
|
| 971 |
+
|
| 972 |
+
def prepare_initial_writer_request(
|
| 973 |
+
self,
|
| 974 |
+
*,
|
| 975 |
+
front_images: tuple[Any, ...] | list[Any],
|
| 976 |
+
wrist_images: tuple[Any | None, ...] | list[Any | None],
|
| 977 |
+
) -> OnlineStage4WriterRequest:
|
| 978 |
+
if self._initial_writer_prepared:
|
| 979 |
+
raise SemanticTransitionRolloutError("initial writer request was already prepared")
|
| 980 |
+
if (
|
| 981 |
+
self._awaiting_policy_response is not None
|
| 982 |
+
or self._pending_chunk is not None
|
| 983 |
+
or self._writer_request is not None
|
| 984 |
+
or self._window.phase is not SemanticWindowPhase.CLOSED
|
| 985 |
+
or self._realized_context.history
|
| 986 |
+
):
|
| 987 |
+
raise SemanticTransitionRolloutError(
|
| 988 |
+
"initial writer request must precede every policy call and executed action"
|
| 989 |
+
)
|
| 990 |
+
fronts = tuple(front_images)
|
| 991 |
+
wrists = tuple(wrist_images)
|
| 992 |
+
if len(fronts) < 2 or len(fronts) != len(wrists):
|
| 993 |
+
raise SemanticTransitionRolloutError(
|
| 994 |
+
"pre-action evidence requires aligned demonstration and execution-start images"
|
| 995 |
+
)
|
| 996 |
+
source = tuple(
|
| 997 |
+
RealizedObservation(
|
| 998 |
+
observation_id=f"{self._window.episode_nonce}:history:{index}",
|
| 999 |
+
step=index,
|
| 1000 |
+
front_image=front,
|
| 1001 |
+
wrist_image=wrists[index],
|
| 1002 |
+
)
|
| 1003 |
+
for index, front in enumerate(fronts)
|
| 1004 |
+
)
|
| 1005 |
+
selected = sample_uniform_observations(source, max_timepoints=8)
|
| 1006 |
+
selected_count = len(selected)
|
| 1007 |
+
prefix_lengths = tuple(
|
| 1008 |
+
sorted(
|
| 1009 |
+
{
|
| 1010 |
+
max(2, (selected_count + 1) // 2),
|
| 1011 |
+
max(2, (3 * selected_count + 3) // 4),
|
| 1012 |
+
selected_count,
|
| 1013 |
+
}
|
| 1014 |
+
)
|
| 1015 |
+
)
|
| 1016 |
+
self._initial_writer_prefixes = [
|
| 1017 |
+
selected[:prefix_length] for prefix_length in prefix_lengths
|
| 1018 |
+
]
|
| 1019 |
+
self._initial_writer_prepared = True
|
| 1020 |
+
return self._cache_next_initial_writer_request()
|
| 1021 |
+
|
| 1022 |
+
def apply_writer_result(
|
| 1023 |
+
self,
|
| 1024 |
+
result: OnlineStage4ValidatedWriterResult,
|
| 1025 |
+
*,
|
| 1026 |
+
commit_memory: bool = True,
|
| 1027 |
+
) -> OnlineStage4WriterApplication:
|
| 1028 |
+
if self._awaiting_policy_response is not None or self._pending_chunk is not None:
|
| 1029 |
+
raise SemanticTransitionRolloutError(
|
| 1030 |
+
"writer results may be applied only between policy calls"
|
| 1031 |
+
)
|
| 1032 |
+
if not isinstance(result, OnlineStage4ValidatedWriterResult):
|
| 1033 |
+
raise TypeError("result must be OnlineStage4ValidatedWriterResult")
|
| 1034 |
+
if type(commit_memory) is not bool:
|
| 1035 |
+
raise TypeError("commit_memory must be bool")
|
| 1036 |
+
previous = self._online_writer_applications.get(result.request_id)
|
| 1037 |
+
if previous is not None:
|
| 1038 |
+
previous_result, previous_commit_memory, application = previous
|
| 1039 |
+
if previous_result != result:
|
| 1040 |
+
raise SemanticTransitionRolloutError(
|
| 1041 |
+
"writer request id was reused with different content"
|
| 1042 |
+
)
|
| 1043 |
+
if previous_commit_memory is not commit_memory:
|
| 1044 |
+
raise SemanticTransitionRolloutError(
|
| 1045 |
+
"writer request retry cannot change commit_memory mode"
|
| 1046 |
+
)
|
| 1047 |
+
return application
|
| 1048 |
+
request = self._writer_request
|
| 1049 |
+
if not isinstance(request, OnlineStage4WriterRequest):
|
| 1050 |
+
raise SemanticTransitionRolloutError(
|
| 1051 |
+
"no online Stage4 writer-ready request is awaiting a result"
|
| 1052 |
+
)
|
| 1053 |
+
if result.request_id != request.request_id or result.window_id != request.window.window_id:
|
| 1054 |
+
raise SemanticTransitionRolloutError(
|
| 1055 |
+
"writer result does not match the current request/window"
|
| 1056 |
+
)
|
| 1057 |
+
|
| 1058 |
+
before_revision = self._online_memory.revision
|
| 1059 |
+
if commit_memory:
|
| 1060 |
+
effective_from_frame = max(request.evidence_frame_indices)
|
| 1061 |
+
if request.purpose is not WriterRequestPurpose.PRE_ACTION_DEMONSTRATION:
|
| 1062 |
+
effective_from_frame += 1
|
| 1063 |
+
effective_from_frame = max(
|
| 1064 |
+
effective_from_frame,
|
| 1065 |
+
self._online_memory.snapshot.effective_from_frame + 1,
|
| 1066 |
+
)
|
| 1067 |
+
self._online_memory.apply(
|
| 1068 |
+
result.decision,
|
| 1069 |
+
effective_from_frame=effective_from_frame,
|
| 1070 |
+
)
|
| 1071 |
+
|
| 1072 |
+
window_resolution_applied = False
|
| 1073 |
+
if request.purpose is WriterRequestPurpose.TRANSITION:
|
| 1074 |
+
ready = self._window.ready_window
|
| 1075 |
+
if ready is None or ready.window_id != result.window_id:
|
| 1076 |
+
raise SemanticTransitionRolloutError(
|
| 1077 |
+
"writer result window is no longer ready"
|
| 1078 |
+
)
|
| 1079 |
+
if result.decision.operation != "abstain":
|
| 1080 |
+
resolution = WindowResolution.UPDATE
|
| 1081 |
+
elif result.decision.reason_code == "no_durable_memory_change":
|
| 1082 |
+
resolution = WindowResolution.NO_CHANGE
|
| 1083 |
+
else:
|
| 1084 |
+
resolution = WindowResolution.ABSTAIN
|
| 1085 |
+
window_resolution_applied = self._window.resolve_ready_window(
|
| 1086 |
+
window_id=result.window_id,
|
| 1087 |
+
decision=resolution,
|
| 1088 |
+
)
|
| 1089 |
+
|
| 1090 |
+
application = OnlineStage4WriterApplication(
|
| 1091 |
+
request_id=result.request_id,
|
| 1092 |
+
operation=result.decision.operation,
|
| 1093 |
+
memory_committed=(
|
| 1094 |
+
commit_memory
|
| 1095 |
+
and self._online_memory.revision != before_revision
|
| 1096 |
+
),
|
| 1097 |
+
memory_before_revision=before_revision,
|
| 1098 |
+
memory_after_revision=self._online_memory.revision,
|
| 1099 |
+
window_resolution_applied=window_resolution_applied,
|
| 1100 |
+
static_semantic_memory=self._online_memory.policy_memory_text,
|
| 1101 |
+
history_required_indices=self._online_memory.history_required_indices,
|
| 1102 |
+
)
|
| 1103 |
+
self._online_writer_applications[result.request_id] = (
|
| 1104 |
+
result,
|
| 1105 |
+
commit_memory,
|
| 1106 |
+
application,
|
| 1107 |
+
)
|
| 1108 |
+
self._previous_online_writer_transition_end_frame = max(
|
| 1109 |
+
request.evidence_frame_indices
|
| 1110 |
+
)
|
| 1111 |
+
self._writer_request = None
|
| 1112 |
+
self._preempted_chunk_result = None
|
| 1113 |
+
if (
|
| 1114 |
+
request.purpose is WriterRequestPurpose.PRE_ACTION_DEMONSTRATION
|
| 1115 |
+
and self._initial_writer_prefixes
|
| 1116 |
+
):
|
| 1117 |
+
self._cache_next_initial_writer_request()
|
| 1118 |
+
return application
|
| 1119 |
+
|
| 1120 |
+
def _cache_next_initial_writer_request(self) -> OnlineStage4WriterRequest:
|
| 1121 |
+
if self._writer_request is not None or not self._initial_writer_prefixes:
|
| 1122 |
+
raise SemanticTransitionRolloutError(
|
| 1123 |
+
"no pre-action demonstration prefix is ready"
|
| 1124 |
+
)
|
| 1125 |
+
source = self._initial_writer_prefixes.pop(0)
|
| 1126 |
+
frame_indices = tuple(observation.step for observation in source)
|
| 1127 |
+
evidence = tuple(
|
| 1128 |
+
RealizedObservation(
|
| 1129 |
+
observation_id=observation.observation_id,
|
| 1130 |
+
step=timepoint_id,
|
| 1131 |
+
front_image=observation.front_image,
|
| 1132 |
+
wrist_image=observation.wrist_image,
|
| 1133 |
+
)
|
| 1134 |
+
for timepoint_id, observation in enumerate(source)
|
| 1135 |
+
)
|
| 1136 |
+
self._initial_writer_sequence += 1
|
| 1137 |
+
window = SemanticWindowState(
|
| 1138 |
+
window_id=(
|
| 1139 |
+
f"{self._window.episode_nonce}:initial-memory:"
|
| 1140 |
+
f"{self._initial_writer_sequence}"
|
| 1141 |
+
),
|
| 1142 |
+
episode_nonce=self._window.episode_nonce,
|
| 1143 |
+
start_step=0,
|
| 1144 |
+
current_step=len(evidence) - 1,
|
| 1145 |
+
max_end_step=len(evidence) - 1,
|
| 1146 |
+
observations=evidence,
|
| 1147 |
+
chunk_ids=(f"{self._window.episode_nonce}:pre-action-demonstration",),
|
| 1148 |
+
phase=SemanticWindowPhase.READY,
|
| 1149 |
+
)
|
| 1150 |
+
request = OnlineStage4WriterRequest(
|
| 1151 |
+
original_task=self.original_task,
|
| 1152 |
+
memory_before=self._online_memory.snapshot,
|
| 1153 |
+
window=window,
|
| 1154 |
+
evidence=evidence,
|
| 1155 |
+
evidence_frame_indices=frame_indices,
|
| 1156 |
+
remaining_episode_frames_after_transition=max(
|
| 1157 |
+
0,
|
| 1158 |
+
self._episode_frame_limit - self.current_step,
|
| 1159 |
+
),
|
| 1160 |
+
episode_fps=self._episode_fps,
|
| 1161 |
+
previous_transition_end_frame=(
|
| 1162 |
+
self._previous_online_writer_transition_end_frame
|
| 1163 |
+
),
|
| 1164 |
+
purpose=WriterRequestPurpose.PRE_ACTION_DEMONSTRATION,
|
| 1165 |
+
memory_references=self._active_memory_references(),
|
| 1166 |
+
)
|
| 1167 |
+
self._retain_writer_evidence(request)
|
| 1168 |
+
self._writer_request = request
|
| 1169 |
+
return request
|
| 1170 |
+
|
| 1171 |
+
def _cache_writer_request(self) -> None:
|
| 1172 |
+
ready = self._window.ready_window
|
| 1173 |
+
if ready is None:
|
| 1174 |
+
raise AssertionError("writer request requires a ready semantic window")
|
| 1175 |
+
evidence = sample_uniform_observations(ready.observations, max_timepoints=8)
|
| 1176 |
+
frame_indices = tuple(
|
| 1177 |
+
self._history_frame_offset + observation.step for observation in evidence
|
| 1178 |
+
)
|
| 1179 |
+
request = OnlineStage4WriterRequest(
|
| 1180 |
+
original_task=self.original_task,
|
| 1181 |
+
memory_before=self._online_memory.snapshot,
|
| 1182 |
+
window=ready,
|
| 1183 |
+
evidence=evidence,
|
| 1184 |
+
evidence_frame_indices=frame_indices,
|
| 1185 |
+
remaining_episode_frames_after_transition=max(
|
| 1186 |
+
0,
|
| 1187 |
+
self._episode_frame_limit - ready.current_step,
|
| 1188 |
+
),
|
| 1189 |
+
episode_fps=self._episode_fps,
|
| 1190 |
+
previous_transition_end_frame=(
|
| 1191 |
+
self._previous_online_writer_transition_end_frame
|
| 1192 |
+
),
|
| 1193 |
+
memory_references=self._active_memory_references(),
|
| 1194 |
+
)
|
| 1195 |
+
self._retain_writer_evidence(request)
|
| 1196 |
+
self._writer_request = request
|
| 1197 |
+
|
| 1198 |
+
def _retain_writer_evidence(self, request: OnlineStage4WriterRequest) -> None:
|
| 1199 |
+
self._retained_writer_observations.update(
|
| 1200 |
+
zip(request.evidence_frame_indices, request.evidence, strict=True)
|
| 1201 |
+
)
|
| 1202 |
+
|
| 1203 |
+
def _active_memory_references(self) -> tuple[OnlineStage4MemoryReference, ...]:
|
| 1204 |
+
references: list[OnlineStage4MemoryReference] = []
|
| 1205 |
+
for item in self._online_memory.snapshot.items:
|
| 1206 |
+
for image_ref in item.image_refs:
|
| 1207 |
+
observation = self._retained_writer_observations.get(image_ref.frame_index)
|
| 1208 |
+
if observation is None:
|
| 1209 |
+
raise SemanticTransitionRolloutError(
|
| 1210 |
+
"active memory anchor has no retained observable image"
|
| 1211 |
+
)
|
| 1212 |
+
references.append(
|
| 1213 |
+
OnlineStage4MemoryReference(
|
| 1214 |
+
item_id=item.item_id,
|
| 1215 |
+
image_ref=image_ref,
|
| 1216 |
+
observation=observation,
|
| 1217 |
+
)
|
| 1218 |
+
)
|
| 1219 |
+
return tuple(references)
|
| 1220 |
+
|
| 1221 |
+
|
| 1222 |
+
|
| 1223 |
+
__all__ = [
|
| 1224 |
+
"CONTEXT_HORIZON",
|
| 1225 |
+
"ROBOT_VECTOR_DIM",
|
| 1226 |
+
"STATUS_HORIZON",
|
| 1227 |
+
"OnlineStage4PolicyRequest",
|
| 1228 |
+
"OnlineStage4SemanticTransitionRolloutAdapter",
|
| 1229 |
+
"OnlineStage4WriterApplication",
|
| 1230 |
+
"RealizedRobotDelta",
|
| 1231 |
+
"RealizedTransitionContext",
|
| 1232 |
+
"SemanticPolicyRequest",
|
| 1233 |
+
"SemanticTransitionRolloutAdapter",
|
| 1234 |
+
"SemanticTransitionRolloutError",
|
| 1235 |
+
"WriterApplication",
|
| 1236 |
+
]
|
checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/shared/mem_buffer.py
ADDED
|
@@ -0,0 +1,635 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 6 |
+
from copy import deepcopy
|
| 7 |
+
import numpy as np
|
| 8 |
+
from typing import Callable
|
| 9 |
+
import cv2
|
| 10 |
+
from collections import defaultdict
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
from openpi.shared import image_tools
|
| 14 |
+
from mme_vla_suite.shared.data_utils import *
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def create_dict(indices):
|
| 18 |
+
result = defaultdict(lambda: defaultdict(list)) # {step_idx: {view_idx: [patch_idx]}}
|
| 19 |
+
for step_idx, view_idx, patch_idx in indices:
|
| 20 |
+
result[step_idx][view_idx].append(patch_idx)
|
| 21 |
+
return result
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class MemoryBuffer:
|
| 25 |
+
# We use 8x8 tokens each image for token dropping and 4x4 tokens for frame sampling.
|
| 26 |
+
def __init__(
|
| 27 |
+
self,
|
| 28 |
+
num_views: int = 1, # number of camera views to be used as memory, better use fixed-views
|
| 29 |
+
img_emb_dim: int = 2048, # the initila image token embedding dimension, siglip is 2048
|
| 30 |
+
pos_emb_dim: int = 768,
|
| 31 |
+
state_emb_dim: int = 8,
|
| 32 |
+
max_steps: int = 4096,
|
| 33 |
+
compute_token_drop_score: bool = False, # set true when using token dropping
|
| 34 |
+
token_drop_keptsize: int = 2048, # max number of tokens to be kept in the heap for similarity score calculation
|
| 35 |
+
token_drop_stride: int = 8, # timestep stride for similarity score calculation, if too close, the difference will be too small
|
| 36 |
+
prepare_buffer: bool = False, # set true during online evaluation, set false during offline training
|
| 37 |
+
pool_type: str = "mean", # pooling type for the image tokens, mean or max
|
| 38 |
+
vision_enc_fn: Callable | None = None, # vision encoding function
|
| 39 |
+
):
|
| 40 |
+
self.num_views = num_views
|
| 41 |
+
self.img_emb_dim = img_emb_dim
|
| 42 |
+
self.pos_emb_dim = pos_emb_dim
|
| 43 |
+
self.state_emb_dim = state_emb_dim
|
| 44 |
+
|
| 45 |
+
self.pool_type = pool_type
|
| 46 |
+
self.token_drop_keptsize = token_drop_keptsize
|
| 47 |
+
self.token_drop_stride = token_drop_stride
|
| 48 |
+
self.token_drop_last_frame = -1
|
| 49 |
+
self.scored_token_heap = []
|
| 50 |
+
self.compute_token_drop_score = compute_token_drop_score
|
| 51 |
+
|
| 52 |
+
self._history_feats = {}
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
if prepare_buffer:
|
| 56 |
+
# load models in GPUs to provide embeedings
|
| 57 |
+
# used for dataset buliding and evaluation
|
| 58 |
+
from mme_vla_suite.shared.posemb_3d import PosEmb3D
|
| 59 |
+
if vision_enc_fn is None:
|
| 60 |
+
from mme_vla_suite.shared.siglip_tokenizer import SigLipTokenizer
|
| 61 |
+
siglip_tokenizer = SigLipTokenizer()
|
| 62 |
+
self.vision_enc = jax.jit(siglip_tokenizer.__call__)
|
| 63 |
+
else:
|
| 64 |
+
self.vision_enc = vision_enc_fn
|
| 65 |
+
pos_embedder = PosEmb3D(dim=pos_emb_dim)
|
| 66 |
+
ranges = jnp.arange(max_steps)
|
| 67 |
+
self.pos_emb_dict = {
|
| 68 |
+
"8x8": np.array(pos_embedder(ranges, 8)),
|
| 69 |
+
"4x4": np.array(pos_embedder(ranges, 4)),
|
| 70 |
+
"2x2": np.array(pos_embedder(ranges, 2)),
|
| 71 |
+
}
|
| 72 |
+
else:
|
| 73 |
+
# used in dataset loading mode
|
| 74 |
+
self.vision_enc = None
|
| 75 |
+
self.pos_emb_dict = None
|
| 76 |
+
|
| 77 |
+
def add_buffer(
|
| 78 |
+
self,
|
| 79 |
+
images, #: (t v h w 3), np.int8
|
| 80 |
+
states, #: (t d), np.float32
|
| 81 |
+
step_idx_list: list[int],
|
| 82 |
+
):
|
| 83 |
+
assert self.vision_enc is not None, "encode is not initialized"
|
| 84 |
+
|
| 85 |
+
t, v, _, _, _ = images.shape
|
| 86 |
+
assert v == self.num_views
|
| 87 |
+
|
| 88 |
+
image_jnp = jnp.array(
|
| 89 |
+
images.astype(np.float32) / 255.0 * 2.0 - 1.0
|
| 90 |
+
)
|
| 91 |
+
image_jnp = einops.rearrange(image_jnp, "t v h w c -> (t v) h w c")
|
| 92 |
+
image_jnp = image_tools.resize_with_pad(image_jnp, 224, 224)
|
| 93 |
+
image_jnp = einops.rearrange(image_jnp, "(t v) h w c -> t v h w c", t=t, v=v)
|
| 94 |
+
output_emb = self.vision_enc(image_jnp) # (t, v, 64, 2048)
|
| 95 |
+
|
| 96 |
+
pooled_emb_8x8 = pool_tokens_to_size(output_emb, 64) # (t, v, 64, 2048)
|
| 97 |
+
pooled_emb_4x4 = pool_tokens_to_size(output_emb, 16) # (t, v, 16, 2048)
|
| 98 |
+
pooled_emb_2x2 = pool_tokens_to_size(output_emb, 4) # (t, v, 4, 2048)
|
| 99 |
+
|
| 100 |
+
for i, step_idx in enumerate(step_idx_list):
|
| 101 |
+
image_emb_8x8 = jax.device_get(pooled_emb_8x8)[i] # (v, 64, 2048)
|
| 102 |
+
image_emb_4x4 = jax.device_get(pooled_emb_4x4)[i] # (v, 16, 2048)
|
| 103 |
+
image_emb_2x2 = jax.device_get(pooled_emb_2x2)[i] # (v, 4, 2048)
|
| 104 |
+
|
| 105 |
+
pos_emb_8x8 = self.pos_emb_dict["8x8"][
|
| 106 |
+
step_idx*self.num_views : (step_idx+1)*self.num_views] # (v, 64, 768)
|
| 107 |
+
pos_emb_4x4 = self.pos_emb_dict["4x4"][
|
| 108 |
+
step_idx*self.num_views : (step_idx+1)*self.num_views] # (v, 16, 768)
|
| 109 |
+
pos_emb_2x2 = self.pos_emb_dict["2x2"][
|
| 110 |
+
step_idx*self.num_views : (step_idx+1)*self.num_views] # (v, 4, 768)
|
| 111 |
+
|
| 112 |
+
token_emb_to_save = {
|
| 113 |
+
"image_pixels": images[i].copy(), # fp32, this is for visualization
|
| 114 |
+
"image_emb_8x8": image_emb_8x8, # bf16
|
| 115 |
+
"image_emb_4x4": image_emb_4x4, # bf16
|
| 116 |
+
"image_emb_2x2": image_emb_2x2, # bf16
|
| 117 |
+
"pos_emb_8x8": pos_emb_8x8, # fp32
|
| 118 |
+
"pos_emb_4x4": pos_emb_4x4, # fp32
|
| 119 |
+
"pos_emb_2x2": pos_emb_2x2, # fp32
|
| 120 |
+
"state_emb": states[i], # fp32
|
| 121 |
+
}
|
| 122 |
+
assert step_idx not in self._history_feats, f"step_idx {step_idx} already in buffer"
|
| 123 |
+
self._history_feats[step_idx] = token_emb_to_save
|
| 124 |
+
|
| 125 |
+
if self.compute_token_drop_score:
|
| 126 |
+
self._process_token_drop_score(step_idx)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def get_history_feats(self, step_idx: int, remove_image_pixels: bool = True):
|
| 130 |
+
if remove_image_pixels:
|
| 131 |
+
return {k: v for k, v in self._history_feats[step_idx].items() if k != "image_pixels"}
|
| 132 |
+
return self._history_feats[step_idx]
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def _process_token_drop_score(self, step_idx):
|
| 136 |
+
if step_idx == 0: # all tokens in the first frame should be kept, only later frames are considered for token dropping
|
| 137 |
+
for patch_idx in range(64): # 64 patches in 8x8 grid, which is fixed here for now
|
| 138 |
+
for view_idx in range(self.num_views):
|
| 139 |
+
heapq.heappush(
|
| 140 |
+
self.scored_token_heap, (1000.0, step_idx, view_idx, patch_idx)
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
if step_idx == self.token_drop_last_frame + self.token_drop_stride:
|
| 144 |
+
prev_img = self._history_feats[max(0, self.token_drop_last_frame)]["image_pixels"]
|
| 145 |
+
curr_img = self._history_feats[step_idx]["image_pixels"]
|
| 146 |
+
|
| 147 |
+
prev_img = prev_img.astype(np.float32) / 255.0 * 2.0 - 1.0
|
| 148 |
+
curr_img = curr_img.astype(np.float32) / 255.0 * 2.0 - 1.0
|
| 149 |
+
|
| 150 |
+
prev_img_tokens = einops.rearrange(prev_img, "v (ph h) (pw w) c -> v (ph pw) (h w c)", ph=8, pw=8)
|
| 151 |
+
curr_img_tokens = einops.rearrange(curr_img, "v (ph h) (pw w) c -> v (ph pw) (h w c)", ph=8, pw=8)
|
| 152 |
+
|
| 153 |
+
for view_idx in range(self.num_views):
|
| 154 |
+
# pixel works better than siglip embedding
|
| 155 |
+
difference = np.abs(prev_img_tokens[view_idx] - curr_img_tokens[view_idx]).mean(axis=-1)
|
| 156 |
+
for patch_idx in range(64):
|
| 157 |
+
if difference[patch_idx] < 1e-4:
|
| 158 |
+
# too similar, skip this patch
|
| 159 |
+
continue
|
| 160 |
+
heapq.heappush(
|
| 161 |
+
self.scored_token_heap,
|
| 162 |
+
(
|
| 163 |
+
difference[patch_idx],
|
| 164 |
+
step_idx, # timestep index
|
| 165 |
+
view_idx, # view index
|
| 166 |
+
patch_idx, # patch index
|
| 167 |
+
),
|
| 168 |
+
)
|
| 169 |
+
if len(self.scored_token_heap) > self.token_drop_keptsize:
|
| 170 |
+
heapq.heappop(self.scored_token_heap)
|
| 171 |
+
|
| 172 |
+
self.token_drop_last_frame += self.token_drop_stride
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def clear(self):
|
| 176 |
+
self.scored_token_heap.clear()
|
| 177 |
+
self.token_drop_last_frame = -1
|
| 178 |
+
self._history_feats.clear()
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def get_token_dropping_indices(self):
|
| 182 |
+
selected_tokens_heap = deepcopy(self.scored_token_heap)
|
| 183 |
+
kept_indices = []
|
| 184 |
+
while selected_tokens_heap:
|
| 185 |
+
_, buffer_idx, view_idx, patch_idx = heapq.heappop(selected_tokens_heap)
|
| 186 |
+
kept_indices.append((buffer_idx, view_idx, patch_idx))
|
| 187 |
+
|
| 188 |
+
return kept_indices
|
| 189 |
+
|
| 190 |
+
@staticmethod
|
| 191 |
+
def filter_token_dropping_indices(kept_indices, step_idx, token_budget, is_sorted=True):
|
| 192 |
+
kept_indices_filtered = [item for item in kept_indices if item[0] <= step_idx]
|
| 193 |
+
kept_indices = kept_indices_filtered[-token_budget:]
|
| 194 |
+
if is_sorted:
|
| 195 |
+
kept_indices = sorted(kept_indices)
|
| 196 |
+
return kept_indices
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def _prepare_token_dropping(self, history_feats, sorted_kept_indices, token_budget):
|
| 200 |
+
img_emb = np.zeros((token_budget, self.img_emb_dim), dtype=np.float32)
|
| 201 |
+
pos_emb = np.zeros((token_budget, self.pos_emb_dim), dtype=np.float32)
|
| 202 |
+
state_emb = np.zeros((token_budget, self.state_emb_dim), dtype=np.float32)
|
| 203 |
+
mask = np.zeros((token_budget), dtype=np.bool_)
|
| 204 |
+
|
| 205 |
+
for idx, (buffer_idx, view_idx, patch_idx) in enumerate(sorted_kept_indices[:token_budget]):
|
| 206 |
+
img_emb[idx] = history_feats[buffer_idx][f"image_emb_8x8"][view_idx][patch_idx]
|
| 207 |
+
pos_emb[idx] = history_feats[buffer_idx][f"pos_emb_8x8"][view_idx][patch_idx]
|
| 208 |
+
state_emb[idx] = history_feats[buffer_idx]["state_emb"]
|
| 209 |
+
mask[idx] = True
|
| 210 |
+
|
| 211 |
+
# print("effective token length: ", np.sum(mask))
|
| 212 |
+
|
| 213 |
+
return img_emb, pos_emb, state_emb, mask
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def prepare_token_dropping(self, step_idx, token_budget, history_feats_gather_fn, kept_indices=None, *args, **kwargs):
|
| 217 |
+
if kept_indices is None:
|
| 218 |
+
indices_to_load = self.get_token_dropping_indices()
|
| 219 |
+
else:
|
| 220 |
+
indices_to_load = kept_indices
|
| 221 |
+
|
| 222 |
+
sorted_kept_indices = self.filter_token_dropping_indices(
|
| 223 |
+
indices_to_load, step_idx, token_budget, is_sorted=True)
|
| 224 |
+
|
| 225 |
+
indices_to_load = sorted(set([item[0] for item in sorted_kept_indices]))
|
| 226 |
+
# print("step_idx: ", step_idx)
|
| 227 |
+
# print(f"indices_to_load (length: {len(indices_to_load)}/{len(sorted_kept_indices)}): {indices_to_load}")
|
| 228 |
+
# self._visualize_token_dropping(sorted_kept_indices, step_idx)
|
| 229 |
+
# import pdb; pdb.set_trace()
|
| 230 |
+
|
| 231 |
+
history_feats = history_feats_gather_fn(indices_to_load, *args, **kwargs)
|
| 232 |
+
|
| 233 |
+
return self._prepare_token_dropping(history_feats, sorted_kept_indices, token_budget)
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def _visualize_token_dropping(self, kept_indices, step_idx):
|
| 237 |
+
dic = create_dict(sorted(kept_indices))
|
| 238 |
+
images = [self._history_feats[idx]["image_pixels"][0] for idx in range(len(self._history_feats))]
|
| 239 |
+
|
| 240 |
+
images_anno = []
|
| 241 |
+
for step_idx in dic:
|
| 242 |
+
img_anno = images[step_idx].copy()
|
| 243 |
+
|
| 244 |
+
img_anno = cv2.putText(
|
| 245 |
+
img_anno,
|
| 246 |
+
f"{step_idx}",
|
| 247 |
+
(img_anno.shape[1] // 2, img_anno.shape[0] // 2),
|
| 248 |
+
cv2.FONT_HERSHEY_SIMPLEX,
|
| 249 |
+
1,
|
| 250 |
+
(0, 0, 255),
|
| 251 |
+
1,
|
| 252 |
+
)
|
| 253 |
+
mask = np.zeros(img_anno.shape[:2], dtype=np.uint8)
|
| 254 |
+
|
| 255 |
+
for patch_idx in range(64):
|
| 256 |
+
if patch_idx in dic[step_idx][0]:
|
| 257 |
+
continue
|
| 258 |
+
h_center = patch_idx // 8 * 32 + 16
|
| 259 |
+
w_center = patch_idx % 8 * 32 + 16
|
| 260 |
+
mask = cv2.rectangle(
|
| 261 |
+
mask,
|
| 262 |
+
(w_center - 16, h_center - 16),
|
| 263 |
+
(w_center + 16, h_center + 16),
|
| 264 |
+
255,
|
| 265 |
+
-1,
|
| 266 |
+
)
|
| 267 |
+
img_anno[mask == 255] = (
|
| 268 |
+
img_anno[mask == 255] * 0.3 + np.array([255, 255, 255]) * 0.7
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
images_anno.append(img_anno)
|
| 272 |
+
|
| 273 |
+
import imageio, os
|
| 274 |
+
imageio.mimsave(
|
| 275 |
+
os.path.join(
|
| 276 |
+
"debug",
|
| 277 |
+
f"token_drop_anno_step_{step_idx}.mp4",
|
| 278 |
+
),
|
| 279 |
+
images_anno,
|
| 280 |
+
fps=10,
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def get_frame_sampling_indices(self, step_idx, token_budget, token_per_image):
|
| 285 |
+
max_size = token_budget // (token_per_image * self.num_views)
|
| 286 |
+
return even_sampling_indices(step_idx, max_size)
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
def _prepare_frame_sampling(self, history_feats, indices_to_load, token_budget, token_per_image):
|
| 290 |
+
spatial_size = str(int(math.sqrt(token_per_image)))
|
| 291 |
+
spatial_key = f"{spatial_size}x{spatial_size}"
|
| 292 |
+
max_size = token_budget // (token_per_image * self.num_views)
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
sampled_img_emb = self._load_emb(history_feats, indices_to_load, f"image_emb_{spatial_key}")
|
| 296 |
+
sampled_pos_emb = self._load_emb(history_feats, indices_to_load, f"pos_emb_{spatial_key}")
|
| 297 |
+
sampled_state_emb = self._load_emb(history_feats, indices_to_load, "state_emb")
|
| 298 |
+
mask = np.ones((sampled_img_emb.shape[0]), dtype=np.bool_)
|
| 299 |
+
|
| 300 |
+
# we use right padding to the perceptual memory
|
| 301 |
+
sampled_img_emb, sampled_pos_emb, sampled_state_emb, mask = right_padding_token_emb(
|
| 302 |
+
sampled_img_emb, sampled_pos_emb, sampled_state_emb, mask, max_size
|
| 303 |
+
)
|
| 304 |
+
|
| 305 |
+
img_emb = np.reshape(sampled_img_emb, (-1, self.img_emb_dim))
|
| 306 |
+
pos_emb = np.reshape(sampled_pos_emb, (-1, self.pos_emb_dim))
|
| 307 |
+
mask = np.repeat(mask, self.num_views * token_per_image)
|
| 308 |
+
state_emb = np.repeat(sampled_state_emb, self.num_views * token_per_image, axis=0)
|
| 309 |
+
|
| 310 |
+
# print("effective token length: ", np.sum(mask))
|
| 311 |
+
|
| 312 |
+
return img_emb, pos_emb, state_emb, mask
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
def prepare_frame_sampling(
|
| 316 |
+
self,
|
| 317 |
+
step_idx,
|
| 318 |
+
token_budget,
|
| 319 |
+
token_per_image,
|
| 320 |
+
history_feats_gather_fn,
|
| 321 |
+
selected_indices=None,
|
| 322 |
+
*args,
|
| 323 |
+
**kwargs,
|
| 324 |
+
):
|
| 325 |
+
if selected_indices is None:
|
| 326 |
+
indices_to_load = self.get_frame_sampling_indices(step_idx, token_budget, token_per_image)
|
| 327 |
+
else:
|
| 328 |
+
tokens_per_frame = token_per_image * self.num_views
|
| 329 |
+
if token_budget <= 0 or token_per_image <= 0 or token_budget % tokens_per_frame:
|
| 330 |
+
raise ValueError("selected-frame geometry must evenly divide the token budget")
|
| 331 |
+
frame_capacity = token_budget // tokens_per_frame
|
| 332 |
+
if not isinstance(selected_indices, (list, tuple)) or not selected_indices:
|
| 333 |
+
raise ValueError("selected_indices must be a non-empty list or tuple")
|
| 334 |
+
if any(
|
| 335 |
+
isinstance(value, bool) or not isinstance(value, (int, np.integer))
|
| 336 |
+
for value in selected_indices
|
| 337 |
+
):
|
| 338 |
+
raise ValueError("selected_indices must contain integers")
|
| 339 |
+
indices_to_load = [int(value) for value in selected_indices]
|
| 340 |
+
expected_count = min(frame_capacity, step_idx + 1)
|
| 341 |
+
if len(indices_to_load) != expected_count:
|
| 342 |
+
raise ValueError(
|
| 343 |
+
f"selected frame count must be exactly {expected_count}, got {len(indices_to_load)}"
|
| 344 |
+
)
|
| 345 |
+
if indices_to_load != sorted(set(indices_to_load)):
|
| 346 |
+
raise ValueError("selected_indices must be sorted and unique")
|
| 347 |
+
if indices_to_load[0] < 0 or indices_to_load[-1] > step_idx:
|
| 348 |
+
raise ValueError("selected_indices must be causal and non-negative")
|
| 349 |
+
|
| 350 |
+
history_feats = history_feats_gather_fn(indices_to_load, *args, **kwargs)
|
| 351 |
+
return self._prepare_frame_sampling(history_feats, indices_to_load, token_budget, token_per_image)
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def prepare_phase_a_frame_sampling(
|
| 355 |
+
self,
|
| 356 |
+
step_idx,
|
| 357 |
+
token_budget,
|
| 358 |
+
frame_indices,
|
| 359 |
+
valid_mask,
|
| 360 |
+
token_counts,
|
| 361 |
+
history_feats_gather_fn,
|
| 362 |
+
*args,
|
| 363 |
+
**kwargs,
|
| 364 |
+
):
|
| 365 |
+
"""Materialize a mixed 64/16/4-token Phase-A frame plan.
|
| 366 |
+
|
| 367 |
+
``frame_indices`` and ``valid_mask`` are the immutable visual plan;
|
| 368 |
+
metadata interventions never enter this method. Consequently every
|
| 369 |
+
metadata arm gathers exactly the same feature blobs and preserves the
|
| 370 |
+
original PosEmb3D values and token mask byte-for-byte.
|
| 371 |
+
"""
|
| 372 |
+
|
| 373 |
+
frame_indices = np.asarray(frame_indices)
|
| 374 |
+
valid_mask = np.asarray(valid_mask)
|
| 375 |
+
token_counts = np.asarray(token_counts)
|
| 376 |
+
if frame_indices.ndim != 1 or frame_indices.shape != valid_mask.shape:
|
| 377 |
+
raise ValueError("Phase-A frame indices and valid mask must be aligned vectors")
|
| 378 |
+
if token_counts.shape != frame_indices.shape:
|
| 379 |
+
raise ValueError("Phase-A token counts must align with frame slots")
|
| 380 |
+
if frame_indices.shape != (32,):
|
| 381 |
+
raise ValueError("Phase-A frame plan must contain exactly 32 slots")
|
| 382 |
+
if valid_mask.dtype != np.bool_:
|
| 383 |
+
raise ValueError("Phase-A valid mask must be boolean")
|
| 384 |
+
if not np.issubdtype(frame_indices.dtype, np.integer):
|
| 385 |
+
raise ValueError("Phase-A frame indices must be integers")
|
| 386 |
+
if not np.issubdtype(token_counts.dtype, np.integer):
|
| 387 |
+
raise ValueError("Phase-A token counts must be integers")
|
| 388 |
+
if self.num_views != 1:
|
| 389 |
+
raise ValueError("Phase-A reader requires exactly one memory view")
|
| 390 |
+
if token_budget != 512 or int(token_counts.sum()) != token_budget:
|
| 391 |
+
raise ValueError("Phase-A reader must materialize exactly 512 tokens")
|
| 392 |
+
if not set(int(value) for value in token_counts).issubset({4, 16, 64}):
|
| 393 |
+
raise ValueError("Phase-A frame token counts must be one of 4, 16 or 64")
|
| 394 |
+
|
| 395 |
+
valid_indices = [int(value) for value in frame_indices[valid_mask]]
|
| 396 |
+
if not valid_indices or valid_indices != sorted(set(valid_indices)):
|
| 397 |
+
raise ValueError("Phase-A valid frame indices must be non-empty, sorted and unique")
|
| 398 |
+
if valid_indices[0] < 0 or valid_indices[-1] > step_idx:
|
| 399 |
+
raise ValueError("Phase-A frame indices must be causal and non-negative")
|
| 400 |
+
if np.any(frame_indices[~valid_mask] != 0):
|
| 401 |
+
raise ValueError("Phase-A padding frame indices must be canonical zeros")
|
| 402 |
+
|
| 403 |
+
history_feats = history_feats_gather_fn(valid_indices, *args, **kwargs)
|
| 404 |
+
if set(history_feats) != set(valid_indices):
|
| 405 |
+
raise ValueError("Phase-A feature gather did not return the exact valid frame set")
|
| 406 |
+
first = history_feats[valid_indices[0]]
|
| 407 |
+
img_dtype = np.asarray(first["image_emb_4x4"]).dtype
|
| 408 |
+
pos_dtype = np.asarray(first["pos_emb_4x4"]).dtype
|
| 409 |
+
state_dtype = np.asarray(first["state_emb"]).dtype
|
| 410 |
+
image_blocks = []
|
| 411 |
+
position_blocks = []
|
| 412 |
+
state_blocks = []
|
| 413 |
+
mask_blocks = []
|
| 414 |
+
spatial_keys = {4: "2x2", 16: "4x4", 64: "8x8"}
|
| 415 |
+
for frame_idx, is_valid, token_count in zip(
|
| 416 |
+
frame_indices.tolist(),
|
| 417 |
+
valid_mask.tolist(),
|
| 418 |
+
token_counts.tolist(),
|
| 419 |
+
strict=True,
|
| 420 |
+
):
|
| 421 |
+
token_count = int(token_count)
|
| 422 |
+
if is_valid:
|
| 423 |
+
feature = history_feats[int(frame_idx)]
|
| 424 |
+
spatial_key = spatial_keys[token_count]
|
| 425 |
+
image = np.asarray(feature[f"image_emb_{spatial_key}"])
|
| 426 |
+
position = np.asarray(feature[f"pos_emb_{spatial_key}"])
|
| 427 |
+
state = np.asarray(feature["state_emb"])
|
| 428 |
+
expected_image = (self.num_views, token_count, self.img_emb_dim)
|
| 429 |
+
expected_position = (self.num_views, token_count, self.pos_emb_dim)
|
| 430 |
+
if image.shape != expected_image:
|
| 431 |
+
raise ValueError(
|
| 432 |
+
f"Phase-A image feature shape {image.shape} != {expected_image}"
|
| 433 |
+
)
|
| 434 |
+
if position.shape != expected_position:
|
| 435 |
+
raise ValueError(
|
| 436 |
+
f"Phase-A position feature shape {position.shape} != {expected_position}"
|
| 437 |
+
)
|
| 438 |
+
if state.shape != (self.state_emb_dim,):
|
| 439 |
+
raise ValueError(
|
| 440 |
+
f"Phase-A state feature shape {state.shape} != {(self.state_emb_dim,)}"
|
| 441 |
+
)
|
| 442 |
+
image_blocks.append(image.reshape(token_count, self.img_emb_dim))
|
| 443 |
+
position_blocks.append(position.reshape(token_count, self.pos_emb_dim))
|
| 444 |
+
state_blocks.append(np.repeat(state[None, :], token_count, axis=0))
|
| 445 |
+
mask_blocks.append(np.ones(token_count, dtype=np.bool_))
|
| 446 |
+
else:
|
| 447 |
+
image_blocks.append(
|
| 448 |
+
np.zeros((token_count, self.img_emb_dim), dtype=img_dtype)
|
| 449 |
+
)
|
| 450 |
+
position_blocks.append(
|
| 451 |
+
np.zeros((token_count, self.pos_emb_dim), dtype=pos_dtype)
|
| 452 |
+
)
|
| 453 |
+
state_blocks.append(
|
| 454 |
+
np.zeros((token_count, self.state_emb_dim), dtype=state_dtype)
|
| 455 |
+
)
|
| 456 |
+
mask_blocks.append(np.zeros(token_count, dtype=np.bool_))
|
| 457 |
+
|
| 458 |
+
img_emb = np.concatenate(image_blocks, axis=0)
|
| 459 |
+
pos_emb = np.concatenate(position_blocks, axis=0)
|
| 460 |
+
state_emb = np.concatenate(state_blocks, axis=0)
|
| 461 |
+
mask = np.concatenate(mask_blocks, axis=0)
|
| 462 |
+
expected_shapes = (
|
| 463 |
+
(token_budget, self.img_emb_dim),
|
| 464 |
+
(token_budget, self.pos_emb_dim),
|
| 465 |
+
(token_budget, self.state_emb_dim),
|
| 466 |
+
(token_budget,),
|
| 467 |
+
)
|
| 468 |
+
if tuple(value.shape for value in (img_emb, pos_emb, state_emb, mask)) != expected_shapes:
|
| 469 |
+
raise ValueError("Phase-A token materializer shape drift")
|
| 470 |
+
return img_emb, pos_emb, state_emb, mask
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
def _visualize_frame_sampling(self, indices_to_load, step_idx):
|
| 474 |
+
images = [self._history_feats[idx]["image_pixels"][0] for idx in indices_to_load]
|
| 475 |
+
|
| 476 |
+
import imageio, os
|
| 477 |
+
imageio.mimsave(
|
| 478 |
+
os.path.join(
|
| 479 |
+
"debug",
|
| 480 |
+
f"frame_sampling_step_{step_idx}.mp4",
|
| 481 |
+
),
|
| 482 |
+
images,
|
| 483 |
+
fps=2,
|
| 484 |
+
)
|
| 485 |
+
|
| 486 |
+
@staticmethod
|
| 487 |
+
def _load_emb(history_feats: dict, indices_to_load: list[int], key: str):
|
| 488 |
+
return np.stack(
|
| 489 |
+
[history_feats[idx][key] for idx in indices_to_load],
|
| 490 |
+
axis=0,
|
| 491 |
+
)
|
| 492 |
+
|
| 493 |
+
def default_history_feats_gather_fn(self, indices_to_load, *args, **kwargs):
|
| 494 |
+
return {idx: self._history_feats[idx] for idx in indices_to_load}
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
class MemoryBufferRecurrent(MemoryBuffer):
|
| 498 |
+
# By default, we use 8x8 tokens each image for recurrent memory.
|
| 499 |
+
def __init__(
|
| 500 |
+
self,
|
| 501 |
+
input_obs_horizon: int = 8,
|
| 502 |
+
max_recur_steps: int = 64, # max number of recurrent steps for all history
|
| 503 |
+
max_video_steps: int = 40, # max number of recurrent steps to load for the video-based observations for certain video-conditioned tasks
|
| 504 |
+
*args, **kwargs
|
| 505 |
+
):
|
| 506 |
+
|
| 507 |
+
super().__init__(*args, **kwargs)
|
| 508 |
+
|
| 509 |
+
self.input_obs_horizon = input_obs_horizon
|
| 510 |
+
self.max_recur_steps = max_recur_steps
|
| 511 |
+
self.max_video_steps = max_video_steps
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
def add_buffer(
|
| 515 |
+
self,
|
| 516 |
+
images, #: (t v h w 3), np.int8
|
| 517 |
+
state, #: (t d), np.float32
|
| 518 |
+
step_idx_list: list[int],
|
| 519 |
+
):
|
| 520 |
+
assert self.vision_enc is not None, "encode is not initialized"
|
| 521 |
+
|
| 522 |
+
t, v, _, _, _ = images.shape
|
| 523 |
+
assert v == self.num_views
|
| 524 |
+
|
| 525 |
+
image_jnp = jnp.array(
|
| 526 |
+
images.astype(np.float32) / 255.0 * 2.0 - 1.0
|
| 527 |
+
)
|
| 528 |
+
image_jnp = einops.rearrange(image_jnp, "t v h w c -> (t v) h w c")
|
| 529 |
+
image_jnp = image_tools.resize_with_pad(image_jnp, 224, 224)
|
| 530 |
+
image_jnp = einops.rearrange(image_jnp, "(t v) h w c -> t v h w c", t=t, v=v)
|
| 531 |
+
output_emb = self.vision_enc(image_jnp) # (t, v, 64, 2048)
|
| 532 |
+
|
| 533 |
+
# use 8x8 tokens, since recurrent memory can take more tokens than perceptual memory
|
| 534 |
+
pooled_emb_8x8 = pool_tokens_to_size(output_emb, 64) # (t, v, 64, 2048)
|
| 535 |
+
|
| 536 |
+
for i, step_idx in enumerate(step_idx_list):
|
| 537 |
+
image_emb_8x8 = jax.device_get(pooled_emb_8x8)[i] # (v, 64, 2048)
|
| 538 |
+
|
| 539 |
+
pos_emb_8x8 = self.pos_emb_dict["8x8"][
|
| 540 |
+
step_idx*self.num_views : (step_idx+1)*self.num_views] # (v, 64, 768)
|
| 541 |
+
|
| 542 |
+
token_emb_to_save = { # recurrent memory only uses 8x8
|
| 543 |
+
# "image_pixels": images[i].copy(), # fp32
|
| 544 |
+
"image_emb_8x8": image_emb_8x8,
|
| 545 |
+
"pos_emb_8x8": pos_emb_8x8,
|
| 546 |
+
"state_emb": state[i],
|
| 547 |
+
}
|
| 548 |
+
assert step_idx not in self._history_feats, f"step_idx {step_idx} already in buffer"
|
| 549 |
+
self._history_feats[step_idx] = token_emb_to_save
|
| 550 |
+
|
| 551 |
+
|
| 552 |
+
def get_token_recurrent_indices(self, step_idx, exec_start_idx):
|
| 553 |
+
input_obs_horizon = self.input_obs_horizon
|
| 554 |
+
max_recur_steps = self.max_recur_steps
|
| 555 |
+
max_video_steps = self.max_video_steps
|
| 556 |
+
|
| 557 |
+
assert step_idx >=0 and step_idx >= exec_start_idx
|
| 558 |
+
|
| 559 |
+
if exec_start_idx == 0:
|
| 560 |
+
# no videos
|
| 561 |
+
if step_idx < input_obs_horizon:
|
| 562 |
+
indices_to_load = [step_idx]
|
| 563 |
+
else:
|
| 564 |
+
start_idx = step_idx % input_obs_horizon
|
| 565 |
+
indices_to_load = list(range(start_idx, step_idx+1, input_obs_horizon))
|
| 566 |
+
indices_to_load = indices_to_load[-max_recur_steps:]
|
| 567 |
+
else:
|
| 568 |
+
if exec_start_idx <= input_obs_horizon * 2:
|
| 569 |
+
# if too short, use more granular sampling
|
| 570 |
+
video_indices = list(range(0, exec_start_idx, input_obs_horizon//2))
|
| 571 |
+
elif exec_start_idx <= max_video_steps * input_obs_horizon:
|
| 572 |
+
# if not too short, use regular sampling
|
| 573 |
+
video_indices = list(range(0, exec_start_idx, input_obs_horizon))
|
| 574 |
+
else:
|
| 575 |
+
# if too long, use fixed-size sampling
|
| 576 |
+
video_indices = np.linspace(0, exec_start_idx - 1, max_video_steps, dtype=int).tolist()
|
| 577 |
+
|
| 578 |
+
if step_idx-exec_start_idx < input_obs_horizon:
|
| 579 |
+
rest_indices = [step_idx]
|
| 580 |
+
else:
|
| 581 |
+
start_idx = (step_idx-exec_start_idx) % input_obs_horizon + exec_start_idx
|
| 582 |
+
rest_indices = list(range(start_idx, step_idx+1, input_obs_horizon))
|
| 583 |
+
|
| 584 |
+
combined_indices = video_indices + rest_indices
|
| 585 |
+
indices_to_load = combined_indices[-max_recur_steps:]
|
| 586 |
+
|
| 587 |
+
assert len(indices_to_load) > 0 and len(indices_to_load) <= max_recur_steps
|
| 588 |
+
|
| 589 |
+
return indices_to_load
|
| 590 |
+
|
| 591 |
+
|
| 592 |
+
def _prepare_token_recurrent(self, history_feats, indices_to_load, padding=True):
|
| 593 |
+
recur_image_embs = []
|
| 594 |
+
recur_pos_embs = []
|
| 595 |
+
recur_state_embs = []
|
| 596 |
+
recur_masks = []
|
| 597 |
+
|
| 598 |
+
for i in indices_to_load:
|
| 599 |
+
recur_image_embs.append(history_feats[i]["image_emb_8x8"]) # (v, p, d)
|
| 600 |
+
recur_pos_embs.append(history_feats[i]["pos_emb_8x8"]) # (v, p, d)
|
| 601 |
+
recur_state_embs.append(history_feats[i]["state_emb"]) # (d)
|
| 602 |
+
recur_masks.append(True) # (1)
|
| 603 |
+
|
| 604 |
+
recur_image_emb = np.stack(recur_image_embs, axis=0)
|
| 605 |
+
recur_pos_emb = np.stack(recur_pos_embs, axis=0)
|
| 606 |
+
recur_state_emb = np.stack(recur_state_embs, axis=0)
|
| 607 |
+
recur_mask = np.stack(recur_masks, axis=0)
|
| 608 |
+
|
| 609 |
+
if padding:
|
| 610 |
+
recur_image_emb, recur_pos_emb, recur_state_emb, recur_mask = left_padding_token_emb(
|
| 611 |
+
recur_image_emb, recur_pos_emb, recur_state_emb, recur_mask, self.max_recur_steps
|
| 612 |
+
)
|
| 613 |
+
return recur_image_emb, recur_pos_emb, recur_state_emb, recur_mask
|
| 614 |
+
|
| 615 |
+
|
| 616 |
+
def prepare_token_recurrent(self, step_idx, exec_start_idx, history_feats_gather_fn, *args, **kwargs):
|
| 617 |
+
indices_to_load = self.get_token_recurrent_indices(step_idx, exec_start_idx)
|
| 618 |
+
# print("step_idx: ", step_idx, "exec_start_idx: ", exec_start_idx)
|
| 619 |
+
# print(f"indices_to_load ({len(indices_to_load)}): {indices_to_load}")
|
| 620 |
+
assert len(indices_to_load) > 0 and len(indices_to_load) <= self.max_recur_steps
|
| 621 |
+
history_feats = history_feats_gather_fn(indices_to_load, *args, **kwargs)
|
| 622 |
+
# self._visualize_token_recurrent(indices_to_load, step_idx)
|
| 623 |
+
return self._prepare_token_recurrent(history_feats, indices_to_load)
|
| 624 |
+
|
| 625 |
+
def _visualize_token_recurrent(self, indices_to_load, step_idx):
|
| 626 |
+
images = [self._history_feats[idx]["image_pixels"][0] for idx in indices_to_load]
|
| 627 |
+
import imageio, os
|
| 628 |
+
imageio.mimsave(
|
| 629 |
+
os.path.join(
|
| 630 |
+
"debug",
|
| 631 |
+
f"token_recurrent_step_{step_idx}.mp4",
|
| 632 |
+
),
|
| 633 |
+
images,
|
| 634 |
+
fps=2,
|
| 635 |
+
)
|
checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/training/dataset.py
ADDED
|
@@ -0,0 +1,501 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import logging
|
| 3 |
+
import os
|
| 4 |
+
import pickle
|
| 5 |
+
import random
|
| 6 |
+
import re
|
| 7 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
from mme_vla_suite.shared.mem_buffer import MemoryBuffer, MemoryBufferRecurrent
|
| 12 |
+
from mme_vla_suite.training.picmem_phase_a import FRAME_BUDGET, RECENT_ANCHOR_COUNT, selected_frame_read
|
| 13 |
+
from mme_vla_suite.training.picmem_phase_a_reader import (
|
| 14 |
+
FACTOR_FIELDS,
|
| 15 |
+
OBSERVATION_FIELDS,
|
| 16 |
+
PhaseAFactors,
|
| 17 |
+
materialize_phase_a_read,
|
| 18 |
+
)
|
| 19 |
+
from omegaconf import DictConfig
|
| 20 |
+
from openpi.training import config as _config
|
| 21 |
+
from openpi.training.data_loader import Dataset
|
| 22 |
+
|
| 23 |
+
from picmem.data.run084_source_consumer import Run084SourceDigestIndex
|
| 24 |
+
from picmem.provenance.frozen_reader import FrozenSelectionReader
|
| 25 |
+
|
| 26 |
+
random.seed(0)
|
| 27 |
+
logger = logging.getLogger(__name__)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def load_vector_file(vector_path: str, step_idx: int) -> tuple[dict, int]:
|
| 31 |
+
with open(vector_path, "rb") as f:
|
| 32 |
+
return np.load(f, allow_pickle=True).item(), step_idx
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class SampleDataset(Dataset):
|
| 37 |
+
def __init__(self, dataset_path: str):
|
| 38 |
+
self.dataset_path = dataset_path
|
| 39 |
+
self.stats = json.load(open(os.path.join(self.dataset_path, "meta", "stats.json")))
|
| 40 |
+
launch_kind = os.environ.get("PICMEM_PHASE_A_LAUNCH_KIND", "")
|
| 41 |
+
source_digest_sha256 = os.environ.get("PICMEM_SOURCE_DIGEST_SHA256", "")
|
| 42 |
+
dataset_sha256 = os.environ.get("PICMEM_DATASET_SHA256", "")
|
| 43 |
+
if launch_kind == "formal" and not source_digest_sha256:
|
| 44 |
+
raise ValueError("formal Phase-A training requires PICMEM_SOURCE_DIGEST_SHA256")
|
| 45 |
+
self.source_digest_index = None
|
| 46 |
+
if source_digest_sha256:
|
| 47 |
+
if not dataset_sha256:
|
| 48 |
+
raise ValueError("source-digest-bound training requires PICMEM_DATASET_SHA256")
|
| 49 |
+
self.source_digest_index = Run084SourceDigestIndex.from_dataset(
|
| 50 |
+
Path(self.dataset_path),
|
| 51 |
+
expected_dataset_manifest_sha256=dataset_sha256,
|
| 52 |
+
expected_manifest_sha256=source_digest_sha256,
|
| 53 |
+
)
|
| 54 |
+
declared_length = self.stats.get("execution_samples", self.stats.get("total_samples"))
|
| 55 |
+
if declared_length != len(self.source_digest_index.records):
|
| 56 |
+
raise ValueError("dataset stats differ from the source-digest row coverage")
|
| 57 |
+
|
| 58 |
+
def __len__(self):
|
| 59 |
+
if "execution_samples" in self.stats:
|
| 60 |
+
return self.stats["execution_samples"]
|
| 61 |
+
else:
|
| 62 |
+
return self.stats["total_samples"]
|
| 63 |
+
|
| 64 |
+
def __getitem__(self, idx):
|
| 65 |
+
if self.source_digest_index is not None:
|
| 66 |
+
return self.source_digest_index.load_pickle(idx)
|
| 67 |
+
with open(os.path.join(self.dataset_path, "data", f"{idx}.pkl"), "rb") as f:
|
| 68 |
+
return pickle.load(f)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class RoboMMEDataset(Dataset):
|
| 72 |
+
def __init__(
|
| 73 |
+
self,
|
| 74 |
+
dataset_path: str,
|
| 75 |
+
data_config: _config.DataConfig,
|
| 76 |
+
history_config: DictConfig | None,
|
| 77 |
+
action_horizon: int,
|
| 78 |
+
compute_norm_stats: bool = False,
|
| 79 |
+
):
|
| 80 |
+
self.history_config = history_config
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
self.action_horizon = action_horizon
|
| 84 |
+
self.dataset = SampleDataset(dataset_path)
|
| 85 |
+
self.feature_dir = Path(self.dataset.dataset_path) / "features"
|
| 86 |
+
self.phase_a_enabled = False
|
| 87 |
+
self.phase_a_sidecar_dir = None
|
| 88 |
+
self.phase_a_frame_budget = FRAME_BUDGET
|
| 89 |
+
self.phase_a_recent_anchor_count = RECENT_ANCHOR_COUNT
|
| 90 |
+
self.phase_a_factors = PhaseAFactors()
|
| 91 |
+
self.phase_a_metadata_seed = 0
|
| 92 |
+
self.phase_a_selection_reader = None
|
| 93 |
+
|
| 94 |
+
if self.history_config is not None:
|
| 95 |
+
self.img_emb_dim = self.history_config.memory_feature.img.input_dim
|
| 96 |
+
self.pos_emb_dim = self.history_config.memory_feature.pos.input_dim
|
| 97 |
+
self.state_emb_dim = self.history_config.memory_feature.state.input_dim
|
| 98 |
+
self.num_views = self.history_config.num_views
|
| 99 |
+
self.streaming_obs_horizon = self.history_config.streaming_obs_horizon
|
| 100 |
+
|
| 101 |
+
if "perceptual_memory" in self.history_config:
|
| 102 |
+
perceptual = self.history_config.perceptual_memory
|
| 103 |
+
frame_selection = perceptual.get("frame_selection")
|
| 104 |
+
else:
|
| 105 |
+
perceptual = None
|
| 106 |
+
frame_selection = None
|
| 107 |
+
if frame_selection is not None and frame_selection.get("type") == "picmem_phase_a":
|
| 108 |
+
if self.history_config.representation_type != "perceptual":
|
| 109 |
+
raise ValueError("picmem_phase_a requires perceptual representation")
|
| 110 |
+
if perceptual.get("type") != "frame_sampling":
|
| 111 |
+
raise ValueError("picmem_phase_a is only a frame_sampling selector")
|
| 112 |
+
unknown = set(frame_selection) - {
|
| 113 |
+
"type",
|
| 114 |
+
"sidecar_dir",
|
| 115 |
+
"frame_budget",
|
| 116 |
+
"recent_anchor_count",
|
| 117 |
+
"selection_mode",
|
| 118 |
+
"metadata_mode",
|
| 119 |
+
"reader_mode",
|
| 120 |
+
"manager_mode",
|
| 121 |
+
"metadata_seed",
|
| 122 |
+
"require_explicit_factors",
|
| 123 |
+
"subset_manifest_path",
|
| 124 |
+
"subset_manifest_sha256",
|
| 125 |
+
"replacement_manifest_path",
|
| 126 |
+
"replacement_manifest_sha256",
|
| 127 |
+
"best_visible_manifest_path",
|
| 128 |
+
"best_visible_manifest_sha256",
|
| 129 |
+
}
|
| 130 |
+
if unknown:
|
| 131 |
+
raise ValueError(f"unknown picmem_phase_a config fields: {sorted(unknown)}")
|
| 132 |
+
sidecar_dir = frame_selection.get("sidecar_dir")
|
| 133 |
+
if not isinstance(sidecar_dir, str) or not sidecar_dir.strip():
|
| 134 |
+
raise ValueError(
|
| 135 |
+
"picmem_phase_a requires perceptual_memory.frame_selection.sidecar_dir"
|
| 136 |
+
)
|
| 137 |
+
self.phase_a_enabled = True
|
| 138 |
+
self.phase_a_sidecar_dir = Path(sidecar_dir).expanduser().resolve(strict=True)
|
| 139 |
+
if not self.phase_a_sidecar_dir.is_dir():
|
| 140 |
+
raise ValueError(
|
| 141 |
+
f"picmem_phase_a sidecar_dir is not a directory: {self.phase_a_sidecar_dir}"
|
| 142 |
+
)
|
| 143 |
+
self.phase_a_frame_budget = int(
|
| 144 |
+
frame_selection.get("frame_budget", FRAME_BUDGET)
|
| 145 |
+
)
|
| 146 |
+
self.phase_a_recent_anchor_count = int(
|
| 147 |
+
frame_selection.get("recent_anchor_count", RECENT_ANCHOR_COUNT)
|
| 148 |
+
)
|
| 149 |
+
require_explicit = bool(
|
| 150 |
+
frame_selection.get("require_explicit_factors", False)
|
| 151 |
+
)
|
| 152 |
+
factor_values = {
|
| 153 |
+
name: frame_selection.get(name)
|
| 154 |
+
for name in FACTOR_FIELDS
|
| 155 |
+
if name in frame_selection
|
| 156 |
+
}
|
| 157 |
+
self.phase_a_factors = PhaseAFactors.from_mapping(
|
| 158 |
+
factor_values,
|
| 159 |
+
require_explicit=require_explicit,
|
| 160 |
+
)
|
| 161 |
+
self.phase_a_factors.validate_implemented_path()
|
| 162 |
+
frozen_fields = {
|
| 163 |
+
name: frame_selection.get(name)
|
| 164 |
+
for name in (
|
| 165 |
+
"subset_manifest_path",
|
| 166 |
+
"subset_manifest_sha256",
|
| 167 |
+
"replacement_manifest_path",
|
| 168 |
+
"replacement_manifest_sha256",
|
| 169 |
+
"best_visible_manifest_path",
|
| 170 |
+
"best_visible_manifest_sha256",
|
| 171 |
+
)
|
| 172 |
+
}
|
| 173 |
+
missing_frozen = [
|
| 174 |
+
name
|
| 175 |
+
for name, value in frozen_fields.items()
|
| 176 |
+
if not isinstance(value, str) or not value
|
| 177 |
+
]
|
| 178 |
+
if missing_frozen:
|
| 179 |
+
raise ValueError(
|
| 180 |
+
"picmem_phase_a requires frozen selection fields: "
|
| 181 |
+
f"{sorted(missing_frozen)}"
|
| 182 |
+
)
|
| 183 |
+
self.phase_a_selection_reader = FrozenSelectionReader.load_formal(
|
| 184 |
+
subset_manifest_path=frozen_fields["subset_manifest_path"],
|
| 185 |
+
subset_manifest_sha256=frozen_fields["subset_manifest_sha256"],
|
| 186 |
+
replacement_manifest_path=frozen_fields["replacement_manifest_path"],
|
| 187 |
+
replacement_manifest_sha256=frozen_fields["replacement_manifest_sha256"],
|
| 188 |
+
best_visible_manifest_path=frozen_fields["best_visible_manifest_path"],
|
| 189 |
+
best_visible_manifest_sha256=frozen_fields["best_visible_manifest_sha256"],
|
| 190 |
+
manager_mode=self.phase_a_factors.manager_mode,
|
| 191 |
+
)
|
| 192 |
+
self.phase_a_metadata_seed = frame_selection.get("metadata_seed", 0)
|
| 193 |
+
if (
|
| 194 |
+
isinstance(self.phase_a_metadata_seed, bool)
|
| 195 |
+
or not isinstance(self.phase_a_metadata_seed, int)
|
| 196 |
+
or self.phase_a_metadata_seed < 0
|
| 197 |
+
):
|
| 198 |
+
raise ValueError("picmem_phase_a metadata_seed must be a non-negative integer")
|
| 199 |
+
tokens_per_frame = int(self.history_config.token_per_image) * int(self.num_views)
|
| 200 |
+
if (
|
| 201 |
+
int(self.history_config.budget) != 512
|
| 202 |
+
or int(self.history_config.token_per_image) != 16
|
| 203 |
+
or int(self.num_views) != 1
|
| 204 |
+
or int(self.history_config.budget) % tokens_per_frame
|
| 205 |
+
or int(self.history_config.budget) // tokens_per_frame != FRAME_BUDGET
|
| 206 |
+
or self.phase_a_frame_budget != FRAME_BUDGET
|
| 207 |
+
or self.phase_a_recent_anchor_count != RECENT_ANCHOR_COUNT
|
| 208 |
+
):
|
| 209 |
+
raise ValueError(
|
| 210 |
+
"picmem_phase_a requires token_budget=512, token_per_image=16, "
|
| 211 |
+
"num_views=1, frame_budget=32, and recent_anchor_count=4"
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
if self.history_config.representation_type == "perceptual":
|
| 215 |
+
self.mem_buffer = MemoryBuffer(
|
| 216 |
+
num_views=self.num_views,
|
| 217 |
+
img_emb_dim=self.img_emb_dim,
|
| 218 |
+
pos_emb_dim=self.pos_emb_dim,
|
| 219 |
+
state_emb_dim=self.state_emb_dim,
|
| 220 |
+
token_drop_stride=self.streaming_obs_horizon // 2,
|
| 221 |
+
)
|
| 222 |
+
elif self.history_config.representation_type == "recurrent":
|
| 223 |
+
self.mem_buffer = MemoryBufferRecurrent(
|
| 224 |
+
num_views=self.num_views,
|
| 225 |
+
img_emb_dim=self.img_emb_dim,
|
| 226 |
+
pos_emb_dim=self.pos_emb_dim,
|
| 227 |
+
state_emb_dim=self.state_emb_dim,
|
| 228 |
+
input_obs_horizon=self.streaming_obs_horizon,
|
| 229 |
+
max_recur_steps=self.history_config.recurrent_memory.max_recur_steps,
|
| 230 |
+
max_video_steps=self.history_config.recurrent_memory.max_pretraj_steps,
|
| 231 |
+
)
|
| 232 |
+
else:
|
| 233 |
+
# symbolic memory does not need mem_buffer
|
| 234 |
+
self.mem_buffer = None
|
| 235 |
+
else:
|
| 236 |
+
logger.info("=== Do not use history ===")
|
| 237 |
+
|
| 238 |
+
self.compute_norm_stats = compute_norm_stats
|
| 239 |
+
|
| 240 |
+
if not compute_norm_stats:
|
| 241 |
+
self.state_norm_stats = data_config.norm_stats['state']
|
| 242 |
+
self.use_quantiles = data_config.use_quantile_norm
|
| 243 |
+
|
| 244 |
+
def _gather_history_feat(self, indices_to_load: list[int], epis_idx: int):
|
| 245 |
+
history_feats = {}
|
| 246 |
+
history_paths = []
|
| 247 |
+
for idx in indices_to_load:
|
| 248 |
+
history_feats[idx] = {}
|
| 249 |
+
history_paths.append(
|
| 250 |
+
os.path.join(self.feature_dir, f"episode_{epis_idx}", f"token_emb_{idx}.npy")
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
if self.history_config.representation_type == "recurrent":
|
| 254 |
+
# load_vector_fn = load_vector_file_lru4096 if self.use_lru else load_vector_file
|
| 255 |
+
load_vector_fn = load_vector_file
|
| 256 |
+
max_workers = min(48, max(4, len(history_paths)))
|
| 257 |
+
else:
|
| 258 |
+
# load_vector_fn = load_vector_file_lru1024 if self.use_lru else load_vector_file
|
| 259 |
+
load_vector_fn = load_vector_file
|
| 260 |
+
max_workers = min(36, max(4, len(history_paths)))
|
| 261 |
+
with ThreadPoolExecutor(max_workers=max_workers) as executor:
|
| 262 |
+
future_to_path = {
|
| 263 |
+
executor.submit(load_vector_fn, path, idx): path
|
| 264 |
+
for path, idx in zip(history_paths, indices_to_load)
|
| 265 |
+
}
|
| 266 |
+
for future in as_completed(future_to_path):
|
| 267 |
+
np_dict, idx = future.result()
|
| 268 |
+
history_feats[idx] = np_dict
|
| 269 |
+
return history_feats
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def prepare_token_drop(self, epis_idx, step_idx):
|
| 273 |
+
token_budget = self.history_config.budget
|
| 274 |
+
kept_indices = json.load(open(os.path.join(self.feature_dir, f"episode_{epis_idx}", "kept_indices.json")))
|
| 275 |
+
|
| 276 |
+
return self.mem_buffer.prepare_token_dropping(
|
| 277 |
+
step_idx, token_budget, self._gather_history_feat,
|
| 278 |
+
kept_indices=kept_indices, epis_idx=epis_idx)
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def prepare_frame_sampling(self, epis_idx, step_idx, *, selected_indices=None):
|
| 282 |
+
token_per_image = self.history_config.token_per_image
|
| 283 |
+
token_budget = self.history_config.budget
|
| 284 |
+
|
| 285 |
+
return self.mem_buffer.prepare_frame_sampling(
|
| 286 |
+
step_idx, token_budget, token_per_image, self._gather_history_feat,
|
| 287 |
+
selected_indices=selected_indices, epis_idx=epis_idx)
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def prepare_phase_a_frame_sampling(self, epis_idx, step_idx, plan):
|
| 291 |
+
return self.mem_buffer.prepare_phase_a_frame_sampling(
|
| 292 |
+
step_idx,
|
| 293 |
+
int(self.history_config.budget),
|
| 294 |
+
plan.frame_indices,
|
| 295 |
+
plan.valid_mask,
|
| 296 |
+
plan.token_counts,
|
| 297 |
+
self._gather_history_feat,
|
| 298 |
+
epis_idx=epis_idx,
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
def prepare_token_recurrent(self, epis_idx, step_idx, exec_start_idx):
|
| 304 |
+
self.mem_buffer.exec_start_idx = exec_start_idx
|
| 305 |
+
|
| 306 |
+
return self.mem_buffer.prepare_token_recurrent(
|
| 307 |
+
step_idx, exec_start_idx, self._gather_history_feat,
|
| 308 |
+
epis_idx=epis_idx)
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def __len__(self):
|
| 312 |
+
return len(self.dataset)
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
def _normalize_state(self, state):
|
| 316 |
+
if self.compute_norm_stats:
|
| 317 |
+
return state
|
| 318 |
+
else:
|
| 319 |
+
if self.use_quantiles:
|
| 320 |
+
return (state - self.state_norm_stats.q01) / (self.state_norm_stats.q99 - self.state_norm_stats.q01 + 1e-6) * 2.0 - 1.0
|
| 321 |
+
else:
|
| 322 |
+
return (state - self.state_norm_stats.mean) / (self.state_norm_stats.std + 1e-6)
|
| 323 |
+
|
| 324 |
+
def _truncated_gaussian_noise(self, max_val: int, std: float = None) -> int:
|
| 325 |
+
"""Generate truncated Gaussian noise centered at 0, clamped to [-max_val, max_val]."""
|
| 326 |
+
if std is None:
|
| 327 |
+
std = max_val / 2.5 # ~95% of samples within range before clamping
|
| 328 |
+
noise = random.gauss(0, std)
|
| 329 |
+
noise = max(-max_val, min(max_val, noise)) # clamp to [-max_val, max_val]
|
| 330 |
+
return int(round(noise))
|
| 331 |
+
|
| 332 |
+
def add_grounding_augmentation(self, subgoal: str, noise_range: int = 8) -> str:
|
| 333 |
+
if not subgoal:
|
| 334 |
+
return subgoal
|
| 335 |
+
|
| 336 |
+
matches = re.findall(r'at <(\d+), (\d+)>', subgoal)
|
| 337 |
+
|
| 338 |
+
if len(matches) == 0 or len(matches) > 1:
|
| 339 |
+
return subgoal
|
| 340 |
+
|
| 341 |
+
x, y = matches[0]
|
| 342 |
+
x = int(x)
|
| 343 |
+
y = int(y)
|
| 344 |
+
noise_x = self._truncated_gaussian_noise(noise_range)
|
| 345 |
+
noise_y = self._truncated_gaussian_noise(noise_range)
|
| 346 |
+
|
| 347 |
+
new_subgoal = subgoal.replace(f'at <{x}, {y}>', f'at <{x + noise_x}, {y + noise_y}>')
|
| 348 |
+
return new_subgoal
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
def __getitem__(self, idx):
|
| 352 |
+
data = self.dataset[idx]
|
| 353 |
+
|
| 354 |
+
data["actions"] = data["actions"][:self.action_horizon]
|
| 355 |
+
|
| 356 |
+
# During online evaluation, the ground-truth subgoal may change earlier than when it was recorded.
|
| 357 |
+
# To make the model robust to this temporal shift and avoid train/test distribution mismatch,
|
| 358 |
+
# we randomly sample from either subgoal or subgoal_online (early change).
|
| 359 |
+
if self.history_config is not None \
|
| 360 |
+
and self.history_config.representation_type == "symbolic" \
|
| 361 |
+
and self.history_config.symbolic_memory.type in ["simple_subgoal", "grounded_subgoal"] \
|
| 362 |
+
and random.random() < 0.5:
|
| 363 |
+
data["simple_subgoal"] = data["simple_subgoal_online"]
|
| 364 |
+
data["grounded_subgoal"] = data["grounded_subgoal_online"]
|
| 365 |
+
data.pop("simple_subgoal_online")
|
| 366 |
+
data.pop("grounded_subgoal_online")
|
| 367 |
+
|
| 368 |
+
if self.history_config is not None and self.history_config.representation_type == "symbolic":
|
| 369 |
+
data["grounded_subgoal"] = self.add_grounding_augmentation(data["grounded_subgoal"], noise_range=8)
|
| 370 |
+
data["simple_subgoal"] = self.add_grounding_augmentation(data["simple_subgoal"], noise_range=8)
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
if self.history_config is not None:
|
| 374 |
+
# use history
|
| 375 |
+
epis_idx = data["epis_idx"].item()
|
| 376 |
+
step_idx = data["step_idx"].item()
|
| 377 |
+
exec_start_idx = data["exec_start_idx"].item()
|
| 378 |
+
|
| 379 |
+
if self.history_config.representation_type == "perceptual":
|
| 380 |
+
if self.history_config.perceptual_memory.type == "token_dropping":
|
| 381 |
+
(
|
| 382 |
+
static_img_emb,
|
| 383 |
+
static_pos_emb,
|
| 384 |
+
static_state_emb,
|
| 385 |
+
static_mask, # >=64
|
| 386 |
+
) = self.prepare_token_drop(epis_idx, step_idx)
|
| 387 |
+
elif self.phase_a_enabled:
|
| 388 |
+
if self.phase_a_sidecar_dir is None:
|
| 389 |
+
raise ValueError("picmem_phase_a sidecar directory was not initialized")
|
| 390 |
+
if self.phase_a_selection_reader is None:
|
| 391 |
+
raise ValueError("picmem_phase_a frozen selection reader was not initialized")
|
| 392 |
+
frozen_row = self.phase_a_selection_reader.subset.validate_raw_sample(
|
| 393 |
+
int(idx),
|
| 394 |
+
data,
|
| 395 |
+
)
|
| 396 |
+
read = selected_frame_read(
|
| 397 |
+
self.phase_a_sidecar_dir,
|
| 398 |
+
episode_id=int(epis_idx),
|
| 399 |
+
step=int(step_idx),
|
| 400 |
+
raw_exec_start=int(exec_start_idx),
|
| 401 |
+
instruction=data.get("prompt"),
|
| 402 |
+
frame_budget=self.phase_a_frame_budget,
|
| 403 |
+
recent_anchor_count=self.phase_a_recent_anchor_count,
|
| 404 |
+
expected_task_id=frozen_row.task_id,
|
| 405 |
+
expected_sidecar_sha256=frozen_row.sidecar_sha256,
|
| 406 |
+
manager_mode=self.phase_a_factors.manager_mode,
|
| 407 |
+
)
|
| 408 |
+
replacement = self.phase_a_selection_reader.record_for(
|
| 409 |
+
frozen_row,
|
| 410 |
+
current_step=int(step_idx),
|
| 411 |
+
)
|
| 412 |
+
read = self.phase_a_selection_reader.render(
|
| 413 |
+
read,
|
| 414 |
+
replacement,
|
| 415 |
+
self.phase_a_factors.selection_mode,
|
| 416 |
+
)
|
| 417 |
+
plan = materialize_phase_a_read(
|
| 418 |
+
read,
|
| 419 |
+
self.phase_a_factors,
|
| 420 |
+
metadata_seed=self.phase_a_metadata_seed,
|
| 421 |
+
selection_applied=self.phase_a_factors.selection_mode,
|
| 422 |
+
)
|
| 423 |
+
(
|
| 424 |
+
static_img_emb,
|
| 425 |
+
static_pos_emb,
|
| 426 |
+
static_state_emb,
|
| 427 |
+
static_mask,
|
| 428 |
+
) = self.prepare_phase_a_frame_sampling(
|
| 429 |
+
epis_idx,
|
| 430 |
+
step_idx,
|
| 431 |
+
plan,
|
| 432 |
+
)
|
| 433 |
+
metadata = plan.metadata.to_observation()
|
| 434 |
+
if not np.array_equal(static_mask, metadata["phase_a_valid_mask"]):
|
| 435 |
+
raise ValueError("Phase-A visual and metadata token masks disagree")
|
| 436 |
+
data.update(metadata)
|
| 437 |
+
else:
|
| 438 |
+
(
|
| 439 |
+
static_img_emb,
|
| 440 |
+
static_pos_emb,
|
| 441 |
+
static_state_emb,
|
| 442 |
+
static_mask, # slow >=64, mid >=16,fast >=4
|
| 443 |
+
) = self.prepare_frame_sampling(epis_idx, step_idx)
|
| 444 |
+
|
| 445 |
+
data["static_image_emb"] = static_img_emb
|
| 446 |
+
data["static_pos_emb"] = static_pos_emb
|
| 447 |
+
data["static_state_emb"] = self._normalize_state(static_state_emb)
|
| 448 |
+
data["static_mask"] = static_mask
|
| 449 |
+
|
| 450 |
+
elif self.history_config.representation_type == "recurrent":
|
| 451 |
+
recur_img_emb, recur_pos_emb, recur_state_emb, recur_mask = (
|
| 452 |
+
self.prepare_token_recurrent(
|
| 453 |
+
epis_idx, step_idx, exec_start_idx)
|
| 454 |
+
)
|
| 455 |
+
|
| 456 |
+
data["recur_image_emb"] = recur_img_emb
|
| 457 |
+
data["recur_pos_emb"] = recur_pos_emb
|
| 458 |
+
data["recur_state_emb"] = self._normalize_state(recur_state_emb)
|
| 459 |
+
data["recur_mask"] = recur_mask # 1 ~ max_exec_steps
|
| 460 |
+
|
| 461 |
+
elif self.history_config.representation_type == "symbolic":
|
| 462 |
+
pass
|
| 463 |
+
else:
|
| 464 |
+
raise ValueError(
|
| 465 |
+
f"Not supported representation type: {self.history_config.representation_type}"
|
| 466 |
+
)
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
for key in [
|
| 470 |
+
"static_image_emb",
|
| 471 |
+
"static_pos_emb",
|
| 472 |
+
"static_state_emb",
|
| 473 |
+
"static_mask",
|
| 474 |
+
|
| 475 |
+
"recur_image_emb",
|
| 476 |
+
"recur_pos_emb",
|
| 477 |
+
"recur_state_emb",
|
| 478 |
+
"recur_mask",
|
| 479 |
+
|
| 480 |
+
"simple_subgoal",
|
| 481 |
+
"grounded_subgoal",
|
| 482 |
+
"prompt",
|
| 483 |
+
# The pinned host RepackTransform names these optional fields even
|
| 484 |
+
# when the active history type is plain frame sampling. Keep them
|
| 485 |
+
# neutral; Phase-A never imports or materializes either old stack.
|
| 486 |
+
"picmem_token_features",
|
| 487 |
+
"picmem_token_mask",
|
| 488 |
+
"picmem_typed_role_ids",
|
| 489 |
+
"picmem_typed_categorical_ids",
|
| 490 |
+
"picmem_typed_numeric_values",
|
| 491 |
+
"picmem_typed_numeric_mask",
|
| 492 |
+
"picmem_typed_age_confidence",
|
| 493 |
+
"picmem_typed_contract_indices",
|
| 494 |
+
"picmem_typed_token_mask",
|
| 495 |
+
"_picmem_typed_task_index",
|
| 496 |
+
*OBSERVATION_FIELDS,
|
| 497 |
+
]:
|
| 498 |
+
if key not in data:
|
| 499 |
+
data[key] = None
|
| 500 |
+
|
| 501 |
+
return data
|
checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/training/picmem_phase_a.py
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fail-closed RoboMME adapter for the standalone Phase-A memory.
|
| 2 |
+
|
| 3 |
+
This is the only host module allowed to translate a raw RoboMME sample into a
|
| 4 |
+
Phase-A visual-frame plan. It deliberately imports no legacy host-side memory
|
| 5 |
+
package and no general PIC-Mem runtime, tensor, or model surface.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import json
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from typing import Any
|
| 13 |
+
|
| 14 |
+
from picmem.memory.contracts import ManagerMode
|
| 15 |
+
from picmem.memory.memory import MemoryInvariantError, Read
|
| 16 |
+
from picmem.provenance.frozen_artifact import sha256_file
|
| 17 |
+
from picmem.provenance.run084 import replay_sidecar
|
| 18 |
+
|
| 19 |
+
FRAME_BUDGET = 32
|
| 20 |
+
RECENT_ANCHOR_COUNT = 4
|
| 21 |
+
SUPPORTED_TASKS = frozenset({"MoveCube", "PickXtimes", "VideoPlaceButton", "VideoUnmask"})
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def load_episode_sidecar(
|
| 25 |
+
sidecar_dir: str | Path,
|
| 26 |
+
*,
|
| 27 |
+
episode_id: int,
|
| 28 |
+
instruction: str,
|
| 29 |
+
) -> tuple[Path, dict[str, Any]]:
|
| 30 |
+
"""Resolve exactly one task-scoped sidecar for a raw host sample."""
|
| 31 |
+
|
| 32 |
+
episode_id = _nonnegative_int(episode_id, "episode_id")
|
| 33 |
+
instruction = _instruction(instruction)
|
| 34 |
+
root = Path(sidecar_dir).expanduser()
|
| 35 |
+
try:
|
| 36 |
+
root = root.resolve(strict=True)
|
| 37 |
+
except OSError as exc:
|
| 38 |
+
raise MemoryInvariantError(f"sidecar directory is unavailable: {root}") from exc
|
| 39 |
+
if not root.is_dir():
|
| 40 |
+
raise MemoryInvariantError(f"sidecar path is not a directory: {root}")
|
| 41 |
+
|
| 42 |
+
names = {f"episode_{episode_id}.json", f"episode_{episode_id:04d}.json"}
|
| 43 |
+
candidates = sorted(
|
| 44 |
+
{
|
| 45 |
+
path.resolve(strict=True)
|
| 46 |
+
for name in names
|
| 47 |
+
for path in root.glob(f"*/{name}")
|
| 48 |
+
}
|
| 49 |
+
)
|
| 50 |
+
if not candidates:
|
| 51 |
+
raise MemoryInvariantError(
|
| 52 |
+
f"no sidecar exists for episode {episode_id}"
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
matches: list[tuple[Path, dict[str, Any]]] = []
|
| 56 |
+
for path in candidates:
|
| 57 |
+
if root not in path.parents:
|
| 58 |
+
raise MemoryInvariantError(f"sidecar escapes configured root: {path}")
|
| 59 |
+
try:
|
| 60 |
+
annotation = json.loads(path.read_text(encoding="utf-8"))
|
| 61 |
+
except (OSError, json.JSONDecodeError) as exc:
|
| 62 |
+
raise MemoryInvariantError(f"cannot read sidecar JSON: {path}") from exc
|
| 63 |
+
if not isinstance(annotation, dict):
|
| 64 |
+
raise MemoryInvariantError(f"sidecar must contain a JSON object: {path}")
|
| 65 |
+
if _nonnegative_int(annotation.get("episode_id"), "sidecar episode_id") != episode_id:
|
| 66 |
+
raise MemoryInvariantError(f"sidecar episode identity mismatch: {path}")
|
| 67 |
+
task_id = annotation.get("task_id")
|
| 68 |
+
if task_id not in SUPPORTED_TASKS or path.parent.name != task_id:
|
| 69 |
+
raise MemoryInvariantError(f"sidecar task identity mismatch: {path}")
|
| 70 |
+
if _instruction(annotation.get("task_instruction")) == instruction:
|
| 71 |
+
matches.append((path, annotation))
|
| 72 |
+
|
| 73 |
+
if len(matches) != 1:
|
| 74 |
+
raise MemoryInvariantError(
|
| 75 |
+
f"expected exactly one episode/instruction sidecar for episode {episode_id}, "
|
| 76 |
+
f"found {len(matches)}"
|
| 77 |
+
)
|
| 78 |
+
return matches[0]
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def selected_frame_indices(
|
| 82 |
+
sidecar_dir: str | Path,
|
| 83 |
+
*,
|
| 84 |
+
episode_id: int,
|
| 85 |
+
step: int,
|
| 86 |
+
raw_exec_start: int,
|
| 87 |
+
instruction: str,
|
| 88 |
+
frame_budget: int = FRAME_BUDGET,
|
| 89 |
+
recent_anchor_count: int = RECENT_ANCHOR_COUNT,
|
| 90 |
+
manager_mode: ManagerMode | str = ManagerMode.FULL_EVOLVING,
|
| 91 |
+
) -> tuple[int, ...]:
|
| 92 |
+
"""Return the sole frame plan consumed by the host perceptual loader."""
|
| 93 |
+
|
| 94 |
+
read = selected_frame_read(
|
| 95 |
+
sidecar_dir,
|
| 96 |
+
episode_id=episode_id,
|
| 97 |
+
step=step,
|
| 98 |
+
raw_exec_start=raw_exec_start,
|
| 99 |
+
instruction=instruction,
|
| 100 |
+
frame_budget=frame_budget,
|
| 101 |
+
recent_anchor_count=recent_anchor_count,
|
| 102 |
+
manager_mode=manager_mode,
|
| 103 |
+
)
|
| 104 |
+
return tuple(read.valid_indices())
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def selected_frame_read(
|
| 108 |
+
sidecar_dir: str | Path,
|
| 109 |
+
*,
|
| 110 |
+
episode_id: int,
|
| 111 |
+
step: int,
|
| 112 |
+
raw_exec_start: int,
|
| 113 |
+
instruction: str,
|
| 114 |
+
frame_budget: int = FRAME_BUDGET,
|
| 115 |
+
recent_anchor_count: int = RECENT_ANCHOR_COUNT,
|
| 116 |
+
expected_task_id: str | None = None,
|
| 117 |
+
expected_sidecar_sha256: str | None = None,
|
| 118 |
+
manager_mode: ManagerMode | str = ManagerMode.FULL_EVOLVING,
|
| 119 |
+
) -> Read:
|
| 120 |
+
"""Return the complete frame plan and provenance for one host sample."""
|
| 121 |
+
|
| 122 |
+
step = _nonnegative_int(step, "step")
|
| 123 |
+
raw_exec_start = _nonnegative_int(raw_exec_start, "raw_exec_start")
|
| 124 |
+
if frame_budget != FRAME_BUDGET:
|
| 125 |
+
raise MemoryInvariantError(f"Phase-A frame_budget must be {FRAME_BUDGET}")
|
| 126 |
+
if recent_anchor_count != RECENT_ANCHOR_COUNT:
|
| 127 |
+
raise MemoryInvariantError(
|
| 128 |
+
f"Phase-A recent_anchor_count must be {RECENT_ANCHOR_COUNT}"
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
path, annotation = load_episode_sidecar(
|
| 132 |
+
sidecar_dir,
|
| 133 |
+
episode_id=episode_id,
|
| 134 |
+
instruction=instruction,
|
| 135 |
+
)
|
| 136 |
+
if expected_task_id is not None and annotation.get("task_id") != expected_task_id:
|
| 137 |
+
raise MemoryInvariantError(
|
| 138 |
+
f"sidecar task differs from frozen sample identity at {path}"
|
| 139 |
+
)
|
| 140 |
+
if expected_sidecar_sha256 is not None:
|
| 141 |
+
actual_sidecar_sha256 = sha256_file(path)
|
| 142 |
+
if actual_sidecar_sha256 != expected_sidecar_sha256:
|
| 143 |
+
raise MemoryInvariantError(
|
| 144 |
+
f"sidecar hash differs from frozen sample identity at {path}"
|
| 145 |
+
)
|
| 146 |
+
sidecar_exec_start = _nonnegative_int(
|
| 147 |
+
annotation.get("exec_start_step"),
|
| 148 |
+
"sidecar exec_start_step",
|
| 149 |
+
)
|
| 150 |
+
step_offset = raw_exec_start - sidecar_exec_start
|
| 151 |
+
if step_offset < 0:
|
| 152 |
+
raise MemoryInvariantError(
|
| 153 |
+
f"raw execution starts before sidecar execution at {path}: "
|
| 154 |
+
f"{raw_exec_start} < {sidecar_exec_start}"
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
read = replay_sidecar(
|
| 158 |
+
annotation,
|
| 159 |
+
step,
|
| 160 |
+
step_offset=step_offset,
|
| 161 |
+
budget=frame_budget,
|
| 162 |
+
recent=recent_anchor_count,
|
| 163 |
+
manager_mode=manager_mode,
|
| 164 |
+
)
|
| 165 |
+
indices = read.valid_indices()
|
| 166 |
+
if not isinstance(indices, list) or any(
|
| 167 |
+
isinstance(value, bool) or not isinstance(value, int) for value in indices
|
| 168 |
+
):
|
| 169 |
+
raise MemoryInvariantError("Phase-A Read.valid_indices() returned non-integers")
|
| 170 |
+
if not indices:
|
| 171 |
+
raise MemoryInvariantError("Phase-A Read selected no visual frames")
|
| 172 |
+
if indices != sorted(set(indices)):
|
| 173 |
+
raise MemoryInvariantError("Phase-A Read selected duplicate or unsorted frames")
|
| 174 |
+
if len(indices) != min(frame_budget, step + 1) or indices[0] < 0 or indices[-1] > step:
|
| 175 |
+
raise MemoryInvariantError("Phase-A Read violated its causal frame budget")
|
| 176 |
+
if tuple(indices) != tuple(
|
| 177 |
+
frame.frame_index for frame in read.selected_frames if frame.valid_mask
|
| 178 |
+
):
|
| 179 |
+
raise MemoryInvariantError("Phase-A Read metadata does not align with valid_indices()")
|
| 180 |
+
return read
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def _instruction(value: Any) -> str:
|
| 184 |
+
if not isinstance(value, str) or not value or "\0" in value:
|
| 185 |
+
raise MemoryInvariantError("instruction must be a non-empty string")
|
| 186 |
+
return value
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def _nonnegative_int(value: Any, name: str) -> int:
|
| 190 |
+
if isinstance(value, bool) or not isinstance(value, int) or value < 0:
|
| 191 |
+
raise MemoryInvariantError(f"{name} must be a non-negative integer")
|
| 192 |
+
return int(value)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
__all__ = [
|
| 196 |
+
"FRAME_BUDGET",
|
| 197 |
+
"RECENT_ANCHOR_COUNT",
|
| 198 |
+
"load_episode_sidecar",
|
| 199 |
+
"selected_frame_indices",
|
| 200 |
+
"selected_frame_read",
|
| 201 |
+
]
|
checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/training/picmem_phase_a_full_state.py
ADDED
|
@@ -0,0 +1,1936 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Trajectory-complete Phase-A checkpoint, sampler, and continuity runtime."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import csv
|
| 6 |
+
import dataclasses
|
| 7 |
+
import functools
|
| 8 |
+
import hashlib
|
| 9 |
+
import json
|
| 10 |
+
import logging
|
| 11 |
+
import math
|
| 12 |
+
import os
|
| 13 |
+
import shutil
|
| 14 |
+
import tempfile
|
| 15 |
+
from collections.abc import Iterator, Mapping
|
| 16 |
+
from datetime import datetime
|
| 17 |
+
from pathlib import Path, PurePosixPath
|
| 18 |
+
from typing import Any, Protocol
|
| 19 |
+
|
| 20 |
+
import jax
|
| 21 |
+
import numpy as np
|
| 22 |
+
import openpi.training.checkpoints as _checkpoints
|
| 23 |
+
import orbax.checkpoint as ocp
|
| 24 |
+
import torch
|
| 25 |
+
from etils import epath
|
| 26 |
+
from mme_vla_suite.models.config.utils import get_history_config
|
| 27 |
+
from mme_vla_suite.models.integration.history_observation import HistAugObservation
|
| 28 |
+
from mme_vla_suite.training.dataset import RoboMMEDataset
|
| 29 |
+
from openpi.shared import normalize as _normalize
|
| 30 |
+
from openpi.training.data_loader import TorchDataLoader, transform_dataset
|
| 31 |
+
|
| 32 |
+
from picmem.memory.contracts import ArmManifest
|
| 33 |
+
from picmem.ops.calibration_manifest import (
|
| 34 |
+
CalibrationManifestError,
|
| 35 |
+
SkuCalibrationManifest,
|
| 36 |
+
load_calibration_manifest,
|
| 37 |
+
)
|
| 38 |
+
from picmem.ops.checkpoint import (
|
| 39 |
+
CheckpointInfo,
|
| 40 |
+
CheckpointMetadata,
|
| 41 |
+
SamplerState,
|
| 42 |
+
StateComponent,
|
| 43 |
+
StateManifest,
|
| 44 |
+
discover_checkpoints,
|
| 45 |
+
finalize_checkpoint,
|
| 46 |
+
is_phase_a_retained_checkpoint,
|
| 47 |
+
path_sha256,
|
| 48 |
+
validate_checkpoint,
|
| 49 |
+
)
|
| 50 |
+
from picmem.ops.continuity import CONTINUITY_SCHEMA, ContinuityMode, SamplerContinuity, WatchState, verify_continuity
|
| 51 |
+
from picmem.ops.registry import RUN084_BUILD_C_LINEAGE
|
| 52 |
+
|
| 53 |
+
PHASE_A_CONTRACT_SCHEMA = "picmem_phase_a_host_full_state_v5"
|
| 54 |
+
PHASE_A_METRICS_SCHEMA = "picmem_phase_a_generation_metrics_v1"
|
| 55 |
+
PHASE_A_HISTORY_CONFIG = "perceptual-picmem-phase-a-modul.yaml"
|
| 56 |
+
SUPPORTED_GPU_CLASSES = frozenset({"h200", "h100_80g", "a100_80g", "a100_40g"})
|
| 57 |
+
FORMAL_SAMPLER_SCHEMA = "picmem_run084_task_balanced_sampler_state_v1"
|
| 58 |
+
SMOKE_SAMPLER_SCHEMA = "picmem_phase_a_smoke_random_sampler_state_v1"
|
| 59 |
+
SMOKE_SUBSET_SHA256 = hashlib.sha256(b"picmem-phase-a-smoke-subset-v1").hexdigest()
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _identifier(value: Any, name: str) -> str:
|
| 63 |
+
portable = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-"
|
| 64 |
+
if not isinstance(value, str) or not value or any(char not in portable for char in value):
|
| 65 |
+
raise ValueError(f"{name} must be a non-empty portable identifier")
|
| 66 |
+
return value
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _sha256(value: Any, name: str, *, nullable: bool = False) -> str | None:
|
| 70 |
+
if nullable and (value is None or value == ""):
|
| 71 |
+
return None
|
| 72 |
+
if not isinstance(value, str) or len(value) != 64 or any(char not in "0123456789abcdef" for char in value):
|
| 73 |
+
raise ValueError(f"{name} must be a lowercase SHA-256 digest")
|
| 74 |
+
return value
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _commit(value: Any, name: str) -> str:
|
| 78 |
+
if not isinstance(value, str) or len(value) != 40 or any(char not in "0123456789abcdef" for char in value):
|
| 79 |
+
raise ValueError(f"{name} must be a full lowercase git commit")
|
| 80 |
+
return value
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _runtime_fraction(value: Any, name: str) -> str:
|
| 84 |
+
if not isinstance(value, str) or value not in {"0.8", "0.9", "0.92"}:
|
| 85 |
+
raise ValueError(f"{name} must be a reviewed canonical runtime fraction")
|
| 86 |
+
return value
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _runtime_true(value: Any, name: str) -> bool:
|
| 90 |
+
if value != "true":
|
| 91 |
+
raise ValueError(f"{name} must be the reviewed canonical value 'true'")
|
| 92 |
+
return True
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def _repr_sha256(value: Any) -> str:
|
| 96 |
+
return hashlib.sha256(repr(value).encode("utf-8")).hexdigest()
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def _natural(value: str | int, name: str) -> int:
|
| 100 |
+
try:
|
| 101 |
+
parsed = int(value)
|
| 102 |
+
except (TypeError, ValueError) as exc:
|
| 103 |
+
raise ValueError(f"{name} must be a non-negative integer") from exc
|
| 104 |
+
if isinstance(value, bool) or parsed < 0 or str(parsed) != str(value):
|
| 105 |
+
raise ValueError(f"{name} must be a canonical non-negative integer")
|
| 106 |
+
return parsed
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def _sampler_natural(value: Any, name: str) -> int:
|
| 110 |
+
if isinstance(value, bool) or not isinstance(value, (int, np.integer)) or int(value) < 0:
|
| 111 |
+
raise ValueError(f"{name} must be a non-negative integer")
|
| 112 |
+
return int(value)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _u64_words(value: int, name: str) -> jax.Array:
|
| 116 |
+
parsed = _natural(value, name)
|
| 117 |
+
if parsed > np.iinfo(np.uint64).max:
|
| 118 |
+
raise ValueError(f"{name} is larger than an unsigned 64-bit integer")
|
| 119 |
+
return jax.numpy.asarray(
|
| 120 |
+
[parsed & 0xFFFFFFFF, (parsed >> 32) & 0xFFFFFFFF],
|
| 121 |
+
dtype=jax.numpy.uint32,
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def _decode_u64_words(value: Any, name: str) -> int:
|
| 126 |
+
words = np.asarray(jax.device_get(value), dtype=np.uint32).reshape(-1)
|
| 127 |
+
if words.shape != (2,):
|
| 128 |
+
raise ValueError(f"{name} must contain exactly two uint32 words")
|
| 129 |
+
return int(words[0]) | (int(words[1]) << 32)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def _digest_bytes(value: str, name: str) -> jax.Array:
|
| 133 |
+
parsed = _sha256(value, name)
|
| 134 |
+
return jax.numpy.asarray(np.frombuffer(bytes.fromhex(str(parsed)), dtype=np.uint8))
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def _decode_digest(value: Any, name: str) -> str:
|
| 138 |
+
raw = np.asarray(jax.device_get(value), dtype=np.uint8).reshape(-1)
|
| 139 |
+
if raw.shape != (32,):
|
| 140 |
+
raise ValueError(f"{name} must contain exactly 32 digest bytes")
|
| 141 |
+
return str(_sha256(raw.tobytes().hex(), name))
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def _ascii_bytes(value: str, name: str) -> jax.Array:
|
| 145 |
+
parsed = _identifier(value, name)
|
| 146 |
+
return jax.numpy.asarray(np.frombuffer(parsed.encode("ascii"), dtype=np.uint8))
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def _decode_ascii(value: Any, name: str) -> str:
|
| 150 |
+
raw = np.asarray(jax.device_get(value), dtype=np.uint8).reshape(-1)
|
| 151 |
+
try:
|
| 152 |
+
decoded = raw.tobytes().decode("ascii")
|
| 153 |
+
except UnicodeDecodeError as exc:
|
| 154 |
+
raise ValueError(f"{name} is not ASCII") from exc
|
| 155 |
+
return _identifier(decoded, name)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def _path_bytes(value: Path, name: str) -> jax.Array:
|
| 159 |
+
parsed = _bound_regular_file(str(value), name)
|
| 160 |
+
return jax.numpy.asarray(np.frombuffer(str(parsed).encode("utf-8"), dtype=np.uint8))
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def _decode_path(value: Any, name: str) -> str:
|
| 164 |
+
raw = np.asarray(jax.device_get(value), dtype=np.uint8).reshape(-1)
|
| 165 |
+
try:
|
| 166 |
+
decoded = raw.tobytes().decode("utf-8")
|
| 167 |
+
except UnicodeDecodeError as exc:
|
| 168 |
+
raise ValueError(f"{name} is not UTF-8") from exc
|
| 169 |
+
return str(_bound_regular_file(decoded, name))
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def _sample_identity(value: Any, name: str) -> str:
|
| 173 |
+
return str(_sha256(value, name))
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def _bound_regular_file(value: Any, name: str) -> Path:
|
| 177 |
+
if not isinstance(value, str) or not value or any(character in value for character in "\r\n\0\\"):
|
| 178 |
+
raise ValueError(f"{name} must be a normalized absolute file path")
|
| 179 |
+
pure = PurePosixPath(value)
|
| 180 |
+
if not pure.is_absolute() or any(part in {"", ".", ".."} for part in pure.parts) or pure.as_posix() != value:
|
| 181 |
+
raise ValueError(f"{name} must be a normalized absolute file path")
|
| 182 |
+
path = Path(value)
|
| 183 |
+
if path.is_symlink() or not path.is_file() or path.resolve() != path:
|
| 184 |
+
raise ValueError(f"{name} must name a real canonical regular file")
|
| 185 |
+
return path
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def _canonical_json(value: Mapping[str, Any]) -> bytes:
|
| 189 |
+
return (json.dumps(value, sort_keys=True, separators=(",", ":")) + "\n").encode()
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def _pairs_no_duplicates(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
| 193 |
+
result: dict[str, Any] = {}
|
| 194 |
+
for key, value in pairs:
|
| 195 |
+
if key in result:
|
| 196 |
+
raise ValueError(f"duplicate JSON key in arm manifest: {key}")
|
| 197 |
+
result[key] = value
|
| 198 |
+
return result
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def _gpu_class_from_sku(value: str) -> str:
|
| 202 |
+
if not isinstance(value, str) or not value.strip():
|
| 203 |
+
raise ValueError("arm.gpu_sku must be a non-empty string")
|
| 204 |
+
sku = value.lower().replace("-", "_")
|
| 205 |
+
if "h200" in sku:
|
| 206 |
+
return "h200"
|
| 207 |
+
if "h100" in sku and "80" in sku:
|
| 208 |
+
return "h100_80g"
|
| 209 |
+
if "a100" in sku and "80" in sku:
|
| 210 |
+
return "a100_80g"
|
| 211 |
+
if "a100" in sku and "40" in sku:
|
| 212 |
+
return "a100_40g"
|
| 213 |
+
raise ValueError(f"unsupported arm gpu_sku: {value!r}")
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def _write_atomic_json(path: Path, value: Mapping[str, Any], *, refuse_existing: bool = True) -> None:
|
| 217 |
+
payload = _canonical_json(value)
|
| 218 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 219 |
+
if path.exists() or path.is_symlink():
|
| 220 |
+
if refuse_existing or path.is_symlink() or not path.is_file() or path.read_bytes() != payload:
|
| 221 |
+
raise ValueError(f"refusing to replace existing JSON contract: {path}")
|
| 222 |
+
return
|
| 223 |
+
descriptor, temporary = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent)
|
| 224 |
+
try:
|
| 225 |
+
with os.fdopen(descriptor, "wb") as handle:
|
| 226 |
+
handle.write(payload)
|
| 227 |
+
handle.flush()
|
| 228 |
+
os.fsync(handle.fileno())
|
| 229 |
+
os.replace(temporary, path)
|
| 230 |
+
directory = os.open(path.parent, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0))
|
| 231 |
+
try:
|
| 232 |
+
os.fsync(directory)
|
| 233 |
+
finally:
|
| 234 |
+
os.close(directory)
|
| 235 |
+
finally:
|
| 236 |
+
if os.path.exists(temporary):
|
| 237 |
+
os.unlink(temporary)
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def validate_phase_a_topology(
|
| 241 |
+
*,
|
| 242 |
+
gpu_class: str,
|
| 243 |
+
world_size: int,
|
| 244 |
+
local_device_count: int,
|
| 245 |
+
process_count: int,
|
| 246 |
+
fsdp_devices: int,
|
| 247 |
+
batch_size: int,
|
| 248 |
+
device_kinds: tuple[str, ...],
|
| 249 |
+
) -> None:
|
| 250 |
+
if gpu_class not in SUPPORTED_GPU_CLASSES:
|
| 251 |
+
raise ValueError(f"unsupported Phase-A GPU class: {gpu_class!r}")
|
| 252 |
+
if (world_size, local_device_count, process_count, fsdp_devices) != (8, 8, 1, 8):
|
| 253 |
+
raise ValueError(
|
| 254 |
+
"Phase-A full state requires exactly one process and eight local/global FSDP devices; "
|
| 255 |
+
f"got world={world_size} local={local_device_count} process={process_count} fsdp={fsdp_devices}"
|
| 256 |
+
)
|
| 257 |
+
if isinstance(batch_size, bool) or not isinstance(batch_size, int) or batch_size <= 0 or batch_size % 4:
|
| 258 |
+
raise ValueError("Phase-A global batch must be a positive integer divisible by four tasks")
|
| 259 |
+
if len(device_kinds) != 8:
|
| 260 |
+
raise ValueError("Phase-A topology must describe exactly eight device kinds")
|
| 261 |
+
family = "H200" if gpu_class == "h200" else "H100" if gpu_class == "h100_80g" else "A100"
|
| 262 |
+
if any(family not in kind.upper() for kind in device_kinds):
|
| 263 |
+
raise ValueError(f"Phase-A runtime device family differs from requested {gpu_class}")
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def initialize_phase_a_checkpoint_dir(
|
| 267 |
+
checkpoint_dir: epath.Path | str,
|
| 268 |
+
*,
|
| 269 |
+
overwrite: bool,
|
| 270 |
+
resume: bool,
|
| 271 |
+
launch_kind: str,
|
| 272 |
+
) -> tuple[ocp.CheckpointManager, bool]:
|
| 273 |
+
"""Create a manager retaining the latest two plus launch-kind milestones."""
|
| 274 |
+
|
| 275 |
+
retention_policy = functools.partial(is_phase_a_retained_checkpoint, launch_kind=launch_kind)
|
| 276 |
+
# Reject an invalid launch kind before overwrite can mutate the checkpoint root.
|
| 277 |
+
retention_policy(0)
|
| 278 |
+
checkpoint_dir = epath.Path(checkpoint_dir).resolve()
|
| 279 |
+
resuming = False
|
| 280 |
+
if checkpoint_dir.exists():
|
| 281 |
+
if overwrite:
|
| 282 |
+
checkpoint_dir.rmtree()
|
| 283 |
+
checkpoint_dir.mkdir(parents=True, exist_ok=True)
|
| 284 |
+
logging.info("Wiped Phase-A checkpoint directory %s", checkpoint_dir)
|
| 285 |
+
elif resume:
|
| 286 |
+
discovery = discover_checkpoints(Path(checkpoint_dir))
|
| 287 |
+
if discovery.rejected:
|
| 288 |
+
details = ", ".join(f"{name}: {reason}" for name, reason in sorted(discovery.rejected.items()))
|
| 289 |
+
raise ValueError(
|
| 290 |
+
"Phase-A resume is blocked by unresolved checkpoint-like paths; "
|
| 291 |
+
"move them to an explicit recovery/abandoned root before retrying: "
|
| 292 |
+
f"{details}"
|
| 293 |
+
)
|
| 294 |
+
resuming = discovery.selected is not None
|
| 295 |
+
if not resuming:
|
| 296 |
+
logging.info("Phase-A checkpoint root contains no finalized checkpoint")
|
| 297 |
+
else:
|
| 298 |
+
raise FileExistsError(f"Checkpoint directory {checkpoint_dir} already exists. Use resume to continue it.")
|
| 299 |
+
checkpoint_dir.mkdir(parents=True, exist_ok=True)
|
| 300 |
+
manager = ocp.CheckpointManager(
|
| 301 |
+
checkpoint_dir,
|
| 302 |
+
item_handlers={
|
| 303 |
+
"assets": _checkpoints.CallbackHandler(),
|
| 304 |
+
"params": ocp.PyTreeCheckpointHandler(),
|
| 305 |
+
"resume_state": ocp.PyTreeCheckpointHandler(),
|
| 306 |
+
},
|
| 307 |
+
options=ocp.CheckpointManagerOptions(
|
| 308 |
+
max_to_keep=2,
|
| 309 |
+
should_keep_fn=retention_policy,
|
| 310 |
+
create=False,
|
| 311 |
+
async_options=ocp.AsyncOptions(timeout_secs=7_200),
|
| 312 |
+
),
|
| 313 |
+
)
|
| 314 |
+
return manager, resuming
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
@dataclasses.dataclass(frozen=True)
|
| 318 |
+
class PhaseAContract:
|
| 319 |
+
launch_kind: str
|
| 320 |
+
experiment: str
|
| 321 |
+
job: str
|
| 322 |
+
run_id: str
|
| 323 |
+
generation: int
|
| 324 |
+
gpu_class: str
|
| 325 |
+
checkpoint_root: Path
|
| 326 |
+
interface_commit: str
|
| 327 |
+
code_commit: str
|
| 328 |
+
config_sha256: str
|
| 329 |
+
dataset_sha256: str
|
| 330 |
+
cohort_sha256: str
|
| 331 |
+
sidecar_sha256: str
|
| 332 |
+
feature_sha256: str
|
| 333 |
+
source_metadata_sha256: str
|
| 334 |
+
source_digest_sha256: str
|
| 335 |
+
artifact_identity_sha256: str
|
| 336 |
+
artifact_hashes_sha256: str
|
| 337 |
+
replacement_manifest_sha256: str
|
| 338 |
+
best_visible_manifest_sha256: str
|
| 339 |
+
sample_order_path: Path
|
| 340 |
+
sample_order_manifest_sha256: str
|
| 341 |
+
sample_order_sha256: str
|
| 342 |
+
training_manifest_kind: str
|
| 343 |
+
training_manifest_sha256: str
|
| 344 |
+
overlay_sha256: str
|
| 345 |
+
runtime_profile_id: str
|
| 346 |
+
runtime_candidate_id: str
|
| 347 |
+
runtime_policy_sha256: str
|
| 348 |
+
runtime_plan_sha256: str
|
| 349 |
+
runtime_matrix_sha256: str
|
| 350 |
+
runtime_calibration_sha256: str
|
| 351 |
+
optimizer_sha256: str
|
| 352 |
+
learning_rate_schedule_sha256: str
|
| 353 |
+
global_batch_size: int
|
| 354 |
+
micro_batch_per_device: int
|
| 355 |
+
gradient_accumulation_steps: int
|
| 356 |
+
dataloader_workers: int
|
| 357 |
+
prefetch_factor: int
|
| 358 |
+
xla_preallocate: bool
|
| 359 |
+
xla_memory_fraction: str
|
| 360 |
+
nccl_collective_channel_cap: int
|
| 361 |
+
nccl_p2p_channel_cap: int
|
| 362 |
+
xla_flags: str
|
| 363 |
+
runtime_checkpoint_interval: int
|
| 364 |
+
parent_metadata_sha256: str | None
|
| 365 |
+
continuity_mode: str
|
| 366 |
+
continuity_request_id: str
|
| 367 |
+
watch_state_dir: Path
|
| 368 |
+
continuity_path: Path
|
| 369 |
+
metrics_path: Path
|
| 370 |
+
|
| 371 |
+
@classmethod
|
| 372 |
+
def from_environment(cls, config: Any) -> PhaseAContract:
|
| 373 |
+
launch_kind = os.environ.get("PICMEM_PHASE_A_LAUNCH_KIND", "")
|
| 374 |
+
if launch_kind not in {"formal", "sku_smoke"}:
|
| 375 |
+
raise ValueError("PICMEM_PHASE_A_LAUNCH_KIND must be formal or sku_smoke")
|
| 376 |
+
gpu_class = os.environ.get("PICMEM_CHECKPOINT_GPU_CLASS", "")
|
| 377 |
+
global_batch_size = _natural(os.environ.get("BATCH_SIZE", ""), "BATCH_SIZE")
|
| 378 |
+
if global_batch_size <= 0:
|
| 379 |
+
raise ValueError("BATCH_SIZE must be positive")
|
| 380 |
+
devices = tuple(jax.devices())
|
| 381 |
+
validate_phase_a_topology(
|
| 382 |
+
gpu_class=gpu_class,
|
| 383 |
+
world_size=jax.device_count(),
|
| 384 |
+
local_device_count=jax.local_device_count(),
|
| 385 |
+
process_count=jax.process_count(),
|
| 386 |
+
fsdp_devices=int(config.fsdp_devices),
|
| 387 |
+
batch_size=global_batch_size,
|
| 388 |
+
device_kinds=tuple(str(device.device_kind) for device in devices),
|
| 389 |
+
)
|
| 390 |
+
checkpoint_root = Path(os.environ.get("PICMEM_CHECKPOINT_ROOT", "")).expanduser().resolve()
|
| 391 |
+
if checkpoint_root != Path(config.checkpoint_dir).resolve():
|
| 392 |
+
raise ValueError("PICMEM_CHECKPOINT_ROOT differs from TrainConfig.checkpoint_dir")
|
| 393 |
+
experiment = _identifier(os.environ.get("PICMEM_CHECKPOINT_EXPERIMENT"), "experiment")
|
| 394 |
+
if experiment != config.exp_name:
|
| 395 |
+
raise ValueError("checkpoint experiment differs from TrainConfig.exp_name")
|
| 396 |
+
generation = _natural(os.environ.get("PICMEM_CHECKPOINT_GENERATION", ""), "generation")
|
| 397 |
+
mode = os.environ.get("PICMEM_CONTINUITY_MODE", "")
|
| 398 |
+
parent = _sha256(
|
| 399 |
+
os.environ.get("PICMEM_PARENT_METADATA_SHA256"),
|
| 400 |
+
"PICMEM_PARENT_METADATA_SHA256",
|
| 401 |
+
nullable=True,
|
| 402 |
+
)
|
| 403 |
+
if generation == 0:
|
| 404 |
+
if mode != "initial" or parent is not None:
|
| 405 |
+
raise ValueError("generation zero must be an initial launch without a checkpoint parent")
|
| 406 |
+
elif mode == ContinuityMode.CHECKPOINT_RESUME.value:
|
| 407 |
+
if parent is None:
|
| 408 |
+
raise ValueError("checkpoint_resume requires its exact parent metadata SHA-256")
|
| 409 |
+
elif mode == ContinuityMode.RESTART_ZERO.value:
|
| 410 |
+
if parent is not None:
|
| 411 |
+
raise ValueError("restart_zero must not name a checkpoint parent")
|
| 412 |
+
else:
|
| 413 |
+
raise ValueError("nonzero launcher generation has an unsupported continuity mode")
|
| 414 |
+
watch_state_dir = Path(os.environ.get("PICMEM_WATCH_STATE_DIR", "")).expanduser().resolve()
|
| 415 |
+
continuity_request_id = _identifier(
|
| 416 |
+
os.environ.get("PICMEM_CONTINUITY_REQUEST_ID"),
|
| 417 |
+
"PICMEM_CONTINUITY_REQUEST_ID",
|
| 418 |
+
)
|
| 419 |
+
if mode != "initial":
|
| 420 |
+
_sha256(continuity_request_id, "PICMEM_CONTINUITY_REQUEST_ID")
|
| 421 |
+
continuity_path = Path(os.environ.get("PICMEM_CONTINUITY_PATH", "")).expanduser().resolve()
|
| 422 |
+
if continuity_path != watch_state_dir / f"continuity-{continuity_request_id}.json":
|
| 423 |
+
raise ValueError("PICMEM_CONTINUITY_PATH is not request-bound to the watchdog state directory")
|
| 424 |
+
metrics_path = Path(os.environ.get("PICMEM_METRICS_PATH", "")).expanduser().resolve()
|
| 425 |
+
expected_suffix = ("attempts", f"generation-{generation}", "metrics.tsv")
|
| 426 |
+
if tuple(metrics_path.parts[-3:]) != expected_suffix:
|
| 427 |
+
raise ValueError("PICMEM_METRICS_PATH is not generation-specific")
|
| 428 |
+
if config.metrics_path is None or metrics_path != Path(config.metrics_path).expanduser().resolve():
|
| 429 |
+
raise ValueError("PICMEM_METRICS_PATH differs from TrainConfig.metrics_path")
|
| 430 |
+
contract = cls(
|
| 431 |
+
launch_kind=launch_kind,
|
| 432 |
+
experiment=experiment,
|
| 433 |
+
job=_identifier(os.environ.get("PICMEM_CHECKPOINT_JOB"), "job"),
|
| 434 |
+
run_id=_identifier(os.environ.get("PICMEM_CHECKPOINT_RUN_ID"), "run_id"),
|
| 435 |
+
generation=generation,
|
| 436 |
+
gpu_class=gpu_class,
|
| 437 |
+
checkpoint_root=checkpoint_root,
|
| 438 |
+
interface_commit=_commit(os.environ.get("PICMEM_INTERFACE_COMMIT"), "PICMEM_INTERFACE_COMMIT"),
|
| 439 |
+
code_commit=_commit(os.environ.get("PICMEM_CODE_COMMIT"), "PICMEM_CODE_COMMIT"),
|
| 440 |
+
config_sha256=str(_sha256(os.environ.get("PICMEM_CONFIG_SHA256"), "PICMEM_CONFIG_SHA256")),
|
| 441 |
+
dataset_sha256=str(_sha256(os.environ.get("PICMEM_DATASET_SHA256"), "PICMEM_DATASET_SHA256")),
|
| 442 |
+
cohort_sha256=str(_sha256(os.environ.get("PICMEM_COHORT_SHA256"), "PICMEM_COHORT_SHA256")),
|
| 443 |
+
sidecar_sha256=str(_sha256(os.environ.get("PICMEM_SIDECAR_SHA256"), "PICMEM_SIDECAR_SHA256")),
|
| 444 |
+
feature_sha256=str(_sha256(os.environ.get("PICMEM_FEATURE_SHA256"), "PICMEM_FEATURE_SHA256")),
|
| 445 |
+
source_metadata_sha256=str(
|
| 446 |
+
_sha256(os.environ.get("PICMEM_SOURCE_METADATA_SHA256"), "PICMEM_SOURCE_METADATA_SHA256")
|
| 447 |
+
),
|
| 448 |
+
source_digest_sha256=str(
|
| 449 |
+
_sha256(os.environ.get("PICMEM_SOURCE_DIGEST_SHA256"), "PICMEM_SOURCE_DIGEST_SHA256")
|
| 450 |
+
),
|
| 451 |
+
artifact_identity_sha256=str(
|
| 452 |
+
_sha256(os.environ.get("PICMEM_ARTIFACT_IDENTITY_SHA256"), "PICMEM_ARTIFACT_IDENTITY_SHA256")
|
| 453 |
+
),
|
| 454 |
+
artifact_hashes_sha256=str(
|
| 455 |
+
_sha256(os.environ.get("PICMEM_ARTIFACT_HASHES_SHA256"), "PICMEM_ARTIFACT_HASHES_SHA256")
|
| 456 |
+
),
|
| 457 |
+
replacement_manifest_sha256=str(
|
| 458 |
+
_sha256(
|
| 459 |
+
os.environ.get("PICMEM_REPLACEMENT_MANIFEST_SHA256"),
|
| 460 |
+
"PICMEM_REPLACEMENT_MANIFEST_SHA256",
|
| 461 |
+
)
|
| 462 |
+
),
|
| 463 |
+
best_visible_manifest_sha256=str(
|
| 464 |
+
_sha256(
|
| 465 |
+
os.environ.get("PICMEM_BEST_VISIBLE_MANIFEST_SHA256"),
|
| 466 |
+
"PICMEM_BEST_VISIBLE_MANIFEST_SHA256",
|
| 467 |
+
)
|
| 468 |
+
),
|
| 469 |
+
sample_order_path=_bound_regular_file(
|
| 470 |
+
os.environ.get("PICMEM_SAMPLE_ORDER_MANIFEST"),
|
| 471 |
+
"PICMEM_SAMPLE_ORDER_MANIFEST",
|
| 472 |
+
),
|
| 473 |
+
sample_order_manifest_sha256=str(
|
| 474 |
+
_sha256(
|
| 475 |
+
os.environ.get("PICMEM_SAMPLE_ORDER_MANIFEST_SHA256"),
|
| 476 |
+
"PICMEM_SAMPLE_ORDER_MANIFEST_SHA256",
|
| 477 |
+
)
|
| 478 |
+
),
|
| 479 |
+
sample_order_sha256=str(
|
| 480 |
+
_sha256(os.environ.get("PICMEM_SAMPLE_ORDER_SHA256"), "PICMEM_SAMPLE_ORDER_SHA256")
|
| 481 |
+
),
|
| 482 |
+
training_manifest_kind=_identifier(
|
| 483 |
+
os.environ.get("PICMEM_TRAINING_MANIFEST_KIND"),
|
| 484 |
+
"PICMEM_TRAINING_MANIFEST_KIND",
|
| 485 |
+
),
|
| 486 |
+
training_manifest_sha256=str(
|
| 487 |
+
_sha256(_training_manifest_sha256_from_environment(), "training manifest SHA-256")
|
| 488 |
+
),
|
| 489 |
+
overlay_sha256=str(_sha256(os.environ.get("PICMEM_OVERLAY_SHA256"), "PICMEM_OVERLAY_SHA256")),
|
| 490 |
+
runtime_profile_id=_identifier(
|
| 491 |
+
os.environ.get("PICMEM_RUNTIME_PROFILE_ID"),
|
| 492 |
+
"PICMEM_RUNTIME_PROFILE_ID",
|
| 493 |
+
),
|
| 494 |
+
runtime_candidate_id=_identifier(
|
| 495 |
+
os.environ.get("PICMEM_RUNTIME_CANDIDATE_ID"),
|
| 496 |
+
"PICMEM_RUNTIME_CANDIDATE_ID",
|
| 497 |
+
),
|
| 498 |
+
runtime_policy_sha256=str(
|
| 499 |
+
_sha256(os.environ.get("PICMEM_RUNTIME_POLICY_SHA256"), "PICMEM_RUNTIME_POLICY_SHA256")
|
| 500 |
+
),
|
| 501 |
+
runtime_plan_sha256=str(
|
| 502 |
+
_sha256(os.environ.get("PICMEM_RUNTIME_PLAN_SHA256"), "PICMEM_RUNTIME_PLAN_SHA256")
|
| 503 |
+
),
|
| 504 |
+
runtime_matrix_sha256=str(
|
| 505 |
+
_sha256(os.environ.get("PICMEM_RUNTIME_MATRIX_SHA256"), "PICMEM_RUNTIME_MATRIX_SHA256")
|
| 506 |
+
),
|
| 507 |
+
runtime_calibration_sha256=str(
|
| 508 |
+
_sha256(
|
| 509 |
+
os.environ.get("PICMEM_RUNTIME_CALIBRATION_SHA256"),
|
| 510 |
+
"PICMEM_RUNTIME_CALIBRATION_SHA256",
|
| 511 |
+
)
|
| 512 |
+
),
|
| 513 |
+
optimizer_sha256=str(_sha256(os.environ.get("PICMEM_OPTIMIZER_SHA256"), "PICMEM_OPTIMIZER_SHA256")),
|
| 514 |
+
learning_rate_schedule_sha256=str(
|
| 515 |
+
_sha256(os.environ.get("PICMEM_LR_SCHEDULE_SHA256"), "PICMEM_LR_SCHEDULE_SHA256")
|
| 516 |
+
),
|
| 517 |
+
global_batch_size=global_batch_size,
|
| 518 |
+
micro_batch_per_device=_natural(
|
| 519 |
+
os.environ.get("MICRO_BATCH_PER_DEVICE", ""),
|
| 520 |
+
"MICRO_BATCH_PER_DEVICE",
|
| 521 |
+
),
|
| 522 |
+
gradient_accumulation_steps=_natural(
|
| 523 |
+
os.environ.get("GRADIENT_ACCUMULATION_STEPS", ""),
|
| 524 |
+
"GRADIENT_ACCUMULATION_STEPS",
|
| 525 |
+
),
|
| 526 |
+
dataloader_workers=_natural(os.environ.get("NUM_WORKERS", ""), "NUM_WORKERS"),
|
| 527 |
+
prefetch_factor=_natural(os.environ.get("PREFETCH_FACTOR", ""), "PREFETCH_FACTOR"),
|
| 528 |
+
xla_preallocate=_runtime_true(
|
| 529 |
+
os.environ.get("XLA_PYTHON_CLIENT_PREALLOCATE"),
|
| 530 |
+
"XLA_PYTHON_CLIENT_PREALLOCATE",
|
| 531 |
+
),
|
| 532 |
+
xla_memory_fraction=_runtime_fraction(
|
| 533 |
+
os.environ.get("XLA_PYTHON_CLIENT_MEM_FRACTION"),
|
| 534 |
+
"XLA_PYTHON_CLIENT_MEM_FRACTION",
|
| 535 |
+
),
|
| 536 |
+
nccl_collective_channel_cap=_natural(
|
| 537 |
+
os.environ.get("NCCL_MAX_NCHANNELS", ""),
|
| 538 |
+
"NCCL_MAX_NCHANNELS",
|
| 539 |
+
),
|
| 540 |
+
nccl_p2p_channel_cap=_natural(
|
| 541 |
+
os.environ.get("PICMEM_XLA_P2P_MAX_NCHANNELS", ""),
|
| 542 |
+
"PICMEM_XLA_P2P_MAX_NCHANNELS",
|
| 543 |
+
),
|
| 544 |
+
xla_flags=os.environ.get("XLA_FLAGS", ""),
|
| 545 |
+
runtime_checkpoint_interval=_natural(os.environ.get("SAVE_INTERVAL", ""), "SAVE_INTERVAL"),
|
| 546 |
+
parent_metadata_sha256=parent,
|
| 547 |
+
continuity_mode=mode,
|
| 548 |
+
continuity_request_id=continuity_request_id,
|
| 549 |
+
watch_state_dir=watch_state_dir,
|
| 550 |
+
continuity_path=continuity_path,
|
| 551 |
+
metrics_path=metrics_path,
|
| 552 |
+
)
|
| 553 |
+
if contract.micro_batch_per_device <= 0 or contract.gradient_accumulation_steps != 1:
|
| 554 |
+
raise ValueError("Phase-A runtime requires positive micro batch and accumulation exactly 1")
|
| 555 |
+
if contract.global_batch_size != int(config.batch_size):
|
| 556 |
+
raise ValueError("runtime global batch differs from TrainConfig.batch_size")
|
| 557 |
+
if 8 * contract.micro_batch_per_device * contract.gradient_accumulation_steps != contract.global_batch_size:
|
| 558 |
+
raise ValueError("runtime batch geometry differs from TrainConfig.batch_size")
|
| 559 |
+
if contract.dataloader_workers != int(config.num_workers):
|
| 560 |
+
raise ValueError("runtime dataloader workers differ from TrainConfig.num_workers")
|
| 561 |
+
if contract.runtime_checkpoint_interval != int(config.save_interval):
|
| 562 |
+
raise ValueError("runtime checkpoint interval differs from TrainConfig.save_interval")
|
| 563 |
+
if (
|
| 564 |
+
contract.dataloader_workers <= 0
|
| 565 |
+
or contract.prefetch_factor <= 0
|
| 566 |
+
or contract.nccl_collective_channel_cap <= 0
|
| 567 |
+
or contract.nccl_p2p_channel_cap <= 0
|
| 568 |
+
):
|
| 569 |
+
raise ValueError("Phase-A runtime requires positive workers and prefetch")
|
| 570 |
+
expected_p2p_flag = f"--xla_gpu_nccl_p2p_max_nchannels={contract.nccl_p2p_channel_cap}"
|
| 571 |
+
if not contract.xla_flags or any(character in contract.xla_flags for character in "\t\r\n"):
|
| 572 |
+
raise ValueError("runtime XLA_FLAGS must be non-empty single-line text")
|
| 573 |
+
if contract.xla_flags.split().count(expected_p2p_flag) != 1:
|
| 574 |
+
raise ValueError("runtime XLA_FLAGS does not contain the exact reviewed P2P channel cap")
|
| 575 |
+
zero = "0" * 64
|
| 576 |
+
if launch_kind == "formal":
|
| 577 |
+
if zero in {
|
| 578 |
+
contract.runtime_matrix_sha256,
|
| 579 |
+
contract.runtime_calibration_sha256,
|
| 580 |
+
contract.optimizer_sha256,
|
| 581 |
+
contract.learning_rate_schedule_sha256,
|
| 582 |
+
}:
|
| 583 |
+
raise ValueError("formal runtime lineage cannot use calibration/smoke sentinels")
|
| 584 |
+
if contract.optimizer_sha256 != _repr_sha256(config.optimizer):
|
| 585 |
+
raise ValueError("formal optimizer config differs from PICMEM_OPTIMIZER_SHA256")
|
| 586 |
+
if contract.learning_rate_schedule_sha256 != _repr_sha256(config.lr_schedule):
|
| 587 |
+
raise ValueError("formal LR schedule differs from PICMEM_LR_SCHEDULE_SHA256")
|
| 588 |
+
elif any(
|
| 589 |
+
value != zero
|
| 590 |
+
for value in (
|
| 591 |
+
contract.runtime_matrix_sha256,
|
| 592 |
+
contract.runtime_calibration_sha256,
|
| 593 |
+
contract.optimizer_sha256,
|
| 594 |
+
contract.learning_rate_schedule_sha256,
|
| 595 |
+
)
|
| 596 |
+
):
|
| 597 |
+
raise ValueError("SKU smoke runtime lineage must use explicit zero-hash sentinels")
|
| 598 |
+
_validate_bound_training_manifest(contract, config)
|
| 599 |
+
return contract
|
| 600 |
+
|
| 601 |
+
def stable_json(self, config: Any) -> dict[str, Any]:
|
| 602 |
+
return {
|
| 603 |
+
"schema_version": PHASE_A_CONTRACT_SCHEMA,
|
| 604 |
+
"launch_kind": self.launch_kind,
|
| 605 |
+
"run": {"experiment": self.experiment, "job": self.job, "run_id": self.run_id},
|
| 606 |
+
"topology": {
|
| 607 |
+
"gpu_class": self.gpu_class,
|
| 608 |
+
"world_size": 8,
|
| 609 |
+
"fsdp_devices": 8,
|
| 610 |
+
"global_batch_size": self.global_batch_size,
|
| 611 |
+
"micro_batch_per_device": self.micro_batch_per_device,
|
| 612 |
+
"gradient_accumulation_steps": self.gradient_accumulation_steps,
|
| 613 |
+
},
|
| 614 |
+
"runtime": {
|
| 615 |
+
"profile_id": self.runtime_profile_id,
|
| 616 |
+
"candidate_id": self.runtime_candidate_id,
|
| 617 |
+
"policy_sha256": self.runtime_policy_sha256,
|
| 618 |
+
"plan_sha256": self.runtime_plan_sha256,
|
| 619 |
+
"matrix_sha256": self.runtime_matrix_sha256,
|
| 620 |
+
"calibration_sha256": self.runtime_calibration_sha256,
|
| 621 |
+
"optimizer_sha256": self.optimizer_sha256,
|
| 622 |
+
"learning_rate_schedule_sha256": self.learning_rate_schedule_sha256,
|
| 623 |
+
"dataloader_workers": self.dataloader_workers,
|
| 624 |
+
"prefetch_factor": self.prefetch_factor,
|
| 625 |
+
"xla_preallocate": self.xla_preallocate,
|
| 626 |
+
"xla_memory_fraction": self.xla_memory_fraction,
|
| 627 |
+
"nccl_collective_channel_cap": self.nccl_collective_channel_cap,
|
| 628 |
+
"nccl_p2p_channel_cap": self.nccl_p2p_channel_cap,
|
| 629 |
+
"xla_flags": self.xla_flags,
|
| 630 |
+
"checkpoint_interval": self.runtime_checkpoint_interval,
|
| 631 |
+
},
|
| 632 |
+
"lineage": {
|
| 633 |
+
"interface_commit": self.interface_commit,
|
| 634 |
+
"code_commit": self.code_commit,
|
| 635 |
+
"config_sha256": self.config_sha256,
|
| 636 |
+
"dataset_sha256": self.dataset_sha256,
|
| 637 |
+
"cohort_sha256": self.cohort_sha256,
|
| 638 |
+
"sidecar_sha256": self.sidecar_sha256,
|
| 639 |
+
"feature_sha256": self.feature_sha256,
|
| 640 |
+
"source_metadata_sha256": self.source_metadata_sha256,
|
| 641 |
+
"source_digest_sha256": self.source_digest_sha256,
|
| 642 |
+
"artifact_identity_sha256": self.artifact_identity_sha256,
|
| 643 |
+
"artifact_hashes_sha256": self.artifact_hashes_sha256,
|
| 644 |
+
"replacement_manifest_sha256": self.replacement_manifest_sha256,
|
| 645 |
+
"best_visible_manifest_sha256": self.best_visible_manifest_sha256,
|
| 646 |
+
"sample_order_path": str(self.sample_order_path),
|
| 647 |
+
"sample_order_manifest_sha256": self.sample_order_manifest_sha256,
|
| 648 |
+
"sample_order_sha256": self.sample_order_sha256,
|
| 649 |
+
"training_manifest_kind": self.training_manifest_kind,
|
| 650 |
+
"training_manifest_sha256": self.training_manifest_sha256,
|
| 651 |
+
"overlay_sha256": self.overlay_sha256,
|
| 652 |
+
},
|
| 653 |
+
"optimizer": repr(config.optimizer),
|
| 654 |
+
"lr_schedule": repr(config.lr_schedule),
|
| 655 |
+
"ema_decay": config.ema_decay,
|
| 656 |
+
"seed": int(config.seed),
|
| 657 |
+
"sampler_seed": int(config.sampler_seed if config.sampler_seed is not None else config.seed),
|
| 658 |
+
}
|
| 659 |
+
|
| 660 |
+
def checkpoint_metadata(self, step: int) -> CheckpointMetadata:
|
| 661 |
+
from picmem.ops.cadence import GpuClass
|
| 662 |
+
|
| 663 |
+
return CheckpointMetadata(
|
| 664 |
+
experiment=self.experiment,
|
| 665 |
+
job=self.job,
|
| 666 |
+
run_id=self.run_id,
|
| 667 |
+
step=step,
|
| 668 |
+
generation=self.generation,
|
| 669 |
+
gpu_class=GpuClass(self.gpu_class),
|
| 670 |
+
world_size=8,
|
| 671 |
+
fsdp_devices=8,
|
| 672 |
+
launch_kind=self.launch_kind,
|
| 673 |
+
training_manifest_kind=self.training_manifest_kind,
|
| 674 |
+
training_manifest_sha256=self.training_manifest_sha256,
|
| 675 |
+
runtime_profile_id=self.runtime_profile_id,
|
| 676 |
+
runtime_candidate_id=self.runtime_candidate_id,
|
| 677 |
+
runtime_policy_sha256=self.runtime_policy_sha256,
|
| 678 |
+
runtime_plan_sha256=self.runtime_plan_sha256,
|
| 679 |
+
runtime_matrix_sha256=self.runtime_matrix_sha256,
|
| 680 |
+
runtime_calibration_sha256=self.runtime_calibration_sha256,
|
| 681 |
+
optimizer_sha256=self.optimizer_sha256,
|
| 682 |
+
learning_rate_schedule_sha256=self.learning_rate_schedule_sha256,
|
| 683 |
+
global_batch_size=self.global_batch_size,
|
| 684 |
+
micro_batch_per_device=self.micro_batch_per_device,
|
| 685 |
+
gradient_accumulation_steps=self.gradient_accumulation_steps,
|
| 686 |
+
dataloader_workers=self.dataloader_workers,
|
| 687 |
+
prefetch_factor=self.prefetch_factor,
|
| 688 |
+
xla_preallocate=self.xla_preallocate,
|
| 689 |
+
xla_memory_fraction=self.xla_memory_fraction,
|
| 690 |
+
nccl_collective_channel_cap=self.nccl_collective_channel_cap,
|
| 691 |
+
nccl_p2p_channel_cap=self.nccl_p2p_channel_cap,
|
| 692 |
+
xla_flags=self.xla_flags,
|
| 693 |
+
checkpoint_interval=self.runtime_checkpoint_interval,
|
| 694 |
+
interface_commit=self.interface_commit,
|
| 695 |
+
code_commit=self.code_commit,
|
| 696 |
+
config_sha256=self.config_sha256,
|
| 697 |
+
dataset_sha256=self.dataset_sha256,
|
| 698 |
+
cohort_sha256=self.cohort_sha256,
|
| 699 |
+
sidecar_sha256=self.sidecar_sha256,
|
| 700 |
+
feature_sha256=self.feature_sha256,
|
| 701 |
+
source_metadata_sha256=self.source_metadata_sha256,
|
| 702 |
+
source_digest_sha256=self.source_digest_sha256,
|
| 703 |
+
artifact_identity_sha256=self.artifact_identity_sha256,
|
| 704 |
+
artifact_hashes_sha256=self.artifact_hashes_sha256,
|
| 705 |
+
replacement_manifest_sha256=self.replacement_manifest_sha256,
|
| 706 |
+
best_visible_manifest_sha256=self.best_visible_manifest_sha256,
|
| 707 |
+
sample_order_path=str(self.sample_order_path),
|
| 708 |
+
sample_order_manifest_sha256=self.sample_order_manifest_sha256,
|
| 709 |
+
sample_order_sha256=self.sample_order_sha256,
|
| 710 |
+
overlay_sha256=self.overlay_sha256,
|
| 711 |
+
parent_metadata_sha256=self.parent_metadata_sha256,
|
| 712 |
+
)
|
| 713 |
+
|
| 714 |
+
|
| 715 |
+
def _training_manifest_environment() -> tuple[str, str, str]:
|
| 716 |
+
kind = os.environ.get("PICMEM_TRAINING_MANIFEST_KIND", "")
|
| 717 |
+
expected = {
|
| 718 |
+
"arm_v3": ("PICMEM_ARM_MANIFEST", "PICMEM_ARM_MANIFEST_SHA256", "formal"),
|
| 719 |
+
"sku_calibration_v1": (
|
| 720 |
+
"PICMEM_CALIBRATION_MANIFEST",
|
| 721 |
+
"PICMEM_CALIBRATION_MANIFEST_SHA256",
|
| 722 |
+
"sku_smoke",
|
| 723 |
+
),
|
| 724 |
+
}
|
| 725 |
+
if kind not in expected:
|
| 726 |
+
raise ValueError("PICMEM_TRAINING_MANIFEST_KIND must be arm_v3 or sku_calibration_v1")
|
| 727 |
+
path_name, sha_name, launch_kind = expected[kind]
|
| 728 |
+
if os.environ.get("PICMEM_PHASE_A_LAUNCH_KIND") != launch_kind:
|
| 729 |
+
raise ValueError("training manifest kind disagrees with PICMEM_PHASE_A_LAUNCH_KIND")
|
| 730 |
+
forbidden = (
|
| 731 |
+
("PICMEM_CALIBRATION_MANIFEST", "PICMEM_CALIBRATION_MANIFEST_SHA256")
|
| 732 |
+
if kind == "arm_v3"
|
| 733 |
+
else ("PICMEM_ARM_MANIFEST", "PICMEM_ARM_MANIFEST_SHA256")
|
| 734 |
+
)
|
| 735 |
+
if any(os.environ.get(name) for name in forbidden):
|
| 736 |
+
raise ValueError("process environment ambiguously carries both training manifest kinds")
|
| 737 |
+
return kind, path_name, sha_name
|
| 738 |
+
|
| 739 |
+
|
| 740 |
+
def _training_manifest_sha256_from_environment() -> str:
|
| 741 |
+
_, _, sha_name = _training_manifest_environment()
|
| 742 |
+
return os.environ.get(sha_name, "")
|
| 743 |
+
|
| 744 |
+
|
| 745 |
+
def _load_bound_training_manifest() -> ArmManifest | SkuCalibrationManifest:
|
| 746 |
+
kind, path_name, sha_name = _training_manifest_environment()
|
| 747 |
+
raw_path = os.environ.get(path_name, "")
|
| 748 |
+
unresolved = Path(raw_path).expanduser()
|
| 749 |
+
if not raw_path or unresolved.is_symlink() or not unresolved.is_file():
|
| 750 |
+
raise ValueError(f"{path_name} must name a real regular file")
|
| 751 |
+
manifest_path = unresolved.resolve()
|
| 752 |
+
expected_sha256 = str(_sha256(os.environ.get(sha_name), sha_name))
|
| 753 |
+
if kind == "sku_calibration_v1":
|
| 754 |
+
try:
|
| 755 |
+
return load_calibration_manifest(
|
| 756 |
+
manifest_path,
|
| 757 |
+
expected_sha256=expected_sha256,
|
| 758 |
+
).manifest
|
| 759 |
+
except CalibrationManifestError as exc:
|
| 760 |
+
raise ValueError(f"{path_name} is not a trusted SKU calibration manifest") from exc
|
| 761 |
+
raw = manifest_path.read_bytes()
|
| 762 |
+
if hashlib.sha256(raw).hexdigest() != expected_sha256:
|
| 763 |
+
raise ValueError(f"{path_name} content differs from {sha_name}")
|
| 764 |
+
try:
|
| 765 |
+
value = json.loads(raw, object_pairs_hook=_pairs_no_duplicates)
|
| 766 |
+
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
|
| 767 |
+
raise ValueError(f"{path_name} is not valid duplicate-free JSON") from exc
|
| 768 |
+
return ArmManifest.from_mapping(value)
|
| 769 |
+
|
| 770 |
+
|
| 771 |
+
def _resume_lineage() -> str:
|
| 772 |
+
resume_lineage = os.environ.get("PICMEM_RESUME_LINEAGE", "")
|
| 773 |
+
if not resume_lineage:
|
| 774 |
+
raise ValueError("PICMEM_RESUME_LINEAGE must be non-empty")
|
| 775 |
+
normalized = PurePosixPath(resume_lineage)
|
| 776 |
+
if (
|
| 777 |
+
normalized.is_absolute()
|
| 778 |
+
or not normalized.parts
|
| 779 |
+
or any(part in {"", ".", ".."} for part in normalized.parts)
|
| 780 |
+
or normalized.as_posix() != resume_lineage
|
| 781 |
+
):
|
| 782 |
+
raise ValueError("PICMEM_RESUME_LINEAGE must be a normalized safe relative path")
|
| 783 |
+
return resume_lineage
|
| 784 |
+
|
| 785 |
+
|
| 786 |
+
def _factor_environment() -> dict[str, str | None]:
|
| 787 |
+
return {
|
| 788 |
+
"selection_mode": os.environ.get("PICMEM_PHASE_A_SELECTION_MODE"),
|
| 789 |
+
"metadata_mode": os.environ.get("PICMEM_PHASE_A_METADATA_MODE"),
|
| 790 |
+
"reader_mode": os.environ.get("PICMEM_PHASE_A_READER_MODE"),
|
| 791 |
+
"manager_mode": os.environ.get("PICMEM_PHASE_A_MANAGER_MODE"),
|
| 792 |
+
}
|
| 793 |
+
|
| 794 |
+
|
| 795 |
+
def _validate_bound_arm(contract: PhaseAContract, config: Any, arm: ArmManifest | None = None) -> None:
|
| 796 |
+
"""Re-validate the exact formal arm inside the training process trust boundary."""
|
| 797 |
+
|
| 798 |
+
loaded = _load_bound_training_manifest() if arm is None else arm
|
| 799 |
+
if not isinstance(loaded, ArmManifest):
|
| 800 |
+
raise ValueError("formal arm validation received a non-arm training manifest")
|
| 801 |
+
arm = loaded
|
| 802 |
+
if contract.training_manifest_kind != "arm_v3":
|
| 803 |
+
raise ValueError("formal checkpoint contract does not bind arm_v3")
|
| 804 |
+
if contract.training_manifest_sha256 != os.environ.get("PICMEM_ARM_MANIFEST_SHA256"):
|
| 805 |
+
raise ValueError("checkpoint contract and process arm-manifest hashes differ")
|
| 806 |
+
process_source_digest_sha256 = str(
|
| 807 |
+
_sha256(
|
| 808 |
+
os.environ.get("PICMEM_SOURCE_DIGEST_SHA256"),
|
| 809 |
+
"PICMEM_SOURCE_DIGEST_SHA256",
|
| 810 |
+
)
|
| 811 |
+
)
|
| 812 |
+
expected_source_digest_sha256 = str(
|
| 813 |
+
_sha256(
|
| 814 |
+
RUN084_BUILD_C_LINEAGE["source_digest_manifest_sha256"],
|
| 815 |
+
"RUN084_BUILD_C_LINEAGE.source_digest_manifest_sha256",
|
| 816 |
+
)
|
| 817 |
+
)
|
| 818 |
+
if contract.source_digest_sha256 != process_source_digest_sha256:
|
| 819 |
+
raise ValueError("checkpoint contract and process source-digest hashes differ")
|
| 820 |
+
if process_source_digest_sha256 != expected_source_digest_sha256:
|
| 821 |
+
raise ValueError("formal training requires the exact verified Run084-v2 build_c source digest")
|
| 822 |
+
resume_lineage = _resume_lineage()
|
| 823 |
+
|
| 824 |
+
factors = _factor_environment()
|
| 825 |
+
expected = {
|
| 826 |
+
"arm_id": contract.job,
|
| 827 |
+
"parent_commit": contract.code_commit,
|
| 828 |
+
"parent_tree": _commit(os.environ.get("PICMEM_CODE_TREE"), "PICMEM_CODE_TREE"),
|
| 829 |
+
"host_overlay_sha256": contract.overlay_sha256,
|
| 830 |
+
"dataset_sha256": contract.dataset_sha256,
|
| 831 |
+
"sidecar_sha256": contract.sidecar_sha256,
|
| 832 |
+
"feature_sha256": contract.feature_sha256,
|
| 833 |
+
"source_metadata_sha256": contract.source_metadata_sha256,
|
| 834 |
+
"artifact_identity_sha256": contract.artifact_identity_sha256,
|
| 835 |
+
"artifact_hashes_sha256": contract.artifact_hashes_sha256,
|
| 836 |
+
"replacement_manifest_sha256": contract.replacement_manifest_sha256,
|
| 837 |
+
"best_visible_manifest_sha256": contract.best_visible_manifest_sha256,
|
| 838 |
+
"sample_order_manifest_sha256": contract.sample_order_manifest_sha256,
|
| 839 |
+
"sample_order_sha256": contract.sample_order_sha256,
|
| 840 |
+
"evaluation_cohort_sha256": contract.cohort_sha256,
|
| 841 |
+
"resume_lineage": resume_lineage,
|
| 842 |
+
"global_batch": contract.global_batch_size,
|
| 843 |
+
"seed": _sampler_natural(config.seed, "config.seed"),
|
| 844 |
+
"checkpoint_interval": _sampler_natural(config.save_interval, "config.save_interval"),
|
| 845 |
+
}
|
| 846 |
+
drift = [name for name, expected_value in expected.items() if getattr(arm, name) != expected_value]
|
| 847 |
+
drift.extend(name for name, expected_value in factors.items() if getattr(arm, name).value != expected_value)
|
| 848 |
+
if _gpu_class_from_sku(arm.gpu_sku) != contract.gpu_class:
|
| 849 |
+
drift.append("gpu_sku")
|
| 850 |
+
sampler_seed = config.sampler_seed if config.sampler_seed is not None else config.seed
|
| 851 |
+
if _sampler_natural(sampler_seed, "config.sampler_seed") != arm.seed:
|
| 852 |
+
drift.append("sampler_seed")
|
| 853 |
+
if drift:
|
| 854 |
+
raise ValueError(f"training-process ArmManifest immutable lineage drift: {sorted(set(drift))}")
|
| 855 |
+
|
| 856 |
+
|
| 857 |
+
def _validate_bound_calibration(
|
| 858 |
+
contract: PhaseAContract,
|
| 859 |
+
config: Any,
|
| 860 |
+
calibration: SkuCalibrationManifest | None = None,
|
| 861 |
+
) -> None:
|
| 862 |
+
loaded = _load_bound_training_manifest() if calibration is None else calibration
|
| 863 |
+
if not isinstance(loaded, SkuCalibrationManifest):
|
| 864 |
+
raise ValueError("SKU calibration validation received a formal ArmManifest")
|
| 865 |
+
calibration = loaded
|
| 866 |
+
if contract.training_manifest_kind != "sku_calibration_v1":
|
| 867 |
+
raise ValueError("SKU calibration checkpoint contract does not bind sku_calibration_v1")
|
| 868 |
+
if contract.training_manifest_sha256 != os.environ.get("PICMEM_CALIBRATION_MANIFEST_SHA256"):
|
| 869 |
+
raise ValueError("checkpoint contract and process calibration-manifest hashes differ")
|
| 870 |
+
|
| 871 |
+
lineage = calibration.lineage
|
| 872 |
+
sample_order = calibration.sample_order
|
| 873 |
+
runtime = calibration.runtime
|
| 874 |
+
factors = _factor_environment()
|
| 875 |
+
expected_lineage = {
|
| 876 |
+
"parent_commit": contract.code_commit,
|
| 877 |
+
"parent_tree": _commit(os.environ.get("PICMEM_CODE_TREE"), "PICMEM_CODE_TREE"),
|
| 878 |
+
"host_overlay_sha256": contract.overlay_sha256,
|
| 879 |
+
"artifact_schema_version": os.environ.get("PICMEM_ARTIFACT_SCHEMA_VERSION"),
|
| 880 |
+
"dataset_version": os.environ.get("PICMEM_DATASET_VERSION"),
|
| 881 |
+
"artifact_hashes_sha256": contract.artifact_hashes_sha256,
|
| 882 |
+
"dataset_sha256": contract.dataset_sha256,
|
| 883 |
+
"sidecar_sha256": contract.sidecar_sha256,
|
| 884 |
+
"feature_sha256": contract.feature_sha256,
|
| 885 |
+
"source_metadata_sha256": contract.source_metadata_sha256,
|
| 886 |
+
"source_digest_manifest_sha256": contract.source_digest_sha256,
|
| 887 |
+
"source_digest_tree_sha256": os.environ.get("PICMEM_SOURCE_DIGEST_TREE_SHA256"),
|
| 888 |
+
"source_digest_rows": _natural(
|
| 889 |
+
os.environ.get("PICMEM_SOURCE_DIGEST_ROWS", ""),
|
| 890 |
+
"PICMEM_SOURCE_DIGEST_ROWS",
|
| 891 |
+
),
|
| 892 |
+
"source_digest_bytes": _natural(
|
| 893 |
+
os.environ.get("PICMEM_SOURCE_DIGEST_BYTES", ""),
|
| 894 |
+
"PICMEM_SOURCE_DIGEST_BYTES",
|
| 895 |
+
),
|
| 896 |
+
"artifact_identity_sha256": contract.artifact_identity_sha256,
|
| 897 |
+
"replacement_manifest_sha256": contract.replacement_manifest_sha256,
|
| 898 |
+
"best_visible_manifest_sha256": contract.best_visible_manifest_sha256,
|
| 899 |
+
"evaluation_cohort_sha256": contract.cohort_sha256,
|
| 900 |
+
}
|
| 901 |
+
expected_order = {
|
| 902 |
+
"dataset_sha256": contract.dataset_sha256,
|
| 903 |
+
"seed": _sampler_natural(
|
| 904 |
+
config.sampler_seed if config.sampler_seed is not None else config.seed,
|
| 905 |
+
"config.sampler_seed",
|
| 906 |
+
),
|
| 907 |
+
"global_batch": contract.global_batch_size,
|
| 908 |
+
"manifest_path": str(contract.sample_order_path),
|
| 909 |
+
"manifest_sha256": contract.sample_order_manifest_sha256,
|
| 910 |
+
"sample_order_sha256": contract.sample_order_sha256,
|
| 911 |
+
}
|
| 912 |
+
expected_runtime = {
|
| 913 |
+
"gpu_count": 8,
|
| 914 |
+
"profile_id": contract.runtime_profile_id,
|
| 915 |
+
"candidate_id": contract.runtime_candidate_id,
|
| 916 |
+
"policy_sha256": contract.runtime_policy_sha256,
|
| 917 |
+
"plan_sha256": contract.runtime_plan_sha256,
|
| 918 |
+
"world_size": 8,
|
| 919 |
+
"global_batch": contract.global_batch_size,
|
| 920 |
+
"micro_batch_per_device": contract.micro_batch_per_device,
|
| 921 |
+
"gradient_accumulation_steps": contract.gradient_accumulation_steps,
|
| 922 |
+
"dataloader_workers": contract.dataloader_workers,
|
| 923 |
+
"prefetch_factor": contract.prefetch_factor,
|
| 924 |
+
"xla_preallocate": contract.xla_preallocate,
|
| 925 |
+
"xla_memory_fraction": contract.xla_memory_fraction,
|
| 926 |
+
"nccl_collective_channel_cap": contract.nccl_collective_channel_cap,
|
| 927 |
+
"nccl_p2p_channel_cap": contract.nccl_p2p_channel_cap,
|
| 928 |
+
"checkpoint_interval": contract.runtime_checkpoint_interval,
|
| 929 |
+
"train_steps": _sampler_natural(config.num_train_steps, "config.num_train_steps"),
|
| 930 |
+
}
|
| 931 |
+
expected_p2p = f"--xla_gpu_nccl_p2p_max_nchannels={contract.nccl_p2p_channel_cap}"
|
| 932 |
+
base_flags = tuple(flag for flag in contract.xla_flags.split() if flag != expected_p2p)
|
| 933 |
+
drift = []
|
| 934 |
+
if calibration.calibration_id != contract.job:
|
| 935 |
+
drift.append("calibration_id")
|
| 936 |
+
if calibration.resume_lineage != _resume_lineage():
|
| 937 |
+
drift.append("resume_lineage")
|
| 938 |
+
drift.extend(
|
| 939 |
+
f"lineage.{name}"
|
| 940 |
+
for name, expected_value in expected_lineage.items()
|
| 941 |
+
if getattr(lineage, name) != expected_value
|
| 942 |
+
)
|
| 943 |
+
drift.extend(
|
| 944 |
+
f"sample_order.{name}"
|
| 945 |
+
for name, expected_value in expected_order.items()
|
| 946 |
+
if getattr(sample_order, name) != expected_value
|
| 947 |
+
)
|
| 948 |
+
drift.extend(
|
| 949 |
+
f"runtime.{name}"
|
| 950 |
+
for name, expected_value in expected_runtime.items()
|
| 951 |
+
if str(getattr(runtime, name)) != str(expected_value)
|
| 952 |
+
)
|
| 953 |
+
if runtime.xla_base_flags != base_flags:
|
| 954 |
+
drift.append("runtime.xla_base_flags")
|
| 955 |
+
if runtime.gpu_class.value != contract.gpu_class:
|
| 956 |
+
drift.append("runtime.gpu_class")
|
| 957 |
+
if _gpu_class_from_sku(runtime.gpu_sku) != contract.gpu_class:
|
| 958 |
+
drift.append("runtime.gpu_sku")
|
| 959 |
+
drift.extend(
|
| 960 |
+
f"factors.{name}"
|
| 961 |
+
for name, expected_value in factors.items()
|
| 962 |
+
if getattr(calibration.factors, name).value != expected_value
|
| 963 |
+
)
|
| 964 |
+
if drift:
|
| 965 |
+
raise ValueError(f"training-process SKU calibration immutable lineage drift: {sorted(set(drift))}")
|
| 966 |
+
|
| 967 |
+
|
| 968 |
+
def _validate_bound_training_manifest(contract: PhaseAContract, config: Any) -> None:
|
| 969 |
+
manifest = _load_bound_training_manifest()
|
| 970 |
+
if contract.launch_kind == "formal":
|
| 971 |
+
if not isinstance(manifest, ArmManifest):
|
| 972 |
+
raise ValueError("formal launch requires an ArmManifest")
|
| 973 |
+
_validate_bound_arm(contract, config, manifest)
|
| 974 |
+
elif contract.launch_kind == "sku_smoke":
|
| 975 |
+
if not isinstance(manifest, SkuCalibrationManifest):
|
| 976 |
+
raise ValueError("SKU smoke requires a SkuCalibrationManifest")
|
| 977 |
+
_validate_bound_calibration(contract, config, manifest)
|
| 978 |
+
else:
|
| 979 |
+
raise ValueError("unsupported Phase-A training manifest launch kind")
|
| 980 |
+
|
| 981 |
+
|
| 982 |
+
def _validate_phase_a_factor_contract(frame_selection: Mapping[str, Any]) -> None:
|
| 983 |
+
"""Require the resolved YAML, process environment, and arm to name one treatment."""
|
| 984 |
+
|
| 985 |
+
if frame_selection.get("require_explicit_factors") is not True:
|
| 986 |
+
raise ValueError("formal Phase-A YAML must require explicit factors")
|
| 987 |
+
manifest = _load_bound_training_manifest()
|
| 988 |
+
factor_source = manifest if isinstance(manifest, ArmManifest) else manifest.factors
|
| 989 |
+
names = {
|
| 990 |
+
"selection_mode": "PICMEM_PHASE_A_SELECTION_MODE",
|
| 991 |
+
"metadata_mode": "PICMEM_PHASE_A_METADATA_MODE",
|
| 992 |
+
"reader_mode": "PICMEM_PHASE_A_READER_MODE",
|
| 993 |
+
"manager_mode": "PICMEM_PHASE_A_MANAGER_MODE",
|
| 994 |
+
}
|
| 995 |
+
drift = []
|
| 996 |
+
for name, environment_name in names.items():
|
| 997 |
+
yaml_value = frame_selection.get(name)
|
| 998 |
+
environment_value = os.environ.get(environment_name)
|
| 999 |
+
manifest_value = getattr(factor_source, name).value
|
| 1000 |
+
if not isinstance(yaml_value, str) or not yaml_value:
|
| 1001 |
+
drift.append(f"yaml.{name}")
|
| 1002 |
+
if not isinstance(environment_value, str) or not environment_value:
|
| 1003 |
+
drift.append(f"environment.{name}")
|
| 1004 |
+
if yaml_value != environment_value or yaml_value != manifest_value:
|
| 1005 |
+
drift.append(name)
|
| 1006 |
+
if drift:
|
| 1007 |
+
raise ValueError(f"Phase-A manifest/environment/YAML factor drift: {sorted(set(drift))}")
|
| 1008 |
+
|
| 1009 |
+
|
| 1010 |
+
class PhaseASampler(Protocol):
|
| 1011 |
+
"""Minimal checkpointable sampler interface consumed by the host runtime."""
|
| 1012 |
+
|
| 1013 |
+
seed: int
|
| 1014 |
+
batch_size: int
|
| 1015 |
+
num_batches: int
|
| 1016 |
+
epoch: int
|
| 1017 |
+
batch_cursor: int
|
| 1018 |
+
|
| 1019 |
+
def state_dict(self) -> dict[str, Any]: ...
|
| 1020 |
+
|
| 1021 |
+
def load_state_dict(self, state: Mapping[str, Any]) -> None: ...
|
| 1022 |
+
|
| 1023 |
+
def mark_batch_consumed(self) -> None: ...
|
| 1024 |
+
|
| 1025 |
+
def next_batch_sample_ids(self) -> tuple[str, ...]: ...
|
| 1026 |
+
|
| 1027 |
+
def __iter__(self) -> Iterator[int]: ...
|
| 1028 |
+
|
| 1029 |
+
def __len__(self) -> int: ...
|
| 1030 |
+
|
| 1031 |
+
|
| 1032 |
+
class PhaseASmokeRandomSampler(torch.utils.data.Sampler[int]):
|
| 1033 |
+
"""Synthetic smoke-only sampler; formal loading never constructs this class."""
|
| 1034 |
+
|
| 1035 |
+
def __init__(
|
| 1036 |
+
self,
|
| 1037 |
+
dataset_size: int,
|
| 1038 |
+
*,
|
| 1039 |
+
batch_size: int,
|
| 1040 |
+
seed: int,
|
| 1041 |
+
epoch: int = 0,
|
| 1042 |
+
batch_cursor: int = 0,
|
| 1043 |
+
) -> None:
|
| 1044 |
+
if dataset_size < batch_size or batch_size <= 0:
|
| 1045 |
+
raise ValueError("checkpointable sampler requires at least one positive full batch")
|
| 1046 |
+
if seed < 0 or epoch < 0 or batch_cursor < 0:
|
| 1047 |
+
raise ValueError("checkpointable sampler seed/position must be non-negative")
|
| 1048 |
+
if seed > np.iinfo(np.uint64).max:
|
| 1049 |
+
raise ValueError("checkpointable sampler seed must fit in uint64")
|
| 1050 |
+
self.dataset_size = int(dataset_size)
|
| 1051 |
+
self.batch_size = int(batch_size)
|
| 1052 |
+
self.seed = int(seed)
|
| 1053 |
+
self.num_batches = self.dataset_size // self.batch_size
|
| 1054 |
+
self.epoch = int(epoch)
|
| 1055 |
+
self.batch_cursor = 0
|
| 1056 |
+
self.set_position(epoch=epoch, batch_cursor=batch_cursor)
|
| 1057 |
+
|
| 1058 |
+
def _order(self, epoch: int) -> np.ndarray:
|
| 1059 |
+
sequence = np.random.SeedSequence([self.seed, int(epoch)])
|
| 1060 |
+
rng = np.random.default_rng(sequence)
|
| 1061 |
+
return rng.permutation(self.dataset_size)[: self.num_batches * self.batch_size]
|
| 1062 |
+
|
| 1063 |
+
def next_batch_sample_ids(self) -> tuple[str, ...]:
|
| 1064 |
+
start = self.batch_cursor * self.batch_size
|
| 1065 |
+
end = start + self.batch_size
|
| 1066 |
+
return tuple(
|
| 1067 |
+
hashlib.sha256(f"picmem-smoke-row:{int(value)}".encode("ascii")).hexdigest()
|
| 1068 |
+
for value in self._order(self.epoch)[start:end]
|
| 1069 |
+
)
|
| 1070 |
+
|
| 1071 |
+
def state_dict(self) -> dict[str, Any]:
|
| 1072 |
+
return {
|
| 1073 |
+
"schema_version": SMOKE_SAMPLER_SCHEMA,
|
| 1074 |
+
"subset_manifest_sha256": SMOKE_SUBSET_SHA256,
|
| 1075 |
+
"seed": self.seed,
|
| 1076 |
+
"batch_size": self.batch_size,
|
| 1077 |
+
"num_batches": self.num_batches,
|
| 1078 |
+
"epoch": self.epoch,
|
| 1079 |
+
"batch_cursor": self.batch_cursor,
|
| 1080 |
+
"next_sample_ids": list(self.next_batch_sample_ids()),
|
| 1081 |
+
}
|
| 1082 |
+
|
| 1083 |
+
def load_state_dict(self, state: Mapping[str, Any]) -> None:
|
| 1084 |
+
expected = {
|
| 1085 |
+
"schema_version",
|
| 1086 |
+
"subset_manifest_sha256",
|
| 1087 |
+
"seed",
|
| 1088 |
+
"batch_size",
|
| 1089 |
+
"num_batches",
|
| 1090 |
+
"epoch",
|
| 1091 |
+
"batch_cursor",
|
| 1092 |
+
"next_sample_ids",
|
| 1093 |
+
}
|
| 1094 |
+
if set(state) != expected:
|
| 1095 |
+
raise ValueError("Phase-A smoke sampler state fields mismatch")
|
| 1096 |
+
immutable = (
|
| 1097 |
+
state["schema_version"],
|
| 1098 |
+
state["subset_manifest_sha256"],
|
| 1099 |
+
state["seed"],
|
| 1100 |
+
state["batch_size"],
|
| 1101 |
+
state["num_batches"],
|
| 1102 |
+
)
|
| 1103 |
+
expected_immutable = (
|
| 1104 |
+
SMOKE_SAMPLER_SCHEMA,
|
| 1105 |
+
SMOKE_SUBSET_SHA256,
|
| 1106 |
+
self.seed,
|
| 1107 |
+
self.batch_size,
|
| 1108 |
+
self.num_batches,
|
| 1109 |
+
)
|
| 1110 |
+
if immutable != expected_immutable:
|
| 1111 |
+
raise ValueError("Phase-A smoke sampler lineage mismatch")
|
| 1112 |
+
self.set_position(epoch=int(state["epoch"]), batch_cursor=int(state["batch_cursor"]))
|
| 1113 |
+
supplied = tuple(
|
| 1114 |
+
_sample_identity(value, "smoke sampler next_sample_ids item") for value in state["next_sample_ids"]
|
| 1115 |
+
)
|
| 1116 |
+
if supplied != self.next_batch_sample_ids():
|
| 1117 |
+
raise ValueError("Phase-A smoke sampler next sample IDs mismatch")
|
| 1118 |
+
|
| 1119 |
+
def set_position(self, *, epoch: int, batch_cursor: int) -> None:
|
| 1120 |
+
if epoch < 0 or not 0 <= batch_cursor < self.num_batches:
|
| 1121 |
+
raise ValueError("Phase-A sampler position is outside the complete-batch epoch")
|
| 1122 |
+
self.epoch = int(epoch)
|
| 1123 |
+
self.batch_cursor = int(batch_cursor)
|
| 1124 |
+
|
| 1125 |
+
def mark_batch_consumed(self) -> None:
|
| 1126 |
+
cursor = self.batch_cursor + 1
|
| 1127 |
+
if cursor == self.num_batches:
|
| 1128 |
+
self.epoch += 1
|
| 1129 |
+
cursor = 0
|
| 1130 |
+
self.batch_cursor = cursor
|
| 1131 |
+
|
| 1132 |
+
def __iter__(self):
|
| 1133 |
+
start = self.batch_cursor * self.batch_size
|
| 1134 |
+
yield from (int(value) for value in self._order(self.epoch)[start:])
|
| 1135 |
+
|
| 1136 |
+
def __len__(self) -> int:
|
| 1137 |
+
return (self.num_batches - self.batch_cursor) * self.batch_size
|
| 1138 |
+
|
| 1139 |
+
|
| 1140 |
+
class PhaseADataLoader:
|
| 1141 |
+
def __init__(
|
| 1142 |
+
self,
|
| 1143 |
+
data_config: Any,
|
| 1144 |
+
data_loader: TorchDataLoader,
|
| 1145 |
+
sampler: PhaseASampler,
|
| 1146 |
+
sample_order: Mapping[str, Any],
|
| 1147 |
+
):
|
| 1148 |
+
self._data_config = data_config
|
| 1149 |
+
self._data_loader = data_loader
|
| 1150 |
+
self.sampler = sampler
|
| 1151 |
+
self._sample_order = dict(sample_order)
|
| 1152 |
+
self.last_batch_task_counts: dict[str, int] = {}
|
| 1153 |
+
|
| 1154 |
+
def data_config(self) -> Any:
|
| 1155 |
+
return self._data_config
|
| 1156 |
+
|
| 1157 |
+
def __iter__(self):
|
| 1158 |
+
for batch in self._data_loader:
|
| 1159 |
+
self._validate_sample_order_state(self.sampler.state_dict())
|
| 1160 |
+
result = HistAugObservation.from_dict(batch), batch["actions"]
|
| 1161 |
+
self.sampler.mark_batch_consumed()
|
| 1162 |
+
yield result
|
| 1163 |
+
|
| 1164 |
+
def sampler_state_dict(self) -> dict[str, Any]:
|
| 1165 |
+
state = self.sampler.state_dict()
|
| 1166 |
+
self._validate_sample_order_state(state)
|
| 1167 |
+
return state
|
| 1168 |
+
|
| 1169 |
+
def load_sampler_state_dict(self, state: Mapping[str, Any]) -> None:
|
| 1170 |
+
self.sampler.load_state_dict(state)
|
| 1171 |
+
self._validate_sample_order_state(self.sampler.state_dict())
|
| 1172 |
+
|
| 1173 |
+
def _validate_sample_order_state(
|
| 1174 |
+
self,
|
| 1175 |
+
state: Mapping[str, Any],
|
| 1176 |
+
*,
|
| 1177 |
+
authoritative_step: int | None = None,
|
| 1178 |
+
) -> None:
|
| 1179 |
+
parsed = _sampler_state(state)
|
| 1180 |
+
step = parsed["epoch"] * parsed["num_batches"] + parsed["batch_cursor"]
|
| 1181 |
+
if authoritative_step is not None and step != authoritative_step:
|
| 1182 |
+
raise ValueError("Run084 sampler cursor differs from the authoritative global step")
|
| 1183 |
+
train_steps = _sampler_natural(self._sample_order.get("train_steps"), "sample_order.train_steps")
|
| 1184 |
+
if step > train_steps:
|
| 1185 |
+
raise ValueError("Run084 sampler advanced beyond the frozen 80k sample order")
|
| 1186 |
+
sample_ids = parsed["next_sample_ids"]
|
| 1187 |
+
if step < train_steps:
|
| 1188 |
+
batch_digests = self._sample_order.get("batch_sha256")
|
| 1189 |
+
if not isinstance(batch_digests, list) or len(batch_digests) != train_steps:
|
| 1190 |
+
raise ValueError("Run084 sample-order batch digest geometry drift")
|
| 1191 |
+
raw = b"".join(bytes.fromhex(identity) for identity in sample_ids)
|
| 1192 |
+
if hashlib.sha256(raw).hexdigest() != batch_digests[step]:
|
| 1193 |
+
raise ValueError("live Run084 sampler batch differs from the frozen sample order")
|
| 1194 |
+
else:
|
| 1195 |
+
probes = self._sample_order.get("probe_batches")
|
| 1196 |
+
expected = probes.get(str(step)) if isinstance(probes, Mapping) else None
|
| 1197 |
+
if expected != sample_ids:
|
| 1198 |
+
raise ValueError("final Run084 sampler cursor differs from the frozen next-batch probe")
|
| 1199 |
+
|
| 1200 |
+
|
| 1201 |
+
def create_phase_a_data_loader(
|
| 1202 |
+
dataset_path: str,
|
| 1203 |
+
data_config: Any,
|
| 1204 |
+
history_config: str,
|
| 1205 |
+
action_horizon: int,
|
| 1206 |
+
batch_size: int,
|
| 1207 |
+
*,
|
| 1208 |
+
sharding: jax.sharding.Sharding,
|
| 1209 |
+
num_workers: int,
|
| 1210 |
+
prefetch_factor: int,
|
| 1211 |
+
seed: int,
|
| 1212 |
+
subset_manifest_sha256: str,
|
| 1213 |
+
sidecar_sha256: str,
|
| 1214 |
+
sample_order_path: str | Path,
|
| 1215 |
+
sample_order_manifest_sha256: str,
|
| 1216 |
+
sample_order_sha256: str,
|
| 1217 |
+
) -> PhaseADataLoader:
|
| 1218 |
+
history = get_history_config(history_config)
|
| 1219 |
+
frame_selection = history.perceptual_memory.get("frame_selection", {})
|
| 1220 |
+
if (
|
| 1221 |
+
history.representation_type != "perceptual"
|
| 1222 |
+
or history.perceptual_memory.type != "frame_sampling"
|
| 1223 |
+
or frame_selection.get("type") != "picmem_phase_a"
|
| 1224 |
+
):
|
| 1225 |
+
raise ValueError("Phase-A full-state loader requires the reviewed picmem_phase_a frame selector")
|
| 1226 |
+
_validate_phase_a_factor_contract(frame_selection)
|
| 1227 |
+
if jax.process_count() != 1:
|
| 1228 |
+
raise ValueError("Phase-A checkpointable data loading supports exactly one JAX process")
|
| 1229 |
+
if isinstance(batch_size, bool) or not isinstance(batch_size, int) or batch_size <= 0 or batch_size % 4:
|
| 1230 |
+
raise ValueError("formal Phase-A loader requires a positive four-task-balanced global batch")
|
| 1231 |
+
from picmem.provenance.frozen_artifact import Run084SubsetIndex
|
| 1232 |
+
from picmem.sampling.run084_sample_order import RUN084_FORMAL_TRAIN_STEPS, load_run084_sample_order
|
| 1233 |
+
from picmem.sampling.run084_sampler import Run084TaskBalancedSampler
|
| 1234 |
+
|
| 1235 |
+
subset = Run084SubsetIndex.load(
|
| 1236 |
+
Path(dataset_path) / "meta" / "picmem_subset_manifest.json",
|
| 1237 |
+
expected_sha256=str(_sha256(subset_manifest_sha256, "subset_manifest_sha256")),
|
| 1238 |
+
)
|
| 1239 |
+
if subset.sidecar_tree_sha256 != _sha256(sidecar_sha256, "sidecar_sha256"):
|
| 1240 |
+
raise ValueError("Run084 subset sidecar tree differs from formal lineage")
|
| 1241 |
+
raw_dataset = RoboMMEDataset(
|
| 1242 |
+
dataset_path=dataset_path,
|
| 1243 |
+
data_config=data_config,
|
| 1244 |
+
history_config=history,
|
| 1245 |
+
action_horizon=action_horizon,
|
| 1246 |
+
)
|
| 1247 |
+
dataset = transform_dataset(raw_dataset, data_config)
|
| 1248 |
+
if len(dataset) != len(subset.records):
|
| 1249 |
+
raise ValueError("host dataset length differs from the frozen Run084 subset")
|
| 1250 |
+
sampler = Run084TaskBalancedSampler(
|
| 1251 |
+
subset,
|
| 1252 |
+
batch_size=batch_size,
|
| 1253 |
+
seed=seed,
|
| 1254 |
+
auto_advance=False,
|
| 1255 |
+
)
|
| 1256 |
+
sample_order = load_run084_sample_order(
|
| 1257 |
+
sample_order_path,
|
| 1258 |
+
expected_manifest_sha256=str(_sha256(sample_order_manifest_sha256, "sample_order_manifest_sha256")),
|
| 1259 |
+
expected_sample_order_sha256=str(_sha256(sample_order_sha256, "sample_order_sha256")),
|
| 1260 |
+
subset=subset,
|
| 1261 |
+
seed=seed,
|
| 1262 |
+
batch_size=batch_size,
|
| 1263 |
+
train_steps=RUN084_FORMAL_TRAIN_STEPS,
|
| 1264 |
+
runtime_sampler=sampler,
|
| 1265 |
+
)
|
| 1266 |
+
loader = TorchDataLoader(
|
| 1267 |
+
dataset,
|
| 1268 |
+
local_batch_size=batch_size,
|
| 1269 |
+
sharding=sharding,
|
| 1270 |
+
shuffle=False,
|
| 1271 |
+
sampler=sampler,
|
| 1272 |
+
num_workers=num_workers,
|
| 1273 |
+
seed=seed,
|
| 1274 |
+
framework="jax",
|
| 1275 |
+
)
|
| 1276 |
+
if num_workers <= 0 or prefetch_factor <= 0:
|
| 1277 |
+
raise ValueError("Phase-A formal loader requires positive workers and prefetch_factor")
|
| 1278 |
+
loader.torch_loader.prefetch_factor = prefetch_factor
|
| 1279 |
+
if loader.torch_loader.prefetch_factor != prefetch_factor:
|
| 1280 |
+
raise ValueError("PyTorch DataLoader did not accept the reviewed prefetch_factor")
|
| 1281 |
+
return PhaseADataLoader(data_config, loader, sampler, sample_order)
|
| 1282 |
+
|
| 1283 |
+
|
| 1284 |
+
def _sampler_state(value: Mapping[str, Any]) -> dict[str, Any]:
|
| 1285 |
+
expected = {
|
| 1286 |
+
"schema_version",
|
| 1287 |
+
"subset_manifest_sha256",
|
| 1288 |
+
"seed",
|
| 1289 |
+
"batch_size",
|
| 1290 |
+
"num_batches",
|
| 1291 |
+
"epoch",
|
| 1292 |
+
"batch_cursor",
|
| 1293 |
+
"next_sample_ids",
|
| 1294 |
+
}
|
| 1295 |
+
if set(value) != expected:
|
| 1296 |
+
raise ValueError("Phase-A full-state sampler fields mismatch")
|
| 1297 |
+
schema_version = _identifier(value["schema_version"], "sampler.schema_version")
|
| 1298 |
+
if schema_version not in {FORMAL_SAMPLER_SCHEMA, SMOKE_SAMPLER_SCHEMA}:
|
| 1299 |
+
raise ValueError("Phase-A sampler schema is unsupported")
|
| 1300 |
+
batch_size = _sampler_natural(value["batch_size"], "sampler.batch_size")
|
| 1301 |
+
next_ids = tuple(_sample_identity(item, "sampler.next_sample_ids item") for item in value["next_sample_ids"])
|
| 1302 |
+
if batch_size <= 0 or len(next_ids) != batch_size:
|
| 1303 |
+
raise ValueError("Phase-A sampler must name exactly one positive ordered next batch")
|
| 1304 |
+
parsed = {
|
| 1305 |
+
"schema_version": schema_version,
|
| 1306 |
+
"subset_manifest_sha256": str(_sha256(value["subset_manifest_sha256"], "sampler.subset_manifest_sha256")),
|
| 1307 |
+
"seed": _sampler_natural(value["seed"], "sampler.seed"),
|
| 1308 |
+
"batch_size": batch_size,
|
| 1309 |
+
"num_batches": _sampler_natural(value["num_batches"], "sampler.num_batches"),
|
| 1310 |
+
"epoch": _sampler_natural(value["epoch"], "sampler.epoch"),
|
| 1311 |
+
"batch_cursor": _sampler_natural(value["batch_cursor"], "sampler.batch_cursor"),
|
| 1312 |
+
"next_sample_ids": list(next_ids),
|
| 1313 |
+
}
|
| 1314 |
+
if parsed["batch_size"] % 4 or parsed["num_batches"] <= 0:
|
| 1315 |
+
raise ValueError("Phase-A sampler must describe a non-empty four-task-balanced run")
|
| 1316 |
+
if parsed["batch_cursor"] >= parsed["num_batches"]:
|
| 1317 |
+
raise ValueError("Phase-A sampler batch_cursor must be smaller than num_batches")
|
| 1318 |
+
if any(parsed[name] > np.iinfo(np.uint64).max for name in ("seed", "num_batches", "epoch", "batch_cursor")):
|
| 1319 |
+
raise ValueError("Phase-A sampler state values must fit in uint64")
|
| 1320 |
+
return parsed
|
| 1321 |
+
|
| 1322 |
+
|
| 1323 |
+
def _scheduler_value(schedule: Any, step: int) -> float:
|
| 1324 |
+
value = float(np.asarray(jax.device_get(schedule(step))))
|
| 1325 |
+
if not math.isfinite(value) or value <= 0:
|
| 1326 |
+
raise ValueError(f"Phase-A learning rate must be finite and positive, got {value}")
|
| 1327 |
+
return value
|
| 1328 |
+
|
| 1329 |
+
|
| 1330 |
+
def _resume_payload(
|
| 1331 |
+
state: Any,
|
| 1332 |
+
*,
|
| 1333 |
+
train_rng: Any,
|
| 1334 |
+
sampler_state: Mapping[str, Any],
|
| 1335 |
+
schedule: Any,
|
| 1336 |
+
contract: PhaseAContract,
|
| 1337 |
+
) -> dict[str, Any]:
|
| 1338 |
+
if state.ema_params is None:
|
| 1339 |
+
raise ValueError("Phase-A full state requires EMA parameters")
|
| 1340 |
+
step = int(np.asarray(jax.device_get(state.step)))
|
| 1341 |
+
sampler = _sampler_state(sampler_state)
|
| 1342 |
+
if sampler["batch_size"] != contract.global_batch_size:
|
| 1343 |
+
raise ValueError("checkpoint sampler batch differs from the runtime-bound Phase-A contract")
|
| 1344 |
+
if contract.launch_kind in {"formal", "sku_smoke"}:
|
| 1345 |
+
sampler_step = sampler["epoch"] * sampler["num_batches"] + sampler["batch_cursor"]
|
| 1346 |
+
if sampler_step != step:
|
| 1347 |
+
raise ValueError("Run084 sampler cursor differs from authoritative TrainState.step")
|
| 1348 |
+
return {
|
| 1349 |
+
"authoritative_step": state.step,
|
| 1350 |
+
"current_params": state.params,
|
| 1351 |
+
"ema_params": state.ema_params,
|
| 1352 |
+
"optimizer": state.opt_state,
|
| 1353 |
+
"scheduler": {
|
| 1354 |
+
"step": state.step,
|
| 1355 |
+
"learning_rate": jax.numpy.asarray(_scheduler_value(schedule, step), dtype=jax.numpy.float32),
|
| 1356 |
+
},
|
| 1357 |
+
"rng": {"train_key_data": jax.random.key_data(train_rng)},
|
| 1358 |
+
"sampler": {
|
| 1359 |
+
"schema_version_ascii": _ascii_bytes(sampler["schema_version"], "sampler.schema_version"),
|
| 1360 |
+
"subset_manifest_sha256": _digest_bytes(
|
| 1361 |
+
sampler["subset_manifest_sha256"], "sampler.subset_manifest_sha256"
|
| 1362 |
+
),
|
| 1363 |
+
"seed_u64": _u64_words(sampler["seed"], "sampler.seed"),
|
| 1364 |
+
"batch_size_u64": _u64_words(sampler["batch_size"], "sampler.batch_size"),
|
| 1365 |
+
"num_batches_u64": _u64_words(sampler["num_batches"], "sampler.num_batches"),
|
| 1366 |
+
"epoch_u64": _u64_words(sampler["epoch"], "sampler.epoch"),
|
| 1367 |
+
"batch_cursor_u64": _u64_words(sampler["batch_cursor"], "sampler.batch_cursor"),
|
| 1368 |
+
"next_sample_identity_sha256": jax.numpy.asarray(
|
| 1369 |
+
np.stack(
|
| 1370 |
+
[np.frombuffer(bytes.fromhex(identity), dtype=np.uint8) for identity in sampler["next_sample_ids"]]
|
| 1371 |
+
)
|
| 1372 |
+
),
|
| 1373 |
+
},
|
| 1374 |
+
"immutable_lineage": {
|
| 1375 |
+
"config_sha256": _digest_bytes(contract.config_sha256, "config_sha256"),
|
| 1376 |
+
"dataset_sha256": _digest_bytes(contract.dataset_sha256, "dataset_sha256"),
|
| 1377 |
+
"cohort_sha256": _digest_bytes(contract.cohort_sha256, "cohort_sha256"),
|
| 1378 |
+
"sidecar_sha256": _digest_bytes(contract.sidecar_sha256, "sidecar_sha256"),
|
| 1379 |
+
"feature_sha256": _digest_bytes(contract.feature_sha256, "feature_sha256"),
|
| 1380 |
+
"source_metadata_sha256": _digest_bytes(
|
| 1381 |
+
contract.source_metadata_sha256,
|
| 1382 |
+
"source_metadata_sha256",
|
| 1383 |
+
),
|
| 1384 |
+
"source_digest_sha256": _digest_bytes(
|
| 1385 |
+
contract.source_digest_sha256,
|
| 1386 |
+
"source_digest_sha256",
|
| 1387 |
+
),
|
| 1388 |
+
"artifact_identity_sha256": _digest_bytes(
|
| 1389 |
+
contract.artifact_identity_sha256,
|
| 1390 |
+
"artifact_identity_sha256",
|
| 1391 |
+
),
|
| 1392 |
+
"artifact_hashes_sha256": _digest_bytes(
|
| 1393 |
+
contract.artifact_hashes_sha256,
|
| 1394 |
+
"artifact_hashes_sha256",
|
| 1395 |
+
),
|
| 1396 |
+
"replacement_manifest_sha256": _digest_bytes(
|
| 1397 |
+
contract.replacement_manifest_sha256,
|
| 1398 |
+
"replacement_manifest_sha256",
|
| 1399 |
+
),
|
| 1400 |
+
"best_visible_manifest_sha256": _digest_bytes(
|
| 1401 |
+
contract.best_visible_manifest_sha256,
|
| 1402 |
+
"best_visible_manifest_sha256",
|
| 1403 |
+
),
|
| 1404 |
+
"sample_order_path_utf8": _path_bytes(contract.sample_order_path, "sample_order_path"),
|
| 1405 |
+
"sample_order_manifest_sha256": _digest_bytes(
|
| 1406 |
+
contract.sample_order_manifest_sha256,
|
| 1407 |
+
"sample_order_manifest_sha256",
|
| 1408 |
+
),
|
| 1409 |
+
"sample_order_sha256": _digest_bytes(
|
| 1410 |
+
contract.sample_order_sha256,
|
| 1411 |
+
"sample_order_sha256",
|
| 1412 |
+
),
|
| 1413 |
+
"training_manifest_sha256": _digest_bytes(
|
| 1414 |
+
contract.training_manifest_sha256,
|
| 1415 |
+
"training_manifest_sha256",
|
| 1416 |
+
),
|
| 1417 |
+
"overlay_sha256": _digest_bytes(contract.overlay_sha256, "overlay_sha256"),
|
| 1418 |
+
"runtime_policy_sha256": _digest_bytes(
|
| 1419 |
+
contract.runtime_policy_sha256,
|
| 1420 |
+
"runtime_policy_sha256",
|
| 1421 |
+
),
|
| 1422 |
+
"runtime_plan_sha256": _digest_bytes(contract.runtime_plan_sha256, "runtime_plan_sha256"),
|
| 1423 |
+
"runtime_matrix_sha256": _digest_bytes(
|
| 1424 |
+
contract.runtime_matrix_sha256,
|
| 1425 |
+
"runtime_matrix_sha256",
|
| 1426 |
+
),
|
| 1427 |
+
"runtime_calibration_sha256": _digest_bytes(
|
| 1428 |
+
contract.runtime_calibration_sha256,
|
| 1429 |
+
"runtime_calibration_sha256",
|
| 1430 |
+
),
|
| 1431 |
+
"optimizer_sha256": _digest_bytes(contract.optimizer_sha256, "optimizer_sha256"),
|
| 1432 |
+
"learning_rate_schedule_sha256": _digest_bytes(
|
| 1433 |
+
contract.learning_rate_schedule_sha256,
|
| 1434 |
+
"learning_rate_schedule_sha256",
|
| 1435 |
+
),
|
| 1436 |
+
},
|
| 1437 |
+
}
|
| 1438 |
+
|
| 1439 |
+
|
| 1440 |
+
def _decode_sampler(payload: Mapping[str, Any]) -> dict[str, Any]:
|
| 1441 |
+
batch_size = _decode_u64_words(payload["batch_size_u64"], "sampler.batch_size_u64")
|
| 1442 |
+
identity_bytes = np.asarray(
|
| 1443 |
+
jax.device_get(payload["next_sample_identity_sha256"]),
|
| 1444 |
+
dtype=np.uint8,
|
| 1445 |
+
)
|
| 1446 |
+
if identity_bytes.shape != (batch_size, 32):
|
| 1447 |
+
raise ValueError("restored sampler next-sample identity matrix has the wrong shape")
|
| 1448 |
+
return _sampler_state(
|
| 1449 |
+
{
|
| 1450 |
+
"schema_version": _decode_ascii(payload["schema_version_ascii"], "sampler.schema_version_ascii"),
|
| 1451 |
+
"subset_manifest_sha256": _decode_digest(
|
| 1452 |
+
payload["subset_manifest_sha256"], "sampler.subset_manifest_sha256"
|
| 1453 |
+
),
|
| 1454 |
+
"seed": _decode_u64_words(payload["seed_u64"], "sampler.seed_u64"),
|
| 1455 |
+
"batch_size": batch_size,
|
| 1456 |
+
"num_batches": _decode_u64_words(payload["num_batches_u64"], "sampler.num_batches_u64"),
|
| 1457 |
+
"epoch": _decode_u64_words(payload["epoch_u64"], "sampler.epoch_u64"),
|
| 1458 |
+
"batch_cursor": _decode_u64_words(payload["batch_cursor_u64"], "sampler.batch_cursor_u64"),
|
| 1459 |
+
"next_sample_ids": [row.tobytes().hex() for row in identity_bytes],
|
| 1460 |
+
}
|
| 1461 |
+
)
|
| 1462 |
+
|
| 1463 |
+
|
| 1464 |
+
def _validate_resume_lineage(payload: Mapping[str, Any], contract: PhaseAContract) -> None:
|
| 1465 |
+
expected = {
|
| 1466 |
+
"config_sha256": contract.config_sha256,
|
| 1467 |
+
"dataset_sha256": contract.dataset_sha256,
|
| 1468 |
+
"cohort_sha256": contract.cohort_sha256,
|
| 1469 |
+
"sidecar_sha256": contract.sidecar_sha256,
|
| 1470 |
+
"feature_sha256": contract.feature_sha256,
|
| 1471 |
+
"source_metadata_sha256": contract.source_metadata_sha256,
|
| 1472 |
+
"source_digest_sha256": contract.source_digest_sha256,
|
| 1473 |
+
"artifact_identity_sha256": contract.artifact_identity_sha256,
|
| 1474 |
+
"artifact_hashes_sha256": contract.artifact_hashes_sha256,
|
| 1475 |
+
"replacement_manifest_sha256": contract.replacement_manifest_sha256,
|
| 1476 |
+
"best_visible_manifest_sha256": contract.best_visible_manifest_sha256,
|
| 1477 |
+
"sample_order_path_utf8": str(contract.sample_order_path),
|
| 1478 |
+
"sample_order_manifest_sha256": contract.sample_order_manifest_sha256,
|
| 1479 |
+
"sample_order_sha256": contract.sample_order_sha256,
|
| 1480 |
+
"training_manifest_sha256": contract.training_manifest_sha256,
|
| 1481 |
+
"overlay_sha256": contract.overlay_sha256,
|
| 1482 |
+
"runtime_policy_sha256": contract.runtime_policy_sha256,
|
| 1483 |
+
"runtime_plan_sha256": contract.runtime_plan_sha256,
|
| 1484 |
+
"runtime_matrix_sha256": contract.runtime_matrix_sha256,
|
| 1485 |
+
"runtime_calibration_sha256": contract.runtime_calibration_sha256,
|
| 1486 |
+
"optimizer_sha256": contract.optimizer_sha256,
|
| 1487 |
+
"learning_rate_schedule_sha256": contract.learning_rate_schedule_sha256,
|
| 1488 |
+
}
|
| 1489 |
+
if set(payload) != set(expected):
|
| 1490 |
+
raise ValueError("Phase-A restored immutable lineage fields mismatch")
|
| 1491 |
+
drift = []
|
| 1492 |
+
for name, value in expected.items():
|
| 1493 |
+
actual = (
|
| 1494 |
+
_decode_path(payload[name], "sample_order_path")
|
| 1495 |
+
if name == "sample_order_path_utf8"
|
| 1496 |
+
else _decode_digest(payload[name], name)
|
| 1497 |
+
)
|
| 1498 |
+
if actual != value:
|
| 1499 |
+
drift.append(name)
|
| 1500 |
+
if drift:
|
| 1501 |
+
raise ValueError(f"Phase-A restored immutable lineage drift: {drift}")
|
| 1502 |
+
|
| 1503 |
+
|
| 1504 |
+
def materialize_phase_a_contract(contract: PhaseAContract, config: Any) -> Path:
|
| 1505 |
+
path = contract.checkpoint_root / "picmem_phase_a_full_state_contract.json"
|
| 1506 |
+
payload = contract.stable_json(config)
|
| 1507 |
+
if path.exists():
|
| 1508 |
+
if path.is_symlink() or not path.is_file() or path.read_bytes() != _canonical_json(payload):
|
| 1509 |
+
raise ValueError("Phase-A immutable checkpoint-root contract drift")
|
| 1510 |
+
else:
|
| 1511 |
+
_write_atomic_json(path, payload)
|
| 1512 |
+
return path
|
| 1513 |
+
|
| 1514 |
+
|
| 1515 |
+
def _save_assets(directory: epath.Path, data_loader: PhaseADataLoader, contract_path: Path) -> None:
|
| 1516 |
+
data_config = data_loader.data_config()
|
| 1517 |
+
if data_config.norm_stats is not None and data_config.asset_id is not None:
|
| 1518 |
+
_normalize.save(directory / data_config.asset_id, data_config.norm_stats)
|
| 1519 |
+
shutil.copyfile(contract_path, Path(directory) / contract_path.name)
|
| 1520 |
+
|
| 1521 |
+
|
| 1522 |
+
def _write_state_manifest(checkpoint_dir: Path, step: int, sampler: Mapping[str, Any]) -> None:
|
| 1523 |
+
assets_digest = path_sha256(checkpoint_dir / "assets")
|
| 1524 |
+
resume_digest = path_sha256(checkpoint_dir / "resume_state")
|
| 1525 |
+
params_digest = path_sha256(checkpoint_dir / "params")
|
| 1526 |
+
components = {
|
| 1527 |
+
"assets": StateComponent("assets", "assets", assets_digest),
|
| 1528 |
+
"trainable_params": StateComponent("resume_state", "resume_state/current_params", resume_digest),
|
| 1529 |
+
"ema_params": StateComponent("resume_state", "resume_state/ema_params", resume_digest),
|
| 1530 |
+
"inference_params": StateComponent("params", "params/inference_params", params_digest),
|
| 1531 |
+
"optimizer": StateComponent("resume_state", "resume_state/optimizer", resume_digest),
|
| 1532 |
+
"scheduler": StateComponent("resume_state", "resume_state/scheduler", resume_digest),
|
| 1533 |
+
"rng": StateComponent("resume_state", "resume_state/rng", resume_digest),
|
| 1534 |
+
}
|
| 1535 |
+
parsed_sampler = _sampler_state(sampler)
|
| 1536 |
+
manifest = StateManifest(
|
| 1537 |
+
authoritative_global_step=step,
|
| 1538 |
+
components=components,
|
| 1539 |
+
sampler=SamplerState(
|
| 1540 |
+
path="resume_state",
|
| 1541 |
+
orbax_item="resume_state/sampler",
|
| 1542 |
+
sha256=resume_digest,
|
| 1543 |
+
schema_version=parsed_sampler["schema_version"],
|
| 1544 |
+
subset_manifest_sha256=parsed_sampler["subset_manifest_sha256"],
|
| 1545 |
+
seed=parsed_sampler["seed"],
|
| 1546 |
+
batch_size=parsed_sampler["batch_size"],
|
| 1547 |
+
num_batches=parsed_sampler["num_batches"],
|
| 1548 |
+
epoch=parsed_sampler["epoch"],
|
| 1549 |
+
batch_cursor=parsed_sampler["batch_cursor"],
|
| 1550 |
+
next_sample_ids=tuple(parsed_sampler["next_sample_ids"]),
|
| 1551 |
+
),
|
| 1552 |
+
)
|
| 1553 |
+
_write_atomic_json(checkpoint_dir / "picmem_state_manifest.json", manifest.to_json())
|
| 1554 |
+
|
| 1555 |
+
|
| 1556 |
+
def save_phase_a_checkpoint(
|
| 1557 |
+
checkpoint_manager: Any,
|
| 1558 |
+
state: Any,
|
| 1559 |
+
data_loader: PhaseADataLoader,
|
| 1560 |
+
step: int,
|
| 1561 |
+
*,
|
| 1562 |
+
contract: PhaseAContract,
|
| 1563 |
+
contract_path: Path,
|
| 1564 |
+
train_rng: Any,
|
| 1565 |
+
schedule: Any,
|
| 1566 |
+
) -> CheckpointInfo:
|
| 1567 |
+
authoritative_step = int(np.asarray(jax.device_get(state.step)))
|
| 1568 |
+
if int(step) != authoritative_step:
|
| 1569 |
+
raise ValueError("checkpoint step differs from authoritative TrainState.step")
|
| 1570 |
+
sampler = data_loader.sampler_state_dict()
|
| 1571 |
+
payload = _resume_payload(
|
| 1572 |
+
state,
|
| 1573 |
+
train_rng=train_rng,
|
| 1574 |
+
sampler_state=sampler,
|
| 1575 |
+
schedule=schedule,
|
| 1576 |
+
contract=contract,
|
| 1577 |
+
)
|
| 1578 |
+
accepted = checkpoint_manager.save(
|
| 1579 |
+
authoritative_step,
|
| 1580 |
+
{
|
| 1581 |
+
"assets": lambda directory: _save_assets(directory, data_loader, contract_path),
|
| 1582 |
+
"params": {"params": state.ema_params},
|
| 1583 |
+
"resume_state": payload,
|
| 1584 |
+
},
|
| 1585 |
+
)
|
| 1586 |
+
if not accepted:
|
| 1587 |
+
raise RuntimeError(f"checkpoint manager rejected Phase-A full-state step {authoritative_step}")
|
| 1588 |
+
checkpoint_manager.wait_until_finished()
|
| 1589 |
+
checkpoint_dir = Path(checkpoint_manager.directory) / str(authoritative_step)
|
| 1590 |
+
_write_state_manifest(checkpoint_dir, authoritative_step, sampler)
|
| 1591 |
+
info = finalize_checkpoint(checkpoint_dir, contract.checkpoint_metadata(authoritative_step))
|
| 1592 |
+
print(f"PICMEM_CHECKPOINT_FINALIZE_COMPLETE step={authoritative_step}", flush=True)
|
| 1593 |
+
return info
|
| 1594 |
+
|
| 1595 |
+
|
| 1596 |
+
def _tree_equal(left: Any, right: Any) -> bool:
|
| 1597 |
+
if jax.tree_util.tree_structure(left) != jax.tree_util.tree_structure(right):
|
| 1598 |
+
return False
|
| 1599 |
+
return all(
|
| 1600 |
+
np.array_equal(np.asarray(jax.device_get(a)), np.asarray(jax.device_get(b)))
|
| 1601 |
+
for a, b in zip(jax.tree_util.tree_leaves(left), jax.tree_util.tree_leaves(right), strict=True)
|
| 1602 |
+
)
|
| 1603 |
+
|
| 1604 |
+
|
| 1605 |
+
def _validate_checkpoint_contract(info: CheckpointInfo, contract: PhaseAContract) -> None:
|
| 1606 |
+
metadata = info.metadata
|
| 1607 |
+
expected = {
|
| 1608 |
+
"experiment": contract.experiment,
|
| 1609 |
+
"job": contract.job,
|
| 1610 |
+
"run_id": contract.run_id,
|
| 1611 |
+
"gpu_class": contract.gpu_class,
|
| 1612 |
+
"world_size": 8,
|
| 1613 |
+
"fsdp_devices": 8,
|
| 1614 |
+
"launch_kind": contract.launch_kind,
|
| 1615 |
+
"training_manifest_kind": contract.training_manifest_kind,
|
| 1616 |
+
"training_manifest_sha256": contract.training_manifest_sha256,
|
| 1617 |
+
"runtime_profile_id": contract.runtime_profile_id,
|
| 1618 |
+
"runtime_candidate_id": contract.runtime_candidate_id,
|
| 1619 |
+
"runtime_policy_sha256": contract.runtime_policy_sha256,
|
| 1620 |
+
"runtime_plan_sha256": contract.runtime_plan_sha256,
|
| 1621 |
+
"runtime_matrix_sha256": contract.runtime_matrix_sha256,
|
| 1622 |
+
"runtime_calibration_sha256": contract.runtime_calibration_sha256,
|
| 1623 |
+
"optimizer_sha256": contract.optimizer_sha256,
|
| 1624 |
+
"learning_rate_schedule_sha256": contract.learning_rate_schedule_sha256,
|
| 1625 |
+
"global_batch_size": contract.global_batch_size,
|
| 1626 |
+
"micro_batch_per_device": contract.micro_batch_per_device,
|
| 1627 |
+
"gradient_accumulation_steps": contract.gradient_accumulation_steps,
|
| 1628 |
+
"dataloader_workers": contract.dataloader_workers,
|
| 1629 |
+
"prefetch_factor": contract.prefetch_factor,
|
| 1630 |
+
"xla_preallocate": contract.xla_preallocate,
|
| 1631 |
+
"xla_memory_fraction": contract.xla_memory_fraction,
|
| 1632 |
+
"nccl_collective_channel_cap": contract.nccl_collective_channel_cap,
|
| 1633 |
+
"nccl_p2p_channel_cap": contract.nccl_p2p_channel_cap,
|
| 1634 |
+
"xla_flags": contract.xla_flags,
|
| 1635 |
+
"checkpoint_interval": contract.runtime_checkpoint_interval,
|
| 1636 |
+
"interface_commit": contract.interface_commit,
|
| 1637 |
+
"code_commit": contract.code_commit,
|
| 1638 |
+
"config_sha256": contract.config_sha256,
|
| 1639 |
+
"dataset_sha256": contract.dataset_sha256,
|
| 1640 |
+
"cohort_sha256": contract.cohort_sha256,
|
| 1641 |
+
"sidecar_sha256": contract.sidecar_sha256,
|
| 1642 |
+
"feature_sha256": contract.feature_sha256,
|
| 1643 |
+
"source_metadata_sha256": contract.source_metadata_sha256,
|
| 1644 |
+
"source_digest_sha256": contract.source_digest_sha256,
|
| 1645 |
+
"artifact_identity_sha256": contract.artifact_identity_sha256,
|
| 1646 |
+
"artifact_hashes_sha256": contract.artifact_hashes_sha256,
|
| 1647 |
+
"replacement_manifest_sha256": contract.replacement_manifest_sha256,
|
| 1648 |
+
"best_visible_manifest_sha256": contract.best_visible_manifest_sha256,
|
| 1649 |
+
"sample_order_path": str(contract.sample_order_path),
|
| 1650 |
+
"sample_order_manifest_sha256": contract.sample_order_manifest_sha256,
|
| 1651 |
+
"sample_order_sha256": contract.sample_order_sha256,
|
| 1652 |
+
"overlay_sha256": contract.overlay_sha256,
|
| 1653 |
+
}
|
| 1654 |
+
actual = {name: getattr(metadata, name) for name in expected}
|
| 1655 |
+
actual["gpu_class"] = metadata.gpu_class.value
|
| 1656 |
+
drift = [name for name, value in expected.items() if actual[name] != value]
|
| 1657 |
+
if drift:
|
| 1658 |
+
raise ValueError(f"Phase-A resume checkpoint lineage drift: {drift}")
|
| 1659 |
+
if metadata.generation >= contract.generation:
|
| 1660 |
+
raise ValueError("Phase-A resume checkpoint is not from an earlier generation")
|
| 1661 |
+
if contract.parent_metadata_sha256 != info.metadata_sha256:
|
| 1662 |
+
raise ValueError("Phase-A resume parent edge differs from the selected checkpoint metadata hash")
|
| 1663 |
+
|
| 1664 |
+
|
| 1665 |
+
def restore_phase_a_checkpoint(
|
| 1666 |
+
checkpoint_manager: Any,
|
| 1667 |
+
state: Any,
|
| 1668 |
+
data_loader: PhaseADataLoader,
|
| 1669 |
+
*,
|
| 1670 |
+
contract: PhaseAContract,
|
| 1671 |
+
train_rng: Any,
|
| 1672 |
+
schedule: Any,
|
| 1673 |
+
step: int,
|
| 1674 |
+
) -> tuple[Any, Any, dict[str, Any], CheckpointInfo]:
|
| 1675 |
+
checkpoint_dir = Path(checkpoint_manager.directory) / str(int(step))
|
| 1676 |
+
info = validate_checkpoint(
|
| 1677 |
+
checkpoint_dir,
|
| 1678 |
+
expected_experiment=contract.experiment,
|
| 1679 |
+
expected_job=contract.job,
|
| 1680 |
+
expected_gpu_class=contract.gpu_class,
|
| 1681 |
+
)
|
| 1682 |
+
_validate_checkpoint_contract(info, contract)
|
| 1683 |
+
target = _resume_payload(
|
| 1684 |
+
state,
|
| 1685 |
+
train_rng=train_rng,
|
| 1686 |
+
sampler_state=data_loader.sampler_state_dict(),
|
| 1687 |
+
schedule=schedule,
|
| 1688 |
+
contract=contract,
|
| 1689 |
+
)
|
| 1690 |
+
try:
|
| 1691 |
+
restored = checkpoint_manager.restore(
|
| 1692 |
+
int(step),
|
| 1693 |
+
items={"resume_state": target, "params": {"params": state.ema_params}},
|
| 1694 |
+
)
|
| 1695 |
+
except Exception as exc:
|
| 1696 |
+
raise ValueError("Phase-A Orbax resume state is missing or corrupt") from exc
|
| 1697 |
+
payload = restored["resume_state"]
|
| 1698 |
+
restored_step = int(np.asarray(jax.device_get(payload["authoritative_step"])))
|
| 1699 |
+
scheduler_step = int(np.asarray(jax.device_get(payload["scheduler"]["step"])))
|
| 1700 |
+
if restored_step != int(step) or scheduler_step != restored_step:
|
| 1701 |
+
raise ValueError("Phase-A authoritative/scheduler/checkpoint steps disagree")
|
| 1702 |
+
saved_lr = float(np.asarray(jax.device_get(payload["scheduler"]["learning_rate"])))
|
| 1703 |
+
expected_lr = _scheduler_value(schedule, restored_step)
|
| 1704 |
+
if not np.isclose(saved_lr, expected_lr, rtol=1e-6, atol=0.0):
|
| 1705 |
+
raise ValueError("Phase-A restored scheduler value differs from the immutable schedule")
|
| 1706 |
+
if not _tree_equal(payload["ema_params"], restored["params"]["params"]):
|
| 1707 |
+
raise ValueError("Phase-A inference params differ from restored EMA params")
|
| 1708 |
+
_validate_resume_lineage(payload["immutable_lineage"], contract)
|
| 1709 |
+
sampler = _decode_sampler(payload["sampler"])
|
| 1710 |
+
if contract.launch_kind in {"formal", "sku_smoke"}:
|
| 1711 |
+
sampler_step = sampler["epoch"] * sampler["num_batches"] + sampler["batch_cursor"]
|
| 1712 |
+
if sampler_step != restored_step:
|
| 1713 |
+
raise ValueError("restored Run084 sampler cursor differs from authoritative checkpoint step")
|
| 1714 |
+
data_loader.load_sampler_state_dict(sampler)
|
| 1715 |
+
restored_rng = jax.random.wrap_key_data(payload["rng"]["train_key_data"])
|
| 1716 |
+
restored_state = dataclasses.replace(
|
| 1717 |
+
state,
|
| 1718 |
+
step=payload["authoritative_step"],
|
| 1719 |
+
params=payload["current_params"],
|
| 1720 |
+
opt_state=payload["optimizer"],
|
| 1721 |
+
ema_params=payload["ema_params"],
|
| 1722 |
+
)
|
| 1723 |
+
return restored_state, restored_rng, sampler, info
|
| 1724 |
+
|
| 1725 |
+
|
| 1726 |
+
class PhaseAMetricWriter:
|
| 1727 |
+
FIELDS = ("schema_version", "wall_time", "step", "learning_rate", "loss", "metrics_json")
|
| 1728 |
+
|
| 1729 |
+
def __init__(self, path: Path):
|
| 1730 |
+
self.path = path
|
| 1731 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 1732 |
+
self._stream = path.open("x", newline="")
|
| 1733 |
+
self._writer = csv.DictWriter(self._stream, fieldnames=self.FIELDS, delimiter="\t", lineterminator="\n")
|
| 1734 |
+
self._writer.writeheader()
|
| 1735 |
+
self._flush()
|
| 1736 |
+
|
| 1737 |
+
def _flush(self) -> None:
|
| 1738 |
+
self._stream.flush()
|
| 1739 |
+
os.fsync(self._stream.fileno())
|
| 1740 |
+
|
| 1741 |
+
def write(self, *, step: int, learning_rate: float, metrics: Mapping[str, Any]) -> None:
|
| 1742 |
+
parsed: dict[str, float] = {}
|
| 1743 |
+
for name, value in metrics.items():
|
| 1744 |
+
array = np.asarray(jax.device_get(value))
|
| 1745 |
+
if array.size == 1:
|
| 1746 |
+
scalar = float(array.reshape(()))
|
| 1747 |
+
if not math.isfinite(scalar):
|
| 1748 |
+
raise ValueError(f"Phase-A metric {name} is not finite")
|
| 1749 |
+
parsed[name] = scalar
|
| 1750 |
+
if "loss" not in parsed:
|
| 1751 |
+
raise ValueError("Phase-A metrics are missing scalar loss")
|
| 1752 |
+
if not math.isfinite(learning_rate) or learning_rate <= 0:
|
| 1753 |
+
raise ValueError("Phase-A metric learning rate must be finite and positive")
|
| 1754 |
+
self._writer.writerow(
|
| 1755 |
+
{
|
| 1756 |
+
"schema_version": PHASE_A_METRICS_SCHEMA,
|
| 1757 |
+
"wall_time": datetime.now().astimezone().isoformat(timespec="seconds"),
|
| 1758 |
+
"step": int(step),
|
| 1759 |
+
"learning_rate": repr(float(learning_rate)),
|
| 1760 |
+
"loss": repr(parsed["loss"]),
|
| 1761 |
+
"metrics_json": json.dumps(parsed, sort_keys=True, separators=(",", ":")),
|
| 1762 |
+
}
|
| 1763 |
+
)
|
| 1764 |
+
self._flush()
|
| 1765 |
+
|
| 1766 |
+
def close(self) -> None:
|
| 1767 |
+
if not self._stream.closed:
|
| 1768 |
+
self._stream.close()
|
| 1769 |
+
|
| 1770 |
+
def __enter__(self) -> PhaseAMetricWriter:
|
| 1771 |
+
return self
|
| 1772 |
+
|
| 1773 |
+
def __exit__(self, *_: Any) -> None:
|
| 1774 |
+
self.close()
|
| 1775 |
+
|
| 1776 |
+
|
| 1777 |
+
class ContinuityEmitter:
|
| 1778 |
+
def __init__(self, contract: PhaseAContract, metrics_path: Path):
|
| 1779 |
+
self.contract = contract
|
| 1780 |
+
self.metrics_path = metrics_path.resolve()
|
| 1781 |
+
if self.metrics_path != contract.metrics_path:
|
| 1782 |
+
raise ValueError("continuity emitter metrics path differs from the Phase-A contract")
|
| 1783 |
+
self.pending: Any | None = None
|
| 1784 |
+
self.sampler: SamplerContinuity | None = None
|
| 1785 |
+
self.resume_step: int | None = None
|
| 1786 |
+
self.rng_sha256: str | None = None
|
| 1787 |
+
self._boundary_step: int | None = None
|
| 1788 |
+
self._boundary_sampler: SamplerContinuity | None = None
|
| 1789 |
+
self._boundary_rng_sha256: str | None = None
|
| 1790 |
+
|
| 1791 |
+
@staticmethod
|
| 1792 |
+
def _sampler(value: Mapping[str, Any]) -> SamplerContinuity:
|
| 1793 |
+
parsed = _sampler_state(value)
|
| 1794 |
+
return SamplerContinuity(
|
| 1795 |
+
schema_version=parsed["schema_version"],
|
| 1796 |
+
subset_manifest_sha256=parsed["subset_manifest_sha256"],
|
| 1797 |
+
seed=parsed["seed"],
|
| 1798 |
+
batch_size=parsed["batch_size"],
|
| 1799 |
+
num_batches=parsed["num_batches"],
|
| 1800 |
+
epoch=parsed["epoch"],
|
| 1801 |
+
batch_cursor=parsed["batch_cursor"],
|
| 1802 |
+
next_sample_ids=tuple(parsed["next_sample_ids"]),
|
| 1803 |
+
)
|
| 1804 |
+
|
| 1805 |
+
@staticmethod
|
| 1806 |
+
def _rng_sha256(train_rng: Any) -> str:
|
| 1807 |
+
key_data = np.asarray(jax.device_get(jax.random.key_data(train_rng)), dtype=np.uint32)
|
| 1808 |
+
return hashlib.sha256(key_data.tobytes(order="C")).hexdigest()
|
| 1809 |
+
|
| 1810 |
+
def _report_path(self, pending: Any) -> Path:
|
| 1811 |
+
return self.contract.watch_state_dir / f"continuity-{pending.request_id}.json"
|
| 1812 |
+
|
| 1813 |
+
def _clear_completed_request(self) -> None:
|
| 1814 |
+
"""Re-arm the live process for a later pause in the same generation."""
|
| 1815 |
+
|
| 1816 |
+
self.pending = None
|
| 1817 |
+
self.sampler = None
|
| 1818 |
+
self.resume_step = None
|
| 1819 |
+
self.rng_sha256 = None
|
| 1820 |
+
|
| 1821 |
+
def _capture_pending_from_boundary(self) -> None:
|
| 1822 |
+
if self.pending is not None:
|
| 1823 |
+
return
|
| 1824 |
+
state_path = self.contract.watch_state_dir / "state.json"
|
| 1825 |
+
if not state_path.is_file() or state_path.is_symlink():
|
| 1826 |
+
return
|
| 1827 |
+
state = WatchState.from_json(json.loads(state_path.read_text(encoding="utf-8")))
|
| 1828 |
+
if (state.experiment, state.job, state.generation) != (
|
| 1829 |
+
self.contract.experiment,
|
| 1830 |
+
self.contract.job,
|
| 1831 |
+
self.contract.generation,
|
| 1832 |
+
):
|
| 1833 |
+
raise ValueError("watch state identity/generation differs from the running Phase-A process")
|
| 1834 |
+
pending = state.pending_continuity
|
| 1835 |
+
if pending is None:
|
| 1836 |
+
return
|
| 1837 |
+
report_path = self._report_path(pending)
|
| 1838 |
+
if report_path.exists():
|
| 1839 |
+
return
|
| 1840 |
+
if self._boundary_step is None or self._boundary_sampler is None or self._boundary_rng_sha256 is None:
|
| 1841 |
+
raise ValueError("continuity request arrived before a live trainer boundary was recorded")
|
| 1842 |
+
if pending.mode is ContinuityMode.RESTART_ZERO:
|
| 1843 |
+
if self._boundary_step != 0 or pending.resume_step != 0:
|
| 1844 |
+
raise ValueError("restart_zero did not begin from authoritative step zero")
|
| 1845 |
+
elif pending.mode is ContinuityMode.CHECKPOINT_RESUME:
|
| 1846 |
+
if self._boundary_step != pending.resume_step:
|
| 1847 |
+
raise ValueError("running state step differs from watchdog checkpoint handoff")
|
| 1848 |
+
elif pending.resume_step is not None or pending.expected_sampler is not None:
|
| 1849 |
+
raise ValueError("paused resume request guessed a lagging checkpoint handoff")
|
| 1850 |
+
if pending.expected_sampler is not None and self._boundary_sampler != pending.expected_sampler:
|
| 1851 |
+
raise ValueError("restored sampler differs from watchdog checkpoint handoff")
|
| 1852 |
+
self.pending = pending
|
| 1853 |
+
self.resume_step = self._boundary_step
|
| 1854 |
+
self.sampler = self._boundary_sampler
|
| 1855 |
+
self.rng_sha256 = self._boundary_rng_sha256
|
| 1856 |
+
|
| 1857 |
+
def capture_pending(
|
| 1858 |
+
self,
|
| 1859 |
+
*,
|
| 1860 |
+
current_step: int,
|
| 1861 |
+
sampler_state: Mapping[str, Any],
|
| 1862 |
+
train_rng: Any,
|
| 1863 |
+
) -> None:
|
| 1864 |
+
"""Record a live loop boundary and acknowledge any pending request.
|
| 1865 |
+
|
| 1866 |
+
The method is intentionally called before every batch. ``after_metric``
|
| 1867 |
+
checks again so a process paused during a device step still uses the
|
| 1868 |
+
exact pre-step sampler/RNG boundary and the first post-resume metric.
|
| 1869 |
+
"""
|
| 1870 |
+
|
| 1871 |
+
self._boundary_step = _sampler_natural(current_step, "continuity current_step")
|
| 1872 |
+
self._boundary_sampler = self._sampler(sampler_state)
|
| 1873 |
+
if self._boundary_sampler.batch_size != self.contract.global_batch_size:
|
| 1874 |
+
raise ValueError("continuity sampler batch differs from the runtime-bound Phase-A contract")
|
| 1875 |
+
self._boundary_rng_sha256 = self._rng_sha256(train_rng)
|
| 1876 |
+
self._capture_pending_from_boundary()
|
| 1877 |
+
|
| 1878 |
+
def after_metric(self, *, first_metric_step: int, learning_rate: float) -> None:
|
| 1879 |
+
self._capture_pending_from_boundary()
|
| 1880 |
+
if self.pending is None or self.sampler is None or self.resume_step is None or self.rng_sha256 is None:
|
| 1881 |
+
return
|
| 1882 |
+
pending = self.pending
|
| 1883 |
+
report_path = self._report_path(pending)
|
| 1884 |
+
if report_path.exists():
|
| 1885 |
+
verify_continuity(
|
| 1886 |
+
report_path,
|
| 1887 |
+
pending,
|
| 1888 |
+
self.contract.experiment,
|
| 1889 |
+
self.contract.job,
|
| 1890 |
+
)
|
| 1891 |
+
self._clear_completed_request()
|
| 1892 |
+
return
|
| 1893 |
+
if first_metric_step != self.resume_step + 1:
|
| 1894 |
+
raise ValueError("first continuity metric is not the exact live next step")
|
| 1895 |
+
marker = "PICMEM_CLEAN_START_OK" if pending.mode is ContinuityMode.RESTART_ZERO else "PICMEM_RESUME_OK"
|
| 1896 |
+
payload = {
|
| 1897 |
+
"schema_version": CONTINUITY_SCHEMA,
|
| 1898 |
+
"experiment": self.contract.experiment,
|
| 1899 |
+
"job": self.contract.job,
|
| 1900 |
+
"generation": self.contract.generation,
|
| 1901 |
+
"mode": pending.mode.value,
|
| 1902 |
+
"request_id": pending.request_id,
|
| 1903 |
+
"resume_marker": marker,
|
| 1904 |
+
"resume_step": self.resume_step,
|
| 1905 |
+
"first_metric_step": int(first_metric_step),
|
| 1906 |
+
"learning_rate": float(learning_rate),
|
| 1907 |
+
"rng_sha256": self.rng_sha256,
|
| 1908 |
+
"sampler": self.sampler.to_json(),
|
| 1909 |
+
"metrics_path": str(self.metrics_path),
|
| 1910 |
+
"prior_metrics_reused": False,
|
| 1911 |
+
}
|
| 1912 |
+
_write_atomic_json(report_path, payload)
|
| 1913 |
+
verify_continuity(
|
| 1914 |
+
report_path,
|
| 1915 |
+
pending,
|
| 1916 |
+
self.contract.experiment,
|
| 1917 |
+
self.contract.job,
|
| 1918 |
+
)
|
| 1919 |
+
self._clear_completed_request()
|
| 1920 |
+
|
| 1921 |
+
|
| 1922 |
+
__all__ = [
|
| 1923 |
+
"PHASE_A_HISTORY_CONFIG",
|
| 1924 |
+
"ContinuityEmitter",
|
| 1925 |
+
"PhaseAContract",
|
| 1926 |
+
"PhaseADataLoader",
|
| 1927 |
+
"PhaseAMetricWriter",
|
| 1928 |
+
"PhaseASampler",
|
| 1929 |
+
"PhaseASmokeRandomSampler",
|
| 1930 |
+
"create_phase_a_data_loader",
|
| 1931 |
+
"initialize_phase_a_checkpoint_dir",
|
| 1932 |
+
"materialize_phase_a_contract",
|
| 1933 |
+
"restore_phase_a_checkpoint",
|
| 1934 |
+
"save_phase_a_checkpoint",
|
| 1935 |
+
"validate_phase_a_topology",
|
| 1936 |
+
]
|
checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/training/picmem_phase_a_reader.py
ADDED
|
@@ -0,0 +1,717 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Token-layout and metadata materialization for the Phase-A visual reader.
|
| 2 |
+
|
| 3 |
+
The standalone :mod:`picmem.memory` package owns the frozen ``Read`` and
|
| 4 |
+
``SelectedFrame`` contracts. This host adapter is deliberately the only place
|
| 5 |
+
that turns those frame-level records into RoboMME's fixed 512-token
|
| 6 |
+
observation. Visual selection is kept separate from metadata interventions so
|
| 7 |
+
all metadata arms retain byte-identical image features, PosEmb3D tensors and
|
| 8 |
+
valid-token masks.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import hashlib
|
| 14 |
+
from collections.abc import Mapping, Sequence
|
| 15 |
+
from dataclasses import dataclass
|
| 16 |
+
from typing import Any
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
|
| 20 |
+
from picmem.memory.contracts import (
|
| 21 |
+
ManagerMode,
|
| 22 |
+
MetadataMode,
|
| 23 |
+
ReaderMode,
|
| 24 |
+
SelectedFrame,
|
| 25 |
+
SelectionMode,
|
| 26 |
+
)
|
| 27 |
+
from picmem.memory.memory import MemoryInvariantError, Read
|
| 28 |
+
|
| 29 |
+
FRAME_BUDGET = 32
|
| 30 |
+
TOKEN_BUDGET = 512
|
| 31 |
+
FIXED_TOKENS_PER_FRAME = 16
|
| 32 |
+
MAX_VARIABLE_EVIDENCE = 6
|
| 33 |
+
FLOAT32_NEGATIVE_ZERO_BITS = np.uint32(0x80000000)
|
| 34 |
+
|
| 35 |
+
TIME_CHANNELS = 3
|
| 36 |
+
EVENT_VOCAB_SIZE = 4096
|
| 37 |
+
CONTRACT_VOCAB_SIZE = 128
|
| 38 |
+
STATUS_VOCAB_SIZE = 32
|
| 39 |
+
EVENT_ORDINAL_VOCAB_SIZE = 128
|
| 40 |
+
|
| 41 |
+
FACTOR_FIELDS = frozenset({"selection_mode", "metadata_mode", "reader_mode", "manager_mode"})
|
| 42 |
+
|
| 43 |
+
OBSERVATION_FIELDS = (
|
| 44 |
+
"phase_a_frame_indices",
|
| 45 |
+
"phase_a_capture_steps",
|
| 46 |
+
"phase_a_time_values",
|
| 47 |
+
"phase_a_time_mask",
|
| 48 |
+
"phase_a_role_ids",
|
| 49 |
+
"phase_a_role_mask",
|
| 50 |
+
"phase_a_event_ids",
|
| 51 |
+
"phase_a_event_ordinals",
|
| 52 |
+
"phase_a_contract_ids",
|
| 53 |
+
"phase_a_status_ids",
|
| 54 |
+
"phase_a_categorical_mask",
|
| 55 |
+
"phase_a_confidence",
|
| 56 |
+
"phase_a_evidence_mask",
|
| 57 |
+
"phase_a_valid_mask",
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
@dataclass(frozen=True)
|
| 62 |
+
class PhaseAFactors:
|
| 63 |
+
"""The four declared experiment factors consumed by this host path."""
|
| 64 |
+
|
| 65 |
+
selection_mode: SelectionMode = SelectionMode.RELEVANT
|
| 66 |
+
metadata_mode: MetadataMode = MetadataMode.NEUTRAL
|
| 67 |
+
reader_mode: ReaderMode = ReaderMode.FIXED16
|
| 68 |
+
manager_mode: ManagerMode = ManagerMode.FULL_EVOLVING
|
| 69 |
+
|
| 70 |
+
@classmethod
|
| 71 |
+
def from_mapping(
|
| 72 |
+
cls,
|
| 73 |
+
raw: Mapping[str, Any] | None,
|
| 74 |
+
*,
|
| 75 |
+
require_explicit: bool = False,
|
| 76 |
+
) -> PhaseAFactors:
|
| 77 |
+
if raw is None:
|
| 78 |
+
raw = {}
|
| 79 |
+
if not isinstance(raw, Mapping):
|
| 80 |
+
raise ValueError("Phase-A factors must be a mapping")
|
| 81 |
+
unknown = set(raw) - FACTOR_FIELDS
|
| 82 |
+
if unknown:
|
| 83 |
+
raise ValueError(f"unknown Phase-A factor fields: {sorted(unknown)}")
|
| 84 |
+
missing = FACTOR_FIELDS - set(raw)
|
| 85 |
+
if require_explicit and missing:
|
| 86 |
+
raise ValueError(f"explicit Phase-A factors are missing: {sorted(missing)}")
|
| 87 |
+
values = {
|
| 88 |
+
"selection_mode": raw.get("selection_mode", SelectionMode.RELEVANT),
|
| 89 |
+
"metadata_mode": raw.get("metadata_mode", MetadataMode.NEUTRAL),
|
| 90 |
+
"reader_mode": raw.get("reader_mode", ReaderMode.FIXED16),
|
| 91 |
+
"manager_mode": raw.get("manager_mode", ManagerMode.FULL_EVOLVING),
|
| 92 |
+
}
|
| 93 |
+
try:
|
| 94 |
+
return cls(
|
| 95 |
+
selection_mode=SelectionMode(values["selection_mode"]),
|
| 96 |
+
metadata_mode=MetadataMode(values["metadata_mode"]),
|
| 97 |
+
reader_mode=ReaderMode(values["reader_mode"]),
|
| 98 |
+
manager_mode=ManagerMode(values["manager_mode"]),
|
| 99 |
+
)
|
| 100 |
+
except ValueError as exc:
|
| 101 |
+
raise ValueError(f"unsupported Phase-A factor value: {exc}") from exc
|
| 102 |
+
|
| 103 |
+
def validate_implemented_path(
|
| 104 |
+
self,
|
| 105 |
+
*,
|
| 106 |
+
selection_applied: SelectionMode | str | None = None,
|
| 107 |
+
) -> None:
|
| 108 |
+
"""Fail rather than silently run a factor this branch does not own."""
|
| 109 |
+
|
| 110 |
+
if selection_applied is not None:
|
| 111 |
+
try:
|
| 112 |
+
applied = SelectionMode(selection_applied)
|
| 113 |
+
except ValueError as exc:
|
| 114 |
+
raise ValueError(f"unsupported applied selection mode: {selection_applied!r}") from exc
|
| 115 |
+
if applied is not self.selection_mode:
|
| 116 |
+
raise NotImplementedError(
|
| 117 |
+
"Phase-A materializer selection_mode does not match the verified frozen selection plan"
|
| 118 |
+
)
|
| 119 |
+
if self.reader_mode is ReaderMode.RAW_VLM:
|
| 120 |
+
raise NotImplementedError("reader_mode='raw_vlm' requires the separately gated raw-image reader")
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
@dataclass(frozen=True)
|
| 124 |
+
class PhaseATokenMetadata:
|
| 125 |
+
"""Model-facing metadata aligned one-to-one with 512 visual tokens."""
|
| 126 |
+
|
| 127 |
+
frame_indices: np.ndarray
|
| 128 |
+
capture_steps: np.ndarray
|
| 129 |
+
time_values: np.ndarray
|
| 130 |
+
time_mask: np.ndarray
|
| 131 |
+
role_ids: np.ndarray
|
| 132 |
+
role_mask: np.ndarray
|
| 133 |
+
event_ids: np.ndarray
|
| 134 |
+
event_ordinals: np.ndarray
|
| 135 |
+
contract_ids: np.ndarray
|
| 136 |
+
status_ids: np.ndarray
|
| 137 |
+
categorical_mask: np.ndarray
|
| 138 |
+
confidence: np.ndarray
|
| 139 |
+
evidence_mask: np.ndarray
|
| 140 |
+
valid_mask: np.ndarray
|
| 141 |
+
|
| 142 |
+
def __post_init__(self) -> None:
|
| 143 |
+
vector_specs = {
|
| 144 |
+
"frame_indices": np.int32,
|
| 145 |
+
"capture_steps": np.int32,
|
| 146 |
+
"role_ids": np.int32,
|
| 147 |
+
"role_mask": np.bool_,
|
| 148 |
+
"event_ids": np.int32,
|
| 149 |
+
"event_ordinals": np.int32,
|
| 150 |
+
"contract_ids": np.int32,
|
| 151 |
+
"status_ids": np.int32,
|
| 152 |
+
"categorical_mask": np.bool_,
|
| 153 |
+
"confidence": np.float32,
|
| 154 |
+
"evidence_mask": np.bool_,
|
| 155 |
+
"valid_mask": np.bool_,
|
| 156 |
+
}
|
| 157 |
+
for name, dtype in vector_specs.items():
|
| 158 |
+
value = getattr(self, name)
|
| 159 |
+
if not isinstance(value, np.ndarray) or value.shape != (TOKEN_BUDGET,):
|
| 160 |
+
raise MemoryInvariantError(f"Phase-A token metadata {name} must have shape {(TOKEN_BUDGET,)}")
|
| 161 |
+
if value.dtype != dtype:
|
| 162 |
+
raise MemoryInvariantError(f"Phase-A token metadata {name} must have dtype {np.dtype(dtype)}")
|
| 163 |
+
for name in ("time_values", "time_mask"):
|
| 164 |
+
value = getattr(self, name)
|
| 165 |
+
expected_dtype = np.float32 if name == "time_values" else np.bool_
|
| 166 |
+
if not isinstance(value, np.ndarray) or value.shape != (
|
| 167 |
+
TOKEN_BUDGET,
|
| 168 |
+
TIME_CHANNELS,
|
| 169 |
+
):
|
| 170 |
+
raise MemoryInvariantError(
|
| 171 |
+
f"Phase-A token metadata {name} must have shape {(TOKEN_BUDGET, TIME_CHANNELS)}"
|
| 172 |
+
)
|
| 173 |
+
if value.dtype != expected_dtype:
|
| 174 |
+
raise MemoryInvariantError(f"Phase-A token metadata {name} must have dtype {np.dtype(expected_dtype)}")
|
| 175 |
+
if np.any(self.time_values.view(np.uint32) == FLOAT32_NEGATIVE_ZERO_BITS):
|
| 176 |
+
raise MemoryInvariantError("Phase-A time values must encode zero as canonical +0.0")
|
| 177 |
+
|
| 178 |
+
invalid = ~self.valid_mask
|
| 179 |
+
if np.any(self.frame_indices < 0) or np.any(self.capture_steps < 0):
|
| 180 |
+
raise MemoryInvariantError("Phase-A token provenance must be non-negative")
|
| 181 |
+
if np.any(self.frame_indices[invalid]) or np.any(self.capture_steps[invalid]):
|
| 182 |
+
raise MemoryInvariantError("Phase-A token padding provenance must be canonical zeros")
|
| 183 |
+
if np.any(self.time_mask[invalid]):
|
| 184 |
+
raise MemoryInvariantError("Phase-A token padding cannot expose temporal metadata")
|
| 185 |
+
for name in ("role_mask", "categorical_mask", "evidence_mask"):
|
| 186 |
+
if np.any(getattr(self, name) & invalid):
|
| 187 |
+
raise MemoryInvariantError(f"Phase-A token {name} cannot mark padding")
|
| 188 |
+
|
| 189 |
+
if not np.array_equal(self.role_mask, self.evidence_mask):
|
| 190 |
+
raise MemoryInvariantError("Phase-A role mask must equal evidence mask")
|
| 191 |
+
if not np.array_equal(self.categorical_mask, self.evidence_mask):
|
| 192 |
+
raise MemoryInvariantError("Phase-A categorical mask must equal evidence mask")
|
| 193 |
+
if not np.array_equal(
|
| 194 |
+
self.time_mask,
|
| 195 |
+
np.repeat(self.time_mask[:, :1], TIME_CHANNELS, axis=1),
|
| 196 |
+
):
|
| 197 |
+
raise MemoryInvariantError("Phase-A time channels must share one token gate")
|
| 198 |
+
|
| 199 |
+
if np.any(self.time_values[~self.time_mask]):
|
| 200 |
+
raise MemoryInvariantError("masked Phase-A time values must be neutral zeros")
|
| 201 |
+
if np.any(self.capture_steps[~np.any(self.time_mask, axis=-1)]):
|
| 202 |
+
raise MemoryInvariantError("masked Phase-A capture steps must be neutral zeros")
|
| 203 |
+
if np.any(self.role_ids[~self.role_mask]):
|
| 204 |
+
raise MemoryInvariantError("masked Phase-A role IDs must be neutral zeros")
|
| 205 |
+
for name in (
|
| 206 |
+
"event_ids",
|
| 207 |
+
"event_ordinals",
|
| 208 |
+
"contract_ids",
|
| 209 |
+
"status_ids",
|
| 210 |
+
"confidence",
|
| 211 |
+
):
|
| 212 |
+
if np.any(getattr(self, name)[~self.categorical_mask]):
|
| 213 |
+
raise MemoryInvariantError(f"masked Phase-A {name} must contain neutral zeros")
|
| 214 |
+
|
| 215 |
+
if not np.all(np.isfinite(self.time_values)):
|
| 216 |
+
raise MemoryInvariantError("Phase-A time values must be finite")
|
| 217 |
+
if np.any((self.time_values < 0) | (self.time_values > 1)):
|
| 218 |
+
raise MemoryInvariantError("Phase-A normalized time values must be in [0, 1]")
|
| 219 |
+
if not np.all(np.isfinite(self.confidence)) or np.any((self.confidence < 0) | (self.confidence > 1)):
|
| 220 |
+
raise MemoryInvariantError("Phase-A confidence must be finite and in [0, 1]")
|
| 221 |
+
if np.any(self.role_ids[self.evidence_mask] == 0):
|
| 222 |
+
raise MemoryInvariantError("Phase-A evidence tokens require a non-background role")
|
| 223 |
+
for name in ("event_ids", "event_ordinals", "contract_ids", "status_ids"):
|
| 224 |
+
if np.any(getattr(self, name)[self.evidence_mask] == 0):
|
| 225 |
+
raise MemoryInvariantError(f"Phase-A evidence tokens require nonzero {name}")
|
| 226 |
+
|
| 227 |
+
def to_observation(self) -> dict[str, np.ndarray]:
|
| 228 |
+
values = {
|
| 229 |
+
"phase_a_frame_indices": self.frame_indices,
|
| 230 |
+
"phase_a_capture_steps": self.capture_steps,
|
| 231 |
+
"phase_a_time_values": self.time_values,
|
| 232 |
+
"phase_a_time_mask": self.time_mask,
|
| 233 |
+
"phase_a_role_ids": self.role_ids,
|
| 234 |
+
"phase_a_role_mask": self.role_mask,
|
| 235 |
+
"phase_a_event_ids": self.event_ids,
|
| 236 |
+
"phase_a_event_ordinals": self.event_ordinals,
|
| 237 |
+
"phase_a_contract_ids": self.contract_ids,
|
| 238 |
+
"phase_a_status_ids": self.status_ids,
|
| 239 |
+
"phase_a_categorical_mask": self.categorical_mask,
|
| 240 |
+
"phase_a_confidence": self.confidence,
|
| 241 |
+
"phase_a_evidence_mask": self.evidence_mask,
|
| 242 |
+
"phase_a_valid_mask": self.valid_mask,
|
| 243 |
+
}
|
| 244 |
+
if tuple(values) != OBSERVATION_FIELDS:
|
| 245 |
+
raise AssertionError("Phase-A observation field registry drift")
|
| 246 |
+
return values
|
| 247 |
+
|
| 248 |
+
@classmethod
|
| 249 |
+
def from_observation(
|
| 250 |
+
cls,
|
| 251 |
+
raw: Mapping[str, Any],
|
| 252 |
+
*,
|
| 253 |
+
metadata_mode: MetadataMode | str,
|
| 254 |
+
) -> PhaseATokenMetadata:
|
| 255 |
+
"""Recover the exact token contract after host observation transforms.
|
| 256 |
+
|
| 257 |
+
Missing or extra Phase-A fields are schema drift. Recovered arrays are
|
| 258 |
+
detached from the host container and made immutable before validation.
|
| 259 |
+
"""
|
| 260 |
+
|
| 261 |
+
if not isinstance(raw, Mapping):
|
| 262 |
+
raise MemoryInvariantError("Phase-A observation must be a mapping")
|
| 263 |
+
if set(raw) != set(OBSERVATION_FIELDS):
|
| 264 |
+
missing = sorted(set(OBSERVATION_FIELDS) - set(raw))
|
| 265 |
+
extra = sorted(set(raw) - set(OBSERVATION_FIELDS))
|
| 266 |
+
raise MemoryInvariantError(f"Phase-A observation field drift (missing={missing}, extra={extra})")
|
| 267 |
+
names = {
|
| 268 |
+
"frame_indices": "phase_a_frame_indices",
|
| 269 |
+
"capture_steps": "phase_a_capture_steps",
|
| 270 |
+
"time_values": "phase_a_time_values",
|
| 271 |
+
"time_mask": "phase_a_time_mask",
|
| 272 |
+
"role_ids": "phase_a_role_ids",
|
| 273 |
+
"role_mask": "phase_a_role_mask",
|
| 274 |
+
"event_ids": "phase_a_event_ids",
|
| 275 |
+
"event_ordinals": "phase_a_event_ordinals",
|
| 276 |
+
"contract_ids": "phase_a_contract_ids",
|
| 277 |
+
"status_ids": "phase_a_status_ids",
|
| 278 |
+
"categorical_mask": "phase_a_categorical_mask",
|
| 279 |
+
"confidence": "phase_a_confidence",
|
| 280 |
+
"evidence_mask": "phase_a_evidence_mask",
|
| 281 |
+
"valid_mask": "phase_a_valid_mask",
|
| 282 |
+
}
|
| 283 |
+
values: dict[str, np.ndarray] = {}
|
| 284 |
+
for name, field in names.items():
|
| 285 |
+
value = np.array(raw[field], copy=True)
|
| 286 |
+
value.setflags(write=False)
|
| 287 |
+
values[name] = value
|
| 288 |
+
metadata = cls(**values)
|
| 289 |
+
metadata.validate_mode(metadata_mode)
|
| 290 |
+
return metadata
|
| 291 |
+
|
| 292 |
+
def validate_mode(self, metadata_mode: MetadataMode | str) -> None:
|
| 293 |
+
"""Enforce the exact mask geometry of one declared metadata arm."""
|
| 294 |
+
|
| 295 |
+
try:
|
| 296 |
+
mode = MetadataMode(metadata_mode)
|
| 297 |
+
except (TypeError, ValueError) as exc:
|
| 298 |
+
raise MemoryInvariantError(f"unsupported Phase-A metadata mode: {metadata_mode!r}") from exc
|
| 299 |
+
full_time = np.repeat(self.valid_mask[:, None], TIME_CHANNELS, axis=1)
|
| 300 |
+
no_time = np.zeros_like(full_time)
|
| 301 |
+
task_aware_modes = {
|
| 302 |
+
MetadataMode.CORRECT,
|
| 303 |
+
MetadataMode.TIME_SHUFFLED,
|
| 304 |
+
MetadataMode.ORDER_REVERSED,
|
| 305 |
+
MetadataMode.ROLE_ONLY,
|
| 306 |
+
}
|
| 307 |
+
if mode in task_aware_modes:
|
| 308 |
+
if not np.array_equal(self.role_mask, self.evidence_mask) or not np.array_equal(
|
| 309 |
+
self.categorical_mask,
|
| 310 |
+
self.evidence_mask,
|
| 311 |
+
):
|
| 312 |
+
raise MemoryInvariantError(f"metadata_mode={mode.value} requires task-aware gates on evidence only")
|
| 313 |
+
elif np.any(self.role_mask) or np.any(self.categorical_mask) or np.any(self.evidence_mask):
|
| 314 |
+
raise MemoryInvariantError(f"metadata_mode={mode.value} requires neutral task-aware gates")
|
| 315 |
+
|
| 316 |
+
expected_time = no_time if mode in {MetadataMode.ROLE_ONLY, MetadataMode.NEUTRAL} else full_time
|
| 317 |
+
if not np.array_equal(self.time_mask, expected_time):
|
| 318 |
+
raise MemoryInvariantError(f"metadata_mode={mode.value} has an invalid temporal gate")
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
@dataclass(frozen=True)
|
| 322 |
+
class PhaseAFramePlan:
|
| 323 |
+
"""A validated frame plan, per-frame token geometry and token metadata."""
|
| 324 |
+
|
| 325 |
+
frame_indices: np.ndarray
|
| 326 |
+
valid_mask: np.ndarray
|
| 327 |
+
evidence_mask: np.ndarray
|
| 328 |
+
token_counts: np.ndarray
|
| 329 |
+
metadata: PhaseATokenMetadata
|
| 330 |
+
|
| 331 |
+
@property
|
| 332 |
+
def valid_indices(self) -> tuple[int, ...]:
|
| 333 |
+
return tuple(int(value) for value in self.frame_indices[self.valid_mask])
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def materialize_phase_a_read(
|
| 337 |
+
read: Read,
|
| 338 |
+
factors: PhaseAFactors,
|
| 339 |
+
*,
|
| 340 |
+
metadata_seed: int = 0,
|
| 341 |
+
selection_applied: SelectionMode | str = SelectionMode.RELEVANT,
|
| 342 |
+
) -> PhaseAFramePlan:
|
| 343 |
+
"""Validate one ``Read`` and produce a strict 512-token host plan."""
|
| 344 |
+
|
| 345 |
+
if not isinstance(read, Read):
|
| 346 |
+
raise MemoryInvariantError("Phase-A materializer requires a Read")
|
| 347 |
+
if not isinstance(factors, PhaseAFactors):
|
| 348 |
+
raise ValueError("factors must be PhaseAFactors")
|
| 349 |
+
factors.validate_implemented_path(selection_applied=selection_applied)
|
| 350 |
+
metadata_seed = _nonnegative_int(metadata_seed, "metadata_seed")
|
| 351 |
+
frames = _validated_selected_frames(read)
|
| 352 |
+
token_counts = _token_layout(frames, factors.reader_mode)
|
| 353 |
+
frame_metadata = _intervene_metadata(
|
| 354 |
+
frames,
|
| 355 |
+
factors.metadata_mode,
|
| 356 |
+
seed=metadata_seed,
|
| 357 |
+
read_step=read.step,
|
| 358 |
+
)
|
| 359 |
+
token_metadata = _repeat_metadata(frame_metadata, token_counts)
|
| 360 |
+
token_metadata.validate_mode(factors.metadata_mode)
|
| 361 |
+
|
| 362 |
+
frame_indices = np.asarray([frame.frame_index for frame in frames], dtype=np.int32)
|
| 363 |
+
valid_mask = np.asarray([frame.valid_mask for frame in frames], dtype=np.bool_)
|
| 364 |
+
evidence_mask = np.asarray([frame.evidence_mask for frame in frames], dtype=np.bool_)
|
| 365 |
+
for value in (frame_indices, valid_mask, evidence_mask, token_counts):
|
| 366 |
+
value.setflags(write=False)
|
| 367 |
+
return PhaseAFramePlan(
|
| 368 |
+
frame_indices=frame_indices,
|
| 369 |
+
valid_mask=valid_mask,
|
| 370 |
+
evidence_mask=evidence_mask,
|
| 371 |
+
token_counts=token_counts,
|
| 372 |
+
metadata=token_metadata,
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
def _validated_selected_frames(read: Read) -> tuple[SelectedFrame, ...]:
|
| 377 |
+
try:
|
| 378 |
+
read_step = _nonnegative_int(read.step, "Read.step")
|
| 379 |
+
except ValueError as exc:
|
| 380 |
+
raise MemoryInvariantError(str(exc)) from exc
|
| 381 |
+
frames = read.selected_frames
|
| 382 |
+
if not isinstance(frames, tuple) or len(frames) != FRAME_BUDGET:
|
| 383 |
+
raise MemoryInvariantError(f"Phase-A Read.selected_frames must contain exactly {FRAME_BUDGET} slots")
|
| 384 |
+
if any(not isinstance(frame, SelectedFrame) for frame in frames):
|
| 385 |
+
raise MemoryInvariantError("Phase-A selected frame has the wrong contract type")
|
| 386 |
+
if read.frame_indices.shape != (FRAME_BUDGET,):
|
| 387 |
+
raise MemoryInvariantError("Phase-A frame_indices shape drift")
|
| 388 |
+
if read.evidence_mask.shape != (FRAME_BUDGET,) or read.valid_mask.shape != (FRAME_BUDGET,):
|
| 389 |
+
raise MemoryInvariantError("Phase-A frame masks shape drift")
|
| 390 |
+
|
| 391 |
+
valid_indices: list[int] = []
|
| 392 |
+
previous_capture: int | None = None
|
| 393 |
+
denominator = max(read_step, 1)
|
| 394 |
+
for slot, frame in enumerate(frames):
|
| 395 |
+
if frame.valid_mask != bool(read.valid_mask[slot]):
|
| 396 |
+
raise MemoryInvariantError("SelectedFrame.valid_mask disagrees with Read.valid_mask")
|
| 397 |
+
if frame.evidence_mask != bool(read.evidence_mask[slot]):
|
| 398 |
+
raise MemoryInvariantError("SelectedFrame.evidence_mask disagrees with Read.evidence_mask")
|
| 399 |
+
if frame.evidence_mask and not frame.valid_mask:
|
| 400 |
+
raise MemoryInvariantError("padding cannot be evidence")
|
| 401 |
+
if frame.valid_mask:
|
| 402 |
+
if frame.frame_index != int(read.frame_indices[slot]):
|
| 403 |
+
raise MemoryInvariantError("SelectedFrame.frame_index disagrees with Read.frame_indices")
|
| 404 |
+
try:
|
| 405 |
+
capture_step = _nonnegative_int(
|
| 406 |
+
frame.capture_step,
|
| 407 |
+
f"SelectedFrame[{slot}].capture_step",
|
| 408 |
+
)
|
| 409 |
+
except ValueError as exc:
|
| 410 |
+
raise MemoryInvariantError(str(exc)) from exc
|
| 411 |
+
if capture_step > read_step:
|
| 412 |
+
raise MemoryInvariantError("SelectedFrame.capture_step is not causal")
|
| 413 |
+
if previous_capture is not None and capture_step < previous_capture:
|
| 414 |
+
raise MemoryInvariantError("SelectedFrame.capture_step must be nondecreasing across valid slots")
|
| 415 |
+
expected_time = np.asarray(
|
| 416 |
+
(
|
| 417 |
+
capture_step / denominator,
|
| 418 |
+
(read_step - capture_step) / denominator,
|
| 419 |
+
0.0 if previous_capture is None else (capture_step - previous_capture) / denominator,
|
| 420 |
+
),
|
| 421 |
+
dtype=np.float32,
|
| 422 |
+
)
|
| 423 |
+
_validate_temporal_values(frame, expected_time, slot=slot)
|
| 424 |
+
valid_indices.append(frame.frame_index)
|
| 425 |
+
previous_capture = capture_step
|
| 426 |
+
elif frame != SelectedFrame.padding():
|
| 427 |
+
raise MemoryInvariantError("invalid Phase-A slots must use canonical padding metadata")
|
| 428 |
+
if valid_indices != sorted(set(valid_indices)):
|
| 429 |
+
raise MemoryInvariantError("Phase-A valid frames must be sorted and unique")
|
| 430 |
+
return frames
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
def _validate_temporal_values(
|
| 434 |
+
frame: SelectedFrame,
|
| 435 |
+
expected: np.ndarray,
|
| 436 |
+
*,
|
| 437 |
+
slot: int,
|
| 438 |
+
) -> None:
|
| 439 |
+
raw = (frame.absolute_time, frame.relative_age, frame.delta_prev)
|
| 440 |
+
names = ("absolute_time", "relative_age", "delta_prev")
|
| 441 |
+
for name, value in zip(names, raw, strict=True):
|
| 442 |
+
if isinstance(value, (bool, np.bool_)) or not isinstance(
|
| 443 |
+
value,
|
| 444 |
+
(int, float, np.integer, np.floating),
|
| 445 |
+
):
|
| 446 |
+
raise MemoryInvariantError(f"SelectedFrame[{slot}].{name} must be numeric")
|
| 447 |
+
actual = np.asarray(raw, dtype=np.float64)
|
| 448 |
+
if not np.all(np.isfinite(actual)):
|
| 449 |
+
raise MemoryInvariantError(f"SelectedFrame[{slot}] temporal coordinates must be finite")
|
| 450 |
+
if np.any((actual < 0.0) | (actual > 1.0)):
|
| 451 |
+
raise MemoryInvariantError(f"SelectedFrame[{slot}] normalized temporal coordinates must be in [0, 1]")
|
| 452 |
+
|
| 453 |
+
# SelectedFrame values originate as Python numerics while the host wire and
|
| 454 |
+
# model consume float32. The only accepted source-to-wire rounding is the
|
| 455 |
+
# local float32 cell that maps to the explicitly derived canonical value.
|
| 456 |
+
# A derived positive zero is stricter: the source must be numeric zero and
|
| 457 |
+
# its float32 wire form must have no sign bit. This prevents underflow drift
|
| 458 |
+
# and IEEE negative zero from changing observation bytes or hashes.
|
| 459 |
+
canonical_wire = np.asarray(raw, dtype=np.float32)
|
| 460 |
+
expected_bits = expected.view(np.uint32)
|
| 461 |
+
canonical_bits = canonical_wire.view(np.uint32)
|
| 462 |
+
for index, (name, value) in enumerate(zip(names, raw, strict=True)):
|
| 463 |
+
if expected_bits[index] == 0 and (value != 0.0 or canonical_bits[index] != 0):
|
| 464 |
+
raise MemoryInvariantError(f"SelectedFrame[{slot}].{name} must encode zero as canonical +0.0")
|
| 465 |
+
if not np.array_equal(canonical_wire, expected):
|
| 466 |
+
raise MemoryInvariantError(f"SelectedFrame[{slot}] temporal coordinates disagree with capture/read steps")
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
def _token_layout(frames: Sequence[SelectedFrame], reader_mode: ReaderMode) -> np.ndarray:
|
| 470 |
+
counts = np.full(FRAME_BUDGET, FIXED_TOKENS_PER_FRAME, dtype=np.int32)
|
| 471 |
+
if reader_mode is ReaderMode.FIXED16:
|
| 472 |
+
counts.setflags(write=False)
|
| 473 |
+
return counts
|
| 474 |
+
if reader_mode is not ReaderMode.VARIABLE64:
|
| 475 |
+
raise NotImplementedError(f"reader mode is not materialized: {reader_mode}")
|
| 476 |
+
|
| 477 |
+
evidence = [index for index, frame in enumerate(frames) if frame.valid_mask and frame.evidence_mask]
|
| 478 |
+
if len(evidence) > MAX_VARIABLE_EVIDENCE:
|
| 479 |
+
raise MemoryInvariantError(
|
| 480 |
+
f"variable64 supports at most {MAX_VARIABLE_EVIDENCE} evidence frames, got {len(evidence)}"
|
| 481 |
+
)
|
| 482 |
+
background = [index for index, frame in enumerate(frames) if not frame.evidence_mask]
|
| 483 |
+
low_resolution_count = 4 * len(evidence)
|
| 484 |
+
if low_resolution_count > len(background):
|
| 485 |
+
raise MemoryInvariantError("variable64 does not have enough background slots")
|
| 486 |
+
|
| 487 |
+
# Spend the reduced-resolution quota on padding first. For a full read,
|
| 488 |
+
# preserve the initial/current/recent anchors when possible and downsample
|
| 489 |
+
# the oldest remaining background slots. This ordering is deterministic
|
| 490 |
+
# and depends only on the already-frozen visual plan.
|
| 491 |
+
valid_slots = [index for index, frame in enumerate(frames) if frame.valid_mask]
|
| 492 |
+
protected = set(valid_slots[:1] + valid_slots[-5:])
|
| 493 |
+
low_resolution_order = sorted(
|
| 494 |
+
background,
|
| 495 |
+
key=lambda index: (
|
| 496 |
+
frames[index].valid_mask,
|
| 497 |
+
index in protected,
|
| 498 |
+
frames[index].frame_index,
|
| 499 |
+
index,
|
| 500 |
+
),
|
| 501 |
+
)
|
| 502 |
+
low_resolution = set(low_resolution_order[:low_resolution_count])
|
| 503 |
+
for index in evidence:
|
| 504 |
+
counts[index] = 64
|
| 505 |
+
for index in low_resolution:
|
| 506 |
+
counts[index] = 4
|
| 507 |
+
|
| 508 |
+
expected_high_background = FRAME_BUDGET - 5 * len(evidence)
|
| 509 |
+
high_background = sum(1 for index in background if counts[index] == FIXED_TOKENS_PER_FRAME)
|
| 510 |
+
if high_background != expected_high_background:
|
| 511 |
+
raise MemoryInvariantError("variable64 high-resolution background geometry drift")
|
| 512 |
+
if int(counts.sum()) != TOKEN_BUDGET:
|
| 513 |
+
raise MemoryInvariantError("variable64 must materialize exactly 512 tokens")
|
| 514 |
+
counts.setflags(write=False)
|
| 515 |
+
return counts
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
def _intervene_metadata(
|
| 519 |
+
frames: Sequence[SelectedFrame],
|
| 520 |
+
mode: MetadataMode,
|
| 521 |
+
*,
|
| 522 |
+
seed: int,
|
| 523 |
+
read_step: int,
|
| 524 |
+
) -> dict[str, np.ndarray]:
|
| 525 |
+
valid = np.asarray([frame.valid_mask for frame in frames], dtype=np.bool_)
|
| 526 |
+
evidence = np.asarray([frame.evidence_mask for frame in frames], dtype=np.bool_)
|
| 527 |
+
frame_indices = np.asarray([frame.frame_index for frame in frames], dtype=np.int32)
|
| 528 |
+
capture = np.asarray([frame.capture_step for frame in frames], dtype=np.int32)
|
| 529 |
+
time = np.asarray(
|
| 530 |
+
[[frame.absolute_time, frame.relative_age, frame.delta_prev] for frame in frames],
|
| 531 |
+
dtype=np.float32,
|
| 532 |
+
)
|
| 533 |
+
role = np.asarray([int(frame.role_id) for frame in frames], dtype=np.int32)
|
| 534 |
+
event = _bucket_ids(
|
| 535 |
+
[frame.event_id for frame in frames],
|
| 536 |
+
vocab_size=EVENT_VOCAB_SIZE,
|
| 537 |
+
label="event_id",
|
| 538 |
+
)
|
| 539 |
+
ordinal = np.asarray(
|
| 540 |
+
[frame.event_ordinal + 1 if frame.event_ordinal >= 0 else 0 for frame in frames],
|
| 541 |
+
dtype=np.int32,
|
| 542 |
+
)
|
| 543 |
+
contract = _bucket_ids(
|
| 544 |
+
[frame.contract_id for frame in frames],
|
| 545 |
+
vocab_size=CONTRACT_VOCAB_SIZE,
|
| 546 |
+
label="contract_id",
|
| 547 |
+
)
|
| 548 |
+
status = _bucket_ids(
|
| 549 |
+
[frame.status_id for frame in frames],
|
| 550 |
+
vocab_size=STATUS_VOCAB_SIZE,
|
| 551 |
+
label="status_id",
|
| 552 |
+
)
|
| 553 |
+
confidence = np.asarray([frame.confidence for frame in frames], dtype=np.float32)
|
| 554 |
+
time_mask = np.repeat(valid[:, None], TIME_CHANNELS, axis=1)
|
| 555 |
+
# Background and padding carry only normalized temporal coordinates. All
|
| 556 |
+
# task-aware categorical IDs and masks remain neutral by contract.
|
| 557 |
+
role_mask = evidence.copy()
|
| 558 |
+
categorical_mask = evidence.copy()
|
| 559 |
+
|
| 560 |
+
background = valid & ~evidence
|
| 561 |
+
if (
|
| 562 |
+
np.any(role[background] != 0)
|
| 563 |
+
or np.any(event[background] != 0)
|
| 564 |
+
or np.any(ordinal[background] != 0)
|
| 565 |
+
or np.any(contract[background] != 0)
|
| 566 |
+
or np.any(status[background] != 0)
|
| 567 |
+
or np.any(confidence[background] != 0)
|
| 568 |
+
):
|
| 569 |
+
raise MemoryInvariantError("background slots must have neutral task-aware metadata")
|
| 570 |
+
|
| 571 |
+
if np.any(ordinal >= EVENT_ORDINAL_VOCAB_SIZE):
|
| 572 |
+
raise MemoryInvariantError(f"event ordinal exceeds reader vocabulary {EVENT_ORDINAL_VOCAB_SIZE - 1}")
|
| 573 |
+
|
| 574 |
+
if mode is MetadataMode.TIME_SHUFFLED:
|
| 575 |
+
slots = np.flatnonzero(valid)
|
| 576 |
+
if slots.size > 1:
|
| 577 |
+
permutation = _nonidentity_permutation(
|
| 578 |
+
slots.size,
|
| 579 |
+
seed=seed,
|
| 580 |
+
identity=(read_step, *frame_indices[valid].tolist()),
|
| 581 |
+
)
|
| 582 |
+
source = slots[permutation]
|
| 583 |
+
capture[slots] = capture[source]
|
| 584 |
+
time[slots] = time[source]
|
| 585 |
+
elif mode is MetadataMode.ORDER_REVERSED:
|
| 586 |
+
slots = np.flatnonzero(evidence)
|
| 587 |
+
if slots.size > 1:
|
| 588 |
+
ordinal[slots] = ordinal[slots[::-1]]
|
| 589 |
+
elif mode is MetadataMode.ROLE_ONLY:
|
| 590 |
+
capture.fill(0)
|
| 591 |
+
time.fill(0)
|
| 592 |
+
time_mask.fill(False)
|
| 593 |
+
elif mode is MetadataMode.TIME_ONLY:
|
| 594 |
+
role.fill(0)
|
| 595 |
+
event.fill(0)
|
| 596 |
+
ordinal.fill(0)
|
| 597 |
+
contract.fill(0)
|
| 598 |
+
status.fill(0)
|
| 599 |
+
confidence.fill(0)
|
| 600 |
+
evidence.fill(False)
|
| 601 |
+
role_mask.fill(False)
|
| 602 |
+
categorical_mask.fill(False)
|
| 603 |
+
elif mode is MetadataMode.NEUTRAL:
|
| 604 |
+
capture.fill(0)
|
| 605 |
+
time.fill(0)
|
| 606 |
+
role.fill(0)
|
| 607 |
+
event.fill(0)
|
| 608 |
+
ordinal.fill(0)
|
| 609 |
+
contract.fill(0)
|
| 610 |
+
status.fill(0)
|
| 611 |
+
confidence.fill(0)
|
| 612 |
+
evidence.fill(False)
|
| 613 |
+
time_mask.fill(False)
|
| 614 |
+
role_mask.fill(False)
|
| 615 |
+
categorical_mask.fill(False)
|
| 616 |
+
elif mode is not MetadataMode.CORRECT:
|
| 617 |
+
raise ValueError(f"unsupported metadata mode: {mode}")
|
| 618 |
+
|
| 619 |
+
# Padding is neutral for every mode. The invariant frame index/valid mask
|
| 620 |
+
# remain available for parity audits but are never made task-aware.
|
| 621 |
+
for value in (capture, role, event, ordinal, contract, status):
|
| 622 |
+
value[~valid] = 0
|
| 623 |
+
time[~valid] = 0
|
| 624 |
+
confidence[~valid] = 0
|
| 625 |
+
evidence[~valid] = False
|
| 626 |
+
time_mask[~valid] = False
|
| 627 |
+
role_mask[~valid] = False
|
| 628 |
+
categorical_mask[~valid] = False
|
| 629 |
+
return {
|
| 630 |
+
"frame_indices": frame_indices,
|
| 631 |
+
"capture_steps": capture,
|
| 632 |
+
"time_values": time,
|
| 633 |
+
"time_mask": time_mask,
|
| 634 |
+
"role_ids": role,
|
| 635 |
+
"role_mask": role_mask,
|
| 636 |
+
"event_ids": event,
|
| 637 |
+
"event_ordinals": ordinal,
|
| 638 |
+
"contract_ids": contract,
|
| 639 |
+
"status_ids": status,
|
| 640 |
+
"categorical_mask": categorical_mask,
|
| 641 |
+
"confidence": confidence,
|
| 642 |
+
"evidence_mask": evidence,
|
| 643 |
+
"valid_mask": valid,
|
| 644 |
+
}
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
def _repeat_metadata(
|
| 648 |
+
values: Mapping[str, np.ndarray],
|
| 649 |
+
token_counts: np.ndarray,
|
| 650 |
+
) -> PhaseATokenMetadata:
|
| 651 |
+
repeated: dict[str, np.ndarray] = {}
|
| 652 |
+
for name, value in values.items():
|
| 653 |
+
repeated_value = np.repeat(value, token_counts, axis=0)
|
| 654 |
+
if repeated_value.shape[0] != TOKEN_BUDGET:
|
| 655 |
+
raise MemoryInvariantError(f"{name} did not materialize exactly 512 tokens")
|
| 656 |
+
repeated_value.setflags(write=False)
|
| 657 |
+
repeated[name] = repeated_value
|
| 658 |
+
return PhaseATokenMetadata(**repeated)
|
| 659 |
+
|
| 660 |
+
|
| 661 |
+
def _bucket_ids(values: Sequence[str], *, vocab_size: int, label: str) -> np.ndarray:
|
| 662 |
+
if vocab_size <= 1:
|
| 663 |
+
raise ValueError("categorical vocabularies must reserve a neutral bucket")
|
| 664 |
+
buckets: dict[int, str] = {}
|
| 665 |
+
output = np.zeros(len(values), dtype=np.int32)
|
| 666 |
+
for index, value in enumerate(values):
|
| 667 |
+
if value == "":
|
| 668 |
+
continue
|
| 669 |
+
if not isinstance(value, str):
|
| 670 |
+
raise MemoryInvariantError(f"{label} must be a string")
|
| 671 |
+
digest = hashlib.sha256(f"picmem-phase-a:{label}:{value}".encode()).digest()
|
| 672 |
+
bucket = int.from_bytes(digest[:8], "big") % (vocab_size - 1) + 1
|
| 673 |
+
collision = buckets.get(bucket)
|
| 674 |
+
if collision is not None and collision != value:
|
| 675 |
+
raise MemoryInvariantError(f"{label} hash collision within one Read: {collision!r} and {value!r}")
|
| 676 |
+
buckets[bucket] = value
|
| 677 |
+
output[index] = bucket
|
| 678 |
+
return output
|
| 679 |
+
|
| 680 |
+
|
| 681 |
+
def _nonidentity_permutation(
|
| 682 |
+
size: int,
|
| 683 |
+
*,
|
| 684 |
+
seed: int,
|
| 685 |
+
identity: tuple[int, ...],
|
| 686 |
+
) -> np.ndarray:
|
| 687 |
+
payload = ":".join(str(value) for value in (seed, *identity)).encode()
|
| 688 |
+
mixed_seed = int.from_bytes(hashlib.sha256(payload).digest()[:8], "big")
|
| 689 |
+
permutation = np.random.default_rng(mixed_seed).permutation(size)
|
| 690 |
+
if np.array_equal(permutation, np.arange(size)):
|
| 691 |
+
permutation = np.roll(permutation, 1)
|
| 692 |
+
return permutation
|
| 693 |
+
|
| 694 |
+
|
| 695 |
+
def _nonnegative_int(value: Any, name: str) -> int:
|
| 696 |
+
if isinstance(value, bool) or not isinstance(value, (int, np.integer)) or int(value) < 0:
|
| 697 |
+
raise ValueError(f"{name} must be a non-negative integer")
|
| 698 |
+
return int(value)
|
| 699 |
+
|
| 700 |
+
|
| 701 |
+
__all__ = [
|
| 702 |
+
"CONTRACT_VOCAB_SIZE",
|
| 703 |
+
"EVENT_ORDINAL_VOCAB_SIZE",
|
| 704 |
+
"EVENT_VOCAB_SIZE",
|
| 705 |
+
"FACTOR_FIELDS",
|
| 706 |
+
"FIXED_TOKENS_PER_FRAME",
|
| 707 |
+
"FRAME_BUDGET",
|
| 708 |
+
"MAX_VARIABLE_EVIDENCE",
|
| 709 |
+
"OBSERVATION_FIELDS",
|
| 710 |
+
"STATUS_VOCAB_SIZE",
|
| 711 |
+
"TIME_CHANNELS",
|
| 712 |
+
"TOKEN_BUDGET",
|
| 713 |
+
"PhaseAFactors",
|
| 714 |
+
"PhaseAFramePlan",
|
| 715 |
+
"PhaseATokenMetadata",
|
| 716 |
+
"materialize_phase_a_read",
|
| 717 |
+
]
|
checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/training/picmem_phase_a_runtime.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Online Phase-A ``RuntimeReadSession`` to RoboMME ``MemoryBuffer`` bridge.
|
| 2 |
+
|
| 3 |
+
This adapter owns no event semantics and performs no online frame selection.
|
| 4 |
+
It accepts only the strict standalone runtime session, materializes its
|
| 5 |
+
policy-visible ``Read`` with the already-reviewed reader geometry, and gathers
|
| 6 |
+
the corresponding features from the live ``MemoryBuffer``. Formal rollout
|
| 7 |
+
workers can therefore use the same 512-token path as offline training without
|
| 8 |
+
reimplementing it in the simulator loop.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import hashlib
|
| 14 |
+
from dataclasses import dataclass
|
| 15 |
+
from typing import Any
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
from mme_vla_suite.shared.mem_buffer import MemoryBuffer
|
| 19 |
+
from mme_vla_suite.training.picmem_phase_a_reader import (
|
| 20 |
+
PhaseAFactors,
|
| 21 |
+
PhaseAFramePlan,
|
| 22 |
+
PhaseATokenMetadata,
|
| 23 |
+
materialize_phase_a_read,
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
from picmem.memory.contracts import SelectionMode
|
| 27 |
+
from picmem.memory.memory import Read
|
| 28 |
+
from picmem.provenance.runtime_reader import RuntimeReadError, RuntimeReadSession, read_sha256
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@dataclass(frozen=True)
|
| 32 |
+
class RuntimePhaseAObservation:
|
| 33 |
+
"""One exact runtime read and its raw, pre-normalization host tensors."""
|
| 34 |
+
|
| 35 |
+
read: Read
|
| 36 |
+
plan: PhaseAFramePlan
|
| 37 |
+
image: np.ndarray
|
| 38 |
+
position: np.ndarray
|
| 39 |
+
state: np.ndarray
|
| 40 |
+
mask: np.ndarray
|
| 41 |
+
metadata: PhaseATokenMetadata
|
| 42 |
+
read_sha256: str
|
| 43 |
+
image_sha256: str
|
| 44 |
+
position_sha256: str
|
| 45 |
+
state_sha256: str
|
| 46 |
+
mask_sha256: str
|
| 47 |
+
|
| 48 |
+
def feature_hashes(self) -> dict[str, str]:
|
| 49 |
+
return {
|
| 50 |
+
"read_sha256": self.read_sha256,
|
| 51 |
+
"image_sha256": self.image_sha256,
|
| 52 |
+
"position_sha256": self.position_sha256,
|
| 53 |
+
"state_sha256": self.state_sha256,
|
| 54 |
+
"mask_sha256": self.mask_sha256,
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def materialize_runtime_observation(
|
| 59 |
+
session: RuntimeReadSession,
|
| 60 |
+
memory_buffer: Any,
|
| 61 |
+
*,
|
| 62 |
+
step: int,
|
| 63 |
+
factors: PhaseAFactors,
|
| 64 |
+
metadata_seed: int,
|
| 65 |
+
) -> RuntimePhaseAObservation:
|
| 66 |
+
"""Gather one relevant online read through the real host buffer method.
|
| 67 |
+
|
| 68 |
+
Selection counterfactuals for an evaluation cohort require a separately
|
| 69 |
+
frozen mutation plan. Until that plan is installed, this online boundary
|
| 70 |
+
accepts only the relevant selector and fails closed for the other four
|
| 71 |
+
selection modes.
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
if type(session) is not RuntimeReadSession:
|
| 75 |
+
raise RuntimeReadError("runtime host adapter requires the exact identity-bound RuntimeReadSession class")
|
| 76 |
+
preview_method = session.preview_read
|
| 77 |
+
commit_method = session.commit_read
|
| 78 |
+
if (
|
| 79 |
+
getattr(preview_method, "__func__", None) is not RuntimeReadSession.preview_read
|
| 80 |
+
or getattr(preview_method, "__self__", None) is not session
|
| 81 |
+
or getattr(commit_method, "__func__", None) is not RuntimeReadSession.commit_read
|
| 82 |
+
or getattr(commit_method, "__self__", None) is not session
|
| 83 |
+
):
|
| 84 |
+
raise RuntimeReadError("runtime host RuntimeReadSession methods were replaced")
|
| 85 |
+
if type(factors) is not PhaseAFactors:
|
| 86 |
+
raise RuntimeReadError("runtime host adapter requires the exact PhaseAFactors class")
|
| 87 |
+
if factors.manager_mode is not session.manager_mode:
|
| 88 |
+
raise RuntimeReadError(
|
| 89 |
+
"runtime Phase-A manager_mode differs from the identity-bound session"
|
| 90 |
+
)
|
| 91 |
+
if factors.selection_mode is not SelectionMode.RELEVANT:
|
| 92 |
+
raise NotImplementedError("online selection counterfactuals require a frozen rollout mutation plan")
|
| 93 |
+
if isinstance(step, bool) or not isinstance(step, (int, np.integer)) or int(step) < 0:
|
| 94 |
+
raise RuntimeReadError("runtime host step must be a non-negative integer")
|
| 95 |
+
if type(memory_buffer) is not MemoryBuffer:
|
| 96 |
+
raise RuntimeReadError("runtime host requires the exact pinned MemoryBuffer class")
|
| 97 |
+
if memory_buffer.num_views != 1:
|
| 98 |
+
raise RuntimeReadError("runtime host requires a one-view Phase-A MemoryBuffer")
|
| 99 |
+
prepare_method = memory_buffer.prepare_phase_a_frame_sampling
|
| 100 |
+
gather_method = memory_buffer.default_history_feats_gather_fn
|
| 101 |
+
if (
|
| 102 |
+
getattr(prepare_method, "__func__", None) is not MemoryBuffer.prepare_phase_a_frame_sampling
|
| 103 |
+
or getattr(prepare_method, "__self__", None) is not memory_buffer
|
| 104 |
+
or getattr(gather_method, "__func__", None) is not MemoryBuffer.default_history_feats_gather_fn
|
| 105 |
+
or getattr(gather_method, "__self__", None) is not memory_buffer
|
| 106 |
+
):
|
| 107 |
+
raise RuntimeReadError("runtime host MemoryBuffer methods were replaced")
|
| 108 |
+
|
| 109 |
+
# Session advancement is a two-phase operation. A malformed/missing host
|
| 110 |
+
# feature, dtype drift, or non-finite tensor must not consume the read step
|
| 111 |
+
# and thereby make a legitimate earlier event permanently late.
|
| 112 |
+
read = RuntimeReadSession.preview_read(session, int(step))
|
| 113 |
+
plan = materialize_phase_a_read(
|
| 114 |
+
read,
|
| 115 |
+
factors,
|
| 116 |
+
metadata_seed=metadata_seed,
|
| 117 |
+
selection_applied=SelectionMode.RELEVANT,
|
| 118 |
+
)
|
| 119 |
+
image, position, state, mask = MemoryBuffer.prepare_phase_a_frame_sampling(
|
| 120 |
+
memory_buffer,
|
| 121 |
+
int(step),
|
| 122 |
+
512,
|
| 123 |
+
plan.frame_indices,
|
| 124 |
+
plan.valid_mask,
|
| 125 |
+
plan.token_counts,
|
| 126 |
+
MemoryBuffer.default_history_feats_gather_fn.__get__(memory_buffer, MemoryBuffer),
|
| 127 |
+
)
|
| 128 |
+
tensors = tuple(np.asarray(value) for value in (image, position, state, mask))
|
| 129 |
+
expected_shapes = ((512, 2048), (512, 768), (512, 8), (512,))
|
| 130 |
+
if tuple(value.shape for value in tensors) != expected_shapes:
|
| 131 |
+
raise RuntimeReadError("runtime MemoryBuffer tensor geometry drift")
|
| 132 |
+
expected_dtypes = ("bfloat16", "float32", "float32", "bool")
|
| 133 |
+
actual_dtypes = tuple(value.dtype.name for value in tensors)
|
| 134 |
+
if actual_dtypes != expected_dtypes:
|
| 135 |
+
raise RuntimeReadError(
|
| 136 |
+
f"runtime MemoryBuffer tensor dtype drift: expected {expected_dtypes}, got {actual_dtypes}"
|
| 137 |
+
)
|
| 138 |
+
if any(not bool(np.isfinite(value).all()) for value in tensors[:3]):
|
| 139 |
+
raise RuntimeReadError("runtime MemoryBuffer tensors must be finite")
|
| 140 |
+
metadata = plan.metadata
|
| 141 |
+
if not np.array_equal(tensors[3], metadata.valid_mask):
|
| 142 |
+
raise RuntimeReadError("runtime visual and metadata token masks disagree")
|
| 143 |
+
prepared_read_sha256 = read_sha256(read)
|
| 144 |
+
feature_hashes = tuple(_array_sha256(value) for value in tensors)
|
| 145 |
+
for value in tensors:
|
| 146 |
+
value.setflags(write=False)
|
| 147 |
+
committed_read = RuntimeReadSession.commit_read(session, read)
|
| 148 |
+
committed_read_sha256 = read_sha256(committed_read)
|
| 149 |
+
if committed_read_sha256 != prepared_read_sha256:
|
| 150 |
+
raise RuntimeReadError("runtime read changed during host materialization")
|
| 151 |
+
return RuntimePhaseAObservation(
|
| 152 |
+
read=committed_read,
|
| 153 |
+
plan=plan,
|
| 154 |
+
image=tensors[0],
|
| 155 |
+
position=tensors[1],
|
| 156 |
+
state=tensors[2],
|
| 157 |
+
mask=tensors[3],
|
| 158 |
+
metadata=metadata,
|
| 159 |
+
read_sha256=committed_read_sha256,
|
| 160 |
+
image_sha256=feature_hashes[0],
|
| 161 |
+
position_sha256=feature_hashes[1],
|
| 162 |
+
state_sha256=feature_hashes[2],
|
| 163 |
+
mask_sha256=feature_hashes[3],
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def _array_sha256(value: np.ndarray) -> str:
|
| 168 |
+
array = np.ascontiguousarray(value)
|
| 169 |
+
digest = hashlib.sha256()
|
| 170 |
+
digest.update(str(array.dtype).encode("ascii"))
|
| 171 |
+
digest.update(str(array.shape).encode("ascii"))
|
| 172 |
+
digest.update(array.tobytes())
|
| 173 |
+
return digest.hexdigest()
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
__all__ = ["RuntimePhaseAObservation", "materialize_runtime_observation"]
|
checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/training/semantic_transition_reader.py
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Strict RoboMME adapter for semantic-transition training targets.
|
| 2 |
+
|
| 3 |
+
The canonical manifest and target construction live in :mod:`picmem`. This
|
| 4 |
+
small host adapter verifies one independently pinned manifest at dataset
|
| 5 |
+
startup and performs constant-time exact-key lookups for scalar training rows.
|
| 6 |
+
Manifest rows stay strict; an opt-in mixed-dataset mode emits masked neutral
|
| 7 |
+
metadata only for episode-step identities absent from the manifest.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
from numbers import Integral
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
from picmem.data.semantic_transition import TRANSITION_CONTEXT_LENGTH
|
| 17 |
+
from picmem.data.semantic_transition import TRANSITION_CONTEXT_WIDTH
|
| 18 |
+
from picmem.data.semantic_transition import TransitionRowKey
|
| 19 |
+
from picmem.data.semantic_transition import TransitionSequenceManifest
|
| 20 |
+
from picmem.data.semantic_transition import load_transition_sequence_manifest
|
| 21 |
+
|
| 22 |
+
TRANSITION_TRAINING_METADATA_FIELDS = frozenset(
|
| 23 |
+
{
|
| 24 |
+
"transition_span_target",
|
| 25 |
+
"transition_last_span_target",
|
| 26 |
+
"transition_status_valid",
|
| 27 |
+
"transition_last_span_valid",
|
| 28 |
+
"transition_context_action_delta",
|
| 29 |
+
"transition_context_state_delta",
|
| 30 |
+
"transition_context_relative_age",
|
| 31 |
+
"transition_context_valid_mask",
|
| 32 |
+
}
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class SemanticTransitionReaderError(RuntimeError):
|
| 37 |
+
"""Transition training configuration or row resolution failed closed."""
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class SemanticTransitionTrainingReader:
|
| 41 |
+
"""Load one hash-pinned manifest and resolve exact RoboMME training rows."""
|
| 42 |
+
|
| 43 |
+
__slots__ = (
|
| 44 |
+
"_allow_unlabeled_rows",
|
| 45 |
+
"_expected_sha256",
|
| 46 |
+
"_manifest",
|
| 47 |
+
"_manifest_path",
|
| 48 |
+
"_manifest_task_id_by_episode",
|
| 49 |
+
"_task_id_by_position",
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
def __init__(
|
| 53 |
+
self,
|
| 54 |
+
*,
|
| 55 |
+
manifest_path: str | Path | None,
|
| 56 |
+
expected_sha256: str | None,
|
| 57 |
+
allow_unlabeled_rows: bool = False,
|
| 58 |
+
) -> None:
|
| 59 |
+
if type(allow_unlabeled_rows) is not bool:
|
| 60 |
+
raise TypeError("allow_unlabeled_rows must be bool")
|
| 61 |
+
if manifest_path is None or (isinstance(manifest_path, str) and not manifest_path.strip()):
|
| 62 |
+
raise SemanticTransitionReaderError("enabled transition training requires a manifest path")
|
| 63 |
+
if expected_sha256 is None or not isinstance(expected_sha256, str) or not expected_sha256.strip():
|
| 64 |
+
raise SemanticTransitionReaderError(
|
| 65 |
+
"enabled transition training requires an independently supplied manifest SHA-256"
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
path = Path(manifest_path).expanduser()
|
| 69 |
+
try:
|
| 70 |
+
manifest = load_transition_sequence_manifest(path, expected_sha256=expected_sha256)
|
| 71 |
+
except (TypeError, ValueError) as exc:
|
| 72 |
+
raise SemanticTransitionReaderError(f"transition training manifest verification failed: {exc}") from exc
|
| 73 |
+
|
| 74 |
+
self._manifest_path = path
|
| 75 |
+
self._expected_sha256 = expected_sha256
|
| 76 |
+
self._manifest = manifest
|
| 77 |
+
self._allow_unlabeled_rows = allow_unlabeled_rows
|
| 78 |
+
manifest_task_id_by_episode: dict[int, str] = {}
|
| 79 |
+
for sequence in manifest.sequences:
|
| 80 |
+
episode_id = sequence.start_key.global_episode_id
|
| 81 |
+
task_id = sequence.start_key.task_id
|
| 82 |
+
existing_task_id = manifest_task_id_by_episode.setdefault(
|
| 83 |
+
episode_id,
|
| 84 |
+
task_id,
|
| 85 |
+
)
|
| 86 |
+
if existing_task_id != task_id:
|
| 87 |
+
raise SemanticTransitionReaderError(
|
| 88 |
+
"transition manifest maps one global episode to multiple task ids: "
|
| 89 |
+
f"{episode_id}"
|
| 90 |
+
)
|
| 91 |
+
self._manifest_task_id_by_episode = manifest_task_id_by_episode
|
| 92 |
+
task_id_by_position: dict[tuple[int, int], str] = {}
|
| 93 |
+
for row in manifest.training_rows():
|
| 94 |
+
position = (row.key.global_episode_id, row.key.step_idx)
|
| 95 |
+
existing_task_id = task_id_by_position.setdefault(position, row.key.task_id)
|
| 96 |
+
if existing_task_id != row.key.task_id:
|
| 97 |
+
raise SemanticTransitionReaderError(
|
| 98 |
+
"transition manifest maps one episode-step to multiple task ids: "
|
| 99 |
+
f"{position}"
|
| 100 |
+
)
|
| 101 |
+
self._task_id_by_position = task_id_by_position
|
| 102 |
+
|
| 103 |
+
def __getstate__(self) -> tuple[Path, str, bool]:
|
| 104 |
+
return self._manifest_path, self._expected_sha256, self._allow_unlabeled_rows
|
| 105 |
+
|
| 106 |
+
def __setstate__(self, state: tuple[Path, str, bool]) -> None:
|
| 107 |
+
manifest_path, expected_sha256, allow_unlabeled_rows = state
|
| 108 |
+
self.__init__(
|
| 109 |
+
manifest_path=manifest_path,
|
| 110 |
+
expected_sha256=expected_sha256,
|
| 111 |
+
allow_unlabeled_rows=allow_unlabeled_rows,
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
@property
|
| 115 |
+
def manifest_path(self) -> Path:
|
| 116 |
+
return self._manifest_path
|
| 117 |
+
|
| 118 |
+
@property
|
| 119 |
+
def expected_sha256(self) -> str:
|
| 120 |
+
return self._expected_sha256
|
| 121 |
+
|
| 122 |
+
@property
|
| 123 |
+
def manifest(self) -> TransitionSequenceManifest:
|
| 124 |
+
return self._manifest
|
| 125 |
+
|
| 126 |
+
@property
|
| 127 |
+
def allow_unlabeled_rows(self) -> bool:
|
| 128 |
+
return self._allow_unlabeled_rows
|
| 129 |
+
|
| 130 |
+
def metadata_for(
|
| 131 |
+
self,
|
| 132 |
+
*,
|
| 133 |
+
task_id: str | None,
|
| 134 |
+
global_episode_id: int,
|
| 135 |
+
step_idx: int,
|
| 136 |
+
owner_sequence_id: str | None = None,
|
| 137 |
+
) -> dict[str, np.ndarray]:
|
| 138 |
+
"""Return the complete numeric contract for one exact logical row.
|
| 139 |
+
|
| 140 |
+
Dataset adjacency is never consulted. An overlapping row must name
|
| 141 |
+
its owner sequence, and a target without its causal 48-step context is
|
| 142 |
+
rejected instead of being trained as an all-zero history.
|
| 143 |
+
"""
|
| 144 |
+
|
| 145 |
+
position = _row_position(global_episode_id, step_idx)
|
| 146 |
+
position_is_labeled = position in self._task_id_by_position
|
| 147 |
+
if task_id is None:
|
| 148 |
+
if (
|
| 149 |
+
self._allow_unlabeled_rows
|
| 150 |
+
and position[0] not in self._manifest_task_id_by_episode
|
| 151 |
+
):
|
| 152 |
+
return runtime_only_zero_transition_metadata()
|
| 153 |
+
raise SemanticTransitionReaderError(
|
| 154 |
+
f"transition training requires a manifest task id for episode {global_episode_id}"
|
| 155 |
+
)
|
| 156 |
+
key = _row_key(task_id, global_episode_id, step_idx)
|
| 157 |
+
if self._allow_unlabeled_rows and not position_is_labeled:
|
| 158 |
+
expected_task_id = self._manifest_task_id_by_episode.get(position[0])
|
| 159 |
+
if expected_task_id is not None and task_id != expected_task_id:
|
| 160 |
+
raise SemanticTransitionReaderError(
|
| 161 |
+
"transition training task id does not match manifest episode "
|
| 162 |
+
f"{global_episode_id}: expected {expected_task_id!r}, got {task_id!r}"
|
| 163 |
+
)
|
| 164 |
+
return runtime_only_zero_transition_metadata()
|
| 165 |
+
try:
|
| 166 |
+
training_row = self._manifest.row_target(key, owner_sequence_id=owner_sequence_id)
|
| 167 |
+
except KeyError as exc:
|
| 168 |
+
raise SemanticTransitionReaderError(f"transition training target is missing for exact row {key}") from exc
|
| 169 |
+
except (TypeError, ValueError) as exc:
|
| 170 |
+
raise SemanticTransitionReaderError(f"cannot resolve transition training row {key}: {exc}") from exc
|
| 171 |
+
|
| 172 |
+
if training_row.target.realized_transition_context is None:
|
| 173 |
+
raise SemanticTransitionReaderError(f"transition training context is missing for exact row {key}")
|
| 174 |
+
|
| 175 |
+
metadata = training_row.as_loader_metadata()
|
| 176 |
+
actual_fields = frozenset(metadata)
|
| 177 |
+
if actual_fields != TRANSITION_TRAINING_METADATA_FIELDS:
|
| 178 |
+
missing = sorted(TRANSITION_TRAINING_METADATA_FIELDS - actual_fields)
|
| 179 |
+
extra = sorted(actual_fields - TRANSITION_TRAINING_METADATA_FIELDS)
|
| 180 |
+
raise SemanticTransitionReaderError(
|
| 181 |
+
f"transition training metadata schema drift for exact row {key}: missing={missing}, extra={extra}"
|
| 182 |
+
)
|
| 183 |
+
return metadata
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def create_semantic_transition_training_reader(
|
| 187 |
+
*,
|
| 188 |
+
enabled: bool,
|
| 189 |
+
manifest_path: str | Path | None = None,
|
| 190 |
+
expected_sha256: str | None = None,
|
| 191 |
+
allow_unlabeled_rows: bool = False,
|
| 192 |
+
) -> SemanticTransitionTrainingReader | None:
|
| 193 |
+
"""Create the one dataset-level reader, or ``None`` when training is off."""
|
| 194 |
+
|
| 195 |
+
if type(enabled) is not bool:
|
| 196 |
+
raise TypeError("enabled must be bool")
|
| 197 |
+
if not enabled:
|
| 198 |
+
return None
|
| 199 |
+
return SemanticTransitionTrainingReader(
|
| 200 |
+
manifest_path=manifest_path,
|
| 201 |
+
expected_sha256=expected_sha256,
|
| 202 |
+
allow_unlabeled_rows=allow_unlabeled_rows,
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def runtime_only_zero_transition_metadata() -> dict[str, np.ndarray]:
|
| 207 |
+
"""Return neutral fields for inference or explicitly masked training rows.
|
| 208 |
+
|
| 209 |
+
The legacy name is retained for existing callers. Strict training never
|
| 210 |
+
falls back to these values; the mixed reader uses them only for positions
|
| 211 |
+
absent from the manifest, with both supervision-valid flags false.
|
| 212 |
+
"""
|
| 213 |
+
|
| 214 |
+
return {
|
| 215 |
+
"transition_span_target": np.asarray(0.0, dtype=np.float32),
|
| 216 |
+
"transition_last_span_target": np.asarray(0.0, dtype=np.float32),
|
| 217 |
+
"transition_status_valid": np.zeros((), dtype=np.bool_),
|
| 218 |
+
"transition_last_span_valid": np.zeros((), dtype=np.bool_),
|
| 219 |
+
"transition_context_action_delta": np.zeros(
|
| 220 |
+
(TRANSITION_CONTEXT_LENGTH, TRANSITION_CONTEXT_WIDTH),
|
| 221 |
+
dtype=np.float32,
|
| 222 |
+
),
|
| 223 |
+
"transition_context_state_delta": np.zeros(
|
| 224 |
+
(TRANSITION_CONTEXT_LENGTH, TRANSITION_CONTEXT_WIDTH),
|
| 225 |
+
dtype=np.float32,
|
| 226 |
+
),
|
| 227 |
+
"transition_context_relative_age": np.zeros(TRANSITION_CONTEXT_LENGTH, dtype=np.float32),
|
| 228 |
+
"transition_context_valid_mask": np.zeros(TRANSITION_CONTEXT_LENGTH, dtype=np.bool_),
|
| 229 |
+
}
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def _row_key(task_id: str, global_episode_id: int, step_idx: int) -> TransitionRowKey:
|
| 233 |
+
episode, step = _row_position(global_episode_id, step_idx)
|
| 234 |
+
try:
|
| 235 |
+
return TransitionRowKey(task_id, episode, step)
|
| 236 |
+
except (TypeError, ValueError) as exc:
|
| 237 |
+
raise SemanticTransitionReaderError(f"invalid exact transition row key: {exc}") from exc
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def _row_position(global_episode_id: int, step_idx: int) -> tuple[int, int]:
|
| 241 |
+
if isinstance(global_episode_id, bool) or not isinstance(global_episode_id, Integral):
|
| 242 |
+
raise SemanticTransitionReaderError("global_episode_id must be a non-negative integer")
|
| 243 |
+
if isinstance(step_idx, bool) or not isinstance(step_idx, Integral):
|
| 244 |
+
raise SemanticTransitionReaderError("step_idx must be a non-negative integer")
|
| 245 |
+
episode = int(global_episode_id)
|
| 246 |
+
step = int(step_idx)
|
| 247 |
+
if episode < 0 or step < 0:
|
| 248 |
+
raise SemanticTransitionReaderError(
|
| 249 |
+
"global_episode_id and step_idx must be non-negative"
|
| 250 |
+
)
|
| 251 |
+
return episode, step
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
__all__ = [
|
| 255 |
+
"TRANSITION_TRAINING_METADATA_FIELDS",
|
| 256 |
+
"SemanticTransitionReaderError",
|
| 257 |
+
"SemanticTransitionTrainingReader",
|
| 258 |
+
"create_semantic_transition_training_reader",
|
| 259 |
+
"runtime_only_zero_transition_metadata",
|
| 260 |
+
]
|
checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/transition_status_manifest.json
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema_version": "picmem_robomme_transition_status_overlay_v1",
|
| 3 |
+
"overlay_id": "transition_status_v1",
|
| 4 |
+
"copied_files": [
|
| 5 |
+
{
|
| 6 |
+
"path": "src/mme_vla_suite/models/config/robomme/perceptual-picmem-transition-v1-modul.yaml",
|
| 7 |
+
"preimage_sha256": null,
|
| 8 |
+
"postimage_sha256": "0691f21107e9746131d7ecefd380a1238b8beeeeee758da0ec440a5d97296827"
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"path": "src/mme_vla_suite/models/representation/transition_status.py",
|
| 12 |
+
"preimage_sha256": null,
|
| 13 |
+
"postimage_sha256": "f2820eb900e8b8badee27b0dabb8d09625b1a35ad96997d56de76ea26662f7e4"
|
| 14 |
+
},
|
| 15 |
+
{
|
| 16 |
+
"path": "src/mme_vla_suite/policies/semantic_transition_runtime.py",
|
| 17 |
+
"preimage_sha256": null,
|
| 18 |
+
"postimage_sha256": "6945725b52b4a4a11b6cea748378fcac0ef502fece1632800794d35025126df6"
|
| 19 |
+
},
|
| 20 |
+
{
|
| 21 |
+
"path": "src/mme_vla_suite/training/semantic_transition_reader.py",
|
| 22 |
+
"preimage_sha256": null,
|
| 23 |
+
"postimage_sha256": "232977ebfc6ebe948f22f62f917bf73a47c0e811fc26c44c9d403a13f37b198e"
|
| 24 |
+
}
|
| 25 |
+
],
|
| 26 |
+
"host_patch": {
|
| 27 |
+
"path": "patches/transition_status_v1_host.patch",
|
| 28 |
+
"sha256": "a1f9042f777aabe1d720a6e7e5fa9774d77de2231cc770ce939eefc308479a70",
|
| 29 |
+
"files": [
|
| 30 |
+
{
|
| 31 |
+
"path": "examples/robomme/eval.py",
|
| 32 |
+
"preimage_sha256": "2b51b942af18f7a3412814b66eca67a0fc4ff374794bceac5f44d87e1e367c41",
|
| 33 |
+
"postimage_sha256": "3c47df922604feb58e90200249762bd74f3bdba04131f1b81aa6d0b6349d354e"
|
| 34 |
+
},
|
| 35 |
+
{
|
| 36 |
+
"path": "src/mme_vla_suite/models/integration/history_observation.py",
|
| 37 |
+
"preimage_sha256": "e510f75496770d418d770f3e2a56f6ddc9d972a5ff68b6cd14b7a15665ec39a8",
|
| 38 |
+
"postimage_sha256": "dedfd82ff19a83395f721c4bb8ed1c3b4600c9e3d234d6deaced8895f452d4e3"
|
| 39 |
+
},
|
| 40 |
+
{
|
| 41 |
+
"path": "src/mme_vla_suite/models/integration/history_pi0.py",
|
| 42 |
+
"preimage_sha256": "9192bfc229ac1386a3d36835c6d1e220617431d44b462016b062bc3df07a337f",
|
| 43 |
+
"postimage_sha256": "b5c5d055bd923e02b3381b1da6007b75393fdf13fbd5dfdc9c85e82bb9852638"
|
| 44 |
+
},
|
| 45 |
+
{
|
| 46 |
+
"path": "src/mme_vla_suite/policies/policy.py",
|
| 47 |
+
"preimage_sha256": "dc31fce752172e1861de4840445b6c300dfa2a675a797dedbee1b108f7f4e20d",
|
| 48 |
+
"postimage_sha256": "85552f440e644ab31c63fa8ddcb856522085a7e414fbacd87eff0ef89e9ba2a5"
|
| 49 |
+
},
|
| 50 |
+
{
|
| 51 |
+
"path": "src/mme_vla_suite/policies/robomme_policy.py",
|
| 52 |
+
"preimage_sha256": "78dbf3393bac91a16096d02b17239ca0e14c38be7ce32042d88f96b1e89e35e2",
|
| 53 |
+
"postimage_sha256": "9cfe10577679189f2b3af345d41c7b40625cb0aef1b2b7077107b532565826cf"
|
| 54 |
+
},
|
| 55 |
+
{
|
| 56 |
+
"path": "src/mme_vla_suite/training/config.py",
|
| 57 |
+
"preimage_sha256": "47041573dae2c48b99b56035763f4fd611f6cc5395e7875849dd6017227ce247",
|
| 58 |
+
"postimage_sha256": "152334f30e20ea529dffe7932fe5575a5c4a11f4f1514fb56718272d9d5ef6c2"
|
| 59 |
+
},
|
| 60 |
+
{
|
| 61 |
+
"path": "src/mme_vla_suite/training/dataset.py",
|
| 62 |
+
"preimage_sha256": "62f867c89b0073f484ba15ff1e3a5f5554ec520bcae00b06cdcff3f19fbf0d3b",
|
| 63 |
+
"postimage_sha256": "db08b26dd964aed7da69f0fc02ed064b688c453777277a274614dd1f0dcbb34a"
|
| 64 |
+
}
|
| 65 |
+
]
|
| 66 |
+
}
|
| 67 |
+
}
|
checkpoints/r2/shuffle/baseline/step9000/code/pyproject.toml
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[build-system]
|
| 2 |
+
requires = ["hatchling"]
|
| 3 |
+
build-backend = "hatchling.build"
|
| 4 |
+
|
| 5 |
+
[project]
|
| 6 |
+
name = "picmem-dev"
|
| 7 |
+
version = "0.2.0"
|
| 8 |
+
description = "Bounded contract memory for long-horizon robot policies"
|
| 9 |
+
readme = "README.md"
|
| 10 |
+
requires-python = ">=3.10,<3.14"
|
| 11 |
+
license = { file = "LICENSE" }
|
| 12 |
+
dependencies = [
|
| 13 |
+
"cryptography==45.0.7",
|
| 14 |
+
"numpy>=1.26",
|
| 15 |
+
]
|
| 16 |
+
|
| 17 |
+
[project.optional-dependencies]
|
| 18 |
+
hdf5 = ["h5py>=3.13"]
|
| 19 |
+
lerobot = ["polars>=1.30"]
|
| 20 |
+
semantic-annotation = [
|
| 21 |
+
"h5py>=3.13",
|
| 22 |
+
"openai>=2,<3",
|
| 23 |
+
"Pillow>=10.4",
|
| 24 |
+
"polars>=1.30",
|
| 25 |
+
]
|
| 26 |
+
model = [
|
| 27 |
+
"flax==0.10.2",
|
| 28 |
+
"jax==0.5.3",
|
| 29 |
+
"jaxtyping==0.2.36",
|
| 30 |
+
]
|
| 31 |
+
counterfactual = ["jax==0.5.3"]
|
| 32 |
+
samplers = ["torch>=2.8,<2.9"]
|
| 33 |
+
training = [
|
| 34 |
+
"jax==0.5.3",
|
| 35 |
+
"torch>=2.8,<2.9",
|
| 36 |
+
]
|
| 37 |
+
dev = [
|
| 38 |
+
"flax==0.10.2",
|
| 39 |
+
"h5py>=3.13",
|
| 40 |
+
"jax==0.5.3",
|
| 41 |
+
"jaxtyping==0.2.36",
|
| 42 |
+
"omegaconf>=2.3",
|
| 43 |
+
"polars>=1.30",
|
| 44 |
+
"pytest>=8.3",
|
| 45 |
+
"ruff>=0.8",
|
| 46 |
+
"torch>=2.8,<2.9",
|
| 47 |
+
]
|
| 48 |
+
|
| 49 |
+
[project.scripts]
|
| 50 |
+
picmem-audit = "picmem.cli.audit:main"
|
| 51 |
+
picmem-crosswalk-receipt = "picmem.cli.crosswalk_receipt:main"
|
| 52 |
+
picmem-dense-caption = "picmem.cli.dense_caption_v7:main"
|
| 53 |
+
picmem-dense-caption-all = "picmem.cli.dense_caption_v7_all:main"
|
| 54 |
+
picmem-semantic-annotate = "picmem.cli.semantic_annotate:main"
|
| 55 |
+
picmem-semantic-calibration = "picmem.cli.semantic_calibration:main"
|
| 56 |
+
picmem-stage1-archive = "picmem.cli.stage1_archive:main"
|
| 57 |
+
picmem-stage1-refine = "picmem.cli.stage1_refine:main"
|
| 58 |
+
picmem-stage2-task-semantics = "picmem.cli.stage2_task_semantics_v7:main"
|
| 59 |
+
picmem-stage3-temporal-mapping = "picmem.cli.stage3_temporal_mapping:main"
|
| 60 |
+
picmem-stage4-semantic-memory = "picmem.cli.stage4_semantic_memory:main"
|
| 61 |
+
picmem-vllm-server = "picmem.cli.vllm_server:main"
|
| 62 |
+
picmem-admit = "picmem.ops.admission:main"
|
| 63 |
+
picmem-amlt = "picmem.ops.amlt:main"
|
| 64 |
+
picmem-cadence = "picmem.ops.cadence:main"
|
| 65 |
+
picmem-checkpoint = "picmem.ops.checkpoint:main"
|
| 66 |
+
picmem-formal-runtime = "picmem.ops.formal_runtime:main"
|
| 67 |
+
picmem-ledger = "picmem.ops.scheduler:main"
|
| 68 |
+
picmem-registry = "picmem.ops.registry:main"
|
| 69 |
+
picmem-runtime-profile = "picmem.ops.runtime_profiles:main"
|
| 70 |
+
picmem-run084-order = "picmem.sampling.run084_sample_order:main"
|
| 71 |
+
picmem-sku-smoke-evidence = "picmem.ops.sku_smoke_evidence:main"
|
| 72 |
+
picmem-submit = "picmem.ops.submit:main"
|
| 73 |
+
picmem-supervisor = "picmem.ops.supervisor:main"
|
| 74 |
+
picmem-uv-cache = "picmem.ops.uv_cache:main"
|
| 75 |
+
picmem-watchdog = "picmem.ops.watchdog:main"
|
| 76 |
+
|
| 77 |
+
[tool.hatch.build.targets.wheel]
|
| 78 |
+
packages = ["src/picmem"]
|
| 79 |
+
|
| 80 |
+
[tool.pytest.ini_options]
|
| 81 |
+
testpaths = ["tests"]
|
| 82 |
+
pythonpath = ["src", "."]
|
| 83 |
+
|
| 84 |
+
[tool.ruff]
|
| 85 |
+
line-length = 120
|
| 86 |
+
target-version = "py310"
|
| 87 |
+
# robomme/ is the vendored upstream RoboMME workspace, carried here so an
|
| 88 |
+
# experiment needs no second checkout. It ships its own ruff configuration and
|
| 89 |
+
# its own style history; linting it under PIC-Mem's rules would report ~1.5k
|
| 90 |
+
# pre-existing upstream findings that nobody here is entitled to "fix".
|
| 91 |
+
extend-exclude = ["robomme"]
|
| 92 |
+
|
| 93 |
+
[tool.ruff.lint]
|
| 94 |
+
select = ["B", "E", "F", "I", "RUF", "SIM", "UP"]
|
| 95 |
+
ignore = ["F722"]
|
| 96 |
+
|
| 97 |
+
# These two files are hash-pinned mirrors of the upstream RoboMME host. Keep
|
| 98 |
+
# its existing style debt isolated here instead of reformatting the reviewed
|
| 99 |
+
# overlay preimages; all PIC-Mem additions and the rest of the repository stay
|
| 100 |
+
# under the normal rule set.
|
| 101 |
+
[tool.ruff.lint.per-file-ignores]
|
| 102 |
+
"integrations/robomme/src/mme_vla_suite/shared/mem_buffer.py" = [
|
| 103 |
+
"E401",
|
| 104 |
+
"E501",
|
| 105 |
+
"F403",
|
| 106 |
+
"F405",
|
| 107 |
+
"F541",
|
| 108 |
+
"I001",
|
| 109 |
+
"SIM108",
|
| 110 |
+
"UP035",
|
| 111 |
+
]
|
| 112 |
+
"integrations/robomme/src/mme_vla_suite/training/dataset.py" = [
|
| 113 |
+
"B905",
|
| 114 |
+
"E501",
|
| 115 |
+
"RUF013",
|
| 116 |
+
"RUF046",
|
| 117 |
+
"SIM115",
|
| 118 |
+
]
|
| 119 |
+
|
| 120 |
+
# The reviewed AzureML image is CUDA 12.6, so torch must come from the matching
|
| 121 |
+
# PyTorch index instead of the PyPI default, which publishes a cu128 build.
|
| 122 |
+
[[tool.uv.index]]
|
| 123 |
+
name = "pytorch-cu126"
|
| 124 |
+
url = "https://download.pytorch.org/whl/cu126"
|
| 125 |
+
explicit = true
|
| 126 |
+
|
| 127 |
+
[tool.uv.sources]
|
| 128 |
+
torch = { index = "pytorch-cu126" }
|
checkpoints/r2/shuffle/baseline/step9000/code/robomme/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Apache License
|
| 2 |
+
Version 2.0, January 2004
|
| 3 |
+
http://www.apache.org/licenses/
|
| 4 |
+
|
| 5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 6 |
+
|
| 7 |
+
1. Definitions.
|
| 8 |
+
|
| 9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 11 |
+
|
| 12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 13 |
+
the copyright owner that is granting the License.
|
| 14 |
+
|
| 15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 16 |
+
other entities that control, are controlled by, or are under common
|
| 17 |
+
control with that entity. For the purposes of this definition,
|
| 18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 19 |
+
direction or management of such entity, whether by contract or
|
| 20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 22 |
+
|
| 23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 24 |
+
exercising permissions granted by this License.
|
| 25 |
+
|
| 26 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 27 |
+
including but not limited to software source code, documentation
|
| 28 |
+
source, and configuration files.
|
| 29 |
+
|
| 30 |
+
"Object" form shall mean any form resulting from mechanical
|
| 31 |
+
transformation or translation of a Source form, including but
|
| 32 |
+
not limited to compiled object code, generated documentation,
|
| 33 |
+
and conversions to other media types.
|
| 34 |
+
|
| 35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 36 |
+
Object form, made available under the License, as indicated by a
|
| 37 |
+
copyright notice that is included in or attached to the work
|
| 38 |
+
(an example is provided in the Appendix below).
|
| 39 |
+
|
| 40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 41 |
+
form, that is based on (or derived from) the Work and for which the
|
| 42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 44 |
+
of this License, Derivative Works shall not include works that remain
|
| 45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 46 |
+
the Work and Derivative Works thereof.
|
| 47 |
+
|
| 48 |
+
"Contribution" shall mean any work of authorship, including
|
| 49 |
+
the original version of the Work and any modifications or additions
|
| 50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 54 |
+
means any form of electronic, verbal, or written communication sent
|
| 55 |
+
to the Licensor or its representatives, including but not limited to
|
| 56 |
+
communication on electronic mailing lists, source code control systems,
|
| 57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 59 |
+
excluding communication that is conspicuously marked or otherwise
|
| 60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 61 |
+
|
| 62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 64 |
+
subsequently incorporated within the Work.
|
| 65 |
+
|
| 66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 71 |
+
Work and such Derivative Works in Source or Object form.
|
| 72 |
+
|
| 73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 76 |
+
(except as stated in this section) patent license to make, have made,
|
| 77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 78 |
+
where such license applies only to those patent claims licensable
|
| 79 |
+
by such Contributor that are necessarily infringed by their
|
| 80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 82 |
+
institute patent litigation against any entity (including a
|
| 83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 84 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 85 |
+
or contributory patent infringement, then any patent licenses
|
| 86 |
+
granted to You under this License for that Work shall terminate
|
| 87 |
+
as of the date such litigation is filed.
|
| 88 |
+
|
| 89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 90 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 91 |
+
modifications, and in Source or Object form, provided that You
|
| 92 |
+
meet the following conditions:
|
| 93 |
+
|
| 94 |
+
(a) You must give any other recipients of the Work or
|
| 95 |
+
Derivative Works a copy of this License; and
|
| 96 |
+
|
| 97 |
+
(b) You must cause any modified files to carry prominent notices
|
| 98 |
+
stating that You changed the files; and
|
| 99 |
+
|
| 100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 101 |
+
that You distribute, all copyright, patent, trademark, and
|
| 102 |
+
attribution notices from the Source form of the Work,
|
| 103 |
+
excluding those notices that do not pertain to any part of
|
| 104 |
+
the Derivative Works; and
|
| 105 |
+
|
| 106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 107 |
+
distribution, then any Derivative Works that You distribute must
|
| 108 |
+
include a readable copy of the attribution notices contained
|
| 109 |
+
within such NOTICE file, excluding those notices that do not
|
| 110 |
+
pertain to any part of the Derivative Works, in at least one
|
| 111 |
+
of the following places: within a NOTICE text file distributed
|
| 112 |
+
as part of the Derivative Works; within the Source form or
|
| 113 |
+
documentation, if provided along with the Derivative Works; or,
|
| 114 |
+
within a display generated by the Derivative Works, if and
|
| 115 |
+
wherever such third-party notices normally appear. The contents
|
| 116 |
+
of the NOTICE file are for informational purposes only and
|
| 117 |
+
do not modify the License. You may add Your own attribution
|
| 118 |
+
notices within Derivative Works that You distribute, alongside
|
| 119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 120 |
+
that such additional attribution notices cannot be construed
|
| 121 |
+
as modifying the License.
|
| 122 |
+
|
| 123 |
+
You may add Your own copyright statement to Your modifications and
|
| 124 |
+
may provide additional or different license terms and conditions
|
| 125 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 126 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 127 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 128 |
+
the conditions stated in this License.
|
| 129 |
+
|
| 130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 132 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 133 |
+
this License, without any additional terms or conditions.
|
| 134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 135 |
+
the terms of any separate license agreement you may have executed
|
| 136 |
+
with Licensor regarding such Contributions.
|
| 137 |
+
|
| 138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 140 |
+
except as required for reasonable and customary use in describing the
|
| 141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 142 |
+
|
| 143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 144 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 147 |
+
implied, including, without limitation, any warranties or conditions
|
| 148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 150 |
+
appropriateness of using or redistributing the Work and assume any
|
| 151 |
+
risks associated with Your exercise of permissions under this License.
|
| 152 |
+
|
| 153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 154 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 155 |
+
unless required by applicable law (such as deliberate and grossly
|
| 156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 157 |
+
liable to You for damages, including any direct, indirect, special,
|
| 158 |
+
incidental, or consequential damages of any character arising as a
|
| 159 |
+
result of this License or out of the use or inability to use the
|
| 160 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 161 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 162 |
+
other commercial damages or losses), even if such Contributor
|
| 163 |
+
has been advised of the possibility of such damages.
|
| 164 |
+
|
| 165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 168 |
+
or other liability obligations and/or rights consistent with this
|
| 169 |
+
License. However, in accepting such obligations, You may act only
|
| 170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 171 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 172 |
+
defend, and hold each Contributor harmless for any liability
|
| 173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 174 |
+
of your accepting any such warranty or additional liability.
|
| 175 |
+
|
| 176 |
+
END OF TERMS AND CONDITIONS
|
| 177 |
+
|
| 178 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 179 |
+
|
| 180 |
+
To apply the Apache License to your work, attach the following
|
| 181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 182 |
+
replaced with your own identifying information. (Don't include
|
| 183 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 184 |
+
comment syntax for the file format. We also recommend that a
|
| 185 |
+
file or class name and description of purpose be included on the
|
| 186 |
+
same "printed page" as the copyright notice for easier
|
| 187 |
+
identification within third-party archives.
|
| 188 |
+
|
| 189 |
+
Copyright [yyyy] [name of copyright owner]
|
| 190 |
+
|
| 191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 192 |
+
you may not use this file except in compliance with the License.
|
| 193 |
+
You may obtain a copy of the License at
|
| 194 |
+
|
| 195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 196 |
+
|
| 197 |
+
Unless required by applicable law or agreed to in writing, software
|
| 198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 200 |
+
See the License for the specific language governing permissions and
|
| 201 |
+
limitations under the License.
|
checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
__version__ = "0.1.0"
|
checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/action_chunk_broker.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Dict
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import tree
|
| 5 |
+
from typing_extensions import override
|
| 6 |
+
|
| 7 |
+
from openpi_client import base_policy as _base_policy
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class ActionChunkBroker(_base_policy.BasePolicy):
|
| 11 |
+
"""Wraps a policy to return action chunks one-at-a-time.
|
| 12 |
+
|
| 13 |
+
Assumes that the first dimension of all action fields is the chunk size.
|
| 14 |
+
|
| 15 |
+
A new inference call to the inner policy is only made when the current
|
| 16 |
+
list of chunks is exhausted.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
def __init__(self, policy: _base_policy.BasePolicy, action_horizon: int):
|
| 20 |
+
self._policy = policy
|
| 21 |
+
self._action_horizon = action_horizon
|
| 22 |
+
self._cur_step: int = 0
|
| 23 |
+
|
| 24 |
+
self._last_results: Dict[str, np.ndarray] | None = None
|
| 25 |
+
|
| 26 |
+
@override
|
| 27 |
+
def infer(self, obs: Dict) -> Dict: # noqa: UP006
|
| 28 |
+
if self._last_results is None:
|
| 29 |
+
self._last_results = self._policy.infer(obs)
|
| 30 |
+
self._cur_step = 0
|
| 31 |
+
|
| 32 |
+
def slicer(x):
|
| 33 |
+
if isinstance(x, np.ndarray):
|
| 34 |
+
return x[self._cur_step, ...]
|
| 35 |
+
else:
|
| 36 |
+
return x
|
| 37 |
+
|
| 38 |
+
results = tree.map_structure(slicer, self._last_results)
|
| 39 |
+
self._cur_step += 1
|
| 40 |
+
|
| 41 |
+
if self._cur_step >= self._action_horizon:
|
| 42 |
+
self._last_results = None
|
| 43 |
+
|
| 44 |
+
return results
|
| 45 |
+
|
| 46 |
+
@override
|
| 47 |
+
def reset(self) -> None:
|
| 48 |
+
self._policy.reset()
|
| 49 |
+
self._last_results = None
|
| 50 |
+
self._cur_step = 0
|
checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/base_policy.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import abc
|
| 2 |
+
from typing import Dict
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class BasePolicy(abc.ABC):
|
| 6 |
+
@abc.abstractmethod
|
| 7 |
+
def infer(self, obs: Dict) -> Dict:
|
| 8 |
+
"""Infer actions from observations."""
|
| 9 |
+
|
| 10 |
+
def reset(self) -> None:
|
| 11 |
+
"""Reset the policy to its initial state."""
|
| 12 |
+
pass
|
checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/image_tools.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from PIL import Image
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def convert_to_uint8(img: np.ndarray) -> np.ndarray:
|
| 6 |
+
"""Converts an image to uint8 if it is a float image.
|
| 7 |
+
|
| 8 |
+
This is important for reducing the size of the image when sending it over the network.
|
| 9 |
+
"""
|
| 10 |
+
if np.issubdtype(img.dtype, np.floating):
|
| 11 |
+
img = (255 * img).astype(np.uint8)
|
| 12 |
+
return img
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def resize_with_pad(images: np.ndarray, height: int, width: int, method=Image.BILINEAR) -> np.ndarray:
|
| 16 |
+
"""Replicates tf.image.resize_with_pad for multiple images using PIL. Resizes a batch of images to a target height.
|
| 17 |
+
|
| 18 |
+
Args:
|
| 19 |
+
images: A batch of images in [..., height, width, channel] format.
|
| 20 |
+
height: The target height of the image.
|
| 21 |
+
width: The target width of the image.
|
| 22 |
+
method: The interpolation method to use. Default is bilinear.
|
| 23 |
+
|
| 24 |
+
Returns:
|
| 25 |
+
The resized images in [..., height, width, channel].
|
| 26 |
+
"""
|
| 27 |
+
# If the images are already the correct size, return them as is.
|
| 28 |
+
if images.shape[-3:-1] == (height, width):
|
| 29 |
+
return images
|
| 30 |
+
|
| 31 |
+
original_shape = images.shape
|
| 32 |
+
|
| 33 |
+
images = images.reshape(-1, *original_shape[-3:])
|
| 34 |
+
resized = np.stack([_resize_with_pad_pil(Image.fromarray(im), height, width, method=method) for im in images])
|
| 35 |
+
return resized.reshape(*original_shape[:-3], *resized.shape[-3:])
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _resize_with_pad_pil(image: Image.Image, height: int, width: int, method: int) -> Image.Image:
|
| 39 |
+
"""Replicates tf.image.resize_with_pad for one image using PIL. Resizes an image to a target height and
|
| 40 |
+
width without distortion by padding with zeros.
|
| 41 |
+
|
| 42 |
+
Unlike the jax version, note that PIL uses [width, height, channel] ordering instead of [batch, h, w, c].
|
| 43 |
+
"""
|
| 44 |
+
cur_width, cur_height = image.size
|
| 45 |
+
if cur_width == width and cur_height == height:
|
| 46 |
+
return image # No need to resize if the image is already the correct size.
|
| 47 |
+
|
| 48 |
+
ratio = max(cur_width / width, cur_height / height)
|
| 49 |
+
resized_height = int(cur_height / ratio)
|
| 50 |
+
resized_width = int(cur_width / ratio)
|
| 51 |
+
resized_image = image.resize((resized_width, resized_height), resample=method)
|
| 52 |
+
|
| 53 |
+
zero_image = Image.new(resized_image.mode, (width, height), 0)
|
| 54 |
+
pad_height = max(0, int((height - resized_height) / 2))
|
| 55 |
+
pad_width = max(0, int((width - resized_width) / 2))
|
| 56 |
+
zero_image.paste(resized_image, (pad_width, pad_height))
|
| 57 |
+
assert zero_image.size == (width, height)
|
| 58 |
+
return zero_image
|
checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/image_tools_test.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
import openpi_client.image_tools as image_tools
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def test_resize_with_pad_shapes():
|
| 7 |
+
# Test case 1: Resize image with larger dimensions
|
| 8 |
+
images = np.zeros((2, 10, 10, 3), dtype=np.uint8) # Input images of shape (batch_size, height, width, channels)
|
| 9 |
+
height = 20
|
| 10 |
+
width = 20
|
| 11 |
+
resized_images = image_tools.resize_with_pad(images, height, width)
|
| 12 |
+
assert resized_images.shape == (2, height, width, 3)
|
| 13 |
+
assert np.all(resized_images == 0)
|
| 14 |
+
|
| 15 |
+
# Test case 2: Resize image with smaller dimensions
|
| 16 |
+
images = np.zeros((3, 30, 30, 3), dtype=np.uint8)
|
| 17 |
+
height = 15
|
| 18 |
+
width = 15
|
| 19 |
+
resized_images = image_tools.resize_with_pad(images, height, width)
|
| 20 |
+
assert resized_images.shape == (3, height, width, 3)
|
| 21 |
+
assert np.all(resized_images == 0)
|
| 22 |
+
|
| 23 |
+
# Test case 3: Resize image with the same dimensions
|
| 24 |
+
images = np.zeros((1, 50, 50, 3), dtype=np.uint8)
|
| 25 |
+
height = 50
|
| 26 |
+
width = 50
|
| 27 |
+
resized_images = image_tools.resize_with_pad(images, height, width)
|
| 28 |
+
assert resized_images.shape == (1, height, width, 3)
|
| 29 |
+
assert np.all(resized_images == 0)
|
| 30 |
+
|
| 31 |
+
# Test case 3: Resize image with odd-numbered padding
|
| 32 |
+
images = np.zeros((1, 256, 320, 3), dtype=np.uint8)
|
| 33 |
+
height = 60
|
| 34 |
+
width = 80
|
| 35 |
+
resized_images = image_tools.resize_with_pad(images, height, width)
|
| 36 |
+
assert resized_images.shape == (1, height, width, 3)
|
| 37 |
+
assert np.all(resized_images == 0)
|
checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/msgpack_numpy.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Adds NumPy array support to msgpack.
|
| 2 |
+
|
| 3 |
+
msgpack is good for (de)serializing data over a network for multiple reasons:
|
| 4 |
+
- msgpack is secure (as opposed to pickle/dill/etc which allow for arbitrary code execution)
|
| 5 |
+
- msgpack is widely used and has good cross-language support
|
| 6 |
+
- msgpack does not require a schema (as opposed to protobuf/flatbuffers/etc) which is convenient in dynamically typed
|
| 7 |
+
languages like Python and JavaScript
|
| 8 |
+
- msgpack is fast and efficient (as opposed to readable formats like JSON/YAML/etc); I found that msgpack was ~4x faster
|
| 9 |
+
than pickle for serializing large arrays using the below strategy
|
| 10 |
+
|
| 11 |
+
The code below is adapted from https://github.com/lebedov/msgpack-numpy. The reason not to use that library directly is
|
| 12 |
+
that it falls back to pickle for object arrays.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import functools
|
| 16 |
+
|
| 17 |
+
import msgpack
|
| 18 |
+
import numpy as np
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def pack_array(obj):
|
| 22 |
+
if (isinstance(obj, (np.ndarray, np.generic))) and obj.dtype.kind in ("V", "O", "c"):
|
| 23 |
+
raise ValueError(f"Unsupported dtype: {obj.dtype}")
|
| 24 |
+
|
| 25 |
+
if isinstance(obj, np.ndarray):
|
| 26 |
+
return {
|
| 27 |
+
b"__ndarray__": True,
|
| 28 |
+
b"data": obj.tobytes(),
|
| 29 |
+
b"dtype": obj.dtype.str,
|
| 30 |
+
b"shape": obj.shape,
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
if isinstance(obj, np.generic):
|
| 34 |
+
return {
|
| 35 |
+
b"__npgeneric__": True,
|
| 36 |
+
b"data": obj.item(),
|
| 37 |
+
b"dtype": obj.dtype.str,
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
return obj
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def unpack_array(obj):
|
| 44 |
+
if b"__ndarray__" in obj:
|
| 45 |
+
return np.ndarray(buffer=obj[b"data"], dtype=np.dtype(obj[b"dtype"]), shape=obj[b"shape"])
|
| 46 |
+
|
| 47 |
+
if b"__npgeneric__" in obj:
|
| 48 |
+
return np.dtype(obj[b"dtype"]).type(obj[b"data"])
|
| 49 |
+
|
| 50 |
+
return obj
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
Packer = functools.partial(msgpack.Packer, default=pack_array)
|
| 54 |
+
packb = functools.partial(msgpack.packb, default=pack_array)
|
| 55 |
+
|
| 56 |
+
Unpacker = functools.partial(msgpack.Unpacker, object_hook=unpack_array)
|
| 57 |
+
unpackb = functools.partial(msgpack.unpackb, object_hook=unpack_array)
|
checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/msgpack_numpy_test.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
import tree
|
| 4 |
+
|
| 5 |
+
from openpi_client import msgpack_numpy
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def _check(expected, actual):
|
| 9 |
+
if isinstance(expected, np.ndarray):
|
| 10 |
+
assert expected.shape == actual.shape
|
| 11 |
+
assert expected.dtype == actual.dtype
|
| 12 |
+
assert np.array_equal(expected, actual, equal_nan=expected.dtype.kind == "f")
|
| 13 |
+
else:
|
| 14 |
+
assert expected == actual
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@pytest.mark.parametrize(
|
| 18 |
+
"data",
|
| 19 |
+
[
|
| 20 |
+
1, # int
|
| 21 |
+
1.0, # float
|
| 22 |
+
"hello", # string
|
| 23 |
+
np.bool_(True), # boolean scalar
|
| 24 |
+
np.array([1, 2, 3])[0], # int scalar
|
| 25 |
+
np.str_("asdf"), # string scalar
|
| 26 |
+
[1, 2, 3], # list
|
| 27 |
+
{"key": "value"}, # dict
|
| 28 |
+
{"key": [1, 2, 3]}, # nested dict
|
| 29 |
+
np.array(1.0), # 0D array
|
| 30 |
+
np.array([1, 2, 3], dtype=np.int32), # 1D integer array
|
| 31 |
+
np.array(["asdf", "qwer"]), # string array
|
| 32 |
+
np.array([True, False]), # boolean array
|
| 33 |
+
np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32), # 2D float array
|
| 34 |
+
np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]], dtype=np.int16), # 3D integer array
|
| 35 |
+
np.array([np.nan, np.inf, -np.inf]), # special float values
|
| 36 |
+
{"arr": np.array([1, 2, 3]), "nested": {"arr": np.array([4, 5, 6])}}, # nested dict with arrays
|
| 37 |
+
[np.array([1, 2]), np.array([3, 4])], # list of arrays
|
| 38 |
+
np.zeros((3, 4, 5), dtype=np.float32), # 3D zeros
|
| 39 |
+
np.ones((2, 3), dtype=np.float64), # 2D ones with double precision
|
| 40 |
+
],
|
| 41 |
+
)
|
| 42 |
+
def test_pack_unpack(data):
|
| 43 |
+
packed = msgpack_numpy.packb(data)
|
| 44 |
+
unpacked = msgpack_numpy.unpackb(packed)
|
| 45 |
+
tree.map_structure(_check, data, unpacked)
|