liujinxin commited on
Commit
ee45955
·
1 Parent(s): e458a7b
.vscode/settings.json DELETED
@@ -1,5 +0,0 @@
1
- {
2
- "python-envs.defaultEnvManager": "ms-python.python:conda",
3
- "python-envs.defaultPackageManager": "ms-python.python:conda",
4
- "python-envs.pythonProjects": []
5
- }
 
 
 
 
 
 
__todo__/todo-arrayspecs-.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # arrayspecs
3
+
4
+ # Bag API
5
+ bag = Bag(("dog", 0, "cat"))
6
+
7
+ # >>> bag.sample(seed=0)
8
+ # "dog"
9
+ # >>> 0 in bag
10
+ # True
11
+
12
+ # Bound API
13
+ bound = Bound((0., 1.))
14
+ # -or- Bound((0, 100), dtype="int")
15
+
16
+ # >>> bound * 2 - 1
17
+ # Bound((-1., 1.))
18
+ # >>> bound * -1
19
+ # Bound((-1., 0.))
20
+ # >>> bound.floor()
21
+ # 0.
22
+ # >>> bound.ceil()
23
+ # 1.
24
+ # >>> .005 in bound
25
+ # True
26
+
27
+ # ArraySpec API
28
+ spec = ArraySpec(
29
+ value={
30
+ # use dimension idx directly
31
+ 0: {
32
+ "red": Bound((0., 255.)),
33
+ }
34
+ },
35
+ )
36
+
37
+ # -or- use named dimensions
38
+ rgb_img_spec = ArraySpec(
39
+ value={
40
+ "channel": {
41
+ "red": Bound((0., 255.)),
42
+ # ...
43
+ },
44
+ },
45
+ shape={
46
+ "height": Bound(640), # NOTE same as literal: 640
47
+ "width": 480,
48
+ "channel": 3,
49
+ },
50
+ # -or-
51
+ # shape=Bag((
52
+ # {"batch": "inf", "height": 640},
53
+ # {"batch": "inf", "height": 1280},
54
+ # )),
55
+ )
56
+
57
+ # >>> rgb_img_spec.ceil()
58
+ # numpy.array(..., shape=(640, 480, 3))
59
+ # >>> rgb_img_spec.sample(seed=0)
60
+ # numpy.array(..., shape=(640, 480, 3))
61
+ # >>> rgb_img_spec.concat([rgb_img_spec, rgb_img_spec + 1, rgb_img_spec.reshape(...)])
62
+ # ArraySpec(value={"channel": {"red": Bound((1., 256.))}}, ...)
63
+
64
+
65
+ observation_spec = DictSpec({
66
+ "images": {
67
+ 0: rgb_img_spec,
68
+ "head_camera": rgb_img_spec,
69
+ },
70
+ "joint_positions": {
71
+ # ...
72
+ "elbow_rpy": ...,
73
+ }
74
+ })
75
+
76
+ # >>> arrayspecs.concat([observation_spec, observation_spec])
77
+
78
+
79
+ # Customization
80
+ class RGBImageSpec(ArraySpec):
81
+ def __init__(self):
82
+ super().__init__(
83
+ value={
84
+ "channel": {
85
+ "red": Bound((0., 255.)),
86
+ # ...
87
+ },
88
+ },
89
+ shape={
90
+ "height": Bound(640), # NOTE same as literal: 640
91
+ "width": 480,
92
+ "channel": 3,
93
+ },
94
+ )
95
+
96
+ # NOTE now RGBImageSpec can be used like any other specs
97
+
__todo__/todo-pi0-ckpt.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
__todo__/todo-pi0-train.ipynb ADDED
@@ -0,0 +1,547 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "id": "ea5c3604",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "\n",
11
+ "import functools\n",
12
+ "from typing import TypedDict\n",
13
+ "\n",
14
+ "from flax import nnx\n",
15
+ "import jax\n",
16
+ "import jax.numpy as jnp\n",
17
+ "import jaxtyping as jt\n",
18
+ "import optax\n",
19
+ "\n",
20
+ "# TODO mv\n",
21
+ "from robotodo.controllers.pi0.nn.pi0 import RegexFilter, Pi0, SpaceVar\n",
22
+ "\n",
23
+ "\n",
24
+ "# TODO\n",
25
+ "nnx.Module\n",
26
+ "\n",
27
+ "class Pi0Trainer:\n",
28
+ " class State(TypedDict):\n",
29
+ " step_num: int\n",
30
+ " optimizer_state: optax.OptState\n",
31
+ "\n",
32
+ "\n",
33
+ " def __init__(self, pi0: Pi0):\n",
34
+ " self._pi0 = pi0\n",
35
+ " # TODO !!!!!!!!!!!!!!!!!!!!!!!\n",
36
+ " self._optimizer: optax.GradientTransformation = optax.sgd()\n",
37
+ "\n",
38
+ " # TODO !!!!!\n",
39
+ " self._state = self.State(\n",
40
+ " step_num=0,\n",
41
+ " optimizer_state=...,\n",
42
+ " )\n",
43
+ "\n",
44
+ " @functools.cached_property\n",
45
+ " def _freeze_filter(self) -> nnx.filterlib.Filter:\n",
46
+ " config: Pi0.Config = self._pi0.config\n",
47
+ "\n",
48
+ " filters = []\n",
49
+ " has_lora = False\n",
50
+ " gemma_params_filter = RegexFilter(\".*llm.*\")\n",
51
+ " action_expert_params_filter = RegexFilter(\".*llm.*_1.*\")\n",
52
+ "\n",
53
+ " if \"lora\" in config.paligemma_variant:\n",
54
+ " filters.append(\n",
55
+ " gemma_params_filter,\n",
56
+ " )\n",
57
+ " if \"lora\" not in config.action_expert_variant:\n",
58
+ " # If only freeze gemma params, exclude action expert params.\n",
59
+ " filters.append(\n",
60
+ " nnx.Not(action_expert_params_filter),\n",
61
+ " )\n",
62
+ " has_lora = True\n",
63
+ " elif \"lora\" in config.action_expert_variant:\n",
64
+ " filters.append(\n",
65
+ " action_expert_params_filter,\n",
66
+ " )\n",
67
+ " has_lora = True\n",
68
+ "\n",
69
+ " if has_lora:\n",
70
+ " # If any lora is used, exclude all lora params.\n",
71
+ " filters.append(\n",
72
+ " nnx.Not(RegexFilter(\".*lora.*\")),\n",
73
+ " )\n",
74
+ "\n",
75
+ " if not filters:\n",
76
+ " return nnx.Nothing\n",
77
+ " return nnx.All(*filters)\n",
78
+ " \n",
79
+ " class StepResult(TypedDict):\n",
80
+ " loss: float\n",
81
+ " grads: jt.Array\n",
82
+ "\n",
83
+ " def step(\n",
84
+ " self, \n",
85
+ " rng: jt.PRNGKeyArray,\n",
86
+ " batch_observation: SpaceVar[Pi0.ObservationSpec.batched], \n",
87
+ " batch_action: SpaceVar[Pi0.ActionSpec.batched],\n",
88
+ " ):\n",
89
+ " # TODO\n",
90
+ " rng_train_step = jax.random.fold_in(rng, self._state[\"step_num\"])\n",
91
+ "\n",
92
+ " # TODO orig: nnx.All(nnx.Param, nnx.Not(self.freeze_filter))\n",
93
+ " trainable_filter = nnx.Not(self._freeze_filter)\n",
94
+ "\n",
95
+ " # @at.typecheck\n",
96
+ " def loss_fn(\n",
97
+ " model: Pi0, \n",
98
+ " rng: jt.PRNGKeyArray, \n",
99
+ " batch_observation: SpaceVar[Pi0.ObservationSpec.batched], \n",
100
+ " batch_action: SpaceVar[Pi0.ActionSpec.batched],\n",
101
+ " ):\n",
102
+ " chunked_loss = model.compute_loss(\n",
103
+ " rng, \n",
104
+ " batch_observation, \n",
105
+ " batch_action,\n",
106
+ " )\n",
107
+ " return jnp.mean(chunked_loss)\n",
108
+ " # TODO\n",
109
+ " self._pi0.train(mode=True)\n",
110
+ " loss, grads = nnx.value_and_grad(\n",
111
+ " loss_fn, \n",
112
+ " # TODO orig: diff_state = nnx.DiffState(0, config.trainable_filter)\n",
113
+ " # argnums=diff_state,\n",
114
+ " argnums=trainable_filter,\n",
115
+ " )(\n",
116
+ " self._pi0, \n",
117
+ " rng=rng_train_step, \n",
118
+ " batch_observation=batch_observation, \n",
119
+ " batch_action=batch_action,\n",
120
+ " )\n",
121
+ "\n",
122
+ " trainable_params = nnx.state(self._pi0, trainable_filter)\n",
123
+ " optimizer_updates, self._state[\"optimizer_state\"] = self._optimizer.update(\n",
124
+ " grads,\n",
125
+ " self._state[\"optimizer_state\"],\n",
126
+ " params=trainable_params,\n",
127
+ " )\n",
128
+ " trainable_params = optax.apply_updates(trainable_params, optimizer_updates)\n",
129
+ "\n",
130
+ " return Pi0Trainer.StepResult(\n",
131
+ " loss=loss,\n",
132
+ " grads=grads,\n",
133
+ " )\n",
134
+ "\n",
135
+ "\n",
136
+ "\n",
137
+ "\n",
138
+ " \n",
139
+ " # TODO\n",
140
+ " params = state.params.filter(trainable_filter)\n",
141
+ " updates, new_opt_state = optimizer.update(\n",
142
+ " grads, \n",
143
+ " state.opt_state, \n",
144
+ " params,\n",
145
+ " )\n",
146
+ " new_params = optax.apply_updates(params, updates)\n",
147
+ "\n",
148
+ " # Update the model in place and return the new full state.\n",
149
+ " nnx.update(model, new_params)\n",
150
+ " new_params = nnx.state(model)\n",
151
+ "\n",
152
+ " new_state = dataclasses.replace(state, step=state.step + 1, params=new_params, opt_state=new_opt_state)\n",
153
+ " if state.ema_decay is not None:\n",
154
+ " new_state = dataclasses.replace(\n",
155
+ " new_state,\n",
156
+ " ema_params=jax.tree.map(\n",
157
+ " lambda old, new: state.ema_decay * old + (1 - state.ema_decay) * new, state.ema_params, new_params\n",
158
+ " ),\n",
159
+ " )\n",
160
+ "\n",
161
+ " # TODO \n",
162
+ " # Filter out params that aren't kernels.\n",
163
+ " kernel_params = nnx.state(\n",
164
+ " model,\n",
165
+ " nnx.All(\n",
166
+ " nnx.Param,\n",
167
+ " nnx.Not(RegexFilter(\".*/(bias|scale|pos_embedding|input_embedding)\")),\n",
168
+ " lambda _, x: x.value.ndim > 1,\n",
169
+ " ),\n",
170
+ " )\n",
171
+ " info = {\n",
172
+ " \"loss\": loss,\n",
173
+ " \"grad_norm\": optax.global_norm(grads),\n",
174
+ " \"param_norm\": optax.global_norm(kernel_params),\n",
175
+ " }\n",
176
+ " return new_state, info"
177
+ ]
178
+ },
179
+ {
180
+ "cell_type": "code",
181
+ "execution_count": 1,
182
+ "id": "63d8a3fb",
183
+ "metadata": {},
184
+ "outputs": [
185
+ {
186
+ "name": "stdout",
187
+ "output_type": "stream",
188
+ "text": [
189
+ "env: JAX_PLATFORMS=cpu\n",
190
+ "env: XLA_PYTHON_CLIENT_PREALLOCATE=false\n"
191
+ ]
192
+ }
193
+ ],
194
+ "source": [
195
+ "%env JAX_PLATFORMS=cpu\n",
196
+ "%env XLA_PYTHON_CLIENT_PREALLOCATE=false"
197
+ ]
198
+ },
199
+ {
200
+ "cell_type": "code",
201
+ "execution_count": 2,
202
+ "id": "be28fc1e",
203
+ "metadata": {},
204
+ "outputs": [],
205
+ "source": [
206
+ "from robotodo.controllers.pi0.nn.pi0 import Pi0, Pi0Trainer\n",
207
+ "\n",
208
+ "pi0 = Pi0()"
209
+ ]
210
+ },
211
+ {
212
+ "cell_type": "code",
213
+ "execution_count": 3,
214
+ "id": "424fc55f",
215
+ "metadata": {},
216
+ "outputs": [],
217
+ "source": [
218
+ "pi0_trainer = Pi0Trainer(pi0)\n"
219
+ ]
220
+ },
221
+ {
222
+ "cell_type": "code",
223
+ "execution_count": 5,
224
+ "id": "dda111f4",
225
+ "metadata": {},
226
+ "outputs": [
227
+ {
228
+ "data": {
229
+ "text/plain": [
230
+ "Pi0Trainer.StepResult(loss=Array(2.9841192, dtype=float32), grads=State({}))"
231
+ ]
232
+ },
233
+ "execution_count": 5,
234
+ "metadata": {},
235
+ "output_type": "execute_result"
236
+ }
237
+ ],
238
+ "source": [
239
+ "pi0_trainer.step(\n",
240
+ " batch_observation=pi0.config.observation_spec.batched().sample(),\n",
241
+ " batch_action=pi0.config.action_spec.batched().sample(),\n",
242
+ ")"
243
+ ]
244
+ },
245
+ {
246
+ "cell_type": "code",
247
+ "execution_count": 7,
248
+ "id": "abe3fdd8",
249
+ "metadata": {},
250
+ "outputs": [
251
+ {
252
+ "data": {
253
+ "text/plain": [
254
+ "State({})"
255
+ ]
256
+ },
257
+ "execution_count": 7,
258
+ "metadata": {},
259
+ "output_type": "execute_result"
260
+ }
261
+ ],
262
+ "source": [
263
+ "import flax.nnx\n",
264
+ "\n",
265
+ "\n",
266
+ "flax.nnx.state(pi0, pi0.trainable_filter)\n"
267
+ ]
268
+ },
269
+ {
270
+ "cell_type": "code",
271
+ "execution_count": 10,
272
+ "id": "08c55c20",
273
+ "metadata": {},
274
+ "outputs": [
275
+ {
276
+ "data": {
277
+ "text/plain": [
278
+ "Pi0.Config(observation_spec=Dict('images': Dict('base_0_rgb': Box(-1.0, 1.0, (224, 224, 3), float32), 'left_wrist_0_rgb': Box(-1.0, 1.0, (224, 224, 3), float32), 'right_wrist_0_rgb': Box(-1.0, 1.0, (224, 224, 3), float32)), 'images.mask': Dict('base_0_rgb': Box(0, 1, (), uint8), 'left_wrist_0_rgb': Box(0, 1, (), uint8), 'right_wrist_0_rgb': Box(0, 1, (), uint8)), 'numeric_state': Box(-inf, inf, (32,), float32), 'tokenized_text': Box(0, 257152, (48,), int32), 'tokenized_text.mask': Box(0, 1, (48,), uint8)), action_spec=Dict('numeric_states': Box(-inf, inf, (50, 32), float32)), dtype='bfloat16', paligemma_variant='gemma_2b', action_expert_variant='gemma_300m')"
279
+ ]
280
+ },
281
+ "execution_count": 10,
282
+ "metadata": {},
283
+ "output_type": "execute_result"
284
+ }
285
+ ],
286
+ "source": [
287
+ "pi0.config"
288
+ ]
289
+ },
290
+ {
291
+ "cell_type": "code",
292
+ "execution_count": 8,
293
+ "id": "19f61166",
294
+ "metadata": {},
295
+ "outputs": [
296
+ {
297
+ "data": {
298
+ "text/plain": [
299
+ "Pi0( # Param: 3,238,048,528 (13.0 GB)\n",
300
+ " PaliGemma=Dict( # Param: 3,234,800,368 (12.9 GB)\n",
301
+ " img=ToNNX( # Param: 414,803,696 (1.7 GB)\n",
302
+ " Transformer={'encoder_norm': {'bias': Param( # 1,152 (4.6 KB)\n",
303
+ " value=Array(shape=(1152,), dtype=dtype('float32'))\n",
304
+ " ), 'scale': Param( # 1,152 (4.6 KB)\n",
305
+ " value=Array(shape=(1152,), dtype=dtype('float32'))\n",
306
+ " )}, 'encoderblock': {'LayerNorm_0': {'bias': Param( # 31,104 (124.4 KB)\n",
307
+ " value=Array(shape=(27, 1152), dtype=dtype('float32'))\n",
308
+ " ), 'scale': Param( # 31,104 (124.4 KB)\n",
309
+ " value=Array(shape=(27, 1152), dtype=dtype('float32'))\n",
310
+ " )}, 'LayerNorm_1': {'bias': Param( # 31,104 (124.4 KB)\n",
311
+ " value=Array(shape=(27, 1152), dtype=dtype('float32'))\n",
312
+ " ), 'scale': Param( # 31,104 (124.4 KB)\n",
313
+ " value=Array(shape=(27, 1152), dtype=dtype('float32'))\n",
314
+ " )}, 'MlpBlock_0': {'Dense_0': {'bias': Param( # 116,208 (464.8 KB)\n",
315
+ " value=Array(shape=(27, 4304), dtype=dtype('float32'))\n",
316
+ " ), 'kernel': Param( # 133,871,616 (535.5 MB)\n",
317
+ " value=Array(shape=(27, 1152, 4304), dtype=dtype('float32'))\n",
318
+ " )}, 'Dense_1': {'bias': Param( # 31,104 (124.4 KB)\n",
319
+ " value=Array(shape=(27, 1152), dtype=dtype('float32'))\n",
320
+ " ), 'kernel': Param( # 133,871,616 (535.5 MB)\n",
321
+ " value=Array(shape=(27, 4304, 1152), dtype=dtype('float32'))\n",
322
+ " )}}, 'MultiHeadDotProductAttention_0': {'key': {'bias': Param( # 31,104 (124.4 KB)\n",
323
+ " value=Array(shape=(27, 16, 72), dtype=dtype('float32'))\n",
324
+ " ), 'kernel': Param( # 35,831,808 (143.3 MB)\n",
325
+ " value=Array(shape=(27, 1152, 16, 72), dtype=dtype('float32'))\n",
326
+ " )}, 'out': {'bias': Param( # 31,104 (124.4 KB)\n",
327
+ " value=Array(shape=(27, 1152), dtype=dtype('float32'))\n",
328
+ " ), 'kernel': Param( # 35,831,808 (143.3 MB)\n",
329
+ " value=Array(shape=(27, 16, 72, 1152), dtype=dtype('float32'))\n",
330
+ " )}, 'query': {'bias': Param( # 31,104 (124.4 KB)\n",
331
+ " value=Array(shape=(27, 16, 72), dtype=dtype('float32'))\n",
332
+ " ), 'kernel': Param( # 35,831,808 (143.3 MB)\n",
333
+ " value=Array(shape=(27, 1152, 16, 72), dtype=dtype('float32'))\n",
334
+ " )}, 'value': {'bias': Param( # 31,104 (124.4 KB)\n",
335
+ " value=Array(shape=(27, 16, 72), dtype=dtype('float32'))\n",
336
+ " ), 'kernel': Param( # 35,831,808 (143.3 MB)\n",
337
+ " value=Array(shape=(27, 1152, 16, 72), dtype=dtype('float32'))\n",
338
+ " )}}}},\n",
339
+ " embedding={'bias': Param( # 1,152 (4.6 KB)\n",
340
+ " value=Array(shape=(1152,), dtype=dtype('float32'))\n",
341
+ " ), 'kernel': Param( # 677,376 (2.7 MB)\n",
342
+ " value=Array(shape=(14, 14, 3, 1152), dtype=dtype('float32'))\n",
343
+ " )},\n",
344
+ " head={'bias': Param( # 2,048 (8.2 KB)\n",
345
+ " value=Array(shape=(2048,), dtype=dtype('float32'))\n",
346
+ " ), 'kernel': Param( # 2,359,296 (9.4 MB)\n",
347
+ " value=Array(shape=(1152, 2048), dtype=dtype('float32'))\n",
348
+ " )},\n",
349
+ " module=_Module(\n",
350
+ " # attributes\n",
351
+ " num_classes = 2048\n",
352
+ " patch_size = (14, 14)\n",
353
+ " width = 1152\n",
354
+ " depth = 27\n",
355
+ " mlp_dim = 4304\n",
356
+ " num_heads = 16\n",
357
+ " posemb = 'learn'\n",
358
+ " rep_size = False\n",
359
+ " dropout = 0.0\n",
360
+ " pool_type = 'none'\n",
361
+ " head_zeroinit = True\n",
362
+ " scan = True\n",
363
+ " remat_policy = 'nothing_saveable'\n",
364
+ " dtype_mm = 'bfloat16'\n",
365
+ " ),\n",
366
+ " pos_embedding=Param( # 294,912 (1.2 MB)\n",
367
+ " value=Array(shape=(1, 256, 1152), dtype=dtype('float32'))\n",
368
+ " ),\n",
369
+ " rngs=None\n",
370
+ " ),\n",
371
+ " llm=ToNNX( # Param: 2,819,996,672 (11.3 GB)\n",
372
+ " embedder={'input_embedding': Param( # 526,647,296 (2.1 GB)\n",
373
+ " value=Array(shape=(257152, 2048), dtype=dtype('float32'))\n",
374
+ " )},\n",
375
+ " final_norm={'scale': Param( # 2,048 (8.2 KB)\n",
376
+ " value=Array(shape=(2048,), dtype=dtype('float32'))\n",
377
+ " )},\n",
378
+ " final_norm_1={'scale': Param( # 1,024 (4.1 KB)\n",
379
+ " value=Array(shape=(1024,), dtype=dtype('float32'))\n",
380
+ " )},\n",
381
+ " layers={'attn': {'attn_vec_einsum': {'w': Param( # 75,497,472 (302.0 MB)\n",
382
+ " value=Array(shape=(18, 8, 256, 2048), dtype=dtype('float32'))\n",
383
+ " )}, 'attn_vec_einsum_1': {'w': Param( # 37,748,736 (151.0 MB)\n",
384
+ " value=Array(shape=(18, 8, 256, 1024), dtype=dtype('float32'))\n",
385
+ " )}, 'kv_einsum': {'w': Param( # 18,874,368 (75.5 MB)\n",
386
+ " value=Array(shape=(18, 2, 1, 2048, 256), dtype=dtype('float32'))\n",
387
+ " )}, 'kv_einsum_1': {'w': Param( # 9,437,184 (37.7 MB)\n",
388
+ " value=Array(shape=(18, 2, 1, 1024, 256), dtype=dtype('float32'))\n",
389
+ " )}, 'q_einsum': {'w': Param( # 75,497,472 (302.0 MB)\n",
390
+ " value=Array(shape=(18, 8, 2048, 256), dtype=dtype('float32'))\n",
391
+ " )}, 'q_einsum_1': {'w': Param( # 37,748,736 (151.0 MB)\n",
392
+ " value=Array(shape=(18, 8, 1024, 256), dtype=dtype('float32'))\n",
393
+ " )}}, 'mlp': {'gating_einsum': Param( # 1,207,959,552 (4.8 GB)\n",
394
+ " value=Array(shape=(18, 2, 2048, 16384), dtype=dtype('float32'))\n",
395
+ " ), 'linear': Param( # 603,979,776 (2.4 GB)\n",
396
+ " value=Array(shape=(18, 16384, 2048), dtype=dtype('float32'))\n",
397
+ " )}, 'mlp_1': {'gating_einsum': Param( # 150,994,944 (604.0 MB)\n",
398
+ " value=Array(shape=(18, 2, 1024, 4096), dtype=dtype('float32'))\n",
399
+ " ), 'linear': Param( # 75,497,472 (302.0 MB)\n",
400
+ " value=Array(shape=(18, 4096, 1024), dtype=dtype('float32'))\n",
401
+ " )}, 'pre_attention_norm': {'scale': Param( # 36,864 (147.5 KB)\n",
402
+ " value=Array(shape=(18, 2048), dtype=dtype('float32'))\n",
403
+ " )}, 'pre_attention_norm_1': {'scale': Param( # 18,432 (73.7 KB)\n",
404
+ " value=Array(shape=(18, 1024), dtype=dtype('float32'))\n",
405
+ " )}, 'pre_ffw_norm': {'scale': Param( # 36,864 (147.5 KB)\n",
406
+ " value=Array(shape=(18, 2048), dtype=dtype('float32'))\n",
407
+ " )}, 'pre_ffw_norm_1': {'scale': Param( # 18,432 (73.7 KB)\n",
408
+ " value=Array(shape=(18, 1024), dtype=dtype('float32'))\n",
409
+ " )}},\n",
410
+ " module=Module(\n",
411
+ " # attributes\n",
412
+ " configs = [Config(width=2048, depth=18, mlp_dim=16384, num_heads=8, num_kv_heads=1, head_dim=256, lora_configs={}), Config(width=1024, depth=18, mlp_dim=4096, num_heads=8, num_kv_heads=1, head_dim=256, lora_configs={})]\n",
413
+ " embed_dtype = 'bfloat16'\n",
414
+ " dropout = 0.0\n",
415
+ " dropout_bdims = ()\n",
416
+ " ),\n",
417
+ " rngs=None\n",
418
+ " )\n",
419
+ " ),\n",
420
+ " action_in_proj=Linear( # Param: 33,792 (135.2 KB)\n",
421
+ " bias=Param( # 1,024 (4.1 KB)\n",
422
+ " value=Array(shape=(1024,), dtype=dtype('float32'))\n",
423
+ " ),\n",
424
+ " bias_init=<function zeros at 0x7ff31f6eeca0>,\n",
425
+ " dot_general=<function dot_general at 0x7ff3200531a0>,\n",
426
+ " dtype=None,\n",
427
+ " in_features=32,\n",
428
+ " kernel=Param( # 32,768 (131.1 KB)\n",
429
+ " value=Array(shape=(32, 1024), dtype=dtype('float32'))\n",
430
+ " ),\n",
431
+ " kernel_init=<function variance_scaling.<locals>.init at 0x7ff31eb22d40>,\n",
432
+ " out_features=1024,\n",
433
+ " param_dtype=float32,\n",
434
+ " precision=None,\n",
435
+ " promote_dtype=<function promote_dtype at 0x7ff31eb23060>,\n",
436
+ " use_bias=True\n",
437
+ " ),\n",
438
+ " action_out_proj=Linear( # Param: 32,800 (131.2 KB)\n",
439
+ " bias=Param( # 32 (128 B)\n",
440
+ " value=Array(shape=(32,), dtype=dtype('float32'))\n",
441
+ " ),\n",
442
+ " bias_init=<function zeros at 0x7ff31f6eeca0>,\n",
443
+ " dot_general=<function dot_general at 0x7ff3200531a0>,\n",
444
+ " dtype=None,\n",
445
+ " in_features=1024,\n",
446
+ " kernel=Param( # 32,768 (131.1 KB)\n",
447
+ " value=Array(shape=(1024, 32), dtype=dtype('float32'))\n",
448
+ " ),\n",
449
+ " kernel_init=<function variance_scaling.<locals>.init at 0x7ff31eb22d40>,\n",
450
+ " out_features=32,\n",
451
+ " param_dtype=float32,\n",
452
+ " precision=None,\n",
453
+ " promote_dtype=<function promote_dtype at 0x7ff31eb23060>,\n",
454
+ " use_bias=True\n",
455
+ " ),\n",
456
+ " action_time_mlp_in=Linear( # Param: 2,098,176 (8.4 MB)\n",
457
+ " bias=Param( # 1,024 (4.1 KB)\n",
458
+ " value=Array(shape=(1024,), dtype=dtype('float32'))\n",
459
+ " ),\n",
460
+ " bias_init=<function zeros at 0x7ff31f6eeca0>,\n",
461
+ " dot_general=<function dot_general at 0x7ff3200531a0>,\n",
462
+ " dtype=None,\n",
463
+ " in_features=2048,\n",
464
+ " kernel=Param( # 2,097,152 (8.4 MB)\n",
465
+ " value=Array(shape=(2048, 1024), dtype=dtype('float32'))\n",
466
+ " ),\n",
467
+ " kernel_init=<function variance_scaling.<locals>.init at 0x7ff31eb22d40>,\n",
468
+ " out_features=1024,\n",
469
+ " param_dtype=float32,\n",
470
+ " precision=None,\n",
471
+ " promote_dtype=<function promote_dtype at 0x7ff31eb23060>,\n",
472
+ " use_bias=True\n",
473
+ " ),\n",
474
+ " action_time_mlp_out=Linear( # Param: 1,049,600 (4.2 MB)\n",
475
+ " bias=Param( # 1,024 (4.1 KB)\n",
476
+ " value=Array(shape=(1024,), dtype=dtype('float32'))\n",
477
+ " ),\n",
478
+ " bias_init=<function zeros at 0x7ff31f6eeca0>,\n",
479
+ " dot_general=<function dot_general at 0x7ff3200531a0>,\n",
480
+ " dtype=None,\n",
481
+ " in_features=1024,\n",
482
+ " kernel=Param( # 1,048,576 (4.2 MB)\n",
483
+ " value=Array(shape=(1024, 1024), dtype=dtype('float32'))\n",
484
+ " ),\n",
485
+ " kernel_init=<function variance_scaling.<locals>.init at 0x7ff31eb22d40>,\n",
486
+ " out_features=1024,\n",
487
+ " param_dtype=float32,\n",
488
+ " precision=None,\n",
489
+ " promote_dtype=<function promote_dtype at 0x7ff31eb23060>,\n",
490
+ " use_bias=True\n",
491
+ " ),\n",
492
+ " gemma_language_model=ToNNX(...),\n",
493
+ " siglip_vision_model=ToNNX(...),\n",
494
+ " state_proj=Linear( # Param: 33,792 (135.2 KB)\n",
495
+ " bias=Param( # 1,024 (4.1 KB)\n",
496
+ " value=Array(shape=(1024,), dtype=dtype('float32'))\n",
497
+ " ),\n",
498
+ " bias_init=<function zeros at 0x7ff31f6eeca0>,\n",
499
+ " dot_general=<function dot_general at 0x7ff3200531a0>,\n",
500
+ " dtype=None,\n",
501
+ " in_features=32,\n",
502
+ " kernel=Param( # 32,768 (131.1 KB)\n",
503
+ " value=Array(shape=(32, 1024), dtype=dtype('float32'))\n",
504
+ " ),\n",
505
+ " kernel_init=<function variance_scaling.<locals>.init at 0x7ff31eb22d40>,\n",
506
+ " out_features=1024,\n",
507
+ " param_dtype=float32,\n",
508
+ " precision=None,\n",
509
+ " promote_dtype=<function promote_dtype at 0x7ff31eb23060>,\n",
510
+ " use_bias=True\n",
511
+ " ),\n",
512
+ " trainable_filter=Nothing\n",
513
+ ")"
514
+ ]
515
+ },
516
+ "execution_count": 8,
517
+ "metadata": {},
518
+ "output_type": "execute_result"
519
+ }
520
+ ],
521
+ "source": [
522
+ "pi0"
523
+ ]
524
+ }
525
+ ],
526
+ "metadata": {
527
+ "kernelspec": {
528
+ "display_name": ".conda",
529
+ "language": "python",
530
+ "name": "python3"
531
+ },
532
+ "language_info": {
533
+ "codemirror_mode": {
534
+ "name": "ipython",
535
+ "version": 3
536
+ },
537
+ "file_extension": ".py",
538
+ "mimetype": "text/x-python",
539
+ "name": "python",
540
+ "nbconvert_exporter": "python",
541
+ "pygments_lexer": "ipython3",
542
+ "version": "3.11.13"
543
+ }
544
+ },
545
+ "nbformat": 4,
546
+ "nbformat_minor": 5
547
+ }
__todo__/todo-pi0.ipynb CHANGED
@@ -227,11 +227,24 @@
227
  },
