File size: 67,333 Bytes
06f9561
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
from __future__ import annotations
import os
import re
import base64
import copy
import json
import math
import time
from io import BytesIO
from typing import (TYPE_CHECKING, Annotated, Any, Dict, List, Optional, Tuple,
                    Union)

import numpy as np
import torch
import torch.nn.functional as F
from PIL import Image
from pydantic import BaseModel, Field, model_validator
from torchvision.transforms import v2
from psi.config.augmentation import *
from psi.data.seed.motion_repr import build_seed_textop_action, build_seed_textop_state
from psi.utils import get_asset_dir, pt_to_pil, resolve_path, pad_to_len

IGNORE_INDEX = -100

class RepackTransform(BaseModel):
    def __call__(self, data: dict[str, Any], **kwargs) -> dict[str, Any]:
        return data

class LerobotRepackTransform(RepackTransform):

    def delta_timestamps(self, fps: int) -> dict[str, list[float]]:
        ...  

class ModelTransform(BaseModel):
    def __call__(self, data: dict[str, Any], no_aug: bool = False, **kwargs) -> dict[str, Any]:
        return data

class FieldTransform(BaseModel):
    def __call__(self, data: dict[str, Any], **kwargs) -> dict[str, Any]:
        return data

class DataTransform(BaseModel):
    repack: RepackTransform
    model: ModelTransform
    field: FieldTransform
    
    def __call__(self, data:dict[str, Any], **kwargs) -> dict[str, Any]:
        data = self.repack(data, **kwargs)
        data = self.field(data, **kwargs)
        data = self.model(data, **kwargs)
        return data
    
class EgodexRepackTransform(BaseModel):
    dataset_name: str = "egodex"
    stage:str = "pretrain"  # "pretrain" or "postpre"
    pad_action_dim: int | None = None
    pad_state_dim: int | None = None

    def __call__(self, data: dict[str, Any], **kwargs) -> dict[str, Any]:
        states, _ = pad_to_len(data["states"], self.pad_state_dim) if self.pad_state_dim is not None else (data["states"], None)
        if self.pad_action_dim is not None:
            actions, mask = pad_to_len(data["actions"], self.pad_action_dim) 
        else:
            actions = data["actions"]
            mask = np.ones_like(actions, dtype=bool)

        return dict(
            observations = [Image.fromarray(img[0]) for img in data["current_images"]],  # list of PIL Image
            states=states,  # (To, Da)
            actions=actions,  # (Tp, Da)
            instruction=data["instruction"].lower(),
            dataset=data.get("dataset_name", self.dataset_name),
            actions_mask=mask, #(Tp, Da)
        )

class HEPretrainRepackTransform(RepackTransform):
    dataset_name: str = "humanoid-everyday"
    num_past_frames: int = 0
    action_chunk_size: int = 1
    use_delta_actions: bool = True
    robot_type: str = "g1"
    # pad_action_dim: int | None = None
    # pad_state_dim: int | None = None

    def _to_numpy(self, value, dtype=np.float32):
        if isinstance(value, torch.Tensor):
            value = value.detach().cpu().numpy()
        return np.asarray(value, dtype=dtype)

    def _ensure_2d(self, value, dim: int, name: str):
        arr = self._to_numpy(value)
        if arr.ndim == 1:
            if arr.shape[0] != dim:
                raise ValueError(f"{name} expected shape ({dim},), got {arr.shape}")
            return arr.reshape(1, dim)
        if arr.ndim == 2:
            if arr.shape[1] != dim:
                raise ValueError(f"{name} expected shape (T,{dim}), got {arr.shape}")
            return arr
        raise ValueError(f"{name} expected 1D or 2D, got {arr.shape}")

    def _rpy_to_rot6d(self, rpy):
        from scipy.spatial.transform import Rotation as R
        rot = R.from_euler("xyz", rpy).as_matrix()
        return rot[:, :2].reshape(6)

    def _delta_rpy(self, rpy_seq):
        from scipy.spatial.transform import Rotation as R
        rot = R.from_euler("xyz", rpy_seq).as_matrix()
        rel = rot[1:] @ np.transpose(rot[:-1], (0, 2, 1))
        return R.from_matrix(rel).as_euler("xyz", degrees=False).astype(np.float32)

    def _build_actions(self, data: dict[str, Any]) -> np.ndarray:
        left_wrist_xyz = self._ensure_2d(
            data["action.wrists.left.xyz"], 3, "action.wrists.left.xyz"
        )
        left_wrist_rpy = self._ensure_2d(
            data["action.wrists.left.rpy"], 3, "action.wrists.left.rpy"
        )
        right_wrist_xyz = self._ensure_2d(
            data["action.wrists.right.xyz"], 3, "action.wrists.right.xyz"
        )
        right_wrist_rpy = self._ensure_2d(
            data["action.wrists.right.rpy"], 3, "action.wrists.right.rpy"
        )

        def tip_xyz(keys):
            for key in keys:
                if key in data:
                    return self._ensure_2d(data[key], 3, key)
            return np.zeros_like(left_wrist_xyz)

        left_thumb = tip_xyz(["action.hands.left_thumb.xyz"])
        left_index = tip_xyz(["action.hands.left_index.xyz"])
        left_middle = tip_xyz(
            ["action.hands.left_middle.xyz", "action.hands.left_middle_finger.xyz"]
        )
        left_ring = tip_xyz(["action.hands.left_ring_finger.xyz"])
        left_little = tip_xyz(["action.hands.left_little_finger.xyz"])

        right_thumb = tip_xyz(["action.hands.right_thumb.xyz"])
        right_index = tip_xyz(["action.hands.right_index.xyz"])
        right_middle = tip_xyz(
            ["action.hands.right_middle.xyz", "action.hands.right_middle_finger.xyz"]
        )
        right_ring = tip_xyz(["action.hands.right_ring_finger.xyz"])
        right_little = tip_xyz(["action.hands.right_little_finger.xyz"])

        if self.use_delta_actions:
            if left_wrist_xyz.shape[0] < 2:
                raise ValueError(
                    "use_delta_actions requires at least 2 action frames; "
                    "increase action_chunk_size or disable delta."
                )
            left_wrist_xyz = left_wrist_xyz[1:] - left_wrist_xyz[:-1]
            right_wrist_xyz = right_wrist_xyz[1:] - right_wrist_xyz[:-1]
            left_wrist_rpy = self._delta_rpy(left_wrist_rpy)
            right_wrist_rpy = self._delta_rpy(right_wrist_rpy)

            left_thumb = left_thumb[1:] - left_thumb[:-1]
            left_index = left_index[1:] - left_index[:-1]
            left_middle = left_middle[1:] - left_middle[:-1]
            left_ring = left_ring[1:] - left_ring[:-1]
            left_little = left_little[1:] - left_little[:-1]

            right_thumb = right_thumb[1:] - right_thumb[:-1]
            right_index = right_index[1:] - right_index[:-1]
            right_middle = right_middle[1:] - right_middle[:-1]
            right_ring = right_ring[1:] - right_ring[:-1]
            right_little = right_little[1:] - right_little[:-1]

            left_rot_pad = np.zeros_like(left_wrist_rpy)
            right_rot_pad = np.zeros_like(right_wrist_rpy)
        else:
            left_rot6d = np.stack(
                [self._rpy_to_rot6d(rpy) for rpy in left_wrist_rpy], axis=0
            )
            right_rot6d = np.stack(
                [self._rpy_to_rot6d(rpy) for rpy in right_wrist_rpy], axis=0
            )
            left_wrist_rpy = left_rot6d
            right_wrist_rpy = right_rot6d
            left_rot_pad = None
            right_rot_pad = None

        left_wrist = (
            np.concatenate([left_wrist_xyz, left_wrist_rpy, left_rot_pad], axis=1) #type:ignore
            if self.use_delta_actions
            else np.concatenate([left_wrist_xyz, left_wrist_rpy], axis=1)
        )
        right_wrist = (
            np.concatenate([right_wrist_xyz, right_wrist_rpy, right_rot_pad], axis=1) #type:ignore
            if self.use_delta_actions
            else np.concatenate([right_wrist_xyz, right_wrist_rpy], axis=1)
        )

        actions = np.concatenate(
            [
                left_wrist,
                left_thumb,
                left_index,
                left_middle,
                left_ring,
                left_little,
                right_wrist,
                right_thumb,
                right_index,
                right_middle,
                right_ring,
                right_little,
            ],
            axis=1,
        ).astype(np.float32)
        return actions

    def __call__(
        self,
        data: dict[str, Any],
        metadata=None,
        **kwargs,
    ) -> dict[str, Any]:
        hand_states = self._to_numpy(data["observation.hand_joints"])
        arm_states = self._to_numpy(data["observation.arm_joints"])
        if hand_states.ndim == 2:
            hand_states = hand_states[-1]
        if arm_states.ndim == 2:
            arm_states = arm_states[-1]
        states = np.concatenate((hand_states, arm_states), axis=0).astype(np.float32)

        try:
            actions = self._build_actions(data)
        except Exception as e:
            print("Error building actions:")
            print(data)

            import traceback
            traceback.print_exc()
            raise e

        instruction = ""
        if metadata is not None and "episode_index" in data:
            episode_idx = int(self._to_numpy(data["episode_index"]).reshape(-1)[0])
            if (
                hasattr(metadata, "episodes")
                and metadata.episodes is not None
                and episode_idx < len(metadata.episodes)
            ):
                instruction = metadata.episodes[episode_idx].get("instruction", "")
        if not instruction and "task" in data:
            instruction = data["task"]
        if isinstance(instruction, bytes):
            instruction = instruction.decode("utf-8")
            instruction = self.nice_instruction(instruction.split("/")[1])

        img = data["observation.images.egocentric"]
        if hasattr(img, "dim") and img.dim() == 4:
            img = img[0]
        elif isinstance(img, np.ndarray) and img.ndim == 4:
            img = img[0]

        return dict(
            observations=[pt_to_pil(img, normalized=False)],  # list of PIL Image
            states=states,
            actions=actions,
            instruction=str(instruction).lower(),
            dataset=data.get("dataset_name", self.dataset_name),
        )

    def nice_instruction(self, instruction: str) -> str:
        instruction = instruction.replace("_", " ").replace("-", " ")
        instruction = re.sub(r"\s+", " ", instruction)
        return instruction.strip()

    def delta_timestamps(self, fps: int):
        delta = {}
        delta["observation.hand_joints"] = [
            -t / fps for t in range(self.num_past_frames, -1, -1)
        ]
        delta["observation.arm_joints"] = [
            -t / fps for t in range(self.num_past_frames, -1, -1)
        ]

        action_keys = [
            "action.joint_angles",
            "action.wrists.left.xyz",
            "action.wrists.left.rpy",
            "action.wrists.right.xyz",
            "action.wrists.right.rpy",
            "action.hands.left_thumb.xyz",
            "action.hands.left_index.xyz",
            "action.hands.right_thumb.xyz",
            "action.hands.right_index.xyz",
        ]
        if self.robot_type == "h1":
            action_keys += [
                "action.hands.left_middle_finger.xyz",
                "action.hands.left_ring_finger.xyz",
                "action.hands.left_little_finger.xyz",
                "action.hands.right_middle_finger.xyz",
                "action.hands.right_ring_finger.xyz",
                "action.hands.right_little_finger.xyz",
            ]
        else:
            action_keys += [
                "action.hands.left_middle.xyz",
                "action.hands.right_middle.xyz",
            ]
        action_len = (
            self.action_chunk_size + 1 if self.use_delta_actions else self.action_chunk_size
        )
        for key in action_keys:
            delta[key] = [t / fps for t in range(action_len)]
        return delta

