ShuoZheLi commited on
Commit
e24d8a8
·
verified ·
1 Parent(s): aab0bfe

dataset and generate script

Browse files
create_dataset.py ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import os, sys
3
+ import random
4
+ import uuid
5
+ import pickle
6
+ from dataclasses import asdict, dataclass
7
+ from pathlib import Path
8
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
9
+ import d4rl
10
+ import gym
11
+ import numpy as np
12
+ import pyrallis
13
+ import torch
14
+ import torch.nn as nn
15
+ import torch.nn.functional as F
16
+ import wandb
17
+ from torch.distributions import Normal
18
+ from torch.optim.lr_scheduler import CosineAnnealingLR
19
+ from torch import autograd
20
+
21
+ import imageio
22
+ import yaml
23
+
24
+ TensorBatch = List[torch.Tensor]
25
+ DEFAULT_DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
26
+
27
+ @dataclass
28
+ class TrainConfig:
29
+ #############################
30
+ ######### Experiment ########
31
+ #############################
32
+ percent_expert: float = 0.1
33
+ env_1: str = "halfcheetah-random-v2"
34
+ env_2: str = "halfcheetah-expert-v2"
35
+ file_name: str = "halfcheetah-10%-expert-random.npy"
36
+
37
+ def get_trajectory_indices(terminals):
38
+ # Finds the indices where each trajectory begins and ends
39
+ end_indices = np.where(terminals)[0]
40
+ if len(end_indices) == 0 or end_indices[-1] != len(terminals) - 1:
41
+ # Ensure the last index is included as an end if not already
42
+ end_indices = np.append(end_indices, len(terminals) - 1)
43
+ start_indices = np.append(0, end_indices[:-1] + 1)
44
+ return list(zip(start_indices, end_indices + 1))
45
+
46
+ def modify_dataset(dataset, expert_dataset):
47
+ # Assuming terminals are stored as boolean where True indicates the end of a trajectory
48
+ trajectory_indices = get_trajectory_indices(dataset['terminals'] + dataset['timeouts'])
49
+ expert_trajectory_indices = get_trajectory_indices(expert_dataset['terminals'] + expert_dataset['timeouts'])
50
+
51
+ # Determine how many trajectories to replace
52
+ trajectories_to_replace = int(config.percent_expert * len(trajectory_indices))
53
+
54
+ # Handle the case when there are no trajectories to replace
55
+ if trajectories_to_replace == 0 or len(expert_trajectory_indices) == 0:
56
+ print("No trajectories to replace or no expert trajectories available.")
57
+ trajectories_to_replace = 0
58
+ indices_replace_map = {}
59
+ else:
60
+ # Randomly choose trajectories to replace
61
+ indices_to_replace = np.random.choice(len(trajectory_indices), trajectories_to_replace, replace=False)
62
+ expert_indices = np.random.choice(len(expert_trajectory_indices), trajectories_to_replace, replace=False)
63
+
64
+ # Create a mapping from dataset trajectory indices to expert trajectory indices
65
+ indices_replace_map = dict(zip(indices_to_replace, expert_indices))
66
+
67
+ mixed_dataset = {}
68
+ keys = ['observations', 'actions', 'next_observations', 'rewards', 'terminals']
69
+
70
+ # Replacement process
71
+ for key in keys:
72
+ mixed_data = []
73
+ for i in range(len(trajectory_indices)):
74
+ if i in indices_replace_map:
75
+ # Use expert trajectory
76
+ expert_traj_idx = indices_replace_map[i]
77
+ expert_start, expert_end = expert_trajectory_indices[expert_traj_idx]
78
+ data_to_append = expert_dataset[key][expert_start:expert_end]
79
+ else:
80
+ # Use original dataset trajectory
81
+ start, end = trajectory_indices[i]
82
+ data_to_append = dataset[key][start:end]
83
+ mixed_data.append(data_to_append)
84
+ if mixed_data:
85
+ # Concatenate all data for the current key
86
+ mixed_dataset[key] = np.concatenate(mixed_data, axis=0)
87
+ else:
88
+ # If mixed_data is empty, create an empty array with the appropriate shape
89
+ mixed_dataset[key] = np.array([], dtype=dataset[key].dtype)
90
+
91
+ # Combine 'init_states' from both datasets
92
+ mixed_dataset['init_states'] = np.concatenate([dataset['init_states'], expert_dataset['init_states']], axis=0)
93
+
94
+ return mixed_dataset
95
+
96
+ def modify_dataset_direct(dataset, expert_dataset):
97
+ mixed_dataset = {}
98
+ keys = ['observations', 'actions', 'next_observations', 'rewards', 'terminals']
99
+ # replace config.percent_expert of the dataset with expert_dataset
100
+ for key in keys:
101
+ mixed_data = []
102
+ for i in reversed(range(len(dataset[key]))):
103
+ if i > len(expert_dataset[key]) - int(config.percent_expert * len(dataset[key])):
104
+ data_to_append = expert_dataset[key][i - len(dataset[key]) + 1]
105
+ else:
106
+ data_to_append = dataset[key][i]
107
+ mixed_data.append(data_to_append)
108
+ if mixed_data:
109
+ # Concatenate all data for the current key
110
+ mixed_dataset[key] = np.array(mixed_data)
111
+ else:
112
+ # If mixed_data is empty, create an empty array with the appropriate shape
113
+ mixed_dataset[key] = np.array([], dtype=dataset[key].dtype)
114
+
115
+ # Combine 'init_states' from both datasets
116
+ mixed_dataset['init_states'] = np.concatenate([dataset['init_states'], expert_dataset['init_states']], axis=0)
117
+
118
+ mixed_dataset['transition_ids'] = np.arange(len(mixed_dataset["observations"]))
119
+
120
+ return mixed_dataset
121
+
122
+
123
+ def qlearning_dataset(env, dataset=None, terminate_on_end=False, **kwargs):
124
+ if dataset is None:
125
+ dataset = env.get_dataset(**kwargs)
126
+
127
+ init_obs_index = np.unique(np.concatenate((np.where(dataset['terminals'])[0][:-1] + 1, np.where(dataset['timeouts'])[0][:-1] + 1)))
128
+ init_obs_ = dataset['observations'][init_obs_index]
129
+
130
+ N = dataset['rewards'].shape[0]
131
+ obs_ = []
132
+ next_obs_ = []
133
+ action_ = []
134
+ reward_ = []
135
+ done_ = []
136
+ timeout_ = []
137
+ task_horizon = []
138
+
139
+ # The newer version of the dataset adds an explicit
140
+ # timeouts field. Keep old method for backwards compatability.
141
+ use_timeouts = False
142
+ if 'timeouts' in dataset:
143
+ use_timeouts = True
144
+
145
+ episode_step = 0
146
+ for i in range(N-1):
147
+ obs = dataset['observations'][i].astype(np.float32)
148
+ new_obs = dataset['observations'][i+1].astype(np.float32)
149
+ action = dataset['actions'][i].astype(np.float32)
150
+ reward = dataset['rewards'][i].astype(np.float32)
151
+ done_bool = bool(dataset['terminals'][i])
152
+ timeout_bool = bool(dataset['timeouts'][i])
153
+
154
+ if use_timeouts:
155
+ final_timestep = dataset['timeouts'][i]
156
+ else:
157
+ final_timestep = (episode_step == env._max_episode_steps - 1)
158
+ if (not terminate_on_end) and final_timestep:
159
+ # Skip this transition and don't apply terminals on the last step of an episode
160
+ episode_step = 0
161
+ continue
162
+ if done_bool or final_timestep:
163
+ episode_step = 0
164
+
165
+ obs_.append(obs)
166
+ next_obs_.append(new_obs)
167
+ action_.append(action)
168
+ reward_.append(reward)
169
+ done_.append(done_bool)
170
+ timeout_.append(timeout_bool)
171
+ task_horizon.append(episode_step)
172
+ episode_step += 1
173
+
174
+
175
+ # add in return for each episode
176
+ return_list = [0]
177
+ length = [0]
178
+ for i in range(len(done_)):
179
+ return_list[-1] += reward_[i]
180
+ length[-1] += 1
181
+ if done_[i] or timeout_[i]:
182
+ return_list.append(0)
183
+ length.append(0)
184
+
185
+ count = 0
186
+ data_return_list = [0] * len(done_)
187
+ for i in range(len(done_)):
188
+ data_return_list[i] = return_list[count]
189
+ if done_[i] or timeout_[i]:
190
+ count +=1
191
+
192
+ data_return_list = env.get_normalized_score(np.array(data_return_list)) * 100.0
193
+ data_return_list = np.array(data_return_list)
194
+
195
+
196
+ epi_obs = []
197
+ epi_n_obs = []
198
+ epi_terminals = []
199
+ epi_rewards = []
200
+ epi_returns = []
201
+ epi_actions = []
202
+ obs = []
203
+ n_obs = []
204
+ terminals = []
205
+ rewards = []
206
+ actions = []
207
+ # task_horizon = []
208
+ task_step = 0
209
+ for i in range(len(done_)):
210
+ obs.append(obs_[i])
211
+ n_obs.append(next_obs_[i])
212
+ terminals.append(done_[i])
213
+ rewards.append(reward_[i])
214
+ actions.append(action_[i])
215
+ # task_horizon.append(task_step)
216
+ task_step += 1
217
+ if done_[i] or timeout_[i]:
218
+ epi_obs.append(np.array(obs))
219
+ epi_n_obs.append(np.array(n_obs))
220
+ epi_terminals.append(np.array(terminals))
221
+ epi_rewards.append(np.array(rewards))
222
+ epi_returns.append(data_return_list[i])
223
+ epi_actions.append(np.array(actions))
224
+ obs = []
225
+ n_obs = []
226
+ terminals = []
227
+ rewards = []
228
+ actions = []
229
+ task_step = 0
230
+
231
+ transition_ids = np.arange(len(obs_))
232
+ return {
233
+ 'observations': np.array(obs_),
234
+ 'actions': np.array(action_),
235
+ 'next_observations': np.array(next_obs_),
236
+ 'rewards': np.array(reward_),
237
+ 'terminals': np.array(done_),
238
+ 'timeouts': np.array(timeout_),
239
+ 'init_states': np.array(init_obs_),
240
+ 'transition_ids': transition_ids,
241
+ 'returns': data_return_list,
242
+ 'epi_obs': np.array(epi_obs, dtype=object),
243
+ 'epi_n_obs': np.array(epi_n_obs, dtype=object),
244
+ 'epi_terminals': np.array(epi_terminals, dtype=object),
245
+ 'epi_rewards': np.array(epi_rewards, dtype=object),
246
+ 'epi_returns': np.array(epi_returns, dtype=object),
247
+ 'epi_actions': np.array(epi_actions, dtype=object),
248
+ 'task_horizon':np.array(task_horizon, dtype=object),
249
+ }
250
+
251
+
252
+ def create_dataset():
253
+ env = gym.make(config.env_1)
254
+ expert_env = gym.make(config.env_2)
255
+
256
+ dataset = qlearning_dataset(env)
257
+ expert_dataset = qlearning_dataset(expert_env)
258
+
259
+ # mixed_dataset = modify_dataset(dataset, expert_dataset)
260
+ mixed_dataset = modify_dataset_direct(dataset, expert_dataset)
261
+
262
+ with open(config.file_name, 'wb') as f:
263
+ pickle.dump(mixed_dataset, f)
264
+
265
+ if __name__ == "__main__":
266
+ config = pyrallis.parse(config_class=TrainConfig)
267
+ create_dataset()
halfcheetah-1%-expert-random.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4e18cc2ea8bbdb8b462905ffee4eab56f2dfc385e0384f9bff039d4f8d2275de
3
+ size 172963474
halfcheetah-10%-expert-random.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:da85d979502e148a51e1791f72dbc3a0e564be77f4d56f330ba5a2d64b6a97ae
3
+ size 172963474
halfcheetah-5%-expert-random.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a3be120165d7c216ba29912cf8026e583486cb2267aff55aa4b8877b4cf21f11
3
+ size 172963474
hopper-1%-expert-random.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c92e8f721102cd506784fd7a94fd07181dfe3e2286739547ed432a7e9e129958
3
+ size 115036069
hopper-10%-expert-random.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f64ead3e6e1c3add72ed5b03a7ac98d26b8233102503401b21ac5ba27df4ee85
3
+ size 115036069
hopper-5%-expert-random.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:19ba2d78abf31bfab1dfa20c0ec710113a72361ff53f7f7663dadad2a048d415
3
+ size 115036069
walker2d-1%-expert-random.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4a51ba580f8b98c1df6370d9ae79a4db29a7b40c1f2e1148dea1104ce292bda7
3
+ size 176393909
walker2d-10%-expert-random.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ec35e7dfa318f3a4fb400600760c98b41cea59564804679cf99bd459c07ed187
3
+ size 176393909
walker2d-5%-expert-random.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7bf098fcf913a2084a0646e80a8fd9eed884194e4a50ac30eede0fa4a93ebcaa
3
+ size 176393909