228
  {
229
  "cell_type": "code",
230
- "execution_count": null,
231
  "id": "c7b0aa56",
232
  "metadata": {},
233
- "outputs": [],
234
- "source": []
 
 
 
 
 
 
 
 
 
 
 
 
 
235
  },
236
  {
237
  "cell_type": "code",
@@ -243,7 +256,7 @@
243
  "name": "stderr",
244
  "output_type": "stream",
245
  "text": [
246
- "2025-07-24 17:43:28.042058: 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 (9861335348 bytes) originally\n"
247
  ]
248
  }
249
  ],
@@ -252,13 +265,17 @@
252
  "\n",
253
  "pi0 = Pi0(Pi0.Config(\n",
254
  " observation_spec=Pi0.ObservationSpec(\n",
 
 
 
255
  " # TODO\n",
256
  " text_vocab_size=1000,\n",
257
- "\n",
258
- " image_names=[\"example\", \"another_example\"], \n",
259
- " numeric_state_size=10,\n",
260
  " ),\n",
261
- " action_spec=Pi0.ActionSpec(numeric_state_size=10,)\n",
 
 
 
262
  "))"
263
  ]
264
  },
@@ -271,12 +288,8 @@
271
  {
272
  "data": {
273
  "text/plain": [
274
- "{'numeric_states': Array([[[ 1.8745872 , 2.0833185 , 0.46031493, 0.38244995,\n",
275
- " 0.5504736 , -2.0773675 , -0.5167864 , -0.6781924 ,\n",
276
- " -0.81481874, -2.6481616 ],\n",
277
- " [ 2.5059624 , -2.3662438 , 1.8594427 , 0.49086943,\n",
278
- " 1.7175095 , 0.10906325, 0.9829361 , 0.22758876,\n",
279
- " -1.736405 , -3.268324 ]]], dtype=float32)}"
280
  ]
281
  },
282
  "execution_count": 2,
@@ -291,14 +304,72 @@
291
  " rng=jax.random.key(0),\n",
292
  " batch_observation=pi0._config.observation_spec.batched().sample(),\n",
293
  " batch_action=pi0._config.action_spec.batched().sample(),\n",
294
- ")\n",
295
- "\n",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
296
  "pi0.sample_actions(\n",
297
  " rng=jax.random.key(0),\n",
298
  " batch_observation=pi0._config.observation_spec.batched().sample(),\n",
299
  ")"
300
  ]
