-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprioritized_replay.h
More file actions
387 lines (320 loc) · 9.28 KB
/
Copy pathprioritized_replay.h
File metadata and controls
387 lines (320 loc) · 9.28 KB
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
//
// Created by qzz on 2023/9/19.
//
#ifndef BRIDGE_LEARNING_RELA_PRIORITIZED_REPLAY_H_
#define BRIDGE_LEARNING_RELA_PRIORITIZED_REPLAY_H_
#include <cmath>
#include <future>
#include <random>
#include <thread>
#include <vector>
#include <queue>
#include <iostream>
#include "tensor_dict.h"
#include "transition.h"
namespace rela {
template<class DataType>
class ConcurrentQueue {
public:
explicit ConcurrentQueue(int capacity)
: capacity(capacity),
head_(0),
tail_(0),
size_(0),
safeTail_(0),
safeSize_(0),
sum_(0),
evicted_(capacity, false),
elements_(capacity),
weights_(capacity, 0) {
}
int safeSize(float *sum) const {
std::unique_lock<std::mutex> lk(m_);
if (sum != nullptr) {
*sum = sum_;
}
return safeSize_;
}
int size() const {
std::unique_lock<std::mutex> lk(m_);
return size_;
}
void clear() {
std::unique_lock<std::mutex> lk(m_);
head_ = 0;
tail_ = 0;
size_ = 0;
safeTail_ = 0;
safeSize_ = 0;
sum_ = 0;
std::fill(evicted_.begin(), evicted_.end(), false);
std::fill(weights_.begin(), weights_.end(), 0.0);
}
void terminate() {
terminated_ = true;
cvSize_.notify_all();
}
void append(const DataType &data, float weight) {
int blockSize = 1;
std::unique_lock<std::mutex> lk(m_);
cvSize_.wait(lk, [=] { return terminated_ || (size_ + blockSize <= capacity); });
if (terminated_) {
return;
}
int start = tail_;
int end = (tail_ + blockSize) % capacity;
tail_ = end;
size_ += blockSize;
checkSize(head_, tail_, size_);
lk.unlock();
float sum = 0;
elements_[start] = data;
weights_[start] = weight;
sum += weight;
lk.lock();
cvTail_.wait(lk, [=] { return safeTail_ == start; });
safeTail_ = end;
safeSize_ += blockSize;
sum_ += sum;
checkSize(head_, safeTail_, safeSize_);
lk.unlock();
cvTail_.notify_all();
}
// ------------------------------------------------------------- //
// blockPop, update are thread-safe against blockAppend
// but they are NOT thread-safe against each other
void blockPop(int blockSize) {
double diff = 0;
int head = head_;
for (int i = 0; i < blockSize; ++i) {
diff -= weights_[head];
evicted_[head] = true;
head = (head + 1) % capacity;
}
{
std::lock_guard<std::mutex> lk(m_);
sum_ += diff;
head_ = head;
safeSize_ -= blockSize;
size_ -= blockSize;
assert(safeSize_ >= 0);
checkSize(head_, safeTail_, safeSize_);
}
cvSize_.notify_all();
}
void update(const std::vector<int> &ids, const torch::Tensor &weights) {
double diff = 0;
auto weightAcc = weights.accessor<float, 1>();
for (int i = 0; i < (int) ids.size(); ++i) {
auto id = ids[i];
if (evicted_[id]) {
continue;
}
diff += (weightAcc[i] - weights_[id]);
weights_[id] = weightAcc[i];
}
std::lock_guard<std::mutex> lk_(m_);
sum_ += diff;
}
// ------------------------------------------------------------- //
// accessing elements is never locked, operate safely!
DataType get(int idx) {
int id = (head_ + idx) % capacity;
return elements_[id];
}
DataType getElementAndMark(int idx) {
int id = (head_ + idx) % capacity;
evicted_[id] = false;
return elements_[id];
}
float getWeight(int idx, int *id) {
assert(id != nullptr);
*id = (head_ + idx) % capacity;
return weights_[*id];
}
const int capacity;
private:
void checkSize(int head, int tail, int size) {
if (size == 0) {
assert(tail == head);
} else if (tail > head) {
if (tail - head != size) {
std::cout << "tail-head: " << tail - head << " vs size: " << size << std::endl;
}
assert(tail - head == size);
} else {
if (tail + capacity - head != size) {
std::cout << "tail-head: " << tail + capacity - head << " vs size: " << size
<< std::endl;
}
assert(tail + capacity - head == size);
}
}
mutable std::mutex m_;
std::condition_variable cvSize_;
std::condition_variable cvTail_;
int head_;
int tail_;
int size_;
int safeTail_;
int safeSize_;
double sum_;
std::vector<bool> evicted_;
std::vector<DataType> elements_;
std::vector<float> weights_;
bool terminated_ = false;
};
template<class DataType>
class PrioritizedReplay {
public:
PrioritizedReplay(int capacity, int seed, float alpha, float beta, int prefetch)
: alpha_(alpha) // priority exponent
, beta_(beta) // importance sampling exponent
, prefetch_(prefetch), capacity_(capacity), storage_(int(1.25 * capacity)), numAdd_(0) {
rng_.seed(seed);
}
void clear() {
assert(sampledIds_.empty());
while (!futures_.empty()) {
futures_.pop();
}
storage_.clear();
numAdd_ = 0;
}
void terminate() {
storage_.terminate();
}
void add(const DataType &sample, float priority) {
numAdd_ += 1;
storage_.append(sample, std::pow(priority, alpha_));
}
void add(const DataType &sample) {
float priority = 1.0;
add(sample, priority);
}
std::tuple<DataType, torch::Tensor> sample(int batchsize, const std::string &device) {
if (!sampledIds_.empty()) {
std::cout << "Error: previous samples' priority has not been updated." << std::endl;
assert(false);
}
DataType batch;
torch::Tensor priority;
if (prefetch_ == 0) {
std::tie(batch, priority, sampledIds_) = sample_(batchsize, device);
return std::make_tuple(batch, priority);
}
if (futures_.empty()) {
std::tie(batch, priority, sampledIds_) = sample_(batchsize, device);
} else {
std::tie(batch, priority, sampledIds_) = futures_.front().get();
futures_.pop();
}
while ((int) futures_.size() < prefetch_) {
auto f = std::async(
std::launch::async,
&PrioritizedReplay<DataType>::sample_,
this,
batchsize,
device);
futures_.push(std::move(f));
}
return std::make_tuple(batch, priority);
}
void updatePriority(const torch::Tensor &priority) {
if (priority.size(0) == 0) {
sampledIds_.clear();
return;
}
assert(priority.dim() == 1);
assert((int) sampledIds_.size() == priority.size(0));
auto weights = torch::pow(priority, alpha_);
{
std::lock_guard<std::mutex> lk(mSampler_);
storage_.update(sampledIds_, weights);
}
sampledIds_.clear();
}
DataType get(int idx) {
return storage_.get(idx);
}
int size() const {
return storage_.safeSize(nullptr);
}
int numAdd() const {
return numAdd_;
}
private:
using SampleWeightIds = std::tuple<DataType, torch::Tensor, std::vector<int>>;
SampleWeightIds sample_(int batchsize, const std::string &device) {
std::unique_lock<std::mutex> lk(mSampler_);
float sum;
int size = storage_.safeSize(&sum);
assert(size >= batchsize);
// storage_ [0, size) remains static in the subsequent section
float segment = sum / batchsize;
std::uniform_real_distribution<float> dist(0.0, segment);
std::vector<DataType> samples;
auto weights = torch::zeros({batchsize}, torch::kFloat32);
auto weightAcc = weights.accessor<float, 1>();
std::vector<int> ids(batchsize);
double accSum = 0;
int nextIdx = 0;
float w = 0;
int id = 0;
for (int i = 0; i < batchsize; i++) {
float rand = dist(rng_) + i * segment;
rand = std::min(sum - (float) 0.1, rand);
while (nextIdx <= size) {
if (accSum > 0 && accSum >= rand) {
assert(nextIdx >= 1);
DataType element = storage_.getElementAndMark(nextIdx - 1);
samples.push_back(element);
weightAcc[i] = w;
ids[i] = id;
break;
}
if (nextIdx == size) {
std::cout << "nextIdx: " << nextIdx << "/" << size << std::endl;
std::cout << std::setprecision(10) << "accSum: " << accSum << ", sum: " << sum
<< ", rand: " << rand << std::endl;
assert(false);
}
w = storage_.getWeight(nextIdx, &id);
accSum += w;
++nextIdx;
}
}
assert((int) samples.size() == batchsize);
// pop storage if full
size = storage_.size();
if (size > capacity_) {
storage_.blockPop(size - capacity_);
}
// safe to unlock, because <samples> contains copys
lk.unlock();
weights = weights / sum;
weights = torch::pow(size * weights, -beta_);
weights /= weights.max();
if (device != "cpu") {
weights = weights.to(torch::Device(device));
}
auto batch = makeBatch(samples, device);
return std::make_tuple(batch, weights, ids);
}
const float alpha_;
const float beta_;
const int prefetch_;
const int capacity_;
ConcurrentQueue<DataType> storage_;
std::atomic<int> numAdd_;
// make sure that sample & update does not overlap
std::mutex mSampler_;
std::vector<int> sampledIds_;
std::queue<std::future<SampleWeightIds>> futures_;
std::mt19937 rng_;
};
using RNNPrioritizedReplay = PrioritizedReplay<RNNTransition>;
using TensorDictReplay = PrioritizedReplay<TensorDict>;
using FFPrioritizedReplay = PrioritizedReplay<FFTransition>;
} // namespace rela
#endif //BRIDGE_LEARNING_RELA_PRIORITIZED_REPLAY_H_