-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclone_data_generator.cc
More file actions
460 lines (409 loc) · 16.1 KB
/
Copy pathclone_data_generator.cc
File metadata and controls
460 lines (409 loc) · 16.1 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
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
#include "clone_data_generator.h"
#include <numeric>
namespace rlcc {
void DataGenLoop::mainLoop() {
RELA_CHECK_GT(game_trajectories_.size(), 0);
std::vector<size_t> idx_left;
while (!terminated()) {
if (idx_left.size() <= 0) {
if (!inf_loop_) {
if (epoch_ == 0) {
++epoch_;
} else {
break;
}
}
idx_left.resize(game_trajectories_.size());
std::iota(idx_left.begin(), idx_left.end(), 0);
std::shuffle(idx_left.begin(), idx_left.end(), rng_);
}
size_t idx = idx_left.back();
idx_left.pop_back();
// std::cout << "Thread " << thread_idx_ << " Get idx\n";
const GameTrajectory game_trajectory = game_trajectories_[idx];
if (reward_type_ == "dds") {
env_options_.playing_phase = false;
} else {
env_options_.playing_phase = true;
}
BridgeEnv env{params_, env_options_};
// Deal.
env.ResetWithDeck(std::vector<int>(game_trajectory.begin(),
game_trajectory.begin() + ble::kNumCards));
// std::cout << "Thread " << thread_idx_ << " Reset env\n";
const size_t end_size =
game_trajectory.size() > ble::kNumCards + ble::kNumPlayers
? game_trajectory.size() - ble::kNumCards
: game_trajectory.size();
for (size_t midx = ble::kNumCards; midx < end_size; ++midx) {
int current_player = env.CurrentPlayer();
// std::cout << "Thread " << thread_idx_
// << " Get cur player: " << current_player << std::endl;
for (int player = 0; player < ble::kNumPlayers; ++player) {
auto feature = env.Feature(player);
// Split public and private.
const int kPrivateFeatureSize = feature.at("s").size(0) - ble::kNumCards;
feature["publ_s"] = feature.at("s").index(
{torch::indexing::Slice(0, kPrivateFeatureSize)});
feature["priv_s"] = feature.at("s");
feature.erase("s");
transition_buffers_[player].PushObs(feature);
// std::cout << "Thread " << thread_idx_
// << " Push obs.\n";
int action;
if (player == current_player) {
action = game_trajectory[midx];
} else {
action = env.NoOPUid();
}
transition_buffers_[player].PushAction({{"a", torch::tensor(action)}});
// std::cout << "Thread " << thread_idx_
// << " Push action.\n";
}
env.Step(game_trajectory[midx]);
if (midx == end_size - 1) {
for (int player = 0; player < ble::kNumPlayers; ++player) {
transition_buffers_[player].PushTerminal();
}
}
}
std::vector<float> rewards;
if (reward_type_ == "dds") {
rewards = env.Rewards();
} else {
// Rollout the playing phase to get rewards.
if (env.Terminated()) {
// May be passed out.
rewards = env.Rewards();
} else {
for (size_t i = end_size; i < game_trajectory.size(); ++i) {
const int uid = game_trajectory.at(i);
env.Step(uid);
}
RELA_CHECK(env.Terminated());
rewards = env.Rewards();
}
}
for (int player = 0; player < ble::kNumPlayers; ++player) {
transition_buffers_[player].PushReward(
{{"r", torch::tensor(rewards[player])}});
}
// std::cout << "Thread " << thread_idx_ << "Simulate game done\n";
for (int player = 0; player < ble::kNumPlayers; ++player) {
replay_buffer_->add(transition_buffers_[player].PopTransition(), 1.0);
}
}
}
void CloneDataGenerator::StartDataGeneration(bool inf_loop, int seed) {
// for (int i = 0; i < num_threads_; ++i) {
// std::cout << i << ": " << game_trajectories_[i].size() << "\n";
// }
std::mt19937 rng(seed);
context_ = std::make_unique<rela::Context>();
for (int i = 0; i < num_threads_; ++i) {
int seed = static_cast<int>(rng());
auto thread = std::make_shared<DataGenLoop>(replay_buffer_,
game_params_,
env_options_,
game_trajectories_[i],
max_len_,
inf_loop, seed,
reward_type_, i);
context_->pushThreadLoop(thread);
threads_.push_back(thread);
}
context_->start();
}
std::vector<rela::RNNTransition> CloneDataGenerator::GenerateEvalData(
int batch_size, const std::string &device,
const std::vector<GameTrajectory> &game_trajectories) {
const int num_games = static_cast<int>(game_trajectories.size());
std::vector<rela::RNNTransition> batches;
// Transition buffers for each player.
std::vector<RNNTransitionBuffer> transition_buffers_;
transition_buffers_.reserve(ble::kNumPlayers);
for (int i = 0; i < ble::kNumPlayers; ++i) {
transition_buffers_.emplace_back(max_len_, 1.0);
}
std::vector<rela::RNNTransition> v_transitions;
for (int i = 0; i < num_games; ++i) {
// std::cout << "i=" << i << std::endl;
const std::vector<int> &game_trajectory = game_trajectories[i];
const size_t end_size =
game_trajectory.size() > ble::kNumCards + ble::kNumPlayers
? game_trajectory.size() - ble::kNumCards
: game_trajectory.size();
if (reward_type_ == "dds") {
env_options_.playing_phase = false;
} else {
env_options_.playing_phase = true;
}
BridgeEnv env{game_params_, env_options_};
// Deal.
env.ResetWithDeck(std::vector<int>(game_trajectory.begin(),
game_trajectory.begin() + ble::kNumCards));
// std::cout << "Reset env" << std::endl;
for (size_t midx = ble::kNumCards; midx < end_size; ++midx) {
const int current_player = env.CurrentPlayer();
for (int player = 0; player < ble::kNumPlayers; ++player) {
auto feature = env.Feature(player);
// Split public and private.
const int kPrivateFeatureSize = feature.at("s").size(0) - ble::kNumCards;
feature["publ_s"] = feature.at("s").index(
{torch::indexing::Slice(0, kPrivateFeatureSize)});
feature["priv_s"] = feature.at("s");
feature.erase("s");
transition_buffers_[player].PushObs(feature);
int action;
if (player == current_player) {
action = game_trajectory[midx];
} else {
action = env.NoOPUid();
}
transition_buffers_[player].PushAction({{"a", torch::tensor(action)}});
}
env.Step(game_trajectory[midx]);
if (midx == end_size - 1) {
// auto rewards = env.Rewards();
for (int player = 0; player < ble::kNumPlayers; ++player) {
transition_buffers_[player].PushTerminal();
// transition_buffers_[player].PushReward(
// {{"r", torch::tensor(rewards[player])}});
}
}
}
std::vector<float> rewards;
if (reward_type_ == "dds") {
rewards = env.Rewards();
} else {
// Rollout the playing phase to get rewards.
if (env.Terminated()) {
// May be passed out.
rewards = env.Rewards();
} else {
for (size_t j = end_size; j < game_trajectory.size(); ++j) {
const int uid = game_trajectory.at(j);
env.Step(uid);
}
RELA_CHECK(env.Terminated());
rewards = env.Rewards();
}
}
for (int player = 0; player < ble::kNumPlayers; ++player) {
transition_buffers_[player].PushReward(
{{"r", torch::tensor(rewards[player])}});
}
for (int player = 0; player < ble::kNumPlayers; ++player) {
v_transitions.push_back(transition_buffers_[player].PopTransition());
if (v_transitions.size() % batch_size == 0) {
rela::RNNTransition transition = rela::makeBatch(v_transitions, device);
batches.push_back(transition);
v_transitions.clear();
}
}
}
return batches;
}
void FFDataGenLoop::mainLoop() {
RELA_CHECK_GT(game_trajectories_.size(), 0);
std::vector<size_t> idx_left;
if (reward_type_ == "dds") {
env_options_.playing_phase = false;
} else {
env_options_.playing_phase = true;
}
while (!terminated()) {
if (idx_left.size() <= 0) {
if (!inf_loop_) {
if (epoch_ == 0) {
++epoch_;
} else {
break;
}
}
idx_left.resize(game_trajectories_.size());
std::iota(idx_left.begin(), idx_left.end(), 0);
std::shuffle(idx_left.begin(), idx_left.end(), rng_);
}
size_t idx = idx_left.back();
idx_left.pop_back();
// std::cout << "get idx" << std::endl;
const GameTrajectory game_trajectory = game_trajectories_[idx];
BridgeEnv env{params_, env_options_};
// Deal.
env.ResetWithDeck(std::vector<int>(game_trajectory.begin(),
game_trajectory.begin() + ble::kNumCards));
const size_t end_size =
game_trajectory.size() > ble::kNumCards + ble::kNumPlayers
? game_trajectory.size() - ble::kNumCards
: game_trajectory.size();
for (size_t midx = ble::kNumCards; midx < end_size; ++midx) {
// std::cout << "midx: " << midx << std::endl;
int current_player = env.CurrentPlayer();
auto feature = env.Feature(current_player);
const auto [_, priv_size, publ_size] = env.FeatureSize();
feature["perf_s"] = feature.at("s");
feature["publ_s"] = feature.at("s").index(
{torch::indexing::Slice(0, publ_size)});
feature["priv_s"] = feature.at("s").index(
{torch::indexing::Slice(0, priv_size)});
feature.erase("s");
feature["legal_move"] = feature.at("legal_move").index(
{torch::indexing::Slice(ble::kNumCards, -1)}
);
transition_buffers_[current_player].PushObs(feature);
const int action = game_trajectory[midx];
transition_buffers_[current_player].PushAction({{"a", torch::tensor(action, {torch::kInt32})}});
env.Step(action);
}
std::vector<float> rewards;
if (reward_type_ == "dds") {
rewards = env.Rewards();
} else {
// Rollout the playing phase to get rewards.
if (env.Terminated()) {
// May be passed out.
rewards = env.Rewards();
} else {
for (size_t i = end_size; i < game_trajectory.size(); ++i) {
const int uid = game_trajectory.at(i);
env.Step(uid);
}
RELA_CHECK(env.Terminated());
rewards = env.Rewards();
}
}
// std::cout << "get reward." << std::endl;
for (int player = 0; player < ble::kNumPlayers; ++player) {
transition_buffers_[player].PushReward(rewards[player]);
transition_buffers_[player].PushTerminal();
}
// std::cout << "push r and t\n";
for (int player = 0; player < ble::kNumPlayers; ++player) {
const auto transitions = transition_buffers_[player].PopTransition();
for (const auto &transition : transitions) {
replay_buffer_->add(transition, 1.0);
}
}
// std::cout << "add to buffer\n";
}
}
void FFCloneDataGenerator::StartDataGeneration(bool inf_loop, int seed) {
std::mt19937 rng(seed);
context_ = std::make_unique<rela::Context>();
for (int i = 0; i < num_threads_; ++i) {
int seed = static_cast<int>(rng());
auto thread = std::make_shared<FFDataGenLoop>(replay_buffer_,
game_params_,
env_options_,
game_trajectories_[i],
inf_loop, seed,
reward_type_,
gamma_,
i);
context_->pushThreadLoop(thread);
threads_.push_back(thread);
}
context_->start();
}
std::vector<rela::FFTransition> FFCloneDataGenerator::GenerateEvalData(int batch_size,
const std::string &device,
const std::vector<GameTrajectory> &game_trajectories) {
const int num_games = static_cast<int>(game_trajectories.size());
std::vector<rela::FFTransition> all_transitions;
// Transition buffers for each player.
std::vector<FFTransitionBuffer> transition_buffers_;
transition_buffers_.reserve(ble::kNumPlayers);
for (int i = 0; i < ble::kNumPlayers; ++i) {
transition_buffers_.emplace_back(gamma_);
}
if (reward_type_ == "dds") {
env_options_.playing_phase = false;
} else {
env_options_.playing_phase = true;
}
for (size_t idx = 0; idx < game_trajectories.size(); ++idx) {
// std::cout << "game idx: " << idx << std::endl;
const GameTrajectory &game_trajectory = game_trajectories[idx];
// std::cout << "trajectory: \n";
// rela::utils::printVector(game_trajectory);
BridgeEnv env{game_params_, env_options_};
// Deal.
env.ResetWithDeck(std::vector<int>(game_trajectory.begin(),
game_trajectory.begin() + ble::kNumCards));
const size_t end_size =
game_trajectory.size() > ble::kNumCards + ble::kNumPlayers
? game_trajectory.size() - ble::kNumCards
: game_trajectory.size();
for (size_t midx = ble::kNumCards; midx < end_size; ++midx) {
// std::cout << "mid idx: " << midx << std::endl;
int current_player = env.CurrentPlayer();
auto feature = env.Feature(current_player);
const auto [_, priv_size, publ_size] = env.FeatureSize();
feature["perf_s"] = feature.at("s");
feature["publ_s"] = feature.at("s").index(
{torch::indexing::Slice(0, publ_size)});
feature["priv_s"] = feature.at("s").index(
{torch::indexing::Slice(0, priv_size)});
feature.erase("s");
feature["legal_move"] = feature.at("legal_move").index(
{torch::indexing::Slice(ble::kNumCards, -1)}
);
transition_buffers_[current_player].PushObs(feature);
const int action = game_trajectory[midx];
transition_buffers_[current_player].PushAction({{"a", torch::tensor(action, {torch::kInt32})}});
env.Step(action);
}
// std::cout << "env:\n" << env.ToString() << std::endl;
// std::cout << "terminated? " << env.Terminated() << std::endl;
std::vector<float> rewards;
if (reward_type_ == "dds") {
rewards = env.Rewards();
} else {
// Rollout the playing phase to get rewards.
if (env.Terminated()) {
// May be passed out.
rewards = env.Rewards();
} else {
for (size_t i = end_size; i < game_trajectory.size(); ++i) {
const int uid = game_trajectory.at(i);
env.Step(uid);
}
RELA_CHECK(env.Terminated());
rewards = env.Rewards();
}
}
// std::cout << "get reward.\n";
// std::cout << "reward: ";
// rela::utils::printVector(rewards);
for (int player = 0; player < ble::kNumPlayers; ++player) {
transition_buffers_[player].PushReward(rewards[player]);
transition_buffers_[player].PushTerminal();
}
// std::cout << "push reward and terminal.\n";
for (int player = 0; player < ble::kNumPlayers; ++player) {
const auto transitions =
transition_buffers_[player].PopTransition();
for (const auto &transition : transitions) {
all_transitions.push_back(transition);
}
}
}
RELA_CHECK_GT(all_transitions.size(), 0);
// std::cout << "num all transitions: " << all_transitions.size() << std::endl;
std::vector<rela::FFTransition> batches;
int num_transitions = static_cast<int>(all_transitions.size());
int num_batches = std::ceil(static_cast<float>(num_transitions) / static_cast<float>(batch_size));
for (int i = 0; i < num_batches; ++i) {
int left = i * batch_size;
int right = std::min(left + batch_size, num_transitions);
std::vector<rela::FFTransition> transition_batch(
std::vector<rela::FFTransition>(all_transitions.begin() + left,
all_transitions.begin() + right)
);
rela::FFTransition batch = rela::makeBatch(transition_batch, device);
batches.push_back(batch);
}
return batches;
}
} // namespace rlcc