301
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
302
  {
303
  "cell_type": "code",
304
  "execution_count": 7,
@@ -905,7 +976,7 @@
905
  ],
906
  "metadata": {
907
  "kernelspec": {
908
- "display_name": ".conda",
909
  "language": "python",
910
  "name": "python3"
911
  },
 
227
  },
228
  {
229
  "cell_type": "code",
230
+ "execution_count": 1,
231
  "id": "c7b0aa56",
232
  "metadata": {},
233
+ "outputs": [
234
+ {
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"
247
+ ]
248
  },
249
  {
250
  "cell_type": "code",
 
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
  ],
 
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
  },
 
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,
 
304
  " rng=jax.random.key(0),\n",
305
  " batch_observation=pi0._config.observation_spec.batched().sample(),\n",
306
  " batch_action=pi0._config.action_spec.batched().sample(),\n",
307
+ ")"
308
+ ]
309
+ },
310
+ {
311
+ "cell_type": "code",
312
+ "execution_count": 4,
313
+ "id": "b05c6fb4",
314
+ "metadata": {},
315
+ "outputs": [
316
+ {
317
+ "data": {
318
+ "text/plain": [
319
+ "{'numeric_states': Array([[[ 2.4204671 , 1.2837857 , -0.6498379 , 0.12193705],\n",
320
+ " [ 1.0678527 , -1.1816808 , -1.2071092 , -0.16615492]]], dtype=float32)}"
321
+ ]
322
+ },
323
+ "execution_count": 4,
324
+ "metadata": {},
325
+ "output_type": "execute_result"
326
+ }
327
+ ],
328
+ "source": [
329
  "pi0.sample_actions(\n",
330
  " rng=jax.random.key(0),\n",
331
  " batch_observation=pi0._config.observation_spec.batched().sample(),\n",
332
  ")"
333
  ]
334
  },