class RealRepackTransform(LerobotRepackTransform):
    dataset_name: str = "real"

    conditions: list[str] = Field(default_factory=lambda: [])
    image_keys: List[str] = Field(default_factory=lambda: ["observation.images.egocentric"])
    state_key: str = "states"
    action_key: str = "action"
    instruction_key: str = "task"

    num_past_frames: int = 0
    action_chunk_size: int = 30

    pad_action_dim: int | None = None
    pad_state_dim: int | None = None

    def delta_timestamps(self, fps):
        delta = {}
        for image_key in self.image_keys:
            delta[image_key] = [-t/fps for t in range(self.num_past_frames, -1, -1)]

        delta[self.state_key] = [-t/fps for t in range(self.num_past_frames, -1, -1)]
        delta[self.action_key] = [t/fps for t in range(self.action_chunk_size)]
        return delta

    def __call__(self, data: dict[str, Any], **kwargs) -> dict[str, Any]:
        states, _ = pad_to_len(data[self.state_key], self.pad_state_dim) if self.pad_state_dim is not None else (data[self.state_key], None)

        if self.pad_action_dim is not None:
            actions, mask = pad_to_len(data[self.action_key], self.pad_action_dim) 
        else:
            actions = data[self.action_key]
            mask = np.ones_like(actions, dtype=bool)

        result = {
            "observations": [ 
                pt_to_pil(data[key], normalized=False)
                for key in self.image_keys
            ], # list of PIL Image
            "states": np.array(states, dtype=np.float32), # (To, Da)
            "actions": np.array(actions, dtype=np.float32),  # (Tp, Da)
            "instruction": data[self.instruction_key].lower(),
            "actions_mask": mask, #(Tp, Da)
        } 
        return result

class SimpleRepackTransform(LerobotRepackTransform):
    dataset_name: str = "simple"

    num_past_frames: int = 0 # single current frame
    action_chunk_size: int = 30

    pad_action_dim: int | None = None
    pad_state_dim: int | None = None

    def delta_timestamps(self, fps: int):
        return {
            "observation.images.egocentric": [-t/fps for t in range(self.num_past_frames, -1, -1)],
            "states": [-t/fps for t in range(self.num_past_frames, -1, -1)],
            "action": [t/fps for t in range(self.action_chunk_size)]
        }
 

    def __call__(self, data: dict[str, Any], **kwargs) -> dict[str, Any]:
        image_key = "observation.images.egocentric"
        states = data["states"].numpy() # (To, Ds)
        actions = data["action"].numpy() # (Tp, Da)
        action_is_pad = data["action_is_pad"].numpy() # (Ta,) 
        pad_mask = np.ones_like(actions) * (1. - action_is_pad[...,None].astype(np.float32))

        states, _ = pad_to_len(states, self.pad_state_dim) if self.pad_state_dim is not None else (states, None)
        if self.pad_action_dim is not None:
            actions, _ = pad_to_len(actions, self.pad_action_dim) 
            mask,_ = pad_to_len(pad_mask, self.pad_action_dim)
        else:
            mask = np.ones_like(actions, dtype=np.float32)

        return {
            "observations": [pt_to_pil(data[image_key],normalized=False)], # single view
            "states": states.astype(np.float32), # (To, Do)
            "actions": actions.astype(np.float32), # (Tp, Da)
            # "action_is_pad": np.array(data["action_is_pad"], dtype=bool),
            "instruction": data["task"].lower(),
            "actions_mask": mask
        }

