xiwenliang commited on
Commit
cbae7c6
·
verified ·
1 Parent(s): c609207

Remove unnecessary uploaded training code

Browse files
code/hb_baselines_20261117/baselines/__init__.py DELETED
@@ -1,8 +0,0 @@
1
- """FM-DiT, DP (Diffusion Policy, DDPM-DiT) and ACT visuomotor baselines of the Humanoid Benchmark.
2
-
3
- Ported from DextraVerse's imitation-learning core (`dextraverse/algorithms/il/models/{fm_dit,ddpm_dit,act}.py` and
4
- their networks), torch only. `train.py` trains one on a task's LeRobot v2.1 expert dataset through a robot contract
5
- (`data.CONTRACTS`: G1 state44/action76 or H2 state78/action75); `runtime.BaselinePolicy` serves a checkpoint to the
6
- G1 evaluation adapters (`evaluation/policy/{FMDiT,DP,ACT}/model.py`, via `adapters.py`) and to the H2 adapter
7
- (`debug/newton/h2_policy_adapters/baseline.py`). Usage and the environment: evaluation/README.md#baselines.
8
- """
 
 
 
 
 
 
 
 
 
code/hb_baselines_20261117/baselines/act_nets.py DELETED
@@ -1,615 +0,0 @@
1
- """ACT (Zhao et al. 2023, "Learning Fine-Grained Bimanual Manipulation with Low-Cost Hardware") network core: the
2
- ResNet backbone with frozen BatchNorm and sine position embedding, the DETR encoder-decoder transformer and the CVAE
3
- action-chunk decoder.
4
-
5
- Ported unchanged from DextraVerse (`dextraverse/algorithms/il/models/nets/act/`), which vendors the ACT repository's
6
- `detr/models/{backbone,position_encoding,transformer,detr_vae}.py` (Apache-2.0, (c) Facebook, Inc. and its
7
- affiliates; see THIRD_PARTY_NOTICES.md) with the NestedTensor/argparse plumbing removed, explicit `qpos_dim` /
8
- `action_dim` instead of the ALOHA 14-DoF constants, and one backbone shared by every camera (upstream behaviour).
9
- The policy uses `return_intermediate_dec=False`: `Transformer.forward(...)[0]` is the final decoder layer.
10
- """
11
- from __future__ import annotations
12
-
13
- import copy
14
- import math
15
- from typing import Optional
16
-
17
- import numpy as np
18
- import torch
19
- import torch.nn.functional as F
20
- import torchvision
21
- from torch import Tensor, nn
22
- from torchvision.models._utils import IntermediateLayerGetter
23
-
24
-
25
- class PositionEmbeddingSine(nn.Module):
26
- """Standard DETR sine embedding over a ``(B, C, H, W)`` feature map."""
27
-
28
- def __init__(
29
- self, num_pos_feats: int = 64, temperature: int = 10000, normalize: bool = False
30
- ) -> None:
31
- super().__init__()
32
- self.num_pos_feats = num_pos_feats
33
- self.temperature = temperature
34
- self.normalize = normalize
35
- self.scale = 2 * math.pi
36
-
37
- def forward(self, x: torch.Tensor) -> torch.Tensor:
38
- not_mask = torch.ones((1, x.shape[-2], x.shape[-1]), device=x.device)
39
- y_embed = not_mask.cumsum(1, dtype=torch.float32)
40
- x_embed = not_mask.cumsum(2, dtype=torch.float32)
41
- if self.normalize:
42
- eps = 1e-6
43
- y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale
44
- x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale
45
-
46
- dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device)
47
- dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats)
48
-
49
- pos_x = x_embed[:, :, :, None] / dim_t
50
- pos_y = y_embed[:, :, :, None] / dim_t
51
- pos_x = torch.stack(
52
- (pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4
53
- ).flatten(3)
54
- pos_y = torch.stack(
55
- (pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4
56
- ).flatten(3)
57
- return torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)
58
-
59
-
60
- class FrozenBatchNorm2d(nn.Module):
61
- """BatchNorm2d with fixed statistics and affine parameters (the DETR/ACT backbone norm)."""
62
-
63
- def __init__(self, n: int) -> None:
64
- super().__init__()
65
- self.register_buffer("weight", torch.ones(n))
66
- self.register_buffer("bias", torch.zeros(n))
67
- self.register_buffer("running_mean", torch.zeros(n))
68
- self.register_buffer("running_var", torch.ones(n))
69
-
70
- def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, *args):
71
- state_dict.pop(prefix + "num_batches_tracked", None)
72
- super()._load_from_state_dict(state_dict, prefix, local_metadata, strict, *args)
73
-
74
- def forward(self, x: torch.Tensor) -> torch.Tensor:
75
- w = self.weight.reshape(1, -1, 1, 1)
76
- b = self.bias.reshape(1, -1, 1, 1)
77
- rv = self.running_var.reshape(1, -1, 1, 1)
78
- rm = self.running_mean.reshape(1, -1, 1, 1)
79
- scale = w * (rv + 1e-5).rsqrt()
80
- return x * scale + (b - rm * scale)
81
-
82
-
83
- class Backbone(nn.Module):
84
- """ResNet trunk returning the layer4 feature map."""
85
-
86
- def __init__(self, name: str = "resnet18", weights: str | None = None) -> None:
87
- super().__init__()
88
- trunk = getattr(torchvision.models, name)(
89
- replace_stride_with_dilation=[False, False, False],
90
- weights=weights,
91
- norm_layer=FrozenBatchNorm2d,
92
- )
93
- self.body = IntermediateLayerGetter(trunk, return_layers={"layer4": "0"})
94
- self.num_channels = 512 if name in ("resnet18", "resnet34") else 2048
95
-
96
- def forward(self, x: torch.Tensor) -> dict[str, torch.Tensor]:
97
- return self.body(x)
98
-
99
-
100
- class Joiner(nn.Sequential):
101
- """Backbone + position embedding, returning matched feature/position lists."""
102
-
103
- def __init__(self, backbone: Backbone, position_embedding: PositionEmbeddingSine) -> None:
104
- super().__init__(backbone, position_embedding)
105
- self.num_channels = backbone.num_channels
106
-
107
- def forward(self, x: torch.Tensor) -> tuple[list[torch.Tensor], list[torch.Tensor]]:
108
- features = list(self[0](x).values())
109
- pos = [self[1](f).to(f.dtype) for f in features]
110
- return features, pos
111
-
112
-
113
- def build_backbone(
114
- name: str = "resnet18", hidden_dim: int = 512, weights: str | None = None
115
- ) -> Joiner:
116
- """The ACT camera backbone: ResNet + sine embedding sized to the transformer width."""
117
- return Joiner(Backbone(name, weights=weights), PositionEmbeddingSine(hidden_dim // 2))
118
-
119
-
120
- class Transformer(nn.Module):
121
- def __init__(
122
- self,
123
- d_model=512,
124
- nhead=8,
125
- num_encoder_layers=6,
126
- num_decoder_layers=6,
127
- dim_feedforward=2048,
128
- dropout=0.1,
129
- activation="relu",
130
- normalize_before=False,
131
- return_intermediate_dec=False,
132
- ):
133
- super().__init__()
134
-
135
- encoder_layer = TransformerEncoderLayer(
136
- d_model, nhead, dim_feedforward, dropout, activation, normalize_before
137
- )
138
- encoder_norm = nn.LayerNorm(d_model) if normalize_before else None
139
- self.encoder = TransformerEncoder(encoder_layer, num_encoder_layers, encoder_norm)
140
-
141
- decoder_layer = TransformerDecoderLayer(
142
- d_model, nhead, dim_feedforward, dropout, activation, normalize_before
143
- )
144
- decoder_norm = nn.LayerNorm(d_model)
145
- self.decoder = TransformerDecoder(
146
- decoder_layer,
147
- num_decoder_layers,
148
- decoder_norm,
149
- return_intermediate=return_intermediate_dec,
150
- )
151
-
152
- self._reset_parameters()
153
-
154
- self.d_model = d_model
155
- self.nhead = nhead
156
-
157
- def _reset_parameters(self):
158
- for p in self.parameters():
159
- if p.dim() > 1:
160
- nn.init.xavier_uniform_(p)
161
-
162
- def forward(
163
- self,
164
- src,
165
- mask,
166
- query_embed,
167
- pos_embed,
168
- latent_input=None,
169
- proprio_input=None,
170
- additional_pos_embed=None,
171
- ):
172
- # TODO flatten only when input has H and W
173
- if len(src.shape) == 4: # has H and W
174
- # flatten NxCxHxW to HWxNxC
175
- bs, c, h, w = src.shape
176
- src = src.flatten(2).permute(2, 0, 1)
177
- pos_embed = pos_embed.flatten(2).permute(2, 0, 1).repeat(1, bs, 1)
178
- query_embed = query_embed.unsqueeze(1).repeat(1, bs, 1)
179
- # mask = mask.flatten(1)
180
-
181
- additional_pos_embed = additional_pos_embed.unsqueeze(1).repeat(
182
- 1, bs, 1
183
- ) # seq, bs, dim
184
- pos_embed = torch.cat([additional_pos_embed, pos_embed], axis=0)
185
-
186
- addition_input = torch.stack([latent_input, proprio_input], axis=0)
187
- src = torch.cat([addition_input, src], axis=0)
188
- else:
189
- assert len(src.shape) == 3
190
- # flatten NxHWxC to HWxNxC
191
- bs, hw, c = src.shape
192
- src = src.permute(1, 0, 2)
193
- pos_embed = pos_embed.unsqueeze(1).repeat(1, bs, 1)
194
- query_embed = query_embed.unsqueeze(1).repeat(1, bs, 1)
195
-
196
- tgt = torch.zeros_like(query_embed)
197
- memory = self.encoder(src, src_key_padding_mask=mask, pos=pos_embed)
198
- hs = self.decoder(
199
- tgt, memory, memory_key_padding_mask=mask, pos=pos_embed, query_pos=query_embed
200
- )
201
- hs = hs.transpose(1, 2)
202
- return hs
203
-
204
-
205
- class TransformerEncoder(nn.Module):
206
- def __init__(self, encoder_layer, num_layers, norm=None):
207
- super().__init__()
208
- self.layers = _get_clones(encoder_layer, num_layers)
209
- self.num_layers = num_layers
210
- self.norm = norm
211
-
212
- def forward(
213
- self,
214
- src,
215
- mask: Optional[Tensor] = None,
216
- src_key_padding_mask: Optional[Tensor] = None,
217
- pos: Optional[Tensor] = None,
218
- ):
219
- output = src
220
-
221
- for layer in self.layers:
222
- output = layer(
223
- output, src_mask=mask, src_key_padding_mask=src_key_padding_mask, pos=pos
224
- )
225
-
226
- if self.norm is not None:
227
- output = self.norm(output)
228
-
229
- return output
230
-
231
-
232
- class TransformerDecoder(nn.Module):
233
- def __init__(self, decoder_layer, num_layers, norm=None, return_intermediate=False):
234
- super().__init__()
235
- self.layers = _get_clones(decoder_layer, num_layers)
236
- self.num_layers = num_layers
237
- self.norm = norm
238
- self.return_intermediate = return_intermediate
239
-
240
- def forward(
241
- self,
242
- tgt,
243
- memory,
244
- tgt_mask: Optional[Tensor] = None,
245
- memory_mask: Optional[Tensor] = None,
246
- tgt_key_padding_mask: Optional[Tensor] = None,
247
- memory_key_padding_mask: Optional[Tensor] = None,
248
- pos: Optional[Tensor] = None,
249
- query_pos: Optional[Tensor] = None,
250
- ):
251
- output = tgt
252
-
253
- intermediate = []
254
-
255
- for layer in self.layers:
256
- output = layer(
257
- output,
258
- memory,
259
- tgt_mask=tgt_mask,
260
- memory_mask=memory_mask,
261
- tgt_key_padding_mask=tgt_key_padding_mask,
262
- memory_key_padding_mask=memory_key_padding_mask,
263
- pos=pos,
264
- query_pos=query_pos,
265
- )
266
- if self.return_intermediate:
267
- intermediate.append(self.norm(output))
268
-
269
- if self.norm is not None:
270
- output = self.norm(output)
271
- if self.return_intermediate:
272
- intermediate.pop()
273
- intermediate.append(output)
274
-
275
- if self.return_intermediate:
276
- return torch.stack(intermediate)
277
-
278
- return output.unsqueeze(0)
279
-
280
-
281
- class TransformerEncoderLayer(nn.Module):
282
- def __init__(
283
- self,
284
- d_model,
285
- nhead,
286
- dim_feedforward=2048,
287
- dropout=0.1,
288
- activation="relu",
289
- normalize_before=False,
290
- ):
291
- super().__init__()
292
- self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
293
- # Implementation of Feedforward model
294
- self.linear1 = nn.Linear(d_model, dim_feedforward)
295
- self.dropout = nn.Dropout(dropout)
296
- self.linear2 = nn.Linear(dim_feedforward, d_model)
297
-
298
- self.norm1 = nn.LayerNorm(d_model)
299
- self.norm2 = nn.LayerNorm(d_model)
300
- self.dropout1 = nn.Dropout(dropout)
301
- self.dropout2 = nn.Dropout(dropout)
302
-
303
- self.activation = _get_activation_fn(activation)
304
- self.normalize_before = normalize_before
305
-
306
- def with_pos_embed(self, tensor, pos: Optional[Tensor]):
307
- return tensor if pos is None else tensor + pos
308
-
309
- def forward_post(
310
- self,
311
- src,
312
- src_mask: Optional[Tensor] = None,
313
- src_key_padding_mask: Optional[Tensor] = None,
314
- pos: Optional[Tensor] = None,
315
- ):
316
- q = k = self.with_pos_embed(src, pos)
317
- src2 = self.self_attn(
318
- q, k, value=src, attn_mask=src_mask, key_padding_mask=src_key_padding_mask
319
- )[0]
320
- src = src + self.dropout1(src2)
321
- src = self.norm1(src)
322
- src2 = self.linear2(self.dropout(self.activation(self.linear1(src))))
323
- src = src + self.dropout2(src2)
324
- src = self.norm2(src)
325
- return src
326
-
327
- def forward_pre(
328
- self,
329
- src,
330
- src_mask: Optional[Tensor] = None,
331
- src_key_padding_mask: Optional[Tensor] = None,
332
- pos: Optional[Tensor] = None,
333
- ):
334
- src2 = self.norm1(src)
335
- q = k = self.with_pos_embed(src2, pos)
336
- src2 = self.self_attn(
337
- q, k, value=src2, attn_mask=src_mask, key_padding_mask=src_key_padding_mask
338
- )[0]
339
- src = src + self.dropout1(src2)
340
- src2 = self.norm2(src)
341
- src2 = self.linear2(self.dropout(self.activation(self.linear1(src2))))
342
- src = src + self.dropout2(src2)
343
- return src
344
-
345
- def forward(
346
- self,
347
- src,
348
- src_mask: Optional[Tensor] = None,
349
- src_key_padding_mask: Optional[Tensor] = None,
350
- pos: Optional[Tensor] = None,
351
- ):
352
- if self.normalize_before:
353
- return self.forward_pre(src, src_mask, src_key_padding_mask, pos)
354
- return self.forward_post(src, src_mask, src_key_padding_mask, pos)
355
-
356
-
357
- class TransformerDecoderLayer(nn.Module):
358
- def __init__(
359
- self,
360
- d_model,
361
- nhead,
362
- dim_feedforward=2048,
363
- dropout=0.1,
364
- activation="relu",
365
- normalize_before=False,
366
- ):
367
- super().__init__()
368
- self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
369
- self.multihead_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
370
- # Implementation of Feedforward model
371
- self.linear1 = nn.Linear(d_model, dim_feedforward)
372
- self.dropout = nn.Dropout(dropout)
373
- self.linear2 = nn.Linear(dim_feedforward, d_model)
374
-
375
- self.norm1 = nn.LayerNorm(d_model)
376
- self.norm2 = nn.LayerNorm(d_model)
377
- self.norm3 = nn.LayerNorm(d_model)
378
- self.dropout1 = nn.Dropout(dropout)
379
- self.dropout2 = nn.Dropout(dropout)
380
- self.dropout3 = nn.Dropout(dropout)
381
-
382
- self.activation = _get_activation_fn(activation)
383
- self.normalize_before = normalize_before
384
-
385
- def with_pos_embed(self, tensor, pos: Optional[Tensor]):
386
- return tensor if pos is None else tensor + pos
387
-
388
- def forward_post(
389
- self,
390
- tgt,
391
- memory,
392
- tgt_mask: Optional[Tensor] = None,
393
- memory_mask: Optional[Tensor] = None,
394
- tgt_key_padding_mask: Optional[Tensor] = None,
395
- memory_key_padding_mask: Optional[Tensor] = None,
396
- pos: Optional[Tensor] = None,
397
- query_pos: Optional[Tensor] = None,
398
- ):
399
- q = k = self.with_pos_embed(tgt, query_pos)
400
- tgt2 = self.self_attn(
401
- q, k, value=tgt, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask
402
- )[0]
403
- tgt = tgt + self.dropout1(tgt2)
404
- tgt = self.norm1(tgt)
405
- tgt2 = self.multihead_attn(
406
- query=self.with_pos_embed(tgt, query_pos),
407
- key=self.with_pos_embed(memory, pos),
408
- value=memory,
409
- attn_mask=memory_mask,
410
- key_padding_mask=memory_key_padding_mask,
411
- )[0]
412
- tgt = tgt + self.dropout2(tgt2)
413
- tgt = self.norm2(tgt)
414
- tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt))))
415
- tgt = tgt + self.dropout3(tgt2)
416
- tgt = self.norm3(tgt)
417
- return tgt
418
-
419
- def forward_pre(
420
- self,
421
- tgt,
422
- memory,
423
- tgt_mask: Optional[Tensor] = None,
424
- memory_mask: Optional[Tensor] = None,
425
- tgt_key_padding_mask: Optional[Tensor] = None,
426
- memory_key_padding_mask: Optional[Tensor] = None,
427
- pos: Optional[Tensor] = None,
428
- query_pos: Optional[Tensor] = None,
429
- ):
430
- tgt2 = self.norm1(tgt)
431
- q = k = self.with_pos_embed(tgt2, query_pos)
432
- tgt2 = self.self_attn(
433
- q, k, value=tgt2, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask
434
- )[0]
435
- tgt = tgt + self.dropout1(tgt2)
436
- tgt2 = self.norm2(tgt)
437
- tgt2 = self.multihead_attn(
438
- query=self.with_pos_embed(tgt2, query_pos),
439
- key=self.with_pos_embed(memory, pos),
440
- value=memory,
441
- attn_mask=memory_mask,
442
- key_padding_mask=memory_key_padding_mask,
443
- )[0]
444
- tgt = tgt + self.dropout2(tgt2)
445
- tgt2 = self.norm3(tgt)
446
- tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2))))
447
- tgt = tgt + self.dropout3(tgt2)
448
- return tgt
449
-
450
- def forward(
451
- self,
452
- tgt,
453
- memory,
454
- tgt_mask: Optional[Tensor] = None,
455
- memory_mask: Optional[Tensor] = None,
456
- tgt_key_padding_mask: Optional[Tensor] = None,
457
- memory_key_padding_mask: Optional[Tensor] = None,
458
- pos: Optional[Tensor] = None,
459
- query_pos: Optional[Tensor] = None,
460
- ):
461
- if self.normalize_before:
462
- return self.forward_pre(
463
- tgt,
464
- memory,
465
- tgt_mask,
466
- memory_mask,
467
- tgt_key_padding_mask,
468
- memory_key_padding_mask,
469
- pos,
470
- query_pos,
471
- )
472
- return self.forward_post(
473
- tgt,
474
- memory,
475
- tgt_mask,
476
- memory_mask,
477
- tgt_key_padding_mask,
478
- memory_key_padding_mask,
479
- pos,
480
- query_pos,
481
- )
482
-
483
-
484
- def _get_clones(module, N):
485
- return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
486
-
487
-
488
- def _get_activation_fn(activation):
489
- """Return an activation function given a string."""
490
- if activation == "relu":
491
- return F.relu
492
- if activation == "gelu":
493
- return F.gelu
494
- raise RuntimeError(f"activation should be relu/gelu, not {activation}.")
495
-
496
-
497
-
498
- def reparametrize(mu: torch.Tensor, logvar: torch.Tensor) -> torch.Tensor:
499
- std = logvar.div(2).exp()
500
- return mu + std * torch.randn_like(std)
501
-
502
-
503
- def get_sinusoid_encoding_table(n_position: int, d_hid: int) -> torch.Tensor:
504
- def angle_vec(position: int) -> list[float]:
505
- return [position / np.power(10000, 2 * (j // 2) / d_hid) for j in range(d_hid)]
506
-
507
- table = np.array([angle_vec(i) for i in range(n_position)])
508
- table[:, 0::2] = np.sin(table[:, 0::2])
509
- table[:, 1::2] = np.cos(table[:, 1::2])
510
- return torch.FloatTensor(table).unsqueeze(0)
511
-
512
-
513
- def build_style_encoder(
514
- hidden_dim: int, nheads: int, dim_feedforward: int, enc_layers: int, dropout: float
515
- ) -> TransformerEncoder:
516
- """The CVAE style encoder (a plain transformer encoder over [CLS, qpos, action seq])."""
517
- layer = TransformerEncoderLayer(hidden_dim, nheads, dim_feedforward, dropout, "relu", False)
518
- return TransformerEncoder(layer, enc_layers, norm=None)
519
-
520
-
521
- class DETRVAE(nn.Module):
522
- """CVAE decoder: (qpos, images[, action seq]) → ``num_queries`` future actions."""
523
-
524
- def __init__(
525
- self,
526
- backbone: Joiner,
527
- transformer: Transformer,
528
- encoder: TransformerEncoder,
529
- *,
530
- qpos_dim: int,
531
- action_dim: int,
532
- num_queries: int,
533
- latent_dim: int = 32,
534
- ) -> None:
535
- super().__init__()
536
- self.num_queries = num_queries
537
- self.transformer = transformer
538
- self.encoder = encoder
539
- hidden_dim = transformer.d_model
540
- self.action_head = nn.Linear(hidden_dim, action_dim)
541
- self.query_embed = nn.Embedding(num_queries, hidden_dim)
542
- self.backbone = backbone # ONE backbone shared by every camera (upstream behavior)
543
- self.input_proj = nn.Conv2d(backbone.num_channels, hidden_dim, kernel_size=1)
544
- self.input_proj_robot_state = nn.Linear(qpos_dim, hidden_dim)
545
-
546
- # CVAE style encoder inputs
547
- self.latent_dim = latent_dim
548
- self.cls_embed = nn.Embedding(1, hidden_dim)
549
- self.encoder_action_proj = nn.Linear(action_dim, hidden_dim)
550
- self.encoder_joint_proj = nn.Linear(qpos_dim, hidden_dim)
551
- self.latent_proj = nn.Linear(hidden_dim, latent_dim * 2)
552
- self.register_buffer(
553
- "pos_table", get_sinusoid_encoding_table(1 + 1 + num_queries, hidden_dim)
554
- )
555
- # decoder side
556
- self.latent_out_proj = nn.Linear(latent_dim, hidden_dim)
557
- self.additional_pos_embed = nn.Embedding(2, hidden_dim) # latent + proprio slots
558
-
559
- def forward(
560
- self,
561
- qpos: torch.Tensor,
562
- images: torch.Tensor,
563
- actions: torch.Tensor | None = None,
564
- is_pad: torch.Tensor | None = None,
565
- ) -> tuple[torch.Tensor, tuple[torch.Tensor | None, torch.Tensor | None]]:
566
- """``qpos (B, Dq)``, ``images (B, ncam, C, H, W)``; train passes ``actions (B, T, Da)``."""
567
- is_training = actions is not None
568
- bs = qpos.shape[0]
569
- if is_training:
570
- action_embed = self.encoder_action_proj(actions)
571
- qpos_embed = self.encoder_joint_proj(qpos).unsqueeze(1)
572
- cls_embed = self.cls_embed.weight.unsqueeze(0).repeat(bs, 1, 1)
573
- encoder_input = torch.cat([cls_embed, qpos_embed, action_embed], dim=1)
574
- encoder_input = encoder_input.permute(1, 0, 2)
575
- if is_pad is None:
576
- is_pad = torch.zeros(bs, actions.shape[1], dtype=torch.bool, device=qpos.device)
577
- cls_joint_is_pad = torch.full((bs, 2), False, device=qpos.device)
578
- key_pad = torch.cat([cls_joint_is_pad, is_pad], dim=1)
579
- pos_embed = self.pos_table.clone().detach().permute(1, 0, 2)
580
- encoder_output = self.encoder(
581
- encoder_input, pos=pos_embed, src_key_padding_mask=key_pad
582
- )[0]
583
- latent_info = self.latent_proj(encoder_output)
584
- mu = latent_info[:, : self.latent_dim]
585
- logvar = latent_info[:, self.latent_dim :]
586
- latent_input = self.latent_out_proj(reparametrize(mu, logvar))
587
- else:
588
- mu = logvar = None
589
- latent_sample = torch.zeros(bs, self.latent_dim, device=qpos.device)
590
- latent_input = self.latent_out_proj(latent_sample)
591
-
592
- all_cam_features, all_cam_pos = [], []
593
- for cam_id in range(images.shape[1]):
594
- features, pos = self.backbone(images[:, cam_id])
595
- all_cam_features.append(self.input_proj(features[0]))
596
- all_cam_pos.append(pos[0])
597
- proprio_input = self.input_proj_robot_state(qpos)
598
- src = torch.cat(all_cam_features, dim=3) # cameras fold into the width axis
599
- pos = torch.cat(all_cam_pos, dim=3)
600
- hs = self.transformer(
601
- src,
602
- None,
603
- self.query_embed.weight,
604
- pos,
605
- latent_input,
606
- proprio_input,
607
- self.additional_pos_embed.weight,
608
- )[0]
609
- return self.action_head(hs), (mu, logvar)
610
-
611
-
612
- def kl_divergence(mu: torch.Tensor, logvar: torch.Tensor) -> torch.Tensor:
613
- """Total KL(q(z|x) || N(0, I)), summed over latent dims, meaned over the batch."""
614
- klds = -0.5 * (1 + logvar - mu.pow(2) - logvar.exp())
615
- return klds.sum(1).mean()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
code/hb_baselines_20261117/baselines/adapters.py DELETED
@@ -1,48 +0,0 @@
1
- """The G1 evaluation adapters of the baselines (evaluation/README.md#the-model-interface): `make_model('fm_dit')`
2
- returns the `Model` class that `evaluation/policy/FMDiT/model.py` exports (likewise DP, ACT).
3
-
4
- Observation: the current ego_view and chest frames (480x640 RGB, resized as the training cache) and state44; no past
5
- actions or earlier frames (the baselines read one frame). Output: the checkpoint's whole chunk (16 rows of action76,
6
- row 0 executed at the request's frame), `execution_steps` rows of it executed before the next query (deploy.yml
7
- `config: execution_steps`, default the whole chunk), the request's seed for the sampling noise (FM-DiT, DP).
8
- """
9
- from __future__ import annotations
10
-
11
- from .runtime import BaselinePolicy
12
-
13
- WIDTH = {'sonic_dfx6': 76}
14
-
15
-
16
- def require(condition, message):
17
- if not condition:
18
- raise RuntimeError(message)
19
-
20
-
21
- def make_model(policy_name: str):
22
- class Model:
23
- history_length = 1 # the current head and chest frames only
24
- video_frames = 0
25
-
26
- def __init__(self, cfg):
27
- self.policy = BaselinePolicy(cfg['checkpoint_path'], device=cfg.get('device', 'cuda:0'),
28
- policy=policy_name, robot='g1')
29
- contract = self.policy.contract
30
- require(cfg['action_space'] in WIDTH and contract['action_space'] == cfg['action_space']
31
- and self.policy.action_dim == WIDTH[cfg['action_space']] and self.policy.state_dim == 44
32
- and list(self.policy.cameras) == ['ego_view', 'chest'],
33
- f"checkpoint contract {contract['name']} does not serve {cfg['action_space']}")
34
- extra = cfg.get('config') or {}
35
- if extra.get('check_task', True):
36
- require(cfg['task'].strip() == (self.policy.task_text or '').strip(),
37
- f'task text {cfg["task"]!r} is not the training task {self.policy.task_text!r}')
38
- self.execution_steps = int(extra.get('execution_steps') or self.policy.horizon)
39
- require(1 <= self.execution_steps <= self.policy.horizon, f'execution_steps {self.execution_steps}')
40
- self.info = dict(self.policy.info(), execution_steps=self.execution_steps)
41
-
42
- def get_action(self, obs):
43
- action, _ = self.policy.predict(obs['images'], obs['state'], seed=obs['seed'])
44
- return dict(action=action, execution_steps=self.execution_steps,
45
- sampling_steps=self.policy.sampling_steps)
46
-
47
- Model.__name__ = Model.__qualname__ = f'Model_{policy_name}'
48
- return Model
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
code/hb_baselines_20261117/baselines/data.py DELETED
@@ -1,288 +0,0 @@
1
- """Training data of the baselines: a task's LeRobot v2.1 expert dataset read through a robot contract.
2
-
3
- A contract names the cameras and which dataset columns form the policy state and the action rows, the same layouts
4
- the registered GR00T / Psi0 checkpoints were trained on:
5
-
6
- - `g1_sonic_dfx6` (G1 + INSPIRE, the evaluation/README.md interface; ego_view, chest): state44 =
7
- `observation.state[0:29]` body, measured `observation.inspire_{left,right}_hand_state`,
8
- `observation.projected_gravity`; action76 (`sonic_dfx6`) = `action.motion_token` 64 and the measured DFX6 of the
9
- same row (row 0 = the current opening);
10
- - `h2_sharpa` (H2 + Sharpa, debug/newton/h2_sharpa_policy_eval.py; head, chest): state78 = `observation.state` 75,
11
- `observation.projected_gravity` 3; action75 = `action.body_target` 31, `action.hands` 44 (absolute targets);
12
- - `h2_sharpa_planner` (H2 + Sharpa a14 v2, h2_policy_planner_eval.py; head, chest): state78; action82 = action75 +
13
- `action.planner` 7.
14
-
15
- Frames: every camera's video is decoded once (PyAV), each frame resized with `resize_frame` (OpenCV INTER_AREA, the
16
- same function the policy runtime applies to live frames) and stored as a uint8 memory map in a cache directory keyed by
17
- the dataset, episodes, camera and size. A training sample is the frame t of an episode: the cameras and the state at t,
18
- and the action rows t..t+horizon-1 (rows past the episode's end repeat its last row, as DextraVerse's windows).
19
- """
20
- from __future__ import annotations
21
-
22
- from dataclasses import dataclass
23
- import hashlib
24
- import json
25
- import os
26
- from pathlib import Path
27
- import sys
28
-
29
- import numpy as np
30
-
31
- CACHE_VERSION = 1
32
-
33
-
34
- @dataclass(frozen=True)
35
- class Contract:
36
- name: str
37
- robot: str
38
- cameras: tuple
39
- state: tuple # ((column, start, end), ...) concatenated in order
40
- action: tuple
41
- action_space: str | None = None # the G1 evaluation interface's action space, if any
42
- body_dims: int = 0 # leading raw-radian body joint angles of the state (augmentation spec v2 perturbs these)
43
-
44
- @property
45
- def state_dim(self) -> int:
46
- return sum(end - start for _, start, end in self.state)
47
-
48
- @property
49
- def action_dim(self) -> int:
50
- return sum(end - start for _, start, end in self.action)
51
-
52
- def to_dict(self, cameras=None) -> dict:
53
- return dict(name=self.name, robot=self.robot, cameras=list(cameras or self.cameras),
54
- state=[list(s) for s in self.state], action=[list(a) for a in self.action],
55
- state_dim=self.state_dim, action_dim=self.action_dim, action_space=self.action_space,
56
- body_dims=self.body_dims)
57
-
58
-
59
- _G1_HANDS = (('observation.inspire_left_hand_state', 0, 6), ('observation.inspire_right_hand_state', 0, 6))
60
- _H2_STATE = (('observation.state', 0, 75), ('observation.projected_gravity', 0, 3))
61
- _H2_ACTION = (('action.body_target', 0, 31), ('action.hands', 0, 44))
62
- # body_dims: G1 observation.state[0:29] are the 29 body joints; H2 observation.state[0:31] are legs 6+6, waist 3,
63
- # head 2, arms 7+7 (docs/unitree_h2_sharpa.md), then the Sharpa hands.
64
- CONTRACTS = {c.name: c for c in (
65
- Contract('g1_sonic_dfx6', 'g1', ('ego_view', 'chest'),
66
- (('observation.state', 0, 29), *_G1_HANDS, ('observation.projected_gravity', 0, 3)),
67
- (('action.motion_token', 0, 64), *_G1_HANDS), action_space='sonic_dfx6', body_dims=29),
68
- Contract('h2_sharpa', 'h2_sharpa', ('head', 'chest'), _H2_STATE, _H2_ACTION, body_dims=31),
69
- Contract('h2_sharpa_planner', 'h2_sharpa', ('head', 'chest'), _H2_STATE,
70
- (*_H2_ACTION, ('action.planner', 0, 7)), body_dims=31),
71
- )}
72
-
73
-
74
- def augmentation_module():
75
- """evaluation/augmentation: the augmentation spec v2 shared by every model's training (imported on demand)."""
76
- evaluation = str(Path(__file__).resolve().parents[1])
77
- if evaluation not in sys.path:
78
- sys.path.insert(0, evaluation)
79
- import augmentation
80
- return augmentation
81
-
82
-
83
- def resize_frame(frame: np.ndarray, hw) -> np.ndarray:
84
- """(H, W, 3) uint8 RGB -> (h, w, 3) uint8, OpenCV INTER_AREA (training cache and live frames alike)."""
85
- import cv2
86
- frame = np.ascontiguousarray(frame, dtype=np.uint8)
87
- if frame.ndim != 3 or frame.shape[2] != 3:
88
- raise ValueError(f'expected an (H, W, 3) RGB frame, got {frame.shape}')
89
- h, w = int(hw[0]), int(hw[1])
90
- if frame.shape[:2] == (h, w):
91
- return frame
92
- return cv2.resize(frame, (w, h), interpolation=cv2.INTER_AREA)
93
-
94
-
95
- class LeRobotDataset:
96
- """A LeRobot v2.1 dataset directory (meta/info.json, meta/episodes.jsonl, data/, videos/)."""
97
-
98
- def __init__(self, root):
99
- self.root = Path(root).expanduser().resolve()
100
- self.info = json.loads((self.root / 'meta/info.json').read_text())
101
- if self.info.get('codebase_version') != 'v2.1':
102
- raise ValueError(f"{self.root}: LeRobot {self.info.get('codebase_version')}, expected v2.1")
103
- rows = [json.loads(line) for line in (self.root / 'meta/episodes.jsonl').read_text().splitlines() if line]
104
- self.lengths = {int(r['episode_index']): int(r['length']) for r in rows}
105
- tasks = [json.loads(line) for line in (self.root / 'meta/tasks.jsonl').read_text().splitlines() if line]
106
- self.tasks = {int(t['task_index']): t['task'] for t in tasks}
107
- self.fps = float(self.info['fps'])
108
-
109
- @property
110
- def name(self) -> str:
111
- """The dataset's folder name (its parent's for an export folder named `lerobot`)."""
112
- return self.root.parent.name if self.root.name == 'lerobot' else self.root.name
113
-
114
- def chunk(self, episode: int) -> int:
115
- return episode // int(self.info['chunks_size'])
116
-
117
- def parquet(self, episode: int) -> Path:
118
- return self.root / self.info['data_path'].format(episode_chunk=self.chunk(episode), episode_index=episode)
119
-
120
- def video(self, episode: int, camera: str) -> Path:
121
- return self.root / self.info['video_path'].format(episode_chunk=self.chunk(episode), episode_index=episode,
122
- video_key=f'observation.images.{camera}')
123
-
124
- def check_contract(self, contract: Contract, cameras):
125
- features = self.info['features']
126
- for column, start, end in (*contract.state, *contract.action):
127
- if column not in features:
128
- raise KeyError(f'{self.root.name}: no column {column!r} (contract {contract.name})')
129
- width = int(np.prod(features[column]['shape']))
130
- if end > width:
131
- raise ValueError(f'{column} has {width} values; the contract reads {start}:{end}')
132
- for camera in cameras:
133
- key = f'observation.images.{camera}'
134
- if features.get(key, {}).get('dtype') != 'video':
135
- raise KeyError(f'{self.root.name}: no video {key!r}')
136
-
137
-
138
- def parse_episodes(spec: str | None, available) -> list:
139
- """'0:100', '0,3,7' or None (all), restricted to the dataset's episodes, sorted."""
140
- available = sorted(available)
141
- if not spec:
142
- return available
143
- chosen = set()
144
- for part in spec.split(','):
145
- if ':' in part:
146
- lo, hi = part.split(':')
147
- chosen.update(range(int(lo or 0), int(hi) if hi else available[-1] + 1))
148
- else:
149
- chosen.add(int(part))
150
- missing = sorted(chosen - set(available))
151
- if missing:
152
- raise ValueError(f'episodes not in the dataset: {missing[:10]}')
153
- return sorted(chosen)
154
-
155
-
156
- def load_lowdim(dataset: LeRobotDataset, contract: Contract, episodes) -> dict:
157
- """State (N, state_dim) and action (N, action_dim) float32 of the episodes in order, plus each episode's start
158
- row, length and task text."""
159
- import pyarrow.parquet as pq
160
- columns = sorted({c for c, _, _ in (*contract.state, *contract.action)} | {'frame_index', 'task_index'})
161
- states, actions, starts, lengths, tasks, offset = [], [], [], [], set(), 0
162
- for episode in episodes:
163
- table = pq.read_table(dataset.parquet(episode), columns=columns)
164
- data = {c: np.asarray(table.column(c).to_pylist(), dtype=np.float64) for c in columns}
165
- n = len(data['frame_index'])
166
- if n != dataset.lengths[episode] or not np.array_equal(data['frame_index'], np.arange(n)):
167
- raise ValueError(f'episode {episode}: {n} rows / frame_index differ from episodes.jsonl')
168
-
169
- def pick(spec):
170
- return np.concatenate([data[c].reshape(n, -1)[:, s:e] for c, s, e in spec], axis=1).astype(np.float32)
171
-
172
- states.append(pick(contract.state))
173
- actions.append(pick(contract.action))
174
- tasks.update(dataset.tasks[int(i)] for i in np.unique(data['task_index']))
175
- starts.append(offset)
176
- lengths.append(n)
177
- offset += n
178
- state, action = np.concatenate(states), np.concatenate(actions)
179
- if not (np.isfinite(state).all() and np.isfinite(action).all()):
180
- raise ValueError('non-finite state or action values')
181
- return dict(state=state, action=action, starts=np.asarray(starts), lengths=np.asarray(lengths),
182
- episodes=list(episodes), tasks=sorted(tasks))
183
-
184
-
185
- def statistics(lowdim: dict, rows: np.ndarray) -> dict:
186
- out = {}
187
- for key in ('state', 'action'):
188
- x = lowdim[key][rows].astype(np.float64)
189
- out[key] = dict(min=x.min(0).tolist(), max=x.max(0).tolist(), mean=x.mean(0).tolist(), std=x.std(0).tolist())
190
- return out
191
-
192
-
193
- # -- frame cache --------------------------------------------------------------------------------------------------
194
- def _decode_into(job):
195
- path, out_path, total, start, length, hw = job
196
- import av
197
- frames = np.memmap(out_path, dtype=np.uint8, mode='r+', shape=(total, hw[0], hw[1], 3))
198
- count = 0
199
- with av.open(str(path)) as container:
200
- stream = container.streams.video[0]
201
- stream.thread_type = 'AUTO'
202
- for frame in container.decode(stream):
203
- if count < length:
204
- frames[start + count] = resize_frame(frame.to_ndarray(format='rgb24'), hw)
205
- count += 1
206
- frames.flush()
207
- del frames
208
- if count != length:
209
- raise ValueError(f'{path}: {count} video frames, {length} data rows')
210
- return length
211
-
212
-
213
- def frame_cache(dataset: LeRobotDataset, lowdim: dict, cameras, hw, cache_root, workers=8) -> dict:
214
- """{camera: path of the (N, h, w, 3) uint8 memory map} for the episodes of `lowdim`, decoded once and reused."""
215
- from multiprocessing import get_context
216
- total = int(lowdim['lengths'].sum())
217
- paths = {}
218
- for camera in cameras:
219
- key = json.dumps(dict(version=CACHE_VERSION, root=str(dataset.root), episodes=lowdim['episodes'],
220
- lengths=lowdim['lengths'].tolist(), camera=camera, hw=list(hw)), sort_keys=True)
221
- digest = hashlib.sha256(key.encode()).hexdigest()[:16]
222
- folder = Path(cache_root).expanduser() / f'{dataset.name}_{camera}_{hw[0]}x{hw[1]}_{digest}'
223
- folder.mkdir(parents=True, exist_ok=True)
224
- out, meta = folder / 'frames.u8', folder / 'meta.json'
225
- if meta.exists() and json.loads(meta.read_text()).get('complete'):
226
- paths[camera] = out
227
- continue
228
- np.memmap(out, dtype=np.uint8, mode='w+', shape=(total, hw[0], hw[1], 3)).flush()
229
- jobs = [(dataset.video(e, camera), out, total, int(s), int(n), tuple(hw))
230
- for e, s, n in zip(lowdim['episodes'], lowdim['starts'], lowdim['lengths'])]
231
- with get_context('spawn').Pool(max(1, int(workers))) as pool: # the caller may hold torch threads
232
- for done, _ in enumerate(pool.imap_unordered(_decode_into, jobs), 1):
233
- if done % 20 == 0 or done == len(jobs):
234
- print(json.dumps(dict(event='frame_cache', camera=camera, episodes=done, of=len(jobs))),
235
- flush=True)
236
- meta.write_text(json.dumps(dict(json.loads(key), frames=total, complete=True), indent=1))
237
- paths[camera] = out
238
- return paths
239
-
240
-
241
- class ChunkDataset:
242
- """torch-style dataset of (images (n_cameras, h, w, 3) uint8, state (state_dim,), action (horizon, action_dim))
243
- over the frames of the selected episodes (positions into lowdim['episodes']). Memory maps open lazily per
244
- process (DataLoader workers).
245
-
246
- `body_dims` > 0 turns on the training augmentation (docs/augmentation_v2.md, evaluation/augmentation): per item,
247
- the cached frames of all cameras get one hb_aug_v2.augment call (one time step, no future targets) and the first
248
- `body_dims` state values the per-sample joint bias + noise; the action rows are never touched. 0 (evaluation,
249
- offline checks) returns the cached frames and the recorded state unchanged, deterministically."""
250
-
251
- def __init__(self, lowdim: dict, frames: dict, cameras, hw, horizon: int, positions, body_dims: int = 0):
252
- self.lowdim, self.paths, self.cameras, self.hw, self.horizon = lowdim, frames, list(cameras), tuple(hw), horizon
253
- self.positions, self.body_dims = list(positions), int(body_dims)
254
- if self.body_dims:
255
- augmentation_module() # asserts the spec version before any worker starts
256
- self.total = int(lowdim['lengths'].sum())
257
- index, end = [], np.zeros(self.total, np.int64)
258
- for p in positions:
259
- s, n = int(lowdim['starts'][p]), int(lowdim['lengths'][p])
260
- index.append(np.arange(s, s + n))
261
- end[s:s + n] = s + n
262
- self.index, self.end = np.concatenate(index), end
263
- self._maps, self._pid = None, None
264
-
265
- def __len__(self):
266
- return len(self.index)
267
-
268
- def _frames(self):
269
- if self._maps is None or self._pid != os.getpid():
270
- self._maps = {c: np.memmap(self.paths[c], dtype=np.uint8, mode='r', shape=(self.total, *self.hw, 3))
271
- for c in self.cameras}
272
- self._pid = os.getpid()
273
- return self._maps
274
-
275
- def rows(self, i: int) -> np.ndarray:
276
- return np.minimum(np.arange(i, i + self.horizon), self.end[i] - 1)
277
-
278
- def __getitem__(self, k):
279
- import torch
280
- i = int(self.index[k])
281
- maps = self._frames()
282
- images = torch.from_numpy(np.stack([maps[c][i] for c in self.cameras]))
283
- state = self.lowdim['state'][i]
284
- if self.body_dims:
285
- augmentation = augmentation_module()
286
- images, _ = augmentation.augment_frames_uint8(images)
287
- state = augmentation.perturb_body(state, self.body_dims)
288
- return images, torch.from_numpy(state), torch.from_numpy(self.lowdim['action'][self.rows(i)])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
code/hb_baselines_20261117/baselines/nets.py DELETED
@@ -1,207 +0,0 @@
1
- """Networks of the FM-DiT and DP (DDPM-DiT) baselines: the AdaLN DiT action backbone and the camera + state encoder.
2
-
3
- Ported from DextraVerse's imitation-learning core (`dextraverse/algorithms/il/models/nets/dit.py`, `layers.py`,
4
- `positional_embedding.py`, `vision/backbones.py`, `vision/encoder.py`), unchanged in architecture and initialization.
5
- Left out: the ROVE improvement embedding, the spatial-softmax / R3M / tactile options and the inpainting path (the
6
- baselines always condition through the global observation feature). Added: the ResNet's normalization choice
7
- (`get_resnet`): DextraVerse's GroupNorm for a backbone trained from scratch, or BatchNorm frozen at the pretrained
8
- statistics (the DETR / ACT practice) for an ImageNet-initialized backbone that is fine-tuned with the policy.
9
- """
10
- from __future__ import annotations
11
-
12
- import math
13
-
14
- import torch
15
- import torch.nn as nn
16
- import torch.nn.functional as F
17
- import torchvision
18
-
19
- IMAGENET_MEAN = (0.485, 0.456, 0.406)
20
- IMAGENET_STD = (0.229, 0.224, 0.225)
21
-
22
-
23
- class SinusoidalPosEmb(nn.Module):
24
- def __init__(self, dim):
25
- super().__init__()
26
- self.dim = dim
27
-
28
- def forward(self, x):
29
- half_dim = self.dim // 2
30
- emb = math.log(10000) / (half_dim - 1)
31
- emb = torch.exp(torch.arange(half_dim, device=x.device) * -emb)
32
- emb = x[:, None] * emb[None, :]
33
- return torch.cat((emb.sin(), emb.cos()), dim=-1)
34
-
35
-
36
- class RotaryPosEmb(nn.Module):
37
- """Rotary position embedding over each attention head's (S, head_dim) slice."""
38
-
39
- def __init__(self, dim):
40
- super().__init__()
41
- self.dim = dim
42
- self.register_buffer('inv_freq', 1.0 / (10000 ** (torch.arange(0, dim, 2).float() / dim)))
43
-
44
- def forward(self, x): # x: (B, heads, S, head_dim)
45
- t = torch.arange(x.shape[-2], device=x.device, dtype=self.inv_freq.dtype)
46
- freqs = torch.outer(t, self.inv_freq.to(x.device))
47
- emb = torch.cat([freqs, freqs], dim=-1)
48
- cos, sin = emb.cos()[None, None], emb.sin()[None, None]
49
- x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2:]
50
- return x * cos + torch.cat([-x2, x1], dim=-1) * sin
51
-
52
-
53
- class Mlp(nn.Module):
54
- """The ViT MLP (timm.layers.Mlp) as DextraVerse's nets/layers.py."""
55
-
56
- def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0):
57
- super().__init__()
58
- out_features = out_features or in_features
59
- hidden_features = hidden_features or in_features
60
- self.fc1 = nn.Linear(in_features, hidden_features)
61
- self.act = act_layer()
62
- self.drop1 = nn.Dropout(drop)
63
- self.norm = nn.Identity()
64
- self.fc2 = nn.Linear(hidden_features, out_features)
65
- self.drop2 = nn.Dropout(drop)
66
-
67
- def forward(self, x):
68
- return self.drop2(self.fc2(self.norm(self.drop1(self.act(self.fc1(x))))))
69
-
70
-
71
- class Attention(nn.Module):
72
- def __init__(self, dim, num_heads=8, qkv_bias=True, attn_drop=0.0, proj_drop=0.0, qk_norm=True):
73
- super().__init__()
74
- assert dim % num_heads == 0, 'dim should be divisible by num_heads'
75
- self.num_heads = num_heads
76
- self.head_dim = dim // num_heads
77
- self.attn_drop = attn_drop
78
- self.proj_drop = nn.Dropout(proj_drop)
79
- self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
80
- self.q_norm = nn.LayerNorm(self.head_dim) if qk_norm else nn.Identity()
81
- self.k_norm = nn.LayerNorm(self.head_dim) if qk_norm else nn.Identity()
82
- self.proj = nn.Linear(dim, dim)
83
- self.rope = RotaryPosEmb(self.head_dim)
84
-
85
- def forward(self, x):
86
- B, S, C = x.shape
87
- qkv = self.qkv(x).reshape(B, S, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4)
88
- q, k, v = qkv.unbind(0)
89
- q, k = self.rope(self.q_norm(q)), self.rope(self.k_norm(k))
90
- x = F.scaled_dot_product_attention(q, k, v, dropout_p=self.attn_drop if self.training else 0.0)
91
- return self.proj_drop(self.proj(x.transpose(1, 2).reshape(B, S, C)))
92
-
93
-
94
- class AdaLNBlock(nn.Module):
95
- """Adaptive-LayerNorm transformer block as in DiT (Peebles et al. 2022)."""
96
-
97
- def __init__(self, dim, num_heads, mlp_ratio=4.0, dropout=0.0):
98
- super().__init__()
99
- self.norm1 = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
100
- self.attn = Attention(dim, num_heads=num_heads, attn_drop=dropout, proj_drop=dropout)
101
- self.norm2 = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
102
- self.mlp = Mlp(in_features=dim, hidden_features=int(dim * mlp_ratio),
103
- act_layer=lambda: nn.GELU(approximate='tanh'), drop=0)
104
- self.ada_ln = nn.Sequential(nn.SiLU(), nn.Linear(dim, 6 * dim))
105
- self.dim = dim
106
- nn.init.constant_(self.ada_ln[-1].weight, 0)
107
- nn.init.constant_(self.ada_ln[-1].bias, 0)
108
-
109
- def forward(self, x, t, c):
110
- B = x.shape[0]
111
- gamma1, gamma2, scale1, scale2, shift1, shift2 = self.ada_ln(F.silu(t + c)).view(B, 6, 1, self.dim).unbind(1)
112
- x = x + self.attn(self.norm1(x).mul(scale1.add(1)).add_(shift1)).mul_(gamma1)
113
- return x + self.mlp(self.norm2(x).mul(scale2.add(1)).add_(shift2)).mul_(gamma2)
114
-
115
-
116
- class FlowTransformer(nn.Module):
117
- """DiT action backbone: AdaLN blocks over the H action tokens, conditioned on time_embed(t) + cond_embed(obs).
118
-
119
- As DextraVerse, the generic Xavier initialization runs after the blocks' zero init of their AdaLN projection, so
120
- it is not the full AdaLN-Zero recipe (kept: it is the reference's training behaviour)."""
121
-
122
- def __init__(self, input_dim, condition_dim, hidden_dim, output_dim, num_layers, num_heads, mlp_ratio=4.0,
123
- dropout=0.1, time_embed_dim=256):
124
- super().__init__()
125
- self.input_proj = nn.Linear(input_dim, hidden_dim)
126
- self.time_embed = nn.Sequential(SinusoidalPosEmb(time_embed_dim), nn.Linear(time_embed_dim, time_embed_dim * 4),
127
- nn.Mish(), nn.Linear(time_embed_dim * 4, hidden_dim))
128
- self.cond_embed = nn.Linear(condition_dim, hidden_dim)
129
- self.transformer_blocks = nn.ModuleList(
130
- [AdaLNBlock(hidden_dim, num_heads, mlp_ratio=mlp_ratio, dropout=dropout) for _ in range(num_layers)])
131
- self.norm = nn.LayerNorm(hidden_dim)
132
- self.out_proj = nn.Linear(hidden_dim, output_dim)
133
-
134
- def basic_init(module):
135
- if isinstance(module, nn.Linear):
136
- nn.init.xavier_uniform_(module.weight)
137
- if module.bias is not None:
138
- nn.init.constant_(module.bias, 0)
139
-
140
- self.apply(basic_init)
141
- nn.init.normal_(self.time_embed[1].weight, std=0.02)
142
- nn.init.normal_(self.time_embed[3].weight, std=0.02)
143
-
144
- def forward(self, x, t, global_cond):
145
- if not torch.is_tensor(t):
146
- t = torch.tensor(t, device=x.device)
147
- if t.ndim == 0:
148
- t = t.expand(x.shape[0])
149
- x = self.input_proj(x)
150
- t = self.time_embed(t)
151
- c = self.cond_embed(global_cond)
152
- for block in self.transformer_blocks:
153
- x = block(x, t, c)
154
- return self.out_proj(self.norm(x))
155
-
156
-
157
- def replace_batchnorm_with_groupnorm(module: nn.Module) -> nn.Module:
158
- """DextraVerse's use_group_norm: every BatchNorm2d becomes GroupNorm(num_features // 16 groups)."""
159
- for name, child in module.named_children():
160
- if isinstance(child, nn.BatchNorm2d):
161
- setattr(module, name, nn.GroupNorm(num_groups=child.num_features // 16, num_channels=child.num_features))
162
- else:
163
- replace_batchnorm_with_groupnorm(child)
164
- return module
165
-
166
-
167
- NORMS = ('group', 'frozen_bn')
168
-
169
-
170
- def get_resnet(name='resnet18', weights=None, norm='group') -> nn.Module:
171
- """A torchvision ResNet with its classifier removed: (N, 3, H, W) -> (N, 512) globally pooled.
172
-
173
- weights: torchvision weights name (e.g. 'IMAGENET1K_V1') to initialize from, or None (random initialization;
174
- a checkpoint load supplies every weight). norm: 'group' replaces every BatchNorm with GroupNorm (DextraVerse's
175
- use_group_norm, for training from scratch: pretrained BatchNorm statistics and affine are dropped); 'frozen_bn'
176
- keeps BatchNorm frozen at its (pretrained) running statistics and affine, the convolutions fine-tune."""
177
- if norm == 'frozen_bn':
178
- from .act_nets import FrozenBatchNorm2d
179
- resnet = getattr(torchvision.models, name)(weights=weights, norm_layer=FrozenBatchNorm2d)
180
- elif norm == 'group':
181
- resnet = replace_batchnorm_with_groupnorm(getattr(torchvision.models, name)(weights=weights))
182
- else:
183
- raise ValueError(f'norm must be one of {NORMS}, got {norm!r}')
184
- resnet.fc = nn.Identity()
185
- return resnet
186
-
187
-
188
- class ImageStateEncoder(nn.Module):
189
- """DextraVerse MultiImageObsEncoder as configured for FM-DiT / DDPM-DiT: one ResNet shared by every camera
190
- (share_rgb_model; `get_resnet` weights and norm), ImageNet normalization of the [0, 1] images, the pooled features
191
- of each camera in the contract's camera order, then the normalized state.
192
- Output (B, n_cameras * 512 + state_dim)."""
193
-
194
- def __init__(self, n_cameras, state_dim, backbone='resnet18', weights=None, norm='group'):
195
- super().__init__()
196
- self.rgb = get_resnet(backbone, weights=weights, norm=norm)
197
- self.n_cameras, self.state_dim = int(n_cameras), int(state_dim)
198
- self.register_buffer('mean', torch.tensor(IMAGENET_MEAN).view(1, 3, 1, 1), persistent=False)
199
- self.register_buffer('std', torch.tensor(IMAGENET_STD).view(1, 3, 1, 1), persistent=False)
200
- self.feature_dim = self.n_cameras * (512 if backbone in ('resnet18', 'resnet34') else 2048) + self.state_dim
201
-
202
- def forward(self, images, state):
203
- """images (B, n_cameras, 3, H, W) in [0, 1]; state (B, state_dim) normalized."""
204
- B = images.shape[0]
205
- x = (images.flatten(0, 1) - self.mean) / self.std
206
- features = self.rgb(x).reshape(B, -1) # camera features side by side, in camera order
207
- return torch.cat([features, state], dim=-1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
code/hb_baselines_20261117/baselines/policies.py DELETED
@@ -1,281 +0,0 @@
1
- """The three baseline policies behind one contract, ported from DextraVerse's imitation-learning core:
2
-
3
- - `fm_dit`, `FMDiTPolicy` (reference: dextraverse/algorithms/il/models/fm_dit.py + fm_base.py): flow matching, MSE on
4
- the velocity `a - noise`; sampled with 10 midpoint steps from noise (20 DiT calls);
5
- - `dp`, `DPPolicy` (ddpm_dit.py + ddpm_base.py: Diffusion Policy with a DiT backbone): DDPM epsilon MSE over 100
6
- steps; sampled with the 100 DDPM steps;
7
- - `act`, `ACTPolicy` (act.py + nets/act/): L1 + `kl_weight` x KL of the CVAE; decoded from the zero latent in one pass.
8
-
9
- Contract (every policy): `compute_loss(images, state, action) -> (loss, metrics)` and
10
- `predict(images, state, generator) -> (action, normalized action)`; images (B, n_cameras, 3, H, W) float in [0, 1],
11
- state (B, state_dim) and action (B, horizon, action_dim) in physical units. Each policy owns its `Normalizer`
12
- (DextraVerse's LinearNormalizer 'limits' mode: state and action to [-1, 1] per dimension, constant dimensions shifted
13
- to 0), saved in its state dict. One observation frame (n_obs_steps 1: the current images and state); the chunk's row 0
14
- is the action of the observation's own frame (the LeRobot rows t..t+horizon-1). The configuration that builds a
15
- policy is a plain dict (`PolicyConfig` fields), stored in the checkpoint.
16
-
17
- The ResNet18 starts from torchvision's ImageNet-1k weights (`backbone_weights` 'IMAGENET1K_V1', the default since
18
- 2026-11-16) and is fine-tuned with the policy, its BatchNorm frozen at the pretrained statistics (`backbone_norm`
19
- 'frozen_bn', as ACT always does); `backbone_weights` None trains from scratch with DextraVerse's GroupNorm encoder
20
- (FM-DiT, DP) or ACT's frozen-BatchNorm one. A checkpoint load builds the structure without fetching any weights.
21
- """
22
- from __future__ import annotations
23
-
24
- from dataclasses import asdict, dataclass, field, replace
25
-
26
- import torch
27
- import torch.nn as nn
28
- import torch.nn.functional as F
29
-
30
- from .act_nets import DETRVAE, Transformer, build_backbone, build_style_encoder, kl_divergence
31
- from .nets import IMAGENET_MEAN, IMAGENET_STD, FlowTransformer, ImageStateEncoder
32
-
33
-
34
- @dataclass
35
- class PolicyConfig:
36
- """Everything that builds a policy (stored in the checkpoint's config.json). Model defaults are DextraVerse's
37
- configs/algorithm/il/model/{fm_dit,ddpm_dit,act}.yaml."""
38
- policy: str
39
- n_cameras: int
40
- state_dim: int
41
- action_dim: int
42
- horizon: int = 16
43
- backbone: str = 'resnet18'
44
- backbone_weights: str | None = 'IMAGENET1K_V1' # torchvision weights to initialize from; None = from scratch
45
- backbone_norm: str | None = None # 'frozen_bn' or 'group'; None: frozen_bn when pretrained or ACT, else group
46
- # FM-DiT / DP (DiT backbone)
47
- hidden_dim: int = 384
48
- num_layers: int = 4
49
- num_heads: int = 8
50
- mlp_ratio: float = 4.0
51
- dropout: float = 0.1
52
- time_embed_dim: int = 128
53
- num_inference_steps: int | None = None # None: FM-DiT 10 midpoint steps, DP every training timestep (100)
54
- # DP noise schedule (diffusers DDPMScheduler)
55
- num_train_timesteps: int = 100
56
- beta_schedule: str = 'squaredcos_cap_v2'
57
- prediction_type: str = 'epsilon'
58
- clip_sample: bool = True
59
- # ACT
60
- act_hidden_dim: int = 512
61
- dim_feedforward: int = 3200
62
- enc_layers: int = 4
63
- dec_layers: int = 7
64
- nheads: int = 8
65
- latent_dim: int = 32
66
- kl_weight: float = 10.0
67
- extra: dict = field(default_factory=dict)
68
-
69
- def __post_init__(self):
70
- if self.backbone_norm is None:
71
- self.backbone_norm = 'frozen_bn' if self.backbone_weights or self.policy == 'act' else 'group'
72
- if self.policy == 'act' and self.backbone_norm != 'frozen_bn':
73
- raise ValueError("ACT's backbone keeps frozen BatchNorm (backbone_norm 'frozen_bn')")
74
-
75
- @classmethod
76
- def from_dict(cls, data: dict) -> PolicyConfig:
77
- known = {k: v for k, v in data.items() if k in cls.__dataclass_fields__}
78
- return cls(**known)
79
-
80
- def to_dict(self) -> dict:
81
- return asdict(self)
82
-
83
-
84
- class Normalizer(nn.Module):
85
- """Per-dimension affine map to [-1, 1] from the training data's min/max (DextraVerse LinearNormalizer, mode
86
- 'limits', fit_offset, range_eps 1e-4): x_n = x * scale + offset; a dimension whose range is below range_eps gets
87
- scale 1 and maps its value to 0."""
88
-
89
- def __init__(self, dim: int):
90
- super().__init__()
91
- self.register_buffer('scale', torch.ones(dim))
92
- self.register_buffer('offset', torch.zeros(dim))
93
-
94
- @torch.no_grad()
95
- def fit(self, minimum, maximum, range_eps=1e-4):
96
- lo = torch.as_tensor(minimum, dtype=torch.float32)
97
- hi = torch.as_tensor(maximum, dtype=torch.float32)
98
- span = hi - lo
99
- ignore = span < range_eps
100
- span[ignore] = 2.0
101
- scale = 2.0 / span
102
- offset = -1.0 - scale * lo
103
- offset[ignore] = -lo[ignore]
104
- self.scale.copy_(scale)
105
- self.offset.copy_(offset)
106
-
107
- def normalize(self, x):
108
- return x * self.scale + self.offset
109
-
110
- def unnormalize(self, x):
111
- return (x - self.offset) / self.scale
112
-
113
-
114
- class BasePolicy(nn.Module):
115
- name = ''
116
- backbone_prefix = '' # state-dict prefix of the image backbone (its own learning rate in training)
117
-
118
- def __init__(self, cfg: PolicyConfig, init_weights=None):
119
- super().__init__()
120
- self.cfg = cfg
121
- self.state_norm = Normalizer(cfg.state_dim)
122
- self.action_norm = Normalizer(cfg.action_dim)
123
-
124
- def fit_normalizers(self, stats: dict):
125
- self.state_norm.fit(stats['state']['min'], stats['state']['max'])
126
- self.action_norm.fit(stats['action']['min'], stats['action']['max'])
127
-
128
- @property
129
- def sampling_steps(self) -> int:
130
- return 1
131
-
132
- def compute_loss(self, images, state, action):
133
- raise NotImplementedError
134
-
135
- def predict(self, images, state, generator=None):
136
- raise NotImplementedError
137
-
138
-
139
- class DiTPolicy(BasePolicy):
140
- """Shared by FM-DiT and DP: the shared-ResNet image + state encoder and the AdaLN DiT over the action chunk
141
- (global observation conditioning, DextraVerse obs_as_global_cond)."""
142
- backbone_prefix = 'obs_encoder.rgb.'
143
-
144
- def __init__(self, cfg: PolicyConfig, init_weights=None):
145
- super().__init__(cfg)
146
- self.obs_encoder = ImageStateEncoder(cfg.n_cameras, cfg.state_dim, backbone=cfg.backbone,
147
- weights=init_weights, norm=cfg.backbone_norm)
148
- self.model = FlowTransformer(input_dim=cfg.action_dim, condition_dim=self.obs_encoder.feature_dim,
149
- hidden_dim=cfg.hidden_dim, output_dim=cfg.action_dim, num_layers=cfg.num_layers,
150
- num_heads=cfg.num_heads, mlp_ratio=cfg.mlp_ratio, dropout=cfg.dropout,
151
- time_embed_dim=cfg.time_embed_dim)
152
-
153
- def condition(self, images, state):
154
- return self.obs_encoder(images, self.state_norm.normalize(state))
155
-
156
-
157
- class FMDiTPolicy(DiTPolicy):
158
- """Flow-matching DiT (DextraVerse FlowMatchingDiTImagePolicy): x_t = (1 - t) noise + t a, t ~ U(0, 1), the DiT
159
- regresses the velocity a - noise; sampling integrates t = 0 -> 1 with the midpoint rule."""
160
- name = 'fm_dit'
161
-
162
- @property
163
- def sampling_steps(self) -> int:
164
- return int(self.cfg.num_inference_steps or 10)
165
-
166
- def compute_loss(self, images, state, action):
167
- cond = self.condition(images, state)
168
- target = self.action_norm.normalize(action)
169
- noise = torch.randn_like(target)
170
- t = torch.rand(target.shape[0], device=target.device)
171
- te = t.view(-1, 1, 1)
172
- x_t = (1 - te) * noise + te * target
173
- loss = F.mse_loss(self.model(x_t, t, cond), target - noise)
174
- return loss, dict(fm=float(loss.detach()))
175
-
176
- @torch.no_grad()
177
- def predict(self, images, state, generator=None):
178
- cond = self.condition(images, state)
179
- B, steps = images.shape[0], self.sampling_steps
180
- x = torch.randn((B, self.cfg.horizon, self.cfg.action_dim), device=cond.device, dtype=cond.dtype,
181
- generator=generator)
182
- times = torch.linspace(0, 1.0, steps + 1, device=cond.device)
183
- for i in range(steps):
184
- t0 = times[i].view(1).expand(B)
185
- t1 = times[i + 1].view(1).expand(B)
186
- dt = (t1 - t0).view(-1, 1, 1)
187
- x_mid = x + self.model(x, t0, cond) * dt / 2
188
- x = x + dt * self.model(x_mid, t0 + (t1 - t0) / 2, cond)
189
- return self.action_norm.unnormalize(x), x
190
-
191
-
192
- class DPPolicy(DiTPolicy):
193
- """Diffusion Policy with the DiT backbone (DextraVerse DiffusionDiTImagePolicy, ddpm_dit.yaml): DDPM with 100
194
- training steps, squaredcos_cap_v2 betas, fixed_small variance, clipped samples, epsilon prediction; sampled with
195
- every training step (100 DiT calls)."""
196
- name = 'dp'
197
-
198
- def __init__(self, cfg: PolicyConfig, init_weights=None):
199
- super().__init__(cfg, init_weights)
200
- from diffusers.schedulers.scheduling_ddpm import DDPMScheduler
201
- self.noise_scheduler = DDPMScheduler(num_train_timesteps=cfg.num_train_timesteps, beta_start=0.0001,
202
- beta_end=0.02, beta_schedule=cfg.beta_schedule,
203
- variance_type='fixed_small', clip_sample=cfg.clip_sample,
204
- prediction_type=cfg.prediction_type)
205
-
206
- @property
207
- def sampling_steps(self) -> int:
208
- return int(self.cfg.num_inference_steps or self.cfg.num_train_timesteps)
209
-
210
- def compute_loss(self, images, state, action):
211
- cond = self.condition(images, state)
212
- target = self.action_norm.normalize(action)
213
- noise = torch.randn_like(target)
214
- t = torch.randint(0, self.noise_scheduler.config.num_train_timesteps, (target.shape[0],),
215
- device=target.device).long()
216
- noisy = self.noise_scheduler.add_noise(target, noise, t)
217
- pred = self.model(noisy, t, cond)
218
- goal = noise if self.cfg.prediction_type == 'epsilon' else target
219
- loss = F.mse_loss(pred, goal)
220
- return loss, dict(ddpm=float(loss.detach()))
221
-
222
- @torch.no_grad()
223
- def predict(self, images, state, generator=None):
224
- cond = self.condition(images, state)
225
- scheduler = self.noise_scheduler
226
- x = torch.randn((images.shape[0], self.cfg.horizon, self.cfg.action_dim), device=cond.device,
227
- dtype=cond.dtype, generator=generator)
228
- scheduler.set_timesteps(self.sampling_steps, device=cond.device)
229
- for t in scheduler.timesteps:
230
- x = scheduler.step(self.model(x, t.to(cond.device), cond), t, x, generator=generator).prev_sample
231
- return self.action_norm.unnormalize(x), x
232
-
233
-
234
- class ACTPolicy(BasePolicy):
235
- """ACT (DextraVerse ACTImagePolicy, act.yaml): ImageNet-normalized cameras through one ResNet with frozen
236
- BatchNorm (spatial tokens, no pooling), the normalized state as qpos, a CVAE style encoder over the action chunk in
237
- training, the DETR decoder with `horizon` queries; loss L1 + kl_weight x KL; inference decodes from the zero
238
- latent (deterministic)."""
239
- name = 'act'
240
- backbone_prefix = 'model.backbone.'
241
-
242
- def __init__(self, cfg: PolicyConfig, init_weights=None):
243
- super().__init__(cfg)
244
- transformer = Transformer(d_model=cfg.act_hidden_dim, nhead=cfg.nheads, num_encoder_layers=cfg.enc_layers,
245
- num_decoder_layers=cfg.dec_layers, dim_feedforward=cfg.dim_feedforward,
246
- dropout=cfg.dropout, return_intermediate_dec=False)
247
- self.model = DETRVAE(build_backbone(cfg.backbone, hidden_dim=cfg.act_hidden_dim, weights=init_weights),
248
- transformer,
249
- build_style_encoder(cfg.act_hidden_dim, cfg.nheads, cfg.dim_feedforward, cfg.enc_layers,
250
- cfg.dropout),
251
- qpos_dim=cfg.state_dim, action_dim=cfg.action_dim, num_queries=cfg.horizon,
252
- latent_dim=cfg.latent_dim)
253
- self.register_buffer('mean', torch.tensor(IMAGENET_MEAN).view(1, 1, 3, 1, 1), persistent=False)
254
- self.register_buffer('std', torch.tensor(IMAGENET_STD).view(1, 1, 3, 1, 1), persistent=False)
255
-
256
- def compute_loss(self, images, state, action):
257
- target = self.action_norm.normalize(action)
258
- a_hat, (mu, logvar) = self.model(self.state_norm.normalize(state), (images - self.mean) / self.std,
259
- actions=target)
260
- l1 = F.l1_loss(a_hat, target)
261
- kl = kl_divergence(mu, logvar)
262
- return l1 + self.cfg.kl_weight * kl, dict(l1=float(l1.detach()), kl=float(kl.detach()))
263
-
264
- @torch.no_grad()
265
- def predict(self, images, state, generator=None): # noqa: ARG002 - deterministic (zero latent)
266
- a_hat, _ = self.model(self.state_norm.normalize(state), (images - self.mean) / self.std)
267
- return self.action_norm.unnormalize(a_hat), a_hat
268
-
269
-
270
- POLICIES = {cls.name: cls for cls in (FMDiTPolicy, DPPolicy, ACTPolicy)}
271
- LABELS = {'fm_dit': 'FM-DiT', 'dp': 'DP (DDPM-DiT)', 'act': 'ACT'}
272
-
273
-
274
- def build_policy(cfg: PolicyConfig | dict, pretrained: bool = True) -> BasePolicy:
275
- """The policy of `cfg`; pretrained=True initializes the backbone from cfg.backbone_weights (training),
276
- False builds the same structure with random weights (a checkpoint load, which must not download anything)."""
277
- cfg = cfg if isinstance(cfg, PolicyConfig) else PolicyConfig.from_dict(cfg)
278
- if cfg.policy not in POLICIES:
279
- raise KeyError(f'unknown baseline {cfg.policy!r}; one of {sorted(POLICIES)}')
280
- cfg = replace(cfg) # a copy (resolved backbone_norm)
281
- return POLICIES[cfg.policy](cfg, init_weights=cfg.backbone_weights if pretrained else None)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
code/hb_baselines_20261117/baselines/requirements.txt DELETED
@@ -1,12 +0,0 @@
1
- # Environment of the FM-DiT / DP / ACT baselines (training and the policy server), Python 3.12, CUDA 12.8 wheels:
2
- # uv venv <env> --python 3.12
3
- # uv pip install --python <env>/bin/python -r evaluation/baselines/requirements.txt \
4
- # --extra-index-url https://download.pytorch.org/whl/cu128 --index-strategy unsafe-best-match
5
- torch==2.9.0+cu128
6
- torchvision==0.24.0+cu128
7
- diffusers==0.35.1
8
- av==15.1.0
9
- pyarrow==23.0.1
10
- numpy==2.2.6
11
- opencv-python-headless==4.11.0.86
12
- pytest==8.4.2
 
 
 
 
 
 
 
 
 
 
 
 
 
code/hb_baselines_20261117/baselines/runtime.py DELETED
@@ -1,123 +0,0 @@
1
- """Checkpoints and inference of the baselines.
2
-
3
- A checkpoint is a directory written by train.py (`<run>/checkpoints/step-NNNNNN/`, `final` links the last one):
4
-
5
- - `model.pt`: torch.save of {format, config (the config.json text), state_dict}: the EMA weights (or the raw ones when
6
- EMA is off) with the policy's state and action normalizers, loaded strictly with `weights_only=True`;
7
- - `config.json`: the policy configuration, the contract (robot, cameras, state and action columns), the image size,
8
- the training task text, dataset, episodes, recipe and statistics;
9
- - `protocol.json`: model.pt's size and SHA-256.
10
-
11
- `BaselinePolicy.predict` takes the live frames of the checkpoint's cameras (any size; resized with data.resize_frame,
12
- as the training cache), the physical state of the contract and a seed, and returns the physical (horizon,
13
- action_dim) chunk with its normalized form; row 0 is the action of the observation's frame.
14
- """
15
- from __future__ import annotations
16
-
17
- import hashlib
18
- import json
19
- from pathlib import Path
20
-
21
- import numpy as np
22
-
23
- FORMAT = 'hb_baselines/1'
24
-
25
-
26
- def sha256(path) -> str:
27
- digest = hashlib.sha256()
28
- with Path(path).open('rb') as stream:
29
- for block in iter(lambda: stream.read(16 << 20), b''):
30
- digest.update(block)
31
- return digest.hexdigest()
32
-
33
-
34
- def save_checkpoint(folder, policy, config: dict):
35
- """Write model.pt, config.json and protocol.json of `policy` (an nn.Module) into `folder`."""
36
- import torch
37
- folder = Path(folder)
38
- folder.mkdir(parents=True, exist_ok=True)
39
- text = json.dumps(dict(config, format=FORMAT), indent=1)
40
- state = {k: v.detach().cpu().contiguous() for k, v in policy.state_dict().items()}
41
- torch.save(dict(format=FORMAT, config=text, state_dict=state), folder / 'model.pt.tmp')
42
- (folder / 'model.pt.tmp').replace(folder / 'model.pt')
43
- (folder / 'config.json').write_text(text)
44
- (folder / 'protocol.json').write_text(json.dumps(dict(
45
- format=FORMAT, step=config.get('step'), policy=config['policy']['policy'],
46
- files={'model.pt': dict(bytes=(folder / 'model.pt').stat().st_size, sha256=sha256(folder / 'model.pt'))}),
47
- indent=1))
48
-
49
-
50
- def load_checkpoint(folder, device='cpu', verify=True):
51
- """(policy in eval mode on `device`, config dict) of a checkpoint directory."""
52
- import torch
53
- from .policies import build_policy
54
- folder = Path(folder)
55
- if verify:
56
- protocol = json.loads((folder / 'protocol.json').read_text())
57
- entry = protocol['files']['model.pt']
58
- if (folder / 'model.pt').stat().st_size != entry['bytes']:
59
- raise ValueError(f'{folder}/model.pt differs from protocol.json')
60
- payload = torch.load(folder / 'model.pt', map_location='cpu', weights_only=True)
61
- if payload.get('format') != FORMAT:
62
- raise ValueError(f"{folder}: format {payload.get('format')!r}, expected {FORMAT}")
63
- config = json.loads(payload['config'])
64
- if json.loads((folder / 'config.json').read_text()) != config:
65
- raise ValueError(f'{folder}: config.json differs from the one inside model.pt')
66
- policy = build_policy(config['policy'], pretrained=False) # every weight comes from model.pt
67
- policy.load_state_dict(payload['state_dict'], strict=True)
68
- return policy.to(device).eval(), config
69
-
70
-
71
- class BaselinePolicy:
72
- """A loaded checkpoint for closed-loop inference (one request at a time)."""
73
-
74
- def __init__(self, checkpoint, device='cuda:0', policy: str | None = None, robot: str | None = None):
75
- import torch
76
- self.torch = torch
77
- self.device = torch.device(device)
78
- self.model, self.config = load_checkpoint(checkpoint, device=self.device)
79
- self.checkpoint = str(Path(checkpoint).resolve())
80
- name, contract = self.config['policy']['policy'], self.config['contract']
81
- if policy is not None and name != policy:
82
- raise ValueError(f'{checkpoint} is a {name!r} checkpoint, not {policy!r}')
83
- if robot is not None and contract['robot'] != robot:
84
- raise ValueError(f"{checkpoint} was trained for {contract['robot']!r} ({contract['name']}), not {robot!r}")
85
- self.name, self.contract = name, contract
86
- self.cameras = tuple(contract['cameras'])
87
- self.image_hw = tuple(self.config['image_hw'])
88
- self.horizon = int(self.config['policy']['horizon'])
89
- self.state_dim, self.action_dim = int(contract['state_dim']), int(contract['action_dim'])
90
- self.sampling_steps = int(self.model.sampling_steps)
91
- self.task_text = self.config.get('task_text')
92
-
93
- def info(self) -> dict:
94
- return dict(model=self.name, checkpoint=self.checkpoint, step=self.config.get('step'),
95
- contract=self.contract['name'], views=list(self.cameras), image_hw=list(self.image_hw),
96
- action_chunk=self.horizon, action_dim=self.action_dim, state_dim=self.state_dim,
97
- sampling_steps=self.sampling_steps, task_text=self.task_text,
98
- training_data=self.config.get('dataset', {}).get('name'))
99
-
100
- def images_tensor(self, images: dict):
101
- from .data import resize_frame
102
- missing = [c for c in self.cameras if c not in images]
103
- if missing:
104
- raise KeyError(f'missing cameras {missing}; the checkpoint reads {list(self.cameras)}')
105
- frames = np.stack([resize_frame(np.asarray(images[c]), self.image_hw) for c in self.cameras])
106
- x = self.torch.from_numpy(frames).to(self.device).permute(0, 3, 1, 2).float().div_(255.)
107
- return x.unsqueeze(0) # (1, n_cameras, 3, h, w)
108
-
109
- def predict(self, images: dict, state, seed: int = 0):
110
- """(action (horizon, action_dim) float32 physical, normalized (horizon, action_dim) float32)."""
111
- torch = self.torch
112
- state = np.asarray(state, np.float32).reshape(-1)
113
- if state.shape != (self.state_dim,) or not np.isfinite(state).all():
114
- raise ValueError(f'expected a finite state of {self.state_dim} values, got {state.shape}')
115
- generator = torch.Generator(device=self.device)
116
- generator.manual_seed(int(seed) % (2 ** 63 - 1))
117
- with torch.inference_mode():
118
- action, raw = self.model.predict(self.images_tensor(images),
119
- torch.from_numpy(state)[None].to(self.device), generator=generator)
120
- action = action[0].float().cpu().numpy()
121
- if action.shape != (self.horizon, self.action_dim) or not np.isfinite(action).all():
122
- raise ValueError(f'invalid prediction {action.shape}')
123
- return np.ascontiguousarray(action, np.float32), raw[0].float().cpu().numpy().astype(np.float32)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
code/hb_baselines_20261117/baselines/train.py DELETED
@@ -1,441 +0,0 @@
1
- """Train an FM-DiT, DP (DDPM-DiT) or ACT baseline on a task's LeRobot v2.1 expert dataset.
2
-
3
- <baselines env>/bin/python -I evaluation/baselines/train.py --policy fm_dit --contract h2_sharpa \\
4
- --dataset data/h2_pour_water/h2_pour_water_r1/lerobot --out <run dir> --steps 60000
5
-
6
- The recipe is DextraVerse's shared IL recipe (configs/algorithm/il/train.yaml; runners/train_dex_flow_matching.py):
7
- AdamW (lr 1e-4, betas 0.95/0.999, weight decay 1e-6), cosine decay (here after a 500-step linear warm-up, as
8
- Diffusion Policy), whole-policy EMA (Diffusion Policy's warm-up schedule, max decay 0.9999) whose weights are the
9
- saved checkpoint, batch 64, one observation frame and 16-row chunks. Added for the humanoid views: frames resized
10
- to 168x224 (the 480x640 aspect). bf16 autocast on CUDA.
11
-
12
- Augmentation (2026-11-16): the Humanoid Benchmark spec v2 (docs/augmentation_v2.md, evaluation/augmentation), the
13
- same for every model of the benchmark, is on by default (--augmentation hb-v2): per training item one hb_aug_v2 call
14
- on the cached 168x224 frames of all cameras (colour shared, geometry / light patches / white balance per camera, one
15
- of the 15 effects boosted 1.5 x) and the per-sample joint bias (+-2 deg) + noise (0.25 deg, clipped 3 sigma) on the
16
- body joint angles of the raw state (G1 29, H2 31), before the policy's normalizers; actions untouched. The native
17
- random shift is off (--shift 0; a shift with hb-v2 is refused). Before the first step a preflight reads training items
18
- through the augmented and the plain path and checks the state width (G1 44 / H2 78, no velocity), that only the body
19
- joints move and by at most 2.75 deg, that the action rows are bit-identical, that the images change, and that the
20
- offline-check items are deterministic; it is stored in run.json (--preflight-only stops after it). --augmentation
21
- none is an explicit exception to the spec, recorded in run.json and the checkpoints. The ResNet18 starts from torchvision's ImageNet-1k weights
22
- (--backbone-weights IMAGENET1K_V1, downloaded once to the torch hub cache) and is fine-tuned at 0.1 x the learning
23
- rate (--backbone-lr-scale, the DETR practice) with its BatchNorm frozen; --backbone-weights none trains it from
24
- scratch (DextraVerse's GroupNorm encoder for FM-DiT and DP).
25
-
26
- Writes into --out: run.json (arguments), train_log.jsonl, checkpoints/step-NNNNNN/ every --save-every steps and at the
27
- end (runtime.py format), checkpoints/final -> the last one, and train_state.pt (optimizer, schedule, EMA, step) that
28
- --resume continues from. Each save also measures the EMA policy offline on fixed frames (held-out episodes with
29
- --val-episodes, else training frames): normalized-action MSE overall and per action group.
30
- """
31
- from __future__ import annotations
32
-
33
- import argparse
34
- import copy
35
- from datetime import datetime
36
- import json
37
- import math
38
- import os
39
- from pathlib import Path
40
- import subprocess
41
- import sys
42
- import time
43
-
44
- import numpy as np
45
-
46
- HERE = Path(__file__).resolve().parent
47
- REPO = HERE.parents[1]
48
- if str(HERE.parent) not in sys.path:
49
- sys.path.insert(0, str(HERE.parent))
50
-
51
- from baselines.data import (CONTRACTS, ChunkDataset, LeRobotDataset, augmentation_module, frame_cache, # noqa: E402
52
- load_lowdim, parse_episodes, statistics)
53
- from baselines.policies import POLICIES, PolicyConfig, build_policy # noqa: E402
54
- from baselines.runtime import save_checkpoint # noqa: E402
55
-
56
- DEFAULTS = dict(lr=1e-4, betas=(0.95, 0.999), weight_decay=1e-6, warmup=500, ema=0.9999, batch_size=64,
57
- backbone_weights='IMAGENET1K_V1', backbone_lr_scale=0.1)
58
-
59
-
60
- def git_commit():
61
- try:
62
- return subprocess.run(['git', '-C', str(REPO), 'rev-parse', 'HEAD'], capture_output=True, text=True,
63
- check=True).stdout.strip()
64
- except Exception: # noqa: BLE001 - outside a checkout
65
- return None
66
-
67
-
68
- def parse_hw(text):
69
- h, w = text.lower().split('x')
70
- return int(h), int(w)
71
-
72
-
73
- def random_shift(images, pad):
74
- """DrQ random shift: replicate-pad by `pad` pixels and crop back at a random offset per sample.
75
- images (B, N, 3, H, W) float."""
76
- import torch
77
- import torch.nn.functional as F
78
- if pad <= 0:
79
- return images
80
- B, N, C, H, W = images.shape
81
- x = F.pad(images.reshape(B * N, C, H, W), (pad,) * 4, mode='replicate')
82
- oy = torch.randint(0, 2 * pad + 1, (B * N,), device=images.device)
83
- ox = torch.randint(0, 2 * pad + 1, (B * N,), device=images.device)
84
- rows = (oy[:, None] + torch.arange(H, device=images.device)[None])[:, None, :, None].expand(-1, C, -1, W + 2 * pad)
85
- x = x.gather(2, rows)
86
- cols = (ox[:, None] + torch.arange(W, device=images.device)[None])[:, None, None, :].expand(-1, C, H, -1)
87
- return x.gather(3, cols).reshape(B, N, C, H, W)
88
-
89
-
90
- class EMA:
91
- """Diffusion Policy's EMAModel schedule: decay = min(max_decay, 1 - (1 + step) ** -0.75), parameters averaged,
92
- buffers (normalizers) copied."""
93
-
94
- def __init__(self, model, max_decay):
95
- self.model = copy.deepcopy(model).eval().requires_grad_(False)
96
- self.max_decay = float(max_decay)
97
-
98
- def update(self, model, step):
99
- import torch
100
- decay = 0.0 if step <= 0 else min(self.max_decay, max(0.0, 1 - (1 + step) ** -0.75))
101
- with torch.no_grad():
102
- for e, p in zip(self.model.parameters(), model.parameters()):
103
- e.mul_(decay).add_(p.detach(), alpha=1 - decay)
104
- for e, b in zip(self.model.buffers(), model.buffers()):
105
- e.copy_(b)
106
- return decay
107
-
108
-
109
- def preflight(train_set, eval_set, contract, samples=64, seed=0) -> dict:
110
- """Training items of `train_set` (augmented unless its body_dims is 0) against the same frames read without
111
- augmentation, and two reads of the offline-check items; raises on any violation of docs/augmentation_v2.md."""
112
- import torch
113
- plain = ChunkDataset(train_set.lowdim, train_set.paths, train_set.cameras, train_set.hw, train_set.horizon,
114
- train_set.positions) # the same frames without augmentation
115
- picks = np.random.default_rng(seed).choice(len(plain), size=min(samples, len(plain)), replace=False)
116
- nb, sd = train_set.body_dims, contract.state_dim
117
- limit = augmentation_module().max_body_offset_rad() * (1 + 1e-5)
118
- images_changed = body_moved = 0
119
- worst = 0.0
120
- for k in picks:
121
- (im, st, ac), (im0, st0, ac0) = train_set[int(k)], plain[int(k)]
122
- if st.shape != (sd,) or st0.shape != (sd,) or ac.shape != ac0.shape:
123
- raise SystemExit(f'preflight: state {tuple(st.shape)} / action {tuple(ac.shape)}, expected ({sd},)')
124
- if not torch.equal(ac, ac0):
125
- raise SystemExit('preflight: an action label differs from the recorded data')
126
- if not torch.equal(st[nb:], st0[nb:]):
127
- raise SystemExit(f'preflight: a state value past the {nb} body joints changed')
128
- delta = (st[:nb].double() - st0[:nb].double()).abs()
129
- if nb:
130
- worst = max(worst, float(delta.max()))
131
- if worst > limit:
132
- raise SystemExit(f'preflight: a body joint moved {math.degrees(worst):.3f} deg (> 2.75)')
133
- body_moved += int((delta > 0).sum())
134
- images_changed += int(not torch.equal(im, im0))
135
- n = len(picks)
136
- moved = body_moved / max(1, n * nb)
137
- if nb and (images_changed < 0.9 * n or moved < 0.95):
138
- raise SystemExit(f'preflight: augmentation inactive ({images_changed}/{n} images changed, {moved:.3f} of the '
139
- 'body joint values moved)')
140
- if not nb and (images_changed or worst):
141
- raise SystemExit('preflight: items changed with the augmentation off')
142
- eval_picks = np.random.default_rng(seed + 1).choice(len(eval_set), size=min(8, len(eval_set)), replace=False)
143
- for k in eval_picks:
144
- a, b = eval_set[int(k)], eval_set[int(k)]
145
- if eval_set.body_dims or not all(torch.equal(x, y) for x, y in zip(a, b)):
146
- raise SystemExit('preflight: the offline-check items are not deterministic')
147
- return dict(samples=n, state_dim=sd, body_dims=nb, images_changed=images_changed,
148
- body_values_moved=round(moved, 4),
149
- max_body_offset_deg=round(math.degrees(worst), 4), actions_bit_identical=True,
150
- non_body_state_bit_identical=True, eval_items_deterministic=len(eval_picks))
151
-
152
-
153
- def offline_eval(policy, dataset, samples, device, groups):
154
- """Normalized-action MSE of policy.predict on fixed dataset items (seeded), overall and per action group."""
155
- import torch
156
- policy.eval()
157
- errs = []
158
- generator = torch.Generator(device=device)
159
- generator.manual_seed(0)
160
- for start in range(0, len(samples), 32):
161
- batch = [dataset[int(k)] for k in samples[start:start + 32]]
162
- images = torch.stack([b[0] for b in batch]).to(device).permute(0, 1, 4, 2, 3).float().div_(255.)
163
- state = torch.stack([b[1] for b in batch]).to(device)
164
- target = torch.stack([b[2] for b in batch]).to(device)
165
- _, raw = policy.predict(images, state, generator=generator)
166
- errs.append((raw.float() - policy.action_norm.normalize(target)).pow(2).cpu().numpy())
167
- err = np.concatenate(errs) # (S, horizon, action_dim)
168
- out = dict(mse=float(err.mean()), mse_row0=float(err[:, 0].mean()))
169
- offset = 0
170
- for column, start, end in groups:
171
- out[f'mse_{column.split(".")[-1]}'] = float(err[..., offset:offset + end - start].mean())
172
- offset += end - start
173
- return out
174
-
175
-
176
- def main():
177
- p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
178
- p.add_argument('--policy', choices=sorted(POLICIES), required=True)
179
- p.add_argument('--dataset', type=Path, required=True, help='LeRobot v2.1 dataset directory')
180
- p.add_argument('--contract', choices=sorted(CONTRACTS), required=True)
181
- p.add_argument('--cameras', help='comma-separated cameras (default: the contract\'s)')
182
- p.add_argument('--episodes', help="episodes to use, e.g. '0:100' (default: all)")
183
- p.add_argument('--val-episodes', type=int, default=0, help='hold out the last N of them for the offline check')
184
- p.add_argument('--out', type=Path, required=True)
185
- p.add_argument('--steps', type=int, default=60000)
186
- p.add_argument('--batch-size', type=int, default=DEFAULTS['batch_size'])
187
- p.add_argument('--lr', type=float, default=DEFAULTS['lr'])
188
- p.add_argument('--weight-decay', type=float, default=DEFAULTS['weight_decay'])
189
- p.add_argument('--warmup', type=int, default=DEFAULTS['warmup'])
190
- p.add_argument('--ema', type=float, default=DEFAULTS['ema'], help='max EMA decay; 0 saves the raw weights')
191
- p.add_argument('--horizon', type=int, default=16)
192
- p.add_argument('--image-size', default='168x224', help='HxW of the policy images')
193
- p.add_argument('--augmentation', choices=['hb-v2', 'none'], default='hb-v2',
194
- help='training augmentation: the benchmark spec v2 (default; docs/augmentation_v2.md) or none '
195
- '(an explicit exception, recorded in run.json)')
196
- p.add_argument('--shift', type=int, default=0,
197
- help='native random-shift augmentation in pixels (default 0: off; only with --augmentation none)')
198
- p.add_argument('--preflight-only', action='store_true', help='run the data preflight, write run.json and stop')
199
- p.add_argument('--backbone-weights', default=DEFAULTS['backbone_weights'],
200
- help="torchvision weights the ResNet18 starts from (default %(default)s); 'none': from scratch")
201
- p.add_argument('--backbone-lr-scale', type=float, default=DEFAULTS['backbone_lr_scale'],
202
- help='learning rate of the image backbone relative to --lr (default %(default)s)')
203
- p.add_argument('--model', action='append', default=[], metavar='KEY=VALUE',
204
- help='override a PolicyConfig field (JSON value), e.g. num_layers=6; repeatable')
205
- p.add_argument('--cache-dir', type=Path, default=Path('~/hb_models/baselines/cache'))
206
- p.add_argument('--workers', type=int, default=32,
207
- help='DataLoader workers (and frame-cache decoders); the v2 augmentation costs ~17 ms of one CPU '
208
- 'core per item, so 8 workers feed only ~6 steps/s at batch 64')
209
- p.add_argument('--prefetch', type=int, default=2, help='batches prefetched per worker')
210
- p.add_argument('--save-every', type=int, default=10000)
211
- p.add_argument('--log-every', type=int, default=100)
212
- p.add_argument('--eval-samples', type=int, default=256)
213
- p.add_argument('--seed', type=int, default=0)
214
- p.add_argument('--device', default='cuda:0')
215
- p.add_argument('--no-amp', action='store_true')
216
- p.add_argument('--resume', action='store_true', help='continue from <out>/train_state.pt')
217
- args = p.parse_args()
218
-
219
- out = args.out.expanduser().resolve()
220
- out.mkdir(parents=True, exist_ok=True)
221
- contract = CONTRACTS[args.contract]
222
- aug = augmentation_module()
223
- aug.check_state_layout(contract.robot, contract.state_dim, [column for column, _, _ in contract.state])
224
- hb_aug = args.augmentation == 'hb-v2'
225
- if hb_aug and args.shift:
226
- raise SystemExit('--shift is the native random shift, which the augmentation spec v2 turns off '
227
- '(docs/augmentation_v2.md); use it only with --augmentation none')
228
- if contract.body_dims != aug.BODY_JOINTS[contract.robot]:
229
- raise SystemExit(f'contract {contract.name}: body_dims {contract.body_dims}, the spec perturbs '
230
- f'{aug.BODY_JOINTS[contract.robot]} body joints')
231
- augmentation = (aug.describe(contract.robot, contract.body_dims) if hb_aug else
232
- dict(version=None, exception='--augmentation none (not the benchmark default)'))
233
- cameras = tuple(args.cameras.split(',')) if args.cameras else contract.cameras
234
- hw = parse_hw(args.image_size)
235
- dataset = LeRobotDataset(args.dataset)
236
- dataset.check_contract(contract, cameras)
237
- episodes = parse_episodes(args.episodes, dataset.lengths)
238
- if not 0 <= args.val_episodes < len(episodes):
239
- raise SystemExit('--val-episodes must leave training episodes')
240
- lowdim = load_lowdim(dataset, contract, episodes)
241
- if len(lowdim['tasks']) != 1:
242
- raise SystemExit(f"the baselines take no language: one task per dataset, found {lowdim['tasks']}")
243
- n_train = len(episodes) - args.val_episodes
244
- train_pos, val_pos = list(range(n_train)), list(range(n_train, len(episodes)))
245
- train_rows = np.concatenate([np.arange(s, s + n) for s, n in
246
- zip(lowdim['starts'][:n_train], lowdim['lengths'][:n_train])])
247
- stats = statistics(lowdim, train_rows)
248
- frames = frame_cache(dataset, lowdim, cameras, hw, args.cache_dir, workers=args.workers)
249
- train_set = ChunkDataset(lowdim, frames, cameras, hw, args.horizon, train_pos,
250
- body_dims=contract.body_dims if hb_aug else 0)
251
- eval_set = ChunkDataset(lowdim, frames, cameras, hw, args.horizon, val_pos or train_pos) # never augmented
252
- checks = preflight(train_set, eval_set, contract, seed=args.seed)
253
- print(json.dumps(dict(event='preflight', augmentation=augmentation.get('version'), **checks)), flush=True)
254
- if args.preflight_only:
255
- (out / 'run.json').write_text(json.dumps(dict(
256
- argv=sys.argv, started=datetime.now().isoformat(timespec='seconds'), host=os.uname().nodename,
257
- contract=contract.to_dict(cameras), image_hw=list(hw), augmentation=augmentation, preflight=checks,
258
- shift_px=args.shift, code_commit=git_commit()), indent=1, default=str))
259
- return
260
-
261
- import torch
262
- # Data parallel when launched by torchrun with WORLD_SIZE > 1: --batch-size stays the global batch (split evenly
263
- # over the ranks, gradients averaged by DDP), rank 0 alone logs, evaluates and saves.
264
- world = int(os.environ.get('WORLD_SIZE', '1'))
265
- rank = int(os.environ.get('RANK', '0'))
266
- if world > 1:
267
- import torch.distributed as dist
268
- if args.batch_size % world:
269
- raise SystemExit(f'--batch-size {args.batch_size} is not divisible by {world} ranks')
270
- device = torch.device('cuda', int(os.environ['LOCAL_RANK']))
271
- torch.cuda.set_device(device)
272
- dist.init_process_group('nccl', device_id=device)
273
- else:
274
- device = torch.device(args.device)
275
- main_rank = rank == 0
276
- torch.manual_seed(args.seed)
277
- np.random.seed(args.seed)
278
- overrides = {k: json.loads(v) for k, v in (item.split('=', 1) for item in args.model)}
279
- weights = None if str(args.backbone_weights).lower() in ('none', '') else args.backbone_weights
280
- pcfg = PolicyConfig.from_dict({**dict(policy=args.policy, n_cameras=len(cameras), state_dim=contract.state_dim,
281
- action_dim=contract.action_dim, horizon=args.horizon,
282
- backbone_weights=weights), **overrides})
283
- policy = build_policy(pcfg)
284
- policy.fit_normalizers(stats)
285
- policy.to(device)
286
- ema = EMA(policy, args.ema) if args.ema > 0 else None
287
- named = list(policy.named_parameters())
288
- backbone = [p for n, p in named if n.startswith(policy.backbone_prefix)]
289
- rest = [p for n, p in named if not n.startswith(policy.backbone_prefix)]
290
- if not backbone:
291
- raise SystemExit(f'no backbone parameters under {policy.backbone_prefix!r}')
292
- optimizer = torch.optim.AdamW([dict(params=rest), dict(params=backbone, lr=args.lr * args.backbone_lr_scale)],
293
- lr=args.lr, betas=DEFAULTS['betas'], weight_decay=args.weight_decay)
294
-
295
- def lr_lambda(step):
296
- if step < args.warmup:
297
- return (step + 1) / max(1, args.warmup)
298
- return 0.5 * (1 + math.cos(math.pi * min(1.0, (step - args.warmup) / max(1, args.steps - args.warmup))))
299
-
300
- scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda)
301
- step = 0
302
- state_path = out / 'train_state.pt'
303
- if args.resume and state_path.exists():
304
- saved = torch.load(state_path, map_location='cpu', weights_only=False)
305
- if saved['config']['policy'] != pcfg.to_dict():
306
- raise SystemExit('train_state.pt was written for another policy configuration')
307
- before = saved['config'].get('training', {})
308
- if (before.get('augmentation') or {}).get('version') != augmentation.get('version') \
309
- or before.get('shift_px') != args.shift:
310
- raise SystemExit('train_state.pt was trained with another augmentation (version / --shift); resuming '
311
- 'would change it mid-run')
312
- policy.load_state_dict(saved['policy'])
313
- optimizer.load_state_dict(saved['optimizer'])
314
- scheduler.load_state_dict(saved['scheduler'])
315
- if ema is not None:
316
- ema.model.load_state_dict(saved['ema'])
317
- step = int(saved['step'])
318
- print(json.dumps(dict(event='resumed', step=step)), flush=True)
319
-
320
- samples = np.random.default_rng(1).choice(len(eval_set), size=min(args.eval_samples, len(eval_set)), replace=False)
321
- config = dict(
322
- policy=pcfg.to_dict(), contract=contract.to_dict(cameras), image_hw=list(hw), task_text=lowdim['tasks'][0],
323
- dataset=dict(name=dataset.name,
324
- root=str(dataset.root), robot_type=dataset.info.get('robot_type'), fps=dataset.fps,
325
- episodes=episodes, train_episodes=episodes[:n_train], val_episodes=episodes[n_train:],
326
- train_frames=int(len(train_set)),
327
- git_commit=dataset.info.get('script_config', {}).get('git_commit')),
328
- training=dict(steps=args.steps, batch_size=args.batch_size, lr=args.lr, betas=list(DEFAULTS['betas']),
329
- weight_decay=args.weight_decay, warmup=args.warmup, schedule='linear warm-up + cosine',
330
- backbone_lr_scale=args.backbone_lr_scale,
331
- ema=args.ema, shift_px=args.shift, amp=not args.no_amp, seed=args.seed,
332
- world_size=world, batch_per_gpu=args.batch_size // world,
333
- augmentation=augmentation, preflight=checks),
334
- stats=stats, code_commit=git_commit())
335
- if main_rank:
336
- run = dict(argv=sys.argv, started=datetime.now().isoformat(timespec='seconds'), host=os.uname().nodename,
337
- torch=torch.__version__, **config)
338
- (out / 'run.json').write_text(json.dumps(run, indent=1, default=str))
339
- sampler = None
340
- if world > 1:
341
- from torch.nn.parallel import DistributedDataParallel
342
- sampler = torch.utils.data.DistributedSampler(train_set, shuffle=True, seed=args.seed, drop_last=True)
343
-
344
- class _Loss(torch.nn.Module):
345
- def __init__(self, inner):
346
- super().__init__()
347
- self.inner = inner
348
-
349
- def forward(self, images, state, action):
350
- return self.inner.compute_loss(images, state, action)
351
-
352
- compute = DistributedDataParallel(_Loss(policy), device_ids=[device.index], find_unused_parameters=True,
353
- gradient_as_bucket_view=True)
354
- torch.manual_seed(args.seed + rank) # per-rank noise draws; workers are seeded from this generator
355
- else:
356
- compute = policy.compute_loss
357
- loader = torch.utils.data.DataLoader(train_set, batch_size=args.batch_size // world, shuffle=sampler is None,
358
- sampler=sampler, drop_last=True,
359
- num_workers=args.workers, pin_memory=True, persistent_workers=True,
360
- prefetch_factor=args.prefetch)
361
- params = sum(x.numel() for x in policy.parameters())
362
- if main_rank:
363
- print(json.dumps(dict(event='start', policy=args.policy, params=params,
364
- backbone_params=sum(x.numel() for x in backbone),
365
- backbone_weights=pcfg.backbone_weights, backbone_norm=pcfg.backbone_norm,
366
- train_frames=len(train_set), steps=args.steps, from_step=step, cameras=list(cameras),
367
- hw=list(hw), world_size=world, batch_per_gpu=args.batch_size // world)), flush=True)
368
- log = (out / 'train_log.jsonl').open('a') if main_rank else None
369
- amp = (not args.no_amp) and device.type == 'cuda'
370
-
371
- def save(step):
372
- folder = out / f'checkpoints/step-{step:06d}'
373
- model = ema.model if ema is not None else policy
374
- metrics = offline_eval(model, eval_set, samples, device, contract.action)
375
- save_checkpoint(folder, model, dict(config, step=step, weights='ema' if ema is not None else 'raw',
376
- offline_eval=dict(metrics, samples=len(samples),
377
- frames='val' if val_pos else 'train')))
378
- final = out / 'checkpoints/final'
379
- if final.is_symlink() or final.exists():
380
- final.unlink()
381
- final.symlink_to(folder.name)
382
- torch.save(dict(policy=policy.state_dict(), optimizer=optimizer.state_dict(), scheduler=scheduler.state_dict(),
383
- ema=None if ema is None else ema.model.state_dict(), step=step, config=config),
384
- out / 'train_state.pt.tmp')
385
- (out / 'train_state.pt.tmp').replace(state_path)
386
- record = dict(event='save', step=step, checkpoint=str(folder), **metrics)
387
- print(json.dumps(record), flush=True)
388
- log.write(json.dumps(record) + '\n')
389
- log.flush()
390
- policy.train()
391
-
392
- policy.train()
393
- t0, data_s, acc = time.monotonic(), 0.0, {}
394
- epoch = step // max(1, len(loader)) # a resumed DDP run continues the sampler's epoch sequence
395
- while step < args.steps:
396
- if sampler is not None:
397
- sampler.set_epoch(epoch)
398
- epoch += 1
399
- tick = time.monotonic()
400
- for images, state, action in loader:
401
- data_s += time.monotonic() - tick
402
- images = images.to(device, non_blocking=True).permute(0, 1, 4, 2, 3).float().div_(255.)
403
- images = random_shift(images, args.shift)
404
- state, action = state.to(device, non_blocking=True), action.to(device, non_blocking=True)
405
- with torch.autocast(device.type, dtype=torch.bfloat16, enabled=amp):
406
- loss, metrics = compute(images, state, action)
407
- optimizer.zero_grad(set_to_none=True)
408
- loss.backward()
409
- optimizer.step()
410
- scheduler.step()
411
- step += 1
412
- decay = ema.update(policy, step) if ema is not None else 0.0
413
- for k, v in dict(metrics, loss=float(loss.detach())).items():
414
- acc[k] = acc.get(k, 0.0) + v
415
- if step % args.log_every == 0 and main_rank:
416
- elapsed = time.monotonic() - t0
417
- record = dict(event='train', step=step, lr=scheduler.get_last_lr()[0],
418
- backbone_lr=scheduler.get_last_lr()[1], ema_decay=round(decay, 6),
419
- it_s=round(args.log_every / elapsed, 2), data_frac=round(data_s / elapsed, 3),
420
- **{k: v / args.log_every for k, v in acc.items()})
421
- print(json.dumps(record), flush=True)
422
- log.write(json.dumps(record) + '\n')
423
- log.flush()
424
- t0, data_s, acc = time.monotonic(), 0.0, {}
425
- if step % args.save_every == 0 or step == args.steps:
426
- if main_rank:
427
- save(step)
428
- if world > 1:
429
- dist.barrier()
430
- if step >= args.steps:
431
- break
432
- tick = time.monotonic()
433
- if main_rank:
434
- log.close()
435
- print(json.dumps(dict(event='done', step=step, checkpoint=str(out / 'checkpoints/final'))), flush=True)
436
- if world > 1:
437
- dist.destroy_process_group()
438
-
439
-
440
- if __name__ == '__main__':
441
- main()