File size: 9,755 Bytes
e24d8a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()