-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtools.py
More file actions
2071 lines (1736 loc) · 75.5 KB
/
tools.py
File metadata and controls
2071 lines (1736 loc) · 75.5 KB
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
import collections
import io
import json
import os
import pathlib
import random
import time
import cv2
from tqdm import trange
from collections import defaultdict
from typing import Any, Callable, Union
from gym.spaces import Dict, Box, Discrete
import h5py
import numpy as np
import torch
from termcolor import cprint
from torch import distributions as torchd
from torch import nn
from torch.nn import functional as F
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm
from common.utils import get_dataset_path_and_meta_info, get_robocasa_dataset_path_and_env_meta, get_real_dataset_path_and_env_meta, get_real_classifier_dataset_path_and_env_meta
import dreamer.networks as networks
import pickle
import wandb
def to_np(x):
return x.detach().cpu().numpy()
def symlog(x):
return torch.sign(x) * torch.log(torch.abs(x) + 1.0)
def symexp(x):
return torch.sign(x) * (torch.exp(torch.abs(x)) - 1.0)
class RequiresGrad:
def __init__(self, model, always_frozen_layers=[]):
self._model = model
self._always_frozen_layers = always_frozen_layers
def __enter__(self):
for name, param in self._model.named_parameters():
if name in self._always_frozen_layers:
param.requires_grad_(False)
else:
param.requires_grad_(True)
def __exit__(self, *args):
self._model.requires_grad_(requires_grad=False)
class TimeRecording:
def __init__(self, comment):
self._comment = comment
def __enter__(self):
self._st = torch.cuda.Event(enable_timing=True)
self._nd = torch.cuda.Event(enable_timing=True)
self._st.record()
def __exit__(self, *args):
self._nd.record()
torch.cuda.synchronize()
print(self._comment, self._st.elapsed_time(self._nd) / 1000)
class DebugLogger:
def __init__(self, logdir, step):
self._logdir = logdir
self._last_step = None
self._last_time = None
self._scalars = {}
self._images = {}
self._videos = {}
self.step = step
# Initialize WandB
def config(self, config_dict):
pass
def scalar(self, name, value):
pass
def image(self, name, value):
pass
def video(self, name, value):
pass
def write(self, fps=False, step=False, fps_namespace="", print_cli=True):
pass
def _compute_fps(self, step):
pass
def offline_scalar(self, name, value, step):
pass
def offline_video(self, name, value, step):
pass
class Logger:
def __init__(self, logdir, step , name):
self._logdir = logdir
self._last_step = None
self._last_time = None
self._scalars = {}
self._images = {}
self._videos = {}
self.step = step
name = name + '_' + str(logdir).split('/')[-2] + '_' + str(logdir).split('/')[-1]
# Initialize WandB
wandb.init(project="failure_prediction", config={"logdir": str(logdir)}, name=name)
def config(self, config_dict):
# Convert PosixPath objects to strings
config_dict = {
k: str(v) if isinstance(v, pathlib.PosixPath) else v
for k, v in config_dict.items()
}
# Log the config
wandb.config.update(config_dict)
def scalar(self, name, value):
self._scalars[name] = float(value)
def image(self, name, value):
self._images[name] = np.array(value)
def video(self, name, value):
self._videos[name] = np.array(value)
def write(self, fps=False, step=False, fps_namespace="", print_cli=True):
if not step:
step = self.step
scalars = list(self._scalars.items())
if fps:
fps_str = fps_namespace + "fps"
scalars.append((fps_str, self._compute_fps(step)))
if print_cli:
print(f"[{step}]", " / ".join(f"{k} {v:.1f}" for k, v in scalars))
# Log metrics to WandB
metrics = {"step": step, **dict(scalars)}
wandb.log(metrics, step=step)
for name, value in self._images.items():
# Log images to WandB
if np.shape(value)[0] == 3:
value = np.transpose(value, (1, 2, 0))
wandb.log({name: [wandb.Image(value, caption=name)]}, step=step)
for name, value in self._videos.items():
name = name if isinstance(name, str) else name.decode("utf-8")
if np.issubdtype(value.dtype, np.floating):
value = np.clip(255 * value, 0, 255).astype(np.uint8)
B, T, H, W, C = value.shape
value = value.transpose(1, 4, 2, 0, 3).reshape((1, T, C, H, B * W))
# Log videos to WandB
wandb.log({name: wandb.Video(value, fps=16, format="mp4")}, step=step)
self._scalars = {}
self._images = {}
self._videos = {}
def _compute_fps(self, step):
if self._last_step is None:
self._last_time = time.time()
self._last_step = step
return 0
steps = step - self._last_step
duration = time.time() - self._last_time
self._last_time += duration
self._last_step = step
return steps / duration
def offline_scalar(self, name, value, step):
# Log scalar metrics to WandB
wandb.log({f"scalars/{name}": value}, step=step)
def offline_video(self, name, value, step):
if np.issubdtype(value.dtype, np.floating):
value = np.clip(255 * value, 0, 255).astype(np.uint8)
B, T, H, W, C = value.shape
value = value.transpose(1, 4, 2, 0, 3).reshape((1, T, C, H, B * W))
# Log videos to WandB
wandb.log({name: wandb.Video(value, fps=16, format="mp4")}, step=step)
def merge_two_dicts_no_relabel(cache1, cache2):
"""
Merges two cache dictionaries without relabeling the trajectories.
Args:
cache1 (dict): The main cache dictionary.
cache2 (dict): The cache dictionary to be merged into cache1.
Returns:
cache1 (dict): Updated cache1 containing both the original and new trajectories.
"""
# Add trajectories from cache2 to cache1, with failure label (0)
last_key = int(list(cache1.keys())[-1].split('_')[-1])
for i, key in enumerate(cache2.keys()):
new_key = f"exp_traj_{i + last_key+1}"
cache1[new_key] = cache2[key].copy() # Copy the trajectory to avoid mutation
return cache1
def merge_two_cache_dicts(cache1, cache2):
"""
Merges two cache dictionaries and assigns labels for success (1) and failure (0).
Args:
cache1 (dict): The main cache dictionary with trajectories labeled as success (1).
cache2 (dict): The cache dictionary to be merged into cache1 with trajectories labeled as failure (0).
Returns:
cache1 (dict): Updated cache1 containing both the original and new trajectories, with appropriate labels.
"""
# Add labels for success (1) in cache1
for key in cache1.keys():
## create 1 label as the same length of the other elements
cache1[key]['label'] = np.ones( cache1[key]['is_first'].shape)# Label success as 1
# Add trajectories from cache2 to cache1, with failure label (0)
last_key = int(list(cache1.keys())[-1].split('_')[-1])
for i, key in enumerate(cache2.keys()):
new_key = f"exp_traj_{i + last_key+1}"
cache1[new_key] = cache2[key].copy() # Copy the trajectory to avoid mutation
cache1[new_key]['label'] = np.zeros( cache2[key]['is_first'].shape) # Label failure as 0
return cache1
def fill_expert_dataset_real_data(config, cache, is_val_set=False, padding=None):
env_name = config.task.split("_", 1)[0]
sample_freq = config.sample_freq
selected_obs_keys = config.obs_keys
env_names = [env_name]
# Initialize extra info to return
norm_dict = None
state_dim = None
action_dim = None
total_id = 0
for env_name_id, env_name in enumerate(env_names):
## load the dataset path and the env meta
dataset_path, _ = get_real_dataset_path_and_env_meta(
env_id=env_name,
config = config,
done_mode=config.done_mode,
)
f = h5py.File(dataset_path, "r")
## get the dir of dataset_path
dataset_dir = os.path.dirname(dataset_path)
# read the norm_dict
with open(os.path.join(dataset_dir, f'norm_dict_{config.action_type}.json'), 'r') as file:
norm_dict = json.load(file)
## make the values of the norm_dict to be np.array
for key in norm_dict.keys():
norm_dict[key] = np.array(norm_dict[key])
demos = list(f["data"].keys())
inds = np.argsort([int(elem[5:]) for elem in demos])
demos = [demos[i] for i in inds]
# if is_val_set, we don't fill the first num_exp_trajs which are used for training
config.num_exp_trajs = (
len(demos) if config.num_exp_trajs == -1 else config.num_exp_trajs
)
if is_val_set:
if config.num_exp_trajs >= len(demos):
print('not enough expert data for val')
burn_in_trajs = 0 if is_val_set else 0
else:
burn_in_trajs = config.num_exp_trajs if is_val_set else 0
else:
burn_in_trajs = config.num_exp_trajs if is_val_set else 0
num_fill_trajs = (
min(len(demos), config.num_exp_trajs + config.validation_mse_trajs)
if is_val_set
else config.num_exp_trajs
)
obs_keys = f['data'][demos[0]]['obs'].keys()
pixel_keys = sorted([key for key in obs_keys if "image" in key and key in selected_obs_keys])
state_keys = config.state_keys
# Initialize norm_dict if it is None
if norm_dict is None:
# Read ob_dim and ac_dim from the first datapoint in the first demo
first_demo = f["data"][demos[0]]
ob_dim = 0
for key in state_keys:
ob_dim += np.prod(first_demo["obs"][key].shape[1:])
ac_dim = first_demo["actions"].shape[1]
print(f"Initizalizing norm_dict with ob_dim={ob_dim} and ac_dim={ac_dim}")
norm_dict = {
"ob_max": -np.inf * np.ones(ob_dim, dtype=np.float32),
"ob_min": np.inf * np.ones(ob_dim, dtype=np.float32),
"ac_max": -np.inf * np.ones(ac_dim, dtype=np.float32),
"ac_min": np.inf * np.ones(ac_dim, dtype=np.float32),
}
origin_shape = list(f["data"][demos[0]]["actions_abs"].shape[1:])
action_space = Box(-1, 1, shape = tuple(origin_shape))
first_demo = f["data"][demos[0]]
# Set state_dim and action_dim
if state_dim is None:
state_dim = 0
for key in state_keys:
state_dim += np.prod(first_demo["obs"][key].shape[1:])
if action_dim is None:
## remove the last base + mode action because it is not used in the policy
## pos: 3dim, axis_angle: 3dim, gripper: 1dim, base: 4 dim, mode: 1 dim
action_dim = first_demo["actions_abs"].shape[1]
obs_space = {}
if config.action_type == 'delta':
action_key = "actions"
elif config.action_type == 'abs':
action_key = "actions_abs"
else:
raise ValueError('action_type should be either delta or abs')
for key in pixel_keys:
obs_space[key] = Box(0, 1, shape = f["data"][demos[0]]["obs"][key].shape[1:])
for key in state_keys:
obs_space[key] = Box(-1, 1, shape = f["data"][demos[0]]["obs"][key].shape[1:])
obs_space['is_terminal'] = Discrete(2)
obs_space['is_first'] = Discrete(2)
obs_space['is_last'] = Discrete(2)
obs_space['discount'] = Box(0, 1, shape = (1,))
obs_space['state'] = Box(-1, 1, shape = (state_dim,))
observation_space = Dict(obs_space)
for i, demo in tqdm(
enumerate(demos),
desc="Loading in expert data",
ncols=0,
leave=False,
total=num_fill_trajs,
):
if i < burn_in_trajs:
continue
elif i >= num_fill_trajs:
print('last demo index', demos[i])
break
traj = f["data"][demo]
label = f["data"][demo].attrs['label']
# Concat state keys to create "state" key
concat_state = []
for t in range(len(traj["obs"][pixel_keys[0]])):
curr_obs_state_vec = [traj["obs"][obs_key][t] for obs_key in state_keys]
curr_obs_state_vec = np.concatenate(
curr_obs_state_vec, dtype=np.float32
)
concat_state.append(curr_obs_state_vec)
# Stack Observations for State and Pixel Keys
stacked_obs = {}
stacked_obs["state"] = concat_state
for key in pixel_keys:
stacked_obs[key] = traj["obs"][key]
length = len(traj["obs"][pixel_keys[0]])
if length == 160 and env_name == 'GraspCup':
## for real data for cup, we only use part of the rollout after the first 41 steps
## for demonstrations, we use the entire rollout
ind_step = 41
else:
if hasattr(config, "classifier_filter") and config.classifier_filter == 'no_demo':
continue
ind_step = 0
cache[f'exp_traj_{total_id}_{ind_step}'] = {}
for key in pixel_keys:
obs_from_ind = np.array(traj["obs"][key])[ind_step::sample_freq]
## concatenate the obs[key][1] to the beginning of the list
if length == 160 and env_name == 'GraspCup':
obs_from_ind = np.concatenate([np.array(traj["obs"][key][1:2]), obs_from_ind], axis=0)
cache[f'exp_traj_{total_id}_{ind_step}'][key] = obs_from_ind
state_from_ind = stacked_obs["state"][ind_step::sample_freq]
if length == 160 and env_name == 'GraspCup':
state_from_ind = np.concatenate([np.array(stacked_obs["state"][1:2]), state_from_ind], axis=0)
## normalize the state
normalized_state = (state_from_ind - norm_dict["ob_min"]) / (norm_dict["ob_max"] - norm_dict["ob_min"])
normalized_state = 2 * normalized_state - 1
cache[f'exp_traj_{total_id}_{ind_step}']['state'] = normalized_state
subsample_actions = np.array(traj[action_key])[sample_freq -1+ind_step::sample_freq]
if (length+ind_step) % sample_freq != 0:
## add the last action to the end of the list
subsample_actions = np.concatenate([subsample_actions, np.array(traj[action_key][-1:])], axis=0)
if length == 160 and env_name == 'GraspCup':
subsample_actions = np.concatenate([np.array(traj[action_key][ind_step-1:ind_step]), subsample_actions], axis=0)
## normalize the actions based on ac_min, ac_max
normalized_actions = (subsample_actions - norm_dict["ac_min"]) / (norm_dict["ac_max"] - norm_dict["ac_min"])
normalized_actions = 2 * normalized_actions - 1
cache[f'exp_traj_{total_id}_{ind_step}']['action'] = normalized_actions #subsample_actions
size = subsample_actions.shape[0]
cache[f'exp_traj_{total_id}_{ind_step}']['discount'] = np.array([1]*size, dtype=np.float32)
cache[f'exp_traj_{total_id}_{ind_step}']['is_last'] = np.array([0] * size, dtype=np.bool_)
cache[f'exp_traj_{total_id}_{ind_step}']['is_terminal'] = np.array([0] * size, dtype=np.bool_)
cache[f'exp_traj_{total_id}_{ind_step}']['is_first'] = np.array([1] + [0]*(size-1), dtype=np.bool_)
## check if all the keys have the same length
for key in cache[f'exp_traj_{total_id}_{ind_step}']:
if len(cache[f'exp_traj_{total_id}_{ind_step}'][key]) != size:
wrong_length = len(cache[f'exp_traj_{total_id}_{ind_step}'][key])
print(f'key {key} has length {wrong_length} but should have length {size}')
raise ValueError(f'key {key} has length {wrong_length} but should have length {size}')
total_id += 1
if not is_val_set:
cprint(
f"Loading expert buffer with {config.num_exp_trajs} trajectories from {dataset_path}",
color="magenta",
attrs=["bold"],
)
else:
cprint(
f"Loading validation buffer with {config.validation_mse_trajs} trajectories from {dataset_path}",
color="magenta",
attrs=["bold"],
)
f.close()
return observation_space, action_space, norm_dict, state_dim, action_dim
def evaluate_mse_trajectories(agent_eval, expert_eps, final_config):
keys = list(expert_eps.keys()) # Convert keys to a list
total_mse = 0
for i in range(final_config.validation_mse_trajs):
data_traj_i = expert_eps[keys[i]]
# convert data_traj_i from dict of lists to dict of np arrays (stacked)
data_traj_i_keys = list(data_traj_i.keys())
for key in data_traj_i_keys:
data_traj_i[key] = np.stack(data_traj_i[key])
# get mse for trajectory i
traj_mse = get_agent_mse_batchlen(agent_eval, data_traj_i)
total_mse += traj_mse
total_mse /= final_config.validation_mse_trajs
return total_mse
def get_agent_mse_batchlen(agent_eval, data_traj_i):
# data_traj_i is a dict of np arrays, each with shape (len_traj, ...)
len_traj = len(data_traj_i["action"])
avg_mse = 0
agent_eval.reset()
for j in range(len_traj):
data_j = {k: v[j] for k, v in data_traj_i.items()}
if data_j["is_first"]:
agent_eval.reset()
action = agent_eval.get_action(data_j)
true_action = data_j["action"]
mse = np.mean((action["action"] - true_action) ** 2)
avg_mse += mse
avg_mse /= len_traj
return avg_mse
def add_to_cache(cache, _id, transition):
if _id not in cache:
cache[_id] = dict()
for key, val in transition.items():
cache[_id][key] = [convert(val)]
else:
for key, val in transition.items():
if key not in cache[_id]:
# fill missing data(action, etc.) at second time
cache[_id][key] = [convert(0 * val)]
cache[_id][key].append(convert(val))
else:
cache[_id][key].append(convert(val))
def erase_over_episodes(cache, dataset_size):
step_in_dataset = 0
for key, ep in reversed(sorted(cache.items(), key=lambda x: x[0])):
if (
not dataset_size
or step_in_dataset + (len(ep["reward"]) - 1) <= dataset_size
):
step_in_dataset += len(ep["reward"]) - 1
else:
del cache[key]
return step_in_dataset
def convert(value, precision=32):
value = np.array(value)
if np.issubdtype(value.dtype, np.floating):
dtype = {16: np.float16, 32: np.float32, 64: np.float64}[precision]
elif np.issubdtype(value.dtype, np.signedinteger):
dtype = {16: np.int16, 32: np.int32, 64: np.int64}[precision]
elif np.issubdtype(value.dtype, np.uint8):
dtype = np.uint8
elif np.issubdtype(value.dtype, bool):
dtype = bool
else:
raise NotImplementedError(value.dtype)
return value.astype(dtype)
def save_episodes(directory, episodes):
directory = pathlib.Path(directory).expanduser()
directory.mkdir(parents=True, exist_ok=True)
for filename, episode in episodes.items():
length = len(episode["reward"])
filename = directory / f"{filename}-{length}.npz"
with io.BytesIO() as f1:
np.savez_compressed(f1, **episode)
f1.seek(0)
with filename.open("wb") as f2:
f2.write(f1.read())
return True
def from_generator(generator, batch_size):
while True:
batch = []
for _ in range(batch_size):
try:
batch.append(next(generator))
except StopIteration:
raise StopIteration
data = {}
for key in batch[0].keys():
data[key] = []
for i in range(batch_size):
data[key].append(batch[i][key])
data[key] = np.stack(data[key], 0)
yield data
def from_eval_generator(generator, batch_size):
"""
Takes a generator and yields batches of data until the generator is exhausted.
"""
while True:
batch = []
for _ in range(batch_size):
try:
new_batch = next(generator)
except RuntimeError:
# If the generator is exhausted, return the partial batch if it exists
if batch:
data = {}
for key in batch[0].keys():
data[key] = []
for i in range(len(batch)):
data[key].append(batch[i][key])
data[key] = np.stack(data[key], 0)
yield data
return # Stop when the generator is fully exhausted
batch.append(new_batch)
# Organize the batch into data dictionary (similar structure as single sample)
data = {}
for key in batch[0].keys():
data[key] = []
for i in range(batch_size):
data[key].append(batch[i][key])
data[key] = np.stack(data[key], 0)
yield data
# def from_traj_generator(generator, batch_size):
class EpisodeSampler:
def __init__(self, episodes, length, seed=0):
self.episodes = episodes
self.length = length
self.episode_keys = list(episodes.keys()) # List of episode keys
self.episode_positions = {key: 0 for key in self.episode_keys} # Position within each episode
self.episode_idx = 0 # Current episode index
self.np_random = np.random.RandomState(seed)
def sample_episodes(self):
"""
Iteratively sample through all episodes without resetting until the end.
"""
while self.episode_idx < len(self.episode_keys):
episode_key = self.episode_keys[self.episode_idx]
episode = self.episodes[episode_key]
total = len(next(iter(episode.values())))
if total < 2:
self.episode_idx += 1 # Skip empty or small episodes
continue
start_index = self.episode_positions[episode_key]
end_index = min(start_index + self.length, total)
# Collect transitions from the current episode
ret = {k: v[start_index:end_index].copy() for k, v in episode.items() if "log_" not in k}
if "is_first" in ret:
ret["is_first"][0] = True
# Update the position in the current episode
self.episode_positions[episode_key] = end_index # start_index +1 #
# If the current episode is exhausted, move to the next episode
if end_index + self.length >= total:
# if start_index + 1 + self.length >= total:
self.episode_idx += 1
yield ret
# When all episodes are exhausted, stop iteration
raise StopIteration("All episodes have been sampled.")
class EpisodeSpecialSampler(EpisodeSampler):
def __init__(self, episodes, length, seed=0):
self.episodes = episodes
self.length = length
self.episode_keys = ['exp_traj_100','exp_traj_101','exp_traj_102', 'exp_traj_103','exp_traj_104', 'exp_traj_105', 'exp_traj_106', 'exp_traj_107','exp_traj_108', 'exp_traj_109'] #',#'exp_traj_106'] #'exp_traj_101', #'exp_traj_104'] #list(episodes.keys()) # List of episode keys
self.episode_positions = dict(exp_traj_100 = 800, exp_traj_101 = 1400, exp_traj_102=880, exp_traj_103=420, exp_traj_104= 700,exp_traj_105 = 600,exp_traj_106=1350, exp_traj_107 = 420, exp_traj_108 = 900,exp_traj_109=1400)#exp_traj_104 =900 ) #{key: 880 for key in self.episode_keys}#{key: 0 for key in self.episode_keys} # Position within each episode
self.episode_idx =0 # 0 # Current episode index
self.np_random = np.random.RandomState(seed)
# for key in self.episode_keys:
# episode = self.episodes[key]
# ## save the trajectory as a video
# img_sequence = episode["robot0_agentview_front_image"]
# img_with_text = []
# for num,img in enumerate(img_sequence):
# image_height, image_width, _ = img.shape
# # Define font, scale, color, and thickness
# font = cv2.FONT_HERSHEY_SIMPLEX
# font_scale = 0.4
# font_color = (255, 255, 255) # White color
# font_thickness = 1
# text = f"Frame: {num}"
# # Calculate text size and position (centered at the bottom)
# text_size = cv2.getTextSize(text, font, font_scale, font_thickness)[0]
# text_x = (image_width - text_size[0]) // 2
# text_y = image_height - 10 # 10 pixels from the bottom
# frame_with_text = cv2.putText(img, text, (text_x, text_y), font, font_scale, font_color, font_thickness, cv2.LINE_AA)
# img_with_text.append(frame_with_text)
# ## use imageio to save the video
# imageio.mimsave(f'./failure_{key}.gif', img_with_text, fps=30)
class EvalEpisodeSampler(EpisodeSampler):
def __init__(self):
self.episode_id = 0
def sample_partial_episodes(self, episodes, length, seed=0, max_length=99, mode='last', start_index = 0):
"""
This function samples part of each episodes from a given dataset of episodes. It ensures the `is_first`
flag is correctly set for each episode.
Args:
episodes (dict): Dictionary containing multiple episodes. Each episode is a dictionary
with keys for observations, actions, etc.
seed (int): Random seed for sampling episodes.
Yields:
dict: A dictionary containing the sampled full episode data, with `is_first` handled properly.
"""
# np_random = np.random.RandomState(seed)
while True:
# Randomly select an episode from the dataset
# episode_key = np_random.choice(list(episodes.keys()))
try :
episode_key = list(episodes.keys())[self.episode_id]
self.episode_id += 1
except:
raise StopIteration
episode = episodes[episode_key]
## save actual length
actual_length = len(episode["is_first"].copy())
# print('actual length', actual_length)
## The original size is (B, T, D), now we need to shape into (B*T/16, 16, D)
## get the folded size of the episode
# Copy the full episode data
# ret = {k: v.copy() for k, v in episode.items() if "log_" not in k}
## copy the full episode data and pad the item to max_length, item can be obs, action, etc.
## item can be 1dim array, 2 dim array, 3 dim array, etc.
if actual_length > max_length:
actual_length = max_length
ret = {k: v[:max_length] for k, v in episode.items() if "log_" not in k}
ret['actual_length'] = max_length * np.ones(max_length, dtype=np.int32)
else:
if mode == 'zero':
ret = {k: np.pad(v, [(0, max_length - len(v))] + [(0, 0)] * (v[0].ndim ),
mode='constant') for k, v in episode.items() if "log_" not in k}
ret['actual_length'] = actual_length * np.ones(max_length, dtype=np.int32)
elif mode == 'last':
ret = {k: np.pad(v, [(0, max_length - len(v))] + [(0, 0)] * (v[0].ndim ),
mode='edge') for k, v in episode.items() if "log_" not in k}
ret['action'][actual_length:, :6] = 0 ## zero out the first 6(pos + axis angle) action for the padded part
ret['actual_length'] = max_length * np.ones(max_length, dtype=np.int32)
else:
raise NotImplementedError
## for each key in ret, only keep the part of the episode from start_index
for key in ret.keys():
ret[key] = ret[key][start_index:]
yield ret
class FullEpisodeSampler:
def __init__(self):
self.episode_index = 0
def sample_episodes_with_varied_length(self, episodes, length, seed =0, max_length=1500):
while True:
# Randomly select an episode from the dataset
# episode_key = np_random.choice(list(episodes.keys()))
# episode = episodes[episode_key]
try:
episode_key = list(episodes.keys())[self.episode_index]
except:
raise StopIteration
episode = episodes[episode_key]
# episode = next(iter(episodes.values()))
print('episode key', episode_key)
self.episode_index += 1
## save actual length
actual_length = len(episode["is_first"].copy())
## The original size is (B, T, D), now we need to shape into (B*T/16, 16, D)
## get the folded size of the episode
# Copy the full episode data
# ret = {k: v.copy() for k, v in episode.items() if "log_" not in k}
## copy the full episode data and pad the item to max_length, item can be obs, action, etc.
## item can be 1dim array, 2 dim array, 3 dim array, etc.
ret = {k: v for k, v in episode.items() if "log_" not in k}
# Ensure that the `is_first` key is set correctly for the entire episode
if "is_first" in ret and length < max_length:
## set every 16th element to True in ret["is_first"]
ret["is_first"][::length] = True
ret['actual_length'] = actual_length * np.ones(actual_length, dtype=np.int32)
yield ret
def sample_full_episodes(self, episodes, length, seed=0, max_length=1500, mode = 'last'):
"""
This function samples entire episodes from a given dataset of episodes. It ensures the `is_first`
flag is correctly set for each episode.
Args:
episodes (dict): Dictionary containing multiple episodes. Each episode is a dictionary
with keys for observations, actions, etc.
seed (int): Random seed for sampling episodes.
Yields:
dict: A dictionary containing the sampled full episode data, with `is_first` handled properly.
"""
# np_random = np.random.RandomState(seed)
while True:
# Randomly select an episode from the dataset
# episode_key = np_random.choice(list(episodes.keys()))
# episode = episodes[episode_key]
try:
episode_key = list(episodes.keys())[self.episode_index]
except:
raise StopIteration
episode = episodes[episode_key]
# episode = next(iter(episodes.values()))
print('episode key', episode_key)
self.episode_index += 1
## save actual length
actual_length = len(episode["is_first"].copy())
print('actual length', actual_length)
## The original size is (B, T, D), now we need to shape into (B*T/16, 16, D)
## get the folded size of the episode
# Copy the full episode data
# ret = {k: v.copy() for k, v in episode.items() if "log_" not in k}
## copy the full episode data and pad the item to max_length, item can be obs, action, etc.
## item can be 1dim array, 2 dim array, 3 dim array, etc.
if mode == 'zero':
ret = {k: np.pad(v, [(0, max_length - len(v))] + [(0, 0)] * (v[0].ndim ),
mode='constant') for k, v in episode.items() if "log_" not in k}
ret['actual_length'] = actual_length * np.ones(max_length, dtype=np.int32)
elif mode == 'last':
ret = {k: np.pad(v, [(0, max_length - len(v))] + [(0, 0)] * (v[0].ndim ),
mode='edge') for k, v in episode.items() if "log_" not in k}
ret['action'][actual_length:, :6] = 0 ## zero out the first 6(pos + axis angle) action for the padded part
ret['actual_length'] = max_length * np.ones(max_length, dtype=np.int32)
else:
raise NotImplementedError
##
# Ensure that the `is_first` key is set correctly for the entire episode
if "is_first" in ret and length < max_length:
## set every 16th element to True in ret["is_first"]
ret["is_first"][::length] = True
ret['actual_length'] = actual_length * np.ones(max_length, dtype=np.int32)
yield ret
def sample_full_episodes(episodes, length, seed=0, max_length=1500, mode='last'):
"""
This function samples entire episodes from a given dataset of episodes. It ensures the `is_first`
flag is correctly set for each episode.
Args:
episodes (dict): Dictionary containing multiple episodes. Each episode is a dictionary
with keys for observations, actions, etc.
seed (int): Random seed for sampling episodes.
Yields:
dict: A dictionary containing the sampled full episode data, with `is_first` handled properly.
"""
np_random = np.random.RandomState(seed)
while True:
# Randomly select an episode from the dataset
episode_key = np_random.choice(list(episodes.keys()))
episode = episodes[episode_key]
## save actual length
actual_length = len(episode["is_first"].copy())
print('actual length', actual_length)
## The original size is (B, T, D), now we need to shape into (B*T/16, 16, D)
## get the folded size of the episode
# Copy the full episode data
# ret = {k: v.copy() for k, v in episode.items() if "log_" not in k}
## copy the full episode data and pad the item to max_length, item can be obs, action, etc.
## item can be 1dim array, 2 dim array, 3 dim array, etc.
if mode == 'zero':
ret = {k: np.pad(v, [(0, max_length - len(v))] + [(0, 0)] * (v[0].ndim ),
mode='constant') for k, v in episode.items() if "log_" not in k}
ret['actual_length'] = actual_length * np.ones(max_length, dtype=np.int32)
elif mode == 'last':
ret = {k: np.pad(v, [(0, max_length - len(v))] + [(0, 0)] * (v[0].ndim ),
mode='edge') for k, v in episode.items() if "log_" not in k}
ret['action'][actual_length:, :6] = 0 ## zero out the first 6(pos + axis angle) action for the padded part
ret['actual_length'] = max_length * np.ones(max_length, dtype=np.int32)
else:
raise NotImplementedError
# Ensure that the `is_first` key is set correctly for the entire episode
if "is_first" in ret and length < max_length:
## set every 16th element to True in ret["is_first"]
ret["is_first"][::length] = True
yield ret
def sample_partial_episodes(episodes, length, seed=0, max_length=99, mode='last', start_index = 0):
"""
This function samples part of each episodes from a given dataset of episodes. It ensures the `is_first`
flag is correctly set for each episode.
Args:
episodes (dict): Dictionary containing multiple episodes. Each episode is a dictionary
with keys for observations, actions, etc.
seed (int): Random seed for sampling episodes.
Yields:
dict: A dictionary containing the sampled full episode data, with `is_first` handled properly.
"""
np_random = np.random.RandomState(seed)
while True:
# Randomly select an episode from the dataset
episode_key = np_random.choice(list(episodes.keys()))
# if isinstance(start_index, list):
# start_index = np_random.choice(start_index)
# max_length = start_index + length
episode = episodes[episode_key]
## save actual length
actual_length = len(episode["is_first"].copy())
# print('actual length', actual_length)
## The original size is (B, T, D), now we need to shape into (B*T/16, 16, D)
## get the folded size of the episode
# Copy the full episode data
# ret = {k: v.copy() for k, v in episode.items() if "log_" not in k}
## copy the full episode data and pad the item to max_length, item can be obs, action, etc.
## item can be 1dim array, 2 dim array, 3 dim array, etc.
if actual_length > max_length:
actual_length = max_length
ret = {k: v[:max_length] for k, v in episode.items() if "log_" not in k}
ret['actual_length'] = max_length * np.ones(max_length, dtype=np.int32)
else:
if mode == 'zero':
ret = {k: np.pad(v, [(0, max_length - len(v))] + [(0, 0)] * (v[0].ndim ),
mode='constant') for k, v in episode.items() if "log_" not in k}
ret['actual_length'] = actual_length * np.ones(max_length, dtype=np.int32)
elif mode == 'last':
ret = {k: np.pad(v, [(0, max_length - len(v))] + [(0, 0)] * (v[0].ndim ),
mode='edge') for k, v in episode.items() if "log_" not in k}
ret['action'][actual_length:, :6] = 0 ## zero out the first 6(pos + axis angle) action for the padded part
ret['actual_length'] = max_length * np.ones(max_length, dtype=np.int32)
else:
raise NotImplementedError
## for each key in ret, only keep the part of the episode from start_index
for key in ret.keys():
ret[key] = ret[key][start_index:max_length]
# Ensure that the `is_first` key is set correctly for the entire episode
# if "is_first" in ret and length < max_length:
## set every 16th element to True in ret["is_first"]
# ret["is_first"][::length] = True
yield ret
def sample_episodes(episodes, length, seed=0):
np_random = np.random.RandomState(seed)
while True:
size = 0
ret = None
p = np.array(
[len(next(iter(episode.values()))) for episode in episodes.values()]
)
p = p / np.sum(p)
# num_ep = 0
# episodes_keys = list(episodes.keys())
# key = next(iter(episodes_keys))
while size < length:
episode = np_random.choice(list(episodes.values()), p=p)
# episode = episodes[episodes_keys[num_ep]]
# num_ep += 1
total = len(next(iter(episode.values())))
# make sure at least one transition included
if total < 2:
continue
if not ret:
index = int(np_random.randint(0, total - 1))
# index = 0
ret = {
k: v[index : min(index + length, total)].copy()
for k, v in episode.items()
if "log_" not in k
}
if "is_first" in ret:
ret["is_first"][0] = True
else:
# 'is_first' comes after 'is_last'
index = 0
possible = length - size
ret = {
k: np.append(
ret[k], v[index : min(index + possible, total)].copy(), axis=0
)
for k, v in episode.items()
if "log_" not in k
}