-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbuffer.py
418 lines (351 loc) · 14.7 KB
/
buffer.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
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# =====================================
# @Time : 2020/6/10
# @Author : Yang Guan (Tsinghua Univ.)
# @FileName: buffer.py
# =====================================
import logging
import os
import random
import numpy as np
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
from utils.segment_tree import SumSegmentTree, MinSegmentTree
class ReplayBuffer(object):
def __init__(self, args, buffer_id):
"""Create Prioritized Replay buffer.
Parameters
----------
size: int
Max number of transitions to store in the buffer. When the buffer
overflows the old memories are dropped.
"""
self.args = args
self.buffer_id = buffer_id
self._storage = []
self._maxsize = self.args.max_buffer_size
self._next_idx = 0
self.replay_starts = self.args.replay_starts
self.replay_batch_size = self.args.replay_batch_size
self.stats = {}
self.replay_times = 0
logger.info('Buffer initialized')
def get_stats(self):
self.stats.update(dict(storage=len(self._storage)))
return self.stats
def __len__(self):
return len(self._storage)
def add(self, obs_t, action, reward, obs_tp1, done, weight):
data = (obs_t, action, reward, obs_tp1, done)
if self._next_idx >= len(self._storage):
self._storage.append(data)
else:
self._storage[self._next_idx] = data
self._next_idx = (self._next_idx + 1) % self._maxsize
def _encode_sample(self, idxes):
obses_t, actions, rewards, obses_tp1, dones = [], [], [], [], []
for i in idxes:
data = self._storage[i]
obs_t, action, reward, obs_tp1, done = data
obses_t.append(np.array(obs_t, copy=False))
actions.append(np.array(action, copy=False))
rewards.append(reward)
obses_tp1.append(np.array(obs_tp1, copy=False))
dones.append(done)
return np.array(obses_t), np.array(actions), np.array(rewards), \
np.array(obses_tp1), np.array(dones)
def sample_idxes(self, batch_size):
return np.array([random.randint(0, len(self._storage) - 1) for _ in range(batch_size)], dtype=np.int32)
def sample_with_idxes(self, idxes):
return list(self._encode_sample(idxes)) + [idxes,]
def sample(self, batch_size):
idxes = self.sample_idxes(batch_size)
return self.sample_with_idxes(idxes)
def add_batch(self, batch):
for trans in batch:
self.add(*trans, 0)
def replay(self):
if len(self._storage) < self.replay_starts:
return None
if self.buffer_id == 1 and self.replay_times % self.args.buffer_log_interval == 0:
logger.info('Buffer info: {}'.format(self.get_stats()))
self.replay_times += 1
return self.sample(self.replay_batch_size)
class ReplayBufferWithCost(object):
def __init__(self, args, buffer_id):
"""Create Prioritized Replay buffer.
Parameters
----------
size: int
Max number of transitions to store in the buffer. When the buffer
overflows the old memories are dropped.
"""
self.args = args
if isinstance(self.args.random_seed, int):
self.set_seed(self.args.random_seed)
self.buffer_id = buffer_id
self._storage = []
self._maxsize = self.args.max_buffer_size
self._next_idx = 0
self.replay_starts = self.args.replay_starts
self.replay_batch_size = self.args.replay_batch_size
self.stats = {}
self.replay_times = 0
logger.info('Buffer initialized')
def set_seed(self, seed):
# self.tf.random.set_seed(seed)
np.random.seed(seed)
random.seed(seed)
# self.env.seed(seed)
def get_stats(self):
self.stats.update(dict(storage=len(self._storage)))
return self.stats
def __len__(self):
return len(self._storage)
def add(self, obs_t, action, reward, obs_tp1, done, cost, sis_info, weight):
data = (obs_t, action, reward, obs_tp1, done, cost, sis_info)
if self._next_idx >= len(self._storage):
self._storage.append(data)
else:
self._storage[self._next_idx] = data
self._next_idx = (self._next_idx + 1) % self._maxsize
def _encode_sample(self, idxes):
obses_t, actions, rewards, obses_tp1, dones, costs, sis_infos = [], [], [], [], [], [], []
for i in idxes:
data = self._storage[i]
obs_t, action, reward, obs_tp1, done, cost, sis_info = data
obses_t.append(np.array(obs_t, copy=False))
actions.append(np.array(action, copy=False))
rewards.append(reward)
obses_tp1.append(np.array(obs_tp1, copy=False))
dones.append(done)
costs.append(cost)
sis_infos.append(sis_info)
return np.array(obses_t), np.array(actions), np.array(rewards), \
np.array(obses_tp1), np.array(dones), np.array(costs), np.array(sis_infos)
def sample_idxes(self, batch_size):
return np.array([random.randint(0, len(self._storage) - 1) for _ in range(batch_size)], dtype=np.int32)
def sample_with_idxes(self, idxes):
return list(self._encode_sample(idxes)) + [idxes,]
def sample(self, batch_size):
idxes = self.sample_idxes(batch_size)
return self.sample_with_idxes(idxes)
def add_batch(self, batch):
for trans in batch:
self.add(*trans, None)
def replay(self):
if len(self._storage) < self.replay_starts:
return None
if self.buffer_id == 1 and self.replay_times % self.args.buffer_log_interval == 0:
logger.info('Buffer info: {}'.format(self.get_stats()))
self.replay_times += 1
# self.count_heatmap()
return self.sample(self.replay_batch_size)
def count_heatmap(self, state_range=None, num=None, iteration=0):
if state_range is None:
state_range = [0.0, 4.0]
if num is None:
num = 16
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
data_to_count = np.stack(np.array(self._storage)[:, 0])
x_data_to_count = np.abs(data_to_count[:, 0])
y_data_to_count = np.abs(data_to_count[:, 1] - data_to_count[:, -1])
dist = np.stack([x_data_to_count, y_data_to_count]).T
blocks = np.linspace(state_range[0], state_range[1], int(num + 1))
df_list = []
for i in range(int(num)):
for j in range(int(num)):
x_low, x_high = blocks[i], blocks[i + 1]
y_low, y_high = blocks[j], blocks[j + 1]
low = np.array([x_low, y_low])
high = np.array([x_high, y_high])
t_or_f = (dist > low) & (dist < high)
count = np.logical_and(t_or_f[:,0], t_or_f[:,1]).sum()
df = pd.DataFrame(dict(x=[x_low], y=[y_low], count=[count]))
df_list.append(df)
total_df = pd.concat(df_list, ignore_index=True)
file_name = 'dist_{}.csv'.format(iteration)
save_path = os.path.join(self.args.log_dir, file_name)
total_df.to_csv(save_path)
total_df = total_df.pivot('x', 'y', 'count')
plt.figure()
sns.heatmap(total_df)
file_name = 'dist_{}.png'.format(iteration)
save_fig = os.path.join(self.args.log_dir, file_name)
plt.savefig(save_fig)
return None
class PrioritizedReplayBuffer(ReplayBuffer):
def __init__(self, args, buffer_id):
"""Create Prioritized Replay buffer.
Parameters
----------
size: int
Max number of transitions to store in the buffer. When the buffer
overflows the old memories are dropped.
alpha: float
how much prioritization is used
(0 - no prioritization, 1 - full prioritization)
beta: float
To what degree to use importance weights
(0 - no corrections, 1 - full correction)
See Also
--------
ReplayBuffer.__init__
"""
super(PrioritizedReplayBuffer, self).__init__(args, buffer_id)
assert self.args.alpha > 0
self._alpha = args.replay_alpha
self._beta = args.replay_beta
it_capacity = 1
while it_capacity < self.args.size:
it_capacity *= 2
self._it_sum = SumSegmentTree(it_capacity)
self._it_min = MinSegmentTree(it_capacity)
self._max_priority = 1.0
def add(self, obs_t, action, reward, obs_tp1, done, weight):
"""See ReplayBuffer.store_effect"""
idx = self._next_idx
super(PrioritizedReplayBuffer, self).add(obs_t, action, reward,
obs_tp1, done, weight)
if weight is None:
weight = self._max_priority
self._it_sum[idx] = weight ** self._alpha
self._it_min[idx] = weight ** self._alpha
def _sample_proportional(self, batch_size):
res = []
for _ in range(batch_size):
mass = random.random() * self._it_sum.sum(0, len(self._storage))
idx = self._it_sum.find_prefixsum_idx(mass)
res.append(idx)
return np.array(res, dtype=np.int32)
def sample_idxes(self, batch_size):
return self._sample_proportional(batch_size)
def sample_with_weights_and_idxes(self, idxes):
weights = []
p_min = self._it_min.min() / self._it_sum.sum()
max_weight = (p_min * len(self._storage)) ** (-self._beta)
for idx in idxes:
p_sample = self._it_sum[idx] / self._it_sum.sum()
weight = (p_sample * len(self._storage)) ** (-self._beta)
weights.append(weight / max_weight)
weights = np.array(weights)
encoded_sample = self._encode_sample(idxes)
return list(encoded_sample) + [weights, idxes]
def sample(self, batch_size):
idxes = self.sample_idxes(batch_size)
return self.sample_with_weights_and_idxes(idxes)
def update_priorities(self, idxes, priorities):
"""Update priorities of sampled transitions.
sets priority of transition at index idxes[i] in buffer
to priorities[i].
Parameters
----------
idxes: [int]
List of idxes of sampled transitions
priorities: [float]
List of updated priorities corresponding to
transitions at the sampled idxes denoted by
variable `idxes`.
"""
assert len(idxes) == len(priorities)
for idx, priority in zip(idxes, priorities):
assert priority > 0
assert 0 <= idx < len(self._storage)
delta = priority ** self._alpha - self._it_sum[idx]
self._it_sum[idx] = priority ** self._alpha
self._it_min[idx] = priority ** self._alpha
self._max_priority = max(self._max_priority, priority)
class PrioritizedReplayBufferWithCost(ReplayBufferWithCost):
def __init__(self, args, buffer_id):
"""Create Prioritized Replay buffer.
Parameters
----------
size: int
Max number of transitions to store in the buffer. When the buffer
overflows the old memories are dropped.
alpha: float
how much prioritization is used
(0 - no prioritization, 1 - full prioritization)
beta: float
To what degree to use importance weights
(0 - no corrections, 1 - full correction)
See Also
--------
ReplayBuffer.__init__
"""
super(PrioritizedReplayBufferWithCost, self).__init__(args, buffer_id)
assert self.args.replay_alpha > 0
self._alpha = args.replay_alpha
self._beta = args.replay_beta
it_capacity = 1
while it_capacity < self.args.max_buffer_size:
it_capacity *= 2
self._it_sum = SumSegmentTree(it_capacity)
self._it_min = MinSegmentTree(it_capacity)
self._max_priority = 1.0
def add(self, obs_t, action, reward, obs_tp1, done, cost, weight):
"""See ReplayBuffer.store_effect"""
idx = self._next_idx
super(PrioritizedReplayBufferWithCost, self).add(obs_t, action, reward,
obs_tp1, done, cost, weight)
if weight is None:
weight = self._max_priority
self._it_sum[idx] = weight ** self._alpha
self._it_min[idx] = weight ** self._alpha
def _sample_proportional(self, batch_size):
res = []
for _ in range(batch_size):
mass = random.random() * self._it_sum.sum(0, len(self._storage))
idx = self._it_sum.find_prefixsum_idx(mass)
res.append(idx)
return np.array(res, dtype=np.int32)
def sample_idxes(self, batch_size):
return self._sample_proportional(batch_size)
def sample_with_weights_and_idxes(self, idxes):
weights = []
p_min = self._it_min.min() / self._it_sum.sum()
max_weight = (p_min * len(self._storage)) ** (-self._beta)
for idx in idxes:
p_sample = self._it_sum[idx] / self._it_sum.sum()
weight = (p_sample * len(self._storage)) ** (-self._beta)
weights.append(weight / max_weight)
weights = np.array(weights)
encoded_sample = self._encode_sample(idxes)
return list(encoded_sample) + [weights, idxes]
def sample(self, batch_size):
idxes = self.sample_idxes(batch_size)
return self.sample_with_weights_and_idxes(idxes)
def update_priorities(self, idxes, priorities):
"""Update priorities of sampled transitions.
sets priority of transition at index idxes[i] in buffer
to priorities[i].
Parameters
----------
idxes: [int]
List of idxes of sampled transitions
priorities: [float]
List of updated priorities corresponding to
transitions at the sampled idxes denoted by
variable `idxes`.
"""
assert len(idxes) == len(priorities)
for idx, priority in zip(idxes, priorities):
assert priority > 0
assert 0 <= idx < len(self._storage)
delta = priority ** self._alpha - self._it_sum[idx]
self._it_sum[idx] = priority ** self._alpha
self._it_min[idx] = priority ** self._alpha
self._max_priority = max(self._max_priority, priority)
def tes_perc():
from train_scripts.train_script import built_FSAC_parser
args = built_FSAC_parser()
buffer = PrioritizedReplayBufferWithCost(args, 0)
for i in range(100):
buffer.add(0, 0, 0, 0, 0, 0, None)
a = buffer.sample(16)
print(a)
if __name__ == '__main__':
tes_perc()