class IdentityTransform(BaseModel):
    # boilerplate transform config
    # define primitive data types only! eg., int, float, str
    # container types are allowed eg., list[int], dict[str, float]
    # default no-op transform
    # passing external dependency through **kwargs, eg., tokenizer, processor
    def __call__(self, data: dict[str, Any], **kwargs) -> dict[str, Any]:
        return data

class ActionStateTransform(FieldTransform):
    
    stat_path: str
    action_norm_type: str = "bounds"  # "bounds_q99"
    stat_action_key: str = "action"
    stat_state_key: str = "states"
    use_norm_mask: bool = False
    action_norm_masks: List[bool] = [
        True,
        True,
        True,
        True,
        True,
        True,
        False,
    ]  # delta-eef + gripper
    action_min: Optional[List[float]] = None
    action_max: Optional[List[float]] = None
    state_min: Optional[List[float]] = None
    state_max: Optional[List[float]] = None
    normalize_state: bool = False  # whether to normalize states

    pad_action_dim: int | None = None
    pad_state_dim: int | None = None

    def model_post_init(self, __context: Any) -> None:
        if not os.path.exists(resolve_path(self.stat_path)):
            return
        with open(resolve_path(self.stat_path), "r") as f:
            stats = json.load(f)
            self.populate_stats(stats)
        
    def populate_stats(self, stats: dict[str, Any]):
        if self.action_norm_type == "bounds_q99":
            self.action_min = stats[self.stat_action_key]["q01"]
            self.action_max = stats[self.stat_action_key]["q99"]
            if self.normalize_state:
                self.state_min = stats[self.stat_state_key]["q01"]
                self.state_max = stats[self.stat_state_key]["q99"]
        elif self.action_norm_type == "bounds":
            self.action_min = stats[self.stat_action_key]["min"]
            self.action_max = stats[self.stat_action_key]["max"]
            if self.normalize_state:
                self.state_min = stats[self.stat_state_key]["min"]
                self.state_max = stats[self.stat_state_key]["max"]
        else:
            raise ValueError(f"Unsupported action normalization type: {self.action_norm_type}")

        if self.pad_action_dim is not None:
            self.action_min= pad_to_len(np.array(self.action_min, dtype=np.float32), self.pad_action_dim, dim=0)[0].tolist()
            self.action_max = pad_to_len(np.array(self.action_max, dtype=np.float32), self.pad_action_dim, dim=0)[0].tolist()

        if self.pad_state_dim is not None and self.normalize_state:
            self.state_min = pad_to_len(np.array(self.state_min, dtype=np.float32), self.pad_state_dim, dim=0)[0].tolist()
            self.state_max = pad_to_len(np.array(self.state_max, dtype=np.float32), self.pad_state_dim, dim=0)[0].tolist()

    def __call__(self, data: dict[str, Any], **kwargs) -> dict[str, Any]:
        assert self.action_min is not None and self.action_max is not None, \
            f"{self.stat_path} is not loaded properly. Probably {resolve_path(self.stat_path)} does not exist."
        action_min = np.array(self.action_min, dtype=np.float32)
        action_max = np.array(self.action_max, dtype=np.float32)
        if self.normalize_state:
            data["states"] = self.normalize_state_func(data["states"])

        # tolerate near-zero, not just exact zero
        ill_mask = np.abs(action_max - action_min) < 1e-4 * (np.abs(action_max) + np.abs(action_min) + 1e-8) 
        action_max[ill_mask] = 1.0  # prevent division by zero
        actions_normalized = np.where(
            ill_mask, data["actions"], (data["actions"] - action_min) / (action_max - action_min) * 2 - 1
        )

        if self.use_norm_mask:
            actions = np.where(self.action_norm_masks, actions_normalized, data["actions"])
        else: 
            actions = actions_normalized

        if "smoothness_context_actions" in data:
            context_actions = np.asarray(
                data["smoothness_context_actions"],
                dtype=np.float32,
            )
            context_normalized = np.where(
                ill_mask,
                context_actions,
                (context_actions - action_min) / (action_max - action_min) * 2 - 1,
            )
            if self.use_norm_mask:
                normalized_context = np.where(
                    self.action_norm_masks,
                    context_normalized,
                    context_actions,
                )
            else:
                normalized_context = context_normalized
            data["raw_smoothness_context_actions"] = context_actions
            data["smoothness_context_actions"] = np.clip(
                normalized_context,
                -1,
                1,
            ).astype(np.float32)

        # if (np.abs(actions) > 10.0).any():
        #     print("Error: values outside quantile range during normalization.")

        actions = np.clip(actions, -1, 1).astype(np.float32)
        # print(data["dataset"], actions.max(), actions.min(), actions.mean(), actions.std())
        data["raw_actions"] = data["actions"]
        data["actions"] = actions

        return data

    def normalize(self, action, **kwargs):
        data = {"actions": action}
        return self.__call__(data)["actions"]

    def normalize_state_func(self, states, **kwargs):
        state_min = np.array(self.state_min, dtype=np.float32)
        state_max = np.array(self.state_max, dtype=np.float32)
        # Normalize states, tolerate near-zero, not just exact zero
        ill_mask = np.abs(state_max - state_min) < 1e-4 * (np.abs(state_max) + np.abs(state_min) + 1e-8)
        state_max[ill_mask] = 1.0  # prevent division by zero
        current_state = np.where(
            ill_mask, 0, 
            (states - state_min) / (state_max - state_min) * 2 - 1
        )
        current_state = np.clip(current_state, -1, 1).astype(np.float32)
        if np.isnan(current_state).any():
            current_state = np.nan_to_num(current_state, nan=0.0)
        return current_state

    def reverse_call(self, array: Any, **kwargs) -> Any:
        assert self.action_min is not None and self.action_max is not None
        action_min = np.array(self.action_min)
        action_max = np.array(self.action_max)
        reversed_array = (array + 1) / 2 * (action_max - action_min) + action_min
        return reversed_array

    def denormalize_L1_action_err(self, L1_err):
        """return denormalized L1 err loss"""
        
        array_class = torch.tensor if torch.is_tensor(L1_err) else np.array
        where = torch.where if torch.is_tensor(L1_err) else np.where
        data_type = L1_err.dtype

        if self.action_norm_type == "bounds" or \
            self.action_norm_type == "bounds_q99":
            low = array_class(self.action_min, dtype=data_type)  # type: ignore
            high = array_class(self.action_max, dtype=data_type)  # type: ignore
            
            if self.use_norm_mask:
                if torch.is_tensor(L1_err):
                    low = low.to(L1_err.device)
                    high = high.to(L1_err.device)
                    action_norm_masks = torch.tensor(
                        self.action_norm_masks, device=L1_err.device
                    )
                else:
                    action_norm_masks = self.action_norm_masks
                result = where(action_norm_masks, 0.5 * L1_err * (high - low), L1_err) # type:ignore
            else:
                result = 0.5 * L1_err * (high - low)
            return result
        else:
            raise NotImplementedError
    
    
    def denormalize(self, normalized: np.ndarray|torch.Tensor) -> np.ndarray|torch.Tensor: 
        """ Denormalize the action. """
        array_class = torch.tensor if torch.is_tensor(normalized) else np.array
        where = torch.where if torch.is_tensor(normalized) else np.where
        data_type = normalized.dtype

        if self.action_norm_type == "bounds" or \
                self.action_norm_type == "bounds_q99":
            if self.action_norm_type == "bounds":
                low = array_class(self.action_min, dtype=data_type)  # type: ignore
                high = array_class(self.action_max, dtype=data_type)  # type: ignore
            elif self.action_norm_type == "bounds_q99":
                low = array_class(self.action_min, dtype=data_type)  # type: ignore
                high = array_class(self.action_max, dtype=data_type)  # type: ignore

            if not self.use_norm_mask:
                assert self.action_min is not None
                action_norm_masks = [True] * len(self.action_min)
            else:
                action_norm_masks = self.action_norm_masks

            if torch.is_tensor(normalized):
                low = low.to(normalized.device)  # type: ignore
                high = high.to(normalized.device)  # type: ignore
                action_norm_masks = torch.tensor(action_norm_masks, device=normalized.device)
            else:
                action_norm_masks = np.array(action_norm_masks)

            action = where(action_norm_masks, 0.5 * (normalized + 1) * (high - low) + low, normalized)  # type: ignore
        return action # type: ignore


