rli14's picture
rsm_rise code snapshot (HF_PUSH_ALL) (part 4)
06df946 verified
Raw History Blame Contribute Delete
60.7 kB
""" 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
"""
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)