File size: 60,742 Bytes
06df946
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
This file contains Dataset classes that are used by torch dataloaders
to fetch batches from hdf5 files.
"""
import os
import h5py
import numpy as np
from copy import deepcopy
from contextlib import contextmanager

import torch
import torch.utils.data

import robomimic.utils.tensor_utils as TensorUtils
import robomimic.utils.obs_utils as ObsUtils
import robomimic.utils.log_utils as LogUtils


class SequenceDataset(torch.utils.data.Dataset):
    def __init__(
        self,
        hdf5_path,
        obs_keys,
        dataset_keys,
        frame_stack=1,
        seq_length=1,
        pad_frame_stack=True,
        pad_seq_length=True,
        get_pad_mask=False,
        goal_mode=None,
        hdf5_cache_mode=None,
        hdf5_use_swmr=True,
        hdf5_normalize_obs=False,
        filter_by_attribute=None,
        load_next_obs=True,
        q_transformer=False,
        support_update=False,
        augment_nearby_states=False,
        advanced_augmentation=False,
        augment_init_cutoff_thresh=50,
        augment_init_cutoff_thresh_expert=20,
        gripper_key='gripper',
        distance_threshold=0.0,
        num_neighbors=10,
        augment_play=True,
        mask_augmentation=False,
        proprio_keys=None,
        expert_play_ratio=None,
        done_mode_terminal_only=False,
    ):
        """
        Dataset class for fetching sequences of experience.
        Length of the fetched sequence is equal to (@frame_stack - 1 + @seq_length)

        Args:
            hdf5_path (str): path to hdf5

            obs_keys (tuple, list): keys to observation items (image, object, etc) to be fetched from the dataset

            dataset_keys (tuple, list): keys to dataset items (actions, rewards, etc) to be fetched from the dataset

            frame_stack (int): numbers of stacked frames to fetch. Defaults to 1 (single frame).

            seq_length (int): length of sequences to sample. Defaults to 1 (single frame).

            pad_frame_stack (int): whether to pad sequence for frame stacking at the beginning of a demo. This
                ensures that partial frame stacks are observed, such as (s_0, s_0, s_0, s_1). Otherwise, the
                first frame stacked observation would be (s_0, s_1, s_2, s_3).

            pad_seq_length (int): whether to pad sequence for sequence fetching at the end of a demo. This
                ensures that partial sequences at the end of a demonstration are observed, such as
                (s_{T-1}, s_{T}, s_{T}, s_{T}). Otherwise, the last sequence provided would be
                (s_{T-3}, s_{T-2}, s_{T-1}, s_{T}).

            get_pad_mask (bool): if True, also provide padding masks as part of the batch. This can be
                useful for masking loss functions on padded parts of the data.

            goal_mode (str): either "last" or None. Defaults to None, which is to not fetch goals

            hdf5_cache_mode (str): one of ["all", "low_dim", or None]. Set to "all" to cache entire hdf5 
                in memory - this is by far the fastest for data loading. Set to "low_dim" to cache all 
                non-image data. Set to None to use no caching - in this case, every batch sample is 
                retrieved via file i/o. You should almost never set this to None, even for large 
                image datasets.

            hdf5_use_swmr (bool): whether to use swmr feature when opening the hdf5 file. This ensures
                that multiple Dataset instances can all access the same hdf5 file without problems.

            hdf5_normalize_obs (bool): if True, normalize observations by computing the mean observation
                and std of each observation (in each dimension and modality), and normalizing to unit
                mean and variance in each dimension.

            filter_by_attribute (str): if provided, use the provided filter key to look up a subset of
                demonstrations to load

            load_next_obs (bool): whether to load next_obs from the dataset
        """
        super(SequenceDataset, self).__init__()

        self.hdf5_path = os.path.expanduser(hdf5_path)
        self.hdf5_use_swmr = hdf5_use_swmr
        self.hdf5_normalize_obs = hdf5_normalize_obs
        self._hdf5_file = None

        assert hdf5_cache_mode in ["all", "low_dim", None]
        self.hdf5_cache_mode = hdf5_cache_mode

        self.load_next_obs = load_next_obs
        self.filter_by_attribute = filter_by_attribute

        # get all keys that needs to be fetched
        self.obs_keys = tuple(obs_keys)
        self.dataset_keys = tuple(dataset_keys)

        self.n_frame_stack = frame_stack
        assert self.n_frame_stack >= 1

        self.seq_length = seq_length
        assert self.seq_length >= 1
        
        self.support_update = support_update
        
        self.augment_nearby_states = augment_nearby_states
        self.distance_threshold = distance_threshold
        self.num_neighbors = num_neighbors
        self.gripper_key = gripper_key
        self.augment_init_cutoff_thresh = augment_init_cutoff_thresh
        self.augment_init_cutoff_thresh_expert = augment_init_cutoff_thresh_expert
        self.advanced_augmentation = advanced_augmentation
        self.augment_play = augment_play
        self.mask_augmentation = mask_augmentation
        self.proprio_keys = proprio_keys
        self.expert_play_ratio = expert_play_ratio    # rsm_rise gen_q#265: None = released (uniform) sampling
        self.done_mode_terminal_only = done_mode_terminal_only   # rsm_rise gen_q#265 wave 2: False = released dones

        self.goal_mode = goal_mode
        if self.goal_mode is not None:
            assert self.goal_mode in ["last"]
        if not self.load_next_obs:
            assert self.goal_mode != "last"  # we use last next_obs as goal

        self.pad_seq_length = pad_seq_length
        self.pad_frame_stack = pad_frame_stack
        self.get_pad_mask = get_pad_mask
        
        self.q_transformer = q_transformer

        self.load_demo_info(filter_by_attribute=self.filter_by_attribute)

        # maybe prepare for observation normalization
        self.obs_normalization_stats = None
        if self.hdf5_normalize_obs:
            self.obs_normalization_stats = self.normalize_obs()
            
        for k in self.obs_keys:
            if ObsUtils.key_is_obs_modality(k, 'rgb'):
                self.has_image_obs = True
                break
        else:
            self.has_image_obs = False
            
        if self.augment_nearby_states and self.hdf5_cache_mode != 'all':
            raise ValueError("Augmented states are only supported when caching all data in memory")

        # maybe store dataset in memory for fast access
        if self.hdf5_cache_mode in ["all", "low_dim"]:
            obs_keys_in_memory = self.obs_keys
            if self.hdf5_cache_mode == "low_dim":
                # only store low-dim observations
                obs_keys_in_memory = []
                for k in self.obs_keys:
                    if ObsUtils.key_is_obs_modality(k, "low_dim"):
                        obs_keys_in_memory.append(k)
            self.obs_keys_in_memory = obs_keys_in_memory

            self.hdf5_cache = self.load_dataset_in_memory(
                demo_list=self.demos,
                hdf5_file=self.hdf5_file,
                obs_keys=self.obs_keys_in_memory,
                dataset_keys=self.dataset_keys,
                load_next_obs=self.load_next_obs
            )

            if self.hdf5_cache_mode == "all":
                # cache getitem calls for even more speedup. We don't do this for
                # "low-dim" since image observations require calls to getitem anyways.
                print("SequenceDataset: caching get_item calls...")
                self.getitem_cache = [self.get_item(i) for i in LogUtils.custom_tqdm(range(self.total_num_sequences))]

                # don't need the previous cache anymore
                del self.hdf5_cache
                self.hdf5_cache = None
                
                if self.augment_nearby_states:
                    if self.has_image_obs:
                        # build feature extractor for images
                        from robomimic.models.obs_core import DinoV2Core
                        
                        self.image_feature_extractor = DinoV2Core(input_shape=(3, 84, 84), backbone_name='dinov2_vits14', concatenate=False)
                        self.model_device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
                        self.image_feature_extractor.to(self.model_device)
                        self.image_feature_extractor.eval()
                        
                    if self.advanced_augmentation and self.mask_augmentation:
                        raise ValueError("Advanced augmentation and mask augmentation cannot be used together")
                        
                    if self.advanced_augmentation:
                        self.build_state_augmentation_data_advanced()
                    elif self.mask_augmentation:
                        self.build_state_augmentation_data_segmentation()
                    else:
                        self.build_state_augmentation_data()
        else:
            self.hdf5_cache = None

        self.close_and_delete_hdf5_handle()

    def load_demo_info(self, filter_by_attribute=None, demos=None):
        """
        Args:
            filter_by_attribute (str): if provided, use the provided filter key
                to select a subset of demonstration trajectories to load

            demos (list): list of demonstration keys to load from the hdf5 file. If 
                omitted, all demos in the file (or under the @filter_by_attribute 
                filter key) are used.
        """
        # filter demo trajectory by mask
        if demos is not None:
            self.demos = demos
        elif filter_by_attribute is not None:
            self.demos = [elem.decode("utf-8") for elem in np.array(self.hdf5_file["mask/{}".format(filter_by_attribute)][:])]
        else:
            self.demos = list(self.hdf5_file["data"].keys())

        # sort demo keys
        inds = np.argsort([int(elem[5:]) for elem in self.demos])
        self.demos = [self.demos[i] for i in inds]

        self.n_demos = len(self.demos)

        # keep internal index maps to know which transitions belong to which demos
        self._index_to_demo_id = dict()  # maps every index to a demo id
        self._demo_id_to_start_indices = dict()  # gives start index per demo id
        self._demo_id_to_demo_length = dict()

        # determine index mapping
        self.total_num_sequences = 0
        for ep in self.demos:
            demo_length = self.hdf5_file["data/{}".format(ep)].attrs["num_samples"]
            self._demo_id_to_start_indices[ep] = self.total_num_sequences
            self._demo_id_to_demo_length[ep] = demo_length

            num_sequences = demo_length
            # determine actual number of sequences taking into account whether to pad for frame_stack and seq_length
            if not self.pad_frame_stack:
                num_sequences -= (self.n_frame_stack - 1)
            if not self.pad_seq_length:
                num_sequences -= (self.seq_length - 1)

            if self.pad_seq_length:
                assert demo_length >= 1  # sequence needs to have at least one sample
                num_sequences = max(num_sequences, 1)
            else:
                assert num_sequences >= 1  # assume demo_length >= (self.n_frame_stack - 1 + self.seq_length)

            for _ in range(num_sequences):
                self._index_to_demo_id[self.total_num_sequences] = ep
                self.total_num_sequences += 1

    @property
    def hdf5_file(self):
        """
        This property allows for a lazy hdf5 file open.
        """
        if self._hdf5_file is None:
            self._hdf5_file = h5py.File(self.hdf5_path, 'r', swmr=self.hdf5_use_swmr, libver='latest')
        return self._hdf5_file

    def close_and_delete_hdf5_handle(self):
        """
        Maybe close the file handle.
        """
        if self._hdf5_file is not None:
            self._hdf5_file.close()
        self._hdf5_file = None

    @contextmanager
    def hdf5_file_opened(self):
        """
        Convenient context manager to open the file on entering the scope
        and then close it on leaving.
        """
        should_close = self._hdf5_file is None
        yield self.hdf5_file
        if should_close:
            self.close_and_delete_hdf5_handle()

    def __del__(self):
        self.close_and_delete_hdf5_handle()

    def __repr__(self):
        """
        Pretty print the class and important attributes on a call to `print`.
        """
        msg = str(self.__class__.__name__)
        msg += " (\n\tpath={}\n\tobs_keys={}\n\tseq_length={}\n\tfilter_key={}\n\tframe_stack={}\n"
        msg += "\tpad_seq_length={}\n\tpad_frame_stack={}\n\tgoal_mode={}\n"
        msg += "\tcache_mode={}\n"
        msg += "\tnum_demos={}\n\tnum_sequences={}\n)"
        filter_key_str = self.filter_by_attribute if self.filter_by_attribute is not None else "none"
        goal_mode_str = self.goal_mode if self.goal_mode is not None else "none"
        cache_mode_str = self.hdf5_cache_mode if self.hdf5_cache_mode is not None else "none"
        msg = msg.format(self.hdf5_path, self.obs_keys, self.seq_length, filter_key_str, self.n_frame_stack,
                         self.pad_seq_length, self.pad_frame_stack, goal_mode_str, cache_mode_str,
                         self.n_demos, self.total_num_sequences)
        return msg

    def __len__(self):
        """
        Ensure that the torch dataloader will do a complete pass through all sequences in 
        the dataset before starting a new iteration.
        """
        if self.augment_nearby_states:
            return self.total_num_sequences + len(self.augmented_data)
        return self.total_num_sequences

    def load_dataset_in_memory(self, demo_list, hdf5_file, obs_keys, dataset_keys, load_next_obs):
        """
        Loads the hdf5 dataset into memory, preserving the structure of the file. Note that this
        differs from `self.getitem_cache`, which, if active, actually caches the outputs of the
        `getitem` operation.

        Args:
            demo_list (list): list of demo keys, e.g., 'demo_0'
            hdf5_file (h5py.File): file handle to the hdf5 dataset.
            obs_keys (list, tuple): observation keys to fetch, e.g., 'images'
            dataset_keys (list, tuple): dataset keys to fetch, e.g., 'actions'
            load_next_obs (bool): whether to load next_obs from the dataset

        Returns:
            all_data (dict): dictionary of loaded data.
        """
        all_data = dict()
        print("SequenceDataset: loading dataset into memory...")
        for ep in LogUtils.custom_tqdm(demo_list):
            all_data[ep] = {}
            all_data[ep]["attrs"] = {}
            all_data[ep]["attrs"]["num_samples"] = hdf5_file["data/{}".format(ep)].attrs["num_samples"]
            # get obs
            all_data[ep]["obs"] = {k: hdf5_file["data/{}/obs/{}".format(ep, k)][()] for k in obs_keys}
            if load_next_obs:
                all_data[ep]["next_obs"] = {k: hdf5_file["data/{}/next_obs/{}".format(ep, k)][()] for k in obs_keys}
            # get other dataset keys
            for k in dataset_keys:
                if k in hdf5_file["data/{}".format(ep)]:
                    all_data[ep][k] = hdf5_file["data/{}/{}".format(ep, k)][()].astype('float32')
                else:
                    all_data[ep][k] = np.zeros((all_data[ep]["attrs"]["num_samples"], 1), dtype=np.float32)

            if "model_file" in hdf5_file["data/{}".format(ep)].attrs:
                all_data[ep]["attrs"]["model_file"] = hdf5_file["data/{}".format(ep)].attrs["model_file"]

        return all_data

    def normalize_obs(self):
        """
        Computes a dataset-wide mean and standard deviation for the observations 
        (per dimension and per obs key) and returns it.
        """
        def _compute_traj_stats(traj_obs_dict):
            """
            Helper function to compute statistics over a single trajectory of observations.
            """
            traj_stats = { k : {} for k in traj_obs_dict }
            for k in traj_obs_dict:
                traj_stats[k]["n"] = traj_obs_dict[k].shape[0]
                traj_stats[k]["mean"] = traj_obs_dict[k].mean(axis=0, keepdims=True) # [1, ...]
                traj_stats[k]["sqdiff"] = ((traj_obs_dict[k] - traj_stats[k]["mean"]) ** 2).sum(axis=0, keepdims=True) # [1, ...]
            return traj_stats

        def _aggregate_traj_stats(traj_stats_a, traj_stats_b):
            """
            Helper function to aggregate trajectory statistics.
            See https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Parallel_algorithm
            for more information.
            """
            merged_stats = {}
            for k in traj_stats_a:
                n_a, avg_a, M2_a = traj_stats_a[k]["n"], traj_stats_a[k]["mean"], traj_stats_a[k]["sqdiff"]
                n_b, avg_b, M2_b = traj_stats_b[k]["n"], traj_stats_b[k]["mean"], traj_stats_b[k]["sqdiff"]
                n = n_a + n_b
                mean = (n_a * avg_a + n_b * avg_b) / n
                delta = (avg_b - avg_a)
                M2 = M2_a + M2_b + (delta ** 2) * (n_a * n_b) / n
                merged_stats[k] = dict(n=n, mean=mean, sqdiff=M2)
            return merged_stats

        # Run through all trajectories. For each one, compute minimal observation statistics, and then aggregate
        # with the previous statistics.
        ep = self.demos[0]
        obs_traj = {k: self.hdf5_file["data/{}/obs/{}".format(ep, k)][()].astype('float32') for k in self.obs_keys}
        obs_traj = ObsUtils.process_obs_dict(obs_traj)
        merged_stats = _compute_traj_stats(obs_traj)
        print("SequenceDataset: normalizing observations...")
        for ep in LogUtils.custom_tqdm(self.demos[1:]):
            obs_traj = {k: self.hdf5_file["data/{}/obs/{}".format(ep, k)][()].astype('float32') for k in self.obs_keys}
            obs_traj = ObsUtils.process_obs_dict(obs_traj)
            traj_stats = _compute_traj_stats(obs_traj)
            merged_stats = _aggregate_traj_stats(merged_stats, traj_stats)

        obs_normalization_stats = { k : {} for k in merged_stats }
        for k in merged_stats:
            # note we add a small tolerance of 1e-3 for std
            obs_normalization_stats[k]["mean"] = merged_stats[k]["mean"].astype(np.float32)
            obs_normalization_stats[k]["std"] = (np.sqrt(merged_stats[k]["sqdiff"] / merged_stats[k]["n"]) + 1e-3).astype(np.float32)
        return obs_normalization_stats

    def get_obs_normalization_stats(self):
        """
        Returns dictionary of mean and std for each observation key if using
        observation normalization, otherwise None.

        Returns:
            obs_normalization_stats (dict): a dictionary for observation
                normalization. This maps observation keys to dicts
                with a "mean" and "std" of shape (1, ...) where ... is the default
                shape for the observation.
        """
        assert self.hdf5_normalize_obs, "not using observation normalization!"
        return deepcopy(self.obs_normalization_stats)

    def get_dataset_for_ep(self, ep, key):
        """
        Helper utility to get a dataset for a specific demonstration.
        Takes into account whether the dataset has been loaded into memory.
        """

        # check if this key should be in memory
        key_should_be_in_memory = (self.hdf5_cache_mode in ["all", "low_dim"])
        if key_should_be_in_memory:
            # if key is an observation, it may not be in memory
            if '/' in key:
                key1, key2 = key.split('/')
                assert(key1 in ['obs', 'next_obs'])
                if key2 not in self.obs_keys_in_memory:
                    key_should_be_in_memory = False

        if key_should_be_in_memory:
            # read cache
            if '/' in key:
                key1, key2 = key.split('/')
                assert(key1 in ['obs', 'next_obs'])
                ret = self.hdf5_cache[ep][key1][key2]
            else:
                ret = self.hdf5_cache[ep][key]
            if key == "dones" and getattr(self, "done_mode_terminal_only", False):   # rsm_rise gen_q#265 wave 2
                ret = np.zeros_like(np.asarray(ret)); ret[-1] = 1
            return ret
        else:
            # read from file
            hd5key = "data/{}/{}".format(ep, key)
            ret = self.hdf5_file[hd5key]
            if key == "dones" and getattr(self, "done_mode_terminal_only", False):   # rsm_rise gen_q#265 wave 2
                ret = np.zeros(ret.shape, dtype=np.asarray(ret[0:1]).dtype); ret[-1] = 1
        return ret

    def __getitem__(self, index):
        """
        Fetch dataset sequence @index (inferred through internal index map), using the getitem_cache if available.
        """
        if self.augment_nearby_states:
            if index < self.total_num_sequences:
                return self.getitem_cache[index]
            else:
                return self.augmented_data[index - self.total_num_sequences]
        data = self.getitem_cache[index] if self.hdf5_cache_mode == "all" else self.get_item(index)
        if self.support_update:
            return index, data
        return data

    def get_item(self, index):
        """
        Main implementation of getitem when not using cache.
        """

        demo_id = self._index_to_demo_id[index]
        demo_start_index = self._demo_id_to_start_indices[demo_id]
        demo_length = self._demo_id_to_demo_length[demo_id]

        # start at offset index if not padding for frame stacking
        demo_index_offset = 0 if self.pad_frame_stack else (self.n_frame_stack - 1)
        index_in_demo = index - demo_start_index + demo_index_offset

        # end at offset index if not padding for seq length
        demo_length_offset = 0 if self.pad_seq_length else (self.seq_length - 1)
        end_index_in_demo = demo_length - demo_length_offset

        meta = self.get_dataset_sequence_from_demo(
            demo_id,
            index_in_demo=index_in_demo,
            keys=self.dataset_keys,
            num_frames_to_stack=self.n_frame_stack - 1, # note: need to decrement self.n_frame_stack by one
            seq_length=self.seq_length 
        )

        # determine goal index
        goal_index = None
        if self.goal_mode == "last":
            goal_index = end_index_in_demo - 1

        meta["obs"] = self.get_obs_sequence_from_demo(
            demo_id,
            index_in_demo=index_in_demo,
            keys=self.obs_keys,
            num_frames_to_stack=self.n_frame_stack - 1,
            seq_length=self.seq_length,
            prefix="obs"
        )

        if self.load_next_obs:
            meta["next_obs"] = self.get_obs_sequence_from_demo(
                demo_id,
                index_in_demo=index_in_demo,
                keys=self.obs_keys,
                num_frames_to_stack=self.n_frame_stack - 1,
                seq_length=self.seq_length,
                prefix="next_obs"
            )

        if goal_index is not None:
            goal = self.get_obs_sequence_from_demo(
                demo_id,
                index_in_demo=goal_index,
                keys=self.obs_keys,
                num_frames_to_stack=0,
                seq_length=1,
                prefix="next_obs",
            )
            meta["goal_obs"] = {k: goal[k][0] for k in goal}  # remove sequence dimension for goal

        if self.q_transformer:
            instruction = np.zeros(shape=(1, 3))
            next_instruction = np.zeros(shape=(1, 3))
            obs = self._convert_obs_dict_to_stacked_img(meta['obs'])
            next_obs = self._convert_obs_dict_to_stacked_img(meta['next_obs'])
            actions = meta['actions']
            reward = meta['rewards']
            done = meta['dones']
            return instruction, obs, actions, next_obs, next_instruction,reward, done
        return meta
        
    def build_state_augmentation_data(self):
        """
        Builds data structures for state augmentation by finding nearby states from different trajectories.
        This creates a mapping from each state to a list of (state_idx, action) pairs from different trajectories
        that are within the distance threshold.
        """
        print("SequenceDataset: Building state augmentation data...")
        
        # Extract all states from the dataset
        all_states = []
        state_to_demo = []  # Maps state index to demo_id
        state_to_idx = []   # Maps state index to index in original dataset
        
        print('SequenceDataset: Extracting features from states...')
        for idx in LogUtils.custom_tqdm(range(self.total_num_sequences)):
            data = self.getitem_cache[idx]
            # Use the first frame of the observation sequence as the state representation
            state = self._extract_state_for_distance(data["obs"])
            all_states.append(state)
            state_to_demo.append(self._index_to_demo_id[idx])
            state_to_idx.append(idx)
        
        # Convert to numpy array for efficient computation
        all_states = np.array(all_states)
        
        # For each state, find nearby states from different trajectories
        self.augmented_data = []
        
        from sklearn.neighbors import NearestNeighbors
        # Build KNN model
        nn_model = NearestNeighbors(n_neighbors=min(self.num_neighbors + 1, len(all_states)))
        nn_model.fit(all_states)
        
        print('SequenceDataset: Finding nearest neighbors...')
        for i in LogUtils.custom_tqdm(range(len(all_states))):
            # Find k nearest neighbors
            distances, indices = nn_model.kneighbors([all_states[i]], n_neighbors=min(self.num_neighbors + 1, len(all_states)))
            
            # Filter neighbors by distance threshold and different trajectory
            for j, (dist, idx) in enumerate(zip(distances[0], indices[0])):
                if i == idx:  # Skip self
                    continue
                if dist > self.distance_threshold:  # Skip if too far
                    continue
                if state_to_demo[i] == state_to_demo[idx]:  # Skip if same trajectory
                    continue
                
                original_obs = self.getitem_cache[state_to_idx[i]]['obs'].copy()
                original_next_obs = self.getitem_cache[state_to_idx[i]].get('next_obs')
                neighbor_action = self.getitem_cache[state_to_idx[idx]]['actions'].copy()
                neighbor_reward = self.getitem_cache[state_to_idx[idx]]['rewards'].copy()
                neighbor_done = self.getitem_cache[state_to_idx[idx]]['dones'].copy()
                # Get the action from the neighbor
                new_data = {
                    'obs': original_obs,
                    'actions': neighbor_action,
                    **({'next_obs': original_next_obs} if original_next_obs is not None else {}),
                    'rewards': neighbor_reward,
                    'dones': neighbor_done,
                }
                self.augmented_data.append(new_data)
        
        print(f"SequenceDataset: Created augmentation data for {len(self.augmented_data)} states")
        
    def build_state_augmentation_data_advanced(self):
        # Extract all states from the dataset
        all_expert_states = []
        expert_state_to_demo = []  # Maps state index to demo_id
        expert_state_to_idx = []   # Maps state index to index in original dataset
        
        all_play_states = []
        play_state_to_demo = []
        play_state_to_idx = []
        
        print('SequenceDataset: Extracting features from states... (advanced)')
        for idx in LogUtils.custom_tqdm(range(self.total_num_sequences)):
            data = self.getitem_cache[idx]
            
            demo_start_index = self._demo_id_to_start_indices[self._index_to_demo_id[idx]]
            demo_index_offset = 0 if self.pad_frame_stack else (self.n_frame_stack - 1)
            index_in_demo = idx - demo_start_index + demo_index_offset
                        
            if np.all(data['rewards'] == 0):
                if index_in_demo < self.augment_init_cutoff_thresh:
                    continue

                all_play_states.append(self._extract_state_for_distance(data["obs"]))
                play_state_to_demo.append(self._index_to_demo_id[idx])
                play_state_to_idx.append(idx)

            else:
                if index_in_demo < self.augment_init_cutoff_thresh_expert:
                    continue
                
                all_expert_states.append(self._extract_state_for_distance(data["obs"]))
                expert_state_to_demo.append(self._index_to_demo_id[idx])
                expert_state_to_idx.append(idx)

        # Convert to numpy array for efficient computation
        all_expert_states = np.array(all_expert_states)
        all_play_states = np.array(all_play_states)
        
        # For each state, find nearby states from different trajectories
        self.augmented_data = []
        
        from sklearn.neighbors import NearestNeighbors
        # Build KNN model
        expert_nn_model = NearestNeighbors(n_neighbors=min(self.num_neighbors + 1, len(all_expert_states)))
        expert_nn_model.fit(all_expert_states)
        
        play_nn_model = NearestNeighbors(n_neighbors=min(self.num_neighbors + 1, len(all_play_states)))
        play_nn_model.fit(all_play_states)
        
        print('SequenceDataset: Finding nearest neighbors...')
        distances_p2e, indicies_p2e = expert_nn_model.kneighbors(all_play_states, n_neighbors=min(self.num_neighbors + 1, len(all_expert_states)))
        distances_p2p, indicies_p2p = play_nn_model.kneighbors(all_play_states, n_neighbors=min(self.num_neighbors + 1, len(all_play_states)))
                
        for i, (distances, idxs) in enumerate(zip(distances_p2e, indicies_p2e)):
            print(distances)
            for (dist, idx) in zip(distances, idxs):
                if dist > self.distance_threshold:
                    continue
                
                original_obs = self.getitem_cache[play_state_to_idx[i]]['obs'].copy() 
                neighbor_obs = self.getitem_cache[expert_state_to_idx[idx]]['obs'].copy()
                
                # check that gripper must be same
                if self.gripper_key is not None and not np.all(original_obs[self.gripper_key] == neighbor_obs[self.gripper_key]):
                    continue
                
                original_next_obs = self.getitem_cache[play_state_to_idx[i]].get('next_obs')
                neighbor_action = self.getitem_cache[expert_state_to_idx[idx]]['actions'].copy()
                neighbor_reward = self.getitem_cache[expert_state_to_idx[idx]]['rewards'].copy()
                neighbor_done = self.getitem_cache[expert_state_to_idx[idx]]['dones'].copy()
                
                new_data = {
                        'obs': original_obs,
                        'actions': neighbor_action,
                        **({'next_obs': original_next_obs} if original_next_obs is not None else {}),
                        'rewards': neighbor_reward,
                        'dones': neighbor_done,
                    }
                self.augmented_data.append(new_data)
        
        if self.augment_play:
            for i, (distances, idxs) in enumerate(zip(distances_p2p, indicies_p2p)):  
                for (dist, idx) in zip(distances, idxs):
                    if dist > self.distance_threshold:
                        continue
                    if play_state_to_idx[i] == play_state_to_idx[idx]:
                        continue
                    if play_state_to_demo[i] == play_state_to_demo[idx]:
                        continue
                
                    original_obs = self.getitem_cache[play_state_to_idx[i]]['obs'].copy()
                    original_next_obs = self.getitem_cache[play_state_to_idx[i]].get('next_obs')
                    neighbor_action = self.getitem_cache[play_state_to_idx[idx]]['actions'].copy()
                    neighbor_reward = self.getitem_cache[play_state_to_idx[idx]]['rewards'].copy()
                    neighbor_done = self.getitem_cache[play_state_to_idx[idx]]['dones'].copy()
                    
                    new_data = {
                        'obs': original_obs,
                        'actions': neighbor_action,
                        **({'next_obs': original_next_obs} if original_next_obs is not None else {}),
                        'rewards': neighbor_reward,
                        'dones': neighbor_done,
                    }
                    self.augmented_data.append(new_data)
        
        print(f"SequenceDataset: Created augmentation data for {len(self.augmented_data)} states")

    def build_state_augmentation_data_segmentation(self):
        # Extract all states from the dataset
        all_expert_states = []
        expert_state_to_demo = []  # Maps state index to demo_id
        expert_state_to_idx = []   # Maps state index to index in original dataset
        
        all_play_states = []
        play_state_to_demo = []
        play_state_to_idx = []
        
        print('SequenceDataset: Extracting features from states... (advanced)')
        for idx in LogUtils.custom_tqdm(range(self.total_num_sequences)):
            data = self.getitem_cache[idx]
            
            demo_id = self._index_to_demo_id[idx]
            
            demo_start_index = self._demo_id_to_start_indices[demo_id]
            demo_index_offset = 0 if self.pad_frame_stack else (self.n_frame_stack - 1)
            index_in_demo = idx - demo_start_index + demo_index_offset
            
            object_masks = self.hdf5_file['data'][demo_id]['object_mask'][f'frame_{index_in_demo}']
                        
            if np.all(data['rewards'] == 0):
                mask_features = self._extract_mask_state_for_distance(object_masks)
                proprio_features = self._extract_proprio_state_for_distance(data["obs"])    
                state = np.concatenate([mask_features, proprio_features])
                
                all_play_states.append(state)
                play_state_to_demo.append(self._index_to_demo_id[idx])
                play_state_to_idx.append(idx)

            else:
                mask_features = self._extract_mask_state_for_distance(object_masks)
                proprio_features = self._extract_proprio_state_for_distance(data["obs"])    
                state = np.concatenate([mask_features, proprio_features])
                
                all_expert_states.append(state)
                expert_state_to_demo.append(self._index_to_demo_id[idx])
                expert_state_to_idx.append(idx)

        all_expert_states = np.array(all_expert_states)
        all_play_states = np.array(all_play_states)
        
        # For each state, find nearby states from different trajectories
        self.augmented_data = []
        
        from sklearn.neighbors import NearestNeighbors
        # Build KNN model
        expert_nn_model = NearestNeighbors(n_neighbors=min(self.num_neighbors + 1, len(all_expert_states)))
        expert_nn_model.fit(all_expert_states)
        
        play_nn_model = NearestNeighbors(n_neighbors=min(self.num_neighbors + 1, len(all_play_states)))
        play_nn_model.fit(all_play_states)
        
        print('SequenceDataset: Finding nearest neighbors...')
        distances_p2e, indicies_p2e = expert_nn_model.kneighbors(all_play_states, n_neighbors=min(self.num_neighbors + 1, len(all_expert_states)))
        distances_p2p, indicies_p2p = play_nn_model.kneighbors(all_play_states, n_neighbors=min(self.num_neighbors + 1, len(all_play_states)))
                
        for i, (distances, idxs) in enumerate(zip(distances_p2e, indicies_p2e)):
            print(distances)
            for (dist, idx) in zip(distances, idxs):
                if dist > self.distance_threshold:
                    continue
                
                original_obs = self.getitem_cache[play_state_to_idx[i]]['obs'].copy() 
                neighbor_obs = self.getitem_cache[expert_state_to_idx[idx]]['obs'].copy()
                
                # check that gripper must be same
                if self.gripper_key is not None and not np.all(original_obs[self.gripper_key] == neighbor_obs[self.gripper_key]):
                    continue
                
                original_next_obs = self.getitem_cache[play_state_to_idx[i]].get('next_obs')
                neighbor_action = self.getitem_cache[expert_state_to_idx[idx]]['actions'].copy()
                neighbor_reward = self.getitem_cache[expert_state_to_idx[idx]]['rewards'].copy()
                neighbor_done = self.getitem_cache[expert_state_to_idx[idx]]['dones'].copy()
                
                new_data = {
                        'obs': original_obs,
                        'actions': neighbor_action,
                        **({'next_obs': original_next_obs} if original_next_obs is not None else {}),
                        'rewards': neighbor_reward,
                        'dones': neighbor_done,
                    }
                self.augmented_data.append(new_data)
        
        if self.augment_play:
            for i, (distances, idxs) in enumerate(zip(distances_p2p, indicies_p2p)):  
                for (dist, idx) in zip(distances, idxs):
                    if dist > self.distance_threshold:
                        continue
                    if play_state_to_idx[i] == play_state_to_idx[idx]:
                        continue
                    if play_state_to_demo[i] == play_state_to_demo[idx]:
                        continue
                
                    original_obs = self.getitem_cache[play_state_to_idx[i]]['obs'].copy()
                    original_next_obs = self.getitem_cache[play_state_to_idx[i]].get('next_obs')
                    neighbor_action = self.getitem_cache[play_state_to_idx[idx]]['actions'].copy()
                    neighbor_reward = self.getitem_cache[play_state_to_idx[idx]]['rewards'].copy()
                    neighbor_done = self.getitem_cache[play_state_to_idx[idx]]['dones'].copy()
                    
                    new_data = {
                        'obs': original_obs,
                        'actions': neighbor_action,
                        **({'next_obs': original_next_obs} if original_next_obs is not None else {}),
                        'rewards': neighbor_reward,
                        'dones': neighbor_done,
                    }
                    self.augmented_data.append(new_data)
        
        print(f"SequenceDataset: Created augmentation data for {len(self.augmented_data)} states")


    def _extract_mask_state_for_distance(self, masks):
        """
        Extract a state representation from the mask for distance calculation.
        Uses polar coordinates to ensure consistent ordering of contour points.
        """
        import cv2
        
        all_features = []
        for mask_id in masks.keys():
            mask = masks[mask_id]
            
            # Calculate area (sum of all True values)
            area = np.sum(mask)
            
            # Calculate centroid
            if area > 0:
                y_indices, x_indices = np.where(mask)
                centroid_y = np.mean(y_indices)
                centroid_x = np.mean(x_indices)
            else:
                centroid_y, centroid_x = 0, 0
            
            # Extract contour points in polar coordinates
            contour_features = []
            if area > 0:
                # Convert boolean mask to uint8 for OpenCV
                mask_uint8 = mask.astype(np.uint8) * 255
                
                # Find contours
                contours, _ = cv2.findContours(mask_uint8, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
                
                if contours:
                    # Get the largest contour
                    largest_contour = max(contours, key=cv2.contourArea)
                    
                    # Flatten contour for easier processing
                    contour_flat = largest_contour.reshape(-1, 2)
                    
                    # Convert to polar coordinates relative to centroid
                    polar_points = []
                    for point in contour_flat:
                        # Calculate relative coordinates
                        dx = point[0] - centroid_x
                        dy = point[1] - centroid_y
                        
                        # Convert to polar coordinates
                        r = np.sqrt(dx**2 + dy**2)
                        theta = np.arctan2(dy, dx)  # Range: [-pi, pi]
                        
                        polar_points.append((theta, r, point[0], point[1]))
                    
                    # Sort by theta to ensure consistent ordering
                    polar_points.sort(key=lambda p: p[0])
                    
                    # Sample evenly in the theta domain
                    num_points = 8
                    theta_step = 2 * np.pi / num_points
                    
                    sampled_points = []
                    for i in range(num_points):
                        target_theta = -np.pi + i * theta_step
                        
                        # Find closest point by theta
                        closest_idx = np.argmin([abs(p[0] - target_theta) for p in polar_points])
                        r = polar_points[closest_idx][1]
                        
                        # Store normalized r and theta
                        sampled_points.extend([r, target_theta])
                    
                    contour_features = sampled_points
            
            # If no contour was found or processing failed, use zeros
            if not contour_features:
                contour_features = [0] * num_points * 2
            
            # Create feature vector: [centroid_y, centroid_x, contour_points...]
            features = np.array([centroid_y, centroid_x] + contour_features)
            all_features.append(features)
            
        all_features = np.array(all_features)
        # Normalize to make euclidean distance meaningful
        all_features = all_features / np.linalg.norm(all_features, axis=1, keepdims=True) if np.linalg.norm(all_features, axis=1, keepdims=True) > 0 else all_features
        
        return all_features
    
    def _extract_proprio_state_for_distance(self, obs_dict):
        """
        Extract a state representation from the observation dictionary for distance calculation.
        """
        proprio = []
        for proprio_key in self.proprio_keys:
            proprio.append(obs_dict[proprio_key])
        proprio = np.concatenate(proprio)
        proprio = proprio / np.linalg.norm(proprio)
        return proprio
        

    def _extract_state_for_distance(self, obs_dict):
        """
        Extract a state representation from the observation dictionary for distance calculation.
        
        Args:
            obs_dict (dict): Observation dictionary
            
        Returns:
            np.ndarray: State representation for distance calculation
        """
        
        curr_obs_index = self.n_frame_stack - 1
        
        state = []
        if self.has_image_obs:
            for key in obs_dict:
                if ObsUtils.key_is_obs_modality(key, 'rgb'):
                    img = torch.from_numpy(obs_dict[key][curr_obs_index])
                    img = ObsUtils.process_obs(obs=img, obs_modality='rgb')
                    img = img.unsqueeze(0).to(self.model_device)
                    features = self.image_feature_extractor(img)
                    state.append(features.flatten().detach().cpu().numpy())
        else:
            for key in obs_dict:
                if key != "pad_mask":
                    state.append(obs_dict[key][curr_obs_index].flatten())
                
        state = np.concatenate(state)
        # normalize to make euclidean distance equivalent to cosine distance ranking
        state = state / np.linalg.norm(state)
        return state

    def _convert_obs_dict_to_stacked_img(self, obs_dict):
        img_stack = []
        for k in obs_dict:
            img_stack.append(obs_dict[k])
        return np.concatenate(img_stack, axis=0)

    def get_sequence_from_demo(self, demo_id, index_in_demo, keys, num_frames_to_stack=0, seq_length=1):
        """
        Extract a (sub)sequence of data items from a demo given the @keys of the items.

        Args:
            demo_id (str): id of the demo, e.g., demo_0
            index_in_demo (int): beginning index of the sequence wrt the demo
            keys (tuple): list of keys to extract
            num_frames_to_stack (int): numbers of frame to stack. Seq gets prepended with repeated items if out of range
            seq_length (int): sequence length to extract. Seq gets post-pended with repeated items if out of range

        Returns:
            a dictionary of extracted items.
        """
        assert num_frames_to_stack >= 0
        assert seq_length >= 1

        demo_length = self._demo_id_to_demo_length[demo_id]
        assert index_in_demo < demo_length

        # determine begin and end of sequence
        seq_begin_index = max(0, index_in_demo - num_frames_to_stack)
        seq_end_index = min(demo_length, index_in_demo + seq_length)

        # determine sequence padding
        seq_begin_pad = max(0, num_frames_to_stack - index_in_demo)  # pad for frame stacking
        seq_end_pad = max(0, index_in_demo + seq_length - demo_length)  # pad for sequence length

        # make sure we are not padding if specified.
        if not self.pad_frame_stack:
            assert seq_begin_pad == 0
        if not self.pad_seq_length:
            assert seq_end_pad == 0

        # fetch observation from the dataset file
        seq = dict()
        for k in keys:
            data = self.get_dataset_for_ep(demo_id, k)
            seq[k] = data[seq_begin_index: seq_end_index]

        seq = TensorUtils.pad_sequence(seq, padding=(seq_begin_pad, seq_end_pad), pad_same=True)
        pad_mask = np.array([0] * seq_begin_pad + [1] * (seq_end_index - seq_begin_index) + [0] * seq_end_pad)
        pad_mask = pad_mask[:, None].astype(bool)

        return seq, pad_mask

    def get_obs_sequence_from_demo(self, demo_id, index_in_demo, keys, num_frames_to_stack=0, seq_length=1, prefix="obs"):
        """
        Extract a (sub)sequence of observation items from a demo given the @keys of the items.

        Args:
            demo_id (str): id of the demo, e.g., demo_0
            index_in_demo (int): beginning index of the sequence wrt the demo
            keys (tuple): list of keys to extract
            num_frames_to_stack (int): numbers of frame to stack. Seq gets prepended with repeated items if out of range
            seq_length (int): sequence length to extract. Seq gets post-pended with repeated items if out of range
            prefix (str): one of "obs", "next_obs"

        Returns:
            a dictionary of extracted items.
        """
        obs, pad_mask = self.get_sequence_from_demo(
            demo_id,
            index_in_demo=index_in_demo,
            keys=tuple('{}/{}'.format(prefix, k) for k in keys),
            num_frames_to_stack=num_frames_to_stack,
            seq_length=seq_length,
        )
        obs = {k.split('/')[1]: obs[k] for k in obs}  # strip the prefix
        if self.get_pad_mask:
            obs["pad_mask"] = pad_mask

        return obs

    def get_dataset_sequence_from_demo(self, demo_id, index_in_demo, keys, num_frames_to_stack=0, seq_length=1):
        """
        Extract a (sub)sequence of dataset items from a demo given the @keys of the items (e.g., states, actions).
        
        Args:
            demo_id (str): id of the demo, e.g., demo_0
            index_in_demo (int): beginning index of the sequence wrt the demo
            keys (tuple): list of keys to extract
            num_frames_to_stack (int): numbers of frame to stack. Seq gets prepended with repeated items if out of range
            seq_length (int): sequence length to extract. Seq gets post-pended with repeated items if out of range

        Returns:
            a dictionary of extracted items.
        """
        data, pad_mask = self.get_sequence_from_demo(
            demo_id,
            index_in_demo=index_in_demo,
            keys=keys,
            num_frames_to_stack=num_frames_to_stack,
            seq_length=seq_length,
        )
        if self.get_pad_mask:
            data["pad_mask"] = pad_mask
        return data

    def get_trajectory_at_index(self, index):
        """
        Method provided as a utility to get an entire trajectory, given
        the corresponding @index.
        """
        demo_id = self.demos[index]
        demo_length = self._demo_id_to_demo_length[demo_id]

        meta = self.get_dataset_sequence_from_demo(
            demo_id,
            index_in_demo=0,
            keys=self.dataset_keys,
            num_frames_to_stack=self.n_frame_stack - 1, # note: need to decrement self.n_frame_stack by one
            seq_length=demo_length
        )
        meta["obs"] = self.get_obs_sequence_from_demo(
            demo_id,
            index_in_demo=0,
            keys=self.obs_keys,
            seq_length=demo_length
        )
        if self.load_next_obs:
            meta["next_obs"] = self.get_obs_sequence_from_demo(
                demo_id,
                index_in_demo=0,
                keys=self.obs_keys,
                seq_length=demo_length,
                prefix="next_obs"
            )

        meta["ep"] = demo_id
        return meta
    
    def update_actions(self, batch_indices, new_actions):
        """
        Updates actions in the dataset for the given batch indices.
        
        Args:
            batch_indices (tensor): Indices from the batch that need updating
            new_actions (tensor): New actions to insert [B x seq_length x action_dim]
        """
        assert self.hdf5_cache_mode == "all", "Action updates only supported with full caching"
        assert self.pad_seq_length == True, "Action updates only supported with padding"
        
        for batch_idx, new_action_seq in zip(batch_indices, new_actions):
            # Get demo info for this index
            demo_id = self._index_to_demo_id[batch_idx]
            demo_start_index = self._demo_id_to_start_indices[demo_id]
            demo_length = self._demo_id_to_demo_length[demo_id]
            
            # Calculate actual index in demo
            demo_index_offset = 0 if self.pad_frame_stack else (self.n_frame_stack - 1)
            index_in_demo = batch_idx - demo_start_index + demo_index_offset
            
            end_seq = self.seq_length
            
            # if the sequence spills over to the end, we need to update the padding
            if index_in_demo + self.seq_length >= demo_length:
                max_pad_idx = demo_length + self.seq_length - 2
                end_seq = max_pad_idx - index_in_demo + 1
                # pad new_action_seq with the last action
                extra_pad = end_seq - self.seq_length
                new_action_seq = np.concatenate([new_action_seq, new_action_seq[-1].repeat(extra_pad, axis=0)], axis=0)
            
            # For each timestep in the sequence
            for seq_idx in range(end_seq):
                curr_demo_idx = index_in_demo + seq_idx           
                                    
                # Find all dataset indices that need this action updated
                update_start = max(0, curr_demo_idx - (self.seq_length - 1))
                update_end = min(demo_length, curr_demo_idx + self.n_frame_stack)
                
                # Convert back to dataset indices
                dataset_start_idx = demo_start_index + update_start - demo_index_offset
                dataset_end_idx = demo_start_index + update_end - demo_index_offset
                
                # Update all affected cached items
                for idx in range(dataset_start_idx, dataset_end_idx):
                    if idx >= len(self.getitem_cache):
                        continue
                        
                    # Calculate where in the sequence this action should go
                    seq_position = curr_demo_idx - (idx - demo_start_index + demo_index_offset) + (self.n_frame_stack - 1)
                    if 0 <= seq_position < (self.seq_length + self.n_frame_stack):
                        self.getitem_cache[idx]["actions"][seq_position] = new_action_seq[seq_idx]


    # ---- rsm_rise gen_q#265: expert:play sampling mixture -------------------------------------------------
    def _demo_is_expert(self, ep):
        """RISE's provenance convention (build_state_augmentation_data*): an episode whose rewards are all
        zero is play/suboptimal, anything else is expert."""
        try:
            r = self.get_dataset_for_ep(ep, "rewards")
        except TypeError:
            # cache_mode 'all': hdf5_cache is freed once getitem_cache is built -> read the (lazily re-opened) file
            r = self.hdf5_file["data/{}/rewards".format(ep)][()]
        return bool(np.any(np.asarray(r) != 0))

    def sequence_weights(self):
        """Per-index sampling weights (length len(self)) under which expert:play sequences are drawn in the
        ratio expert_play_ratio:1 in expectation -- separately inside the regular pool and the augmented
        pool, so the odd/even epoch alternation of AugmentedRandomSampler is untouched.  Play weight 1,
        expert weight r * n_play / n_expert; a pool holding only one kind stays uniform.  None when
        expert_play_ratio is None (released behaviour)."""
        if self.expert_play_ratio is None:
            return None
        r = float(self.expert_play_ratio)
        n_total = len(self)
        is_expert = np.zeros(n_total, dtype=bool)
        expert_demos = {ep for ep in self.demos if self._demo_is_expert(ep)}
        self.close_and_delete_hdf5_handle()      # in case _demo_is_expert re-opened the file
        for idx in range(self.total_num_sequences):
            is_expert[idx] = self._index_to_demo_id[idx] in expert_demos
        if self.augment_nearby_states:
            for j, d in enumerate(self.augmented_data):
                is_expert[self.total_num_sequences + j] = bool(np.any(np.asarray(d["rewards"]) != 0))
        w = np.ones(n_total, dtype=np.float64)
        for lo, hi, pool in ((0, self.total_num_sequences, "regular"), (self.total_num_sequences, n_total, "augmented")):
            if hi <= lo:
                continue
            ne = int(is_expert[lo:hi].sum()); npl = (hi - lo) - ne
            we = r * npl / ne if (ne > 0 and npl > 0) else 1.0
            w[lo:hi][is_expert[lo:hi]] = we
            print("SequenceDataset: expert_play_ratio={}: {} pool {} expert / {} play sequences ({} expert demos of {}), "
                  "natural {:.3f}:1 -> expert weight {:.3f}, play weight 1.0".format(
                      r, pool, ne, npl, len(expert_demos), self.n_demos, ne / max(npl, 1), we), flush=True)
        return w

    def get_dataset_sampler(self, data_source=None, generator=None):
        """
        Return instance of torch.utils.data.Sampler or None. Allows
        for dataset to define custom sampling logic, such as
        re-weighting the probability of samples being drawn.
        See the `train` function in scripts/train.py, and torch
        `DataLoader` documentation, for more info.
        """
        weights = self.sequence_weights()      # None unless train.expert_play_ratio is set (rsm_rise gen_q#265)
        if self.augment_nearby_states:
            return AugmentedRandomSampler(self.total_num_sequences, data_source=data_source, generator=generator,
                                          weights=weights)
        if weights is not None:
            dev = generator.device if generator is not None else "cpu"
            return torch.utils.data.WeightedRandomSampler(
                torch.as_tensor(weights, dtype=torch.float64, device=dev), num_samples=self.total_num_sequences,
                replacement=True, generator=generator)
        return None

class AugmentedRandomSampler(torch.utils.data.Sampler):
    def __init__(
        self,
        non_augmented_size,
        data_source=None,
        generator=None,
        weights=None,
        *args,
        **kwargs,
    ):
        self.data_source = data_source
        self.generator = generator
        # rsm_rise gen_q#265: optional per-index sampling weights (SequenceDataset.sequence_weights).  None
        # keeps the released uniform permutation; otherwise each pool is drawn with replacement by weight.
        self.weights = None if weights is None else torch.as_tensor(weights, dtype=torch.float64)
        
        self.non_augmented_size = non_augmented_size
        self.total_size = len(data_source)
        self.augmented_size = self.total_size - self.non_augmented_size
        
        # Prepare separate indices for regular and augmented data
        self.regular_indices = None
        self.augmented_indices = None
        self.regular_position = 0
        self.augmented_position = 0
        
        # Default to regular data
        self.sample_augmented = False
        
        # Reset for the first epoch
        self.reset_indices()
        
        super().__init__(*args, **kwargs)
        
    def reset_indices(self):
        """Reset and reshuffle all indices for a new epoch"""
        if self.generator is None:
            seed = int(torch.empty((), dtype=torch.int64).random_().item())
            generator = torch.Generator()
            generator.manual_seed(seed)
        else:
            generator = self.generator
            
        # Shuffle both sets of indices
        if self.weights is None:
            self.regular_indices = torch.randperm(self.non_augmented_size, generator=generator).tolist()
            self.augmented_indices = (torch.randperm(self.augmented_size, generator=generator) + 
                                     self.non_augmented_size).tolist()
        else:
            w = self.weights.to(generator.device)
            self.regular_indices = torch.multinomial(w[:self.non_augmented_size], self.non_augmented_size,
                                                     replacement=True, generator=generator).tolist()
            if self.augmented_size > 0:
                self.augmented_indices = (torch.multinomial(w[self.non_augmented_size:], self.augmented_size,
                                                            replacement=True, generator=generator)
                                          + self.non_augmented_size).tolist()
            else:
                self.augmented_indices = []
        
        # Reset positions
        self.regular_position = 0
        self.augmented_position = 0
    
    def __iter__(self):
        return self
    
    def __next__(self):
        if self.sample_augmented:
            # Check if we've exhausted augmented indices
            if self.augmented_position >= len(self.augmented_indices):
                self.reset_indices()  # Start a new epoch
                
            # Get next augmented index
            idx = self.augmented_indices[self.augmented_position]
            self.augmented_position += 1
            return idx
        else:
            # Check if we've exhausted regular indices
            if self.regular_position >= len(self.regular_indices):
                self.reset_indices()  # Start a new epoch
                
            # Get next regular index
            idx = self.regular_indices[self.regular_position]
            self.regular_position += 1
            return idx
    
    def __len__(self):
        return self.total_size  # Total size for DataLoader's benefit
    
    def set_augmented(self):
        """Switch to sampling from augmented data"""
        self.sample_augmented = True
    
    def set_regular(self):
        """Switch to sampling from regular data"""
        self.sample_augmented = False