liujinxin commited on
Commit
d7cc125
·
1 Parent(s): ee45955
README.md CHANGED
@@ -1,5 +1,9 @@
1
  # robotodo
2
 
 
 
 
 
3
  ## TODO
4
  - https://github.com/RoboTwin-Platform/RoboTwin
5
 
 
1
  # robotodo
2
 
3
+ ## Installation
4
+ The package can be directly installed using pip.
5
+ See https://pip.pypa.io/en/stable/cli/pip_install/#examples.
6
+
7
  ## TODO
8
  - https://github.com/RoboTwin-Platform/RoboTwin
9
 
{packages → __todo__}/arrayspecs/__init__.py RENAMED
File without changes
{packages → __todo__}/arrayspecs/base.py RENAMED
File without changes
{packages → __todo__}/arrayspecs/enum.py RENAMED
File without changes
{packages → __todo__}/arrayspecs/number.py RENAMED
File without changes
{packages → __todo__}/arrayspecs/struct.py RENAMED
File without changes
{packages → __todo__}/arrayspecs/tensor.py RENAMED
File without changes
__todo__/controllers_curobo/__init__.py ADDED
File without changes
__todo__/controllers_curobo/path_planner.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from curobo.types.robot import RobotConfig
2
+ from curobo.geom.types import WorldConfig
3
+
4
+ from curobo.types.math import Pose as CuroboPose
5
+ import time
6
+ from curobo.types.robot import JointState
7
+ from curobo.wrap.reacher.motion_gen import (
8
+ MotionGen,
9
+ MotionGenConfig,
10
+ MotionGenPlanConfig,
11
+ PoseCostMetric,
12
+ )
13
+ import torch
14
+ import yaml
15
+
16
+
17
+ class CuroboPlanner:
18
+
19
+ def __init__(
20
+ self,
21
+ robot_origin_pose,
22
+ active_joints_name,
23
+ all_joints,
24
+ yml_path=None,
25
+ ):
26
+ super().__init__()
27
+
28
+ if yml_path != None:
29
+ self.yml_path = yml_path
30
+ else:
31
+ raise ValueError("[Planner.py]: CuroboPlanner yml_path is None!")
32
+ self.robot_origion_pose = robot_origin_pose
33
+ self.active_joints_name = active_joints_name
34
+ self.all_joints = all_joints
35
+
36
+ # translate from baselink to arm's base
37
+ with open(self.yml_path, "r") as f:
38
+ yml_data = yaml.safe_load(f)
39
+ self.frame_bias = yml_data["planner"]["frame_bias"]
40
+
41
+ # motion generation
42
+ # TODO
43
+ WorldConfig(
44
+ mesh=[],
45
+ )
46
+
47
+
48
+ if True:
49
+ # TODO !!!!!! WorldConfig
50
+
51
+ world_config = {
52
+ # TODO "mesh"
53
+ "cuboid": {
54
+ "table": {
55
+ "dims": [0.7, 2, 0.04], # x, y, z
56
+ "pose": [
57
+ self.robot_origion_pose.p[1],
58
+ 0.0,
59
+ 0.74 - self.robot_origion_pose.p[2],
60
+ 1,
61
+ 0,
62
+ 0,
63
+ 0.0,
64
+ ], # x, y, z, qw, qx, qy, qz
65
+ },
66
+ }
67
+ }
68
+
69
+ # motion_gen_config = MotionGenConfig.load_from_robot_config(
70
+ # self.yml_path,
71
+ # world_config,
72
+ # interpolation_dt=1 / 250,
73
+ # num_trajopt_seeds=1,
74
+ # )
75
+ # self.motion_gen = MotionGen(motion_gen_config)
76
+ # self.motion_gen.warmup()
77
+
78
+ # TODO
79
+ # RobotConfig.from_basic(
80
+ # urdf_path=...,
81
+ # base_link=...,
82
+ # ee_link=...,
83
+ # )
84
+ RobotConfig
85
+
86
+
87
+ self._motion_gen = MotionGen(
88
+ MotionGenConfig.load_from_robot_config(
89
+ # TODO #######
90
+ robot_cfg=self.yml_path,
91
+ # #############
92
+ world_model=world_config,
93
+ interpolation_dt=1 / 250,
94
+ num_trajopt_seeds=1,
95
+ num_graph_seeds=1,
96
+ )
97
+ )
98
+ # TODO orig: self._motion_gen.warmup(batch=CONFIGS.ROTATE_NUM)
99
+ self._motion_gen.warmup()
100
+
101
+
__todo__/todo-arrayspecs-padding.ipynb ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "id": "d6701a90",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "import jax\n",
11
+ "import jax.numpy as jnp\n",
12
+ "from typing import List\n",
13
+ "\n",
14
+ "# TODO mv to pi0\n",
15
+ "@jax.jit\n",
16
+ "def pad_sequences(arrays: List[jnp.ndarray]):\n",
17
+ " \"\"\"\n",
18
+ " TODO doc\n",
19
+ " Converts a list of JAX arrays with unequal first dimensions into a masked array.\n",
20
+ " \n",
21
+ " Args:\n",
22
+ " - arrays: List of JAX arrays (arrays of unequal first dimension).\n",
23
+ " \n",
24
+ " Returns:\n",
25
+ " - result: Masked JAX array containing the stacked arrays.\n",
26
+ " - mask: Mask indicating the valid elements in the result.\n",
27
+ " \"\"\"\n",
28
+ "\n",
29
+ " # Determine first dimension shape\n",
30
+ " first_shape = (len(arrays), max(array.shape[0] for array in arrays))\n",
31
+ " \n",
32
+ " # Extract the shape of the remaining dimensions\n",
33
+ " rest_shapes = [array.shape[1:] for array in arrays]\n",
34
+ " assert len(set(rest_shapes)) == 1, \"All arrays must have the same shape except for the first dimension.\"\n",
35
+ " rest_shape = next(iter(rest_shapes))\n",
36
+ " \n",
37
+ " # Initialize the mask and the result array\n",
38
+ " mask = jnp.full(first_shape, False, dtype=jnp.bool)\n",
39
+ " result = jnp.empty((first_shape[0], first_shape[1], *rest_shape), dtype=jnp.result_type(*arrays))\n",
40
+ "\n",
41
+ " # Stack arrays and update the mask\n",
42
+ " for i, array in enumerate(arrays):\n",
43
+ " slices = tuple(slice(0, s) for s in array.shape)\n",
44
+ " mask = mask.at[i, slices[0]].set(True) \n",
45
+ " result = result.at[i, *slices].set(array) \n",
46
+ "\n",
47
+ " return result, mask\n",
48
+ "\n",
49
+ "\n",
50
+ "# TODO also pad_to(array, shape, ) # left or right; mode; etc...; return_mask: bool;\n",
51
+ "# TODO also pad_like; as shortcut for pad_to(array, array.shape, ...)"
52
+ ]
53
+ },
54
+ {
55
+ "cell_type": "code",
56
+ "execution_count": null,
57
+ "id": "62008809",
58
+ "metadata": {},
59
+ "outputs": [],
60
+ "source": []
61
+ },
62
+ {
63
+ "cell_type": "code",
64
+ "execution_count": null,
65
+ "id": "d09edf3c",
66
+ "metadata": {},
67
+ "outputs": [],
68
+ "source": []
69
+ },
70
+ {
71
+ "cell_type": "code",
72
+ "execution_count": 2,
73
+ "id": "82a66fa6",
74
+ "metadata": {},
75
+ "outputs": [],
76
+ "source": [
77
+ "import jax\n",
78
+ "\n",
79
+ "a = jax.numpy.empty((3, 3, 3))"
80
+ ]
81
+ },
82
+ {
83
+ "cell_type": "code",
84
+ "execution_count": 3,
85
+ "id": "9106c6b8",
86
+ "metadata": {},
87
+ "outputs": [
88
+ {
89
+ "data": {
90
+ "text/plain": [
91
+ "Array([[[1., 5., 2.],\n",
92
+ " [2., 3., 4.],\n",
93
+ " [4., 5., 6.]],\n",
94
+ "\n",
95
+ " [[1., 5., 2.],\n",
96
+ " [2., 3., 4.],\n",
97
+ " [4., 5., 6.]],\n",
98
+ "\n",
99
+ " [[1., 5., 2.],\n",
100
+ " [2., 3., 4.],\n",
101
+ " [4., 5., 6.]]], dtype=float32)"
102
+ ]
103
+ },
104
+ "execution_count": 3,
105
+ "metadata": {},
106
+ "output_type": "execute_result"
107
+ }
108
+ ],
109
+ "source": [
110
+ "a.at[...].set([\n",
111
+ " [1, 5, 2],\n",
112
+ " [2, 3, 4],\n",
113
+ " [4, 5, 6]\n",
114
+ "])"
115
+ ]
116
+ },
117
+ {
118
+ "cell_type": "code",
119
+ "execution_count": 7,
120
+ "id": "3beb05ad",
121
+ "metadata": {},
122
+ "outputs": [
123
+ {
124
+ "data": {
125
+ "text/plain": [
126
+ "Array([[1.],\n",
127
+ " [1.],\n",
128
+ " [0.]], dtype=float32)"
129
+ ]
130
+ },
131
+ "execution_count": 7,
132
+ "metadata": {},
133
+ "output_type": "execute_result"
134
+ }
135
+ ],
136
+ "source": [
137
+ "b = jax.numpy.ones((2, 1))\n",
138
+ "a = jax.numpy.zeros((3, 1))\n",
139
+ "\n",
140
+ "\n",
141
+ "a.at[tuple(slice(0, s) for s in b.shape)].set(b)"
142
+ ]
143
+ },
144
+ {
145
+ "cell_type": "code",
146
+ "execution_count": null,
147
+ "id": "e71c5a69",
148
+ "metadata": {},
149
+ "outputs": [],
150
+ "source": []
151
+ },
152
+ {
153
+ "cell_type": "code",
154
+ "execution_count": 12,
155
+ "id": "bf661386",
156
+ "metadata": {},
157
+ "outputs": [],
158
+ "source": [
159
+ "import gymnasium.spaces \n",
160
+ "from gymnasium.spaces.utils import flatten_space"
161
+ ]
162
+ },
163
+ {
164
+ "cell_type": "code",
165
+ "execution_count": null,
166
+ "id": "59c5085f",
167
+ "metadata": {},
168
+ "outputs": [],
169
+ "source": [
170
+ "# gymnasium.spaces.utils.flatten_space(target_spec[\"joint_states\"])"
171
+ ]
172
+ },
173
+ {
174
+ "cell_type": "code",
175
+ "execution_count": null,
176
+ "id": "5e4cad08",
177
+ "metadata": {},
178
+ "outputs": [
179
+ {
180
+ "data": {
181
+ "text/plain": [
182
+ "Box(-inf, inf, (2,), float32)"
183
+ ]
184
+ },
185
+ "execution_count": 18,
186
+ "metadata": {},
187
+ "output_type": "execute_result"
188
+ },
189
+ {
190
+ "ename": "",
191
+ "evalue": "",
192
+ "output_type": "error",
193
+ "traceback": [
194
+ "\u001b[1;31mThe Kernel crashed while executing code in the current cell or a previous cell. \n",
195
+ "\u001b[1;31mPlease review the code in the cell(s) to identify a possible cause of the failure. \n",
196
+ "\u001b[1;31mClick <a href='https://aka.ms/vscodeJupyterKernelCrash'>here</a> for more info. \n",
197
+ "\u001b[1;31mView Jupyter <a href='command:jupyter.viewOutput'>log</a> for further details."
198
+ ]
199
+ }
200
+ ],
201
+ "source": [
202
+ "flatten_space(gymnasium.spaces.Dict({\n",
203
+ " # \"images\": gymnasium.spaces.Box(low=0., high=1., shape=(1, 224, 224, 3)),\n",
204
+ " # \"text\": gymnasium.spaces.Text(max_length=48),\n",
205
+ " \"joint_state\": gymnasium.spaces.Dict({\n",
206
+ " \"todo\": gymnasium.spaces.Box(low=-float(\"inf\"), high=float(\"inf\"), shape=()),\n",
207
+ " }),\n",
208
+ "}))\n",
209
+ "\n",
210
+ "flatten_space(\n",
211
+ " gymnasium.spaces.Box(low=-float(\"inf\"), high=float(\"inf\"), shape=(2,))\n",
212
+ ")"
213
+ ]
214
+ },
215
+ {
216
+ "cell_type": "code",
217
+ "execution_count": 17,
218
+ "id": "8d6fbe4a",
219
+ "metadata": {},
220
+ "outputs": [
221
+ {
222
+ "data": {
223
+ "text/plain": [
224
+ "{'joint_state': array([1., 2.], dtype=float32)}"
225
+ ]
226
+ },
227
+ "execution_count": 17,
228
+ "metadata": {},
229
+ "output_type": "execute_result"
230
+ }
231
+ ],
232
+ "source": [
233
+ "gymnasium.spaces.unflatten(\n",
234
+ " gymnasium.spaces.Dict({\n",
235
+ " \"joint_state\": gymnasium.spaces.Box(low=-float(\"inf\"), high=float(\"inf\"), shape=(2,)),\n",
236
+ " }),\n",
237
+ " jax.numpy.array([1.0, 2.0])\n",
238
+ ")"
239
+ ]
240
+ }
241
+ ],
242
+ "metadata": {
243
+ "kernelspec": {
244
+ "display_name": "Python 3",
245
+ "language": "python",
246
+ "name": "python3"
247
+ },
248
+ "language_info": {
249
+ "codemirror_mode": {
250
+ "name": "ipython",
251
+ "version": 3
252
+ },
253
+ "file_extension": ".py",
254
+ "mimetype": "text/x-python",
255
+ "name": "python",
256
+ "nbconvert_exporter": "python",
257
+ "pygments_lexer": "ipython3",
258
+ "version": "3.11.13"
259
+ }
260
+ },
261
+ "nbformat": 4,
262
+ "nbformat_minor": 5
263
+ }
__todo__/todo-arrayspecs-v1.ipynb ADDED
@@ -0,0 +1,705 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "id": "563c017a",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "class BaseSpec:\n",
11
+ " # TODO traceback???\n",
12
+ " def validate(self, value):\n",
13
+ " ...\n",
14
+ "\n",
15
+ " def sample(self, rng):\n",
16
+ " ...\n",
17
+ "\n",
18
+ "# TODO impl: stack(specs: Sequence[BaseSpec]) -> BaseSpec"
19
+ ]
20
+ },
21
+ {
22
+ "cell_type": "code",
23
+ "execution_count": null,
24
+ "id": "7cd9be77",
25
+ "metadata": {},
26
+ "outputs": [],
27
+ "source": [
28
+ "from typing import Any, Sequence, Mapping\n",
29
+ "\n",
30
+ "import jax.numpy\n",
31
+ "\n",
32
+ "# TODO ShapeSpec ???\n",
33
+ "\n",
34
+ "class BoxSpec:\n",
35
+ " def __init__(\n",
36
+ " self,\n",
37
+ " low: jax.numpy.ndarray = -jax.numpy.inf, \n",
38
+ " high: jax.numpy.ndarray = +jax.numpy.inf,\n",
39
+ " shape: int | Sequence[int | None] | Mapping[Any, int | Sequence[int] | None] | None = None,\n",
40
+ " dtype: str | None = None, # or type...\n",
41
+ " ):\n",
42
+ " self.low, self.high = jax.numpy.broadcast_arrays(low, high)\n",
43
+ "\n",
44
+ " # TODO \n",
45
+ " if isinstance(shape, int):\n",
46
+ " self.shape = int(shape)\n",
47
+ " elif isinstance(shape, Sequence):\n",
48
+ " self.shape = tuple(shape)\n",
49
+ " elif isinstance(shape, Mapping):\n",
50
+ " self.shape = shape\n",
51
+ " elif shape is None:\n",
52
+ " self.shape = self.low.shape\n",
53
+ " else:\n",
54
+ " raise TypeError(f\"Invalid shape: {shape}\")\n",
55
+ "\n",
56
+ " if dtype is None:\n",
57
+ " self.dtype = self.low.dtype\n",
58
+ " else: \n",
59
+ " self.dtype = jax.numpy.dtype(dtype)\n",
60
+ "\n",
61
+ " def __repr__(self):\n",
62
+ " return f\"BoxSpec(low={self.low}, high={self.high}, shape={self.shape}, dtype={self.dtype})\"\n",
63
+ "\n",
64
+ " # TODO\n",
65
+ " def unrag(self, data):\n",
66
+ " raise NotImplementedError\n",
67
+ "\n",
68
+ " # TODO\n",
69
+ " def sample(self, rng=None):\n",
70
+ " # TODO !!!!!\n",
71
+ " return jax.numpy.empty(self.shape, dtype=self.dtype)\n",
72
+ " raise NotImplementedError\n",
73
+ "\n",
74
+ " def validate(self, data):\n",
75
+ " raise NotImplementedError\n",
76
+ "\n",
77
+ " def __getitem__(self, key):\n",
78
+ " raise NotImplementedError"
79
+ ]
80
+ },
81
+ {
82
+ "cell_type": "code",
83
+ "execution_count": null,
84
+ "id": "40ab11e4",
85
+ "metadata": {},
86
+ "outputs": [],
87
+ "source": [
88
+ "# TODO\n",
89
+ "# shape=(ScalarSpec(0, 10), 12, 3, 5)\n",
90
+ "# shape=((..., ), 3, 4) # ragged\n",
91
+ "# shape=((0, 2, 5), 3, 4) # ragged"
92
+ ]
93
+ },
94
+ {
95
+ "cell_type": "code",
96
+ "execution_count": 1,
97
+ "id": "62a3807c",
98
+ "metadata": {},
99
+ "outputs": [
100
+ {
101
+ "data": {
102
+ "text/plain": [
103
+ "0j"
104
+ ]
105
+ },
106
+ "execution_count": 1,
107
+ "metadata": {},
108
+ "output_type": "execute_result"
109
+ }
110
+ ],
111
+ "source": [
112
+ "0j"
113
+ ]
114
+ },
115
+ {
116
+ "cell_type": "code",
117
+ "execution_count": null,
118
+ "id": "91a03edc",
119
+ "metadata": {},
120
+ "outputs": [
121
+ {
122
+ "data": {
123
+ "text/plain": [
124
+ "BoxSpec(low=-inf, high=inf, shape=(None, None, 12, 3, 4), dtype=int64)"
125
+ ]
126
+ },
127
+ "execution_count": 4,
128
+ "metadata": {},
129
+ "output_type": "execute_result"
130
+ }
131
+ ],
132
+ "source": [
133
+ "BoxSpec(shape=(None, 3, None, 12, 3, 4), dtype=int)"
134
+ ]
135
+ },
136
+ {
137
+ "cell_type": "code",
138
+ "execution_count": null,
139
+ "id": "79a809db",
140
+ "metadata": {},
141
+ "outputs": [],
142
+ "source": [
143
+ "# TODO\n",
144
+ "# BoxSpec.pad()"
145
+ ]
146
+ },
147
+ {
148
+ "cell_type": "code",
149
+ "execution_count": null,
150
+ "id": "198b68d6",
151
+ "metadata": {},
152
+ "outputs": [],
153
+ "source": [
154
+ "# shape should support BoxSpec?"
155
+ ]
156
+ },
157
+ {
158
+ "cell_type": "code",
159
+ "execution_count": null,
160
+ "id": "1d2e355c",
161
+ "metadata": {},
162
+ "outputs": [],
163
+ "source": [
164
+ "# TODO: (None, 3, None) to (<max_len>, 3, <max_len>)"
165
+ ]
166
+ },
167
+ {
168
+ "cell_type": "code",
169
+ "execution_count": null,
170
+ "id": "8bdee4dc",
171
+ "metadata": {},
172
+ "outputs": [],
173
+ "source": [
174
+ "import jaxtyping\n"
175
+ ]
176
+ },
177
+ {
178
+ "cell_type": "code",
179
+ "execution_count": null,
180
+ "id": "8a6a778b",
181
+ "metadata": {},
182
+ "outputs": [],
183
+ "source": [
184
+ "import jax\n",
185
+ "jax.tree_util.register_pytree_node"
186
+ ]
187
+ },
188
+ {
189
+ "cell_type": "code",
190
+ "execution_count": 15,
191
+ "id": "90dcf664",
192
+ "metadata": {},
193
+ "outputs": [
194
+ {
195
+ "data": {
196
+ "text/plain": [
197
+ "True"
198
+ ]
199
+ },
200
+ "execution_count": 15,
201
+ "metadata": {},
202
+ "output_type": "execute_result"
203
+ }
204
+ ],
205
+ "source": [
206
+ "isinstance({1: 2}, Mapping)"
207
+ ]
208
+ },
209
+ {
210
+ "cell_type": "code",
211
+ "execution_count": 30,
212
+ "id": "a01e2543",
213
+ "metadata": {},
214
+ "outputs": [
215
+ {
216
+ "data": {
217
+ "text/plain": [
218
+ "dtype('int64')"
219
+ ]
220
+ },
221
+ "execution_count": 30,
222
+ "metadata": {},
223
+ "output_type": "execute_result"
224
+ }
225
+ ],
226
+ "source": [
227
+ "jax.numpy.dtype(int)"
228
+ ]
229
+ },
230
+ {
231
+ "cell_type": "code",
232
+ "execution_count": null,
233
+ "id": "ea9d0b9f",
234
+ "metadata": {},
235
+ "outputs": [],
236
+ "source": [
237
+ "jax.numpy.ndarray"
238
+ ]
239
+ },
240
+ {
241
+ "cell_type": "code",
242
+ "execution_count": 3,
243
+ "id": "42f7079f",
244
+ "metadata": {},
245
+ "outputs": [
246
+ {
247
+ "data": {
248
+ "text/plain": [
249
+ "[Array([1, 2], dtype=int32), Array([1, 1], dtype=int32)]"
250
+ ]
251
+ },
252
+ "execution_count": 3,
253
+ "metadata": {},
254
+ "output_type": "execute_result"
255
+ }
256
+ ],
257
+ "source": [
258
+ "jax.numpy.broadcast_arrays(jax.numpy.array([1, 2]), jax.numpy.array([1]))"
259
+ ]
260
+ },
261
+ {
262
+ "cell_type": "code",
263
+ "execution_count": null,
264
+ "id": "0bd07e7d",
265
+ "metadata": {},
266
+ "outputs": [],
267
+ "source": [
268
+ "BoxSpec(\n",
269
+ " # default low and high values - inf\n",
270
+ " # default dtype\n",
271
+ " shape={\n",
272
+ " \"batch\": None, # None: infer\n",
273
+ " \"index\": (10, 20, 12), # DiscreteSpec((0, 10, 12)) # BoxSpec(0, 10, dtype=int)\n",
274
+ " \"width\": 100,\n",
275
+ " \"height\": 200,\n",
276
+ " \"channel\": 3,\n",
277
+ " },\n",
278
+ " # -or-\n",
279
+ " # shape=(None, 100, 200, 3),\n",
280
+ " # -instead-\n",
281
+ " # indices={2: [\"r\", \"g\", \"b\"]},\n",
282
+ " # indices={\"channel\": [\"r\", \"g\", \"b\"]},\n",
283
+ ")\n",
284
+ "\n",
285
+ "# BoxSpec.validate\n",
286
+ "# BoxSpec.pack\n",
287
+ "# BoxSpec.unpack"
288
+ ]
289
+ },
290
+ {
291
+ "cell_type": "code",
292
+ "execution_count": 47,
293
+ "id": "8368e07d",
294
+ "metadata": {},
295
+ "outputs": [
296
+ {
297
+ "data": {
298
+ "text/plain": [
299
+ "(3, (1, 3, 5), (2, 2, 4), 3, (0, 0, 4))"
300
+ ]
301
+ },
302
+ "execution_count": 47,
303
+ "metadata": {},
304
+ "output_type": "execute_result"
305
+ }
306
+ ],
307
+ "source": [
308
+ "import itertools\n",
309
+ "\n",
310
+ "def _todo_get_shape(data):\n",
311
+ " # TODO support numpy\n",
312
+ " if isinstance(data, jax.numpy.ndarray):\n",
313
+ " return data.shape\n",
314
+ "\n",
315
+ " def _collapse(sizes):\n",
316
+ " unique_sizes = set(sizes)\n",
317
+ " return unique_sizes.pop() if len(unique_sizes) == 1 else tuple(sizes)\n",
318
+ " return (\n",
319
+ " len(data),\n",
320
+ " *(\n",
321
+ " _collapse(sizes)\n",
322
+ " for sizes in itertools.zip_longest(\n",
323
+ " *(_todo_get_shape(d) for d in data),\n",
324
+ " fillvalue=0,\n",
325
+ " )\n",
326
+ " ),\n",
327
+ " )\n",
328
+ "\n",
329
+ "shape = _todo_get_shape([\n",
330
+ " jax.numpy.empty([1, 2, 3]),\n",
331
+ " jax.numpy.empty([3, 2, 3]),\n",
332
+ " jax.numpy.empty([5, 4, 3, 4]),\n",
333
+ " # (\n",
334
+ " # jax.numpy.empty([3, 2, 3]),\n",
335
+ " # jax.numpy.empty([5, 2, 3]),\n",
336
+ " # ),\n",
337
+ "])\n",
338
+ "shape"
339
+ ]
340
+ },
341
+ {
342
+ "cell_type": "code",
343
+ "execution_count": 53,
344
+ "id": "e00c5a13",
345
+ "metadata": {},
346
+ "outputs": [
347
+ {
348
+ "data": {
349
+ "text/plain": [
350
+ "((slice(0, 3, None),\n",
351
+ " slice(0, 1, None),\n",
352
+ " slice(0, 2, None),\n",
353
+ " slice(0, 3, None),\n",
354
+ " slice(0, 0, None)),\n",
355
+ " (slice(0, 3, None),\n",
356
+ " slice(0, 3, None),\n",
357
+ " slice(0, 2, None),\n",
358
+ " slice(0, 3, None),\n",
359
+ " slice(0, 0, None)),\n",
360
+ " (slice(0, 3, None),\n",
361
+ " slice(0, 5, None),\n",
362
+ " slice(0, 4, None),\n",
363
+ " slice(0, 3, None),\n",
364
+ " slice(0, 4, None)))"
365
+ ]
366
+ },
367
+ "execution_count": 53,
368
+ "metadata": {},
369
+ "output_type": "execute_result"
370
+ }
371
+ ],
372
+ "source": [
373
+ "import numpy\n",
374
+ "\n",
375
+ "tuple(\n",
376
+ " max(sizes) if isinstance(sizes, (list, tuple)) else sizes\n",
377
+ " for sizes in shape\n",
378
+ ")\n",
379
+ "\n",
380
+ "tuple(\n",
381
+ " tuple(slice(0, size) for size in element_shape)\n",
382
+ " for element_shape in zip(*numpy.broadcast_arrays(*shape))\n",
383
+ ")"
384
+ ]
385
+ },
386
+ {
387
+ "cell_type": "code",
388
+ "execution_count": null,
389
+ "id": "3be08373",
390
+ "metadata": {},
391
+ "outputs": [],
392
+ "source": [
393
+ "import gymnasium.vector.utils"
394
+ ]
395
+ },
396
+ {
397
+ "cell_type": "code",
398
+ "execution_count": null,
399
+ "id": "702d4819",
400
+ "metadata": {},
401
+ "outputs": [],
402
+ "source": [
403
+ "\n",
404
+ "\n",
405
+ "class BatchSpec:\n",
406
+ " pass\n",
407
+ "\n"
408
+ ]
409
+ },
410
+ {
411
+ "cell_type": "markdown",
412
+ "id": "727d16dc",
413
+ "metadata": {},
414
+ "source": [
415
+ "## Next"
416
+ ]
417
+ },
418
+ {
419
+ "cell_type": "code",
420
+ "execution_count": null,
421
+ "id": "d267026b",
422
+ "metadata": {},
423
+ "outputs": [],
424
+ "source": [
425
+ "import gymnasium.spaces"
426
+ ]
427
+ },
428
+ {
429
+ "cell_type": "code",
430
+ "execution_count": null,
431
+ "id": "2fc220e2",
432
+ "metadata": {},
433
+ "outputs": [],
434
+ "source": [
435
+ "# TODO\n",
436
+ "# einops: reduce, repeat, rearrange, einsum\n",
437
+ "# even https://einops.rocks/api/pack_unpack/\n",
438
+ "\n",
439
+ "class RescalingTransform:\n",
440
+ " pass"
441
+ ]
442
+ },
443
+ {
444
+ "cell_type": "code",
445
+ "execution_count": null,
446
+ "id": "15d66021",
447
+ "metadata": {},
448
+ "outputs": [],
449
+ "source": [
450
+ "import jax\n",
451
+ "from gymnasium.spaces import Box as _BoxSpec\n",
452
+ "\n",
453
+ "class PaddingTransform:\n",
454
+ " def __init__(self, in_spec: _BoxSpec, out_spec: _BoxSpec):\n",
455
+ " self.in_spec = in_spec\n",
456
+ " self.out_spec = out_spec\n",
457
+ "\n",
458
+ " def __call__(self, data):\n",
459
+ " in_shape = self.in_spec.shape\n",
460
+ " out_shape = self.out_spec.shape\n",
461
+ " # TODO handle when shape has None\n",
462
+ "\n",
463
+ " # jax.numpy.pad(data, )\n"
464
+ ]
465
+ },
466
+ {
467
+ "cell_type": "code",
468
+ "execution_count": null,
469
+ "id": "e199e6f9",
470
+ "metadata": {},
471
+ "outputs": [],
472
+ "source": []
473
+ },
474
+ {
475
+ "cell_type": "code",
476
+ "execution_count": null,
477
+ "id": "410f54e7",
478
+ "metadata": {},
479
+ "outputs": [],
480
+ "source": []
481
+ },
482
+ {
483
+ "cell_type": "code",
484
+ "execution_count": 1,
485
+ "id": "5b5f02fc",
486
+ "metadata": {},
487
+ "outputs": [],
488
+ "source": [
489
+ "import numpy as np\n",
490
+ "from einops import pack, unpack\n",
491
+ "\n",
492
+ "h, w = 100, 200\n",
493
+ "# image_rgb is 3-dimensional (h, w, 3) and depth is 2-dimensional (h, w)\n",
494
+ "image_rgb = np.random.random([h, w, 3])\n",
495
+ "image_depth = np.random.random([h, w])\n",
496
+ "# but we can stack them\n",
497
+ "image_rgbd, ps = pack([image_rgb, image_depth], \"h w *\")"
498
+ ]
499
+ },
500
+ {
501
+ "cell_type": "code",
502
+ "execution_count": 3,
503
+ "id": "18ad8082",
504
+ "metadata": {},
505
+ "outputs": [
506
+ {
507
+ "data": {
508
+ "text/plain": [
509
+ "(100, 200, 4)"
510
+ ]
511
+ },
512
+ "execution_count": 3,
513
+ "metadata": {},
514
+ "output_type": "execute_result"
515
+ }
516
+ ],
517
+ "source": [
518
+ "image_rgbd.shape"
519
+ ]
520
+ },
521
+ {
522
+ "cell_type": "code",
523
+ "execution_count": 4,
524
+ "id": "44bad786",
525
+ "metadata": {},
526
+ "outputs": [
527
+ {
528
+ "data": {
529
+ "text/plain": [
530
+ "[(3,), ()]"
531
+ ]
532
+ },
533
+ "execution_count": 4,
534
+ "metadata": {},
535
+ "output_type": "execute_result"
536
+ }
537
+ ],
538
+ "source": [
539
+ "ps"
540
+ ]
541
+ },
542
+ {
543
+ "cell_type": "code",
544
+ "execution_count": null,
545
+ "id": "9e59b007",
546
+ "metadata": {},
547
+ "outputs": [],
548
+ "source": [
549
+ "# TODO einx"
550
+ ]
551
+ },
552
+ {
553
+ "cell_type": "code",
554
+ "execution_count": null,
555
+ "id": "2abc8fe1",
556
+ "metadata": {},
557
+ "outputs": [],
558
+ "source": [
559
+ "import functools\n",
560
+ "import itertools\n",
561
+ "from typing import Sequence\n",
562
+ "\n",
563
+ "class ShapeSpec:\n",
564
+ " def __init__(\n",
565
+ " self,\n",
566
+ " sizes: Sequence[int],\n",
567
+ " names: Sequence[str | None] | None = None,\n",
568
+ " ):\n",
569
+ " self._sizes = tuple(sizes)\n",
570
+ " self._index_names = tuple(names) if names is not None else tuple()\n",
571
+ "\n",
572
+ " def __repr__(self):\n",
573
+ " return f\"ShapeSpec(sizes={self._sizes}, names={self._index_names})\"\n",
574
+ "\n",
575
+ " @functools.cached_property\n",
576
+ " def _name_indices(self):\n",
577
+ " return {name: index for index, name in enumerate(self._index_names)}\n",
578
+ "\n",
579
+ " def __getitem__(self, key: int | str | slice):\n",
580
+ " ...\n",
581
+ "\n",
582
+ "\n",
583
+ "# ShapeSpec()[0]\n",
584
+ "# ShapeSpec()[\"batch\"]\n",
585
+ "# ShapeSpec((12, 3, 5), names={\"batch\": 0, \"height\": 1, \"width\": 2})"
586
+ ]
587
+ },
588
+ {
589
+ "cell_type": "code",
590
+ "execution_count": null,
591
+ "id": "92dafd6b",
592
+ "metadata": {},
593
+ "outputs": [],
594
+ "source": [
595
+ "ShapeSpec((1, 2, 3))"
596
+ ]
597
+ },
598
+ {
599
+ "cell_type": "code",
600
+ "execution_count": null,
601
+ "id": "d35abaaf",
602
+ "metadata": {},
603
+ "outputs": [],
604
+ "source": [
605
+ "ShapeSpec()[\"a\":\"fdsfds\"]"
606
+ ]
607
+ },
608
+ {
609
+ "cell_type": "code",
610
+ "execution_count": null,
611
+ "id": "0280872d",
612
+ "metadata": {},
613
+ "outputs": [
614
+ {
615
+ "data": {
616
+ "text/plain": [
617
+ "slice('fasd', 'fasd', None)"
618
+ ]
619
+ },
620
+ "metadata": {},
621
+ "output_type": "display_data"
622
+ }
623
+ ],
624
+ "source": [
625
+ "slice(\"fasd\", \"fasd\")"
626
+ ]
627
+ },
628
+ {
629
+ "cell_type": "code",
630
+ "execution_count": null,
631
+ "id": "6eb0f9a6",
632
+ "metadata": {},
633
+ "outputs": [],
634
+ "source": [
635
+ "# BoxSpec(...)\n",
636
+ "# shape_of(some_spec)[\"action_horizon\"]"
637
+ ]
638
+ },
639
+ {
640
+ "cell_type": "code",
641
+ "execution_count": 14,
642
+ "id": "5119acc5",
643
+ "metadata": {},
644
+ "outputs": [
645
+ {
646
+ "data": {
647
+ "text/plain": [
648
+ "False"
649
+ ]
650
+ },
651
+ "execution_count": 14,
652
+ "metadata": {},
653
+ "output_type": "execute_result"
654
+ }
655
+ ],
656
+ "source": [
657
+ "from typing import Collection\n",
658
+ "\n",
659
+ "import gymnasium.spaces\n",
660
+ "\n",
661
+ "isinstance(gymnasium.spaces.Tuple, Collection)"
662
+ ]
663
+ },
664
+ {
665
+ "cell_type": "code",
666
+ "execution_count": null,
667
+ "id": "893ac55e",
668
+ "metadata": {},
669
+ "outputs": [],
670
+ "source": [
671
+ "class CollectionSpec:\n",
672
+ " pass"
673
+ ]
674
+ },
675
+ {
676
+ "cell_type": "code",
677
+ "execution_count": null,
678
+ "id": "e24863d3",
679
+ "metadata": {},
680
+ "outputs": [],
681
+ "source": []
682
+ }
683
+ ],
684
+ "metadata": {
685
+ "kernelspec": {
686
+ "display_name": "Python 3",
687
+ "language": "python",
688
+ "name": "python3"
689
+ },
690
+ "language_info": {
691
+ "codemirror_mode": {
692
+ "name": "ipython",
693
+ "version": 3
694
+ },
695
+ "file_extension": ".py",
696
+ "mimetype": "text/x-python",
697
+ "name": "python",
698
+ "nbconvert_exporter": "python",
699
+ "pygments_lexer": "ipython3",
700
+ "version": "3.11.13"
701
+ }
702
+ },
703
+ "nbformat": 4,
704
+ "nbformat_minor": 5
705
+ }
__todo__/todo-fscaching.ipynb ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "id": "0be51656",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "import fsspec\n",
11
+ "import platformdirs\n",
12
+ "\n",
13
+ "# Use the standard cache directory for your application\n",
14
+ "default_cache_dir = platformdirs.user_cache_dir(appname=\"fsspec\", appauthor=False)\n",
15
+ "\n",
16
+ "\n",
17
+ "\n",
18
+ "fs = fsspec.filesystem(\n",
19
+ " \"filecache\",\n",
20
+ " target_protocol=\"https\",\n",
21
+ " cache_storage=default_cache_dir,\n",
22
+ " same_names=True\n",
23
+ ")\n"
24
+ ]
25
+ },
26
+ {
27
+ "cell_type": "code",
28
+ "execution_count": null,
29
+ "id": "4155b43c",
30
+ "metadata": {},
31
+ "outputs": [
32
+ {
33
+ "ename": "ValueError",
34
+ "evalue": "Please provide filesystem instance(fs) or target_protocol",
35
+ "output_type": "error",
36
+ "traceback": [
37
+ "\u001b[31m---------------------------------------------------------------------------\u001b[39m",
38
+ "\u001b[31mValueError\u001b[39m Traceback (most recent call last)",
39
+ "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[3]\u001b[39m\u001b[32m, line 3\u001b[39m\n\u001b[32m 1\u001b[39m \u001b[38;5;28;01mfrom\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34;01mfsspec\u001b[39;00m\u001b[34;01m.\u001b[39;00m\u001b[34;01mimplementations\u001b[39;00m\u001b[34;01m.\u001b[39;00m\u001b[34;01mcached\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;28;01mimport\u001b[39;00m WholeFileCacheFileSystem\n\u001b[32m----> \u001b[39m\u001b[32m3\u001b[39m fs = \u001b[43mWholeFileCacheFileSystem\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n",
40
+ "\u001b[36mFile \u001b[39m\u001b[32m~/RoboTwin/.conda/lib/python3.11/site-packages/fsspec/spec.py:81\u001b[39m, in \u001b[36m_Cached.__call__\u001b[39m\u001b[34m(cls, *args, **kwargs)\u001b[39m\n\u001b[32m 79\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mcls\u001b[39m._cache[token]\n\u001b[32m 80\u001b[39m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[32m---> \u001b[39m\u001b[32m81\u001b[39m obj = \u001b[38;5;28;43msuper\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[43m.\u001b[49m\u001b[34;43m__call__\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43m*\u001b[49m\u001b[43margs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43m*\u001b[49m\u001b[43m*\u001b[49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 82\u001b[39m \u001b[38;5;66;03m# Setting _fs_token here causes some static linters to complain.\u001b[39;00m\n\u001b[32m 83\u001b[39m obj._fs_token_ = token\n",
41
+ "\u001b[36mFile \u001b[39m\u001b[32m~/RoboTwin/.conda/lib/python3.11/site-packages/fsspec/implementations/cached.py:121\u001b[39m, in \u001b[36mCachingFileSystem.__init__\u001b[39m\u001b[34m(self, target_protocol, cache_storage, cache_check, check_files, expiry_time, target_options, fs, same_names, compression, cache_mapper, **kwargs)\u001b[39m\n\u001b[32m 119\u001b[39m \u001b[38;5;28msuper\u001b[39m().\u001b[34m__init__\u001b[39m(**kwargs)\n\u001b[32m 120\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m fs \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m target_protocol \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[32m--> \u001b[39m\u001b[32m121\u001b[39m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\n\u001b[32m 122\u001b[39m \u001b[33m\"\u001b[39m\u001b[33mPlease provide filesystem instance(fs) or target_protocol\u001b[39m\u001b[33m\"\u001b[39m\n\u001b[32m 123\u001b[39m )\n\u001b[32m 124\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m (fs \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m) ^ (target_protocol \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m):\n\u001b[32m 125\u001b[39m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\n\u001b[32m 126\u001b[39m \u001b[33m\"\u001b[39m\u001b[33mBoth filesystems (fs) and target_protocol may not be both given.\u001b[39m\u001b[33m\"\u001b[39m\n\u001b[32m 127\u001b[39m )\n",
42
+ "\u001b[31mValueError\u001b[39m: Please provide filesystem instance(fs) or target_protocol"
43
+ ]
44
+ }
45
+ ],
46
+ "source": [
47
+ "from fsspec.implementations.cached import WholeFileCacheFileSystem\n",
48
+ "\n",
49
+ "# fs = WholeFileCacheFileSystem()"
50
+ ]
51
+ },
52
+ {
53
+ "cell_type": "code",
54
+ "execution_count": null,
55
+ "id": "184308db",
56
+ "metadata": {},
57
+ "outputs": [],
58
+ "source": []
59
+ },
60
+ {
61
+ "cell_type": "code",
62
+ "execution_count": null,
63
+ "id": "d6a59c57",
64
+ "metadata": {},
65
+ "outputs": [
66
+ {
67
+ "data": {
68
+ "text/plain": [
69
+ "257152"
70
+ ]
71
+ },
72
+ "execution_count": 1,
73
+ "metadata": {},
74
+ "output_type": "execute_result"
75
+ }
76
+ ],
77
+ "source": []
78
+ },
79
+ {
80
+ "cell_type": "markdown",
81
+ "id": "24ea1a87",
82
+ "metadata": {},
83
+ "source": []
84
+ },
85
+ {
86
+ "cell_type": "code",
87
+ "execution_count": 3,
88
+ "id": "72fc057b",
89
+ "metadata": {},
90
+ "outputs": [
91
+ {
92
+ "data": {
93
+ "text/plain": [
94
+ "(<fsspec.implementations.cached.WholeFileCacheFileSystem at 0x7fc6f1915fd0>,\n",
95
+ " 'big_vision/paligemma_tokenizer.model')"
96
+ ]
97
+ },
98
+ "execution_count": 3,
99
+ "metadata": {},
100
+ "output_type": "execute_result"
101
+ }
102
+ ],
103
+ "source": [
104
+ "fsspec.core.url_to_fs(\"filecache::gs://big_vision/paligemma_tokenizer.model\")"
105
+ ]
106
+ }
107
+ ],
108
+ "metadata": {
109
+ "kernelspec": {
110
+ "display_name": ".conda",
111
+ "language": "python",
112
+ "name": "python3"
113
+ },
114
+ "language_info": {
115
+ "codemirror_mode": {
116
+ "name": "ipython",
117
+ "version": 3
118
+ },
119
+ "file_extension": ".py",
120
+ "mimetype": "text/x-python",
121
+ "name": "python",
122
+ "nbconvert_exporter": "python",
123
+ "pygments_lexer": "ipython3",
124
+ "version": "3.11.13"
125
+ }
126
+ },
127
+ "nbformat": 4,
128
+ "nbformat_minor": 5
129
+ }
__todo__/todo-motionplanning-v2-mplib.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
__todo__/todo-motionplanning-v2.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
__todo__/todo-motionplanning-worldmesh.ipynb ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "a64e338b",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "from robotodo.scenes.robotwin_labs import World\n",
11
+ "from robotodo.actors.unitree_robots import UnitreeG1DFQRobot\n",
12
+ "\n",
13
+ "world = World()\n",
14
+ "world.prepare_tabletop()"
15
+ ]
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "execution_count": 3,
20
+ "id": "9202962e",
21
+ "metadata": {},
22
+ "outputs": [],
23
+ "source": [
24
+ "for entity in world._scene.entities:\n",
25
+ " entity"
26
+ ]
27
+ },
28
+ {
29
+ "cell_type": "code",
30
+ "execution_count": 7,
31
+ "id": "b96cff77",
32
+ "metadata": {},
33
+ "outputs": [
34
+ {
35
+ "data": {
36
+ "text/plain": [
37
+ "[<sapien.pysapien.physx.PhysxCollisionShapeConvexMesh at 0x7f24544593f0>,\n",
38
+ " <sapien.pysapien.physx.PhysxCollisionShapeConvexMesh at 0x7f2449c468b0>,\n",
39
+ " <sapien.pysapien.physx.PhysxCollisionShapeConvexMesh at 0x7f2449c45f70>,\n",
40
+ " <sapien.pysapien.physx.PhysxCollisionShapeConvexMesh at 0x7f2449c463f0>,\n",
41
+ " <sapien.pysapien.physx.PhysxCollisionShapeConvexMesh at 0x7f2449c46e70>,\n",
42
+ " <sapien.pysapien.physx.PhysxCollisionShapeConvexMesh at 0x7f2449c452b0>,\n",
43
+ " <sapien.pysapien.physx.PhysxCollisionShapeConvexMesh at 0x7f2449c44cb0>,\n",
44
+ " <sapien.pysapien.physx.PhysxCollisionShapeConvexMesh at 0x7f24549f7a30>,\n",
45
+ " <sapien.pysapien.physx.PhysxCollisionShapeConvexMesh at 0x7f2384ec2030>,\n",
46
+ " <sapien.pysapien.physx.PhysxCollisionShapeConvexMesh at 0x7f2449c6f530>,\n",
47
+ " <sapien.pysapien.physx.PhysxCollisionShapeConvexMesh at 0x7f2449c6ce70>,\n",
48
+ " <sapien.pysapien.physx.PhysxCollisionShapeConvexMesh at 0x7f2449c6de70>,\n",
49
+ " <sapien.pysapien.physx.PhysxCollisionShapeConvexMesh at 0x7f2380a057b0>,\n",
50
+ " <sapien.pysapien.physx.PhysxCollisionShapeConvexMesh at 0x7f2380a043b0>,\n",
51
+ " <sapien.pysapien.physx.PhysxCollisionShapeConvexMesh at 0x7f2380a04830>,\n",
52
+ " <sapien.pysapien.physx.PhysxCollisionShapeConvexMesh at 0x7f2449c37370>,\n",
53
+ " <sapien.pysapien.physx.PhysxCollisionShapeConvexMesh at 0x7f2449c37f30>,\n",
54
+ " <sapien.pysapien.physx.PhysxCollisionShapeConvexMesh at 0x7f2449c349b0>,\n",
55
+ " <sapien.pysapien.physx.PhysxCollisionShapeConvexMesh at 0x7f2449c34b30>,\n",
56
+ " <sapien.pysapien.physx.PhysxCollisionShapeConvexMesh at 0x7f2449c35370>,\n",
57
+ " <sapien.pysapien.physx.PhysxCollisionShapeConvexMesh at 0x7f2449c36a70>,\n",
58
+ " <sapien.pysapien.physx.PhysxCollisionShapeConvexMesh at 0x7f2449c34f70>,\n",
59
+ " <sapien.pysapien.physx.PhysxCollisionShapeConvexMesh at 0x7f2449c345b0>,\n",
60
+ " <sapien.pysapien.physx.PhysxCollisionShapeConvexMesh at 0x7f2449c34570>,\n",
61
+ " <sapien.pysapien.physx.PhysxCollisionShapeConvexMesh at 0x7f2449c34e70>,\n",
62
+ " <sapien.pysapien.physx.PhysxCollisionShapeConvexMesh at 0x7f2449c343f0>,\n",
63
+ " <sapien.pysapien.physx.PhysxCollisionShapeConvexMesh at 0x7f2449c36330>,\n",
64
+ " <sapien.pysapien.physx.PhysxCollisionShapeConvexMesh at 0x7f2449c35af0>]"
65
+ ]
66
+ },
67
+ "execution_count": 7,
68
+ "metadata": {},
69
+ "output_type": "execute_result"
70
+ }
71
+ ],
72
+ "source": [
73
+ "c = entity.components[1]\n",
74
+ "c.collision_shapes"
75
+ ]
76
+ },
77
+ {
78
+ "cell_type": "code",
79
+ "execution_count": 13,
80
+ "id": "d190f130",
81
+ "metadata": {},
82
+ "outputs": [
83
+ {
84
+ "data": {
85
+ "text/plain": [
86
+ "Mesh(name='', pose=None, scale=None, color=None, texture_id=None, texture=None, material=Material(metallic=0.0, roughness=0.4), tensor_args=TensorDeviceType(device=device(type='cuda', index=0), dtype=torch.float32, collision_geometry_dtype=torch.float32, collision_gradient_dtype=torch.float32, collision_distance_dtype=torch.float32), file_path=None, file_string=None, urdf_path=None, vertices=array([[-3.18372935e-01, 1.65347368e-01, 1.10476792e+00],\n",
87
+ " [-2.56312340e-01, 1.53907448e-01, 1.11186969e+00],\n",
88
+ " [-1.19304284e-01, 1.66559070e-01, 1.14343333e+00],\n",
89
+ " [-1.67234510e-01, 1.82043940e-01, 1.14016414e+00],\n",
90
+ " [-2.63207972e-01, 1.82043940e-01, 1.12178969e+00],\n",
91
+ " [-1.13872576e+00, 1.82043940e-01, 1.96976393e-01],\n",
92
+ " [-1.10560417e+00, 1.64117843e-01, 3.21652591e-01],\n",
93
+ " [-1.10176063e+00, 1.74310416e-01, 3.47918034e-01],\n",
94
+ " [-1.10616946e+00, 1.82043940e-01, 3.40027094e-01],\n",
95
+ " [-1.06536078e+00, 1.26626343e-01, 3.57274354e-01],\n",
96
+ " [-1.10458660e+00, 1.26786709e-01, 2.00132743e-01],\n",
97
+ " [ 6.90712186e-05, 1.82043940e-01, 1.00613165e+00],\n",
98
+ " [ 6.90712186e-05, 1.32791758e-01, 1.54826790e-04],\n",
99
+ " [-1.00623941e+00, 1.82043940e-01, 1.54826790e-04],\n",
100
+ " [-9.42144036e-01, 1.09087229e-02, 3.44987094e-01],\n",
101
+ " [-9.05631125e-01, 9.48315859e-03, 4.31448817e-01],\n",
102
+ " [-1.02319574e+00, 1.29067570e-01, 4.68986928e-01],\n",
103
+ " [-9.06309366e-01, 1.27677649e-01, 6.69528484e-01],\n",
104
+ " [-7.48275280e-01, 9.30500031e-03, 6.69303060e-01],\n",
105
+ " [-7.38892794e-01, 1.55951381e-02, 6.89932108e-01],\n",
106
+ " [-7.92475104e-01, 1.24915719e-01, 7.92288363e-01],\n",
107
+ " [-8.31022739e-01, 1.25236422e-01, 7.52608299e-01],\n",
108
+ " [-4.35033262e-01, 1.66006684e-01, 1.06497526e+00],\n",
109
+ " [-5.16085088e-01, 1.64135695e-01, 1.02676070e+00],\n",
110
+ " [-4.68946159e-01, 1.29245758e-01, 1.02304077e+00],\n",
111
+ " [-3.56694520e-01, 1.26840174e-01, 1.06497526e+00],\n",
112
+ " [-3.25381607e-01, 1.82043940e-01, 1.10690975e+00],\n",
113
+ " [-4.40346301e-01, 1.82043940e-01, 1.06711709e+00],\n",
114
+ " [-1.06569982e+00, 1.65008813e-01, 4.36634243e-01],\n",
115
+ " [-1.02794361e+00, 1.62727952e-01, 5.18023252e-01],\n",
116
+ " [-1.03144789e+00, 1.82043940e-01, 5.24448693e-01],\n",
117
+ " [-1.06830001e+00, 1.82043940e-01, 4.42834258e-01],\n",
118
+ " [-1.14709091e+00, 1.60892576e-01, 1.97693631e-02],\n",
119
+ " [-1.15466475e+00, 1.82043940e-01, 1.97693631e-02],\n",
120
+ " [-1.15455174e+00, 1.82043940e-01, 1.54826790e-04],\n",
121
+ " [-1.14709091e+00, 1.60892576e-01, 1.54826790e-04],\n",
122
+ " [-9.83404636e-01, 1.29317015e-01, 5.48121393e-01],\n",
123
+ " [-9.86174494e-02, 1.22189373e-01, 1.10995328e+00],\n",
124
+ " [-5.91654480e-02, 1.43964380e-01, 1.13080788e+00],\n",
125
+ " [-1.98886544e-01, 1.27089620e-01, 1.10420430e+00],\n",
126
+ " [-8.65839958e-01, 9.57226753e-03, 5.10357797e-01],\n",
127
+ " [-8.21979344e-01, 1.20669603e-02, 5.83179533e-01],\n",
128
+ " [-1.38069421e-01, 7.59434700e-03, 9.88208115e-01],\n",
129
+ " [ 6.90712186e-05, 5.93715906e-03, 9.92153466e-01],\n",
130
+ " [ 6.90712186e-05, 1.86421871e-02, 1.01188076e+00],\n",
131
+ " [-1.98264942e-02, 1.86600685e-02, 1.01188076e+00],\n",
132
+ " [-5.92389047e-01, 1.65971041e-01, 9.86178994e-01],\n",
133
+ " [-6.21101975e-01, 1.82043940e-01, 9.73553538e-01],\n",
134
+ " [-6.60101771e-01, 1.82043940e-01, 9.47851717e-01],\n",
135
+ " [-6.39188886e-01, 1.59377962e-01, 9.51909900e-01],\n",
136
+ " [-1.10989976e+00, 1.22189373e-01, 9.85656083e-02],\n",
137
+ " [-9.86343801e-01, 8.64565372e-03, 1.62481889e-01],\n",
138
+ " [-9.07665849e-01, 1.65739417e-01, 7.10561156e-01],\n",
139
+ " [-8.69909525e-01, 1.63583308e-01, 7.52044737e-01],\n",
140
+ " [-9.52204764e-01, 1.58861190e-01, 6.40332103e-01],\n",
141
+ " [-9.86682951e-01, 1.65311724e-01, 5.93099475e-01],\n",
142
+ " [-9.89395916e-01, 1.82043940e-01, 5.97495854e-01],\n",
143
+ " [-7.09275484e-01, 1.67735159e-01, 9.06480908e-01],\n",
144
+ " [-7.55623102e-01, 1.82043940e-01, 8.72662723e-01],\n",
145
+ " [-7.97562063e-01, 1.82043940e-01, 8.36251855e-01],\n",
146
+ " [-7.51666605e-01, 1.64206922e-01, 8.69393647e-01],\n",
147
+ " [-7.10745096e-01, 1.26644135e-01, 8.68266344e-01],\n",
148
+ " [-9.86174494e-02, 4.12369072e-02, 1.03025532e+00],\n",
149
+ " [ 6.90712186e-05, 3.83680463e-02, 1.03228438e+00],\n",
150
+ " [-1.98264942e-02, 1.20888561e-01, 1.11153150e+00],\n",
151
+ " [-4.97546047e-01, 1.82043940e-01, 1.04141521e+00],\n",
152
+ " [-5.76223969e-01, 1.82043940e-01, 9.99818921e-01],\n",
153
+ " [-7.92814195e-01, 1.62086457e-01, 8.31855536e-01],\n",
154
+ " [-7.78683841e-01, 1.35785371e-01, 8.18666458e-01],\n",
155
+ " [-7.52457917e-01, 1.25361204e-01, 8.30728233e-01],\n",
156
+ " [-5.47397971e-01, 1.29798144e-01, 9.83022630e-01],\n",
157
+ " [-9.26544070e-01, 2.17199326e-04, 1.54826790e-04],\n",
158
+ " [-9.26544070e-01, 4.13239002e-04, 2.16929108e-01],\n",
159
+ " [-9.65996027e-01, 3.63850594e-03, 1.38020113e-01],\n",
160
+ " [-9.65996027e-01, 2.51585245e-03, 1.54826790e-04],\n",
161
+ " [-6.67449653e-01, 1.29067570e-01, 9.04677212e-01],\n",
162
+ " [-3.74668330e-01, 1.57554746e-02, 9.36128080e-01],\n",
163
+ " [-4.53459263e-01, 1.42052770e-02, 8.98815453e-01],\n",
164
+ " [-4.04398650e-01, 6.95288181e-03, 9.10989940e-01],\n",
165
+ " [-3.19503367e-01, 8.41403008e-03, 9.47288096e-01],\n",
166
+ " [-2.56312340e-01, 1.34181678e-01, 1.09789145e+00],\n",
167
+ " [-6.74175993e-02, 1.82043940e-01, 1.15042233e+00],\n",
168
+ " [-1.31173804e-01, 1.82043940e-01, 1.14557517e+00],\n",
169
+ " [-1.98264942e-02, 1.62941784e-01, 1.14557517e+00],\n",
170
+ " [ 6.90712186e-05, 1.62941784e-01, 1.14557517e+00],\n",
171
+ " [ 6.90712186e-05, 1.82043940e-01, 1.15177512e+00],\n",
172
+ " [-1.14268208e+00, 1.68929040e-01, 1.51209190e-01],\n",
173
+ " [-1.14403868e+00, 1.65775031e-01, 1.24943748e-01],\n",
174
+ " [-1.14256907e+00, 1.82043940e-01, 1.77474588e-01],\n",
175
+ " [-2.56312340e-01, 5.29569387e-03, 9.56080794e-01],\n",
176
+ " [-5.83458722e-01, 1.27262473e-02, 8.21259201e-01],\n",
177
+ " [-5.57232678e-01, 7.38048553e-03, 8.31291854e-01],\n",
178
+ " [-5.32363296e-01, 1.57198906e-02, 8.57670069e-01],\n",
179
+ " [-5.95893383e-01, 1.25325561e-01, 9.48866308e-01],\n",
180
+ " [-6.22119367e-01, 1.33094668e-01, 9.40073609e-01],\n",
181
+ " [-6.69710457e-01, 9.21589136e-03, 7.48550177e-01],\n",
182
+ " [-2.56312340e-01, 1.51674747e-02, 9.75808024e-01],\n",
183
+ " [-2.16973394e-01, 1.10155940e-02, 9.81106222e-01],\n",
184
+ " [-1.92330047e-01, 9.50098038e-03, 9.84262586e-01],\n",
185
+ " [ 6.90712186e-05, 1.43233806e-01, 1.13125873e+00],\n",
186
+ " [-9.78882968e-01, 1.24589801e-02, 2.16929108e-01],\n",
187
+ " [-4.53459263e-01, 6.98328018e-04, 8.47637296e-01],\n",
188
+ " [-3.74668330e-01, 1.03688240e-03, 8.87091875e-01],\n",
189
+ " [-4.82850462e-01, 6.63208961e-03, 8.72324586e-01],\n",
190
+ " [-5.32363296e-01, 1.25074387e-03, 8.08182836e-01],\n",
191
+ " [-9.43952739e-01, 1.73544198e-01, 6.66597605e-01],\n",
192
+ " [-8.79744232e-01, 5.31345606e-03, 4.53430593e-01],\n",
193
+ " [-8.08640242e-01, 4.99272346e-03, 5.70779502e-01],\n",
194
+ " [-7.95753360e-01, 6.52515888e-03, 6.00877643e-01],\n",
195
+ " [-9.47004855e-01, 8.61001015e-03, 3.18721712e-01],\n",
196
+ " [-9.28013623e-01, 5.29569387e-03, 3.33150774e-01],\n",
197
+ " [-6.89945102e-01, 2.67624855e-03, 6.89932108e-01],\n",
198
+ " [-6.89945102e-01, 6.88159466e-03, 7.19353855e-01],\n",
199
+ " [-7.10066736e-01, 8.85951519e-03, 7.09997535e-01],\n",
200
+ " [-9.89735067e-01, 6.91723824e-03, 1.54826790e-04],\n",
201
+ " [-8.32040131e-01, 1.61961734e-01, 7.92739213e-01],\n",
202
+ " [-8.20735812e-01, 1.82043940e-01, 8.13593745e-01],\n",
203
+ " [ 6.90712186e-05, 1.81555748e-04, 8.47637296e-01],\n",
204
+ " [ 6.90712186e-05, 1.60706043e-03, 9.65888083e-01],\n",
205
+ " [-2.56312340e-01, 9.65595245e-04, 9.26433504e-01],\n",
206
+ " [-7.29397118e-01, 5.37991524e-04, 6.11023068e-01],\n",
207
+ " [-8.47640038e-01, 8.58664513e-04, 4.53430593e-01],\n",
208
+ " [-8.87092054e-01, 1.30414963e-03, 3.74634326e-01],\n",
209
+ " [ 6.90712186e-05, 5.73575497e-04, 1.54826790e-04],\n",
210
+ " [-1.13081264e+00, 1.42307192e-01, 5.91111369e-02],\n",
211
+ " [-1.13160396e+00, 1.41184598e-01, 1.54826790e-04],\n",
212
+ " [-9.86174494e-02, 2.15288997e-02, 1.00973892e+00],\n",
213
+ " [ 6.90712186e-05, 1.20924205e-01, 1.11153150e+00],\n",
214
+ " [-1.11193442e+00, 1.20692581e-01, 1.54826790e-04],\n",
215
+ " [-1.11182141e+00, 1.20692581e-01, 1.97693631e-02],\n",
216
+ " [-9.52430964e-01, 1.82043940e-01, 6.57241285e-01],\n",
217
+ " [-9.10491884e-01, 1.82043940e-01, 7.13942945e-01],\n",
218
+ " [-8.59622598e-01, 1.82043940e-01, 7.72222877e-01],\n",
219
+ " [-9.86174494e-02, 2.40898132e-03, 9.65888083e-01],\n",
220
+ " [-8.08188140e-01, 1.51801109e-03, 5.32339573e-01],\n",
221
+ " [-1.00906539e+00, 2.33464539e-02, 5.91111369e-02],\n",
222
+ " [-1.00940466e+00, 2.22595334e-02, 1.54826790e-04],\n",
223
+ " [-1.09870839e+00, 1.82043940e-01, 3.63361627e-01],\n",
224
+ " [-9.59213495e-01, 4.88585234e-03, 2.16929108e-01],\n",
225
+ " [-8.18814099e-01, 1.35678470e-01, 7.78873801e-01],\n",
226
+ " [-9.36604857e-01, 1.82043940e-01, 6.80237532e-01],\n",
227
+ " [-6.94127738e-01, 1.82043940e-01, 9.22262669e-01],\n",
228
+ " [-1.11272573e+00, 1.53764933e-01, 2.56270826e-01],\n",
229
+ " [-1.15319514e+00, 1.82043940e-01, 5.91111369e-02],\n",
230
+ " [-1.14731693e+00, 1.82043940e-01, 1.39598280e-01],\n",
231
+ " [-6.12623751e-01, 4.24432755e-03, 7.70419240e-01]], dtype=float32), faces=None, vertex_colors=None, vertex_normals=None, face_colors=None)"
232
+ ]
233
+ },
234
+ "execution_count": 13,
235
+ "metadata": {},
236
+ "output_type": "execute_result"
237
+ }
238
+ ],
239
+ "source": [
240
+ "from curobo.geom.types import Mesh\n",
241
+ "\n",
242
+ "Mesh(name=c.name, vertices=c.collision_shapes[0].vertices)"
243
+ ]
244
+ }
245
+ ],
246
+ "metadata": {
247
+ "kernelspec": {
248
+ "display_name": ".conda",
249
+ "language": "python",
250
+ "name": "python3"
251
+ },
252
+ "language_info": {
253
+ "codemirror_mode": {
254
+ "name": "ipython",
255
+ "version": 3
256
+ },
257
+ "file_extension": ".py",
258
+ "mimetype": "text/x-python",
259
+ "name": "python",
260
+ "nbconvert_exporter": "python",
261
+ "pygments_lexer": "ipython3",
262
+ "version": "3.11.13"
263
+ }
264
+ },
265
+ "nbformat": 4,
266
+ "nbformat_minor": 5
267
+ }
__todo__/todo-motionplanning.ipynb ADDED
@@ -0,0 +1,1000 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "id": "7a49ca8e",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "import transforms3d as t3d\n",
11
+ "import numpy as np\n",
12
+ "\n",
13
+ "\n",
14
+ "# 世界坐标euler角\n",
15
+ "# t3d.euler.quat2euler(quat) = theta_x, theta_y, theta_z\n",
16
+ "# theta_y 控制俯仰角,theta_z控制垂直桌面平面上的旋转\n",
17
+ "GRASP_DIRECTION_DIC = {\n",
18
+ " \"left\": [0, 0, 0, -1],\n",
19
+ " \"front_left\": [-0.383, 0, 0, -0.924],\n",
20
+ " \"front\": [-0.707, 0, 0, -0.707],\n",
21
+ " \"front_right\": [-0.924, 0, 0, -0.383],\n",
22
+ " \"right\": [-1, 0, 0, 0],\n",
23
+ " \"top_down\": [-0.5, 0.5, -0.5, -0.5],\n",
24
+ " \"down_right\": [-0.707, 0, -0.707, 0],\n",
25
+ " \"down_left\": [0, 0.707, 0, -0.707],\n",
26
+ " \"top_down_little_left\": [-0.353523, 0.61239, -0.353524, -0.61239],\n",
27
+ " \"top_down_little_right\": [-0.61239, 0.353523, -0.61239, -0.353524],\n",
28
+ " \"left_arm_perf\": [-0.853532, 0.146484, -0.353542, -0.3536],\n",
29
+ " \"right_arm_perf\": [-0.353518, 0.353564, -0.14642, -0.853568],\n",
30
+ "}\n",
31
+ "\n",
32
+ "WORLD_DIRECTION_DIC = {\n",
33
+ " \"left\": [0, -0.707, 0, 0.707], # -z -y -x\n",
34
+ " \"front\": [0.5, -0.5, 0.5, 0.5], # y z -x\n",
35
+ " \"right\": [0.707, 0, 0.707, 0], # z y -x\n",
36
+ " \"top_down\": [0, 0.707, -0.707, 0], # -x -y -z\n",
37
+ "}\n",
38
+ "\n",
39
+ "ROTATE_NUM = 10\n",
40
+ "\n",
41
+ "\n",
42
+ "\n",
43
+ "def cal_quat_dis(quat1, quat2):\n",
44
+ " qmult = t3d.quaternions.qmult\n",
45
+ " qinv = t3d.quaternions.qinverse\n",
46
+ " qnorm = t3d.quaternions.qnorm\n",
47
+ " delta_quat = qmult(qinv(quat1), quat2)\n",
48
+ " return 2 * np.arccos(np.fabs((delta_quat / qnorm(delta_quat))[0])) / np.pi\n",
49
+ "\n",
50
+ "\n",
51
+ "\n",
52
+ "from typing import Literal\n",
53
+ "import sapien\n",
54
+ "\n",
55
+ "def rotate_cone(new_pt: np.ndarray, origin: np.ndarray, z_dir: np.ndarray = [0, 0, 1]):\n",
56
+ " x = origin - new_pt\n",
57
+ " x = x / np.linalg.norm(x)\n",
58
+ " bx_ = np.array(z_dir).reshape(3)\n",
59
+ " z = bx_ - np.dot(x, bx_) * x\n",
60
+ " z = z / np.linalg.norm(z)\n",
61
+ " y = np.cross(z, x)\n",
62
+ " return np.stack([x, y, z], axis=1)\n",
63
+ "\n",
64
+ "def rotate_along_axis(\n",
65
+ " target_pose: sapien.Pose,\n",
66
+ " center_pose: sapien.Pose,\n",
67
+ " axis,\n",
68
+ " theta: float = np.pi / 2,\n",
69
+ " axis_type: Literal[\"center\", \"target\", \"world\"] = \"center\",\n",
70
+ " towards=None,\n",
71
+ " camera_face=None,\n",
72
+ ") -> sapien.Pose:\n",
73
+ " \"\"\"\n",
74
+ " 以 center 为中心,沿着指定轴旋转指定角度。通过 towards 可指定旋转方向(方向为 center->target 向量与 towards 向量乘积为正的方向)\n",
75
+ "\n",
76
+ " target_pose: 目标点(比如在物体正上方的预抓取点)\n",
77
+ " center_pose: 中心点(比如物体的位置)\n",
78
+ " axis: 旋转轴\n",
79
+ " theta: 旋转角度(单位:弧度)\n",
80
+ " axis_type: 旋转轴的类型('center':相对于 center_pose,'target':相对于 target_pose,'world':世界坐标系),默认是 'center'\n",
81
+ " towards: 旋转方向(可选),如果指定了这个参数,则会根据这个参数来决定旋转的方向\n",
82
+ " camera_face: 相机朝向(可选),会限制相机向量与该向量点积为正;如果设置为 None,只旋转不考虑相机朝向\n",
83
+ " 返回值:列表,前3个元素是坐标,后4个元素是四元数\n",
84
+ " \"\"\"\n",
85
+ " target_pose, center_pose = (target_pose), (center_pose)\n",
86
+ " if theta == 0:\n",
87
+ " return target_pose.p.tolist() + target_pose.q.tolist()\n",
88
+ " rotate_mat = t3d.axangles.axangle2mat(axis, theta)\n",
89
+ "\n",
90
+ " target_mat = target_pose.to_transformation_matrix()\n",
91
+ " center_mat = center_pose.to_transformation_matrix()\n",
92
+ " if axis_type == \"center\":\n",
93
+ " world_axis = (center_mat[:3, :3] @ np.array(axis).reshape(3, 1)).reshape(3)\n",
94
+ " elif axis_type == \"target\":\n",
95
+ " world_axis = (target_mat[:3, :3] @ np.array(axis).reshape(3, 1)).reshape(3)\n",
96
+ " else:\n",
97
+ " world_axis = np.array(axis).reshape(3)\n",
98
+ "\n",
99
+ " rotate_mat = t3d.axangles.axangle2mat(world_axis, theta)\n",
100
+ " p = (rotate_mat @ (target_pose.p - center_pose.p).reshape(3, 1)).reshape(3) + center_pose.p\n",
101
+ " if towards is not None:\n",
102
+ " towards = np.dot(p - center_pose.p, np.array(towards).reshape(3))\n",
103
+ " if towards < 0:\n",
104
+ " rotate_mat = t3d.axangles.axangle2mat(world_axis, -theta)\n",
105
+ " p = (rotate_mat @ (target_pose.p - center_pose.p).reshape(3, 1)).reshape(3) + center_pose.p\n",
106
+ "\n",
107
+ " if camera_face is None:\n",
108
+ " q = t3d.quaternions.mat2quat(rotate_mat @ target_mat[:3, :3])\n",
109
+ " else:\n",
110
+ " q = t3d.quaternions.mat2quat(rotate_cone(p, center_pose.p, camera_face))\n",
111
+ "\n",
112
+ " return sapien.Pose(p=p, q=q)\n",
113
+ "\n",
114
+ "\n",
115
+ "\n",
116
+ "\n",
117
+ "def get_align_matrix(v1: np.ndarray, v2: np.ndarray) -> np.ndarray:\n",
118
+ " \"\"\"\n",
119
+ " 获取从 v1 到 v2 的旋转矩阵\n",
120
+ " \"\"\"\n",
121
+ " v1 = np.array(v1).reshape(3)\n",
122
+ " v2 = np.array(v2).reshape(3)\n",
123
+ "\n",
124
+ " v1 = v1 / np.linalg.norm(v1)\n",
125
+ " v2 = v2 / np.linalg.norm(v2)\n",
126
+ " axis = np.cross(v1, v2)\n",
127
+ " angle = np.arccos(np.dot(v1, v2))\n",
128
+ "\n",
129
+ " if np.linalg.norm(axis) < 1e-6:\n",
130
+ " return np.eye(3)\n",
131
+ " else:\n",
132
+ " return t3d.axangles.axangle2mat(axis, angle)\n",
133
+ " \n",
134
+ "def get_product_vector(v1: np.ndarray, v2: np.ndarray) -> np.ndarray:\n",
135
+ " \"\"\"\n",
136
+ " 获取 v2 在 v1 上的投影向量\n",
137
+ " \"\"\"\n",
138
+ " v1 = np.array(v1).reshape(3)\n",
139
+ " v1 = v1 / np.linalg.norm(v1)\n",
140
+ " v2 = np.array(v2).reshape(3)\n",
141
+ " return np.dot(v1, v2) * v1\n",
142
+ "\n",
143
+ "\n",
144
+ "def get_place_pose(\n",
145
+ " actor_pose: sapien.Pose,\n",
146
+ " target_pose: sapien.Pose,\n",
147
+ " constrain: Literal[\"free\", \"align\"] = \"free\",\n",
148
+ " align_axis: list[np.ndarray] | np.ndarray | list = None,\n",
149
+ " actor_axis: np.ndarray | list = [1, 0, 0],\n",
150
+ " actor_axis_type: Literal[\"actor\", \"world\"] = \"actor\",\n",
151
+ " z_transform: bool = True,\n",
152
+ ") -> sapien.Pose:\n",
153
+ " \"\"\"\n",
154
+ " 获取物体应当被放置到的位置\n",
155
+ " 考虑因素:\n",
156
+ " 1. 三维坐标与给定坐标一致\n",
157
+ " 2. 物体的朝向合理\n",
158
+ " - 物体 z 轴与给定坐标 z 轴一致\n",
159
+ " - 满足在 xy 平面上的一定约束\n",
160
+ " - 无约束(直接采用物体当前的 x,y 在 xOy 平面上的投影)\n",
161
+ " - 物体的 x 轴对齐给定 x 轴\n",
162
+ " - 选取物体的 x 轴与给定的世界轴单位向量集合中点积最小的方向\n",
163
+ "\n",
164
+ " actor_pose: 物体当前的 pose\n",
165
+ " target_pose: 物体应当被放置到的位置\n",
166
+ " constrain: 物体的约束类型\n",
167
+ " - free: 无约束\n",
168
+ " - align: 物体的 x 轴与给定的世界轴向量集合中点积最小的方向\n",
169
+ " align_axis: 给定的世界轴向量集合,如果设置为 None,默认使用 target_pose 的 x 轴\n",
170
+ " actor_axis: 计算点积的 actor 轴,默认使用 x 轴\n",
171
+ " actor_axis_type: actor_axis 的类型,默认使用局部坐标系\n",
172
+ " - actor: actor_pose 的局部坐标系\n",
173
+ " - world: 世界坐标系\n",
174
+ " \"\"\"\n",
175
+ " actor_pose_mat = (actor_pose).to_transformation_matrix()\n",
176
+ " target_pose_mat = (target_pose).to_transformation_matrix()\n",
177
+ "\n",
178
+ " # 将物体的三维坐标与给定坐标对齐\n",
179
+ " actor_pose_mat[:3, 3] = target_pose_mat[:3, 3]\n",
180
+ "\n",
181
+ " target_x = target_pose_mat[:3, 0]\n",
182
+ " target_y = target_pose_mat[:3, 1]\n",
183
+ " target_z = target_pose_mat[:3, 2]\n",
184
+ "\n",
185
+ " # 将物体的 z 轴与给定坐标的 z 轴对齐\n",
186
+ " actor2world = np.array([[1.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]]).T\n",
187
+ " if z_transform:\n",
188
+ " z_align_matrix = get_align_matrix(actor_pose_mat[:3, :3] @ actor2world[:3, 2], target_z)\n",
189
+ " else:\n",
190
+ " z_align_matrix = get_align_matrix(actor_pose_mat[:3, 2], target_z)\n",
191
+ " actor_pose_mat[:3, :3] = z_align_matrix @ actor_pose_mat[:3, :3]\n",
192
+ "\n",
193
+ " if constrain == \"align\":\n",
194
+ " if align_axis is None:\n",
195
+ " align_axis = np.array(target_pose_mat[:3, :3] @ np.array([[1, 0, 0]]).T)\n",
196
+ " elif isinstance(align_axis, list):\n",
197
+ " align_axis = np.array(align_axis).reshape((-1, 3)).T\n",
198
+ " else:\n",
199
+ " align_axis = np.array(align_axis).reshape((3, -1))\n",
200
+ " align_axis = align_axis / np.linalg.norm(align_axis, axis=0)\n",
201
+ "\n",
202
+ " if actor_axis_type == \"actor\":\n",
203
+ " actor_axis = actor_pose_mat[:3, :3] @ np.array(actor_axis).reshape(3, 1)\n",
204
+ " elif actor_axis_type == \"world\":\n",
205
+ " actor_axis = np.array(actor_axis)\n",
206
+ " closest_axis_id = np.argmax(actor_axis.reshape(3) @ align_axis)\n",
207
+ " align_axis = align_axis[:, closest_axis_id]\n",
208
+ "\n",
209
+ " actor_axis_xOy = get_product_vector(target_x, actor_axis) + get_product_vector(target_y, actor_axis)\n",
210
+ " align_axis_xOy = get_product_vector(target_x, align_axis) + get_product_vector(target_y, align_axis)\n",
211
+ " align_mat_xOy = get_align_matrix(actor_axis_xOy, align_axis_xOy)\n",
212
+ " actor_pose_mat[:3, :3] = align_mat_xOy @ actor_pose_mat[:3, :3]\n",
213
+ "\n",
214
+ " # TODO orig: return (actor_pose_mat[:3, 3].tolist() + t3d.quaternions.mat2quat(actor_pose_mat[:3, :3]).tolist())\n",
215
+ " return sapien.Pose(\n",
216
+ " p=actor_pose_mat[:3, 3],\n",
217
+ " q=t3d.quaternions.mat2quat(actor_pose_mat[:3, :3]),\n",
218
+ " )\n",
219
+ "\n",
220
+ "\n",
221
+ "\n",
222
+ "\n",
223
+ "import numpy as np\n",
224
+ "\n",
225
+ "\n",
226
+ "\n",
227
+ "class _TODO:\n",
228
+ "\n",
229
+ " def create_target_pose_list(\n",
230
+ " self, \n",
231
+ " origin_pose: sapien.Pose, \n",
232
+ " center_pose: sapien.Pose, \n",
233
+ "\n",
234
+ " # TODO\n",
235
+ " # TODO left_embodiment_args.get(\"rotate_range\", [0, 0])\n",
236
+ " # TODO NOTE orig: rotate_lim = (self.left_rotate_lim if arm_tag == \"left\" else self.right_rotate_lim)\n",
237
+ " rotation_fromto: tuple[float, float] = (0, 0),\n",
238
+ " ):\n",
239
+ " res_lst = []\n",
240
+ "\n",
241
+ "\n",
242
+ " # TODO left_embodiment_args.get(\"rotate_lim\", [0, 0])\n",
243
+ " # rotate_lim = (self.left_rotate_lim if arm_tag == \"left\" else self.right_rotate_lim)\n",
244
+ " # #############################\n",
245
+ "\n",
246
+ " for rotation in np.linspace(*rotation_fromto, num=ROTATE_NUM): \n",
247
+ " now_pose = rotate_along_axis(\n",
248
+ " origin_pose,\n",
249
+ " center_pose,\n",
250
+ " axis=[0, 1, 0],\n",
251
+ " theta=rotation,\n",
252
+ " axis_type=\"target\",\n",
253
+ " towards=[0, -1, 0],\n",
254
+ " )\n",
255
+ " res_lst.append(now_pose)\n",
256
+ "\n",
257
+ " return res_lst\n",
258
+ "\n",
259
+ " def choose_best_pose(\n",
260
+ " self, \n",
261
+ " res_pose: sapien.Pose, \n",
262
+ " center_pose: sapien.Pose, \n",
263
+ "\n",
264
+ " # TODO !!!!\n",
265
+ " rotation_fromto: tuple[float, float] = (0, 0),\n",
266
+ "\n",
267
+ " # TODO\n",
268
+ " # arm_tag: ArmTag = None,\n",
269
+ " ):\n",
270
+ " \"\"\"\n",
271
+ " Choose the best pose from the list of target poses.\n",
272
+ " - target_lst: List of target poses.\n",
273
+ " \"\"\"\n",
274
+ "\n",
275
+ " # TODO raise\n",
276
+ " # if not self.plan_success:\n",
277
+ " # return [-1, -1, -1, -1, -1, -1, -1]\n",
278
+ " \n",
279
+ " # TODO ###################\n",
280
+ " # if arm_tag == \"left\":\n",
281
+ " # plan_multi_pose = self.robot.left_plan_multi_path\n",
282
+ " # if arm_tag == \"right\":\n",
283
+ " # plan_multi_pose = self.robot.right_plan_multi_path\n",
284
+ " # #########################33\n",
285
+ " plan_multi_pose = ... # TODO robotwin planner\n",
286
+ " \n",
287
+ "\n",
288
+ " target_lst = self.create_target_pose_list(\n",
289
+ " res_pose, \n",
290
+ " center_pose, \n",
291
+ " rotation_fromto=rotation_fromto,\n",
292
+ " )\n",
293
+ " pose_num = len(target_lst)\n",
294
+ " traj_lst = plan_multi_pose(target_lst)\n",
295
+ " now_pose = None\n",
296
+ " now_step = -1\n",
297
+ " for i in range(pose_num):\n",
298
+ " if traj_lst[\"status\"][i] != \"Success\":\n",
299
+ " continue\n",
300
+ " if now_pose is None or len(traj_lst[\"position\"][i]) < now_step:\n",
301
+ " now_pose = target_lst[i]\n",
302
+ " return now_pose\n",
303
+ "\n",
304
+ " def get_grasp_pose(\n",
305
+ " self,\n",
306
+ "\n",
307
+ " # TODO orig: contact_point_id: int = 0,\n",
308
+ " contact_point: sapien.Pose, #= actor.get_contact_point(contact_point_id=0)\n",
309
+ "\n",
310
+ " pre_dis: float = 0.0,\n",
311
+ " ) -> list:\n",
312
+ " \"\"\"\n",
313
+ " Obtain the grasp pose through the marked grasp point.\n",
314
+ " - actor: The instance of the object to be grasped.\n",
315
+ " - arm_tag: The arm to be used, either \"left\" or \"right\".\n",
316
+ " - pre_dis: The distance in front of the grasp point.\n",
317
+ " - contact_point_id: The index of the grasp point.\n",
318
+ " \"\"\"\n",
319
+ "\n",
320
+ " # TODO raise\n",
321
+ " # if not self.plan_success:\n",
322
+ " # return [-1, -1, -1, -1, -1, -1, -1]\n",
323
+ "\n",
324
+ " global_contact_pose_matrix = (\n",
325
+ " contact_point.to_transformation_matrix() \n",
326
+ " @ np.array([\n",
327
+ " [0, 0, 1, 0], \n",
328
+ " [-1, 0, 0, 0], \n",
329
+ " [0, -1, 0, 0],\n",
330
+ " [0, 0, 0, 1]\n",
331
+ " ])\n",
332
+ " )\n",
333
+ " global_contact_pose_matrix_q = global_contact_pose_matrix[:3, :3]\n",
334
+ " global_grasp_pose_p = (global_contact_pose_matrix[:3, 3] +\n",
335
+ " # TODO -0.12 should be from pre_dis???\n",
336
+ " global_contact_pose_matrix_q @ np.array([-0.12 - pre_dis, 0, 0]).T)\n",
337
+ " global_grasp_pose_q = t3d.quaternions.mat2quat(global_contact_pose_matrix_q)\n",
338
+ "\n",
339
+ " res_pose = sapien.Pose(\n",
340
+ " p=global_grasp_pose_p,\n",
341
+ " q=global_grasp_pose_q,\n",
342
+ " )\n",
343
+ " # TODO @###########################\n",
344
+ " res_pose = self.choose_best_pose(\n",
345
+ " res_pose, \n",
346
+ " contact_point, \n",
347
+ " )\n",
348
+ " # ##########################\n",
349
+ "\n",
350
+ " return res_pose\n",
351
+ "\n",
352
+ " def choose_grasp_pose(\n",
353
+ " self,\n",
354
+ "\n",
355
+ " # TODO literal\n",
356
+ " # (\"top_down_little_left\" if arm_tag == \"right\" else \"top_down_little_right\")\n",
357
+ " topdown_grasp_direction: str,\n",
358
+ " # TODO literal\n",
359
+ " # TODO {left,right}_embodiment_args.get(\"grasp_perfect_direction\", [\"front_right\", \"front_left\"])[0]\n",
360
+ " side_grasp_direction: str,\n",
361
+ "\n",
362
+ " # TODO = actor.iter_contact_points(),\n",
363
+ " contact_points: list[sapien.Pose],\n",
364
+ "\n",
365
+ " pre_dis=0.1,\n",
366
+ " target_dis=0,\n",
367
+ " ) -> list:\n",
368
+ " \"\"\"\n",
369
+ " Test the grasp pose function.\n",
370
+ " - actor: The actor to be grasped.\n",
371
+ " - arm_tag: The arm to be used for grasping, either \"left\" or \"right\".\n",
372
+ " - pre_dis: The distance in front of the grasp point, default is 0.1.\n",
373
+ " \"\"\"\n",
374
+ "\n",
375
+ " # if not self.plan_success:\n",
376
+ " # return\n",
377
+ " \n",
378
+ " res_pre_top_down_pose = None\n",
379
+ " res_top_down_pose = None\n",
380
+ " dis_top_down = 1e9\n",
381
+ " res_pre_side_pose = None\n",
382
+ " res_side_pose = None\n",
383
+ " dis_side = 1e9\n",
384
+ " res_pre_pose = None\n",
385
+ " res_pose = None\n",
386
+ " dis = 1e9\n",
387
+ "\n",
388
+ " # TODO read from config\n",
389
+ " # TODO left_embodiment_args.get(\"grasp_perfect_direction\", [\"front_right\", \"front_left\"])[0]\n",
390
+ " # pref_direction = self.robot.get_grasp_perfect_direction(arm_tag)\n",
391
+ " # ##################################\n",
392
+ "\n",
393
+ " def get_grasp_pose(pre_grasp_pose, pre_grasp_dis):\n",
394
+ " import copy\n",
395
+ " grasp_pose = copy.deepcopy(pre_grasp_pose)\n",
396
+ " grasp_pose = np.array(grasp_pose)\n",
397
+ " direction_mat = t3d.quaternions.quat2mat(grasp_pose[-4:])\n",
398
+ " grasp_pose[:3] += [pre_grasp_dis, 0, 0] @ np.linalg.inv(direction_mat)\n",
399
+ " grasp_pose = grasp_pose.tolist()\n",
400
+ " return sapien.Pose(grasp_pose[:3], grasp_pose[3:])\n",
401
+ "\n",
402
+ " # def check_pose(pre_pose, pose, arm_tag):\n",
403
+ " # if arm_tag == \"left\":\n",
404
+ " # plan_func = self.robot.left_plan_path\n",
405
+ " # else:\n",
406
+ " # plan_func = self.robot.right_plan_path\n",
407
+ " # pre_path = plan_func(pre_pose)\n",
408
+ " # if pre_path[\"status\"] != \"Success\":\n",
409
+ " # return False\n",
410
+ " # pre_qpos = pre_path[\"position\"][-1]\n",
411
+ " # return plan_func(pose)[\"status\"] == \"Success\"\n",
412
+ "\n",
413
+ " for contact_point in contact_points:\n",
414
+ " pre_pose = self.get_grasp_pose(contact_point=contact_point, pre_dis=pre_dis)\n",
415
+ " if pre_pose is None:\n",
416
+ " continue\n",
417
+ " pose = get_grasp_pose(pre_pose, pre_dis - target_dis)\n",
418
+ " now_dis_top_down = cal_quat_dis(\n",
419
+ " pose.q,\n",
420
+ " GRASP_DIRECTION_DIC[topdown_grasp_direction],\n",
421
+ " )\n",
422
+ " now_dis_side = cal_quat_dis(\n",
423
+ " pose.q, \n",
424
+ " GRASP_DIRECTION_DIC[side_grasp_direction],\n",
425
+ " )\n",
426
+ "\n",
427
+ " if res_pre_top_down_pose is None or now_dis_top_down < dis_top_down:\n",
428
+ " res_pre_top_down_pose = pre_pose\n",
429
+ " res_top_down_pose = pose\n",
430
+ " dis_top_down = now_dis_top_down\n",
431
+ "\n",
432
+ " if res_pre_side_pose is None or now_dis_side < dis_side:\n",
433
+ " res_pre_side_pose = pre_pose\n",
434
+ " res_side_pose = pose\n",
435
+ " dis_side = now_dis_side\n",
436
+ "\n",
437
+ " now_dis = 0.7 * now_dis_top_down + 0.3 * now_dis_side\n",
438
+ " if res_pre_pose is None or now_dis < dis:\n",
439
+ " res_pre_pose = pre_pose\n",
440
+ " res_pose = pose\n",
441
+ " dis = now_dis\n",
442
+ "\n",
443
+ " if dis_top_down < 0.15:\n",
444
+ " return res_pre_top_down_pose, res_top_down_pose\n",
445
+ " if dis_side < 0.15:\n",
446
+ " return res_pre_side_pose, res_side_pose\n",
447
+ " return res_pre_pose, res_pose\n",
448
+ "\n",
449
+ " def grasp_actor(\n",
450
+ " self,\n",
451
+ "\n",
452
+ " contact_points: list[sapien.Pose],\n",
453
+ "\n",
454
+ " pre_grasp_dis=0.1,\n",
455
+ " grasp_dis=0,\n",
456
+ " gripper_pos=0.0,\n",
457
+ " ):\n",
458
+ " # if not self.plan_success:\n",
459
+ " # return None, []\n",
460
+ "\n",
461
+ " # NOTE no longer used ~!!!!!!!\n",
462
+ " arm_tag = None\n",
463
+ " \n",
464
+ " pre_grasp_pose, grasp_pose = self.choose_grasp_pose(\n",
465
+ " contact_points=contact_points,\n",
466
+ " pre_dis=pre_grasp_dis,\n",
467
+ " target_dis=grasp_dis,\n",
468
+ " )\n",
469
+ " if pre_grasp_pose == grasp_dis:\n",
470
+ " return arm_tag, [\n",
471
+ " Action(arm_tag, \"move\", target_pose=pre_grasp_pose),\n",
472
+ " Action(arm_tag, \"close\", target_gripper_pos=gripper_pos),\n",
473
+ " ]\n",
474
+ " else:\n",
475
+ " return arm_tag, [\n",
476
+ " Action(arm_tag, \"move\", target_pose=pre_grasp_pose),\n",
477
+ " Action(\n",
478
+ " arm_tag,\n",
479
+ " \"move\",\n",
480
+ " target_pose=grasp_pose,\n",
481
+ " constraint_pose=[1, 1, 1, 0, 0, 0],\n",
482
+ " ),\n",
483
+ " Action(arm_tag, \"close\", target_gripper_pos=gripper_pos),\n",
484
+ " ]\n",
485
+ " \n",
486
+ "\n",
487
+ " # TODO !!!!!!!! use sapien.Pose\n",
488
+ " # TODO use sapien.Pose.__mul__\n",
489
+ " def move_by_displacement(\n",
490
+ " self,\n",
491
+ "\n",
492
+ " # TODO\n",
493
+ " # curr_pose: sapien.Pose,\n",
494
+ "\n",
495
+ " arm_tag: ArmTag,\n",
496
+ "\n",
497
+ "\n",
498
+ " x: float = 0.0,\n",
499
+ " y: float = 0.0,\n",
500
+ " z: float = 0.0,\n",
501
+ " quat: list = None,\n",
502
+ " move_axis: Literal[\"world\", \"arm\"] = \"world\",\n",
503
+ " ):\n",
504
+ " # TODO ##############\n",
505
+ " if arm_tag == \"left\":\n",
506
+ " origin_pose = (self.robot.get_left_ee_pose())\n",
507
+ " if arm_tag == \"right\":\n",
508
+ " origin_pose = (self.robot.get_right_ee_pose())\n",
509
+ " # ##################\n",
510
+ " \n",
511
+ " # TODO sapien.Pose\n",
512
+ " displacement = np.zeros(7, dtype=np.float64)\n",
513
+ " if move_axis == \"world\":\n",
514
+ " displacement[:3] = np.array([x, y, z], dtype=np.float64)\n",
515
+ " else:\n",
516
+ " # TODO\n",
517
+ " dir_vec = (origin_pose).to_transformation_matrix()[:3, 0]\n",
518
+ " dir_vec /= np.linalg.norm(dir_vec)\n",
519
+ " displacement[:3] = -z * dir_vec\n",
520
+ "\n",
521
+ " origin_pose += displacement\n",
522
+ " if quat is not None:\n",
523
+ " origin_pose[3:] = quat\n",
524
+ "\n",
525
+ " # TODO\n",
526
+ " origin_pose = sapien.Pose(p=origin_pose[:3], q=origin_pose[3:])\n",
527
+ " return arm_tag, [Action(arm_tag, \"move\", target_pose=origin_pose)]\n",
528
+ " \n",
529
+ "\n",
530
+ " def get_place_pose(\n",
531
+ " self,\n",
532
+ "\n",
533
+ " # TODO\n",
534
+ " # end_effector_pose = (self.robot.get_left_ee_pose() if arm_tag == \"left\" else self.robot.get_right_ee_pose())\n",
535
+ " end_effector_pose: sapien.Pose,\n",
536
+ "\n",
537
+ " # TODO orig: actor: Actor,\n",
538
+ " actor_initial_pose: sapien.Pose,\n",
539
+ " # TODO NOTE world coord\n",
540
+ " # TODO = actor.get_functional_point(functional_point_id, \"pose\")\n",
541
+ " actor_functional_point_pose: sapien.Pose | None,\n",
542
+ " \n",
543
+ " \n",
544
+ " # TODO orig: target_pose: list | np.ndarray,\n",
545
+ " target_pose: sapien.Pose, \n",
546
+ "\n",
547
+ " # TODO\n",
548
+ " constrain: Literal[\"free\", \"align\", \"auto_left\", \"auto_right\"] = \"free\",\n",
549
+ "\n",
550
+ "\n",
551
+ " align_axis: list[np.ndarray] | np.ndarray | list = None,\n",
552
+ " actor_axis: np.ndarray | list = [1, 0, 0],\n",
553
+ " actor_axis_type: Literal[\"actor\", \"world\"] = \"actor\",\n",
554
+ " pre_dis: float = 0.1,\n",
555
+ " pre_dis_axis: Literal[\"grasp\", \"fp\"] | np.ndarray | list = \"grasp\",\n",
556
+ " ):\n",
557
+ "\n",
558
+ "\n",
559
+ " # TODO raise\n",
560
+ " # if not self.plan_success:\n",
561
+ " # return [-1, -1, -1, -1, -1, -1, -1]\n",
562
+ "\n",
563
+ " actor_matrix = actor_initial_pose.to_transformation_matrix()\n",
564
+ " if actor_functional_point_pose is not None:\n",
565
+ " place_start_pose = actor_functional_point_pose\n",
566
+ " z_transform = False\n",
567
+ " else:\n",
568
+ " place_start_pose = actor_initial_pose\n",
569
+ " z_transform = True\n",
570
+ "\n",
571
+ " if constrain == \"auto_left\" or constrain == \"auto_right\":\n",
572
+ " grasp_direct_vec = place_start_pose.p - end_effector_pose[:3]\n",
573
+ " if np.abs(np.dot(grasp_direct_vec, [0, 0, 1])) <= 0.1:\n",
574
+ " place_pose = get_place_pose(\n",
575
+ " place_start_pose,\n",
576
+ " target_pose,\n",
577
+ " constrain=\"align\",\n",
578
+ " actor_axis=grasp_direct_vec,\n",
579
+ " actor_axis_type=\"world\",\n",
580
+ " align_axis=[1, 1, 0] if constrain == \"auto_left\" else [-1, 1, 0],\n",
581
+ " z_transform=z_transform,\n",
582
+ " )\n",
583
+ " else:\n",
584
+ " camera_vec = (end_effector_pose).to_transformation_matrix()[:3, 2]\n",
585
+ " place_pose = get_place_pose(\n",
586
+ " place_start_pose,\n",
587
+ " target_pose,\n",
588
+ " constrain=\"align\",\n",
589
+ " actor_axis=camera_vec,\n",
590
+ " actor_axis_type=\"world\",\n",
591
+ " align_axis=[0, 1, 0],\n",
592
+ " z_transform=z_transform,\n",
593
+ " )\n",
594
+ " else:\n",
595
+ " place_pose = get_place_pose(\n",
596
+ " place_start_pose,\n",
597
+ " target_pose,\n",
598
+ " constrain=constrain,\n",
599
+ " actor_axis=actor_axis,\n",
600
+ " actor_axis_type=actor_axis_type,\n",
601
+ " align_axis=align_axis,\n",
602
+ " z_transform=z_transform,\n",
603
+ " )\n",
604
+ "\n",
605
+ "\n",
606
+ " start2target = ((place_pose).to_transformation_matrix()[:3, :3]\n",
607
+ " @ place_start_pose.to_transformation_matrix()[:3, :3].T)\n",
608
+ " target_point = (start2target @ (actor_matrix[:3, 3] - place_start_pose.p).reshape(3, 1)).reshape(3) + np.array(\n",
609
+ " place_pose[:3])\n",
610
+ "\n",
611
+ " ee_pose_matrix = t3d.quaternions.quat2mat(end_effector_pose[-4:])\n",
612
+ " target_grasp_matrix = start2target @ ee_pose_matrix\n",
613
+ "\n",
614
+ " res_matrix = np.eye(4)\n",
615
+ " res_matrix[:3, 3] = actor_matrix[:3, 3] - end_effector_pose[:3]\n",
616
+ " res_matrix[:3, 3] = np.linalg.inv(ee_pose_matrix) @ res_matrix[:3, 3]\n",
617
+ " target_grasp_qpose = t3d.quaternions.mat2quat(target_grasp_matrix)\n",
618
+ "\n",
619
+ " grasp_bias = target_grasp_matrix @ res_matrix[:3, 3]\n",
620
+ " if pre_dis_axis == \"grasp\":\n",
621
+ " target_dis_vec = target_grasp_matrix @ res_matrix[:3, 3]\n",
622
+ " target_dis_vec /= np.linalg.norm(target_dis_vec)\n",
623
+ " else:\n",
624
+ " target_pose_mat = (target_pose).to_transformation_matrix()\n",
625
+ " if pre_dis_axis == \"fp\":\n",
626
+ " pre_dis_axis = [0.0, 0.0, 1.0]\n",
627
+ " pre_dis_axis = np.array(pre_dis_axis)\n",
628
+ " pre_dis_axis /= np.linalg.norm(pre_dis_axis)\n",
629
+ " target_dis_vec = (target_pose_mat[:3, :3] @ np.array(pre_dis_axis).reshape(3, 1)).reshape(3)\n",
630
+ " target_dis_vec /= np.linalg.norm(target_dis_vec)\n",
631
+ "\n",
632
+ "\n",
633
+ " return sapien.Pose(\n",
634
+ " p=target_point - grasp_bias - pre_dis * target_dis_vec,\n",
635
+ " q=target_grasp_qpose,\n",
636
+ " )\n",
637
+ "\n",
638
+ "\n",
639
+ " def _Ttodo_plan_place_actor(\n",
640
+ " self,\n",
641
+ "\n",
642
+ " # TODO !!!!!!! read directly\n",
643
+ " end_effector_pose: sapien.Pose,\n",
644
+ " \n",
645
+ " # TODO orig: actor: Actor,\n",
646
+ " actor_initial_pose: sapien.Pose,\n",
647
+ " # TODO = actor.get_functional_point(functional_point_id, \"pose\")\n",
648
+ " actor_functional_point_pose: sapien.Pose | None,\n",
649
+ "\n",
650
+ " target_pose: sapien.Pose,\n",
651
+ " \n",
652
+ " # TODO multiple distances instead\n",
653
+ " pre_dis: float = 0.1,\n",
654
+ " dis: float = 0.02,\n",
655
+ " # ####\n",
656
+ "\n",
657
+ " is_open: bool = True,\n",
658
+ " **args,\n",
659
+ " ):\n",
660
+ " \n",
661
+ "\n",
662
+ " # TODO raise \n",
663
+ " # if not self.plan_success:\n",
664
+ " # return None, []\n",
665
+ " arm_tag = None # NOTE unused\n",
666
+ "\n",
667
+ "\n",
668
+ " place_pre_pose = self.get_place_pose(\n",
669
+ " end_effector_pose=end_effector_pose,\n",
670
+ " actor_initial_pose=actor_initial_pose,\n",
671
+ " actor_functional_point_pose=actor_functional_point_pose,\n",
672
+ " target_pose=target_pose,\n",
673
+ " pre_dis=pre_dis,\n",
674
+ " **args,\n",
675
+ " )\n",
676
+ " place_pose = self.get_place_pose(\n",
677
+ " end_effector_pose=end_effector_pose,\n",
678
+ " actor_initial_pose=actor_initial_pose,\n",
679
+ " actor_functional_point_pose=actor_functional_point_pose,\n",
680
+ " target_pose=target_pose,\n",
681
+ " pre_dis=dis,\n",
682
+ " **args,\n",
683
+ " )\n",
684
+ "\n",
685
+ " actions = [\n",
686
+ " Action(arm_tag, \"move\", target_pose=place_pre_pose),\n",
687
+ " Action(arm_tag, \"move\", target_pose=place_pose),\n",
688
+ " ]\n",
689
+ " if is_open:\n",
690
+ " actions.append(Action(arm_tag, \"open\", target_gripper_pos=1.0))\n",
691
+ " return arm_tag, actions\n"
692
+ ]
693
+ },
694
+ {
695
+ "cell_type": "code",
696
+ "execution_count": null,
697
+ "id": "886fd176",
698
+ "metadata": {},
699
+ "outputs": [],
700
+ "source": [
701
+ "\n"
702
+ ]
703
+ },
704
+ {
705
+ "cell_type": "code",
706
+ "execution_count": null,
707
+ "id": "5cac2a92",
708
+ "metadata": {},
709
+ "outputs": [],
710
+ "source": [
711
+ "from copy import deepcopy\n",
712
+ "\n",
713
+ "class TODOMotionExec:\n",
714
+ " \n",
715
+ "\n",
716
+ " def together_move_to_pose(\n",
717
+ " self,\n",
718
+ " left_target_pose,\n",
719
+ " right_target_pose,\n",
720
+ " left_constraint_pose=None,\n",
721
+ " right_constraint_pose=None,\n",
722
+ " use_point_cloud=False,\n",
723
+ " use_attach=False,\n",
724
+ " # save_freq=-1,\n",
725
+ " ):\n",
726
+ " \"\"\"\n",
727
+ " Interpolative planning with screw motion.\n",
728
+ " Will not avoid collision and will fail if the path contains collision.\n",
729
+ " \"\"\"\n",
730
+ " if not self.plan_success:\n",
731
+ " return\n",
732
+ " if left_target_pose is None or right_target_pose is None:\n",
733
+ " self.plan_success = False; raise Exception('TODO plan failure')\n",
734
+ " return\n",
735
+ " if type(left_target_pose) == sapien.Pose:\n",
736
+ " left_target_pose = left_target_pose.p.tolist() + left_target_pose.q.tolist()\n",
737
+ " if type(right_target_pose) == sapien.Pose:\n",
738
+ " right_target_pose = (right_target_pose.p.tolist() + right_target_pose.q.tolist())\n",
739
+ " # save_freq = self.save_freq if save_freq == -1 else save_freq\n",
740
+ "\n",
741
+ " # TODO\n",
742
+ " if self.need_plan:\n",
743
+ " left_result = self.robot.left_plan_path(left_target_pose, constraint_pose=left_constraint_pose)\n",
744
+ " right_result = self.robot.right_plan_path(right_target_pose, constraint_pose=right_constraint_pose)\n",
745
+ " # TODO for recording purposes only???\n",
746
+ " self.left_joint_path.append(deepcopy(left_result))\n",
747
+ " self.right_joint_path.append(deepcopy(right_result))\n",
748
+ " else:\n",
749
+ " left_result = deepcopy(self.left_joint_path[self.left_cnt])\n",
750
+ " right_result = deepcopy(self.right_joint_path[self.right_cnt])\n",
751
+ " self.left_cnt += 1\n",
752
+ " self.right_cnt += 1\n",
753
+ "\n",
754
+ " # TODO\n",
755
+ " # try:\n",
756
+ " # left_success = left_result[\"status\"] == \"Success\"\n",
757
+ " # right_success = right_result[\"status\"] == \"Success\"\n",
758
+ " # if not left_success or not right_success:\n",
759
+ " # self.plan_success = False; raise Exception('TODO plan failure')\n",
760
+ " # # return TODO\n",
761
+ " # except Exception as e:\n",
762
+ " # if left_result is None or right_result is None:\n",
763
+ " # self.plan_success = False; raise Exception('TODO plan failure')\n",
764
+ " # return # TODO\n",
765
+ " \n",
766
+ " if left_result is None or right_result is None:\n",
767
+ " self.plan_success = False; raise Exception('TODO plan failure')\n",
768
+ " return # TODO\n",
769
+ " left_success = left_result[\"status\"] == \"Success\"\n",
770
+ " right_success = right_result[\"status\"] == \"Success\"\n",
771
+ " if not left_success or not right_success:\n",
772
+ " self.plan_success = False; raise Exception(rf'TODO plan failure: {left_result} {right_result}')\n",
773
+ " # return TODO\n",
774
+ "\n",
775
+ " # if save_freq != None:\n",
776
+ " # self._take_picture()\n",
777
+ "\n",
778
+ " now_left_id = 0\n",
779
+ " now_right_id = 0\n",
780
+ " # i = 0\n",
781
+ "\n",
782
+ " left_n_step = left_result[\"position\"].shape[0] if left_success else 0\n",
783
+ " right_n_step = right_result[\"position\"].shape[0] if right_success else 0\n",
784
+ "\n",
785
+ " while now_left_id < left_n_step or now_right_id < right_n_step:\n",
786
+ " # set the joint positions and velocities for move group joints only.\n",
787
+ " # The others are not the responsibility of the planner\n",
788
+ " if (left_success and now_left_id < left_n_step\n",
789
+ " and (not right_success or now_left_id / left_n_step <= now_right_id / right_n_step)):\n",
790
+ " self.robot.set_arm_joints(\n",
791
+ " left_result[\"position\"][now_left_id],\n",
792
+ " left_result[\"velocity\"][now_left_id],\n",
793
+ " \"left\",\n",
794
+ " )\n",
795
+ " now_left_id += 1\n",
796
+ "\n",
797
+ " if (right_success and now_right_id < right_n_step\n",
798
+ " and (not left_success or now_right_id / right_n_step <= now_left_id / left_n_step)):\n",
799
+ " self.robot.set_arm_joints(\n",
800
+ " right_result[\"position\"][now_right_id],\n",
801
+ " right_result[\"velocity\"][now_right_id],\n",
802
+ " \"right\",\n",
803
+ " )\n",
804
+ " now_right_id += 1\n",
805
+ "\n",
806
+ " # TODO\n",
807
+ " self.scene.step()\n",
808
+ " # if self.render_freq and i % self.render_freq == 0:\n",
809
+ " # self._update_render()\n",
810
+ " # self.viewer.render()\n",
811
+ "\n",
812
+ " # if save_freq != None and i % save_freq == 0:\n",
813
+ " # self._update_render()\n",
814
+ " # self._take_picture()\n",
815
+ " # i += 1\n",
816
+ "\n",
817
+ " # if save_freq != None:\n",
818
+ " # self._take_picture()\n",
819
+ "\n",
820
+ "\n",
821
+ " def move(\n",
822
+ " self,\n",
823
+ " actions_by_arm1: tuple[ArmTag, list[Action]],\n",
824
+ " actions_by_arm2: tuple[ArmTag, list[Action]] = None,\n",
825
+ " save_freq=-1,\n",
826
+ " ):\n",
827
+ " \"\"\"\n",
828
+ " Take action for the robot.\n",
829
+ " \"\"\"\n",
830
+ "\n",
831
+ " def get_actions(actions, arm_tag: ArmTag) -> list[Action]:\n",
832
+ " if actions[1] is None:\n",
833
+ " if actions[0][0] == arm_tag:\n",
834
+ " return actions[0][1]\n",
835
+ " else:\n",
836
+ " return []\n",
837
+ " else:\n",
838
+ " if actions[0][0] == actions[0][1]:\n",
839
+ " raise ValueError(\"\")\n",
840
+ " if actions[0][0] == arm_tag:\n",
841
+ " return actions[0][1]\n",
842
+ " else:\n",
843
+ " return actions[1][1]\n",
844
+ "\n",
845
+ " if self.plan_success is False:\n",
846
+ " return False\n",
847
+ "\n",
848
+ " actions = [actions_by_arm1, actions_by_arm2]\n",
849
+ " left_actions = get_actions(actions, \"left\")\n",
850
+ " right_actions = get_actions(actions, \"right\")\n",
851
+ "\n",
852
+ " max_len = max(len(left_actions), len(right_actions))\n",
853
+ " left_actions += [None] * (max_len - len(left_actions))\n",
854
+ " right_actions += [None] * (max_len - len(right_actions))\n",
855
+ "\n",
856
+ " for left, right in zip(left_actions, right_actions):\n",
857
+ "\n",
858
+ " if (left is not None and left.arm_tag != \"left\") or (right is not None\n",
859
+ " and right.arm_tag != \"right\"): # check\n",
860
+ " raise ValueError(f\"Invalid arm tag: {left.arm_tag} or {right.arm_tag}. Must be 'left' or 'right'.\")\n",
861
+ "\n",
862
+ " if (left is not None and left.action == \"move\") and (right is not None\n",
863
+ " and right.action == \"move\"): # together move\n",
864
+ " self.together_move_to_pose( # TODO\n",
865
+ " left_target_pose=left.target_pose,\n",
866
+ " right_target_pose=right.target_pose,\n",
867
+ " left_constraint_pose=left.args.get(\"constraint_pose\"),\n",
868
+ " right_constraint_pose=right.args.get(\"constraint_pose\"),\n",
869
+ " )\n",
870
+ " if self.plan_success is False:\n",
871
+ " return False\n",
872
+ " continue # TODO\n",
873
+ " else:\n",
874
+ " control_seq = {\n",
875
+ " \"left_arm\": None,\n",
876
+ " \"left_gripper\": None,\n",
877
+ " \"right_arm\": None,\n",
878
+ " \"right_gripper\": None,\n",
879
+ " }\n",
880
+ " if left is not None:\n",
881
+ " if left.action == \"move\":\n",
882
+ " control_seq[\"left_arm\"] = self.left_move_to_pose(\n",
883
+ " pose=left.target_pose,\n",
884
+ " constraint_pose=left.args.get(\"constraint_pose\"),\n",
885
+ " )\n",
886
+ " else: # left.action == 'gripper'\n",
887
+ " control_seq[\"left_gripper\"] = self.set_gripper(left_pos=left.target_gripper_pos, set_tag=\"left\")\n",
888
+ " if self.plan_success is False:\n",
889
+ " return False\n",
890
+ "\n",
891
+ " # if right is not None:\n",
892
+ " # if right.action == \"move\":\n",
893
+ " # control_seq[\"right_arm\"] = self.right_move_to_pose(\n",
894
+ " # pose=right.target_pose,\n",
895
+ " # constraint_pose=right.args.get(\"constraint_pose\"),\n",
896
+ " # )\n",
897
+ " # else: # right.action == 'gripper'\n",
898
+ " # control_seq[\"right_gripper\"] = self.set_gripper(right_pos=right.target_gripper_pos,\n",
899
+ " # set_tag=\"right\")\n",
900
+ " # if self.plan_success is False:\n",
901
+ " # return False\n",
902
+ "\n",
903
+ " self.take_dense_action(control_seq)\n",
904
+ "\n",
905
+ " return True\n",
906
+ " \n",
907
+ "\n",
908
+ " def take_dense_action(self, control_seq, save_freq=-1):\n",
909
+ " \"\"\"\n",
910
+ " control_seq:\n",
911
+ " left_arm, right_arm, left_gripper, right_gripper\n",
912
+ " \"\"\"\n",
913
+ " left_arm, left_gripper, right_arm, right_gripper = (\n",
914
+ " control_seq[\"left_arm\"],\n",
915
+ " control_seq[\"left_gripper\"],\n",
916
+ " control_seq[\"right_arm\"],\n",
917
+ " control_seq[\"right_gripper\"],\n",
918
+ " )\n",
919
+ "\n",
920
+ " # TODO rm\n",
921
+ " # save_freq = self.save_freq if save_freq == -1 else save_freq\n",
922
+ " # if save_freq != None:\n",
923
+ " # self._take_picture()\n",
924
+ "\n",
925
+ " max_control_len = 0\n",
926
+ "\n",
927
+ " if left_arm is not None:\n",
928
+ " max_control_len = max(max_control_len, left_arm[\"position\"].shape[0])\n",
929
+ " if left_gripper is not None:\n",
930
+ " max_control_len = max(max_control_len, left_gripper[\"num_step\"])\n",
931
+ " if right_arm is not None:\n",
932
+ " max_control_len = max(max_control_len, right_arm[\"position\"].shape[0])\n",
933
+ " if right_gripper is not None:\n",
934
+ " max_control_len = max(max_control_len, right_gripper[\"num_step\"])\n",
935
+ "\n",
936
+ " for control_idx in range(max_control_len):\n",
937
+ "\n",
938
+ " if (left_arm is not None and control_idx < left_arm[\"position\"].shape[0]): # control left arm\n",
939
+ " self.robot.set_arm_joints(\n",
940
+ " left_arm[\"position\"][control_idx],\n",
941
+ " left_arm[\"velocity\"][control_idx],\n",
942
+ " \"left\",\n",
943
+ " )\n",
944
+ "\n",
945
+ " if left_gripper is not None and control_idx < left_gripper[\"num_step\"]:\n",
946
+ " self.robot.set_gripper(\n",
947
+ " left_gripper[\"result\"][control_idx],\n",
948
+ " \"left\",\n",
949
+ " left_gripper[\"per_step\"],\n",
950
+ " ) # TODO\n",
951
+ "\n",
952
+ " if (right_arm is not None and control_idx < right_arm[\"position\"].shape[0]): # control right arm\n",
953
+ " self.robot.set_arm_joints(\n",
954
+ " right_arm[\"position\"][control_idx],\n",
955
+ " right_arm[\"velocity\"][control_idx],\n",
956
+ " \"right\",\n",
957
+ " )\n",
958
+ "\n",
959
+ " if right_gripper is not None and control_idx < right_gripper[\"num_step\"]:\n",
960
+ " self.robot.set_gripper(\n",
961
+ " right_gripper[\"result\"][control_idx],\n",
962
+ " \"right\",\n",
963
+ " right_gripper[\"per_step\"],\n",
964
+ " ) # TODO\n",
965
+ "\n",
966
+ " # TODO\n",
967
+ " self.scene.step()\n",
968
+ "\n",
969
+ " # TODO rm\n",
970
+ " # if self.render_freq and control_idx % self.render_freq == 0:\n",
971
+ " # self._update_render()\n",
972
+ " # self.viewer.render()\n",
973
+ "\n",
974
+ " # if save_freq != None and control_idx % save_freq == 0:\n",
975
+ " # self._update_render()\n",
976
+ " # self._take_picture()\n",
977
+ "\n",
978
+ " # if save_freq != None:\n",
979
+ " # self._take_picture()\n",
980
+ "\n",
981
+ " return True # TODO: maybe need try error"
982
+ ]
983
+ },
984
+ {
985
+ "cell_type": "code",
986
+ "execution_count": null,
987
+ "id": "43a9e58d",
988
+ "metadata": {},
989
+ "outputs": [],
990
+ "source": []
991
+ }
992
+ ],
993
+ "metadata": {
994
+ "language_info": {
995
+ "name": "python"
996
+ }
997
+ },
998
+ "nbformat": 4,
999
+ "nbformat_minor": 5
1000
+ }
__todo__/todo-pi0-ckpt.ipynb CHANGED
The diff for this file is too large to render. See raw diff
 
__todo__/todo-pi0-v1.ipynb ADDED
@@ -0,0 +1,2328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "id": "78e10bc1",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": []
10
+ },
11
+ {
12
+ "cell_type": "code",
13
+ "execution_count": 1,
14
+ "id": "8abdf5e2",
15
+ "metadata": {},
16
+ "outputs": [],
17
+ "source": [
18
+ "from robotodo.controllers.pi0 import Pi0Controller\n",
19
+ "from robotodo.controllers.pi0.nn.pi0 import Pi0\n",
20
+ "\n"
21
+ ]
22
+ },
23
+ {
24
+ "cell_type": "code",
25
+ "execution_count": null,
26
+ "id": "2c5defb7",
27
+ "metadata": {},
28
+ "outputs": [],
29
+ "source": []
30
+ },
31
+ {
32
+ "cell_type": "code",
33
+ "execution_count": 2,
34
+ "id": "d75d8c32",
35
+ "metadata": {},
36
+ "outputs": [
37
+ {
38
+ "data": {
39
+ "text/plain": [
40
+ "Dict('images': Dict('base_0_rgb': Box(0.0, 1.0, (224, 224, 3), float32), 'left_wrist_0_rgb': Box(0.0, 1.0, (224, 224, 3), float32), 'right_wrist_0_rgb': Box(0.0, 1.0, (224, 224, 3), float32)), 'joint_state': Dict('todo': Box(-inf, inf, (), float32)), 'text': Text(1, 48, charset=0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz))"
41
+ ]
42
+ },
43
+ "execution_count": 2,
44
+ "metadata": {},
45
+ "output_type": "execute_result"
46
+ }
47
+ ],
48
+ "source": [
49
+ "Pi0Controller.ObservationSpec()"
50
+ ]
51
+ },
52
+ {
53
+ "cell_type": "code",
54
+ "execution_count": null,
55
+ "id": "24d15721",
56
+ "metadata": {},
57
+ "outputs": [
58
+ {
59
+ "data": {
60
+ "text/plain": [
61
+ "{'numeric_states': (array([-0.34458885], dtype=float32),\n",
62
+ " array([1.0347432], dtype=float32),\n",
63
+ " array([1.9053354], dtype=float32),\n",
64
+ " array([-0.1576305], dtype=float32),\n",
65
+ " array([0.24221042], dtype=float32),\n",
66
+ " array([-1.2492683], dtype=float32))}"
67
+ ]
68
+ },
69
+ "execution_count": 12,
70
+ "metadata": {},
71
+ "output_type": "execute_result"
72
+ }
73
+ ],
74
+ "source": [
75
+ "action = Pi0Controller.ActionSpec().sample()\n",
76
+ "\n",
77
+ "batch_action_nn = Pi0Controller._encode_action(\n",
78
+ " target_spec=Pi0.ActionSpec(),\n",
79
+ " source_spec=Pi0Controller.ActionSpec(),\n",
80
+ " maybe_batch=action,\n",
81
+ ")\n",
82
+ "batch_action_nn"
83
+ ]
84
+ },
85
+ {
86
+ "cell_type": "code",
87
+ "execution_count": null,
88
+ "id": "9da8913b",
89
+ "metadata": {},
90
+ "outputs": [
91
+ {
92
+ "data": {
93
+ "text/plain": [
94
+ "True"
95
+ ]
96
+ },
97
+ "execution_count": 14,
98
+ "metadata": {},
99
+ "output_type": "execute_result"
100
+ }
101
+ ],
102
+ "source": [
103
+ "Pi0Controller._decode_action(\n",
104
+ " target_action_spec=Pi0Controller.ActionSpec(),\n",
105
+ " source_action_spec=Pi0.ActionSpec(),\n",
106
+ " maybe_batch_action=batch_action_nn,\n",
107
+ ") == action"
108
+ ]
109
+ },
110
+ {
111
+ "cell_type": "code",
112
+ "execution_count": 11,
113
+ "id": "93cffaf8",
114
+ "metadata": {},
115
+ "outputs": [
116
+ {
117
+ "data": {
118
+ "text/plain": [
119
+ "{'joint_states': ({'todo': array(1.0434374, dtype=float32)},\n",
120
+ " {'todo': array(1.2621018, dtype=float32)})}"
121
+ ]
122
+ },
123
+ "execution_count": 11,
124
+ "metadata": {},
125
+ "output_type": "execute_result"
126
+ }
127
+ ],
128
+ "source": [
129
+ "action"
130
+ ]
131
+ },
132
+ {
133
+ "cell_type": "code",
134
+ "execution_count": 3,
135
+ "id": "52b10e6e",
136
+ "metadata": {},
137
+ "outputs": [
138
+ {
139
+ "data": {
140
+ "text/plain": [
141
+ "Dict('joint_states': Sequence(Dict('todo': Box(-inf, inf, (), float32)), stack=False))"
142
+ ]
143
+ },
144
+ "execution_count": 3,
145
+ "metadata": {},
146
+ "output_type": "execute_result"
147
+ }
148
+ ],
149
+ "source": [
150
+ "Pi0Controller.ActionSpec()"
151
+ ]
152
+ },
153
+ {
154
+ "cell_type": "code",
155
+ "execution_count": null,
156
+ "id": "00e45a61",
157
+ "metadata": {},
158
+ "outputs": [],
159
+ "source": [
160
+ "observation_spec = Pi0Controller.ObservationSpec()\n"
161
+ ]
162
+ },
163
+ {
164
+ "cell_type": "code",
165
+ "execution_count": 4,
166
+ "id": "e04137d4",
167
+ "metadata": {},
168
+ "outputs": [
169
+ {
170
+ "data": {
171
+ "text/plain": [
172
+ "Box(0.0, 1.0, (451584,), float32)"
173
+ ]
174
+ },
175
+ "execution_count": 4,
176
+ "metadata": {},
177
+ "output_type": "execute_result"
178
+ }
179
+ ],
180
+ "source": [
181
+ "from gymnasium.spaces.utils import flatten_space\n",
182
+ "\n",
183
+ "flatten_space(observation_spec[\"images\"])"
184
+ ]
185
+ },
186
+ {
187
+ "cell_type": "code",
188
+ "execution_count": 8,
189
+ "id": "d9c5e1c3",
190
+ "metadata": {},
191
+ "outputs": [
192
+ {
193
+ "data": {
194
+ "text/plain": [
195
+ "[Box(0.0, 1.0, (224, 224, 3), float32),\n",
196
+ " Box(0.0, 1.0, (224, 224, 3), float32),\n",
197
+ " Box(0.0, 1.0, (224, 224, 3), float32)]"
198
+ ]
199
+ },
200
+ "execution_count": 8,
201
+ "metadata": {},
202
+ "output_type": "execute_result"
203
+ }
204
+ ],
205
+ "source": [
206
+ "list(observation_spec[\"images\"].values())"
207
+ ]
208
+ },
209
+ {
210
+ "cell_type": "code",
211
+ "execution_count": null,
212
+ "id": "f5b18199",
213
+ "metadata": {},
214
+ "outputs": [],
215
+ "source": []
216
+ },
217
+ {
218
+ "cell_type": "code",
219
+ "execution_count": null,
220
+ "id": "a0717400",
221
+ "metadata": {},
222
+ "outputs": [],
223
+ "source": []
224
+ },
225
+ {
226
+ "cell_type": "code",
227
+ "execution_count": 1,
228
+ "id": "326e301f",
229
+ "metadata": {},
230
+ "outputs": [],
231
+ "source": [
232
+ "from typing import Any\n",
233
+ "import gymnasium.spaces\n",
234
+ "a: \"gymnasium.spaces.Dict[Any, gymnasium.spaces.Box]\" = None"
235
+ ]
236
+ },
237
+ {
238
+ "cell_type": "code",
239
+ "execution_count": null,
240
+ "id": "a9d2c084",
241
+ "metadata": {},
242
+ "outputs": [],
243
+ "source": []
244
+ },
245
+ {
246
+ "cell_type": "code",
247
+ "execution_count": 2,
248
+ "id": "3b76c14b",
249
+ "metadata": {},
250
+ "outputs": [],
251
+ "source": [
252
+ "\n",
253
+ "import gymnasium.spaces\n",
254
+ "from gymnasium.spaces.utils import flatten_space, flatten\n",
255
+ "\n",
256
+ "\n",
257
+ "some_nested_space = gymnasium.spaces.Sequence(\n",
258
+ " gymnasium.spaces.Dict({\n",
259
+ " \"a\": gymnasium.spaces.Box(\n",
260
+ " low=0.0, high=1.0, shape=(3,), dtype=float\n",
261
+ " ),\n",
262
+ " \"b_nested_dict\": gymnasium.spaces.Dict({\n",
263
+ " \"c\": gymnasium.spaces.Box(\n",
264
+ " low=0.0, high=1.0, shape=(2,), dtype=float\n",
265
+ " ),\n",
266
+ " \"d\": gymnasium.spaces.Box(\n",
267
+ " low=0.0, high=1.0, shape=(224, 224, 3), dtype=float\n",
268
+ " ),\n",
269
+ " }),\n",
270
+ " }),\n",
271
+ " stack=True,\n",
272
+ ")\n"
273
+ ]
274
+ },
275
+ {
276
+ "cell_type": "code",
277
+ "execution_count": 3,
278
+ "id": "8de36cc3",
279
+ "metadata": {},
280
+ "outputs": [
281
+ {
282
+ "data": {
283
+ "text/plain": [
284
+ "Sequence(Box(0.0, 1.0, (150533,), float64), stack=True)"
285
+ ]
286
+ },
287
+ "execution_count": 3,
288
+ "metadata": {},
289
+ "output_type": "execute_result"
290
+ }
291
+ ],
292
+ "source": [
293
+ "flatten_space(some_nested_space)\n"
294
+ ]
295
+ },
296
+ {
297
+ "cell_type": "code",
298
+ "execution_count": 4,
299
+ "id": "d303b1e4",
300
+ "metadata": {},
301
+ "outputs": [
302
+ {
303
+ "data": {
304
+ "text/plain": [
305
+ "(14, 150533)"
306
+ ]
307
+ },
308
+ "execution_count": 4,
309
+ "metadata": {},
310
+ "output_type": "execute_result"
311
+ }
312
+ ],
313
+ "source": [
314
+ "flatten(some_nested_space, some_nested_space.sample()).shape"
315
+ ]
316
+ },
317
+ {
318
+ "cell_type": "code",
319
+ "execution_count": null,
320
+ "id": "15806932",
321
+ "metadata": {},
322
+ "outputs": [],
323
+ "source": []
324
+ },
325
+ {
326
+ "cell_type": "code",
327
+ "execution_count": 1,
328
+ "id": "864eb7bf",
329
+ "metadata": {},
330
+ "outputs": [
331
+ {
332
+ "name": "stdout",
333
+ "output_type": "stream",
334
+ "text": [
335
+ "env: JAX_PLATFORMS=cpu\n",
336
+ "env: XLA_PYTHON_CLIENT_PREALLOCATE=false\n"
337
+ ]
338
+ }
339
+ ],
340
+ "source": [
341
+ "%env JAX_PLATFORMS=cpu\n",
342
+ "# %env JAX_DISABLE_JIT=1 \n",
343
+ "# %env CUDA_VISIBLE_DEVICES=1\n",
344
+ "%env XLA_PYTHON_CLIENT_PREALLOCATE=false"
345
+ ]
346
+ },
347
+ {
348
+ "cell_type": "code",
349
+ "execution_count": 2,
350
+ "id": "4093262c",
351
+ "metadata": {},
352
+ "outputs": [],
353
+ "source": [
354
+ "import flax.nnx\n",
355
+ "import jax\n",
356
+ "from robotodo.controllers.pi0.nn.pi0 import Pi0\n",
357
+ "\n",
358
+ "\n",
359
+ "pi0 = Pi0(rngs=flax.nnx.Rngs(0), config=Pi0.Config(numeric_state_size=34, image_shape=(224, 224, 4)))"
360
+ ]
361
+ },
362
+ {
363
+ "cell_type": "code",
364
+ "execution_count": null,
365
+ "id": "45712b46",
366
+ "metadata": {},
367
+ "outputs": [],
368
+ "source": []
369
+ },
370
+ {
371
+ "cell_type": "code",
372
+ "execution_count": 3,
373
+ "id": "ea9fa329",
374
+ "metadata": {},
375
+ "outputs": [
376
+ {
377
+ "data": {
378
+ "text/plain": [
379
+ "Dict('images': Box(-1.0, 1.0, (10, 3, 224, 224, 4), float32), 'images.mask': Box(0, 1, (10, 3), uint8), 'numeric_state': Box(-inf, inf, (10, 34), float32), 'tokenized_text': Box(0, 257151, (10, 48), int32), 'tokenized_text.mask': Box(0, 1, (10, 48), uint8))"
380
+ ]
381
+ },
382
+ "execution_count": 3,
383
+ "metadata": {},
384
+ "output_type": "execute_result"
385
+ }
386
+ ],
387
+ "source": [
388
+ "pi0.observation_spec().batched(10)"
389
+ ]
390
+ },
391
+ {
392
+ "cell_type": "code",
393
+ "execution_count": null,
394
+ "id": "9fdc7624",
395
+ "metadata": {},
396
+ "outputs": [],
397
+ "source": []
398
+ },
399
+ {
400
+ "cell_type": "code",
401
+ "execution_count": 4,
402
+ "id": "ac849707",
403
+ "metadata": {},
404
+ "outputs": [
405
+ {
406
+ "data": {
407
+ "text/plain": [
408
+ "{'numeric_states': Array([[[ 1.38199329e-01, 1.10747504e+00, 8.35821748e-01,\n",
409
+ " 1.36278793e-01, 4.05587971e-01, -6.82720065e-01,\n",
410
+ " -2.63441622e-01, 6.68898642e-01, 1.42532682e+00,\n",
411
+ " -1.74349165e+00, 2.61842418e+00, -1.93898344e+00,\n",
412
+ " 9.29467916e-01, 9.33548808e-03, 2.76658177e+00,\n",
413
+ " 1.21262074e-01, -2.82733619e-01, 1.48521638e+00,\n",
414
+ " 1.02102184e+00, -1.32489061e+00, -1.71325207e-02,\n",
415
+ " 1.60174537e+00, 1.78692412e+00, 4.85989124e-01,\n",
416
+ " -6.55691564e-01, 3.34782690e-01, 3.19460869e-01,\n",
417
+ " 8.81149292e-01, -1.24743283e+00, -4.92948920e-01,\n",
418
+ " -1.07919240e+00, -9.41543281e-02, -2.26342297e+00,\n",
419
+ " -8.00139904e-01],\n",
420
+ " [-1.79063261e+00, -5.55798054e-01, 9.78834093e-01,\n",
421
+ " -2.47909844e-01, 6.02814138e-01, -1.11111656e-01,\n",
422
+ " -7.05544353e-01, -9.66730714e-01, 3.11808109e-01,\n",
423
+ " -4.33347225e-01, 1.68987262e+00, -1.20438123e+00,\n",
424
+ " 8.16072583e-01, -1.76548183e+00, 2.91771698e+00,\n",
425
+ " -2.30956078e-01, -6.31921887e-01, 8.22563887e-01,\n",
426
+ " -4.58145142e-02, 2.58027911e-01, 1.20141113e+00,\n",
427
+ " 3.40695828e-01, -6.53632879e-02, 2.61812568e-01,\n",
428
+ " -9.52707350e-01, -3.48883659e-01, -9.14866209e-01,\n",
429
+ " -1.88400781e+00, -1.72816467e+00, 1.97749197e-01,\n",
430
+ " 7.37310767e-01, -1.29350150e+00, -2.07297516e+00,\n",
431
+ " 1.18162405e+00]],\n",
432
+ " \n",
433
+ " [[ 8.47136319e-01, 1.15350640e+00, -3.81971240e-01,\n",
434
+ " -9.77874577e-01, -5.16661167e-01, 1.07412672e+00,\n",
435
+ " 1.99610567e+00, 3.23131609e+00, -9.78159904e-02,\n",
436
+ " 1.13902712e+00, 1.53129959e+00, 2.07748473e-01,\n",
437
+ " -4.35771823e-01, 1.46814728e+00, 1.39496469e+00,\n",
438
+ " 1.25192404e-01, 1.02314317e+00, 3.62683028e-01,\n",
439
+ " 2.29583120e+00, 8.82123232e-01, -1.94674718e+00,\n",
440
+ " -5.82750916e-01, -1.43944287e+00, -1.40450656e+00,\n",
441
+ " 2.07816315e+00, -5.43704212e-01, 1.06920052e+00,\n",
442
+ " -3.68077546e-01, 3.43775749e-02, -2.11020327e+00,\n",
443
+ " 4.88858998e-01, -1.61163664e+00, 2.34203601e+00,\n",
444
+ " -6.61691964e-01],\n",
445
+ " [ 1.58818483e+00, 1.03457797e+00, -1.56830120e+00,\n",
446
+ " -7.14247584e-01, -1.53801227e+00, -1.74076068e+00,\n",
447
+ " 2.57173121e-01, 3.18516016e+00, 3.03181618e-01,\n",
448
+ " 1.03972614e+00, 1.26419806e+00, -7.72367537e-01,\n",
449
+ " 1.33993566e+00, -1.10432744e+00, -2.83293128e-01,\n",
450
+ " 4.26669359e-01, 1.48125136e+00, -1.47134566e+00,\n",
451
+ " -1.55559421e-01, 1.80716586e+00, -7.98292518e-01,\n",
452
+ " -1.42317140e+00, 6.28676593e-01, -1.89048791e+00,\n",
453
+ " 8.34561348e-01, -7.26972401e-01, 1.99689960e+00,\n",
454
+ " 7.39746034e-01, 1.38303280e+00, -6.94496274e-01,\n",
455
+ " -2.20227766e+00, -3.91308260e+00, -6.87372684e-01,\n",
456
+ " -1.35915589e+00]],\n",
457
+ " \n",
458
+ " [[ 1.44673872e+00, 7.87892580e-01, 3.65907431e-01,\n",
459
+ " 4.27318156e-01, -1.25891399e+00, -4.74851549e-01,\n",
460
+ " -1.31995231e-01, -7.37033725e-01, -1.61515272e+00,\n",
461
+ " -9.28019285e-01, -7.85010815e-01, -2.46863127e-01,\n",
462
+ " 3.44028902e+00, 7.85599709e-01, -1.70975566e+00,\n",
463
+ " 8.30424726e-01, 3.77590179e-01, -1.03405869e+00,\n",
464
+ " -2.06042433e+00, 1.24313951e+00, -5.70187628e-01,\n",
465
+ " -2.70877886e+00, 9.37052965e-01, -9.11028147e-01,\n",
466
+ " 4.93628621e-01, -6.04334354e-01, -9.69354957e-02,\n",
467
+ " -2.96139240e+00, -8.54247689e-01, -7.10648656e-01,\n",
468
+ " 1.12528276e+00, -1.69798660e+00, -8.71006966e-01,\n",
469
+ " -7.70722330e-01],\n",
470
+ " [-6.43252134e-01, 2.03411150e+00, -8.73440266e-01,\n",
471
+ " 7.90917158e-01, 1.11456990e+00, 8.83533359e-02,\n",
472
+ " -1.01654351e+00, 1.20593667e+00, -3.43658972e+00,\n",
473
+ " -1.89544487e+00, -1.91902936e+00, -1.27303600e-02,\n",
474
+ " 1.44316971e+00, -1.00226438e+00, -2.08780393e-01,\n",
475
+ " -1.25529957e+00, 3.52455735e-01, -1.66923594e+00,\n",
476
+ " -2.66142797e+00, 1.78823805e+00, 1.05981278e+00,\n",
477
+ " -2.56497335e+00, -4.94338393e-01, -9.83857334e-01,\n",
478
+ " 4.12559092e-01, -5.51674843e-01, 2.18037224e+00,\n",
479
+ " -2.04803371e+00, -2.08990276e-01, 2.06684494e+00,\n",
480
+ " -2.60829628e-01, 1.77748883e+00, 1.58565640e+00,\n",
481
+ " -9.20422554e-01]],\n",
482
+ " \n",
483
+ " [[-7.31412768e-02, -8.64032328e-01, -9.02979851e-01,\n",
484
+ " -7.80296206e-01, 1.55013752e+00, 1.39569795e+00,\n",
485
+ " -9.07088697e-01, -9.04163122e-01, -4.50788498e-01,\n",
486
+ " -3.41242361e+00, 1.18717760e-01, 1.14080071e+00,\n",
487
+ " -5.62048316e-01, 2.32710266e+00, -1.30397677e+00,\n",
488
+ " -3.52632105e-01, 4.57994044e-01, -1.07408667e+00,\n",
489
+ " -2.22685719e+00, 3.68365705e-01, 1.03096282e+00,\n",
490
+ " -5.38104653e-01, 1.03047395e+00, 7.84179211e-01,\n",
491
+ " -8.48331451e-02, 8.51346850e-01, 6.62329137e-01,\n",
492
+ " 3.23494601e+00, 1.56681561e+00, 3.42787206e-01,\n",
493
+ " 8.26631308e-01, 3.90653729e-01, 4.68917906e-01,\n",
494
+ " -7.02590287e-01],\n",
495
+ " [ 4.39778119e-01, -1.91499639e+00, -8.64701509e-01,\n",
496
+ " 2.72857690e+00, 7.50923991e-01, 3.06621194e+00,\n",
497
+ " -1.76311696e+00, -1.24553120e+00, -1.14210606e+00,\n",
498
+ " -2.23708868e+00, 3.04643178e+00, -1.05194664e+00,\n",
499
+ " -3.24146795e+00, 2.22395062e+00, 5.75199604e-01,\n",
500
+ " 1.40941083e-01, 1.01800013e+00, -2.09145999e+00,\n",
501
+ " 2.47585106e+00, -1.39389133e+00, -9.06539023e-01,\n",
502
+ " 1.29228354e+00, 4.72039253e-01, -5.01675963e-01,\n",
503
+ " 7.67203689e-01, -1.07389832e+00, 1.24529874e+00,\n",
504
+ " 6.30395591e-01, 1.82147241e+00, -1.56542861e+00,\n",
505
+ " 2.25408125e+00, -1.86777294e+00, 1.34775802e-01,\n",
506
+ " -8.00670624e-01]],\n",
507
+ " \n",
508
+ " [[ 6.23033196e-02, 1.33808303e+00, -2.09081841e+00,\n",
509
+ " -1.60575271e+00, 2.01698375e+00, 5.24670243e-01,\n",
510
+ " -1.58049870e+00, 6.51937544e-01, -2.90766954e-02,\n",
511
+ " 1.36108446e+00, 7.60267615e-01, -1.45855045e+00,\n",
512
+ " -3.90157759e-01, -9.01711404e-01, -2.10141087e+00,\n",
513
+ " -7.80763686e-01, -4.29397583e+00, 7.32075512e-01,\n",
514
+ " -2.22912967e-01, -1.62254989e+00, 6.25824928e-02,\n",
515
+ " -2.11993337e+00, 6.61156356e-01, 2.00391412e-01,\n",
516
+ " -1.68775654e+00, -3.61481965e-01, -1.13692093e+00,\n",
517
+ " -2.61214113e+00, 5.71375012e-01, -1.38710427e+00,\n",
518
+ " 6.97515547e-01, -2.62053180e+00, -8.04708540e-01,\n",
519
+ " -6.41963482e-01],\n",
520
+ " [ 7.09465802e-01, -1.86132312e+00, -5.12921154e-01,\n",
521
+ " 7.25420356e-01, 1.62132716e+00, 6.70345783e-01,\n",
522
+ " -3.99126172e-01, -6.34476542e-01, -5.77216566e-01,\n",
523
+ " -2.88540065e-01, -1.57627940e+00, -1.18039489e+00,\n",
524
+ " 1.66546702e-02, 3.33578885e-01, -1.11044359e+00,\n",
525
+ " 2.89379358e-02, 3.77142429e-01, 6.79054707e-02,\n",
526
+ " -2.27836028e-01, -1.10411584e+00, 3.14605713e-01,\n",
527
+ " -3.40386868e+00, 2.22249532e+00, -1.20098495e+00,\n",
528
+ " 1.01684499e+00, 1.47755027e+00, -3.40158534e+00,\n",
529
+ " -1.36072665e-01, 5.88140309e-01, 7.94145525e-01,\n",
530
+ " 1.50576437e+00, -1.87327588e+00, -1.21018577e+00,\n",
531
+ " -3.69293690e-01]],\n",
532
+ " \n",
533
+ " [[-1.86619222e-01, -1.11457419e+00, 3.84937143e+00,\n",
534
+ " -1.18355262e+00, 1.83275962e+00, 1.64913416e-01,\n",
535
+ " -5.01962125e-01, -3.95217299e-01, -1.86735988e-02,\n",
536
+ " 2.11598635e+00, -5.13893366e-01, -2.23462611e-01,\n",
537
+ " 1.34839225e+00, 1.71697426e+00, 7.50617862e-01,\n",
538
+ " 1.41777110e+00, 3.69107783e-01, 2.04593515e+00,\n",
539
+ " 6.25651479e-01, 1.07621241e+00, -1.86277235e+00,\n",
540
+ " -2.29701710e+00, -1.13192320e+00, -4.03011203e-01,\n",
541
+ " 3.20684403e-01, -7.38262713e-01, 1.84437990e-01,\n",
542
+ " 6.40240371e-01, -8.68190885e-01, -9.82226312e-01,\n",
543
+ " -1.70525658e+00, 1.67397916e+00, -1.80527836e-01,\n",
544
+ " 2.07915044e+00],\n",
545
+ " [ 1.25567400e+00, 3.77350032e-01, 2.12807608e+00,\n",
546
+ " -3.41380930e+00, 1.03656864e+00, -2.90562630e-01,\n",
547
+ " -8.68529916e-01, 3.71831536e-01, 4.00702894e-01,\n",
548
+ " 7.15973258e-01, 6.38630509e-01, -1.06953099e-01,\n",
549
+ " 1.55171263e+00, -5.37745595e-01, -6.60307050e-01,\n",
550
+ " 2.29257250e+00, 2.35534877e-01, 1.51035047e+00,\n",
551
+ " -1.34138870e+00, 8.38007629e-01, -1.29746819e+00,\n",
552
+ " -1.87811327e+00, -1.72137594e+00, -1.12582564e+00,\n",
553
+ " 2.16068840e+00, -3.63037872e+00, -1.07908905e+00,\n",
554
+ " 2.77470589e+00, 6.95744574e-01, 6.05865598e-01,\n",
555
+ " -2.07206416e+00, -9.37378407e-01, -1.49237931e+00,\n",
556
+ " 1.88019484e-01]],\n",
557
+ " \n",
558
+ " [[ 1.08050324e-01, -3.34478110e-01, 2.24412012e+00,\n",
559
+ " -1.47214913e+00, 5.19567132e-01, 1.49610984e+00,\n",
560
+ " 1.49414659e+00, 2.83969450e+00, 6.22815311e-01,\n",
561
+ " 2.89181376e+00, -5.25898933e-02, 1.01238823e+00,\n",
562
+ " -1.61692488e+00, 4.19403374e-01, -4.50647449e+00,\n",
563
+ " 4.22272652e-01, 1.30085039e+00, 1.20739889e+00,\n",
564
+ " -1.13275349e-01, -2.72032857e+00, -4.74425983e+00,\n",
565
+ " 1.74002126e-01, 3.14478636e-01, -2.90870667e-03,\n",
566
+ " -1.56787485e-01, 3.23669732e-01, -1.09454036e-01,\n",
567
+ " -6.39174134e-02, -1.85726762e-01, -5.09917736e-01,\n",
568
+ " 2.58429384e+00, -1.00502062e+00, 2.43536711e+00,\n",
569
+ " 1.01697242e+00],\n",
570
+ " [-6.76628351e-02, 5.29604435e-01, 1.58685613e+00,\n",
571
+ " -4.04265940e-01, 7.97543406e-01, 2.95590591e+00,\n",
572
+ " -1.89530897e+00, 3.34177542e+00, -1.15904558e+00,\n",
573
+ " 1.53034556e+00, -2.71868992e+00, -1.15116191e+00,\n",
574
+ " -1.09810218e-01, 9.81350064e-01, -2.87920403e+00,\n",
575
+ " 3.06571674e+00, 6.99768841e-01, 1.16800070e-02,\n",
576
+ " 3.00019145e-01, -3.31310177e+00, -1.15039015e+00,\n",
577
+ " 9.20639992e-01, 2.64605910e-01, 1.48498571e+00,\n",
578
+ " -1.57045579e+00, -3.11622441e-01, 2.29183897e-01,\n",
579
+ " 7.15047479e-01, -4.81463194e-01, 9.93204236e-01,\n",
580
+ " 1.96289706e+00, 1.62350312e-01, -4.00538564e-01,\n",
581
+ " -4.02545571e-01]],\n",
582
+ " \n",
583
+ " [[-9.34034646e-01, 4.49019074e-01, 1.47022510e+00,\n",
584
+ " -6.45941973e-01, -7.82020867e-01, 1.89841628e+00,\n",
585
+ " -1.05324817e+00, -2.46736145e+00, -2.01015496e+00,\n",
586
+ " 1.96297050e+00, -3.37050438e-01, 1.24410653e+00,\n",
587
+ " 2.88663596e-01, 1.78690064e+00, 3.49685788e-01,\n",
588
+ " -1.13593566e+00, -2.42874765e+00, 1.27996969e+00,\n",
589
+ " -1.86387372e+00, 6.72769248e-01, -7.66083002e-02,\n",
590
+ " -1.23117137e+00, 7.62495041e-01, 6.61843121e-01,\n",
591
+ " -4.72184181e-01, 7.31606007e-01, 7.53620028e-01,\n",
592
+ " 1.01423931e+00, -2.85059619e+00, -1.10359073e-01,\n",
593
+ " 5.31930029e-01, 6.21649623e-01, 1.65528393e+00,\n",
594
+ " 3.74468714e-02],\n",
595
+ " [ 7.83229351e-01, -4.45797920e-01, 2.11266041e+00,\n",
596
+ " -4.14842874e-01, 3.64640266e-01, -1.10017431e+00,\n",
597
+ " -1.22421861e+00, -5.97917438e-01, -1.94731998e+00,\n",
598
+ " 1.43434012e+00, 3.13386393e+00, 3.60676050e-01,\n",
599
+ " 7.63031840e-01, -1.50763780e-01, -5.27755558e-01,\n",
600
+ " -2.61608291e+00, -2.61726832e+00, -2.32986450e+00,\n",
601
+ " -2.60349059e+00, 4.31749225e-02, -8.92975807e-01,\n",
602
+ " -1.00544438e-01, 1.35032511e+00, 2.44627595e-01,\n",
603
+ " -8.57893407e-01, 1.38448322e+00, -1.40706098e+00,\n",
604
+ " -1.05854189e+00, -1.24495959e+00, 1.09442329e+00,\n",
605
+ " -4.63711083e-01, 5.72895408e-01, 1.61688781e+00,\n",
606
+ " 1.01324081e+00]],\n",
607
+ " \n",
608
+ " [[ 1.80273056e+00, 1.19070506e+00, -1.20567769e-01,\n",
609
+ " 1.12320960e+00, 7.96973705e-01, -1.38518381e+00,\n",
610
+ " 8.03212225e-02, -1.45538819e+00, 1.92241991e+00,\n",
611
+ " 2.50707293e+00, -1.09405279e+00, -4.04755265e-01,\n",
612
+ " 1.69331753e+00, -1.58847952e+00, -3.01435053e-01,\n",
613
+ " 4.94136453e-01, -1.00789517e-02, -9.55825448e-01,\n",
614
+ " 2.12681198e+00, 9.74663794e-01, -9.46874261e-01,\n",
615
+ " 2.46410561e+00, 9.88218129e-01, -4.01069450e+00,\n",
616
+ " 6.04863703e-01, -4.73491371e-01, 1.65480137e+00,\n",
617
+ " -6.32112026e-01, -9.61102128e-01, 1.48311532e+00,\n",
618
+ " -4.36259359e-01, 8.88043642e-03, -6.26674116e-01,\n",
619
+ " -2.10239077e+00],\n",
620
+ " [ 1.15516019e+00, 1.71522945e-02, 1.45818520e+00,\n",
621
+ " -9.68697131e-01, -5.11248708e-01, -1.57809627e+00,\n",
622
+ " 6.87673926e-01, 8.67295325e-01, 1.61984098e+00,\n",
623
+ " -1.57702243e+00, 5.77153444e-01, 8.36637616e-02,\n",
624
+ " 3.21553409e-01, -2.12756932e-01, 1.18414497e+00,\n",
625
+ " 2.46890068e+00, -5.63436449e-01, 1.47114849e+00,\n",
626
+ " 1.06064546e+00, -1.50939143e+00, -6.99386716e-01,\n",
627
+ " 2.59919190e+00, 1.26403499e+00, -2.68051052e+00,\n",
628
+ " 3.27747971e-01, -9.73147452e-01, 1.78368676e+00,\n",
629
+ " 7.97161996e-01, 1.42644212e-01, 1.69202793e+00,\n",
630
+ " -1.19964826e+00, -7.34192431e-01, 6.30575418e-02,\n",
631
+ " -1.32647312e+00]],\n",
632
+ " \n",
633
+ " [[-6.30901933e-01, -7.13921070e-01, 2.67281103e+00,\n",
634
+ " -7.30642796e-01, 1.62232518e+00, 1.54881573e+00,\n",
635
+ " 8.41742277e-01, -2.90167034e-01, -1.94286966e+00,\n",
636
+ " -1.15102935e+00, -1.71167225e-01, -2.22312593e+00,\n",
637
+ " 3.43806458e+00, 2.56260347e+00, 1.47779986e-01,\n",
638
+ " -5.04667878e-01, 2.75110930e-01, -1.23666930e+00,\n",
639
+ " -6.47997379e-01, 9.19276059e-01, 5.68554878e-01,\n",
640
+ " 7.60348201e-01, -1.24003148e+00, -3.16113925e+00,\n",
641
+ " -1.03221774e+00, 8.60363424e-01, -6.41938746e-01,\n",
642
+ " -3.07883191e+00, 2.06296110e+00, -2.43227816e+00,\n",
643
+ " -1.49008572e-01, -5.23218691e-01, -1.32170630e+00,\n",
644
+ " 5.05840480e-01],\n",
645
+ " [-7.05626786e-01, -8.84220541e-01, 1.66022527e+00,\n",
646
+ " -4.94577408e-01, -7.82126427e-01, 1.22818542e+00,\n",
647
+ " 5.45588374e-01, 3.65606010e-01, -2.87227678e+00,\n",
648
+ " -1.66418779e+00, 7.20768213e-01, -4.58562344e-01,\n",
649
+ " 3.26762438e+00, 2.36510158e+00, 4.28559959e-01,\n",
650
+ " -2.56422377e+00, 3.51960182e-01, -7.46671557e-01,\n",
651
+ " 1.27523363e+00, 1.08243454e+00, 8.98495436e-01,\n",
652
+ " 1.70658183e+00, 1.80342019e-01, -1.01962578e+00,\n",
653
+ " 1.30239320e+00, -4.26320434e-02, -4.88645852e-01,\n",
654
+ " -2.25123692e+00, 1.50117087e+00, -1.37741220e+00,\n",
655
+ " -7.10380852e-01, -1.83778882e+00, -5.03213465e-01,\n",
656
+ " 2.63263464e-01]]], dtype=float32)}"
657
+ ]
658
+ },
659
+ "execution_count": 4,
660
+ "metadata": {},
661
+ "output_type": "execute_result"
662
+ }
663
+ ],
664
+ "source": [
665
+ "pi0.sample_actions(\n",
666
+ " rng=jax.random.key(0),\n",
667
+ " batch_observation=(pi0.observation_spec().batched(10).sample()),\n",
668
+ " num_actions=2,\n",
669
+ " diffusion_num_steps=1,\n",
670
+ ")"
671
+ ]
672
+ },
673
+ {
674
+ "cell_type": "code",
675
+ "execution_count": 5,
676
+ "id": "46d8e4c6",
677
+ "metadata": {},
678
+ "outputs": [
679
+ {
680
+ "data": {
681
+ "text/plain": [
682
+ "(10, 2, 34)"
683
+ ]
684
+ },
685
+ "execution_count": 5,
686
+ "metadata": {},
687
+ "output_type": "execute_result"
688
+ }
689
+ ],
690
+ "source": [
691
+ "_[\"numeric_states\"].shape"
692
+ ]
693
+ },
694
+ {
695
+ "cell_type": "code",
696
+ "execution_count": 24,
697
+ "id": "0730fcf4",
698
+ "metadata": {},
699
+ "outputs": [],
700
+ "source": [
701
+ "emb, input_masks, ar_masks = pi0._embed_prefix(pi0.config.observation_spec.batched().sample())"
702
+ ]
703
+ },
704
+ {
705
+ "cell_type": "code",
706
+ "execution_count": 25,
707
+ "id": "2703afcb",
708
+ "metadata": {},
709
+ "outputs": [
710
+ {
711
+ "data": {
712
+ "text/plain": [
713
+ "(1, 816, 2048)"
714
+ ]
715
+ },
716
+ "execution_count": 25,
717
+ "metadata": {},
718
+ "output_type": "execute_result"
719
+ }
720
+ ],
721
+ "source": [
722
+ "emb.shape"
723
+ ]
724
+ },
725
+ {
726
+ "cell_type": "code",
727
+ "execution_count": 31,
728
+ "id": "6c84df86",
729
+ "metadata": {},
730
+ "outputs": [
731
+ {
732
+ "data": {
733
+ "text/plain": [
734
+ "(1, 816)"
735
+ ]
736
+ },
737
+ "execution_count": 31,
738
+ "metadata": {},
739
+ "output_type": "execute_result"
740
+ }
741
+ ],
742
+ "source": [
743
+ "input_masks.shape"
744
+ ]
745
+ },
746
+ {
747
+ "cell_type": "code",
748
+ "execution_count": 42,
749
+ "id": "84b60022",
750
+ "metadata": {},
751
+ "outputs": [
752
+ {
753
+ "data": {
754
+ "text/plain": [
755
+ "(20,)"
756
+ ]
757
+ },
758
+ "execution_count": 42,
759
+ "metadata": {},
760
+ "output_type": "execute_result"
761
+ }
762
+ ],
763
+ "source": [
764
+ "jax.numpy.concatenate([jax.numpy.full(10, False), jax.numpy.full(10, False)], axis=0).shape"
765
+ ]
766
+ },
767
+ {
768
+ "cell_type": "code",
769
+ "execution_count": 34,
770
+ "id": "079624b9",
771
+ "metadata": {},
772
+ "outputs": [
773
+ {
774
+ "data": {
775
+ "text/plain": [
776
+ "Array([False, False, False, False, False, False, False, False, False,\n",
777
+ " False], dtype=bool)"
778
+ ]
779
+ },
780
+ "execution_count": 34,
781
+ "metadata": {},
782
+ "output_type": "execute_result"
783
+ }
784
+ ],
785
+ "source": [
786
+ "jax.numpy.full(10, False)"
787
+ ]
788
+ },
789
+ {
790
+ "cell_type": "code",
791
+ "execution_count": 29,
792
+ "id": "2a5d63e3",
793
+ "metadata": {},
794
+ "outputs": [
795
+ {
796
+ "data": {
797
+ "text/plain": [
798
+ "(816,)"
799
+ ]
800
+ },
801
+ "execution_count": 29,
802
+ "metadata": {},
803
+ "output_type": "execute_result"
804
+ }
805
+ ],
806
+ "source": [
807
+ "ar_masks.shape"
808
+ ]
809
+ },
810
+ {
811
+ "cell_type": "code",
812
+ "execution_count": null,
813
+ "id": "d5490990",
814
+ "metadata": {},
815
+ "outputs": [],
816
+ "source": [
817
+ "import jax\n",
818
+ "\n",
819
+ "from robotodo.controllers.pi0 import Pi0Controller\n",
820
+ "from robotodo.controllers.pi0.nn.pi0 import Pi0\n",
821
+ "\n",
822
+ "# TODO match params\n",
823
+ "nn_observation_spec = Pi0.ObservationSpec()\n",
824
+ "controller_observation_spec = Pi0Controller.ObservationSpec()"
825
+ ]
826
+ },
827
+ {
828
+ "cell_type": "code",
829
+ "execution_count": 26,
830
+ "id": "ba4566a5",
831
+ "metadata": {},
832
+ "outputs": [
833
+ {
834
+ "data": {
835
+ "text/plain": [
836
+ "Dict('images': Box(-1.0, 1.0, (3, 224, 224, 3), float32), 'images.mask': Box(0, 1, (3,), uint8), 'numeric_state': Box(-inf, inf, (32,), float32), 'tokenized_text': Box(0, 257152, (48,), int32), 'tokenized_text.mask': Box(0, 1, (48,), uint8))"
837
+ ]
838
+ },
839
+ "execution_count": 26,
840
+ "metadata": {},
841
+ "output_type": "execute_result"
842
+ }
843
+ ],
844
+ "source": [
845
+ "nn_observation_spec"
846
+ ]
847
+ },
848
+ {
849
+ "cell_type": "code",
850
+ "execution_count": 27,
851
+ "id": "009a1c4f",
852
+ "metadata": {},
853
+ "outputs": [
854
+ {
855
+ "data": {
856
+ "text/plain": [
857
+ "Dict('images': Dict('base_0_rgb': Box(0.0, 1.0, (224, 224, 3), float32), 'left_wrist_0_rgb': Box(0.0, 1.0, (224, 224, 3), float32), 'right_wrist_0_rgb': Box(0.0, 1.0, (224, 224, 3), float32)), 'joint_state': Dict('todo': Box(-inf, inf, (), float32)), 'text': Text(1, 48, charset=0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz))"
858
+ ]
859
+ },
860
+ "execution_count": 27,
861
+ "metadata": {},
862
+ "output_type": "execute_result"
863
+ }
864
+ ],
865
+ "source": [
866
+ "controller_observation_spec"
867
+ ]
868
+ },
869
+ {
870
+ "cell_type": "code",
871
+ "execution_count": null,
872
+ "id": "bc2c4b11",
873
+ "metadata": {},
874
+ "outputs": [],
875
+ "source": []
876
+ },
877
+ {
878
+ "cell_type": "code",
879
+ "execution_count": null,
880
+ "id": "f45a0802",
881
+ "metadata": {},
882
+ "outputs": [],
883
+ "source": [
884
+ "batch_size = 10\n",
885
+ "\n",
886
+ "controller_observation = controller_observation_spec.batched(batch_size).sample()\n",
887
+ "nn_observation = Pi0Controller._encode_observation(\n",
888
+ " target_spec=nn_observation_spec,\n",
889
+ " source_spec=controller_observation_spec,\n",
890
+ " batch=controller_observation,\n",
891
+ " image_transform=lambda x, target_shape: jax.numpy.full((x.shape[0], *target_shape), 0.),\n",
892
+ " text_tokenizer=lambda texts, max_len: (jax.numpy.full((len(texts), max_len), 0.), jax.numpy.full((len(texts), max_len), False))\n",
893
+ ")"
894
+ ]
895
+ },
896
+ {
897
+ "cell_type": "code",
898
+ "execution_count": null,
899
+ "id": "11c1517b",
900
+ "metadata": {},
901
+ "outputs": [],
902
+ "source": []
903
+ },
904
+ {
905
+ "cell_type": "code",
906
+ "execution_count": 15,
907
+ "id": "d9eddcde",
908
+ "metadata": {},
909
+ "outputs": [
910
+ {
911
+ "data": {
912
+ "text/plain": [
913
+ "(10, 224, 224, 3)"
914
+ ]
915
+ },
916
+ "execution_count": 15,
917
+ "metadata": {},
918
+ "output_type": "execute_result"
919
+ }
920
+ ],
921
+ "source": [
922
+ "controller_observation[\"images\"][\"base_0_rgb\"].shape"
923
+ ]
924
+ },
925
+ {
926
+ "cell_type": "code",
927
+ "execution_count": 19,
928
+ "id": "03f7ee77",
929
+ "metadata": {},
930
+ "outputs": [
931
+ {
932
+ "name": "stderr",
933
+ "output_type": "stream",
934
+ "text": [
935
+ "/home/ace/RoboTwin/.conda/lib/python3.11/site-packages/gymnasium/spaces/box.py:424: UserWarning: \u001b[33mWARN: Casting input x to numpy array.\u001b[0m\n",
936
+ " gym.logger.warn(\"Casting input x to numpy array.\")\n"
937
+ ]
938
+ },
939
+ {
940
+ "data": {
941
+ "text/plain": [
942
+ "False"
943
+ ]
944
+ },
945
+ "execution_count": 19,
946
+ "metadata": {},
947
+ "output_type": "execute_result"
948
+ }
949
+ ],
950
+ "source": [
951
+ "# TODO gymnasium upstream issue???\n",
952
+ "nn_observation in nn_observation_spec.batched(batch_size)"
953
+ ]
954
+ },
955
+ {
956
+ "cell_type": "code",
957
+ "execution_count": 20,
958
+ "id": "6f371f81",
959
+ "metadata": {},
960
+ "outputs": [
961
+ {
962
+ "data": {
963
+ "text/plain": [
964
+ "Dict('images': Box(-1.0, 1.0, (10, 3, 224, 224, 3), float32), 'images.mask': Box(0, 1, (10, 3), uint8), 'numeric_state': Box(-inf, inf, (10, 32), float32), 'tokenized_text': Box(0, 257152, (10, 48), int32), 'tokenized_text.mask': Box(0, 1, (10, 48), uint8))"
965
+ ]
966
+ },
967
+ "execution_count": 20,
968
+ "metadata": {},
969
+ "output_type": "execute_result"
970
+ }
971
+ ],
972
+ "source": [
973
+ "nn_observation_spec.batched(batch_size)"
974
+ ]
975
+ },
976
+ {
977
+ "cell_type": "code",
978
+ "execution_count": 24,
979
+ "id": "efdef692",
980
+ "metadata": {},
981
+ "outputs": [
982
+ {
983
+ "data": {
984
+ "text/plain": [
985
+ "(10, 1)"
986
+ ]
987
+ },
988
+ "execution_count": 24,
989
+ "metadata": {},
990
+ "output_type": "execute_result"
991
+ }
992
+ ],
993
+ "source": [
994
+ "nn_observation[\"numeric_state\"].shape"
995
+ ]
996
+ },
997
+ {
998
+ "cell_type": "code",
999
+ "execution_count": null,
1000
+ "id": "2c820dbb",
1001
+ "metadata": {},
1002
+ "outputs": [],
1003
+ "source": [
1004
+ "nn_observation_spec"
1005
+ ]
1006
+ },
1007
+ {
1008
+ "cell_type": "code",
1009
+ "execution_count": 12,
1010
+ "id": "253fad94",
1011
+ "metadata": {},
1012
+ "outputs": [
1013
+ {
1014
+ "data": {
1015
+ "text/plain": [
1016
+ "(10, 224, 224, 3)"
1017
+ ]
1018
+ },
1019
+ "execution_count": 12,
1020
+ "metadata": {},
1021
+ "output_type": "execute_result"
1022
+ }
1023
+ ],
1024
+ "source": [
1025
+ "controller_observation[\"images\"][\"base_0_rgb\"].shape "
1026
+ ]
1027
+ },
1028
+ {
1029
+ "cell_type": "code",
1030
+ "execution_count": 13,
1031
+ "id": "e6ce38c7",
1032
+ "metadata": {},
1033
+ "outputs": [
1034
+ {
1035
+ "data": {
1036
+ "text/plain": [
1037
+ "(10, 3, 224, 224, 3)"
1038
+ ]
1039
+ },
1040
+ "execution_count": 13,
1041
+ "metadata": {},
1042
+ "output_type": "execute_result"
1043
+ }
1044
+ ],
1045
+ "source": [
1046
+ "nn_observation[\"images\"].shape"
1047
+ ]
1048
+ },
1049
+ {
1050
+ "cell_type": "code",
1051
+ "execution_count": 17,
1052
+ "id": "a605cce0",
1053
+ "metadata": {},
1054
+ "outputs": [
1055
+ {
1056
+ "data": {
1057
+ "text/plain": [
1058
+ "Dict('images': Box(-1.0, 1.0, (1, 3, 224, 224, 3), float32), 'images.mask': Box(0, 1, (1, 3), uint8), 'numeric_state': Box(-inf, inf, (1, 32), float32), 'tokenized_text': Box(0, 257152, (1, 48), int32), 'tokenized_text.mask': Box(0, 1, (1, 48), uint8))"
1059
+ ]
1060
+ },
1061
+ "execution_count": 17,
1062
+ "metadata": {},
1063
+ "output_type": "execute_result"
1064
+ }
1065
+ ],
1066
+ "source": [
1067
+ "nn_observation_spec.batched()"
1068
+ ]
1069
+ },
1070
+ {
1071
+ "cell_type": "code",
1072
+ "execution_count": 8,
1073
+ "id": "61cde93f",
1074
+ "metadata": {},
1075
+ "outputs": [
1076
+ {
1077
+ "data": {
1078
+ "text/plain": [
1079
+ "(10, 3)"
1080
+ ]
1081
+ },
1082
+ "execution_count": 8,
1083
+ "metadata": {},
1084
+ "output_type": "execute_result"
1085
+ }
1086
+ ],
1087
+ "source": [
1088
+ "nn_observation[\"images.mask\"].shape"
1089
+ ]
1090
+ },
1091
+ {
1092
+ "cell_type": "code",
1093
+ "execution_count": 4,
1094
+ "id": "37342c4b",
1095
+ "metadata": {},
1096
+ "outputs": [
1097
+ {
1098
+ "data": {
1099
+ "text/plain": [
1100
+ "Dict('images': Box(-1.0, 1.0, (3, 224, 224, 3), float32), 'images.mask': Box(0, 1, (3,), uint8), 'numeric_state': Box(-inf, inf, (32,), float32), 'tokenized_text': Box(0, 257152, (48,), int32), 'tokenized_text.mask': Box(0, 1, (48,), uint8))"
1101
+ ]
1102
+ },
1103
+ "execution_count": 4,
1104
+ "metadata": {},
1105
+ "output_type": "execute_result"
1106
+ }
1107
+ ],
1108
+ "source": [
1109
+ "nn_observation_spec"
1110
+ ]
1111
+ },
1112
+ {
1113
+ "cell_type": "code",
1114
+ "execution_count": 4,
1115
+ "id": "af38eca9",
1116
+ "metadata": {},
1117
+ "outputs": [
1118
+ {
1119
+ "data": {
1120
+ "text/plain": [
1121
+ "Sequence(Dict('todo': Box(-inf, inf, (), float32)), stack=False)"
1122
+ ]
1123
+ },
1124
+ "execution_count": 4,
1125
+ "metadata": {},
1126
+ "output_type": "execute_result"
1127
+ }
1128
+ ],
1129
+ "source": [
1130
+ "import gymnasium.spaces\n",
1131
+ "gymnasium.spaces.Sequence(controller_observation_spec[\"joint_state\"])"
1132
+ ]
1133
+ },
1134
+ {
1135
+ "cell_type": "code",
1136
+ "execution_count": 8,
1137
+ "id": "47548e31",
1138
+ "metadata": {},
1139
+ "outputs": [
1140
+ {
1141
+ "data": {
1142
+ "text/plain": [
1143
+ "array([[ 1.8357197 ],\n",
1144
+ " [-1.1746476 ],\n",
1145
+ " [ 1.1199156 ],\n",
1146
+ " [-0.54861826],\n",
1147
+ " [ 0.4472829 ],\n",
1148
+ " [-0.27640054],\n",
1149
+ " [ 1.1524948 ],\n",
1150
+ " [ 0.30810565],\n",
1151
+ " [ 0.42107326],\n",
1152
+ " [-1.946566 ]], dtype=float32)"
1153
+ ]
1154
+ },
1155
+ "execution_count": 8,
1156
+ "metadata": {},
1157
+ "output_type": "execute_result"
1158
+ }
1159
+ ],
1160
+ "source": [
1161
+ "import gymnasium.spaces.utils\n",
1162
+ "\n",
1163
+ "gymnasium.spaces.utils.flatten(\n",
1164
+ " gymnasium.spaces.Sequence(controller_observation_spec[\"joint_state\"], stack=True),\n",
1165
+ " controller_observation_spec.batched(10).sample()[\"joint_state\"],\n",
1166
+ ")"
1167
+ ]
1168
+ },
1169
+ {
1170
+ "cell_type": "code",
1171
+ "execution_count": null,
1172
+ "id": "adce77ea",
1173
+ "metadata": {},
1174
+ "outputs": [],
1175
+ "source": []
1176
+ },
1177
+ {
1178
+ "cell_type": "code",
1179
+ "execution_count": 6,
1180
+ "id": "37a81ffb",
1181
+ "metadata": {},
1182
+ "outputs": [
1183
+ {
1184
+ "data": {
1185
+ "text/plain": [
1186
+ "{'images': array([[[[[-7.63066709e-01, -4.86898810e-01, -3.28803122e-01],\n",
1187
+ " [ 1.15918905e-01, -4.77899909e-01, -9.61596847e-01],\n",
1188
+ " [ 3.47825319e-01, -4.16202277e-01, 8.17094862e-01],\n",
1189
+ " ...,\n",
1190
+ " [ 8.17682669e-02, -7.36483216e-01, 8.60057175e-01],\n",
1191
+ " [ 1.41438484e-01, -4.98428315e-01, 3.98288876e-01],\n",
1192
+ " [-6.52770162e-01, 9.12108600e-01, 8.15696716e-01]],\n",
1193
+ " \n",
1194
+ " [[-9.96807039e-01, 1.80117473e-01, 8.55348289e-01],\n",
1195
+ " [ 6.92389846e-01, 6.36956930e-01, -4.07546997e-01],\n",
1196
+ " [ 7.32183993e-01, -4.42438096e-01, 3.67562383e-01],\n",
1197
+ " ...,\n",
1198
+ " [ 4.35965359e-01, 8.21272254e-01, 6.06464362e-03],\n",
1199
+ " [-4.08415228e-01, -3.83150488e-01, 3.56163472e-01],\n",
1200
+ " [ 8.44573617e-01, -7.68670380e-01, 6.88558519e-02]],\n",
1201
+ " \n",
1202
+ " [[-1.45453736e-01, 5.14207035e-02, -3.83789152e-01],\n",
1203
+ " [-3.97731252e-02, -4.18441892e-01, -5.78567982e-01],\n",
1204
+ " [ 6.79687485e-02, 5.93478918e-01, -2.69040048e-01],\n",
1205
+ " ...,\n",
1206
+ " [-4.74398732e-01, 8.67069483e-01, -8.58119011e-01],\n",
1207
+ " [ 2.92781264e-01, -7.47302398e-02, -5.27478814e-01],\n",
1208
+ " [ 9.64767635e-02, -9.72617745e-01, -1.53698176e-01]],\n",
1209
+ " \n",
1210
+ " ...,\n",
1211
+ " \n",
1212
+ " [[-4.04339522e-01, -1.22675657e-01, -4.80002016e-01],\n",
1213
+ " [-6.78351045e-01, 5.46467543e-01, 3.49014848e-01],\n",
1214
+ " [-3.05397838e-01, 9.58368003e-01, -3.45104486e-02],\n",
1215
+ " ...,\n",
1216
+ " [ 9.60051894e-01, 1.59948654e-02, -9.19202745e-01],\n",
1217
+ " [-5.50102055e-01, 6.53040290e-01, 3.73153716e-01],\n",
1218
+ " [ 2.15034038e-01, 3.40258360e-01, 7.03863442e-01]],\n",
1219
+ " \n",
1220
+ " [[-5.59194386e-01, 6.34340703e-01, -2.74762899e-01],\n",
1221
+ " [ 2.01177061e-01, -8.74299645e-01, 8.50910544e-02],\n",
1222
+ " [ 9.58502412e-01, -8.21278453e-01, -3.37577701e-01],\n",
1223
+ " ...,\n",
1224
+ " [-5.83267845e-02, 2.15180755e-01, 9.45367396e-01],\n",
1225
+ " [ 2.18393549e-01, -6.77678660e-02, -7.63152599e-01],\n",
1226
+ " [ 6.11724079e-01, -9.11003351e-01, -4.17288750e-01]],\n",
1227
+ " \n",
1228
+ " [[-3.95997703e-01, -6.88499361e-02, 4.71715145e-02],\n",
1229
+ " [-6.15282893e-01, 6.70028985e-01, 5.17555773e-01],\n",
1230
+ " [ 7.24781454e-02, -4.42294151e-01, -3.38035047e-01],\n",
1231
+ " ...,\n",
1232
+ " [-7.35449910e-01, 1.25244588e-01, 4.82940644e-01],\n",
1233
+ " [ 8.80490065e-01, -6.46659434e-01, -4.28825825e-01],\n",
1234
+ " [ 6.19819283e-01, -6.09023750e-01, 7.86099374e-01]]],\n",
1235
+ " \n",
1236
+ " \n",
1237
+ " [[[-3.74607593e-01, -8.14093232e-01, -5.53252578e-01],\n",
1238
+ " [-1.81806549e-01, -7.18796015e-01, 6.30754530e-02],\n",
1239
+ " [-7.33448684e-01, 5.50130248e-01, 9.27205980e-01],\n",
1240
+ " ...,\n",
1241
+ " [-5.08580029e-01, -2.98937351e-01, 3.10781300e-01],\n",
1242
+ " [ 9.28937316e-01, 9.12188113e-01, -2.45957643e-01],\n",
1243
+ " [ 7.08523750e-01, 2.81037420e-01, 8.78856003e-01]],\n",
1244
+ " \n",
1245
+ " [[-6.01615369e-01, -3.74974996e-01, 4.30683494e-01],\n",
1246
+ " [-7.42039561e-01, -8.03337097e-01, 3.89026701e-02],\n",
1247
+ " [-9.24577534e-01, -5.46242893e-01, -4.56938326e-01],\n",
1248
+ " ...,\n",
1249
+ " [-1.47866204e-01, 5.86117208e-01, -3.21605057e-01],\n",
1250
+ " [-1.92893818e-01, 2.87876189e-01, 8.81081939e-01],\n",
1251
+ " [ 1.97334051e-01, 4.03879315e-01, -4.69163984e-01]],\n",
1252
+ " \n",
1253
+ " [[ 1.06647573e-01, 6.59908593e-01, -7.91585565e-01],\n",
1254
+ " [ 3.11045736e-01, 4.52418812e-02, -9.13812160e-01],\n",
1255
+ " [-3.71673912e-01, -7.17218518e-01, 2.03249548e-02],\n",
1256
+ " ...,\n",
1257
+ " [ 8.15164506e-01, 9.29874301e-01, -1.44171700e-01],\n",
1258
+ " [-2.00240612e-01, 5.53812921e-01, -6.95841074e-01],\n",
1259
+ " [ 4.26995277e-01, 2.28053138e-01, 1.06774569e-01]],\n",
1260
+ " \n",
1261
+ " ...,\n",
1262
+ " \n",
1263
+ " [[-9.54031944e-01, 6.21188521e-01, -2.27589354e-01],\n",
1264
+ " [ 1.51772603e-01, 7.93324649e-01, -5.70351183e-01],\n",
1265
+ " [-3.46542783e-02, 4.76339579e-01, 4.61076111e-01],\n",
1266
+ " ...,\n",
1267
+ " [ 6.68162882e-01, -8.21792245e-01, -2.93848902e-01],\n",
1268
+ " [-8.36609185e-01, -9.44537818e-01, -8.61234404e-03],\n",
1269
+ " [-4.09087501e-02, -1.54874265e-01, 3.23844671e-01]],\n",
1270
+ " \n",
1271
+ " [[-5.11141531e-02, -8.61401781e-02, -3.05378288e-01],\n",
1272
+ " [-8.02168250e-01, 6.55312896e-01, 5.74917085e-02],\n",
1273
+ " [-2.55265385e-01, 4.54365700e-01, -4.26413119e-01],\n",
1274
+ " ...,\n",
1275
+ " [-4.54962179e-02, 9.01133418e-01, -8.49330723e-01],\n",
1276
+ " [-5.80645204e-01, -1.42904982e-01, -4.09653932e-01],\n",
1277
+ " [ 2.25605387e-02, 5.49245358e-01, -5.17659485e-01]],\n",
1278
+ " \n",
1279
+ " [[-6.95924222e-01, 7.61406124e-01, 1.39832094e-01],\n",
1280
+ " [-4.97843444e-01, -5.77789187e-01, 2.33159348e-01],\n",
1281
+ " [ 4.76556659e-01, 9.84797001e-01, -5.87266922e-01],\n",
1282
+ " ...,\n",
1283
+ " [ 5.35299778e-01, 6.06907070e-01, 6.06947422e-01],\n",
1284
+ " [ 2.14409202e-01, 2.21119881e-01, 1.90878257e-01],\n",
1285
+ " [-6.77289426e-01, 7.63259113e-01, -5.20431221e-01]]],\n",
1286
+ " \n",
1287
+ " \n",
1288
+ " [[[-4.85314429e-01, 5.11174262e-01, 8.81680608e-01],\n",
1289
+ " [-6.33072972e-01, 1.19294092e-01, 5.75236860e-04],\n",
1290
+ " [ 1.11356072e-01, 3.25914212e-02, 3.32486242e-01],\n",
1291
+ " ...,\n",
1292
+ " [-7.74683595e-01, 7.14179397e-01, 3.59156698e-01],\n",
1293
+ " [-4.18679684e-01, 9.38510299e-01, -3.17852646e-01],\n",
1294
+ " [ 3.44710588e-01, -4.17608827e-01, -5.23580730e-01]],\n",
1295
+ " \n",
1296
+ " [[-1.00512505e-02, -4.47481424e-01, -1.85110271e-01],\n",
1297
+ " [ 3.91401619e-01, 4.61104691e-01, 1.31781489e-01],\n",
1298
+ " [ 4.80068088e-01, 7.91860759e-01, 2.91928630e-02],\n",
1299
+ " ...,\n",
1300
+ " [-1.92594841e-01, 1.70318067e-01, 8.46203327e-01],\n",
1301
+ " [ 8.40307176e-01, -5.27777433e-01, -5.47426045e-01],\n",
1302
+ " [-5.48930943e-01, -3.85328382e-01, 2.05109149e-01]],\n",
1303
+ " \n",
1304
+ " [[ 7.33117461e-01, -2.33969763e-01, 6.04177654e-01],\n",
1305
+ " [ 1.96841896e-01, -7.97043800e-01, 1.81611061e-01],\n",
1306
+ " [-4.93985452e-02, 1.63460195e-01, -2.67090410e-01],\n",
1307
+ " ...,\n",
1308
+ " [ 7.35010743e-01, 3.22224170e-01, 5.99886954e-01],\n",
1309
+ " [ 2.44633481e-01, 5.03130376e-01, 5.83880544e-01],\n",
1310
+ " [ 9.20040369e-01, 1.82502314e-01, 9.84956026e-01]],\n",
1311
+ " \n",
1312
+ " ...,\n",
1313
+ " \n",
1314
+ " [[ 6.61259711e-01, 9.03410390e-02, 3.63834649e-01],\n",
1315
+ " [-9.24901783e-01, 1.25897884e-01, 4.80659515e-01],\n",
1316
+ " [-6.21640921e-01, 9.81222451e-01, -1.02242537e-01],\n",
1317
+ " ...,\n",
1318
+ " [-8.15072179e-01, -7.33374298e-01, -8.46619606e-01],\n",
1319
+ " [ 6.19441271e-01, -1.46906987e-01, -7.17343241e-02],\n",
1320
+ " [-5.54435372e-01, -8.15739930e-01, 3.60474944e-01]],\n",
1321
+ " \n",
1322
+ " [[-7.14026213e-01, 6.93810821e-01, 9.32798088e-01],\n",
1323
+ " [ 5.14027357e-01, 9.04652655e-01, -3.48061234e-01],\n",
1324
+ " [-9.05711234e-01, 8.70546520e-01, 2.46836901e-01],\n",
1325
+ " ...,\n",
1326
+ " [ 9.66548204e-01, 3.49923849e-01, 7.88954869e-02],\n",
1327
+ " [ 7.48201311e-01, -2.59742171e-01, -7.13311851e-01],\n",
1328
+ " [ 5.96099138e-01, 8.28109741e-01, 6.57843351e-01]],\n",
1329
+ " \n",
1330
+ " [[-8.64170969e-01, -7.26604685e-02, 3.49216938e-01],\n",
1331
+ " [-5.12289584e-01, 3.53810608e-01, -2.07740515e-02],\n",
1332
+ " [-7.22295642e-01, -7.88866162e-01, -8.37581277e-01],\n",
1333
+ " ...,\n",
1334
+ " [-9.99607444e-01, 5.65209627e-01, 9.43709731e-01],\n",
1335
+ " [-9.83632635e-03, 6.01234019e-01, -4.19777036e-01],\n",
1336
+ " [-3.16685408e-01, 9.69036818e-01, 8.44856441e-01]]]]],\n",
1337
+ " dtype=float32),\n",
1338
+ " 'images.mask': array([[1, 0, 1]], dtype=uint8),\n",
1339
+ " 'numeric_state': array([[-0.7412936 , -0.2827789 , 0.22433746, 0.7594694 , -0.6897594 ,\n",
1340
+ " 0.03764075, 1.2097055 , 0.664567 , -0.28887856, 0.9374326 ,\n",
1341
+ " 0.28345597, -0.4784544 , 0.5802223 , 0.6018164 , 0.19421902,\n",
1342
+ " 0.17423563, -1.3312759 , -0.30213767, 0.7510119 , 0.8973251 ,\n",
1343
+ " 2.0444806 , 0.84161663, 1.7336248 , -1.3980262 , 1.737931 ,\n",
1344
+ " 1.9398062 , 0.15704961, 0.3795424 , -0.12483855, 0.5486015 ,\n",
1345
+ " -0.97479284, 0.7064516 ]], dtype=float32),\n",
1346
+ " 'tokenized_text': array([[210215, 66783, 148301, 253649, 183916, 219697, 29536, 224774,\n",
1347
+ " 144561, 204303, 93610, 88319, 101550, 90088, 119865, 132293,\n",
1348
+ " 155925, 67991, 203656, 246097, 211946, 17846, 65806, 117400,\n",
1349
+ " 124331, 105203, 39779, 113751, 47278, 215951, 239094, 136717,\n",
1350
+ " 21770, 190087, 90307, 219439, 28896, 252565, 112091, 16476,\n",
1351
+ " 200823, 238483, 123332, 153160, 237640, 198824, 159047, 163113]],\n",
1352
+ " dtype=int32),\n",
1353
+ " 'tokenized_text.mask': array([[0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1,\n",
1354
+ " 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0,\n",
1355
+ " 1, 1, 0, 1]], dtype=uint8)}"
1356
+ ]
1357
+ },
1358
+ "execution_count": 6,
1359
+ "metadata": {},
1360
+ "output_type": "execute_result"
1361
+ }
1362
+ ],
1363
+ "source": [
1364
+ "from robotodo.controllers.pi0.nn.pi0 import Pi0\n",
1365
+ "\n",
1366
+ "Pi0.ObservationSpec().batched().sample()"
1367
+ ]
1368
+ },
1369
+ {
1370
+ "cell_type": "code",
1371
+ "execution_count": 5,
1372
+ "id": "391ead2f",
1373
+ "metadata": {},
1374
+ "outputs": [
1375
+ {
1376
+ "data": {
1377
+ "text/plain": [
1378
+ "{'images': (array([[[[ 0.95667833, -0.40699133, 0.5916939 ],\n",
1379
+ " [-0.45432368, 0.35492876, 0.04977155],\n",
1380
+ " [ 0.57454115, -0.61496896, 0.90819734],\n",
1381
+ " ...,\n",
1382
+ " [ 0.8853567 , 0.66773367, -0.47145224],\n",
1383
+ " [-0.95155185, -0.64696056, -0.9360273 ],\n",
1384
+ " [ 0.25477016, 0.24183251, 0.876387 ]],\n",
1385
+ " \n",
1386
+ " [[ 0.91196865, 0.6465922 , 0.816801 ],\n",
1387
+ " [ 0.04057588, -0.8699094 , -0.13232271],\n",
1388
+ " [-0.4557091 , 0.38671178, 0.04560573],\n",
1389
+ " ...,\n",
1390
+ " [ 0.24370934, -0.12613262, 0.97744757],\n",
1391
+ " [-0.13074061, -0.4150135 , 0.6785771 ],\n",
1392
+ " [-0.46789727, 0.16481422, -0.23333523]],\n",
1393
+ " \n",
1394
+ " [[ 0.45314372, -0.19051759, -0.0719211 ],\n",
1395
+ " [ 0.77616763, -0.51360285, 0.6170974 ],\n",
1396
+ " [ 0.78629714, -0.16609211, 0.62559223],\n",
1397
+ " ...,\n",
1398
+ " [-0.52874386, -0.6156537 , 0.7392557 ],\n",
1399
+ " [ 0.3120252 , -0.01810281, 0.9112832 ],\n",
1400
+ " [ 0.74832225, 0.9671439 , 0.2893931 ]],\n",
1401
+ " \n",
1402
+ " ...,\n",
1403
+ " \n",
1404
+ " [[ 0.13945536, -0.6403558 , -0.7836828 ],\n",
1405
+ " [ 0.80822843, -0.19383521, 0.35970712],\n",
1406
+ " [ 0.9693394 , -0.36991912, -0.6210652 ],\n",
1407
+ " ...,\n",
1408
+ " [ 0.2705082 , 0.9690494 , -0.8253107 ],\n",
1409
+ " [-0.9317098 , 0.7471916 , 0.42454836],\n",
1410
+ " [-0.65926933, -0.29663178, -0.08690747]],\n",
1411
+ " \n",
1412
+ " [[ 0.76668996, -0.09911609, -0.23278494],\n",
1413
+ " [ 0.99499846, 0.9766532 , 0.66441375],\n",
1414
+ " [ 0.86751825, -0.02274521, -0.32604477],\n",
1415
+ " ...,\n",
1416
+ " [-0.9853346 , -0.00682022, 0.7171635 ],\n",
1417
+ " [-0.08696323, -0.05667413, 0.87342036],\n",
1418
+ " [ 0.6004617 , -0.88708836, -0.26810724]],\n",
1419
+ " \n",
1420
+ " [[-0.5743125 , -0.28754738, -0.38174978],\n",
1421
+ " [ 0.24815533, -0.57756484, 0.93569994],\n",
1422
+ " [-0.7405034 , -0.32665822, 0.08748504],\n",
1423
+ " ...,\n",
1424
+ " [-0.7491653 , -0.22141415, 0.45474625],\n",
1425
+ " [-0.57349765, 0.4679093 , 0.38798517],\n",
1426
+ " [ 0.6612893 , 0.41478157, 0.22837359]]],\n",
1427
+ " \n",
1428
+ " \n",
1429
+ " [[[ 0.23990859, 0.67921597, -0.0824727 ],\n",
1430
+ " [ 0.9907199 , -0.05199495, 0.68338317],\n",
1431
+ " [-0.30894232, 0.16669795, -0.9820439 ],\n",
1432
+ " ...,\n",
1433
+ " [ 0.3199286 , -0.18558857, -0.47307304],\n",
1434
+ " [ 0.76532894, -0.18667097, -0.03431672],\n",
1435
+ " [-0.99945 , 0.2608576 , 0.21886484]],\n",
1436
+ " \n",
1437
+ " [[-0.7637533 , -0.7089846 , 0.33706984],\n",
1438
+ " [-0.14597686, 0.12005411, 0.67450196],\n",
1439
+ " [-0.41098934, -0.26850244, -0.62142074],\n",
1440
+ " ...,\n",
1441
+ " [ 0.03754954, 0.8318801 , -0.39396647],\n",
1442
+ " [-0.94338244, 0.51633537, 0.5040307 ],\n",
1443
+ " [-0.74726474, -0.46540555, -0.90814143]],\n",
1444
+ " \n",
1445
+ " [[-0.97426575, -0.05216308, 0.33192778],\n",
1446
+ " [ 0.79409444, -0.39431155, -0.8361488 ],\n",
1447
+ " [-0.7443832 , -0.71833146, 0.18875524],\n",
1448
+ " ...,\n",
1449
+ " [ 0.16434367, -0.17734596, 0.8922563 ],\n",
1450
+ " [-0.05866683, -0.12135171, -0.8696513 ],\n",
1451
+ " [-0.8378553 , 0.39082694, -0.8282066 ]],\n",
1452
+ " \n",
1453
+ " ...,\n",
1454
+ " \n",
1455
+ " [[-0.78078943, -0.28758067, 0.55912423],\n",
1456
+ " [-0.41945398, 0.10534741, -0.08547217],\n",
1457
+ " [ 0.40273872, -0.5773211 , -0.55002224],\n",
1458
+ " ...,\n",
1459
+ " [ 0.41769743, -0.7536503 , 0.68870306],\n",
1460
+ " [-0.07471471, 0.18406834, 0.43383718],\n",
1461
+ " [ 0.10514516, 0.38181868, -0.7030233 ]],\n",
1462
+ " \n",
1463
+ " [[ 0.34112328, -0.7097054 , -0.3172068 ],\n",
1464
+ " [ 0.563122 , 0.48956668, -0.32000723],\n",
1465
+ " [ 0.9611757 , 0.31197235, -0.7195999 ],\n",
1466
+ " ...,\n",
1467
+ " [ 0.82261676, -0.15997183, 0.8282803 ],\n",
1468
+ " [-0.7897127 , -0.05511652, 0.13720344],\n",
1469
+ " [-0.61187834, -0.17737533, 0.15863198]],\n",
1470
+ " \n",
1471
+ " [[-0.5428852 , -0.6527795 , -0.14247131],\n",
1472
+ " [ 0.32340297, 0.2847535 , 0.51328224],\n",
1473
+ " [ 0.5035177 , -0.7584425 , -0.62289554],\n",
1474
+ " ...,\n",
1475
+ " [-0.70956707, 0.9313676 , 0.7000527 ],\n",
1476
+ " [ 0.9710743 , -0.5294576 , -0.7983858 ],\n",
1477
+ " [ 0.7939999 , -0.03741058, -0.8584245 ]]],\n",
1478
+ " \n",
1479
+ " \n",
1480
+ " [[[ 0.8901845 , -0.43774545, -0.89030087],\n",
1481
+ " [ 0.14179797, 0.611246 , 0.00644357],\n",
1482
+ " [ 0.02542099, -0.62599826, -0.06975403],\n",
1483
+ " ...,\n",
1484
+ " [ 0.41743374, -0.61252105, -0.72888297],\n",
1485
+ " [ 0.97254425, -0.5409909 , 0.8970997 ],\n",
1486
+ " [ 0.36102986, -0.9833065 , -0.45462072]],\n",
1487
+ " \n",
1488
+ " [[ 0.24190257, -0.04418936, -0.52343076],\n",
1489
+ " [ 0.52312666, 0.9861895 , 0.6383785 ],\n",
1490
+ " [-0.19900928, -0.48770672, -0.0808301 ],\n",
1491
+ " ...,\n",
1492
+ " [-0.3295493 , 0.054899 , 0.22847334],\n",
1493
+ " [ 0.5941548 , 0.5818441 , -0.04857951],\n",
1494
+ " [ 0.6923948 , -0.10657102, -0.18672003]],\n",
1495
+ " \n",
1496
+ " [[-0.66279167, 0.60028064, -0.99437755],\n",
1497
+ " [-0.27764222, -0.40241897, 0.10143552],\n",
1498
+ " [-0.5356752 , 0.11343295, -0.6149851 ],\n",
1499
+ " ...,\n",
1500
+ " [-0.09456982, -0.02978504, -0.82244366],\n",
1501
+ " [-0.71680355, -0.52770984, 0.276709 ],\n",
1502
+ " [-0.76549846, -0.11741817, 0.1673337 ]],\n",
1503
+ " \n",
1504
+ " ...,\n",
1505
+ " \n",
1506
+ " [[-0.9019588 , -0.74713886, -0.09043121],\n",
1507
+ " [ 0.12472935, -0.32747027, 0.5888375 ],\n",
1508
+ " [ 0.41626027, -0.52641034, -0.21418609],\n",
1509
+ " ...,\n",
1510
+ " [-0.72639674, 0.52203554, -0.5446443 ],\n",
1511
+ " [-0.351838 , -0.28190666, 0.7792516 ],\n",
1512
+ " [-0.07992145, 0.83498347, -0.41640225]],\n",
1513
+ " \n",
1514
+ " [[-0.15768051, -0.2605806 , 0.25499323],\n",
1515
+ " [-0.24911173, -0.8049011 , 0.12153912],\n",
1516
+ " [ 0.7586365 , 0.3035122 , 0.5292572 ],\n",
1517
+ " ...,\n",
1518
+ " [-0.64439803, -0.02354313, -0.28976336],\n",
1519
+ " [ 0.3624827 , -0.7111544 , 0.00895626],\n",
1520
+ " [-0.7225201 , 0.5968738 , -0.90544784]],\n",
1521
+ " \n",
1522
+ " [[-0.20056196, 0.36224863, -0.63471746],\n",
1523
+ " [ 0.5109507 , 0.371023 , -0.14084384],\n",
1524
+ " [-0.5134931 , -0.6323056 , 0.45017627],\n",
1525
+ " ...,\n",
1526
+ " [-0.70404285, 0.08635035, 0.6546207 ],\n",
1527
+ " [ 0.16384816, 0.09740724, -0.59950197],\n",
1528
+ " [ 0.7292889 , 0.32022667, -0.804577 ]]],\n",
1529
+ " \n",
1530
+ " \n",
1531
+ " ...,\n",
1532
+ " \n",
1533
+ " \n",
1534
+ " [[[ 0.8632959 , 0.23315103, -0.2725876 ],\n",
1535
+ " [ 0.20504592, -0.04780598, -0.5718923 ],\n",
1536
+ " [-0.72774106, -0.96962607, 0.97729003],\n",
1537
+ " ...,\n",
1538
+ " [-0.21135814, -0.14353034, -0.9695071 ],\n",
1539
+ " [-0.7038561 , -0.98513675, 0.61275756],\n",
1540
+ " [ 0.35675755, -0.83099693, -0.2592585 ]],\n",
1541
+ " \n",
1542
+ " [[-0.45146814, 0.5089786 , 0.5684371 ],\n",
1543
+ " [ 0.6286422 , 0.57635343, 0.9317202 ],\n",
1544
+ " [ 0.5068013 , 0.2801699 , 0.57054186],\n",
1545
+ " ...,\n",
1546
+ " [ 0.1552294 , 0.464232 , -0.93938786],\n",
1547
+ " [-0.20987932, 0.8206099 , -0.33238935],\n",
1548
+ " [ 0.901621 , -0.02599482, -0.14379497]],\n",
1549
+ " \n",
1550
+ " [[-0.6968208 , 0.00414733, -0.22662742],\n",
1551
+ " [ 0.9541678 , -0.92105657, 0.43932232],\n",
1552
+ " [-0.10794581, -0.7354901 , -0.16855466],\n",
1553
+ " ...,\n",
1554
+ " [ 0.1740309 , 0.9954902 , -0.18840998],\n",
1555
+ " [ 0.16357523, 0.70654786, 0.5858755 ],\n",
1556
+ " [ 0.54051095, -0.08337101, -0.19213425]],\n",
1557
+ " \n",
1558
+ " ...,\n",
1559
+ " \n",
1560
+ " [[ 0.42826653, -0.1250443 , 0.7330338 ],\n",
1561
+ " [ 0.5163002 , -0.13500777, 0.06314756],\n",
1562
+ " [ 0.9741123 , 0.456963 , -0.40399393],\n",
1563
+ " ...,\n",
1564
+ " [-0.14186057, 0.35157713, 0.45124835],\n",
1565
+ " [-0.8106887 , -0.2952597 , -0.00138865],\n",
1566
+ " [ 0.80122894, -0.06712676, -0.12358644]],\n",
1567
+ " \n",
1568
+ " [[ 0.10288525, -0.73420316, -0.49193767],\n",
1569
+ " [ 0.95312274, -0.10698953, 0.45929238],\n",
1570
+ " [-0.39555478, -0.22329426, 0.76963884],\n",
1571
+ " ...,\n",
1572
+ " [-0.35652 , 0.7178503 , -0.16420537],\n",
1573
+ " [-0.31216472, 0.7369841 , -0.08176024],\n",
1574
+ " [ 0.8919196 , 0.99512047, 0.8206974 ]],\n",
1575
+ " \n",
1576
+ " [[ 0.8600763 , -0.65400755, -0.76536787],\n",
1577
+ " [-0.9348416 , 0.9015583 , 0.8686483 ],\n",
1578
+ " [ 0.08320471, -0.75950325, 0.60284853],\n",
1579
+ " ...,\n",
1580
+ " [-0.74470997, 0.79727405, 0.29623058],\n",
1581
+ " [-0.931635 , 0.39461872, 0.32315913],\n",
1582
+ " [ 0.8596173 , -0.11210055, -0.9014713 ]]],\n",
1583
+ " \n",
1584
+ " \n",
1585
+ " [[[ 0.9557131 , 0.51511854, 0.51625407],\n",
1586
+ " [-0.7998263 , -0.9888872 , -0.25109488],\n",
1587
+ " [ 0.6247858 , 0.03450096, 0.6986955 ],\n",
1588
+ " ...,\n",
1589
+ " [-0.62218463, -0.09981211, -0.48238307],\n",
1590
+ " [-0.91681355, -0.76599586, -0.42799118],\n",
1591
+ " [ 0.54166514, -0.0272945 , 0.50488085]],\n",
1592
+ " \n",
1593
+ " [[-0.7732551 , 0.93639505, -0.6052133 ],\n",
1594
+ " [-0.26438248, -0.8784178 , 0.17651004],\n",
1595
+ " [ 0.89367765, 0.5923974 , 0.35096487],\n",
1596
+ " ...,\n",
1597
+ " [-0.52759904, -0.7916573 , 0.7133445 ],\n",
1598
+ " [ 0.7226203 , 0.32371753, 0.46221355],\n",
1599
+ " [-0.45732328, 0.18426989, 0.30426434]],\n",
1600
+ " \n",
1601
+ " [[-0.08537266, -0.8033094 , -0.6089663 ],\n",
1602
+ " [-0.59840065, 0.14420089, 0.33707345],\n",
1603
+ " [-0.17465238, 0.20823634, 0.5888653 ],\n",
1604
+ " ...,\n",
1605
+ " [-0.2677055 , 0.14733633, 0.5407291 ],\n",
1606
+ " [-0.36229333, -0.0729902 , 0.8718523 ],\n",
1607
+ " [-0.90160805, 0.00141446, 0.7210703 ]],\n",
1608
+ " \n",
1609
+ " ...,\n",
1610
+ " \n",
1611
+ " [[-0.85141885, -0.51382506, -0.06678717],\n",
1612
+ " [ 0.05432899, -0.6202059 , -0.9049751 ],\n",
1613
+ " [-0.60066575, -0.26520628, -0.01333359],\n",
1614
+ " ...,\n",
1615
+ " [ 0.22806203, 0.3521899 , -0.43207094],\n",
1616
+ " [-0.81630826, 0.59435016, -0.46893248],\n",
1617
+ " [-0.5959631 , 0.7167057 , -0.23267433]],\n",
1618
+ " \n",
1619
+ " [[-0.52592236, 0.917724 , 0.56912273],\n",
1620
+ " [-0.16404797, 0.01199967, 0.5534951 ],\n",
1621
+ " [-0.13700093, -0.02836936, 0.992241 ],\n",
1622
+ " ...,\n",
1623
+ " [ 0.97559524, 0.14499836, -0.8145345 ],\n",
1624
+ " [-0.8679686 , 0.2716515 , -0.6882405 ],\n",
1625
+ " [ 0.7061002 , -0.8457013 , -0.29838315]],\n",
1626
+ " \n",
1627
+ " [[ 0.02104092, -0.80090034, 0.6654512 ],\n",
1628
+ " [ 0.81835026, 0.98487353, -0.6736776 ],\n",
1629
+ " [-0.6045387 , -0.72641295, -0.6428804 ],\n",
1630
+ " ...,\n",
1631
+ " [-0.1317824 , -0.4277776 , 0.59556156],\n",
1632
+ " [ 0.12357017, 0.66459644, -0.02918302],\n",
1633
+ " [ 0.64688176, 0.57444984, -0.7633122 ]]],\n",
1634
+ " \n",
1635
+ " \n",
1636
+ " [[[ 0.88441813, 0.13186614, -0.19332951],\n",
1637
+ " [ 0.38274857, 0.46528432, -0.59135216],\n",
1638
+ " [ 0.41270712, 0.6391209 , -0.12653033],\n",
1639
+ " ...,\n",
1640
+ " [-0.46041277, 0.15823546, -0.36274964],\n",
1641
+ " [-0.01825326, -0.39985612, -0.79977125],\n",
1642
+ " [ 0.6753411 , 0.8756111 , -0.28732926]],\n",
1643
+ " \n",
1644
+ " [[-0.711089 , -0.43889335, 0.3260634 ],\n",
1645
+ " [ 0.7734591 , -0.03330078, -0.9913227 ],\n",
1646
+ " [ 0.7343164 , 0.3724718 , -0.3069795 ],\n",
1647
+ " ...,\n",
1648
+ " [ 0.902753 , -0.15250501, 0.15584068],\n",
1649
+ " [ 0.73821497, 0.7488559 , 0.14212039],\n",
1650
+ " [-0.5618118 , 0.9826356 , -0.7965195 ]],\n",
1651
+ " \n",
1652
+ " [[-0.46017474, -0.15891087, 0.7655822 ],\n",
1653
+ " [ 0.13344122, -0.17511413, 0.41764355],\n",
1654
+ " [ 0.9100026 , 0.10703834, 0.43876615],\n",
1655
+ " ...,\n",
1656
+ " [-0.532919 , -0.43651375, -0.6527969 ],\n",
1657
+ " [-0.8039171 , 0.32828027, 0.9531818 ],\n",
1658
+ " [ 0.1933955 , -0.47509086, -0.5242459 ]],\n",
1659
+ " \n",
1660
+ " ...,\n",
1661
+ " \n",
1662
+ " [[-0.74735814, 0.72423774, 0.1607682 ],\n",
1663
+ " [-0.49932945, -0.28452674, 0.583701 ],\n",
1664
+ " [ 0.4539929 , -0.2301782 , -0.57468385],\n",
1665
+ " ...,\n",
1666
+ " [ 0.9332663 , -0.7137419 , -0.76694316],\n",
1667
+ " [-0.9713287 , -0.54707056, 0.6367553 ],\n",
1668
+ " [-0.3407068 , 0.48964027, -0.34655765]],\n",
1669
+ " \n",
1670
+ " [[ 0.63276297, -0.0025239 , -0.9229073 ],\n",
1671
+ " [ 0.97217876, -0.6745119 , -0.23177056],\n",
1672
+ " [-0.95159733, -0.25796613, -0.1879078 ],\n",
1673
+ " ...,\n",
1674
+ " [-0.29919153, -0.7822294 , -0.830865 ],\n",
1675
+ " [ 0.05126443, -0.00114107, 0.3076648 ],\n",
1676
+ " [-0.3034132 , 0.02711284, 0.14348714]],\n",
1677
+ " \n",
1678
+ " [[-0.28522325, 0.7907883 , 0.6343502 ],\n",
1679
+ " [-0.5154842 , 0.38837066, 0.62787414],\n",
1680
+ " [ 0.9281381 , -0.9275004 , 0.22157295],\n",
1681
+ " ...,\n",
1682
+ " [ 0.538515 , -0.6402134 , -0.749157 ],\n",
1683
+ " [ 0.66603833, 0.4040758 , 0.41578275],\n",
1684
+ " [ 0.40337127, 0.17796195, 0.48830876]]]], dtype=float32),\n",
1685
+ " array([[[[-0.09761024, -0.30392915, -0.532037 ],\n",
1686
+ " [-0.4985318 , -0.26200393, 0.74756134],\n",
1687
+ " [ 0.5456366 , 0.5216474 , 0.17573003],\n",
1688
+ " ...,\n",
1689
+ " [-0.35066032, -0.9676611 , 0.16510126],\n",
1690
+ " [-0.03528262, 0.1672383 , 0.4722226 ],\n",
1691
+ " [ 0.8486285 , 0.44736686, 0.46429393]],\n",
1692
+ " \n",
1693
+ " [[ 0.8957866 , -0.7141274 , 0.7524458 ],\n",
1694
+ " [-0.17791416, 0.24181178, 0.5095949 ],\n",
1695
+ " [-0.16257447, 0.6047909 , 0.6541636 ],\n",
1696
+ " ...,\n",
1697
+ " [ 0.4791796 , -0.25393185, 0.57068074],\n",
1698
+ " [ 0.21887556, -0.82492507, -0.40770605],\n",
1699
+ " [-0.86580145, 0.6994423 , 0.56402194]],\n",
1700
+ " \n",
1701
+ " [[-0.44615242, 0.37368667, 0.487562 ],\n",
1702
+ " [ 0.46959826, 0.4146808 , 0.8709558 ],\n",
1703
+ " [ 0.466646 , 0.8664238 , -0.7941095 ],\n",
1704
+ " ...,\n",
1705
+ " [ 0.31342426, -0.14214593, -0.24526963],\n",
1706
+ " [ 0.03417497, 0.3613936 , -0.46797788],\n",
1707
+ " [ 0.08023469, -0.44023722, 0.3067228 ]],\n",
1708
+ " \n",
1709
+ " ...,\n",
1710
+ " \n",
1711
+ " [[ 0.90941036, 0.66813934, 0.143825 ],\n",
1712
+ " [ 0.86224645, -0.69228095, 0.14004375],\n",
1713
+ " [ 0.54902893, 0.27830395, -0.11832863],\n",
1714
+ " ...,\n",
1715
+ " [ 0.9694666 , -0.49526292, 0.60761684],\n",
1716
+ " [ 0.6885517 , -0.21032126, 0.83271325],\n",
1717
+ " [ 0.4008625 , 0.39925125, 0.46474057]],\n",
1718
+ " \n",
1719
+ " [[-0.26691753, 0.36299744, 0.9040832 ],\n",
1720
+ " [ 0.71295077, 0.90513664, -0.57749367],\n",
1721
+ " [ 0.8669232 , 0.75442845, -0.21071313],\n",
1722
+ " ...,\n",
1723
+ " [ 0.10470442, -0.91280633, -0.42264822],\n",
1724
+ " [ 0.74220043, -0.5006377 , 0.47649434],\n",
1725
+ " [ 0.5809972 , -0.9898106 , -0.54520124]],\n",
1726
+ " \n",
1727
+ " [[ 0.8578593 , -0.4514605 , -0.95225835],\n",
1728
+ " [ 0.59103155, 0.74154574, -0.14905412],\n",
1729
+ " [ 0.565652 , -0.3944241 , 0.96364313],\n",
1730
+ " ...,\n",
1731
+ " [-0.5746383 , -0.99080217, -0.15032336],\n",
1732
+ " [-0.58851385, -0.9083053 , -0.3877851 ],\n",
1733
+ " [ 0.5251193 , -0.77367866, -0.03464826]]],\n",
1734
+ " \n",
1735
+ " \n",
1736
+ " [[[-0.7700639 , 0.6727907 , -0.5305355 ],\n",
1737
+ " [-0.38343665, 0.10980862, -0.15998466],\n",
1738
+ " [-0.76086086, 0.04810994, 0.6140598 ],\n",
1739
+ " ...,\n",
1740
+ " [ 0.9684511 , -0.5625563 , -0.6988832 ],\n",
1741
+ " [-0.60180825, 0.11137901, -0.43545145],\n",
1742
+ " [-0.02136761, -0.5755145 , -0.23514289]],\n",
1743
+ " \n",
1744
+ " [[ 0.1880484 , -0.45053557, -0.6444847 ],\n",
1745
+ " [-0.49953768, 0.13226132, 0.6894241 ],\n",
1746
+ " [-0.58495694, 0.2673738 , 0.36261198],\n",
1747
+ " ...,\n",
1748
+ " [-0.56476676, -0.91512537, 0.3463638 ],\n",
1749
+ " [ 0.16266131, 0.19705893, 0.62607545],\n",
1750
+ " [-0.5773459 , -0.04495085, 0.7959926 ]],\n",
1751
+ " \n",
1752
+ " [[ 0.05681601, 0.7062089 , -0.15438975],\n",
1753
+ " [-0.37692162, -0.84395754, -0.23036075],\n",
1754
+ " [-0.52323174, -0.5597486 , 0.18381292],\n",
1755
+ " ...,\n",
1756
+ " [-0.05755488, 0.5762286 , -0.25126597],\n",
1757
+ " [ 0.87147176, 0.45814615, 0.9410781 ],\n",
1758
+ " [ 0.6294345 , 0.7147004 , 0.59225434]],\n",
1759
+ " \n",
1760
+ " ...,\n",
1761
+ " \n",
1762
+ " [[ 0.11636508, -0.41076738, 0.71641374],\n",
1763
+ " [-0.96412325, 0.9335117 , 0.79578024],\n",
1764
+ " [-0.46454152, 0.7533581 , 0.9619629 ],\n",
1765
+ " ...,\n",
1766
+ " [-0.3700655 , 0.5271773 , 0.23149076],\n",
1767
+ " [-0.37072185, 0.09876549, -0.0831551 ],\n",
1768
+ " [ 0.04362793, 0.2436407 , 0.07159407]],\n",
1769
+ " \n",
1770
+ " [[ 0.95503896, -0.7910851 , -0.29814336],\n",
1771
+ " [-0.19001536, 0.9374673 , 0.39852333],\n",
1772
+ " [-0.9246351 , -0.53165865, -0.13787708],\n",
1773
+ " ...,\n",
1774
+ " [-0.57892203, -0.97029454, -0.7449691 ],\n",
1775
+ " [ 0.5401612 , 0.8652369 , 0.9676358 ],\n",
1776
+ " [ 0.89398664, 0.13884948, -0.6947489 ]],\n",
1777
+ " \n",
1778
+ " [[-0.12104174, 0.5399893 , -0.45787314],\n",
1779
+ " [ 0.46745577, -0.04551645, -0.44435573],\n",
1780
+ " [-0.7169747 , -0.00952705, -0.46401465],\n",
1781
+ " ...,\n",
1782
+ " [ 0.7135665 , 0.14663117, -0.02600863],\n",
1783
+ " [-0.09997784, 0.2724123 , -0.13589467],\n",
1784
+ " [ 0.32932022, -0.24653798, -0.8703547 ]]],\n",
1785
+ " \n",
1786
+ " \n",
1787
+ " [[[ 0.87572485, -0.8187371 , 0.9611577 ],\n",
1788
+ " [-0.15702325, 0.28702363, 0.98309314],\n",
1789
+ " [-0.5654241 , 0.04852458, 0.39296043],\n",
1790
+ " ...,\n",
1791
+ " [-0.3014218 , 0.0580539 , -0.20785046],\n",
1792
+ " [ 0.9558934 , 0.5346459 , 0.6446185 ],\n",
1793
+ " [ 0.26713362, -0.23455794, -0.10412423]],\n",
1794
+ " \n",
1795
+ " [[-0.2697786 , 0.4073575 , -0.50415117],\n",
1796
+ " [-0.4951515 , 0.4364923 , 0.9737966 ],\n",
1797
+ " [ 0.7009036 , 0.5579904 , 0.68727493],\n",
1798
+ " ...,\n",
1799
+ " [ 0.0097886 , 0.11514235, 0.87599474],\n",
1800
+ " [-0.29946226, 0.61298895, 0.1020955 ],\n",
1801
+ " [ 0.59954906, -0.26519343, -0.78347236]],\n",
1802
+ " \n",
1803
+ " [[-0.7213799 , 0.7840852 , -0.19820659],\n",
1804
+ " [ 0.5428176 , -0.35510898, -0.41404557],\n",
1805
+ " [ 0.27182126, 0.01733118, -0.84065384],\n",
1806
+ " ...,\n",
1807
+ " [ 0.92033416, -0.5976892 , -0.64507836],\n",
1808
+ " [ 0.18807815, -0.96800643, -0.3395124 ],\n",
1809
+ " [ 0.28158996, -0.35724983, 0.43961713]],\n",
1810
+ " \n",
1811
+ " ...,\n",
1812
+ " \n",
1813
+ " [[-0.60179234, 0.5150797 , -0.25477463],\n",
1814
+ " [ 0.8940863 , -0.05375351, 0.5048189 ],\n",
1815
+ " [ 0.05627483, -0.07155563, -0.86517763],\n",
1816
+ " ...,\n",
1817
+ " [ 0.66762495, 0.08343208, 0.8836395 ],\n",
1818
+ " [-0.69654983, 0.6624872 , -0.95558155],\n",
1819
+ " [ 0.7626284 , 0.29368255, 0.8936367 ]],\n",
1820
+ " \n",
1821
+ " [[ 0.93593705, 0.49275655, 0.18476433],\n",
1822
+ " [ 0.1462863 , 0.8068025 , -0.17627642],\n",
1823
+ " [ 0.75060433, -0.34054723, 0.0236972 ],\n",
1824
+ " ...,\n",
1825
+ " [-0.81033224, -0.05584071, -0.96746147],\n",
1826
+ " [ 0.190843 , 0.2095473 , -0.00276738],\n",
1827
+ " [-0.8388976 , 0.395619 , -0.8727371 ]],\n",
1828
+ " \n",
1829
+ " [[ 0.4763672 , -0.57040495, -0.27286014],\n",
1830
+ " [-0.27356914, -0.9704355 , -0.5486967 ],\n",
1831
+ " [ 0.8077848 , 0.4638954 , -0.00473936],\n",
1832
+ " ...,\n",
1833
+ " [-0.40994737, 0.24910924, -0.27021465],\n",
1834
+ " [ 0.6625665 , -0.72203106, -0.5544267 ],\n",
1835
+ " [ 0.61208624, -0.24642837, -0.685424 ]]],\n",
1836
+ " \n",
1837
+ " \n",
1838
+ " ...,\n",
1839
+ " \n",
1840
+ " \n",
1841
+ " [[[-0.7948106 , -0.75185704, 0.4360157 ],\n",
1842
+ " [ 0.43322718, -0.76922876, -0.4553052 ],\n",
1843
+ " [ 0.05483327, 0.9044349 , -0.7246787 ],\n",
1844
+ " ...,\n",
1845
+ " [ 0.87762576, 0.94784695, -0.5004968 ],\n",
1846
+ " [-0.86759263, -0.67458004, 0.7349677 ],\n",
1847
+ " [ 0.44185647, -0.94727844, 0.7037094 ]],\n",
1848
+ " \n",
1849
+ " [[-0.5886433 , -0.25528598, 0.04338403],\n",
1850
+ " [-0.18014134, 0.53792703, -0.28259423],\n",
1851
+ " [ 0.9449422 , -0.2244961 , 0.2869904 ],\n",
1852
+ " ...,\n",
1853
+ " [ 0.3551327 , 0.43994123, -0.63882345],\n",
1854
+ " [ 0.1068863 , -0.8962502 , -0.22137173],\n",
1855
+ " [-0.79460657, 0.46858925, 0.03730566]],\n",
1856
+ " \n",
1857
+ " [[-0.79706234, -0.742086 , 0.75119 ],\n",
1858
+ " [-0.10779676, -0.7682731 , -0.5131967 ],\n",
1859
+ " [ 0.63736546, 0.19444293, 0.20428057],\n",
1860
+ " ...,\n",
1861
+ " [ 0.20556358, 0.5195544 , -0.78763014],\n",
1862
+ " [-0.3594062 , -0.05217754, 0.61888605],\n",
1863
+ " [-0.30911717, -0.57907045, 0.3458311 ]],\n",
1864
+ " \n",
1865
+ " ...,\n",
1866
+ " \n",
1867
+ " [[ 0.12832934, 0.70479363, 0.11475497],\n",
1868
+ " [ 0.7319854 , -0.01197664, -0.7304614 ],\n",
1869
+ " [-0.82062304, -0.0462975 , -0.49395818],\n",
1870
+ " ...,\n",
1871
+ " [-0.14975296, -0.62077576, 0.4199367 ],\n",
1872
+ " [ 0.98021966, -0.20368218, 0.4674815 ],\n",
1873
+ " [-0.3750655 , 0.21562403, 0.08286006]],\n",
1874
+ " \n",
1875
+ " [[ 0.31126094, -0.77887255, 0.4148582 ],\n",
1876
+ " [-0.16197252, 0.7042316 , 0.3025308 ],\n",
1877
+ " [-0.45805016, 0.01282571, 0.1056814 ],\n",
1878
+ " ...,\n",
1879
+ " [ 0.55814236, 0.04306215, -0.77490586],\n",
1880
+ " [-0.19841512, 0.34406593, -0.2557008 ],\n",
1881
+ " [-0.63005334, 0.26157996, 0.10701808]],\n",
1882
+ " \n",
1883
+ " [[ 0.6764019 , -0.14582644, -0.09643065],\n",
1884
+ " [-0.70117056, -0.60354304, 0.9400171 ],\n",
1885
+ " [-0.07303251, -0.89738184, 0.24160327],\n",
1886
+ " ...,\n",
1887
+ " [-0.7651852 , -0.7743618 , 0.18953589],\n",
1888
+ " [ 0.06112038, 0.5937549 , 0.34018585],\n",
1889
+ " [ 0.32967502, -0.06467862, -0.40678322]]],\n",
1890
+ " \n",
1891
+ " \n",
1892
+ " [[[ 0.6970428 , 0.5396038 , 0.34120265],\n",
1893
+ " [-0.42208767, 0.8108379 , -0.5076897 ],\n",
1894
+ " [-0.50729525, 0.5388338 , -0.74883556],\n",
1895
+ " ...,\n",
1896
+ " [ 0.5340539 , -0.26003975, -0.01295209],\n",
1897
+ " [ 0.3404956 , -0.66367525, -0.32117507],\n",
1898
+ " [ 0.14763127, -0.12502591, 0.07325792]],\n",
1899
+ " \n",
1900
+ " [[-0.50035733, 0.21759143, 0.46326548],\n",
1901
+ " [-0.57341117, -0.11163796, -0.8019593 ],\n",
1902
+ " [ 0.64425105, 0.20590416, 0.2841419 ],\n",
1903
+ " ...,\n",
1904
+ " [-0.2891181 , 0.6199787 , 0.1329077 ],\n",
1905
+ " [ 0.98585474, 0.30883643, 0.52461624],\n",
1906
+ " [-0.32508534, 0.58094764, 0.4109113 ]],\n",
1907
+ " \n",
1908
+ " [[ 0.7266321 , -0.7991032 , 0.8310582 ],\n",
1909
+ " [ 0.19519348, 0.18852802, 0.18234654],\n",
1910
+ " [ 0.25242078, 0.36649138, -0.14911096],\n",
1911
+ " ...,\n",
1912
+ " [-0.27351817, -0.570457 , 0.19408393],\n",
1913
+ " [ 0.35675475, 0.8473438 , -0.9616454 ],\n",
1914
+ " [-0.9180633 , -0.7418181 , 0.64946944]],\n",
1915
+ " \n",
1916
+ " ...,\n",
1917
+ " \n",
1918
+ " [[-0.61166084, -0.02655862, 0.67064494],\n",
1919
+ " [ 0.19977483, -0.8276316 , -0.5333372 ],\n",
1920
+ " [ 0.26700214, -0.75375295, 0.20355786],\n",
1921
+ " ...,\n",
1922
+ " [-0.40376526, -0.35340172, -0.04956197],\n",
1923
+ " [ 0.39045045, 0.5281777 , 0.288333 ],\n",
1924
+ " [ 0.90908843, 0.04581974, 0.79881626]],\n",
1925
+ " \n",
1926
+ " [[-0.1149637 , -0.21368992, -0.9369082 ],\n",
1927
+ " [-0.9492007 , 0.08806126, -0.41788852],\n",
1928
+ " [-0.33896145, 0.04518719, 0.2994801 ],\n",
1929
+ " ...,\n",
1930
+ " [ 0.15014993, -0.82760036, -0.04961308],\n",
1931
+ " [-0.6249205 , 0.27146855, -0.54995453],\n",
1932
+ " [ 0.06103103, -0.01895145, -0.20486538]],\n",
1933
+ " \n",
1934
+ " [[-0.9538385 , 0.14689353, -0.66378343],\n",
1935
+ " [ 0.2980317 , -0.6901191 , 0.9777879 ],\n",
1936
+ " [ 0.8764587 , 0.8116734 , 0.6305636 ],\n",
1937
+ " ...,\n",
1938
+ " [-0.32657132, 0.06848861, 0.07808213],\n",
1939
+ " [-0.92897373, 0.97584784, 0.3637699 ],\n",
1940
+ " [ 0.74152094, -0.9745608 , 0.34177887]]],\n",
1941
+ " \n",
1942
+ " \n",
1943
+ " [[[-0.36440805, 0.7464876 , -0.96985495],\n",
1944
+ " [-0.790166 , -0.6137034 , -0.6600737 ],\n",
1945
+ " [ 0.9985732 , 0.5086009 , -0.0034632 ],\n",
1946
+ " ...,\n",
1947
+ " [ 0.37532693, 0.97525036, -0.25674835],\n",
1948
+ " [ 0.5447518 , -0.11340256, 0.78214973],\n",
1949
+ " [-0.07224173, -0.9528834 , -0.00884683]],\n",
1950
+ " \n",
1951
+ " [[-0.38090953, -0.23881558, 0.79807127],\n",
1952
+ " [ 0.4279492 , -0.13885075, 0.9887274 ],\n",
1953
+ " [-0.53672445, -0.94442815, -0.26483425],\n",
1954
+ " ...,\n",
1955
+ " [ 0.47182775, -0.98600316, -0.27102533],\n",
1956
+ " [-0.09377925, -0.5953442 , -0.41579443],\n",
1957
+ " [ 0.2206279 , -0.10346638, -0.959961 ]],\n",
1958
+ " \n",
1959
+ " [[ 0.11452412, 0.5565668 , -0.42076495],\n",
1960
+ " [ 0.8975008 , -0.6634841 , -0.94643855],\n",
1961
+ " [-0.718168 , 0.640608 , -0.3462668 ],\n",
1962
+ " ...,\n",
1963
+ " [ 0.64919907, -0.0396354 , 0.10784635],\n",
1964
+ " [ 0.1326577 , 0.9520043 , -0.7041344 ],\n",
1965
+ " [ 0.85544074, -0.66000926, 0.7548248 ]],\n",
1966
+ " \n",
1967
+ " ...,\n",
1968
+ " \n",
1969
+ " [[ 0.5389891 , -0.46764085, -0.3879391 ],\n",
1970
+ " [-0.14177312, 0.5880945 , 0.66012514],\n",
1971
+ " [ 0.6047202 , -0.81624335, -0.7253651 ],\n",
1972
+ " ...,\n",
1973
+ " [-0.99838865, -0.2535178 , 0.7322661 ],\n",
1974
+ " [-0.09629101, -0.328984 , 0.7505362 ],\n",
1975
+ " [ 0.73272383, -0.3906752 , 0.63080835]],\n",
1976
+ " \n",
1977
+ " [[ 0.5777079 , 0.9498767 , -0.43157396],\n",
1978
+ " [ 0.7095449 , 0.9593572 , -0.7768859 ],\n",
1979
+ " [ 0.31529334, -0.5999169 , -0.90815216],\n",
1980
+ " ...,\n",
1981
+ " [ 0.05615072, 0.23518236, 0.45681182],\n",
1982
+ " [ 0.8676728 , 0.84458476, 0.76299095],\n",
1983
+ " [-0.39043453, -0.7991876 , 0.18761688]],\n",
1984
+ " \n",
1985
+ " [[ 0.99921376, 0.3966546 , -0.08978812],\n",
1986
+ " [ 0.57658494, -0.9250148 , 0.02217562],\n",
1987
+ " [ 0.34381852, -0.9457439 , -0.1960047 ],\n",
1988
+ " ...,\n",
1989
+ " [-0.10982312, -0.34750128, -0.1745162 ],\n",
1990
+ " [-0.5160771 , 0.2821715 , -0.904882 ],\n",
1991
+ " [ 0.04304201, 0.04218881, -0.04785283]]]], dtype=float32)),\n",
1992
+ " 'images.mask': (array([1, 0, 1, 1, 0], dtype=uint8), array([1], dtype=uint8)),\n",
1993
+ " 'numeric_state': array([[ 1.8376809 , 1.1338784 , 0.5727793 , 0.01476933, -1.5394237 ,\n",
1994
+ " 0.42149323, -0.390883 , -0.61183983, 1.9005232 , 1.4375548 ,\n",
1995
+ " -1.5471035 , 0.49237502, 0.44047335, 0.9869103 , -0.6251644 ,\n",
1996
+ " -0.24667569, 0.62240875, 0.4202634 , -1.4045496 , 0.9524107 ,\n",
1997
+ " -0.99612767, -2.890442 , 0.4567491 , 1.2895898 , 0.35284355,\n",
1998
+ " -0.5857049 , 0.3442675 , 1.0593696 , -1.6187135 , -2.4965794 ,\n",
1999
+ " -2.7430422 , 2.8443644 ],\n",
2000
+ " [ 0.62603813, 0.42341325, -0.80942756, 0.42096514, -0.2508196 ,\n",
2001
+ " 0.6267991 , 0.4376274 , -2.1533499 , 0.44512403, 0.27406594,\n",
2002
+ " -0.41945305, -2.0222352 , -0.0639386 , 0.90138483, 1.6011438 ,\n",
2003
+ " 0.6226233 , 0.4007397 , -0.28588122, 0.9984836 , -0.70039254,\n",
2004
+ " -0.34809205, 0.7487102 , -0.46809694, 0.18789259, -1.1118935 ,\n",
2005
+ " 0.64455765, -0.8660118 , 0.65826243, 0.00590917, -2.064305 ,\n",
2006
+ " 0.24475242, 0.36426893]], dtype=float32),\n",
2007
+ " 'tokenized_text': (array([1], dtype=int32),\n",
2008
+ " array([0, 0, 0, 1, 0, 3, 1, 0, 0, 1, 0, 1, 1], dtype=int32)),\n",
2009
+ " 'tokenized_text.mask': (array([0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0], dtype=uint8),\n",
2010
+ " array([0, 1, 1, 0, 0, 1, 1], dtype=uint8))}"
2011
+ ]
2012
+ },
2013
+ "execution_count": 5,
2014
+ "metadata": {},
2015
+ "output_type": "execute_result"
2016
+ }
2017
+ ],
2018
+ "source": [
2019
+ "from robotodo.controllers.pi0.nn.pi0 import Pi0\n",
2020
+ "\n",
2021
+ "Pi0._TODO_ObservationSpec().batched(2).sample()"
2022
+ ]
2023
+ },
2024
+ {
2025
+ "cell_type": "code",
2026
+ "execution_count": 2,
2027
+ "id": "1af9a4ad",
2028
+ "metadata": {},
2029
+ "outputs": [],
2030
+ "source": [
2031
+ "sample = Pi0.ObservationSpec().batched(12).sample()"
2032
+ ]
2033
+ },
2034
+ {
2035
+ "cell_type": "code",
2036
+ "execution_count": 3,
2037
+ "id": "47c6e5a7",
2038
+ "metadata": {},
2039
+ "outputs": [
2040
+ {
2041
+ "data": {
2042
+ "text/plain": [
2043
+ "Dict('images': Box(-1.0, 1.0, (12, 3, 224, 224, 3), float32), 'images.mask': Box(0, 1, (12, 3), uint8), 'numeric_state': Box(-inf, inf, (12, 32), float32), 'tokenized_text': Box(0, 257152, (12, 48), int32), 'tokenized_text.mask': Box(0, 1, (12, 48), uint8))"
2044
+ ]
2045
+ },
2046
+ "execution_count": 3,
2047
+ "metadata": {},
2048
+ "output_type": "execute_result"
2049
+ }
2050
+ ],
2051
+ "source": [
2052
+ "Pi0.ObservationSpec().batched(12)"
2053
+ ]
2054
+ },
2055
+ {
2056
+ "cell_type": "code",
2057
+ "execution_count": 4,
2058
+ "id": "25aef1d2",
2059
+ "metadata": {},
2060
+ "outputs": [
2061
+ {
2062
+ "data": {
2063
+ "text/plain": [
2064
+ "Box(-1.0, 1.0, (1, 3, 224, 224, 3), float32)"
2065
+ ]
2066
+ },
2067
+ "execution_count": 4,
2068
+ "metadata": {},
2069
+ "output_type": "execute_result"
2070
+ }
2071
+ ],
2072
+ "source": [
2073
+ "Pi0.ObservationSpec().batched()[\"images\"] #.sample().shape"
2074
+ ]
2075
+ },
2076
+ {
2077
+ "cell_type": "code",
2078
+ "execution_count": 5,
2079
+ "id": "ae3189ed",
2080
+ "metadata": {},
2081
+ "outputs": [
2082
+ {
2083
+ "data": {
2084
+ "text/plain": [
2085
+ "masked_array(\n",
2086
+ " data=[[1.0, 2.0, 3.0],\n",
2087
+ " [4.0, 5.0, --],\n",
2088
+ " [6.0, --, --]],\n",
2089
+ " mask=[[False, False, False],\n",
2090
+ " [False, False, True],\n",
2091
+ " [False, True, True]],\n",
2092
+ " fill_value=1e+20)"
2093
+ ]
2094
+ },
2095
+ "execution_count": 5,
2096
+ "metadata": {},
2097
+ "output_type": "execute_result"
2098
+ }
2099
+ ],
2100
+ "source": [
2101
+ "import numpy as np\n",
2102
+ "\n",
2103
+ "\n",
2104
+ "\n",
2105
+ "def pad_arrays(arrays, fill_value=np.ma.masked):\n",
2106
+ " # Step 1: Find the maximum length\n",
2107
+ " max_len = max(len(arr) for arr in arrays)\n",
2108
+ "\n",
2109
+ " # Step 2: Pad each array to max_len with a mask fill value (e.g., 0)\n",
2110
+ " padded = np.full((len(arrays), max_len), fill_value=fill_value, dtype=float)\n",
2111
+ " mask = np.ones_like(padded, dtype=bool)\n",
2112
+ "\n",
2113
+ " for i, arr in enumerate(arrays):\n",
2114
+ " padded[i, :len(arr)] = arr\n",
2115
+ " mask[i, :len(arr)] = False\n",
2116
+ "\n",
2117
+ " # Step 3: Create masked array\n",
2118
+ " return np.ma.masked_array(padded, mask=mask)\n",
2119
+ "\n",
2120
+ "arrays = (\n",
2121
+ " np.array([1, 2, 3]),\n",
2122
+ " np.array([4, 5]),\n",
2123
+ " np.array([6])\n",
2124
+ ")\n",
2125
+ "pad_arrays(arrays)"
2126
+ ]
2127
+ },
2128
+ {
2129
+ "cell_type": "code",
2130
+ "execution_count": null,
2131
+ "id": "9ee53d91",
2132
+ "metadata": {},
2133
+ "outputs": [],
2134
+ "source": [
2135
+ "# import numpy as np\n",
2136
+ "\n",
2137
+ "# def stack_to_masked(arrays):\n",
2138
+ "# \"\"\"\n",
2139
+ "# Converts a tuple of NumPy arrays with unequal first dimensions\n",
2140
+ "# into a masked array.\n",
2141
+ "# \"\"\"\n",
2142
+ "# # Determine the max shape across all arrays\n",
2143
+ "# ndim = arrays[0].ndim\n",
2144
+ "# max_shape = list(arrays[0].shape)\n",
2145
+ "# for arr in arrays[1:]:\n",
2146
+ "# for i in range(ndim):\n",
2147
+ "# if arr.shape[i] > max_shape[i]:\n",
2148
+ "# max_shape[i] = arr.shape[i]\n",
2149
+ " \n",
2150
+ "# # Create padded and mask arrays\n",
2151
+ "# padded_shape = (len(arrays), *max_shape)\n",
2152
+ "# result = np.full(padded_shape, fill_value=np.ma.masked, dtype=np.result_type(*arrays))\n",
2153
+ "# mask = np.full((padded_shape[0], padded_shape[1]), fill_value=False, dtype=bool)\n",
2154
+ "\n",
2155
+ "# for i, arr in enumerate(arrays):\n",
2156
+ "# slices = tuple(slice(0, s) for s in arr.shape)\n",
2157
+ "# result[(i, *slices)] = arr\n",
2158
+ "# # mask[(i, *slices)] = False\n",
2159
+ "# mask[(i, slices[0])] = True\n",
2160
+ "\n",
2161
+ "# return result, mask\n",
2162
+ "# # return np.ma.masked_array(result, mask=mask)\n",
2163
+ "\n",
2164
+ "\n",
2165
+ "# def stack_to_masked(arrays: list[np.ndarray]):\n",
2166
+ "# \"\"\"\n",
2167
+ "# TODO doc\n",
2168
+ "\n",
2169
+ "# Converts a tuple of NumPy arrays with unequal first dimensions\n",
2170
+ "# into a masked array.\n",
2171
+ "# \"\"\"\n",
2172
+ "\n",
2173
+ "# first_shape = (len(arrays), max(array.shape[0] for array in arrays))\n",
2174
+ "# # TODO optimize\n",
2175
+ "# rest_shapes = [array.shape[1:] for array in arrays]\n",
2176
+ "# assert len(set(rest_shapes)) == 1, \"All arrays must have the same shape except for the first dimension.\"\n",
2177
+ "# rest_shape = next(iter(rest_shapes))\n",
2178
+ "\n",
2179
+ "# mask = np.full((*first_shape, ), fill_value=False, dtype=bool)\n",
2180
+ "# result = np.full((*first_shape, *rest_shape), fill_value=np.ma.masked, dtype=np.result_type(*arrays))\n",
2181
+ "\n",
2182
+ "# for i, arr in enumerate(arrays):\n",
2183
+ "# slices = tuple(slice(0, s) for s in arr.shape)\n",
2184
+ "# mask[i, slices[0]] = True\n",
2185
+ "# result[i, *slices] = arr\n",
2186
+ "\n",
2187
+ "# return result, mask\n",
2188
+ "\n",
2189
+ "\n",
2190
+ "\n",
2191
+ "import jax\n",
2192
+ "import jax.numpy as jnp\n",
2193
+ "from typing import List\n",
2194
+ "\n",
2195
+ "# TODO mv to pi0\n",
2196
+ "@jax.jit\n",
2197
+ "def stack_to_masked(arrays: List[jnp.ndarray]):\n",
2198
+ " \"\"\"\n",
2199
+ " TODO doc\n",
2200
+ " Converts a list of JAX arrays with unequal first dimensions into a masked array.\n",
2201
+ " \n",
2202
+ " Args:\n",
2203
+ " - arrays: List of JAX arrays (arrays of unequal first dimension).\n",
2204
+ " \n",
2205
+ " Returns:\n",
2206
+ " - result: Masked JAX array containing the stacked arrays.\n",
2207
+ " - mask: Mask indicating the valid elements in the result.\n",
2208
+ " \"\"\"\n",
2209
+ " # Determine first dimension shape\n",
2210
+ " first_shape = (len(arrays), max(array.shape[0] for array in arrays))\n",
2211
+ " \n",
2212
+ " # Extract the shape of the remaining dimensions\n",
2213
+ " rest_shapes = [array.shape[1:] for array in arrays]\n",
2214
+ " assert len(set(rest_shapes)) == 1, \"All arrays must have the same shape except for the first dimension.\"\n",
2215
+ " rest_shape = next(iter(rest_shapes))\n",
2216
+ " \n",
2217
+ " # Initialize the mask and the result array\n",
2218
+ " mask = jnp.full(first_shape, False, dtype=jnp.bool)\n",
2219
+ " result = jnp.empty((first_shape[0], first_shape[1], *rest_shape), dtype=jnp.result_type(*arrays))\n",
2220
+ "\n",
2221
+ " # Stack arrays and update the mask\n",
2222
+ " for i, array in enumerate(arrays):\n",
2223
+ " slices = tuple(slice(0, s) for s in array.shape)\n",
2224
+ " mask = mask.at[i, slices[0]].set(True) \n",
2225
+ " result = result.at[i, *slices].set(array) \n",
2226
+ "\n",
2227
+ " return result, mask\n",
2228
+ "\n"
2229
+ ]
2230
+ },
2231
+ {
2232
+ "cell_type": "code",
2233
+ "execution_count": 23,
2234
+ "id": "da8c238d",
2235
+ "metadata": {},
2236
+ "outputs": [],
2237
+ "source": [
2238
+ "sample_images = jax.device_put(sample[\"images\"], jax.devices()[0])"
2239
+ ]
2240
+ },
2241
+ {
2242
+ "cell_type": "code",
2243
+ "execution_count": 39,
2244
+ "id": "8845cd21",
2245
+ "metadata": {},
2246
+ "outputs": [
2247
+ {
2248
+ "name": "stdout",
2249
+ "output_type": "stream",
2250
+ "text": [
2251
+ "49 μs ± 134 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)\n"
2252
+ ]
2253
+ }
2254
+ ],
2255
+ "source": [
2256
+ "%%timeit\n",
2257
+ "res, mask = stack_to_masked(sample_images)\n"
2258
+ ]
2259
+ },
2260
+ {
2261
+ "cell_type": "code",
2262
+ "execution_count": 40,
2263
+ "id": "166385f4",
2264
+ "metadata": {},
2265
+ "outputs": [],
2266
+ "source": [
2267
+ "# with jax.profiler.trace(\"/tmp/jax-trace\"):\n",
2268
+ "# res, mask = stack_to_masked(sample[\"images\"])"
2269
+ ]
2270
+ },
2271
+ {
2272
+ "cell_type": "code",
2273
+ "execution_count": 43,
2274
+ "id": "fbee3f92",
2275
+ "metadata": {},
2276
+ "outputs": [
2277
+ {
2278
+ "name": "stdout",
2279
+ "output_type": "stream",
2280
+ "text": [
2281
+ "52.6 μs ± 612 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)\n"
2282
+ ]
2283
+ }
2284
+ ],
2285
+ "source": [
2286
+ "%%timeit\n",
2287
+ "jnp.empty(sample_images.shape)"
2288
+ ]
2289
+ },
2290
+ {
2291
+ "cell_type": "code",
2292
+ "execution_count": null,
2293
+ "id": "498665d4",
2294
+ "metadata": {},
2295
+ "outputs": [],
2296
+ "source": []
2297
+ },
2298
+ {
2299
+ "cell_type": "code",
2300
+ "execution_count": null,
2301
+ "id": "d60769ea",
2302
+ "metadata": {},
2303
+ "outputs": [],
2304
+ "source": []
2305
+ }
2306
+ ],
2307
+ "metadata": {
2308
+ "kernelspec": {
2309
+ "display_name": "Python 3",
2310
+ "language": "python",
2311
+ "name": "python3"
2312
+ },
2313
+ "language_info": {
2314
+ "codemirror_mode": {
2315
+ "name": "ipython",
2316
+ "version": 3
2317
+ },
2318
+ "file_extension": ".py",
2319
+ "mimetype": "text/x-python",
2320
+ "name": "python",
2321
+ "nbconvert_exporter": "python",
2322
+ "pygments_lexer": "ipython3",
2323
+ "version": "3.11.13"
2324
+ }
2325
+ },
2326
+ "nbformat": 4,
2327
+ "nbformat_minor": 5
2328
+ }
__todo__/todo-pi0.ipynb CHANGED
@@ -235,12 +235,13 @@
235
  "name": "stdout",
236
  "output_type": "stream",
237
  "text": [
 
238
  "env: XLA_PYTHON_CLIENT_PREALLOCATE=false\n"
239
  ]
240
  }
241
  ],
242
  "source": [
243
- "# %env JAX_PLATFORMS=cpu\n",
244
  "# %env JAX_DISABLE_JIT=1 \n",
245
  "# %env CUDA_VISIBLE_DEVICES=1\n",
246
  "%env XLA_PYTHON_CLIENT_PREALLOCATE=false"
@@ -248,7 +249,7 @@
248
  },
249
  {
250
  "cell_type": "code",
251
- "execution_count": 1,
252
  "id": "a3b16cfc",
253
  "metadata": {},
254
  "outputs": [
@@ -256,47 +257,132 @@
256
  "name": "stderr",
257
  "output_type": "stream",
258
  "text": [
259
- "2025-07-26 00:52:05.225396: W external/xla/xla/hlo/transforms/simplifiers/hlo_rematerialization.cc:3425] Can't reduce memory use below 7.66GiB (8226198857 bytes) by rematerialization; only reduced to 8.98GiB (9643192104 bytes), down from 9.18GiB (9861826868 bytes) originally\n"
260
  ]
261
  }
262
  ],
263
  "source": [
264
  "from robotodo.controllers.pi0.nn.pi0 import Pi0\n",
265
  "\n",
266
- "pi0 = Pi0(Pi0.Config(\n",
267
- " observation_spec=Pi0.ObservationSpec(\n",
268
- " image_names=[\"example\", \"another_example\"], \n",
269
- " image_size=(64, 64),\n",
270
- " text_max_len=48,\n",
271
- " # TODO\n",
272
- " text_vocab_size=1000,\n",
273
- " numeric_state_size=4,\n",
274
- " ),\n",
275
- " action_spec=Pi0.ActionSpec(\n",
276
- " numeric_state_size=4,\n",
277
- " numeric_state_horizon=2,\n",
278
- " )\n",
279
- "))"
 
 
 
280
  ]
281
  },
282
  {
283
  "cell_type": "code",
284
- "execution_count": 2,
285
- "id": "fa728f74",
286
  "metadata": {},
287
  "outputs": [
288
  {
289
  "data": {
290
  "text/plain": [
291
- "{'numeric_states': Array([[[ 2.4204671 , 1.2837857 , -0.6498379 , 0.12193705],\n",
292
- " [ 1.0678527 , -1.1816808 , -1.2071092 , -0.16615492]]], dtype=float32)}"
293
  ]
294
  },
295
- "execution_count": 2,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
296
  "metadata": {},
297
  "output_type": "execute_result"
298
  }
299
  ],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
300
  "source": [
301
  "import jax\n",
302
  "\n",
@@ -976,7 +1062,7 @@
976
  ],
977
  "metadata": {
978
  "kernelspec": {
979
- "display_name": "Python 3",
980
  "language": "python",
981
  "name": "python3"
982
  },
 
235
  "name": "stdout",
236
  "output_type": "stream",
237
  "text": [
238
+ "env: JAX_PLATFORMS=cpu\n",
239
  "env: XLA_PYTHON_CLIENT_PREALLOCATE=false\n"
240
  ]
241
  }
242
  ],
243
  "source": [
244
+ "%env JAX_PLATFORMS=cpu\n",
245
  "# %env JAX_DISABLE_JIT=1 \n",
246
  "# %env CUDA_VISIBLE_DEVICES=1\n",
247
  "%env XLA_PYTHON_CLIENT_PREALLOCATE=false"
 
249
  },
250
  {
251
  "cell_type": "code",
252
+ "execution_count": 2,
253
  "id": "a3b16cfc",
254
  "metadata": {},
255
  "outputs": [
 
257
  "name": "stderr",
258
  "output_type": "stream",
259
  "text": [
260
+ "2025-07-31 15:26:18.594486: W external/xla/xla/hlo/transforms/simplifiers/hlo_rematerialization.cc:3425] Can't reduce memory use below 7.66GiB (8226198857 bytes) by rematerialization; only reduced to 8.98GiB (9643192104 bytes), down from 9.18GiB (9861826868 bytes) originally\n"
261
  ]
262
  }
263
  ],
264
  "source": [
265
  "from robotodo.controllers.pi0.nn.pi0 import Pi0\n",
266
  "\n",
267
+ "# pi0 = Pi0(Pi0.Config(\n",
268
+ "# observation_spec=Pi0.ObservationSpec(\n",
269
+ "# image_names=[\"example\", \"another_example\"], \n",
270
+ "# image_size=(64, 64),\n",
271
+ "# text_max_len=48,\n",
272
+ "# # TODO\n",
273
+ "# text_vocab_size=1000,\n",
274
+ "# numeric_state_size=4,\n",
275
+ "# ),\n",
276
+ "# action_spec=Pi0.ActionSpec(\n",
277
+ "# numeric_state_size=4,\n",
278
+ "# numeric_state_horizon=2,\n",
279
+ "# )\n",
280
+ "# ))\n",
281
+ "import flax.nnx\n",
282
+ "\n",
283
+ "pi0 = Pi0(rngs=flax.nnx.Rngs(0))"
284
  ]
285
  },
286
  {
287
  "cell_type": "code",
288
+ "execution_count": 3,
289
+ "id": "8b0fc12c",
290
  "metadata": {},
291
  "outputs": [
292
  {
293
  "data": {
294
  "text/plain": [
295
+ "Dict('images': Box(-1.0, 1.0, (3, 224, 224, 3), float32), 'images.mask': Box(0, 1, (3,), uint8), 'numeric_state': Box(-inf, inf, (32,), float32), 'tokenized_text': Box(0, 257152, (48,), int32), 'tokenized_text.mask': Box(0, 1, (48,), uint8))"
 
296
  ]
297
  },
298
+ "execution_count": 3,
299
+ "metadata": {},
300
+ "output_type": "execute_result"
301
+ }
302
+ ],
303
+ "source": [
304
+ "pi0._config.observation_spec"
305
+ ]
306
+ },
307
+ {
308
+ "cell_type": "code",
309
+ "execution_count": 4,
310
+ "id": "c0818466",
311
+ "metadata": {},
312
+ "outputs": [
313
+ {
314
+ "data": {
315
+ "text/plain": [
316
+ "Dict('numeric_states': Box(-inf, inf, (50, 32), float32))"
317
+ ]
318
+ },
319
+ "execution_count": 4,
320
+ "metadata": {},
321
+ "output_type": "execute_result"
322
+ }
323
+ ],
324
+ "source": [
325
+ "pi0._config.action_spec"
326
+ ]
327
+ },
328
+ {
329
+ "cell_type": "code",
330
+ "execution_count": null,
331
+ "id": "4d629bcb",
332
+ "metadata": {},
333
+ "outputs": [],
334
+ "source": []
335
+ },
336
+ {
337
+ "cell_type": "code",
338
+ "execution_count": 3,
339
+ "id": "3ff74a60",
340
+ "metadata": {},
341
+ "outputs": [
342
+ {
343
+ "data": {
344
+ "text/plain": [
345
+ "(1, 3, 224, 224, 3)"
346
+ ]
347
+ },
348
+ "execution_count": 3,
349
  "metadata": {},
350
  "output_type": "execute_result"
351
  }
352
  ],
353
+ "source": [
354
+ "pi0._config.observation_spec.batched().sample()[\"images\"].shape"
355
+ ]
356
+ },
357
+ {
358
+ "cell_type": "code",
359
+ "execution_count": 5,
360
+ "id": "fa728f74",
361
+ "metadata": {},
362
+ "outputs": [
363
+ {
364
+ "ename": "XlaRuntimeError",
365
+ "evalue": "INTERNAL: the library was not initialized",
366
+ "output_type": "error",
367
+ "traceback": [
368
+ "\u001b[31m---------------------------------------------------------------------------\u001b[39m",
369
+ "\u001b[31mXlaRuntimeError\u001b[39m Traceback (most recent call last)",
370
+ "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[5]\u001b[39m\u001b[32m, line 3\u001b[39m\n\u001b[32m 1\u001b[39m \u001b[38;5;28;01mimport\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34;01mjax\u001b[39;00m\n\u001b[32m----> \u001b[39m\u001b[32m3\u001b[39m \u001b[43mpi0\u001b[49m\u001b[43m.\u001b[49m\u001b[43mcompute_loss\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m 4\u001b[39m \u001b[43m \u001b[49m\u001b[43mrng\u001b[49m\u001b[43m=\u001b[49m\u001b[43mjax\u001b[49m\u001b[43m.\u001b[49m\u001b[43mrandom\u001b[49m\u001b[43m.\u001b[49m\u001b[43mkey\u001b[49m\u001b[43m(\u001b[49m\u001b[32;43m0\u001b[39;49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 5\u001b[39m \u001b[43m \u001b[49m\u001b[43mbatch_observation\u001b[49m\u001b[43m=\u001b[49m\u001b[43mpi0\u001b[49m\u001b[43m.\u001b[49m\u001b[43m_config\u001b[49m\u001b[43m.\u001b[49m\u001b[43mobservation_spec\u001b[49m\u001b[43m.\u001b[49m\u001b[43mbatched\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[43m.\u001b[49m\u001b[43msample\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 6\u001b[39m \u001b[43m \u001b[49m\u001b[43mbatch_action\u001b[49m\u001b[43m=\u001b[49m\u001b[43mpi0\u001b[49m\u001b[43m.\u001b[49m\u001b[43m_config\u001b[49m\u001b[43m.\u001b[49m\u001b[43maction_spec\u001b[49m\u001b[43m.\u001b[49m\u001b[43mbatched\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[43m.\u001b[49m\u001b[43msample\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 7\u001b[39m \u001b[43m)\u001b[49m\n",
371
+ "\u001b[36mFile \u001b[39m\u001b[32m~/RoboTwin/packages/robotodo/controllers/pi0/nn/pi0.py:490\u001b[39m, in \u001b[36mPi0.compute_loss\u001b[39m\u001b[34m(self, rng, batch_observation, batch_action)\u001b[39m\n\u001b[32m 488\u001b[39m \u001b[38;5;66;03m# one big forward pass of prefix + suffix at once\u001b[39;00m\n\u001b[32m 489\u001b[39m prefix_tokens, prefix_mask, prefix_ar_mask = \u001b[38;5;28mself\u001b[39m._embed_prefix(batch_observation)\n\u001b[32m--> \u001b[39m\u001b[32m490\u001b[39m suffix_tokens, suffix_mask, suffix_ar_mask = \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43m_embed_suffix\u001b[49m\u001b[43m(\u001b[49m\u001b[43mbatch_observation\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43m{\u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mnumeric_states\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mx_t\u001b[49m\u001b[43m}\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mtime\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 491\u001b[39m input_mask = jnp.concatenate([prefix_mask, suffix_mask], axis=\u001b[32m1\u001b[39m)\n\u001b[32m 492\u001b[39m ar_mask = jnp.concatenate([prefix_ar_mask, suffix_ar_mask], axis=\u001b[32m0\u001b[39m)\n",
372
+ "\u001b[36mFile \u001b[39m\u001b[32m~/RoboTwin/packages/robotodo/controllers/pi0/nn/pi0.py:384\u001b[39m, in \u001b[36mPi0._embed_suffix\u001b[39m\u001b[34m(self, batch_observation, batch_noisy_action, timestep)\u001b[39m\n\u001b[32m 382\u001b[39m time_emb = posemb_sincos(timestep, \u001b[38;5;28mself\u001b[39m.action_in_proj.out_features, min_period=\u001b[32m4e-3\u001b[39m, max_period=\u001b[32m4.0\u001b[39m)\n\u001b[32m 383\u001b[39m \u001b[38;5;66;03m# mix timestep + action information using an MLP\u001b[39;00m\n\u001b[32m--> \u001b[39m\u001b[32m384\u001b[39m action_tokens = \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43maction_in_proj\u001b[49m\u001b[43m(\u001b[49m\u001b[43mbatch_noisy_action\u001b[49m\u001b[43m[\u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mnumeric_states\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m]\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 385\u001b[39m \u001b[38;5;66;03m# TODO !!!!\u001b[39;00m\n\u001b[32m 386\u001b[39m time_tokens = einops.repeat(time_emb, \u001b[33m\"\u001b[39m\u001b[33mb emb -> b s emb\u001b[39m\u001b[33m\"\u001b[39m, s=action_horizon)\n",
373
+ "\u001b[36mFile \u001b[39m\u001b[32m~/RoboTwin/.conda/lib/python3.11/site-packages/flax/nnx/nn/linear.py:387\u001b[39m, in \u001b[36mLinear.__call__\u001b[39m\u001b[34m(self, inputs)\u001b[39m\n\u001b[32m 382\u001b[39m bias = \u001b[38;5;28mself\u001b[39m.bias.value \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m.bias \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;28;01melse\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m\n\u001b[32m 384\u001b[39m inputs, kernel, bias = \u001b[38;5;28mself\u001b[39m.promote_dtype(\n\u001b[32m 385\u001b[39m (inputs, kernel, bias), dtype=\u001b[38;5;28mself\u001b[39m.dtype\n\u001b[32m 386\u001b[39m )\n\u001b[32m--> \u001b[39m\u001b[32m387\u001b[39m y = \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mdot_general\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m 388\u001b[39m \u001b[43m \u001b[49m\u001b[43minputs\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 389\u001b[39m \u001b[43m \u001b[49m\u001b[43mkernel\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 390\u001b[39m \u001b[43m \u001b[49m\u001b[43m(\u001b[49m\u001b[43m(\u001b[49m\u001b[43m(\u001b[49m\u001b[43minputs\u001b[49m\u001b[43m.\u001b[49m\u001b[43mndim\u001b[49m\u001b[43m \u001b[49m\u001b[43m-\u001b[49m\u001b[43m \u001b[49m\u001b[32;43m1\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43m(\u001b[49m\u001b[32;43m0\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m)\u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43m(\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[43m)\u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 391\u001b[39m \u001b[43m \u001b[49m\u001b[43mprecision\u001b[49m\u001b[43m=\u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mprecision\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 392\u001b[39m \u001b[43m\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 393\u001b[39m \u001b[38;5;28;01massert\u001b[39;00m \u001b[38;5;28mself\u001b[39m.use_bias == (bias \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m)\n\u001b[32m 394\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m bias \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n",
374
+ "\u001b[36mFile \u001b[39m\u001b[32m~/RoboTwin/.conda/lib/python3.11/site-packages/jax/_src/lax/lax.py:2523\u001b[39m, in \u001b[36mdot_general\u001b[39m\u001b[34m(lhs, rhs, dimension_numbers, precision, preferred_element_type, out_sharding)\u001b[39m\n\u001b[32m 2519\u001b[39m preferred_element_type = (\n\u001b[32m 2520\u001b[39m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;28;01mif\u001b[39;00m preferred_element_type \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;28;01melse\u001b[39;00m\n\u001b[32m 2521\u001b[39m dtypes.canonicalize_dtype(np.dtype(preferred_element_type)))\n\u001b[32m 2522\u001b[39m lhs, rhs = core.standard_insert_pvary(lhs, rhs)\n\u001b[32m-> \u001b[39m\u001b[32m2523\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mdot_general_p\u001b[49m\u001b[43m.\u001b[49m\u001b[43mbind\u001b[49m\u001b[43m(\u001b[49m\u001b[43mlhs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mrhs\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 2524\u001b[39m \u001b[43m \u001b[49m\u001b[43mdimension_numbers\u001b[49m\u001b[43m=\u001b[49m\u001b[43m(\u001b[49m\u001b[43mcdims\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mbdims\u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 2525\u001b[39m \u001b[43m \u001b[49m\u001b[43mprecision\u001b[49m\u001b[43m=\u001b[49m\u001b[43mcanonicalize_precision\u001b[49m\u001b[43m(\u001b[49m\u001b[43mprecision\u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 2526\u001b[39m \u001b[43m \u001b[49m\u001b[43mpreferred_element_type\u001b[49m\u001b[43m=\u001b[49m\u001b[43mpreferred_element_type\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 2527\u001b[39m \u001b[43m \u001b[49m\u001b[43mout_sharding\u001b[49m\u001b[43m=\u001b[49m\u001b[43mout_sharding\u001b[49m\u001b[43m)\u001b[49m\n",
375
+ "\u001b[36mFile \u001b[39m\u001b[32m~/RoboTwin/.conda/lib/python3.11/site-packages/jax/_src/core.py:576\u001b[39m, in \u001b[36mPrimitive.bind\u001b[39m\u001b[34m(self, *args, **params)\u001b[39m\n\u001b[32m 574\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34mbind\u001b[39m(\u001b[38;5;28mself\u001b[39m, *args, **params):\n\u001b[32m 575\u001b[39m args = args \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m.skip_canonicalization \u001b[38;5;28;01melse\u001b[39;00m \u001b[38;5;28mmap\u001b[39m(canonicalize_value, args)\n\u001b[32m--> \u001b[39m\u001b[32m576\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43m_true_bind\u001b[49m\u001b[43m(\u001b[49m\u001b[43m*\u001b[49m\u001b[43margs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43m*\u001b[49m\u001b[43m*\u001b[49m\u001b[43mparams\u001b[49m\u001b[43m)\u001b[49m\n",
376
+ "\u001b[36mFile \u001b[39m\u001b[32m~/RoboTwin/.conda/lib/python3.11/site-packages/jax/_src/core.py:592\u001b[39m, in \u001b[36mPrimitive._true_bind\u001b[39m\u001b[34m(self, *args, **params)\u001b[39m\n\u001b[32m 590\u001b[39m trace_ctx.set_trace(eval_trace)\n\u001b[32m 591\u001b[39m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[32m--> \u001b[39m\u001b[32m592\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mbind_with_trace\u001b[49m\u001b[43m(\u001b[49m\u001b[43mprev_trace\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43margs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mparams\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 593\u001b[39m \u001b[38;5;28;01mfinally\u001b[39;00m:\n\u001b[32m 594\u001b[39m trace_ctx.set_trace(prev_trace)\n",
377
+ "\u001b[36mFile \u001b[39m\u001b[32m~/RoboTwin/.conda/lib/python3.11/site-packages/jax/_src/core.py:602\u001b[39m, in \u001b[36mPrimitive.bind_with_trace\u001b[39m\u001b[34m(self, trace, args, params)\u001b[39m\n\u001b[32m 599\u001b[39m \u001b[38;5;28;01mwith\u001b[39;00m set_current_trace(trace):\n\u001b[32m 600\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m.to_lojax(*args, **params) \u001b[38;5;66;03m# type: ignore\u001b[39;00m\n\u001b[32m--> \u001b[39m\u001b[32m602\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mtrace\u001b[49m\u001b[43m.\u001b[49m\u001b[43mprocess_primitive\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43margs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mparams\u001b[49m\u001b[43m)\u001b[49m\n",
378
+ "\u001b[36mFile \u001b[39m\u001b[32m~/RoboTwin/.conda/lib/python3.11/site-packages/jax/_src/core.py:1126\u001b[39m, in \u001b[36mEvalTrace.process_primitive\u001b[39m\u001b[34m(self, primitive, args, params)\u001b[39m\n\u001b[32m 1124\u001b[39m args = \u001b[38;5;28mmap\u001b[39m(full_lower, args)\n\u001b[32m 1125\u001b[39m check_eval_args(args)\n\u001b[32m-> \u001b[39m\u001b[32m1126\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mprimitive\u001b[49m\u001b[43m.\u001b[49m\u001b[43mimpl\u001b[49m\u001b[43m(\u001b[49m\u001b[43m*\u001b[49m\u001b[43margs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43m*\u001b[49m\u001b[43m*\u001b[49m\u001b[43mparams\u001b[49m\u001b[43m)\u001b[49m\n",
379
+ "\u001b[36mFile \u001b[39m\u001b[32m~/RoboTwin/.conda/lib/python3.11/site-packages/jax/_src/dispatch.py:91\u001b[39m, in \u001b[36mapply_primitive\u001b[39m\u001b[34m(prim, *args, **params)\u001b[39m\n\u001b[32m 89\u001b[39m prev = lib.jax_jit.swap_thread_local_state_disable_jit(\u001b[38;5;28;01mFalse\u001b[39;00m)\n\u001b[32m 90\u001b[39m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[32m---> \u001b[39m\u001b[32m91\u001b[39m outs = \u001b[43mfun\u001b[49m\u001b[43m(\u001b[49m\u001b[43m*\u001b[49m\u001b[43margs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 92\u001b[39m \u001b[38;5;28;01mfinally\u001b[39;00m:\n\u001b[32m 93\u001b[39m lib.jax_jit.swap_thread_local_state_disable_jit(prev)\n",
380
+ " \u001b[31m[... skipping hidden 11 frame]\u001b[39m\n",
381
+ "\u001b[36mFile \u001b[39m\u001b[32m~/RoboTwin/.conda/lib/python3.11/site-packages/jax/_src/compiler.py:377\u001b[39m, in \u001b[36mbackend_compile_and_load\u001b[39m\u001b[34m(backend, module, executable_devices, options, host_callbacks)\u001b[39m\n\u001b[32m 368\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m backend.compile_and_load(\n\u001b[32m 369\u001b[39m built_c,\n\u001b[32m 370\u001b[39m executable_devices=executable_devices,\n\u001b[32m 371\u001b[39m compile_options=options,\n\u001b[32m 372\u001b[39m host_callbacks=host_callbacks,\n\u001b[32m 373\u001b[39m )\n\u001b[32m 374\u001b[39m \u001b[38;5;66;03m# Some backends don't have `host_callbacks` option yet\u001b[39;00m\n\u001b[32m 375\u001b[39m \u001b[38;5;66;03m# TODO(sharadmv): remove this fallback when all backends allow `compile`\u001b[39;00m\n\u001b[32m 376\u001b[39m \u001b[38;5;66;03m# to take in `host_callbacks`\u001b[39;00m\n\u001b[32m--> \u001b[39m\u001b[32m377\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mbackend\u001b[49m\u001b[43m.\u001b[49m\u001b[43mcompile_and_load\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m 378\u001b[39m \u001b[43m \u001b[49m\u001b[43mbuilt_c\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 379\u001b[39m \u001b[43m \u001b[49m\u001b[43mexecutable_devices\u001b[49m\u001b[43m=\u001b[49m\u001b[43mexecutable_devices\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 380\u001b[39m \u001b[43m \u001b[49m\u001b[43mcompile_options\u001b[49m\u001b[43m=\u001b[49m\u001b[43moptions\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 381\u001b[39m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 382\u001b[39m \u001b[38;5;28;01mexcept\u001b[39;00m xc.XlaRuntimeError \u001b[38;5;28;01mas\u001b[39;00m e:\n\u001b[32m 383\u001b[39m \u001b[38;5;28;01mfor\u001b[39;00m error_handler \u001b[38;5;129;01min\u001b[39;00m _XLA_RUNTIME_ERROR_HANDLERS:\n",
382
+ "\u001b[31mXlaRuntimeError\u001b[39m: INTERNAL: the library was not initialized"
383
+ ]
384
+ }
385
+ ],
386
  "source": [
387
  "import jax\n",
388
  "\n",
 
1062
  ],
1063
  "metadata": {
1064
  "kernelspec": {
1065
+ "display_name": ".conda",
1066
  "language": "python",
1067
  "name": "python3"
1068
  },
__todo__/todo-pi0controller.ipynb ADDED
@@ -0,0 +1,1394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "78d84ad4",
7
+ "metadata": {},
8
+ "outputs": [
9
+ {
10
+ "data": {
11
+ "text/plain": [
12
+ "Dict('images': Dict('another_camera': Box(0, 255, (1, 64, 128, 3), int64), 'some_camera': Box(0, 255, (1, 64, 64, 3), int64)), 'joint_state': Dict('todo': Box(-inf, inf, (1,), float32), 'todo2': Box(-inf, inf, (1,), float32)), 'text': Tuple(Text(1, 48, charset=0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz)))"
13
+ ]
14
+ },
15
+ "execution_count": 1,
16
+ "metadata": {},
17
+ "output_type": "execute_result"
18
+ }
19
+ ],
20
+ "source": [
21
+ "from robotodo.controllers.pi0 import Pi0Controller\n",
22
+ "from robotodo.controllers.pi0.nn.pi0 import Pi0\n",
23
+ "\n",
24
+ "\n",
25
+ "import gymnasium.spaces\n",
26
+ "\n",
27
+ "Pi0Controller.ObservationSpec(\n",
28
+ " images=gymnasium.spaces.Dict({\n",
29
+ " \"some_camera\": gymnasium.spaces.Box(\n",
30
+ " low=0, high=255, shape=(64, 64, 3),\n",
31
+ " dtype=int,\n",
32
+ " ),\n",
33
+ " \"another_camera\": gymnasium.spaces.Box(\n",
34
+ " low=0, high=255, shape=(64, 128, 3),\n",
35
+ " dtype=int,\n",
36
+ " ),\n",
37
+ " }),\n",
38
+ ").batched()\n"
39
+ ]
40
+ },
41
+ {
42
+ "cell_type": "code",
43
+ "execution_count": 2,
44
+ "id": "23b35bea",
45
+ "metadata": {},
46
+ "outputs": [],
47
+ "source": [
48
+ "import jax\n",
49
+ "\n",
50
+ "from robotodo.controllers.pi0 import Pi0Controller\n",
51
+ "from robotodo.controllers.pi0.nn.pi0 import Pi0\n",
52
+ "\n",
53
+ "# TODO match params\n",
54
+ "nn_observation_spec = Pi0.ObservationSpec()\n",
55
+ "controller_observation_spec = Pi0Controller.ObservationSpec()"
56
+ ]
57
+ },
58
+ {
59
+ "cell_type": "code",
60
+ "execution_count": 3,
61
+ "id": "2c8538ab",
62
+ "metadata": {},
63
+ "outputs": [],
64
+ "source": [
65
+ "batch_size = 10\n",
66
+ "\n",
67
+ "controller_observation = controller_observation_spec.batched(batch_size).sample()\n",
68
+ "nn_observation = Pi0Controller._encode_observation(\n",
69
+ " target_spec=nn_observation_spec,\n",
70
+ " source_spec=controller_observation_spec,\n",
71
+ " batch=controller_observation,\n",
72
+ " image_transform=lambda x, target_shape: jax.numpy.full((x.shape[0], *target_shape), 0.),\n",
73
+ " text_tokenizer=lambda texts, max_len: (jax.numpy.full((len(texts), max_len), 0.), jax.numpy.full((len(texts), max_len), False))\n",
74
+ ")"
75
+ ]
76
+ },
77
+ {
78
+ "cell_type": "code",
79
+ "execution_count": 4,
80
+ "id": "47353fab",
81
+ "metadata": {},
82
+ "outputs": [
83
+ {
84
+ "data": {
85
+ "text/plain": [
86
+ "(10, 3, 224, 224, 3)"
87
+ ]
88
+ },
89
+ "execution_count": 4,
90
+ "metadata": {},
91
+ "output_type": "execute_result"
92
+ }
93
+ ],
94
+ "source": [
95
+ "nn_observation[\"images\"].shape"
96
+ ]
97
+ },
98
+ {
99
+ "cell_type": "code",
100
+ "execution_count": 5,
101
+ "id": "82c1428d",
102
+ "metadata": {},
103
+ "outputs": [],
104
+ "source": [
105
+ "# nn_action_spec = Pi0.ActionSpec(numeric_state_horizon=4) #.batched()\n",
106
+ "# controller_action_spec = Pi0Controller.ActionSpec() #.batched()\n",
107
+ "\n",
108
+ "# true_action = controller_action_spec.sample()\n",
109
+ "\n",
110
+ "# decoded_action = Pi0Controller._decode_action(\n",
111
+ "# target_spec=controller_action_spec,\n",
112
+ "# source_spec=nn_action_spec,\n",
113
+ "# maybe_batch=Pi0Controller._encode_action(\n",
114
+ "# target_spec=nn_action_spec,\n",
115
+ "# source_spec=controller_action_spec,\n",
116
+ "# maybe_batch=true_action,\n",
117
+ "# ),\n",
118
+ "# )\n",
119
+ "\n",
120
+ "# # TODO !!!!!!\n",
121
+ "# assert decoded_action == true_action, \"Decoded action does not match the original action.\"\n",
122
+ "# # decoded_action"
123
+ ]
124
+ },
125
+ {
126
+ "cell_type": "code",
127
+ "execution_count": 6,
128
+ "id": "79db5b02",
129
+ "metadata": {},
130
+ "outputs": [
131
+ {
132
+ "ename": "TypeError",
133
+ "evalue": "Pi0Controller._encode_action() got an unexpected keyword argument 'maybe_batch'",
134
+ "output_type": "error",
135
+ "traceback": [
136
+ "\u001b[31m---------------------------------------------------------------------------\u001b[39m",
137
+ "\u001b[31mTypeError\u001b[39m Traceback (most recent call last)",
138
+ "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[6]\u001b[39m\u001b[32m, line 11\u001b[39m\n\u001b[32m 3\u001b[39m true_action = controller_action_spec.sample()\n\u001b[32m 5\u001b[39m nn_action_spec = Pi0.ActionSpec(numeric_state_horizon=\u001b[38;5;28mlen\u001b[39m(true_action[\u001b[33m\"\u001b[39m\u001b[33mjoint_states\u001b[39m\u001b[33m\"\u001b[39m]))\n\u001b[32m 8\u001b[39m decoded_action = Pi0Controller._decode_action(\n\u001b[32m 9\u001b[39m target_spec=controller_action_spec,\n\u001b[32m 10\u001b[39m source_spec=nn_action_spec,\n\u001b[32m---> \u001b[39m\u001b[32m11\u001b[39m maybe_batch=\u001b[43mPi0Controller\u001b[49m\u001b[43m.\u001b[49m\u001b[43m_encode_action\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m 12\u001b[39m \u001b[43m \u001b[49m\u001b[43mtarget_spec\u001b[49m\u001b[43m=\u001b[49m\u001b[43mnn_action_spec\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 13\u001b[39m \u001b[43m \u001b[49m\u001b[43msource_spec\u001b[49m\u001b[43m=\u001b[49m\u001b[43mcontroller_action_spec\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 14\u001b[39m \u001b[43m \u001b[49m\u001b[43mmaybe_batch\u001b[49m\u001b[43m=\u001b[49m\u001b[43mtrue_action\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 15\u001b[39m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m,\n\u001b[32m 16\u001b[39m )\n\u001b[32m 18\u001b[39m \u001b[38;5;66;03m# TODO !!!!!!\u001b[39;00m\n\u001b[32m 19\u001b[39m \u001b[38;5;28;01massert\u001b[39;00m decoded_action == true_action, \u001b[33m\"\u001b[39m\u001b[33mDecoded action does not match the original action.\u001b[39m\u001b[33m\"\u001b[39m\n",
139
+ "\u001b[31mTypeError\u001b[39m: Pi0Controller._encode_action() got an unexpected keyword argument 'maybe_batch'"
140
+ ]
141
+ }
142
+ ],
143
+ "source": [
144
+ "controller_action_spec = Pi0Controller.ActionSpec()\n",
145
+ "\n",
146
+ "true_action = controller_action_spec.sample()\n",
147
+ "\n",
148
+ "nn_action_spec = Pi0.ActionSpec(numeric_state_horizon=len(true_action[\"joint_states\"]))\n",
149
+ "\n",
150
+ "\n",
151
+ "decoded_action = Pi0Controller._decode_action(\n",
152
+ " target_spec=controller_action_spec,\n",
153
+ " source_spec=nn_action_spec,\n",
154
+ " maybe_batch=Pi0Controller._encode_action(\n",
155
+ " target_spec=nn_action_spec,\n",
156
+ " source_spec=controller_action_spec,\n",
157
+ " maybe_batch=true_action,\n",
158
+ " ),\n",
159
+ ")\n",
160
+ "\n",
161
+ "# TODO !!!!!!\n",
162
+ "assert decoded_action == true_action, \"Decoded action does not match the original action.\"\n",
163
+ "# decoded_action"
164
+ ]
165
+ },
166
+ {
167
+ "cell_type": "code",
168
+ "execution_count": null,
169
+ "id": "0aac4037",
170
+ "metadata": {},
171
+ "outputs": [
172
+ {
173
+ "data": {
174
+ "text/plain": [
175
+ "({'todo': array(-0.2099437, dtype=float32),\n",
176
+ " 'todo2': array(-0.7873387, dtype=float32)},\n",
177
+ " {'todo': array(0.8495735, dtype=float32),\n",
178
+ " 'todo2': array(-0.0784022, dtype=float32)})"
179
+ ]
180
+ },
181
+ "execution_count": 7,
182
+ "metadata": {},
183
+ "output_type": "execute_result"
184
+ }
185
+ ],
186
+ "source": [
187
+ "true_action[\"joint_states\"]"
188
+ ]
189
+ },
190
+ {
191
+ "cell_type": "code",
192
+ "execution_count": null,
193
+ "id": "d0118905",
194
+ "metadata": {},
195
+ "outputs": [
196
+ {
197
+ "ename": "AttributeError",
198
+ "evalue": "'Sequence' object has no attribute 'spaces'",
199
+ "output_type": "error",
200
+ "traceback": [
201
+ "\u001b[31m---------------------------------------------------------------------------\u001b[39m",
202
+ "\u001b[31mAttributeError\u001b[39m Traceback (most recent call last)",
203
+ "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[8]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m \u001b[43m(\u001b[49m\u001b[43mcontroller_action_spec\u001b[49m\u001b[43m[\u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mjoint_states\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m]\u001b[49m\u001b[43m)\u001b[49m\u001b[43m.\u001b[49m\u001b[43mspaces\u001b[49m[\u001b[32m0\u001b[39m].feature_space\n",
204
+ "\u001b[31mAttributeError\u001b[39m: 'Sequence' object has no attribute 'spaces'"
205
+ ]
206
+ }
207
+ ],
208
+ "source": [
209
+ "(controller_action_spec[\"joint_states\"]).spaces[0].feature_space"
210
+ ]
211
+ },
212
+ {
213
+ "cell_type": "code",
214
+ "execution_count": null,
215
+ "id": "b8cef4e8",
216
+ "metadata": {},
217
+ "outputs": [],
218
+ "source": []
219
+ },
220
+ {
221
+ "cell_type": "code",
222
+ "execution_count": null,
223
+ "id": "2833013c",
224
+ "metadata": {},
225
+ "outputs": [],
226
+ "source": [
227
+ "def _todo_get_shapes(space: gymnasium.spaces.Space):\n",
228
+ " def _collapse(sizes):\n",
229
+ " unique_sizes = set(sizes)\n",
230
+ " return unique_sizes.pop() if len(unique_sizes) == 1 else tuple(sizes)\n",
231
+ "\n",
232
+ " if isinstance(space, gymnasium.spaces.Sequence):\n",
233
+ " return (\"variable\", *_todo_get_shapes(space.feature_space), )\n",
234
+ " if isinstance(space, gymnasium.spaces.Tuple):\n",
235
+ " return (\"any\", _collapse((_todo_get_shapes(s) for s in space.spaces)), )\n",
236
+ " if isinstance(space, gymnasium.spaces.Box):\n",
237
+ " return space.shape\n",
238
+ " # if isinstance(space, gymnasium.spaces.Dict):\n",
239
+ " # return space.spaces.values()\n",
240
+ " return (None, )\n",
241
+ " raise NotImplementedError\n",
242
+ "\n"
243
+ ]
244
+ },
245
+ {
246
+ "cell_type": "code",
247
+ "execution_count": null,
248
+ "id": "bd1516e2",
249
+ "metadata": {},
250
+ "outputs": [],
251
+ "source": [
252
+ "todo_spec = gymnasium.spaces.Dict({\n",
253
+ " \"joint_states\": gymnasium.spaces.Sequence(\n",
254
+ " gymnasium.spaces.Dict({\n",
255
+ " \"time\": gymnasium.spaces.Box(low=0, high=1, shape=(), dtype=float),\n",
256
+ " \"joint_index\": gymnasium.spaces.Discrete(10),\n",
257
+ " \"joint_position\": gymnasium.spaces.Box(low=-1, high=1, shape=(3,), dtype=float),\n",
258
+ " \"joint_velocity\": gymnasium.spaces.Box(low=-1, high=1, shape=(3,), dtype=float),\n",
259
+ " }),\n",
260
+ " ),\n",
261
+ " \"images\": gymnasium.spaces.Dict({\n",
262
+ " \"camera_1\": gymnasium.spaces.Box(low=0, high=255, shape=(64, 64, 3), dtype=int),\n",
263
+ " \"camera_2\": gymnasium.spaces.Box(low=0, high=255, shape=(128, 128, 3), dtype=int),\n",
264
+ " }),\n",
265
+ "})"
266
+ ]
267
+ },
268
+ {
269
+ "cell_type": "code",
270
+ "execution_count": null,
271
+ "id": "8aa5b54f",
272
+ "metadata": {},
273
+ "outputs": [
274
+ {
275
+ "data": {
276
+ "text/plain": [
277
+ "('any', ('variable', 2))"
278
+ ]
279
+ },
280
+ "execution_count": 47,
281
+ "metadata": {},
282
+ "output_type": "execute_result"
283
+ }
284
+ ],
285
+ "source": [
286
+ "from gymnasium.spaces.utils import flatten_space\n",
287
+ "\n",
288
+ "_todo_get_shapes(\n",
289
+ " flatten_space(controller_action_spec.batched(12))[\"joint_states\"])"
290
+ ]
291
+ },
292
+ {
293
+ "cell_type": "code",
294
+ "execution_count": null,
295
+ "id": "8fd7bec7",
296
+ "metadata": {},
297
+ "outputs": [
298
+ {
299
+ "data": {
300
+ "text/plain": [
301
+ "((array([0.85607225, 0.72125006], dtype=float32),\n",
302
+ " array([-0.70082533, -0.69842404], dtype=float32),\n",
303
+ " array([-0.01163369, -1.4920965 ], dtype=float32),\n",
304
+ " array([-0.06599382, 0.26672447], dtype=float32),\n",
305
+ " array([ 0.8558541 , -0.78532594], dtype=float32),\n",
306
+ " array([-0.6572756 , 0.08941177], dtype=float32),\n",
307
+ " array([-0.03469807, -2.0117505 ], dtype=float32),\n",
308
+ " array([ 0.74335843, -1.381109 ], dtype=float32),\n",
309
+ " array([-0.26126713, -1.0044067 ], dtype=float32),\n",
310
+ " array([0.60616934, 1.0154957 ], dtype=float32)),\n",
311
+ " (array([ 0.16813388, -0.49250507], dtype=float32),\n",
312
+ " array([-0.2689605, -0.1500428], dtype=float32)),\n",
313
+ " (array([1.0107105 , 0.20680448], dtype=float32),\n",
314
+ " array([-0.41026923, 0.30793977], dtype=float32),\n",
315
+ " array([-0.08843809, -0.08304607], dtype=float32),\n",
316
+ " array([0.44297883, 0.34052294], dtype=float32),\n",
317
+ " array([-0.7012652 , 0.96701336], dtype=float32),\n",
318
+ " array([0.04022446, 0.2014813 ], dtype=float32),\n",
319
+ " array([-0.7302966, -0.8917434], dtype=float32),\n",
320
+ " array([-1.4457557 , -0.38217607], dtype=float32),\n",
321
+ " array([-0.15775612, 0.60783684], dtype=float32),\n",
322
+ " array([-0.28369823, 0.2105117 ], dtype=float32),\n",
323
+ " array([-0.15830924, -0.7770295 ], dtype=float32),\n",
324
+ " array([ 0.85901105, -1.1952757 ], dtype=float32)),\n",
325
+ " (array([-1.4374448 , -0.07747232], dtype=float32),\n",
326
+ " array([ 1.0000523 , -0.39073467], dtype=float32)),\n",
327
+ " (array([-0.11799106, -1.1824393 ], dtype=float32),),\n",
328
+ " (array([-0.17305812, -0.17309916], dtype=float32),\n",
329
+ " array([-0.93062973, 0.1089174 ], dtype=float32)),\n",
330
+ " (array([-1.0932742, 0.1428427], dtype=float32),),\n",
331
+ " (array([ 0.27324578, -1.1939694 ], dtype=float32),),\n",
332
+ " (array([-1.8608497, -0.4194057], dtype=float32),\n",
333
+ " array([-1.2735873 , 0.69892734], dtype=float32),\n",
334
+ " array([ 0.7560703 , -0.11460541], dtype=float32),\n",
335
+ " array([-0.7790617, -0.5934243], dtype=float32),\n",
336
+ " array([-0.02360659, -0.35273558], dtype=float32),\n",
337
+ " array([0.4311765 , 0.04507197], dtype=float32),\n",
338
+ " array([-0.70334196, -0.1100123 ], dtype=float32),\n",
339
+ " array([-1.0433946, 0.5627225], dtype=float32),\n",
340
+ " array([0.32563594, 1.155541 ], dtype=float32)),\n",
341
+ " (array([ 1.2635654, -1.1647648], dtype=float32),),\n",
342
+ " (array([-0.551036, -2.061472], dtype=float32),\n",
343
+ " array([-0.15095699, -0.45311156], dtype=float32)),\n",
344
+ " (array([-0.52052385, -2.4870036 ], dtype=float32),\n",
345
+ " array([ 0.59720516, -0.70111895], dtype=float32),\n",
346
+ " array([ 0.06827085, -0.43836373], dtype=float32)))"
347
+ ]
348
+ },
349
+ "execution_count": 21,
350
+ "metadata": {},
351
+ "output_type": "execute_result"
352
+ }
353
+ ],
354
+ "source": [
355
+ "flatten_space(controller_action_spec.batched(12))[\"joint_states\"].sample()"
356
+ ]
357
+ },
358
+ {
359
+ "cell_type": "code",
360
+ "execution_count": null,
361
+ "id": "93daadd6",
362
+ "metadata": {},
363
+ "outputs": [],
364
+ "source": []
365
+ },
366
+ {
367
+ "cell_type": "code",
368
+ "execution_count": null,
369
+ "id": "2996ba0b",
370
+ "metadata": {},
371
+ "outputs": [
372
+ {
373
+ "data": {
374
+ "text/plain": [
375
+ "(array([ 0.51813537, -0.40174687], dtype=float32),\n",
376
+ " array([-0.20135991, -0.997153 ], dtype=float32),\n",
377
+ " array([-0.14955288, 1.5498478 ], dtype=float32),\n",
378
+ " array([-0.63566685, 1.3893775 ], dtype=float32),\n",
379
+ " array([ 0.54045063, -0.39440677], dtype=float32),\n",
380
+ " array([-0.70493084, 1.5659952 ], dtype=float32),\n",
381
+ " array([-0.56468016, -0.35411438], dtype=float32),\n",
382
+ " array([-0.37112427, -0.3278518 ], dtype=float32),\n",
383
+ " array([-1.5715653, -0.6040235], dtype=float32),\n",
384
+ " array([-0.01465762, -0.07865378], dtype=float32),\n",
385
+ " array([-0.7902249 , 0.31941113], dtype=float32),\n",
386
+ " array([0.69585234, 0.80401933], dtype=float32),\n",
387
+ " array([-1.0972252, -0.6560456], dtype=float32),\n",
388
+ " array([0.37363115, 1.9545896 ], dtype=float32))"
389
+ ]
390
+ },
391
+ "execution_count": 16,
392
+ "metadata": {},
393
+ "output_type": "execute_result"
394
+ }
395
+ ],
396
+ "source": [
397
+ "flatten_space(controller_action_spec)[\"joint_states\"].sample()"
398
+ ]
399
+ },
400
+ {
401
+ "cell_type": "code",
402
+ "execution_count": null,
403
+ "id": "809e6578",
404
+ "metadata": {},
405
+ "outputs": [
406
+ {
407
+ "ename": "AttributeError",
408
+ "evalue": "'Tuple' object has no attribute 'feature_space'",
409
+ "output_type": "error",
410
+ "traceback": [
411
+ "\u001b[31m---------------------------------------------------------------------------\u001b[39m",
412
+ "\u001b[31mAttributeError\u001b[39m Traceback (most recent call last)",
413
+ "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[7]\u001b[39m\u001b[32m, line 8\u001b[39m\n\u001b[32m 3\u001b[39m true_action = controller_action_spec.sample()\n\u001b[32m 5\u001b[39m nn_action_spec = Pi0.ActionSpec(numeric_state_horizon=\u001b[38;5;28mlen\u001b[39m(true_action[\u001b[33m\"\u001b[39m\u001b[33mjoint_states\u001b[39m\u001b[33m\"\u001b[39m][\u001b[32m0\u001b[39m])).batched()\n\u001b[32m----> \u001b[39m\u001b[32m8\u001b[39m decoded_action = \u001b[43mPi0Controller\u001b[49m\u001b[43m.\u001b[49m\u001b[43m_decode_action\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m 9\u001b[39m \u001b[43m \u001b[49m\u001b[43mtarget_spec\u001b[49m\u001b[43m=\u001b[49m\u001b[43mcontroller_action_spec\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 10\u001b[39m \u001b[43m \u001b[49m\u001b[43msource_spec\u001b[49m\u001b[43m=\u001b[49m\u001b[43mnn_action_spec\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 11\u001b[39m \u001b[43m \u001b[49m\u001b[43mmaybe_batch\u001b[49m\u001b[43m=\u001b[49m\u001b[43mPi0Controller\u001b[49m\u001b[43m.\u001b[49m\u001b[43m_encode_action\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m 12\u001b[39m \u001b[43m \u001b[49m\u001b[43mtarget_spec\u001b[49m\u001b[43m=\u001b[49m\u001b[43mnn_action_spec\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 13\u001b[39m \u001b[43m \u001b[49m\u001b[43msource_spec\u001b[49m\u001b[43m=\u001b[49m\u001b[43mcontroller_action_spec\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 14\u001b[39m \u001b[43m \u001b[49m\u001b[43mmaybe_batch\u001b[49m\u001b[43m=\u001b[49m\u001b[43mtrue_action\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 15\u001b[39m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 16\u001b[39m \u001b[43m)\u001b[49m\n\u001b[32m 18\u001b[39m \u001b[38;5;66;03m# # TODO !!!!!!\u001b[39;00m\n\u001b[32m 19\u001b[39m \u001b[38;5;66;03m# assert decoded_action == true_action, \"Decoded action does not match the original action.\"\u001b[39;00m\n\u001b[32m 20\u001b[39m \u001b[38;5;66;03m# # decoded_action\u001b[39;00m\n",
414
+ "\u001b[36mFile \u001b[39m\u001b[32m~/RoboTwin/packages/robotodo/controllers/pi0/pi0_controller.py:328\u001b[39m, in \u001b[36mPi0Controller._decode_action\u001b[39m\u001b[34m(target_spec, source_spec, maybe_batch)\u001b[39m\n\u001b[32m 307\u001b[39m \u001b[38;5;129m@staticmethod\u001b[39m\n\u001b[32m 308\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34m_decode_action\u001b[39m(\n\u001b[32m 309\u001b[39m target_spec: \u001b[33m\"\u001b[39m\u001b[33mPi0Controller.ActionSpec | Pi0Controller.ActionSpec.batched\u001b[39m\u001b[33m\"\u001b[39m,\n\u001b[32m (...)\u001b[39m\u001b[32m 312\u001b[39m ):\n\u001b[32m 313\u001b[39m \u001b[38;5;66;03m# TODO\u001b[39;00m\n\u001b[32m 314\u001b[39m \u001b[38;5;250m \u001b[39m\u001b[33;03m\"\"\"\u001b[39;00m\n\u001b[32m 315\u001b[39m \u001b[33;03m TODO\u001b[39;00m\n\u001b[32m 316\u001b[39m \n\u001b[32m 317\u001b[39m \n\u001b[32m 318\u001b[39m \u001b[33;03m \"\"\"\u001b[39;00m\n\u001b[32m 320\u001b[39m joint_states = (\n\u001b[32m 321\u001b[39m jax.numpy.asarray(maybe_batch[\u001b[33m\"\u001b[39m\u001b[33mnumeric_states\u001b[39m\u001b[33m\"\u001b[39m])\n\u001b[32m 322\u001b[39m \u001b[38;5;66;03m# TODO \u001b[39;00m\n\u001b[32m 323\u001b[39m .at[(..., ) + \u001b[38;5;28mtuple\u001b[39m(\n\u001b[32m 324\u001b[39m \u001b[38;5;28mslice\u001b[39m(\u001b[32m0\u001b[39m, s) \n\u001b[32m 325\u001b[39m \u001b[38;5;66;03m# TODO instead: target_spec[\"joint_states\"].flatten() \u001b[39;00m\n\u001b[32m 326\u001b[39m \u001b[38;5;66;03m# TODO target_spec[\"joint_states\"].batch()\u001b[39;00m\n\u001b[32m 327\u001b[39m \u001b[38;5;28;01mfor\u001b[39;00m s \u001b[38;5;129;01min\u001b[39;00m gymnasium.spaces.utils.flatten_space(\n\u001b[32m--> \u001b[39m\u001b[32m328\u001b[39m \u001b[43mtarget_spec\u001b[49m\u001b[43m[\u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mjoint_states\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m]\u001b[49m\u001b[43m.\u001b[49m\u001b[43mfeature_space\u001b[49m,\n\u001b[32m 329\u001b[39m ).shape \u001b[38;5;66;03m#[-1]\u001b[39;00m\n\u001b[32m 330\u001b[39m )]\n\u001b[32m 331\u001b[39m .get()\n\u001b[32m 332\u001b[39m )\n\u001b[32m 333\u001b[39m joint_states = gymnasium.spaces.utils.unflatten(\n\u001b[32m 334\u001b[39m target_spec[\u001b[33m\"\u001b[39m\u001b[33mjoint_states\u001b[39m\u001b[33m\"\u001b[39m],\n\u001b[32m 335\u001b[39m joint_states,\n\u001b[32m 336\u001b[39m )\n\u001b[32m 338\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m {\n\u001b[32m 339\u001b[39m \u001b[33m\"\u001b[39m\u001b[33mjoint_states\u001b[39m\u001b[33m\"\u001b[39m: joint_states,\n\u001b[32m 340\u001b[39m }\n",
415
+ "\u001b[31mAttributeError\u001b[39m: 'Tuple' object has no attribute 'feature_space'"
416
+ ]
417
+ }
418
+ ],
419
+ "source": [
420
+ "controller_action_spec = Pi0Controller.ActionSpec().batched()\n",
421
+ "\n",
422
+ "true_action = controller_action_spec.sample()\n",
423
+ "\n",
424
+ "nn_action_spec = Pi0.ActionSpec(numeric_state_horizon=len(true_action[\"joint_states\"][0])).batched()\n",
425
+ "\n",
426
+ "\n",
427
+ "decoded_action = Pi0Controller._decode_action(\n",
428
+ " target_spec=controller_action_spec,\n",
429
+ " source_spec=nn_action_spec,\n",
430
+ " maybe_batch=Pi0Controller._encode_action(\n",
431
+ " target_spec=nn_action_spec,\n",
432
+ " source_spec=controller_action_spec,\n",
433
+ " maybe_batch=true_action,\n",
434
+ " ),\n",
435
+ ")\n",
436
+ "\n",
437
+ "# # TODO !!!!!!\n",
438
+ "# assert decoded_action == true_action, \"Decoded action does not match the original action.\"\n",
439
+ "# # decoded_action"
440
+ ]
441
+ },
442
+ {
443
+ "cell_type": "code",
444
+ "execution_count": 19,
445
+ "id": "24413547",
446
+ "metadata": {},
447
+ "outputs": [],
448
+ "source": [
449
+ "controller_action_spec = Pi0Controller.ActionSpec()\n",
450
+ "\n",
451
+ "true_action = controller_action_spec.batched(1000).sample()\n",
452
+ "\n",
453
+ "nn_action_spec = Pi0.ActionSpec(numeric_state_horizon=len(true_action[\"joint_states\"][0]))\n"
454
+ ]
455
+ },
456
+ {
457
+ "cell_type": "code",
458
+ "execution_count": 22,
459
+ "id": "7e509e1f",
460
+ "metadata": {},
461
+ "outputs": [
462
+ {
463
+ "name": "stdout",
464
+ "output_type": "stream",
465
+ "text": [
466
+ "2.16 ms ± 309 μs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n"
467
+ ]
468
+ }
469
+ ],
470
+ "source": [
471
+ "%%timeit -n 10\n",
472
+ "\n",
473
+ "\n",
474
+ "\n",
475
+ "decoded_action = Pi0Controller._decode_action(\n",
476
+ " target_spec=controller_action_spec,\n",
477
+ " source_spec=nn_action_spec,\n",
478
+ " batch=Pi0Controller._encode_action(\n",
479
+ " target_spec=nn_action_spec,\n",
480
+ " source_spec=controller_action_spec,\n",
481
+ " batch=true_action,\n",
482
+ " ),\n",
483
+ ")\n",
484
+ "\n",
485
+ "# # TODO !!!!!!\n",
486
+ "# assert decoded_action == true_action, \"Decoded action does not match the original action.\"\n",
487
+ "# # decoded_action"
488
+ ]
489
+ },
490
+ {
491
+ "cell_type": "code",
492
+ "execution_count": 9,
493
+ "id": "b0297a98",
494
+ "metadata": {},
495
+ "outputs": [
496
+ {
497
+ "data": {
498
+ "text/plain": [
499
+ "{'joint_states': (({'todo': array(-2.0677366, dtype=float32),\n",
500
+ " 'todo2': array(-0.5832673, dtype=float32)},),)}"
501
+ ]
502
+ },
503
+ "execution_count": 9,
504
+ "metadata": {},
505
+ "output_type": "execute_result"
506
+ }
507
+ ],
508
+ "source": [
509
+ "decoded_action"
510
+ ]
511
+ },
512
+ {
513
+ "cell_type": "code",
514
+ "execution_count": 50,
515
+ "id": "14525b6a",
516
+ "metadata": {},
517
+ "outputs": [
518
+ {
519
+ "data": {
520
+ "text/plain": [
521
+ "(({'todo': array(-0.7294564, dtype=float32),\n",
522
+ " 'todo2': array(0.46035165, dtype=float32)},),)"
523
+ ]
524
+ },
525
+ "execution_count": 50,
526
+ "metadata": {},
527
+ "output_type": "execute_result"
528
+ }
529
+ ],
530
+ "source": [
531
+ "true_action[\"joint_states\"]"
532
+ ]
533
+ },
534
+ {
535
+ "cell_type": "code",
536
+ "execution_count": 16,
537
+ "id": "9a156759",
538
+ "metadata": {},
539
+ "outputs": [
540
+ {
541
+ "name": "stdout",
542
+ "output_type": "stream",
543
+ "text": [
544
+ "1.08 ms ± 74.1 μs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n"
545
+ ]
546
+ }
547
+ ],
548
+ "source": [
549
+ "%%timeit -n 10\n",
550
+ "\n",
551
+ "# TODO .validate instead\n",
552
+ "Pi0Controller._encode_action(\n",
553
+ " target_spec=nn_action_spec,\n",
554
+ " source_spec=controller_action_spec,\n",
555
+ " batch=true_action,\n",
556
+ ")"
557
+ ]
558
+ },
559
+ {
560
+ "cell_type": "code",
561
+ "execution_count": null,
562
+ "id": "57b70595",
563
+ "metadata": {},
564
+ "outputs": [],
565
+ "source": [
566
+ "gymnasium.spaces.utils.flatten(\n",
567
+ " \n",
568
+ ")"
569
+ ]
570
+ },
571
+ {
572
+ "cell_type": "code",
573
+ "execution_count": 9,
574
+ "id": "8a5388bb",
575
+ "metadata": {},
576
+ "outputs": [
577
+ {
578
+ "data": {
579
+ "text/plain": [
580
+ "Dict('joint_states': Tuple(Sequence(Dict('todo': Box(-inf, inf, (), float32), 'todo2': Box(-inf, inf, (), float32)), stack=False)))"
581
+ ]
582
+ },
583
+ "execution_count": 9,
584
+ "metadata": {},
585
+ "output_type": "execute_result"
586
+ }
587
+ ],
588
+ "source": [
589
+ "controller_action_spec"
590
+ ]
591
+ },
592
+ {
593
+ "cell_type": "code",
594
+ "execution_count": null,
595
+ "id": "b00a3e27",
596
+ "metadata": {},
597
+ "outputs": [],
598
+ "source": [
599
+ "decoded_action"
600
+ ]
601
+ },
602
+ {
603
+ "cell_type": "code",
604
+ "execution_count": 12,
605
+ "id": "64851fdf",
606
+ "metadata": {},
607
+ "outputs": [
608
+ {
609
+ "data": {
610
+ "text/plain": [
611
+ "Dict('joint_states': Tuple(Sequence(Dict('todo': Box(-inf, inf, (), float32), 'todo2': Box(-inf, inf, (), float32)), stack=False)))"
612
+ ]
613
+ },
614
+ "execution_count": 12,
615
+ "metadata": {},
616
+ "output_type": "execute_result"
617
+ }
618
+ ],
619
+ "source": [
620
+ "controller_action_spec"
621
+ ]
622
+ },
623
+ {
624
+ "cell_type": "code",
625
+ "execution_count": 9,
626
+ "id": "0541ad83",
627
+ "metadata": {},
628
+ "outputs": [
629
+ {
630
+ "data": {
631
+ "text/plain": [
632
+ "{'joint_states': ({'todo': array(0.45333853, dtype=float32),\n",
633
+ " 'todo2': array(-1.2251883, dtype=float32)},\n",
634
+ " {'todo': array(-0.11103404, dtype=float32),\n",
635
+ " 'todo2': array(-1.5537481, dtype=float32)},\n",
636
+ " {'todo': array(-1.435329, dtype=float32),\n",
637
+ " 'todo2': array(1.391846, dtype=float32)},\n",
638
+ " {'todo': array(-0.65113515, dtype=float32),\n",
639
+ " 'todo2': array(-1.3501737, dtype=float32)},\n",
640
+ " {'todo': array(0.17569777, dtype=float32),\n",
641
+ " 'todo2': array(-2.490336, dtype=float32)},\n",
642
+ " {'todo': array(1.4868027, dtype=float32),\n",
643
+ " 'todo2': array(-0.47145063, dtype=float32)},\n",
644
+ " {'todo': array(-0.8305958, dtype=float32),\n",
645
+ " 'todo2': array(0.24674042, dtype=float32)},\n",
646
+ " {'todo': array(-0.77655226, dtype=float32),\n",
647
+ " 'todo2': array(1.4923424, dtype=float32)},\n",
648
+ " {'todo': array(-0.9274552, dtype=float32),\n",
649
+ " 'todo2': array(0.31926712, dtype=float32)})}"
650
+ ]
651
+ },
652
+ "execution_count": 9,
653
+ "metadata": {},
654
+ "output_type": "execute_result"
655
+ }
656
+ ],
657
+ "source": [
658
+ "decoded_action"
659
+ ]
660
+ },
661
+ {
662
+ "cell_type": "code",
663
+ "execution_count": null,
664
+ "id": "c8b303e1",
665
+ "metadata": {},
666
+ "outputs": [
667
+ {
668
+ "data": {
669
+ "text/plain": [
670
+ "1"
671
+ ]
672
+ },
673
+ "execution_count": 18,
674
+ "metadata": {},
675
+ "output_type": "execute_result"
676
+ }
677
+ ],
678
+ "source": []
679
+ },
680
+ {
681
+ "cell_type": "code",
682
+ "execution_count": 15,
683
+ "id": "c744eadf",
684
+ "metadata": {},
685
+ "outputs": [
686
+ {
687
+ "data": {
688
+ "text/plain": [
689
+ "{'joint_states': ({'todo': array(-0.1979545, dtype=float32),\n",
690
+ " 'todo2': array(-1.1866441, dtype=float32)},\n",
691
+ " {'todo': array(-0.01813658, dtype=float32),\n",
692
+ " 'todo2': array(-1.5947139, dtype=float32)},\n",
693
+ " {'todo': array(1.205353, dtype=float32),\n",
694
+ " 'todo2': array(1.1273603, dtype=float32)},\n",
695
+ " {'todo': array(-0.00598024, dtype=float32),\n",
696
+ " 'todo2': array(0.7835698, dtype=float32)},\n",
697
+ " {'todo': array(-0.05552755, dtype=float32),\n",
698
+ " 'todo2': array(-0.57986724, dtype=float32)})}"
699
+ ]
700
+ },
701
+ "execution_count": 15,
702
+ "metadata": {},
703
+ "output_type": "execute_result"
704
+ }
705
+ ],
706
+ "source": [
707
+ "controller_action_spec.sample()"
708
+ ]
709
+ },
710
+ {
711
+ "cell_type": "code",
712
+ "execution_count": 16,
713
+ "id": "d870991f",
714
+ "metadata": {},
715
+ "outputs": [
716
+ {
717
+ "data": {
718
+ "text/plain": [
719
+ "Dict('numeric_states': Box(-inf, inf, (4, 32), float32))"
720
+ ]
721
+ },
722
+ "execution_count": 16,
723
+ "metadata": {},
724
+ "output_type": "execute_result"
725
+ }
726
+ ],
727
+ "source": [
728
+ "nn_action_spec"
729
+ ]
730
+ },
731
+ {
732
+ "cell_type": "code",
733
+ "execution_count": 17,
734
+ "id": "7f51ca68",
735
+ "metadata": {},
736
+ "outputs": [
737
+ {
738
+ "data": {
739
+ "text/plain": [
740
+ "({'todo': array(-0.39156017, dtype=float32),\n",
741
+ " 'todo2': array(1.4564499, dtype=float32)},)"
742
+ ]
743
+ },
744
+ "execution_count": 17,
745
+ "metadata": {},
746
+ "output_type": "execute_result"
747
+ }
748
+ ],
749
+ "source": [
750
+ "true_action[\"joint_states\"]"
751
+ ]
752
+ },
753
+ {
754
+ "cell_type": "code",
755
+ "execution_count": 31,
756
+ "id": "652f4ea6",
757
+ "metadata": {},
758
+ "outputs": [
759
+ {
760
+ "data": {
761
+ "text/plain": [
762
+ "Box(-inf, inf, (1,), float32)"
763
+ ]
764
+ },
765
+ "execution_count": 31,
766
+ "metadata": {},
767
+ "output_type": "execute_result"
768
+ }
769
+ ],
770
+ "source": [
771
+ "gymnasium.spaces.utils.flatten_space(controller_action_spec)"
772
+ ]
773
+ },
774
+ {
775
+ "cell_type": "code",
776
+ "execution_count": 34,
777
+ "id": "433da96d",
778
+ "metadata": {},
779
+ "outputs": [
780
+ {
781
+ "data": {
782
+ "text/plain": [
783
+ "Box(-1.0, 1.0, (2,), float64)"
784
+ ]
785
+ },
786
+ "execution_count": 34,
787
+ "metadata": {},
788
+ "output_type": "execute_result"
789
+ }
790
+ ],
791
+ "source": [
792
+ "from gymnasium.spaces import Dict, Box\n",
793
+ "\n",
794
+ "todo = Dict({\n",
795
+ " \"joint_states\": Dict({\n",
796
+ " \"joint1\": Box(low=-1.0, high=1.0, shape=(), dtype=float),\n",
797
+ " \"joint2\": Box(low=-1.0, high=1.0, shape=(), dtype=float),\n",
798
+ " })\n",
799
+ "})\n",
800
+ "gymnasium.spaces.utils.flatten_space(todo)\n"
801
+ ]
802
+ },
803
+ {
804
+ "cell_type": "code",
805
+ "execution_count": null,
806
+ "id": "5317f2c4",
807
+ "metadata": {},
808
+ "outputs": [],
809
+ "source": []
810
+ },
811
+ {
812
+ "cell_type": "code",
813
+ "execution_count": 57,
814
+ "id": "ff252cb2",
815
+ "metadata": {},
816
+ "outputs": [],
817
+ "source": [
818
+ "\n",
819
+ "\n",
820
+ "numeric_states = gymnasium.spaces.utils.flatten(\n",
821
+ " controller_action_spec,\n",
822
+ " true_action,\n",
823
+ " )"
824
+ ]
825
+ },
826
+ {
827
+ "cell_type": "code",
828
+ "execution_count": 50,
829
+ "id": "ca031f36",
830
+ "metadata": {},
831
+ "outputs": [
832
+ {
833
+ "data": {
834
+ "text/plain": [
835
+ "Array([[0.85594803, 0.85594803, 0.85594803, 0.85594803, 0.85594803,\n",
836
+ " 0.85594803, 0.85594803, 0.85594803, 0.85594803, 0.85594803,\n",
837
+ " 0.85594803, 0.85594803, 0.85594803, 0.85594803, 0.85594803,\n",
838
+ " 0.85594803, 0.85594803, 0.85594803, 0.85594803, 0.85594803,\n",
839
+ " 0.85594803, 0.85594803, 0.85594803, 0.85594803, 0.85594803,\n",
840
+ " 0.85594803, 0.85594803, 0.85594803, 0.85594803, 0.85594803,\n",
841
+ " 0.85594803, 0.85594803]], dtype=float32, weak_type=True)"
842
+ ]
843
+ },
844
+ "execution_count": 50,
845
+ "metadata": {},
846
+ "output_type": "execute_result"
847
+ }
848
+ ],
849
+ "source": [
850
+ "a = Pi0Controller._encode_action(\n",
851
+ " target_spec=nn_action_spec,\n",
852
+ " source_spec=controller_action_spec,\n",
853
+ " maybe_batch=true_action,\n",
854
+ " )\n",
855
+ "\n",
856
+ "(\n",
857
+ " jax.numpy.asarray(a[\"numeric_states\"])\n",
858
+ " .at[tuple(\n",
859
+ " slice(0, s) \n",
860
+ " # TODO instead: target_spec[\"joint_states\"].flatten() \n",
861
+ " # TODO target_spec[\"joint_states\"].batch()\n",
862
+ " for s in gymnasium.spaces.utils.flatten_space(\n",
863
+ " controller_action_spec[\"joint_states\"],\n",
864
+ " ).shape\n",
865
+ " )]\n",
866
+ " .get(fill_value=0.)\n",
867
+ " )"
868
+ ]
869
+ },
870
+ {
871
+ "cell_type": "code",
872
+ "execution_count": 54,
873
+ "id": "113fadef",
874
+ "metadata": {},
875
+ "outputs": [
876
+ {
877
+ "data": {
878
+ "text/plain": [
879
+ "(slice(0, 1, None),)"
880
+ ]
881
+ },
882
+ "execution_count": 54,
883
+ "metadata": {},
884
+ "output_type": "execute_result"
885
+ }
886
+ ],
887
+ "source": [
888
+ "tuple(\n",
889
+ " slice(0, s) \n",
890
+ " # TODO instead: target_spec[\"joint_states\"].flatten() \n",
891
+ " # TODO target_spec[\"joint_states\"].batch()\n",
892
+ " for s in gymnasium.spaces.utils.flatten_space(\n",
893
+ " controller_action_spec[\"joint_states\"],\n",
894
+ " ).shape\n",
895
+ " )"
896
+ ]
897
+ },
898
+ {
899
+ "cell_type": "code",
900
+ "execution_count": 53,
901
+ "id": "1ff8af10",
902
+ "metadata": {},
903
+ "outputs": [
904
+ {
905
+ "data": {
906
+ "text/plain": [
907
+ "{'joint_states': {'todo': array([0.85594803], dtype=float32)}}"
908
+ ]
909
+ },
910
+ "execution_count": 53,
911
+ "metadata": {},
912
+ "output_type": "execute_result"
913
+ }
914
+ ],
915
+ "source": [
916
+ "true_action"
917
+ ]
918
+ },
919
+ {
920
+ "cell_type": "code",
921
+ "execution_count": 51,
922
+ "id": "c7d85e1b",
923
+ "metadata": {},
924
+ "outputs": [
925
+ {
926
+ "data": {
927
+ "text/plain": [
928
+ "{'numeric_states': Array([[0.85594803, 0.85594803, 0.85594803, 0.85594803, 0.85594803,\n",
929
+ " 0.85594803, 0.85594803, 0.85594803, 0.85594803, 0.85594803,\n",
930
+ " 0.85594803, 0.85594803, 0.85594803, 0.85594803, 0.85594803,\n",
931
+ " 0.85594803, 0.85594803, 0.85594803, 0.85594803, 0.85594803,\n",
932
+ " 0.85594803, 0.85594803, 0.85594803, 0.85594803, 0.85594803,\n",
933
+ " 0.85594803, 0.85594803, 0.85594803, 0.85594803, 0.85594803,\n",
934
+ " 0.85594803, 0.85594803]], dtype=float32, weak_type=True)}"
935
+ ]
936
+ },
937
+ "execution_count": 51,
938
+ "metadata": {},
939
+ "output_type": "execute_result"
940
+ }
941
+ ],
942
+ "source": [
943
+ "a"
944
+ ]
945
+ },
946
+ {
947
+ "cell_type": "code",
948
+ "execution_count": 28,
949
+ "id": "c1464f27",
950
+ "metadata": {},
951
+ "outputs": [
952
+ {
953
+ "data": {
954
+ "text/plain": [
955
+ "{'numeric_states': Array([[0.85594803, 0.85594803, 0.85594803, 0.85594803, 0.85594803,\n",
956
+ " 0.85594803, 0.85594803, 0.85594803, 0.85594803, 0.85594803,\n",
957
+ " 0.85594803, 0.85594803, 0.85594803, 0.85594803, 0.85594803,\n",
958
+ " 0.85594803, 0.85594803, 0.85594803, 0.85594803, 0.85594803,\n",
959
+ " 0.85594803, 0.85594803, 0.85594803, 0.85594803, 0.85594803,\n",
960
+ " 0.85594803, 0.85594803, 0.85594803, 0.85594803, 0.85594803,\n",
961
+ " 0.85594803, 0.85594803]], dtype=float32, weak_type=True)}"
962
+ ]
963
+ },
964
+ "execution_count": 28,
965
+ "metadata": {},
966
+ "output_type": "execute_result"
967
+ }
968
+ ],
969
+ "source": [
970
+ "a"
971
+ ]
972
+ },
973
+ {
974
+ "cell_type": "code",
975
+ "execution_count": 22,
976
+ "id": "71bda4e0",
977
+ "metadata": {},
978
+ "outputs": [
979
+ {
980
+ "data": {
981
+ "text/plain": [
982
+ "{'joint_states': {'todo': array([0.85594803], dtype=float32)}}"
983
+ ]
984
+ },
985
+ "execution_count": 22,
986
+ "metadata": {},
987
+ "output_type": "execute_result"
988
+ }
989
+ ],
990
+ "source": [
991
+ "true_action"
992
+ ]
993
+ },
994
+ {
995
+ "cell_type": "code",
996
+ "execution_count": 21,
997
+ "id": "8b2a2b3f",
998
+ "metadata": {},
999
+ "outputs": [
1000
+ {
1001
+ "data": {
1002
+ "text/plain": [
1003
+ "(50, 32)"
1004
+ ]
1005
+ },
1006
+ "execution_count": 21,
1007
+ "metadata": {},
1008
+ "output_type": "execute_result"
1009
+ }
1010
+ ],
1011
+ "source": [
1012
+ "a[\"numeric_states\"].shape"
1013
+ ]
1014
+ },
1015
+ {
1016
+ "cell_type": "code",
1017
+ "execution_count": 17,
1018
+ "id": "1be9b307",
1019
+ "metadata": {},
1020
+ "outputs": [
1021
+ {
1022
+ "data": {
1023
+ "text/plain": [
1024
+ "(1,)"
1025
+ ]
1026
+ },
1027
+ "execution_count": 17,
1028
+ "metadata": {},
1029
+ "output_type": "execute_result"
1030
+ }
1031
+ ],
1032
+ "source": [
1033
+ "gymnasium.spaces.utils.flatten_space(\n",
1034
+ " controller_action_spec[\"joint_states\"],\n",
1035
+ " ).shape"
1036
+ ]
1037
+ },
1038
+ {
1039
+ "cell_type": "code",
1040
+ "execution_count": 8,
1041
+ "id": "aecd4831",
1042
+ "metadata": {},
1043
+ "outputs": [
1044
+ {
1045
+ "data": {
1046
+ "text/plain": [
1047
+ "Dict('numeric_states': Box(-inf, inf, (50, 32), float32))"
1048
+ ]
1049
+ },
1050
+ "execution_count": 8,
1051
+ "metadata": {},
1052
+ "output_type": "execute_result"
1053
+ }
1054
+ ],
1055
+ "source": [
1056
+ "nn_action_spec"
1057
+ ]
1058
+ },
1059
+ {
1060
+ "cell_type": "code",
1061
+ "execution_count": 9,
1062
+ "id": "77cf8a9a",
1063
+ "metadata": {},
1064
+ "outputs": [
1065
+ {
1066
+ "data": {
1067
+ "text/plain": [
1068
+ "Dict('joint_states': Dict('todo': Box(-inf, inf, (1,), float32)))"
1069
+ ]
1070
+ },
1071
+ "execution_count": 9,
1072
+ "metadata": {},
1073
+ "output_type": "execute_result"
1074
+ }
1075
+ ],
1076
+ "source": [
1077
+ "controller_action_spec"
1078
+ ]
1079
+ },
1080
+ {
1081
+ "cell_type": "code",
1082
+ "execution_count": 16,
1083
+ "id": "e037a0dc",
1084
+ "metadata": {},
1085
+ "outputs": [
1086
+ {
1087
+ "data": {
1088
+ "text/plain": [
1089
+ "Dict('joint_states': Sequence(Dict('todo': Box(-inf, inf, (), float32)), stack=True))"
1090
+ ]
1091
+ },
1092
+ "execution_count": 16,
1093
+ "metadata": {},
1094
+ "output_type": "execute_result"
1095
+ }
1096
+ ],
1097
+ "source": [
1098
+ "controller_action_spec"
1099
+ ]
1100
+ },
1101
+ {
1102
+ "cell_type": "code",
1103
+ "execution_count": 18,
1104
+ "id": "e5eb6951",
1105
+ "metadata": {},
1106
+ "outputs": [
1107
+ {
1108
+ "data": {
1109
+ "text/plain": [
1110
+ "(17,)"
1111
+ ]
1112
+ },
1113
+ "execution_count": 18,
1114
+ "metadata": {},
1115
+ "output_type": "execute_result"
1116
+ }
1117
+ ],
1118
+ "source": [
1119
+ "true_action[\"joint_states\"][\"todo\"].shape"
1120
+ ]
1121
+ },
1122
+ {
1123
+ "cell_type": "code",
1124
+ "execution_count": 17,
1125
+ "id": "7eb5f0ba",
1126
+ "metadata": {},
1127
+ "outputs": [
1128
+ {
1129
+ "data": {
1130
+ "text/plain": [
1131
+ "Dict('numeric_states': Box(-inf, inf, (50, 32), float32))"
1132
+ ]
1133
+ },
1134
+ "execution_count": 17,
1135
+ "metadata": {},
1136
+ "output_type": "execute_result"
1137
+ }
1138
+ ],
1139
+ "source": [
1140
+ "nn_action_spec"
1141
+ ]
1142
+ },
1143
+ {
1144
+ "cell_type": "code",
1145
+ "execution_count": 19,
1146
+ "id": "c705c2c9",
1147
+ "metadata": {},
1148
+ "outputs": [
1149
+ {
1150
+ "data": {
1151
+ "text/plain": [
1152
+ "(50, 32)"
1153
+ ]
1154
+ },
1155
+ "execution_count": 19,
1156
+ "metadata": {},
1157
+ "output_type": "execute_result"
1158
+ }
1159
+ ],
1160
+ "source": [
1161
+ "Pi0Controller._encode_action(\n",
1162
+ " target_spec=nn_action_spec,\n",
1163
+ " source_spec=controller_action_spec,\n",
1164
+ " maybe_batch=true_action,\n",
1165
+ " )[\"numeric_states\"].shape"
1166
+ ]
1167
+ },
1168
+ {
1169
+ "cell_type": "code",
1170
+ "execution_count": 8,
1171
+ "id": "d2678ba7",
1172
+ "metadata": {},
1173
+ "outputs": [
1174
+ {
1175
+ "data": {
1176
+ "text/plain": [
1177
+ "{'joint_states': (({'todo': array(0.29307076, dtype=float32)},\n",
1178
+ " {'todo': array(0.5457149, dtype=float32)},\n",
1179
+ " {'todo': array(-1.4348172, dtype=float32)},\n",
1180
+ " {'todo': array(0.7655879, dtype=float32)}),)}"
1181
+ ]
1182
+ },
1183
+ "execution_count": 8,
1184
+ "metadata": {},
1185
+ "output_type": "execute_result"
1186
+ }
1187
+ ],
1188
+ "source": [
1189
+ "true_action"
1190
+ ]
1191
+ },
1192
+ {
1193
+ "cell_type": "code",
1194
+ "execution_count": null,
1195
+ "id": "86aa0ed9",
1196
+ "metadata": {},
1197
+ "outputs": [],
1198
+ "source": []
1199
+ },
1200
+ {
1201
+ "cell_type": "code",
1202
+ "execution_count": 1,
1203
+ "id": "0a84d5bf",
1204
+ "metadata": {},
1205
+ "outputs": [
1206
+ {
1207
+ "name": "stdout",
1208
+ "output_type": "stream",
1209
+ "text": [
1210
+ "env: JAX_PLATFORMS=cpu\n",
1211
+ "env: XLA_PYTHON_CLIENT_PREALLOCATE=false\n"
1212
+ ]
1213
+ }
1214
+ ],
1215
+ "source": [
1216
+ "%env JAX_PLATFORMS=cpu\n",
1217
+ "# %env JAX_DISABLE_JIT=1 \n",
1218
+ "# %env CUDA_VISIBLE_DEVICES=1\n",
1219
+ "%env XLA_PYTHON_CLIENT_PREALLOCATE=false"
1220
+ ]
1221
+ },
1222
+ {
1223
+ "cell_type": "code",
1224
+ "execution_count": 2,
1225
+ "id": "c6796b29",
1226
+ "metadata": {},
1227
+ "outputs": [],
1228
+ "source": [
1229
+ "from robotodo.controllers.pi0 import Pi0Controller\n",
1230
+ "from robotodo.controllers.pi0.nn.pi0 import Pi0\n",
1231
+ "\n",
1232
+ "# import jax\n",
1233
+ "# jax.image.resize(jax.numpy.zeros((12, 64, 64, 3)), shape=(12, 128, 128, 3), method=\"nearest\")"
1234
+ ]
1235
+ },
1236
+ {
1237
+ "cell_type": "code",
1238
+ "execution_count": 3,
1239
+ "id": "1baf3a81",
1240
+ "metadata": {},
1241
+ "outputs": [
1242
+ {
1243
+ "data": {
1244
+ "text/plain": [
1245
+ "<robotodo.controllers.pi0.pi0_controller.Pi0Controller at 0x7fe138257210>"
1246
+ ]
1247
+ },
1248
+ "execution_count": 3,
1249
+ "metadata": {},
1250
+ "output_type": "execute_result"
1251
+ }
1252
+ ],
1253
+ "source": [
1254
+ "controller = Pi0Controller()\n",
1255
+ "controller"
1256
+ ]
1257
+ },
1258
+ {
1259
+ "cell_type": "code",
1260
+ "execution_count": 5,
1261
+ "id": "790b06d7",
1262
+ "metadata": {},
1263
+ "outputs": [
1264
+ {
1265
+ "ename": "TypeError",
1266
+ "evalue": "dot_general requires contracting dimensions to have the same shape, got (1,) and (32,).",
1267
+ "output_type": "error",
1268
+ "traceback": [
1269
+ "\u001b[31m---------------------------------------------------------------------------\u001b[39m",
1270
+ "\u001b[31mTypeError\u001b[39m Traceback (most recent call last)",
1271
+ "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[5]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m \u001b[43mcontroller\u001b[49m\u001b[43m.\u001b[49m\u001b[43mcompute_action\u001b[49m\u001b[43m(\u001b[49m\u001b[43mcontroller\u001b[49m\u001b[43m.\u001b[49m\u001b[43m_config\u001b[49m\u001b[43m[\u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mobservation_spec\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m]\u001b[49m\u001b[43m.\u001b[49m\u001b[43mbatched\u001b[49m\u001b[43m(\u001b[49m\u001b[32;43m10\u001b[39;49m\u001b[43m)\u001b[49m\u001b[43m.\u001b[49m\u001b[43msample\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[43m)\u001b[49m\n",
1272
+ "\u001b[36mFile \u001b[39m\u001b[32m~/RoboTwin/packages/robotodo/controllers/pi0/pi0_controller.py:264\u001b[39m, in \u001b[36mPi0Controller.compute_action\u001b[39m\u001b[34m(self, maybe_batch_observation, rng, num_actions, diffusion_num_steps)\u001b[39m\n\u001b[32m 241\u001b[39m rng = rng \u001b[38;5;129;01mor\u001b[39;00m jax.random.key(\u001b[32m0\u001b[39m)\n\u001b[32m 243\u001b[39m batch_observation_nn = Pi0Controller._encode_observation(\n\u001b[32m 244\u001b[39m \u001b[38;5;66;03m# TODO\u001b[39;00m\n\u001b[32m 245\u001b[39m target_observation_spec=\u001b[38;5;28mself\u001b[39m._nn.observation_spec(),\n\u001b[32m (...)\u001b[39m\u001b[32m 261\u001b[39m ),\n\u001b[32m 262\u001b[39m )\n\u001b[32m--> \u001b[39m\u001b[32m264\u001b[39m batch_actions_nn = \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43m_nn\u001b[49m\u001b[43m.\u001b[49m\u001b[43msample_actions\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m 265\u001b[39m \u001b[43m \u001b[49m\u001b[38;5;66;43;03m# TODO !!!!\u001b[39;49;00m\n\u001b[32m 266\u001b[39m \u001b[43m \u001b[49m\u001b[43mrng\u001b[49m\u001b[43m=\u001b[49m\u001b[43mrng\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\n\u001b[32m 267\u001b[39m \u001b[43m \u001b[49m\u001b[43mbatch_observation\u001b[49m\u001b[43m=\u001b[49m\u001b[43mbatch_observation_nn\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 268\u001b[39m \u001b[43m \u001b[49m\u001b[43mnum_actions\u001b[49m\u001b[43m=\u001b[49m\u001b[43mnum_actions\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 269\u001b[39m \u001b[43m \u001b[49m\u001b[43mdiffusion_num_steps\u001b[49m\u001b[43m=\u001b[49m\u001b[43mdiffusion_num_steps\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 270\u001b[39m \u001b[43m\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 272\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m Pi0Controller._decode_action(\n\u001b[32m 273\u001b[39m target_action_spec=\u001b[38;5;28mself\u001b[39m._config[\u001b[33m\"\u001b[39m\u001b[33maction_spec\u001b[39m\u001b[33m\"\u001b[39m],\n\u001b[32m 274\u001b[39m source_action_spec=\u001b[38;5;28mself\u001b[39m._nn.action_spec(),\n\u001b[32m 275\u001b[39m maybe_batch_action=batch_actions_nn,\n\u001b[32m 276\u001b[39m )\n",
1273
+ "\u001b[36mFile \u001b[39m\u001b[32m~/RoboTwin/packages/robotodo/controllers/pi0/nn/pi0.py:482\u001b[39m, in \u001b[36mPi0.sample_actions\u001b[39m\u001b[34m(self, rng, batch_observation, num_actions, diffusion_num_steps)\u001b[39m\n\u001b[32m 479\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m time >= -dt / \u001b[32m2\u001b[39m\n\u001b[32m 481\u001b[39m noise = jax.random.normal(rng, (batch_size, num_actions, \u001b[38;5;28mself\u001b[39m.action_out_proj.out_features))\n\u001b[32m--> \u001b[39m\u001b[32m482\u001b[39m x_0, _ = \u001b[43mjax\u001b[49m\u001b[43m.\u001b[49m\u001b[43mlax\u001b[49m\u001b[43m.\u001b[49m\u001b[43mwhile_loop\u001b[49m\u001b[43m(\u001b[49m\u001b[43mcond\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mstep\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43m(\u001b[49m\u001b[43mnoise\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[32;43m1.0\u001b[39;49m\u001b[43m)\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 483\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m {\u001b[33m\"\u001b[39m\u001b[33mnumeric_states\u001b[39m\u001b[33m\"\u001b[39m: x_0}\n",
1274
+ " \u001b[31m[... skipping hidden 10 frame]\u001b[39m\n",
1275
+ "\u001b[36mFile \u001b[39m\u001b[32m~/RoboTwin/packages/robotodo/controllers/pi0/nn/pi0.py:448\u001b[39m, in \u001b[36mPi0.sample_actions.<locals>.step\u001b[39m\u001b[34m(carry)\u001b[39m\n\u001b[32m 446\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34mstep\u001b[39m(carry: \u001b[38;5;28mtuple\u001b[39m[\u001b[38;5;28mfloat\u001b[39m, \u001b[38;5;28mfloat\u001b[39m]):\n\u001b[32m 447\u001b[39m x_t, time = carry\n\u001b[32m--> \u001b[39m\u001b[32m448\u001b[39m suffix_tokens, suffix_mask, suffix_ar_mask = \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43m_embed_suffix\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m 449\u001b[39m \u001b[43m \u001b[49m\u001b[43mbatch_observation\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43m{\u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mnumeric_states\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mx_t\u001b[49m\u001b[43m}\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mjnp\u001b[49m\u001b[43m.\u001b[49m\u001b[43mbroadcast_to\u001b[49m\u001b[43m(\u001b[49m\u001b[43mtime\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mbatch_size\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 450\u001b[39m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 451\u001b[39m \u001b[38;5;66;03m# `suffix_attn_mask` is shape (b, suffix_len, suffix_len) indicating how the suffix tokens can attend to each\u001b[39;00m\n\u001b[32m 452\u001b[39m \u001b[38;5;66;03m# other\u001b[39;00m\n\u001b[32m 453\u001b[39m suffix_attn_mask = make_attn_mask(suffix_mask, suffix_ar_mask)\n",
1276
+ "\u001b[36mFile \u001b[39m\u001b[32m~/RoboTwin/packages/robotodo/controllers/pi0/nn/pi0.py:393\u001b[39m, in \u001b[36mPi0._embed_suffix\u001b[39m\u001b[34m(self, batch_observation, batch_noisy_action, timestep)\u001b[39m\n\u001b[32m 390\u001b[39m tokens = []\n\u001b[32m 392\u001b[39m \u001b[38;5;66;03m# add a single state token\u001b[39;00m\n\u001b[32m--> \u001b[39m\u001b[32m393\u001b[39m state_token = \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mstate_proj\u001b[49m\u001b[43m(\u001b[49m\u001b[43mbatch_observation\u001b[49m\u001b[43m[\u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mnumeric_state\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m]\u001b[49m\u001b[43m)\u001b[49m[:, \u001b[38;5;28;01mNone\u001b[39;00m, :]\n\u001b[32m 394\u001b[39m tokens.append(state_token)\n\u001b[32m 395\u001b[39m input_mask.append(jnp.ones((batch_observation[\u001b[33m\"\u001b[39m\u001b[33mnumeric_state\u001b[39m\u001b[33m\"\u001b[39m].shape[\u001b[32m0\u001b[39m], \u001b[32m1\u001b[39m), dtype=jnp.bool_))\n",
1277
+ "\u001b[36mFile \u001b[39m\u001b[32m~/RoboTwin/.conda/lib/python3.11/site-packages/flax/nnx/nn/linear.py:387\u001b[39m, in \u001b[36mLinear.__call__\u001b[39m\u001b[34m(self, inputs)\u001b[39m\n\u001b[32m 382\u001b[39m bias = \u001b[38;5;28mself\u001b[39m.bias.value \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m.bias \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;28;01melse\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m\n\u001b[32m 384\u001b[39m inputs, kernel, bias = \u001b[38;5;28mself\u001b[39m.promote_dtype(\n\u001b[32m 385\u001b[39m (inputs, kernel, bias), dtype=\u001b[38;5;28mself\u001b[39m.dtype\n\u001b[32m 386\u001b[39m )\n\u001b[32m--> \u001b[39m\u001b[32m387\u001b[39m y = \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mdot_general\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m 388\u001b[39m \u001b[43m \u001b[49m\u001b[43minputs\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 389\u001b[39m \u001b[43m \u001b[49m\u001b[43mkernel\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 390\u001b[39m \u001b[43m \u001b[49m\u001b[43m(\u001b[49m\u001b[43m(\u001b[49m\u001b[43m(\u001b[49m\u001b[43minputs\u001b[49m\u001b[43m.\u001b[49m\u001b[43mndim\u001b[49m\u001b[43m \u001b[49m\u001b[43m-\u001b[49m\u001b[43m \u001b[49m\u001b[32;43m1\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43m(\u001b[49m\u001b[32;43m0\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m)\u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43m(\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[43m)\u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 391\u001b[39m \u001b[43m \u001b[49m\u001b[43mprecision\u001b[49m\u001b[43m=\u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mprecision\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 392\u001b[39m \u001b[43m\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 393\u001b[39m \u001b[38;5;28;01massert\u001b[39;00m \u001b[38;5;28mself\u001b[39m.use_bias == (bias \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m)\n\u001b[32m 394\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m bias \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n",
1278
+ " \u001b[31m[... skipping hidden 12 frame]\u001b[39m\n",
1279
+ "\u001b[36mFile \u001b[39m\u001b[32m~/RoboTwin/.conda/lib/python3.11/site-packages/jax/_src/lax/lax.py:5206\u001b[39m, in \u001b[36m_dot_general_shape_rule\u001b[39m\u001b[34m(lhs, rhs, dimension_numbers, precision, preferred_element_type, out_sharding)\u001b[39m\n\u001b[32m 5203\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m core.definitely_equal_shape(lhs_contracting_shape, rhs_contracting_shape):\n\u001b[32m 5204\u001b[39m msg = (\u001b[33m\"\u001b[39m\u001b[33mdot_general requires contracting dimensions to have the same \u001b[39m\u001b[33m\"\u001b[39m\n\u001b[32m 5205\u001b[39m \u001b[33m\"\u001b[39m\u001b[33mshape, got \u001b[39m\u001b[38;5;132;01m{}\u001b[39;00m\u001b[33m and \u001b[39m\u001b[38;5;132;01m{}\u001b[39;00m\u001b[33m.\u001b[39m\u001b[33m\"\u001b[39m)\n\u001b[32m-> \u001b[39m\u001b[32m5206\u001b[39m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mTypeError\u001b[39;00m(msg.format(lhs_contracting_shape, rhs_contracting_shape))\n\u001b[32m 5208\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m _dot_general_shape_computation(lhs.shape, rhs.shape, dimension_numbers)\n",
1280
+ "\u001b[31mTypeError\u001b[39m: dot_general requires contracting dimensions to have the same shape, got (1,) and (32,)."
1281
+ ]
1282
+ }
1283
+ ],
1284
+ "source": [
1285
+ "controller.compute_action(controller._config[\"observation_spec\"].batched(10).sample())"
1286
+ ]
1287
+ },
1288
+ {
1289
+ "cell_type": "code",
1290
+ "execution_count": null,
1291
+ "id": "3f4ee490",
1292
+ "metadata": {},
1293
+ "outputs": [],
1294
+ "source": []
1295
+ },
1296
+ {
1297
+ "cell_type": "code",
1298
+ "execution_count": 1,
1299
+ "id": "442e21f3",
1300
+ "metadata": {},
1301
+ "outputs": [],
1302
+ "source": [
1303
+ "from robotodo.controllers.pi0.nn.paligemma_tokenizer import PaligemmaTokenizer\n",
1304
+ "\n",
1305
+ "tokenizer = PaligemmaTokenizer()"
1306
+ ]
1307
+ },
1308
+ {
1309
+ "cell_type": "code",
1310
+ "execution_count": 2,
1311
+ "id": "1989d55c",
1312
+ "metadata": {},
1313
+ "outputs": [
1314
+ {
1315
+ "data": {
1316
+ "text/plain": [
1317
+ "(Array([[ 2, 1124, 2142, 235303, 235256, 749, 736, 108,\n",
1318
+ " 0, 0, 0, 0, 0, 0, 0, 0,\n",
1319
+ " 0, 0, 0, 0, 0, 0, 0, 0,\n",
1320
+ " 0, 0, 0, 0, 0, 0, 0, 0,\n",
1321
+ " 0, 0, 0, 0, 0, 0, 0, 0,\n",
1322
+ " 0, 0, 0, 0, 0, 0, 0, 0],\n",
1323
+ " [ 2, 31844, 2793, 108, 0, 0, 0, 0,\n",
1324
+ " 0, 0, 0, 0, 0, 0, 0, 0,\n",
1325
+ " 0, 0, 0, 0, 0, 0, 0, 0,\n",
1326
+ " 0, 0, 0, 0, 0, 0, 0, 0,\n",
1327
+ " 0, 0, 0, 0, 0, 0, 0, 0,\n",
1328
+ " 0, 0, 0, 0, 0, 0, 0, 0]], dtype=int32),\n",
1329
+ " Array([[ True, True, True, True, True, True, True, True, False,\n",
1330
+ " False, False, False, False, False, False, False, False, False,\n",
1331
+ " False, False, False, False, False, False, False, False, False,\n",
1332
+ " False, False, False, False, False, False, False, False, False,\n",
1333
+ " False, False, False, False, False, False, False, False, False,\n",
1334
+ " False, False, False],\n",
1335
+ " [ True, True, True, True, False, False, False, False, False,\n",
1336
+ " False, False, False, False, False, False, False, False, False,\n",
1337
+ " False, False, False, False, False, False, False, False, False,\n",
1338
+ " False, False, False, False, False, False, False, False, False,\n",
1339
+ " False, False, False, False, False, False, False, False, False,\n",
1340
+ " False, False, False]], dtype=bool))"
1341
+ ]
1342
+ },
1343
+ "execution_count": 2,
1344
+ "metadata": {},
1345
+ "output_type": "execute_result"
1346
+ }
1347
+ ],
1348
+ "source": [
1349
+ "# %%timeit -n 50\n",
1350
+ "tokenizer._todo_call([\"ok let's do this\", \"another text\"], max_len=48)"
1351
+ ]
1352
+ },
1353
+ {
1354
+ "cell_type": "code",
1355
+ "execution_count": 7,
1356
+ "id": "737d1cb5",
1357
+ "metadata": {},
1358
+ "outputs": [
1359
+ {
1360
+ "name": "stdout",
1361
+ "output_type": "stream",
1362
+ "text": [
1363
+ "32.1 μs ± 4.3 μs per loop (mean ± std. dev. of 7 runs, 50 loops each)\n"
1364
+ ]
1365
+ }
1366
+ ],
1367
+ "source": [
1368
+ "%%timeit -n 50\n",
1369
+ "tokenizer(\"ok let's do this\")"
1370
+ ]
1371
+ }
1372
+ ],
1373
+ "metadata": {
1374
+ "kernelspec": {
1375
+ "display_name": "Python 3",
1376
+ "language": "python",
1377
+ "name": "python3"
1378
+ },
1379
+ "language_info": {
1380
+ "codemirror_mode": {
1381
+ "name": "ipython",
1382
+ "version": 3
1383
+ },
1384
+ "file_extension": ".py",
1385
+ "mimetype": "text/x-python",
1386
+ "name": "python",
1387
+ "nbconvert_exporter": "python",
1388
+ "pygments_lexer": "ipython3",
1389
+ "version": "3.11.13"
1390
+ }
1391
+ },
1392
+ "nbformat": 4,
1393
+ "nbformat_minor": 5
1394
+ }
__todo__/todo.md CHANGED
@@ -66,6 +66,24 @@ some_robot.some_sensor.state_space # ... .value
66
 
67
  ```
68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  - robotodo.controllers.pi0:
70
  - [-] inference
71
  - [ ] checkpointing
@@ -74,4 +92,24 @@ some_robot.some_sensor.state_space # ... .value
74
  - [ ] load from lerobot
75
  - [ ] training
76
 
77
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
  ```
68
 
69
+ urdf articulation/actor description loading
70
+
71
+ ```
72
+ from robotodo.core import ArticulationSpec, Articulation
73
+
74
+ articulation_spec = ArticulationSpec.from_urdf("/some/urdf/path.urdf")
75
+
76
+ # TODO
77
+ articulation_spec.links.find("L_hand_whatever")
78
+ articulation_spec.links.find(re.compile("L_*"))
79
+
80
+
81
+ articulation = Articulation(articulation_spec)
82
+ articulation.links # ...
83
+
84
+ ```
85
+
86
+
87
  - robotodo.controllers.pi0:
88
  - [-] inference
89
  - [ ] checkpointing
 
92
  - [ ] load from lerobot
93
  - [ ] training
94
 
95
+
96
+ - controllables.Ref
97
+ ```python
98
+ class SomeRef:
99
+ __spec__ = Box(...)
100
+
101
+ ref = SomeRef()
102
+ ref.current # overridable by provider
103
+ ref.current = 1. # validatable by provider
104
+
105
+ class SomeComplexRef:
106
+ __spec__ = Struct({
107
+ "some_field": Box(...),
108
+ "another_field": Struct(...),
109
+ })
110
+
111
+ robot.joints_ref.spec
112
+ robot.joints_ref.current
113
+ robot.joints_ref.spec.sample()
114
+
115
+ ```
examples/demo-controller_setup.ipynb ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "91ec3890",
6
+ "metadata": {},
7
+ "source": [
8
+ "# TODO"
9
+ ]
10
+ }
11
+ ],
12
+ "metadata": {
13
+ "language_info": {
14
+ "name": "python"
15
+ }
16
+ },
17
+ "nbformat": 4,
18
+ "nbformat_minor": 5
19
+ }
examples/demo-scene_setup.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
examples/demo.ipynb DELETED
The diff for this file is too large to render. See raw diff
 
packages/robotodo/actors/unitree_robots/__init__.py CHANGED
@@ -76,7 +76,7 @@ class UnitreeG1DFQRobot:
76
  pose=sapien.Pose(),
77
  width=1280,
78
  height=720,
79
- # TODO
80
  fovy=numpy.deg2rad(0),
81
  near=.1,
82
  far=100.,
@@ -93,8 +93,8 @@ class UnitreeG1DFQRobot:
93
  self._cameras["head_camera"] = self._cameras["d435_link"]
94
 
95
  # # TODO !!!!!!!!
96
- for link in self._entity.links:
97
- link.set_mass(1)
98
 
99
  @property
100
  def root_pose(self):
 
76
  pose=sapien.Pose(),
77
  width=1280,
78
  height=720,
79
+ # NOTE fovx and fovy are set below
80
  fovy=numpy.deg2rad(0),
81
  near=.1,
82
  far=100.,
 
93
  self._cameras["head_camera"] = self._cameras["d435_link"]
94
 
95
  # # TODO !!!!!!!!
96
+ # for link in self._entity.links:
97
+ # link.set_mass(1)
98
 
99
  @property
100
  def root_pose(self):
packages/robotodo/controllers/pi0/nn/paligemma_tokenizer.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from typing import Sequence
3
+ import warnings
4
+
5
+ import fsspec
6
+ import sentencepiece
7
+ import jax
8
+ # import numpy as np
9
+
10
+
11
+ class PaligemmaTokenizer:
12
+ def __init__(self):
13
+ # TODO better handling
14
+ import platformdirs
15
+ with fsspec.open(
16
+ "filecache::https://storage.googleapis.com/big_vision/paligemma_tokenizer.model",
17
+ mode="rb",
18
+ # token="anon",
19
+ cache_storage=platformdirs.user_cache_dir(appname="paligemma_tokenizer.big_vision.todo", appauthor=False),
20
+ same_names=True,
21
+ ) as f:
22
+ self._tokenizer = sentencepiece.SentencePieceProcessor(model_proto=f.read())
23
+
24
+ @property
25
+ def vocab_size(self):
26
+ return self._tokenizer.GetPieceSize()
27
+
28
+ def __call__(
29
+ self,
30
+ batch_text: Sequence[str],
31
+ max_len: int | None = None,
32
+ ):
33
+ input_max_len = max(len(text) for text in batch_text)
34
+ if max_len is None:
35
+ max_len = input_max_len
36
+ if input_max_len > max_len:
37
+ warnings.warn(
38
+ f"Max length of text in batch_text ({input_max_len}) "
39
+ f"exceeds max_len ({max_len})! Tokens will be truncated "
40
+ f"and consider increasing max_len above {input_max_len}."
41
+ )
42
+
43
+ batch_text = [
44
+ # tokenize "\n" separately as the "start of answer" token
45
+ str.strip(text).replace("_", " ").replace("\n", " ") + "\n"
46
+ for text in batch_text
47
+ ]
48
+ batch_tokens = self._tokenizer.Encode(batch_text, add_bos=True)
49
+
50
+ batch_tokens_padded = jax.numpy.stack([
51
+ jax.numpy.pad(
52
+ jax.numpy.array(tokens[:max_len]),
53
+ (0, max_len - len(tokens[:max_len])),
54
+ )
55
+ for tokens in batch_tokens
56
+ ])
57
+ batch_token_masks = jax.numpy.stack([
58
+ jax.numpy.concatenate([
59
+ jax.numpy.full(len(tokens[:max_len]), True, dtype=jax.numpy.bool),
60
+ jax.numpy.full(max_len - len(tokens[:max_len]), False, dtype=jax.numpy.bool)
61
+ ])
62
+ for tokens in batch_tokens
63
+ ])
64
+ return batch_tokens_padded, batch_token_masks
65
+
66
+
67
+
68
+ # # TODO rm
69
+ # def __call__(self, prompt: str, max_len: int = 48) -> tuple[np.ndarray, np.ndarray]:
70
+ # cleaned_text = prompt.strip().replace("_", " ").replace("\n", " ")
71
+ # # tokenize "\n" separately as the "start of answer" token
72
+ # tokens = self._tokenizer.Encode(cleaned_text, add_bos=True) + self._tokenizer.Encode("\n")
73
+ # tokens_len = len(tokens)
74
+ # if tokens_len < max_len:
75
+ # padding = [False] * (max_len - tokens_len)
76
+ # mask = [True] * tokens_len + padding
77
+ # tokens = tokens + padding
78
+ # else:
79
+ # if len(tokens) > max_len:
80
+ # warnings.warn(
81
+ # f"Token length ({len(tokens)}) exceeds max length ({max_len}), truncating. "
82
+ # "Consider increasing the `max_token_len` in your model config if this happens frequently."
83
+ # )
84
+ # tokens = tokens[: max_len]
85
+ # mask = [True] * max_len
86
+
87
+ # # TODO mask necesito???
88
+ # return np.asarray(tokens), np.asarray(mask)
packages/robotodo/controllers/pi0/nn/pi0.py CHANGED
@@ -20,7 +20,7 @@ import numpy
20
 
21
 
22
  # TODO placeholder for now; implement upstream !!!!!
23
- from typing import Type # TODO !!!!!
24
  SpaceVar = Type
25
  # ######################################
26
 
@@ -105,7 +105,6 @@ def posemb_sincos(
105
  return jnp.concatenate([jnp.sin(sinusoid_input), jnp.cos(sinusoid_input)], axis=-1)
106
 
107
 
108
- # TODO
109
  class Pi0(nnx.Module):
110
  """
111
  TODO
@@ -120,24 +119,25 @@ class Pi0(nnx.Module):
120
  class ObservationSpec(gymnasium.spaces.Dict):
121
  def __init__(
122
  self,
123
- image_names: tuple[str, ...] = (
124
- "base_0_rgb",
125
- "left_wrist_0_rgb",
126
- "right_wrist_0_rgb",
127
- ),
128
- image_size: tuple[int, int] = (224, 224),
129
- text_max_len: int = 48,
130
- text_vocab_size: int | None = 257_152,
131
  numeric_state_size: int = 32,
 
 
 
132
  ):
133
  """
134
  Observation specification (unbatched).
135
 
136
- :param image_names: Names of images in the observation. TODO
137
- :param image_size: Resolution of input images: (height, width). TODO or width height?
138
- :param text_max_len: Maximum length of text tokens. (TODO)
139
- :param text_vocab_size: Size of text vocabulary. Infinite if :class:`None`.
140
- :param numeric_state_size: Size of numeric state (e.g. number of motors).
 
 
 
 
 
141
 
142
  .. seealso::
143
  Default values from the official Pi0 implementation:
@@ -148,40 +148,25 @@ class Pi0(nnx.Module):
148
  - `numeric_state_size <https://github.com/Physical-Intelligence/openpi/blob/84cd4dc87854856a4fd878cc8951cbc59023eaa7/src/openpi/models/pi0.py#L74>`_
149
  """
150
 
151
- self.feature_specs = {
152
- "image": gymnasium.spaces.Box(
153
  low=-1., high=1.,
154
- shape=(*image_size, 3),
155
  dtype=numpy.float32,
156
- )
157
- }
158
-
159
- super().__init__({
160
- "images": gymnasium.spaces.Dict({
161
- image_name: self.feature_specs["image"]
162
- for image_name in image_names
163
- }),
164
- "images.mask": gymnasium.spaces.Dict({
165
- image_name: gymnasium.spaces.Box(
166
- low=0, high=1,
167
- shape=(), # TODO
168
- dtype=numpy.uint8,
169
- )
170
- for image_name in image_names
171
- }),
172
  "tokenized_text": gymnasium.spaces.Box(
173
- low=0, high=(
174
- text_vocab_size
175
- if text_vocab_size is not None else
176
- numpy.inf
177
- - 1
178
- ),
179
- shape=(text_max_len, ), # TODO
180
  dtype=numpy.int32,
181
  ),
182
  "tokenized_text.mask": gymnasium.spaces.Box(
183
  low=0, high=1,
184
- shape=(text_max_len, ), # TODO
185
  dtype=numpy.uint8,
186
  ),
187
  "numeric_state": gymnasium.spaces.Box(
@@ -199,13 +184,17 @@ class Pi0(nnx.Module):
199
  def __init__(
200
  self,
201
  numeric_state_size: int = 32,
202
- numeric_state_horizon: int = 50,
203
  ):
204
  """
205
  Action specification (unbatched).
206
 
 
 
 
 
207
  :param numeric_state_size: Size of numeric state (e.g. number of motor positions).
208
- :param numeric_state_horizon: The number of future states to predict.
209
 
210
  .. seealso::
211
  Default values from the official Pi0 implementation:
@@ -225,10 +214,14 @@ class Pi0(nnx.Module):
225
  def batched(self, batch_size: int = 1):
226
  return gymnasium.vector.utils.batch_space(self, n=batch_size)
227
 
 
228
  @dataclasses.dataclass(frozen=True)
229
  class Config:
230
- observation_spec: "Pi0.ObservationSpec"
231
- action_spec: "Pi0.ActionSpec"
 
 
 
232
 
233
  dtype: str = "bfloat16"
234
  paligemma_variant: _gemma.Variant = "gemma_2b"
@@ -236,16 +229,15 @@ class Pi0(nnx.Module):
236
 
237
  def __init__(
238
  self,
239
- config: Config = Config(
240
- observation_spec=ObservationSpec(),
241
- action_spec=ActionSpec(),
242
- ),
243
- rngs: nnx.Rngs | None = None,
244
  ):
 
 
 
 
 
245
  self._config = config
246
- if rngs is None:
247
- # TODO
248
- rngs = nnx.Rngs(0)
249
 
250
  paligemma_config = _gemma.get_config(config.paligemma_variant)
251
  action_expert_config = _gemma.get_config(config.action_expert_variant)
@@ -269,24 +261,25 @@ class Pi0(nnx.Module):
269
  dtype_mm=config.dtype,
270
  )
271
  )
 
272
  self.siglip_vision_model.lazy_init(
273
- gymnasium.vector.utils.batch_space(
274
- config.observation_spec.feature_specs["image"],
275
- n=1,
276
- ).sample(),
277
  train=False,
278
  rngs=rngs,
279
  method="init",
280
  )
281
 
282
  # TODO !!!!! make it named!!!!!!
283
- _, action_dim = config.action_spec["numeric_states"].shape
 
284
 
285
- self.state_proj = nnx.Linear(action_dim, action_expert_config.width, rngs=rngs)
286
- self.action_in_proj = nnx.Linear(action_dim, action_expert_config.width, rngs=rngs)
287
  self.action_time_mlp_in = nnx.Linear(2 * action_expert_config.width, action_expert_config.width, rngs=rngs)
288
  self.action_time_mlp_out = nnx.Linear(action_expert_config.width, action_expert_config.width, rngs=rngs)
289
- self.action_out_proj = nnx.Linear(action_expert_config.width, action_dim, rngs=rngs)
290
 
291
  # NOTE compat
292
  self.PaliGemma = nnx.Dict(
@@ -295,9 +288,22 @@ class Pi0(nnx.Module):
295
  )
296
 
297
  # TODO necesito?
298
- @property
299
- def config(self) -> Config:
300
- return self._config
 
 
 
 
 
 
 
 
 
 
 
 
 
301
 
302
  # @jt.typecheck
303
  def _embed_prefix(
@@ -311,28 +317,38 @@ class Pi0(nnx.Module):
311
  input_masks = []
312
  ar_masks = []
313
 
314
- # TODO !!!!!!
 
315
  # embed images
316
- for name in batch_observation["images"]:
317
  image_embeddings, _ = self.siglip_vision_model(
318
  # TODO
319
- batch_observation["images"][name],
320
  train=False,
321
  )
322
 
323
  embeddings.append(image_embeddings)
324
 
 
 
 
325
  input_masks.append(
326
- # TODO repeat/broadcast only when necessary!!!!!!
 
 
 
 
 
327
  einops.repeat(
328
- batch_observation["images.mask"][name],
329
  "b -> b s",
330
  s=image_embeddings.shape[1],
331
  )
332
  )
333
 
334
  # image tokens attend to each other
335
- ar_masks += [False] * image_embeddings.shape[1]
 
336
 
337
  # add language (aka tokenized inputs)
338
  if batch_observation.get("tokenized_text", None) is not None:
@@ -344,17 +360,18 @@ class Pi0(nnx.Module):
344
 
345
  embeddings.append(language_embeddings)
346
 
347
- input_mask = batch_observation.get("tokenized_text.mask", None)
348
- if input_mask is None:
349
- input_mask = jnp.ones_like(batch_observation["tokenized_text"], dtype=jnp.bool_)
350
- input_masks.append(input_mask)
 
351
 
352
  # full attention between image and language inputs
353
- ar_masks += [False] * language_embeddings.shape[1]
354
 
355
  embeddings = jnp.concatenate(embeddings, axis=1)
356
  input_masks = jnp.concatenate(input_masks, axis=1)
357
- ar_masks = jnp.array(ar_masks)
358
 
359
  return embeddings, input_masks, ar_masks
360
 
@@ -367,7 +384,6 @@ class Pi0(nnx.Module):
367
  timestep: jt.Float[jt.Array, " b"],
368
  ) -> tuple[jt.Float[jt.Array, "b s emb"], jt.Bool[jt.Array, "b s"], jt.Bool[jt.Array, " s"]]:
369
  _, action_horizon, _ = batch_noisy_action["numeric_states"].shape
370
- # print("TODO", batch_noisy_action["numeric_states"].shape)
371
 
372
  input_mask = []
373
  ar_mask = []
@@ -405,10 +421,10 @@ class Pi0(nnx.Module):
405
  # @override
406
  def sample_actions(
407
  self,
408
- rng: jt.PRNGKeyArray, # TODO mv
409
  batch_observation: SpaceVar[ObservationSpec.batched],
410
- # *,
411
- num_steps: int | jt.Int[jt.Array, ""] = 10,
412
  ) -> SpaceVar[ActionSpec.batched]:
413
  # TODO rm
414
  # observation = _model.preprocess_observation(None, observation, train=False)
@@ -416,10 +432,10 @@ class Pi0(nnx.Module):
416
 
417
  # note that we use the convention more common in diffusion literature, where t=1 is noise and t=0 is the target
418
  # distribution. yes, this is the opposite of the pi0 paper, and I'm sorry.
419
- dt = -1.0 / num_steps
420
  batch_size, *_ = batch_observation["numeric_state"].shape
421
- action_horizon, action_dim = self._config.action_spec["numeric_states"].shape
422
- noise = jax.random.normal(rng, (batch_size, action_horizon, action_dim))
423
 
424
  # first fill KV cache with a forward pass of the prefix
425
  prefix_tokens, prefix_mask, prefix_ar_mask = self._embed_prefix(batch_observation)
@@ -427,7 +443,7 @@ class Pi0(nnx.Module):
427
  positions = jnp.cumsum(prefix_mask, axis=1) - 1
428
  _, kv_cache = self.gemma_language_model([prefix_tokens, None], mask=prefix_attn_mask, positions=positions)
429
 
430
- def step(carry):
431
  x_t, time = carry
432
  suffix_tokens, suffix_mask, suffix_ar_mask = self._embed_suffix(
433
  batch_observation, {"numeric_states": x_t}, jnp.broadcast_to(time, batch_size)
@@ -453,15 +469,16 @@ class Pi0(nnx.Module):
453
  [None, suffix_tokens], mask=full_attn_mask, positions=positions, kv_cache=kv_cache
454
  )
455
  assert prefix_out is None
456
- v_t = self.action_out_proj(suffix_out[:, -action_horizon:])
457
 
458
  return x_t + dt * v_t, time + dt
459
 
460
- def cond(carry):
461
  _, time = carry
462
  # robust to floating-point error
463
  return time >= -dt / 2
464
 
 
465
  x_0, _ = jax.lax.while_loop(cond, step, (noise, 1.0))
466
  return {"numeric_states": x_0}
467
 
@@ -469,10 +486,9 @@ class Pi0(nnx.Module):
469
  # @override
470
  def compute_loss(
471
  self,
472
- rng: jt.PRNGKeyArray, # TODO mv
473
  batch_observation: SpaceVar[ObservationSpec.batched],
474
  batch_action: SpaceVar[ActionSpec.batched],
475
- # *,
476
  # train: bool = False,
477
  ) -> jt.Float[jt.Array, "*b ah"]:
478
  # TODO
@@ -502,6 +518,7 @@ class Pi0(nnx.Module):
502
 
503
  return jnp.mean(jnp.square(v_t - u_t), axis=-1)
504
 
 
505
  @functools.cached_property
506
  def trainable_filter(self):
507
  config: Pi0.Config = self._config
@@ -611,6 +628,7 @@ class Pi0Trainer(nnx.Module):
611
  Example usage:
612
  .. code-block:: python
613
 
 
614
  import optax
615
 
616
  model = Pi0()
@@ -619,18 +637,20 @@ class Pi0Trainer(nnx.Module):
619
  optimizer=optax.adam(1e-3),
620
  )
621
  )
 
 
622
  for _ in range(1):
623
  trainer.step(
624
- batch_observation=pi0.config.observation_spec.batched().sample(),
625
- batch_action=pi0.config.action_spec.batched().sample(),
 
626
  )
627
 
628
  """
629
 
630
  @dataclasses.dataclass(frozen=True)
631
  class Config:
632
- # TODO or str
633
- optimizer: optax.GradientTransformation = optax.adam(1e-3)
634
 
635
  @dataclasses.dataclass
636
  class State:
@@ -655,9 +675,9 @@ class Pi0Trainer(nnx.Module):
655
 
656
  def step(
657
  self,
 
658
  batch_observation: SpaceVar[Pi0.ObservationSpec.batched],
659
  batch_action: SpaceVar[Pi0.ActionSpec.batched],
660
- rng: jt.PRNGKeyArray = jax.random.key(0),
661
  ) -> StepResult:
662
 
663
  # TODO
@@ -680,9 +700,8 @@ class Pi0Trainer(nnx.Module):
680
  self._model.train(mode=True)
681
  loss, grads = nnx.value_and_grad(
682
  loss_fn,
683
- # TODO
684
  argnums=nnx.DiffState(0, self._model.trainable_filter),
685
- # argnums=self._model.trainable_filter,
686
  )(
687
  self._model,
688
  rng=rng_train_step,
 
20
 
21
 
22
  # TODO placeholder for now; implement upstream !!!!!
23
+ from typing import Type, Optional # TODO !!!!!
24
  SpaceVar = Type
25
  # ######################################
26
 
 
105
  return jnp.concatenate([jnp.sin(sinusoid_input), jnp.cos(sinusoid_input)], axis=-1)
106
 
107
 
 
108
  class Pi0(nnx.Module):
109
  """
110
  TODO
 
119
  class ObservationSpec(gymnasium.spaces.Dict):
120
  def __init__(
121
  self,
122
+ image_shape: tuple[int, int, int] = (224, 224, 3),
 
 
 
 
 
 
 
123
  numeric_state_size: int = 32,
124
+ image_state_size: int = 3, # TODO flexible
125
+ text_state_size: int = 48, # TODO flexible
126
+ text_vocab_size: int = 257_152, # TODO flexible
127
  ):
128
  """
129
  Observation specification (unbatched).
130
 
131
+ .. note::
132
+ The following parameters CANNOT be changed after the model is constructed:
133
+ - image_shape
134
+ - numeric_state_size
135
+
136
+ :param image_shape: Resolution of input images: (height, width). TODO or width height?
137
+ :param numeric_state_size: Size of numeric state (e.g. number of motor positions).
138
+ :param image_state_size: Maximum number of images within a state. (Flexible)
139
+ :param text_state_size: Maximum length of text tokens within a state. (Flexible)
140
+ :param text_vocab_size: Size of text vocabulary. Infinite if :class:`None`. (Flexible)
141
 
142
  .. seealso::
143
  Default values from the official Pi0 implementation:
 
148
  - `numeric_state_size <https://github.com/Physical-Intelligence/openpi/blob/84cd4dc87854856a4fd878cc8951cbc59023eaa7/src/openpi/models/pi0.py#L74>`_
149
  """
150
 
151
+ super().__init__({
152
+ "images": gymnasium.spaces.Box(
153
  low=-1., high=1.,
154
+ shape=(image_state_size, *image_shape),
155
  dtype=numpy.float32,
156
+ ),
157
+ "images.mask": gymnasium.spaces.Box(
158
+ low=0, high=1,
159
+ shape=(image_state_size, ), # TODO
160
+ dtype=numpy.uint8,
161
+ ),
 
 
 
 
 
 
 
 
 
 
162
  "tokenized_text": gymnasium.spaces.Box(
163
+ low=0, high=(text_vocab_size - 1),
164
+ shape=(text_state_size, ), # TODO
 
 
 
 
 
165
  dtype=numpy.int32,
166
  ),
167
  "tokenized_text.mask": gymnasium.spaces.Box(
168
  low=0, high=1,
169
+ shape=(text_state_size, ), # TODO
170
  dtype=numpy.uint8,
171
  ),
172
  "numeric_state": gymnasium.spaces.Box(
 
184
  def __init__(
185
  self,
186
  numeric_state_size: int = 32,
187
+ numeric_state_horizon: int = 50, # TODO flexible
188
  ):
189
  """
190
  Action specification (unbatched).
191
 
192
+ .. note::
193
+ The following parameters CANNOT be changed after the model is constructed:
194
+ - numeric_state_size
195
+
196
  :param numeric_state_size: Size of numeric state (e.g. number of motor positions).
197
+ :param numeric_state_horizon: The number of future states to predict. (Flexible)
198
 
199
  .. seealso::
200
  Default values from the official Pi0 implementation:
 
214
  def batched(self, batch_size: int = 1):
215
  return gymnasium.vector.utils.batch_space(self, n=batch_size)
216
 
217
+ # TODO make it TypedDict to support pytree?
218
  @dataclasses.dataclass(frozen=True)
219
  class Config:
220
+ # TODO
221
+ image_shape: tuple[int, int, int] = (224, 224, 3)
222
+ """TODO doc"""
223
+ numeric_state_size: int = 32
224
+ """TODO doc"""
225
 
226
  dtype: str = "bfloat16"
227
  paligemma_variant: _gemma.Variant = "gemma_2b"
 
229
 
230
  def __init__(
231
  self,
232
+ rngs: nnx.Rngs,
233
+ config: Config = Config(),
 
 
 
234
  ):
235
+ """
236
+ TODO doc
237
+
238
+ """
239
+
240
  self._config = config
 
 
 
241
 
242
  paligemma_config = _gemma.get_config(config.paligemma_variant)
243
  action_expert_config = _gemma.get_config(config.action_expert_variant)
 
261
  dtype_mm=config.dtype,
262
  )
263
  )
264
+ # TODO
265
  self.siglip_vision_model.lazy_init(
266
+ # TODO NOTE the batch size isnt actually correct; but the model only cares about the image shape
267
+ # config.observation_spec["images"].sample(),
268
+ jnp.empty((1, *config.image_shape)),
 
269
  train=False,
270
  rngs=rngs,
271
  method="init",
272
  )
273
 
274
  # TODO !!!!! make it named!!!!!!
275
+ # _, action_dim = config.action_spec["numeric_states"].shape
276
+ # action_dim = config.state_proj_features
277
 
278
+ self.state_proj = nnx.Linear(config.numeric_state_size, action_expert_config.width, rngs=rngs)
279
+ self.action_in_proj = nnx.Linear(config.numeric_state_size, action_expert_config.width, rngs=rngs)
280
  self.action_time_mlp_in = nnx.Linear(2 * action_expert_config.width, action_expert_config.width, rngs=rngs)
281
  self.action_time_mlp_out = nnx.Linear(action_expert_config.width, action_expert_config.width, rngs=rngs)
282
+ self.action_out_proj = nnx.Linear(action_expert_config.width, config.numeric_state_size, rngs=rngs)
283
 
284
  # NOTE compat
285
  self.PaliGemma = nnx.Dict(
 
288
  )
289
 
290
  # TODO necesito?
291
+ # @property
292
+ # def config(self) -> Config:
293
+ # return self._config
294
+
295
+ def observation_spec(self, **kwds):
296
+ return self.ObservationSpec(
297
+ image_shape=self._config.image_shape,
298
+ numeric_state_size=self._config.numeric_state_size,
299
+ **kwds,
300
+ )
301
+
302
+ def action_spec(self, **kwds):
303
+ return self.ActionSpec(
304
+ numeric_state_size= self._config.numeric_state_size,
305
+ **kwds,
306
+ )
307
 
308
  # @jt.typecheck
309
  def _embed_prefix(
 
317
  input_masks = []
318
  ar_masks = []
319
 
320
+ # TODO optimize
321
+ # TODO NOTE !!!!!! batch is the first dim !!!!!
322
  # embed images
323
+ for image_index in range(batch_observation["images"].shape[1]):
324
  image_embeddings, _ = self.siglip_vision_model(
325
  # TODO
326
+ batch_observation["images"][:, image_index],
327
  train=False,
328
  )
329
 
330
  embeddings.append(image_embeddings)
331
 
332
+ # TODO ...
333
+ # einops.parse_shape(image_embeddings.shape)
334
+
335
  input_masks.append(
336
+ jnp.full(
337
+ (image_embeddings.shape[0], image_embeddings.shape[1]),
338
+ True,
339
+ dtype=jnp.bool,
340
+ )
341
+ if batch_observation.get("images.mask", None) is None else
342
  einops.repeat(
343
+ batch_observation["images.mask"][:, image_index],
344
  "b -> b s",
345
  s=image_embeddings.shape[1],
346
  )
347
  )
348
 
349
  # image tokens attend to each other
350
+ # TODO
351
+ ar_masks.append(jnp.full(image_embeddings.shape[1], False))
352
 
353
  # add language (aka tokenized inputs)
354
  if batch_observation.get("tokenized_text", None) is not None:
 
360
 
361
  embeddings.append(language_embeddings)
362
 
363
+ input_masks.append(
364
+ jnp.full(batch_observation["tokenized_text"], True, dtype=jnp.bool)
365
+ if batch_observation.get("tokenized_text.mask", None) is None else
366
+ batch_observation["tokenized_text.mask"]
367
+ )
368
 
369
  # full attention between image and language inputs
370
+ ar_masks.append(jnp.full(language_embeddings.shape[1], False))
371
 
372
  embeddings = jnp.concatenate(embeddings, axis=1)
373
  input_masks = jnp.concatenate(input_masks, axis=1)
374
+ ar_masks = jnp.concatenate(ar_masks)
375
 
376
  return embeddings, input_masks, ar_masks
377
 
 
384
  timestep: jt.Float[jt.Array, " b"],
385
  ) -> tuple[jt.Float[jt.Array, "b s emb"], jt.Bool[jt.Array, "b s"], jt.Bool[jt.Array, " s"]]:
386
  _, action_horizon, _ = batch_noisy_action["numeric_states"].shape
 
387
 
388
  input_mask = []
389
  ar_mask = []
 
421
  # @override
422
  def sample_actions(
423
  self,
424
+ rng: jt.PRNGKeyArray,
425
  batch_observation: SpaceVar[ObservationSpec.batched],
426
+ num_actions: int = 1,
427
+ diffusion_num_steps: int | jt.Int[jt.Array, ""] = 10,
428
  ) -> SpaceVar[ActionSpec.batched]:
429
  # TODO rm
430
  # observation = _model.preprocess_observation(None, observation, train=False)
 
432
 
433
  # note that we use the convention more common in diffusion literature, where t=1 is noise and t=0 is the target
434
  # distribution. yes, this is the opposite of the pi0 paper, and I'm sorry.
435
+ dt = -1.0 / diffusion_num_steps
436
  batch_size, *_ = batch_observation["numeric_state"].shape
437
+ # TODO rm?
438
+ # action_horizon, action_dim = self._config.action_spec["numeric_states"].shape
439
 
440
  # first fill KV cache with a forward pass of the prefix
441
  prefix_tokens, prefix_mask, prefix_ar_mask = self._embed_prefix(batch_observation)
 
443
  positions = jnp.cumsum(prefix_mask, axis=1) - 1
444
  _, kv_cache = self.gemma_language_model([prefix_tokens, None], mask=prefix_attn_mask, positions=positions)
445
 
446
+ def step(carry: tuple[float, float]):
447
  x_t, time = carry
448
  suffix_tokens, suffix_mask, suffix_ar_mask = self._embed_suffix(
449
  batch_observation, {"numeric_states": x_t}, jnp.broadcast_to(time, batch_size)
 
469
  [None, suffix_tokens], mask=full_attn_mask, positions=positions, kv_cache=kv_cache
470
  )
471
  assert prefix_out is None
472
+ v_t = self.action_out_proj(suffix_out[:, -num_actions:])
473
 
474
  return x_t + dt * v_t, time + dt
475
 
476
+ def cond(carry: tuple[float, float]):
477
  _, time = carry
478
  # robust to floating-point error
479
  return time >= -dt / 2
480
 
481
+ noise = jax.random.normal(rng, (batch_size, num_actions, self.action_out_proj.out_features))
482
  x_0, _ = jax.lax.while_loop(cond, step, (noise, 1.0))
483
  return {"numeric_states": x_0}
484
 
 
486
  # @override
487
  def compute_loss(
488
  self,
489
+ rng: jt.PRNGKeyArray,
490
  batch_observation: SpaceVar[ObservationSpec.batched],
491
  batch_action: SpaceVar[ActionSpec.batched],
 
492
  # train: bool = False,
493
  ) -> jt.Float[jt.Array, "*b ah"]:
494
  # TODO
 
518
 
519
  return jnp.mean(jnp.square(v_t - u_t), axis=-1)
520
 
521
+ # TODO
522
  @functools.cached_property
523
  def trainable_filter(self):
524
  config: Pi0.Config = self._config
 
628
  Example usage:
629
  .. code-block:: python
630
 
631
+ import jax
632
  import optax
633
 
634
  model = Pi0()
 
637
  optimizer=optax.adam(1e-3),
638
  )
639
  )
640
+
641
+ rng = jax.random.key(0)
642
  for _ in range(1):
643
  trainer.step(
644
+ rng=rng,
645
+ batch_observation=pi0.observation_spec().batched().sample(),
646
+ batch_action=pi0.action_spec().batched().sample(),
647
  )
648
 
649
  """
650
 
651
  @dataclasses.dataclass(frozen=True)
652
  class Config:
653
+ optimizer: optax.GradientTransformation = Pi0OptimizerRecipes.sgd()
 
654
 
655
  @dataclasses.dataclass
656
  class State:
 
675
 
676
  def step(
677
  self,
678
+ rng: jt.PRNGKeyArray,
679
  batch_observation: SpaceVar[Pi0.ObservationSpec.batched],
680
  batch_action: SpaceVar[Pi0.ActionSpec.batched],
 
681
  ) -> StepResult:
682
 
683
  # TODO
 
700
  self._model.train(mode=True)
701
  loss, grads = nnx.value_and_grad(
702
  loss_fn,
703
+ # TODO simplify?
704
  argnums=nnx.DiffState(0, self._model.trainable_filter),
 
705
  )(
706
  self._model,
707
  rng=rng_train_step,
packages/robotodo/controllers/pi0/paligemma_tokenizer.py DELETED
@@ -1,39 +0,0 @@
1
-
2
- import warnings
3
-
4
- import fsspec
5
- import sentencepiece
6
- # TODO jax?
7
- import numpy as np
8
-
9
-
10
- class PaligemmaTokenizer:
11
- def __init__(self, max_len: int = 48):
12
- self._max_len = max_len
13
-
14
- # TODO better handling
15
- url = "simplecache::gs://big_vision/paligemma_tokenizer.model"
16
- with fsspec.open(url, mode="rb", token="anon") as f:
17
- self._tokenizer = sentencepiece.SentencePieceProcessor(model_proto=f.read())
18
-
19
- # TODO
20
- def tokenize(self, prompt: str) -> tuple[np.ndarray, np.ndarray]:
21
- cleaned_text = prompt.strip().replace("_", " ").replace("\n", " ")
22
- # tokenize "\n" separately as the "start of answer" token
23
- tokens = self._tokenizer.Encode(cleaned_text, add_bos=True) + self._tokenizer.Encode("\n")
24
- tokens_len = len(tokens)
25
- if tokens_len < self._max_len:
26
- padding = [False] * (self._max_len - tokens_len)
27
- mask = [True] * tokens_len + padding
28
- tokens = tokens + padding
29
- else:
30
- if len(tokens) > self._max_len:
31
- warnings.warn(
32
- f"Token length ({len(tokens)}) exceeds max length ({self._max_len}), truncating. "
33
- "Consider increasing the `max_token_len` in your model config if this happens frequently."
34
- )
35
- tokens = tokens[: self._max_len]
36
- mask = [True] * self._max_len
37
-
38
- # TODO mask necesito???
39
- return np.asarray(tokens), np.asarray(mask)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/robotodo/controllers/pi0/pi0_controller.py CHANGED
@@ -1,13 +1,18 @@
1
 
 
 
 
 
2
 
3
- from typing import TypedDict
4
-
5
  # TODO
6
  import gymnasium.spaces
 
7
 
8
 
9
  from .nn.pi0 import Pi0, Pi0Trainer
10
- from .paligemma_tokenizer import PaligemmaTokenizer
11
 
12
 
13
 
@@ -17,55 +22,467 @@ SpaceVar = Type
17
  # ######################################
18
 
19
 
20
-
21
  # TODO
22
  class Pi0Controller:
 
 
 
 
 
23
  class ObservationSpec(gymnasium.spaces.Dict):
24
  def __init__(
25
  self,
26
- image_names: list[str] = [],
27
- image_size: tuple[int, int] = (64, 64),
28
- text_max_len: int = 32,
29
- ):
30
- super().__init__({
31
- "images": gymnasium.spaces.Dict({
32
  # TODO rescaling !!!!!!!
33
  name: gymnasium.spaces.Box(
 
34
  low=0., high=1.,
35
- shape=(*image_size, 3),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  )
37
- for name in image_names
38
  }),
39
- "text": gymnasium.spaces.Text(max_length=text_max_len),
40
- # TODO
41
- # "numeric_state": gymnasium.spaces.Box(
42
- # )
 
43
  })
44
 
 
45
  # TODO deprecate this once we have StackedSequence StackedTuple !!!!!!
46
  def batched(self, batch_size: int = 1):
47
  return gymnasium.vector.utils.batch_space(self, n=batch_size)
48
 
 
49
  class ActionSpec(gymnasium.spaces.Dict):
50
- def __init__(self):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  # TODO
52
- super().__init__({})
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
 
 
 
54
 
55
- class Config(TypedDict):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
- ...
 
 
 
 
 
 
 
 
 
 
 
58
 
59
- def __init__(self):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  # TODO
61
- self._nn = Pi0()
62
- # TODO max len
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  self._tokenizer = PaligemmaTokenizer()
64
 
 
 
 
 
 
 
 
 
 
 
65
  @property
66
  def nn(self):
67
  return self._nn
68
 
69
- # TODO
70
- def compute_action(self, observation: SpaceVar[ObservationSpec.batched] | SpaceVar[ObservationSpec]):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  raise NotImplementedError
 
 
 
 
 
 
 
1
 
2
+ import warnings
3
+ import dataclasses
4
+ import itertools
5
+ from typing import Any, Callable, Protocol, TypedDict
6
 
7
+ import jax
8
+ import jaxtyping as jt
9
  # TODO
10
  import gymnasium.spaces
11
+ import gymnasium.spaces.utils
12
 
13
 
14
  from .nn.pi0 import Pi0, Pi0Trainer
15
+ from .nn.paligemma_tokenizer import PaligemmaTokenizer
16
 
17
 
18
 
 
22
  # ######################################
23
 
24
 
 
25
  # TODO
26
  class Pi0Controller:
27
+ """
28
+ TODO doc
29
+
30
+ """
31
+
32
  class ObservationSpec(gymnasium.spaces.Dict):
33
  def __init__(
34
  self,
35
+ # TODO NOTE currently typing does not work due to gymnasium
36
+ images: "gymnasium.spaces.Dict[Any, gymnasium.spaces.Box] | gymnasium.spaces.Box"
37
+ = gymnasium.spaces.Dict({
 
 
 
38
  # TODO rescaling !!!!!!!
39
  name: gymnasium.spaces.Box(
40
+ # TODO make customizable
41
  low=0., high=1.,
42
+ shape=(224, 224, 3),
43
+ )
44
+ for name in (
45
+ "base_0_rgb",
46
+ "left_wrist_0_rgb",
47
+ "right_wrist_0_rgb",
48
+ )
49
+ }),
50
+ text: gymnasium.spaces.Text = gymnasium.spaces.Text(max_length=48),
51
+ # TODO
52
+ joint_state: "gymnasium.spaces.Space[float]"
53
+ = gymnasium.spaces.Dict({
54
+ # TODO
55
+ name: gymnasium.spaces.Box(
56
+ low=-float("inf"), high=float("inf"),
57
+ shape=(),
58
+ )
59
+ # TODO !!!!!
60
+ for name in (
61
+ "todo",
62
+ "todo2",
63
  )
 
64
  }),
65
+ ):
66
+ super().__init__({
67
+ "images": images,
68
+ "text": text,
69
+ "joint_state": joint_state,
70
  })
71
 
72
+ # TODO api to check if batched
73
  # TODO deprecate this once we have StackedSequence StackedTuple !!!!!!
74
  def batched(self, batch_size: int = 1):
75
  return gymnasium.vector.utils.batch_space(self, n=batch_size)
76
 
77
+ # TODO
78
  class ActionSpec(gymnasium.spaces.Dict):
79
+ def __init__(
80
+ self,
81
+ # TODO instead: BoxSpec(shape={...: ..., "time": ..., "joint_index": ...}, indices={"joint_index": (...)})
82
+ # TODO
83
+ joint_state: "gymnasium.spaces.Dict"
84
+ = gymnasium.spaces.Dict({
85
+ # TODO
86
+ name: gymnasium.spaces.Box(
87
+ low=-float("inf"), high=float("inf"),
88
+ shape=(),
89
+ )
90
+ # TODO !!!!!
91
+ for name in (
92
+ "todo",
93
+ "todo2",
94
+ )
95
+ }),
96
+ ):
97
  # TODO
98
+ super().__init__({
99
+ # TODO upstream impl: BatchSpec(joint_state, length=num_entries)
100
+ # "joint_states": gymnasium.vector.utils.batch_space(
101
+ # joint_state, n=num_timesteps,
102
+ # ),
103
+ "joint_states": gymnasium.spaces.Sequence(
104
+ joint_state, # length=...,
105
+ )
106
+ })
107
+
108
+ # TODO api to check if batched
109
+ # TODO deprecate this once we have StackedSequence StackedTuple !!!!!!
110
+ def batched(self, batch_size: int = 1):
111
+ return gymnasium.vector.utils.batch_space(self, n=batch_size)
112
 
113
+ class _ImageTransformCallable(Protocol):
114
+ def __call__(self, batch_image: jt.Array, target_shape: tuple[int, int, int]) -> jt.Array:
115
+ ...
116
 
117
+ class _TextTokenizerCallable(Protocol):
118
+ def __call__(self, batch_text: list[str], max_len: int) -> tuple[jt.Array, jt.Array]:
119
+ ...
120
+
121
+ # TODO
122
+ @staticmethod
123
+ def _encode_observation(
124
+ # TODO
125
+ target_spec: Pi0.ObservationSpec,
126
+ source_spec: "Pi0Controller.ObservationSpec",
127
+ #
128
+ batch: SpaceVar["Pi0Controller.ObservationSpec.batched"],
129
+ image_transform: _ImageTransformCallable,
130
+ text_tokenizer: _TextTokenizerCallable,
131
+ # TODO
132
+ # strict: bool = False,
133
+ ) -> SpaceVar["Pi0.ObservationSpec.batched"]:
134
+ """
135
+ TODO doc
136
+ """
137
+
138
+ # TODO
139
+ # source_spec["images"].resolve(batch)
140
+
141
+ # TODO
142
+ batch_images = []
143
+ batch_images_mask = []
144
+ # TODO image (-1, 1) rescaling!!!!!
145
+ # TODO upstream: gymnasium.spaces.Box needs to allow __getitem__!!!@! to make this less confusing
146
+ _, *target_shape = target_spec["images"].shape
147
+ # TODO FIXME NOTE very hacky way to get batch size due to gymnasium !!!!!! should be able to just do SequenceSpec().len(data)
148
+ for image_key, _ in batch["images"].items():
149
+ batch_size_images, *_ = batch["images"][image_key].shape
150
+ # ###################
151
+ # TODO readability: SequenceSpec.flatten(target_spec["images"], source_spec["images"], batch["images"])
152
+ for image_key, image_spec in source_spec["images"].items():
153
+ batch_images.append(
154
+ image_transform(batch["images"][image_key], target_shape)
155
+ if image_key in batch["images"] else
156
+ # NOTE the content of the image is not important as it's masked anyways
157
+ jax.numpy.empty((batch_size_images, *target_shape), dtype=image_spec.dtype)
158
+ )
159
+ batch_images_mask.append(
160
+ jax.numpy.full((batch_size_images, ), fill_value=(image_key in batch["images"]))
161
+ )
162
+ # TODO
163
+ batch_images = jax.numpy.stack(batch_images, axis=1)
164
+ batch_images_mask = jax.numpy.stack(batch_images_mask, axis=1)
165
+
166
+ # TODO max_len !!!!!! enforce equal len????
167
+ tokenized_text, tokenized_text_mask = text_tokenizer(
168
+ batch["text"],
169
+ # TODO !!!!
170
+ target_spec["tokenized_text"].shape[0],
171
+ )
172
+
173
+ # TODO enforce equal len???
174
+ numeric_state = gymnasium.spaces.utils.flatten(
175
+ gymnasium.spaces.Sequence(source_spec["joint_state"], stack=True),
176
+ batch["joint_state"],
177
+ )
178
+ # TODO trunc & pad !!!!!!!!!
179
+ # # numeric_state[:, target_spec["numeric_state"].shape[0]:]
180
+ # TODO readability
181
+ # TODO upstream: SequenceSpec.truncate(...)
182
+ # TODO upstream: SequenceSpec.pad(target_spec["numeric_state"], source_spec["numeric_state"], data, fill_value=0.)
183
+ # TODO upstream: .unpad?
184
+ numeric_state = jax.numpy.pad(
185
+ numeric_state,
186
+ [(0, 0), (0, target_spec["numeric_state"].shape[0] - numeric_state.shape[1])],
187
+ constant_values=0.,
188
+ )
189
+
190
+ # TODO sanity check???
191
+
192
+ res = {
193
+ "images": batch_images,
194
+ "images.mask": batch_images_mask,
195
+ "tokenized_text": tokenized_text,
196
+ "tokenized_text.mask": tokenized_text_mask,
197
+ "numeric_state": numeric_state,
198
+ }
199
+ # TODO FIXME: doing this bc gymnasium doesnt have cast!!!!! or validate!!!!!!
200
+ return {
201
+ key: jax.numpy.asarray(value, dtype=target_spec[key].dtype)
202
+ for key, value in res.items()
203
+ }
204
+
205
+ # TODO next
206
+ @staticmethod
207
+ def _todo_encode_observation(
208
+ # TODO
209
+ target_spec: Pi0.ObservationSpec,
210
+ source_spec: "Pi0Controller.ObservationSpec",
211
+ #
212
+ batch: SpaceVar["Pi0Controller.ObservationSpec.batched"],
213
+ image_transform: _ImageTransformCallable,
214
+ text_tokenizer: _TextTokenizerCallable,
215
+ # TODO
216
+ # strict: bool = False,
217
+ ) -> SpaceVar["Pi0.ObservationSpec.batched"]:
218
+ """
219
+ TODO doc
220
+ """
221
+
222
+ # TODO
223
+ # source_spec["images"].resolve(batch)
224
+
225
+ batch_size = ...
226
+ # TODO FIXME very hacky way to get batch size due to gymnasium !!!!!! should be able to just do SequenceSpec().len(batch)
227
+ batch_size = len(batch["text"])
228
+
229
+ res = {}
230
+
231
+ res["images"] = jax.numpy.empty(target_spec.batched(batch_size)["images"].shape)
232
+ res["images.mask"] = jax.numpy.full(target_spec.batched(batch_size)["images.mask"].shape, False)
233
+ for index, (image_key, image_spec) in enumerate(source_spec["images"].items()):
234
+ # TODO use image_spec for validation???
235
+ if image_key not in batch["images"]:
236
+ continue
237
+ res["images"] = res["images"].at[:, index].set(
238
+ image_transform(
239
+ batch["images"][image_key],
240
+ res["images"].shape[-3:],
241
+ # target_spec["images"].shape_of(
242
+ # res["images"],
243
+ # (..., "width", "height", "channels"),
244
+ # )
245
+ )
246
+ )
247
+ res["images.mask"] = res["images.mask"].at[:, index].set(True)
248
+
249
+ # TODO
250
+ res["tokenized_text"] = jax.numpy.empty(
251
+ target_spec.batched(batch_size)["tokenized_text"].shape
252
+ )
253
+ res["tokenized_text.mask"] = jax.numpy.full(
254
+ target_spec.batched(batch_size)["tokenized_text.mask"].shape,
255
+ False,
256
+ )
257
+ for index, tokens in enumerate(text_tokenizer(batch["text"])):
258
+ if (source_len := len(tokens)) > (target_len := len(res["tokenized_text"][index])):
259
+ warnings.warn(
260
+ f"Tokenized text at index {index} "
261
+ f"has length {source_len} > {target_len}, truncating: "
262
+ f"{tokens}"
263
+ )
264
+ res["tokenized_text"] = (
265
+ res["tokenized_text"].at[index, :len(tokens)].set(tokens)
266
+ )
267
+ res["tokenized_text.mask"] = (
268
+ res["tokenized_text.mask"].at[index, :len(tokens)].set(True)
269
+ )
270
+
271
+ # TODO rm: no magic
272
+ # res["tokenized_text"], res["tokenized_text.mask"] = target_spec["tokenized_text"].replace(
273
+ # res["tokenized_text"],
274
+ # text_tokenizer(batch["text"]),
275
+ # # offset=...,
276
+ # # return_mask=True,
277
+ # )
278
+ # res["tokenized_text"].at[...].set(tokenized_text)
279
+ # res["tokenized_text.mask"].at[..., len(tokenized_text):].set(True)
280
+
281
+ res["numeric_state"] = jax.numpy.full(target_spec.batched(batch_size)["numeric_state"].shape, 0.)
282
+ for index, (joint_key, joint_spec) in enumerate(source_spec["joint_state"].items()):
283
+ # TODO !!!!!
284
+ if joint_key not in batch["joint_state"]:
285
+ raise ValueError(f"Missing joint state {joint_key} in batch")
286
+ res["numeric_state"] = res["numeric_state"].at[:, index].set(batch["joint_state"][joint_key])
287
 
288
+ # TODO rm??
289
+ # numeric_state = gymnasium.spaces.utils.flatten(
290
+ # source_spec.batched(batch_size)["joint_state"],
291
+ # batch["joint_state"],
292
+ # )
293
+ # res["numeric_state"] = (
294
+ # jax.numpy.full(target_spec.batched(batch_size)["numeric_state"].shape, 0.)
295
+ # .at[tuple(slice(0, s) for s in numeric_state.shape)]
296
+ # .set(numeric_state)
297
+ # )
298
+
299
+ return res
300
 
301
+
302
+ @staticmethod
303
+ def _encode_action(
304
+ target_spec: Pi0.ActionSpec,
305
+ source_spec: "Pi0Controller.ActionSpec",
306
+ batch: SpaceVar["Pi0Controller.ActionSpec.batched"],
307
+ ):
308
+ # TODO new syntax? "... height width channels"
309
+ # TODO BoxSpec(shape=("*", 3, 3, 5)) # -1 | "*": any shape; None: variable shape; ...: any num of shapes
310
+ # TODO truncate/pad !!!!!!! pad_to(..., target_spec["numeric_states"].shape)
311
+
312
+ # TODO -or- handle the missing keys here???
313
+ numeric_states = gymnasium.spaces.utils.flatten(
314
+ source_spec.batched(len(batch))["joint_states"],
315
+ batch["joint_states"],
316
+ )
317
+
318
+ # TODO ensure consistent dims
319
+ numeric_states = jax.numpy.asarray(numeric_states)
320
+
321
+ numeric_states = (
322
+ jax.numpy.full(
323
+ target_spec.batched(len(batch))["numeric_states"].shape,
324
+ fill_value=0.,
325
+ )
326
+
327
+ # .at[(..., ) + tuple(
328
+ # slice(0, s)
329
+ # # TODO instead: target_spec["joint_states"].flatten()
330
+ # # TODO target_spec["joint_states"].batch()
331
+ # for s in gymnasium.spaces.utils.flatten_space(
332
+ # source_spec["joint_states"].feature_space,
333
+ # ).shape
334
+ # )]
335
+
336
+ .at[tuple(
337
+ slice(0, s)
338
+ for s in numeric_states.shape
339
+ )]
340
+ .set(numeric_states)
341
+ )
342
+
343
+ return {
344
+ "numeric_states": numeric_states,
345
+ }
346
+
347
+ # TODO rm
348
+ # return {
349
+ # "numeric_states": gymnasium.spaces.utils.flatten(
350
+ # source_spec["joint_states"],
351
+ # maybe_batch["joint_states"],
352
+ # ),
353
+ # }
354
+
355
+ # TODO truncate/pad !!!!!!!
356
+ @staticmethod
357
+ def _decode_action(
358
+ target_spec: "Pi0Controller.ActionSpec",
359
+ source_spec: Pi0.ActionSpec,
360
+ batch: SpaceVar["Pi0.ActionSpec.batched"],
361
+ ):
362
  # TODO
363
+ """
364
+ TODO
365
+
366
+
367
+ """
368
+
369
+ # TODO order keys !!!!!!
370
+
371
+ # TODO detect maybe_batch action horizon
372
+
373
+ joint_states = (
374
+ jax.numpy.asarray(batch["numeric_states"])
375
+ # TODO
376
+ .at[(..., ) + tuple(
377
+ slice(0, s)
378
+ # TODO instead: target_spec["joint_states"].flatten()
379
+ # TODO target_spec["joint_states"].batch()
380
+ for s in gymnasium.spaces.utils.flatten_space(
381
+ target_spec["joint_states"].feature_space,
382
+ ).shape #[-1]
383
+ )]
384
+ .get()
385
+ )
386
+ joint_states = gymnasium.spaces.utils.unflatten(
387
+ target_spec.batched(len(batch))["joint_states"],
388
+ # TODO NOTE gymnasium expects tuple as specified in spec
389
+ tuple(joint_states),
390
+ )
391
+
392
+ return {
393
+ "joint_states": joint_states,
394
+ }
395
+
396
+ # TODO rm
397
+ # return {
398
+ # "joint_states": gymnasium.spaces.utils.unflatten(
399
+ # target_spec["joint_states"],
400
+ # maybe_batch["numeric_states"],
401
+ # ),
402
+ # }
403
+
404
+ class Config(TypedDict):
405
+ observation_spec: "Pi0Controller.ObservationSpec"
406
+ action_spec: "Pi0Controller.ActionSpec"
407
+
408
+ # TODO
409
+ def __init__(self, config: Config = Config(
410
+ observation_spec=ObservationSpec(),
411
+ action_spec=ActionSpec(),
412
+ )):
413
+ self._config = config
414
+
415
  self._tokenizer = PaligemmaTokenizer()
416
 
417
+ # TODO !!!!!
418
+ # TODO the specs maybe determined directly by nn
419
+ # TODO NOTE pipeline: input -> transformation -> nn
420
+ import flax.nnx
421
+
422
+ self._nn = Pi0(
423
+ rngs=flax.nnx.Rngs(0), # TODO
424
+ # config=Pi0.Config(...),
425
+ )
426
+
427
  @property
428
  def nn(self):
429
  return self._nn
430
 
431
+ # TODO | SpaceVar[ObservationSpec]
432
+ def compute_action(
433
+ self,
434
+ maybe_batch_observation: SpaceVar[ObservationSpec.batched], # TODO or non-batched
435
+ rng: jt.PRNGKeyArray | None = None,
436
+ num_actions: int = 1,
437
+ diffusion_num_steps: int = 10,
438
+ ):
439
+ rng = rng or jax.random.key(0)
440
+
441
+ batch_observation_nn = Pi0Controller._encode_observation(
442
+ # TODO
443
+ target_spec=self._nn.observation_spec(),
444
+ source_spec=self._config["observation_spec"],
445
+ batch=maybe_batch_observation,
446
+ # TODO !!!!!!!!!! image_transform
447
+ image_transform=(
448
+ lambda batch_image, target_shape:
449
+ # TODO channel
450
+ jax.image.resize(
451
+ batch_image,
452
+ shape=(batch_image.shape[0], *target_shape),
453
+ method="linear", # TODO make configurable
454
+ )
455
+ ),
456
+ text_tokenizer=(
457
+ lambda texts, max_len, self=self:
458
+ # TODO vectorize this!!!!!
459
+ self._tokenizer.__call__(texts, max_len)
460
+ ),
461
+ )
462
+
463
+ batch_actions_nn = self._nn.sample_actions(
464
+ rng=rng,
465
+ batch_observation=batch_observation_nn,
466
+ num_actions=num_actions,
467
+ diffusion_num_steps=diffusion_num_steps,
468
+ )
469
+
470
+ return Pi0Controller._decode_action(
471
+ target_spec=self._config["action_spec"],
472
+ source_spec=self._nn.action_spec(),
473
+ maybe_batch=batch_actions_nn,
474
+ )
475
+
476
+ # TODO !!!!!
477
+ def learn(
478
+ self,
479
+ maybe_batch_observation: SpaceVar[ObservationSpec.batched], # TODO or non-batched,
480
+ maybe_batch_action: SpaceVar[ActionSpec.batched], # TODO or non-batched,
481
+ ):
482
  raise NotImplementedError
483
+
484
+
485
+ __all__ = [
486
+ "Pi0Controller",
487
+ ]
488
+
packages/robotodo/controllers/pi0/test_pi0_controller.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from robotodo.controllers.pi0 import Pi0Controller
2
+ from robotodo.controllers.pi0.nn.pi0 import Pi0
3
+
4
+
5
+ class TestPi0Controller:
6
+
7
+ def test_encode_decode_action(self):
8
+ nn_action_spec = Pi0.ActionSpec()
9
+ controller_action_spec = Pi0Controller.ActionSpec()
10
+
11
+ true_action = controller_action_spec.sample()
12
+
13
+ decoded_action = Pi0Controller._decode_action(
14
+ target_spec=controller_action_spec,
15
+ source_spec=nn_action_spec,
16
+ maybe_batch=Pi0Controller._encode_action(
17
+ target_spec=nn_action_spec,
18
+ source_spec=controller_action_spec,
19
+ maybe_batch=true_action,
20
+ ),
21
+ )
22
+
23
+ # TODO !!!!!!
24
+ assert decoded_action == true_action, "Decoded action does not match the original action."
25
+
26
+ def test_encode_decode_action_batched(self):
27
+ nn_action_spec = Pi0.ActionSpec().batched()
28
+ controller_action_spec = Pi0Controller.ActionSpec().batched()
29
+
30
+ true_action = controller_action_spec.sample()
31
+
32
+ decoded_action = Pi0Controller._decode_action(
33
+ target_spec=controller_action_spec,
34
+ source_spec=nn_action_spec,
35
+ maybe_batch=Pi0Controller._encode_action(
36
+ target_spec=nn_action_spec,
37
+ source_spec=controller_action_spec,
38
+ maybe_batch=true_action,
39
+ ),
40
+ )
41
+
42
+ # TODO !!!!!!
43
+ assert decoded_action == true_action, "Decoded action does not match the original action."
packages/robotodo/scenes/robotwin_labs/__init__.py CHANGED
@@ -106,65 +106,78 @@ def _todo_get_plain_render_material(color=(1, 1, 1)) -> sapien.render.RenderMate
106
 
107
 
108
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  def _todo_create_observer_camera(scene: sapien.Scene):
110
  import numpy
111
 
112
- # near, far = 0.1, 100
113
- # width, height = 640, 480
114
- # camera = self.scene.add_camera(
115
- # # TODO
116
- # name="camera",
117
- # width=width,
118
- # height=height,
119
- # fovy=numpy.deg2rad(90),
120
- # near=near,
121
- # far=far,
122
- # )
123
- # camera.set_pose(sapien.Pose(p=[1, 0, 0]))
124
-
125
- # observer camera
126
- import numpy as np
127
-
128
- observer_camera = scene.add_camera(
129
- name="observer_camera",
130
- width=640,
131
- height=480,
132
- fovy=np.deg2rad(93),
133
- near=.1,
134
- far=100,
135
  )
136
- # TODO
137
- # observer_cam_pos = np.array([0.0, -0.23, 1.33])
138
- observer_cam_pos = np.array([0.0, 0.5, 1.5])
139
- # observer_cam_forward = np.array([0, -1, -1.02])
140
- observer_cam_forward = np.array([0, -2, -1.02])
141
- # observer_cam_left = np.array([1,-1, 0])
142
- observer_cam_left = np.array([1, 0, 0])
143
- observer_up = np.cross(observer_cam_forward, observer_cam_left)
144
- observer_mat44 = np.eye(4)
145
- observer_mat44[:3, :3] = np.stack([observer_cam_forward, observer_cam_left, observer_up], axis=1)
146
- observer_mat44[:3, 3] = observer_cam_pos
147
- observer_camera.entity.set_pose(sapien.Pose(observer_mat44))
148
 
149
- return observer_camera
 
 
150
 
151
 
152
  def _todo_create_observer_camera_birdview(scene: sapien.Scene):
153
  import numpy
154
 
155
- near, far = 0.1, 100
156
- width, height = 1280, 768
157
  camera = scene.add_camera(
158
  # TODO
159
  name="camera",
160
- width=width,
161
- height=height,
162
  fovy=numpy.deg2rad(90),
163
- near=near,
164
- far=far,
165
  )
166
 
167
- pose = sapien.Pose(p=[0, 0, 1.5])
168
  pose.set_rpy([0, numpy.deg2rad(90), 0])
169
  camera.entity_pose = pose
170
 
@@ -494,7 +507,7 @@ class World:
494
  )
495
 
496
  # TODO
497
- self._observer_camera = _todo_create_observer_camera_birdview(scene=self._scene)
498
 
499
  self._lighting = LightingController(scene=self._scene)
500
 
@@ -507,7 +520,7 @@ class World:
507
  scene=self._scene,
508
  # TODO
509
  length=1.,
510
- width=1.,
511
  height=.8,
512
  thickness=.1,
513
  render_material=_todo_get_textured_render_material(),
@@ -572,12 +585,16 @@ class World:
572
  )
573
  return manipulator
574
 
575
- def prepare_tabletop(self):
576
  """
577
  Prepare the tabletop by scattering objects on it.
578
  """
579
 
580
- def prepare_tabletop(scene: sapien.Scene, table: Table):
 
 
 
 
581
  # TODO
582
  import random
583
  from robotodo.actors.robotwin_objects import RobotwinEntityFactory
@@ -599,7 +616,8 @@ class World:
599
  "hammer",
600
  "woodenmallet",
601
  )
602
- ], 10
 
603
  ):
604
  entities.extend(entity_factory.create(scene, name=object_name))
605
 
@@ -610,7 +628,7 @@ class World:
610
  scene.remove_entity(unused_entity)
611
 
612
  # NOTE prepare the tabletop afterwards to avoid collisions
613
- prepare_tabletop(self._scene, self._table)
614
 
615
  def step(self, render: bool = True):
616
  """
 
106
 
107
 
108
 
109
+ # TODO rm
110
+ # def _todo_create_observer_camera(scene: sapien.Scene):
111
+ # import numpy
112
+
113
+ # # near, far = 0.1, 100
114
+ # # width, height = 640, 480
115
+ # # camera = self.scene.add_camera(
116
+ # # # TODO
117
+ # # name="camera",
118
+ # # width=width,
119
+ # # height=height,
120
+ # # fovy=numpy.deg2rad(90),
121
+ # # near=near,
122
+ # # far=far,
123
+ # # )
124
+ # # camera.set_pose(sapien.Pose(p=[1, 0, 0]))
125
+
126
+ # # observer camera
127
+ # import numpy as np
128
+
129
+ # observer_camera = scene.add_camera(
130
+ # name="observer_camera",
131
+ # width=640,
132
+ # height=480,
133
+ # fovy=np.deg2rad(93),
134
+ # near=.1,
135
+ # far=100,
136
+ # )
137
+ # # TODO
138
+ # # observer_cam_pos = np.array([0.0, -0.23, 1.33])
139
+ # observer_cam_pos = np.array([0.0, 0.5, 1.5])
140
+ # # observer_cam_forward = np.array([0, -1, -1.02])
141
+ # observer_cam_forward = np.array([0, -2, -1.02])
142
+ # # observer_cam_left = np.array([1,-1, 0])
143
+ # observer_cam_left = np.array([1, 0, 0])
144
+ # observer_up = np.cross(observer_cam_forward, observer_cam_left)
145
+ # observer_mat44 = np.eye(4)
146
+ # observer_mat44[:3, :3] = np.stack([observer_cam_forward, observer_cam_left, observer_up], axis=1)
147
+ # observer_mat44[:3, 3] = observer_cam_pos
148
+ # observer_camera.entity.set_pose(sapien.Pose(observer_mat44))
149
+
150
+ # return observer_camera
151
+
152
+
153
  def _todo_create_observer_camera(scene: sapien.Scene):
154
  import numpy
155
 
156
+ camera = scene.add_camera(
157
+ # TODO
158
+ name="camera",
159
+ width=1280, height=768,
160
+ fovy=numpy.deg2rad(90),
161
+ near=.1, far=100,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
162
  )
 
 
 
 
 
 
 
 
 
 
 
 
163
 
164
+ camera.entity_pose = sapien.Pose(p=[0, 0.5, 1.5], q=[0.669469, 0.22762, 0.22762, -0.669469])
165
+
166
+ return camera
167
 
168
 
169
  def _todo_create_observer_camera_birdview(scene: sapien.Scene):
170
  import numpy
171
 
 
 
172
  camera = scene.add_camera(
173
  # TODO
174
  name="camera",
175
+ width=1280, height=768,
 
176
  fovy=numpy.deg2rad(90),
177
+ near=.1, far=100,
 
178
  )
179
 
180
+ pose = sapien.Pose(p=[0, 0, 2])
181
  pose.set_rpy([0, numpy.deg2rad(90), 0])
182
  camera.entity_pose = pose
183
 
 
507
  )
508
 
509
  # TODO
510
+ self._observer_camera = _todo_create_observer_camera(scene=self._scene)
511
 
512
  self._lighting = LightingController(scene=self._scene)
513
 
 
520
  scene=self._scene,
521
  # TODO
522
  length=1.,
523
+ width=.5,
524
  height=.8,
525
  thickness=.1,
526
  render_material=_todo_get_textured_render_material(),
 
585
  )
586
  return manipulator
587
 
588
+ def prepare_tabletop(self, num_objects: int = 1):
589
  """
590
  Prepare the tabletop by scattering objects on it.
591
  """
592
 
593
+ def prepare_tabletop(
594
+ scene: sapien.Scene,
595
+ table: Table,
596
+ num_objects: int = 1,
597
+ ):
598
  # TODO
599
  import random
600
  from robotodo.actors.robotwin_objects import RobotwinEntityFactory
 
616
  "hammer",
617
  "woodenmallet",
618
  )
619
+ ],
620
+ num_objects,
621
  ):
622
  entities.extend(entity_factory.create(scene, name=object_name))
623
 
 
628
  scene.remove_entity(unused_entity)
629
 
630
  # NOTE prepare the tabletop afterwards to avoid collisions
631
+ prepare_tabletop(self._scene, self._table, num_objects=num_objects)
632
 
633
  def step(self, render: bool = True):
634
  """
pyproject.toml CHANGED
@@ -13,11 +13,12 @@ version = '0.0.0b0'
13
  #readme = 'README.md'
14
  #license = {file = 'LICENSE.txt'}
15
  dependencies = [
16
- #'nvidia_curobo @ git+https://github.com/NVlabs/curobo.git@v0.7.7',
17
  'sapien == 3.0.0b1',
 
 
18
 
19
  # TODO pi0; lock version range
20
- 'jax',
21
  'jaxtyping',
22
  'einops',
23
  # TODO
 
13
  #readme = 'README.md'
14
  #license = {file = 'LICENSE.txt'}
15
  dependencies = [
 
16
  'sapien == 3.0.0b1',
17
+ # TODO robotodo.controllers.curobo
18
+ # 'nvidia_curobo @ git+https://github.com/NVlabs/curobo.git@v0.7.7',
19
 
20
  # TODO pi0; lock version range
21
+ 'jax[cuda12]',
22
  'jaxtyping',
23
  'einops',
24
  # TODO