-
Notifications
You must be signed in to change notification settings - Fork 31
/
python_module.cpp
563 lines (494 loc) · 17.6 KB
/
python_module.cpp
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
#include <numeric>
#include <omp.h>
#include "cppshogi.h"
void init() {
initTable();
Position::initZobrist();
HuffmanCodedPos::init();
}
// make result
inline float make_result(const uint8_t result, const Color color) {
const GameResult gameResult = (GameResult)(result & 0x3);
if (gameResult == Draw)
return 0.5f;
if ((color == Black && gameResult == BlackWin) ||
(color == White && gameResult == WhiteWin)) {
return 1.0f;
}
else {
return 0.0f;
}
}
template<typename T>
inline T is_sennichite(const uint8_t result) {
return static_cast<T>(result & GAMERESULT_SENNICHITE ? 1 : 0);
}
template<typename T>
inline T is_nyugyoku(const uint8_t result) {
return static_cast<T>(result & GAMERESULT_NYUGYOKU ? 1 : 0);
}
void __hcpe_decode_with_value(const size_t len, char* ndhcpe, char* ndfeatures1, char* ndfeatures2, char* ndmove, char* ndresult, char* ndvalue) {
HuffmanCodedPosAndEval* hcpe = reinterpret_cast<HuffmanCodedPosAndEval*>(ndhcpe);
features1_t* features1 = reinterpret_cast<features1_t*>(ndfeatures1);
features2_t* features2 = reinterpret_cast<features2_t*>(ndfeatures2);
int64_t* move = reinterpret_cast<int64_t*>(ndmove);
float* result = reinterpret_cast<float*>(ndresult);
float* value = reinterpret_cast<float*>(ndvalue);
// set all zero
std::fill_n((float*)features1, sizeof(features1_t) / sizeof(float) * len, 0.0f);
std::fill_n((float*)features2, sizeof(features2_t) / sizeof(float) * len, 0.0f);
Position position;
for (size_t i = 0; i < len; i++, hcpe++, features1++, features2++, value++, move++, result++) {
position.set(hcpe->hcp);
// input features
make_input_features(position, *features1, *features2);
// move
*move = make_move_label(hcpe->bestMove16, position.turn());
// game result
*result = make_result(hcpe->gameResult, position.turn());
// eval
*value = score_to_value((Score)hcpe->eval);
}
}
void __hcpe2_decode_with_value(const size_t len, char* ndhcpe2, char* ndfeatures1, char* ndfeatures2, char* ndmove, char* ndresult, char* ndvalue, char* ndaux) {
HuffmanCodedPosAndEval2* hcpe = reinterpret_cast<HuffmanCodedPosAndEval2*>(ndhcpe2);
features1_t* features1 = reinterpret_cast<features1_t*>(ndfeatures1);
features2_t* features2 = reinterpret_cast<features2_t*>(ndfeatures2);
int64_t* move = reinterpret_cast<int64_t*>(ndmove);
float* result = reinterpret_cast<float*>(ndresult);
float* value = reinterpret_cast<float*>(ndvalue);
auto aux = reinterpret_cast<float(*)[2]>(ndaux);
// set all zero
std::fill_n((float*)features1, sizeof(features1_t) / sizeof(float) * len, 0.0f);
std::fill_n((float*)features2, sizeof(features2_t) / sizeof(float) * len, 0.0f);
Position position;
for (size_t i = 0; i < len; i++, hcpe++, features1++, features2++, value++, move++, result++, aux++) {
position.set(hcpe->hcp);
// input features
make_input_features(position, *features1, *features2);
// move
*move = make_move_label(hcpe->bestMove16, position.turn());
// game result
*result = make_result(hcpe->result, position.turn());
// eval
*value = score_to_value((Score)hcpe->eval);
// sennichite
(*aux)[0] = is_sennichite<float>(hcpe->result);
// nyugyoku
(*aux)[1] = is_nyugyoku<float>(hcpe->result);
}
}
std::vector<TrainingData> trainingData;
// 重複チェック用 局面に対応するtrainingDataのインデックスを保持
std::unordered_map<HuffmanCodedPos, unsigned int> duplicates;
void __hcpe3_create_cache(const std::string& filepath) {
std::ofstream ofs(filepath, std::ios::binary);
// インデックス部
// 局面数
const size_t num = trainingData.size();
ofs.write((const char*)&num, sizeof(num));
// 各局面の開始位置
size_t pos = sizeof(num) + sizeof(pos) * num;
for (const auto& hcpe3 : trainingData) {
ofs.write((const char*)&pos, sizeof(pos));
pos += sizeof(Hcpe3CacheBody) + sizeof(Hcpe3CacheCandidate) * hcpe3.candidates.size();
}
// ボディ部
for (const auto& hcpe3 : trainingData) {
Hcpe3CacheBody body{
hcpe3.hcp,
hcpe3.value,
hcpe3.result,
hcpe3.count
};
ofs.write((const char*)&body, sizeof(body));
for (const auto kv : hcpe3.candidates) {
Hcpe3CacheCandidate candidate{
kv.first,
kv.second
};
ofs.write((const char*)&candidate, sizeof(candidate));
}
}
// メモリ開放
// trainingDataを開放してしまうため、キャッシュを作成した場合、データはキャッシュから読み込むこと
trainingData.clear();
trainingData.shrink_to_fit();
duplicates.clear();
std::unordered_map<HuffmanCodedPos, unsigned int>(duplicates).swap(duplicates);
}
// hcpe3キャッシュ
std::ifstream* cache;
std::vector<size_t> cache_pos;
size_t __hcpe3_load_cache(const std::string& filepath) {
cache = new std::ifstream(filepath, std::ios::binary);
size_t num;
cache->read((char*)&num, sizeof(num));
cache_pos.resize(num + 1);
cache->read((char*)cache_pos.data(), sizeof(size_t) * num);
cache->seekg(0, std::ios_base::end);
cache_pos[num] = cache->tellg();
return num;
}
size_t __hcpe3_get_cache_num() {
return cache_pos.size() > 0 ? cache_pos.size() - 1 : 0;
}
TrainingData get_cache(const size_t i) {
const size_t pos = cache_pos[i];
const size_t candidateNum = ((cache_pos[i + 1] - pos) - sizeof(Hcpe3CacheBody)) / sizeof(Hcpe3CacheCandidate);
struct Hcpe3CacheBuf {
Hcpe3CacheBody body;
Hcpe3CacheCandidate candidates[MaxLegalMoves];
} buf;
cache->seekg(pos, std::ios_base::beg);
cache->read((char*)&buf, sizeof(Hcpe3CacheBody) + sizeof(Hcpe3CacheCandidate) * candidateNum);
return TrainingData(buf.body, buf.candidates, candidateNum);
}
TrainingData get_cache_with_lock(const size_t i) {
const size_t pos = cache_pos[i];
const size_t candidateNum = ((cache_pos[i + 1] - pos) - sizeof(Hcpe3CacheBody)) / sizeof(Hcpe3CacheCandidate);
struct Hcpe3CacheBuf {
Hcpe3CacheBody body;
Hcpe3CacheCandidate candidates[MaxLegalMoves];
} buf;
#pragma omp critical
{
cache->seekg(pos, std::ios_base::beg);
cache->read((char*)&buf, sizeof(Hcpe3CacheBody) + sizeof(Hcpe3CacheCandidate) * candidateNum);
}
return TrainingData(buf.body, buf.candidates, candidateNum);
}
// hcpe形式の指し手をone-hotの方策として読み込む
size_t load_hcpe(const std::string& filepath, std::ifstream& ifs, bool use_average, const double eval_scale, size_t& len) {
for (int p = 0; ifs; ++p) {
HuffmanCodedPosAndEval hcpe;
ifs.read((char*)&hcpe, sizeof(HuffmanCodedPosAndEval));
if (ifs.eof()) {
break;
}
const float value = score_to_value((Score)(hcpe.eval * eval_scale));
if (use_average) {
auto ret = duplicates.emplace(hcpe.hcp, trainingData.size());
if (ret.second) {
auto& data = trainingData.emplace_back(
hcpe.hcp,
value,
make_result(hcpe.gameResult, hcpe.hcp.color())
);
data.candidates[hcpe.bestMove16] = 1;
}
else {
// 重複データの場合、加算する(hcpe3_decode_with_valueで平均にする)
auto& data = trainingData[ret.first->second];
data.value += value;
data.result += make_result(hcpe.gameResult, hcpe.hcp.color());
data.candidates[hcpe.bestMove16] += 1;
data.count++;
}
}
else {
auto& data = trainingData.emplace_back(
hcpe.hcp,
value,
make_result(hcpe.gameResult, hcpe.hcp.color())
);
data.candidates[hcpe.bestMove16] = 1;
}
++len;
}
return trainingData.size();
}
template <bool add>
inline void visits_to_proberbility(TrainingData& data, const std::vector<MoveVisits>& candidates, const double temperature) {
if (candidates.size() == 1) {
// one-hot
const auto& moveVisits = candidates[0];
if constexpr (add)
data.candidates[moveVisits.move16] += 1.0f;
else
data.candidates[moveVisits.move16] = 1.0f;
}
else if (temperature == 0) {
// greedy
const auto itr = std::max_element(candidates.begin(), candidates.end(), [](const MoveVisits& a, const MoveVisits& b) { return a.visitNum < b.visitNum; });
const MoveVisits& moveVisits = *itr;
if constexpr (add)
data.candidates[moveVisits.move16] += 1.0f;
else
data.candidates[moveVisits.move16] = 1.0f;
}
else if (temperature == 1) {
const float sum_visitNum = (float)std::accumulate(candidates.begin(), candidates.end(), 0, [](int acc, const MoveVisits& move_visits) { return acc + move_visits.visitNum; });
for (const auto& moveVisits : candidates) {
const float proberbility = (float)moveVisits.visitNum / sum_visitNum;
if constexpr (add)
data.candidates[moveVisits.move16] += proberbility;
else
data.candidates[moveVisits.move16] = proberbility;
}
}
else {
double exponentiated_visits[593];
double sum = 0;
for (size_t i = 0; i < candidates.size(); i++) {
const auto& moveVisits = candidates[i];
const auto new_visits = std::pow(moveVisits.visitNum, 1.0 / temperature);
exponentiated_visits[i] = new_visits;
sum += new_visits;
}
for (size_t i = 0; i < candidates.size(); i++) {
const auto& moveVisits = candidates[i];
const float proberbility = (float)(exponentiated_visits[i] / sum);
if constexpr (add)
data.candidates[moveVisits.move16] += proberbility;
else
data.candidates[moveVisits.move16] = proberbility;
}
}
}
// フォーマット自動判別
bool is_hcpe(std::ifstream& ifs) {
if (ifs.tellg() % sizeof(HuffmanCodedPosAndEval) == 0) {
// 最後のデータがhcpeであるかで判別
ifs.seekg(-sizeof(HuffmanCodedPosAndEval), std::ios_base::end);
HuffmanCodedPosAndEval hcpe;
ifs.read((char*)&hcpe, sizeof(HuffmanCodedPosAndEval));
if (hcpe.hcp.isOK() && hcpe.bestMove16 >= 1 && hcpe.bestMove16 <= 26703) {
return true;
}
}
return false;
}
// hcpe3形式のデータを読み込み、ランダムアクセス可能なように加工し、trainingDataに保存する
// 複数回呼ぶことで、複数ファイルの読み込みが可能
size_t __load_hcpe3(const std::string& filepath, bool use_average, double a, double temperature, size_t& len) {
std::ifstream ifs(filepath, std::ifstream::binary | std::ios::ate);
if (!ifs) return trainingData.size();
const double eval_scale = a == 0 ? 1 : 756.0864962951762 / a;
// フォーマット自動判別
// hcpeの場合は、指し手をone-hotの方策として読み込む
if (is_hcpe(ifs)) {
ifs.seekg(std::ios_base::beg);
return load_hcpe(filepath, ifs, use_average, eval_scale, len);
}
ifs.seekg(std::ios_base::beg);
std::vector<MoveVisits> candidates;
for (int p = 0; ifs; ++p) {
HuffmanCodedPosAndEval3 hcpe3;
ifs.read((char*)&hcpe3, sizeof(HuffmanCodedPosAndEval3));
if (ifs.eof()) {
break;
}
assert(hcpe3.moveNum <= 513);
// 開始局面
Position pos;
if (!pos.set(hcpe3.hcp)) {
std::stringstream ss("INCORRECT_HUFFMAN_CODE at ");
ss << filepath << "(" << p << ")";
throw std::runtime_error(ss.str());
}
StateListPtr states{ new std::deque<StateInfo>(1) };
for (int i = 0; i < hcpe3.moveNum; ++i) {
MoveInfo moveInfo;
ifs.read((char*)&moveInfo, sizeof(MoveInfo));
assert(moveInfo.candidateNum <= 593);
// candidateNum==0の手は読み飛ばす
if (moveInfo.candidateNum > 0) {
candidates.resize(moveInfo.candidateNum);
ifs.read((char*)candidates.data(), sizeof(MoveVisits) * moveInfo.candidateNum);
const auto hcp = pos.toHuffmanCodedPos();
const float value = score_to_value((Score)(moveInfo.eval * eval_scale));
if (use_average) {
auto ret = duplicates.emplace(hcp, trainingData.size());
if (ret.second) {
auto& data = trainingData.emplace_back(
hcp,
value,
make_result(hcpe3.result, pos.turn())
);
visits_to_proberbility<false>(data, candidates, temperature);
}
else {
// 重複データの場合、加算する(hcpe3_decode_with_valueで平均にする)
auto& data = trainingData[ret.first->second];
data.value += value;
data.result += make_result(hcpe3.result, pos.turn());
visits_to_proberbility<true>(data, candidates, temperature);
data.count++;
}
}
else {
auto& data = trainingData.emplace_back(
hcp,
value,
make_result(hcpe3.result, pos.turn())
);
visits_to_proberbility<false>(data, candidates, temperature);
}
++len;
}
const Move move = move16toMove((Move)moveInfo.selectedMove16, pos);
pos.doMove(move, states->emplace_back(StateInfo()));
}
}
return trainingData.size();
}
size_t __hcpe3_patch_with_hcpe(const std::string& filepath, size_t& add_len) {
std::ifstream ifs(filepath, std::ifstream::binary);
size_t sum_len = 0;
while (ifs) {
HuffmanCodedPosAndEval hcpe;
ifs.read((char*)&hcpe, sizeof(HuffmanCodedPosAndEval));
if (ifs.eof()) {
break;
}
bool found = false;
const float value = score_to_value((Score)hcpe.eval);
for (auto& data : trainingData) {
if (data.hcp == hcpe.hcp) {
found = true;
data.count = 1;
data.value = value;
data.result = make_result(hcpe.gameResult, hcpe.hcp.color());
data.candidates.clear();
data.candidates[hcpe.bestMove16] = 1;
}
}
if (!found) {
auto& data = trainingData.emplace_back(
hcpe.hcp,
value,
make_result(hcpe.gameResult, hcpe.hcp.color())
);
data.candidates[hcpe.bestMove16] = 1;
++add_len;
}
++sum_len;
}
return sum_len;
}
// load_hcpe3で読み込み済みのtrainingDataから、インデックスを使用してサンプリングする
// 重複データは平均化する
void __hcpe3_decode_with_value(const size_t len, char* ndindex, char* ndfeatures1, char* ndfeatures2, char* ndprobability, char* ndresult, char* ndvalue) {
unsigned int* index = reinterpret_cast<unsigned int*>(ndindex);
features1_t* features1 = reinterpret_cast<features1_t*>(ndfeatures1);
features2_t* features2 = reinterpret_cast<features2_t*>(ndfeatures2);
auto probability = reinterpret_cast<float(*)[9 * 9 * MAX_MOVE_LABEL_NUM]>(ndprobability);
float* result = reinterpret_cast<float*>(ndresult);
float* value = reinterpret_cast<float*>(ndvalue);
// set all zero
std::fill_n((float*)features1, sizeof(features1_t) / sizeof(float) * len, 0.0f);
std::fill_n((float*)features2, sizeof(features2_t) / sizeof(float) * len, 0.0f);
std::fill_n((float*)probability, 9 * 9 * MAX_MOVE_LABEL_NUM * len, 0.0f);
#pragma omp parallel for num_threads(2) if (len > 1)
for (size_t i = 0; i < len; i++) {
const auto& hcpe3 = cache ? (len > 1 ? get_cache_with_lock(index[i]) : get_cache(index[i])) : trainingData[index[i]];
Position position;
position.set(hcpe3.hcp);
// input features
make_input_features(position, features1[i], features2[i]);
// move probability
for (const auto kv : hcpe3.candidates) {
const auto label = make_move_label(kv.first, position.turn());
assert(label < 9 * 9 * MAX_MOVE_LABEL_NUM);
probability[i][label] = kv.second / hcpe3.count;
}
// game result
result[i] = hcpe3.result / hcpe3.count;
// eval
value[i] = hcpe3.value / hcpe3.count;
}
}
// load_hcpe3で読み込み済みのtrainingDataから、インデックスを指定してhcpeを取り出す
void __hcpe3_get_hcpe(const size_t index, char* ndhcpe) {
HuffmanCodedPosAndEval* hcpe = reinterpret_cast<HuffmanCodedPosAndEval*>(ndhcpe);
const auto& hcpe3 = cache ? get_cache(index) : trainingData[index];
hcpe->hcp = hcpe3.hcp;
float max_prob = FLT_MIN;
for (const auto kv : hcpe3.candidates) {
const auto& move16 = kv.first;
const auto& prob = kv.second;
if (prob > max_prob) {
hcpe->bestMove16 = move16;
max_prob = prob;
}
}
hcpe->eval = s16(-logf(1.0f / (hcpe3.value / hcpe3.count) - 1.0f) * 756.0f);
const auto result = (hcpe3.result / hcpe3.count);
if (result < 0.5f) {
hcpe->gameResult = hcpe3.hcp.color() == Black ? WhiteWin : BlackWin;
}
else if (result > 0.5f) {
hcpe->gameResult = hcpe3.hcp.color() == Black ? BlackWin : WhiteWin;
}
else {
hcpe->gameResult = Draw;
}
}
// evalの補正用データ準備
std::vector<int> eval;
std::vector<float> result;
size_t __load_evalfix(const std::string& filepath) {
eval.clear();
result.clear();
std::ifstream ifs(filepath, std::ifstream::binary | std::ios::ate);
if (!ifs) return 0;
// フォーマット自動判別
bool hcpe3 = !is_hcpe(ifs);
ifs.seekg(std::ios_base::beg);
if (hcpe3) {
for (int p = 0; ifs; ++p) {
HuffmanCodedPosAndEval3 hcpe3;
ifs.read((char*)&hcpe3, sizeof(HuffmanCodedPosAndEval3));
if (ifs.eof()) {
break;
}
assert(hcpe3.moveNum <= 513);
// 開始局面
Position pos;
if (!pos.set(hcpe3.hcp)) {
std::stringstream ss("INCORRECT_HUFFMAN_CODE at ");
ss << filepath << "(" << p << ")";
throw std::runtime_error(ss.str());
}
StateListPtr states{ new std::deque<StateInfo>(1) };
for (int i = 0; i < hcpe3.moveNum; ++i) {
MoveInfo moveInfo;
ifs.read((char*)&moveInfo, sizeof(MoveInfo));
assert(moveInfo.candidateNum <= 593);
// candidateNum==0の手は読み飛ばす
if (moveInfo.candidateNum > 0) {
ifs.seekg(sizeof(MoveVisits) * moveInfo.candidateNum, std::ios_base::cur);
// 詰みは除く
if (std::abs(moveInfo.eval) < 30000) {
eval.emplace_back(moveInfo.eval);
result.emplace_back(make_result(hcpe3.result, pos.turn()));
}
}
assert(moveInfo.selectedMove16 <= 0x7fff);
const Move move = move16toMove((Move)moveInfo.selectedMove16, pos);
pos.doMove(move, states->emplace_back(StateInfo()));
}
}
}
else {
// hcpeフォーマット
for (int p = 0; ifs; ++p) {
HuffmanCodedPosAndEval hcpe;
ifs.read((char*)&hcpe, sizeof(HuffmanCodedPosAndEval));
if (ifs.eof()) {
break;
}
// 詰みは除く
if (std::abs(hcpe.eval) < 30000) {
eval.emplace_back(hcpe.eval);
result.emplace_back(make_result(hcpe.gameResult, hcpe.hcp.color()));
}
}
}
return result.size();
}
void __hcpe3_prepare_evalfix(char* ndeval, char* ndresult) {
std::copy(eval.begin(), eval.end(), reinterpret_cast<int*>(ndeval));
std::copy(result.begin(), result.end(), reinterpret_cast<float*>(ndresult));
}