335
+ {
336
+ "cell_type": "code",
337
+ "execution_count": 6,
338
+ "id": "0853ce62",
339
+ "metadata": {},
340
+ "outputs": [
341
+ {
342
+ "data": {
343
+ "text/plain": [
344
+ "Linear( # Param: 11,264 (45.1 KB)\n",
345
+ " kernel=Param( # 10,240 (41.0 KB)\n",
346
+ " value=Array(shape=(10, 1024), dtype=dtype('float32'))\n",
347
+ " ),\n",
348
+ " bias=Param( # 1,024 (4.1 KB)\n",
349
+ " value=Array(shape=(1024,), dtype=dtype('float32'))\n",
350
+ " ),\n",
351
+ " in_features=10,\n",
352
+ " out_features=1024,\n",
353
+ " use_bias=True,\n",
354
+ " dtype=None,\n",
355
+ " param_dtype=float32,\n",
356
+ " precision=None,\n",
357
+ " kernel_init=<function variance_scaling.<locals>.init at 0x7f348025ed40>,\n",
358
+ " bias_init=<function zeros at 0x7f3480e607c0>,\n",
359
+ " dot_general=<function dot_general at 0x7f34817cccc0>,\n",
360
+ " promote_dtype=<function promote_dtype at 0x7f348025efc0>\n",
361
+ ")"
362
+ ]
363
+ },
364
+ "execution_count": 6,
365
+ "metadata": {},
366
+ "output_type": "execute_result"
367
+ }
368
+ ],
369
+ "source": [
370
+ "pi0.action_in_proj"
371
+ ]
372
+ },
373
  {
374
  "cell_type": "code",
375
  "execution_count": 7,
 
976
  ],
