souglad21 commited on
Commit
d8a2faa
·
verified ·
1 Parent(s): 7f0ff60

Add files using upload-large-folder tool

Browse files
Files changed (50) hide show
  1. real_inference/README.md +64 -0
  2. real_inference/environments/act_pip_freeze.txt +89 -0
  3. real_inference/environments/dp_pip_freeze.txt +136 -0
  4. real_inference/environments/pi05_packages.txt +225 -0
  5. real_inference/manifest.sha256 +207 -0
  6. real_inference/provenance.json +31 -0
  7. real_inference/reference/deform_manip_sim/__init__.py +0 -0
  8. real_inference/reference/deform_manip_sim/policy/__init__.py +1 -0
  9. real_inference/reference/deform_manip_sim/policy/aloha/__init__.py +1 -0
  10. real_inference/reference/deform_manip_sim/policy/aloha/adapters.py +89 -0
  11. real_inference/reference/deform_manip_sim/policy/bridge_client.py +245 -0
  12. real_inference/reference/deform_manip_sim/policy/schema.py +227 -0
  13. real_inference/reference/scripts/serve_policy.py +155 -0
  14. real_inference/source/XPolicyLab/LICENSE +201 -0
  15. real_inference/source/XPolicyLab/policy/Pi_05/openpi/.python-version +1 -0
  16. real_inference/source/XPolicyLab/policy/Pi_05/openpi/LICENSE +201 -0
  17. real_inference/source/XPolicyLab/policy/Pi_05/openpi/LICENSE_GEMMA.txt +77 -0
  18. real_inference/source/XPolicyLab/policy/Pi_05/openpi/README.md +323 -0
  19. real_inference/source/XPolicyLab/policy/Pi_05/openpi/pyproject.toml +138 -0
  20. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/__init__.py +0 -0
  21. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/conftest.py +17 -0
  22. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/__init__.py +0 -0
  23. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/gemma.py +459 -0
  24. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/gemma_fast.py +437 -0
  25. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/lora.py +148 -0
  26. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/lora_test.py +94 -0
  27. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/model.py +332 -0
  28. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/pi0_fast.py +313 -0
  29. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/pi0_test.py +46 -0
  30. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/siglip.py +373 -0
  31. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/tokenizer.py +371 -0
  32. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/tokenizer_test.py +27 -0
  33. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/vit.py +307 -0
  34. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models_pytorch/preprocessing_pytorch.py +173 -0
  35. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/py.typed +0 -0
  36. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/serving/websocket_policy_server.py +90 -0
  37. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/shared/__init__.py +0 -0
  38. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/shared/array_typing.py +89 -0
  39. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/shared/download.py +226 -0
  40. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/shared/download_test.py +54 -0
  41. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/shared/image_tools.py +126 -0
  42. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/shared/image_tools_test.py +37 -0
  43. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/shared/nnx_utils.py +69 -0
  44. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/shared/normalize.py +146 -0
  45. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/shared/normalize_test.py +43 -0
  46. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/transforms.py +495 -0
  47. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/transforms_test.py +141 -0
  48. real_inference/source/XPolicyLab/policy/Pi_05/openpi/uv.lock +0 -0
  49. real_inference/source/xpolicylab_local_changes.patch +467 -0
  50. real_inference/verify_files.py +25 -0
real_inference/README.md ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Aloha 2 号机真机推理:模型与复现材料
2
+
3
+ 这个目录整理了服务器上训练得到的 ACT、DP 和 π0.5 LoRA 模型、配套统计量、模型源码快照、依赖版本记录和离线输入样本,供实验室工控机上的开发者或 Codex 接入当地已有的 ROS 代码。本目录**不是已经完成真机验证的 ROS 部署程序**,不会自动连接或控制机械臂。
4
+
5
+ ## 目录与文件
6
+
7
+ | 路径 | 作用 |
8
+ | --- | --- |
9
+ | `models/act/policy_best.ckpt` | ACT 的最佳验证 checkpoint,预测 50×14 |
10
+ | `models/act/dataset_stats.pkl` | ACT 的训练集 state/action 均值和标准差;需与 checkpoint 配套 |
11
+ | `models/dp/10.ckpt` | DP 最后一轮 checkpoint(包括 EMA、模型、归一化及训练状态),预测 6×14 可执行动作 |
12
+ | `models/pi05/29999/` | π0.5 LoRA 的完整 Orbax checkpoint。`params/` 是参数,`assets/aloha_garment/norm_stats.json` 是推理归一化统计,`train_state/` 与元数据用于保留原始 checkpoint 结构 |
13
+ | `models/shared/openpi/big_vision/paligemma_tokenizer.model` | π0.5 使用的 tokenizer,便于离线加载 |
14
+ | `models/shared/torch/hub/checkpoints/resnet18-f37072fd.pth` | 当前 ACT 初始化时可能访问的 torchvision 缓存;最终权重仍由 ACT checkpoint 覆盖 |
15
+ | `source/XPolicyLab/` | 实际使用的 ACT `detr/`、DP `diffusion_policy/` 和 OpenPI `src/`、客户端包、锁文件及许可证的快照,包含服务器未提交的代码 |
16
+ | `source/xpolicylab_local_changes.patch` | 服务器 XPolicyLab 相对基线的相关已跟踪文件差异,供核对;未跟踪的源码已直接包含在快照中 |
17
+ | `reference/` | 仿真中使用的策略 adapter、通信协议和服务脚本参考;原始 adapter 仍含服务器绝对路径,不能直接作为工控机启动脚本 |
18
+ | `environments/` | 服务器 Python 包版本清单;用于比对,不是可直接复制的虚拟环境或经过工控机验证的锁定安装方案 |
19
+ | `fixtures/0041_episode0_frame100.npz` | 一帧真实录制的三路 RGB、14 维 qpos 和下一帧动作,供不连接机器人时检查 |
20
+ | `check_fixture.py` | 使用上述本地权重和快照进行模型单次推理的参考检查,不发送 ROS 指令 |
21
+ | `manifest.sha256`、`verify_files.py` | 文件 SHA-256 清单和校验工具 |
22
+
23
+ 服务器基线为 XPolicyLab `1e815ad750ba27407ec2e1a97cb4674a43d0734d`;因为本次训练有本地改动,不能仅依赖该 Git 版本复现,应该以本目录快照与补丁为准。源码的上游许可证随快照保留。
24
+
25
+ ## 输入输出约定
26
+
27
+ - 相机:`cam_high`、`cam_left_wrist`、`cam_right_wrist`,依次对应 `camera_f`、`camera_l`、`camera_r`。模型适配器输入 RGB uint8;ACT 使用 640×480,DP 适配器缩放到 320×240,π0.5 使用 OpenPI 自身的图像变换。
28
+ - 状态和动作:14 维,按 `[左臂 6 关节, 左夹爪, 右臂 6 关节, 右夹爪]` 排列;使用数据采集时的绝对关节位置和夹爪开度,不是末端轨迹。采集数据 `action[t]` 是配对后的下一时刻从臂状态。工控机接入时必须核对真实驱动的顺序、量纲和夹爪数值语义。
29
+ - 动作时间间隔为 0.04 秒。ACT 无 temporal aggregation 的参考方式为预测 50、执行 50;DP 观测最近 3 帧、预测 horizon 8、执行 6;π0.5 预测 50、执行 5。DP 执行多步期间也需每个控制步采样并更新观测历史。以上是已实现的仿真评测设置,真机效果尚未验证。
30
+ - π0.5 任务指令:`Fold the garment.`;本次配置使用 `adapt_to_pi=False` 和 `use_delta_joint_actions=False`,不要套用其他 Aloha 硬件的关节翻转、夹爪变换或 delta action。
31
+
32
+ ## 工控机接入边界
33
+
34
+ 设备手册说明 2 号机推理模式使用 `/puppet/pos_joint_cmd_left`、`/puppet/pos_joint_cmd_right`,状态使用 `/puppet/joint_left`、`/puppet/joint_right`;三路彩色相机为 `/camera_f/color/image_raw`、`/camera_l/color/image_raw`、`/camera_r/color/image_raw`。最终话题、消息字段、频率、关节顺序和单位应以工控机实际驱动核实。
35
+
36
+ 手册要求从遥操作模式切换到推理模式时,先给机械臂断电,再启动推理模式,否则从臂可能失能掉落。ROS 客户端、动作限幅、紧急停止、接入验证及实机操作由工控机侧基于本机现有代码实现和检查。本目录里的参考 WebSocket 服务协议与手册 OpenPI 客户端协议不同,不应直接假定互通。
37
+
38
+ ## 校验与离线模型检查
39
+
40
+ 传输后在本目录运行:
41
+
42
+ ```bash
43
+ python verify_files.py
44
+ ```
45
+
46
+ 工具会读取 `manifest.sha256` 并校验已列文件。计算权重哈希需要读取约 8 GiB 数据;不会联网或运行机器人。
47
+
48
+ 在分别安装了对应依赖的环境中,可以对真实样本执行模型检查:
49
+
50
+ ```bash
51
+ CUDA_VISIBLE_DEVICES=0 python check_fixture.py act
52
+ CUDA_VISIBLE_DEVICES=0 python check_fixture.py dp
53
+ CUDA_VISIBLE_DEVICES=0 python check_fixture.py pi05
54
+ ```
55
+
56
+ ACT、DP 的参考 adapter 当前使用 CUDA;π0.5 可用 `JAX_PLATFORMS=cpu` 做较慢的 CPU 检查。DP 原服务器运行时把 `policy_training/dp_compat` 放在 `PYTHONPATH` 最前面(有效 numpy 1.23.5、OpenCV 4.10.0);本目录没有复制依赖机器 ABI 的兼容目录,工控机需安装兼容版本。原始源码中部分训练用途的路径仍指向服务器,`check_fixture.py` 只在运行时覆盖参考 adapter 所需权重和代码路径。三种策略均可能有随机性,脚本只核验输出维度和有限性,不以单帧预测误差衡量模型优劣。
57
+
58
+ `act_pip_freeze.txt`、`dp_pip_freeze.txt` 是服务器环境快照,含本地 editable 依赖,**不应直接当作可移植 requirements 安装**;π0.5 的完整环境版本见 `pi05_packages.txt` 和 OpenPI 的 `uv.lock`。应按工控机操作系统、驱动、CUDA 及 ROS Python 版本重新配置或验证模型环境。模型服务与 ROS 客户端可使用不同 Python 环境。
59
+
60
+ 服务器离线检查记录:ACT 与 DP 在各自 GPU 环境、π0.5 在 CPU 环境,均以本目录的源码快照、权重和 0041 第 100 帧样本完成单帧推理;输出分别为 `(50,14)`、`(6,14)`、`(50,14)`,全部为有限值。DP 检查仍使用服务器已有的 `dp_compat`;这不代表工控机依赖或 ROS 接口已完成验证。
61
+
62
+ ## 传输
63
+
64
+ 整个目录约 8.2 GiB,可传到 Hugging Face 仓库或用其他方式复制。请保持 `models/pi05/29999/` 的目录结构,传输后运行校验。当前上层仓库的 `.gitignore` 默认忽略新的顶层目录;普通 GitHub push 不会自动包含本目录,且权重不适合直接放入普通 Git。这里尚未将任何文件上传。
real_inference/environments/act_pip_freeze.txt ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ absl-py==2.5.1
2
+ annotated-types==0.8.0
3
+ asttokens==3.0.2
4
+ attrs==26.1.0
5
+ catkin-pkg==1.1.1
6
+ certifi==2026.10.23
7
+ charset-normalizer==3.5.2
8
+ contourpy==1.3.2
9
+ cycler==0.12.1
10
+ decorator==5.3.1
11
+ -e git+https://github.com/XPolicyLab/XPolicyLab.git@1e815ad750ba27407ec2e1a97cb4674a43d0734d#egg=detr&subdirectory=../../XPolicyLab/policy/ACT/detr
12
+ distro==1.9.0
13
+ dm-control==1.0.14
14
+ dm-env==1.6
15
+ dm-tree==0.1.10
16
+ docutils==0.23
17
+ einops==0.8.2
18
+ exceptiongroup==1.3.1
19
+ executing==2.3.0
20
+ filelock==4.1.0
21
+ fonttools==4.65.0
22
+ fsspec==2026.9.0
23
+ glfw==2.11.0
24
+ h5py==3.16.0
25
+ idna==3.20
26
+ ipython==8.39.0
27
+ jedi==0.20.1
28
+ Jinja2==3.1.6
29
+ kiwisolver==1.5.1
30
+ labmaze==1.0.6
31
+ lxml==6.1.3
32
+ MarkupSafe==3.0.4
33
+ matplotlib==3.10.9
34
+ matplotlib-inline==0.2.2
35
+ mpmath==1.3.0
36
+ msgpack==1.2.4
37
+ msgpack-numpy==0.4.8
38
+ mujoco==2.3.7
39
+ networkx==3.4.2
40
+ numpy==2.2.6
41
+ nvidia-cublas-cu12==12.1.3.1
42
+ nvidia-cuda-cupti-cu12==12.1.105
43
+ nvidia-cuda-nvrtc-cu12==12.1.105
44
+ nvidia-cuda-runtime-cu12==12.1.105
45
+ nvidia-cudnn-cu12==9.1.0.70
46
+ nvidia-cufft-cu12==11.0.2.54
47
+ nvidia-curand-cu12==10.3.2.106
48
+ nvidia-cusolver-cu12==11.4.5.107
49
+ nvidia-cusparse-cu12==12.1.0.106
50
+ nvidia-nccl-cu12==2.20.5
51
+ nvidia-nvjitlink-cu12==12.9.86
52
+ nvidia-nvtx-cu12==12.1.105
53
+ opencv-python==5.0.0.93
54
+ opencv-python-headless==5.0.0.93
55
+ packaging==26.3
56
+ parso==0.8.7
57
+ pexpect==4.9.0
58
+ pillow==12.3.0
59
+ prompt_toolkit==3.0.53
60
+ protobuf==7.36.2
61
+ ptyprocess==0.7.0
62
+ pure_eval==0.2.4
63
+ pydantic==2.14.3
64
+ pydantic_core==2.50.4
65
+ Pygments==2.21.0
66
+ PyOpenGL==3.1.10
67
+ pyparsing==3.3.3
68
+ pyquaternion==0.9.9
69
+ python-dateutil==3.0.0
70
+ PyYAML==6.0.3
71
+ requests==2.34.2
72
+ rospkg==1.6.3
73
+ scipy==1.15.3
74
+ six==1.17.0
75
+ stack-data==0.6.3
76
+ sympy==1.14.0
77
+ torch==2.4.1
78
+ torchvision==0.19.1
79
+ tqdm==4.70.1
80
+ traitlets==5.16.1
81
+ triton==3.0.0
82
+ typing-inspection==0.4.5
83
+ typing_extensions==4.16.0
84
+ tzdata==2026.6
85
+ urllib3==2.8.0
86
+ wcwidth==0.9.4
87
+ websockets==16.1.1
88
+ wrapt==2.5.2
89
+ -e git+https://github.com/XPolicyLab/XPolicyLab.git@1e815ad750ba27407ec2e1a97cb4674a43d0734d#egg=xpolicylab&subdirectory=../../XPolicyLab
real_inference/environments/dp_pip_freeze.txt ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ absl-py==2.5.1
2
+ annotated-types==0.8.0
3
+ antlr4-python3-runtime==4.9.3
4
+ anyio==4.16.0
5
+ asciitree==1.0.0
6
+ asttokens==3.0.2
7
+ attrs==26.1.0
8
+ av==17.1.0
9
+ blessed==1.52.0
10
+ certifi==2026.10.23
11
+ charset-normalizer==3.5.2
12
+ click==8.5.1
13
+ contourpy==1.3.2
14
+ cwevals==0.0.1b1
15
+ cycler==0.12.1
16
+ decorator==4.4.2
17
+ diffusers==0.11.1
18
+ -e git+https://github.com/XPolicyLab/XPolicyLab.git@1e815ad750ba27407ec2e1a97cb4674a43d0734d#egg=diffusion_policy&subdirectory=../../XPolicyLab/policy/DP
19
+ dill==0.3.5.1
20
+ distro==1.9.0
21
+ dm-env==1.6
22
+ dm-tree==0.1.10
23
+ dm_control==1.0.50
24
+ einops==0.4.1
25
+ etils==1.13.0
26
+ exceptiongroup==1.3.1
27
+ executing==2.3.0
28
+ fasteners==0.20
29
+ filelock==4.1.0
30
+ fonttools==4.65.0
31
+ fsspec==2026.9.0
32
+ glfw==2.11.0
33
+ googleapis-common-protos==1.76.0
34
+ gpustat==1.1.1
35
+ h11==0.16.0
36
+ h5py==3.16.0
37
+ httpcore==1.0.9
38
+ httpx==0.28.1
39
+ huggingface-hub==0.25.2
40
+ hydra-core==1.2.0
41
+ idna==3.20
42
+ ImageIO==2.38.0
43
+ imageio-ffmpeg==0.8.1
44
+ importlib_metadata==9.0.1
45
+ importlib_resources==7.1.0
46
+ ipdb==0.13.13
47
+ ipython==8.39.0
48
+ jedi==0.20.1
49
+ Jinja2==3.1.6
50
+ jinxed==2.1.0
51
+ kiwisolver==1.5.1
52
+ labmaze==1.0.6
53
+ llvmlite==0.39.1
54
+ lxml==6.1.3
55
+ MarkupSafe==3.0.4
56
+ matplotlib==3.10.9
57
+ matplotlib-inline==0.2.2
58
+ moviepy==1.0.3
59
+ mpmath==1.3.0
60
+ msgpack==1.2.4
61
+ msgpack-numpy==0.4.8
62
+ mujoco==3.17.0
63
+ networkx==3.4.2
64
+ numba==0.56.4
65
+ numcodecs==0.13.1
66
+ numpy==2.2.6
67
+ nvidia-cublas-cu12==12.1.3.1
68
+ nvidia-cuda-cupti-cu12==12.1.105
69
+ nvidia-cuda-nvrtc-cu12==12.1.105
70
+ nvidia-cuda-runtime-cu12==12.1.105
71
+ nvidia-cudnn-cu12==9.1.0.70
72
+ nvidia-cufft-cu12==11.0.2.54
73
+ nvidia-curand-cu12==10.3.2.106
74
+ nvidia-cusolver-cu12==11.4.5.107
75
+ nvidia-cusparse-cu12==12.1.0.106
76
+ nvidia-ml-py==13.615.71
77
+ nvidia-nccl-cu12==2.20.5
78
+ nvidia-nvjitlink-cu12==12.9.86
79
+ nvidia-nvtx-cu12==12.1.105
80
+ omegaconf==2.4.0
81
+ opencv-python==4.11.0.86
82
+ opencv-python-headless==5.0.0.93
83
+ opentelemetry-api==1.45.2
84
+ opentelemetry-exporter-http-transport==0.66b2
85
+ opentelemetry-exporter-otlp-common==0.66b2
86
+ opentelemetry-exporter-otlp-proto-common==1.45.2
87
+ opentelemetry-exporter-otlp-proto-http==1.45.2
88
+ opentelemetry-proto==1.45.2
89
+ opentelemetry-sdk==1.45.2
90
+ opentelemetry-semantic-conventions==0.66b2
91
+ packaging==26.3
92
+ pandas==2.3.3
93
+ parso==0.8.7
94
+ pexpect==4.9.0
95
+ pillow==12.3.0
96
+ platformdirs==4.12.4
97
+ proglog==0.1.12
98
+ prompt_toolkit==3.0.53
99
+ protobuf==7.36.2
100
+ psutil==7.2.2
101
+ ptyprocess==0.7.0
102
+ pure_eval==0.2.4
103
+ pydantic==2.14.3
104
+ pydantic_core==2.50.4
105
+ Pygments==2.21.0
106
+ PyOpenGL==3.1.10
107
+ pyparsing==3.3.3
108
+ python-dateutil==3.0.0
109
+ pytz==2026.6
110
+ PyYAML==6.0.3
111
+ regex==2026.9.29
112
+ requests==2.34.2
113
+ scipy==1.15.3
114
+ six==1.17.0
115
+ sniffio==1.3.1
116
+ stack-data==0.6.3
117
+ sympy==1.14.0
118
+ termcolor==3.3.0
119
+ tomli==2.5.0
120
+ torch==2.4.1
121
+ torchvision==0.19.1
122
+ tqdm==4.70.1
123
+ traitlets==5.16.1
124
+ triton==3.0.0
125
+ typing-inspection==0.4.5
126
+ typing_extensions==4.16.0
127
+ tzdata==2026.6
128
+ urllib3==2.8.0
129
+ wandb==0.31.0
130
+ wcwidth==0.9.4
131
+ websockets==16.1.1
132
+ wrapt==2.5.2
133
+ -e git+https://github.com/XPolicyLab/XPolicyLab.git@1e815ad750ba27407ec2e1a97cb4674a43d0734d#egg=xpolicylab&subdirectory=../../XPolicyLab
134
+ xxhash==4.0.2
135
+ zarr==2.12.0
136
+ zipp==4.1.2
real_inference/environments/pi05_packages.txt ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python 3.11.15 (main, Aug 7 2026, 02:25:55) [Clang 22.1.3 ]
2
+ absl-py==2.3.0
3
+ accelerate==1.13.0
4
+ aiohappyeyeballs==2.6.1
5
+ aiohttp==3.12.4
6
+ aiosignal==1.3.2
7
+ annotated-types==0.7.0
8
+ anyio==4.13.0
9
+ asttokens==3.0.0
10
+ attrs==25.3.0
11
+ augmax==0.4.1
12
+ av==15.1.0
13
+ beartype==0.19.0
14
+ cachetools==5.5.2
15
+ certifi==2025.4.26
16
+ cfgv==3.4.0
17
+ charset-normalizer==3.4.2
18
+ chex==0.1.89
19
+ click==8.2.1
20
+ cloudpickle==3.1.1
21
+ cmake==4.0.2
22
+ comm==0.2.2
23
+ contourpy==1.3.2
24
+ cuda-bindings==12.9.4
25
+ cuda-pathfinder==1.5.5
26
+ cycler==0.12.1
27
+ datasets==4.8.5
28
+ debugpy==1.8.14
29
+ decorator==5.2.1
30
+ deepdiff==8.5.0
31
+ diffusers==0.33.1
32
+ dill==0.3.8
33
+ distlib==0.3.9
34
+ dm-tree==0.1.9
35
+ docstring_parser==0.16
36
+ draccus==0.10.0
37
+ einops==0.8.1
38
+ equinox==0.12.2
39
+ etils==1.12.2
40
+ evdev==1.9.2
41
+ executing==2.2.0
42
+ Farama-Notifications==0.0.4
43
+ filelock==3.18.0
44
+ flatbuffers==25.2.10
45
+ flax==0.10.2
46
+ fonttools==4.58.1
47
+ frozenlist==1.6.0
48
+ fsspec==2025.3.0
49
+ gcsfs==2025.3.0
50
+ gitdb==4.0.12
51
+ GitPython==3.1.44
52
+ google-api-core==2.24.2
53
+ google-auth==2.40.2
54
+ google-auth-oauthlib==1.2.2
55
+ google-cloud-core==2.4.3
56
+ google-cloud-storage==3.1.0
57
+ google-crc32c==1.7.1
58
+ google-resumable-media==2.7.2
59
+ googleapis-common-protos==1.70.0
60
+ gymnasium==1.3.0
61
+ h11==0.16.0
62
+ h5py==3.16.0
63
+ hf-xet==1.5.0
64
+ hf_transfer==0.1.9
65
+ httpcore==1.0.9
66
+ httpx==0.28.1
67
+ huggingface-hub==0.35.3
68
+ humanize==4.12.3
69
+ identify==2.6.12
70
+ idna==3.10
71
+ imageio==2.37.0
72
+ imageio-ffmpeg==0.6.0
73
+ importlib_metadata==8.7.0
74
+ importlib_resources==6.5.2
75
+ iniconfig==2.1.0
76
+ inquirerpy==0.3.4
77
+ ipykernel==6.29.5
78
+ ipython==9.2.0
79
+ ipython_pygments_lexers==1.1.1
80
+ ipywidgets==8.1.7
81
+ jax==0.5.3
82
+ jax-cuda12-pjrt==0.5.3
83
+ jax-cuda12-plugin==0.5.3
84
+ jaxlib==0.5.3
85
+ jaxtyping==0.2.36
86
+ jedi==0.19.2
87
+ Jinja2==3.1.6
88
+ jsonlines==4.0.0
89
+ jupyter_client==8.6.3
90
+ jupyter_core==5.8.1
91
+ jupyterlab_widgets==3.0.15
92
+ kiwisolver==1.4.8
93
+ lerobot==0.4.4
94
+ markdown-it-py==3.0.0
95
+ MarkupSafe==3.0.2
96
+ matplotlib==3.10.3
97
+ matplotlib-inline==0.1.7
98
+ mdurl==0.1.2
99
+ mergedeep==1.3.4
100
+ ml-dtypes==0.4.1
101
+ ml_collections==1.0.0
102
+ mpmath==1.3.0
103
+ msgpack==1.1.0
104
+ msgpack-numpy==0.4.8
105
+ multidict==6.4.4
106
+ multiprocess==0.70.16
107
+ mypy_extensions==1.1.0
108
+ nest-asyncio==1.6.0
109
+ networkx==3.5
110
+ nodeenv==1.9.1
111
+ numpy==1.26.4
112
+ numpydantic==1.6.9
113
+ nvidia-cublas-cu12==12.8.4.1
114
+ nvidia-cuda-cupti-cu12==12.8.90
115
+ nvidia-cuda-nvcc-cu12==12.9.41
116
+ nvidia-cuda-nvrtc-cu12==12.8.93
117
+ nvidia-cuda-runtime-cu12==12.8.90
118
+ nvidia-cudnn-cu12==9.10.2.21
119
+ nvidia-cufft-cu12==11.3.3.83
120
+ nvidia-cufile-cu12==1.13.1.3
121
+ nvidia-curand-cu12==10.3.9.90
122
+ nvidia-cusolver-cu12==11.7.3.90
123
+ nvidia-cusparse-cu12==12.5.8.93
124
+ nvidia-cusparselt-cu12==0.7.1
125
+ nvidia-ml-py==12.575.51
126
+ nvidia-nccl-cu12==2.27.5
127
+ nvidia-nvjitlink-cu12==12.8.93
128
+ nvidia-nvshmem-cu12==3.4.5
129
+ nvidia-nvtx-cu12==12.8.90
130
+ oauthlib==3.2.2
131
+ opencv-python==4.11.0.86
132
+ opencv-python-headless==4.11.0.86
133
+ openpi==0.1.0
134
+ openpi-client==0.1.0
135
+ opt_einsum==3.4.0
136
+ optax==0.2.4
137
+ orbax-checkpoint==0.11.13
138
+ orderly-set==5.4.1
139
+ packaging==25.0
140
+ pandas==2.2.3
141
+ parso==0.8.4
142
+ pexpect==4.9.0
143
+ pfzy==0.3.4
144
+ pillow==11.2.1
145
+ platformdirs==4.3.8
146
+ pluggy==1.6.0
147
+ polars==1.30.0
148
+ pre_commit==4.2.0
149
+ prompt_toolkit==3.0.51
150
+ propcache==0.3.1
151
+ proto-plus==1.26.1
152
+ protobuf==4.25.8
153
+ psutil==7.0.0
154
+ ptyprocess==0.7.0
155
+ pure_eval==0.2.3
156
+ pyarrow==24.0.0
157
+ pyasn1==0.6.1
158
+ pyasn1_modules==0.4.2
159
+ pydantic==2.11.5
160
+ pydantic_core==2.33.2
161
+ Pygments==2.19.1
162
+ pynput==1.8.1
163
+ pynvml==12.0.0
164
+ pyparsing==3.2.3
165
+ pyserial==3.5
166
+ pytest==8.3.5
167
+ python-dateutil==2.9.0.post0
168
+ python-xlib==0.33
169
+ pytz==2025.2
170
+ PyYAML==6.0.2
171
+ pyyaml-include==1.4.1
172
+ pyzmq==26.4.0
173
+ regex==2024.11.6
174
+ requests==2.32.3
175
+ requests-oauthlib==2.0.0
176
+ rerun-sdk==0.26.2
177
+ rich==14.0.0
178
+ rsa==4.9.1
179
+ ruff==0.11.12
180
+ safetensors==0.5.3
181
+ scipy==1.15.3
182
+ sentencepiece==0.2.0
183
+ sentry-sdk==2.29.1
184
+ setuptools==80.9.0
185
+ shtab==1.7.2
186
+ simplejson==3.20.1
187
+ six==1.17.0
188
+ smmap==5.0.2
189
+ stack-data==0.6.3
190
+ svgwrite==1.4.3
191
+ sympy==1.14.0
192
+ tensorstore==0.1.74
193
+ termcolor==3.1.0
194
+ tokenizers==0.21.1
195
+ toml==0.10.2
196
+ toolz==1.0.0
197
+ torch==2.10.0
198
+ torchcodec==0.10.0
199
+ torchvision==0.25.0
200
+ tornado==6.5.1
201
+ tqdm==4.67.1
202
+ tqdm-loggable==0.2
203
+ traitlets==5.14.3
204
+ transformers==4.53.2
205
+ Tree==0.2.4
206
+ treescope==0.1.9
207
+ triton==3.6.0
208
+ typeguard==4.4.2
209
+ typing-inspect==0.9.0
210
+ typing-inspection==0.4.1
211
+ typing_extensions==4.13.2
212
+ tyro==0.9.22
213
+ tzdata==2025.2
214
+ urllib3==2.4.0
215
+ virtualenv==20.31.2
216
+ wadler_lindig==0.1.6
217
+ wandb==0.24.2
218
+ wcwidth==0.2.13
219
+ websockets==15.0.1
220
+ widgetsnbextension==4.0.14
221
+ wrapt==1.14.1
222
+ xpolicylab==0.0.1
223
+ xxhash==3.5.0
224
+ yarl==1.20.0
225
+ zipp==3.22.0
real_inference/manifest.sha256 ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ d247d7fc20b2c48c22ff64c6efb7e19bb47e064e38386585f22e6b25943c7f80 README.md
2
+ 9a856e6c5c804d0fd4b73a84bb440b7f05a8b659a560e0d469ae442434a02c81 check_fixture.py
3
+ c253e55558c7a8350c668837fbca96ea61bb3cad4ad0cb24154b3286584df22a environments/act_pip_freeze.txt
4
+ e3669e71e38410773cb9700d0d477fd12770f454d980d1f4884cf33d7090bd4b environments/dp_pip_freeze.txt
5
+ e92774979d8acee5eee4ecfadc9fcaf3ee201b3a54faa747b27fa9b038970cec environments/pi05_packages.txt
6
+ 3c0a343d3e47fbace99a902f0c1251926b748002c91fc8ae56c343f08c86e6d2 fixtures/0041_episode0_frame100.npz
7
+ 9bfe8de73a8b29e6fd335c73135ed125e6777c0d5fad070207c0df3088443651 models/act/dataset_stats.pkl
8
+ 8cc45d9a95d8942102368d4ade28ce3b1e2c2a40b3b5c5447af4bfba5d16b2b6 models/act/policy_best.ckpt
9
+ d3096f7b7744259761819ba47ecf72a9d76e756a105fdb4e07b3d64682fb7dce models/dp/10.ckpt
10
+ 3a22a8e6c9e8db04d6231f0c43bcdecd60625edbd08626eb275f380d069965b1 models/pi05/29999/_CHECKPOINT_METADATA
11
+ 431056d043a070e22c993fd83bf1837485b4ab00757b6d1ba356e973b9f12065 models/pi05/29999/assets/aloha_garment/norm_stats.json
12
+ 88464a384c524c50fa1a92c1685d23a79570c62807a0ccf021f5f9307fff137c models/pi05/29999/params/_METADATA
13
+ 54899ee3f4d45eee96ddada379a19a9da1324792b141fa0449608620571e6b01 models/pi05/29999/params/_sharding
14
+ da5f8952b77ab352fa92e3e58d742bfe0db5b9c1b956212f8279895b9df03721 models/pi05/29999/params/array_metadatas/process_0
15
+ 07f9785cf62e6bfa977b4da86fb4213d7eaa9813ac090df1a3a6101d95933a0d models/pi05/29999/params/d/06333319d86d6322317baf3a3eac4ad0
16
+ aaaa5de82859481d737cbfdc83c79a24766e4d3b5ebe5f3d223e6901f6ce1575 models/pi05/29999/params/manifest.ocdbt
17
+ e94b6f05ceef55173200b9a654bc6d84fae3656f3c7e168fafc6291a2847bc7a models/pi05/29999/params/ocdbt.process_0/d/366797c577724144889229f01578f9bd
18
+ a7529dbe32d1effa51ffc7ccea0cc8fe6ed7457c7c6769b7acc5621b583102ec models/pi05/29999/params/ocdbt.process_0/d/780a5b6463312c36c65b532cb5c5c630
19
+ 75b7f446e5fb5a304b7989c76077152a72ebf21f2d6cee57f8a8cde1471e4a48 models/pi05/29999/params/ocdbt.process_0/d/8326f82906296621ce83e0ef00b39dcf
20
+ 846141ddc272b836589ee4359cf3c4ce65ed8e4fddd75f9a1b18db189f2f0431 models/pi05/29999/params/ocdbt.process_0/d/863f8f5edafc9c0283c9c0e39f8bb80b
21
+ bbbb9f85d7dcdffa058288d36dd4b77e49f4fd314eb96bbed53c70fcdb0e43aa models/pi05/29999/params/ocdbt.process_0/d/88272c645a2a08ab0ea0a491f721c696
22
+ 1ecfb7b2d39c7e35a2255bdbeb0bf840f86ea48dc5c8894033f29bbe469fe429 models/pi05/29999/params/ocdbt.process_0/d/97a38f866cf57e5ac239d6dd5e3ecb4d
23
+ c5bf3363ca850197ec394367a792a47f110a8acc5060423f72c1a1cae251776b models/pi05/29999/params/ocdbt.process_0/d/a092f4574281d2f0ae1f037e702c3197
24
+ efd26dd1e0ca4a1a708b29a1b181d70dbf46bd521e7e5c182900bc66f17956cb models/pi05/29999/params/ocdbt.process_0/d/d3974835cdb6b10d70315290f2a85cbc
25
+ 90d24d7766bf7713f33b14c2baf86b0e7a43688699cbcad13d34d45445af8bc2 models/pi05/29999/params/ocdbt.process_0/d/e17de3b568a701ef9e6f1a35243d6f92
26
+ d4f04e9be9adf4bb451735599d8d9d644de3465414abe5d96eb497776bbeec6c models/pi05/29999/params/ocdbt.process_0/manifest.ocdbt
27
+ f642d4038df7bf98addfd10db1b7d7c54c030aa2f42f4d3f1dd15cbd7a237d33 models/pi05/29999/train_state/_METADATA
28
+ ab273f886dd11d3933e8c13cd73ec9994da4259378dfa90609d02ab62e72968e models/pi05/29999/train_state/_sharding
29
+ c34703e55a203ddc31398d036b36f1b4dbf3526d3078442c1118b65c2e188a1e models/pi05/29999/train_state/array_metadatas/process_0
30
+ 335bd3ea39a7d4cdefb7e8f74d16906a4fb93eff9f3511d3fc8aded22195a649 models/pi05/29999/train_state/d/54d554dcf73117307fd5fc1be16e9d3a
31
+ 6805f0c42d560e5052aa3c1bfb13f91f386d1737b7dbf38bdc4cfbe3e0181096 models/pi05/29999/train_state/manifest.ocdbt
32
+ f5f07a5628102c460a35c1799e565092abbfdcc8fea4dbb2d0da03309ba35945 models/pi05/29999/train_state/ocdbt.process_0/d/431a2806b246e72e9fd091a350a7c94d
33
+ 1c1a10df6d4422e44a53495b4cb5d46322f2a5cdc47af5f2c3a34d35e33d991f models/pi05/29999/train_state/ocdbt.process_0/d/515c0ef0445b4ef38fc13c6478d474bc
34
+ 4322e96cd3829e98d2a117a6ec7128cdaa27f5f3a65c63fc53133c63c1413e9b models/pi05/29999/train_state/ocdbt.process_0/d/7137c5918b57537691d56243eb5926f8
35
+ 2e7709a2f3ab837541deb5b19191b5564f34ee3934b8fefe154f5965045f9671 models/pi05/29999/train_state/ocdbt.process_0/d/fce79687f9af6009dbecb732076e5547
36
+ 6feb64c62938b4018120e5269ed9c150060d17daf6243b3bdbdab62c301d3a54 models/pi05/29999/train_state/ocdbt.process_0/manifest.ocdbt
37
+ 8986bb4f423f07f8c7f70d0dbe3526fb2316056c17bae71b1ea975e77a168fc6 models/shared/openpi/big_vision/paligemma_tokenizer.model
38
+ f37072fd47e89c5e827621c5baffa7500819f7896bbacec160b1a16c560e07ec models/shared/torch/hub/checkpoints/resnet18-f37072fd.pth
39
+ a60066840d7b34f3797a6a19b4d27d42339645116edd0f749f4c9315bfac34cb provenance.json
40
+ e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 reference/deform_manip_sim/__init__.py
41
+ 6895cabcabc21dfcc8b09e7b8ec83b5558d8162a9c61b9fcc8592f71845ee419 reference/deform_manip_sim/policy/__init__.py
42
+ 7acc2687fdc644a2016e93a153781e219838c823f930751d37968ac017129f0e reference/deform_manip_sim/policy/aloha/__init__.py
43
+ c804c2ec33d43d4177c8e2a8f6c22d13f1513d61185bbb7e63244a93721c7665 reference/deform_manip_sim/policy/aloha/adapters.py
44
+ 7fedc104b039893cd332c42ef357a5ef5b64402e0d00bb46f70ac488b4068ac4 reference/deform_manip_sim/policy/bridge_client.py
45
+ fb7b87236875b7e29aaebb79ec210718d16ef456be73be32c6cb3e20f79e1e85 reference/deform_manip_sim/policy/schema.py
46
+ 58147eced98404580b604122b0a43ab02e709fd6552d26fb7c9e733545cc0fc5 reference/scripts/serve_policy.py
47
+ c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4 source/XPolicyLab/LICENSE
48
+ 3c7b0d9bcd054154d4246a7783c09d269d2a262c6b008dfc3b49988185b33500 source/XPolicyLab/policy/ACT/detr/.gitignore
49
+ b208c52b00a2df2c8f4c3298c34407bf2bfe409968213372251c91fcc737a1a5 source/XPolicyLab/policy/ACT/detr/LICENSE
50
+ 56f4d26214510a82e532dfd452bb06bb143f8f04300dc2017fa04149e5323fc3 source/XPolicyLab/policy/ACT/detr/act_policy.py
51
+ dd4e8cab2b0e721a7da644c9d16520490a8b558c685affe95bb9a1ca13be1661 source/XPolicyLab/policy/ACT/detr/detr.egg-info/PKG-INFO
52
+ 333ba1359bc7c12f06e440e9173c33c94d0fe04dbbe65a8a53011093ba7c5f71 source/XPolicyLab/policy/ACT/detr/detr.egg-info/SOURCES.txt
53
+ 01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b source/XPolicyLab/policy/ACT/detr/detr.egg-info/dependency_links.txt
54
+ e104c6b3e081b16e5cd3606769d0f11e6c5fd71828431fc894edff0a9ca7e119 source/XPolicyLab/policy/ACT/detr/detr.egg-info/top_level.txt
55
+ 5db61b9312644ce0421d110079e4aed2baf442bd6fa5eae6d6a5be26d3a57b9c source/XPolicyLab/policy/ACT/detr/main.py
56
+ 3c09396628dc91ed32b59beeedb4f818fbd7bf3e5154b728513063ecdc0ac1c5 source/XPolicyLab/policy/ACT/detr/models/__init__.py
57
+ 476d954304220c4d34fa9eb725ea2eaa54da72be452e8a645e19989f95880aee source/XPolicyLab/policy/ACT/detr/models/backbone.py
58
+ 292e0e78997941ab8a8c592ffb3f88960e5971ffb0f621b9ff02fb942db45306 source/XPolicyLab/policy/ACT/detr/models/detr_vae.py
59
+ 12578dbadbaea2d8252c43f818b5826b1cf141feb8df1de2a012da81138080e4 source/XPolicyLab/policy/ACT/detr/models/position_encoding.py
60
+ 837506820a3c564896d9d694681b9a803c14e6ec30081ec9336f493158c06f4b source/XPolicyLab/policy/ACT/detr/models/transformer.py
61
+ 32e7e93134ab194d05c8f02495d53264b9956ee8d7e0cfac2a3fd63881ef0c46 source/XPolicyLab/policy/ACT/detr/process_data.py
62
+ 9a44d0125d73963ca219fd16cb511426b5fa2dfb7a499b7d9f08422ab822ccfe source/XPolicyLab/policy/ACT/detr/setup.py
63
+ 9e535c45af09ac24ef8d5631a151f77febafe72a92ad6bfeb2d941f0c4a54e35 source/XPolicyLab/policy/ACT/detr/util/__init__.py
64
+ 4c28aba49a4bb3ff18385e4940ad8ca7ad788aa4cfb03b075d15d9b4294d6aa6 source/XPolicyLab/policy/ACT/detr/util/box_ops.py
65
+ f9210613ef5d7477c01ad1cc6946c36a0221102cf6159ad7c261dd20b8feb374 source/XPolicyLab/policy/ACT/detr/util/misc.py
66
+ e8d46523fbf7aca10c2911be55441685e0cd1a6f4faa7382fcefb62c06b3bdca source/XPolicyLab/policy/ACT/detr/util/plot_utils.py
67
+ e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 source/XPolicyLab/policy/DP/diffusion_policy/__init__.py
68
+ 41bc1e81aa2f988eb0aaf134baea592e5c7fa9486330b2db85307de91cf48a77 source/XPolicyLab/policy/DP/diffusion_policy/common/checkpoint_util.py
69
+ c26440ec98788d7bcb9a839573a0eb2c6e6fe2395acc240b62e71f95365168bd source/XPolicyLab/policy/DP/diffusion_policy/common/cv2_util.py
70
+ 2ac6e9b690b38ef5c9671dd1b238955857f803e8d623cc32b1fb28e236c472fe source/XPolicyLab/policy/DP/diffusion_policy/common/env_util.py
71
+ ca6884937e1e6f5c7a7afa079f413bf1137178e1a6627ec152c2cae792dbd4c7 source/XPolicyLab/policy/DP/diffusion_policy/common/json_logger.py
72
+ 4aa208dbcc298489854678b88b06e18b672dd776670e67ba65305e9158a6e1eb source/XPolicyLab/policy/DP/diffusion_policy/common/nested_dict_util.py
73
+ 78376a000e4ac189df9777250b27a7559255647ba407d16f8a8a8e7e96aca55e source/XPolicyLab/policy/DP/diffusion_policy/common/normalize_util.py
74
+ feedb5130eb3267198957cf5ff2507c76ec0f48196944cac34ca2a46426104e7 source/XPolicyLab/policy/DP/diffusion_policy/common/pose_trajectory_interpolator.py
75
+ b82bd5ed3d5a116aa0097a2a16b0db35fa5e1bce38fc5a2ea37fe2b322f2e8d3 source/XPolicyLab/policy/DP/diffusion_policy/common/precise_sleep.py
76
+ 92c8059f9d8fb551193ccf135272318ab43d796cf8a8af3492156fcb297b4740 source/XPolicyLab/policy/DP/diffusion_policy/common/pymunk_override.py
77
+ 3190b005acd101408e7226b658077a5f27772d6b59f1fe8b642ee527b160e054 source/XPolicyLab/policy/DP/diffusion_policy/common/pymunk_util.py
78
+ ce68ea9aa3eaad156364ff58ed842026406c00e07ed9b632445d3b5c6f8620a9 source/XPolicyLab/policy/DP/diffusion_policy/common/pytorch_util.py
79
+ 11ba406b5bd88fa05680072e70ea414a61d7788295741a0efadb6d49873523da source/XPolicyLab/policy/DP/diffusion_policy/common/replay_buffer.py
80
+ d7424c5e1931b24ecc4acbd869b4771dce91eb844f83d8ca093bda91bd68fb3c source/XPolicyLab/policy/DP/diffusion_policy/common/robomimic_config_util.py
81
+ 7862574196c70f71cb64a64906c6e87ec56ce1beaee80a405e70222decab5d80 source/XPolicyLab/policy/DP/diffusion_policy/common/robomimic_util.py
82
+ 879bfab2bf068816d3952c814325c8fd989dabc9fa688ce7f859c9234b3f3b2f source/XPolicyLab/policy/DP/diffusion_policy/common/sampler.py
83
+ d568552511c1b3ef158ec6146acfad1e1e187357daaca35ed6688752ee5c8eb8 source/XPolicyLab/policy/DP/diffusion_policy/common/timestamp_accumulator.py
84
+ 44a7c934ad0f5253705f65a16fba102a757f445e7b93b03d1f07c907359fd4dd source/XPolicyLab/policy/DP/diffusion_policy/config/robot_dp.yaml
85
+ 0d4214c41cd2d045590acd37ed6633f808d15ac2451c286c62e206f3458ae8f1 source/XPolicyLab/policy/DP/diffusion_policy/config/task/aloha_garment.yaml
86
+ d1ed4fcbac031ca7d507f6471aef8c033afadb000749178a47e9558ed8f8a271 source/XPolicyLab/policy/DP/diffusion_policy/config/task/default_task.yaml
87
+ 7cd18962090681d6f8ccf2e16e90ce4217335bb16d2ef10badfc29a21ab028ab source/XPolicyLab/policy/DP/diffusion_policy/dataset/base_dataset.py
88
+ dfd33a488fe2fd38b383936284edaaa02f5215cae5e0b215d36d19d647ae4782 source/XPolicyLab/policy/DP/diffusion_policy/dataset/robot_image_dataset.py
89
+ aba2e5f21bc48d64cb90e8aa3f59c5bce7ff57eadd30289dd29e7cc3dbaf1e27 source/XPolicyLab/policy/DP/diffusion_policy/env_runner/dp_runner.py
90
+ e90b80222484c9d8602ee2e0d49a20c744d5e102da6ac95ba93358562ca1df0b source/XPolicyLab/policy/DP/diffusion_policy/model/bet/action_ae/__init__.py
91
+ 0cfa8991f05c29f73536b8cb8ba1ce8a5141df8ffdb59be869a46cf0cf301b5a source/XPolicyLab/policy/DP/diffusion_policy/model/bet/action_ae/discretizers/k_means.py
92
+ a92d651b1aee0bd6301ed4f138ae04faa3cbabbac5d874d6352b3254fe798315 source/XPolicyLab/policy/DP/diffusion_policy/model/bet/latent_generators/latent_generator.py
93
+ c50a2b5f414dc1f4bf756d41c9c5e30237fb216a7f97505bb48c486e9946a45e source/XPolicyLab/policy/DP/diffusion_policy/model/bet/latent_generators/mingpt.py
94
+ 0873c819f7dd26a858944345eebe8a11c7eb82f4fb3835595e53d1d600cd1072 source/XPolicyLab/policy/DP/diffusion_policy/model/bet/latent_generators/transformer.py
95
+ ac1a796e62fae864f78cfae9780dac510460f4c33bf2732c5dc508fdca4029b4 source/XPolicyLab/policy/DP/diffusion_policy/model/bet/libraries/loss_fn.py
96
+ 1868a048bfe0f991cf82ee0f8c357b50887bc32549a47762dbca96e87ebb9483 source/XPolicyLab/policy/DP/diffusion_policy/model/bet/libraries/mingpt/LICENSE
97
+ e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 source/XPolicyLab/policy/DP/diffusion_policy/model/bet/libraries/mingpt/__init__.py
98
+ e85b9ad8c098cdae2b81fc09e835cf4a217c5e6f1cf8e265b10beaa34f739f34 source/XPolicyLab/policy/DP/diffusion_policy/model/bet/libraries/mingpt/model.py
99
+ 397620fbdb3b2c0e4bf021c5a6d0889d7c8d69e139d9fa091d584c2e6da56bc9 source/XPolicyLab/policy/DP/diffusion_policy/model/bet/libraries/mingpt/trainer.py
100
+ c875b0a8615564b768bccd674fba3d1a9faa8524cdc0640bf2dfc6c4b30d314e source/XPolicyLab/policy/DP/diffusion_policy/model/bet/libraries/mingpt/utils.py
101
+ 3b5c34ecbf6bb54182199811771eeb35dee2712e68fe90d5ba1c5c107e28c2fa source/XPolicyLab/policy/DP/diffusion_policy/model/bet/utils.py
102
+ ff3be833276dda9d395f6204aec6769f30317a68c8634ab37d7f375e274be1f0 source/XPolicyLab/policy/DP/diffusion_policy/model/common/dict_of_tensor_mixin.py
103
+ 3e91c244c0be4a4d758388e6db5882b9d616467239f5eef99a2d2d0e2a5636eb source/XPolicyLab/policy/DP/diffusion_policy/model/common/lr_scheduler.py
104
+ 37bb26e0ac9bcba6161dba613929d9d3f475f2bba683885fcb49df323d6dade7 source/XPolicyLab/policy/DP/diffusion_policy/model/common/module_attr_mixin.py
105
+ 6360c630fbe134dd7b311d279977104212c68b5987e54134fdfe64fc9cba0ae8 source/XPolicyLab/policy/DP/diffusion_policy/model/common/normalizer.py
106
+ af505851e7a530bda4f596801f5e44ae075846b2667d6c93148314d9a2cc044d source/XPolicyLab/policy/DP/diffusion_policy/model/common/rotation_transformer.py
107
+ 9751d6dc7342877a455a36fbccb4df6fb515cdb3b5ecbd2873e6d5c8fc876d3a source/XPolicyLab/policy/DP/diffusion_policy/model/common/shape_util.py
108
+ 3a00f0a6bada6490944f31502cfa3ed515515b91145d1d4146f11c4eb0e510dd source/XPolicyLab/policy/DP/diffusion_policy/model/common/tensor_util.py
109
+ 332a392e168ae4642ab197f1934bc2cf5c10010b994f9b2ed9975b90ee0f8c67 source/XPolicyLab/policy/DP/diffusion_policy/model/diffusion/conditional_unet1d.py
110
+ 4342ecb9391ffd053aadf38d4c833b5a7d68b79b442572fd1d786c07f1a9f12e source/XPolicyLab/policy/DP/diffusion_policy/model/diffusion/conv1d_components.py
111
+ c6f1ae757bb2b10e5d20d5875d9c8c7a1c620aa4ecea6424a87b4b1bea76bd1a source/XPolicyLab/policy/DP/diffusion_policy/model/diffusion/ema_model.py
112
+ d646443f3f2e3379d1e7b535605466248a851a86836136934deb75c1356614e5 source/XPolicyLab/policy/DP/diffusion_policy/model/diffusion/mask_generator.py
113
+ 87eaca54c0037e6084c6401425e9548b141366be3e5ab1544a6fdd24ae7d4e59 source/XPolicyLab/policy/DP/diffusion_policy/model/diffusion/positional_embedding.py
114
+ 76f9ea5ead2ca166a9868167ea49fbce018eb924960e05892eba2976b4945b03 source/XPolicyLab/policy/DP/diffusion_policy/model/diffusion/transformer_for_diffusion.py
115
+ ea7ca0e4ce7192b89d0ce70a6f0c056084480ac24b08063a8e5b191d4b1a247a source/XPolicyLab/policy/DP/diffusion_policy/model/vision/crop_randomizer.py
116
+ 07615235ef9675c47549712eb7d3f6764d6f9dad30c543f86c5a82ca322b0638 source/XPolicyLab/policy/DP/diffusion_policy/model/vision/model_getter.py
117
+ 68c446d507b29707153ef9a17342c399e3595321f83a23289a65e0d8a37e0f15 source/XPolicyLab/policy/DP/diffusion_policy/model/vision/multi_image_obs_encoder.py
118
+ 3765eda42f717caabf5d488e0e456adbc82133f516747163b4de4194102e8512 source/XPolicyLab/policy/DP/diffusion_policy/policy/base_image_policy.py
119
+ d5a50e36b6e57eb52267e8c35f87c8451ce74b66f043cf723198246a19b65181 source/XPolicyLab/policy/DP/diffusion_policy/policy/diffusion_unet_image_policy.py
120
+ ad39f770def1b305860e040c14489e6be7e30a7cfc405fe66640a6d11caf0789 source/XPolicyLab/policy/DP/diffusion_policy/process_data.py
121
+ 3409e41508f14718ab73ca6d26c854fda533228e2262be6c7aa7e51628e0a651 source/XPolicyLab/policy/DP/diffusion_policy/shared_memory/shared_memory_queue.py
122
+ c5f8d45da42b2581a6220a2f5efead87756d4785bb3b1ccd78e13846d85b29c6 source/XPolicyLab/policy/DP/diffusion_policy/shared_memory/shared_memory_ring_buffer.py
123
+ 4683afe1d810c25e941d75a2dc121e73353c422bfd41c105fc5f5ab3bb75efa7 source/XPolicyLab/policy/DP/diffusion_policy/shared_memory/shared_memory_util.py
124
+ 11f4a2dbb9b3722d36419b617b585d155ff5c55e8c15bb775d8f5c45de78bca6 source/XPolicyLab/policy/DP/diffusion_policy/shared_memory/shared_ndarray.py
125
+ 9e0a457e7d2c90409b7bec3723b61640e40a8f83a89b8eefd0652fa3602418ef source/XPolicyLab/policy/DP/diffusion_policy/workspace/base_workspace.py
126
+ 265307f01e353e84cadfe7981541809c6a7fb99cf0c19ddf3fb02c8fe2a0b5a0 source/XPolicyLab/policy/DP/diffusion_policy/workspace/robotworkspace.py
127
+ bb0635f951bfd55419a47fc08a859192049b4d0949cf2d09a4d4d6b2cafafb94 source/XPolicyLab/policy/Pi_05/openpi/.python-version
128
+ 43070e2d4e532684de521b885f385d0841030efa2b1a20bafb76133a5e1379c1 source/XPolicyLab/policy/Pi_05/openpi/LICENSE
129
+ 3e2c24001f9ef57bf7ec959a3658fbb49cdad113cdf394c264da9d16f9bdd132 source/XPolicyLab/policy/Pi_05/openpi/LICENSE_GEMMA.txt
130
+ 567fc57766bd736664f50126cab8145af4071ca16cc5e238f2b11e369169c3b5 source/XPolicyLab/policy/Pi_05/openpi/README.md
131
+ 00e8cb0e589d8f473588528f271f780fbe20cb67ba778e3e827d30cc3eb6cc92 source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/pyproject.toml
132
+ 91447944015cec709e8aa7655f7e9d64e1e4508e7023a57fe3746911c0fc6fed source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/__init__.py
133
+ 019b9d69cb26cc681331a2f95dbe60a2cc7b02d6d309c5d15b6457ab39798234 source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/action_chunk_broker.py
134
+ 88e98e0f06293f3c4767db675061664c4bba12f87242ba1e64377d1b8de8069e source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/base_policy.py
135
+ d48b4bd7f44e79fe6db8a8e07c9161144fa250be686e1245014a8b47e6171977 source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/image_tools.py
136
+ 4df4b0ba0b95ba5e47160039c3e837a64d50c802b419a588211dffbaa732589c source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/image_tools_test.py
137
+ c04568948fcee52b691e3be4b6cffb759f7e79ad67530fcd5d23095a0d13c057 source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/msgpack_numpy.py
138
+ 2c6dd236720dae716d7bdf842b7d506a165e9563bf9d4376c95289269adcb973 source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/msgpack_numpy_test.py
139
+ b559885afd9645a91b9b6ee12a28513295474f987d11b16610fc0479dbe6de5b source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/runtime/agent.py
140
+ c4d63952d1954bd4b72a3122223df36794812fea74cf1c7023433b5a90473c1c source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/runtime/agents/policy_agent.py
141
+ 1c12e5054b3401dec5f1f8b71eef0f625cb60e2b50784dcf19afa32c77107a7e source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/runtime/environment.py
142
+ 3daa242a9ce61ffb210789ef3ba6b1e3cade9de757fcd36af7b174c530345ea8 source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/runtime/runtime.py
143
+ d269a2af8ec4056beb310e5c3c97d4468af01549c7ef80dd905652d8ac64f85b source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/runtime/subscriber.py
144
+ 36557cb0b91ccf31cd4fb4b508306850d76ed0feb4028dac5182d0f5a5d88005 source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/websocket_client_policy.py
145
+ 83333f95befe8ae5649c3ab070ab93c74736efcb51c518a6248af338b2148709 source/XPolicyLab/policy/Pi_05/openpi/pyproject.toml
146
+ e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 source/XPolicyLab/policy/Pi_05/openpi/src/openpi/__init__.py
147
+ 626672e385fb276396c119e2220421065c58f8ec602401e8bf2ae509f9fffaf3 source/XPolicyLab/policy/Pi_05/openpi/src/openpi/conftest.py
148
+ e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/__init__.py
149
+ 7e42ada4ae7e9995f0ef3e33a0c224758323c2015e2d9d72ec15726a8a001d2a source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/gemma.py
150
+ 563c6e1ffd8afa31c406bcb8894a605e87df88f6c075d398d97a57af6bc3aefa source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/gemma_fast.py
151
+ ced28716950c34d84a1a6d0b03b1d9550000732721df884818080b6e78cb3289 source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/lora.py
152
+ a0f10525de7773310402b3ffa636e88ffff7035f3179b140aacc6809c122f085 source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/lora_test.py
153
+ 0d74bc1d8f4623ac3d8e543710b8bf75f9b95e588a3ebf6127c659e001385cff source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/model.py
154
+ f8e71f195045d4e3ef1ddfafb2337fa52e5aa2f89bce1fde62f5cbfb67121f21 source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/model_test.py
155
+ 24b32d7c6ed5e409459afa8ca5af96a4dae09c2dcdf48e828907e411f4f12342 source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/pi0.py
156
+ d321858c30b398126035ea2b6da09e1c422eeeebb5ebf8df631daf9dc77647fa source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/pi0_config.py
157
+ 627332a555046f2744ef144c45f8bd3361a9820cf68854a4528d0fdbba7e9aa3 source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/pi0_fast.py
158
+ 5082873014a7fc45fb8414f517909e1c24cdafea980a1fb612e0aea6058ed0fe source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/pi0_test.py
159
+ 14b4df0be280d5769fb0dc31a40cde27525dbb1980cc998c28475d62fa3cad32 source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/siglip.py
160
+ 965be8b3c393a6811875bbc32da9e01a5d01cc2f87802de801cf7293e049748c source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/tokenizer.py
161
+ 5abd179ce883420e39d4d18b33d0123290af752da243003aa48a3bc06dbb9517 source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/tokenizer_test.py
162
+ 88866638ee4775f46a222561a957bd35e20600fe38c5888b587016ad77b1065f source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/utils/fsq_tokenizer.py
163
+ d285d057636c3cba2d1fd3b37693b18075ad4b9c3b47bbde807c34c6c376ac93 source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/vit.py
164
+ 08fd8d750519f0fb44fc5173311e50a30f4c8f32c02e51244b4f8e47b32cd52f source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models_pytorch/gemma_pytorch.py
165
+ dcd7b6f508808ce4b7170a1720a4c62c6da04edae3652d16c94a469dca924e16 source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models_pytorch/pi0_pytorch.py
166
+ 6a44e91be2d7a724c6140d2cc98ed0a631b8d38bbb29f63b380a0a19f903bbf6 source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models_pytorch/preprocessing_pytorch.py
167
+ 26fd0d0f52730ab32b6f337eb73ae9a26cb71ae0915bc49eced1d0e2ed8d0ec6 source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models_pytorch/transformers_replace/models/gemma/configuration_gemma.py
168
+ 17eeb54e277939e58cd6f8a92719a275e36baf0c9f463b2754227d42f87aedde source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models_pytorch/transformers_replace/models/gemma/modeling_gemma.py
169
+ c945d330b829264f927f3ee5339f977238631772de07a28e855e265bb85fd53c source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models_pytorch/transformers_replace/models/paligemma/modeling_paligemma.py
170
+ 466e8eb7887ac5ccc98118a3169298d6ab65a284d834bae74751e3854dbc4245 source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models_pytorch/transformers_replace/models/siglip/check.py
171
+ ef2e99500f263fdd78db9d4d9a255e29d844eb92f53c25ad640f8056700ef84b source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models_pytorch/transformers_replace/models/siglip/modeling_siglip.py
172
+ c37aa90797665b1ec57cd5286fa5d6cbf29af0559ffce36d3fed98c02329eaea source/XPolicyLab/policy/Pi_05/openpi/src/openpi/policies/aloha_policy.py
173
+ 7d0893555964d485e231f70084125084a99495705ddd74b29461229d524fff26 source/XPolicyLab/policy/Pi_05/openpi/src/openpi/policies/droid_policy.py
174
+ ad01e5be74516d9ec9aeb1f76294d5c9f7f7179a60f1f7fbbb35e7646534f81a source/XPolicyLab/policy/Pi_05/openpi/src/openpi/policies/libero_policy.py
175
+ 509b8ffb151060f7373527d575bbb67f74a1877c592272eae07d7a680d454742 source/XPolicyLab/policy/Pi_05/openpi/src/openpi/policies/pika_bimanual_policy.py
176
+ 429f4be0309e0c7533a84b6719363d2b4b03ceecec3b82d48bf38043585abc17 source/XPolicyLab/policy/Pi_05/openpi/src/openpi/policies/pika_bimanual_policy_test.py
177
+ 5a19b73e8d9c60a9e21849bf482c0e9c72f454c3aa88f2de544a24f209913b99 source/XPolicyLab/policy/Pi_05/openpi/src/openpi/policies/policy.py
178
+ aaf42ab04a33b6c91d2447926211646c33ebd8ebfa427f026d7b6c4f7c45ec52 source/XPolicyLab/policy/Pi_05/openpi/src/openpi/policies/policy_config.py
179
+ 9dbb20963600367a7e7abfc97d1e326916777c57a87b39b1bc4070ba64676683 source/XPolicyLab/policy/Pi_05/openpi/src/openpi/policies/policy_test.py
180
+ 98046d038740dff6ebf41b0e3bf59674ac30246332a33cfc0624e5a06c855310 source/XPolicyLab/policy/Pi_05/openpi/src/openpi/policies/wuji_policy.py
181
+ e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 source/XPolicyLab/policy/Pi_05/openpi/src/openpi/py.typed
182
+ 1370d345e6c3c5b8f15573050e485e60a5b423d1df33e24b237805e6b442b026 source/XPolicyLab/policy/Pi_05/openpi/src/openpi/serving/websocket_policy_server.py
183
+ e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 source/XPolicyLab/policy/Pi_05/openpi/src/openpi/shared/__init__.py
184
+ 6524945566eab3eb97b75a6280ba4724617b4d028c55f05172b283c3de68a026 source/XPolicyLab/policy/Pi_05/openpi/src/openpi/shared/array_typing.py
185
+ ed0c86bf70796c5211908d6fe728334ab9a12dcca9d9b55ba801f8246ed7ecae source/XPolicyLab/policy/Pi_05/openpi/src/openpi/shared/download.py
186
+ 234ee70ab2501a1421f6c44cbd83c1e16747597023319ae1446bed9d44f17072 source/XPolicyLab/policy/Pi_05/openpi/src/openpi/shared/download_test.py
187
+ 0f8fcb355288119e56acb56d550c1cc1f3a9edddceb0dc5b319f955943ef7767 source/XPolicyLab/policy/Pi_05/openpi/src/openpi/shared/image_tools.py
188
+ 842374579dc9f4c2907da5e8bb555efe5a3f4902b659720c8e90115863dd59fe source/XPolicyLab/policy/Pi_05/openpi/src/openpi/shared/image_tools_test.py
189
+ 4da7111ba3011c4d1c381c9ed17257771df6a50ed89182647c3fb6f79208005e source/XPolicyLab/policy/Pi_05/openpi/src/openpi/shared/nnx_utils.py
190
+ 6c2cea4946fb07e51801530400d2b2fd94730e195cd290d6b6960114eca9739d source/XPolicyLab/policy/Pi_05/openpi/src/openpi/shared/normalize.py
191
+ fda27a21cf37f337b12bcab71229407c2a349c5965c33f278bdc468ed03f58af source/XPolicyLab/policy/Pi_05/openpi/src/openpi/shared/normalize_test.py
192
+ 3cc32682ec3609e9075dabd991488edb9d7f6c045443f58963d733f99c468dbd source/XPolicyLab/policy/Pi_05/openpi/src/openpi/training/checkpoints.py
193
+ b224ba8a661c1f3f6ddc70c2cb0159b842065d9688fd4280ff848f8821c4f99f source/XPolicyLab/policy/Pi_05/openpi/src/openpi/training/config.py
194
+ 21ed6c95ae43edc7c9cb9b7684187f0f38c4949ad366c826e499df59952660ee source/XPolicyLab/policy/Pi_05/openpi/src/openpi/training/data_loader.py
195
+ a0cf1bc293e8b0eb9bc5516bc05d30d9940da06c94fcfa1addca7267f8358815 source/XPolicyLab/policy/Pi_05/openpi/src/openpi/training/data_loader_test.py
196
+ 1d3a057a040240218234d7dbc6680ee4fe8256f2058531a0f9fefd3f7ee995a4 source/XPolicyLab/policy/Pi_05/openpi/src/openpi/training/droid_rlds_dataset.py
197
+ c2ab92efb5e0d675118ad812113fd1c3cb3a62cdab5d79066014266e82df12d8 source/XPolicyLab/policy/Pi_05/openpi/src/openpi/training/misc/polaris_config.py
198
+ 914acdd74ccf90e6779c13a5093140595c7e4f687e9e0b167439446a81d74c01 source/XPolicyLab/policy/Pi_05/openpi/src/openpi/training/misc/roboarena_config.py
199
+ cfb5d6f6aec61fbe961287b4015c652260628a0ed4682a0dbdc271b8e65431fa source/XPolicyLab/policy/Pi_05/openpi/src/openpi/training/optimizer.py
200
+ c67c4112a126ab097571c8a882fd1ee3f106b15b6e608e7205ac7f29b44ca985 source/XPolicyLab/policy/Pi_05/openpi/src/openpi/training/sharding.py
201
+ b684e674343f86ef5e976f279a586d3fe2f885e901f396ac899ed136abc7eca6 source/XPolicyLab/policy/Pi_05/openpi/src/openpi/training/utils.py
202
+ ef98cee058972ef54269c2a41f81ad265bc3f137432044824c09e1a0462ef714 source/XPolicyLab/policy/Pi_05/openpi/src/openpi/training/weight_loaders.py
203
+ 9f40be2871c01f42f1a58e60fdc3b20641cff87bb147abc3be8fdbc8ae39aaf8 source/XPolicyLab/policy/Pi_05/openpi/src/openpi/transforms.py
204
+ f84cb46a5c4b4bd819871376038c35da8662d85f67a2284822ea068d610fb2fb source/XPolicyLab/policy/Pi_05/openpi/src/openpi/transforms_test.py
205
+ 2ffa14b9cb4c46791b11785cab6a003cca70fa696f8db3af52fc6e745a15b1e8 source/XPolicyLab/policy/Pi_05/openpi/uv.lock
206
+ 837e79146271a02da46ed20ee619c267adc1979fa7589cc1c0a78c467b81979f source/xpolicylab_local_changes.patch
207
+ d14af952c5234e43d41b3dae24f05aa0cb265548114b4d65c2357bd106a97fb7 verify_files.py
real_inference/provenance.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "xpolicylab_git_commit": "1e815ad750ba27407ec2e1a97cb4674a43d0734d",
3
+ "source_snapshot": "selected actual server working tree including uncommitted changes",
4
+ "model_files": {
5
+ "act": "models/act/policy_best.ckpt",
6
+ "act_stats": "models/act/dataset_stats.pkl",
7
+ "dp": "models/dp/10.ckpt",
8
+ "pi05": "models/pi05/29999",
9
+ "pi05_tokenizer": "models/shared/openpi/big_vision/paligemma_tokenizer.model"
10
+ },
11
+ "fixture": "fixtures/0041_episode0_frame100.npz",
12
+ "instruction": "Fold the garment.",
13
+ "camera_order": [
14
+ "cam_high",
15
+ "cam_left_wrist",
16
+ "cam_right_wrist"
17
+ ],
18
+ "action_order": [
19
+ "left_joint_1_to_6",
20
+ "left_gripper",
21
+ "right_joint_1_to_6",
22
+ "right_gripper"
23
+ ],
24
+ "dt_seconds": 0.04,
25
+ "act_prediction_steps": 50,
26
+ "dp_observation_steps": 3,
27
+ "dp_prediction_horizon": 8,
28
+ "dp_executable_steps": 6,
29
+ "pi05_prediction_steps": 50,
30
+ "pi05_replan_steps": 5
31
+ }
real_inference/reference/deform_manip_sim/__init__.py ADDED
File without changes
real_inference/reference/deform_manip_sim/policy/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Minimal policy protocol package for the offline reference adapter."""
real_inference/reference/deform_manip_sim/policy/aloha/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Adapters for dual-Piper three-camera Aloha policies."""
real_inference/reference/deform_manip_sim/policy/aloha/adapters.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Checkpoint-specific policy adapters, loaded in each policy's own environment."""
2
+ from collections import deque
3
+ from pathlib import Path
4
+ import os, pickle, sys
5
+ import numpy as np
6
+ from deform_manip_sim.policy.schema import ActionChunk
7
+
8
+ ROOT=Path('/data2/wushuang/my_projects/RoboDojo/XPolicyLab')
9
+ CAMERAS=('cam_high','cam_left_wrist','cam_right_wrist')
10
+ DT=.04
11
+
12
+ def _images(obs):
13
+ missing=set(CAMERAS)-set(obs.images)
14
+ if missing: raise ValueError(f'Aloha policy needs three cameras; missing {sorted(missing)}')
15
+ return {k:np.asarray(obs.images[k],dtype=np.uint8) for k in CAMERAS}
16
+
17
+ class ACTAdapter:
18
+ def __init__(self):
19
+ import argparse,torch
20
+ os.environ['ACT_ACTION_DIM']='14'
21
+ sys.path.insert(0,str(ROOT/'policy/ACT'))
22
+ from detr.act_policy import ACTPolicy
23
+ from detr.main import get_args_parser
24
+ p=argparse.ArgumentParser(parents=[get_args_parser()])
25
+ a=p.parse_args(['--ckpt_dir','/tmp','--policy_class','ACT','--bench_name','aloha','--task_name','aloha','--seed','42','--num_epochs','1','--chunk_size','50'])
26
+ for k,v in dict(lr=1e-5,lr_backbone=1e-5,backbone='resnet18',enc_layers=4,dec_layers=7,nheads=8,hidden_dim=512,dim_feedforward=3200,camera_names=list(CAMERAS)).items():setattr(a,k,v)
27
+ self.torch=torch;self.device=torch.device('cuda:0');self.model=ACTPolicy({'kl_weight':10},a)
28
+ base=Path(os.environ.get('ALOHA_ACT_CHECKPOINT_DIR',str(ROOT/'policy/ACT/checkpoints/aloha_garment_aloha_rgb3')))
29
+ with (base/'dataset_stats.pkl').open('rb') as f:self.stats=pickle.load(f)
30
+ self.model.load_state_dict(torch.load(base/'policy_best.ckpt',map_location=self.device,weights_only=True));self.model.eval()
31
+ def reset(self):pass
32
+ def __call__(self,obs):
33
+ images=_images(obs);torch=self.torch
34
+ x=np.stack([images[k].transpose(2,0,1) for k in CAMERAS]).astype(np.float32)/255
35
+ q=(obs.qpos-self.stats['qpos_mean'])/self.stats['qpos_std']
36
+ with torch.inference_mode(): out=self.model(torch.as_tensor(q,device=self.device).float()[None],torch.as_tensor(x,device=self.device)[None]).cpu().numpy()[0]
37
+ out=out*self.stats['action_std']+self.stats['action_mean']
38
+ return ActionChunk('joint_position',DT,out,{'policy':'act','execute_steps':50,'observation_steps':1})
39
+
40
+ class DPAdapter:
41
+ def __init__(self):
42
+ import torch,hydra,dill
43
+ sys.path.insert(0,str(ROOT/'policy/DP'))
44
+ from omegaconf import OmegaConf
45
+ OmegaConf.register_new_resolver('eval',eval,replace=True)
46
+ path=Path(os.environ.get('ALOHA_DP_CHECKPOINT',str(ROOT/'policy/DP/checkpoints/dp-42/10.ckpt')))
47
+ with path.open('rb') as f: payload=torch.load(f,pickle_module=dill,map_location='cpu',weights_only=False)
48
+ cfg=payload['cfg'];workspace=hydra.utils.get_class(cfg._target_)(cfg,output_dir=None)
49
+ workspace.load_payload(payload,exclude_keys=None,include_keys=None)
50
+ self.model=workspace.ema_model if cfg.training.use_ema else workspace.model
51
+ self.model.to('cuda:0').eval();self.torch=torch;self.history=deque(maxlen=3)
52
+ def reset(self):self.history.clear()
53
+ def __call__(self,obs):
54
+ import cv2
55
+ def preprocess(item):
56
+ images=_images(item)
57
+ frame={key:cv2.resize(images[src],(320,240),interpolation=cv2.INTER_AREA).transpose(2,0,1).astype(np.float32)/255 for key,src in zip(('head_cam','left_cam','right_cam'),CAMERAS)}
58
+ frame['agent_pos']=np.asarray(item.qpos,dtype=np.float32).copy()
59
+ return frame
60
+ if obs.history:
61
+ self.history.clear()
62
+ self.history.extend(preprocess(item) for item in (*obs.history,obs))
63
+ else:
64
+ self.history.append(preprocess(obs))
65
+ frame=self.history[-1]
66
+ seq=[self.history[0]]*(3-len(self.history))+list(self.history)
67
+ data={k:self.torch.from_numpy(np.stack([f[k] for f in seq]))[None].to('cuda:0') for k in frame}
68
+ with self.torch.inference_mode():out=self.model.predict_action(data)['action'][0].detach().cpu().numpy()
69
+ return ActionChunk('joint_position',DT,out,{'policy':'dp','execute_steps':6,'observation_steps':3})
70
+
71
+ class Pi05Adapter:
72
+ def __init__(self):
73
+ from openpi.training import config
74
+ from openpi.policies import policy_config
75
+ ck=Path(os.environ.get('ALOHA_PI05_CHECKPOINT',str(ROOT/'policy/Pi_05/openpi/checkpoints/pi05_aloha_garment_lora/aloha_rgb3_lora/29999')))
76
+ self.policy=policy_config.create_trained_policy(config.get_config('pi05_aloha_garment_lora'),ck)
77
+ def reset(self):pass
78
+ def __call__(self,obs):
79
+ images=_images(obs)
80
+ data={'state':np.asarray(obs.qpos,dtype=np.float32),'images':{k:v.transpose(2,0,1) for k,v in images.items()},'prompt':obs.instruction}
81
+ out=np.asarray(self.policy.infer(data)['actions'],dtype=np.float32)
82
+ return ActionChunk('joint_position',DT,out,{'policy':'pi05','execute_steps':5,'observation_steps':1})
83
+
84
+ class HoldAdapter:
85
+ """Testing only: hold the currently observed 14-D joint position."""
86
+ def reset(self):pass
87
+ def __call__(self,obs):
88
+ _images(obs)
89
+ return ActionChunk('joint_position',DT,np.asarray(obs.qpos,np.float32)[None])
real_inference/reference/deform_manip_sim/policy/bridge_client.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Non-blocking localhost WebSocket client used from Kit's physics loop.
2
+
3
+ The transport intentionally uses ``websockets.sync.client`` in its dedicated
4
+ thread. Isaac Sim patches ``asyncio.run`` process-wide for its Kit event
5
+ engine; creating a second asyncio runner from Script Editor can corrupt that
6
+ main loop. Synchronous I/O is safe here because the worker never touches USD,
7
+ PhysX, or Kit APIs and the physics callback only accesses thread-safe queues.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import inspect
13
+ import json
14
+ import queue
15
+ import threading
16
+ import time
17
+ from dataclasses import dataclass
18
+ from typing import Any
19
+
20
+ from .schema import ActionChunk, Observation, action_chunk_from_wire
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class BridgeStatus:
25
+ connected: bool
26
+ request_pending: bool
27
+ last_error: str | None
28
+ last_latency_ms: float | None
29
+ submitted_requests: int
30
+ received_actions: int
31
+
32
+
33
+ class PolicyBridgeClient:
34
+ """Own all network waits in a daemon thread, never in a PhysX callback.
35
+
36
+ The bridge allows only one in-flight observation. That intentional
37
+ backpressure keeps a slow policy from accumulating stale camera frames and
38
+ executing actions for a past cloth state.
39
+ """
40
+
41
+ def __init__(
42
+ self,
43
+ url: str,
44
+ *,
45
+ response_timeout_s: float = 2.0,
46
+ reconnect_delay_s: float = 1.0,
47
+ max_message_bytes: int = 32 * 1024 * 1024,
48
+ ) -> None:
49
+ if response_timeout_s <= 0.0 or reconnect_delay_s <= 0.0:
50
+ raise ValueError("response_timeout_s and reconnect_delay_s must be positive")
51
+ self.url = str(url)
52
+ self.response_timeout_s = float(response_timeout_s)
53
+ self.reconnect_delay_s = float(reconnect_delay_s)
54
+ self.max_message_bytes = int(max_message_bytes)
55
+ self._outbound: queue.Queue[tuple[int, Observation, float]] = queue.Queue(maxsize=1)
56
+ self._inbound: queue.Queue[ActionChunk] = queue.Queue(maxsize=1)
57
+ self._lock = threading.Lock()
58
+ self._stop_event = threading.Event()
59
+ self._thread: threading.Thread | None = None
60
+ self._websocket: Any | None = None
61
+ self._next_request_id = 1
62
+ self._connected = False
63
+ self._request_pending = False
64
+ self._last_error: str | None = None
65
+ self._last_latency_ms: float | None = None
66
+ self._submitted_requests = 0
67
+ self._received_actions = 0
68
+
69
+ def start(self) -> None:
70
+ if self._thread is not None and self._thread.is_alive():
71
+ if self._stop_event.is_set():
72
+ raise RuntimeError("Policy bridge is still closing; start a new session")
73
+ return
74
+ self._stop_event.clear()
75
+ self._thread = threading.Thread(target=self._thread_main, name="deform-manip-policy-bridge", daemon=True)
76
+ self._thread.start()
77
+
78
+ def close(self, join_timeout_s: float = 2.0) -> None:
79
+ self._stop_event.set()
80
+ # ``recv(timeout=...)`` normally bounds shutdown latency. Closing the
81
+ # socket as well wakes a worker currently blocked in a long receive.
82
+ with self._lock:
83
+ websocket = self._websocket
84
+ if websocket is not None:
85
+ try:
86
+ if join_timeout_s <= 0:
87
+ threading.Thread(target=websocket.close, name="policy-socket-close", daemon=True).start()
88
+ else:
89
+ websocket.close()
90
+ except Exception:
91
+ pass
92
+ thread = self._thread
93
+ if thread is not None and thread.is_alive():
94
+ thread.join(timeout=max(0.0, float(join_timeout_s)))
95
+ if thread is None or not thread.is_alive():
96
+ self._thread = None
97
+ with self._lock:
98
+ self._connected = False
99
+ self._request_pending = False
100
+ self._drain(self._outbound)
101
+ self._drain(self._inbound)
102
+
103
+ @staticmethod
104
+ def _drain(items: queue.Queue[Any]) -> None:
105
+ while True:
106
+ try:
107
+ items.get_nowait()
108
+ except queue.Empty:
109
+ return
110
+
111
+ def submit(self, observation: Observation) -> bool:
112
+ """Queue one newest observation, returning false when one is pending."""
113
+ with self._lock:
114
+ if self._stop_event.is_set() or self._request_pending:
115
+ return False
116
+ request_id = self._next_request_id
117
+ self._next_request_id += 1
118
+ self._request_pending = True
119
+ self._submitted_requests += 1
120
+ try:
121
+ self._outbound.put_nowait((request_id, observation, time.monotonic()))
122
+ except queue.Full:
123
+ # This should be unreachable because _request_pending was false,
124
+ # but preserve the invariant if a thread is being shut down.
125
+ with self._lock:
126
+ self._request_pending = False
127
+ self._last_error = "outbound policy queue unexpectedly full"
128
+ return False
129
+ return True
130
+
131
+ def poll_action(self) -> ActionChunk | None:
132
+ """Return at most one validated response without blocking Kit."""
133
+ try:
134
+ return self._inbound.get_nowait()
135
+ except queue.Empty:
136
+ return None
137
+
138
+ def status(self) -> BridgeStatus:
139
+ with self._lock:
140
+ return BridgeStatus(
141
+ connected=self._connected,
142
+ request_pending=self._request_pending,
143
+ last_error=self._last_error,
144
+ last_latency_ms=self._last_latency_ms,
145
+ submitted_requests=self._submitted_requests,
146
+ received_actions=self._received_actions,
147
+ )
148
+
149
+ def _set_error(self, error: Exception | str) -> None:
150
+ message = str(error)
151
+ with self._lock:
152
+ self._last_error = message
153
+ self._connected = False
154
+ self._request_pending = False
155
+
156
+ def _thread_main(self) -> None:
157
+ try:
158
+ from websockets.sync.client import connect
159
+ except ImportError as error:
160
+ self._set_error(
161
+ "The Kit Python environment needs websockets.sync.client for policy bridging: "
162
+ f"{error}"
163
+ )
164
+ return
165
+
166
+ while not self._stop_event.is_set():
167
+ websocket: Any | None = None
168
+ try:
169
+ # ``proxy=None`` is essential on machines with HTTP(S)_PROXY:
170
+ # websockets >=15 otherwise tries to proxy even 127.0.0.1.
171
+ # Keep a narrow fallback for old sync-client releases that do
172
+ # not expose this keyword.
173
+ connect_kwargs: dict[str, Any] = {
174
+ "compression": None,
175
+ "max_size": self.max_message_bytes,
176
+ "open_timeout": self.response_timeout_s,
177
+ }
178
+ try:
179
+ if "proxy" in inspect.signature(connect).parameters:
180
+ connect_kwargs["proxy"] = None
181
+ except (TypeError, ValueError):
182
+ pass
183
+ websocket = connect(self.url, **connect_kwargs)
184
+ with self._lock:
185
+ self._websocket = websocket
186
+ self._last_error = None
187
+ # Reset model-specific state (for example a DP observation
188
+ # deque) once for every newly established connection, before
189
+ # the first observation is sent. The service's reset response
190
+ # intentionally has no request_id because it is not an action.
191
+ websocket.send(json.dumps({"kind": "reset"}, separators=(",", ":")))
192
+ reset_response = json.loads(websocket.recv(timeout=self.response_timeout_s))
193
+ if reset_response.get("kind") != "reset" or not reset_response.get("ok", False):
194
+ raise RuntimeError(f"Policy reset was rejected: {reset_response}")
195
+ with self._lock:
196
+ self._connected = True
197
+ self._serve_connection_sync(websocket)
198
+ except Exception as error:
199
+ if not self._stop_event.is_set():
200
+ self._set_error(error)
201
+ # Event.wait is interruptible by close(), unlike sleep().
202
+ self._stop_event.wait(self.reconnect_delay_s)
203
+ finally:
204
+ if websocket is not None:
205
+ try:
206
+ websocket.close()
207
+ except Exception:
208
+ pass
209
+ with self._lock:
210
+ if self._websocket is websocket:
211
+ self._websocket = None
212
+ self._connected = False
213
+
214
+ def _serve_connection_sync(self, websocket: Any) -> None:
215
+ """Send one request at a time on the worker thread's sync socket."""
216
+ while not self._stop_event.is_set():
217
+ try:
218
+ # A finite queue wait lets ``close()`` join promptly even when
219
+ # no policy observations are currently being produced.
220
+ request_id, observation, submitted_at = self._outbound.get(timeout=0.05)
221
+ except queue.Empty:
222
+ continue
223
+ try:
224
+ websocket.send(json.dumps(observation.to_wire(request_id), separators=(",", ":")))
225
+ raw_response = websocket.recv(timeout=self.response_timeout_s)
226
+ response = json.loads(raw_response)
227
+ if int(response.get("request_id", -1)) != request_id:
228
+ raise RuntimeError(
229
+ f"Policy response request_id={response.get('request_id')!r} does not match {request_id}"
230
+ )
231
+ action_chunk = action_chunk_from_wire(response)
232
+ # A full queue contains a less recent policy result. Drop it:
233
+ # executing stale cloth actions is worse than skipping one.
234
+ self._drain(self._inbound)
235
+ self._inbound.put_nowait(action_chunk)
236
+ with self._lock:
237
+ self._last_latency_ms = (time.monotonic() - submitted_at) * 1000.0
238
+ self._received_actions += 1
239
+ self._request_pending = False
240
+ self._last_error = None
241
+ except Exception as error:
242
+ self._set_error(error)
243
+ # Let the outer loop close and reconnect; a policy process may
244
+ # have restarted or the server may have rejected a payload.
245
+ raise
real_inference/reference/deform_manip_sim/policy/schema.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Versioned, model-independent policy wire contract.
2
+
3
+ Images are sent as uncompressed RGB in the first implementation. Two
4
+ 640x480 wrist frames are roughly 1.8 MB per request, which is acceptable for
5
+ a localhost smoke test and avoids adding image-codec dependencies to Kit.
6
+ The ``encoding`` field keeps the protocol extensible to JPEG later.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import base64
12
+ from dataclasses import dataclass
13
+ from typing import Any, Mapping
14
+
15
+ import numpy as np
16
+
17
+
18
+ SCHEMA_VERSION = "deform_manip_sim.v1"
19
+ WRIST_CAMERA_NAMES = ("cam_left_wrist", "cam_right_wrist")
20
+ ACTION_DIMS = {
21
+ "joint_position": 14,
22
+ # Per arm: world position xyz, orientation [w, x, y, z], gripper openness.
23
+ "ee_pose": 16,
24
+ # Per arm: world-frame translation xyz, rotation-vector xyz, gripper openness.
25
+ "ee_delta": 14,
26
+ }
27
+
28
+
29
+ def _float_vector(value: Any, shape: tuple[int, ...], name: str) -> np.ndarray:
30
+ result = np.asarray(value, dtype=np.float32)
31
+ if result.shape != shape or not np.isfinite(result).all():
32
+ raise ValueError(f"{name} must be finite float32 with shape {shape}, got {result.shape}")
33
+ return result
34
+
35
+
36
+ def _rgb_image(value: Any, name: str) -> np.ndarray:
37
+ if hasattr(value, "detach"):
38
+ value = value.detach().cpu().numpy()
39
+ array = np.asarray(value)
40
+ if array.ndim != 3 or array.shape[2] != 3:
41
+ raise ValueError(f"{name} must have RGB HWC shape (H, W, 3), got {array.shape}")
42
+ if array.dtype != np.uint8:
43
+ # Isaac Sim may provide float RGB in some annotator configurations.
44
+ # This conversion is explicit and bounded rather than silently sending
45
+ # an unknown numeric range to the model server.
46
+ if not np.isfinite(array).all():
47
+ raise ValueError(f"{name} contains non-finite RGB values")
48
+ if array.size and float(array.max()) <= 1.0 and float(array.min()) >= 0.0:
49
+ array = np.rint(array * 255.0)
50
+ array = np.clip(array, 0, 255).astype(np.uint8)
51
+ return np.ascontiguousarray(array)
52
+
53
+
54
+ def encode_rgb(image: np.ndarray) -> dict[str, Any]:
55
+ """Encode a HWC uint8 RGB image into JSON-safe raw bytes."""
56
+ image = _rgb_image(image, "image")
57
+ return {
58
+ "encoding": "raw_rgb",
59
+ "shape": list(image.shape),
60
+ "data_b64": base64.b64encode(image.tobytes()).decode("ascii"),
61
+ }
62
+
63
+
64
+ def decode_rgb(payload: Mapping[str, Any]) -> np.ndarray:
65
+ """Decode an image emitted by :func:`encode_rgb` in the policy process."""
66
+ if payload.get("encoding") != "raw_rgb":
67
+ raise ValueError(f"Unsupported image encoding {payload.get('encoding')!r}")
68
+ shape = tuple(int(x) for x in payload.get("shape", ()))
69
+ if len(shape) != 3 or shape[2] != 3 or min(shape[:2], default=0) <= 0:
70
+ raise ValueError(f"Invalid raw_rgb shape {shape}")
71
+ raw = base64.b64decode(payload["data_b64"], validate=True)
72
+ expected = int(np.prod(shape))
73
+ if len(raw) != expected:
74
+ raise ValueError(f"raw_rgb byte count is {len(raw)}, expected {expected} for shape {shape}")
75
+ return np.frombuffer(raw, dtype=np.uint8).reshape(shape).copy()
76
+
77
+
78
+ @dataclass(frozen=True)
79
+ class Observation:
80
+ """A single wrist-only simulator observation before model preprocessing.
81
+
82
+ ``policy_state`` is optional diagnostic input for replaying a recorded
83
+ training observation while executing its predicted local action from the
84
+ *current* simulator end-effector pose. Normal closed-loop simulation
85
+ leaves it as ``None``: policy adapters then derive their state from
86
+ ``qpos`` and ``ee_pose`` exactly as before.
87
+ """
88
+
89
+ timestamp_ns: int
90
+ episode_step: int
91
+ instruction: str
92
+ images: Mapping[str, np.ndarray]
93
+ qpos: np.ndarray
94
+ ee_pose: np.ndarray
95
+ policy_state: np.ndarray | None = None
96
+ history: tuple[Observation, ...] = ()
97
+
98
+ def __post_init__(self) -> None:
99
+ if int(self.timestamp_ns) < 0 or int(self.episode_step) < 0:
100
+ raise ValueError("timestamp_ns and episode_step must be non-negative")
101
+ if not isinstance(self.instruction, str):
102
+ raise TypeError("instruction must be a string")
103
+ names = set(self.images)
104
+ required = set(WRIST_CAMERA_NAMES)
105
+ if names not in (required, required | {"cam_high"}):
106
+ raise ValueError(f"Observation must have both wrist cameras and optional cam_high, got {sorted(names)}")
107
+ for name in self.images:
108
+ _rgb_image(self.images[name], name)
109
+ _float_vector(self.qpos, (14,), "qpos")
110
+ _float_vector(self.ee_pose, (14,), "ee_pose")
111
+ if self.policy_state is not None:
112
+ _float_vector(self.policy_state, (14,), "policy_state")
113
+ if len(self.history) > 2:
114
+ raise ValueError('At most two previous observations are supported')
115
+ for i, previous in enumerate(self.history):
116
+ if not isinstance(previous, Observation) or previous.history:
117
+ raise ValueError('History must contain unnested Observation objects')
118
+ if previous.episode_step != self.episode_step-len(self.history)+i:
119
+ raise ValueError('History must contain consecutive previous control steps')
120
+
121
+ def to_wire(self, request_id: int) -> dict[str, Any]:
122
+ """Return a JSON-compatible request accepted by ``serve_policy.py``."""
123
+ robot = {
124
+ "qpos": _float_vector(self.qpos, (14,), "qpos").tolist(),
125
+ "ee_pose": _float_vector(self.ee_pose, (14,), "ee_pose").tolist(),
126
+ }
127
+ if self.policy_state is not None:
128
+ robot["policy_state"] = _float_vector(self.policy_state, (14,), "policy_state").tolist()
129
+ result = {
130
+ "kind": "observation",
131
+ "schema_version": SCHEMA_VERSION,
132
+ "request_id": int(request_id),
133
+ "observation": {
134
+ "timestamp_ns": int(self.timestamp_ns),
135
+ "episode_step": int(self.episode_step),
136
+ "instruction": self.instruction,
137
+ "images": {name: encode_rgb(image) for name, image in self.images.items()},
138
+ "robot": robot,
139
+ },
140
+ }
141
+ if self.history:
142
+ result['observation']['history'] = [item.to_wire(0)['observation'] for item in self.history]
143
+ return result
144
+
145
+
146
+ def observation_from_wire(payload: Mapping[str, Any]) -> Observation:
147
+ """Decode a wire observation in the external policy process."""
148
+ if payload.get("schema_version") != SCHEMA_VERSION:
149
+ raise ValueError(f"Unsupported schema version {payload.get('schema_version')!r}")
150
+ data = payload["observation"]
151
+ images = {name: decode_rgb(image) for name, image in data["images"].items()}
152
+ robot = data["robot"]
153
+ return Observation(
154
+ timestamp_ns=int(data["timestamp_ns"]),
155
+ episode_step=int(data["episode_step"]),
156
+ instruction=str(data["instruction"]),
157
+ images=images,
158
+ qpos=np.asarray(robot["qpos"], dtype=np.float32),
159
+ ee_pose=np.asarray(robot["ee_pose"], dtype=np.float32),
160
+ policy_state=(
161
+ np.asarray(robot["policy_state"], dtype=np.float32) if robot.get("policy_state") is not None else None
162
+ ),
163
+ history=tuple(observation_from_wire({'schema_version': SCHEMA_VERSION, 'observation': item})
164
+ for item in data.get('history', ())),
165
+ )
166
+
167
+
168
+ @dataclass(frozen=True)
169
+ class ActionChunk:
170
+ """A time-ordered sequence of canonical robot commands."""
171
+
172
+ action_type: str
173
+ dt: float
174
+ actions: np.ndarray
175
+ # Optional, JSON-safe evidence emitted by an external adapter. It is
176
+ # never interpreted by PhysX; dataset-input diagnostics use it to retain
177
+ # the model-space action before coordinate conversion.
178
+ diagnostics: Mapping[str, Any] | None = None
179
+
180
+ def __post_init__(self) -> None:
181
+ if self.action_type not in ACTION_DIMS:
182
+ raise ValueError(f"Unsupported action_type {self.action_type!r}; expected one of {sorted(ACTION_DIMS)}")
183
+ if not np.isfinite(self.dt) or float(self.dt) <= 0.0:
184
+ raise ValueError(f"ActionChunk dt must be positive and finite, got {self.dt!r}")
185
+ actions = np.asarray(self.actions, dtype=np.float32)
186
+ if actions.ndim == 1:
187
+ actions = actions[None, :]
188
+ expected = ACTION_DIMS[self.action_type]
189
+ if actions.ndim != 2 or actions.shape[0] == 0 or actions.shape[1] != expected or not np.isfinite(actions).all():
190
+ raise ValueError(
191
+ f"{self.action_type} actions must be finite shape (horizon, {expected}), got {actions.shape}"
192
+ )
193
+ object.__setattr__(self, "actions", np.ascontiguousarray(actions))
194
+ if self.diagnostics is not None and not isinstance(self.diagnostics, Mapping):
195
+ raise TypeError("ActionChunk diagnostics must be a mapping when provided")
196
+ if self.diagnostics is not None:
197
+ object.__setattr__(self, "diagnostics", dict(self.diagnostics))
198
+
199
+ def to_wire(self, request_id: int) -> dict[str, Any]:
200
+ action = {
201
+ "action_type": self.action_type,
202
+ "dt": float(self.dt),
203
+ "actions": self.actions.tolist(),
204
+ }
205
+ if self.diagnostics is not None:
206
+ action["diagnostics"] = dict(self.diagnostics)
207
+ return {
208
+ "kind": "action",
209
+ "schema_version": SCHEMA_VERSION,
210
+ "request_id": int(request_id),
211
+ "action": action,
212
+ }
213
+
214
+
215
+ def action_chunk_from_wire(payload: Mapping[str, Any]) -> ActionChunk:
216
+ """Decode and validate a policy response before it reaches PhysX."""
217
+ if payload.get("schema_version") != SCHEMA_VERSION:
218
+ raise ValueError(f"Unsupported schema version {payload.get('schema_version')!r}")
219
+ if payload.get("kind") != "action":
220
+ raise ValueError(f"Expected policy response kind='action', got {payload.get('kind')!r}")
221
+ action = payload["action"]
222
+ return ActionChunk(
223
+ action_type=str(action["action_type"]),
224
+ dt=float(action["dt"]),
225
+ actions=np.asarray(action["actions"], dtype=np.float32),
226
+ diagnostics=action.get("diagnostics"),
227
+ )
real_inference/reference/scripts/serve_policy.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Serve a canonical policy over localhost WebSocket.
3
+
4
+ This file intentionally does not contain DP or pi0.5 dependencies. Use the
5
+ mock modes to validate DeformManipSim end-to-end, then pass ``--adapter`` to
6
+ load a callable from the Python environment that owns a real checkpoint.
7
+
8
+ Adapter contract::
9
+
10
+ def adapter(observation: Observation) -> ActionChunk | dict:
11
+ ...
12
+
13
+ The returned dict must have ``action_type``, ``dt`` and ``actions`` fields.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ import asyncio
20
+ import importlib
21
+ import json
22
+ import sys
23
+ import time
24
+ from pathlib import Path
25
+ from typing import Any, Callable
26
+
27
+ import numpy as np
28
+
29
+
30
+ PROJECT_ROOT = Path(__file__).resolve().parents[1]
31
+ if str(PROJECT_ROOT) not in sys.path:
32
+ sys.path.insert(0, str(PROJECT_ROOT))
33
+
34
+ from deform_manip_sim.policy.schema import ActionChunk, Observation, action_chunk_from_wire, observation_from_wire
35
+
36
+
37
+ def _chunk(action_type: str, dt: float, actions: Any) -> ActionChunk:
38
+ return ActionChunk(action_type=action_type, dt=dt, actions=np.asarray(actions, dtype=np.float32))
39
+
40
+
41
+ def hold_policy(observation: Observation) -> ActionChunk:
42
+ """Echo qpos as a safe 14-D joint-position command."""
43
+ return _chunk("joint_position", 0.1, observation.qpos[None, :])
44
+
45
+
46
+ def joint_demo_policy(observation: Observation) -> ActionChunk:
47
+ """Small, reversible left-joint motion for bridge smoke testing only."""
48
+ action = observation.qpos.copy()
49
+ phase = (observation.episode_step % 40) / 39.0
50
+ action[1] = np.float32(0.15 * np.sin(2.0 * np.pi * phase))
51
+ action[8] = np.float32(-0.15 * np.sin(2.0 * np.pi * phase))
52
+ return _chunk("joint_position", 0.1, action[None, :])
53
+
54
+
55
+ def ee_demo_policy(observation: Observation) -> ActionChunk:
56
+ """Return the current commanded Cartesian poses without moving them."""
57
+ action = np.empty(16, dtype=np.float32)
58
+ action[0:7] = observation.ee_pose[0:7]
59
+ action[7] = observation.qpos[6]
60
+ action[8:15] = observation.ee_pose[7:14]
61
+ action[15] = observation.qpos[13]
62
+ return _chunk("ee_pose", 0.1, action[None, :])
63
+
64
+
65
+ def _load_adapter(spec: str) -> Callable[[Observation], ActionChunk]:
66
+ if ":" not in spec:
67
+ raise ValueError("--adapter must have MODULE:ATTRIBUTE form")
68
+ module_name, attribute_name = spec.split(":", 1)
69
+ obj = getattr(importlib.import_module(module_name), attribute_name)
70
+ # Accept either a function or a no-argument adapter class/instance.
71
+ adapter = obj() if isinstance(obj, type) else obj
72
+ if not callable(adapter):
73
+ raise TypeError(f"Adapter {spec!r} is not callable")
74
+
75
+ def call(observation: Observation) -> ActionChunk:
76
+ output = adapter(observation)
77
+ if isinstance(output, ActionChunk):
78
+ return output
79
+ if isinstance(output, dict):
80
+ return ActionChunk(
81
+ action_type=str(output["action_type"]),
82
+ dt=float(output["dt"]),
83
+ actions=np.asarray(output["actions"], dtype=np.float32),
84
+ )
85
+ raise TypeError(f"Adapter {spec!r} returned {type(output)}, not ActionChunk or dict")
86
+
87
+ # Preserve the optional reset hook on the wrapper. It is needed by DP
88
+ # adapters that maintain image/state history, while remaining a no-op for
89
+ # stateless policies such as the current Pi0.5 adapter.
90
+ reset = getattr(adapter, "reset", None)
91
+ if callable(reset):
92
+ setattr(call, "reset", reset)
93
+ return call
94
+
95
+
96
+ async def _serve(host: str, port: int, policy: Callable[[Observation], ActionChunk]) -> None:
97
+ try:
98
+ import websockets
99
+ except ImportError as error:
100
+ raise RuntimeError("Install websockets in the policy environment: pip install websockets") from error
101
+
102
+ async def handler(websocket: Any, *_unused_path: Any) -> None:
103
+ async for raw_request in websocket:
104
+ try:
105
+ request = json.loads(raw_request)
106
+ if request.get("kind") == "health":
107
+ await websocket.send(json.dumps({"kind": "health", "ok": True}))
108
+ continue
109
+ if request.get("kind") == "reset":
110
+ reset = getattr(policy, "reset", None)
111
+ if callable(reset):
112
+ reset()
113
+ await websocket.send(json.dumps({"kind": "reset", "ok": True}))
114
+ continue
115
+ observation = observation_from_wire(request)
116
+ started = time.perf_counter()
117
+ chunk = policy(observation)
118
+ elapsed_ms = (time.perf_counter() - started) * 1000.0
119
+ response = chunk.to_wire(int(request["request_id"]))
120
+ response['action'].setdefault('diagnostics', {})['server_inference_ms'] = elapsed_ms
121
+ await websocket.send(json.dumps(response, separators=(",", ":")))
122
+ except Exception as error:
123
+ error_response = {
124
+ "kind": "error",
125
+ "request_id": request.get("request_id") if "request" in locals() else None,
126
+ "error": f"{type(error).__name__}: {error}",
127
+ }
128
+ await websocket.send(json.dumps(error_response, separators=(",", ":")))
129
+
130
+ print(f"[DeformManipSim] policy server listening at ws://{host}:{port}", flush=True)
131
+ async with websockets.serve(handler, host, port, max_size=32 * 1024 * 1024):
132
+ await asyncio.Future()
133
+
134
+
135
+ def main() -> None:
136
+ parser = argparse.ArgumentParser(description=__doc__)
137
+ parser.add_argument("--host", default="127.0.0.1")
138
+ parser.add_argument("--port", type=int, default=8765)
139
+ parser.add_argument("--mock", choices=("hold", "joint_demo", "ee_demo"), default="ee_demo")
140
+ parser.add_argument("--adapter", help="Real policy callable in MODULE:ATTRIBUTE form; overrides --mock")
141
+ args = parser.parse_args()
142
+ if args.adapter:
143
+ policy = _load_adapter(args.adapter)
144
+ print(f"[DeformManipSim] loaded external policy adapter {args.adapter}", flush=True)
145
+ else:
146
+ policy = {"hold": hold_policy, "joint_demo": joint_demo_policy, "ee_demo": ee_demo_policy}[args.mock]
147
+ print(f"[DeformManipSim] using mock policy {args.mock}", flush=True)
148
+ try:
149
+ asyncio.run(_serve(args.host, args.port, policy))
150
+ except KeyboardInterrupt:
151
+ print("\n[DeformManipSim] policy server stopped", flush=True)
152
+
153
+
154
+ if __name__ == "__main__":
155
+ main()
real_inference/source/XPolicyLab/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.
real_inference/source/XPolicyLab/policy/Pi_05/openpi/.python-version ADDED
@@ -0,0 +1 @@
 
 
1
+ 3.11
real_inference/source/XPolicyLab/policy/Pi_05/openpi/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.
real_inference/source/XPolicyLab/policy/Pi_05/openpi/LICENSE_GEMMA.txt ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Gemma Terms of Use
2
+
3
+ Last modified: February 21, 2024
4
+
5
+ By using, reproducing, modifying, distributing, performing or displaying any portion or element of Gemma, Model Derivatives including via any Hosted Service, (each as defined below) (collectively, the "Gemma Services") or otherwise accepting the terms of this Agreement, you agree to be bound by this Agreement.
6
+
7
+ Section 1: DEFINITIONS
8
+ 1.1 Definitions
9
+ (a) "Agreement" or "Gemma Terms of Use" means these terms and conditions that govern the use, reproduction, Distribution or modification of the Gemma Services and any terms and conditions incorporated by reference.
10
+
11
+ (b) "Distribution" or "Distribute" means any transmission, publication, or other sharing of Gemma or Model Derivatives to a third party, including by providing or making Gemma or its functionality available as a hosted service via API, web access, or any other electronic or remote means ("Hosted Service").
12
+
13
+ (c) "Gemma" means the set of machine learning language models, trained model weights and parameters identified at ai.google.dev/gemma, regardless of the source that you obtained it from.
14
+
15
+ (d) "Google" means Google LLC.
16
+
17
+ (e) "Model Derivatives" means all (i) modifications to Gemma, (ii) works based on Gemma, or (iii) any other machine learning model which is created by transfer of patterns of the weights, parameters, operations, or Output of Gemma, to that model in order to cause that model to perform similarly to Gemma, including distillation methods that use intermediate data representations or methods based on the generation of synthetic data Outputs by Gemma for training that model. For clarity, Outputs are not deemed Model Derivatives.
18
+
19
+ (f) "Output" means the information content output of Gemma or a Model Derivative that results from operating or otherwise using Gemma or the Model Derivative, including via a Hosted Service.
20
+
21
+ 1.2
22
+ As used in this Agreement, "including" means "including without limitation".
23
+
24
+ Section 2: ELIGIBILITY AND USAGE
25
+ 2.1 Eligibility
26
+ You represent and warrant that you have the legal capacity to enter into this Agreement (including being of sufficient age of consent). If you are accessing or using any of the Gemma Services for or on behalf of a legal entity, (a) you are entering into this Agreement on behalf of yourself and that legal entity, (b) you represent and warrant that you have the authority to act on behalf of and bind that entity to this Agreement and (c) references to "you" or "your" in the remainder of this Agreement refers to both you (as an individual) and that entity.
27
+
28
+ 2.2 Use
29
+ You may use, reproduce, modify, Distribute, perform or display any of the Gemma Services only in accordance with the terms of this Agreement, and must not violate (or encourage or permit anyone else to violate) any term of this Agreement.
30
+
31
+ Section 3: DISTRIBUTION AND RESTRICTIONS
32
+ 3.1 Distribution and Redistribution
33
+ You may reproduce or Distribute copies of Gemma or Model Derivatives if you meet all of the following conditions:
34
+
35
+ You must include the use restrictions referenced in Section 3.2 as an enforceable provision in any agreement (e.g., license agreement, terms of use, etc.) governing the use and/or distribution of Gemma or Model Derivatives and you must provide notice to subsequent users you Distribute to that Gemma or Model Derivatives are subject to the use restrictions in Section 3.2.
36
+ You must provide all third party recipients of Gemma or Model Derivatives a copy of this Agreement.
37
+ You must cause any modified files to carry prominent notices stating that you modified the files.
38
+ All Distributions (other than through a Hosted Service) must be accompanied by a "Notice" text file that contains the following notice: "Gemma is provided under and subject to the Gemma Terms of Use found at ai.google.dev/gemma/terms".
39
+ You may add your own intellectual property statement to your modifications and, except as set forth in this Section, may provide additional or different terms and conditions for use, reproduction, or Distribution of your modifications, or for any such Model Derivatives as a whole, provided your use, reproduction, modification, Distribution, performance, and display of Gemma otherwise complies with the terms and conditions of this Agreement. Any additional or different terms and conditions you impose must not conflict with the terms of this Agreement.
40
+
41
+ 3.2 Use Restrictions
42
+ You must not use any of the Gemma Services:
43
+
44
+ for the restricted uses set forth in the Gemma Prohibited Use Policy at ai.google.dev/gemma/prohibited_use_policy ("Prohibited Use Policy"), which is hereby incorporated by reference into this Agreement; or
45
+ in violation of applicable laws and regulations.
46
+ To the maximum extent permitted by law, Google reserves the right to restrict (remotely or otherwise) usage of any of the Gemma Services that Google reasonably believes are in violation of this Agreement.
47
+
48
+ 3.3 Generated Output
49
+ Google claims no rights in Outputs you generate using Gemma. You and your users are solely responsible for Outputs and their subsequent uses.
50
+
51
+ Section 4: ADDITIONAL PROVISIONS
52
+ 4.1 Updates
53
+ Google may update Gemma from time to time, and you must make reasonable efforts to use the latest version of Gemma.
54
+
55
+ 4.2 Trademarks
56
+ Nothing in this Agreement grants you any rights to use Google's trademarks, trade names, logos or to otherwise suggest endorsement or misrepresent the relationship between you and Google. Google reserves any rights not expressly granted herein.
57
+
58
+ 4.3 DISCLAIMER OF WARRANTY
59
+ UNLESS REQUIRED BY APPLICABLE LAW, THE GEMMA SERVICES, AND OUTPUTS, ARE PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USING, REPRODUCING, MODIFYING, PERFORMING, DISPLAYING OR OR DISTRIBUTING ANY OF THE GEMMA SERVICES OR OUTPUTS AND ASSUME ANY AND ALL RISKS ASSOCIATED WITH YOUR USE OR DISTRIBUTION OF ANY OF THE GEMMA SERVICES OR OUTPUTS AND YOUR EXERCISE OF RIGHTS AND PERMISSIONS UNDER THIS AGREEMENT.
60
+
61
+ 4.4 LIMITATION OF LIABILITY
62
+ TO THE FULLEST EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), PRODUCT LIABILITY, CONTRACT, OR OTHERWISE, UNLESS REQUIRED BY APPLICABLE LAW, SHALL GOOGLE OR ITS AFFILIATES BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, EXEMPLARY, CONSEQUENTIAL, OR PUNITIVE DAMAGES, OR LOST PROFITS OF ANY KIND ARISING FROM THIS AGREEMENT OR RELATED TO, ANY OF THE GEMMA SERVICES OR OUTPUTS EVEN IF GOOGLE OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
63
+
64
+ 4.5 Term, Termination, and Survival
65
+ The term of this Agreement will commence upon your acceptance of this Agreement (including acceptance by your use, modification, or Distribution, reproduction, performance or display of any portion or element of the Gemma Services) and will continue in full force and effect until terminated in accordance with the terms of this Agreement. Google may terminate this Agreement if you are in breach of any term of this Agreement. Upon termination of this Agreement, you must delete and cease use and Distribution of all copies of Gemma and Model Derivatives in your possession or control. Sections 1, 2.1, 3.3, 4.2 to 4.9 shall survive the termination of this Agreement.
66
+
67
+ 4.6 Governing Law and Jurisdiction
68
+ This Agreement will be governed by the laws of the State of California without regard to choice of law principles. The UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. The state and federal courts of Santa Clara County, California shall have exclusive jurisdiction of any dispute arising out of this Agreement.
69
+
70
+ 4.7 Severability
71
+ If any provision of this Agreement is held to be invalid, illegal or unenforceable, the remaining provisions shall be unaffected thereby and remain valid as if such provision had not been set forth herein.
72
+
73
+ 4.8 Entire Agreement
74
+ This Agreement states all the terms agreed between the parties and supersedes all other agreements between the parties as of the date of acceptance relating to its subject matter.
75
+
76
+ 4.9 No Waiver
77
+ Google will not be treated as having waived any rights by not exercising (or delaying the exercise of) any rights under this Agreement.
real_inference/source/XPolicyLab/policy/Pi_05/openpi/README.md ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # openpi
2
+
3
+ openpi holds open-source models and packages for robotics, published by the [Physical Intelligence team](https://www.physicalintelligence.company/).
4
+
5
+ Currently, this repo contains three types of models:
6
+ - the [π₀ model](https://www.physicalintelligence.company/blog/pi0), a flow-based vision-language-action model (VLA).
7
+ - the [π₀-FAST model](https://www.physicalintelligence.company/research/fast), an autoregressive VLA, based on the FAST action tokenizer.
8
+ - the [π₀.₅ model](https://www.physicalintelligence.company/blog/pi05), an upgraded version of π₀ with better open-world generalization trained with [knowledge insulation](https://www.physicalintelligence.company/research/knowledge_insulation). Note that, in this repository, we currently only support the flow matching head for both $\pi_{0.5}$ training and inference.
9
+
10
+ For all models, we provide _base model_ checkpoints, pre-trained on 10k+ hours of robot data, and examples for using them out of the box or fine-tuning them to your own datasets.
11
+
12
+ This is an experiment: $\pi_0$ was developed for our own robots, which differ from the widely used platforms such as [ALOHA](https://tonyzhaozh.github.io/aloha/) and [DROID](https://droid-dataset.github.io/), and though we are optimistic that researchers and practitioners will be able to run creative new experiments adapting $\pi_0$ to their own platforms, we do not expect every such attempt to be successful. All this is to say: $\pi_0$ may or may not work for you, but you are welcome to try it and see!
13
+
14
+ ## Updates
15
+
16
+ - [Sept 2025] We released PyTorch support in openpi.
17
+ - [Sept 2025] We released pi05, an upgraded version of pi0 with better open-world generalization.
18
+ - [Sept 2025]: We have added an [improved idle filter](examples/droid/README_train.md#data-filtering) for DROID training.
19
+ - [Jun 2025]: We have added [instructions](examples/droid/README_train.md) for using `openpi` to train VLAs on the full [DROID dataset](https://droid-dataset.github.io/). This is an approximate open-source implementation of the training pipeline used to train pi0-FAST-DROID.
20
+
21
+
22
+ ## Requirements
23
+
24
+ To run the models in this repository, you will need an NVIDIA GPU with at least the following specifications. These estimations assume a single GPU, but you can also use multiple GPUs with model parallelism to reduce per-GPU memory requirements by configuring `fsdp_devices` in the training config. Please also note that the current training script does not yet support multi-node training.
25
+
26
+ | Mode | Memory Required | Example GPU |
27
+ | ------------------ | --------------- | ------------------ |
28
+ | Inference | > 8 GB | RTX 4090 |
29
+ | Fine-Tuning (LoRA) | > 22.5 GB | RTX 4090 |
30
+ | Fine-Tuning (Full) | > 70 GB | A100 (80GB) / H100 |
31
+
32
+ The repo has been tested with Ubuntu 22.04, we do not currently support other operating systems.
33
+
34
+ ## Installation
35
+
36
+ When cloning this repo, make sure to update submodules:
37
+
38
+ ```bash
39
+ git clone --recurse-submodules git@github.com:Physical-Intelligence/openpi.git
40
+
41
+ # Or if you already cloned the repo:
42
+ git submodule update --init --recursive
43
+ ```
44
+
45
+ We use [uv](https://docs.astral.sh/uv/) to manage Python dependencies. See the [uv installation instructions](https://docs.astral.sh/uv/getting-started/installation/) to set it up. Once uv is installed, run the following to set up the environment:
46
+
47
+ ```bash
48
+ GIT_LFS_SKIP_SMUDGE=1 uv sync
49
+ GIT_LFS_SKIP_SMUDGE=1 uv pip install -e .
50
+ ```
51
+
52
+ NOTE: `GIT_LFS_SKIP_SMUDGE=1` is needed to pull LeRobot as a dependency.
53
+
54
+ **Docker**: As an alternative to uv installation, we provide instructions for installing openpi using Docker. If you encounter issues with your system setup, consider using Docker to simplify installation. See [Docker Setup](docs/docker.md) for more details.
55
+
56
+
57
+
58
+
59
+ ## Model Checkpoints
60
+
61
+ ### Base Models
62
+ We provide multiple base VLA model checkpoints. These checkpoints have been pre-trained on 10k+ hours of robot data, and can be used for fine-tuning.
63
+
64
+ | Model | Use Case | Description | Checkpoint Path |
65
+ | ------------ | ----------- | ----------------------------------------------------------------------------------------------------------- | ---------------------------------------------- |
66
+ | $\pi_0$ | Fine-Tuning | Base [π₀ model](https://www.physicalintelligence.company/blog/pi0) for fine-tuning | `gs://openpi-assets/checkpoints/pi0_base` |
67
+ | $\pi_0$-FAST | Fine-Tuning | Base autoregressive [π₀-FAST model](https://www.physicalintelligence.company/research/fast) for fine-tuning | `gs://openpi-assets/checkpoints/pi0_fast_base` |
68
+ | $\pi_{0.5}$ | Fine-Tuning | Base [π₀.₅ model](https://www.physicalintelligence.company/blog/pi05) for fine-tuning | `gs://openpi-assets/checkpoints/pi05_base` |
69
+
70
+ ### Fine-Tuned Models
71
+ We also provide "expert" checkpoints for various robot platforms and tasks. These models are fine-tuned from the base models above and intended to run directly on the target robot. These may or may not work on your particular robot. Since these checkpoints were fine-tuned on relatively small datasets collected with more widely available robots, such as ALOHA and the DROID Franka setup, they might not generalize to your particular setup, though we found some of these, especially the DROID checkpoint, to generalize quite broadly in practice.
72
+
73
+ | Model | Use Case | Description | Checkpoint Path |
74
+ | ------------------------ | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- |
75
+ | $\pi_0$-FAST-DROID | Inference | $\pi_0$-FAST model fine-tuned on the [DROID dataset](https://droid-dataset.github.io/): can perform a wide range of simple table-top manipulation tasks 0-shot in new scenes on the DROID robot platform | `gs://openpi-assets/checkpoints/pi0_fast_droid` |
76
+ | $\pi_0$-DROID | Fine-Tuning | $\pi_0$ model fine-tuned on the [DROID dataset](https://droid-dataset.github.io/): faster inference than $\pi_0$-FAST-DROID, but may not follow language commands as well | `gs://openpi-assets/checkpoints/pi0_droid` |
77
+ | $\pi_0$-ALOHA-towel | Inference | $\pi_0$ model fine-tuned on internal [ALOHA](https://tonyzhaozh.github.io/aloha/) data: can fold diverse towels 0-shot on ALOHA robot platforms | `gs://openpi-assets/checkpoints/pi0_aloha_towel` |
78
+ | $\pi_0$-ALOHA-tupperware | Inference | $\pi_0$ model fine-tuned on internal [ALOHA](https://tonyzhaozh.github.io/aloha/) data: can unpack food from a tupperware container | `gs://openpi-assets/checkpoints/pi0_aloha_tupperware` |
79
+ | $\pi_0$-ALOHA-pen-uncap | Inference | $\pi_0$ model fine-tuned on public [ALOHA](https://dit-policy.github.io/) data: can uncap a pen | `gs://openpi-assets/checkpoints/pi0_aloha_pen_uncap` |
80
+ | $\pi_{0.5}$-LIBERO | Inference | $\pi_{0.5}$ model fine-tuned for the [LIBERO](https://libero-project.github.io/datasets) benchmark: gets state-of-the-art performance (see [LIBERO README](examples/libero/README.md)) | `gs://openpi-assets/checkpoints/pi05_libero` |
81
+ | $\pi_{0.5}$-DROID | Inference / Fine-Tuning | $\pi_{0.5}$ model fine-tuned on the [DROID dataset](https://droid-dataset.github.io/) with [knowledge insulation](https://www.physicalintelligence.company/research/knowledge_insulation): fast inference and good language-following | `gs://openpi-assets/checkpoints/pi05_droid` |
82
+
83
+
84
+ By default, checkpoints are automatically downloaded from `gs://openpi-assets` and are cached in `~/.cache/openpi` when needed. You can overwrite the download path by setting the `OPENPI_DATA_HOME` environment variable.
85
+
86
+
87
+
88
+
89
+ ## Running Inference for a Pre-Trained Model
90
+
91
+ Our pre-trained model checkpoints can be run with a few lines of code (here our $\pi_0$-FAST-DROID model):
92
+ ```python
93
+ from openpi.training import config as _config
94
+ from openpi.policies import policy_config
95
+ from openpi.shared import download
96
+
97
+ config = _config.get_config("pi05_droid")
98
+ checkpoint_dir = download.maybe_download("gs://openpi-assets/checkpoints/pi05_droid")
99
+
100
+ # Create a trained policy.
101
+ policy = policy_config.create_trained_policy(config, checkpoint_dir)
102
+
103
+ # Run inference on a dummy example.
104
+ example = {
105
+ "observation/exterior_image_1_left": ...,
106
+ "observation/wrist_image_left": ...,
107
+ ...
108
+ "prompt": "pick up the fork"
109
+ }
110
+ action_chunk = policy.infer(example)["actions"]
111
+ ```
112
+ You can also test this out in the [example notebook](examples/inference.ipynb).
113
+
114
+ We provide detailed step-by-step examples for running inference of our pre-trained checkpoints on [DROID](examples/droid/README.md) and [ALOHA](examples/aloha_real/README.md) robots.
115
+
116
+ **Remote Inference**: We provide [examples and code](docs/remote_inference.md) for running inference of our models **remotely**: the model can run on a different server and stream actions to the robot via a websocket connection. This makes it easy to use more powerful GPUs off-robot and keep robot and policy environments separate.
117
+
118
+ **Test inference without a robot**: We provide a [script](examples/simple_client/README.md) for testing inference without a robot. This script will generate a random observation and run inference with the model. See [here](examples/simple_client/README.md) for more details.
119
+
120
+
121
+
122
+
123
+
124
+ ## Fine-Tuning Base Models on Your Own Data
125
+
126
+ We will fine-tune the $\pi_{0.5}$ model on the [LIBERO dataset](https://libero-project.github.io/datasets) as a running example for how to fine-tune a base model on your own data. We will explain three steps:
127
+ 1. Convert your data to a LeRobot dataset (which we use for training)
128
+ 2. Defining training configs and running training
129
+ 3. Spinning up a policy server and running inference
130
+
131
+ ### 1. Convert your data to a LeRobot dataset
132
+
133
+ We provide a minimal example script for converting LIBERO data to a LeRobot dataset in [`examples/libero/convert_libero_data_to_lerobot.py`](examples/libero/convert_libero_data_to_lerobot.py). You can easily modify it to convert your own data! You can download the raw LIBERO dataset from [here](https://huggingface.co/datasets/openvla/modified_libero_rlds), and run the script with:
134
+
135
+ ```bash
136
+ uv run examples/libero/convert_libero_data_to_lerobot.py --data_dir /path/to/your/libero/data
137
+ ```
138
+
139
+ **Note:** If you just want to fine-tune on LIBERO, you can skip this step, because our LIBERO fine-tuning configs point to a pre-converted LIBERO dataset. This step is merely an example that you can adapt to your own data.
140
+
141
+ ### 2. Defining training configs and running training
142
+
143
+ To fine-tune a base model on your own data, you need to define configs for data processing and training. We provide example configs with detailed comments for LIBERO below, which you can modify for your own dataset:
144
+
145
+ - [`LiberoInputs` and `LiberoOutputs`](src/openpi/policies/libero_policy.py): Defines the data mapping from the LIBERO environment to the model and vice versa. Will be used for both, training and inference.
146
+ - [`LeRobotLiberoDataConfig`](src/openpi/training/config.py): Defines how to process raw LIBERO data from LeRobot dataset for training.
147
+ - [`TrainConfig`](src/openpi/training/config.py): Defines fine-tuning hyperparameters, data config, and weight loader.
148
+
149
+ We provide example fine-tuning configs for [π₀](src/openpi/training/config.py), [π₀-FAST](src/openpi/training/config.py), and [π₀.₅](src/openpi/training/config.py) on LIBERO data.
150
+
151
+ Before we can run training, we need to compute the normalization statistics for the training data. Run the script below with the name of your training config:
152
+
153
+ ```bash
154
+ uv run scripts/compute_norm_stats.py --config-name pi05_libero
155
+ ```
156
+
157
+ Now we can kick off training with the following command (the `--overwrite` flag is used to overwrite existing checkpoints if you rerun fine-tuning with the same config):
158
+
159
+ ```bash
160
+ XLA_PYTHON_CLIENT_MEM_FRACTION=0.9 uv run scripts/train.py pi05_libero --exp-name=my_experiment --overwrite
161
+ ```
162
+
163
+ The command will log training progress to the console and save checkpoints to the `checkpoints` directory. You can also monitor training progress on the Weights & Biases dashboard. For maximally using the GPU memory, set `XLA_PYTHON_CLIENT_MEM_FRACTION=0.9` before running training -- this enables JAX to use up to 90% of the GPU memory (vs. the default of 75%).
164
+
165
+ **Note:** We provide functionality for *reloading* normalization statistics for state / action normalization from pre-training. This can be beneficial if you are fine-tuning to a new task on a robot that was part of our pre-training mixture. For more details on how to reload normalization statistics, see the [norm_stats.md](docs/norm_stats.md) file.
166
+
167
+ ### 3. Spinning up a policy server and running inference
168
+
169
+ Once training is complete, we can run inference by spinning up a policy server and then querying it from a LIBERO evaluation script. Launching a model server is easy (we use the checkpoint for iteration 20,000 for this example, modify as needed):
170
+
171
+ ```bash
172
+ uv run scripts/serve_policy.py policy:checkpoint --policy.config=pi05_libero --policy.dir=checkpoints/pi05_libero/my_experiment/20000
173
+ ```
174
+
175
+ This will spin up a server that listens on port 8000 and waits for observations to be sent to it. We can then run an evaluation script (or robot runtime) that queries the server.
176
+
177
+ For running the LIBERO eval in particular, we provide (and recommend using) a Dockerized workflow that handles both the policy server and the evaluation script together. See the [LIBERO README](examples/libero/README.md) for more details.
178
+
179
+ If you want to embed a policy server call in your own robot runtime, we have a minimal example of how to do so in the [remote inference docs](docs/remote_inference.md).
180
+
181
+
182
+
183
+ ### More Examples
184
+
185
+ We provide more examples for how to fine-tune and run inference with our models on the ALOHA platform in the following READMEs:
186
+ - [ALOHA Simulator](examples/aloha_sim)
187
+ - [ALOHA Real](examples/aloha_real)
188
+ - [UR5](examples/ur5)
189
+
190
+ ## PyTorch Support
191
+
192
+ openpi now provides PyTorch implementations of π₀ and π₀.₅ models alongside the original JAX versions! The PyTorch implementation has been validated on the LIBERO benchmark (both inference and finetuning). A few features are currently not supported (this may change in the future):
193
+
194
+ - The π₀-FAST model
195
+ - Mixed precision training
196
+ - FSDP (fully-sharded data parallelism) training
197
+ - LoRA (low-rank adaptation) training
198
+ - EMA (exponential moving average) weights during training
199
+
200
+ ### Setup
201
+ 1. Make sure that you have the latest version of all dependencies installed: `uv sync`
202
+
203
+ 2. Double check that you have transformers 4.53.2 installed: `uv pip show transformers`
204
+
205
+ 3. Apply the transformers library patches:
206
+ ```bash
207
+ cp -r ./src/openpi/models_pytorch/transformers_replace/* .venv/lib/python3.11/site-packages/transformers/
208
+ ```
209
+
210
+ This overwrites several files in the transformers library with necessary model changes: 1) supporting AdaRMS, 2) correctly controlling the precision of activations, and 3) allowing the KV cache to be used without being updated.
211
+
212
+ **WARNING**: With the default uv link mode (hardlink), this will permanently affect the transformers library in your uv cache, meaning the changes will survive reinstallations of transformers and could even propagate to other projects that use transformers. To fully undo this operation, you must run `uv cache clean transformers`.
213
+
214
+ ### Converting JAX Models to PyTorch
215
+
216
+ To convert a JAX model checkpoint to PyTorch format:
217
+
218
+ ```bash
219
+ uv run examples/convert_jax_model_to_pytorch.py \
220
+ --checkpoint_dir /path/to/jax/checkpoint \
221
+ --config_name <config name> \
222
+ --output_path /path/to/converted/pytorch/checkpoint
223
+ ```
224
+
225
+ ### Running Inference with PyTorch
226
+
227
+ The PyTorch implementation uses the same API as the JAX version - you only need to change the checkpoint path to point to the converted PyTorch model:
228
+
229
+ ```python
230
+ from openpi.training import config as _config
231
+ from openpi.policies import policy_config
232
+ from openpi.shared import download
233
+
234
+ config = _config.get_config("pi05_droid")
235
+ checkpoint_dir = "/path/to/converted/pytorch/checkpoint"
236
+
237
+ # Create a trained policy (automatically detects PyTorch format)
238
+ policy = policy_config.create_trained_policy(config, checkpoint_dir)
239
+
240
+ # Run inference (same API as JAX)
241
+ action_chunk = policy.infer(example)["actions"]
242
+ ```
243
+
244
+ ### Policy Server with PyTorch
245
+
246
+ The policy server works identically with PyTorch models - just point to the converted checkpoint directory:
247
+
248
+ ```bash
249
+ uv run scripts/serve_policy.py policy:checkpoint \
250
+ --policy.config=pi05_droid \
251
+ --policy.dir=/path/to/converted/pytorch/checkpoint
252
+ ```
253
+
254
+ ### Finetuning with PyTorch
255
+
256
+ To finetune a model in PyTorch:
257
+
258
+ 1. Convert the JAX base model to PyTorch format:
259
+ ```bash
260
+ uv run examples/convert_jax_model_to_pytorch.py \
261
+ --config_name <config name> \
262
+ --checkpoint_dir /path/to/jax/base/model \
263
+ --output_path /path/to/pytorch/base/model
264
+ ```
265
+
266
+ 2. Specify the converted PyTorch model path in your config using `pytorch_weight_path`
267
+
268
+ 3. Launch training using one of these modes:
269
+
270
+ ```bash
271
+ # Single GPU training:
272
+ uv run scripts/train_pytorch.py <config_name> --exp_name <run_name> --save_interval <interval>
273
+
274
+ # Example:
275
+ uv run scripts/train_pytorch.py debug --exp_name pytorch_test
276
+ uv run scripts/train_pytorch.py debug --exp_name pytorch_test --resume # Resume from latest checkpoint
277
+
278
+ # Multi-GPU training (single node):
279
+ uv run torchrun --standalone --nnodes=1 --nproc_per_node=<num_gpus> scripts/train_pytorch.py <config_name> --exp_name <run_name>
280
+
281
+ # Example:
282
+ uv run torchrun --standalone --nnodes=1 --nproc_per_node=2 scripts/train_pytorch.py pi0_aloha_sim --exp_name pytorch_ddp_test
283
+ uv run torchrun --standalone --nnodes=1 --nproc_per_node=2 scripts/train_pytorch.py pi0_aloha_sim --exp_name pytorch_ddp_test --resume
284
+
285
+ # Multi-Node Training:
286
+ uv run torchrun \
287
+ --nnodes=<num_nodes> \
288
+ --nproc_per_node=<gpus_per_node> \
289
+ --node_rank=<rank_of_node> \
290
+ --master_addr=<master_ip> \
291
+ --master_port=<port> \
292
+ scripts/train_pytorch.py <config_name> --exp_name=<run_name> --save_interval <interval>
293
+ ```
294
+
295
+ ### Precision Settings
296
+
297
+ JAX and PyTorch implementations handle precision as follows:
298
+
299
+ **JAX:**
300
+ 1. Inference: most weights and computations in bfloat16, with a few computations in float32 for stability
301
+ 2. Training: defaults to mixed precision: weights and gradients in float32, (most) activations and computations in bfloat16. You can change to full float32 training by setting `dtype` to float32 in the config.
302
+
303
+ **PyTorch:**
304
+ 1. Inference: matches JAX -- most weights and computations in bfloat16, with a few weights converted to float32 for stability
305
+ 2. Training: supports either full bfloat16 (default) or full float32. You can change it by setting `pytorch_training_precision` in the config. bfloat16 uses less memory but exhibits higher losses compared to float32. Mixed precision is not yet supported.
306
+
307
+ With torch.compile, inference speed is comparable between JAX and PyTorch.
308
+
309
+ ## Troubleshooting
310
+
311
+ We will collect common issues and their solutions here. If you encounter an issue, please check here first. If you can't find a solution, please file an issue on the repo (see [here](CONTRIBUTING.md) for guidelines).
312
+
313
+ | Issue | Resolution |
314
+ | ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
315
+ | `uv sync` fails with dependency conflicts | Try removing the virtual environment directory (`rm -rf .venv`) and running `uv sync` again. If issues persist, check that you have the latest version of `uv` installed (`uv self update`). |
316
+ | Training runs out of GPU memory | Make sure you set `XLA_PYTHON_CLIENT_MEM_FRACTION=0.9` (or higher) before running training to allow JAX to use more GPU memory. You can also use `--fsdp-devices <n>` where `<n>` is your number of GPUs, to enable [fully-sharded data parallelism](https://engineering.fb.com/2021/07/15/open-source/fsdp/), which reduces memory usage in exchange for slower training (the amount of slowdown depends on your particular setup). If you are still running out of memory, you may want to consider disabling EMA. |
317
+ | Policy server connection errors | Check that the server is running and listening on the expected port. Verify network connectivity and firewall settings between client and server. |
318
+ | Missing norm stats error when training | Run `scripts/compute_norm_stats.py` with your config name before starting training. |
319
+ | Dataset download fails | Check your internet connection. For HuggingFace datasets, ensure you're logged in (`huggingface-cli login`). |
320
+ | CUDA/GPU errors | Verify NVIDIA drivers are installed correctly. For Docker, ensure nvidia-container-toolkit is installed. Check GPU compatibility. You do NOT need CUDA libraries installed at a system level --- they will be installed via uv. You may even want to try *uninstalling* system CUDA libraries if you run into CUDA issues, since system libraries can sometimes cause conflicts. |
321
+ | Import errors when running examples | Make sure you've installed all dependencies with `uv sync`. Some examples may have additional requirements listed in their READMEs. |
322
+ | Action dimensions mismatch | Verify your data processing transforms match the expected input/output dimensions of your robot. Check the action space definitions in your policy classes. |
323
+ | Diverging training loss | Check the `q01`, `q99`, and `std` values in `norm_stats.json` for your dataset. Certain dimensions that are rarely used can end up with very small `q01`, `q99`, or `std` values, leading to huge states and actions after normalization. You can manually adjust the norm stats as a workaround. |
real_inference/source/XPolicyLab/policy/Pi_05/openpi/pyproject.toml ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "openpi"
3
+ version = "0.1.0"
4
+ description = "Physical Intelligence open source repo"
5
+ readme = "README.md"
6
+ requires-python = ">=3.11,<3.14"
7
+ license = { file = "LICENSE" }
8
+ dependencies = [
9
+ "augmax>=0.3.4",
10
+ "dm-tree>=0.1.8",
11
+ "einops>=0.8.0",
12
+ "equinox>=0.11.8",
13
+ "flatbuffers>=24.3.25",
14
+ "flax==0.10.2",
15
+ "fsspec[gcs]>=2024.6.0",
16
+ "imageio>=2.36.1",
17
+ "jax[cuda12]==0.5.3",
18
+ "jaxtyping==0.2.36",
19
+ "ml_collections==1.0.0",
20
+ "numpy>=1.22.4,<2.0.0",
21
+ "numpydantic>=1.6.6",
22
+ "opencv-python>=4.10.0.84",
23
+ "openpi-client",
24
+ "orbax-checkpoint==0.11.13",
25
+ "pillow>=11.0.0",
26
+ "sentencepiece>=0.2.0",
27
+ "torch==2.10.0",
28
+ "torchvision==0.25.0",
29
+ "torchcodec==0.10.0",
30
+ "tqdm-loggable>=0.2",
31
+ "typing-extensions>=4.12.2",
32
+ "tyro>=0.9.5",
33
+ "wandb>=0.19.1",
34
+ "filelock>=3.16.1",
35
+ "beartype==0.19.0",
36
+ "treescope>=0.1.7",
37
+ "transformers==4.53.2",
38
+ "rich>=14.0.0",
39
+ "polars>=1.30.0",
40
+ ]
41
+
42
+
43
+ [project.urls]
44
+ Repository = "https://github.com/Physical-Intelligence/openpi"
45
+
46
+ [dependency-groups]
47
+ lerobot = [
48
+ "lerobot==0.4.4",
49
+ ]
50
+ dev = [
51
+ "pytest>=8.3.4",
52
+ "ruff>=0.8.6",
53
+ "pre-commit>=4.0.1",
54
+ "ipykernel>=6.29.5",
55
+ "ipywidgets>=8.1.5",
56
+ "matplotlib>=3.10.0",
57
+ "pynvml>=12.0.0",
58
+ ]
59
+
60
+ [tool.uv]
61
+ override-dependencies = [
62
+ "ml-dtypes==0.4.1",
63
+ "numpy>=1.22.4,<2.0.0",
64
+ "tensorstore==0.1.74",
65
+ ]
66
+
67
+ [tool.uv.sources]
68
+ openpi-client = { workspace = true }
69
+ dlimp = { git = "https://github.com/kvablack/dlimp", rev = "ad72ce3a9b414db2185bc0b38461d4101a65477a" }
70
+
71
+ [tool.uv.workspace]
72
+ members = ["packages/*"]
73
+
74
+ [tool.ruff]
75
+ line-length = 120
76
+ target-version = "py311"
77
+ extend-exclude = ["docker", "third_party", "src/openpi/models_pytorch/transformers_replace/*"]
78
+
79
+ [tool.ruff.lint]
80
+ # https://docs.astral.sh/ruff/rules/
81
+ select = [
82
+ "B",
83
+ "C4",
84
+ "DTZ",
85
+ "E4",
86
+ "E7",
87
+ "E9",
88
+ "F",
89
+ "FBT",
90
+ "FURB",
91
+ "I",
92
+ "ICN",
93
+ "ISC",
94
+ "LOG",
95
+ "N",
96
+ "PD",
97
+ "PERF",
98
+ "PIE",
99
+ "PLC",
100
+ "PLE",
101
+ "PLR1",
102
+ "PLR5",
103
+ "PLW",
104
+ "PT",
105
+ "Q",
106
+ "RET",
107
+ "RUF",
108
+ "SIM",
109
+ "SLF",
110
+ "T10",
111
+ "T20",
112
+ "UP",
113
+ "W",
114
+ ]
115
+ ignore = [
116
+ "F722", # Conflicts with array typing.
117
+ "T201", # We use print statements.
118
+ "PD008", # Lots of false positives.
119
+ "ISC001", # Disabling to support ruff format.
120
+ "LOG015", # Use logger.info.
121
+ ]
122
+ unfixable = [
123
+ "B905", # Fix defaults to strict=False, which is not what we want.
124
+ ]
125
+
126
+ [tool.ruff.lint.isort]
127
+ force-single-line = true
128
+ force-sort-within-sections = true
129
+ single-line-exclusions = ["collections.abc", "typing", "typing_extensions"]
130
+ known-third-party = ["wandb"]
131
+
132
+ [build-system]
133
+ requires = ["hatchling"]
134
+ build-backend = "hatchling.build"
135
+
136
+ [tool.pytest.ini_options]
137
+ markers = ["manual: should be run manually."]
138
+ testpaths = ["src", "scripts", "packages"]
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/__init__.py ADDED
File without changes
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/conftest.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import pynvml
4
+ import pytest
5
+
6
+
7
+ def set_jax_cpu_backend_if_no_gpu() -> None:
8
+ try:
9
+ pynvml.nvmlInit()
10
+ pynvml.nvmlShutdown()
11
+ except pynvml.NVMLError:
12
+ # No GPU found.
13
+ os.environ["JAX_PLATFORMS"] = "cpu"
14
+
15
+
16
+ def pytest_configure(config: pytest.Config) -> None:
17
+ set_jax_cpu_backend_if_no_gpu()
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/__init__.py ADDED
File without changes
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/gemma.py ADDED
@@ -0,0 +1,459 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Big Vision Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Gemma adaptation for Pi, taken from big_vision.
16
+
17
+ We follow this einsum axis naming convention:
18
+ B: batch
19
+ T: query length
20
+ S: k/v length
21
+ N: num query heads
22
+ K: num k/v heads
23
+ G: num query heads per k/v head
24
+ H: head dim
25
+ D: d_model ("features")
26
+ """
27
+
28
+ from collections.abc import Sequence
29
+ import dataclasses
30
+ from typing import Literal, TypeAlias
31
+
32
+ import einops
33
+ import flax.linen as nn
34
+ import jax
35
+ import jax.numpy as jnp
36
+
37
+ import openpi.models.lora as lora
38
+ import openpi.shared.array_typing as at
39
+ import openpi.training.sharding as sharding
40
+
41
+ PALIGEMMA_VOCAB_SIZE = 257_152
42
+
43
+
44
+ @dataclasses.dataclass
45
+ class Config:
46
+ width: int
47
+ depth: int
48
+ mlp_dim: int
49
+ num_heads: int
50
+ num_kv_heads: int
51
+ head_dim: int
52
+ lora_configs: dict[str, lora.LoRAConfig] = dataclasses.field(default_factory=dict)
53
+
54
+
55
+ Variant = Literal["dummy", "gemma_300m", "gemma_300m_lora", "gemma_2b", "gemma_2b_lora"]
56
+
57
+
58
+ def get_config(variant: Variant) -> Config:
59
+ """Returns config for specified gemma variant."""
60
+ if variant == "dummy":
61
+ return Config(
62
+ width=64,
63
+ depth=4,
64
+ mlp_dim=128,
65
+ num_heads=8,
66
+ num_kv_heads=1,
67
+ head_dim=16,
68
+ )
69
+ if variant == "gemma_300m":
70
+ # 311M params
71
+ return Config(
72
+ width=1024,
73
+ depth=18,
74
+ mlp_dim=4096,
75
+ num_heads=8,
76
+ num_kv_heads=1,
77
+ head_dim=256,
78
+ )
79
+ if variant == "gemma_2b":
80
+ return Config(
81
+ width=2048,
82
+ depth=18,
83
+ mlp_dim=16_384,
84
+ num_heads=8,
85
+ num_kv_heads=1,
86
+ head_dim=256,
87
+ )
88
+ if variant == "gemma_2b_lora":
89
+ return Config(
90
+ width=2048,
91
+ depth=18,
92
+ mlp_dim=16_384,
93
+ num_heads=8,
94
+ num_kv_heads=1,
95
+ head_dim=256,
96
+ lora_configs={"attn": lora.LoRAConfig(rank=16, alpha=16.0), "ffn": lora.LoRAConfig(rank=16, alpha=16.0)},
97
+ )
98
+ if variant == "gemma_300m_lora":
99
+ # 311M params
100
+ return Config(
101
+ width=1024,
102
+ depth=18,
103
+ mlp_dim=4096,
104
+ num_heads=8,
105
+ num_kv_heads=1,
106
+ head_dim=256,
107
+ lora_configs={"attn": lora.LoRAConfig(rank=32, alpha=32.0), "ffn": lora.LoRAConfig(rank=32, alpha=32.0)},
108
+ )
109
+ raise ValueError(f"Unknown variant: {variant}")
110
+
111
+
112
+ @at.typecheck
113
+ class RMSNorm(nn.Module):
114
+ @nn.compact
115
+ def __call__(self, x, cond):
116
+ dtype = x.dtype # original dtype, could be half-precision
117
+ var = jnp.mean(jnp.square(x.astype(jnp.float32)), axis=-1, keepdims=True) # compute variance in float32
118
+ normed_inputs = jnp.asarray(x * jnp.reciprocal(jnp.sqrt(var + 1e-06))) # compute normalization in float32
119
+ if cond is None:
120
+ # regular RMSNorm
121
+ scale = self.param("scale", nn.initializers.zeros_init(), (x.shape[-1]))
122
+ normed_inputs = normed_inputs * (
123
+ 1 + scale
124
+ ) # scale by learned parameter in float32 (matches Flax implementation)
125
+ return normed_inputs.astype(dtype), None # return in original dtype
126
+
127
+ # adaptive RMSNorm
128
+ modulation = nn.Dense(x.shape[-1] * 3, kernel_init=nn.initializers.zeros, dtype=dtype)(cond)
129
+ scale, shift, gate = jnp.split(modulation[:, None, :], 3, axis=-1)
130
+ normed_inputs = normed_inputs * (1 + scale) + shift # scale and shift in float32
131
+ return normed_inputs.astype(dtype), gate
132
+
133
+
134
+ @at.typecheck
135
+ class Embedder(nn.Module):
136
+ """Embedder module."""
137
+
138
+ vocab_size: int
139
+ embed_dim: int
140
+
141
+ def setup(self):
142
+ self.input_embedding_table = self.param(
143
+ "input_embedding",
144
+ nn.initializers.normal(),
145
+ (self.vocab_size, self.embed_dim),
146
+ )
147
+
148
+ def encode(self, x):
149
+ x = self.input_embedding_table[(x,)]
150
+ x *= jnp.sqrt(self.embed_dim).astype(x.dtype)
151
+ return x
152
+
153
+ def decode(self, x):
154
+ return jnp.dot(x, self.input_embedding_table.T)
155
+
156
+
157
+ @at.typecheck
158
+ class Attention(nn.Module):
159
+ """Attention module."""
160
+
161
+ configs: Sequence[Config]
162
+
163
+ @nn.compact
164
+ def __call__(self, xs, positions, attn_mask, kv_cache):
165
+ # all experts must share the same head dim, num heads, and num kv heads for self-attention to work
166
+ assert all(config.head_dim == self.configs[0].head_dim for config in self.configs)
167
+ assert all(config.num_heads == self.configs[0].num_heads for config in self.configs)
168
+ assert all(config.num_kv_heads == self.configs[0].num_kv_heads for config in self.configs)
169
+
170
+ dtype = next(x.dtype for x in xs if x is not None) # original dtype, could be half-precision
171
+
172
+ qkvs = []
173
+ for i, (x, config) in enumerate(zip(xs, self.configs, strict=True)):
174
+ if x is None:
175
+ continue
176
+ if config.num_kv_heads == config.num_heads:
177
+ qkv_einsum = lora.Einsum(
178
+ shape=(3, config.num_heads, config.width, config.head_dim),
179
+ name=_name("qkv_einsum", i),
180
+ init_fn=nn.initializers.lecun_normal(in_axis=-2, out_axis=-1, batch_axis=(0, 1)),
181
+ lora_config=config.lora_configs.get("attn"),
182
+ )
183
+ qkvs.append(qkv_einsum("BSD,3KDH->3BSKH", x))
184
+ else:
185
+ q_einsum = lora.Einsum(
186
+ shape=(config.num_heads, config.width, config.head_dim),
187
+ name=_name("q_einsum", i),
188
+ init_fn=nn.initializers.lecun_normal(in_axis=-2, out_axis=-1, batch_axis=(0,)),
189
+ lora_config=config.lora_configs.get("attn"),
190
+ )
191
+ q = q_einsum("BTD,NDH->BTNH", x)
192
+ kv_einsum = lora.Einsum(
193
+ shape=(2, config.num_kv_heads, config.width, config.head_dim),
194
+ name=_name("kv_einsum", i),
195
+ init_fn=nn.initializers.lecun_normal(in_axis=-2, out_axis=-1, batch_axis=(0, 1)),
196
+ lora_config=config.lora_configs.get("attn"),
197
+ )
198
+ k, v = kv_einsum("BSD,2KDH->2BSKH", x)
199
+ qkvs.append((q, k, v))
200
+
201
+ q, k, v = (jnp.concatenate(y, axis=1) for y in zip(*qkvs, strict=True))
202
+
203
+ q = _apply_rope(q, positions=positions)
204
+ q *= self.configs[0].head_dim ** -0.5
205
+
206
+ k = _apply_rope(k, positions=positions)
207
+
208
+ # should still be half-precision here (if input was half-precision)
209
+ assert q.dtype == k.dtype == v.dtype == dtype
210
+
211
+ if kv_cache is not None:
212
+ cache_k, cache_v = kv_cache
213
+ k = jnp.concatenate([cache_k, k], axis=1)
214
+ v = jnp.concatenate([cache_v, v], axis=1)
215
+
216
+ q = einops.rearrange(q, "B T (K G) H -> B T K G H", K=self.configs[0].num_kv_heads)
217
+ logits = jnp.einsum("BTKGH,BSKH->BKGTS", q, k, preferred_element_type=jnp.float32)
218
+
219
+ if attn_mask.shape != (q.shape[0], 1, q.shape[1], k.shape[1]):
220
+ raise ValueError(
221
+ f"Attention mask with shape {attn_mask.shape} but shapes for q and k are: {q.shape} and {k.shape}"
222
+ )
223
+
224
+ # big_neg = jnp.finfo(logits.dtype).min
225
+ big_neg = -2.3819763e38 # See gemma/modules.py
226
+ masked_logits = jnp.where(attn_mask[:, :, None, :, :], logits, big_neg)
227
+
228
+ probs = jax.nn.softmax(masked_logits, axis=-1).astype(dtype)
229
+
230
+ encoded = jnp.einsum("BKGTS,BSKH->BTKGH", probs, v)
231
+ encoded = einops.rearrange(encoded, "B T K G H -> B T (K G) H")
232
+
233
+ out = []
234
+ start = 0
235
+ for i, (x, config) in enumerate(zip(xs, self.configs, strict=True)):
236
+ if x is not None:
237
+ end = start + x.shape[1]
238
+ out_einsum = lora.Einsum(
239
+ shape=(config.num_heads, config.head_dim, config.width),
240
+ name=_name("attn_vec_einsum", i),
241
+ init_fn=nn.initializers.lecun_normal(in_axis=(-3, -2), out_axis=-1),
242
+ lora_config=config.lora_configs.get("attn"),
243
+ )
244
+ out.append(out_einsum("BTNH,NHD->BTD", encoded[:, start:end]))
245
+ start = end
246
+ else:
247
+ out.append(None)
248
+
249
+ return out, (k, v)
250
+
251
+
252
+ @at.typecheck
253
+ class FeedForward(nn.Module):
254
+ """Feed forward module."""
255
+
256
+ features: int
257
+ hidden_dim: int
258
+
259
+ @nn.compact
260
+ def __call__(self, x):
261
+ dtype = x.dtype # original dtype, could be half-precision
262
+ w_gating = self.param(
263
+ "gating_einsum",
264
+ nn.initializers.lecun_normal(in_axis=-2, out_axis=-1, batch_axis=(0,)),
265
+ (2, self.features, self.hidden_dim),
266
+ ).astype(dtype)
267
+ ff_gate = jnp.dot(x, w_gating[0])
268
+ gate_value = nn.gelu(ff_gate)
269
+
270
+ ff1 = jnp.dot(x, w_gating[1])
271
+ activations = gate_value * ff1
272
+
273
+ w_linear = self.param(
274
+ "linear",
275
+ nn.initializers.lecun_normal(in_axis=-2, out_axis=-1),
276
+ (self.hidden_dim, self.features),
277
+ ).astype(dtype)
278
+ outputs = jnp.dot(activations, w_linear)
279
+ assert outputs.dtype == dtype
280
+ return outputs
281
+
282
+
283
+ @at.typecheck
284
+ class Block(nn.Module):
285
+ """Transformer block."""
286
+
287
+ configs: tuple[Config, ...]
288
+
289
+ dropout: float = 0.0
290
+ dropout_bdims: tuple[int, ...] = ()
291
+
292
+ @nn.compact
293
+ def __call__(self, xs, kv_cache, positions, attn_mask, adarms_cond, deterministic=True): # noqa: FBT002
294
+ xs = sharding.activation_sharding_constraint(xs)
295
+ drop = nn.Dropout(self.dropout, self.dropout_bdims) if self.dropout else lambda x, _: x
296
+
297
+ attn = Attention(configs=self.configs, name="attn")
298
+
299
+ pre_attn = []
300
+ gates = []
301
+ for i, x in enumerate(xs):
302
+ if x is not None:
303
+ x, gate = RMSNorm(name=_name("pre_attention_norm", i))(x, adarms_cond[i]) # noqa: PLW2901
304
+ pre_attn.append(x)
305
+ gates.append(gate if x is not None else None)
306
+
307
+ pre_attn = sharding.activation_sharding_constraint(pre_attn)
308
+ post_attn, kv_cache = attn(pre_attn, positions, attn_mask, kv_cache)
309
+ post_attn = jax.tree.map(lambda x: drop(x, deterministic), post_attn)
310
+ post_attn = sharding.activation_sharding_constraint(post_attn)
311
+ xs = [_gated_residual(x, y, gate) for x, y, gate in zip(xs, post_attn, gates, strict=True)]
312
+ xs = sharding.activation_sharding_constraint(xs)
313
+
314
+ out = []
315
+ gates = []
316
+ for i, (x, config) in enumerate(zip(xs, self.configs, strict=True)):
317
+ if x is not None:
318
+ x, gate = RMSNorm(name=_name("pre_ffw_norm", i))(x, adarms_cond[i]) # noqa: PLW2901
319
+ x = lora.FeedForward( # noqa: PLW2901
320
+ features=config.width,
321
+ hidden_dim=config.mlp_dim,
322
+ name=_name("mlp", i),
323
+ lora_config=config.lora_configs.get("ffn"),
324
+ )(x)
325
+ out.append(x)
326
+ gates.append(gate if x is not None else None)
327
+
328
+ out = sharding.activation_sharding_constraint(out)
329
+ out = jax.tree.map(lambda x: drop(x, deterministic), out)
330
+ xs = [_gated_residual(x, y, gate) for x, y, gate in zip(xs, out, gates, strict=True)]
331
+ xs = sharding.activation_sharding_constraint(xs)
332
+
333
+ return xs, kv_cache
334
+
335
+
336
+ KVCache: TypeAlias = tuple[at.Float[at.Array, "l b _t _k _h"], at.Float[at.Array, "l b _t _v _h"]]
337
+
338
+
339
+ @at.typecheck
340
+ class Module(nn.Module):
341
+ """Transformer model, supporting a mixture of different weights for different tokens."""
342
+
343
+ configs: Sequence[Config] # list of configs, one for each expert
344
+ embed_dtype: str
345
+
346
+ dropout: float = 0.0
347
+ dropout_bdims: tuple[int, ...] = () # Every float is dropped independently.
348
+ adarms: bool = False
349
+
350
+ def setup(self):
351
+ # all experts must have the same depth
352
+ assert all(config.depth == self.configs[0].depth for config in self.configs)
353
+
354
+ self.embedder = Embedder(
355
+ vocab_size=PALIGEMMA_VOCAB_SIZE,
356
+ embed_dim=self.configs[0].width, # embedder for first expert only
357
+ name="embedder",
358
+ )
359
+ block_cls = nn.remat(
360
+ Block,
361
+ prevent_cse=False,
362
+ static_argnums=(5,), # 0=self, 6=deterministic
363
+ policy=jax.checkpoint_policies.nothing_saveable,
364
+ )
365
+ self.layers = nn.scan(
366
+ block_cls,
367
+ variable_axes={"params": 0},
368
+ split_rngs={"params": True, "dropout": True},
369
+ in_axes=(
370
+ 0,
371
+ nn.broadcast,
372
+ nn.broadcast,
373
+ nn.broadcast,
374
+ nn.broadcast,
375
+ ), # 0=kv_cache, 1=positions, 2=mask, 3=adarms_cond, 4=deterministic
376
+ length=self.configs[0].depth,
377
+ )(
378
+ configs=self.configs,
379
+ dropout=self.dropout,
380
+ dropout_bdims=self.dropout_bdims,
381
+ )
382
+ self.final_norms = [RMSNorm(name=_name("final_norm", i)) for i in range(len(self.configs))]
383
+
384
+ @at.typecheck
385
+ def embed(self, tokens: at.Int[at.Array, "b t"]) -> at.Float[at.Array, "b t d"]:
386
+ return self.embedder.encode(tokens).astype(self.embed_dtype)
387
+
388
+ @at.typecheck
389
+ def __call__(
390
+ self,
391
+ # list of token arrays, one for each expert, or None if that expert should not be run
392
+ embedded: Sequence[at.Float[at.Array, "b _t _d"] | None],
393
+ positions: at.Int[at.Array, "b t"],
394
+ mask: at.Bool[at.Array, "b t s"],
395
+ adarms_cond: Sequence[at.Float[at.Array, "b _d"] | None] | None = None,
396
+ *,
397
+ kv_cache: KVCache | None = None,
398
+ deterministic: bool = True,
399
+ ) -> tuple[Sequence[at.Float[at.Array, "b _t _d"] | None], KVCache]:
400
+ embedded = jax.tree.map(lambda e: e.astype(self.embed_dtype), embedded)
401
+ mask = jnp.asarray(mask)[:, None, :, :]
402
+ if adarms_cond is None:
403
+ adarms_cond = [None] * len(self.configs)
404
+
405
+ embedded, kv_cache = self.layers(embedded, kv_cache, positions, mask, adarms_cond, deterministic)
406
+
407
+ assert all(e.dtype == jnp.dtype(self.embed_dtype) for e in embedded if e is not None)
408
+
409
+ return [
410
+ f(e, a)[0] if e is not None else e for f, e, a in zip(self.final_norms, embedded, adarms_cond, strict=True)
411
+ ], kv_cache
412
+
413
+ def init(self, use_adarms: Sequence[bool]):
414
+ """Convenience method for initializing all parameters, necessary due to the quirks of linen."""
415
+ self.embed(jnp.zeros((1, 1), dtype=jnp.int32))
416
+ self(
417
+ [jnp.zeros((1, 1, c.width)) for c in self.configs],
418
+ jnp.zeros((1, len(self.configs)), dtype=jnp.int32),
419
+ jnp.zeros((1, len(self.configs), len(self.configs)), dtype=bool),
420
+ adarms_cond=[jnp.zeros((1, c.width)) if u else None for u, c in zip(use_adarms, self.configs, strict=True)],
421
+ )
422
+
423
+
424
+ def _apply_rope(x, *, positions, max_wavelength=10_000):
425
+ """Applies RoPE positions [B, L] to x [B, L, H, D]."""
426
+ freq_exponents = (2.0 / x.shape[-1]) * jnp.arange(x.shape[-1] // 2, dtype=jnp.float32)
427
+ timescale = max_wavelength**freq_exponents
428
+ radians = positions[..., None] / timescale[None, None, :]
429
+ radians = radians[..., None, :]
430
+ assert radians.dtype == jnp.float32
431
+ # radians.shape = [...,L,1,d=D/2]
432
+ sin, cos = jnp.sin(radians), jnp.cos(radians)
433
+ x1, x2 = jnp.split(x, 2, axis=-1)
434
+ res = jnp.concatenate([x1 * cos - x2 * sin, x2 * cos + x1 * sin], axis=-1)
435
+ assert res.dtype == jnp.float32
436
+ # The original bigvision impl allows RoPE to upcast to float32. It is then immediately downcast again to the cache
437
+ # dtype when in inference mode (but not in training mode). I don't think any of this was intentional. Based on the
438
+ # original DeepMind impl, as well as the widely-used transformers impl, it is ok to always downcast back to bfloat16
439
+ # here.
440
+ return res.astype(x.dtype)
441
+
442
+
443
+ def _name(name, i):
444
+ # we name layers like this because we want the first expert's weights to have no suffix (e.g., "attn"), so that they
445
+ # can be loaded seamlessly from the existing PaliGemma checkpoint. subsequent experts will have a suffix (e.g.,
446
+ # "attn_1") and their weights will be initialized from scratch. in practice, we only use two experts -- PaliGemma,
447
+ # and the action expert.
448
+ if i == 0:
449
+ return name
450
+ return f"{name}_{i}"
451
+
452
+
453
+ def _gated_residual(x, y, gate):
454
+ assert (x is None) == (y is None)
455
+ if x is None:
456
+ return None
457
+ if gate is None:
458
+ return x + y
459
+ return x + y * gate
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/gemma_fast.py ADDED
@@ -0,0 +1,437 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Big Vision Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ Gemma model implementation from big_vision/models/ppp/gemma.py (with small modifications for NNX compatibility)
17
+ Used for FAST autoregressive policies.
18
+ """
19
+
20
+ import dataclasses
21
+ from typing import Literal, TypeAlias
22
+
23
+ import einops
24
+ import flax.linen as nn
25
+ import jax
26
+ import jax.numpy as jnp
27
+ import ml_collections
28
+
29
+ import openpi.models.lora as lora
30
+ import openpi.shared.array_typing as at
31
+
32
+ Variant = Literal["gemma_2b", "gemma_2b_lora"]
33
+
34
+
35
+ def get_config(variant):
36
+ """Returns config for specified gemma variant."""
37
+ if variant == "gemma_2b":
38
+ return ml_collections.ConfigDict(
39
+ {
40
+ "variant": variant,
41
+ "width": 2048,
42
+ "depth": 18,
43
+ "mlp_dim": 16_384,
44
+ "num_heads": 8,
45
+ "num_kv_heads": 1,
46
+ "head_dim": 256,
47
+ "norm_eps": 1e-6,
48
+ "vocab_size": 257_152,
49
+ "scan": True,
50
+ "remat_policy": "nothing_saveable",
51
+ }
52
+ )
53
+ if variant == "gemma_2b_lora":
54
+ return ml_collections.ConfigDict(
55
+ {
56
+ "variant": variant,
57
+ "width": 2048,
58
+ "depth": 18,
59
+ "mlp_dim": 16_384,
60
+ "num_heads": 8,
61
+ "num_kv_heads": 1,
62
+ "head_dim": 256,
63
+ "norm_eps": 1e-6,
64
+ "vocab_size": 257_152,
65
+ "scan": True,
66
+ "remat_policy": "nothing_saveable",
67
+ "lora_configs": {
68
+ "attn": lora.LoRAConfig(rank=16, alpha=16.0),
69
+ "ffn": lora.LoRAConfig(rank=16, alpha=16.0),
70
+ },
71
+ }
72
+ )
73
+ raise ValueError(f"Unknown variant: {variant}")
74
+
75
+
76
+ @at.typecheck
77
+ class Einsum(nn.Module):
78
+ shape: tuple[int, ...]
79
+
80
+ @nn.compact
81
+ def __call__(self, eqn, x):
82
+ dtype = x.dtype # original dtype, could be half-precision
83
+ w = self.param("w", nn.initializers.zeros_init(), self.shape).astype(dtype)
84
+ return jnp.einsum(eqn, x, w)
85
+
86
+
87
+ @at.typecheck
88
+ class RMSNorm(nn.Module):
89
+ @nn.compact
90
+ def __call__(self, x):
91
+ dtype = x.dtype # original dtype, could be half-precision
92
+ scale = self.param("scale", nn.initializers.zeros_init(), (x.shape[-1]))
93
+ var = jnp.mean(jnp.square(x.astype(jnp.float32)), axis=-1, keepdims=True) # compute variance in float32
94
+ normed_inputs = jnp.asarray(x * jnp.reciprocal(jnp.sqrt(var + 1e-06))) # compute normalization in float32
95
+ normed_inputs = normed_inputs * (
96
+ 1 + scale
97
+ ) # scale by learned parameter in float32 (matches Flax implementation)
98
+ return normed_inputs.astype(dtype) # return in original dtype
99
+
100
+
101
+ @at.typecheck
102
+ class Embedder(nn.Module):
103
+ """Embedder module."""
104
+
105
+ vocab_size: int
106
+ embed_dim: int
107
+
108
+ def setup(self):
109
+ self.input_embedding_table = self.param(
110
+ "input_embedding",
111
+ nn.initializers.zeros_init(),
112
+ (self.vocab_size, self.embed_dim),
113
+ )
114
+
115
+ def encode(self, x):
116
+ x = self.input_embedding_table[(x,)]
117
+ x *= jnp.sqrt(self.embed_dim).astype(x.dtype)
118
+ return x
119
+
120
+ def decode(self, x):
121
+ return jnp.dot(x, self.input_embedding_table.T)
122
+
123
+
124
+ @at.typecheck
125
+ class Attention(nn.Module):
126
+ """Attention module."""
127
+
128
+ num_heads: int
129
+ num_kv_heads: int
130
+ features: int
131
+ head_dim: int
132
+
133
+ cache_dtype: str | None = None
134
+
135
+ lora_config: lora.LoRAConfig | None = None
136
+
137
+ def setup(self):
138
+ if self.num_kv_heads == self.num_heads:
139
+ self.qkv_einsum = lora.Einsum(
140
+ shape=(3, self.num_heads, self.features, self.head_dim),
141
+ name="qkv_einsum",
142
+ init_fn=nn.initializers.lecun_normal(in_axis=-2, out_axis=-1, batch_axis=(0, 1)),
143
+ lora_config=self.lora_config,
144
+ )
145
+ else:
146
+ self.q_einsum = lora.Einsum(
147
+ shape=(self.num_heads, self.features, self.head_dim),
148
+ name="q_einsum",
149
+ init_fn=nn.initializers.lecun_normal(in_axis=-2, out_axis=-1, batch_axis=(0,)),
150
+ lora_config=self.lora_config,
151
+ )
152
+ self.kv_einsum = lora.Einsum(
153
+ shape=(2, self.num_kv_heads, self.features, self.head_dim),
154
+ name="kv_einsum",
155
+ init_fn=nn.initializers.lecun_normal(in_axis=-2, out_axis=-1, batch_axis=(0, 1)),
156
+ lora_config=self.lora_config,
157
+ )
158
+ self.attn_vec_einsum = lora.Einsum(
159
+ shape=(self.num_heads, self.head_dim, self.features),
160
+ name="attn_vec_einsum",
161
+ init_fn=nn.initializers.lecun_normal(in_axis=-2, out_axis=-1, batch_axis=(0,)),
162
+ lora_config=self.lora_config,
163
+ )
164
+
165
+ def _init_cache(self, k, v, cache_size):
166
+ """Initialize KV cache"""
167
+ prefill_len = k.shape[1]
168
+ pad_width = ((0, 0), (0, cache_size - prefill_len), (0, 0), (0, 0))
169
+ cache_dtype = self.cache_dtype or k.dtype
170
+ k_cache = jnp.pad(k.astype(cache_dtype), pad_width)
171
+ v_cache = jnp.pad(v.astype(cache_dtype), pad_width)
172
+ idx = jnp.zeros((k.shape[0],), dtype=jnp.int32) + prefill_len
173
+ return idx, k_cache, v_cache
174
+
175
+ def _update_cache(self, k, v, idx, k_cache, v_cache):
176
+ """Update KV cache with new values"""
177
+ assert k.shape[1] == 1, "Only support kv-cache updates of length 1"
178
+ indices = (0, idx[0], 0, 0)
179
+ cache_dtype = self.cache_dtype or k.dtype
180
+ k_new = jax.lax.dynamic_update_slice(k_cache, k.astype(cache_dtype), indices)
181
+ v_new = jax.lax.dynamic_update_slice(v_cache, v.astype(cache_dtype), indices)
182
+ idx_new = idx + 1
183
+ return idx_new, k_new, v_new
184
+
185
+ @nn.compact
186
+ def __call__(self, x, positions, attn_mask, kv_cache, decode, deterministic=True): # noqa: FBT002
187
+ dtype = x.dtype # original dtype, could be half-precision
188
+ if self.num_kv_heads == self.num_heads:
189
+ q, k, v = self.qkv_einsum("BSD,3KDH->3BSKH", x)
190
+ else:
191
+ q = self.q_einsum("BTD,NDH->BTNH", x)
192
+ k, v = self.kv_einsum("BSD,2KDH->2BSKH", x)
193
+
194
+ q = _apply_rope(q, positions=positions) # promotes to float32
195
+ q *= self.head_dim**-0.5
196
+
197
+ k = _apply_rope(k, positions=positions) # promotes to float32
198
+
199
+ if kv_cache is None:
200
+ idx, k_cache, v_cache = self._init_cache(k, v, attn_mask.shape[-1])
201
+ else:
202
+ idx, k_cache, v_cache = kv_cache
203
+ idx, k_cache, v_cache = self._update_cache(k, v, idx, k_cache, v_cache)
204
+
205
+ k, v = k_cache, v_cache
206
+ kv_cache = (idx, k_cache, v_cache)
207
+
208
+ q = einops.rearrange(q, "B T (K G) H -> B T K G H", K=self.num_kv_heads)
209
+ logits = jnp.einsum("BTKGH,BSKH->BKGTS", q, k, preferred_element_type=jnp.float32)
210
+
211
+ if attn_mask.shape != (q.shape[0], 1, q.shape[1], k.shape[1]):
212
+ raise ValueError(
213
+ f"Attention mask with shape {attn_mask.shape} but shapes for q and k are: {q.shape} and {k.shape}"
214
+ )
215
+
216
+ # big_neg = jnp.finfo(logits.dtype).min
217
+ big_neg = -2.3819763e38 # See gemma/modules.py
218
+ masked_logits = jnp.where(attn_mask[:, :, None, :, :], logits, big_neg)
219
+
220
+ probs = jax.nn.softmax(masked_logits, axis=-1).astype(dtype)
221
+
222
+ encoded = jnp.einsum("BKGTS,BSKH->BTKGH", probs, v)
223
+ encoded = einops.rearrange(encoded, "B T K G H -> B T (K G) H")
224
+ return self.attn_vec_einsum("BTNH,NHD->BTD", encoded), kv_cache
225
+
226
+
227
+ @at.typecheck
228
+ class Block(nn.Module):
229
+ """Transformer block."""
230
+
231
+ num_heads: int
232
+ num_kv_heads: int
233
+ embed_dim: int
234
+ head_dim: int
235
+ hidden_dim: int
236
+
237
+ dropout: float = 0.0
238
+ dropout_bdims: tuple[int, ...] = ()
239
+ cache_dtype: str | None = None
240
+ lora_configs: ml_collections.ConfigDict = dataclasses.field(default_factory=ml_collections.ConfigDict)
241
+
242
+ def setup(self):
243
+ self.pre_attention_norm = RMSNorm()
244
+ self.attn = Attention(
245
+ num_heads=self.num_heads,
246
+ num_kv_heads=self.num_kv_heads,
247
+ features=self.embed_dim,
248
+ head_dim=self.head_dim,
249
+ cache_dtype=self.cache_dtype,
250
+ lora_config=self.lora_configs.get("attn"),
251
+ )
252
+ self.pre_ffw_norm = RMSNorm()
253
+ self.mlp = lora.FeedForward(
254
+ features=self.embed_dim, hidden_dim=self.hidden_dim, name="mlp", lora_config=self.lora_configs.get("ffn")
255
+ )
256
+ if self.dropout:
257
+ self.drop = nn.Dropout(self.dropout, self.dropout_bdims)
258
+ else:
259
+ self.drop = lambda x, _: x
260
+
261
+ def __call__(self, x, kv_cache, positions, attn_mask, decode, deterministic=True): # noqa: FBT002
262
+ x = nn.with_logical_constraint(x, ("act_batch", "act_len", "act_emb"))
263
+ inputs_normalized = self.pre_attention_norm(x)
264
+ attn_output, kv_cache = self.attn(inputs_normalized, positions, attn_mask, kv_cache, decode, deterministic)
265
+ attn_output = self.drop(attn_output, deterministic)
266
+ attn_output += x
267
+ residual = attn_output
268
+ attn_output = self.pre_ffw_norm(attn_output)
269
+ outputs = self.mlp(attn_output)
270
+ outputs = self.drop(outputs, deterministic)
271
+ outputs = residual + outputs
272
+ return outputs, kv_cache
273
+
274
+
275
+ KVCache: TypeAlias = tuple[at.Int[at.Array, " b"], at.Float[at.Array, "b _t _k _h"], at.Float[at.Array, "b _t _v _h"]]
276
+
277
+
278
+ @at.typecheck
279
+ class Module(nn.Module):
280
+ """gemma model."""
281
+
282
+ variant: str
283
+
284
+ width: int
285
+ depth: int
286
+ mlp_dim: int
287
+ num_heads: int
288
+ num_kv_heads: int
289
+ head_dim: int
290
+ norm_eps: float
291
+ vocab_size: int
292
+ embed_dtype: str
293
+
294
+ dropout: float = 0.0
295
+ dropout_bdims: tuple[int, ...] = () # Every float is dropped independently.
296
+ cache_dtype: str | None = None
297
+
298
+ scan: bool = False
299
+ remat_policy: str = "none"
300
+ lora_configs: ml_collections.ConfigDict = dataclasses.field(default_factory=ml_collections.ConfigDict)
301
+
302
+ @nn.compact
303
+ def __call__(
304
+ self,
305
+ tokens=None,
306
+ embedded_prefix=None,
307
+ embed_only=False, # noqa: FBT002
308
+ pre_logits=None,
309
+ positions=None,
310
+ mask=None,
311
+ decode=False, # noqa: FBT002
312
+ kv_cache=None,
313
+ deterministic=True, # noqa: FBT002
314
+ return_prelogits=False, # noqa: FBT002
315
+ ):
316
+ """Embed only, or complete forward pass.
317
+
318
+ Args:
319
+ tokens: Embedded, then and appended to `embedded_prefix`. Can be None.
320
+ embedded_prefix: Optional prefix that is already embedded.
321
+ embed_only: Whether to compute embeddings only.
322
+ pre_logits: If present computes logits from pre_logits and returns.
323
+ positions: Optional `[B, T]` allows to specify the absolute position of
324
+ the tokens.
325
+ mask: Optional attention mask `[B, T, S]`.
326
+ decode: Whether to use kv-cache. Caller must pass masks and positions.
327
+ deterministic: Forwarded to all dropout layers.
328
+ return_prelogits: Whether to return the pre-logits.
329
+
330
+ Returns:
331
+ If `embed_only=False`, then `(logits, out)` will be returned.
332
+ If `embed_only=True`, then the embeddings will be returned.
333
+ If `return_prelogits=True`, then the pre-logits will be returned.
334
+ """
335
+ out = {}
336
+
337
+ embedder = Embedder(vocab_size=self.vocab_size, embed_dim=self.width, name="embedder")
338
+
339
+ if pre_logits is not None:
340
+ x = out["pre_logits"] = pre_logits
341
+ logits = out["logits"] = embedder.decode(x)
342
+ return logits, out
343
+
344
+ x = []
345
+ if embedded_prefix is not None:
346
+ x.append(embedded_prefix)
347
+ if tokens is not None:
348
+ x.append(embedder.encode(tokens))
349
+
350
+ x = jnp.concatenate(x, axis=-2)
351
+ x = x.astype(self.embed_dtype)
352
+ batch_size, seq_len, width = x.shape
353
+
354
+ if embed_only:
355
+ return x
356
+
357
+ if decode:
358
+ assert positions is not None and mask is not None, ( # noqa: PT018
359
+ "Must explicitly pass positions and mask for decoding."
360
+ )
361
+
362
+ if positions is None:
363
+ positions = jnp.arange(seq_len).astype(jnp.int32)[None, :]
364
+ assert positions.shape[1] == x.shape[1], (positions.shape, x.shape)
365
+
366
+ if mask is None:
367
+ mask = nn.attention.make_causal_mask(jnp.ones([batch_size, seq_len]))
368
+ if mask.ndim == 3:
369
+ mask = mask[:, None, :, :]
370
+ cache_size = max(seq_len, mask.shape[-1])
371
+ assert mask.shape == (batch_size, 1, seq_len, cache_size), mask.shape
372
+
373
+ if self.remat_policy == "none":
374
+ block_cls = Block
375
+ else:
376
+ block_cls = nn.remat(
377
+ Block,
378
+ prevent_cse=not self.scan,
379
+ static_argnums=(5, 6), # 0=self, 5=decode, 6=deterministic
380
+ policy=getattr(jax.checkpoint_policies, self.remat_policy),
381
+ )
382
+
383
+ block_kw = {
384
+ "num_heads": self.num_heads,
385
+ "head_dim": self.head_dim,
386
+ "num_kv_heads": self.num_kv_heads,
387
+ "embed_dim": width,
388
+ "hidden_dim": self.mlp_dim,
389
+ "dropout": self.dropout,
390
+ "dropout_bdims": self.dropout_bdims,
391
+ "cache_dtype": self.cache_dtype,
392
+ "lora_configs": self.lora_configs,
393
+ }
394
+ layers = self.scope.push("layers")
395
+ blocks = [
396
+ nn.scan(
397
+ block_cls,
398
+ variable_axes={"params": 0},
399
+ split_rngs={"params": True, "dropout": True},
400
+ in_axes=(0, nn.broadcast, nn.broadcast, nn.broadcast, nn.broadcast), # 0=kv_cache, 1=positions, 2=mask
401
+ length=self.depth,
402
+ )(parent=layers, **block_kw)
403
+ ]
404
+ for block in blocks:
405
+ x, kv_cache = block(x, kv_cache, positions, mask, decode, deterministic)
406
+
407
+ assert x.dtype == jnp.dtype(self.embed_dtype) # Sanity check.
408
+ out["encoded"] = x
409
+
410
+ x = RMSNorm(name="final_norm")(x)
411
+ out["pre_logits"] = x
412
+ if return_prelogits:
413
+ return x, kv_cache, out
414
+
415
+ x = embedder.decode(x)
416
+ out["logits"] = x
417
+
418
+ return x, kv_cache, out
419
+
420
+ def init(self):
421
+ """Convenience method for initializing all parameters, necessary due to the quirks of linen."""
422
+ self(jnp.zeros((1, 1), dtype=jnp.int32))
423
+
424
+
425
+ def _apply_rope(x, *, positions, max_wavelength=10_000):
426
+ """Applies RoPE positions [B, L] to x [B, L, H, D]."""
427
+ freq_exponents = (2.0 / x.shape[-1]) * jnp.arange(x.shape[-1] // 2, dtype=jnp.float32)
428
+ timescale = max_wavelength**freq_exponents
429
+ radians = positions[..., None] / timescale[None, None, :]
430
+ radians = radians[..., None, :]
431
+ assert radians.dtype == jnp.float32
432
+ # radians.shape = [...,L,1,d=D/2]
433
+ sin, cos = jnp.sin(radians), jnp.cos(radians)
434
+ x1, x2 = jnp.split(x, 2, axis=-1)
435
+ res = jnp.concatenate([x1 * cos - x2 * sin, x2 * cos + x1 * sin], axis=-1)
436
+ assert res.dtype == jnp.float32
437
+ return res
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/lora.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import re
3
+
4
+ import flax.linen as nn
5
+ import flax.struct as struct
6
+ import jax.numpy as jnp
7
+
8
+ import openpi.shared.array_typing as at
9
+
10
+
11
+ @struct.dataclass
12
+ class LoRAConfig:
13
+ """Configuration for LoRA."""
14
+
15
+ # LoRA rank.
16
+ rank: int
17
+ # LoRA scaling factor.
18
+ alpha: float = 1.0
19
+ # Initialization function for LoRA parameters.
20
+ init_fn: nn.initializers.Initializer = nn.initializers.normal(stddev=0.01)
21
+ # Enable rank-stabilized LoRA: https://arxiv.org/pdf/2312.03732
22
+ rslora: bool = False
23
+ # Axes in the weight to apply LoRA to. Should typically be the last two axes.
24
+ axes: tuple[int, int] = (-2, -1)
25
+ # Axis label which is used by LoRA in einsum equations. Must not be present in the original equation.
26
+ label: str = "L"
27
+
28
+ @property
29
+ def scaling_value(self) -> float:
30
+ return self.alpha / math.sqrt(self.rank) if self.rslora else self.alpha / self.rank
31
+
32
+
33
+ class Einsum(nn.Module):
34
+ """Einsum with LoRA support. Can be used as a drop-in replacement for the Gemma Einsum."""
35
+
36
+ # Shape of the weight.
37
+ shape: tuple[int, ...]
38
+ # Initialization function for the weight.
39
+ init_fn: nn.initializers.Initializer = nn.initializers.zeros
40
+ # If not None, apply LoRA to the weight.
41
+ lora_config: LoRAConfig | None = None
42
+
43
+ def setup(self):
44
+ self.w = self.param("w", self.init_fn, self.shape)
45
+
46
+ if config := self.lora_config:
47
+ # Setup LoRA parameters.
48
+ shape_a, shape_b = list(self.shape), list(self.shape)
49
+ shape_a[config.axes[1]] = config.rank
50
+ shape_b[config.axes[0]] = config.rank
51
+ self.w_a = self.param("lora_a", config.init_fn, shape_a)
52
+ self.w_b = self.param("lora_b", config.init_fn, shape_b)
53
+
54
+ @nn.compact
55
+ def __call__(self, eqn: str, x):
56
+ dtype = x.dtype # original dtype, could be half-precision
57
+ result = jnp.einsum(eqn, x, self.w.astype(dtype))
58
+
59
+ if config := self.lora_config:
60
+ eqn_a, eqn_b = self._make_lora_eqns(eqn)
61
+ lora = jnp.einsum(eqn_a, x, self.w_a.astype(dtype))
62
+ lora = jnp.einsum(eqn_b, lora, self.w_b.astype(dtype))
63
+ result = result + lora * config.scaling_value
64
+
65
+ return result
66
+
67
+ def _make_lora_eqns(self, eqn: str) -> tuple[str, str]:
68
+ if "L" in eqn:
69
+ raise ValueError(f"L already in eqn: {eqn}")
70
+ if not (m := re.match("(.*),(.*)->(.*)", eqn)):
71
+ raise ValueError(f"Unsupported einsum eqn: {eqn}")
72
+ lhs, rhs, out = m.groups()
73
+
74
+ assert self.lora_config is not None
75
+ a_label, b_label = (rhs[x] for x in self.lora_config.axes)
76
+ label = self.lora_config.label
77
+
78
+ a_rhs = rhs.replace(b_label, label)
79
+ a_out = out.replace(b_label, label)
80
+ eqn_a = f"{lhs},{a_rhs}->{a_out}"
81
+
82
+ b_rhs = rhs.replace(a_label, label)
83
+ eqn_b = f"{a_out},{b_rhs}->{out}"
84
+
85
+ return eqn_a, eqn_b
86
+
87
+
88
+ class FeedForward(nn.Module):
89
+ """Feed forward module."""
90
+
91
+ features: int
92
+ hidden_dim: int
93
+ # If not None, apply LoRA to the weight.
94
+ lora_config: LoRAConfig | None = None
95
+
96
+ def setup(self):
97
+ self.w_gating = self.param(
98
+ "gating_einsum",
99
+ nn.initializers.lecun_normal(in_axis=-2, out_axis=-1, batch_axis=(0,)),
100
+ (2, self.features, self.hidden_dim),
101
+ )
102
+ self.w_linear = self.param(
103
+ "linear",
104
+ nn.initializers.lecun_normal(in_axis=-2, out_axis=-1),
105
+ (self.hidden_dim, self.features),
106
+ )
107
+ self.w_gating_lora = None
108
+ self.w_linear_lora = None
109
+ if self.lora_config:
110
+ # Setup LoRA parameters.
111
+ # TODO: follow up with a simplified init_fn api.
112
+ self.w_gating_lora = (
113
+ self.param("gating_einsum_lora_a", self.lora_config.init_fn, (2, self.features, self.lora_config.rank)),
114
+ self.param(
115
+ "gating_einsum_lora_b", self.lora_config.init_fn, (2, self.lora_config.rank, self.hidden_dim)
116
+ ),
117
+ )
118
+ self.w_linear_lora = (
119
+ self.param("linear_lora_a", self.lora_config.init_fn, (self.hidden_dim, self.lora_config.rank)),
120
+ self.param("linear_lora_b", self.lora_config.init_fn, (self.lora_config.rank, self.features)),
121
+ )
122
+
123
+ @nn.compact
124
+ def __call__(self, x):
125
+ dtype = x.dtype # original dtype, could be half-precision
126
+ ff_gate = self._dot(
127
+ x,
128
+ self.w_gating[0],
129
+ None if self.w_gating_lora is None else (self.w_gating_lora[0][0], self.w_gating_lora[1][0]),
130
+ )
131
+ gate_value = nn.gelu(ff_gate)
132
+
133
+ ff1 = self._dot(
134
+ x,
135
+ self.w_gating[1],
136
+ None if self.w_gating_lora is None else (self.w_gating_lora[0][1], self.w_gating_lora[1][1]),
137
+ )
138
+ activations = gate_value * ff1
139
+
140
+ outputs = self._dot(activations, self.w_linear, self.w_linear_lora)
141
+ assert outputs.dtype == dtype
142
+ return outputs
143
+
144
+ def _dot(self, x: at.Array, w: at.Array, lora_weights: tuple[at.Array, at.Array] | None) -> at.Array:
145
+ base = jnp.dot(x, w.astype(x.dtype))
146
+ if lora_weights is None:
147
+ return base
148
+ return base + jnp.dot(jnp.dot(x, lora_weights[0].astype(x.dtype)), lora_weights[1].astype(x.dtype))
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/lora_test.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import flax.linen as nn
2
+ import jax
3
+ import jax.numpy as jnp
4
+
5
+ import openpi.models.lora as lora
6
+
7
+
8
+ def test_lora_einsum_params_shape():
9
+ shape = (3, 8, 32, 4) # (3KDH)
10
+ einsum = lora.Einsum(shape)
11
+ lora0 = lora.Einsum(shape, lora_config=lora.LoRAConfig(rank=2))
12
+ lora1 = lora.Einsum(shape, lora_config=lora.LoRAConfig(rank=2, axes=(1, 2)))
13
+
14
+ key = jax.random.key(0)
15
+ x = jax.random.normal(key, (8, 64, 32)) # (BSD)
16
+ eqn = "BSD,3KDH->3BSKH"
17
+
18
+ # Ensure that lora parameters are not initialized when LoRA is not used.
19
+ params = einsum.init(key, eqn, x)
20
+ assert "lora_a" not in params["params"]
21
+ assert "lora_b" not in params["params"]
22
+
23
+ # Check that default axes work.
24
+ params_lora0 = lora0.init(key, eqn, x)
25
+ assert params_lora0["params"]["lora_a"].shape == (3, 8, 32, 2)
26
+ assert params_lora0["params"]["lora_b"].shape == (3, 8, 2, 4)
27
+
28
+ # Check that user provided axes work.
29
+ params_lora1 = lora1.init(key, eqn, x)
30
+ assert params_lora1["params"]["lora_a"].shape == (3, 8, 2, 4)
31
+ assert params_lora1["params"]["lora_b"].shape == (3, 2, 32, 4)
32
+
33
+
34
+ def test_lora_einsum_same_output():
35
+ shape = (3, 8, 32, 4) # (3KDH)
36
+ einsum = lora.Einsum(shape)
37
+ einsum_lora = lora.Einsum(shape, lora_config=lora.LoRAConfig(rank=2, init_fn=nn.initializers.zeros))
38
+
39
+ key = jax.random.key(0)
40
+ x = jax.random.normal(key, (8, 64, 32)) # (BSD)
41
+ eqn = "BSD,3KDH->3BSKH"
42
+
43
+ params = einsum.init(key, eqn, x)
44
+ output = einsum.apply(params, eqn, x)
45
+
46
+ params_lora = einsum_lora.init(key, eqn, x)
47
+ output_lora = einsum_lora.apply(params_lora, eqn, x)
48
+
49
+ # Results are the same since the LoRA parameters are initialized to zeros.
50
+ assert jnp.allclose(output, output_lora)
51
+
52
+
53
+ def test_lora_ffn_params_shape():
54
+ ffn = lora.FeedForward(features=8, hidden_dim=32)
55
+ ffn_lora = lora.FeedForward(
56
+ features=8,
57
+ hidden_dim=32,
58
+ lora_config=lora.LoRAConfig(rank=2),
59
+ )
60
+
61
+ key = jax.random.key(0)
62
+ x = jax.random.normal(key, (2, 8))
63
+
64
+ params = ffn.init(key, x)
65
+ assert params["params"]["gating_einsum"].shape == (2, 8, 32)
66
+ assert params["params"]["linear"].shape == (32, 8)
67
+
68
+ params_lora = ffn_lora.init(key, x)
69
+ assert params_lora["params"]["gating_einsum"].shape == (2, 8, 32)
70
+ assert params_lora["params"]["linear"].shape == (32, 8)
71
+ assert params_lora["params"]["gating_einsum_lora_a"].shape == (2, 8, 2)
72
+ assert params_lora["params"]["gating_einsum_lora_b"].shape == (2, 2, 32)
73
+ assert params_lora["params"]["linear_lora_a"].shape == (32, 2)
74
+ assert params_lora["params"]["linear_lora_b"].shape == (2, 8)
75
+
76
+
77
+ def test_lora_ffn_same_output():
78
+ ffn = lora.FeedForward(features=8, hidden_dim=32)
79
+ ffn_lora = lora.FeedForward(
80
+ features=8,
81
+ hidden_dim=32,
82
+ lora_config=lora.LoRAConfig(rank=2, init_fn=nn.initializers.zeros),
83
+ )
84
+
85
+ key = jax.random.key(0)
86
+ x = jax.random.normal(key, (2, 8))
87
+
88
+ params = ffn.init(key, x)
89
+ output = ffn.apply(params, x)
90
+
91
+ params_lora = ffn_lora.init(key, x)
92
+ output_lora = ffn_lora.apply(params_lora, x)
93
+
94
+ assert jnp.allclose(output, output_lora)
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/model.py ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import abc
2
+ from collections.abc import Sequence
3
+ import dataclasses
4
+ import enum
5
+ import logging
6
+ import pathlib
7
+ from typing import Generic, TypeVar
8
+
9
+ import augmax
10
+ from flax import nnx
11
+ from flax import struct
12
+ from flax import traverse_util
13
+ import jax
14
+ import jax.numpy as jnp
15
+ import numpy as np
16
+ import orbax.checkpoint as ocp
17
+ import safetensors
18
+ import torch
19
+
20
+ from openpi.models_pytorch import pi0_pytorch
21
+ from openpi.shared import image_tools
22
+ import openpi.shared.array_typing as at
23
+
24
+ logger = logging.getLogger("openpi")
25
+
26
+ # Type variable for array types (JAX arrays, PyTorch tensors, or numpy arrays)
27
+ ArrayT = TypeVar("ArrayT", bound=jax.Array | torch.Tensor | np.ndarray)
28
+
29
+
30
+ class ModelType(enum.Enum):
31
+ """Supported model types."""
32
+
33
+ PI0 = "pi0"
34
+ PI0_FAST = "pi0_fast"
35
+ PI05 = "pi05"
36
+
37
+
38
+ # The model always expects these images
39
+ IMAGE_KEYS = (
40
+ "base_0_rgb",
41
+ "left_wrist_0_rgb",
42
+ "right_wrist_0_rgb",
43
+ )
44
+
45
+
46
+ # This may need change if we release a small model.
47
+ IMAGE_RESOLUTION = (224, 224)
48
+
49
+
50
+ # Data format
51
+ #
52
+ # Data transforms produce the model input as a nested dictionary which is later converted
53
+ # into `Obesrvation` and `Actions` objects. See below.
54
+ #
55
+ # In the dictory form, this data should look like:
56
+ # {
57
+ # # Observation data.
58
+ # "image": {
59
+ # "base_0_rgb": (float32|uint8)[*b, h, w, 3], # RGB image in [-1, 1] or [0, 255]
60
+ # ... # Additional camera views
61
+ # },
62
+ # "image_mask": {
63
+ # "base_0_rgb": bool[*b], # True if image is valid
64
+ # ... # Masks for additional views
65
+ # },
66
+ # "state": float32[*b, s], # Low-dimensional robot state
67
+ # "tokenized_prompt": int32[*b, l], # Optional, tokenized language prompt
68
+ # "tokenized_prompt_mask": bool[*b, l], # Optional, mask for tokenized prompt
69
+ # "token_ar_mask": int32[*b, l], # Optional, autoregressive mask for FAST model
70
+ # "token_loss_mask": bool[*b, l], # Optional, loss mask for FAST model
71
+ #
72
+ # # Actions data.
73
+ # "actions": float32[*b ah ad]
74
+ # }
75
+ # where:
76
+ # *b = batch dimensions
77
+ # h,w = image height/width
78
+ # s = state dimension
79
+ # l = sequence length
80
+ #
81
+ @at.typecheck
82
+ @struct.dataclass
83
+ class Observation(Generic[ArrayT]):
84
+ """Holds observations, i.e., inputs to the model.
85
+
86
+ See `Observation.from_dict` to see the expected dictionary form. This is the format
87
+ that should be produced by the data transforms.
88
+ """
89
+
90
+ # Images, in [-1, 1] float32.
91
+ images: dict[str, at.Float[ArrayT, "*b h w c"]]
92
+ # Image masks, with same keys as images.
93
+ image_masks: dict[str, at.Bool[ArrayT, "*b"]]
94
+ # Low-dimensional robot state.
95
+ state: at.Float[ArrayT, "*b s"]
96
+
97
+ # Tokenized prompt.
98
+ tokenized_prompt: at.Int[ArrayT, "*b l"] | None = None
99
+ # Tokenized prompt mask.
100
+ tokenized_prompt_mask: at.Bool[ArrayT, "*b l"] | None = None
101
+
102
+ # pi0-fast model specific fields.
103
+
104
+ # Token auto-regressive mask (for FAST autoregressive model).
105
+ token_ar_mask: at.Int[ArrayT, "*b l"] | None = None
106
+ # Token loss mask (for FAST autoregressive model).
107
+ token_loss_mask: at.Bool[ArrayT, "*b l"] | None = None
108
+
109
+ @classmethod
110
+ def from_dict(cls, data: at.PyTree[ArrayT]) -> "Observation[ArrayT]":
111
+ """This method defines the mapping between unstructured data (i.e., nested dict) to the structured Observation format."""
112
+ # Ensure that tokenized_prompt and tokenized_prompt_mask are provided together.
113
+ if ("tokenized_prompt" in data) != ("tokenized_prompt_mask" in data):
114
+ raise ValueError("tokenized_prompt and tokenized_prompt_mask must be provided together.")
115
+ # If images are uint8, convert them to [-1, 1] float32.
116
+ for key in data["image"]:
117
+ if data["image"][key].dtype == np.uint8:
118
+ data["image"][key] = data["image"][key].astype(np.float32) / 255.0 * 2.0 - 1.0
119
+ elif hasattr(data["image"][key], "dtype") and data["image"][key].dtype == torch.uint8:
120
+ data["image"][key] = data["image"][key].to(torch.float32).permute(0, 3, 1, 2) / 255.0 * 2.0 - 1.0
121
+ return cls(
122
+ images=data["image"],
123
+ image_masks=data["image_mask"],
124
+ state=data["state"],
125
+ tokenized_prompt=data.get("tokenized_prompt"),
126
+ tokenized_prompt_mask=data.get("tokenized_prompt_mask"),
127
+ token_ar_mask=data.get("token_ar_mask"),
128
+ token_loss_mask=data.get("token_loss_mask"),
129
+ )
130
+
131
+ def to_dict(self) -> at.PyTree[ArrayT]:
132
+ """Convert the Observation to a nested dict."""
133
+ result = dataclasses.asdict(self)
134
+ result["image"] = result.pop("images")
135
+ result["image_mask"] = result.pop("image_masks")
136
+ return result
137
+
138
+
139
+ # Defines the format of the actions. This field is included as "actions" inside the dictionary
140
+ # produced by the data transforms.
141
+ Actions = at.Float[ArrayT, "*b ah ad"]
142
+
143
+
144
+ def preprocess_observation(
145
+ rng: at.KeyArrayLike | None,
146
+ observation: Observation,
147
+ *,
148
+ train: bool = False,
149
+ image_keys: Sequence[str] = IMAGE_KEYS,
150
+ image_resolution: tuple[int, int] = IMAGE_RESOLUTION,
151
+ ) -> Observation:
152
+ """Preprocess the observations by performing image augmentations (if train=True), resizing (if necessary), and
153
+ filling in a default image mask (if necessary).
154
+ """
155
+
156
+ if not set(image_keys).issubset(observation.images):
157
+ raise ValueError(f"images dict missing keys: expected {image_keys}, got {list(observation.images)}")
158
+
159
+ batch_shape = observation.state.shape[:-1]
160
+
161
+ out_images = {}
162
+ for key in image_keys:
163
+ image = observation.images[key]
164
+ if image.shape[1:3] != image_resolution:
165
+ logger.info(f"Resizing image {key} from {image.shape[1:3]} to {image_resolution}")
166
+ image = image_tools.resize_with_pad(image, *image_resolution)
167
+
168
+ if train:
169
+ # Convert from [-1, 1] to [0, 1] for augmax.
170
+ image = image / 2.0 + 0.5
171
+
172
+ transforms = []
173
+ if "wrist" not in key:
174
+ height, width = image.shape[1:3]
175
+ transforms += [
176
+ augmax.RandomCrop(int(width * 0.95), int(height * 0.95)),
177
+ augmax.Resize(width, height),
178
+ augmax.Rotate((-5, 5)),
179
+ ]
180
+ transforms += [
181
+ augmax.ColorJitter(brightness=0.3, contrast=0.4, saturation=0.5),
182
+ ]
183
+ sub_rngs = jax.random.split(rng, image.shape[0])
184
+ image = jax.vmap(augmax.Chain(*transforms))(sub_rngs, image)
185
+
186
+ # Back to [-1, 1].
187
+ image = image * 2.0 - 1.0
188
+
189
+ out_images[key] = image
190
+
191
+ # obtain mask
192
+ out_masks = {}
193
+ for key in out_images:
194
+ if key not in observation.image_masks:
195
+ # do not mask by default
196
+ out_masks[key] = jnp.ones(batch_shape, dtype=jnp.bool)
197
+ else:
198
+ out_masks[key] = jnp.asarray(observation.image_masks[key])
199
+
200
+ return Observation(
201
+ images=out_images,
202
+ image_masks=out_masks,
203
+ state=observation.state,
204
+ tokenized_prompt=observation.tokenized_prompt,
205
+ tokenized_prompt_mask=observation.tokenized_prompt_mask,
206
+ token_ar_mask=observation.token_ar_mask,
207
+ token_loss_mask=observation.token_loss_mask,
208
+ )
209
+
210
+
211
+ @dataclasses.dataclass(frozen=True)
212
+ class BaseModelConfig(abc.ABC):
213
+ """Configuration shared by all models. Specific models should inherit from this class, and implement the `create`
214
+ method to create the corresponding model.
215
+ """
216
+
217
+ # Action space dimension.
218
+ action_dim: int
219
+ # Action sequence length.
220
+ action_horizon: int
221
+ # Tokenized prompt maximum length.
222
+ max_token_len: int
223
+
224
+ @property
225
+ @abc.abstractmethod
226
+ def model_type(self) -> ModelType:
227
+ """The model type."""
228
+
229
+ @abc.abstractmethod
230
+ def create(self, rng: at.KeyArrayLike) -> "BaseModel":
231
+ """Create a new model, initializing parameters."""
232
+
233
+ def load(self, params: at.Params, *, remove_extra_params: bool = True) -> "BaseModel":
234
+ """Create a model with the given parameters."""
235
+ model = nnx.eval_shape(self.create, jax.random.key(0))
236
+ graphdef, state = nnx.split(model)
237
+ if remove_extra_params:
238
+ params = ocp.transform_utils.intersect_trees(state.to_pure_dict(), params)
239
+ at.check_pytree_equality(expected=state.to_pure_dict(), got=params, check_shapes=True, check_dtypes=False)
240
+ state.replace_by_pure_dict(params)
241
+ return nnx.merge(graphdef, state)
242
+
243
+ def load_pytorch(self, train_config, weight_path: str):
244
+ logger.info(f"train_config: {train_config}")
245
+ model = pi0_pytorch.PI0Pytorch(config=train_config.model)
246
+ safetensors.torch.load_model(model, weight_path)
247
+ return model
248
+
249
+ @abc.abstractmethod
250
+ def inputs_spec(self, *, batch_size: int = 1) -> tuple[Observation, Actions]:
251
+ """Returns the input specification for the model. Values are jax.ShapeDtypeStruct."""
252
+
253
+ def fake_obs(self, batch_size: int = 1) -> Observation:
254
+ observation_spec, _ = self.inputs_spec(batch_size=batch_size)
255
+ return jax.tree.map(lambda x: jnp.ones(x.shape, x.dtype), observation_spec)
256
+
257
+ def fake_act(self, batch_size: int = 1) -> Actions:
258
+ _, action_spec = self.inputs_spec(batch_size=batch_size)
259
+ return jax.tree.map(lambda x: jnp.ones(x.shape, x.dtype), action_spec)
260
+
261
+
262
+ @dataclasses.dataclass
263
+ class BaseModel(nnx.Module, abc.ABC):
264
+ """Base class for all model implementations. Specific models should inherit from this class. They should call
265
+ super().__init__() to initialize the shared attributes (action_dim, action_horizon, and max_token_len).
266
+ """
267
+
268
+ action_dim: int
269
+ action_horizon: int
270
+ max_token_len: int
271
+
272
+ @abc.abstractmethod
273
+ def compute_loss(
274
+ self,
275
+ rng: at.KeyArrayLike,
276
+ observation: Observation,
277
+ actions: Actions,
278
+ *,
279
+ train: bool = False,
280
+ ) -> at.Float[at.Array, "*b ah"]: ...
281
+
282
+ @abc.abstractmethod
283
+ def sample_actions(self, rng: at.KeyArrayLike, observation: Observation, **kwargs) -> Actions: ...
284
+
285
+
286
+ def restore_params(
287
+ params_path: pathlib.Path | str,
288
+ *,
289
+ restore_type: type[np.ndarray] | type[jax.Array] = jax.Array,
290
+ dtype: jnp.dtype | None = None,
291
+ sharding: jax.sharding.Sharding | None = None,
292
+ ) -> at.Params:
293
+ """Restores unstructured params PyTree from a checkpoint.
294
+
295
+ This works with checkpoints saved with `save_state` during openpi training (see `training/checkpoints.py`) as
296
+ well as pre-trained checkpoints released for openpi.
297
+
298
+ Args:
299
+ params_path: The local path to the checkpoint directory.
300
+ restore_type: The type to restore the params as. Can be set to `np.ndarray` to load the params as a numpy array.
301
+ dtype: The dtype to restore all params as. If not provided, will use the original dtype from the checkpoint.
302
+ sharding: The sharding to use for the params. If not provided, the params will be replicated across all devices.
303
+
304
+ Returns:
305
+ The restored params.
306
+ """
307
+ params_path = pathlib.Path(params_path).resolve() if not str(params_path).startswith("gs://") else params_path
308
+
309
+ if restore_type is jax.Array and sharding is None:
310
+ mesh = jax.sharding.Mesh(jax.devices(), ("x",))
311
+ sharding = jax.sharding.NamedSharding(mesh, jax.sharding.PartitionSpec())
312
+
313
+ with ocp.PyTreeCheckpointer() as ckptr:
314
+ metadata = ckptr.metadata(params_path)
315
+ item = {"params": metadata["params"]}
316
+
317
+ params = ckptr.restore(
318
+ params_path,
319
+ ocp.args.PyTreeRestore(
320
+ item=item,
321
+ restore_args=jax.tree.map(
322
+ lambda _: ocp.ArrayRestoreArgs(sharding=sharding, restore_type=restore_type, dtype=dtype), item
323
+ ),
324
+ ),
325
+ )["params"]
326
+
327
+ # If the params were saved with `save_state` during openpi training, every key path will end with "value", which is
328
+ # added by `nnx.State`. We remove the "value" suffix here and always return what NNX calls a "pure dict".
329
+ flat_params = traverse_util.flatten_dict(params)
330
+ if all(kp[-1] == "value" for kp in flat_params):
331
+ flat_params = {kp[:-1]: v for kp, v in flat_params.items()}
332
+ return traverse_util.unflatten_dict(flat_params)
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/pi0_fast.py ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dataclasses
2
+ import logging
3
+ from typing import Any
4
+
5
+ import einops
6
+ import flax.nnx as nnx
7
+ import flax.nnx.bridge as nnx_bridge
8
+ import jax
9
+ import jax.numpy as jnp
10
+ from typing_extensions import override
11
+
12
+ from openpi.models import model as _model
13
+ import openpi.models.gemma_fast as _gemma
14
+ import openpi.models.siglip as _siglip
15
+ from openpi.shared import array_typing as at
16
+ import openpi.shared.nnx_utils as nnx_utils
17
+
18
+ logger = logging.getLogger("openpi")
19
+
20
+ PALIGEMMA_EOS_TOKEN = 1
21
+
22
+
23
+ def make_attn_mask(input_mask, mask_ar):
24
+ """Adapted from big_vision.
25
+
26
+ Tokens can attend to valid inputs tokens which have a cumulative mask_ar
27
+ smaller or equal to theirs. This way `mask_ar` bool[?B, N] can be used to
28
+ setup several types of attention, for example:
29
+
30
+ [[1 1 1 1 1 1]]: pure causal attention.
31
+
32
+ [[0 0 0 1 1 1]]: prefix-lm attention. The first 3 tokens can attend between
33
+ themselves and the last 3 tokens have a causal attention. The first
34
+ entry could also be a 1 without changing behaviour.
35
+
36
+ [[1 0 1 0 1 0 0 1 0 0]]: causal attention between 4 blocks. Tokens of a
37
+ block can attend all previous blocks and all tokens on the same block.
38
+
39
+ Args:
40
+ input_mask: bool[B, N] true if its part of the input, false if padding.
41
+ mask_ar: bool[?B, N] mask that's true where previous tokens cannot depend on
42
+ it and false where it shares the same attention mask as the previous token.
43
+ """
44
+ mask_ar = jnp.broadcast_to(mask_ar, input_mask.shape)
45
+ cumsum = jnp.cumsum(mask_ar, axis=1)
46
+ attn_mask = cumsum[:, None, :] <= cumsum[:, :, None]
47
+ valid_mask = input_mask[:, None, :] * input_mask[:, :, None]
48
+ return jnp.logical_and(attn_mask, valid_mask)
49
+
50
+
51
+ @jax.vmap
52
+ def left_to_right_align(x, input_mask, attn_mask):
53
+ """Converts input from left-align to right-aligned."""
54
+ # Due to vmap, this is operating in a single example (not batch level).
55
+ assert x.ndim == 2
56
+ assert input_mask.ndim == 1
57
+ assert attn_mask.ndim == 2
58
+ assert x.shape[0] == input_mask.shape[0]
59
+ assert attn_mask.shape[0] == attn_mask.shape[1], attn_mask.shape
60
+ seqlen = jnp.max(input_mask * jnp.arange(input_mask.shape[0])) + 1
61
+ x = jnp.roll(x, -seqlen, axis=0)
62
+ input_mask = jnp.roll(input_mask, -seqlen, axis=0)
63
+ attn_mask = jnp.roll(attn_mask, -seqlen, axis=(0, 1))
64
+ return x, input_mask, attn_mask
65
+
66
+
67
+ def put_along_last_axis(arr, indices, values):
68
+ """Like np.put_along_axis(..., axis=-1), since jax is missing it."""
69
+ assert arr.ndim == indices.ndim == values.ndim, (arr.ndim, indices.ndim, values.ndim)
70
+ onehot = jax.nn.one_hot(indices, arr.shape[-1], dtype=values.dtype)
71
+ put_mask = jnp.einsum("...i,...in->...n", jnp.ones(values.shape, jnp.int32), onehot)
72
+ put_values = jnp.einsum("...i,...in->...n", values, onehot)
73
+ return jnp.where(put_mask, put_values, arr)
74
+
75
+
76
+ @dataclasses.dataclass(frozen=True)
77
+ class Pi0FASTConfig(_model.BaseModelConfig):
78
+ dtype: str = "bfloat16"
79
+ paligemma_variant: _gemma.Variant = "gemma_2b"
80
+
81
+ # Set the model specific defaults.
82
+ action_dim: int = 32
83
+ action_horizon: int = 32
84
+ max_token_len: int = 250
85
+
86
+ # Tokenizer for the fast model.
87
+ fast_model_tokenizer: Any | None = None
88
+ # Keyword arguments for the fast model tokenizer.
89
+ fast_model_tokenizer_kwargs: dict[str, Any] | None = None
90
+
91
+ @property
92
+ @override
93
+ def model_type(self) -> _model.ModelType:
94
+ return _model.ModelType.PI0_FAST
95
+
96
+ @override
97
+ def create(self, rng: at.KeyArrayLike) -> "Pi0FAST":
98
+ return Pi0FAST(self, rngs=nnx.Rngs(rng))
99
+
100
+ @override
101
+ def inputs_spec(self, *, batch_size: int = 1) -> tuple[_model.Observation, _model.Actions]:
102
+ image_spec = jax.ShapeDtypeStruct([batch_size, *_model.IMAGE_RESOLUTION, 3], jnp.float32)
103
+ image_mask_spec = jax.ShapeDtypeStruct([batch_size], jnp.bool_)
104
+
105
+ with at.disable_typechecking():
106
+ observation_spec = _model.Observation(
107
+ images={
108
+ "base_0_rgb": image_spec,
109
+ "base_1_rgb": image_spec,
110
+ "wrist_0_rgb": image_spec,
111
+ },
112
+ image_masks={
113
+ "base_0_rgb": image_mask_spec,
114
+ "base_1_rgb": image_mask_spec,
115
+ "wrist_0_rgb": image_mask_spec,
116
+ },
117
+ state=jax.ShapeDtypeStruct([batch_size, self.action_dim], jnp.float32),
118
+ tokenized_prompt=jax.ShapeDtypeStruct([batch_size, self.max_token_len], jnp.int32),
119
+ tokenized_prompt_mask=jax.ShapeDtypeStruct([batch_size, self.max_token_len], bool),
120
+ token_ar_mask=jax.ShapeDtypeStruct([batch_size, self.max_token_len], jnp.int32),
121
+ token_loss_mask=jax.ShapeDtypeStruct([batch_size, self.max_token_len], jnp.bool_),
122
+ )
123
+ action_spec = jax.ShapeDtypeStruct([batch_size, self.action_horizon, self.action_dim], jnp.float32)
124
+
125
+ return observation_spec, action_spec
126
+
127
+ def get_freeze_filter(self) -> nnx.filterlib.Filter:
128
+ """Returns the freeze filter based on the model config."""
129
+ if "lora" in self.paligemma_variant:
130
+ return nnx.All(nnx_utils.PathRegex(".*llm.*"), nnx.Not(nnx_utils.PathRegex(".*lora.*")))
131
+ return nnx.Nothing
132
+
133
+
134
+ class Pi0FAST(_model.BaseModel):
135
+ def __init__(self, config: Pi0FASTConfig, rngs: nnx.Rngs):
136
+ super().__init__(config.action_dim, config.action_horizon, config.max_token_len)
137
+ paligemma_config = _gemma.get_config(config.paligemma_variant)
138
+ # TODO: rewrite gemma in NNX. For now, use bridge.
139
+ llm = nnx_bridge.ToNNX(
140
+ _gemma.Module(
141
+ **paligemma_config,
142
+ embed_dtype=config.dtype,
143
+ cache_dtype=config.dtype,
144
+ )
145
+ )
146
+ llm.lazy_init(rngs=rngs, method="init")
147
+ img = nnx_bridge.ToNNX(
148
+ _siglip.Module(
149
+ num_classes=paligemma_config.width,
150
+ variant="So400m/14",
151
+ pool_type="none",
152
+ scan=True,
153
+ dtype_mm=config.dtype,
154
+ )
155
+ )
156
+ img.lazy_init(next(iter(config.fake_obs().images.values())), train=False, rngs=rngs)
157
+ self.PaliGemma = nnx.Dict(llm=llm, img=img)
158
+
159
+ @at.typecheck
160
+ def embed_inputs(
161
+ self, obs: _model.Observation
162
+ ) -> tuple[at.Float[at.Array, "b s emb"], at.Bool[at.Array, "b s"], at.Int[at.Array, "b s"]]:
163
+ input_mask = []
164
+ ar_mask = []
165
+ token_embeddings = []
166
+ # embed images
167
+ for name in obs.images:
168
+ image_token_embeddings, _ = self.PaliGemma.img(obs.images[name], train=False)
169
+
170
+ token_embeddings.append(image_token_embeddings)
171
+ input_mask.append(
172
+ einops.repeat(
173
+ obs.image_masks[name],
174
+ "b -> b s",
175
+ s=image_token_embeddings.shape[1],
176
+ )
177
+ )
178
+ # image tokens attend to each other --> AR mask = 0
179
+ ar_mask.append(0 * input_mask[-1])
180
+
181
+ # add tokenized inputs
182
+ assert obs.tokenized_prompt is not None, "Tokenized prompt is required"
183
+ assert obs.tokenized_prompt_mask is not None, "Tokenized prompt mask is required"
184
+ assert obs.token_ar_mask is not None, "Token auto-regressive mask is required"
185
+ tokenized_inputs_embeddings = self.PaliGemma.llm(obs.tokenized_prompt, embed_only=True)
186
+ token_embeddings.append(tokenized_inputs_embeddings)
187
+ input_mask.append(obs.tokenized_prompt_mask)
188
+ ar_mask.append(obs.token_ar_mask)
189
+
190
+ # return embeddings, input mask, and ar mask
191
+ return (
192
+ jnp.concatenate(token_embeddings, axis=1),
193
+ jnp.concatenate(input_mask, axis=1),
194
+ jnp.concatenate(ar_mask, axis=1),
195
+ )
196
+
197
+ @override
198
+ def compute_loss(
199
+ self, rng: at.KeyArrayLike, observation: _model.Observation, actions: _model.Actions, *, train: bool = False
200
+ ) -> at.Float[at.Array, "*b ah"]:
201
+ observation = _model.preprocess_observation(
202
+ rng, observation, train=train, image_keys=list(observation.images.keys())
203
+ )
204
+
205
+ # Compute inputs: one big forward pass of prefix + suffix at once
206
+ input_token_embeddings, input_mask, ar_mask = self.embed_inputs(observation)
207
+ attn_mask = make_attn_mask(input_mask, ar_mask)
208
+
209
+ # Compute one-hot targets: we predict *next* token, so shift the input tokens by one.
210
+ targets = jax.nn.one_hot(
211
+ observation.tokenized_prompt[:, 1:],
212
+ self.PaliGemma.llm.module.vocab_size,
213
+ )
214
+
215
+ # Each input predicts *next* token, so we don't input the last token.
216
+ pre_logits, _, _ = self.PaliGemma.llm(
217
+ embedded_prefix=input_token_embeddings[:, :-1],
218
+ mask=attn_mask[:, :-1, :-1],
219
+ return_prelogits=True,
220
+ )
221
+
222
+ # Only decode logits for the target tokens to save memory
223
+ # (decoding matmul is large because it is a seq_len x vocab_size dense layer).
224
+ logits, _ = self.PaliGemma.llm(
225
+ pre_logits=pre_logits[:, -targets.shape[1] :],
226
+ )
227
+ logp = jax.nn.log_softmax(logits, axis=-1)
228
+
229
+ # Compute CE loss on token targets
230
+ assert observation.token_loss_mask is not None, "Token loss mask is required"
231
+ loss_mask = observation.token_loss_mask[:, 1:]
232
+ token_pplx = jnp.sum(targets * logp, axis=-1)
233
+ return -jnp.sum(token_pplx * loss_mask, axis=-1) / jnp.clip(jnp.sum(loss_mask, -1), 1)
234
+
235
+ @override
236
+ def sample_actions(
237
+ self,
238
+ rng: at.KeyArrayLike,
239
+ observation: _model.Observation,
240
+ *,
241
+ max_decoding_steps: int | at.Int[at.Array, ""] = 256,
242
+ temperature: float = 0.0,
243
+ ) -> _model.Actions:
244
+ # TODO: this is a hack to get the image keys.
245
+ observation = _model.preprocess_observation(
246
+ None, observation, train=False, image_keys=list(observation.images.keys())
247
+ )
248
+
249
+ # embed inputs
250
+ prefix_token_embeddings, prefix_mask, prefix_ar_mask = self.embed_inputs(observation)
251
+ prefix_attn_mask = make_attn_mask(prefix_mask, prefix_ar_mask)
252
+
253
+ # left to right align all input token sequences
254
+ prefix_token_embeddings, prefix_mask, prefix_attn_mask = left_to_right_align(
255
+ prefix_token_embeddings, prefix_mask, prefix_attn_mask
256
+ )
257
+ prefill_size = prefix_token_embeddings.shape[1]
258
+ prefill_len = jnp.sum(prefix_mask, axis=-1)
259
+ prefix_start = prefill_size - prefill_len
260
+
261
+ # first fill KV cache with a forward pass of the prefix
262
+ # pad attention mask to set the size of the KV cache (prefill_size + max_decoding_steps)
263
+ prefix_attn_mask = jnp.pad(prefix_attn_mask, ((0, 0), (0, 0), (0, max_decoding_steps)))
264
+ prefix_positions = jnp.cumsum(prefix_mask, axis=-1) - 1
265
+ prefix_logits, kv_cache, _ = self.PaliGemma.llm(
266
+ embedded_prefix=prefix_token_embeddings, mask=prefix_attn_mask, positions=prefix_positions, decode=True
267
+ )
268
+
269
+ # prepare decoding -- final logit decodes the first token
270
+ last_logit = prefix_logits[:, -1:]
271
+ output_tokens = jnp.zeros((last_logit.shape[0], max_decoding_steps))
272
+
273
+ def step(carry):
274
+ rng, last_logit, output_tokens, cache, _, step = carry
275
+
276
+ # Sample token from last logit
277
+ # Split RNG for this step
278
+ rng, rng_step = jax.random.split(rng)
279
+ token = jax.lax.cond(
280
+ temperature > 0.0,
281
+ lambda _: jax.random.categorical(rng_step, last_logit / temperature, axis=-1),
282
+ lambda _: jnp.argmax(last_logit, axis=-1),
283
+ operand=None,
284
+ )
285
+ output_tokens = put_along_last_axis(output_tokens, jnp.broadcast_to(step, (token.shape[0], 1)), token)
286
+
287
+ # Check for early stopping --> stop if all batch elements have EOS token
288
+ has_eos = jnp.any(token == PALIGEMMA_EOS_TOKEN, axis=-1)
289
+ all_eos = jnp.all(has_eos)
290
+
291
+ # Decode one step
292
+ token_embedding = self.PaliGemma.llm(token, embed_only=True)
293
+ positions = prefill_len[:, None] + step + 1
294
+ mask = jnp.logical_and(
295
+ jnp.arange(prefill_size + max_decoding_steps)[None, None, :] >= prefix_start[:, None, None],
296
+ jnp.arange(prefill_size + max_decoding_steps)[None, None, :]
297
+ < (jnp.broadcast_to(prefill_size + step + 1, (prefix_start.shape[0], 1, 1))),
298
+ )
299
+ last_logit, kv_cache, _ = self.PaliGemma.llm(
300
+ embedded_prefix=token_embedding, mask=mask, positions=positions, decode=True, kv_cache=cache
301
+ )
302
+
303
+ return rng, last_logit, output_tokens, kv_cache, all_eos, step + 1
304
+
305
+ def cond(carry):
306
+ _, _, _, _, all_eos, step = carry
307
+ return (~all_eos) & (step < max_decoding_steps)
308
+
309
+ # Use lax.while_loop so we can jit the full decoding loop.
310
+ _, _, output_tokens, _, _, _ = jax.lax.while_loop(
311
+ cond, step, (rng, last_logit, output_tokens, kv_cache, False, 0)
312
+ )
313
+ return output_tokens
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/pi0_test.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import flax.nnx as nnx
2
+ import jax
3
+
4
+ import openpi.models.pi0_config as _pi0_config
5
+
6
+
7
+ def _get_frozen_state(config: _pi0_config.Pi0Config) -> nnx.State:
8
+ abstract_model = nnx.eval_shape(config.create, jax.random.key(0))
9
+
10
+ freeze_filter = config.get_freeze_filter()
11
+ return nnx.state(abstract_model, nnx.All(nnx.Param, freeze_filter)).flat_state()
12
+
13
+
14
+ def test_pi0_full_finetune():
15
+ config = _pi0_config.Pi0Config()
16
+ state = _get_frozen_state(config)
17
+ assert len(state) == 0
18
+
19
+
20
+ def test_pi0_gemma_lora():
21
+ config = _pi0_config.Pi0Config(paligemma_variant="gemma_2b_lora")
22
+ state = _get_frozen_state(config)
23
+ assert len(state) == 9
24
+ assert all("lora" not in p for p in state)
25
+ assert all("llm" in p for p in state)
26
+ assert all("_1" not in p for p in state)
27
+
28
+
29
+ def test_pi0_action_expert_lora():
30
+ config = _pi0_config.Pi0Config(action_expert_variant="gemma_300m_lora")
31
+ state = _get_frozen_state(config)
32
+ # excluding embedder, rest of the params should be same as gemma_lora.
33
+ assert len(state) == 8
34
+ assert all("lora" not in p for p in state)
35
+ assert all("llm" in p for p in state)
36
+ # all frozen params should have _1 in their path since it's the action expert.
37
+ assert all(any("_1" in p for p in path) for path in state)
38
+
39
+
40
+ def test_pi0_all_lora():
41
+ config = _pi0_config.Pi0Config(paligemma_variant="gemma_2b_lora", action_expert_variant="gemma_300m_lora")
42
+ state = _get_frozen_state(config)
43
+ # sum of gemma_lora and action_expert_lora's frozen params.
44
+ assert len(state) == 17
45
+ assert all("lora" not in p for p in state)
46
+ assert all("llm" in p for p in state)
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/siglip.py ADDED
@@ -0,0 +1,373 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Big Vision Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """A refactored and simplified ViT adoptation for Pi, taken from big_vision."""
16
+
17
+ from collections.abc import Sequence
18
+
19
+ import flax.linen as nn
20
+ import jax
21
+ import jax.numpy as jnp
22
+ import numpy as np
23
+
24
+ import openpi.training.sharding as sharding
25
+
26
+
27
+ def posemb_sincos_2d(h, w, width, temperature=10_000.0, dtype=jnp.float32):
28
+ """Follows the MoCo v3 logic."""
29
+ y, x = jnp.mgrid[:h, :w]
30
+
31
+ assert width % 4 == 0, "Width must be mult of 4 for sincos posemb"
32
+ omega = jnp.arange(width // 4) / (width // 4 - 1)
33
+ omega = 1.0 / (temperature**omega)
34
+ y = jnp.einsum("m,d->md", y.flatten(), omega)
35
+ x = jnp.einsum("m,d->md", x.flatten(), omega)
36
+ pe = jnp.concatenate([jnp.sin(x), jnp.cos(x), jnp.sin(y), jnp.cos(y)], axis=1)
37
+ return jnp.asarray(pe, dtype)[None, :, :]
38
+
39
+
40
+ def get_posemb(self, typ, seqshape, width, name, dtype=jnp.float32):
41
+ if typ == "learn":
42
+ return self.param(
43
+ name,
44
+ nn.initializers.normal(stddev=1 / np.sqrt(width)),
45
+ (1, np.prod(seqshape), width),
46
+ dtype,
47
+ )
48
+ if typ == "sincos2d":
49
+ return posemb_sincos_2d(*seqshape, width, dtype=dtype)
50
+ raise ValueError(f"Unknown posemb type: {typ}")
51
+
52
+
53
+ class MlpBlock(nn.Module):
54
+ """Transformer MLP / feed-forward block."""
55
+
56
+ mlp_dim: int | None = None # Defaults to 4x input dim
57
+ dropout: float = 0.0
58
+ dtype_mm: str = "float32"
59
+
60
+ @nn.compact
61
+ def __call__(self, x, deterministic=True): # noqa: FBT002
62
+ """Applies Transformer MlpBlock module."""
63
+ inits = {
64
+ "kernel_init": nn.initializers.xavier_uniform(),
65
+ "bias_init": nn.initializers.normal(stddev=1e-6),
66
+ }
67
+
68
+ _, _, d = x.shape # n,l,d
69
+ x = nn.Dense(self.mlp_dim or 4 * d, dtype=self.dtype_mm, **inits)(x)
70
+ x = nn.gelu(x)
71
+ x = nn.Dropout(rate=self.dropout)(x, deterministic)
72
+ return nn.Dense(d, dtype=self.dtype_mm, **inits)(x)
73
+
74
+
75
+ class Encoder1DBlock(nn.Module):
76
+ """Single transformer encoder block (MHSA + MLP)."""
77
+
78
+ mlp_dim: int | None = None # Defaults to 4x input dim
79
+ num_heads: int = 12
80
+ dropout: float = 0.0
81
+ dtype_mm: str = "float32"
82
+
83
+ @nn.compact
84
+ def __call__(self, x, deterministic=True): # noqa: FBT002
85
+ out = {}
86
+ x = sharding.activation_sharding_constraint(x)
87
+ y = nn.LayerNorm(dtype=self.dtype_mm)(x)
88
+ y = out["sa"] = nn.MultiHeadDotProductAttention(
89
+ num_heads=self.num_heads,
90
+ kernel_init=nn.initializers.xavier_uniform(),
91
+ deterministic=deterministic,
92
+ dtype=self.dtype_mm,
93
+ )(y, y)
94
+ y = sharding.activation_sharding_constraint(y)
95
+ y = nn.Dropout(rate=self.dropout)(y, deterministic)
96
+ x = out["+sa"] = x + y
97
+
98
+ y = nn.LayerNorm(dtype=self.dtype_mm)(x)
99
+ y = out["mlp"] = MlpBlock(
100
+ mlp_dim=self.mlp_dim,
101
+ dropout=self.dropout,
102
+ dtype_mm=self.dtype_mm,
103
+ )(y, deterministic)
104
+ y = sharding.activation_sharding_constraint(y)
105
+ y = nn.Dropout(rate=self.dropout)(y, deterministic)
106
+ x = out["+mlp"] = x + y
107
+ x = sharding.activation_sharding_constraint(x)
108
+ return x, out
109
+
110
+
111
+ class Encoder(nn.Module):
112
+ """Transformer Model Encoder for sequence to sequence translation."""
113
+
114
+ depth: int
115
+ mlp_dim: int | None = None # Defaults to 4x input dim
116
+ num_heads: int = 12
117
+ dropout: float = 0.0
118
+ scan: bool = False
119
+ remat_policy: str = "nothing_saveable"
120
+ dtype_mm: str = "float32"
121
+
122
+ @nn.compact
123
+ def __call__(self, x, deterministic=True): # noqa: FBT002
124
+ out = {}
125
+
126
+ if self.scan:
127
+ block = nn.remat(
128
+ Encoder1DBlock,
129
+ prevent_cse=False,
130
+ static_argnums=(2,), # 0=self, 2=deterministic
131
+ policy=getattr(jax.checkpoint_policies, self.remat_policy, None),
132
+ )
133
+ x, scan_out = nn.scan(
134
+ block,
135
+ variable_axes={"params": 0},
136
+ split_rngs={"params": True, "dropout": True},
137
+ in_axes=nn.broadcast,
138
+ length=self.depth,
139
+ )(
140
+ name="encoderblock",
141
+ dtype_mm=self.dtype_mm,
142
+ mlp_dim=self.mlp_dim,
143
+ num_heads=self.num_heads,
144
+ dropout=self.dropout,
145
+ )(x, deterministic)
146
+ for lyr in range(self.depth):
147
+ out[f"block{lyr:02d}"] = jax.tree.map(lambda o, lyr=lyr: o[lyr], scan_out)
148
+ else:
149
+ # Input Encoder
150
+ for lyr in range(self.depth):
151
+ block_cur = Encoder1DBlock(
152
+ name=f"encoderblock_{lyr}",
153
+ dtype_mm=self.dtype_mm,
154
+ mlp_dim=self.mlp_dim,
155
+ num_heads=self.num_heads,
156
+ dropout=self.dropout,
157
+ )
158
+ x, out[f"block{lyr:02d}"] = block_cur(x, deterministic)
159
+ out["pre_ln"] = x # Alias for last block, but without the number in it.
160
+
161
+ return nn.LayerNorm(name="encoder_norm", dtype=self.dtype_mm)(x), out
162
+
163
+
164
+ class MAPHead(nn.Module):
165
+ """Multihead Attention Pooling."""
166
+
167
+ mlp_dim: int | None = None # Defaults to 4x input dim
168
+ num_heads: int = 12
169
+ dtype_mm: str = "float32"
170
+
171
+ @nn.compact
172
+ def __call__(self, x):
173
+ n, _, d = x.shape # n,l,d
174
+ probe = self.param("probe", nn.initializers.xavier_uniform(), (1, 1, d), x.dtype)
175
+ probe = jnp.tile(probe, [n, 1, 1])
176
+
177
+ x = nn.MultiHeadDotProductAttention(
178
+ num_heads=self.num_heads,
179
+ dtype=self.dtype_mm,
180
+ kernel_init=nn.initializers.xavier_uniform(),
181
+ )(probe, x)
182
+
183
+ y = nn.LayerNorm(dtype=self.dtype_mm)(x)
184
+ x = x + MlpBlock(mlp_dim=self.mlp_dim, dtype=self.dtype_mm)(y)
185
+ return x[:, 0]
186
+
187
+
188
+ class _Module(nn.Module):
189
+ """ViT model."""
190
+
191
+ num_classes: int | None = None
192
+ patch_size: Sequence[int] = (16, 16)
193
+ width: int = 768
194
+ depth: int = 12
195
+ mlp_dim: int | None = None # Defaults to 4x input dim
196
+ num_heads: int = 12
197
+ posemb: str = "learn" # Can also be "sincos2d"
198
+ rep_size: int | bool = False
199
+ dropout: float = 0.0
200
+ pool_type: str = "gap" # Can also be "map" or "tok"
201
+ head_zeroinit: bool = True
202
+ scan: bool = False
203
+ # or "dots_with_no_batch_dims_saveable" for more speed (memory costly)
204
+ remat_policy: str = "nothing_saveable"
205
+ dtype_mm: str = "float32"
206
+
207
+ @nn.compact
208
+ def __call__(self, image, *, train=False):
209
+ out = {}
210
+
211
+ # Kevin edit: do patch extraction and posemb in float32,
212
+ # because I feel like it's a bit safer.
213
+ image = jnp.asarray(image, jnp.float32)
214
+
215
+ # Patch extraction
216
+ x = out["stem"] = nn.Conv(
217
+ self.width,
218
+ self.patch_size,
219
+ strides=self.patch_size,
220
+ padding="VALID",
221
+ name="embedding",
222
+ dtype=jnp.float32,
223
+ )(image)
224
+
225
+ n, h, w, c = x.shape
226
+ x = jnp.reshape(x, [n, h * w, c])
227
+
228
+ # Add posemb before adding extra token.
229
+ x = out["with_posemb"] = x + get_posemb(self, self.posemb, (h, w), c, "pos_embedding", jnp.float32)
230
+
231
+ if self.pool_type == "tok":
232
+ cls = self.param("cls", nn.initializers.zeros, (1, 1, c), x.dtype)
233
+ x = jnp.concatenate([jnp.tile(cls, [n, 1, 1]), x], axis=1)
234
+
235
+ n, _, c = x.shape # n,l,d
236
+ x = nn.Dropout(rate=self.dropout)(x, not train)
237
+
238
+ # Kevin edit: now cast back to dtype_mm (potentially half precision)
239
+ x = x.astype(self.dtype_mm)
240
+
241
+ x, out["encoder"] = Encoder(
242
+ depth=self.depth,
243
+ mlp_dim=self.mlp_dim,
244
+ num_heads=self.num_heads,
245
+ dropout=self.dropout,
246
+ scan=self.scan,
247
+ remat_policy=self.remat_policy,
248
+ dtype_mm=self.dtype_mm,
249
+ name="Transformer",
250
+ )(x, deterministic=not train)
251
+ encoded = out["encoded"] = x
252
+
253
+ if self.pool_type == "map":
254
+ x = out["head_input"] = MAPHead(
255
+ num_heads=self.num_heads,
256
+ mlp_dim=self.mlp_dim,
257
+ dtype=self.dtype_mm,
258
+ )(x)
259
+ elif self.pool_type == "gap":
260
+ x = out["head_input"] = jnp.mean(x, axis=1)
261
+ elif self.pool_type == "0":
262
+ x = out["head_input"] = x[:, 0]
263
+ elif self.pool_type == "tok":
264
+ x = out["head_input"] = x[:, 0]
265
+ encoded = encoded[:, 1:]
266
+ elif self.pool_type == "none":
267
+ pass
268
+ else:
269
+ raise ValueError(f"Unknown pool type: '{self.pool_type}'")
270
+
271
+ x_2d = jnp.reshape(encoded, [n, h, w, -1])
272
+
273
+ if self.rep_size:
274
+ rep_size = self.width if self.rep_size is True else self.rep_size
275
+ hid = nn.Dense(rep_size, dtype=self.dtype_mm, name="pre_logits")
276
+ # NOTE: In the past we did not include tanh in pre_logits.
277
+ # For few-shot, it should not matter much, as it whitens anyways.
278
+ x_2d = nn.tanh(hid(x_2d))
279
+ x = nn.tanh(hid(x))
280
+
281
+ out["pre_logits_2d"] = x_2d
282
+ out["pre_logits"] = x
283
+
284
+ if self.num_classes:
285
+ kw = {"kernel_init": nn.initializers.zeros} if self.head_zeroinit else {}
286
+ head = nn.Dense(self.num_classes, dtype=self.dtype_mm, name="head", **kw)
287
+ x_2d = out["logits_2d"] = head(x_2d)
288
+ x = out["logits"] = head(x)
289
+
290
+ return x, out
291
+
292
+
293
+ def Module(num_classes=None, *, variant=None, **kw): # pylint: disable=invalid-name # noqa: N802
294
+ """Factory function, because linen really don't like what I'm doing!"""
295
+ return _Module(num_classes, **{**decode_variant(variant), **kw})
296
+
297
+
298
+ def decode_variant(variant):
299
+ """Converts a string like "B" or "B/32" into a params dict."""
300
+ if variant is None:
301
+ return {}
302
+
303
+ v, patch = variant, {}
304
+ if "/" in variant:
305
+ v, patch = variant.split("/")
306
+ patch = {"patch_size": (int(patch), int(patch))}
307
+
308
+ return {
309
+ # pylint:disable=line-too-long
310
+ # Reference: Table 2 of https://arxiv.org/abs/2106.04560.
311
+ "width": {
312
+ "mu": 32,
313
+ "Ti": 192,
314
+ "S": 384,
315
+ "M": 512,
316
+ "B": 768,
317
+ "L": 1024,
318
+ "So400m": 1152,
319
+ "H": 1280,
320
+ "g": 1408,
321
+ "g-opt": 1536,
322
+ "G": 1664,
323
+ "G-opt": 1536,
324
+ "e": 1792,
325
+ }[v],
326
+ "depth": {
327
+ "mu": 1,
328
+ "Ti": 12,
329
+ "S": 12,
330
+ "M": 12,
331
+ "B": 12,
332
+ "L": 24,
333
+ "So400m": 27,
334
+ "H": 32,
335
+ "g": 40,
336
+ "g-opt": 40,
337
+ "G": 48,
338
+ "G-opt": 48,
339
+ "e": 56,
340
+ }[v],
341
+ "mlp_dim": {
342
+ "mu": 128,
343
+ "Ti": 768,
344
+ "S": 1536,
345
+ "M": 2048,
346
+ "B": 3072,
347
+ "L": 4096,
348
+ "So400m": 4304,
349
+ "H": 5120,
350
+ "g": 6144,
351
+ "g-opt": 6144,
352
+ "G": 8192,
353
+ "G-opt": 8192,
354
+ "e": 15360,
355
+ }[v],
356
+ "num_heads": {
357
+ "mu": 2,
358
+ "Ti": 3,
359
+ "S": 6,
360
+ "M": 8,
361
+ "B": 12,
362
+ "L": 16,
363
+ "So400m": 16,
364
+ "H": 16,
365
+ "g": 16,
366
+ "g-opt": 16,
367
+ "G": 16,
368
+ "G-opt": 16,
369
+ "e": 16,
370
+ }[v],
371
+ # pylint:enable=line-too-long
372
+ **patch,
373
+ }
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/tokenizer.py ADDED
@@ -0,0 +1,371 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+
4
+ import jax
5
+ import numpy as np
6
+ import orbax.checkpoint as ocp
7
+ import sentencepiece
8
+ from transformers import AutoProcessor
9
+
10
+ import openpi.models.utils.fsq_tokenizer as fsq_tokenizer
11
+ import openpi.shared.download as download
12
+
13
+
14
+ class PaligemmaTokenizer:
15
+ def __init__(self, max_len: int = 48):
16
+ self._max_len = max_len
17
+
18
+ path = download.maybe_download("gs://big_vision/paligemma_tokenizer.model", gs={"token": "anon"})
19
+ with path.open("rb") as f:
20
+ self._tokenizer = sentencepiece.SentencePieceProcessor(model_proto=f.read())
21
+
22
+ def tokenize(self, prompt: str, state: np.ndarray | None = None) -> tuple[np.ndarray, np.ndarray]:
23
+ cleaned_text = prompt.strip().replace("_", " ").replace("\n", " ")
24
+ if state is not None:
25
+ # This is the Pi05 format, where the state is part of the discrete language input.
26
+ discretized_state = np.digitize(state, bins=np.linspace(-1, 1, 256 + 1)[:-1]) - 1
27
+ state_str = " ".join(map(str, discretized_state))
28
+ full_prompt = f"Task: {cleaned_text}, State: {state_str};\nAction: "
29
+ tokens = self._tokenizer.encode(full_prompt, add_bos=True)
30
+ else:
31
+ # This is the Pi0 format, where the state is part of the continuous action expert input.
32
+ # tokenize "\n" separately as the "start of answer" token
33
+ tokens = self._tokenizer.encode(cleaned_text, add_bos=True) + self._tokenizer.encode("\n")
34
+ tokens_len = len(tokens)
35
+ if tokens_len < self._max_len:
36
+ padding = [False] * (self._max_len - tokens_len)
37
+ mask = [True] * tokens_len + padding
38
+ tokens = tokens + padding
39
+ else:
40
+ if len(tokens) > self._max_len:
41
+ logging.warning(
42
+ f"Token length ({len(tokens)}) exceeds max length ({self._max_len}), truncating. "
43
+ "Consider increasing the `max_token_len` in your model config if this happens frequently."
44
+ )
45
+ tokens = tokens[: self._max_len]
46
+ mask = [True] * self._max_len
47
+
48
+ return np.asarray(tokens), np.asarray(mask)
49
+
50
+
51
+ class FASTTokenizer:
52
+ def __init__(self, max_len: int = 256, fast_tokenizer_path: str = "physical-intelligence/fast"):
53
+ self._max_len = max_len
54
+
55
+ # Download base PaliGemma tokenizer
56
+ path = download.maybe_download("gs://big_vision/paligemma_tokenizer.model", gs={"token": "anon"})
57
+ with path.open("rb") as f:
58
+ self._paligemma_tokenizer = sentencepiece.SentencePieceProcessor(model_proto=f.read())
59
+
60
+ # Instantiate FAST tokenizer
61
+ self._fast_tokenizer = AutoProcessor.from_pretrained(fast_tokenizer_path, trust_remote_code=True)
62
+ self._fast_skip_tokens = 128 # Skip last 128 tokens in PaliGemma vocab since they are special tokens
63
+
64
+ def tokenize(
65
+ self, prompt: str, state: np.ndarray, actions: np.ndarray | None
66
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
67
+ cleaned_text = prompt.lower().strip().replace("_", " ")
68
+
69
+ # Convention: state gets discretized into 256 discrete bins (assumed range after normalization: [-1, 1])
70
+ discretized_state = np.digitize(state, bins=np.linspace(-1, 1, 256 + 1)[:-1]) - 1
71
+
72
+ # Convention: prefix includes prompt and string-representation of state, followed by ';'
73
+ state_str = " ".join(map(str, discretized_state))
74
+ prefix = f"Task: {cleaned_text}, State: {state_str};\n"
75
+ prefix_tokens = self._paligemma_tokenizer.encode(prefix, add_bos=True)
76
+
77
+ if actions is not None:
78
+ # Tokenize actions with FAST tokenizer --> map to last tokens in PaliGemma vocab
79
+ action_tokens = self._fast_tokenizer(actions[None])[0]
80
+ action_tokens_in_pg = self._act_tokens_to_paligemma_tokens(action_tokens)
81
+
82
+ # Convention: postfix contains 'Action:' followed by FAST tokens, followed by '|'
83
+ postfix_tokens = (
84
+ self._paligemma_tokenizer.encode("Action: ")
85
+ + action_tokens_in_pg.tolist()
86
+ + self._paligemma_tokenizer.encode("|", add_eos=True)
87
+ )
88
+ else:
89
+ postfix_tokens = []
90
+
91
+ # Create output token sequence & masks
92
+ # AR mask is 0 on prefix (bidirectional attention) and 1 on postfix (causal attention to all previous tokens)
93
+ tokens = prefix_tokens + postfix_tokens
94
+ token_mask = [True] * len(tokens)
95
+ ar_mask = [0] * len(prefix_tokens) + [1] * len(postfix_tokens)
96
+ loss_mask = [False] * len(prefix_tokens) + [True] * len(postfix_tokens) # Loss on postfix only
97
+
98
+ # Pad tokens to max length
99
+ tokens_len = len(tokens)
100
+ if tokens_len < self._max_len:
101
+ padding = [False] * (self._max_len - tokens_len)
102
+ tokens = tokens + padding
103
+ token_mask = token_mask + padding
104
+ ar_mask = ar_mask + padding
105
+ loss_mask = loss_mask + padding
106
+ else:
107
+ if len(tokens) > self._max_len:
108
+ logging.warning(
109
+ f"Token length ({len(tokens)}) exceeds max length ({self._max_len}), truncating. "
110
+ "Consider increasing the `max_token_len` in your model config if this happens frequently."
111
+ )
112
+ tokens = tokens[: self._max_len]
113
+ token_mask = token_mask[: self._max_len]
114
+ ar_mask = ar_mask[: self._max_len]
115
+ loss_mask = loss_mask[: self._max_len]
116
+
117
+ return np.asarray(tokens), np.asarray(token_mask), np.asarray(ar_mask), np.asarray(loss_mask)
118
+
119
+ def extract_actions(self, tokens: np.ndarray, action_horizon: int, action_dim: int) -> np.ndarray:
120
+ # Decode predicted output tokens
121
+ decoded_tokens = self._paligemma_tokenizer.decode(tokens.tolist())
122
+
123
+ # Extract actions from FAST model outputs
124
+ if "Action: " not in decoded_tokens:
125
+ return np.zeros((action_horizon, action_dim), dtype=np.float32)
126
+
127
+ # Extract actions from decoded tokens
128
+ raw_action_tokens = np.array(
129
+ self._paligemma_tokenizer.encode(decoded_tokens.split("Action: ")[1].split("|")[0].strip())
130
+ )
131
+ action_tokens = self._act_tokens_to_paligemma_tokens(raw_action_tokens)
132
+ return self._fast_tokenizer.decode(
133
+ [action_tokens.tolist()], time_horizon=action_horizon, action_dim=action_dim
134
+ )[0]
135
+
136
+ def _act_tokens_to_paligemma_tokens(self, tokens: np.ndarray | list[int]) -> np.ndarray:
137
+ if isinstance(tokens, list):
138
+ tokens = np.array(tokens)
139
+ return self._paligemma_tokenizer.vocab_size() - 1 - self._fast_skip_tokens - tokens
140
+
141
+
142
+ ###########################################################################
143
+ ## The tokenizers below are used for RoboArena baseline implementations. ##
144
+ ## They are *not* used for pi0-style models. ##
145
+ ###########################################################################
146
+
147
+
148
+ class BinningTokenizer:
149
+ """
150
+ Standard RT-2 / OpenVLA style binning tokenizer.
151
+ """
152
+
153
+ def __init__(self, max_len: int = 256, n_bins: int = 256):
154
+ self._max_len = max_len
155
+ self._n_bins = n_bins
156
+
157
+ # Download base PaliGemma tokenizer
158
+ path = download.maybe_download("gs://big_vision/paligemma_tokenizer.model", gs={"token": "anon"})
159
+ with path.open("rb") as f:
160
+ self._paligemma_tokenizer = sentencepiece.SentencePieceProcessor(model_proto=f.read())
161
+
162
+ self._fast_skip_tokens = 128 # Skip last 128 tokens in PaliGemma vocab since they are special tokens
163
+
164
+ def tokenize(
165
+ self, prompt: str, state: np.ndarray, actions: np.ndarray | None
166
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
167
+ """Tokenize a prompt and state into a sequence of tokens.
168
+
169
+ Args:
170
+ prompt: The text prompt to tokenize.
171
+ state: The state array to discretize and tokenize.
172
+ actions: Must be None. Action encoding is not currently supported.
173
+
174
+ Returns:
175
+ A tuple of (tokens, token_mask, ar_mask, targets).
176
+
177
+ Raises:
178
+ NotImplementedError: If actions is not None.
179
+ """
180
+ cleaned_text = prompt.lower().strip().replace("_", " ")
181
+
182
+ # Convention: state gets discretized into 256 discrete bins (assumed range after normalization: [-1, 1])
183
+ discretized_state = np.digitize(state, bins=np.linspace(-1, 1, 256 + 1)[:-1]) - 1
184
+
185
+ # Convention: prefix includes prompt and string-representation of state, followed by ';'
186
+ state_str = " ".join(map(str, discretized_state))
187
+ prefix = f"Task: {cleaned_text}, State: {state_str};\n"
188
+ prefix_tokens = self._paligemma_tokenizer.encode(prefix, add_bos=True)
189
+
190
+ if actions is not None:
191
+ raise NotImplementedError("BinningTokenizer does not support encoding actions atm (only for inference use)")
192
+ postfix_tokens = []
193
+
194
+ # Create output token sequence & masks
195
+ # AR mask is 0 on prefix (bidirectional attention) and 1 on postfix (causal attention to all previous tokens)
196
+ tokens = prefix_tokens + postfix_tokens
197
+ token_mask = [True] * len(tokens)
198
+ ar_mask = [0] * len(prefix_tokens) + [1] * len(postfix_tokens)
199
+ loss_mask = [False] * len(prefix_tokens) + [True] * len(postfix_tokens) # Loss on postfix only
200
+
201
+ # Pad tokens to max length
202
+ tokens_len = len(tokens)
203
+ if tokens_len < self._max_len:
204
+ padding = [False] * (self._max_len - tokens_len)
205
+ tokens = tokens + padding
206
+ token_mask = token_mask + padding
207
+ ar_mask = ar_mask + padding
208
+ loss_mask = loss_mask + padding
209
+ else:
210
+ if len(tokens) > self._max_len:
211
+ logging.warning(
212
+ f"Token length ({len(tokens)}) exceeds max length ({self._max_len}), truncating. "
213
+ "Consider increasing the `max_token_len` in your model config if this happens frequently."
214
+ )
215
+ tokens = tokens[: self._max_len]
216
+ token_mask = token_mask[: self._max_len]
217
+ ar_mask = ar_mask[: self._max_len]
218
+ loss_mask = loss_mask[: self._max_len]
219
+
220
+ return np.asarray(tokens), np.asarray(token_mask), np.asarray(ar_mask), np.asarray(loss_mask)
221
+
222
+ def extract_actions(self, tokens: np.ndarray, action_horizon: int, action_dim: int) -> np.ndarray:
223
+ # Decode predicted output tokens
224
+ decoded_tokens = self._paligemma_tokenizer.decode(tokens.tolist())
225
+
226
+ # Extract actions from FAST model outputs
227
+ if "Action: " not in decoded_tokens:
228
+ return np.zeros((action_horizon, action_dim), dtype=np.float32)
229
+
230
+ # Extract actions from decoded tokens
231
+ raw_action_tokens = np.array(
232
+ self._paligemma_tokenizer.encode(decoded_tokens.split("Action: ")[1].split("|")[0].strip())
233
+ )
234
+ action_tokens = self._act_tokens_to_paligemma_tokens(raw_action_tokens)
235
+ if len(action_tokens) < action_horizon * action_dim:
236
+ return np.zeros([action_horizon, action_dim], dtype=np.float32)
237
+ action_tokens = action_tokens[: (action_horizon * action_dim)].reshape([action_horizon, action_dim])
238
+ return action_tokens / self._n_bins * 2 - 1
239
+
240
+ def _act_tokens_to_paligemma_tokens(self, tokens: np.ndarray | list[int]) -> np.ndarray:
241
+ if isinstance(tokens, list):
242
+ tokens = np.array(tokens)
243
+ return self._paligemma_tokenizer.vocab_size() - 1 - self._fast_skip_tokens - tokens
244
+
245
+
246
+ class FSQTokenizer:
247
+ """
248
+ FSQ tokenizer from the FAST paper baselines.
249
+ """
250
+
251
+ def __init__(self, max_len: int = 256, fsq_tokenizer_path: str | None = None):
252
+ self._max_len = max_len
253
+
254
+ assert fsq_tokenizer_path is not None, "fsq_tokenizer_path must be provided"
255
+ # Download tokenizer
256
+ path = download.maybe_download(fsq_tokenizer_path)
257
+ tok_path = os.path.join(path, os.listdir(path)[0])
258
+
259
+ # Split step from path
260
+ step = int(tok_path.split("/")[-1])
261
+ base_path = tok_path.rsplit("/", 1)[0]
262
+
263
+ mgr = ocp.CheckpointManager(
264
+ base_path,
265
+ item_handlers={
266
+ "params": ocp.StandardCheckpointHandler(),
267
+ "opt_state": ocp.StandardCheckpointHandler(),
268
+ "config": ocp.JsonCheckpointHandler(),
269
+ },
270
+ options=ocp.CheckpointManagerOptions(max_to_keep=1),
271
+ )
272
+
273
+ try:
274
+ restored = mgr.restore(
275
+ step, args=ocp.args.Composite(config=ocp.args.JsonRestore(), params=ocp.args.StandardRestore())
276
+ )
277
+ config = restored["config"]
278
+ self._params = restored["params"]
279
+ self._fsq_tokenizer = fsq_tokenizer.FsqAttentionTokenizer(**config)
280
+ except Exception as e:
281
+ raise RuntimeError(
282
+ f"Failed to load FSQ tokenizer checkpoint from {fsq_tokenizer_path}. Error: {e!s}"
283
+ ) from e
284
+
285
+ # Compile tokenize and detokenize functions
286
+ self._tokenize_fn = jax.jit(
287
+ lambda params, x: self._fsq_tokenizer.apply({"params": params}, x, method=self._fsq_tokenizer.tokenize)
288
+ )
289
+ self._detokenize_fn = jax.jit(
290
+ lambda params, x: self._fsq_tokenizer.apply({"params": params}, x, method=self._fsq_tokenizer.detokenize)
291
+ )
292
+
293
+ # Download base PaliGemma tokenizer
294
+ path = download.maybe_download("gs://big_vision/paligemma_tokenizer.model", gs={"token": "anon"})
295
+ with path.open("rb") as f:
296
+ self._paligemma_tokenizer = sentencepiece.SentencePieceProcessor(model_proto=f.read())
297
+
298
+ self._fast_skip_tokens = 128 # Skip last 128 tokens in PaliGemma vocab since they are special tokens
299
+
300
+ def tokenize(
301
+ self, prompt: str, state: np.ndarray, actions: np.ndarray | None
302
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
303
+ cleaned_text = prompt.lower().strip().replace("_", " ")
304
+
305
+ # Convention: state gets discretized into 256 discrete bins (assumed range after normalization: [-1, 1])
306
+ discretized_state = np.digitize(state, bins=np.linspace(-1, 1, 256 + 1)[:-1]) - 1
307
+
308
+ # Convention: prefix includes prompt and string-representation of state, followed by ';'
309
+ state_str = " ".join(map(str, discretized_state))
310
+ prefix = f"Task: {cleaned_text}, State: {state_str};\n"
311
+ prefix_tokens = self._paligemma_tokenizer.encode(prefix, add_bos=True)
312
+
313
+ if actions is not None:
314
+ raise NotImplementedError("FSQTokenizer does not support encoding actions atm (only for inference use)")
315
+ postfix_tokens = []
316
+
317
+ # Create output token sequence & masks
318
+ # AR mask is 0 on prefix (bidirectional attention) and 1 on postfix (causal attention to all previous tokens)
319
+ tokens = prefix_tokens + postfix_tokens
320
+ token_mask = [True] * len(tokens)
321
+ ar_mask = [0] * len(prefix_tokens) + [1] * len(postfix_tokens)
322
+ loss_mask = [False] * len(prefix_tokens) + [True] * len(postfix_tokens) # Loss on postfix only
323
+
324
+ # Pad tokens to max length
325
+ tokens_len = len(tokens)
326
+ if tokens_len < self._max_len:
327
+ padding = [False] * (self._max_len - tokens_len)
328
+ tokens = tokens + padding
329
+ token_mask = token_mask + padding
330
+ ar_mask = ar_mask + padding
331
+ loss_mask = loss_mask + padding
332
+ else:
333
+ if len(tokens) > self._max_len:
334
+ logging.warning(
335
+ f"Token length ({len(tokens)}) exceeds max length ({self._max_len}), truncating. "
336
+ "Consider increasing the `max_token_len` in your model config if this happens frequently."
337
+ )
338
+ tokens = tokens[: self._max_len]
339
+ token_mask = token_mask[: self._max_len]
340
+ ar_mask = ar_mask[: self._max_len]
341
+ loss_mask = loss_mask[: self._max_len]
342
+
343
+ return np.asarray(tokens), np.asarray(token_mask), np.asarray(ar_mask), np.asarray(loss_mask)
344
+
345
+ def extract_actions(self, tokens: np.ndarray, action_horizon: int, action_dim: int) -> np.ndarray:
346
+ # Decode predicted output tokens
347
+ decoded_tokens = self._paligemma_tokenizer.decode(tokens.tolist())
348
+
349
+ # Extract actions from FAST model outputs
350
+ if "Action: " not in decoded_tokens:
351
+ return np.zeros((action_horizon, action_dim), dtype=np.float32)
352
+
353
+ # Extract actions from decoded tokens
354
+ raw_action_tokens = np.array(
355
+ self._paligemma_tokenizer.encode(decoded_tokens.split("Action: ")[1].split("|")[0].strip())
356
+ )
357
+ action_tokens = self._act_tokens_to_paligemma_tokens(raw_action_tokens)
358
+ try:
359
+ # Move computation to CPU and compile on-demand
360
+ device = jax.devices("cpu")[0]
361
+ with jax.default_device(device):
362
+ detok_act = self._detokenize_fn(self._params, action_tokens[None, ...])[0]
363
+ return detok_act[: action_horizon * action_dim].reshape([action_horizon, action_dim])
364
+ except Exception as e:
365
+ logging.warning(f"Error decoding FSQ: {e}")
366
+ return np.zeros((action_horizon, action_dim))
367
+
368
+ def _act_tokens_to_paligemma_tokens(self, tokens: np.ndarray | list[int]) -> np.ndarray:
369
+ if isinstance(tokens, list):
370
+ tokens = np.array(tokens)
371
+ return self._paligemma_tokenizer.vocab_size() - 1 - self._fast_skip_tokens - tokens
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/tokenizer_test.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from openpi.models import tokenizer as _tokenizer
4
+
5
+
6
+ def test_tokenize():
7
+ tokenizer = _tokenizer.PaligemmaTokenizer(max_len=10)
8
+ tokens, masks = tokenizer.tokenize("Hello, world!")
9
+
10
+ assert tokens.shape == (10,)
11
+ assert masks.shape == (10,)
12
+
13
+
14
+ def test_fast_tokenizer():
15
+ prompt = "Hello, world!"
16
+ state = np.random.rand(5).astype(np.float32)
17
+ action = np.random.rand(3, 2).astype(np.float32)
18
+ tokenizer = _tokenizer.FASTTokenizer(max_len=256)
19
+ tokens, token_masks, ar_masks, loss_masks = tokenizer.tokenize(prompt, state, action)
20
+
21
+ assert tokens.shape == (256,)
22
+ assert token_masks.shape == (256,)
23
+ assert ar_masks.shape == (256,)
24
+ assert loss_masks.shape == (256,)
25
+
26
+ act = tokenizer.extract_actions(tokens, 3, 2)
27
+ assert act.shape == (3, 2)
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/vit.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """ViT implementation adapted from https://github.com/google-research/vision_transformer/blob/main/vit_jax/models_vit.py."""
15
+
16
+ from collections.abc import Callable
17
+ from typing import Any
18
+
19
+ import flax.linen as nn
20
+ import jax
21
+ import jax.numpy as jnp
22
+
23
+ from openpi.models import resnet as models_resnet
24
+
25
+ Array = Any
26
+ PRNGKey = Any
27
+ Shape = tuple[int]
28
+ Dtype = Any
29
+
30
+
31
+ class IdentityLayer(nn.Module):
32
+ """Identity layer, convenient for giving a name to an array."""
33
+
34
+ @nn.compact
35
+ def __call__(self, x):
36
+ return x
37
+
38
+
39
+ class AddPositionEmbs(nn.Module):
40
+ """Adds learned positional embeddings to the inputs.
41
+
42
+ Attributes:
43
+ posemb_init: positional embedding initializer.
44
+ """
45
+
46
+ posemb_init: Callable[[PRNGKey, Shape, Dtype], Array]
47
+ param_dtype: Dtype = jnp.float32
48
+
49
+ @nn.compact
50
+ def __call__(self, inputs):
51
+ """Applies the AddPositionEmbs module.
52
+
53
+ Args:
54
+ inputs: Inputs to the layer.
55
+
56
+ Returns:
57
+ Output tensor with shape `(bs, timesteps, in_dim)`.
58
+ """
59
+ # inputs.shape is (batch_size, seq_len, emb_dim).
60
+ assert inputs.ndim == 3, f"Number of dimensions should be 3, but it is: {inputs.ndim}"
61
+ pos_emb_shape = (1, inputs.shape[1], inputs.shape[2])
62
+ pe = self.param("pos_embedding", self.posemb_init, pos_emb_shape, self.param_dtype)
63
+ return inputs + pe
64
+
65
+
66
+ class MlpBlock(nn.Module):
67
+ """Transformer MLP / feed-forward block."""
68
+
69
+ mlp_dim: int
70
+ dtype: Dtype = jnp.float32
71
+ param_dtype: Dtype = jnp.float32
72
+ out_dim: int | None = None
73
+ dropout_rate: float = 0.1
74
+ kernel_init: Callable[[PRNGKey, Shape, Dtype], Array] = nn.initializers.xavier_uniform()
75
+ bias_init: Callable[[PRNGKey, Shape, Dtype], Array] = nn.initializers.normal(stddev=1e-6)
76
+
77
+ @nn.compact
78
+ def __call__(self, inputs, *, deterministic):
79
+ """Applies Transformer MlpBlock module."""
80
+ actual_out_dim = inputs.shape[-1] if self.out_dim is None else self.out_dim
81
+ x = nn.Dense(
82
+ features=self.mlp_dim,
83
+ dtype=self.dtype,
84
+ param_dtype=self.param_dtype,
85
+ kernel_init=self.kernel_init,
86
+ bias_init=self.bias_init,
87
+ )( # pytype: disable=wrong-arg-types
88
+ inputs
89
+ )
90
+ x = nn.gelu(x)
91
+ x = nn.Dropout(rate=self.dropout_rate)(x, deterministic=deterministic)
92
+ output = nn.Dense(
93
+ features=actual_out_dim,
94
+ dtype=self.dtype,
95
+ param_dtype=self.param_dtype,
96
+ kernel_init=self.kernel_init,
97
+ bias_init=self.bias_init,
98
+ )( # pytype: disable=wrong-arg-types
99
+ x
100
+ )
101
+ return nn.Dropout(rate=self.dropout_rate)(output, deterministic=deterministic)
102
+
103
+
104
+ class Encoder1DBlock(nn.Module):
105
+ """Transformer encoder layer.
106
+
107
+ Attributes:
108
+ inputs: input data.
109
+ mlp_dim: dimension of the mlp on top of attention block.
110
+ dtype: the dtype of the computation (default: float32).
111
+ dropout_rate: dropout rate.
112
+ attention_dropout_rate: dropout for attention heads.
113
+ deterministic: bool, deterministic or not (to apply dropout).
114
+ num_heads: Number of heads in nn.MultiHeadDotProductAttention
115
+ """
116
+
117
+ mlp_dim: int
118
+ num_heads: int
119
+ dtype: Dtype = jnp.float32
120
+ dropout_rate: float = 0.1
121
+ attention_dropout_rate: float = 0.1
122
+
123
+ @nn.compact
124
+ def __call__(self, inputs, deterministic):
125
+ """Applies Encoder1DBlock module.
126
+
127
+ Args:
128
+ inputs: Inputs to the layer.
129
+ deterministic: Dropout will not be applied when set to true.
130
+
131
+ Returns:
132
+ output after transformer encoder block.
133
+ """
134
+
135
+ # Attention block.
136
+ assert inputs.ndim == 3, f"Expected (batch, seq, hidden) got {inputs.shape}"
137
+ x = nn.LayerNorm(dtype=self.dtype)(inputs)
138
+ x = nn.MultiHeadDotProductAttention(
139
+ dtype=self.dtype,
140
+ kernel_init=nn.initializers.xavier_uniform(),
141
+ broadcast_dropout=False,
142
+ deterministic=deterministic,
143
+ dropout_rate=self.attention_dropout_rate,
144
+ num_heads=self.num_heads,
145
+ # why isn't this true by default???
146
+ force_fp32_for_softmax=True,
147
+ )(x, x)
148
+ x = nn.Dropout(rate=self.dropout_rate)(x, deterministic=deterministic)
149
+ x = x + inputs
150
+
151
+ # MLP block.
152
+ y = nn.LayerNorm(dtype=self.dtype)(x)
153
+ y = MlpBlock(mlp_dim=self.mlp_dim, dtype=self.dtype, dropout_rate=self.dropout_rate)(
154
+ y, deterministic=deterministic
155
+ )
156
+
157
+ return x + y, None
158
+
159
+
160
+ class Encoder(nn.Module):
161
+ """Transformer Model Encoder for sequence to sequence translation.
162
+
163
+ Attributes:
164
+ num_layers: number of layers
165
+ mlp_dim: dimension of the mlp on top of attention block
166
+ num_heads: Number of heads in nn.MultiHeadDotProductAttention
167
+ dropout_rate: dropout rate.
168
+ attention_dropout_rate: dropout rate in self attention.
169
+ """
170
+
171
+ dtype: jax.typing.DTypeLike
172
+ num_layers: int
173
+ mlp_dim: int
174
+ num_heads: int
175
+ dropout_rate: float = 0.1
176
+ attention_dropout_rate: float = 0.1
177
+ add_position_embedding: bool = True
178
+
179
+ @nn.compact
180
+ def __call__(self, x, *, train):
181
+ """Applies Transformer model on the inputs.
182
+
183
+ Args:
184
+ x: Inputs to the layer.
185
+ train: Set to `True` when training.
186
+
187
+ Returns:
188
+ output of a transformer encoder.
189
+ """
190
+ assert x.ndim == 3 # (batch, len, emb)
191
+
192
+ if self.add_position_embedding:
193
+ x = AddPositionEmbs(
194
+ posemb_init=nn.initializers.normal(stddev=0.02), # from BERT.
195
+ name="posembed_input",
196
+ )(x)
197
+ x = nn.Dropout(rate=self.dropout_rate)(x, deterministic=not train)
198
+
199
+ x = x.astype(self.dtype)
200
+ # Input Encoder
201
+ block = nn.remat(Encoder1DBlock, prevent_cse=False, static_argnums=(2,))
202
+ x, _ = nn.scan(
203
+ block,
204
+ variable_axes={"params": 0},
205
+ split_rngs={"params": True, "dropout": True},
206
+ in_axes=nn.broadcast,
207
+ length=self.num_layers,
208
+ )(
209
+ name="encoderblock",
210
+ mlp_dim=self.mlp_dim,
211
+ dropout_rate=self.dropout_rate,
212
+ attention_dropout_rate=self.attention_dropout_rate,
213
+ dtype=self.dtype,
214
+ num_heads=self.num_heads,
215
+ )(x, not train)
216
+ return nn.LayerNorm(name="encoder_norm", dtype=self.dtype)(x)
217
+
218
+
219
+ class VisionTransformer(nn.Module):
220
+ """VisionTransformer."""
221
+
222
+ dtype: jax.typing.DTypeLike
223
+ num_classes: int
224
+ patches: Any
225
+ transformer: Any
226
+ hidden_size: int
227
+ resnet: Any | None = None
228
+ representation_size: int | None = None
229
+ classifier: str = "token"
230
+ head_bias_init: float = 0.0
231
+ encoder: type[nn.Module] = Encoder
232
+ model_name: str | None = None
233
+
234
+ @nn.compact
235
+ def __call__(self, inputs, *, train):
236
+ x = inputs
237
+ # (Possibly partial) ResNet root.
238
+ if self.resnet is not None:
239
+ width = int(64 * self.resnet.width_factor)
240
+
241
+ # Root block.
242
+ x = models_resnet.StdConv(
243
+ features=width, kernel_size=(7, 7), strides=(2, 2), use_bias=False, name="conv_root"
244
+ )(x)
245
+ x = nn.GroupNorm(name="gn_root")(x)
246
+ x = nn.relu(x)
247
+ x = nn.max_pool(x, window_shape=(3, 3), strides=(2, 2), padding="SAME")
248
+
249
+ # ResNet stages.
250
+ if self.resnet.num_layers:
251
+ x = models_resnet.ResNetStage(
252
+ block_size=self.resnet.num_layers[0], nout=width, first_stride=(1, 1), name="block1"
253
+ )(x)
254
+ for i, block_size in enumerate(self.resnet.num_layers[1:], 1):
255
+ x = models_resnet.ResNetStage(
256
+ block_size=block_size, nout=width * 2**i, first_stride=(2, 2), name=f"block{i + 1}"
257
+ )(x)
258
+
259
+ n, h, w, c = x.shape
260
+
261
+ # We can merge s2d+emb into a single conv; it's the same.
262
+ x = nn.Conv(
263
+ features=self.hidden_size,
264
+ kernel_size=self.patches.size,
265
+ strides=self.patches.size,
266
+ padding="VALID",
267
+ name="embedding",
268
+ )(x)
269
+
270
+ # Here, x is a grid of embeddings.
271
+
272
+ # (Possibly partial) Transformer.
273
+ if self.transformer is not None:
274
+ n, h, w, c = x.shape
275
+ x = jnp.reshape(x, [n, h * w, c])
276
+
277
+ # If we want to add a class token, add it here.
278
+ if self.classifier in ["token", "token_unpooled"]:
279
+ cls = self.param("cls", nn.initializers.zeros, (1, 1, c))
280
+ cls = jnp.tile(cls, [n, 1, 1])
281
+ x = jnp.concatenate([cls, x], axis=1)
282
+
283
+ x = self.encoder(name="Transformer", **self.transformer, dtype=self.dtype)(x, train=train)
284
+
285
+ if self.classifier == "token":
286
+ x = x[:, 0]
287
+ elif self.classifier == "gap":
288
+ x = jnp.mean(x, axis=list(range(1, x.ndim - 1))) # (1,) or (1,2)
289
+ elif self.classifier in ["unpooled", "token_unpooled"]:
290
+ pass
291
+ else:
292
+ raise ValueError(f"Invalid classifier={self.classifier}")
293
+
294
+ if self.representation_size is not None:
295
+ x = nn.Dense(features=self.representation_size, name="pre_logits")(x)
296
+ x = nn.tanh(x)
297
+ else:
298
+ x = IdentityLayer(name="pre_logits")(x)
299
+
300
+ if self.num_classes:
301
+ x = nn.Dense(
302
+ features=self.num_classes,
303
+ name="head",
304
+ kernel_init=nn.initializers.zeros,
305
+ bias_init=nn.initializers.constant(self.head_bias_init),
306
+ )(x)
307
+ return x
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models_pytorch/preprocessing_pytorch.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Sequence
2
+ import logging
3
+
4
+ import torch
5
+
6
+ from openpi.shared import image_tools
7
+
8
+ logger = logging.getLogger("openpi")
9
+
10
+ # Constants moved from model.py
11
+ IMAGE_KEYS = (
12
+ "base_0_rgb",
13
+ "left_wrist_0_rgb",
14
+ "right_wrist_0_rgb",
15
+ )
16
+
17
+ IMAGE_RESOLUTION = (224, 224)
18
+
19
+
20
+ def preprocess_observation_pytorch(
21
+ observation,
22
+ *,
23
+ train: bool = False,
24
+ image_keys: Sequence[str] = IMAGE_KEYS,
25
+ image_resolution: tuple[int, int] = IMAGE_RESOLUTION,
26
+ ):
27
+ """Torch.compile-compatible version of preprocess_observation_pytorch with simplified type annotations.
28
+
29
+ This function avoids complex type annotations that can cause torch.compile issues.
30
+ """
31
+ if not set(image_keys).issubset(observation.images):
32
+ raise ValueError(f"images dict missing keys: expected {image_keys}, got {list(observation.images)}")
33
+
34
+ batch_shape = observation.state.shape[:-1]
35
+
36
+ out_images = {}
37
+ for key in image_keys:
38
+ image = observation.images[key]
39
+
40
+ # TODO: This is a hack to handle both [B, C, H, W] and [B, H, W, C] formats
41
+ # Handle both [B, C, H, W] and [B, H, W, C] formats
42
+ is_channels_first = image.shape[1] == 3 # Check if channels are in dimension 1
43
+
44
+ if is_channels_first:
45
+ # Convert [B, C, H, W] to [B, H, W, C] for processing
46
+ image = image.permute(0, 2, 3, 1)
47
+
48
+ if image.shape[1:3] != image_resolution:
49
+ logger.info(f"Resizing image {key} from {image.shape[1:3]} to {image_resolution}")
50
+ image = image_tools.resize_with_pad_torch(image, *image_resolution)
51
+
52
+ if train:
53
+ # Convert from [-1, 1] to [0, 1] for PyTorch augmentations
54
+ image = image / 2.0 + 0.5
55
+
56
+ # Apply PyTorch-based augmentations
57
+ if "wrist" not in key:
58
+ # Geometric augmentations for non-wrist cameras
59
+ height, width = image.shape[1:3]
60
+
61
+ # Random crop and resize
62
+ crop_height = int(height * 0.95)
63
+ crop_width = int(width * 0.95)
64
+
65
+ # Random crop
66
+ max_h = height - crop_height
67
+ max_w = width - crop_width
68
+ if max_h > 0 and max_w > 0:
69
+ # Use tensor operations instead of .item() for torch.compile compatibility
70
+ start_h = torch.randint(0, max_h + 1, (1,), device=image.device)
71
+ start_w = torch.randint(0, max_w + 1, (1,), device=image.device)
72
+ image = image[:, start_h : start_h + crop_height, start_w : start_w + crop_width, :]
73
+
74
+ # Resize back to original size
75
+ image = torch.nn.functional.interpolate(
76
+ image.permute(0, 3, 1, 2), # [b, h, w, c] -> [b, c, h, w]
77
+ size=(height, width),
78
+ mode="bilinear",
79
+ align_corners=False,
80
+ ).permute(0, 2, 3, 1) # [b, c, h, w] -> [b, h, w, c]
81
+
82
+ # Random rotation (small angles)
83
+ # Use tensor operations instead of .item() for torch.compile compatibility
84
+ angle = torch.rand(1, device=image.device) * 10 - 5 # Random angle between -5 and 5 degrees
85
+ if torch.abs(angle) > 0.1: # Only rotate if angle is significant
86
+ # Convert to radians
87
+ angle_rad = angle * torch.pi / 180.0
88
+
89
+ # Create rotation matrix
90
+ cos_a = torch.cos(angle_rad)
91
+ sin_a = torch.sin(angle_rad)
92
+
93
+ # Apply rotation using grid_sample
94
+ grid_x = torch.linspace(-1, 1, width, device=image.device)
95
+ grid_y = torch.linspace(-1, 1, height, device=image.device)
96
+
97
+ # Create meshgrid
98
+ grid_y, grid_x = torch.meshgrid(grid_y, grid_x, indexing="ij")
99
+
100
+ # Expand to batch dimension
101
+ grid_x = grid_x.unsqueeze(0).expand(image.shape[0], -1, -1)
102
+ grid_y = grid_y.unsqueeze(0).expand(image.shape[0], -1, -1)
103
+
104
+ # Apply rotation transformation
105
+ grid_x_rot = grid_x * cos_a - grid_y * sin_a
106
+ grid_y_rot = grid_x * sin_a + grid_y * cos_a
107
+
108
+ # Stack and reshape for grid_sample
109
+ grid = torch.stack([grid_x_rot, grid_y_rot], dim=-1)
110
+
111
+ image = torch.nn.functional.grid_sample(
112
+ image.permute(0, 3, 1, 2), # [b, h, w, c] -> [b, c, h, w]
113
+ grid,
114
+ mode="bilinear",
115
+ padding_mode="zeros",
116
+ align_corners=False,
117
+ ).permute(0, 2, 3, 1) # [b, c, h, w] -> [b, h, w, c]
118
+
119
+ # Color augmentations for all cameras
120
+ # Random brightness
121
+ # Use tensor operations instead of .item() for torch.compile compatibility
122
+ brightness_factor = 0.7 + torch.rand(1, device=image.device) * 0.6 # Random factor between 0.7 and 1.3
123
+ image = image * brightness_factor
124
+
125
+ # Random contrast
126
+ # Use tensor operations instead of .item() for torch.compile compatibility
127
+ contrast_factor = 0.6 + torch.rand(1, device=image.device) * 0.8 # Random factor between 0.6 and 1.4
128
+ mean = image.mean(dim=[1, 2, 3], keepdim=True)
129
+ image = (image - mean) * contrast_factor + mean
130
+
131
+ # Random saturation (convert to HSV, modify S, convert back)
132
+ # For simplicity, we'll just apply a random scaling to the color channels
133
+ # Use tensor operations instead of .item() for torch.compile compatibility
134
+ saturation_factor = 0.5 + torch.rand(1, device=image.device) * 1.0 # Random factor between 0.5 and 1.5
135
+ gray = image.mean(dim=-1, keepdim=True)
136
+ image = gray + (image - gray) * saturation_factor
137
+
138
+ # Clamp values to [0, 1]
139
+ image = torch.clamp(image, 0, 1)
140
+
141
+ # Back to [-1, 1]
142
+ image = image * 2.0 - 1.0
143
+
144
+ # Convert back to [B, C, H, W] format if it was originally channels-first
145
+ if is_channels_first:
146
+ image = image.permute(0, 3, 1, 2) # [B, H, W, C] -> [B, C, H, W]
147
+
148
+ out_images[key] = image
149
+
150
+ # obtain mask
151
+ out_masks = {}
152
+ for key in out_images:
153
+ if key not in observation.image_masks:
154
+ # do not mask by default
155
+ out_masks[key] = torch.ones(batch_shape, dtype=torch.bool, device=observation.state.device)
156
+ else:
157
+ out_masks[key] = observation.image_masks[key]
158
+
159
+ # Create a simple object with the required attributes instead of using the complex Observation class
160
+ class SimpleProcessedObservation:
161
+ def __init__(self, **kwargs):
162
+ for key, value in kwargs.items():
163
+ setattr(self, key, value)
164
+
165
+ return SimpleProcessedObservation(
166
+ images=out_images,
167
+ image_masks=out_masks,
168
+ state=observation.state,
169
+ tokenized_prompt=observation.tokenized_prompt,
170
+ tokenized_prompt_mask=observation.tokenized_prompt_mask,
171
+ token_ar_mask=observation.token_ar_mask,
172
+ token_loss_mask=observation.token_loss_mask,
173
+ )
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/py.typed ADDED
File without changes
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/serving/websocket_policy_server.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import http
3
+ import logging
4
+ import time
5
+ import traceback
6
+
7
+ from openpi_client import base_policy as _base_policy
8
+ from openpi_client import msgpack_numpy
9
+ import websockets.asyncio.server as _server
10
+ import websockets.frames
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ class WebsocketPolicyServer:
16
+ """Serves a policy using the websocket protocol. See websocket_client_policy.py for a client implementation.
17
+
18
+ Currently only implements the `load` and `infer` methods.
19
+ """
20
+
21
+ def __init__(
22
+ self,
23
+ policy: _base_policy.BasePolicy,
24
+ host: str = "0.0.0.0",
25
+ port: int | None = None,
26
+ metadata: dict | None = None,
27
+ ) -> None:
28
+ self._policy = policy
29
+ self._host = host
30
+ self._port = port
31
+ self._metadata = metadata or {}
32
+ logging.getLogger("websockets.server").setLevel(logging.INFO)
33
+
34
+ def serve_forever(self) -> None:
35
+ asyncio.run(self.run())
36
+
37
+ async def run(self):
38
+ async with _server.serve(
39
+ self._handler,
40
+ self._host,
41
+ self._port,
42
+ compression=None,
43
+ max_size=None,
44
+ process_request=_health_check,
45
+ ) as server:
46
+ await server.serve_forever()
47
+
48
+ async def _handler(self, websocket: _server.ServerConnection):
49
+ logger.info(f"Connection from {websocket.remote_address} opened")
50
+ packer = msgpack_numpy.Packer()
51
+
52
+ await websocket.send(packer.pack(self._metadata))
53
+
54
+ prev_total_time = None
55
+ while True:
56
+ try:
57
+ start_time = time.monotonic()
58
+ obs = msgpack_numpy.unpackb(await websocket.recv())
59
+
60
+ infer_time = time.monotonic()
61
+ action = self._policy.infer(obs)
62
+ infer_time = time.monotonic() - infer_time
63
+
64
+ action["server_timing"] = {
65
+ "infer_ms": infer_time * 1000,
66
+ }
67
+ if prev_total_time is not None:
68
+ # We can only record the last total time since we also want to include the send time.
69
+ action["server_timing"]["prev_total_ms"] = prev_total_time * 1000
70
+
71
+ await websocket.send(packer.pack(action))
72
+ prev_total_time = time.monotonic() - start_time
73
+
74
+ except websockets.ConnectionClosed:
75
+ logger.info(f"Connection from {websocket.remote_address} closed")
76
+ break
77
+ except Exception:
78
+ await websocket.send(traceback.format_exc())
79
+ await websocket.close(
80
+ code=websockets.frames.CloseCode.INTERNAL_ERROR,
81
+ reason="Internal server error. Traceback included in previous frame.",
82
+ )
83
+ raise
84
+
85
+
86
+ def _health_check(connection: _server.ServerConnection, request: _server.Request) -> _server.Response | None:
87
+ if request.path == "/healthz":
88
+ return connection.respond(http.HTTPStatus.OK, "OK\n")
89
+ # Continue with the normal request handling.
90
+ return None
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/shared/__init__.py ADDED
File without changes
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/shared/array_typing.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import functools as ft
3
+ import inspect
4
+ from typing import TypeAlias, TypeVar, cast
5
+
6
+ import beartype
7
+ import jax
8
+ import jax._src.tree_util as private_tree_util
9
+ import jax.core
10
+ from jaxtyping import ArrayLike
11
+ from jaxtyping import Bool # noqa: F401
12
+ from jaxtyping import DTypeLike # noqa: F401
13
+ from jaxtyping import Float
14
+ from jaxtyping import Int # noqa: F401
15
+ from jaxtyping import Key # noqa: F401
16
+ from jaxtyping import Num # noqa: F401
17
+ from jaxtyping import PyTree
18
+ from jaxtyping import Real # noqa: F401
19
+ from jaxtyping import UInt8 # noqa: F401
20
+ from jaxtyping import config
21
+ from jaxtyping import jaxtyped
22
+ import jaxtyping._decorator
23
+ import torch
24
+
25
+ # patch jaxtyping to handle https://github.com/patrick-kidger/jaxtyping/issues/277.
26
+ # the problem is that custom PyTree nodes are sometimes initialized with arbitrary types (e.g., `jax.ShapeDtypeStruct`,
27
+ # `jax.Sharding`, or even <object>) due to JAX tracing operations. this patch skips typechecking when the stack trace
28
+ # contains `jax._src.tree_util`, which should only be the case during tree unflattening.
29
+ _original_check_dataclass_annotations = jaxtyping._decorator._check_dataclass_annotations # noqa: SLF001
30
+ # Redefine Array to include both JAX arrays and PyTorch tensors
31
+ Array = jax.Array | torch.Tensor
32
+
33
+
34
+ def _check_dataclass_annotations(self, typechecker):
35
+ if not any(
36
+ frame.frame.f_globals.get("__name__") in {"jax._src.tree_util", "flax.nnx.transforms.compilation"}
37
+ for frame in inspect.stack()
38
+ ):
39
+ return _original_check_dataclass_annotations(self, typechecker)
40
+ return None
41
+
42
+
43
+ jaxtyping._decorator._check_dataclass_annotations = _check_dataclass_annotations # noqa: SLF001
44
+
45
+ KeyArrayLike: TypeAlias = jax.typing.ArrayLike
46
+ Params: TypeAlias = PyTree[Float[ArrayLike, "..."]]
47
+
48
+ T = TypeVar("T")
49
+
50
+
51
+ # runtime type-checking decorator
52
+ def typecheck(t: T) -> T:
53
+ return cast(T, ft.partial(jaxtyped, typechecker=beartype.beartype)(t))
54
+
55
+
56
+ @contextlib.contextmanager
57
+ def disable_typechecking():
58
+ initial = config.jaxtyping_disable
59
+ config.update("jaxtyping_disable", True) # noqa: FBT003
60
+ yield
61
+ config.update("jaxtyping_disable", initial)
62
+
63
+
64
+ def check_pytree_equality(*, expected: PyTree, got: PyTree, check_shapes: bool = False, check_dtypes: bool = False):
65
+ """Checks that two PyTrees have the same structure and optionally checks shapes and dtypes. Creates a much nicer
66
+ error message than if `jax.tree.map` is naively used on PyTrees with different structures.
67
+ """
68
+
69
+ if errors := list(private_tree_util.equality_errors(expected, got)):
70
+ raise ValueError(
71
+ "PyTrees have different structure:\n"
72
+ + (
73
+ "\n".join(
74
+ f" - at keypath '{jax.tree_util.keystr(path)}': expected {thing1}, got {thing2}, so {explanation}.\n"
75
+ for path, thing1, thing2, explanation in errors
76
+ )
77
+ )
78
+ )
79
+
80
+ if check_shapes or check_dtypes:
81
+
82
+ def check(kp, x, y):
83
+ if check_shapes and x.shape != y.shape:
84
+ raise ValueError(f"Shape mismatch at {jax.tree_util.keystr(kp)}: expected {x.shape}, got {y.shape}")
85
+
86
+ if check_dtypes and x.dtype != y.dtype:
87
+ raise ValueError(f"Dtype mismatch at {jax.tree_util.keystr(kp)}: expected {x.dtype}, got {y.dtype}")
88
+
89
+ jax.tree_util.tree_map_with_path(check, expected, got)
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/shared/download.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import concurrent.futures
2
+ import datetime
3
+ import logging
4
+ import os
5
+ import pathlib
6
+ import re
7
+ import shutil
8
+ import stat
9
+ import subprocess
10
+ import time
11
+ import urllib.parse
12
+
13
+ import filelock
14
+ import fsspec
15
+ import fsspec.generic
16
+ import tqdm_loggable.auto as tqdm
17
+
18
+ # Environment variable to control cache directory path, ~/.cache/openpi will be used by default.
19
+ _OPENPI_DATA_HOME = "OPENPI_DATA_HOME"
20
+ DEFAULT_CACHE_DIR = "~/.cache/openpi"
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+
25
+ def get_cache_dir() -> pathlib.Path:
26
+ cache_dir = pathlib.Path(os.getenv(_OPENPI_DATA_HOME, DEFAULT_CACHE_DIR)).expanduser().resolve()
27
+ cache_dir.mkdir(parents=True, exist_ok=True)
28
+ _set_folder_permission(cache_dir)
29
+ return cache_dir
30
+
31
+
32
+ def maybe_download(url: str, *, force_download: bool = False, **kwargs) -> pathlib.Path:
33
+ """Download a file or directory from a remote filesystem to the local cache, and return the local path.
34
+
35
+ If the local file already exists, it will be returned directly.
36
+
37
+ It is safe to call this function concurrently from multiple processes.
38
+ See `get_cache_dir` for more details on the cache directory.
39
+
40
+ Args:
41
+ url: URL to the file to download.
42
+ force_download: If True, the file will be downloaded even if it already exists in the cache.
43
+ **kwargs: Additional arguments to pass to fsspec.
44
+
45
+ Returns:
46
+ Local path to the downloaded file or directory. That path is guaranteed to exist and is absolute.
47
+ """
48
+ # Don't use fsspec to parse the url to avoid unnecessary connection to the remote filesystem.
49
+ parsed = urllib.parse.urlparse(url)
50
+
51
+ # Short circuit if this is a local path.
52
+ if parsed.scheme == "":
53
+ path = pathlib.Path(url)
54
+ if not path.exists():
55
+ raise FileNotFoundError(f"File not found at {url}")
56
+ return path.resolve()
57
+
58
+ cache_dir = get_cache_dir()
59
+
60
+ local_path = cache_dir / parsed.netloc / parsed.path.strip("/")
61
+ local_path = local_path.resolve()
62
+
63
+ # Check if the cache should be invalidated.
64
+ invalidate_cache = False
65
+ if local_path.exists():
66
+ if force_download or _should_invalidate_cache(cache_dir, local_path):
67
+ invalidate_cache = True
68
+ else:
69
+ return local_path
70
+
71
+ try:
72
+ lock_path = local_path.with_suffix(".lock")
73
+ with filelock.FileLock(lock_path):
74
+ # Ensure consistent permissions for the lock file.
75
+ _ensure_permissions(lock_path)
76
+ # First, remove the existing cache if it is expired.
77
+ if invalidate_cache:
78
+ logger.info(f"Removing expired cached entry: {local_path}")
79
+ if local_path.is_dir():
80
+ shutil.rmtree(local_path)
81
+ else:
82
+ local_path.unlink()
83
+
84
+ if not local_path.exists():
85
+ # Download the data to a local cache.
86
+ logger.info(f"Downloading {url} to {local_path}")
87
+ scratch_path = local_path.with_suffix(".partial")
88
+ # A previously interrupted transfer can leave this scratch path
89
+ # behind. fsspec then nests a fresh recursive download inside
90
+ # it, while stale truncated shards remain at its root. Start a
91
+ # new download from an empty scratch path instead.
92
+ if scratch_path.exists():
93
+ logger.warning(f"Removing stale partial download: {scratch_path}")
94
+ if scratch_path.is_dir():
95
+ shutil.rmtree(scratch_path)
96
+ else:
97
+ scratch_path.unlink()
98
+ # Route openpi-assets through gsutil to avoid gcsfs auth issues with this bucket.
99
+ # All other gs:// URLs (e.g. big_vision) continue to use gcsfs as normal.
100
+ if parsed.scheme == "gs" and parsed.netloc == "openpi-assets":
101
+ _download_gsutil(url, scratch_path, **kwargs)
102
+ else:
103
+ _download_fsspec(url, scratch_path, **kwargs)
104
+
105
+ shutil.move(scratch_path, local_path)
106
+ _ensure_permissions(local_path)
107
+
108
+ except PermissionError as e:
109
+ msg = (
110
+ f"Local file permission error was encountered while downloading {url}. "
111
+ f"Please try again after removing the cached data using: `rm -rf {local_path}*`"
112
+ )
113
+ raise PermissionError(msg) from e
114
+
115
+ return local_path
116
+
117
+
118
+ def _download_gsutil(url: str, local_path: pathlib.Path, **kwargs) -> None:
119
+ """Download a file or directory from GCS using gsutil if available, otherwise fall back to gcsfs."""
120
+ if shutil.which("gsutil") is None:
121
+ logger.warning(
122
+ "gsutil not found, falling back to gcsfs. This may fail if GCP credentials are not configured correctly."
123
+ )
124
+ _download_fsspec(url, local_path, **kwargs)
125
+ return
126
+ local_path.mkdir(parents=True, exist_ok=True)
127
+ subprocess.run(
128
+ ["gsutil", "-m", "cp", "-r", f"{url}/*", str(local_path)],
129
+ check=True,
130
+ )
131
+
132
+
133
+ def _download_fsspec(url: str, local_path: pathlib.Path, **kwargs) -> None:
134
+ """Download a file from a remote filesystem to the local cache, and return the local path."""
135
+ fs, _ = fsspec.core.url_to_fs(url, **kwargs)
136
+ info = fs.info(url)
137
+ # Folders are represented by 0-byte objects with a trailing forward slash.
138
+ if is_dir := (info["type"] == "directory" or (info["size"] == 0 and info["name"].endswith("/"))):
139
+ total_size = fs.du(url)
140
+ else:
141
+ total_size = info["size"]
142
+ with tqdm.tqdm(total=total_size, unit="iB", unit_scale=True, unit_divisor=1024) as pbar:
143
+ executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
144
+ future = executor.submit(fs.get, url, local_path, recursive=is_dir)
145
+ while not future.done():
146
+ current_size = sum(f.stat().st_size for f in [*local_path.rglob("*"), local_path] if f.is_file())
147
+ pbar.update(current_size - pbar.n)
148
+ time.sleep(1)
149
+ pbar.update(total_size - pbar.n)
150
+
151
+
152
+ def _set_permission(path: pathlib.Path, target_permission: int):
153
+ """chmod requires executable permission to be set, so we skip if the permission is already match with the target."""
154
+ if path.stat().st_mode & target_permission == target_permission:
155
+ logger.debug(f"Skipping {path} because it already has correct permissions")
156
+ return
157
+ path.chmod(target_permission)
158
+ logger.debug(f"Set {path} to {target_permission}")
159
+
160
+
161
+ def _set_folder_permission(folder_path: pathlib.Path) -> None:
162
+ """Set folder permission to be read, write and searchable."""
163
+ _set_permission(folder_path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
164
+
165
+
166
+ def _ensure_permissions(path: pathlib.Path) -> None:
167
+ """Since we are sharing cache directory with containerized runtime as well as training script, we need to
168
+ ensure that the cache directory has the correct permissions.
169
+ """
170
+
171
+ def _setup_folder_permission_between_cache_dir_and_path(path: pathlib.Path) -> None:
172
+ cache_dir = get_cache_dir()
173
+ relative_path = path.relative_to(cache_dir)
174
+ moving_path = cache_dir
175
+ for part in relative_path.parts:
176
+ _set_folder_permission(moving_path / part)
177
+ moving_path = moving_path / part
178
+
179
+ def _set_file_permission(file_path: pathlib.Path) -> None:
180
+ """Set all files to be read & writable, if it is a script, keep it as a script."""
181
+ file_rw = stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IWGRP | stat.S_IROTH | stat.S_IWOTH
182
+ if file_path.stat().st_mode & 0o100:
183
+ _set_permission(file_path, file_rw | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
184
+ else:
185
+ _set_permission(file_path, file_rw)
186
+
187
+ _setup_folder_permission_between_cache_dir_and_path(path)
188
+ for root, dirs, files in os.walk(str(path)):
189
+ root_path = pathlib.Path(root)
190
+ for file in files:
191
+ file_path = root_path / file
192
+ _set_file_permission(file_path)
193
+
194
+ for dir in dirs:
195
+ dir_path = root_path / dir
196
+ _set_folder_permission(dir_path)
197
+
198
+
199
+ def _get_mtime(year: int, month: int, day: int) -> float:
200
+ """Get the mtime of a given date at midnight UTC."""
201
+ date = datetime.datetime(year, month, day, tzinfo=datetime.UTC)
202
+ return time.mktime(date.timetuple())
203
+
204
+
205
+ # Map of relative paths, defined as regular expressions, to expiration timestamps (mtime format).
206
+ # Partial matching will be used from top to bottom and the first match will be chosen.
207
+ # Cached entries will be retained only if they are newer than the expiration timestamp.
208
+ _INVALIDATE_CACHE_DIRS: dict[re.Pattern, float] = {
209
+ re.compile("openpi-assets/checkpoints/pi0_aloha_pen_uncap"): _get_mtime(2025, 2, 17),
210
+ re.compile("openpi-assets/checkpoints/pi0_libero"): _get_mtime(2025, 2, 6),
211
+ re.compile("openpi-assets/checkpoints/"): _get_mtime(2025, 2, 3),
212
+ }
213
+
214
+
215
+ def _should_invalidate_cache(cache_dir: pathlib.Path, local_path: pathlib.Path) -> bool:
216
+ """Invalidate the cache if it is expired. Return True if the cache was invalidated."""
217
+
218
+ assert local_path.exists(), f"File not found at {local_path}"
219
+
220
+ relative_path = str(local_path.relative_to(cache_dir))
221
+ for pattern, expire_time in _INVALIDATE_CACHE_DIRS.items():
222
+ if pattern.match(relative_path):
223
+ # Remove if not newer than the expiration timestamp.
224
+ return local_path.stat().st_mtime <= expire_time
225
+
226
+ return False
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/shared/download_test.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pathlib
2
+
3
+ import pytest
4
+
5
+ import openpi.shared.download as download
6
+
7
+
8
+ @pytest.fixture(scope="session", autouse=True)
9
+ def set_openpi_data_home(tmp_path_factory):
10
+ temp_dir = tmp_path_factory.mktemp("openpi_data")
11
+ with pytest.MonkeyPatch().context() as mp:
12
+ mp.setenv("OPENPI_DATA_HOME", str(temp_dir))
13
+ yield
14
+
15
+
16
+ def test_download_local(tmp_path: pathlib.Path):
17
+ local_path = tmp_path / "local"
18
+ local_path.touch()
19
+
20
+ result = download.maybe_download(str(local_path))
21
+ assert result == local_path
22
+
23
+ with pytest.raises(FileNotFoundError):
24
+ download.maybe_download("bogus")
25
+
26
+
27
+ def test_download_gs_dir():
28
+ remote_path = "gs://openpi-assets/testdata/random"
29
+
30
+ local_path = download.maybe_download(remote_path)
31
+ assert local_path.exists()
32
+
33
+ new_local_path = download.maybe_download(remote_path)
34
+ assert new_local_path == local_path
35
+
36
+
37
+ def test_download_gs():
38
+ remote_path = "gs://openpi-assets/testdata/random/random_512kb.bin"
39
+
40
+ local_path = download.maybe_download(remote_path)
41
+ assert local_path.exists()
42
+
43
+ new_local_path = download.maybe_download(remote_path)
44
+ assert new_local_path == local_path
45
+
46
+
47
+ def test_download_fsspec():
48
+ remote_path = "gs://big_vision/paligemma_tokenizer.model"
49
+
50
+ local_path = download.maybe_download(remote_path, gs={"token": "anon"})
51
+ assert local_path.exists()
52
+
53
+ new_local_path = download.maybe_download(remote_path, gs={"token": "anon"})
54
+ assert new_local_path == local_path
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/shared/image_tools.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+
3
+ import jax
4
+ import jax.numpy as jnp
5
+ import torch
6
+ import torch.nn.functional as F # noqa: N812
7
+
8
+ import openpi.shared.array_typing as at
9
+
10
+
11
+ @functools.partial(jax.jit, static_argnums=(1, 2, 3))
12
+ @at.typecheck
13
+ def resize_with_pad(
14
+ images: at.UInt8[at.Array, "*b h w c"] | at.Float[at.Array, "*b h w c"],
15
+ height: int,
16
+ width: int,
17
+ method: jax.image.ResizeMethod = jax.image.ResizeMethod.LINEAR,
18
+ ) -> at.UInt8[at.Array, "*b {height} {width} c"] | at.Float[at.Array, "*b {height} {width} c"]:
19
+ """Replicates tf.image.resize_with_pad. Resizes an image to a target height and width without distortion
20
+ by padding with black. If the image is float32, it must be in the range [-1, 1].
21
+ """
22
+ has_batch_dim = images.ndim == 4
23
+ if not has_batch_dim:
24
+ images = images[None] # type: ignore
25
+ cur_height, cur_width = images.shape[1:3]
26
+ ratio = max(cur_width / width, cur_height / height)
27
+ resized_height = int(cur_height / ratio)
28
+ resized_width = int(cur_width / ratio)
29
+ resized_images = jax.image.resize(
30
+ images, (images.shape[0], resized_height, resized_width, images.shape[3]), method=method
31
+ )
32
+ if images.dtype == jnp.uint8:
33
+ # round from float back to uint8
34
+ resized_images = jnp.round(resized_images).clip(0, 255).astype(jnp.uint8)
35
+ elif images.dtype == jnp.float32:
36
+ resized_images = resized_images.clip(-1.0, 1.0)
37
+ else:
38
+ raise ValueError(f"Unsupported image dtype: {images.dtype}")
39
+
40
+ pad_h0, remainder_h = divmod(height - resized_height, 2)
41
+ pad_h1 = pad_h0 + remainder_h
42
+ pad_w0, remainder_w = divmod(width - resized_width, 2)
43
+ pad_w1 = pad_w0 + remainder_w
44
+ padded_images = jnp.pad(
45
+ resized_images,
46
+ ((0, 0), (pad_h0, pad_h1), (pad_w0, pad_w1), (0, 0)),
47
+ constant_values=0 if images.dtype == jnp.uint8 else -1.0,
48
+ )
49
+
50
+ if not has_batch_dim:
51
+ padded_images = padded_images[0]
52
+ return padded_images
53
+
54
+
55
+ def resize_with_pad_torch(
56
+ images: torch.Tensor,
57
+ height: int,
58
+ width: int,
59
+ mode: str = "bilinear",
60
+ ) -> torch.Tensor:
61
+ """PyTorch version of resize_with_pad. Resizes an image to a target height and width without distortion
62
+ by padding with black. If the image is float32, it must be in the range [-1, 1].
63
+
64
+ Args:
65
+ images: Tensor of shape [*b, h, w, c] or [*b, c, h, w]
66
+ height: Target height
67
+ width: Target width
68
+ mode: Interpolation mode ('bilinear', 'nearest', etc.)
69
+
70
+ Returns:
71
+ Resized and padded tensor with same shape format as input
72
+ """
73
+ # Check if input is in channels-last format [*b, h, w, c] or channels-first [*b, c, h, w]
74
+ if images.shape[-1] <= 4: # Assume channels-last format
75
+ channels_last = True
76
+ # Convert to channels-first for torch operations
77
+ if images.dim() == 3:
78
+ images = images.unsqueeze(0) # Add batch dimension
79
+ images = images.permute(0, 3, 1, 2) # [b, h, w, c] -> [b, c, h, w]
80
+ else:
81
+ channels_last = False
82
+ if images.dim() == 3:
83
+ images = images.unsqueeze(0) # Add batch dimension
84
+
85
+ batch_size, channels, cur_height, cur_width = images.shape
86
+
87
+ # Calculate resize ratio
88
+ ratio = max(cur_width / width, cur_height / height)
89
+ resized_height = int(cur_height / ratio)
90
+ resized_width = int(cur_width / ratio)
91
+
92
+ # Resize
93
+ resized_images = F.interpolate(
94
+ images, size=(resized_height, resized_width), mode=mode, align_corners=False if mode == "bilinear" else None
95
+ )
96
+
97
+ # Handle dtype-specific clipping
98
+ if images.dtype == torch.uint8:
99
+ resized_images = torch.round(resized_images).clamp(0, 255).to(torch.uint8)
100
+ elif images.dtype == torch.float32:
101
+ resized_images = resized_images.clamp(-1.0, 1.0)
102
+ else:
103
+ raise ValueError(f"Unsupported image dtype: {images.dtype}")
104
+
105
+ # Calculate padding
106
+ pad_h0, remainder_h = divmod(height - resized_height, 2)
107
+ pad_h1 = pad_h0 + remainder_h
108
+ pad_w0, remainder_w = divmod(width - resized_width, 2)
109
+ pad_w1 = pad_w0 + remainder_w
110
+
111
+ # Pad
112
+ constant_value = 0 if images.dtype == torch.uint8 else -1.0
113
+ padded_images = F.pad(
114
+ resized_images,
115
+ (pad_w0, pad_w1, pad_h0, pad_h1), # left, right, top, bottom
116
+ mode="constant",
117
+ value=constant_value,
118
+ )
119
+
120
+ # Convert back to original format if needed
121
+ if channels_last:
122
+ padded_images = padded_images.permute(0, 2, 3, 1) # [b, c, h, w] -> [b, h, w, c]
123
+ if batch_size == 1 and images.shape[0] == 1:
124
+ padded_images = padded_images.squeeze(0) # Remove batch dimension if it was added
125
+
126
+ return padded_images
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/shared/image_tools_test.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import jax.numpy as jnp
2
+
3
+ from openpi.shared import image_tools
4
+
5
+
6
+ def test_resize_with_pad_shapes():
7
+ # Test case 1: Resize image with larger dimensions
8
+ images = jnp.zeros((2, 10, 10, 3), dtype=jnp.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 jnp.all(resized_images == 0)
14
+
15
+ # Test case 2: Resize image with smaller dimensions
16
+ images = jnp.zeros((3, 30, 30, 3), dtype=jnp.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 jnp.all(resized_images == 0)
22
+
23
+ # Test case 3: Resize image with the same dimensions
24
+ images = jnp.zeros((1, 50, 50, 3), dtype=jnp.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 jnp.all(resized_images == 0)
30
+
31
+ # Test case 3: Resize image with odd-numbered padding
32
+ images = jnp.zeros((1, 256, 320, 3), dtype=jnp.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 jnp.all(resized_images == 0)
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/shared/nnx_utils.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Callable
2
+ import dataclasses
3
+ import functools
4
+ import inspect
5
+ import re
6
+ from typing import Any, ParamSpec, TypeVar
7
+
8
+ import flax.nnx as nnx
9
+ import jax
10
+
11
+ P = ParamSpec("P")
12
+ R = TypeVar("R")
13
+
14
+
15
+ def module_jit(meth: Callable[P, R], *jit_args, **jit_kwargs) -> Callable[P, R]:
16
+ """A higher-order function to JIT-compile `nnx.Module` methods, freezing the module's state in the process.
17
+
18
+ Why not `nnx.jit`? For some reason, naively applying `nnx.jit` to `nnx.Module` methods, bound or unbound, uses much
19
+ more memory than necessary. I'm guessing it has something to do with the fact that it must keep track of module
20
+ mutations. Also, `nnx.jit` has some inherent overhead compared to a standard `jax.jit`, since every call must
21
+ traverse the NNX module graph. See https://github.com/google/flax/discussions/4224 for details.
22
+
23
+ `module_jit` is an alternative that avoids these issues by freezing the module's state. The function returned by
24
+ `module_jit` acts exactly like the original method, except that the state of the module is frozen to whatever it was
25
+ when `module_jit` was called. Mutations to the module within `meth` are still allowed, but they will be discarded
26
+ after the method call completes.
27
+ """
28
+ if not (inspect.ismethod(meth) and isinstance(meth.__self__, nnx.Module)):
29
+ raise ValueError("module_jit must only be used on bound methods of nnx.Modules.")
30
+
31
+ graphdef, state = nnx.split(meth.__self__)
32
+
33
+ def fun(state: nnx.State, *args: P.args, **kwargs: P.kwargs) -> R:
34
+ module = nnx.merge(graphdef, state)
35
+ return meth.__func__(module, *args, **kwargs)
36
+
37
+ jitted_fn = jax.jit(fun, *jit_args, **jit_kwargs)
38
+
39
+ @functools.wraps(meth)
40
+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
41
+ return jitted_fn(state, *args, **kwargs)
42
+
43
+ return wrapper
44
+
45
+
46
+ @dataclasses.dataclass(frozen=True)
47
+ class PathRegex:
48
+ """NNX Filter that matches paths using a regex.
49
+
50
+ By default, paths are joined with a `/` separator. This can be overridden by setting the `sep` argument.
51
+ """
52
+
53
+ pattern: str | re.Pattern
54
+ sep: str = "/"
55
+
56
+ def __post_init__(self):
57
+ if not isinstance(self.pattern, re.Pattern):
58
+ object.__setattr__(self, "pattern", re.compile(self.pattern))
59
+
60
+ def __call__(self, path: nnx.filterlib.PathParts, x: Any) -> bool:
61
+ joined_path = self.sep.join(str(x) for x in path)
62
+ assert isinstance(self.pattern, re.Pattern)
63
+ return self.pattern.fullmatch(joined_path) is not None
64
+
65
+
66
+ def state_map(state: nnx.State, filter: nnx.filterlib.Filter, fn: Callable[[Any], Any]) -> nnx.State:
67
+ """Apply a function to the leaves of the state that match the filter."""
68
+ filtered_keys = set(state.filter(filter).flat_state())
69
+ return state.map(lambda k, v: fn(v) if k in filtered_keys else v)
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/shared/normalize.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import pathlib
3
+
4
+ import numpy as np
5
+ import numpydantic
6
+ import pydantic
7
+
8
+
9
+ @pydantic.dataclasses.dataclass
10
+ class NormStats:
11
+ mean: numpydantic.NDArray
12
+ std: numpydantic.NDArray
13
+ q01: numpydantic.NDArray | None = None # 1st quantile
14
+ q99: numpydantic.NDArray | None = None # 99th quantile
15
+
16
+
17
+ class RunningStats:
18
+ """Compute running statistics of a batch of vectors."""
19
+
20
+ def __init__(self):
21
+ self._count = 0
22
+ self._mean = None
23
+ self._mean_of_squares = None
24
+ self._min = None
25
+ self._max = None
26
+ self._histograms = None
27
+ self._bin_edges = None
28
+ self._num_quantile_bins = 5000 # for computing quantiles on the fly
29
+
30
+ def update(self, batch: np.ndarray) -> None:
31
+ """
32
+ Update the running statistics with a batch of vectors.
33
+
34
+ Args:
35
+ vectors (np.ndarray): An array where all dimensions except the last are batch dimensions.
36
+ """
37
+ batch = batch.reshape(-1, batch.shape[-1])
38
+ num_elements, vector_length = batch.shape
39
+ if self._count == 0:
40
+ self._mean = np.mean(batch, axis=0)
41
+ self._mean_of_squares = np.mean(batch**2, axis=0)
42
+ self._min = np.min(batch, axis=0)
43
+ self._max = np.max(batch, axis=0)
44
+ self._histograms = [np.zeros(self._num_quantile_bins) for _ in range(vector_length)]
45
+ self._bin_edges = [
46
+ np.linspace(self._min[i] - 1e-10, self._max[i] + 1e-10, self._num_quantile_bins + 1)
47
+ for i in range(vector_length)
48
+ ]
49
+ else:
50
+ if vector_length != self._mean.size:
51
+ raise ValueError("The length of new vectors does not match the initialized vector length.")
52
+ new_max = np.max(batch, axis=0)
53
+ new_min = np.min(batch, axis=0)
54
+ max_changed = np.any(new_max > self._max)
55
+ min_changed = np.any(new_min < self._min)
56
+ self._max = np.maximum(self._max, new_max)
57
+ self._min = np.minimum(self._min, new_min)
58
+
59
+ if max_changed or min_changed:
60
+ self._adjust_histograms()
61
+
62
+ self._count += num_elements
63
+
64
+ batch_mean = np.mean(batch, axis=0)
65
+ batch_mean_of_squares = np.mean(batch**2, axis=0)
66
+
67
+ # Update running mean and mean of squares.
68
+ self._mean += (batch_mean - self._mean) * (num_elements / self._count)
69
+ self._mean_of_squares += (batch_mean_of_squares - self._mean_of_squares) * (num_elements / self._count)
70
+
71
+ self._update_histograms(batch)
72
+
73
+ def get_statistics(self) -> NormStats:
74
+ """
75
+ Compute and return the statistics of the vectors processed so far.
76
+
77
+ Returns:
78
+ dict: A dictionary containing the computed statistics.
79
+ """
80
+ if self._count < 2:
81
+ raise ValueError("Cannot compute statistics for less than 2 vectors.")
82
+
83
+ variance = self._mean_of_squares - self._mean**2
84
+ stddev = np.sqrt(np.maximum(0, variance))
85
+ q01, q99 = self._compute_quantiles([0.01, 0.99])
86
+ return NormStats(mean=self._mean, std=stddev, q01=q01, q99=q99)
87
+
88
+ def _adjust_histograms(self):
89
+ """Adjust histograms when min or max changes."""
90
+ for i in range(len(self._histograms)):
91
+ old_edges = self._bin_edges[i]
92
+ new_edges = np.linspace(self._min[i], self._max[i], self._num_quantile_bins + 1)
93
+
94
+ # Redistribute the existing histogram counts to the new bins
95
+ new_hist, _ = np.histogram(old_edges[:-1], bins=new_edges, weights=self._histograms[i])
96
+
97
+ self._histograms[i] = new_hist
98
+ self._bin_edges[i] = new_edges
99
+
100
+ def _update_histograms(self, batch: np.ndarray) -> None:
101
+ """Update histograms with new vectors."""
102
+ for i in range(batch.shape[1]):
103
+ hist, _ = np.histogram(batch[:, i], bins=self._bin_edges[i])
104
+ self._histograms[i] += hist
105
+
106
+ def _compute_quantiles(self, quantiles):
107
+ """Compute quantiles based on histograms."""
108
+ results = []
109
+ for q in quantiles:
110
+ target_count = q * self._count
111
+ q_values = []
112
+ for hist, edges in zip(self._histograms, self._bin_edges, strict=True):
113
+ cumsum = np.cumsum(hist)
114
+ idx = np.searchsorted(cumsum, target_count)
115
+ q_values.append(edges[idx])
116
+ results.append(np.array(q_values))
117
+ return results
118
+
119
+
120
+ class _NormStatsDict(pydantic.BaseModel):
121
+ norm_stats: dict[str, NormStats]
122
+
123
+
124
+ def serialize_json(norm_stats: dict[str, NormStats]) -> str:
125
+ """Serialize the running statistics to a JSON string."""
126
+ return _NormStatsDict(norm_stats=norm_stats).model_dump_json(indent=2)
127
+
128
+
129
+ def deserialize_json(data: str) -> dict[str, NormStats]:
130
+ """Deserialize the running statistics from a JSON string."""
131
+ return _NormStatsDict(**json.loads(data)).norm_stats
132
+
133
+
134
+ def save(directory: pathlib.Path | str, norm_stats: dict[str, NormStats]) -> None:
135
+ """Save the normalization stats to a directory."""
136
+ path = pathlib.Path(directory) / "norm_stats.json"
137
+ path.parent.mkdir(parents=True, exist_ok=True)
138
+ path.write_text(serialize_json(norm_stats))
139
+
140
+
141
+ def load(directory: pathlib.Path | str) -> dict[str, NormStats]:
142
+ """Load the normalization stats from a directory."""
143
+ path = pathlib.Path(directory) / "norm_stats.json"
144
+ if not path.exists():
145
+ raise FileNotFoundError(f"Norm stats file not found at: {path}")
146
+ return deserialize_json(path.read_text())
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/shared/normalize_test.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ import openpi.shared.normalize as normalize
4
+
5
+
6
+ def test_normalize_update():
7
+ arr = np.arange(12).reshape(4, 3) # 4 vectors of length 3
8
+
9
+ stats = normalize.RunningStats()
10
+ for i in range(len(arr)):
11
+ stats.update(arr[i : i + 1]) # Update with one vector at a time
12
+ results = stats.get_statistics()
13
+
14
+ assert np.allclose(results.mean, np.mean(arr, axis=0))
15
+ assert np.allclose(results.std, np.std(arr, axis=0))
16
+
17
+
18
+ def test_serialize_deserialize():
19
+ stats = normalize.RunningStats()
20
+ stats.update(np.arange(12).reshape(4, 3)) # 4 vectors of length 3
21
+
22
+ norm_stats = {"test": stats.get_statistics()}
23
+ norm_stats2 = normalize.deserialize_json(normalize.serialize_json(norm_stats))
24
+ assert np.allclose(norm_stats["test"].mean, norm_stats2["test"].mean)
25
+ assert np.allclose(norm_stats["test"].std, norm_stats2["test"].std)
26
+
27
+
28
+ def test_multiple_batch_dimensions():
29
+ # Test with multiple batch dimensions: (2, 3, 4) where 4 is vector dimension
30
+ batch_shape = (2, 3, 4)
31
+ arr = np.random.rand(*batch_shape)
32
+
33
+ stats = normalize.RunningStats()
34
+ stats.update(arr) # Should handle (2, 3, 4) -> reshape to (6, 4)
35
+ results = stats.get_statistics()
36
+
37
+ # Flatten batch dimensions and compute expected stats
38
+ flattened = arr.reshape(-1, arr.shape[-1]) # (6, 4)
39
+ expected_mean = np.mean(flattened, axis=0)
40
+ expected_std = np.std(flattened, axis=0)
41
+
42
+ assert np.allclose(results.mean, expected_mean)
43
+ assert np.allclose(results.std, expected_std)
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/transforms.py ADDED
@@ -0,0 +1,495 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Callable, Mapping, Sequence
2
+ import dataclasses
3
+ import re
4
+ from typing import Protocol, TypeAlias, TypeVar, runtime_checkable
5
+
6
+ import flax.traverse_util as traverse_util
7
+ import jax
8
+ import numpy as np
9
+ from openpi_client import image_tools
10
+
11
+ from openpi.models import tokenizer as _tokenizer
12
+ from openpi.shared import array_typing as at
13
+ from openpi.shared import normalize as _normalize
14
+
15
+ DataDict: TypeAlias = at.PyTree
16
+ NormStats: TypeAlias = _normalize.NormStats
17
+
18
+
19
+ T = TypeVar("T")
20
+ S = TypeVar("S")
21
+
22
+
23
+ @runtime_checkable
24
+ class DataTransformFn(Protocol):
25
+ def __call__(self, data: DataDict) -> DataDict:
26
+ """Apply transformation to the data.
27
+
28
+ Args:
29
+ data: The data to apply the transform to. This is a possibly nested dictionary that contains
30
+ unbatched data elements. Each leaf is expected to be a numpy array. Using JAX arrays is allowed
31
+ but not recommended since it may result in extra GPU memory usage inside data loader worker
32
+ processes.
33
+
34
+ Returns:
35
+ The transformed data. Could be the input `data` that was modified in place, or a new data structure.
36
+ """
37
+
38
+
39
+ @dataclasses.dataclass(frozen=True)
40
+ class Group:
41
+ """A group of transforms."""
42
+
43
+ # Transforms that are applied to the model input data.
44
+ inputs: Sequence[DataTransformFn] = ()
45
+
46
+ # Transforms that are applied to the model output data.
47
+ outputs: Sequence[DataTransformFn] = ()
48
+
49
+ def push(self, *, inputs: Sequence[DataTransformFn] = (), outputs: Sequence[DataTransformFn] = ()) -> "Group":
50
+ """Append transforms to the group and return a new group.
51
+
52
+ Args:
53
+ inputs: Appended to the *end* of the current input transforms.
54
+ outputs: Appended to the *beginning* of the current output transforms.
55
+
56
+ Returns:
57
+ A new group with the appended transforms.
58
+ """
59
+ return Group(inputs=(*self.inputs, *inputs), outputs=(*outputs, *self.outputs))
60
+
61
+
62
+ @dataclasses.dataclass(frozen=True)
63
+ class CompositeTransform(DataTransformFn):
64
+ """A composite transform that applies a sequence of transforms in order."""
65
+
66
+ transforms: Sequence[DataTransformFn]
67
+
68
+ def __call__(self, data: DataDict) -> DataDict:
69
+ for transform in self.transforms:
70
+ data = transform(data)
71
+ return data
72
+
73
+
74
+ def compose(transforms: Sequence[DataTransformFn]) -> DataTransformFn:
75
+ """Compose a sequence of transforms into a single transform."""
76
+ return CompositeTransform(transforms)
77
+
78
+
79
+ @dataclasses.dataclass(frozen=True)
80
+ class RepackTransform(DataTransformFn):
81
+ """Repacks an input dictionary into a new dictionary.
82
+
83
+ Repacking is defined using a dictionary where the keys are the new keys and the values
84
+ are the flattened paths to the old keys. We use '/' as the separator during flattening.
85
+
86
+ Example:
87
+ {
88
+ "images": {
89
+ "cam_high": "observation.images.top",
90
+ "cam_low": "observation.images.bottom",
91
+ },
92
+ "state": "observation.state",
93
+ "actions": "action",
94
+ }
95
+ """
96
+
97
+ structure: at.PyTree[str]
98
+
99
+ def __call__(self, data: DataDict) -> DataDict:
100
+ flat_item = flatten_dict(data)
101
+ return jax.tree.map(lambda k: flat_item[k], self.structure)
102
+
103
+
104
+ @dataclasses.dataclass(frozen=True)
105
+ class InjectDefaultPrompt(DataTransformFn):
106
+ prompt: str | None
107
+
108
+ def __call__(self, data: DataDict) -> DataDict:
109
+ if self.prompt is not None and "prompt" not in data:
110
+ data["prompt"] = np.asarray(self.prompt)
111
+ return data
112
+
113
+
114
+ @dataclasses.dataclass(frozen=True)
115
+ class Normalize(DataTransformFn):
116
+ norm_stats: at.PyTree[NormStats] | None
117
+ # If true, will use quantile normalization. Otherwise, normal z-score normalization will be used.
118
+ use_quantiles: bool = False
119
+ # If true, will raise an error if any of the keys in the norm stats are not present in the data.
120
+ strict: bool = False
121
+
122
+ def __post_init__(self):
123
+ if self.norm_stats is not None and self.use_quantiles:
124
+ _assert_quantile_stats(self.norm_stats)
125
+
126
+ def __call__(self, data: DataDict) -> DataDict:
127
+ if self.norm_stats is None:
128
+ return data
129
+
130
+ return apply_tree(
131
+ data,
132
+ self.norm_stats,
133
+ self._normalize_quantile if self.use_quantiles else self._normalize,
134
+ strict=self.strict,
135
+ )
136
+
137
+ def _normalize(self, x, stats: NormStats):
138
+ mean, std = stats.mean[..., : x.shape[-1]], stats.std[..., : x.shape[-1]]
139
+ return (x - mean) / (std + 1e-6)
140
+
141
+ def _normalize_quantile(self, x, stats: NormStats):
142
+ assert stats.q01 is not None
143
+ assert stats.q99 is not None
144
+ q01, q99 = stats.q01[..., : x.shape[-1]], stats.q99[..., : x.shape[-1]]
145
+ return (x - q01) / (q99 - q01 + 1e-6) * 2.0 - 1.0
146
+
147
+
148
+ @dataclasses.dataclass(frozen=True)
149
+ class Unnormalize(DataTransformFn):
150
+ norm_stats: at.PyTree[NormStats] | None
151
+ # If true, will use quantile normalization. Otherwise, normal z-score normalization will be used.
152
+ use_quantiles: bool = False
153
+
154
+ def __post_init__(self):
155
+ if self.norm_stats is not None and self.use_quantiles:
156
+ _assert_quantile_stats(self.norm_stats)
157
+
158
+ def __call__(self, data: DataDict) -> DataDict:
159
+ if self.norm_stats is None:
160
+ return data
161
+
162
+ # Make sure that all the keys in the norm stats are present in the data.
163
+ return apply_tree(
164
+ data,
165
+ self.norm_stats,
166
+ self._unnormalize_quantile if self.use_quantiles else self._unnormalize,
167
+ strict=True,
168
+ )
169
+
170
+ def _unnormalize(self, x, stats: NormStats):
171
+ mean = pad_to_dim(stats.mean, x.shape[-1], axis=-1, value=0.0)
172
+ std = pad_to_dim(stats.std, x.shape[-1], axis=-1, value=1.0)
173
+ return x * (std + 1e-6) + mean
174
+
175
+ def _unnormalize_quantile(self, x, stats: NormStats):
176
+ assert stats.q01 is not None
177
+ assert stats.q99 is not None
178
+ q01, q99 = stats.q01, stats.q99
179
+ if (dim := q01.shape[-1]) < x.shape[-1]:
180
+ return np.concatenate([(x[..., :dim] + 1.0) / 2.0 * (q99 - q01 + 1e-6) + q01, x[..., dim:]], axis=-1)
181
+ return (x + 1.0) / 2.0 * (q99 - q01 + 1e-6) + q01
182
+
183
+
184
+ @dataclasses.dataclass(frozen=True)
185
+ class ResizeImages(DataTransformFn):
186
+ height: int
187
+ width: int
188
+
189
+ def __call__(self, data: DataDict) -> DataDict:
190
+ data["image"] = {k: image_tools.resize_with_pad(v, self.height, self.width) for k, v in data["image"].items()}
191
+ return data
192
+
193
+
194
+ @dataclasses.dataclass(frozen=True)
195
+ class SubsampleActions(DataTransformFn):
196
+ stride: int
197
+
198
+ def __call__(self, data: DataDict) -> DataDict:
199
+ data["actions"] = data["actions"][:: self.stride]
200
+ return data
201
+
202
+
203
+ @dataclasses.dataclass(frozen=True)
204
+ class DeltaActions(DataTransformFn):
205
+ """Repacks absolute actions into delta action space."""
206
+
207
+ # Boolean mask for the action dimensions to be repacked into delta action space. Length
208
+ # can be smaller than the actual number of dimensions. If None, this transform is a no-op.
209
+ # See `make_bool_mask` for more details.
210
+ mask: Sequence[bool] | None
211
+
212
+ def __call__(self, data: DataDict) -> DataDict:
213
+ if "actions" not in data or self.mask is None:
214
+ return data
215
+
216
+ state, actions = data["state"], data["actions"]
217
+ mask = np.asarray(self.mask)
218
+ dims = mask.shape[-1]
219
+ actions[..., :dims] -= np.expand_dims(np.where(mask, state[..., :dims], 0), axis=-2)
220
+ data["actions"] = actions
221
+
222
+ return data
223
+
224
+
225
+ @dataclasses.dataclass(frozen=True)
226
+ class AbsoluteActions(DataTransformFn):
227
+ """Repacks delta actions into absolute action space."""
228
+
229
+ # Boolean mask for the action dimensions to be repacked into absolute action space. Length
230
+ # can be smaller than the actual number of dimensions. If None, this transform is a no-op.
231
+ # See `make_bool_mask` for more details.
232
+ mask: Sequence[bool] | None
233
+
234
+ def __call__(self, data: DataDict) -> DataDict:
235
+ if "actions" not in data or self.mask is None:
236
+ return data
237
+
238
+ state, actions = data["state"], data["actions"]
239
+ mask = np.asarray(self.mask)
240
+ dims = mask.shape[-1]
241
+ actions[..., :dims] += np.expand_dims(np.where(mask, state[..., :dims], 0), axis=-2)
242
+ data["actions"] = actions
243
+
244
+ return data
245
+
246
+
247
+ @dataclasses.dataclass(frozen=True)
248
+ class TokenizePrompt(DataTransformFn):
249
+ tokenizer: _tokenizer.PaligemmaTokenizer
250
+ discrete_state_input: bool = False
251
+
252
+ def __call__(self, data: DataDict) -> DataDict:
253
+ if (prompt := data.pop("prompt", None)) is None:
254
+ raise ValueError("Prompt is required")
255
+
256
+ # InjectDefaultPrompt stores a single default string as a zero-dimensional
257
+ # ndarray. Treat that as a scalar prompt, not as a batch (``list`` on a
258
+ # 0-D array raises TypeError during policy inference).
259
+ is_batched_prompt = isinstance(prompt, list) or (
260
+ isinstance(prompt, (np.ndarray, jax.Array)) and np.ndim(prompt) > 0
261
+ )
262
+
263
+ if self.discrete_state_input:
264
+ if (state := data.get("state", None)) is None:
265
+ raise ValueError("State is required.")
266
+ else:
267
+ state = None
268
+
269
+ if is_batched_prompt:
270
+ prompts = list(prompt)
271
+ states = state if self.discrete_state_input else [None] * len(prompts)
272
+ token_list = []
273
+ mask_list = []
274
+ for prompt_item, state_item in zip(prompts, states, strict=True):
275
+ if not isinstance(prompt_item, str):
276
+ prompt_item = prompt_item.item()
277
+ tokens, token_masks = self.tokenizer.tokenize(prompt_item, state_item)
278
+ token_list.append(tokens)
279
+ mask_list.append(token_masks)
280
+ tokens = np.stack(token_list)
281
+ token_masks = np.stack(mask_list)
282
+ else:
283
+ if not isinstance(prompt, str):
284
+ prompt = prompt.item()
285
+ tokens, token_masks = self.tokenizer.tokenize(prompt, state)
286
+
287
+ return {**data, "tokenized_prompt": tokens, "tokenized_prompt_mask": token_masks}
288
+
289
+
290
+ @dataclasses.dataclass(frozen=True)
291
+ class TokenizeFASTInputs(DataTransformFn):
292
+ tokenizer: _tokenizer.FASTTokenizer
293
+
294
+ def __call__(self, data: DataDict) -> DataDict:
295
+ if (prompt := data.pop("prompt", None)) is None:
296
+ raise ValueError("Prompt is required")
297
+
298
+ if not isinstance(prompt, str):
299
+ prompt = prompt.item()
300
+
301
+ state, actions = data["state"], data.get("actions")
302
+ tokens, token_mask, ar_mask, loss_mask = self.tokenizer.tokenize(prompt, state, actions)
303
+ return {
304
+ **data,
305
+ "tokenized_prompt": tokens,
306
+ "tokenized_prompt_mask": token_mask,
307
+ "token_ar_mask": ar_mask,
308
+ "token_loss_mask": loss_mask,
309
+ }
310
+
311
+
312
+ @dataclasses.dataclass(frozen=True)
313
+ class ExtractFASTActions(DataTransformFn):
314
+ tokenizer: _tokenizer.FASTTokenizer
315
+ action_horizon: int
316
+ action_dim: int
317
+
318
+ def __call__(self, data: DataDict) -> DataDict:
319
+ if "actions" not in data:
320
+ return data
321
+ # Model outputs are saved in "actions", but for FAST models they represent tokens.
322
+ tokens = data.pop("actions")
323
+ actions = self.tokenizer.extract_actions(tokens.astype(np.int32), self.action_horizon, self.action_dim)
324
+ return {
325
+ **data,
326
+ "actions": actions,
327
+ }
328
+
329
+
330
+ @dataclasses.dataclass(frozen=True)
331
+ class PromptFromLeRobotTask(DataTransformFn):
332
+ """Extracts a prompt from the current LeRobot dataset task."""
333
+
334
+ # Contains the LeRobot dataset tasks (dataset.meta.tasks).
335
+ tasks: object
336
+
337
+ def _get_prompt(self, task_index: int) -> str | None:
338
+ if isinstance(self.tasks, Mapping):
339
+ prompt = self.tasks.get(task_index)
340
+ return None if prompt is None else str(prompt)
341
+
342
+ columns = getattr(self.tasks, "columns", None)
343
+ index = getattr(self.tasks, "index", None)
344
+ if columns is not None and index is not None and "task_index" in columns:
345
+ matches = index[self.tasks["task_index"] == task_index]
346
+ if len(matches) > 0:
347
+ return str(matches[0])
348
+
349
+ return None
350
+
351
+ def __call__(self, data: DataDict) -> DataDict:
352
+ if "task_index" not in data:
353
+ raise ValueError('Cannot extract prompt without "task_index"')
354
+
355
+ task_index = int(data["task_index"])
356
+ if (prompt := self._get_prompt(task_index)) is None:
357
+ raise ValueError(f"{task_index=} not found in task mapping: {self.tasks}")
358
+
359
+ return {**data, "prompt": prompt}
360
+
361
+
362
+ @dataclasses.dataclass(frozen=True)
363
+ class PadStatesAndActions(DataTransformFn):
364
+ """Zero-pads states and actions to the model action dimension."""
365
+
366
+ model_action_dim: int
367
+
368
+ def __call__(self, data: DataDict) -> DataDict:
369
+ data["state"] = pad_to_dim(data["state"], self.model_action_dim, axis=-1)
370
+ if "actions" in data:
371
+ data["actions"] = pad_to_dim(data["actions"], self.model_action_dim, axis=-1)
372
+ return data
373
+
374
+
375
+ def flatten_dict(tree: at.PyTree) -> dict:
376
+ """Flatten a nested dictionary. Uses '/' as the separator."""
377
+ return traverse_util.flatten_dict(tree, sep="/")
378
+
379
+
380
+ def unflatten_dict(tree: dict) -> at.PyTree:
381
+ """Unflatten a flattened dictionary. Assumes that '/' was used as a separator."""
382
+ return traverse_util.unflatten_dict(tree, sep="/")
383
+
384
+
385
+ def transform_dict(patterns: Mapping[str, str | None], tree: at.PyTree) -> at.PyTree:
386
+ """Transform the structure of a nested dictionary using a set of patterns.
387
+
388
+ The transformation is defined using the `patterns` dictionary. The keys are the
389
+ input keys that should be matched and the values are the new names inside the output
390
+ dictionary. If the value is None, the input key is removed.
391
+
392
+ Both keys and values should represent flattened paths using '/' as the separator.
393
+ Keys can be regular expressions and values can include backreferences to the
394
+ matched groups (see `re.sub` for more details). Note that the regular expression
395
+ must match the entire key.
396
+
397
+ The order inside the `patterns` dictionary is important. Only the first pattern that
398
+ matches the input key will be used.
399
+
400
+ See unit tests for more examples.
401
+
402
+ Args:
403
+ patterns: A mapping from old keys to new keys.
404
+ tree: The nested dictionary to transform.
405
+
406
+ Returns:
407
+ The transformed nested dictionary.
408
+ """
409
+ data = flatten_dict(tree)
410
+
411
+ # Compile the patterns.
412
+ compiled = {re.compile(k): v for k, v in patterns.items()}
413
+
414
+ output = {}
415
+ for k in data:
416
+ for pattern, repl in compiled.items():
417
+ if pattern.fullmatch(k):
418
+ new_k = pattern.sub(repl, k, count=1) if repl is not None else None
419
+ break
420
+ else:
421
+ # Use the original key if no match is found.
422
+ new_k = k
423
+
424
+ if new_k is not None:
425
+ if new_k in output:
426
+ raise ValueError(f"Key '{new_k}' already exists in output")
427
+ output[new_k] = data[k]
428
+
429
+ # Validate the output structure to make sure that it can be unflattened.
430
+ names = sorted(output)
431
+ for i in range(len(names) - 1):
432
+ name, next_name = names[i : i + 2]
433
+ if next_name.startswith(name + "/"):
434
+ raise ValueError(f"Leaf '{name}' aliases a node of '{next_name}'")
435
+
436
+ return unflatten_dict(output)
437
+
438
+
439
+ def apply_tree(
440
+ tree: at.PyTree[T], selector: at.PyTree[S], fn: Callable[[T, S], T], *, strict: bool = False
441
+ ) -> at.PyTree[T]:
442
+ tree = flatten_dict(tree)
443
+ selector = flatten_dict(selector)
444
+
445
+ def transform(k: str, v: T) -> T:
446
+ if k in selector:
447
+ return fn(v, selector[k])
448
+ return v
449
+
450
+ if strict:
451
+ for k in selector:
452
+ if k not in tree:
453
+ raise ValueError(f"Selector key {k} not found in tree")
454
+
455
+ return unflatten_dict({k: transform(k, v) for k, v in tree.items()})
456
+
457
+
458
+ def pad_to_dim(x: np.ndarray, target_dim: int, axis: int = -1, value: float = 0.0) -> np.ndarray:
459
+ """Pad an array to the target dimension with zeros along the specified axis."""
460
+ current_dim = x.shape[axis]
461
+ if current_dim < target_dim:
462
+ pad_width = [(0, 0)] * len(x.shape)
463
+ pad_width[axis] = (0, target_dim - current_dim)
464
+ return np.pad(x, pad_width, constant_values=value)
465
+ return x
466
+
467
+
468
+ def make_bool_mask(*dims: int) -> tuple[bool, ...]:
469
+ """Make a boolean mask for the given dimensions.
470
+
471
+ Example:
472
+ make_bool_mask(2, -2, 2) == (True, True, False, False, True, True)
473
+ make_bool_mask(2, 0, 2) == (True, True, True, True)
474
+
475
+ Args:
476
+ dims: The dimensions to make the mask for.
477
+
478
+ Returns:
479
+ A tuple of booleans.
480
+ """
481
+ result = []
482
+ for dim in dims:
483
+ if dim > 0:
484
+ result.extend([True] * (dim))
485
+ else:
486
+ result.extend([False] * (-dim))
487
+ return tuple(result)
488
+
489
+
490
+ def _assert_quantile_stats(norm_stats: at.PyTree[NormStats]) -> None:
491
+ for k, v in flatten_dict(norm_stats).items():
492
+ if v.q01 is None or v.q99 is None:
493
+ raise ValueError(
494
+ f"quantile stats must be provided if use_quantile_norm is True. Key {k} is missing q01 or q99."
495
+ )
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/transforms_test.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ import pytest
4
+
5
+ import openpi.models.tokenizer as _tokenizer
6
+ import openpi.transforms as _transforms
7
+
8
+
9
+ def test_repack_transform():
10
+ transform = _transforms.RepackTransform(
11
+ structure={
12
+ "a": {"b": "b/c"},
13
+ "d": "e/f",
14
+ }
15
+ )
16
+ item = {"b": {"c": 1}, "e": {"f": 2}}
17
+ assert transform(item) == {"a": {"b": 1}, "d": 2}
18
+
19
+
20
+ def test_delta_actions():
21
+ item = {"state": np.array([1, 2, 3]), "actions": np.array([[3, 4, 5], [5, 6, 7]])}
22
+
23
+ transform = _transforms.DeltaActions(mask=[False, True])
24
+ transformed = transform(item)
25
+
26
+ assert np.all(transformed["state"] == np.array([1, 2, 3]))
27
+ assert np.all(transformed["actions"] == np.array([[3, 2, 5], [5, 4, 7]]))
28
+
29
+
30
+ def test_delta_actions_noop():
31
+ item = {"state": np.array([1, 2, 3]), "actions": np.array([[3, 4, 5], [5, 6, 7]])}
32
+
33
+ # No-op when the mask is disabled.
34
+ transform = _transforms.DeltaActions(mask=None)
35
+ assert transform(item) is item
36
+
37
+ # No-op when there are no actions in the input.
38
+ del item["actions"]
39
+ transform = _transforms.DeltaActions(mask=[True, False])
40
+ assert transform(item) is item
41
+
42
+
43
+ def test_absolute_actions():
44
+ item = {"state": np.array([1, 2, 3]), "actions": np.array([[3, 4, 5], [5, 6, 7]])}
45
+
46
+ transform = _transforms.AbsoluteActions(mask=[False, True])
47
+ transformed = transform(item)
48
+
49
+ assert np.all(transformed["state"] == np.array([1, 2, 3]))
50
+ assert np.all(transformed["actions"] == np.array([[3, 6, 5], [5, 8, 7]]))
51
+
52
+
53
+ def test_absolute_actions_noop():
54
+ item = {"state": np.array([1, 2, 3]), "actions": np.array([[3, 4, 5], [5, 6, 7]])}
55
+
56
+ # No-op when the mask is disabled.
57
+ transform = _transforms.AbsoluteActions(mask=None)
58
+ assert transform(item) is item
59
+
60
+ # No-op when there are no actions in the input.
61
+ del item["actions"]
62
+ transform = _transforms.AbsoluteActions(mask=[True, False])
63
+ assert transform(item) is item
64
+
65
+
66
+ def test_make_bool_mask():
67
+ assert _transforms.make_bool_mask(2, -2, 2) == (True, True, False, False, True, True)
68
+ assert _transforms.make_bool_mask(2, 0, 2) == (True, True, True, True)
69
+
70
+
71
+ def test_tokenize_prompt():
72
+ tokenizer = _tokenizer.PaligemmaTokenizer(max_len=12)
73
+ transform = _transforms.TokenizePrompt(tokenizer)
74
+
75
+ data = transform({"prompt": "Hello, world!"})
76
+
77
+ tok_prompt, tok_mask = tokenizer.tokenize("Hello, world!")
78
+ assert np.allclose(tok_prompt, data["tokenized_prompt"])
79
+ assert np.allclose(tok_mask, data["tokenized_prompt_mask"])
80
+
81
+
82
+ def test_tokenize_scalar_array_prompt():
83
+ tokenizer = _tokenizer.PaligemmaTokenizer(max_len=12)
84
+ transform = _transforms.TokenizePrompt(tokenizer)
85
+
86
+ data = transform({"prompt": np.asarray("Fold the T-shirt.")})
87
+
88
+ tok_prompt, tok_mask = tokenizer.tokenize("Fold the T-shirt.")
89
+ assert np.allclose(tok_prompt, data["tokenized_prompt"])
90
+ assert np.allclose(tok_mask, data["tokenized_prompt_mask"])
91
+
92
+
93
+ def test_tokenize_no_prompt():
94
+ transform = _transforms.TokenizePrompt(_tokenizer.PaligemmaTokenizer())
95
+
96
+ with pytest.raises(ValueError, match="Prompt is required"):
97
+ transform({})
98
+
99
+
100
+ def test_transform_dict():
101
+ # Rename and remove keys.
102
+ input = {"a": {"b": 1, "c": 2}}
103
+ output = _transforms.transform_dict({"a/b": "a/c", "a/c": None}, input)
104
+ assert output == {"a": {"c": 1}}
105
+
106
+ # Raises and error since the renamed key conflicts with an existing key.
107
+ with pytest.raises(ValueError, match="Key 'a/c' already exists in output"):
108
+ _transforms.transform_dict({"a/b": "a/c"}, input)
109
+
110
+ # Full match is required and so nothing will be removed.
111
+ input = {"a": {"b": 1, "c": 2}}
112
+ output = _transforms.transform_dict({"a": None}, input)
113
+ assert output == input
114
+
115
+ # The regex matches the entire key and so the entire input will be removed.
116
+ input = {"a": {"b": 1, "c": 2}}
117
+ output = _transforms.transform_dict({"a.+": None}, input)
118
+ assert output == {}
119
+
120
+ # Replace keys using backreferences. All leaves named 'c' are replaced with 'd'.
121
+ input = {"a": {"b": 1, "c": 1}, "b": {"c": 2}}
122
+ output = _transforms.transform_dict({"(.+)/c": r"\1/d"}, input)
123
+ assert output == {"a": {"b": 1, "d": 1}, "b": {"d": 2}}
124
+
125
+
126
+ def test_extract_prompt_from_task():
127
+ transform = _transforms.PromptFromLeRobotTask({1: "Hello, world!"})
128
+
129
+ data = transform({"task_index": 1})
130
+ assert data["prompt"] == "Hello, world!"
131
+
132
+ with pytest.raises(ValueError, match="task_index=2 not found in task mapping"):
133
+ transform({"task_index": 2})
134
+
135
+
136
+ def test_extract_prompt_from_task_dataframe():
137
+ tasks = pd.DataFrame({"task_index": [0, 1]}, index=["Task zero", "Hello, world!"])
138
+ transform = _transforms.PromptFromLeRobotTask(tasks)
139
+
140
+ data = transform({"task_index": 1})
141
+ assert data["prompt"] == "Hello, world!"
real_inference/source/XPolicyLab/policy/Pi_05/openpi/uv.lock ADDED
The diff for this file is too large to render. See raw diff
 
real_inference/source/xpolicylab_local_changes.patch ADDED
@@ -0,0 +1,467 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/policy/ACT/imitate_episodes.py b/policy/ACT/imitate_episodes.py
2
+ index 9d87e43..f26be34 100644
3
+ --- a/policy/ACT/imitate_episodes.py
4
+ +++ b/policy/ACT/imitate_episodes.py
5
+ @@ -37,9 +37,13 @@ def main(args):
6
+ num_epochs = args["num_epochs"]
7
+
8
+ # get task parameters
9
+ - from constants import TASK_CONFIGS
10
+ -
11
+ - task_config = TASK_CONFIGS[ckpt_setting]
12
+ + aloha_manifest = os.environ.get("ALOHA_POLICY_MANIFEST")
13
+ + if aloha_manifest:
14
+ + task_config = {"dataset_dir": "", "num_episodes": 0, "episode_len": 0,
15
+ + "camera_names": ["cam_high", "cam_left_wrist", "cam_right_wrist"]}
16
+ + else:
17
+ + from constants import TASK_CONFIGS
18
+ + task_config = TASK_CONFIGS[ckpt_setting]
19
+ dataset_dir = task_config["dataset_dir"]
20
+ num_episodes = task_config["num_episodes"]
21
+ episode_len = task_config["episode_len"]
22
+ @@ -93,8 +97,11 @@ def main(args):
23
+ "save_freq": args['save_freq']
24
+ }
25
+
26
+ - train_dataloader, val_dataloader, stats, _ = load_data(dataset_dir, num_episodes, camera_names, batch_size_train,
27
+ - batch_size_val)
28
+ + if aloha_manifest:
29
+ + from aloha_dataset import act_load_data
30
+ + train_dataloader, val_dataloader, stats, _ = act_load_data(aloha_manifest, batch_size_train, batch_size_val, args["chunk_size"])
31
+ + else:
32
+ + train_dataloader, val_dataloader, stats, _ = load_data(dataset_dir, num_episodes, camera_names, batch_size_train, batch_size_val)
33
+
34
+ # save dataset stats
35
+ if not os.path.isdir(ckpt_dir):
36
+ @@ -204,6 +211,8 @@ def train_bc(train_dataloader, val_dataloader, config):
37
+ for k, v in epoch_summary.items():
38
+ summary_string += f"{k}: {v.item():.3f} "
39
+
40
+ + print(f"epoch {epoch + 1}/{num_epochs}: train_loss={epoch_summary['loss'].item():.6f} val_loss={epoch_val_loss.item():.6f}", flush=True)
41
+ +
42
+ if (epoch + 1) % config['save_freq'] == 0:
43
+ ckpt_path = os.path.join(ckpt_dir, f"policy_epoch_{epoch + 1}_seed_{seed}.ckpt")
44
+ torch.save(policy.state_dict(), ckpt_path)
45
+ @@ -211,6 +220,11 @@ def train_bc(train_dataloader, val_dataloader, config):
46
+ ckpt_path = os.path.join(ckpt_dir, f"policy_last.ckpt")
47
+ torch.save(policy.state_dict(), ckpt_path)
48
+
49
+ + if best_ckpt_info is not None:
50
+ + best_epoch, best_val_loss, best_state_dict = best_ckpt_info
51
+ + torch.save(best_state_dict, os.path.join(ckpt_dir, "policy_best.ckpt"))
52
+ + print(f"best validation: epoch {best_epoch + 1}, loss={best_val_loss.item():.6f}", flush=True)
53
+ +
54
+ # best_epoch, min_val_loss, best_state_dict = best_ckpt_info
55
+ # ckpt_path = os.path.join(ckpt_dir, f"policy_epoch_{best_epoch}_seed_{seed}.ckpt")
56
+ # torch.save(best_state_dict, ckpt_path)
57
+ diff --git a/policy/DP/diffusion_policy/dataset/robot_image_dataset.py b/policy/DP/diffusion_policy/dataset/robot_image_dataset.py
58
+ index 49ab621..17918e8 100644
59
+ --- a/policy/DP/diffusion_policy/dataset/robot_image_dataset.py
60
+ +++ b/policy/DP/diffusion_policy/dataset/robot_image_dataset.py
61
+ @@ -26,16 +26,21 @@ class RobotImageDataset(BaseImageDataset):
62
+ val_ratio=0.0,
63
+ batch_size=128,
64
+ max_train_episodes=None,
65
+ + aloha_manifest_split=False,
66
+ ):
67
+
68
+ super().__init__()
69
+ - self.replay_buffer = ReplayBuffer.copy_from_path(
70
+ - zarr_path,
71
+ - keys=["head_camera", "left_camera", "right_camera", "state", "action"],
72
+ - )
73
+ + if aloha_manifest_split:
74
+ + self.replay_buffer = ReplayBuffer.create_from_path(zarr_path, mode="r")
75
+ + if not self.replay_buffer.root.attrs.get("complete", False):
76
+ + raise ValueError("Incomplete Aloha Zarr conversion")
77
+ + else:
78
+ + self.replay_buffer = ReplayBuffer.copy_from_path(
79
+ + zarr_path, keys=["head_camera", "left_camera", "right_camera", "state", "action"])
80
+ + self.aloha_manifest_split = aloha_manifest_split
81
+
82
+ val_mask = get_val_mask(n_episodes=self.replay_buffer.n_episodes, val_ratio=val_ratio, seed=seed)
83
+ - train_mask = ~val_mask
84
+ + train_mask = np.asarray(self.replay_buffer.root["meta/train_mask"][:], dtype=bool) if aloha_manifest_split else ~val_mask
85
+ train_mask = downsample_mask(mask=train_mask, max_n=max_train_episodes, seed=seed)
86
+
87
+ self.sampler = SequenceSampler(
88
+ @@ -58,7 +63,8 @@ class RobotImageDataset(BaseImageDataset):
89
+ }
90
+ self.buffers_torch = {k: torch.from_numpy(v) for k, v in self.buffers.items()}
91
+ for v in self.buffers_torch.values():
92
+ - v.pin_memory()
93
+ + if torch.cuda.is_available():
94
+ + v.pin_memory()
95
+
96
+ def get_validation_dataset(self):
97
+ val_set = copy.copy(self)
98
+ @@ -73,10 +79,13 @@ class RobotImageDataset(BaseImageDataset):
99
+ return val_set
100
+
101
+ def get_normalizer(self, mode="limits", **kwargs):
102
+ - data = {
103
+ - "action": self.replay_buffer["action"],
104
+ - "agent_pos": self.replay_buffer["state"],
105
+ - }
106
+ + if self.aloha_manifest_split:
107
+ + ends = self.replay_buffer.episode_ends[:]
108
+ + starts = np.r_[0, ends[:-1]]
109
+ + data = {key: np.concatenate([self.replay_buffer[src][int(a):int(b)] for a, b, keep in zip(starts, ends, self.train_mask) if keep])
110
+ + for key, src in (("action", "action"), ("agent_pos", "state"))}
111
+ + else:
112
+ + data = {"action": self.replay_buffer["action"], "agent_pos": self.replay_buffer["state"]}
113
+ normalizer = LinearNormalizer()
114
+ normalizer.fit(data=data, last_n_dims=1, mode=mode, **kwargs)
115
+ normalizer["head_cam"] = get_image_range_normalizer()
116
+ @@ -115,6 +124,9 @@ class RobotImageDataset(BaseImageDataset):
117
+ sample = dict_apply(sample, torch.from_numpy)
118
+ return sample
119
+ elif isinstance(idx, np.ndarray):
120
+ + if self.aloha_manifest_split:
121
+ + samples = [self.sampler.sample_sequence(int(i)) for i in idx]
122
+ + return {key: torch.from_numpy(np.stack([s[key] for s in samples])) for key in samples[0]}
123
+ assert len(idx) == self.batch_size
124
+ for k, v in self.sampler.replay_buffer.items():
125
+ batch_sample_sequence(
126
+ diff --git a/policy/Pi_05/openpi/src/openpi/shared/download.py b/policy/Pi_05/openpi/src/openpi/shared/download.py
127
+ index 582f839..2931988 100644
128
+ --- a/policy/Pi_05/openpi/src/openpi/shared/download.py
129
+ +++ b/policy/Pi_05/openpi/src/openpi/shared/download.py
130
+ @@ -85,6 +85,16 @@ def maybe_download(url: str, *, force_download: bool = False, **kwargs) -> pathl
131
+ # Download the data to a local cache.
132
+ logger.info(f"Downloading {url} to {local_path}")
133
+ scratch_path = local_path.with_suffix(".partial")
134
+ + # A previously interrupted transfer can leave this scratch path
135
+ + # behind. fsspec then nests a fresh recursive download inside
136
+ + # it, while stale truncated shards remain at its root. Start a
137
+ + # new download from an empty scratch path instead.
138
+ + if scratch_path.exists():
139
+ + logger.warning(f"Removing stale partial download: {scratch_path}")
140
+ + if scratch_path.is_dir():
141
+ + shutil.rmtree(scratch_path)
142
+ + else:
143
+ + scratch_path.unlink()
144
+ # Route openpi-assets through gsutil to avoid gcsfs auth issues with this bucket.
145
+ # All other gs:// URLs (e.g. big_vision) continue to use gcsfs as normal.
146
+ if parsed.scheme == "gs" and parsed.netloc == "openpi-assets":
147
+ diff --git a/policy/Pi_05/openpi/src/openpi/training/config.py b/policy/Pi_05/openpi/src/openpi/training/config.py
148
+ index c6babbc..fbc7301 100644
149
+ --- a/policy/Pi_05/openpi/src/openpi/training/config.py
150
+ +++ b/policy/Pi_05/openpi/src/openpi/training/config.py
151
+ @@ -5,6 +5,7 @@ from collections.abc import Sequence
152
+ import dataclasses
153
+ import difflib
154
+ import logging
155
+ +import os
156
+ import pathlib
157
+ from typing import Any, Literal, Protocol, TypeAlias
158
+
159
+ @@ -20,8 +21,10 @@ import openpi.models.tokenizer as _tokenizer
160
+ import openpi.policies.aloha_policy as aloha_policy
161
+ import openpi.policies.droid_policy as droid_policy
162
+ import openpi.policies.libero_policy as libero_policy
163
+ +import openpi.policies.pika_bimanual_policy as pika_bimanual_policy
164
+ import openpi.policies.wuji_policy as wuji_policy
165
+ import openpi.shared.download as _download
166
+ +import openpi.shared.nnx_utils as nnx_utils
167
+ import openpi.shared.normalize as _normalize
168
+ import openpi.training.droid_rlds_dataset as droid_rlds_dataset
169
+ import openpi.training.misc.polaris_config as polaris_config
170
+ @@ -71,6 +74,11 @@ class AssetsConfig:
171
+ class DataConfig:
172
+ # LeRobot repo id. If None, fake data will be created.
173
+ repo_id: str | None = None
174
+ + # Optional physical root for a local LeRobot dataset. This avoids requiring
175
+ + # the data to be placed below HF_LEROBOT_HOME/<repo_id>.
176
+ + lerobot_root: str | None = None
177
+ + # Optional subset of LeRobot episode indices, applied before sampling.
178
+ + episode_indices: Sequence[int] | None = None
179
+ # Video decoder backend for LeRobot datasets. Forced to pyav by default because
180
+ # torchcodec is present in some environments but not fully functional at runtime.
181
+ video_backend: Literal["pyav", "torchcodec", "video_reader"] = "pyav"
182
+ @@ -424,6 +432,73 @@ class LeRobotWujiDataConfig(DataConfigFactory):
183
+ )
184
+
185
+
186
+ +@dataclasses.dataclass(frozen=True)
187
+ +class LeRobotPikaBimanualDataConfig(DataConfigFactory):
188
+ + """Local LeRobot configuration for two-fisheye, 14-D dual-arm Pika data.
189
+ +
190
+ + The converter writes absolute next-state targets, therefore action deltas
191
+ + deliberately remain disabled. ``PIKA_LEROBOT_ROOT`` points at the physical
192
+ + local dataset root and can be overridden with ``local_dataset_root``.
193
+ + """
194
+ +
195
+ + local_dataset_root: str | None = None
196
+ + episode_indices: Sequence[int] = tuple(range(50))
197
+ + default_prompt: str = "Fold the T-shirt."
198
+ + action_sequence_keys: Sequence[str] = ("action",)
199
+ + # Relative mode removes the arbitrary Pika/Lighthouse world origin. State
200
+ + # is anchored at the current left Pika and each action is a full local
201
+ + # SE(3) transform from that arm's current pose to its future target.
202
+ + relative_pose: bool = False
203
+ +
204
+ + @override
205
+ + def create(self, assets_dirs: pathlib.Path, model_config: _model.BaseModelConfig) -> DataConfig:
206
+ + if model_config.action_dim != pika_bimanual_policy.PIKA_BIMANUAL_ACTION_DIM:
207
+ + raise ValueError(
208
+ + "Pika bimanual config requires model.action_dim="
209
+ + f"{pika_bimanual_policy.PIKA_BIMANUAL_ACTION_DIM}, got {model_config.action_dim}."
210
+ + )
211
+ + dataset_root = self.local_dataset_root or os.environ.get("PIKA_LEROBOT_ROOT")
212
+ + if not dataset_root:
213
+ + raise ValueError(
214
+ + "Set PIKA_LEROBOT_ROOT to the local converted LeRobot dataset, or set "
215
+ + "data.local_dataset_root explicitly."
216
+ + )
217
+ +
218
+ + repack_transform = _transforms.Group(
219
+ + inputs=[
220
+ + _transforms.RepackTransform(
221
+ + {
222
+ + "observation/image": "observation.images.cam_left_wrist",
223
+ + "observation/wrist_image": "observation.images.cam_right_wrist",
224
+ + "observation/state": "observation.state",
225
+ + "actions": "action",
226
+ + "prompt": "prompt",
227
+ + }
228
+ + )
229
+ + ]
230
+ + )
231
+ + data_transforms = _transforms.Group(
232
+ + inputs=[
233
+ + pika_bimanual_policy.PikaBimanualInputs(
234
+ + model_type=model_config.model_type,
235
+ + relative_pose=self.relative_pose,
236
+ + )
237
+ + ],
238
+ + outputs=[pika_bimanual_policy.PikaBimanualOutputs()],
239
+ + )
240
+ +
241
+ + return dataclasses.replace(
242
+ + self.create_base_config(assets_dirs, model_config),
243
+ + lerobot_root=dataset_root,
244
+ + episode_indices=self.episode_indices,
245
+ + repack_transforms=repack_transform,
246
+ + data_transforms=data_transforms,
247
+ + model_transforms=ModelTransformFactory(default_prompt=self.default_prompt)(model_config),
248
+ + action_sequence_keys=self.action_sequence_keys,
249
+ + prompt_from_task=True,
250
+ + )
251
+ +
252
+ +
253
+ @dataclasses.dataclass(frozen=True)
254
+ class RLDSDroidDataConfig(DataConfigFactory):
255
+ """
256
+ @@ -631,7 +706,43 @@ class TrainConfig:
257
+
258
+
259
+ # Use `get_config` if you need to get a config by name in your code.
260
+ +_PIKA_BIMANUAL_LORA_MODEL = pi0_config.Pi0Config(
261
+ + pi05=True,
262
+ + action_dim=14,
263
+ + action_horizon=16,
264
+ + max_token_len=256,
265
+ + # Train LoRA adapters in both the PaliGemma backbone and action expert.
266
+ + paligemma_variant="gemma_2b_lora",
267
+ + action_expert_variant="gemma_300m_lora",
268
+ +)
269
+ +
270
+ +_ALOHA_GARMENT_MODEL = pi0_config.Pi0Config(
271
+ + pi05=True, paligemma_variant="gemma_2b_lora", action_expert_variant="gemma_300m_lora")
272
+ +_ALOHA_GARMENT_ROOT = "/data2/wushuang/my_projects/Aloha2-CollectData-DeformableObject/policy_training"
273
+ +
274
+ +def _aloha_garment_data(split: str) -> LeRobotAlohaDataConfig:
275
+ + return LeRobotAlohaDataConfig(
276
+ + repo_id=f"local/aloha_garment_{split}",
277
+ + assets=AssetsConfig(asset_id="aloha_garment"),
278
+ + base_config=DataConfig(lerobot_root=f"{_ALOHA_GARMENT_ROOT}/lerobot_{split}", prompt_from_task=True),
279
+ + use_delta_joint_actions=False, adapt_to_pi=False,
280
+ + repack_transforms=_transforms.Group(inputs=[_transforms.RepackTransform({
281
+ + "images": {"cam_high": "observation.images.cam_high", "cam_left_wrist": "observation.images.cam_left_wrist", "cam_right_wrist": "observation.images.cam_right_wrist"},
282
+ + "state": "observation.state", "actions": "action", "prompt": "prompt"})]),
283
+ + )
284
+ +
285
+ _CONFIGS = [
286
+ + TrainConfig(
287
+ + name="pi05_aloha_garment_lora", model=_ALOHA_GARMENT_MODEL,
288
+ + freeze_filter=nnx.Any(
289
+ + _ALOHA_GARMENT_MODEL.get_freeze_filter(),
290
+ + nnx_utils.PathRegex("PaliGemma/img/.*"),
291
+ + ),
292
+ + ema_decay=None,
293
+ + data=_aloha_garment_data("train"),
294
+ + weight_loader=weight_loaders.CheckpointWeightLoader("/data2/wushuang/.cache/openpi/openpi-assets/checkpoints/pi05_base/params"),
295
+ + batch_size=2, num_workers=2, wandb_enabled=False,
296
+ + ),
297
+ TrainConfig(
298
+ name="pi05_base_aloha_full_sim_arx-x5_seed_0",
299
+ model=pi0_config.Pi0Config(pi05=True),
300
+ @@ -768,6 +879,132 @@ _CONFIGS = [
301
+ decay_lr=5e-6,
302
+ ),
303
+ ),
304
+ + # Pika dual-arm T-shirt folding: 14-D absolute next-state targets at 10 Hz.
305
+ + TrainConfig(
306
+ + name="pi05_pika_bimanual_fisheye",
307
+ + model=pi0_config.Pi0Config(pi05=True, action_dim=14, action_horizon=16, max_token_len=256),
308
+ + data=LeRobotPikaBimanualDataConfig(
309
+ + repo_id="pika/fold_cloth_0910_bimanual_fisheye",
310
+ + # Must match compute_norm_stats.py, which writes below repo_id.
311
+ + assets=AssetsConfig(asset_id="pika/fold_cloth_0910_bimanual_fisheye"),
312
+ + ),
313
+ + weight_loader=weight_loaders.PartialCheckpointWeightLoader(
314
+ + "gs://openpi-assets/checkpoints/pi05_base/params"
315
+ + ),
316
+ + # The launchers set this to pika_manip/data/openpi_assets. Keeping the
317
+ + # default permits a standalone OpenPI checkout to use ./assets instead.
318
+ + assets_base_dir=os.environ.get("PIKA_OPENPI_ASSETS_BASE_DIR", "./assets"),
319
+ + num_train_steps=30_000,
320
+ + batch_size=64,
321
+ + num_workers=4,
322
+ + lr_schedule=_optimizer.CosineDecaySchedule(
323
+ + warmup_steps=1_000,
324
+ + peak_lr=5e-5,
325
+ + decay_steps=30_000,
326
+ + decay_lr=5e-6,
327
+ + ),
328
+ + ),
329
+ + # Single-GPU-friendly LoRA alternative to the full Pika fine-tune above.
330
+ + # It reuses the same local 50-episode train split and normalization stats.
331
+ + TrainConfig(
332
+ + name="pi05_pika_bimanual_fisheye_lora",
333
+ + model=_PIKA_BIMANUAL_LORA_MODEL,
334
+ + freeze_filter=nnx.Any(
335
+ + _PIKA_BIMANUAL_LORA_MODEL.get_freeze_filter(),
336
+ + # The ViT is not a LoRA module in OpenPI. Freeze it explicitly so
337
+ + # this is adapter + Pika-projection tuning rather than an implicit
338
+ + # full visual-backbone fine-tune.
339
+ + nnx_utils.PathRegex("PaliGemma/img/.*"),
340
+ + ),
341
+ + data=LeRobotPikaBimanualDataConfig(
342
+ + repo_id="pika/fold_cloth_0910_bimanual_fisheye",
343
+ + # Reuse stats generated by prepare_pi05_pika_bimanual.sh for the
344
+ + # full configuration; data semantics are identical.
345
+ + assets=AssetsConfig(
346
+ + assets_dir=os.path.join(
347
+ + os.environ.get("PIKA_OPENPI_ASSETS_BASE_DIR", "./assets"),
348
+ + "pi05_pika_bimanual_fisheye",
349
+ + ),
350
+ + asset_id="pika/fold_cloth_0910_bimanual_fisheye",
351
+ + ),
352
+ + ),
353
+ + weight_loader=weight_loaders.PartialCheckpointWeightLoader(
354
+ + "gs://openpi-assets/checkpoints/pi05_base/params"
355
+ + ),
356
+ + # EMA would update and retain a second copy of every frozen base weight
357
+ + # on every step. It is prohibitively expensive for single-GPU LoRA and
358
+ + # provides little value for this small, task-specific dataset.
359
+ + ema_decay=None,
360
+ + # Conservative starting point for one RTX 4090. The LoRA launcher
361
+ + # defaults to this value but users may override BATCH_SIZE.
362
+ + num_train_steps=30_000,
363
+ + batch_size=4,
364
+ + num_workers=4,
365
+ + lr_schedule=_optimizer.CosineDecaySchedule(
366
+ + warmup_steps=1_000,
367
+ + peak_lr=5e-5,
368
+ + decay_steps=30_000,
369
+ + decay_lr=5e-6,
370
+ + ),
371
+ + ),
372
+ + # Relative-pose Pika dual-arm configuration. The underlying LeRobot data
373
+ + # deliberately remains lossless absolute pose data; the data transform
374
+ + # converts it to a current-frame SE(3) representation before computing
375
+ + # normalization statistics and before every training/inference call.
376
+ + TrainConfig(
377
+ + name="pi05_pika_bimanual_fisheye_relative",
378
+ + model=pi0_config.Pi0Config(pi05=True, action_dim=14, action_horizon=16, max_token_len=256),
379
+ + data=LeRobotPikaBimanualDataConfig(
380
+ + repo_id="pika/fold_cloth_0910_bimanual_fisheye",
381
+ + assets=AssetsConfig(asset_id="pika/fold_cloth_0910_bimanual_fisheye"),
382
+ + relative_pose=True,
383
+ + ),
384
+ + weight_loader=weight_loaders.PartialCheckpointWeightLoader(
385
+ + "gs://openpi-assets/checkpoints/pi05_base/params"
386
+ + ),
387
+ + assets_base_dir=os.environ.get("PIKA_OPENPI_ASSETS_BASE_DIR", "./assets"),
388
+ + num_train_steps=30_000,
389
+ + batch_size=64,
390
+ + num_workers=4,
391
+ + lr_schedule=_optimizer.CosineDecaySchedule(
392
+ + warmup_steps=1_000,
393
+ + peak_lr=5e-5,
394
+ + decay_steps=30_000,
395
+ + decay_lr=5e-6,
396
+ + ),
397
+ + ),
398
+ + TrainConfig(
399
+ + name="pi05_pika_bimanual_fisheye_relative_lora",
400
+ + model=_PIKA_BIMANUAL_LORA_MODEL,
401
+ + freeze_filter=nnx.Any(
402
+ + _PIKA_BIMANUAL_LORA_MODEL.get_freeze_filter(),
403
+ + nnx_utils.PathRegex("PaliGemma/img/.*"),
404
+ + ),
405
+ + data=LeRobotPikaBimanualDataConfig(
406
+ + repo_id="pika/fold_cloth_0910_bimanual_fisheye",
407
+ + assets=AssetsConfig(
408
+ + assets_dir=os.path.join(
409
+ + os.environ.get("PIKA_OPENPI_ASSETS_BASE_DIR", "./assets"),
410
+ + "pi05_pika_bimanual_fisheye_relative",
411
+ + ),
412
+ + asset_id="pika/fold_cloth_0910_bimanual_fisheye",
413
+ + ),
414
+ + relative_pose=True,
415
+ + ),
416
+ + weight_loader=weight_loaders.PartialCheckpointWeightLoader(
417
+ + "gs://openpi-assets/checkpoints/pi05_base/params"
418
+ + ),
419
+ + ema_decay=None,
420
+ + num_train_steps=30_000,
421
+ + batch_size=4,
422
+ + num_workers=4,
423
+ + lr_schedule=_optimizer.CosineDecaySchedule(
424
+ + warmup_steps=1_000,
425
+ + peak_lr=5e-5,
426
+ + decay_steps=30_000,
427
+ + decay_lr=5e-6,
428
+ + ),
429
+ + ),
430
+ ]
431
+
432
+ if len({config.name for config in _CONFIGS}) != len(_CONFIGS):
433
+ diff --git a/policy/Pi_05/openpi/src/openpi/training/data_loader.py b/policy/Pi_05/openpi/src/openpi/training/data_loader.py
434
+ index bf67dd1..e2563dc 100644
435
+ --- a/policy/Pi_05/openpi/src/openpi/training/data_loader.py
436
+ +++ b/policy/Pi_05/openpi/src/openpi/training/data_loader.py
437
+ @@ -143,9 +143,11 @@ def create_torch_dataset(
438
+ if repo_id == "fake":
439
+ return FakeDataset(model_config, num_samples=1024)
440
+
441
+ - dataset_meta = lerobot_dataset.LeRobotDatasetMetadata(repo_id)
442
+ + dataset_meta = lerobot_dataset.LeRobotDatasetMetadata(repo_id, root=data_config.lerobot_root)
443
+ dataset = lerobot_dataset.LeRobotDataset(
444
+ data_config.repo_id,
445
+ + root=data_config.lerobot_root,
446
+ + episodes=list(data_config.episode_indices) if data_config.episode_indices is not None else None,
447
+ delta_timestamps={
448
+ key: [t / dataset_meta.fps for t in range(action_horizon)] for key in data_config.action_sequence_keys
449
+ },
450
+ diff --git a/policy/Pi_05/openpi/src/openpi/transforms.py b/policy/Pi_05/openpi/src/openpi/transforms.py
451
+ index b01e9db..71badd6 100644
452
+ --- a/policy/Pi_05/openpi/src/openpi/transforms.py
453
+ +++ b/policy/Pi_05/openpi/src/openpi/transforms.py
454
+ @@ -253,7 +253,12 @@ class TokenizePrompt(DataTransformFn):
455
+ if (prompt := data.pop("prompt", None)) is None:
456
+ raise ValueError("Prompt is required")
457
+
458
+ - is_batched_prompt = isinstance(prompt, (list, np.ndarray, jax.Array)) and not isinstance(prompt, str)
459
+ + # InjectDefaultPrompt stores a single default string as a zero-dimensional
460
+ + # ndarray. Treat that as a scalar prompt, not as a batch (``list`` on a
461
+ + # 0-D array raises TypeError during policy inference).
462
+ + is_batched_prompt = isinstance(prompt, list) or (
463
+ + isinstance(prompt, (np.ndarray, jax.Array)) and np.ndim(prompt) > 0
464
+ + )
465
+
466
+ if self.discrete_state_input:
467
+ if (state := data.get("state", None)) is None:
real_inference/verify_files.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Check a transferred package against its SHA-256 manifest."""
3
+ from pathlib import Path
4
+ import hashlib
5
+ import sys
6
+
7
+ root=Path(__file__).resolve().parent
8
+ failures=[];count=0
9
+ for line in (root/'manifest.sha256').read_text().splitlines():
10
+ digest,sep,rel=line.partition(' ')
11
+ if not sep or len(digest)!=64:
12
+ raise ValueError(f'Invalid manifest line: {line!r}')
13
+ path=(root/rel).resolve()
14
+ if not path.is_relative_to(root) or not path.is_file():
15
+ failures.append((rel,'missing or invalid path'));continue
16
+ h=hashlib.sha256()
17
+ with path.open('rb') as f:
18
+ for chunk in iter(lambda:f.read(8*1024*1024),b''):h.update(chunk)
19
+ count+=1
20
+ if h.hexdigest()!=digest:failures.append((rel,'SHA-256 mismatch'))
21
+ if path.stat().st_size>100_000_000:print(f'checked {rel}',flush=True)
22
+ if failures:
23
+ for rel,reason in failures:print(f'FAIL {rel}: {reason}',file=sys.stderr)
24
+ raise SystemExit(1)
25
+ print(f'OK: {count} files match manifest.sha256')