uct_search() result cannot change: Check against worst.time instead of desired.time
[pachi/json.git] / uct / uct.c
blobb4c73aa74437a9bff5f3044f7779934f26980fa9
1 #include <assert.h>
2 #include <pthread.h>
3 #include <signal.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <time.h>
9 #define DEBUG
11 #include "debug.h"
12 #include "board.h"
13 #include "gtp.h"
14 #include "move.h"
15 #include "mq.h"
16 #include "playout.h"
17 #include "playout/elo.h"
18 #include "playout/moggy.h"
19 #include "playout/light.h"
20 #include "random.h"
21 #include "timeinfo.h"
22 #include "tactics.h"
23 #include "uct/internal.h"
24 #include "uct/prior.h"
25 #include "uct/tree.h"
26 #include "uct/uct.h"
27 #include "uct/walk.h"
29 struct uct_policy *policy_ucb1_init(struct uct *u, char *arg);
30 struct uct_policy *policy_ucb1amaf_init(struct uct *u, char *arg);
31 static void uct_pondering_stop(struct uct *u);
34 /* Default number of simulations to perform per move.
35 * Note that this is now in total over all threads! (Unless TM_ROOT.) */
36 #define MC_GAMES 80000
37 #define MC_GAMELEN MAX_GAMELEN
38 static const struct time_info default_ti = {
39 .period = TT_MOVE,
40 .dim = TD_GAMES,
41 .len = { .games = MC_GAMES },
44 /* How big proportion of ownermap counts must be of one color to consider
45 * the point sure. */
46 #define GJ_THRES 0.8
47 /* How many games to consider at minimum before judging groups. */
48 #define GJ_MINGAMES 500
50 /* How often to inspect the tree from the main thread to check for playout
51 * stop, progress reports, etc. (in seconds) */
52 #define TREE_BUSYWAIT_INTERVAL 0.1 /* 100ms */
54 /* Once per how many simulations (per thread) to show a progress report line. */
55 #define TREE_SIMPROGRESS_INTERVAL 10000
57 /* When terminating uct_search() early, the safety margin to add to the
58 * remaining playout number estimate when deciding whether the result can
59 * still change. */
60 #define PLAYOUT_DELTA_SAFEMARGIN 1000
63 static void
64 setup_state(struct uct *u, struct board *b, enum stone color)
66 u->t = tree_init(b, color, u->fast_alloc ? u->max_tree_size: 0);
67 if (u->force_seed)
68 fast_srandom(u->force_seed);
69 if (UDEBUGL(0))
70 fprintf(stderr, "Fresh board with random seed %lu\n", fast_getseed());
71 //board_print(b, stderr);
72 if (!u->no_book && b->moves == 0) {
73 assert(color == S_BLACK);
74 tree_load(u->t, b);
78 static void
79 reset_state(struct uct *u)
81 assert(u->t);
82 tree_done(u->t); u->t = NULL;
85 static void
86 setup_dynkomi(struct uct *u, struct board *b, enum stone to_play)
88 if (u->dynkomi > b->moves && u->t->use_extra_komi)
89 u->t->extra_komi = uct_get_extra_komi(u, b);
90 else
91 u->t->extra_komi = 0;
94 static void
95 prepare_move(struct engine *e, struct board *b, enum stone color)
97 struct uct *u = e->data;
99 if (u->t) {
100 /* Verify that we have sane state. */
101 assert(b->es == u);
102 assert(u->t && b->moves);
103 if (color != stone_other(u->t->root_color)) {
104 fprintf(stderr, "Fatal: Non-alternating play detected %d %d\n",
105 color, u->t->root_color);
106 exit(1);
109 } else {
110 /* We need fresh state. */
111 b->es = u;
112 setup_state(u, b, color);
115 u->ownermap.playouts = 0;
116 memset(u->ownermap.map, 0, board_size2(b) * sizeof(u->ownermap.map[0]));
119 static void
120 dead_group_list(struct uct *u, struct board *b, struct move_queue *mq)
122 struct group_judgement gj;
123 gj.thres = GJ_THRES;
124 gj.gs = alloca(board_size2(b) * sizeof(gj.gs[0]));
125 board_ownermap_judge_group(b, &u->ownermap, &gj);
126 groups_of_status(b, &gj, GS_DEAD, mq);
129 bool
130 uct_pass_is_safe(struct uct *u, struct board *b, enum stone color, bool pass_all_alive)
132 if (u->ownermap.playouts < GJ_MINGAMES)
133 return false;
135 struct move_queue mq = { .moves = 0 };
136 if (!pass_all_alive)
137 dead_group_list(u, b, &mq);
138 return pass_is_safe(b, color, &mq);
142 static void
143 uct_printhook_ownermap(struct board *board, coord_t c, FILE *f)
145 struct uct *u = board->es;
146 assert(u);
147 const char chr[] = ":XO,"; // dame, black, white, unclear
148 const char chm[] = ":xo,";
149 char ch = chr[board_ownermap_judge_point(&u->ownermap, c, GJ_THRES)];
150 if (ch == ',') { // less precise estimate then?
151 ch = chm[board_ownermap_judge_point(&u->ownermap, c, 0.67)];
153 fprintf(f, "%c ", ch);
156 static char *
157 uct_notify_play(struct engine *e, struct board *b, struct move *m)
159 struct uct *u = e->data;
160 if (!u->t) {
161 /* No state, create one - this is probably game beginning
162 * and we need to load the opening book right now. */
163 prepare_move(e, b, m->color);
164 assert(u->t);
167 /* Stop pondering. */
168 /* XXX: If we are about to receive multiple 'play' commands,
169 * e.g. in a rengo, we will not ponder during the rest of them. */
170 uct_pondering_stop(u);
172 if (is_resign(m->coord)) {
173 /* Reset state. */
174 reset_state(u);
175 return NULL;
178 /* Promote node of the appropriate move to the tree root. */
179 assert(u->t->root);
180 if (!tree_promote_at(u->t, b, m->coord)) {
181 if (UDEBUGL(0))
182 fprintf(stderr, "Warning: Cannot promote move node! Several play commands in row?\n");
183 reset_state(u);
184 return NULL;
186 /* Setting up dynkomi is not necessary here, probably, but we
187 * better do it anyway for consistency reasons. */
188 setup_dynkomi(u, b, stone_other(m->color));
189 return NULL;
192 static char *
193 uct_chat(struct engine *e, struct board *b, char *cmd)
195 struct uct *u = e->data;
196 static char reply[1024];
198 cmd += strspn(cmd, " \n\t");
199 if (!strncasecmp(cmd, "winrate", 7)) {
200 if (!u->t)
201 return "no game context (yet?)";
202 enum stone color = u->t->root_color;
203 struct tree_node *n = u->t->root;
204 snprintf(reply, 1024, "In %d playouts at %d threads, %s %s can win with %.2f%% probability",
205 n->u.playouts, u->threads, stone2str(color), coord2sstr(n->coord, b),
206 tree_node_get_value(u->t, -1, n->u.value) * 100);
207 if (u->t->use_extra_komi && abs(u->t->extra_komi) >= 0.5) {
208 sprintf(reply + strlen(reply), ", while self-imposing extra komi %.1f",
209 u->t->extra_komi);
211 strcat(reply, ".");
212 return reply;
214 return NULL;
217 static void
218 uct_dead_group_list(struct engine *e, struct board *b, struct move_queue *mq)
220 struct uct *u = e->data;
222 /* This means the game is probably over, no use pondering on. */
223 uct_pondering_stop(u);
225 if (u->pass_all_alive)
226 return; // no dead groups
228 bool mock_state = false;
230 if (!u->t) {
231 /* No state, but we cannot just back out - we might
232 * have passed earlier, only assuming some stones are
233 * dead, and then re-connected, only to lose counting
234 * when all stones are assumed alive. */
235 /* Mock up some state and seed the ownermap by few
236 * simulations. */
237 prepare_move(e, b, S_BLACK); assert(u->t);
238 for (int i = 0; i < GJ_MINGAMES; i++)
239 uct_playout(u, b, S_BLACK, u->t);
240 mock_state = true;
243 dead_group_list(u, b, mq);
245 if (mock_state) {
246 /* Clean up the mock state in case we will receive
247 * a genmove; we could get a non-alternating-move
248 * error from prepare_move() in that case otherwise. */
249 reset_state(u);
253 static void
254 playout_policy_done(struct playout_policy *p)
256 if (p->done) p->done(p);
257 if (p->data) free(p->data);
258 free(p);
261 static void
262 uct_done(struct engine *e)
264 /* This is called on engine reset, especially when clear_board
265 * is received and new game should begin. */
266 struct uct *u = e->data;
267 uct_pondering_stop(u);
268 if (u->t) reset_state(u);
269 free(u->ownermap.map);
271 free(u->policy);
272 free(u->random_policy);
273 playout_policy_done(u->playout);
274 uct_prior_done(u->prior);
278 /* Pachi threading structure (if uct_playouts_parallel() is used):
280 * main thread
281 * | main(), GTP communication, ...
282 * | starts and stops the search managed by thread_manager
284 * thread_manager
285 * | spawns and collects worker threads
287 * worker0
288 * worker1
289 * ...
290 * workerK
291 * uct_playouts() loop, doing descend-playout until uct_halt
293 * Another way to look at it is by functions (lines denote thread boundaries):
295 * | uct_genmove()
296 * | uct_search() (uct_search_start() .. uct_search_stop())
297 * | -----------------------
298 * | spawn_thread_manager()
299 * | -----------------------
300 * | spawn_worker()
301 * V uct_playouts() */
303 /* Set in thread manager in case the workers should stop. */
304 volatile sig_atomic_t uct_halt = 0;
305 /* ID of the running worker thread. */
306 __thread int thread_id = -1;
307 /* ID of the thread manager. */
308 static pthread_t thread_manager;
309 static bool thread_manager_running;
311 static pthread_mutex_t finish_mutex = PTHREAD_MUTEX_INITIALIZER;
312 static pthread_cond_t finish_cond = PTHREAD_COND_INITIALIZER;
313 static volatile int finish_thread;
314 static pthread_mutex_t finish_serializer = PTHREAD_MUTEX_INITIALIZER;
316 struct spawn_ctx {
317 int tid;
318 struct uct *u;
319 struct board *b;
320 enum stone color;
321 struct tree *t;
322 unsigned long seed;
323 int games;
326 static void *
327 spawn_worker(void *ctx_)
329 struct spawn_ctx *ctx = ctx_;
330 /* Setup */
331 fast_srandom(ctx->seed);
332 thread_id = ctx->tid;
333 /* Run */
334 ctx->games = uct_playouts(ctx->u, ctx->b, ctx->color, ctx->t);
335 /* Finish */
336 pthread_mutex_lock(&finish_serializer);
337 pthread_mutex_lock(&finish_mutex);
338 finish_thread = ctx->tid;
339 pthread_cond_signal(&finish_cond);
340 pthread_mutex_unlock(&finish_mutex);
341 return ctx;
344 /* Thread manager, controlling worker threads. It must be called with
345 * finish_mutex lock held, but it will unlock it itself before exiting;
346 * this is necessary to be completely deadlock-free. */
347 /* The finish_cond can be signalled for it to stop; in that case,
348 * the caller should set finish_thread = -1. */
349 /* After it is started, it will update mctx->t to point at some tree
350 * used for the actual search (matters only for TM_ROOT), on return
351 * it will set mctx->games to the number of performed simulations. */
352 static void *
353 spawn_thread_manager(void *ctx_)
355 /* In thread_manager, we use only some of the ctx fields. */
356 struct spawn_ctx *mctx = ctx_;
357 struct uct *u = mctx->u;
358 struct tree *t = mctx->t;
359 bool shared_tree = u->parallel_tree;
360 fast_srandom(mctx->seed);
362 int played_games = 0;
363 pthread_t threads[u->threads];
364 int joined = 0;
366 uct_halt = 0;
368 /* Spawn threads... */
369 for (int ti = 0; ti < u->threads; ti++) {
370 struct spawn_ctx *ctx = malloc(sizeof(*ctx));
371 ctx->u = u; ctx->b = mctx->b; ctx->color = mctx->color;
372 mctx->t = ctx->t = shared_tree ? t : tree_copy(t);
373 ctx->tid = ti; ctx->seed = fast_random(65536) + ti;
374 pthread_create(&threads[ti], NULL, spawn_worker, ctx);
375 if (UDEBUGL(2))
376 fprintf(stderr, "Spawned worker %d\n", ti);
379 /* ...and collect them back: */
380 while (joined < u->threads) {
381 /* Wait for some thread to finish... */
382 pthread_cond_wait(&finish_cond, &finish_mutex);
383 if (finish_thread < 0) {
384 /* Stop-by-caller. Tell the workers to wrap up. */
385 uct_halt = 1;
386 continue;
388 /* ...and gather its remnants. */
389 struct spawn_ctx *ctx;
390 pthread_join(threads[finish_thread], (void **) &ctx);
391 played_games += ctx->games;
392 joined++;
393 if (!shared_tree) {
394 if (ctx->t == mctx->t) mctx->t = t;
395 tree_merge(t, ctx->t);
396 tree_done(ctx->t);
398 free(ctx);
399 if (UDEBUGL(2))
400 fprintf(stderr, "Joined worker %d\n", finish_thread);
401 pthread_mutex_unlock(&finish_serializer);
404 pthread_mutex_unlock(&finish_mutex);
406 if (!shared_tree)
407 tree_normalize(mctx->t, u->threads);
409 mctx->games = played_games;
410 return mctx;
413 static struct spawn_ctx *
414 uct_search_start(struct uct *u, struct board *b, enum stone color, struct tree *t)
416 assert(u->threads > 0);
417 assert(!thread_manager_running);
419 struct spawn_ctx ctx = { .u = u, .b = b, .color = color, .t = t, .seed = fast_random(65536) };
420 static struct spawn_ctx mctx; mctx = ctx;
421 pthread_mutex_lock(&finish_mutex);
422 pthread_create(&thread_manager, NULL, spawn_thread_manager, &mctx);
423 thread_manager_running = true;
424 return &mctx;
427 static struct spawn_ctx *
428 uct_search_stop(void)
430 assert(thread_manager_running);
432 /* Signal thread manager to stop the workers. */
433 pthread_mutex_lock(&finish_mutex);
434 finish_thread = -1;
435 pthread_cond_signal(&finish_cond);
436 pthread_mutex_unlock(&finish_mutex);
438 /* Collect the thread manager. */
439 struct spawn_ctx *pctx;
440 thread_manager_running = false;
441 pthread_join(thread_manager, (void **) &pctx);
442 return pctx;
446 /* Run time-limited MCTS search on foreground. */
447 static int
448 uct_search(struct uct *u, struct board *b, struct time_info *ti, enum stone color, struct tree *t)
450 int base_playouts = u->t->root->u.playouts;
451 if (UDEBUGL(2) && base_playouts > 0)
452 fprintf(stderr, "<pre-simulated %d games skipped>\n", base_playouts);
454 /* Set up time conditions. */
455 if (ti->period == TT_NULL) *ti = default_ti;
456 struct time_stop stop;
457 time_stop_conditions(ti, b, u->fuseki_end, u->yose_start, &stop);
459 /* Number of last game with progress print. */
460 int last_print = t->root->u.playouts;
461 /* Number of simulations to wait before next print. */
462 int print_interval = TREE_SIMPROGRESS_INTERVAL * (u->thread_model == TM_ROOT ? 1 : u->threads);
463 /* Printed notification about full memory? */
464 bool print_fullmem = false;
466 struct spawn_ctx *ctx = uct_search_start(u, b, color, t);
468 /* The search tree is ctx->t. This is normally == t, but in case of
469 * TM_ROOT, it is one of the trees belonging to the independent
470 * workers. It is important to reference ctx->t directly since the
471 * thread manager will swap the tree pointer asynchronously. */
472 /* XXX: This means TM_ROOT support is suboptimal since single stalled
473 * thread can stall the others in case of limiting the search by game
474 * count. However, TM_ROOT just does not deserve any more extra code
475 * right now. */
477 struct tree_node *best = NULL, *prev_best;
478 struct tree_node *winner = NULL, *prev_winner;
480 double busywait_interval = TREE_BUSYWAIT_INTERVAL;
482 /* Now, just periodically poll the search tree. */
483 while (1) {
484 time_sleep(busywait_interval);
485 /* busywait_interval should never be less than desired time, or the
486 * time control is broken. But if it happens to be less, we still search
487 * at least 100ms otherwise the move is completely random. */
489 int i = ctx->t->root->u.playouts;
491 /* Print progress? */
492 if (i - last_print > print_interval) {
493 last_print += print_interval; // keep the numbers tidy
494 uct_progress_status(u, ctx->t, color, last_print);
496 if (!print_fullmem && ctx->t->nodes_size > u->max_tree_size) {
497 if (UDEBUGL(2))
498 fprintf(stderr, "memory limit hit (%ld > %lu)\n", ctx->t->nodes_size, u->max_tree_size);
499 print_fullmem = true;
502 /* Check against time settings. */
503 bool desired_done = false;
504 if (ti->dim == TD_WALLTIME) {
505 double elapsed = time_now() - ti->len.t.timer_start;
506 if (elapsed > stop.worst.time) break;
507 desired_done = elapsed > stop.desired.time;
509 } else { assert(ti->dim == TD_GAMES);
510 if (i > stop.worst.playouts) break;
511 desired_done = i > stop.desired.playouts;
514 prev_best = best;
515 best = u->policy->choose(u->policy, ctx->t->root, b, color, resign);
516 /* Second-best move. */
517 struct tree_node *best2 = u->policy->choose(u->policy, ctx->t->root, b, color, best->coord);
519 /* Early break in won situation. */
520 if (best && ((best->u.playouts >= 2000 && tree_node_get_value(ctx->t, 1, best->u.value) >= u->loss_threshold)
521 || (best->u.playouts >= 500 && tree_node_get_value(ctx->t, 1, best->u.value) >= 0.95)))
522 break;
523 /* Break early if we estimate the second-best move cannot
524 * catch up in assigned time anymore. We use all our time
525 * if we are in byoyomi with single stone remaining in our
526 * period, however. */
527 if (best && best2 && ti->dim == TD_WALLTIME
528 && (ti->len.t.main_time > 0 || ti->len.t.byoyomi_stones > 1)) {
529 double elapsed = time_now() - ti->len.t.timer_start;
530 double remaining = stop.worst.time - elapsed;
531 double pps = ((double)i - base_playouts) / elapsed;
532 double estplayouts = remaining * pps + PLAYOUT_DELTA_SAFEMARGIN;
533 if (best->u.playouts > best2->u.playouts + estplayouts) {
534 if (UDEBUGL(2))
535 fprintf(stderr, "Early stop, result cannot change: "
536 "best %d, best2 %d, estimated %f simulations to go\n",
537 best->u.playouts, best2->u.playouts, estplayouts);
538 break;
542 /* We want to stop simulating, but are willing to keep trying
543 * if we aren't completely sure about the winner yet. */
544 if (desired_done) {
545 if (!best) {
546 if (UDEBUGL(2))
547 fprintf(stderr, "Did not find best move, still trying...\n");
548 continue;
551 if (u->best2_ratio > 0) {
552 /* Check best/best2 simulations ratio. If the
553 * two best moves give very similar results,
554 * keep simulating. */
555 if (best2 && best2->u.playouts
556 && (double)best->u.playouts / best2->u.playouts < u->best2_ratio) {
557 if (UDEBUGL(2))
558 fprintf(stderr, "Best2 ratio %f < threshold %f\n",
559 (double)best->u.playouts / best2->u.playouts,
560 u->best2_ratio);
561 continue;
565 if (u->policy->winner && u->policy->evaluate) {
566 prev_winner = winner;
567 winner = u->policy->winner(u->policy, ctx->t, ctx->t->root);
568 if (winner && winner != best) {
569 /* Keep simulating if best explored
570 * does not have also highest value. */
571 if (UDEBUGL(2) && (best != prev_best || winner != prev_winner)) {
572 fprintf(stderr, "[%d] best %3s [%d] %f != winner %3s [%d] %f\n", i,
573 coord2sstr(best->coord, ctx->t->board),
574 best->u.playouts, tree_node_get_value(ctx->t, 1, best->u.value),
575 coord2sstr(winner->coord, ctx->t->board),
576 winner->u.playouts, tree_node_get_value(ctx->t, 1, winner->u.value));
578 continue;
582 /* No reason to keep simulating, bye. */
583 break;
586 /* TODO: Early break if best->variance goes under threshold and we already
587 * have enough playouts (possibly thanks to book or to pondering)? */
590 ctx = uct_search_stop();
592 if (UDEBUGL(2))
593 tree_dump(t, u->dumpthres);
594 if (UDEBUGL(0))
595 uct_progress_status(u, t, color, ctx->games);
597 return ctx->games;
601 /* Start pondering background with @color to play. */
602 static void
603 uct_pondering_start(struct uct *u, struct board *b0, struct tree *t, enum stone color)
605 if (UDEBUGL(1))
606 fprintf(stderr, "Starting to ponder with color %s\n", stone2str(stone_other(color)));
607 u->pondering = true;
609 /* We need a local board copy to ponder upon. */
610 struct board *b = malloc(sizeof(*b)); board_copy(b, b0);
612 /* *b0 did not have the genmove'd move played yet. */
613 struct move m = { t->root->coord, t->root_color };
614 int res = board_play(b, &m);
615 assert(res >= 0);
616 setup_dynkomi(u, b, stone_other(m.color));
618 /* Start MCTS manager thread "headless". */
619 uct_search_start(u, b, color, t);
622 /* uct_search_stop() frontend for the pondering (non-genmove) mode. */
623 static void
624 uct_pondering_stop(struct uct *u)
626 u->pondering = false;
627 if (!thread_manager_running)
628 return;
630 /* Stop the thread manager. */
631 struct spawn_ctx *ctx = uct_search_stop();
632 if (UDEBUGL(1)) {
633 fprintf(stderr, "(pondering) ");
634 uct_progress_status(u, ctx->t, ctx->color, ctx->games);
636 free(ctx->b);
640 static coord_t *
641 uct_genmove(struct engine *e, struct board *b, struct time_info *ti, enum stone color, bool pass_all_alive)
643 double start_time = time_now();
644 struct uct *u = e->data;
646 if (b->superko_violation) {
647 fprintf(stderr, "!!! WARNING: SUPERKO VIOLATION OCCURED BEFORE THIS MOVE\n");
648 fprintf(stderr, "Maybe you play with situational instead of positional superko?\n");
649 fprintf(stderr, "I'm going to ignore the violation, but note that I may miss\n");
650 fprintf(stderr, "some moves valid under this ruleset because of this.\n");
651 b->superko_violation = false;
654 /* Seed the tree. */
655 uct_pondering_stop(u);
656 prepare_move(e, b, color);
657 assert(u->t);
659 /* How to decide whether to use dynkomi in this game? Since we use
660 * pondering, it's not simple "who-to-play" matter. Decide based on
661 * the last genmove issued. */
662 u->t->use_extra_komi = !!(u->dynkomi_mask & color);
663 setup_dynkomi(u, b, color);
665 /* Perform the Monte Carlo Tree Search! */
666 int played_games = uct_search(u, b, ti, color, u->t);
668 /* Choose the best move from the tree. */
669 struct tree_node *best = u->policy->choose(u->policy, u->t->root, b, color, resign);
670 if (!best) {
671 reset_state(u);
672 return coord_copy(pass);
674 if (UDEBUGL(1))
675 fprintf(stderr, "*** WINNER is %s (%d,%d) with score %1.4f (%d/%d:%d games)\n",
676 coord2sstr(best->coord, b), coord_x(best->coord, b), coord_y(best->coord, b),
677 tree_node_get_value(u->t, 1, best->u.value),
678 best->u.playouts, u->t->root->u.playouts, played_games);
680 /* Do not resign if we're so short of time that evaluation of best move is completely
681 * unreliable, we might be winning actually. In this case best is almost random but
682 * still better than resign. */
683 if (tree_node_get_value(u->t, 1, best->u.value) < u->resign_ratio && !is_pass(best->coord)
684 && best->u.playouts > GJ_MINGAMES) {
685 reset_state(u);
686 return coord_copy(resign);
689 /* If the opponent just passed and we win counting, always
690 * pass as well. */
691 if (b->moves > 1 && is_pass(b->last_move.coord)) {
692 /* Make sure enough playouts are simulated. */
693 while (u->ownermap.playouts < GJ_MINGAMES)
694 uct_playout(u, b, color, u->t);
695 if (uct_pass_is_safe(u, b, color, u->pass_all_alive || pass_all_alive)) {
696 if (UDEBUGL(0))
697 fprintf(stderr, "<Will rather pass, looks safe enough.>\n");
698 best->coord = pass;
702 tree_promote_node(u->t, &best);
703 /* After a pass, pondering is harmful for two reasons:
704 * (i) We might keep pondering even when the game is over.
705 * Of course this is the case for opponent resign as well.
706 * (ii) More importantly, the ownermap will get skewed since
707 * the UCT will start cutting off any playouts. */
708 if (u->pondering_opt && !is_pass(best->coord)) {
709 uct_pondering_start(u, b, u->t, stone_other(color));
711 if (UDEBUGL(2)) {
712 double time = time_now() - start_time + 0.000001; /* avoid divide by zero */
713 fprintf(stderr, "genmove in %0.2fs (%d games/s, %d games/s/thread)\n",
714 time, (int)(played_games/time), (int)(played_games/time/u->threads));
716 return coord_copy(best->coord);
720 bool
721 uct_genbook(struct engine *e, struct board *b, struct time_info *ti, enum stone color)
723 struct uct *u = e->data;
724 if (!u->t) prepare_move(e, b, color);
725 assert(u->t);
727 if (ti->dim == TD_GAMES) {
728 /* Don't count in games that already went into the book. */
729 ti->len.games += u->t->root->u.playouts;
731 uct_search(u, b, ti, color, u->t);
733 assert(ti->dim == TD_GAMES);
734 tree_save(u->t, b, ti->len.games / 100);
736 return true;
739 void
740 uct_dumpbook(struct engine *e, struct board *b, enum stone color)
742 struct uct *u = e->data;
743 struct tree *t = tree_init(b, color, u->fast_alloc ? u->max_tree_size: 0);
744 tree_load(t, b);
745 tree_dump(t, 0);
746 tree_done(t);
750 struct uct *
751 uct_state_init(char *arg, struct board *b)
753 struct uct *u = calloc(1, sizeof(struct uct));
755 u->debug_level = 3;
756 u->gamelen = MC_GAMELEN;
757 u->mercymin = 0;
758 u->expand_p = 2;
759 u->dumpthres = 1000;
760 u->playout_amaf = true;
761 u->playout_amaf_nakade = false;
762 u->amaf_prior = false;
763 u->max_tree_size = 3072ULL * 1048576;
765 if (board_size(b) - 2 >= 19)
766 u->dynkomi = 200;
767 u->dynkomi_mask = S_BLACK;
769 u->threads = 1;
770 u->thread_model = TM_TREEVL;
771 u->parallel_tree = true;
772 u->virtual_loss = true;
773 u->fuseki_end = 20; // max time at 361*20% = 72 moves (our 36th move, still 99 to play)
774 u->yose_start = 40; // (100-40-25)*361/100/2 = 63 moves still to play by us then
776 u->val_scale = 0.04; u->val_points = 40;
778 if (arg) {
779 char *optspec, *next = arg;
780 while (*next) {
781 optspec = next;
782 next += strcspn(next, ",");
783 if (*next) { *next++ = 0; } else { *next = 0; }
785 char *optname = optspec;
786 char *optval = strchr(optspec, '=');
787 if (optval) *optval++ = 0;
789 if (!strcasecmp(optname, "debug")) {
790 if (optval)
791 u->debug_level = atoi(optval);
792 else
793 u->debug_level++;
794 } else if (!strcasecmp(optname, "mercy") && optval) {
795 /* Minimal difference of black/white captures
796 * to stop playout - "Mercy Rule". Speeds up
797 * hopeless playouts at the expense of some
798 * accuracy. */
799 u->mercymin = atoi(optval);
800 } else if (!strcasecmp(optname, "gamelen") && optval) {
801 u->gamelen = atoi(optval);
802 } else if (!strcasecmp(optname, "expand_p") && optval) {
803 u->expand_p = atoi(optval);
804 } else if (!strcasecmp(optname, "dumpthres") && optval) {
805 u->dumpthres = atoi(optval);
806 } else if (!strcasecmp(optname, "best2_ratio") && optval) {
807 /* If set, prolong simulating while
808 * first_best/second_best playouts ratio
809 * is less than best2_ratio. */
810 u->best2_ratio = atof(optval);
811 } else if (!strcasecmp(optname, "playout_amaf")) {
812 /* Whether to include random playout moves in
813 * AMAF as well. (Otherwise, only tree moves
814 * are included in AMAF. Of course makes sense
815 * only in connection with an AMAF policy.) */
816 /* with-without: 55.5% (+-4.1) */
817 if (optval && *optval == '0')
818 u->playout_amaf = false;
819 else
820 u->playout_amaf = true;
821 } else if (!strcasecmp(optname, "playout_amaf_nakade")) {
822 /* Whether to include nakade moves from playouts
823 * in the AMAF statistics; this tends to nullify
824 * the playout_amaf effect by adding too much
825 * noise. */
826 if (optval && *optval == '0')
827 u->playout_amaf_nakade = false;
828 else
829 u->playout_amaf_nakade = true;
830 } else if (!strcasecmp(optname, "playout_amaf_cutoff") && optval) {
831 /* Keep only first N% of playout stage AMAF
832 * information. */
833 u->playout_amaf_cutoff = atoi(optval);
834 } else if ((!strcasecmp(optname, "policy") || !strcasecmp(optname, "random_policy")) && optval) {
835 char *policyarg = strchr(optval, ':');
836 struct uct_policy **p = !strcasecmp(optname, "policy") ? &u->policy : &u->random_policy;
837 if (policyarg)
838 *policyarg++ = 0;
839 if (!strcasecmp(optval, "ucb1")) {
840 *p = policy_ucb1_init(u, policyarg);
841 } else if (!strcasecmp(optval, "ucb1amaf")) {
842 *p = policy_ucb1amaf_init(u, policyarg);
843 } else {
844 fprintf(stderr, "UCT: Invalid tree policy %s\n", optval);
845 exit(1);
847 } else if (!strcasecmp(optname, "playout") && optval) {
848 char *playoutarg = strchr(optval, ':');
849 if (playoutarg)
850 *playoutarg++ = 0;
851 if (!strcasecmp(optval, "moggy")) {
852 u->playout = playout_moggy_init(playoutarg);
853 } else if (!strcasecmp(optval, "light")) {
854 u->playout = playout_light_init(playoutarg);
855 } else if (!strcasecmp(optval, "elo")) {
856 u->playout = playout_elo_init(playoutarg);
857 } else {
858 fprintf(stderr, "UCT: Invalid playout policy %s\n", optval);
859 exit(1);
861 } else if (!strcasecmp(optname, "prior") && optval) {
862 u->prior = uct_prior_init(optval, b);
863 } else if (!strcasecmp(optname, "amaf_prior") && optval) {
864 u->amaf_prior = atoi(optval);
865 } else if (!strcasecmp(optname, "threads") && optval) {
866 /* By default, Pachi will run with only single
867 * tree search thread! */
868 u->threads = atoi(optval);
869 } else if (!strcasecmp(optname, "thread_model") && optval) {
870 if (!strcasecmp(optval, "root")) {
871 /* Root parallelization - each thread
872 * does independent search, trees are
873 * merged at the end. */
874 u->thread_model = TM_ROOT;
875 u->parallel_tree = false;
876 u->virtual_loss = false;
877 } else if (!strcasecmp(optval, "tree")) {
878 /* Tree parallelization - all threads
879 * grind on the same tree. */
880 u->thread_model = TM_TREE;
881 u->parallel_tree = true;
882 u->virtual_loss = false;
883 } else if (!strcasecmp(optval, "treevl")) {
884 /* Tree parallelization, but also
885 * with virtual losses - this discou-
886 * rages most threads choosing the
887 * same tree branches to read. */
888 u->thread_model = TM_TREEVL;
889 u->parallel_tree = true;
890 u->virtual_loss = true;
891 } else {
892 fprintf(stderr, "UCT: Invalid thread model %s\n", optval);
893 exit(1);
895 } else if (!strcasecmp(optname, "pondering")) {
896 /* Keep searching even during opponent's turn. */
897 u->pondering_opt = !optval || atoi(optval);
898 } else if (!strcasecmp(optname, "fuseki_end") && optval) {
899 /* At the very beginning it's not worth thinking
900 * too long because the playout evaluations are
901 * very noisy. So gradually increase the thinking
902 * time up to maximum when fuseki_end percent
903 * of the board has been played.
904 * This only applies if we are not in byoyomi. */
905 u->fuseki_end = atoi(optval);
906 } else if (!strcasecmp(optname, "yose_start") && optval) {
907 /* When yose_start percent of the board has been
908 * played, or if we are in byoyomi, stop spending
909 * more time and spread the remaining time
910 * uniformly.
911 * Between fuseki_end and yose_start, we spend
912 * a constant proportion of the remaining time
913 * on each move. (yose_start should actually
914 * be much earlier than when real yose start,
915 * but "yose" is a good short name to convey
916 * the idea.) */
917 u->yose_start = atoi(optval);
918 } else if (!strcasecmp(optname, "force_seed") && optval) {
919 u->force_seed = atoi(optval);
920 } else if (!strcasecmp(optname, "no_book")) {
921 u->no_book = true;
922 } else if (!strcasecmp(optname, "dynkomi")) {
923 /* Dynamic komi in handicap game; linearly
924 * decreases to basic settings until move
925 * #optval. */
926 u->dynkomi = optval ? atoi(optval) : 150;
927 } else if (!strcasecmp(optname, "dynkomi_mask") && optval) {
928 /* Bitmask of colors the player must be
929 * for dynkomi be applied; you may want
930 * to use dynkomi_mask=3 to allow dynkomi
931 * even in games where Pachi is white. */
932 u->dynkomi_mask = atoi(optval);
933 } else if (!strcasecmp(optname, "val_scale") && optval) {
934 /* How much of the game result value should be
935 * influenced by win size. Zero means it isn't. */
936 u->val_scale = atof(optval);
937 } else if (!strcasecmp(optname, "val_points") && optval) {
938 /* Maximum size of win to be scaled into game
939 * result value. Zero means boardsize^2. */
940 u->val_points = atoi(optval) * 2; // result values are doubled
941 } else if (!strcasecmp(optname, "val_extra")) {
942 /* If false, the score coefficient will be simply
943 * added to the value, instead of scaling the result
944 * coefficient because of it. */
945 u->val_extra = !optval || atoi(optval);
946 } else if (!strcasecmp(optname, "root_heuristic") && optval) {
947 /* Whether to bias exploration by root node values
948 * (must be supported by the used policy).
949 * 0: Don't.
950 * 1: Do, value = result.
951 * Try to temper the result:
952 * 2: Do, value = 0.5+(result-expected)/2.
953 * 3: Do, value = 0.5+bzz((result-expected)^2). */
954 u->root_heuristic = atoi(optval);
955 } else if (!strcasecmp(optname, "pass_all_alive")) {
956 /* Whether to consider all stones alive at the game
957 * end instead of marking dead groupd. */
958 u->pass_all_alive = !optval || atoi(optval);
959 } else if (!strcasecmp(optname, "random_policy_chance") && optval) {
960 /* If specified (N), with probability 1/N, random_policy policy
961 * descend is used instead of main policy descend; useful
962 * if specified policy (e.g. UCB1AMAF) can make unduly biased
963 * choices sometimes, you can fall back to e.g.
964 * random_policy=UCB1. */
965 u->random_policy_chance = atoi(optval);
966 } else if (!strcasecmp(optname, "max_tree_size") && optval) {
967 /* Maximum amount of memory [MiB] consumed by the move tree.
968 * Default is 3072 (3 GiB). Note that if you use TM_ROOT,
969 * this limits size of only one of the trees, not all of them
970 * together. */
971 u->max_tree_size = atol(optval) * 1048576;
972 } else if (!strcasecmp(optname, "fast_alloc")) {
973 u->fast_alloc = !optval || atoi(optval);
974 } else if (!strcasecmp(optname, "banner") && optval) {
975 /* Additional banner string. This must come as the
976 * last engine parameter. */
977 if (*next) *--next = ',';
978 u->banner = strdup(optval);
979 break;
980 } else {
981 fprintf(stderr, "uct: Invalid engine argument %s or missing value\n", optname);
982 exit(1);
987 u->resign_ratio = 0.2; /* Resign when most games are lost. */
988 u->loss_threshold = 0.85; /* Stop reading if after at least 5000 playouts this is best value. */
989 if (!u->policy)
990 u->policy = policy_ucb1amaf_init(u, NULL);
992 if (!!u->random_policy_chance ^ !!u->random_policy) {
993 fprintf(stderr, "uct: Only one of random_policy and random_policy_chance is set\n");
994 exit(1);
997 if (u->fast_alloc && !u->parallel_tree) {
998 fprintf(stderr, "fast_alloc not supported with root parallelization.\n");
999 exit(1);
1002 if (!u->prior)
1003 u->prior = uct_prior_init(NULL, b);
1005 if (!u->playout)
1006 u->playout = playout_moggy_init(NULL);
1007 u->playout->debug_level = u->debug_level;
1009 u->ownermap.map = malloc(board_size2(b) * sizeof(u->ownermap.map[0]));
1011 /* Some things remain uninitialized for now - the opening book
1012 * is not loaded and the tree not set up. */
1013 /* This will be initialized in setup_state() at the first move
1014 * received/requested. This is because right now we are not aware
1015 * about any komi or handicap setup and such. */
1017 return u;
1020 struct engine *
1021 engine_uct_init(char *arg, struct board *b)
1023 struct uct *u = uct_state_init(arg, b);
1024 struct engine *e = calloc(1, sizeof(struct engine));
1025 e->name = "UCT Engine";
1026 e->printhook = uct_printhook_ownermap;
1027 e->notify_play = uct_notify_play;
1028 e->chat = uct_chat;
1029 e->genmove = uct_genmove;
1030 e->dead_group_list = uct_dead_group_list;
1031 e->done = uct_done;
1032 e->data = u;
1034 const char banner[] = "I'm playing UCT. When I'm losing, I will resign, "
1035 "if I think I win, I play until you pass. "
1036 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
1037 if (!u->banner) u->banner = "";
1038 e->comment = malloc(sizeof(banner) + strlen(u->banner) + 1);
1039 sprintf(e->comment, "%s %s", banner, u->banner);
1041 return e;