-
Notifications
You must be signed in to change notification settings - Fork 15
/
alg_utils.py
151 lines (123 loc) · 6.92 KB
/
alg_utils.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
"""
This project was developed by Rocky Duan, Peter Chen, Pieter Abbeel for the Berkeley Deep RL Bootcamp, August 2017. Bootcamp website with slides and lecture videos: https://sites.google.com/view/deep-rl-bootcamp/.
Copyright 2017 Deep RL Bootcamp Organizers.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
from utils import *
# ==============================
# Shared utilities
# ==============================
def compute_cumulative_returns(rewards, baselines, discount):
# This method builds up the cumulative sum of discounted rewards for each time step:
# R[t] = sum_{t'>=t} γ^(t'-t)*r_t'
# Note that we use γ^(t'-t) instead of γ^t'. This gives us a biased gradient but lower variance
returns = []
# Use the last baseline prediction to back up
cum_return = baselines[-1]
for reward in rewards[::-1]:
cum_return = cum_return * discount + reward
returns.append(cum_return)
return returns[::-1]
def compute_advantages(rewards, baselines, discount, gae_lambda):
# Given returns R_t and baselines b(s_t), compute (generalized) advantage estimate A_t
deltas = rewards + discount * baselines[1:] - baselines[:-1]
advs = []
cum_adv = 0
multiplier = discount * gae_lambda
for delta in deltas[::-1]:
cum_adv = cum_adv * multiplier + delta
advs.append(cum_adv)
return advs[::-1]
def compute_pg_vars(trajs, policy, baseline, discount, gae_lambda):
"""
Compute chainer variables needed for various policy gradient algorithms
"""
for traj in trajs:
# Include the last observation here, in case the trajectory is not finished
baselines = baseline.predict(np.concatenate(
[traj["observations"], [traj["last_observation"]]]))
if traj['finished']:
# If already finished, the future cumulative rewards starting from the final state is 0
baselines[-1] = 0.
# This is useful when fitting baselines. It uses the baseline prediction of the last state value to perform
# Bellman backup if the trajectory is not finished.
traj['returns'] = compute_cumulative_returns(
traj['rewards'], baselines, discount)
traj['advantages'] = compute_advantages(
traj['rewards'], baselines, discount, gae_lambda)
traj['baselines'] = baselines[:-1]
# First, we compute a flattened list of observations, actions, and advantages
all_obs = np.concatenate([traj['observations'] for traj in trajs], axis=0)
all_acts = np.concatenate([traj['actions'] for traj in trajs], axis=0)
all_advs = np.concatenate([traj['advantages'] for traj in trajs], axis=0)
all_dists = {
k: np.concatenate([traj['distributions'][k] for traj in trajs], axis=0)
for k in trajs[0]['distributions'].keys()
}
# Normalizing the advantage values can make the algorithm more robust to reward scaling
all_advs = (all_advs - np.mean(all_advs)) / (np.std(all_advs) + 1e-8)
# Form chainer variables
all_obs = Variable(all_obs)
all_acts = Variable(all_acts)
all_advs = Variable(all_advs.astype(np.float32, copy=False))
all_dists = policy.distribution.from_dict(
{k: Variable(v) for k, v in all_dists.items()})
return all_obs, all_acts, all_advs, all_dists
# ==============================
# Helper methods for logging
# ==============================
def log_reward_statistics(env):
# keep unwrapping until we get the monitor
while not isinstance(env, gym.wrappers.Monitor): # and not isinstance()
if not isinstance(env, gym.Wrapper):
assert False
env = env.env
# env.unwrapped
assert isinstance(env, gym.wrappers.Monitor)
all_stats = None
for _ in range(10):
try:
all_stats = gym.wrappers.monitoring.load_results(env.directory)
except FileNotFoundError:
time.sleep(1)
continue
if all_stats is not None:
episode_rewards = all_stats['episode_rewards']
episode_lengths = all_stats['episode_lengths']
recent_episode_rewards = episode_rewards[-100:]
recent_episode_lengths = episode_lengths[-100:]
if len(recent_episode_rewards) > 0:
logger.logkv('AverageReturn', np.mean(recent_episode_rewards))
logger.logkv('MinReturn', np.min(recent_episode_rewards))
logger.logkv('MaxReturn', np.max(recent_episode_rewards))
logger.logkv('StdReturn', np.std(recent_episode_rewards))
logger.logkv('AverageEpisodeLength',
np.mean(recent_episode_lengths))
logger.logkv('MinEpisodeLength', np.min(recent_episode_lengths))
logger.logkv('MaxEpisodeLength', np.max(recent_episode_lengths))
logger.logkv('StdEpisodeLength', np.std(recent_episode_lengths))
logger.logkv('TotalNEpisodes', len(episode_rewards))
logger.logkv('TotalNSamples', np.sum(episode_lengths))
def log_baseline_statistics(trajs):
# Specifically, compute the explained variance, defined as
baselines = np.concatenate([traj['baselines'] for traj in trajs])
returns = np.concatenate([traj['returns'] for traj in trajs])
logger.logkv('ExplainedVariance',
explained_variance_1d(baselines, returns))
def log_action_distribution_statistics(dists):
with chainer.no_backprop_mode():
entropy = F.mean(dists.entropy()).data
logger.logkv('Entropy', entropy)
logger.logkv('Perplexity', np.exp(entropy))
if isinstance(dists, Gaussian):
logger.logkv('AveragePolicyStd', F.mean(
F.exp(dists.log_stds)).data)
for idx in range(dists.log_stds.shape[-1]):
logger.logkv('AveragePolicyStd[{}]'.format(
idx), F.mean(F.exp(dists.log_stds[..., idx])).data)
elif isinstance(dists, Categorical):
probs = F.mean(F.softmax(dists.logits), axis=0).data
for idx in range(len(probs)):
logger.logkv('AveragePolicyProb[{}]'.format(idx), probs[idx])