-
Notifications
You must be signed in to change notification settings - Fork 2
/
Tuner.h
340 lines (299 loc) · 11.1 KB
/
Tuner.h
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
#ifndef LIBCHESS_TUNER_H
#define LIBCHESS_TUNER_H
#include <array>
#include <cmath>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <random>
#include <sstream>
#include <string>
#include <vector>
namespace libchess {
class TunableParameter {
public:
TunableParameter(std::string name, int value) noexcept : name_(std::move(name)), value_(value) {
}
TunableParameter operator+(int rhs) const noexcept {
return TunableParameter{name(), value() + rhs};
}
TunableParameter operator-(int rhs) const noexcept {
return TunableParameter{name(), value_ - rhs};
}
void operator+=(int rhs) noexcept {
value_ += rhs;
}
void operator-=(int rhs) noexcept {
value_ -= rhs;
}
[[nodiscard]] const std::string& name() const noexcept {
return name_;
}
[[nodiscard]] int value() const noexcept {
return value_;
}
void set_value(int value) noexcept {
value_ = value;
}
[[nodiscard]] std::string to_str() const noexcept {
return name_ + ": " + std::to_string(value_);
}
private:
const std::string name_;
int value_;
};
enum class Result
{
BLACK_WIN,
DRAW,
WHITE_WIN
};
template <class Position>
class NormalizedResult {
public:
NormalizedResult(Position position, Result result) noexcept : position_(std::move(position)) {
switch (result) {
case Result::BLACK_WIN:
value_ = 0.0;
break;
case Result::DRAW:
value_ = 0.5;
break;
case Result::WHITE_WIN:
value_ = 1.0;
break;
}
}
[[nodiscard]] Position& position() noexcept {
return position_;
}
[[nodiscard]] double value() const noexcept {
return value_;
}
static std::vector<NormalizedResult<Position>> parse_epd(
const std::string& path,
std::function<Position(const std::string&)> fen_parser,
const std::string& result_opcode = "c9") noexcept {
std::string line;
std::ifstream file_stream{path};
std::vector<NormalizedResult<Position>> normalized_results;
while (true) {
std::getline(file_stream, line);
if (line.empty()) {
break;
}
std::string_view line_view{line};
auto curr_pos = line_view.begin();
for (unsigned i = 0; i < 4; ++i) {
curr_pos = std::find(curr_pos + 1, line_view.end(), ' ');
}
std::string fen{line_view.begin(), curr_pos};
std::string post_fen{curr_pos + 1, line_view.end()};
Result result = [&result_opcode, &post_fen] {
std::istringstream post_fen_stream{post_fen};
std::string opcode;
while (post_fen_stream >> opcode) {
if (opcode == ";") {
break;
}
std::string value;
post_fen_stream >> std::quoted(value);
if (opcode != result_opcode) {
continue;
}
if (value == "1-0") {
return Result::WHITE_WIN;
} else if (value == "0-1") {
return Result::BLACK_WIN;
} else {
return Result::DRAW;
}
}
return Result::DRAW;
}();
normalized_results.push_back(NormalizedResult{fen_parser(fen), result});
}
return normalized_results;
}
private:
Position position_;
double value_;
};
template <class Position>
class Tuner {
public:
Tuner(std::vector<NormalizedResult<Position>> normalized_results,
std::vector<TunableParameter> tunable_parameters,
std::function<int(Position&, const std::vector<TunableParameter>&)> eval_function)
: normalized_results_(std::move(normalized_results)),
tunable_parameters_(std::move(tunable_parameters)),
eval_function_(std::move(eval_function)) {
}
[[nodiscard]] const std::vector<TunableParameter>& tunable_parameters() const noexcept {
return tunable_parameters_;
}
[[nodiscard]] double error() noexcept {
double sum = 0.0;
#pragma omp parallel for reduction(+ : sum)
for (unsigned i = 0; i < normalized_results_.size(); ++i) {
auto& normalized_result = normalized_results_.at(i);
double normalized_eval = sigmoid(eval(normalized_result.position()));
double err = normalized_result.value() - normalized_eval;
sum += err * err;
}
return sum / double(normalized_results_.size());
}
void local_tune() noexcept {
double least_error = error();
std::vector<LocalParameterTuningData> parameter_tuning_data;
parameter_tuning_data.reserve(tunable_parameters_.size());
for (unsigned i = 0; i < tunable_parameters_.size(); ++i) {
parameter_tuning_data.push_back(LocalParameterTuningData{});
}
while (!all_done(parameter_tuning_data)) {
auto param_iter = tunable_parameters_.begin();
auto tune_data_iter = parameter_tuning_data.begin();
for (; param_iter != tunable_parameters_.end() &&
tune_data_iter != parameter_tuning_data.end();
++param_iter, ++tune_data_iter) {
if (tune_data_iter->done()) {
continue;
}
*param_iter += tune_data_iter->increment();
double new_error = error();
if (new_error < least_error) {
least_error = new_error;
} else {
tune_data_iter->reverse_direction();
*param_iter += 2 * tune_data_iter->increment();
new_error = error();
if (new_error < least_error) {
least_error = new_error;
} else {
*param_iter -= tune_data_iter->increment();
tune_data_iter->set_direction(0);
}
}
}
for (unsigned i = 0; i < tunable_parameters_.size(); ++i) {
TunableParameter& parameter = tunable_parameters_[i];
LocalParameterTuningData& tuning_data = parameter_tuning_data[i];
std::cout << parameter.name() << ": " << parameter.value() << " improving "
<< tuning_data.improving() << "\n";
}
std::cout << "Least error: " << least_error << "\n";
for (LocalParameterTuningData& tune_data : parameter_tuning_data) {
if (!tune_data.improving()) {
if (tune_data.can_reduce_increment()) {
tune_data.reduce_increment();
tune_data.set_direction(1);
} else {
tune_data.set_done(true);
}
}
}
}
}
void simulated_annealing(int max_steps) noexcept {
std::random_device random_device;
std::mt19937 rng{random_device()};
std::uniform_int_distribution<> increment_distribution{0, increment_values.size() - 1};
std::uniform_int_distribution<> parameter_distribution{0, tunable_parameters_.size() - 1};
auto random_bool = [&](double probability) {
std::bernoulli_distribution bool_distribution{probability};
return bool_distribution(rng);
};
auto random_increment = [&]() {
return (random_bool(0.5) ? 1 : -1) * increment_values[increment_distribution(rng)];
};
double current_error = error();
for (int step = 0; step < max_steps; ++step) {
double temperature = 1.0 / (1.667 * (1.0 + double(step)));
int increment = random_increment();
TunableParameter& tunable_parameter = tunable_parameters_[parameter_distribution(rng)];
tunable_parameter += increment;
double new_error = error();
double acceptance_probability =
new_error < current_error
? 1.0
: std::exp(-(new_error - current_error) / double(temperature));
if (random_bool(acceptance_probability)) {
current_error = new_error;
} else {
tunable_parameter -= increment;
}
display();
std::cout << "acceptance prob: " << acceptance_probability << " step: " << step
<< " temperature: " << temperature << " error: " << current_error << "\n";
}
}
void tune() noexcept {
simulated_annealing(1000);
local_tune();
}
void display() const noexcept {
for (auto& param : tunable_parameters_) {
std::cout << param.to_str() << "\n";
}
}
protected:
[[nodiscard]] static double sigmoid(int score, double k = 1.13) noexcept {
return 1.0 / (1.0 + std::pow(10.0, -k * score / 400.0));
}
[[nodiscard]] int eval(Position& position) noexcept {
return eval_function_(position, tunable_parameters_);
}
private:
constexpr static std::array<int, 7> increment_values{100, 50, 25, 12, 6, 3, 1};
struct LocalParameterTuningData {
public:
[[nodiscard]] bool improving() const noexcept {
return direction_ != 0;
}
[[nodiscard]] bool done() const noexcept {
return done_;
}
[[nodiscard]] int direction() const noexcept {
return direction_;
}
[[nodiscard]] int increment() const noexcept {
return direction_ * increment_values[increment_offset_];
}
[[nodiscard]] bool can_reduce_increment() const noexcept {
return increment_offset_ < increment_values.size() - 1;
}
void reduce_increment() noexcept {
if (can_reduce_increment()) {
++increment_offset_;
}
}
void reverse_direction() noexcept {
direction_ = -direction_;
}
void set_done(bool value) noexcept {
done_ = value;
}
void set_direction(int value) noexcept {
direction_ = value;
}
private:
bool done_ = false;
unsigned increment_offset_ = 0;
int direction_ = 1;
};
[[nodiscard]] static bool all_done(
const std::vector<LocalParameterTuningData>& tuning_data_list) noexcept {
for (auto& tuning_data : tuning_data_list) {
if (!tuning_data.done()) {
return false;
}
}
return true;
}
std::vector<NormalizedResult<Position>> normalized_results_{};
std::vector<TunableParameter> tunable_parameters_{};
std::function<int(Position&, const std::vector<TunableParameter>&)> eval_function_{};
};
} // namespace libchess
#endif // LIBCHESS_TUNER_H