977
  "metadata": {
978
  "kernelspec": {
979
+ "display_name": "Python 3",
980
  "language": "python",
981
  "name": "python3"
982
  },
__todo__/todo.md CHANGED
@@ -18,7 +18,8 @@ component.attach(shape)
18
  # ...
19
  ```
20
 
21
-
 
22
 
23
  - robotodo universal sim/ctrl API
24
 
 
18
  # ...
19
  ```
20
 
21
+ - resource metadata API
22
+ - fsspec? virtual fs?
23
 
24
  - robotodo universal sim/ctrl API
25
 
packages/robotodo/controllers/pi0/nn/pi0.py CHANGED
@@ -6,12 +6,15 @@ TODO
6
  # TODO ref pi0!!!!
7
 
8
 
 
9
  import re
10
  import dataclasses
11
  from typing import Any
12
  # TODO
13
  import dataclasses
14
 
 
 
15
  import gymnasium.spaces
16
  import numpy
17
 
@@ -29,14 +32,6 @@ import flax.nnx.bridge as nnx_bridge
29
  import jax
30
  import jax.numpy as jnp
31
  import jaxtyping as jt
32
- # from typing_extensions import override
33
-
34
- # TODO
35
- # from openpi.models import model as _model
36
- # import openpi.models.gemma as _gemma
37
- # import openpi.models.siglip as _siglip
38
- # from openpi.shared import array_typing as at
39
- # import openpi.shared.nnx_utils as nnx_utils
40
 
41
  from . import gemma as _gemma
42
  from . import siglip as _siglip
@@ -114,17 +109,26 @@ def posemb_sincos(
114
  class Pi0(nnx.Module):
115
  """
116
  TODO
 
 
 
 
 
117
 
118
  """
119
 
120
  class ObservationSpec(gymnasium.spaces.Dict):
121
  def __init__(
122
  self,
123
- image_names: list[str] = [], # TODO
124
- image_size: tuple[int, int] = (64, 64),
125
- text_max_len: int = 48, # TODO
126
- text_vocab_size: int | None = None,
127
- numeric_state_size: int = 4,
 
 
 
 
128
  ):
129
  """
130
  Observation specification (unbatched).
@@ -134,6 +138,14 @@ class Pi0(nnx.Module):
134
  :param text_max_len: Maximum length of text tokens. (TODO)
135
  :param text_vocab_size: Size of text vocabulary. Infinite if :class:`None`.
136
  :param numeric_state_size: Size of numeric state (e.g. number of motors).
 
 
 
 
 
 
 
 
137
  """
138
 
139
  self.feature_specs = {
@@ -186,15 +198,19 @@ class Pi0(nnx.Module):
186
  class ActionSpec(gymnasium.spaces.Dict):
187
  def __init__(
188
  self,
189
- numeric_state_size: int = 4,
190
- # TODO NOTE ...
191
- numeric_state_horizon: int = 2,
192
  ):
193
  """
194
  Action specification (unbatched).
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.
 
 
 
 
 
198
  """
199
 
200
  super().__init__({
@@ -218,7 +234,14 @@ class Pi0(nnx.Module):
218
  paligemma_variant: _gemma.Variant = "gemma_2b"
219
  action_expert_variant: _gemma.Variant = "gemma_300m"
220
 
221
- def __init__(self, config: Config, rngs: nnx.Rngs | None = None):
 
 
 
 
 
 
 
222
  self._config = config
223
  if rngs is None:
224
  # TODO
@@ -228,16 +251,16 @@ class Pi0(nnx.Module):
228
  action_expert_config = _gemma.get_config(config.action_expert_variant)
229
 
230
  # TODO: rewrite gemma in NNX. For now, use bridge.
231
- self._language_model = nnx_bridge.ToNNX(
232
  _gemma.Module(
233
  configs=[paligemma_config, action_expert_config],
234
  embed_dtype=config.dtype,
235
  )
236
  )
237
  # TODO
238
- self._language_model.lazy_init(rngs=rngs, method="init")
239
 
240
- self._vision_model = nnx_bridge.ToNNX(
241
  _siglip.Module(
242
  num_classes=paligemma_config.width,
243
  variant="So400m/14",
@@ -246,7 +269,7 @@ class Pi0(nnx.Module):
246
  dtype_mm=config.dtype,
247
  )
248
  )
249
- self._vision_model.lazy_init(
250
  gymnasium.vector.utils.batch_space(
251
  config.observation_spec.feature_specs["image"],
252
  n=1,
@@ -256,17 +279,22 @@ class Pi0(nnx.Module):
256
  method="init",
257
  )
258
 
259
- # TODO !!!!!!!!
260
- # self.max_token_len ...
261
  # TODO !!!!! make it named!!!!!!
262
- self.action_horizon, self.action_dim = config.action_spec["numeric_states"].shape
263
 
264
- self.state_proj = nnx.Linear(self.action_dim, action_expert_config.width, rngs=rngs)
265
- self.action_in_proj = nnx.Linear(self.action_dim, action_expert_config.width, rngs=rngs)
266
  self.action_time_mlp_in = nnx.Linear(2 * action_expert_config.width, action_expert_config.width, rngs=rngs)
267
  self.action_time_mlp_out = nnx.Linear(action_expert_config.width, action_expert_config.width, rngs=rngs)
268
- self.action_out_proj = nnx.Linear(action_expert_config.width, self.action_dim, rngs=rngs)
 
 
 
 
 
 
269
 
 
270
  @property
271
  def config(self) -> Config:
272
  return self._config
@@ -286,7 +314,7 @@ class Pi0(nnx.Module):
286
  # TODO !!!!!!
287
  # embed images
288
  for name in batch_observation["images"]:
289
- image_embeddings, _ = self._vision_model(
290
  # TODO
291
  batch_observation["images"][name],
292
  train=False,
@@ -297,7 +325,6 @@ class Pi0(nnx.Module):
297
  input_masks.append(
298
  # TODO repeat/broadcast only when necessary!!!!!!
299
  einops.repeat(
300
- # TODO make masks on the fly: see _model.preprocess_observation
301
  batch_observation["images.mask"][name],
302
  "b -> b s",
303
  s=image_embeddings.shape[1],
@@ -309,7 +336,7 @@ class Pi0(nnx.Module):
309
 
310
  # add language (aka tokenized inputs)
311
  if batch_observation.get("tokenized_text", None) is not None:
312
- language_embeddings = self._language_model(
313
  # TODO
314
  batch_observation["tokenized_text"],
315
  method="embed",
@@ -339,13 +366,18 @@ class Pi0(nnx.Module):
339
  batch_noisy_action: SpaceVar[ActionSpec.batched],
340
  timestep: jt.Float[jt.Array, " b"],
341
  ) -> tuple[jt.Float[jt.Array, "b s emb"], jt.Bool[jt.Array, "b s"], jt.Bool[jt.Array, " s"]]:
 
 
 
342
  input_mask = []
343
  ar_mask = []
344
  tokens = []
 
345
  # add a single state token
346
  state_token = self.state_proj(batch_observation["numeric_state"])[:, None, :]
347
  tokens.append(state_token)
348
  input_mask.append(jnp.ones((batch_observation["numeric_state"].shape[0], 1), dtype=jnp.bool_))
 
349
  # image/language inputs do not attend to state or actions
350
  ar_mask += [True]
351
 
@@ -353,7 +385,8 @@ class Pi0(nnx.Module):
353
  time_emb = posemb_sincos(timestep, self.action_in_proj.out_features, min_period=4e-3, max_period=4.0)
354
  # mix timestep + action information using an MLP
355
  action_tokens = self.action_in_proj(batch_noisy_action["numeric_states"])
356
- time_tokens = einops.repeat(time_emb, "b emb -> b s emb", s=self.action_horizon)
 
357
  action_time_tokens = jnp.concatenate([action_tokens, time_tokens], axis=-1)
358
  action_time_tokens = self.action_time_mlp_in(action_time_tokens)
359
  action_time_tokens = nnx.swish(action_time_tokens)
@@ -361,51 +394,18 @@ class Pi0(nnx.Module):
361
  tokens.append(action_time_tokens)
362
  input_mask.append(jnp.ones(action_time_tokens.shape[:2], dtype=jnp.bool_))
363
  # image/language/state inputs do not attend to action tokens
364
- ar_mask += [True] + ([False] * (self.action_horizon - 1))
365
  tokens = jnp.concatenate(tokens, axis=1)
366
  input_mask = jnp.concatenate(input_mask, axis=1)
367
  ar_mask = jnp.array(ar_mask)
368
- return tokens, input_mask, ar_mask
369
-
370
- # TODO typing
371
- # @override
372
- def compute_loss(
373
- self,
374
- rng: jt.PRNGKeyArray,
375
- batch_observation: SpaceVar[ObservationSpec.batched],
376
- batch_action: SpaceVar[ActionSpec.batched],
377
- # *,
378
- # train: bool = False,
379
- ) -> jt.Float[jt.Array, "*b ah"]:
380
- preprocess_rng, noise_rng, time_rng = jax.random.split(rng, 3)
381
- # TODO rm
382
- # observation = _model.preprocess_observation(preprocess_rng, observation, train=train)
383
 
384
- batch_shape = batch_action["numeric_states"].shape[:-2]
385
- noise = jax.random.normal(noise_rng, batch_action["numeric_states"].shape)
386
- time = jax.random.beta(time_rng, 1.5, 1, batch_shape) * 0.999 + 0.001
387
- time_expanded = time[..., None, None]
388
- x_t = time_expanded * noise + (1 - time_expanded) * batch_action["numeric_states"]
389
- u_t = noise - batch_action["numeric_states"]
390
-
391
- # one big forward pass of prefix + suffix at once
392
- prefix_tokens, prefix_mask, prefix_ar_mask = self._embed_prefix(batch_observation)
393
- suffix_tokens, suffix_mask, suffix_ar_mask = self._embed_suffix(batch_observation, {"numeric_states": x_t}, time)
394
- input_mask = jnp.concatenate([prefix_mask, suffix_mask], axis=1)
395
- ar_mask = jnp.concatenate([prefix_ar_mask, suffix_ar_mask], axis=0)
396
- attn_mask = make_attn_mask(input_mask, ar_mask)
397
- positions = jnp.cumsum(input_mask, axis=1) - 1
398
- (prefix_out, suffix_out), _ = self._language_model(
399
- [prefix_tokens, suffix_tokens], mask=attn_mask, positions=positions
400
- )
401
- v_t = self.action_out_proj(suffix_out[:, -self.action_horizon :])
402
-
403
- return jnp.mean(jnp.square(v_t - u_t), axis=-1)
404
 
 
405
  # @override
406
  def sample_actions(
407
  self,
408
- rng: jt.PRNGKeyArray,
409
  batch_observation: SpaceVar[ObservationSpec.batched],
410
  # *,
411
  num_steps: int | jt.Int[jt.Array, ""] = 10,
@@ -417,14 +417,15 @@ class Pi0(nnx.Module):
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[0]
421
- noise = jax.random.normal(rng, (batch_size, self.action_horizon, self.action_dim))
 
422
 
423
  # first fill KV cache with a forward pass of the prefix
424
  prefix_tokens, prefix_mask, prefix_ar_mask = self._embed_prefix(batch_observation)
425
  prefix_attn_mask = make_attn_mask(prefix_mask, prefix_ar_mask)
426
  positions = jnp.cumsum(prefix_mask, axis=1) - 1
427
- _, kv_cache = self._language_model([prefix_tokens, None], mask=prefix_attn_mask, positions=positions)
428
 
429
  def step(carry):
430
  x_t, time = carry
@@ -448,11 +449,11 @@ class Pi0(nnx.Module):
448
  # `positions` is shape (b, suffix_len) indicating the positions of the suffix tokens
449
  positions = jnp.sum(prefix_mask, axis=-1)[:, None] + jnp.cumsum(suffix_mask, axis=-1) - 1
450
 
451
- (prefix_out, suffix_out), _ = self._language_model(
452
  [None, suffix_tokens], mask=full_attn_mask, positions=positions, kv_cache=kv_cache
453
  )
454
  assert prefix_out is None
455
- v_t = self.action_out_proj(suffix_out[:, -self.action_horizon :])
456
 
457
  return x_t + dt * v_t, time + dt
458
 
@@ -464,8 +465,250 @@ class Pi0(nnx.Module):
464
  x_0, _ = jax.lax.while_loop(cond, step, (noise, 1.0))
465
  return {"numeric_states": x_0}
466
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
467
 
468
  # TODO
469
  __all__ = [
470
  "Pi0",
 
471
  ]
 
6
  # TODO ref pi0!!!!
7
 
8
 
9
+ import functools
10
  import re
11
  import dataclasses
12
  from typing import Any
13
  # TODO
14
  import dataclasses
15
 
16
+ import optax
17
+
18
  import gymnasium.spaces
19
  import numpy
20
 
 
32
  import jax
33
  import jax.numpy as jnp
34
  import jaxtyping as jt
 
 
 
 
 
 
 
 
35
 
36
  from . import gemma as _gemma
37
  from . import siglip as _siglip
 
109
  class Pi0(nnx.Module):
110
  """
111
  TODO
112
+
113
+ Example:
114
+ .. code-block:: python
115
+
116
+ # TODO
117
 
118
  """
119
 
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).
 
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:
144
+ - `image_names <https://github.com/Physical-Intelligence/openpi/blob/84cd4dc87854856a4fd878cc8951cbc59023eaa7/src/openpi/models/model.py#L33-L38>`_
145
+ - `image_size <https://github.com/Physical-Intelligence/openpi/blob/84cd4dc87854856a4fd878cc8951cbc59023eaa7/src/openpi/models/model.py#L42>`_
146
+ - `text_max_len <https://github.com/Physical-Intelligence/openpi/blob/84cd4dc87854856a4fd878cc8951cbc59023eaa7/src/openpi/models/pi0.py#L76>`_
147
+ - `text_vocab_size <https://github.com/Physical-Intelligence/openpi/blob/84cd4dc87854856a4fd878cc8951cbc59023eaa7/src/openpi/models/gemma.py#L41>`_
148
+ - `numeric_state_size <https://github.com/Physical-Intelligence/openpi/blob/84cd4dc87854856a4fd878cc8951cbc59023eaa7/src/openpi/models/pi0.py#L74>`_
149
  """
150
 
151
  self.feature_specs = {
 
198
  class ActionSpec(gymnasium.spaces.Dict):
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:
212
+ - `numeric_state_size <https://github.com/Physical-Intelligence/openpi/blob/84cd4dc87854856a4fd878cc8951cbc59023eaa7/src/openpi/models/pi0.py#L74>`_
213
+ - `numeric_state_horizon <https://github.com/Physical-Intelligence/openpi/blob/84cd4dc87854856a4fd878cc8951cbc59023eaa7/src/openpi/models/pi0.py#L75>`_
214
  """
215
 
216
  super().__init__({
 
234
  paligemma_variant: _gemma.Variant = "gemma_2b"
235
  action_expert_variant: _gemma.Variant = "gemma_300m"
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
 
251
  action_expert_config = _gemma.get_config(config.action_expert_variant)
252
 
253
  # TODO: rewrite gemma in NNX. For now, use bridge.
254
+ self.gemma_language_model = nnx_bridge.ToNNX(
255
  _gemma.Module(
256
  configs=[paligemma_config, action_expert_config],
257
  embed_dtype=config.dtype,
258
  )
259
  )
260
  # TODO
261
+ self.gemma_language_model.lazy_init(rngs=rngs, method="init")
262
 
263
+ self.siglip_vision_model = nnx_bridge.ToNNX(
264
  _siglip.Module(
265
  num_classes=paligemma_config.width,
266
  variant="So400m/14",
 
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,
 
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(
293
+ llm=self.gemma_language_model,
294
+ img=self.siglip_vision_model,
295
+ )
296
 
297
+ # TODO necesito?
298
  @property
299
  def config(self) -> Config:
300
  return self._config
 
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,
 
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],
 
336
 
337
  # add language (aka tokenized inputs)
338
  if batch_observation.get("tokenized_text", None) is not None:
339
+ language_embeddings = self.gemma_language_model(
340
  # TODO
341
  batch_observation["tokenized_text"],
342
  method="embed",
 
366
  batch_noisy_action: SpaceVar[ActionSpec.batched],
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 = []
374
  tokens = []
375
+
376
  # add a single state token
377
  state_token = self.state_proj(batch_observation["numeric_state"])[:, None, :]
378
  tokens.append(state_token)
379
  input_mask.append(jnp.ones((batch_observation["numeric_state"].shape[0], 1), dtype=jnp.bool_))
380
+
381
  # image/language inputs do not attend to state or actions
382
  ar_mask += [True]
383
 
 
385
  time_emb = posemb_sincos(timestep, self.action_in_proj.out_features, min_period=4e-3, max_period=4.0)
386
  # mix timestep + action information using an MLP
387
  action_tokens = self.action_in_proj(batch_noisy_action["numeric_states"])
388
+ # TODO !!!!
389
+ time_tokens = einops.repeat(time_emb, "b emb -> b s emb", s=action_horizon)
390
  action_time_tokens = jnp.concatenate([action_tokens, time_tokens], axis=-1)
391
  action_time_tokens = self.action_time_mlp_in(action_time_tokens)
392
  action_time_tokens = nnx.swish(action_time_tokens)
 
394
  tokens.append(action_time_tokens)
395
  input_mask.append(jnp.ones(action_time_tokens.shape[:2], dtype=jnp.bool_))
396
  # image/language/state inputs do not attend to action tokens
397
+ ar_mask += [True] + ([False] * (action_horizon - 1))
398
  tokens = jnp.concatenate(tokens, axis=1)
399
  input_mask = jnp.concatenate(input_mask, axis=1)
400
  ar_mask = jnp.array(ar_mask)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
401
 
402
+ return tokens, input_mask, ar_mask
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
403
 
404
+ # TODO
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,
 
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)
426
  prefix_attn_mask = make_attn_mask(prefix_mask, prefix_ar_mask)
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
 
449
  # `positions` is shape (b, suffix_len) indicating the positions of the suffix tokens
450
  positions = jnp.sum(prefix_mask, axis=-1)[:, None] + jnp.cumsum(suffix_mask, axis=-1) - 1
451
 
452
+ (prefix_out, suffix_out), _ = self.gemma_language_model(
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
 
 
465
  x_0, _ = jax.lax.while_loop(cond, step, (noise, 1.0))
466
  return {"numeric_states": x_0}
467
 
468
+ # TODO typing
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
479
+ preprocess_rng, noise_rng, time_rng = jax.random.split(rng, 3)
480
+ # TODO rm
481
+ # observation = _model.preprocess_observation(preprocess_rng, observation, train=train)
482
+
483
+ batch_size, action_horizon, _ = batch_action["numeric_states"].shape
484
+
485
+ noise = jax.random.normal(noise_rng, batch_action["numeric_states"].shape)
486
+ time = jax.random.beta(time_rng, 1.5, 1, (batch_size, )) * 0.999 + 0.001
487
+ time_expanded = time[..., None, None]
488
+ x_t = time_expanded * noise + (1 - time_expanded) * batch_action["numeric_states"]
489
+ u_t = noise - batch_action["numeric_states"]
490
+
491
+ # one big forward pass of prefix + suffix at once
492
+ prefix_tokens, prefix_mask, prefix_ar_mask = self._embed_prefix(batch_observation)
493
+ suffix_tokens, suffix_mask, suffix_ar_mask = self._embed_suffix(batch_observation, {"numeric_states": x_t}, time)
494
+ input_mask = jnp.concatenate([prefix_mask, suffix_mask], axis=1)
495
+ ar_mask = jnp.concatenate([prefix_ar_mask, suffix_ar_mask], axis=0)
496
+ attn_mask = make_attn_mask(input_mask, ar_mask)
497
+ positions = jnp.cumsum(input_mask, axis=1) - 1
498
+ (prefix_out, suffix_out), _ = self.gemma_language_model(
499
+ [prefix_tokens, suffix_tokens], mask=attn_mask, positions=positions
500
+ )
501
+ v_t = self.action_out_proj(suffix_out[:, -action_horizon :])
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
508
+
509
+ filters = []
510
+ has_lora = False
511
+ gemma_params_filter = RegexFilter(".*llm.*")
512
+ action_expert_params_filter = RegexFilter(".*llm.*_1.*")
513
+
514
+ if "lora" in config.paligemma_variant:
515
+ filters.append(
516
+ gemma_params_filter,
517
+ )
518
+ if "lora" not in config.action_expert_variant:
519
+ # If only freeze gemma params, exclude action expert params.
520
+ filters.append(
521
+ nnx.Not(action_expert_params_filter),
522
+ )
523
+ has_lora = True
524
+ elif "lora" in config.action_expert_variant:
525
+ filters.append(
526
+ action_expert_params_filter,
527
+ )
528
+ has_lora = True
529
+
530
+ if has_lora:
531
+ # If any lora is used, exclude all lora params.
532
+ filters.append(
533
+ nnx.Not(RegexFilter(".*lora.*")),
534
+ )
535
+
536
+ if not filters:
537
+ return nnx.Nothing
538
+
539
+ # TODO orig: nnx.All(nnx.Param, nnx.Not(nnx.All(*filters)))
540
+ return nnx.All(nnx.Param, nnx.Not(nnx.All(*filters)))
541
+
542
+
543
+ class Pi0LearningRateScheduleRecipes:
544
+ @classmethod
545
+ def warmup_cosine_decay_schedule(
546
+ cls,
547
+ warmup_steps: int = 1_000,
548
+ peak_lr: float = 2.5e-5,
549
+ decay_steps: int = 30_000,
550
+ decay_lr: float = 2.5e-6,
551
+ ):
552
+ return optax.warmup_cosine_decay_schedule(
553
+ init_value=peak_lr / (warmup_steps + 1),
554
+ peak_value=peak_lr,
555
+ warmup_steps=warmup_steps,
556
+ decay_steps=decay_steps,
557
+ end_value=decay_lr,
558
+ )
559
+
560
+ @classmethod
561
+ def rsqrt_decay_schedule(
562
+ cls,
563
+ warmup_steps: int = 1_000,
564
+ peak_lr: float = 5e-5,
565
+ timescale: float = 10_000,
566
+ ):
567
+ return optax.join_schedules(
568
+ [
569
+ optax.linear_schedule(
570
+ init_value=peak_lr / (warmup_steps + 1),
571
+ end_value=peak_lr,
572
+ transition_steps=warmup_steps,
573
+ ),
574
+ lambda step: peak_lr / jnp.sqrt((timescale + step) / timescale),
575
+ ],
576
+ [warmup_steps],
577
+ )
578
+
579
+ class Pi0OptimizerRecipes:
580
+ @classmethod
581
+ def adamw(
582
+ cls,
583
+ clip_gradient_norm: float = 1.,
584
+ **optax_adamw_kwargs,
585
+ ):
586
+ return optax.chain(
587
+ optax.clip_by_global_norm(clip_gradient_norm),
588
+ optax.adamw(**{
589
+ "b1": 0.9,
590
+ "b2": 0.95,
591
+ "eps": 1e-8,
592
+ "weight_decay": 1e-10,
593
+ **optax_adamw_kwargs,
594
+ })
595
+ )
596
+
597
+ @classmethod
598
+ def sgd(cls, **optax_sgd_kwargs):
599
+ return optax.sgd(**{
600
+ "learning_rate": 5e-5,
601
+ "momentum": 0.9,
602
+ "nesterov": False,
603
+ **optax_sgd_kwargs,
604
+ })
605
+
606
+ class Pi0Trainer(nnx.Module):
607
+ """
608
+ TODO
609
+
610
+
611
+ Example usage:
612
+ .. code-block:: python
613
+
614
+ import optax
615
+
616
+ model = Pi0()
617
+ trainer = Pi0Trainer(
618
+ config=Pi0Trainer.Config(
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:
637
+ optimizer_state: optax.OptState
638
+ step_n: int = 0
639
+
640
+ def __init__(self, model: Pi0, config: Config = Config()):
641
+ self._model = model
642
+ self._config = config
643
+ #
644
+ self._state = self.State(
645
+ optimizer_state=self._config.optimizer.init(
646
+ nnx.state(self._model, self._model.trainable_filter),
647
+ ),
648
+ step_n=0,
649
+ )
650
+
651
+ @dataclasses.dataclass(frozen=True)
652
+ class StepResult:
653
+ loss: jt.Array
654
+ grads: jt.Array
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
664
+ rng_train_step = jax.random.fold_in(rng, self._state.step_n)
665
+
666
+ # @at.typecheck
667
+ def loss_fn(
668
+ model: Pi0,
669
+ rng: jt.PRNGKeyArray,
670
+ batch_observation: SpaceVar[Pi0.ObservationSpec.batched],
671
+ batch_action: SpaceVar[Pi0.ActionSpec.batched],
672
+ ):
673
+ chunked_loss = model.compute_loss(
674
+ batch_observation=batch_observation,
675
+ batch_action=batch_action,
676
+ rng=rng,
677
+ )
678
+ return jnp.mean(chunked_loss)
679
+ # TODO
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,
689
+ batch_observation=batch_observation,
690
+ batch_action=batch_action,
691
+ )
692
+
693
+ trainable_params = nnx.state(self._model, self._model.trainable_filter)
694
+ optimizer_updates, self._state.optimizer_state = self._config.optimizer.update(
695
+ grads,
696
+ self._state.optimizer_state,
697
+ params=trainable_params,
698
+ )
699
+ trainable_params = optax.apply_updates(trainable_params, optimizer_updates)
700
+ nnx.update(self._model, trainable_params)
701
+
702
+ self._state.step_n += 1
703
+
704
+ return self.StepResult(
705
+ loss=loss,
706
+ grads=grads,
707
+ )
708
+
709
 
710
  # TODO
711
  __all__ = [
712
  "Pi0",
713
+ "Pi0Trainer",
714
  ]
packages/robotodo/controllers/pi0/nn/siglip.py CHANGED
@@ -207,7 +207,8 @@ class _Module(nn.Module):
207
 
208
  def init(self, image, *, train=False):
209
  # TODO NOTE image: batch, height, width, channels
210
- if (jnp.array(image.shape)[jnp.array([1, 2])] < jnp.array(self.patch_size)).any():
 
211
  raise ValueError(
212
  f"Image shape ({image.shape}) must be at least "
213
  f"the patch size ({self.patch_size}) in height and width."
 
207
 
208
  def init(self, image, *, train=False):
209
  # TODO NOTE image: batch, height, width, channels
210
+ image = jnp.asarray(image)
211
+ if any(s < p for s, p in zip(image.shape[1:3], self.patch_size)):
212
  raise ValueError(
213
  f"Image shape ({image.shape}) must be at least "
214
  f"the patch size ({self.patch_size}) in height and width."
packages/robotodo/controllers/pi0/pi0_controller.py CHANGED
@@ -6,7 +6,7 @@ from typing import TypedDict
6
  import gymnasium.spaces
7
 
8
 
9
- from .nn.pi0 import Pi0
10
  from .paligemma_tokenizer import PaligemmaTokenizer
11
 
12
 
 
6
  import gymnasium.spaces
7
 
8
 
9
+ from .nn.pi0 import Pi0, Pi0Trainer
10
  from .paligemma_tokenizer import PaligemmaTokenizer
11
 
12
 
packages/robotodo/controllers/pi0/utils/download.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # TODO ref pi0
2
+
3
+
4
+ import concurrent.futures
5
+ import datetime
6
+ import getpass
7
+ import logging
8
+ import os
9
+ import pathlib
10
+ import re
11
+ import shutil
12
+ import stat
13
+ import time
14
+ import urllib.parse
15
+
16
+ import filelock
17
+ import fsspec
18
+ import fsspec.generic
19
+ # TODO
20
+ # import tqdm_loggable.auto as tqdm
21
+ import tqdm.auto as tqdm
22
+
23
+ # Environment variable to control cache directory path, ~/.cache/openpi will be used by default.
24
+ _OPENPI_DATA_HOME = "OPENPI_DATA_HOME"
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+
29
+ def get_cache_dir() -> pathlib.Path:
30
+ default_dir = "~/.cache/openpi"
31
+ # if os.path.exists("/mnt/weka"): # noqa: PTH110
32
+ # default_dir = f"/mnt/weka/{getpass.getuser()}/.cache/openpi"
33
+
34
+ cache_dir = pathlib.Path(os.getenv(_OPENPI_DATA_HOME, default_dir)).expanduser().resolve()
35
+ cache_dir.mkdir(parents=True, exist_ok=True)
36
+ _set_folder_permission(cache_dir)
37
+ return cache_dir
38
+
39
+
40
+ def maybe_download(url: str, *, force_download: bool = False, **kwargs) -> pathlib.Path:
41
+ """Download a file or directory from a remote filesystem to the local cache, and return the local path.
42
+
43
+ If the local file already exists, it will be returned directly.
44
+
45
+ It is safe to call this function concurrently from multiple processes.
46
+ See `get_cache_dir` for more details on the cache directory.
47
+
48
+ Args:
49
+ url: URL to the file to download.
50
+ force_download: If True, the file will be downloaded even if it already exists in the cache.
51
+ **kwargs: Additional arguments to pass to fsspec.
52
+
53
+ Returns:
54
+ Local path to the downloaded file or directory. That path is guaranteed to exist and is absolute.
55
+ """
56
+ # Don't use fsspec to parse the url to avoid unnecessary connection to the remote filesystem.
57
+ parsed = urllib.parse.urlparse(url)
58
+
59
+ # Short circuit if this is a local path.
60
+ if parsed.scheme == "":
61
+ path = pathlib.Path(url)
62
+ if not path.exists():
63
+ raise FileNotFoundError(f"File not found at {url}")
64
+ return path.resolve()
65
+
66
+ cache_dir = get_cache_dir()
67
+
68
+ local_path = cache_dir / parsed.netloc / parsed.path.strip("/")
69
+ local_path = local_path.resolve()
70
+
71
+ # Check if the cache should be invalidated.
72
+ invalidate_cache = False
73
+ if local_path.exists():
74
+ if force_download or _should_invalidate_cache(cache_dir, local_path):
75
+ invalidate_cache = True
76
+ else:
77
+ return local_path
78
+
79
+ try:
80
+ lock_path = local_path.with_suffix(".lock")
81
+ with filelock.FileLock(lock_path):
82
+ # Ensure consistent permissions for the lock file.
83
+ _ensure_permissions(lock_path)
84
+ # First, remove the existing cache if it is expired.
85
+ if invalidate_cache:
86
+ logger.info(f"Removing expired cached entry: {local_path}")
87
+ if local_path.is_dir():
88
+ shutil.rmtree(local_path)
89
+ else:
90
+ local_path.unlink()
91
+
92
+ # Download the data to a local cache.
93
+ logger.info(f"Downloading {url} to {local_path}")
94
+ scratch_path = local_path.with_suffix(".partial")
95
+ _download_fsspec(url, scratch_path, **kwargs)
96
+
97
+ shutil.move(scratch_path, local_path)
98
+ _ensure_permissions(local_path)
99
+
100
+ except PermissionError as e:
101
+ msg = (
102
+ f"Local file permission error was encountered while downloading {url}. "
103
+ f"Please try again after removing the cached data using: `rm -rf {local_path}*`"
104
+ )
105
+ raise PermissionError(msg) from e
106
+
107
+ return local_path
108
+
109
+
110
+ def _download_fsspec(url: str, local_path: pathlib.Path, **kwargs) -> None:
111
+ """Download a file from a remote filesystem to the local cache, and return the local path."""
112
+ fs, _ = fsspec.core.url_to_fs(url, **kwargs)
113
+ info = fs.info(url)
114
+ # Folders are represented by 0-byte objects with a trailing forward slash.
115
+ if is_dir := (info["type"] == "directory" or (info["size"] == 0 and info["name"].endswith("/"))):
116
+ total_size = fs.du(url)
117
+ else:
118
+ total_size = info["size"]
119
+ with tqdm.tqdm(total=total_size, unit="iB", unit_scale=True, unit_divisor=1024) as pbar:
120
+ executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
121
+ future = executor.submit(fs.get, url, local_path, recursive=is_dir)
122
+ while not future.done():
123
+ current_size = sum(f.stat().st_size for f in [*local_path.rglob("*"), local_path] if f.is_file())
124
+ pbar.update(current_size - pbar.n)
125
+ time.sleep(1)
126
+ pbar.update(total_size - pbar.n)
127
+
128
+
129
+ def _set_permission(path: pathlib.Path, target_permission: int):
130
+ """chmod requires executable permission to be set, so we skip if the permission is already match with the target."""
131
+ if path.stat().st_mode & target_permission == target_permission:
132
+ logger.debug(f"Skipping {path} because it already has correct permissions")
133
+ return
134
+ path.chmod(target_permission)
135
+ logger.debug(f"Set {path} to {target_permission}")
136
+
137
+
138
+ def _set_folder_permission(folder_path: pathlib.Path) -> None:
139
+ """Set folder permission to be read, write and searchable."""
140
+ _set_permission(folder_path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
141
+
142
+
143
+ def _ensure_permissions(path: pathlib.Path) -> None:
144
+ """Since we are sharing cache directory with containerized runtime as well as training script, we need to
145
+ ensure that the cache directory has the correct permissions.
146
+ """
147
+
148
+ def _setup_folder_permission_between_cache_dir_and_path(path: pathlib.Path) -> None:
149
+ cache_dir = get_cache_dir()
150
+ relative_path = path.relative_to(cache_dir)
151
+ moving_path = cache_dir
152
+ for part in relative_path.parts:
153
+ _set_folder_permission(moving_path / part)
154
+ moving_path = moving_path / part
155
+
156
+ def _set_file_permission(file_path: pathlib.Path) -> None:
157
+ """Set all files to be read & writable, if it is a script, keep it as a script."""
158
+ file_rw = stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IWGRP | stat.S_IROTH | stat.S_IWOTH
159
+ if file_path.stat().st_mode & 0o100:
160
+ _set_permission(file_path, file_rw | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
161
+ else:
162
+ _set_permission(file_path, file_rw)
163
+
164
+ _setup_folder_permission_between_cache_dir_and_path(path)
165
+ for root, dirs, files in os.walk(str(path)):
166
+ root_path = pathlib.Path(root)
167
+ for file in files:
168
+ file_path = root_path / file
169
+ _set_file_permission(file_path)
170
+
171
+ for dir in dirs:
172
+ dir_path = root_path / dir
173
+ _set_folder_permission(dir_path)
174
+
175
+
176
+ def _get_mtime(year: int, month: int, day: int) -> float:
177
+ """Get the mtime of a given date at midnight UTC."""
178
+ date = datetime.datetime(year, month, day, tzinfo=datetime.UTC)
179
+ return time.mktime(date.timetuple())
180
+
181
+
182
+ # Map of relative paths, defined as regular expressions, to expiration timestamps (mtime format).
183
+ # Partial matching will be used from top to bottom and the first match will be chosen.
184
+ # Cached entries will be retained only if they are newer than the expiration timestamp.
185
+ _INVALIDATE_CACHE_DIRS: dict[re.Pattern, float] = {
186
+ re.compile("openpi-assets/checkpoints/pi0_aloha_pen_uncap"): _get_mtime(2025, 2, 17),
187
+ re.compile("openpi-assets/checkpoints/pi0_libero"): _get_mtime(2025, 2, 6),
188
+ re.compile("openpi-assets/checkpoints/"): _get_mtime(2025, 2, 3),
189
+ }
190
+
191
+
192
+ def _should_invalidate_cache(cache_dir: pathlib.Path, local_path: pathlib.Path) -> bool:
193
+ """Invalidate the cache if it is expired. Return True if the cache was invalidated."""
194
+
195
+ assert local_path.exists(), f"File not found at {local_path}"
196
+
197
+ relative_path = str(local_path.relative_to(cache_dir))
198
+ for pattern, expire_time in _INVALIDATE_CACHE_DIRS.items():
199
+ if pattern.match(relative_path):
200
+ # Remove if not newer than the expiration timestamp.
201
+ return local_path.stat().st_mtime <= expire_time
202
+
203
+ return False
packages/robotodo/scenes/robotwin_labs/__init__.py CHANGED
@@ -8,7 +8,7 @@ import sapien
8
 
9
 
10
  # TODO
11
- def make_scene():
12
  engine = sapien.Engine()
13
  # declare sapien renderer
14
  # from sapien.render import set_global_config
 
8
 
9
 
10
  # TODO
11
+ def _todo_make_scene():
12
  engine = sapien.Engine()
13
  # declare sapien renderer
14
  # from sapien.render import set_global_config