-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmatch.cpp
More file actions
423 lines (366 loc) · 14.6 KB
/
Copy pathmatch.cpp
File metadata and controls
423 lines (366 loc) · 14.6 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
#include "../core/global.h"
#include "../core/fileutils.h"
#include "../core/makedir.h"
#include "../core/config_parser.h"
#include "../core/timer.h"
#include "../dataio/sgf.h"
#include "../search/asyncbot.h"
#include "../search/patternbonustable.h"
#include "../program/setup.h"
#include "../program/play.h"
#include "../command/commandline.h"
#include "../main.h"
#include <csignal>
using namespace std;
static std::atomic<bool> sigReceived(false);
static std::atomic<bool> shouldStop(false);
static void signalHandler(int signal)
{
if(signal == SIGINT || signal == SIGTERM) {
sigReceived.store(true);
shouldStop.store(true);
}
}
int MainCmds::match(const vector<string>& args) {
Board::initHash();
ScoreValue::initTables();
Rand seedRand;
ConfigParser cfg;
string logFile;
string nnPredictorPath;
string sgfOutputDir;
try {
KataGoCommandLine cmd("Play different nets against each other with different search settings in a match or tournament.");
cmd.addConfigFileArg("","match_example.cfg");
TCLAP::ValueArg<string> logFileArg("","log-file","Log file to output to",false,string(),"FILE");
TCLAP::ValueArg<string> sgfOutputDirArg("","sgf-output-dir","Dir to output sgf files",false,string(),"DIR");
cmd.add(logFileArg);
cmd.add(sgfOutputDirArg);
cmd.setShortUsageArgLimit();
cmd.addOverrideConfigArg();
cmd.parseArgs(args);
logFile = logFileArg.getValue();
sgfOutputDir = sgfOutputDirArg.getValue();
cmd.getConfig(cfg);
}
catch (TCLAP::ArgException &e) {
cerr << "Error: " << e.error() << " for argument " << e.argId() << endl;
return 1;
}
Logger logger(&cfg);
logger.addFile(logFile);
logger.write("Match Engine starting...");
logger.write(string("Git revision: ") + Version::getGitRevision());
//Load per-bot search config, first, which also tells us how many bots we're running
vector<SearchParams> paramss = Setup::loadParams(cfg,Setup::SETUP_FOR_MATCH);
assert(paramss.size() > 0);
int numBots = (int)paramss.size();
//Figure out all pairs of bots that will be playing.
std::vector<std::pair<int,int>> matchupsPerRound;
{
//Load a filter on what bots we actually want to run. By default, include everything.
vector<bool> includeBot(numBots);
if(cfg.contains("includeBots")) {
vector<int> includeBotIdxs = cfg.getInts("includeBots",0,Setup::MAX_BOT_PARAMS_FROM_CFG);
for(int i = 0; i<numBots; i++) {
if(contains(includeBotIdxs,i))
includeBot[i] = true;
}
}
else {
for(int i = 0; i<numBots; i++) {
includeBot[i] = true;
}
}
std::vector<int> secondaryBotIdxs;
if(cfg.contains("secondaryBots"))
secondaryBotIdxs = cfg.getInts("secondaryBots",0,Setup::MAX_BOT_PARAMS_FROM_CFG);
std::vector<int> secondaryBot2Idxs;
if(cfg.contains("secondaryBots2"))
secondaryBot2Idxs = cfg.getInts("secondaryBots2",0,Setup::MAX_BOT_PARAMS_FROM_CFG);
for(const auto& botIdxs : {secondaryBotIdxs, secondaryBot2Idxs}) {
for(int i = 0; i<botIdxs.size(); i++)
assert(botIdxs[i] >= 0 && botIdxs[i] < numBots);
}
for(int i = 0; i<numBots; i++) {
if(!includeBot[i])
continue;
for(int j = 0; j<numBots; j++) {
if(!includeBot[j])
continue;
if(i < j
&& !(contains(secondaryBotIdxs,i) && contains(secondaryBotIdxs,j))
&& !(contains(secondaryBot2Idxs,i) && contains(secondaryBot2Idxs,j))
) {
matchupsPerRound.push_back(make_pair(i,j));
matchupsPerRound.push_back(make_pair(j,i));
}
}
}
if(cfg.contains("extraPairs")) {
string pairsStr = cfg.getString("extraPairs");
std::vector<string> pairStrs = Global::split(pairsStr,',');
for(const string& pairStr: pairStrs) {
if(Global::trim(pairStr).size() <= 0)
continue;
std::vector<string> pieces = Global::split(Global::trim(pairStr),'-');
if(pieces.size() != 2) {
throw IOError("Could not parse pair: " + pairStr);
}
bool suc;
int p0;
int p1;
suc = Global::tryStringToInt(pieces[0],p0);
if(!suc)
throw IOError("Could not parse pair: " + pairStr);
suc = Global::tryStringToInt(pieces[1],p1);
if(!suc)
throw IOError("Could not parse pair: " + pairStr);
if(p0 < 0 || p0 >= numBots)
throw IOError("Invalid player index in pair: " + pairStr);
if(p1 < 0 || p1 >= numBots)
throw IOError("Invalid player index in pair: " + pairStr);
if(cfg.contains("extraPairsAreOneSidedBW") && cfg.getBool("extraPairsAreOneSidedBW")) {
matchupsPerRound.push_back(std::make_pair(p0,p1));
}
else {
matchupsPerRound.push_back(std::make_pair(p0,p1));
matchupsPerRound.push_back(std::make_pair(p1,p0));
}
}
}
}
// Maybe load the predictor path
string predictorPath = "";
if (cfg.contains("predictorPath")) {
predictorPath = cfg.getString("predictorPath");
}
//Load the names of the bots and which model each bot is using
vector<string> nnModelFilesByBot(numBots);
vector<string> botNames(numBots);
for(int i = 0; i<numBots; i++) {
string idxStr = Global::intToString(i);
if(cfg.contains("botName"+idxStr))
botNames[i] = cfg.getString("botName"+idxStr);
else if(numBots == 1)
botNames[i] = cfg.getString("botName");
else
throw StringError("If more than one bot, must specify botName0, botName1,... individually");
if(cfg.contains("nnModelFile"+idxStr))
nnModelFilesByBot[i] = cfg.getString("nnModelFile"+idxStr);
else
nnModelFilesByBot[i] = cfg.getString("nnModelFile");
}
vector<bool> botIsUsed(numBots);
for(const std::pair<int,int> pair: matchupsPerRound) {
botIsUsed[pair.first] = true;
botIsUsed[pair.second] = true;
}
//Dedup and load each necessary model exactly once
vector<string> nnModelFiles;
vector<int> whichNNModel(numBots);
for(int i = 0; i<numBots; i++) {
if(!botIsUsed[i])
continue;
const string& desiredFile = nnModelFilesByBot[i];
int alreadyFoundIdx = -1;
for(int j = 0; j<nnModelFiles.size(); j++) {
if(nnModelFiles[j] == desiredFile) {
alreadyFoundIdx = j;
break;
}
}
if(alreadyFoundIdx != -1)
whichNNModel[i] = alreadyFoundIdx;
else {
whichNNModel[i] = (int)nnModelFiles.size();
nnModelFiles.push_back(desiredFile);
}
}
//Load match runner settings
int numGameThreads = cfg.getInt("numGameThreads",1,16384);
const string gameSeedBase = Global::uint64ToHexString(seedRand.nextUInt64());
//Work out an upper bound on how many concurrent nneval requests we could end up making.
int maxConcurrentEvals;
int expectedConcurrentEvals;
{
//Work out the max threads any one bot uses
int maxBotThreads = 0;
for(int i = 0; i<numBots; i++)
if(paramss[i].numThreads > maxBotThreads)
maxBotThreads = paramss[i].numThreads;
//Mutiply by the number of concurrent games we could have
expectedConcurrentEvals = maxBotThreads * numGameThreads;
//Multiply by 2 and add some buffer, just so we have plenty of headroom.
maxConcurrentEvals = expectedConcurrentEvals * 2 + 16;
}
//Initialize object for randomizing game settings and running games
PlaySettings playSettings = PlaySettings::loadForMatch(cfg);
GameRunner* gameRunner = new GameRunner(cfg, playSettings, logger);
const int minBoardXSizeUsed = gameRunner->getGameInitializer()->getMinBoardXSize();
const int minBoardYSizeUsed = gameRunner->getGameInitializer()->getMinBoardYSize();
const int maxBoardXSizeUsed = gameRunner->getGameInitializer()->getMaxBoardXSize();
const int maxBoardYSizeUsed = gameRunner->getGameInitializer()->getMaxBoardYSize();
//Initialize neural net inference engine globals, and load models
Setup::initializeSession(cfg);
const vector<string>& nnModelNames = nnModelFiles;
const int defaultMaxBatchSize = -1;
const bool defaultRequireExactNNLen = minBoardXSizeUsed == maxBoardXSizeUsed && minBoardYSizeUsed == maxBoardYSizeUsed;
const bool disableFP16 = false;
const vector<string> expectedSha256s;
vector<NNEvaluator*> nnEvals = Setup::initializeNNEvaluators(
nnModelNames,nnModelFiles,expectedSha256s,cfg,logger,seedRand,maxConcurrentEvals,expectedConcurrentEvals,
maxBoardXSizeUsed,maxBoardYSizeUsed,defaultMaxBatchSize,defaultRequireExactNNLen,disableFP16,
Setup::SETUP_FOR_MATCH
);
logger.write("Loaded neural net");
NNEvaluator *predictorEval = nullptr;
if (nnPredictorPath != "") {
const string expectedSha256 = "";
predictorEval = Setup::initializeNNEvaluator(
nnPredictorPath, nnPredictorPath, expectedSha256, cfg, logger, seedRand, maxConcurrentEvals, expectedConcurrentEvals,
maxBoardXSizeUsed, maxBoardYSizeUsed, defaultMaxBatchSize, defaultRequireExactNNLen,disableFP16,
Setup::SETUP_FOR_MATCH
);
}
vector<NNEvaluator*> nnEvalsByBot(numBots);
for(int i = 0; i<numBots; i++) {
if(!botIsUsed[i])
continue;
nnEvalsByBot[i] = nnEvals[whichNNModel[i]];
}
std::vector<std::unique_ptr<PatternBonusTable>> patternBonusTables = Setup::loadAvoidSgfPatternBonusTables(cfg,logger);
assert(patternBonusTables.size() == numBots);
//Initialize object for randomly pairing bots
int64_t numGamesTotal = cfg.getInt64("numGamesTotal",1,((int64_t)1) << 62);
MatchPairer* matchPairer = new MatchPairer(cfg,numBots,botNames,nnEvalsByBot,paramss,matchupsPerRound,numGamesTotal);
//Check for unused config keys
cfg.warnUnusedKeys(cerr,&logger);
//Done loading!
//------------------------------------------------------------------------------------
logger.write("Loaded all config stuff, starting matches");
if(!logger.isLoggingToStdout())
cout << "Loaded all config stuff, starting matches" << endl;
if(sgfOutputDir != string())
MakeDir::make(sgfOutputDir);
if(!std::atomic_is_lock_free(&shouldStop))
throw StringError("shouldStop is not lock free, signal-quitting mechanism for terminating matches will NOT work!");
std::signal(SIGINT, signalHandler);
std::signal(SIGTERM, signalHandler);
std::mutex statsMutex;
int64_t gameCount = 0;
std::map<string,double> timeUsedByBotMap;
std::map<string,double> movesByBotMap;
auto runMatchLoop = [
&gameRunner,&matchPairer,&predictorEval,&sgfOutputDir,&logger,&gameSeedBase,&patternBonusTables,
&statsMutex, &gameCount, &timeUsedByBotMap, &movesByBotMap
](
uint64_t threadHash
) {
ofstream* sgfOut = NULL;
if(sgfOutputDir.length() > 0) {
sgfOut = new ofstream();
FileUtils::open(*sgfOut, sgfOutputDir + "/" + Global::uint64ToHexString(threadHash) + ".sgfs");
}
auto shouldStopFunc = []() {
return shouldStop.load();
};
WaitableFlag* shouldPause = nullptr;
Rand thisLoopSeedRand;
while(true) {
if(shouldStop.load())
break;
FinishedGameData* gameData = NULL;
MatchPairer::BotSpec botSpecB;
MatchPairer::BotSpec botSpecW;
if (predictorEval) {
if (botSpecB.botIdx == 1)
botSpecB.predictorNNEval = predictorEval;
else
botSpecW.predictorNNEval = predictorEval;
}
if(matchPairer->getMatchup(botSpecB, botSpecW, logger)) {
string seed = gameSeedBase + ":" + Global::uint64ToHexString(thisLoopSeedRand.nextUInt64());
std::function<void(const MatchPairer::BotSpec&, Search*)> afterInitialization = [&patternBonusTables](const MatchPairer::BotSpec& spec, Search* search) {
assert(spec.botIdx < patternBonusTables.size());
search->setCopyOfExternalPatternBonusTable(patternBonusTables[spec.botIdx]);
};
const string gameDescription = "game " + seed + " between "
+ botSpecB.botName + "-" + botSpecB.baseParams.getSearchAlgoAsStr() + " (B) "
+ botSpecW.botName + "-" + botSpecW.baseParams.getSearchAlgoAsStr() + " (W)";
logger.write("Launching " + gameDescription);
gameData = gameRunner->runGame(
seed, botSpecB, botSpecW, NULL, NULL, logger,
shouldStopFunc, shouldPause, nullptr, afterInitialization, nullptr
);
logger.write("Finished " + gameDescription);
}
bool shouldContinue = gameData != NULL;
if(gameData != NULL) {
if(sgfOut != NULL) {
WriteSgf::writeSgf(*sgfOut,gameData->bName,gameData->wName,gameData->endHist,gameData,false,true);
(*sgfOut) << endl;
}
{
std::lock_guard<std::mutex> lock(statsMutex);
gameCount += 1;
timeUsedByBotMap[gameData->bName] += gameData->bTimeUsed;
timeUsedByBotMap[gameData->wName] += gameData->wTimeUsed;
movesByBotMap[gameData->bName] += (double)gameData->bMoveCount;
movesByBotMap[gameData->wName] += (double)gameData->wMoveCount;
int64_t x = gameCount;
while(x % 2 == 0 && x > 1) x /= 2;
if(x == 1 || x == 3 || x == 5) {
for(auto& pair : timeUsedByBotMap) {
logger.write(
"Avg move time used by " + pair.first + " " +
Global::doubleToString(pair.second / movesByBotMap[pair.first]) + " " +
Global::doubleToString(movesByBotMap[pair.first]) + " moves"
);
}
}
}
delete gameData;
}
if(shouldStop.load())
break;
if(!shouldContinue)
break;
}
if(sgfOut != NULL) {
sgfOut->close();
delete sgfOut;
}
logger.write("Match loop thread terminating");
};
auto runMatchLoopProtected = [&logger,&runMatchLoop](uint64_t threadHash) {
Logger::logThreadUncaught("match loop", &logger, [&](){ runMatchLoop(threadHash); });
};
Rand hashRand;
vector<std::thread> threads;
for(int i = 0; i<numGameThreads; i++) {
threads.push_back(std::thread(runMatchLoopProtected, hashRand.nextUInt64()));
}
for(int i = 0; i<threads.size(); i++)
threads[i].join();
delete matchPairer;
delete gameRunner;
nnEvalsByBot.clear();
for(int i = 0; i<nnEvals.size(); i++) {
if(nnEvals[i] != NULL) {
logger.write(nnEvals[i]->getModelFileName());
logger.write("NN rows: " + Global::int64ToString(nnEvals[i]->numRowsProcessed()));
logger.write("NN batches: " + Global::int64ToString(nnEvals[i]->numBatchesProcessed()));
logger.write("NN avg batch size: " + Global::doubleToString(nnEvals[i]->averageProcessedBatchSize()));
delete nnEvals[i];
}
}
if (predictorEval)
delete predictorEval;
NeuralNet::globalCleanup();
ScoreValue::freeTables();
if(sigReceived.load())
logger.write("Exited cleanly after signal");
logger.write("All cleaned up, quitting");
return 0;
}