Increase MIN_MOVES_LEFT from 10 to 30 to give much larger safety
[pachi.git] / uct / uct.c
blob73ce93345d84536e8aa272e37ed52689fe5c7822
1 #include <assert.h>
2 #include <math.h>
3 #include <pthread.h>
4 #include <signal.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <time.h>
10 #define DEBUG
12 #include "debug.h"
13 #include "board.h"
14 #include "gtp.h"
15 #include "move.h"
16 #include "mq.h"
17 #include "playout.h"
18 #include "playout/elo.h"
19 #include "playout/moggy.h"
20 #include "playout/light.h"
21 #include "random.h"
22 #include "tactics.h"
23 #include "timeinfo.h"
24 #include "uct/dynkomi.h"
25 #include "uct/internal.h"
26 #include "uct/prior.h"
27 #include "uct/tree.h"
28 #include "uct/uct.h"
29 #include "uct/walk.h"
31 struct uct_policy *policy_ucb1_init(struct uct *u, char *arg);
32 struct uct_policy *policy_ucb1amaf_init(struct uct *u, char *arg);
33 static void uct_pondering_stop(struct uct *u);
36 /* Default number of simulations to perform per move.
37 * Note that this is now in total over all threads! (Unless TM_ROOT.) */
38 #define MC_GAMES 80000
39 #define MC_GAMELEN MAX_GAMELEN
40 static const struct time_info default_ti = {
41 .period = TT_MOVE,
42 .dim = TD_GAMES,
43 .len = { .games = MC_GAMES },
46 /* How big proportion of ownermap counts must be of one color to consider
47 * the point sure. */
48 #define GJ_THRES 0.8
49 /* How many games to consider at minimum before judging groups. */
50 #define GJ_MINGAMES 500
52 /* How often to inspect the tree from the main thread to check for playout
53 * stop, progress reports, etc. (in seconds) */
54 #define TREE_BUSYWAIT_INTERVAL 0.1 /* 100ms */
56 /* Once per how many simulations (per thread) to show a progress report line. */
57 #define TREE_SIMPROGRESS_INTERVAL 10000
59 /* When terminating uct_search() early, the safety margin to add to the
60 * remaining playout number estimate when deciding whether the result can
61 * still change. */
62 #define PLAYOUT_DELTA_SAFEMARGIN 1000
65 static void
66 setup_state(struct uct *u, struct board *b, enum stone color)
68 u->t = tree_init(b, color, u->fast_alloc ? u->max_tree_size : 0, u->local_tree_aging);
69 if (u->force_seed)
70 fast_srandom(u->force_seed);
71 if (UDEBUGL(0))
72 fprintf(stderr, "Fresh board with random seed %lu\n", fast_getseed());
73 //board_print(b, stderr);
74 if (!u->no_book && b->moves == 0) {
75 assert(color == S_BLACK);
76 tree_load(u->t, b);
80 static void
81 reset_state(struct uct *u)
83 assert(u->t);
84 tree_done(u->t); u->t = NULL;
87 static void
88 setup_dynkomi(struct uct *u, struct board *b, enum stone to_play)
90 if (u->t->use_extra_komi && u->dynkomi->permove)
91 u->t->extra_komi = u->dynkomi->permove(u->dynkomi, b, u->t);
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 return NULL;
189 static char *
190 uct_chat(struct engine *e, struct board *b, char *cmd)
192 struct uct *u = e->data;
193 static char reply[1024];
195 cmd += strspn(cmd, " \n\t");
196 if (!strncasecmp(cmd, "winrate", 7)) {
197 if (!u->t)
198 return "no game context (yet?)";
199 enum stone color = u->t->root_color;
200 struct tree_node *n = u->t->root;
201 snprintf(reply, 1024, "In %d playouts at %d threads, %s %s can win with %.2f%% probability",
202 n->u.playouts, u->threads, stone2str(color), coord2sstr(n->coord, b),
203 tree_node_get_value(u->t, -1, n->u.value) * 100);
204 if (u->t->use_extra_komi && abs(u->t->extra_komi) >= 0.5) {
205 sprintf(reply + strlen(reply), ", while self-imposing extra komi %.1f",
206 u->t->extra_komi);
208 strcat(reply, ".");
209 return reply;
211 return NULL;
214 static void
215 uct_dead_group_list(struct engine *e, struct board *b, struct move_queue *mq)
217 struct uct *u = e->data;
219 /* This means the game is probably over, no use pondering on. */
220 uct_pondering_stop(u);
222 if (u->pass_all_alive)
223 return; // no dead groups
225 bool mock_state = false;
227 if (!u->t) {
228 /* No state, but we cannot just back out - we might
229 * have passed earlier, only assuming some stones are
230 * dead, and then re-connected, only to lose counting
231 * when all stones are assumed alive. */
232 /* Mock up some state and seed the ownermap by few
233 * simulations. */
234 prepare_move(e, b, S_BLACK); assert(u->t);
235 for (int i = 0; i < GJ_MINGAMES; i++)
236 uct_playout(u, b, S_BLACK, u->t);
237 mock_state = true;
240 dead_group_list(u, b, mq);
242 if (mock_state) {
243 /* Clean up the mock state in case we will receive
244 * a genmove; we could get a non-alternating-move
245 * error from prepare_move() in that case otherwise. */
246 reset_state(u);
250 static void
251 playout_policy_done(struct playout_policy *p)
253 if (p->done) p->done(p);
254 if (p->data) free(p->data);
255 free(p);
258 static void
259 uct_done(struct engine *e)
261 /* This is called on engine reset, especially when clear_board
262 * is received and new game should begin. */
263 struct uct *u = e->data;
264 uct_pondering_stop(u);
265 if (u->t) reset_state(u);
266 free(u->ownermap.map);
268 free(u->policy);
269 free(u->random_policy);
270 playout_policy_done(u->playout);
271 uct_prior_done(u->prior);
275 /* Pachi threading structure (if uct_playouts_parallel() is used):
277 * main thread
278 * | main(), GTP communication, ...
279 * | starts and stops the search managed by thread_manager
281 * thread_manager
282 * | spawns and collects worker threads
284 * worker0
285 * worker1
286 * ...
287 * workerK
288 * uct_playouts() loop, doing descend-playout until uct_halt
290 * Another way to look at it is by functions (lines denote thread boundaries):
292 * | uct_genmove()
293 * | uct_search() (uct_search_start() .. uct_search_stop())
294 * | -----------------------
295 * | spawn_thread_manager()
296 * | -----------------------
297 * | spawn_worker()
298 * V uct_playouts() */
300 /* Set in thread manager in case the workers should stop. */
301 volatile sig_atomic_t uct_halt = 0;
302 /* ID of the running worker thread. */
303 __thread int thread_id = -1;
304 /* ID of the thread manager. */
305 static pthread_t thread_manager;
306 static bool thread_manager_running;
308 static pthread_mutex_t finish_mutex = PTHREAD_MUTEX_INITIALIZER;
309 static pthread_cond_t finish_cond = PTHREAD_COND_INITIALIZER;
310 static volatile int finish_thread;
311 static pthread_mutex_t finish_serializer = PTHREAD_MUTEX_INITIALIZER;
313 struct spawn_ctx {
314 int tid;
315 struct uct *u;
316 struct board *b;
317 enum stone color;
318 struct tree *t;
319 unsigned long seed;
320 int games;
323 static void *
324 spawn_worker(void *ctx_)
326 struct spawn_ctx *ctx = ctx_;
327 /* Setup */
328 fast_srandom(ctx->seed);
329 thread_id = ctx->tid;
330 /* Run */
331 ctx->games = uct_playouts(ctx->u, ctx->b, ctx->color, ctx->t);
332 /* Finish */
333 pthread_mutex_lock(&finish_serializer);
334 pthread_mutex_lock(&finish_mutex);
335 finish_thread = ctx->tid;
336 pthread_cond_signal(&finish_cond);
337 pthread_mutex_unlock(&finish_mutex);
338 return ctx;
341 /* Thread manager, controlling worker threads. It must be called with
342 * finish_mutex lock held, but it will unlock it itself before exiting;
343 * this is necessary to be completely deadlock-free. */
344 /* The finish_cond can be signalled for it to stop; in that case,
345 * the caller should set finish_thread = -1. */
346 /* After it is started, it will update mctx->t to point at some tree
347 * used for the actual search (matters only for TM_ROOT), on return
348 * it will set mctx->games to the number of performed simulations. */
349 static void *
350 spawn_thread_manager(void *ctx_)
352 /* In thread_manager, we use only some of the ctx fields. */
353 struct spawn_ctx *mctx = ctx_;
354 struct uct *u = mctx->u;
355 struct tree *t = mctx->t;
356 bool shared_tree = u->parallel_tree;
357 fast_srandom(mctx->seed);
359 int played_games = 0;
360 pthread_t threads[u->threads];
361 int joined = 0;
363 uct_halt = 0;
365 /* Garbage collect the tree by preference when pondering. */
366 if (u->pondering && t->nodes && t->nodes_size > t->max_tree_size/2) {
367 unsigned long temp_size = (MIN_FREE_MEM_PERCENT * t->max_tree_size) / 100;
368 t->root = tree_garbage_collect(t, temp_size, t->root);
371 /* Spawn threads... */
372 for (int ti = 0; ti < u->threads; ti++) {
373 struct spawn_ctx *ctx = malloc(sizeof(*ctx));
374 ctx->u = u; ctx->b = mctx->b; ctx->color = mctx->color;
375 mctx->t = ctx->t = shared_tree ? t : tree_copy(t);
376 ctx->tid = ti; ctx->seed = fast_random(65536) + ti;
377 pthread_create(&threads[ti], NULL, spawn_worker, ctx);
378 if (UDEBUGL(3))
379 fprintf(stderr, "Spawned worker %d\n", ti);
382 /* ...and collect them back: */
383 while (joined < u->threads) {
384 /* Wait for some thread to finish... */
385 pthread_cond_wait(&finish_cond, &finish_mutex);
386 if (finish_thread < 0) {
387 /* Stop-by-caller. Tell the workers to wrap up. */
388 uct_halt = 1;
389 continue;
391 /* ...and gather its remnants. */
392 struct spawn_ctx *ctx;
393 pthread_join(threads[finish_thread], (void **) &ctx);
394 played_games += ctx->games;
395 joined++;
396 if (!shared_tree) {
397 if (ctx->t == mctx->t) mctx->t = t;
398 tree_merge(t, ctx->t);
399 tree_done(ctx->t);
401 free(ctx);
402 if (UDEBUGL(3))
403 fprintf(stderr, "Joined worker %d\n", finish_thread);
404 pthread_mutex_unlock(&finish_serializer);
407 pthread_mutex_unlock(&finish_mutex);
409 if (!shared_tree)
410 tree_normalize(mctx->t, u->threads);
412 mctx->games = played_games;
413 return mctx;
416 static struct spawn_ctx *
417 uct_search_start(struct uct *u, struct board *b, enum stone color, struct tree *t)
419 assert(u->threads > 0);
420 assert(!thread_manager_running);
422 struct spawn_ctx ctx = { .u = u, .b = b, .color = color, .t = t, .seed = fast_random(65536) };
423 static struct spawn_ctx mctx; mctx = ctx;
424 pthread_mutex_lock(&finish_mutex);
425 pthread_create(&thread_manager, NULL, spawn_thread_manager, &mctx);
426 thread_manager_running = true;
427 return &mctx;
430 static struct spawn_ctx *
431 uct_search_stop(void)
433 assert(thread_manager_running);
435 /* Signal thread manager to stop the workers. */
436 pthread_mutex_lock(&finish_mutex);
437 finish_thread = -1;
438 pthread_cond_signal(&finish_cond);
439 pthread_mutex_unlock(&finish_mutex);
441 /* Collect the thread manager. */
442 struct spawn_ctx *pctx;
443 thread_manager_running = false;
444 pthread_join(thread_manager, (void **) &pctx);
445 return pctx;
449 /* Determine whether we should terminate the search early. */
450 static bool
451 uct_search_stop_early(struct uct *u, struct tree *t, struct board *b,
452 struct time_info *ti, struct time_stop *stop,
453 struct tree_node *best, struct tree_node *best2,
454 int base_playouts, int i)
456 /* Early break in won situation. */
457 if (best->u.playouts >= 2000 && tree_node_get_value(t, 1, best->u.value) >= u->loss_threshold)
458 return true;
459 /* Earlier break in super-won situation. */
460 if (best->u.playouts >= 500 && tree_node_get_value(t, 1, best->u.value) >= 0.95)
461 return true;
463 /* Break early if we estimate the second-best move cannot
464 * catch up in assigned time anymore. We use all our time
465 * if we are in byoyomi with single stone remaining in our
466 * period, however - it's better to pre-ponder. */
467 bool time_indulgent = (!ti->len.t.main_time && ti->len.t.byoyomi_stones == 1);
468 if (best2 && ti->dim == TD_WALLTIME && !time_indulgent) {
469 double elapsed = time_now() - ti->len.t.timer_start;
470 double remaining = stop->worst.time - elapsed;
471 double pps = ((double)i - base_playouts) / elapsed;
472 double estplayouts = remaining * pps + PLAYOUT_DELTA_SAFEMARGIN;
473 if (best->u.playouts > best2->u.playouts + estplayouts) {
474 if (UDEBUGL(2))
475 fprintf(stderr, "Early stop, result cannot change: "
476 "best %d, best2 %d, estimated %f simulations to go\n",
477 best->u.playouts, best2->u.playouts, estplayouts);
478 return true;
482 return false;
485 /* Determine whether we should terminate the search later. */
486 static bool
487 uct_search_keep_looking(struct uct *u, struct tree *t, struct board *b,
488 struct tree_node *best, struct tree_node *best2,
489 struct tree_node *bestr, struct tree_node *winner, int i)
491 if (!best) {
492 if (UDEBUGL(2))
493 fprintf(stderr, "Did not find best move, still trying...\n");
494 return true;
497 if (u->best2_ratio > 0) {
498 /* Check best/best2 simulations ratio. If the
499 * two best moves give very similar results,
500 * keep simulating. */
501 if (best2 && best2->u.playouts
502 && (double)best->u.playouts / best2->u.playouts < u->best2_ratio) {
503 if (UDEBUGL(2))
504 fprintf(stderr, "Best2 ratio %f < threshold %f\n",
505 (double)best->u.playouts / best2->u.playouts,
506 u->best2_ratio);
507 return true;
511 if (u->bestr_ratio > 0) {
512 /* Check best, best_best value difference. If the best move
513 * and its best child do not give similar enough results,
514 * keep simulating. */
515 if (bestr && bestr->u.playouts
516 && fabs((double)best->u.value - bestr->u.value) > u->bestr_ratio) {
517 if (UDEBUGL(2))
518 fprintf(stderr, "Bestr delta %f > threshold %f\n",
519 fabs((double)best->u.value - bestr->u.value),
520 u->bestr_ratio);
521 return true;
525 if (winner && winner != best) {
526 /* Keep simulating if best explored
527 * does not have also highest value. */
528 if (UDEBUGL(2))
529 fprintf(stderr, "[%d] best %3s [%d] %f != winner %3s [%d] %f\n", i,
530 coord2sstr(best->coord, t->board),
531 best->u.playouts, tree_node_get_value(t, 1, best->u.value),
532 coord2sstr(winner->coord, t->board),
533 winner->u.playouts, tree_node_get_value(t, 1, winner->u.value));
534 return true;
537 /* No reason to keep simulating, bye. */
538 return false;
541 /* Run time-limited MCTS search on foreground. */
542 static int
543 uct_search(struct uct *u, struct board *b, struct time_info *ti, enum stone color, struct tree *t)
545 int base_playouts = u->t->root->u.playouts;
546 if (UDEBUGL(2) && base_playouts > 0)
547 fprintf(stderr, "<pre-simulated %d games skipped>\n", base_playouts);
549 /* Set up time conditions. */
550 if (ti->period == TT_NULL) *ti = default_ti;
551 struct time_stop stop;
552 time_stop_conditions(ti, b, u->fuseki_end, u->yose_start, &stop);
554 /* Number of last dynkomi adjustment. */
555 int last_dynkomi = t->root->u.playouts;
556 /* Number of last game with progress print. */
557 int last_print = t->root->u.playouts;
558 /* Number of simulations to wait before next print. */
559 int print_interval = TREE_SIMPROGRESS_INTERVAL * (u->thread_model == TM_ROOT ? 1 : u->threads);
560 /* Printed notification about full memory? */
561 bool print_fullmem = false;
563 struct spawn_ctx *ctx = uct_search_start(u, b, color, t);
565 /* The search tree is ctx->t. This is normally == t, but in case of
566 * TM_ROOT, it is one of the trees belonging to the independent
567 * workers. It is important to reference ctx->t directly since the
568 * thread manager will swap the tree pointer asynchronously. */
569 /* XXX: This means TM_ROOT support is suboptimal since single stalled
570 * thread can stall the others in case of limiting the search by game
571 * count. However, TM_ROOT just does not deserve any more extra code
572 * right now. */
574 struct tree_node *best = NULL;
575 struct tree_node *best2 = NULL; // Second-best move.
576 struct tree_node *bestr = NULL; // best's best child.
577 struct tree_node *winner = NULL;
579 double busywait_interval = TREE_BUSYWAIT_INTERVAL;
581 /* Now, just periodically poll the search tree. */
582 while (1) {
583 time_sleep(busywait_interval);
584 /* busywait_interval should never be less than desired time, or the
585 * time control is broken. But if it happens to be less, we still search
586 * at least 100ms otherwise the move is completely random. */
588 int i = ctx->t->root->u.playouts;
590 /* Adjust dynkomi? */
591 if (ctx->t->use_extra_komi && u->dynkomi->permove
592 && u->dynkomi_interval
593 && i > last_dynkomi + u->dynkomi_interval) {
594 float old_dynkomi = ctx->t->extra_komi;
595 ctx->t->extra_komi = u->dynkomi->permove(u->dynkomi, b, ctx->t);
596 if (UDEBUGL(3) && old_dynkomi != ctx->t->extra_komi)
597 fprintf(stderr, "dynkomi adjusted (%f -> %f)\n", old_dynkomi, ctx->t->extra_komi);
600 /* Print progress? */
601 if (i - last_print > print_interval) {
602 last_print += print_interval; // keep the numbers tidy
603 uct_progress_status(u, ctx->t, color, last_print);
605 if (!print_fullmem && ctx->t->nodes_size > u->max_tree_size) {
606 if (UDEBUGL(2))
607 fprintf(stderr, "memory limit hit (%lu > %lu)\n", ctx->t->nodes_size, u->max_tree_size);
608 print_fullmem = true;
611 /* Never consider stopping if we played too few simulations.
612 * Maybe we risk losing on time when playing in super-extreme
613 * time pressure but the tree is going to be just too messed
614 * up otherwise - we might even play invalid suicides or pass
615 * when we mustn't. */
616 if (i < GJ_MINGAMES)
617 continue;
619 best = u->policy->choose(u->policy, ctx->t->root, b, color, resign);
620 if (best) best2 = u->policy->choose(u->policy, ctx->t->root, b, color, best->coord);
622 /* Possibly stop search early if it's no use to try on. */
623 if (best && uct_search_stop_early(u, ctx->t, b, ti, &stop, best, best2, base_playouts, i))
624 break;
626 /* Check against time settings. */
627 bool desired_done = false;
628 if (ti->dim == TD_WALLTIME) {
629 double elapsed = time_now() - ti->len.t.timer_start;
630 if (elapsed > stop.worst.time) break;
631 desired_done = elapsed > stop.desired.time;
633 } else { assert(ti->dim == TD_GAMES);
634 if (i > stop.worst.playouts) break;
635 desired_done = i > stop.desired.playouts;
638 /* We want to stop simulating, but are willing to keep trying
639 * if we aren't completely sure about the winner yet. */
640 if (desired_done) {
641 if (u->policy->winner && u->policy->evaluate) {
642 struct uct_descent descent = { .node = ctx->t->root };
643 u->policy->winner(u->policy, ctx->t, &descent);
644 winner = descent.node;
646 if (best)
647 bestr = u->policy->choose(u->policy, best, b, stone_other(color), resign);
648 if (!uct_search_keep_looking(u, ctx->t, b, best, best2, bestr, winner, i))
649 break;
652 /* TODO: Early break if best->variance goes under threshold and we already
653 * have enough playouts (possibly thanks to book or to pondering)? */
656 ctx = uct_search_stop();
658 if (UDEBUGL(2))
659 tree_dump(t, u->dumpthres);
660 if (UDEBUGL(0))
661 uct_progress_status(u, t, color, ctx->games);
663 return ctx->games;
667 /* Start pondering background with @color to play. */
668 static void
669 uct_pondering_start(struct uct *u, struct board *b0, struct tree *t, enum stone color)
671 if (UDEBUGL(1))
672 fprintf(stderr, "Starting to ponder with color %s\n", stone2str(stone_other(color)));
673 u->pondering = true;
675 /* We need a local board copy to ponder upon. */
676 struct board *b = malloc(sizeof(*b)); board_copy(b, b0);
678 /* *b0 did not have the genmove'd move played yet. */
679 struct move m = { t->root->coord, t->root_color };
680 int res = board_play(b, &m);
681 assert(res >= 0);
682 setup_dynkomi(u, b, stone_other(m.color));
684 /* Start MCTS manager thread "headless". */
685 uct_search_start(u, b, color, t);
688 /* uct_search_stop() frontend for the pondering (non-genmove) mode. */
689 static void
690 uct_pondering_stop(struct uct *u)
692 u->pondering = false;
693 if (!thread_manager_running)
694 return;
696 /* Stop the thread manager. */
697 struct spawn_ctx *ctx = uct_search_stop();
698 if (UDEBUGL(1)) {
699 fprintf(stderr, "(pondering) ");
700 uct_progress_status(u, ctx->t, ctx->color, ctx->games);
702 free(ctx->b);
706 static coord_t *
707 uct_genmove(struct engine *e, struct board *b, struct time_info *ti, enum stone color, bool pass_all_alive)
709 double start_time = time_now();
710 struct uct *u = e->data;
712 if (b->superko_violation) {
713 fprintf(stderr, "!!! WARNING: SUPERKO VIOLATION OCCURED BEFORE THIS MOVE\n");
714 fprintf(stderr, "Maybe you play with situational instead of positional superko?\n");
715 fprintf(stderr, "I'm going to ignore the violation, but note that I may miss\n");
716 fprintf(stderr, "some moves valid under this ruleset because of this.\n");
717 b->superko_violation = false;
720 /* Seed the tree. */
721 uct_pondering_stop(u);
722 prepare_move(e, b, color);
723 assert(u->t);
725 /* How to decide whether to use dynkomi in this game? Since we use
726 * pondering, it's not simple "who-to-play" matter. Decide based on
727 * the last genmove issued. */
728 u->t->use_extra_komi = !!(u->dynkomi_mask & color);
729 setup_dynkomi(u, b, color);
731 /* Make pessimistic assumption about komi for Japanese rules to
732 * avoid losing by 0.5 when winning by 0.5 with Chinese rules.
733 * The rules usually give the same winner if the integer part of komi
734 * is odd so we adjust the komi only if it is even (for a board of
735 * odd size). We are not trying to get an exact evaluation for rare
736 * cases of seki. For details see http://home.snafu.de/jasiek/parity.html
737 * TODO: Support the kgs-rules command once available. */
738 if (u->territory_scoring && (((int)floor(b->komi) + board_size(b)) & 1)) {
739 b->komi += (color == S_BLACK ? 1.0 : -1.0);
740 if (UDEBUGL(0))
741 fprintf(stderr, "Setting komi to %.1f assuming Japanese rules\n",
742 b->komi);
745 int base_playouts = u->t->root->u.playouts;
746 /* Perform the Monte Carlo Tree Search! */
747 int played_games = uct_search(u, b, ti, color, u->t);
749 /* Choose the best move from the tree. */
750 struct tree_node *best = u->policy->choose(u->policy, u->t->root, b, color, resign);
751 if (!best) {
752 reset_state(u);
753 return coord_copy(pass);
755 if (UDEBUGL(1))
756 fprintf(stderr, "*** WINNER is %s (%d,%d) with score %1.4f (%d/%d:%d/%d games), extra komi %f\n",
757 coord2sstr(best->coord, b), coord_x(best->coord, b), coord_y(best->coord, b),
758 tree_node_get_value(u->t, 1, best->u.value), best->u.playouts,
759 u->t->root->u.playouts, u->t->root->u.playouts - base_playouts, played_games,
760 u->t->extra_komi);
762 /* Do not resign if we're so short of time that evaluation of best
763 * move is completely unreliable, we might be winning actually.
764 * In this case best is almost random but still better than resign.
765 * Also do not resign if we are getting bad results while actually
766 * giving away extra komi points (dynkomi). */
767 if (tree_node_get_value(u->t, 1, best->u.value) < u->resign_ratio
768 && !is_pass(best->coord) && best->u.playouts > GJ_MINGAMES
769 && u->t->extra_komi <= 1 /* XXX we assume dynamic komi == we are black */) {
770 reset_state(u);
771 return coord_copy(resign);
774 /* If the opponent just passed and we win counting, always
775 * pass as well. */
776 if (b->moves > 1 && is_pass(b->last_move.coord)) {
777 /* Make sure enough playouts are simulated. */
778 while (u->ownermap.playouts < GJ_MINGAMES)
779 uct_playout(u, b, color, u->t);
780 if (uct_pass_is_safe(u, b, color, u->pass_all_alive || pass_all_alive)) {
781 if (UDEBUGL(0))
782 fprintf(stderr, "<Will rather pass, looks safe enough.>\n");
783 best->coord = pass;
787 tree_promote_node(u->t, &best);
788 /* After a pass, pondering is harmful for two reasons:
789 * (i) We might keep pondering even when the game is over.
790 * Of course this is the case for opponent resign as well.
791 * (ii) More importantly, the ownermap will get skewed since
792 * the UCT will start cutting off any playouts. */
793 if (u->pondering_opt && !is_pass(best->coord)) {
794 uct_pondering_start(u, b, u->t, stone_other(color));
796 if (UDEBUGL(2)) {
797 double time = time_now() - start_time + 0.000001; /* avoid divide by zero */
798 fprintf(stderr, "genmove in %0.2fs (%d games/s, %d games/s/thread)\n",
799 time, (int)(played_games/time), (int)(played_games/time/u->threads));
801 return coord_copy(best->coord);
805 bool
806 uct_genbook(struct engine *e, struct board *b, struct time_info *ti, enum stone color)
808 struct uct *u = e->data;
809 if (!u->t) prepare_move(e, b, color);
810 assert(u->t);
812 if (ti->dim == TD_GAMES) {
813 /* Don't count in games that already went into the book. */
814 ti->len.games += u->t->root->u.playouts;
816 uct_search(u, b, ti, color, u->t);
818 assert(ti->dim == TD_GAMES);
819 tree_save(u->t, b, ti->len.games / 100);
821 return true;
824 void
825 uct_dumpbook(struct engine *e, struct board *b, enum stone color)
827 struct uct *u = e->data;
828 struct tree *t = tree_init(b, color, u->fast_alloc ? u->max_tree_size : 0, u->local_tree_aging);
829 tree_load(t, b);
830 tree_dump(t, 0);
831 tree_done(t);
835 struct uct *
836 uct_state_init(char *arg, struct board *b)
838 struct uct *u = calloc(1, sizeof(struct uct));
839 bool using_elo = false;
841 u->debug_level = debug_level;
842 u->gamelen = MC_GAMELEN;
843 u->mercymin = 0;
844 u->expand_p = 2;
845 u->dumpthres = 1000;
846 u->playout_amaf = true;
847 u->playout_amaf_nakade = false;
848 u->amaf_prior = false;
849 u->max_tree_size = 3072ULL * 1048576;
851 u->dynkomi_mask = S_BLACK;
853 u->threads = 1;
854 u->thread_model = TM_TREEVL;
855 u->parallel_tree = true;
856 u->virtual_loss = true;
858 u->fuseki_end = 20; // max time at 361*20% = 72 moves (our 36th move, still 99 to play)
859 u->yose_start = 40; // (100-40-25)*361/100/2 = 63 moves still to play by us then
860 u->bestr_ratio = 0.02;
861 // 2.5 is clearly too much, but seems to compensate well for overly stern time allocations.
862 // TODO: Further tuning and experiments with better time allocation schemes.
863 u->best2_ratio = 2.5;
865 u->val_scale = 0.04; u->val_points = 40;
867 u->tenuki_d = 4;
868 u->local_tree_aging = 2;
870 if (arg) {
871 char *optspec, *next = arg;
872 while (*next) {
873 optspec = next;
874 next += strcspn(next, ",");
875 if (*next) { *next++ = 0; } else { *next = 0; }
877 char *optname = optspec;
878 char *optval = strchr(optspec, '=');
879 if (optval) *optval++ = 0;
881 if (!strcasecmp(optname, "debug")) {
882 if (optval)
883 u->debug_level = atoi(optval);
884 else
885 u->debug_level++;
886 } else if (!strcasecmp(optname, "mercy") && optval) {
887 /* Minimal difference of black/white captures
888 * to stop playout - "Mercy Rule". Speeds up
889 * hopeless playouts at the expense of some
890 * accuracy. */
891 u->mercymin = atoi(optval);
892 } else if (!strcasecmp(optname, "gamelen") && optval) {
893 u->gamelen = atoi(optval);
894 } else if (!strcasecmp(optname, "expand_p") && optval) {
895 u->expand_p = atoi(optval);
896 } else if (!strcasecmp(optname, "dumpthres") && optval) {
897 u->dumpthres = atoi(optval);
898 } else if (!strcasecmp(optname, "best2_ratio") && optval) {
899 /* If set, prolong simulating while
900 * first_best/second_best playouts ratio
901 * is less than best2_ratio. */
902 u->best2_ratio = atof(optval);
903 } else if (!strcasecmp(optname, "bestr_ratio") && optval) {
904 /* If set, prolong simulating while
905 * best,best_best_child values delta
906 * is more than bestr_ratio. */
907 u->bestr_ratio = atof(optval);
908 } else if (!strcasecmp(optname, "playout_amaf")) {
909 /* Whether to include random playout moves in
910 * AMAF as well. (Otherwise, only tree moves
911 * are included in AMAF. Of course makes sense
912 * only in connection with an AMAF policy.) */
913 /* with-without: 55.5% (+-4.1) */
914 if (optval && *optval == '0')
915 u->playout_amaf = false;
916 else
917 u->playout_amaf = true;
918 } else if (!strcasecmp(optname, "playout_amaf_nakade")) {
919 /* Whether to include nakade moves from playouts
920 * in the AMAF statistics; this tends to nullify
921 * the playout_amaf effect by adding too much
922 * noise. */
923 if (optval && *optval == '0')
924 u->playout_amaf_nakade = false;
925 else
926 u->playout_amaf_nakade = true;
927 } else if (!strcasecmp(optname, "playout_amaf_cutoff") && optval) {
928 /* Keep only first N% of playout stage AMAF
929 * information. */
930 u->playout_amaf_cutoff = atoi(optval);
931 } else if ((!strcasecmp(optname, "policy") || !strcasecmp(optname, "random_policy")) && optval) {
932 char *policyarg = strchr(optval, ':');
933 struct uct_policy **p = !strcasecmp(optname, "policy") ? &u->policy : &u->random_policy;
934 if (policyarg)
935 *policyarg++ = 0;
936 if (!strcasecmp(optval, "ucb1")) {
937 *p = policy_ucb1_init(u, policyarg);
938 } else if (!strcasecmp(optval, "ucb1amaf")) {
939 *p = policy_ucb1amaf_init(u, policyarg);
940 } else {
941 fprintf(stderr, "UCT: Invalid tree policy %s\n", optval);
942 exit(1);
944 } else if (!strcasecmp(optname, "playout") && optval) {
945 char *playoutarg = strchr(optval, ':');
946 if (playoutarg)
947 *playoutarg++ = 0;
948 if (!strcasecmp(optval, "moggy")) {
949 u->playout = playout_moggy_init(playoutarg, b);
950 } else if (!strcasecmp(optval, "light")) {
951 u->playout = playout_light_init(playoutarg, b);
952 } else if (!strcasecmp(optval, "elo")) {
953 u->playout = playout_elo_init(playoutarg, b);
954 using_elo = true;
955 } else {
956 fprintf(stderr, "UCT: Invalid playout policy %s\n", optval);
957 exit(1);
959 } else if (!strcasecmp(optname, "prior") && optval) {
960 u->prior = uct_prior_init(optval, b);
961 } else if (!strcasecmp(optname, "amaf_prior") && optval) {
962 u->amaf_prior = atoi(optval);
963 } else if (!strcasecmp(optname, "threads") && optval) {
964 /* By default, Pachi will run with only single
965 * tree search thread! */
966 u->threads = atoi(optval);
967 } else if (!strcasecmp(optname, "thread_model") && optval) {
968 if (!strcasecmp(optval, "root")) {
969 /* Root parallelization - each thread
970 * does independent search, trees are
971 * merged at the end. */
972 u->thread_model = TM_ROOT;
973 u->parallel_tree = false;
974 u->virtual_loss = false;
975 } else if (!strcasecmp(optval, "tree")) {
976 /* Tree parallelization - all threads
977 * grind on the same tree. */
978 u->thread_model = TM_TREE;
979 u->parallel_tree = true;
980 u->virtual_loss = false;
981 } else if (!strcasecmp(optval, "treevl")) {
982 /* Tree parallelization, but also
983 * with virtual losses - this discou-
984 * rages most threads choosing the
985 * same tree branches to read. */
986 u->thread_model = TM_TREEVL;
987 u->parallel_tree = true;
988 u->virtual_loss = true;
989 } else {
990 fprintf(stderr, "UCT: Invalid thread model %s\n", optval);
991 exit(1);
993 } else if (!strcasecmp(optname, "pondering")) {
994 /* Keep searching even during opponent's turn. */
995 u->pondering_opt = !optval || atoi(optval);
996 } else if (!strcasecmp(optname, "fuseki_end") && optval) {
997 /* At the very beginning it's not worth thinking
998 * too long because the playout evaluations are
999 * very noisy. So gradually increase the thinking
1000 * time up to maximum when fuseki_end percent
1001 * of the board has been played.
1002 * This only applies if we are not in byoyomi. */
1003 u->fuseki_end = atoi(optval);
1004 } else if (!strcasecmp(optname, "yose_start") && optval) {
1005 /* When yose_start percent of the board has been
1006 * played, or if we are in byoyomi, stop spending
1007 * more time and spread the remaining time
1008 * uniformly.
1009 * Between fuseki_end and yose_start, we spend
1010 * a constant proportion of the remaining time
1011 * on each move. (yose_start should actually
1012 * be much earlier than when real yose start,
1013 * but "yose" is a good short name to convey
1014 * the idea.) */
1015 u->yose_start = atoi(optval);
1016 } else if (!strcasecmp(optname, "force_seed") && optval) {
1017 u->force_seed = atoi(optval);
1018 } else if (!strcasecmp(optname, "no_book")) {
1019 u->no_book = true;
1020 } else if (!strcasecmp(optname, "dynkomi") && optval) {
1021 /* Dynamic komi approach; there are multiple
1022 * ways to adjust komi dynamically throughout
1023 * play. We currently support two: */
1024 char *dynkomiarg = strchr(optval, ':');
1025 if (dynkomiarg)
1026 *dynkomiarg++ = 0;
1027 if (!strcasecmp(optval, "none")) {
1028 u->dynkomi = uct_dynkomi_init_none(u, dynkomiarg, b);
1029 } else if (!strcasecmp(optval, "linear")) {
1030 u->dynkomi = uct_dynkomi_init_linear(u, dynkomiarg, b);
1031 } else if (!strcasecmp(optval, "adaptive")) {
1032 u->dynkomi = uct_dynkomi_init_adaptive(u, dynkomiarg, b);
1033 } else {
1034 fprintf(stderr, "UCT: Invalid dynkomi mode %s\n", optval);
1035 exit(1);
1037 } else if (!strcasecmp(optname, "dynkomi_mask") && optval) {
1038 /* Bitmask of colors the player must be
1039 * for dynkomi be applied; you may want
1040 * to use dynkomi_mask=3 to allow dynkomi
1041 * even in games where Pachi is white. */
1042 u->dynkomi_mask = atoi(optval);
1043 } else if (!strcasecmp(optname, "dynkomi_interval") && optval) {
1044 /* If non-zero, re-adjust dynamic komi
1045 * throughout a single genmove reading,
1046 * roughly every N simulations. */
1047 u->dynkomi_interval = atoi(optval);
1048 } else if (!strcasecmp(optname, "val_scale") && optval) {
1049 /* How much of the game result value should be
1050 * influenced by win size. Zero means it isn't. */
1051 u->val_scale = atof(optval);
1052 } else if (!strcasecmp(optname, "val_points") && optval) {
1053 /* Maximum size of win to be scaled into game
1054 * result value. Zero means boardsize^2. */
1055 u->val_points = atoi(optval) * 2; // result values are doubled
1056 } else if (!strcasecmp(optname, "val_extra")) {
1057 /* If false, the score coefficient will be simply
1058 * added to the value, instead of scaling the result
1059 * coefficient because of it. */
1060 u->val_extra = !optval || atoi(optval);
1061 } else if (!strcasecmp(optname, "local_tree") && optval) {
1062 /* Whether to bias exploration by local tree values
1063 * (must be supported by the used policy).
1064 * 0: Don't.
1065 * 1: Do, value = result.
1066 * Try to temper the result:
1067 * 2: Do, value = 0.5+(result-expected)/2.
1068 * 3: Do, value = 0.5+bzz((result-expected)^2).
1069 * 4: Do, value = 0.5+sqrt(result-expected)/2. */
1070 u->local_tree = atoi(optval);
1071 } else if (!strcasecmp(optname, "tenuki_d") && optval) {
1072 /* Tenuki distance at which to break the local tree. */
1073 u->tenuki_d = atoi(optval);
1074 if (u->tenuki_d > TREE_NODE_D_MAX + 1) {
1075 fprintf(stderr, "uct: tenuki_d must not be larger than TREE_NODE_D_MAX+1 %d\n", TREE_NODE_D_MAX + 1);
1076 exit(1);
1078 } else if (!strcasecmp(optname, "local_tree_aging") && optval) {
1079 /* How much to reduce local tree values between moves. */
1080 u->local_tree_aging = atof(optval);
1081 } else if (!strcasecmp(optname, "local_tree_allseq")) {
1082 /* By default, only complete sequences are stored
1083 * in the local tree. If this is on, also
1084 * subsequences starting at each move are stored. */
1085 u->local_tree_allseq = !optval || atoi(optval);
1086 } else if (!strcasecmp(optname, "local_tree_playout")) {
1087 /* Whether to adjust ELO playout probability
1088 * distributions according to matched localtree
1089 * information. */
1090 u->local_tree_playout = !optval || atoi(optval);
1091 } else if (!strcasecmp(optname, "local_tree_pseqroot")) {
1092 /* By default, when we have no sequence move
1093 * to suggest in-playout, we give up. If this
1094 * is on, we make probability distribution from
1095 * sequences first moves instead. */
1096 u->local_tree_pseqroot = !optval || atoi(optval);
1097 } else if (!strcasecmp(optname, "pass_all_alive")) {
1098 /* Whether to consider all stones alive at the game
1099 * end instead of marking dead groupd. */
1100 u->pass_all_alive = !optval || atoi(optval);
1101 } else if (!strcasecmp(optname, "territory_scoring")) {
1102 /* Use territory scoring (default is area scoring).
1103 * An explicit kgs-rules command overrides this. */
1104 u->territory_scoring = !optval || atoi(optval);
1105 } else if (!strcasecmp(optname, "random_policy_chance") && optval) {
1106 /* If specified (N), with probability 1/N, random_policy policy
1107 * descend is used instead of main policy descend; useful
1108 * if specified policy (e.g. UCB1AMAF) can make unduly biased
1109 * choices sometimes, you can fall back to e.g.
1110 * random_policy=UCB1. */
1111 u->random_policy_chance = atoi(optval);
1112 } else if (!strcasecmp(optname, "max_tree_size") && optval) {
1113 /* Maximum amount of memory [MiB] consumed by the move tree.
1114 * For fast_alloc it includes the temp tree used for pruning.
1115 * Default is 3072 (3 GiB). Note that if you use TM_ROOT,
1116 * this limits size of only one of the trees, not all of them
1117 * together. */
1118 u->max_tree_size = atol(optval) * 1048576;
1119 } else if (!strcasecmp(optname, "fast_alloc")) {
1120 u->fast_alloc = !optval || atoi(optval);
1121 } else if (!strcasecmp(optname, "banner") && optval) {
1122 /* Additional banner string. This must come as the
1123 * last engine parameter. */
1124 if (*next) *--next = ',';
1125 u->banner = strdup(optval);
1126 break;
1127 } else {
1128 fprintf(stderr, "uct: Invalid engine argument %s or missing value\n", optname);
1129 exit(1);
1134 u->resign_ratio = 0.2; /* Resign when most games are lost. */
1135 u->loss_threshold = 0.85; /* Stop reading if after at least 5000 playouts this is best value. */
1136 if (!u->policy)
1137 u->policy = policy_ucb1amaf_init(u, NULL);
1139 if (!!u->random_policy_chance ^ !!u->random_policy) {
1140 fprintf(stderr, "uct: Only one of random_policy and random_policy_chance is set\n");
1141 exit(1);
1144 if (!u->local_tree) {
1145 /* No ltree aging. */
1146 u->local_tree_aging = 1.0f;
1148 if (!using_elo)
1149 u->local_tree_playout = false;
1151 if (u->fast_alloc && !u->parallel_tree) {
1152 fprintf(stderr, "fast_alloc not supported with root parallelization.\n");
1153 exit(1);
1155 if (u->fast_alloc)
1156 u->max_tree_size = (100ULL * u->max_tree_size) / (100 + MIN_FREE_MEM_PERCENT);
1158 if (!u->prior)
1159 u->prior = uct_prior_init(NULL, b);
1161 if (!u->playout)
1162 u->playout = playout_moggy_init(NULL, b);
1163 u->playout->debug_level = u->debug_level;
1165 u->ownermap.map = malloc(board_size2(b) * sizeof(u->ownermap.map[0]));
1167 if (!u->dynkomi)
1168 u->dynkomi = uct_dynkomi_init_linear(u, NULL, b);
1170 /* Some things remain uninitialized for now - the opening book
1171 * is not loaded and the tree not set up. */
1172 /* This will be initialized in setup_state() at the first move
1173 * received/requested. This is because right now we are not aware
1174 * about any komi or handicap setup and such. */
1176 return u;
1179 struct engine *
1180 engine_uct_init(char *arg, struct board *b)
1182 struct uct *u = uct_state_init(arg, b);
1183 struct engine *e = calloc(1, sizeof(struct engine));
1184 e->name = "UCT Engine";
1185 e->printhook = uct_printhook_ownermap;
1186 e->notify_play = uct_notify_play;
1187 e->chat = uct_chat;
1188 e->genmove = uct_genmove;
1189 e->dead_group_list = uct_dead_group_list;
1190 e->done = uct_done;
1191 e->data = u;
1193 const char banner[] = "I'm playing UCT. When I'm losing, I will resign, "
1194 "if I think I win, I play until you pass. "
1195 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
1196 if (!u->banner) u->banner = "";
1197 e->comment = malloc(sizeof(banner) + strlen(u->banner) + 1);
1198 sprintf(e->comment, "%s %s", banner, u->banner);
1200 return e;