For TD_GAMES (no time control), set worst_playouts = desired_playouts.
[pachi.git] / uct / uct.c
blobf9ea26bc16607da6ec4db31b8ecd228b8d5d41fc
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
39 /* How big proportion of ownermap counts must be of one color to consider
40 * the point sure. */
41 #define GJ_THRES 0.8
42 /* How many games to consider at minimum before judging groups. */
43 #define GJ_MINGAMES 500
45 /* How often to inspect the tree from the main thread to check for playout
46 * stop, progress reports, etc. (in seconds) */
47 #define TREE_BUSYWAIT_INTERVAL 0.1 /* 100ms */
49 /* For safety, use at most 3 times the desired time on a single move
50 * in main time, and 1.1 times in byoyomi. */
51 #define MAX_MAIN_TIME_EXTENSION 3.0
52 #define MAX_BYOYOMI_TIME_EXTENSION 1.1
54 /* Once per how many simulations (per thread) to show a progress report line. */
55 #define TREE_SIMPROGRESS_INTERVAL 10000
58 static void
59 setup_state(struct uct *u, struct board *b, enum stone color)
61 u->t = tree_init(b, color, u->fast_alloc ? u->max_tree_size: 0);
62 if (u->force_seed)
63 fast_srandom(u->force_seed);
64 if (UDEBUGL(0))
65 fprintf(stderr, "Fresh board with random seed %lu\n", fast_getseed());
66 //board_print(b, stderr);
67 if (!u->no_book && b->moves == 0) {
68 assert(color == S_BLACK);
69 tree_load(u->t, b);
73 static void
74 reset_state(struct uct *u)
76 assert(u->t);
77 tree_done(u->t); u->t = NULL;
80 static void
81 prepare_move(struct engine *e, struct board *b, enum stone color)
83 struct uct *u = e->data;
85 if (u->t) {
86 /* Verify that we have sane state. */
87 assert(b->es == u);
88 assert(u->t && b->moves);
89 if (color != stone_other(u->t->root_color)) {
90 fprintf(stderr, "Fatal: Non-alternating play detected %d %d\n",
91 color, u->t->root_color);
92 exit(1);
95 } else {
96 /* We need fresh state. */
97 b->es = u;
98 setup_state(u, b, color);
101 if (u->dynkomi && u->dynkomi > b->moves && (color & u->dynkomi_mask))
102 u->t->extra_komi = uct_get_extra_komi(u, b);
104 u->ownermap.playouts = 0;
105 memset(u->ownermap.map, 0, board_size2(b) * sizeof(u->ownermap.map[0]));
108 static void
109 dead_group_list(struct uct *u, struct board *b, struct move_queue *mq)
111 struct group_judgement gj;
112 gj.thres = GJ_THRES;
113 gj.gs = alloca(board_size2(b) * sizeof(gj.gs[0]));
114 board_ownermap_judge_group(b, &u->ownermap, &gj);
115 groups_of_status(b, &gj, GS_DEAD, mq);
118 bool
119 uct_pass_is_safe(struct uct *u, struct board *b, enum stone color, bool pass_all_alive)
121 if (u->ownermap.playouts < GJ_MINGAMES)
122 return false;
124 struct move_queue mq = { .moves = 0 };
125 if (!pass_all_alive)
126 dead_group_list(u, b, &mq);
127 return pass_is_safe(b, color, &mq);
131 static void
132 uct_printhook_ownermap(struct board *board, coord_t c, FILE *f)
134 struct uct *u = board->es;
135 assert(u);
136 const char chr[] = ":XO,"; // dame, black, white, unclear
137 const char chm[] = ":xo,";
138 char ch = chr[board_ownermap_judge_point(&u->ownermap, c, GJ_THRES)];
139 if (ch == ',') { // less precise estimate then?
140 ch = chm[board_ownermap_judge_point(&u->ownermap, c, 0.67)];
142 fprintf(f, "%c ", ch);
145 static char *
146 uct_notify_play(struct engine *e, struct board *b, struct move *m)
148 struct uct *u = e->data;
149 if (!u->t) {
150 /* No state, create one - this is probably game beginning
151 * and we need to load the opening book right now. */
152 prepare_move(e, b, m->color);
153 assert(u->t);
156 /* Stop pondering. */
157 /* XXX: If we are about to receive multiple 'play' commands,
158 * e.g. in a rengo, we will not ponder during the rest of them. */
159 uct_pondering_stop(u);
161 if (is_resign(m->coord)) {
162 /* Reset state. */
163 reset_state(u);
164 return NULL;
167 /* Promote node of the appropriate move to the tree root. */
168 assert(u->t->root);
169 if (!tree_promote_at(u->t, b, m->coord)) {
170 if (UDEBUGL(0))
171 fprintf(stderr, "Warning: Cannot promote move node! Several play commands in row?\n");
172 reset_state(u);
173 return NULL;
176 return NULL;
179 static char *
180 uct_chat(struct engine *e, struct board *b, char *cmd)
182 struct uct *u = e->data;
183 static char reply[1024];
185 cmd += strspn(cmd, " \n\t");
186 if (!strncasecmp(cmd, "winrate", 7)) {
187 if (!u->t)
188 return "no game context (yet?)";
189 enum stone color = u->t->root_color;
190 struct tree_node *n = u->t->root;
191 snprintf(reply, 1024, "In %d playouts at %d threads, %s %s can win with %.2f%% probability",
192 n->u.playouts, u->threads, stone2str(color), coord2sstr(n->coord, b),
193 tree_node_get_value(u->t, -1, n->u.value) * 100);
194 if (abs(u->t->extra_komi) >= 0.5) {
195 sprintf(reply + strlen(reply), ", while self-imposing extra komi %.1f",
196 u->t->extra_komi);
198 strcat(reply, ".");
199 return reply;
201 return NULL;
204 static void
205 uct_dead_group_list(struct engine *e, struct board *b, struct move_queue *mq)
207 struct uct *u = e->data;
209 /* This means the game is probably over, no use pondering on. */
210 uct_pondering_stop(u);
212 if (u->pass_all_alive)
213 return; // no dead groups
215 bool mock_state = false;
217 if (!u->t) {
218 /* No state, but we cannot just back out - we might
219 * have passed earlier, only assuming some stones are
220 * dead, and then re-connected, only to lose counting
221 * when all stones are assumed alive. */
222 /* Mock up some state and seed the ownermap by few
223 * simulations. */
224 prepare_move(e, b, S_BLACK); assert(u->t);
225 for (int i = 0; i < GJ_MINGAMES; i++)
226 uct_playout(u, b, S_BLACK, u->t);
227 mock_state = true;
230 dead_group_list(u, b, mq);
232 if (mock_state) {
233 /* Clean up the mock state in case we will receive
234 * a genmove; we could get a non-alternating-move
235 * error from prepare_move() in that case otherwise. */
236 reset_state(u);
240 static void
241 playout_policy_done(struct playout_policy *p)
243 if (p->done) p->done(p);
244 if (p->data) free(p->data);
245 free(p);
248 static void
249 uct_done(struct engine *e)
251 /* This is called on engine reset, especially when clear_board
252 * is received and new game should begin. */
253 struct uct *u = e->data;
254 uct_pondering_stop(u);
255 if (u->t) reset_state(u);
256 free(u->ownermap.map);
258 free(u->policy);
259 free(u->random_policy);
260 playout_policy_done(u->playout);
261 uct_prior_done(u->prior);
265 /* Pachi threading structure (if uct_playouts_parallel() is used):
267 * main thread
268 * | main(), GTP communication, ...
269 * | starts and stops the search managed by thread_manager
271 * thread_manager
272 * | spawns and collects worker threads
274 * worker0
275 * worker1
276 * ...
277 * workerK
278 * uct_playouts() loop, doing descend-playout until uct_halt
280 * Another way to look at it is by functions (lines denote thread boundaries):
282 * | uct_genmove()
283 * | uct_search() (uct_search_start() .. uct_search_stop())
284 * | -----------------------
285 * | spawn_thread_manager()
286 * | -----------------------
287 * | spawn_worker()
288 * V uct_playouts() */
290 /* Set in thread manager in case the workers should stop. */
291 volatile sig_atomic_t uct_halt = 0;
292 /* ID of the running worker thread. */
293 __thread int thread_id = -1;
294 /* ID of the thread manager. */
295 static pthread_t thread_manager;
296 static bool thread_manager_running;
298 static pthread_mutex_t finish_mutex = PTHREAD_MUTEX_INITIALIZER;
299 static pthread_cond_t finish_cond = PTHREAD_COND_INITIALIZER;
300 static volatile int finish_thread;
301 static pthread_mutex_t finish_serializer = PTHREAD_MUTEX_INITIALIZER;
303 struct spawn_ctx {
304 int tid;
305 struct uct *u;
306 struct board *b;
307 enum stone color;
308 struct tree *t;
309 unsigned long seed;
310 int games;
313 static void *
314 spawn_worker(void *ctx_)
316 struct spawn_ctx *ctx = ctx_;
317 /* Setup */
318 fast_srandom(ctx->seed);
319 thread_id = ctx->tid;
320 /* Run */
321 ctx->games = uct_playouts(ctx->u, ctx->b, ctx->color, ctx->t);
322 /* Finish */
323 pthread_mutex_lock(&finish_serializer);
324 pthread_mutex_lock(&finish_mutex);
325 finish_thread = ctx->tid;
326 pthread_cond_signal(&finish_cond);
327 pthread_mutex_unlock(&finish_mutex);
328 return ctx;
331 /* Thread manager, controlling worker threads. It must be called with
332 * finish_mutex lock held, but it will unlock it itself before exiting;
333 * this is necessary to be completely deadlock-free. */
334 /* The finish_cond can be signalled for it to stop; in that case,
335 * the caller should set finish_thread = -1. */
336 /* After it is started, it will update mctx->t to point at some tree
337 * used for the actual search (matters only for TM_ROOT), on return
338 * it will set mctx->games to the number of performed simulations. */
339 static void *
340 spawn_thread_manager(void *ctx_)
342 /* In thread_manager, we use only some of the ctx fields. */
343 struct spawn_ctx *mctx = ctx_;
344 struct uct *u = mctx->u;
345 struct tree *t = mctx->t;
346 bool shared_tree = u->parallel_tree;
347 fast_srandom(mctx->seed);
349 int played_games = 0;
350 pthread_t threads[u->threads];
351 int joined = 0;
353 uct_halt = 0;
355 /* Spawn threads... */
356 for (int ti = 0; ti < u->threads; ti++) {
357 struct spawn_ctx *ctx = malloc(sizeof(*ctx));
358 ctx->u = u; ctx->b = mctx->b; ctx->color = mctx->color;
359 mctx->t = ctx->t = shared_tree ? t : tree_copy(t);
360 ctx->tid = ti; ctx->seed = fast_random(65536) + ti;
361 pthread_create(&threads[ti], NULL, spawn_worker, ctx);
362 if (UDEBUGL(2))
363 fprintf(stderr, "Spawned worker %d\n", ti);
366 /* ...and collect them back: */
367 while (joined < u->threads) {
368 /* Wait for some thread to finish... */
369 pthread_cond_wait(&finish_cond, &finish_mutex);
370 if (finish_thread < 0) {
371 /* Stop-by-caller. Tell the workers to wrap up. */
372 uct_halt = 1;
373 continue;
375 /* ...and gather its remnants. */
376 struct spawn_ctx *ctx;
377 pthread_join(threads[finish_thread], (void **) &ctx);
378 played_games += ctx->games;
379 joined++;
380 if (!shared_tree) {
381 if (ctx->t == mctx->t) mctx->t = t;
382 tree_merge(t, ctx->t);
383 tree_done(ctx->t);
385 free(ctx);
386 if (UDEBUGL(2))
387 fprintf(stderr, "Joined worker %d\n", finish_thread);
388 pthread_mutex_unlock(&finish_serializer);
391 pthread_mutex_unlock(&finish_mutex);
393 if (!shared_tree)
394 tree_normalize(mctx->t, u->threads);
396 mctx->games = played_games;
397 return mctx;
400 static struct spawn_ctx *
401 uct_search_start(struct uct *u, struct board *b, enum stone color, struct tree *t)
403 assert(u->threads > 0);
404 assert(!thread_manager_running);
406 struct spawn_ctx ctx = { .u = u, .b = b, .color = color, .t = t, .seed = fast_random(65536) };
407 static struct spawn_ctx mctx; mctx = ctx;
408 pthread_mutex_lock(&finish_mutex);
409 pthread_create(&thread_manager, NULL, spawn_thread_manager, &mctx);
410 thread_manager_running = true;
411 return &mctx;
414 static struct spawn_ctx *
415 uct_search_stop(void)
417 assert(thread_manager_running);
419 /* Signal thread manager to stop the workers. */
420 pthread_mutex_lock(&finish_mutex);
421 finish_thread = -1;
422 pthread_cond_signal(&finish_cond);
423 pthread_mutex_unlock(&finish_mutex);
425 /* Collect the thread manager. */
426 struct spawn_ctx *pctx;
427 thread_manager_running = false;
428 pthread_join(thread_manager, (void **) &pctx);
429 return pctx;
433 /* Search stopping conditions */
434 union stop_conditions {
435 struct { // TD_WALLTIME
436 double desired_stop; /* stop at that time if possible */
437 double worst_stop; /* stop no later than this */
438 } t;
439 struct { // TD_GAMES
440 int desired_playouts;
441 int worst_playouts;
442 } p;
445 /* Pre-process time_info for search control and sets the desired stopping conditions. */
446 static void
447 time_prep(struct time_info *ti, struct uct *u, struct board *b, union stop_conditions *stop)
449 assert(ti->period != TT_TOTAL);
451 if (ti->period == TT_NULL) {
452 ti->period = TT_MOVE;
453 ti->dim = TD_GAMES;
454 ti->len.games = MC_GAMES;
456 if (ti->dim == TD_GAMES) {
457 stop->p.desired_playouts = ti->len.games;
458 /* We force worst == desired, so note that we will not loop
459 * until best == winner. */
460 stop->p.worst_playouts = ti->len.games;
462 } else {
463 double desired_time = ti->len.t.recommended_time;
464 double worst_time;
465 if (time_in_byoyomi(ti)) {
466 // make recommended == average(desired, worst)
467 worst_time = desired_time * MAX_BYOYOMI_TIME_EXTENSION;
468 desired_time *= (2 - MAX_BYOYOMI_TIME_EXTENSION);
470 } else {
471 int bsize = (board_size(b)-2)*(board_size(b)-2);
472 int fuseki_end = u->fuseki_end * bsize / 100; // move nb at fuseki end
473 int yose_start = u->yose_start * bsize / 100; // move nb at yose start
475 int left_at_yose_start = (b->moves - yose_start) / 2 + board_estimated_moves_left(b);
476 // ^- /2 because we only consider the moves we have to play ourselves
477 if (left_at_yose_start < MIN_MOVES_LEFT)
478 left_at_yose_start = MIN_MOVES_LEFT;
479 double longest_time = ti->len.t.max_time / left_at_yose_start;
480 if (longest_time < desired_time) {
481 // Should rarely happen, but keep desired_time anyway
482 } else if (b->moves < fuseki_end) {
483 desired_time += ((longest_time - desired_time) * b->moves) / fuseki_end;
484 /* In this branch fuseki_end can't be 0 */
485 } else if (b->moves < yose_start) {
486 desired_time = longest_time;
488 worst_time = desired_time * MAX_MAIN_TIME_EXTENSION;
490 if (worst_time > ti->len.t.max_time)
491 worst_time = ti->len.t.max_time;
492 if (desired_time > worst_time)
493 desired_time = worst_time;
495 stop->t.desired_stop = ti->len.t.timer_start + desired_time - ti->len.t.net_lag;
496 stop->t.worst_stop = ti->len.t.timer_start + worst_time - ti->len.t.net_lag;
497 // Both stop points may be in the past if too much lag.
499 if (UDEBUGL(2))
500 fprintf(stderr, "desired time %.02f, worst %.02f\n", desired_time, worst_time);
504 /* Run time-limited MCTS search on foreground. */
505 static int
506 uct_search(struct uct *u, struct board *b, struct time_info *ti, enum stone color, struct tree *t)
508 union stop_conditions stop;
509 time_prep(ti, u, b, &stop);
510 if (UDEBUGL(2) && u->t->root->u.playouts > 0)
511 fprintf(stderr, "<pre-simulated %d games skipped>\n", u->t->root->u.playouts);
513 /* Number of last game with progress print. */
514 int last_print = t->root->u.playouts;
515 /* Number of simulations to wait before next print. */
516 int print_interval = TREE_SIMPROGRESS_INTERVAL * (u->thread_model == TM_ROOT ? 1 : u->threads);
517 /* Printed notification about full memory? */
518 bool print_fullmem = false;
520 struct spawn_ctx *ctx = uct_search_start(u, b, color, t);
522 /* The search tree is ctx->t. This is normally == t, but in case of
523 * TM_ROOT, it is one of the trees belonging to the independent
524 * workers. It is important to reference ctx->t directly since the
525 * thread manager will swap the tree pointer asynchronously. */
526 /* XXX: This means TM_ROOT support is suboptimal since single stalled
527 * thread can stall the others in case of limiting the search by game
528 * count. However, TM_ROOT just does not deserve any more extra code
529 * right now. */
531 struct tree_node *best = NULL, *prev_best;
532 struct tree_node *winner = NULL, *prev_winner;
534 double busywait_interval = TREE_BUSYWAIT_INTERVAL;
536 /* Now, just periodically poll the search tree. */
537 while (1) {
538 time_sleep(busywait_interval);
539 /* busywait_interval should never be less than desired time, or the
540 * time control is broken. But if it happens to be less, we still search
541 * at least 100ms otherwise the move is completely random. */
543 int i = ctx->t->root->u.playouts;
545 /* Print progress? */
546 if (i - last_print > print_interval) {
547 last_print += print_interval; // keep the numbers tidy
548 uct_progress_status(u, ctx->t, color, last_print);
550 if (!print_fullmem && ctx->t->nodes_size > u->max_tree_size) {
551 if (UDEBUGL(2))
552 fprintf(stderr, "memory limit hit (%ld > %lu)\n", ctx->t->nodes_size, u->max_tree_size);
553 print_fullmem = true;
556 /* Check against time settings. */
557 bool desired_done = false;
558 if (ti->dim == TD_WALLTIME) {
559 double now = time_now();
560 if (now > stop.t.worst_stop) break;
561 desired_done = now > stop.t.desired_stop;
562 } else {
563 assert(ti->dim == TD_GAMES);
564 if (i > stop.p.worst_playouts) break;
565 desired_done = i > stop.p.desired_playouts;
568 /* Early break in won situation. */
569 prev_best = best;
570 best = u->policy->choose(u->policy, ctx->t->root, b, color);
571 if (best && ((best->u.playouts >= 2000 && tree_node_get_value(ctx->t, 1, best->u.value) >= u->loss_threshold)
572 || (best->u.playouts >= 500 && tree_node_get_value(ctx->t, 1, best->u.value) >= 0.95)))
573 break;
575 if (desired_done) {
576 if (!u->policy->winner || !u->policy->evaluate)
577 break;
578 /* Stop only if best explored has also highest value: */
579 prev_winner = winner;
580 winner = u->policy->winner(u->policy, ctx->t, ctx->t->root);
581 if (best && best == winner)
582 break;
583 if (UDEBUGL(3) && (best != prev_best || winner != prev_winner)) {
584 fprintf(stderr, "[%d] best", i);
585 if (best)
586 fprintf(stderr, " %3s [%d] %f", coord2sstr(best->coord, ctx->t->board),
587 best->u.playouts, tree_node_get_value(ctx->t, 1, best->u.value));
588 fprintf(stderr, " != winner");
589 if (winner)
590 fprintf(stderr, " %3s [%d] %f ", coord2sstr(winner->coord, ctx->t->board),
591 winner->u.playouts, tree_node_get_value(ctx->t, 1, winner->u.value));
592 fprintf(stderr, "\n");
596 /* TODO: Early break if best->variance goes under threshold and we already
597 * have enough playouts (possibly thanks to book or to pondering). */
598 /* TODO: Early break if second best has no chance to catch up. */
601 ctx = uct_search_stop();
603 if (UDEBUGL(2))
604 tree_dump(t, u->dumpthres);
605 if (UDEBUGL(0))
606 uct_progress_status(u, t, color, ctx->games);
608 return ctx->games;
612 /* Start pondering background with @color to play. */
613 static void
614 uct_pondering_start(struct uct *u, struct board *b0, struct tree *t, enum stone color)
616 if (UDEBUGL(1))
617 fprintf(stderr, "Starting to ponder with color %s\n", stone2str(stone_other(color)));
618 u->pondering = true;
620 /* We need a local board copy to ponder upon. */
621 struct board *b = malloc(sizeof(*b)); board_copy(b, b0);
623 /* *b0 did not have the genmove'd move played yet. */
624 struct move m = { t->root->coord, t->root_color };
625 int res = board_play(b, &m);
626 assert(res >= 0);
628 /* Start MCTS manager thread "headless". */
629 uct_search_start(u, b, color, t);
632 /* uct_search_stop() frontend for the pondering (non-genmove) mode. */
633 static void
634 uct_pondering_stop(struct uct *u)
636 u->pondering = false;
637 if (!thread_manager_running)
638 return;
640 /* Stop the thread manager. */
641 struct spawn_ctx *ctx = uct_search_stop();
642 if (UDEBUGL(1)) {
643 fprintf(stderr, "(pondering) ");
644 uct_progress_status(u, ctx->t, ctx->color, ctx->games);
646 free(ctx->b);
650 static coord_t *
651 uct_genmove(struct engine *e, struct board *b, struct time_info *ti, enum stone color, bool pass_all_alive)
653 double start_time = time_now();
654 struct uct *u = e->data;
656 if (b->superko_violation) {
657 fprintf(stderr, "!!! WARNING: SUPERKO VIOLATION OCCURED BEFORE THIS MOVE\n");
658 fprintf(stderr, "Maybe you play with situational instead of positional superko?\n");
659 fprintf(stderr, "I'm going to ignore the violation, but note that I may miss\n");
660 fprintf(stderr, "some moves valid under this ruleset because of this.\n");
661 b->superko_violation = false;
664 /* Seed the tree. */
665 uct_pondering_stop(u);
666 prepare_move(e, b, color);
667 assert(u->t);
669 /* Perform the Monte Carlo Tree Search! */
670 int played_games = uct_search(u, b, ti, color, u->t);
672 /* Choose the best move from the tree. */
673 struct tree_node *best = u->policy->choose(u->policy, u->t->root, b, color);
674 if (!best) {
675 reset_state(u);
676 return coord_copy(pass);
678 if (UDEBUGL(1))
679 fprintf(stderr, "*** WINNER is %s (%d,%d) with score %1.4f (%d/%d:%d games)\n",
680 coord2sstr(best->coord, b), coord_x(best->coord, b), coord_y(best->coord, b),
681 tree_node_get_value(u->t, 1, best->u.value),
682 best->u.playouts, u->t->root->u.playouts, played_games);
684 /* Do not resign if we're so short of time that evaluation of best move is completely
685 * unreliable, we might be winning actually. In this case best is almost random but
686 * still better than resign. */
687 if (tree_node_get_value(u->t, 1, best->u.value) < u->resign_ratio && !is_pass(best->coord)
688 && best->u.playouts > GJ_MINGAMES) {
689 reset_state(u);
690 return coord_copy(resign);
693 /* If the opponent just passed and we win counting, always
694 * pass as well. */
695 if (b->moves > 1 && is_pass(b->last_move.coord)) {
696 /* Make sure enough playouts are simulated. */
697 while (u->ownermap.playouts < GJ_MINGAMES)
698 uct_playout(u, b, color, u->t);
699 if (uct_pass_is_safe(u, b, color, u->pass_all_alive || pass_all_alive)) {
700 if (UDEBUGL(0))
701 fprintf(stderr, "<Will rather pass, looks safe enough.>\n");
702 best->coord = pass;
706 tree_promote_node(u->t, &best);
707 /* After a pass, pondering is harmful for two reasons:
708 * (i) We might keep pondering even when the game is over.
709 * Of course this is the case for opponent resign as well.
710 * (ii) More importantly, the ownermap will get skewed since
711 * the UCT will start cutting off any playouts. */
712 if (u->pondering_opt && !is_pass(best->coord)) {
713 uct_pondering_start(u, b, u->t, stone_other(color));
715 if (UDEBUGL(2)) {
716 double time = time_now() - start_time + 0.000001; /* avoid divide by zero */
717 fprintf(stderr, "genmove in %0.2fs (%d games/s, %d games/s/thread)\n",
718 time, (int)(played_games/time), (int)(played_games/time/u->threads));
720 return coord_copy(best->coord);
724 bool
725 uct_genbook(struct engine *e, struct board *b, struct time_info *ti, enum stone color)
727 struct uct *u = e->data;
728 if (!u->t) prepare_move(e, b, color);
729 assert(u->t);
731 if (ti->dim == TD_GAMES) {
732 /* Don't count in games that already went into the book. */
733 ti->len.games += u->t->root->u.playouts;
735 uct_search(u, b, ti, color, u->t);
737 assert(ti->dim == TD_GAMES);
738 tree_save(u->t, b, ti->len.games / 100);
740 return true;
743 void
744 uct_dumpbook(struct engine *e, struct board *b, enum stone color)
746 struct uct *u = e->data;
747 struct tree *t = tree_init(b, color, u->fast_alloc ? u->max_tree_size: 0);
748 tree_load(t, b);
749 tree_dump(t, 0);
750 tree_done(t);
754 struct uct *
755 uct_state_init(char *arg, struct board *b)
757 struct uct *u = calloc(1, sizeof(struct uct));
759 u->debug_level = 1;
760 u->gamelen = MC_GAMELEN;
761 u->mercymin = 0;
762 u->expand_p = 2;
763 u->dumpthres = 1000;
764 u->playout_amaf = true;
765 u->playout_amaf_nakade = false;
766 u->amaf_prior = false;
767 u->max_tree_size = 3072ULL * 1048576;
769 if (board_size(b) - 2 >= 19)
770 u->dynkomi = 200;
771 u->dynkomi_mask = S_BLACK;
773 u->threads = 1;
774 u->thread_model = TM_TREEVL;
775 u->parallel_tree = true;
776 u->virtual_loss = true;
777 u->fuseki_end = 20; // max time at 361*20% = 72 moves (our 36th move, still 99 to play)
778 u->yose_start = 40; // (100-40-25)*361/100/2 = 63 moves still to play by us then
780 u->val_scale = 0.04; u->val_points = 40;
782 if (arg) {
783 char *optspec, *next = arg;
784 while (*next) {
785 optspec = next;
786 next += strcspn(next, ",");
787 if (*next) { *next++ = 0; } else { *next = 0; }
789 char *optname = optspec;
790 char *optval = strchr(optspec, '=');
791 if (optval) *optval++ = 0;
793 if (!strcasecmp(optname, "debug")) {
794 if (optval)
795 u->debug_level = atoi(optval);
796 else
797 u->debug_level++;
798 } else if (!strcasecmp(optname, "mercy") && optval) {
799 /* Minimal difference of black/white captures
800 * to stop playout - "Mercy Rule". Speeds up
801 * hopeless playouts at the expense of some
802 * accuracy. */
803 u->mercymin = atoi(optval);
804 } else if (!strcasecmp(optname, "gamelen") && optval) {
805 u->gamelen = atoi(optval);
806 } else if (!strcasecmp(optname, "expand_p") && optval) {
807 u->expand_p = atoi(optval);
808 } else if (!strcasecmp(optname, "dumpthres") && optval) {
809 u->dumpthres = atoi(optval);
810 } else if (!strcasecmp(optname, "playout_amaf")) {
811 /* Whether to include random playout moves in
812 * AMAF as well. (Otherwise, only tree moves
813 * are included in AMAF. Of course makes sense
814 * only in connection with an AMAF policy.) */
815 /* with-without: 55.5% (+-4.1) */
816 if (optval && *optval == '0')
817 u->playout_amaf = false;
818 else
819 u->playout_amaf = true;
820 } else if (!strcasecmp(optname, "playout_amaf_nakade")) {
821 /* Whether to include nakade moves from playouts
822 * in the AMAF statistics; this tends to nullify
823 * the playout_amaf effect by adding too much
824 * noise. */
825 if (optval && *optval == '0')
826 u->playout_amaf_nakade = false;
827 else
828 u->playout_amaf_nakade = true;
829 } else if (!strcasecmp(optname, "playout_amaf_cutoff") && optval) {
830 /* Keep only first N% of playout stage AMAF
831 * information. */
832 u->playout_amaf_cutoff = atoi(optval);
833 } else if ((!strcasecmp(optname, "policy") || !strcasecmp(optname, "random_policy")) && optval) {
834 char *policyarg = strchr(optval, ':');
835 struct uct_policy **p = !strcasecmp(optname, "policy") ? &u->policy : &u->random_policy;
836 if (policyarg)
837 *policyarg++ = 0;
838 if (!strcasecmp(optval, "ucb1")) {
839 *p = policy_ucb1_init(u, policyarg);
840 } else if (!strcasecmp(optval, "ucb1amaf")) {
841 *p = policy_ucb1amaf_init(u, policyarg);
842 } else {
843 fprintf(stderr, "UCT: Invalid tree policy %s\n", optval);
844 exit(1);
846 } else if (!strcasecmp(optname, "playout") && optval) {
847 char *playoutarg = strchr(optval, ':');
848 if (playoutarg)
849 *playoutarg++ = 0;
850 if (!strcasecmp(optval, "moggy")) {
851 u->playout = playout_moggy_init(playoutarg);
852 } else if (!strcasecmp(optval, "light")) {
853 u->playout = playout_light_init(playoutarg);
854 } else if (!strcasecmp(optval, "elo")) {
855 u->playout = playout_elo_init(playoutarg);
856 } else {
857 fprintf(stderr, "UCT: Invalid playout policy %s\n", optval);
858 exit(1);
860 } else if (!strcasecmp(optname, "prior") && optval) {
861 u->prior = uct_prior_init(optval, b);
862 } else if (!strcasecmp(optname, "amaf_prior") && optval) {
863 u->amaf_prior = atoi(optval);
864 } else if (!strcasecmp(optname, "threads") && optval) {
865 /* By default, Pachi will run with only single
866 * tree search thread! */
867 u->threads = atoi(optval);
868 } else if (!strcasecmp(optname, "thread_model") && optval) {
869 if (!strcasecmp(optval, "root")) {
870 /* Root parallelization - each thread
871 * does independent search, trees are
872 * merged at the end. */
873 u->thread_model = TM_ROOT;
874 u->parallel_tree = false;
875 u->virtual_loss = false;
876 } else if (!strcasecmp(optval, "tree")) {
877 /* Tree parallelization - all threads
878 * grind on the same tree. */
879 u->thread_model = TM_TREE;
880 u->parallel_tree = true;
881 u->virtual_loss = false;
882 } else if (!strcasecmp(optval, "treevl")) {
883 /* Tree parallelization, but also
884 * with virtual losses - this discou-
885 * rages most threads choosing the
886 * same tree branches to read. */
887 u->thread_model = TM_TREEVL;
888 u->parallel_tree = true;
889 u->virtual_loss = true;
890 } else {
891 fprintf(stderr, "UCT: Invalid thread model %s\n", optval);
892 exit(1);
894 } else if (!strcasecmp(optname, "pondering")) {
895 /* Keep searching even during opponent's turn. */
896 u->pondering_opt = !optval || atoi(optval);
897 } else if (!strcasecmp(optname, "fuseki_end") && optval) {
898 /* At the very beginning it's not worth thinking
899 * too long because the playout evaluations are
900 * very noisy. So gradually increase the thinking
901 * time up to maximum when fuseki_end percent
902 * of the board has been played.
903 * This only applies if we are not in byoyomi. */
904 u->fuseki_end = atoi(optval);
905 } else if (!strcasecmp(optname, "yose_start") && optval) {
906 /* When yose_start percent of the board has been
907 * played, or if we are in byoyomi, stop spending
908 * more time and spread the remaining time
909 * uniformly.
910 * Between fuseki_end and yose_start, we spend
911 * a constant proportion of the remaining time
912 * on each move. (yose_start should actually
913 * be much earlier than when real yose start,
914 * but "yose" is a good short name to convey
915 * the idea.) */
916 u->yose_start = atoi(optval);
917 } else if (!strcasecmp(optname, "force_seed") && optval) {
918 u->force_seed = atoi(optval);
919 } else if (!strcasecmp(optname, "no_book")) {
920 u->no_book = true;
921 } else if (!strcasecmp(optname, "dynkomi")) {
922 /* Dynamic komi in handicap game; linearly
923 * decreases to basic settings until move
924 * #optval. */
925 u->dynkomi = optval ? atoi(optval) : 150;
926 } else if (!strcasecmp(optname, "dynkomi_mask") && optval) {
927 /* Bitmask of colors the player must be
928 * for dynkomi be applied; you may want
929 * to use dynkomi_mask=3 to allow dynkomi
930 * even in games where Pachi is white. */
931 u->dynkomi_mask = atoi(optval);
932 } else if (!strcasecmp(optname, "val_scale") && optval) {
933 /* How much of the game result value should be
934 * influenced by win size. Zero means it isn't. */
935 u->val_scale = atof(optval);
936 } else if (!strcasecmp(optname, "val_points") && optval) {
937 /* Maximum size of win to be scaled into game
938 * result value. Zero means boardsize^2. */
939 u->val_points = atoi(optval) * 2; // result values are doubled
940 } else if (!strcasecmp(optname, "val_extra")) {
941 /* If false, the score coefficient will be simply
942 * added to the value, instead of scaling the result
943 * coefficient because of it. */
944 u->val_extra = !optval || atoi(optval);
945 } else if (!strcasecmp(optname, "root_heuristic") && optval) {
946 /* Whether to bias exploration by root node values
947 * (must be supported by the used policy).
948 * 0: Don't.
949 * 1: Do, value = result.
950 * Try to temper the result:
951 * 2: Do, value = 0.5+(result-expected)/2.
952 * 3: Do, value = 0.5+bzz((result-expected)^2). */
953 u->root_heuristic = atoi(optval);
954 } else if (!strcasecmp(optname, "pass_all_alive")) {
955 /* Whether to consider all stones alive at the game
956 * end instead of marking dead groupd. */
957 u->pass_all_alive = !optval || atoi(optval);
958 } else if (!strcasecmp(optname, "random_policy_chance") && optval) {
959 /* If specified (N), with probability 1/N, random_policy policy
960 * descend is used instead of main policy descend; useful
961 * if specified policy (e.g. UCB1AMAF) can make unduly biased
962 * choices sometimes, you can fall back to e.g.
963 * random_policy=UCB1. */
964 u->random_policy_chance = atoi(optval);
965 } else if (!strcasecmp(optname, "max_tree_size") && optval) {
966 /* Maximum amount of memory [MiB] consumed by the move tree.
967 * Default is 3072 (3 GiB). Note that if you use TM_ROOT,
968 * this limits size of only one of the trees, not all of them
969 * together. */
970 u->max_tree_size = atol(optval) * 1048576;
971 } else if (!strcasecmp(optname, "banner") && optval) {
972 /* Additional banner string. This must come as the
973 * last engine parameter. */
974 if (*next) *--next = ',';
975 u->banner = strdup(optval);
976 break;
977 } else {
978 fprintf(stderr, "uct: Invalid engine argument %s or missing value\n", optname);
979 exit(1);
984 u->resign_ratio = 0.2; /* Resign when most games are lost. */
985 u->loss_threshold = 0.85; /* Stop reading if after at least 5000 playouts this is best value. */
986 if (!u->policy)
987 u->policy = policy_ucb1amaf_init(u, NULL);
989 if (!!u->random_policy_chance ^ !!u->random_policy) {
990 fprintf(stderr, "uct: Only one of random_policy and random_policy_chance is set\n");
991 exit(1);
994 if (u->fast_alloc && !u->parallel_tree) {
995 fprintf(stderr, "fast_alloc not supported with root parallelization.\n");
996 exit(1);
999 if (!u->prior)
1000 u->prior = uct_prior_init(NULL, b);
1002 if (!u->playout)
1003 u->playout = playout_moggy_init(NULL);
1004 u->playout->debug_level = u->debug_level;
1006 u->ownermap.map = malloc(board_size2(b) * sizeof(u->ownermap.map[0]));
1008 /* Some things remain uninitialized for now - the opening book
1009 * is not loaded and the tree not set up. */
1010 /* This will be initialized in setup_state() at the first move
1011 * received/requested. This is because right now we are not aware
1012 * about any komi or handicap setup and such. */
1014 return u;
1017 struct engine *
1018 engine_uct_init(char *arg, struct board *b)
1020 struct uct *u = uct_state_init(arg, b);
1021 struct engine *e = calloc(1, sizeof(struct engine));
1022 e->name = "UCT Engine";
1023 e->printhook = uct_printhook_ownermap;
1024 e->notify_play = uct_notify_play;
1025 e->chat = uct_chat;
1026 e->genmove = uct_genmove;
1027 e->dead_group_list = uct_dead_group_list;
1028 e->done = uct_done;
1029 e->data = u;
1031 const char banner[] = "I'm playing UCT. When I'm losing, I will resign, "
1032 "if I think I win, I play until you pass. "
1033 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
1034 if (!u->banner) u->banner = "";
1035 e->comment = malloc(sizeof(banner) + strlen(u->banner) + 1);
1036 sprintf(e->comment, "%s %s", banner, u->banner);
1038 return e;