class Qwen3vlModelTransform(ModelTransform):
    resize: ResizeImage = Field(default_factory=lambda: ResizeImage(size=(270, 480)))
    color_jitter: ColorJitter
    img_aug: bool = False
    # anchor_size: tuple[int, int] = (256, 256) # H, W

    # for mixed dataset with different image sizes
    adaptive_resize: bool = False
    img_sizes: dict[str, Any] = Field(default_factory=lambda: {
        "egodex": [270, 480],
        "he"    : [240, 320],
    })

    def __call__(
        self, 
        data: dict[str, Any], 
        no_aug: bool = False,
        vlm_processor = None, 
        action_tokenizer = None, 
        **kwargs
    ) -> dict[str, Any]:
        if vlm_processor is None or action_tokenizer is None:
            return {"raw_actions": data["actions"], **data}
        """
        data: dict with keys:
            - instruction: str
            - observations: List[Image] (To x PIL)
            - states: (To, Da) torch.Tensor
            - action: (Tp, Da) torch.Tensor
        """
        do_img_aug = False if no_aug else self.img_aug
        if self.adaptive_resize:
            assert data["dataset"] is not None
            match data["dataset"]:
                case "egodex":
                    target_size = self.img_sizes["egodex"]
                case "humanoid-everyday":
                    target_size = self.img_sizes["he"]
                case _:
                    target_size = (256, 256)
            resizer = ResizeImage(size=tuple(target_size))() # type: ignore
        else:
            resizer = self.resize()
        t1 = v2.Compose([
            resizer,
            self.color_jitter() if do_img_aug else v2.Identity(),
        ])
        
        images = [t1(img) for img in data["observations"]]
        instruction = data["instruction"]
        state = data["states"]
        action = data["actions"]
        inputs, num_answer_tokens_list = self.build_qwenvl_inputs(
            vlm_processor, action_tokenizer, [images], [instruction], [state], [action]
        )
        labels = copy.deepcopy(inputs["input_ids"])
        # keep loss on the answer + EOS + formatting tokens
        labels[:, : -(num_answer_tokens_list[0] + 2)] = IGNORE_INDEX 
        inputs["labels"] = labels
        inputs["dataset_name"] = data.get("dataset", "unknown")
        inputs["raw_actions"] = action
        # inputs["raw_instruction"] = instruction
        inputs["raw_images"] = np.stack([np.array(img) for img in images])
        return inputs

    def build_qwenvl_inputs(
        self,
        vlm_processor,
        action_tokenizer,
        images,
        instructions,
        states,
        actions,
        **kwargs,
    ):
        """adapted from Qwen_VL_Interface.build_qwenvl_inputs"""
        # Create messages: one message per sample
        messages = []
        num_answer_tokens_list = []
        assert len(images) == len(
            instructions
        ), "Images and instructions must have the same length"

        for imgs, instruction, action in zip(images, instructions, actions):
            tokenized_action = action_tokenizer(action)
            raw_action_tokens = vlm_processor.tokenizer(tokenized_action)["input_ids"]
            num_answer_tokens = len(raw_action_tokens)
            num_answer_tokens_list.append(num_answer_tokens)

            # print(action[0].shape)
            content = [{"type": "image", "image": img} for img in imgs]
            content.append({"type": "text", "text": instruction})
            user_msg = {"role": "user", "content": content}
            assistant_msg = {
                "role": "assistant",
                "content": [
                    {"type": "text", "text": tokenized_action}
                ],  # squeeze batch dim
            }
            messages.append([user_msg, assistant_msg])

        # Prepare text prompts using processor
        # default process is json --> message --> texts --> input_ids
        texts = [
            vlm_processor.apply_chat_template(
                m, tokenize=False, add_generation_prompt=False
            )
            for m in messages
        ]

        try:
            from qwen_vl_utils import process_vision_info
        except:
            raise ImportError("qwen_vl_utils not found, make sure to install it if using Qwen-VL model!")
        image_inputs, video_inputs = process_vision_info(messages, image_patch_size=16)  # type: ignore
        inputs = vlm_processor(
            text=texts,
            images=image_inputs,
            videos=video_inputs,
            padding=True,
            return_tensors="pt",
        )
        return inputs, num_answer_tokens_list

class HEPosttrainRepackTransform(RepackTransform):
    dataset_name: str = "humanoid-everyday"
    num_past_frames: int = 0
    action_chunk_size: int = 16
    use_delta_actions: bool = True
    pad_action_dim: int | None = None
    pad_state_dim: int | None = None

    def __call__(
        self,
        data: dict[str, Any],
        **kwargs,
    ) -> dict[str, Any]:
        # HACK: different action format determines robot type
        if data["action.joint_angles"].shape[1] == 26:
            # H1 robot
            raw = data["action.joint_angles"]
            actions = np.concatenate([
                raw[:, 6:12][::-1], # from left thumb to little
                np.zeros((raw.shape[0], 1), dtype=np.float32), # pad finger to 7 dof
                raw[:, 0:6][::-1], # from right thumb to little
                np.zeros((raw.shape[0], 1), dtype=np.float32), # pad finger to 7 dof
                raw[:, 12:], # left arm + right arm (each from should to wrist)
            ], axis=1).astype(np.float32)
            hand = data["observation.hand_joints"]
            states = np.concatenate([
                hand[:, 6:12],
                np.zeros((hand.shape[0], 1), dtype=np.float32), # pad finger to 7 dof
                hand[:, 0:6],
                np.zeros((hand.shape[0], 1), dtype=np.float32), # pad finger to 7 dof 
                data["observation.arm_joints"]
            ], axis=1).astype(np.float32)
        else:
           actions = data["action.joint_angles"].astype(np.float32)
           states = np.concatenate((data["observation.hand_joints"], data["observation.arm_joints"]), axis=1).astype(np.float32)


        if self.use_delta_actions:
            actions = actions[1:] - actions[:-1]
            action_mask = data["action_mask"][1:]
        else:
            action_mask = data["action_mask"]

        # Expand action_mask to (T, Da) by repeating along last dimension
        if action_mask.ndim == 1:
            action_mask = np.repeat(action_mask[:, None], actions.shape[1], axis=1)

        states, _ = pad_to_len(states, self.pad_state_dim) if self.pad_state_dim is not None else (states, None)
        if self.pad_action_dim is not None:
            actions, _ = pad_to_len(actions, self.pad_action_dim)
            mask, _  = pad_to_len(action_mask, self.pad_action_dim)
        else:
            mask = np.ones_like(actions, dtype=bool)
            # mask = action_mask
        return {
            "observations": [pt_to_pil(img, normalized=False) for img in data["observation.images.egocentric"]],
            "states": states,
            "actions": actions,
            "instruction": str(data["task"]).lower(),
            "dataset": data.get("dataset_name", self.dataset_name),
            "actions_mask": mask,# torch.from_numpy(mask),
            "obs_mask": data["obs_mask"], #torch.from_numpy(data["obs_mask"]),
        }

