uct_search(): Factor out uct_search_keep_looking()
[pachi/t.git] / uct / uct.c
blob6779ac2f6c5e8296c6a73bcd7c0b761591d6edde
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 /* Determine whether we should terminate the search early. */
447 static bool
448 uct_search_stop_early(struct uct *u, struct tree *t, struct board *b,
449 struct time_info *ti, struct time_stop *stop,
450 struct tree_node *best, struct tree_node *best2,
451 int base_playouts, int i)
453 /* Early break in won situation. */
454 if (best->u.playouts >= 2000 && tree_node_get_value(t, 1, best->u.value) >= u->loss_threshold)
455 return true;
456 /* Earlier break in super-won situation. */
457 if (best->u.playouts >= 500 && tree_node_get_value(t, 1, best->u.value) >= 0.95)
458 return true;
460 /* Break early if we estimate the second-best move cannot
461 * catch up in assigned time anymore. We use all our time
462 * if we are in byoyomi with single stone remaining in our
463 * period, however - it's better to pre-ponder. */
464 bool time_indulgent = (!ti->len.t.main_time && ti->len.t.byoyomi_stones == 1);
465 if (best2 && ti->dim == TD_WALLTIME && !time_indulgent) {
466 double elapsed = time_now() - ti->len.t.timer_start;
467 double remaining = stop->worst.time - elapsed;
468 double pps = ((double)i - base_playouts) / elapsed;
469 double estplayouts = remaining * pps + PLAYOUT_DELTA_SAFEMARGIN;
470 if (best->u.playouts > best2->u.playouts + estplayouts) {
471 if (UDEBUGL(2))
472 fprintf(stderr, "Early stop, result cannot change: "
473 "best %d, best2 %d, estimated %f simulations to go\n",
474 best->u.playouts, best2->u.playouts, estplayouts);
475 return true;
479 return false;
482 /* Determine whether we should terminate the search later. */
483 static bool
484 uct_search_keep_looking(struct uct *u, struct tree *t, struct board *b,
485 struct tree_node *best, struct tree_node *best2,
486 struct tree_node *winner,
487 struct tree_node *prev_best, struct tree_node *prev_winner,
488 int i)
490 if (!best) {
491 if (UDEBUGL(2))
492 fprintf(stderr, "Did not find best move, still trying...\n");
493 return true;
496 if (u->best2_ratio > 0) {
497 /* Check best/best2 simulations ratio. If the
498 * two best moves give very similar results,
499 * keep simulating. */
500 if (best2 && best2->u.playouts
501 && (double)best->u.playouts / best2->u.playouts < u->best2_ratio) {
502 if (UDEBUGL(2))
503 fprintf(stderr, "Best2 ratio %f < threshold %f\n",
504 (double)best->u.playouts / best2->u.playouts,
505 u->best2_ratio);
506 return true;
510 if (winner && winner != best) {
511 /* Keep simulating if best explored
512 * does not have also highest value. */
513 if (UDEBUGL(2) && (best != prev_best || winner != prev_winner)) {
514 fprintf(stderr, "[%d] best %3s [%d] %f != winner %3s [%d] %f\n", i,
515 coord2sstr(best->coord, t->board),
516 best->u.playouts, tree_node_get_value(t, 1, best->u.value),
517 coord2sstr(winner->coord, t->board),
518 winner->u.playouts, tree_node_get_value(t, 1, winner->u.value));
520 return true;
523 /* No reason to keep simulating, bye. */
524 return false;
527 /* Run time-limited MCTS search on foreground. */
528 static int
529 uct_search(struct uct *u, struct board *b, struct time_info *ti, enum stone color, struct tree *t)
531 int base_playouts = u->t->root->u.playouts;
532 if (UDEBUGL(2) && base_playouts > 0)
533 fprintf(stderr, "<pre-simulated %d games skipped>\n", base_playouts);
535 /* Set up time conditions. */
536 if (ti->period == TT_NULL) *ti = default_ti;
537 struct time_stop stop;
538 time_stop_conditions(ti, b, u->fuseki_end, u->yose_start, &stop);
540 /* Number of last game with progress print. */
541 int last_print = t->root->u.playouts;
542 /* Number of simulations to wait before next print. */
543 int print_interval = TREE_SIMPROGRESS_INTERVAL * (u->thread_model == TM_ROOT ? 1 : u->threads);
544 /* Printed notification about full memory? */
545 bool print_fullmem = false;
547 struct spawn_ctx *ctx = uct_search_start(u, b, color, t);
549 /* The search tree is ctx->t. This is normally == t, but in case of
550 * TM_ROOT, it is one of the trees belonging to the independent
551 * workers. It is important to reference ctx->t directly since the
552 * thread manager will swap the tree pointer asynchronously. */
553 /* XXX: This means TM_ROOT support is suboptimal since single stalled
554 * thread can stall the others in case of limiting the search by game
555 * count. However, TM_ROOT just does not deserve any more extra code
556 * right now. */
558 struct tree_node *best = NULL, *prev_best;
559 struct tree_node *best2 = NULL; // Second-best move.
560 struct tree_node *winner = NULL, *prev_winner = NULL;
562 double busywait_interval = TREE_BUSYWAIT_INTERVAL;
564 /* Now, just periodically poll the search tree. */
565 while (1) {
566 time_sleep(busywait_interval);
567 /* busywait_interval should never be less than desired time, or the
568 * time control is broken. But if it happens to be less, we still search
569 * at least 100ms otherwise the move is completely random. */
571 int i = ctx->t->root->u.playouts;
573 /* Print progress? */
574 if (i - last_print > print_interval) {
575 last_print += print_interval; // keep the numbers tidy
576 uct_progress_status(u, ctx->t, color, last_print);
578 if (!print_fullmem && ctx->t->nodes_size > u->max_tree_size) {
579 if (UDEBUGL(2))
580 fprintf(stderr, "memory limit hit (%ld > %lu)\n", ctx->t->nodes_size, u->max_tree_size);
581 print_fullmem = true;
584 /* Check against time settings. */
585 bool desired_done = false;
586 if (ti->dim == TD_WALLTIME) {
587 double elapsed = time_now() - ti->len.t.timer_start;
588 if (elapsed > stop.worst.time) break;
589 desired_done = elapsed > stop.desired.time;
591 } else { assert(ti->dim == TD_GAMES);
592 if (i > stop.worst.playouts) break;
593 desired_done = i > stop.desired.playouts;
596 prev_best = best;
597 best = u->policy->choose(u->policy, ctx->t->root, b, color, resign);
598 best2 = u->policy->choose(u->policy, ctx->t->root, b, color, best->coord);
600 if (best && uct_search_stop_early(u, ctx->t, b, ti, &stop, best, best2, base_playouts, i))
601 break;
603 /* We want to stop simulating, but are willing to keep trying
604 * if we aren't completely sure about the winner yet. */
605 if (desired_done) {
606 if (u->policy->winner && u->policy->evaluate) {
607 prev_winner = winner;
608 winner = u->policy->winner(u->policy, ctx->t, ctx->t->root);
610 if (!uct_search_keep_looking(u, ctx->t, b, best, best2, winner, prev_best, prev_winner, i))
611 break;
614 /* TODO: Early break if best->variance goes under threshold and we already
615 * have enough playouts (possibly thanks to book or to pondering)? */
618 ctx = uct_search_stop();
620 if (UDEBUGL(2))
621 tree_dump(t, u->dumpthres);
622 if (UDEBUGL(0))
623 uct_progress_status(u, t, color, ctx->games);
625 return ctx->games;
629 /* Start pondering background with @color to play. */
630 static void
631 uct_pondering_start(struct uct *u, struct board *b0, struct tree *t, enum stone color)
633 if (UDEBUGL(1))
634 fprintf(stderr, "Starting to ponder with color %s\n", stone2str(stone_other(color)));
635 u->pondering = true;
637 /* We need a local board copy to ponder upon. */
638 struct board *b = malloc(sizeof(*b)); board_copy(b, b0);
640 /* *b0 did not have the genmove'd move played yet. */
641 struct move m = { t->root->coord, t->root_color };
642 int res = board_play(b, &m);
643 assert(res >= 0);
644 setup_dynkomi(u, b, stone_other(m.color));
646 /* Start MCTS manager thread "headless". */
647 uct_search_start(u, b, color, t);
650 /* uct_search_stop() frontend for the pondering (non-genmove) mode. */
651 static void
652 uct_pondering_stop(struct uct *u)
654 u->pondering = false;
655 if (!thread_manager_running)
656 return;
658 /* Stop the thread manager. */
659 struct spawn_ctx *ctx = uct_search_stop();
660 if (UDEBUGL(1)) {
661 fprintf(stderr, "(pondering) ");
662 uct_progress_status(u, ctx->t, ctx->color, ctx->games);
664 free(ctx->b);
668 static coord_t *
669 uct_genmove(struct engine *e, struct board *b, struct time_info *ti, enum stone color, bool pass_all_alive)
671 double start_time = time_now();
672 struct uct *u = e->data;
674 if (b->superko_violation) {
675 fprintf(stderr, "!!! WARNING: SUPERKO VIOLATION OCCURED BEFORE THIS MOVE\n");
676 fprintf(stderr, "Maybe you play with situational instead of positional superko?\n");
677 fprintf(stderr, "I'm going to ignore the violation, but note that I may miss\n");
678 fprintf(stderr, "some moves valid under this ruleset because of this.\n");
679 b->superko_violation = false;
682 /* Seed the tree. */
683 uct_pondering_stop(u);
684 prepare_move(e, b, color);
685 assert(u->t);
687 /* How to decide whether to use dynkomi in this game? Since we use
688 * pondering, it's not simple "who-to-play" matter. Decide based on
689 * the last genmove issued. */
690 u->t->use_extra_komi = !!(u->dynkomi_mask & color);
691 setup_dynkomi(u, b, color);
693 /* Perform the Monte Carlo Tree Search! */
694 int played_games = uct_search(u, b, ti, color, u->t);
696 /* Choose the best move from the tree. */
697 struct tree_node *best = u->policy->choose(u->policy, u->t->root, b, color, resign);
698 if (!best) {
699 reset_state(u);
700 return coord_copy(pass);
702 if (UDEBUGL(1))
703 fprintf(stderr, "*** WINNER is %s (%d,%d) with score %1.4f (%d/%d:%d games)\n",
704 coord2sstr(best->coord, b), coord_x(best->coord, b), coord_y(best->coord, b),
705 tree_node_get_value(u->t, 1, best->u.value),
706 best->u.playouts, u->t->root->u.playouts, played_games);
708 /* Do not resign if we're so short of time that evaluation of best move is completely
709 * unreliable, we might be winning actually. In this case best is almost random but
710 * still better than resign. */
711 if (tree_node_get_value(u->t, 1, best->u.value) < u->resign_ratio && !is_pass(best->coord)
712 && best->u.playouts > GJ_MINGAMES) {
713 reset_state(u);
714 return coord_copy(resign);
717 /* If the opponent just passed and we win counting, always
718 * pass as well. */
719 if (b->moves > 1 && is_pass(b->last_move.coord)) {
720 /* Make sure enough playouts are simulated. */
721 while (u->ownermap.playouts < GJ_MINGAMES)
722 uct_playout(u, b, color, u->t);
723 if (uct_pass_is_safe(u, b, color, u->pass_all_alive || pass_all_alive)) {
724 if (UDEBUGL(0))
725 fprintf(stderr, "<Will rather pass, looks safe enough.>\n");
726 best->coord = pass;
730 tree_promote_node(u->t, &best);
731 /* After a pass, pondering is harmful for two reasons:
732 * (i) We might keep pondering even when the game is over.
733 * Of course this is the case for opponent resign as well.
734 * (ii) More importantly, the ownermap will get skewed since
735 * the UCT will start cutting off any playouts. */
736 if (u->pondering_opt && !is_pass(best->coord)) {
737 uct_pondering_start(u, b, u->t, stone_other(color));
739 if (UDEBUGL(2)) {
740 double time = time_now() - start_time + 0.000001; /* avoid divide by zero */
741 fprintf(stderr, "genmove in %0.2fs (%d games/s, %d games/s/thread)\n",
742 time, (int)(played_games/time), (int)(played_games/time/u->threads));
744 return coord_copy(best->coord);
748 bool
749 uct_genbook(struct engine *e, struct board *b, struct time_info *ti, enum stone color)
751 struct uct *u = e->data;
752 if (!u->t) prepare_move(e, b, color);
753 assert(u->t);
755 if (ti->dim == TD_GAMES) {
756 /* Don't count in games that already went into the book. */
757 ti->len.games += u->t->root->u.playouts;
759 uct_search(u, b, ti, color, u->t);
761 assert(ti->dim == TD_GAMES);
762 tree_save(u->t, b, ti->len.games / 100);
764 return true;
767 void
768 uct_dumpbook(struct engine *e, struct board *b, enum stone color)
770 struct uct *u = e->data;
771 struct tree *t = tree_init(b, color, u->fast_alloc ? u->max_tree_size: 0);
772 tree_load(t, b);
773 tree_dump(t, 0);
774 tree_done(t);
778 struct uct *
779 uct_state_init(char *arg, struct board *b)
781 struct uct *u = calloc(1, sizeof(struct uct));
783 u->debug_level = 3;
784 u->gamelen = MC_GAMELEN;
785 u->mercymin = 0;
786 u->expand_p = 2;
787 u->dumpthres = 1000;
788 u->playout_amaf = true;
789 u->playout_amaf_nakade = false;
790 u->amaf_prior = false;
791 u->max_tree_size = 3072ULL * 1048576;
793 if (board_size(b) - 2 >= 19)
794 u->dynkomi = 200;
795 u->dynkomi_mask = S_BLACK;
797 u->threads = 1;
798 u->thread_model = TM_TREEVL;
799 u->parallel_tree = true;
800 u->virtual_loss = true;
801 u->fuseki_end = 20; // max time at 361*20% = 72 moves (our 36th move, still 99 to play)
802 u->yose_start = 40; // (100-40-25)*361/100/2 = 63 moves still to play by us then
804 u->val_scale = 0.04; u->val_points = 40;
806 if (arg) {
807 char *optspec, *next = arg;
808 while (*next) {
809 optspec = next;
810 next += strcspn(next, ",");
811 if (*next) { *next++ = 0; } else { *next = 0; }
813 char *optname = optspec;
814 char *optval = strchr(optspec, '=');
815 if (optval) *optval++ = 0;
817 if (!strcasecmp(optname, "debug")) {
818 if (optval)
819 u->debug_level = atoi(optval);
820 else
821 u->debug_level++;
822 } else if (!strcasecmp(optname, "mercy") && optval) {
823 /* Minimal difference of black/white captures
824 * to stop playout - "Mercy Rule". Speeds up
825 * hopeless playouts at the expense of some
826 * accuracy. */
827 u->mercymin = atoi(optval);
828 } else if (!strcasecmp(optname, "gamelen") && optval) {
829 u->gamelen = atoi(optval);
830 } else if (!strcasecmp(optname, "expand_p") && optval) {
831 u->expand_p = atoi(optval);
832 } else if (!strcasecmp(optname, "dumpthres") && optval) {
833 u->dumpthres = atoi(optval);
834 } else if (!strcasecmp(optname, "best2_ratio") && optval) {
835 /* If set, prolong simulating while
836 * first_best/second_best playouts ratio
837 * is less than best2_ratio. */
838 u->best2_ratio = atof(optval);
839 } else if (!strcasecmp(optname, "playout_amaf")) {
840 /* Whether to include random playout moves in
841 * AMAF as well. (Otherwise, only tree moves
842 * are included in AMAF. Of course makes sense
843 * only in connection with an AMAF policy.) */
844 /* with-without: 55.5% (+-4.1) */
845 if (optval && *optval == '0')
846 u->playout_amaf = false;
847 else
848 u->playout_amaf = true;
849 } else if (!strcasecmp(optname, "playout_amaf_nakade")) {
850 /* Whether to include nakade moves from playouts
851 * in the AMAF statistics; this tends to nullify
852 * the playout_amaf effect by adding too much
853 * noise. */
854 if (optval && *optval == '0')
855 u->playout_amaf_nakade = false;
856 else
857 u->playout_amaf_nakade = true;
858 } else if (!strcasecmp(optname, "playout_amaf_cutoff") && optval) {
859 /* Keep only first N% of playout stage AMAF
860 * information. */
861 u->playout_amaf_cutoff = atoi(optval);
862 } else if ((!strcasecmp(optname, "policy") || !strcasecmp(optname, "random_policy")) && optval) {
863 char *policyarg = strchr(optval, ':');
864 struct uct_policy **p = !strcasecmp(optname, "policy") ? &u->policy : &u->random_policy;
865 if (policyarg)
866 *policyarg++ = 0;
867 if (!strcasecmp(optval, "ucb1")) {
868 *p = policy_ucb1_init(u, policyarg);
869 } else if (!strcasecmp(optval, "ucb1amaf")) {
870 *p = policy_ucb1amaf_init(u, policyarg);
871 } else {
872 fprintf(stderr, "UCT: Invalid tree policy %s\n", optval);
873 exit(1);
875 } else if (!strcasecmp(optname, "playout") && optval) {
876 char *playoutarg = strchr(optval, ':');
877 if (playoutarg)
878 *playoutarg++ = 0;
879 if (!strcasecmp(optval, "moggy")) {
880 u->playout = playout_moggy_init(playoutarg);
881 } else if (!strcasecmp(optval, "light")) {
882 u->playout = playout_light_init(playoutarg);
883 } else if (!strcasecmp(optval, "elo")) {
884 u->playout = playout_elo_init(playoutarg);
885 } else {
886 fprintf(stderr, "UCT: Invalid playout policy %s\n", optval);
887 exit(1);
889 } else if (!strcasecmp(optname, "prior") && optval) {
890 u->prior = uct_prior_init(optval, b);
891 } else if (!strcasecmp(optname, "amaf_prior") && optval) {
892 u->amaf_prior = atoi(optval);
893 } else if (!strcasecmp(optname, "threads") && optval) {
894 /* By default, Pachi will run with only single
895 * tree search thread! */
896 u->threads = atoi(optval);
897 } else if (!strcasecmp(optname, "thread_model") && optval) {
898 if (!strcasecmp(optval, "root")) {
899 /* Root parallelization - each thread
900 * does independent search, trees are
901 * merged at the end. */
902 u->thread_model = TM_ROOT;
903 u->parallel_tree = false;
904 u->virtual_loss = false;
905 } else if (!strcasecmp(optval, "tree")) {
906 /* Tree parallelization - all threads
907 * grind on the same tree. */
908 u->thread_model = TM_TREE;
909 u->parallel_tree = true;
910 u->virtual_loss = false;
911 } else if (!strcasecmp(optval, "treevl")) {
912 /* Tree parallelization, but also
913 * with virtual losses - this discou-
914 * rages most threads choosing the
915 * same tree branches to read. */
916 u->thread_model = TM_TREEVL;
917 u->parallel_tree = true;
918 u->virtual_loss = true;
919 } else {
920 fprintf(stderr, "UCT: Invalid thread model %s\n", optval);
921 exit(1);
923 } else if (!strcasecmp(optname, "pondering")) {
924 /* Keep searching even during opponent's turn. */
925 u->pondering_opt = !optval || atoi(optval);
926 } else if (!strcasecmp(optname, "fuseki_end") && optval) {
927 /* At the very beginning it's not worth thinking
928 * too long because the playout evaluations are
929 * very noisy. So gradually increase the thinking
930 * time up to maximum when fuseki_end percent
931 * of the board has been played.
932 * This only applies if we are not in byoyomi. */
933 u->fuseki_end = atoi(optval);
934 } else if (!strcasecmp(optname, "yose_start") && optval) {
935 /* When yose_start percent of the board has been
936 * played, or if we are in byoyomi, stop spending
937 * more time and spread the remaining time
938 * uniformly.
939 * Between fuseki_end and yose_start, we spend
940 * a constant proportion of the remaining time
941 * on each move. (yose_start should actually
942 * be much earlier than when real yose start,
943 * but "yose" is a good short name to convey
944 * the idea.) */
945 u->yose_start = atoi(optval);
946 } else if (!strcasecmp(optname, "force_seed") && optval) {
947 u->force_seed = atoi(optval);
948 } else if (!strcasecmp(optname, "no_book")) {
949 u->no_book = true;
950 } else if (!strcasecmp(optname, "dynkomi")) {
951 /* Dynamic komi in handicap game; linearly
952 * decreases to basic settings until move
953 * #optval. */
954 u->dynkomi = optval ? atoi(optval) : 150;
955 } else if (!strcasecmp(optname, "dynkomi_mask") && optval) {
956 /* Bitmask of colors the player must be
957 * for dynkomi be applied; you may want
958 * to use dynkomi_mask=3 to allow dynkomi
959 * even in games where Pachi is white. */
960 u->dynkomi_mask = atoi(optval);
961 } else if (!strcasecmp(optname, "val_scale") && optval) {
962 /* How much of the game result value should be
963 * influenced by win size. Zero means it isn't. */
964 u->val_scale = atof(optval);
965 } else if (!strcasecmp(optname, "val_points") && optval) {
966 /* Maximum size of win to be scaled into game
967 * result value. Zero means boardsize^2. */
968 u->val_points = atoi(optval) * 2; // result values are doubled
969 } else if (!strcasecmp(optname, "val_extra")) {
970 /* If false, the score coefficient will be simply
971 * added to the value, instead of scaling the result
972 * coefficient because of it. */
973 u->val_extra = !optval || atoi(optval);
974 } else if (!strcasecmp(optname, "root_heuristic") && optval) {
975 /* Whether to bias exploration by root node values
976 * (must be supported by the used policy).
977 * 0: Don't.
978 * 1: Do, value = result.
979 * Try to temper the result:
980 * 2: Do, value = 0.5+(result-expected)/2.
981 * 3: Do, value = 0.5+bzz((result-expected)^2). */
982 u->root_heuristic = atoi(optval);
983 } else if (!strcasecmp(optname, "pass_all_alive")) {
984 /* Whether to consider all stones alive at the game
985 * end instead of marking dead groupd. */
986 u->pass_all_alive = !optval || atoi(optval);
987 } else if (!strcasecmp(optname, "random_policy_chance") && optval) {
988 /* If specified (N), with probability 1/N, random_policy policy
989 * descend is used instead of main policy descend; useful
990 * if specified policy (e.g. UCB1AMAF) can make unduly biased
991 * choices sometimes, you can fall back to e.g.
992 * random_policy=UCB1. */
993 u->random_policy_chance = atoi(optval);
994 } else if (!strcasecmp(optname, "max_tree_size") && optval) {
995 /* Maximum amount of memory [MiB] consumed by the move tree.
996 * Default is 3072 (3 GiB). Note that if you use TM_ROOT,
997 * this limits size of only one of the trees, not all of them
998 * together. */
999 u->max_tree_size = atol(optval) * 1048576;
1000 } else if (!strcasecmp(optname, "fast_alloc")) {
1001 u->fast_alloc = !optval || atoi(optval);
1002 } else if (!strcasecmp(optname, "banner") && optval) {
1003 /* Additional banner string. This must come as the
1004 * last engine parameter. */
1005 if (*next) *--next = ',';
1006 u->banner = strdup(optval);
1007 break;
1008 } else {
1009 fprintf(stderr, "uct: Invalid engine argument %s or missing value\n", optname);
1010 exit(1);
1015 u->resign_ratio = 0.2; /* Resign when most games are lost. */
1016 u->loss_threshold = 0.85; /* Stop reading if after at least 5000 playouts this is best value. */
1017 if (!u->policy)
1018 u->policy = policy_ucb1amaf_init(u, NULL);
1020 if (!!u->random_policy_chance ^ !!u->random_policy) {
1021 fprintf(stderr, "uct: Only one of random_policy and random_policy_chance is set\n");
1022 exit(1);
1025 if (u->fast_alloc && !u->parallel_tree) {
1026 fprintf(stderr, "fast_alloc not supported with root parallelization.\n");
1027 exit(1);
1030 if (!u->prior)
1031 u->prior = uct_prior_init(NULL, b);
1033 if (!u->playout)
1034 u->playout = playout_moggy_init(NULL);
1035 u->playout->debug_level = u->debug_level;
1037 u->ownermap.map = malloc(board_size2(b) * sizeof(u->ownermap.map[0]));
1039 /* Some things remain uninitialized for now - the opening book
1040 * is not loaded and the tree not set up. */
1041 /* This will be initialized in setup_state() at the first move
1042 * received/requested. This is because right now we are not aware
1043 * about any komi or handicap setup and such. */
1045 return u;
1048 struct engine *
1049 engine_uct_init(char *arg, struct board *b)
1051 struct uct *u = uct_state_init(arg, b);
1052 struct engine *e = calloc(1, sizeof(struct engine));
1053 e->name = "UCT Engine";
1054 e->printhook = uct_printhook_ownermap;
1055 e->notify_play = uct_notify_play;
1056 e->chat = uct_chat;
1057 e->genmove = uct_genmove;
1058 e->dead_group_list = uct_dead_group_list;
1059 e->done = uct_done;
1060 e->data = u;
1062 const char banner[] = "I'm playing UCT. When I'm losing, I will resign, "
1063 "if I think I win, I play until you pass. "
1064 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
1065 if (!u->banner) u->banner = "";
1066 e->comment = malloc(sizeof(banner) + strlen(u->banner) + 1);
1067 sprintf(e->comment, "%s %s", banner, u->banner);
1069 return e;