-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathevaluation.py
201 lines (173 loc) · 6.15 KB
/
evaluation.py
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
"""
Copyright (c) Meta Platforms, Inc. and affiliates.
This source code is licensed under the CC BY-NC license found in the
LICENSE.md file in the root directory of this source tree.
"""
import numpy as np
import torch
MAX_EPISODE_LEN = 1000
def create_vec_eval_episodes_fn(
vec_env,
eval_rtg,
state_dim,
act_dim,
state_mean,
state_std,
device,
use_mean=False,
reward_scale=0.001,
):
def eval_episodes_fn(model):
target_return = [eval_rtg * reward_scale] * vec_env.num_envs
returns, lengths, _ = vec_evaluate_episode_rtg(
vec_env,
state_dim,
act_dim,
model,
max_ep_len=MAX_EPISODE_LEN,
reward_scale=reward_scale,
target_return=target_return,
mode="normal",
state_mean=state_mean,
state_std=state_std,
device=device,
use_mean=use_mean,
)
suffix = "_gm" if use_mean else ""
return {
f"evaluation/return_mean{suffix}": np.mean(returns),
f"evaluation/return_std{suffix}": np.std(returns),
f"evaluation/length_mean{suffix}": np.mean(lengths),
f"evaluation/length_std{suffix}": np.std(lengths),
}
return eval_episodes_fn
@torch.no_grad()
def vec_evaluate_episode_rtg(
vec_env,
state_dim,
act_dim,
model,
target_return: list,
max_ep_len=1000,
reward_scale=0.001,
state_mean=0.0,
state_std=1.0,
device="cuda",
mode="normal",
use_mean=False,
):
assert len(target_return) == vec_env.num_envs
model.eval()
model.to(device=device)
state_mean = torch.from_numpy(state_mean).to(device=device)
state_std = torch.from_numpy(state_std).to(device=device)
num_envs = vec_env.num_envs
state = vec_env.reset()
# we keep all the histories on the device
# note that the latest action and reward will be "padding"
states = (
torch.from_numpy(state)
.reshape(num_envs, state_dim)
.to(device=device, dtype=torch.float32)
).reshape(num_envs, -1, state_dim)
actions = torch.zeros(0, device=device, dtype=torch.float32)
rewards = torch.zeros(0, device=device, dtype=torch.float32)
ep_return = target_return
target_return = torch.tensor(ep_return, device=device, dtype=torch.float32).reshape(
num_envs, -1, 1
)
timesteps = torch.tensor([0] * num_envs, device=device, dtype=torch.long).reshape(
num_envs, -1
)
# episode_return, episode_length = 0.0, 0
episode_return = np.zeros((num_envs, 1)).astype(float)
episode_length = np.full(num_envs, np.inf)
unfinished = np.ones(num_envs).astype(bool)
for t in range(max_ep_len):
# add padding
actions = torch.cat(
[
actions,
torch.zeros((num_envs, act_dim), device=device).reshape(
num_envs, -1, act_dim
),
],
dim=1,
)
rewards = torch.cat(
[
rewards,
torch.zeros((num_envs, 1), device=device).reshape(num_envs, -1, 1),
],
dim=1,
)
state_pred, action_dist, reward_pred = model.get_predictions(
(states.to(dtype=torch.float32) - state_mean) / state_std,
actions.to(dtype=torch.float32),
rewards.to(dtype=torch.float32),
target_return.to(dtype=torch.float32),
timesteps.to(dtype=torch.long),
num_envs=num_envs,
)
state_pred = state_pred.detach().cpu().numpy().reshape(num_envs, -1)
reward_pred = reward_pred.detach().cpu().numpy().reshape(num_envs)
# the return action is a SquashNormal distribution
action = action_dist.sample().reshape(num_envs, -1, act_dim)[:, -1]
if use_mean:
action = action_dist.mean.reshape(num_envs, -1, act_dim)[:, -1]
action = action.clamp(*model.action_range)
state, reward, done, _ = vec_env.step(action.detach().cpu().numpy())
# eval_env.step() will execute the action for all the sub-envs, for those where
# the episodes have terminated, the envs will be reset. Hence we use
# "unfinished" to track whether the first episode we roll out for each sub-env is
# finished. In contrast, "done" only relates to the current episode
episode_return[unfinished] += reward[unfinished].reshape(-1, 1)
actions[:, -1] = action
state = (
torch.from_numpy(state).to(device=device).reshape(num_envs, -1, state_dim)
)
states = torch.cat([states, state], dim=1)
reward = torch.from_numpy(reward).to(device=device).reshape(num_envs, 1)
rewards[:, -1] = reward
if mode != "delayed":
pred_return = target_return[:, -1] - (reward * reward_scale)
else:
pred_return = target_return[:, -1]
target_return = torch.cat(
[target_return, pred_return.reshape(num_envs, -1, 1)], dim=1
)
timesteps = torch.cat(
[
timesteps,
torch.ones((num_envs, 1), device=device, dtype=torch.long).reshape(
num_envs, 1
)
* (t + 1),
],
dim=1,
)
if t == max_ep_len - 1:
done = np.ones(done.shape).astype(bool)
if np.any(done):
ind = np.where(done)[0]
unfinished[ind] = False
episode_length[ind] = np.minimum(episode_length[ind], t + 1)
if not np.any(unfinished):
break
trajectories = []
for ii in range(num_envs):
ep_len = episode_length[ii].astype(int)
terminals = np.zeros(ep_len)
terminals[-1] = 1
traj = {
"observations": states[ii].detach().cpu().numpy()[:ep_len],
"actions": actions[ii].detach().cpu().numpy()[:ep_len],
"rewards": rewards[ii].detach().cpu().numpy()[:ep_len],
"terminals": terminals,
}
trajectories.append(traj)
return (
episode_return.reshape(num_envs),
episode_length.reshape(num_envs),
trajectories,
)