class MixedRepackTransform(RepackTransform):
    dataset_name: str = "mixed"

    num_past_frames: int = 0
    action_chunk_size: int = 1
    use_delta_actions: bool = True
    robot_type: str = "mixed"
    stage: str = "pretrain"  # "pretrain" or "postpre"
    pad_action_dim: int | None = None
    pad_state_dim: int | None = None

    def model_post_init(self, __context: Any) -> None:
        if self.stage == "pretrain":
            self._he_repacker = HEPretrainRepackTransform.model_validate(self.model_dump())
        else:
            self._he_repacker = HEPosttrainRepackTransform.model_validate(self.model_dump())
        self._egodex_repacker = EgodexRepackTransform.model_validate(self.model_dump())

    def __call__(self, data: dict[str, Any], **kwargs) -> dict[str, Any]:
        dataset_name = data.get("dataset_name", "default")
        match(dataset_name):
            case "egodex":
                return self._egodex_repacker(data, **kwargs)
            case "humanoid-everyday":
                return self._he_repacker(data, **kwargs)
        return data
    
# <modify>
class SeedPosttrainRepackTransform(ModelTransform):
    dataset_name: str = "seed-g1"
    action_chunk_size: int = 16
    # Maximum deployment RTC overlap. Dense training still supplies a complete
    # future action horizon; the trainer samples a clean prefix from 0..N.
    rtc_prefix_frames: int = 0
    use_delta_actions: bool = False
    # TextOp 39D: joint_abs(29)+root_delta_xy(2)+root_rot5(5)+root_height(1)+foot_contact(2).
    textop_actions: bool = False
    root40_actions: bool = False
    # <modify_jerk> 简单hybrid baseline:关节action保持绝对值,root xyz/quat使用相邻帧delta。
    root_delta_actions: bool = False
    # <modify_states> 用于驱动SEED数据集返回过去几帧state;repack本身保持透传。
    num_past_frames: int = 0
    pad_action_dim: int | None = None
    pad_state_dim: int | None = None

    def __call__(
        self,
        data: dict[str, Any],
        **kwargs,
    ) -> dict[str, Any]:
        actions = np.asarray(data["actions"], dtype=np.float32)
        action_mask = np.asarray(
            data.get("action_mask", np.ones(actions.shape[0], dtype=np.float32)),
            dtype=np.float32,
        )
        # TextOp actions are the complete future horizon. Their first root
        # delta is measured from the current observation state immediately
        # before that horizon.
        states = data.get("states", np.zeros((1, actions.shape[1]), dtype=np.float32))
        states = np.asarray(states, dtype=np.float32)
        if states.ndim == 1:
            states = states[None, :]
        action_reference_states = data.get("action_reference_states", states)
        action_reference_states = np.asarray(
            action_reference_states,
            dtype=np.float32,
        )
        if action_reference_states.ndim == 1:
            action_reference_states = action_reference_states[None, :]
        smoothness_context_actions = data.get("smoothness_context_actions")
        smoothness_context_reference_states = data.get(
            "smoothness_context_reference_states"
        )
        if (smoothness_context_actions is None) != (
            smoothness_context_reference_states is None
        ):
            raise ValueError(
                "Temporal smoothness context actions/reference must be provided together"
            )
        if smoothness_context_actions is not None:
            smoothness_context_actions = np.asarray(
                smoothness_context_actions,
                dtype=np.float32,
            )
            smoothness_context_reference_states = np.asarray(
                smoothness_context_reference_states,
                dtype=np.float32,
            )
            if smoothness_context_actions.ndim == 1:
                smoothness_context_actions = smoothness_context_actions[None, :]
            if smoothness_context_reference_states.ndim == 1:
                smoothness_context_reference_states = (
                    smoothness_context_reference_states[None, :]
                )

        # <modify_textop_repr> 三种动作模式只能开一个,避免训练目标和推理decode语义混在一起。
        if self.root40_actions and not self.textop_actions:
            raise ValueError("root40_actions requires the SEED textop action pipeline")
        enabled_action_modes = int(self.textop_actions) + int(self.use_delta_actions) + int(self.root_delta_actions)
        if enabled_action_modes > 1:
            raise ValueError("Only one of textop_actions/use_delta_actions/root_delta_actions can be enabled")

        # TextOp模式下action/state都转到同一套39D motion token,保证训推输入语义一致。
        if self.textop_actions:
            if (
                actions.shape[1] < 36
                or states.shape[1] < 36
                or action_reference_states.shape[1] < 36
            ):
                raise ValueError(
                    "textop_actions requires 36D SEED action/state/reference"
                )
            if self.root40_actions:
                from psi.data.seed.motion_repr40 import build_root40_action, build_root40_state, choose_heading_anchor
                # One observed anchor for the target, state and both context
                # frames. Never choose a separate anchor from future targets.
                anchor = choose_heading_anchor(states[:, :36])
                actions = build_root40_action(actions[:, :36], action_reference_states[:, :36], anchor)
                states = build_root40_state(states[:, :36], anchor)
            else:
                actions = build_seed_textop_action(actions[:, :36], action_reference_states[:, :36])
                states = build_seed_textop_state(states[:, :36])
            if smoothness_context_actions is not None:
                if (
                    smoothness_context_actions.shape != (2, 36)
                    or smoothness_context_reference_states.shape != (1, 36)
                ):
                    raise ValueError(
                        "TextOp temporal context requires two 36D actions and "
                        "one 36D reference state, got "
                        f"actions={smoothness_context_actions.shape} "
                        f"reference={smoothness_context_reference_states.shape}"
                    )
                if self.root40_actions:
                    smoothness_context_actions = build_root40_action(
                        smoothness_context_actions, smoothness_context_reference_states, anchor)
                else:
                    smoothness_context_actions = build_seed_textop_action(
                        smoothness_context_actions, smoothness_context_reference_states)
            # TextOp changes the feature layout from 36D to 39D, but padding is
            # a frame property.  Preserve that frame-validity information and
            # expand it over the new representation.  The previous fallback
            # replaced any 36D mask with all ones, accidentally supervising
            # padded/repeated tail frames.
            if action_mask.ndim == 1:
                frame_mask = action_mask
            elif action_mask.ndim == 2:
                if action_mask.shape[0] != actions.shape[0]:
                    raise ValueError(
                        "TextOp action mask length does not match actions: "
                        f"mask={action_mask.shape}, actions={actions.shape}"
                    )
                frame_mask = (action_mask > 0).any(axis=1).astype(np.float32)
            else:
                raise ValueError(
                    f"TextOp action mask must be 1D or 2D, got {action_mask.shape}"
                )
            action_mask = np.repeat(
                frame_mask[:, None], actions.shape[1], axis=1
            )
        elif self.use_delta_actions:
            if actions.shape[0] < 2:
                raise ValueError("SeedPosttrainRepackTransform requires at least 2 action steps for delta mode")
            actions = actions[1:] - actions[:-1]
            action_mask = action_mask[1:]
            if "future_progress" in data:
                data = dict(data)
                data["future_progress"] = np.asarray(data["future_progress"], dtype=np.float32)[1:]
        elif self.root_delta_actions:
            if actions.shape[1] < 36 or states.shape[1] < 36:
                raise ValueError("root_delta_actions requires 36D SEED action/state")
            # 原逻辑:root xyz/quat 7维都做分量相减,保留为旧checkpoint兼容分支。
            prev_root = np.concatenate([states[-1:, 29:36], actions[:-1, 29:36]], axis=0)
            actions = actions.copy()
            actions[:, 29:36] = actions[:, 29:36] - prev_root

        if action_mask.ndim == 1:
            action_mask = np.repeat(action_mask[:, None], actions.shape[1], axis=1)

        states, _ = (
            pad_to_len(states, self.pad_state_dim)
            if self.pad_state_dim is not None
            else (states, None)
        )
        if self.pad_action_dim is not None:
            actions, _ = pad_to_len(actions, self.pad_action_dim)
            action_mask, _ = pad_to_len(action_mask, self.pad_action_dim)
            if smoothness_context_actions is not None:
                smoothness_context_actions, _ = pad_to_len(
                    smoothness_context_actions,
                    self.pad_action_dim,
                )

        instruction = str(data.get("instruction", "")).strip()
        output = {
            "states": states.astype(np.float32),
            "actions": actions.astype(np.float32),
            "instruction": instruction,
            "dataset": data.get("dataset_name", self.dataset_name),
            "actions_mask": action_mask.astype(np.float32),
        }
        if "progress" in data:
            output["progress"] = np.asarray(data["progress"], dtype=np.float32)
        if "future_progress" in data:
            output["future_progress"] = np.asarray(data["future_progress"], dtype=np.float32)
        if smoothness_context_actions is not None:
            output["smoothness_context_actions"] = np.asarray(
                smoothness_context_actions,
                dtype=np.float32,
            )
        # <modify_audio> 音频训练数据需要把已切好的audio片段和对齐信息一路透传到model transform。
        # <modify_video> video->motion训练同样透传整段抽帧视频,保证train/infer输入一致。
        for key in (
            "row_id",
            "step_index",
            "move_name",
            "motion_name",
            "motion_dir",
            "frame_id",
            "audio",
            "audio_waveform",
            "audio_sampling_rate",
            "audio_path",
            "audio_start_sec",
            "audio_duration_sec",
            "full_audio",
            "video",
            "video_path",
            "video_sample_fps",
            "video_size_pixels",
            "source_video_fps",
            "video_duration_sec",
            "full_video",
            "video_embed_path",
            "pixel_values_videos",
            "video_grid_thw",
            "video_second_per_grid",
            "vlm_hidden_states",
            "omni_hidden_path",
            "total_frames",
        ):
            if key in data:
                output[key] = data[key]
        return output


