import copy import os, sys import random import uuid import pickle from dataclasses import asdict, dataclass from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Tuple, Union import d4rl import gym import numpy as np import pyrallis import torch import torch.nn as nn import torch.nn.functional as F import wandb from torch.distributions import Normal from torch.optim.lr_scheduler import CosineAnnealingLR from torch import autograd import imageio import yaml TensorBatch = List[torch.Tensor] DEFAULT_DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu' @dataclass class TrainConfig: ############################# ######### Experiment ######## ############################# percent_expert: float = 0.1 env_1: str = "halfcheetah-random-v2" env_2: str = "halfcheetah-expert-v2" file_name: str = "halfcheetah-10%-expert-random.npy" def get_trajectory_indices(terminals): # Finds the indices where each trajectory begins and ends end_indices = np.where(terminals)[0] if len(end_indices) == 0 or end_indices[-1] != len(terminals) - 1: # Ensure the last index is included as an end if not already end_indices = np.append(end_indices, len(terminals) - 1) start_indices = np.append(0, end_indices[:-1] + 1) return list(zip(start_indices, end_indices + 1)) def modify_dataset(dataset, expert_dataset): # Assuming terminals are stored as boolean where True indicates the end of a trajectory trajectory_indices = get_trajectory_indices(dataset['terminals'] + dataset['timeouts']) expert_trajectory_indices = get_trajectory_indices(expert_dataset['terminals'] + expert_dataset['timeouts']) # Determine how many trajectories to replace trajectories_to_replace = int(config.percent_expert * len(trajectory_indices)) # Handle the case when there are no trajectories to replace if trajectories_to_replace == 0 or len(expert_trajectory_indices) == 0: print("No trajectories to replace or no expert trajectories available.") trajectories_to_replace = 0 indices_replace_map = {} else: # Randomly choose trajectories to replace indices_to_replace = np.random.choice(len(trajectory_indices), trajectories_to_replace, replace=False) expert_indices = np.random.choice(len(expert_trajectory_indices), trajectories_to_replace, replace=False) # Create a mapping from dataset trajectory indices to expert trajectory indices indices_replace_map = dict(zip(indices_to_replace, expert_indices)) mixed_dataset = {} keys = ['observations', 'actions', 'next_observations', 'rewards', 'terminals'] # Replacement process for key in keys: mixed_data = [] for i in range(len(trajectory_indices)): if i in indices_replace_map: # Use expert trajectory expert_traj_idx = indices_replace_map[i] expert_start, expert_end = expert_trajectory_indices[expert_traj_idx] data_to_append = expert_dataset[key][expert_start:expert_end] else: # Use original dataset trajectory start, end = trajectory_indices[i] data_to_append = dataset[key][start:end] mixed_data.append(data_to_append) if mixed_data: # Concatenate all data for the current key mixed_dataset[key] = np.concatenate(mixed_data, axis=0) else: # If mixed_data is empty, create an empty array with the appropriate shape mixed_dataset[key] = np.array([], dtype=dataset[key].dtype) # Combine 'init_states' from both datasets mixed_dataset['init_states'] = np.concatenate([dataset['init_states'], expert_dataset['init_states']], axis=0) return mixed_dataset def modify_dataset_direct(dataset, expert_dataset): mixed_dataset = {} keys = ['observations', 'actions', 'next_observations', 'rewards', 'terminals'] # replace config.percent_expert of the dataset with expert_dataset for key in keys: mixed_data = [] for i in reversed(range(len(dataset[key]))): if i > len(expert_dataset[key]) - int(config.percent_expert * len(dataset[key])): data_to_append = expert_dataset[key][i - len(dataset[key]) + 1] else: data_to_append = dataset[key][i] mixed_data.append(data_to_append) if mixed_data: # Concatenate all data for the current key mixed_dataset[key] = np.array(mixed_data) else: # If mixed_data is empty, create an empty array with the appropriate shape mixed_dataset[key] = np.array([], dtype=dataset[key].dtype) # Combine 'init_states' from both datasets mixed_dataset['init_states'] = np.concatenate([dataset['init_states'], expert_dataset['init_states']], axis=0) mixed_dataset['transition_ids'] = np.arange(len(mixed_dataset["observations"])) return mixed_dataset def qlearning_dataset(env, dataset=None, terminate_on_end=False, **kwargs): if dataset is None: dataset = env.get_dataset(**kwargs) init_obs_index = np.unique(np.concatenate((np.where(dataset['terminals'])[0][:-1] + 1, np.where(dataset['timeouts'])[0][:-1] + 1))) init_obs_ = dataset['observations'][init_obs_index] N = dataset['rewards'].shape[0] obs_ = [] next_obs_ = [] action_ = [] reward_ = [] done_ = [] timeout_ = [] task_horizon = [] # The newer version of the dataset adds an explicit # timeouts field. Keep old method for backwards compatability. use_timeouts = False if 'timeouts' in dataset: use_timeouts = True episode_step = 0 for i in range(N-1): obs = dataset['observations'][i].astype(np.float32) new_obs = dataset['observations'][i+1].astype(np.float32) action = dataset['actions'][i].astype(np.float32) reward = dataset['rewards'][i].astype(np.float32) done_bool = bool(dataset['terminals'][i]) timeout_bool = bool(dataset['timeouts'][i]) if use_timeouts: final_timestep = dataset['timeouts'][i] else: final_timestep = (episode_step == env._max_episode_steps - 1) if (not terminate_on_end) and final_timestep: # Skip this transition and don't apply terminals on the last step of an episode episode_step = 0 continue if done_bool or final_timestep: episode_step = 0 obs_.append(obs) next_obs_.append(new_obs) action_.append(action) reward_.append(reward) done_.append(done_bool) timeout_.append(timeout_bool) task_horizon.append(episode_step) episode_step += 1 # add in return for each episode return_list = [0] length = [0] for i in range(len(done_)): return_list[-1] += reward_[i] length[-1] += 1 if done_[i] or timeout_[i]: return_list.append(0) length.append(0) count = 0 data_return_list = [0] * len(done_) for i in range(len(done_)): data_return_list[i] = return_list[count] if done_[i] or timeout_[i]: count +=1 data_return_list = env.get_normalized_score(np.array(data_return_list)) * 100.0 data_return_list = np.array(data_return_list) epi_obs = [] epi_n_obs = [] epi_terminals = [] epi_rewards = [] epi_returns = [] epi_actions = [] obs = [] n_obs = [] terminals = [] rewards = [] actions = [] # task_horizon = [] task_step = 0 for i in range(len(done_)): obs.append(obs_[i]) n_obs.append(next_obs_[i]) terminals.append(done_[i]) rewards.append(reward_[i]) actions.append(action_[i]) # task_horizon.append(task_step) task_step += 1 if done_[i] or timeout_[i]: epi_obs.append(np.array(obs)) epi_n_obs.append(np.array(n_obs)) epi_terminals.append(np.array(terminals)) epi_rewards.append(np.array(rewards)) epi_returns.append(data_return_list[i]) epi_actions.append(np.array(actions)) obs = [] n_obs = [] terminals = [] rewards = [] actions = [] task_step = 0 transition_ids = np.arange(len(obs_)) return { 'observations': np.array(obs_), 'actions': np.array(action_), 'next_observations': np.array(next_obs_), 'rewards': np.array(reward_), 'terminals': np.array(done_), 'timeouts': np.array(timeout_), 'init_states': np.array(init_obs_), 'transition_ids': transition_ids, 'returns': data_return_list, 'epi_obs': np.array(epi_obs, dtype=object), 'epi_n_obs': np.array(epi_n_obs, dtype=object), 'epi_terminals': np.array(epi_terminals, dtype=object), 'epi_rewards': np.array(epi_rewards, dtype=object), 'epi_returns': np.array(epi_returns, dtype=object), 'epi_actions': np.array(epi_actions, dtype=object), 'task_horizon':np.array(task_horizon, dtype=object), } def create_dataset(): env = gym.make(config.env_1) expert_env = gym.make(config.env_2) dataset = qlearning_dataset(env) expert_dataset = qlearning_dataset(expert_env) # mixed_dataset = modify_dataset(dataset, expert_dataset) mixed_dataset = modify_dataset_direct(dataset, expert_dataset) with open(config.file_name, 'wb') as f: pickle.dump(mixed_dataset, f) if __name__ == "__main__": config = pyrallis.parse(config_class=TrainConfig) create_dataset()