class Psi0ModelTransform(ModelTransform):
    resize: ResizeImage = Field(default_factory=lambda: ResizeImage(size=(224)))
    center_crop: CenterCrop = Field(default_factory=lambda: CenterCrop(size=224))
    color_jitter: ColorJitter = Field(default_factory=lambda: ColorJitter())
    gaussian_noise: GaussianNoise = Field(default_factory=lambda: GaussianNoise(mean=0, std=3, prob_skip=0.1))
    img_aug: bool = False
    text_only: bool = False  # <modify>
    # <modify_audio> 音频输入分支:可在同一个Qwen-Omni user message中同时放audio和text。
    audio_only: bool = False
    # <modify_video> 纯视频输入分支:只使用video token,可选携带简短文本提示。
    video_only: bool = False
    video_size_pixels: int = 50176
    
    # for mixed dataset with different image sizes
    adaptive_resize: bool = False
    img_sizes: dict[str, Any] = Field(default_factory=lambda: {
        "egodex": [270, 480],
        "he"    : [240, 320],
    })

    def __call__(
        self, data: dict[str, Any], vlm_processor=None, no_aug=False, **kwargs
    ) -> dict[str, Any]:
        if self.audio_only and "audio_waveform" in data:
            if vlm_processor is None:
                raise ValueError(
                    "HFDv2 online audio requires the Qwen2.5-Omni processor"
                )
            from psi.data.seed.qwen_streaming_audio import (
                prepare_qwen_streaming_audio_window,
            )

            inputs = prepare_qwen_streaming_audio_window(
                vlm_processor,
                data["audio_waveform"],
                first_window=int(data.get("step_index", 0)) == 0,
                sampling_rate=int(data.get("audio_sampling_rate", 16_000)),
            )
            inputs["dataset_name"] = data.get(
                "dataset",
                data.get("dataset_name", "unknown"),
            )
            inputs["raw_actions"] = data["raw_actions"]
            if "actions_mask" in data:
                inputs["actions_mask"] = data["actions_mask"]
            inputs["actions"] = data["actions"]
            inputs["states"] = data["states"]
            inputs["instruction"] = str(data.get("instruction", ""))
            if "progress" in data:
                inputs["progress"] = data["progress"]
            if "future_progress" in data:
                inputs["future_progress"] = data["future_progress"]
            if "smoothness_context_actions" in data:
                inputs["smoothness_context_actions"] = data[
                    "smoothness_context_actions"
                ]
            return inputs

        if "vlm_hidden_states" in data:
            instruction = str(data.get("instruction", ""))
            hidden_states = torch.as_tensor(data["vlm_hidden_states"])
            inputs = {
                "input_ids": torch.ones((hidden_states.shape[0],), dtype=torch.long),
                "attention_mask": torch.ones((hidden_states.shape[0],), dtype=torch.long),
                "vlm_hidden_states": hidden_states,
            }
            inputs["dataset_name"] = data.get("dataset", data.get("dataset_name", "unknown"))
            inputs["raw_actions"] = data["raw_actions"]
            if "actions_mask" in data:
                inputs["actions_mask"] = data["actions_mask"]
            inputs["actions"] = data["actions"]
            inputs["states"] = data["states"]
            inputs["instruction"] = instruction
            if "progress" in data:
                inputs["progress"] = data["progress"]
            if "future_progress" in data:
                inputs["future_progress"] = data["future_progress"]
            if "smoothness_context_actions" in data:
                inputs["smoothness_context_actions"] = data[
                    "smoothness_context_actions"
                ]
            for key in (
                "row_id",
                "move_name",
                "motion_name",
                "motion_dir",
                "frame_id",
                "total_frames",
                "audio_path",
                "audio_start_sec",
                "audio_duration_sec",
                "full_audio",
                "video_path",
                "video_sample_fps",
                "video_size_pixels",
                "source_video_fps",
                "video_duration_sec",
                "full_video",
                "video_embed_path",
                "video_clip_start_sec",
                "video_clip_duration_sec",
                "omni_hidden_path",
            ):
                if key in data:
                    inputs[key] = data[key]
            return inputs

        if self.video_only and ("video" in data or "pixel_values_videos" in data):
            instruction = str(data.get("instruction", "")).strip()
            inputs = self.build_qwenvl_inputs(
                vlm_processor,
                imgs=None,
                instruction=instruction,
                video=data.get("video", None),
                video_path=data.get("video_path", "video.mp4"),
                video_size_pixels=data.get("video_size_pixels", self.video_size_pixels),
                video_sample_fps=data.get("video_sample_fps", 1.0),
                pixel_values_videos=data.get("pixel_values_videos", None),
                video_grid_thw=data.get("video_grid_thw", None),
                video_second_per_grid=data.get("video_second_per_grid", None),
            )
            inputs["dataset_name"] = data.get("dataset", "unknown")
            inputs["raw_actions"] = data["raw_actions"]
            if "actions_mask" in data:
                inputs["actions_mask"] = data["actions_mask"]
            inputs["actions"] = data["actions"]
            inputs["states"] = data["states"]
            inputs["instruction"] = instruction
            if "progress" in data:
                inputs["progress"] = data["progress"]
            if "future_progress" in data:
                inputs["future_progress"] = data["future_progress"]
            for key in (
                "row_id",
                "move_name",
                "motion_name",
                "motion_dir",
                "frame_id",
                "total_frames",
                "video_path",
                "video_sample_fps",
                "video_size_pixels",
                "source_video_fps",
                "video_duration_sec",
                "full_video",
                "video_embed_path",
            ):
                if key in data:
                    inputs[key] = data[key]
            return inputs

        # <modify_audio> 音频分支,使用Qwen2.5-Omni processor把音频片段转成input_features。
        if self.audio_only and "vlm_hidden_states" in data:
            instruction = str(data.get("instruction", ""))
            hidden_states = torch.as_tensor(data["vlm_hidden_states"])
            inputs = {
                "input_ids": torch.ones((hidden_states.shape[0],), dtype=torch.long),
                "attention_mask": torch.ones((hidden_states.shape[0],), dtype=torch.long),
                "vlm_hidden_states": hidden_states,
            }
            inputs["dataset_name"] = data.get("dataset", "unknown")
            inputs["raw_actions"] = data["raw_actions"]
            if "actions_mask" in data:
                inputs["actions_mask"] = data["actions_mask"]
            inputs["actions"] = data["actions"]
            inputs["states"] = data["states"]
            inputs["instruction"] = instruction
            if "progress" in data:
                inputs["progress"] = data["progress"]
            if "future_progress" in data:
                inputs["future_progress"] = data["future_progress"]
            for key in (
                "row_id",
                "move_name",
                "motion_name",
                "motion_dir",
                "frame_id",
                "total_frames",
                "audio_path",
                "audio_start_sec",
                "audio_duration_sec",
                "full_audio",
                "omni_hidden_path",
            ):
                if key in data:
                    inputs[key] = data[key]
            return inputs

        if self.audio_only and "audio" in data:
            instruction = str(data.get("instruction", ""))
            inputs = self.build_qwenvl_inputs(
                vlm_processor,
                imgs=None,
                instruction=instruction,
                audio=data["audio"],
                audio_path=data.get("audio_path", "audio.wav"),
            )
            inputs["dataset_name"] = data.get("dataset", "unknown")
            inputs["raw_actions"] = data["raw_actions"]
            if "actions_mask" in data:
                inputs["actions_mask"] = data["actions_mask"]
            inputs["actions"] = data["actions"]
            inputs["states"] = data["states"]
            inputs["instruction"] = instruction
            if "progress" in data:
                inputs["progress"] = data["progress"]
            if "future_progress" in data:
                inputs["future_progress"] = data["future_progress"]
            for key in (
                "row_id",
                "move_name",
                "motion_name",
                "motion_dir",
                "frame_id",
                "total_frames",
                "audio_path",
                "audio_start_sec",
                "audio_duration_sec",
                "full_audio",
            ):
                if key in data:
                    inputs[key] = data[key]
            return inputs

        # <modify> 纯文本分支,去掉image处理和读取
        if self.text_only:
            instruction = data["instruction"]
            inputs = self.build_qwenvl_inputs(vlm_processor, imgs=None, instruction=instruction)
            inputs["dataset_name"] = data.get("dataset", "unknown")
            inputs["raw_actions"] = data["raw_actions"]
            if "actions_mask" in data:
                inputs["actions_mask"] = data["actions_mask"]
            inputs["actions"] = data["actions"]
            inputs["states"] = data["states"]
            inputs["instruction"] = instruction
            if "progress" in data:
                inputs["progress"] = data["progress"]
            if "future_progress" in data:
                inputs["future_progress"] = data["future_progress"]
            # <modify_temp> 临时透传样本来源信息,方便定位大梯度batch。
            for key in ("row_id", "move_name", "motion_dir", "frame_id", "total_frames"):
                if key in data:
                    inputs[key] = data[key]
            return inputs

        # 原VL分支
        do_img_aug = False if no_aug else self.img_aug
        if self.adaptive_resize:
            assert data["dataset"] is not None
            match data["dataset"]:
                case "egodex":
                    target_size = self.img_sizes["egodex"]
                case "humanoid-everyday":
                    target_size = self.img_sizes["he"]
                case _:
                    target_size = (256, 256)
            resizer = ResizeImage(size=tuple(target_size))() # type: ignore
            center_crop = CenterCrop(size=tuple(target_size))() # type: ignore
        else:
            resizer = self.resize()
            center_crop = self.center_crop()
            
        t1 = v2.Compose([
            resizer,
            center_crop,
            self.color_jitter() if do_img_aug else v2.Identity(),
        ])

        images = [t1(img) for img in data["observations"]]
        instruction = data["instruction"]

        inputs: dict = self.build_qwenvl_inputs(
            vlm_processor, images, instruction,
        ) # type: ignore
        inputs["dataset_name"] = data.get("dataset", "unknown")
        inputs["raw_actions"] = data["raw_actions"]
        if "actions_mask" in data:
            inputs["actions_mask"] = data["actions_mask"]

        inputs["raw_images"] = images
        inputs['actions'] = data["actions"]
        inputs['states'] = data["states"]
        inputs['instruction'] = data["instruction"]
        if "progress" in data:
            inputs["progress"] = data["progress"]
        if "future_progress" in data:
            inputs["future_progress"] = data["future_progress"]
        # <modify_temp> 临时透传样本来源信息,方便定位大梯度batch。
        for key in ("row_id", "move_name", "motion_dir", "frame_id", "total_frames"):
            if key in data:
                inputs[key] = data[key]
        return inputs

    def build_qwenvl_inputs(
        self,
        vlm_processor,
        imgs,
        instruction,
        audio=None,
        audio_path=None,
        video=None,
        video_path=None,
        video_size_pixels=None,
        video_sample_fps=1.0,
        pixel_values_videos=None,
        video_grid_thw=None,
        video_second_per_grid=None,
        # state,
        # action,
        **kwargs,
    ) -> tuple[dict, int]:
        # <modify>
        omni_default_system = (
            "You are Qwen, a virtual human developed by the Qwen Team, Alibaba Group, "
            "capable of perceiving auditory and visual inputs, as well as generating text and speech."
        )

        # <modify_audio> 音频训练:真实waveform通过processor的audio参数传入;
        # user content按Qwen-Omni混合媒体格式排列为audio后接可选text。
        if audio is not None:
            content = [{"type": "audio", "audio": str(audio_path or "audio.wav")}]
            if str(instruction).strip():
                content.append({"type": "text", "text": str(instruction).strip()})
            messages = [[
                {"role": "system", "content": [{"type": "text", "text": omni_default_system}]},
                {"role": "user", "content": content},
            ]]
            texts = [
                vlm_processor.apply_chat_template(m, tokenize=False, add_generation_prompt=True)
                for m in messages
            ]
            inputs = vlm_processor(
                text=texts,
                audio=[np.asarray(audio, dtype=np.float32)],
                padding=True,
                return_tensors="pt",
            )
            return inputs

        if video is not None or pixel_values_videos is not None:
            size_pixels = int(video_size_pixels or self.video_size_pixels)
            content = [{"type": "video", "video": str(video_path or "video.mp4")}]
            if str(instruction).strip():
                content.append({"type": "text", "text": str(instruction).strip()})
            messages = [[
                {"role": "system", "content": [{"type": "text", "text": omni_default_system}]},
                {"role": "user", "content": content},
            ]]
            texts = [
                vlm_processor.apply_chat_template(m, tokenize=False, add_generation_prompt=True)
                for m in messages
            ]
            if pixel_values_videos is not None and video_grid_thw is not None:
                video_grid_arr = np.asarray(video_grid_thw)
                video_grid_for_text = video_grid_arr[0] if video_grid_arr.ndim == 2 else video_grid_arr
                if video_second_per_grid is None:
                    second_per_grid = float(vlm_processor.video_processor.temporal_patch_size) / float(video_sample_fps)
                    video_second_per_grid = np.asarray([second_per_grid], dtype=np.float32)
                texts = vlm_processor.replace_multimodal_special_tokens(
                    texts,
                    iter([]),
                    iter([]),
                    iter([video_grid_for_text]),
                    iter([float(np.asarray(video_second_per_grid).reshape(-1)[0])]),
                    False,
                    25,
                    2.0,
                )
                inputs = vlm_processor.tokenizer(
                    texts,
                    padding=True,
                    return_tensors="pt",
                )
                inputs = {k: v for k, v in inputs.items()}
                inputs["pixel_values_videos"] = torch.as_tensor(pixel_values_videos, dtype=torch.float32)
                inputs["video_grid_thw"] = torch.as_tensor(video_grid_thw, dtype=torch.long)
                inputs["video_second_per_grid"] = torch.as_tensor(
                    video_second_per_grid,
                    dtype=torch.float32,
                ).reshape(-1)
                return inputs

            return vlm_processor(
                text=texts,
                videos=[np.asarray(video, dtype=np.uint8)],
                padding=True,
                return_tensors="pt",
                use_audio_in_video=False,
                videos_kwargs={
                    "size": {
                        "shortest_edge": size_pixels,
                        "longest_edge": size_pixels,
                    },
                    "fps": float(video_sample_fps),
                },
            )

        # <modify>
        if imgs is None:
            messages = [[
                {"role": "system", "content": [{"type": "text", "text": omni_default_system}]},
                {"role": "user", "content": [{"type": "text", "text": instruction}]},
            ]]
            texts = [
                vlm_processor.apply_chat_template(m, tokenize=False, add_generation_prompt=True)  # 把人类语言转换成模型喜欢的特定格式,未tokenize
                for m in messages
            ]
            # 查字典,把字符串变成token,找到对应id
            inputs = vlm_processor(
                text=texts,
                padding=True,
                return_tensors="pt",
            )
            return inputs


        from qwen_vl_utils import process_vision_info

        """adapted from Qwen_VL_Interface.build_qwenvl_inputs"""
        messages = []

        content = [{"type": "image", "image": img} for img in imgs]
        content.append({"type": "text", "text": instruction})
        user_msg = {"role": "user", "content": content}
        # <modify>
        system_msg = {"role": "system", "content": [{"type": "text", "text": omni_default_system}]}
        messages.append([system_msg, user_msg])
        # messages.append([user_msg])

        # Prepare text prompts using processor
        # default process is json --> message --> texts --> input_ids
        texts = [
            vlm_processor.apply_chat_template(
                m, tokenize=False, add_generation_prompt=True
            )
            for m in messages
        ]
        image_inputs, video_inputs = process_vision_info(messages, image_patch_size=16)  # type: ignore
        inputs = vlm_processor(
            text=texts,
            images=image_inputs,
            videos=video_inputs,
            padding=True,
            return_tensors="pt",
        )
        return inputs

class ACTModelTransform(ModelTransform):
    resize: ResizeImage
    center_crop: CenterCrop
    color_jitter: ColorJitter
    normalize: Normalize
    img_aug: bool = False
    
    def __call__(
        self,
        data: dict[str, Any],
        no_aug: bool = False,
        **kwargs,
    ) -> dict[str, Any]:
        do_img_aug = False if no_aug else self.img_aug
        
        # Image transform pipeline
        t = v2.Compose(
            [
                v2.ToImage(),
                v2.ToDtype(torch.float32, scale=True),
                self.resize(),
                self.center_crop(),
                self.color_jitter() if do_img_aug else v2.Identity(),
                self.normalize(),
            ]
        )
        
        processed_images = torch.stack([t(img) for img in data["observations"]]) # (N*To, C, H, W)
        
        if "action_is_pad" in data:
            # LerobotRepackTransform format: (chunk_size,), True=padded
            action_is_pad = data["action_is_pad"]
        elif "actions_mask" in data:
            # WeGR00TRepackTransform format: (chunk_size, Da), True=original, False=padded
            actions_mask = data["actions_mask"]
            if isinstance(actions_mask, np.ndarray):
                actions_mask = actions_mask.astype(bool)
                # (chunk_size, Da) --> (chunk_size,)
                if actions_mask.ndim == 2:
                    action_is_pad = ~actions_mask[:, 0]  # Invert: True->False (original), False->True (padded)
                else:
                    action_is_pad = ~actions_mask
            else:
                actions_mask = actions_mask.bool() if hasattr(actions_mask, 'bool') else actions_mask
                action_is_pad = ~actions_mask[:, 0] if len(actions_mask.shape) == 2 else ~actions_mask
        else:
            action_is_pad = np.zeros(data["actions"].shape[0], dtype=bool)
        
        return {
            "observation.images": processed_images,  # (N*To, C, H, W)
            "observation.state": data["states"],  # (state_dim,) or (obs_horizon, state_dim)
            "action": data["actions"],  # (chunk_size, action_dim)
            "action_is_pad": action_is_pad,  # (chunk_size,), standardized: True=padded, False=original
        }
    
class DiffusionPolicyModelTransform(ModelTransform):
    resize: ResizeImage
    color_jitter: ColorJitter
    center_crop: CenterCrop
    normalize: Normalize
    img_aug: bool = False
    
    def __call__(
        self,
        data: dict[str, Any],
        no_aug: bool = False,
        **kwargs,
    ) -> dict[str, Any]:

        # import torch
        # try:
        # from torchvision.transforms import v2
        # except:
        #     from torchvision import transforms as v2
        do_img_aug = False if no_aug else self.img_aug
        t = v2.Compose(
            [
                v2.ToImage(),
                v2.ToDtype(torch.float32, scale=True),
                self.resize(),
                self.center_crop(),
                self.color_jitter() if do_img_aug else v2.Identity(),
                self.normalize(),
            ]
        )
        processed_images = torch.stack([t(img) for img in data["observations"]]) # (To, 3, H, W)
        
        if "action_is_pad" in data:
            # LerobotRepackTransform format: (chunk_size,), True=padded
            action_is_pad = data["action_is_pad"]
        elif "actions_mask" in data:
            # WeGR00TRepackTransform format: (chunk_size, Da), True=original, False=padded
            actions_mask = data["actions_mask"]
            if isinstance(actions_mask, np.ndarray):
                actions_mask = actions_mask.astype(bool)
                # (chunk_size, Da) --> (chunk_size,)
                if actions_mask.ndim == 2:
                    action_is_pad = ~actions_mask[:, 0]  # Invert: True->False (original), False->True (padded)
                else:
                    action_is_pad = ~actions_mask
            else:
                actions_mask = actions_mask.bool() if hasattr(actions_mask, 'bool') else actions_mask
                action_is_pad = ~actions_mask[:, 0] if len(actions_mask.shape) == 2 else ~actions_mask
        else:
            action_is_pad = np.zeros(data["actions"].shape[0], dtype=bool)
        
        
        return dict(
            image=processed_images, # (To, 3, H, W)
            agent_pos=data["states"], # (To, Da)
            action=data["actions"], #(Tp, Da)
            action_is_pad=action_is_pad,  # (Tp,), standardized: True=padded, False=original
        )
        
        # return {
        #     "observation.images": processed_images,  # (To, C, H, W)
        #     "observation.state": data["states"],  # (To, state_dim)
        #     "action": data["actions"],  # (Tp, Da)
        # }