Slave thread: check for updated command before replying.
[pachi.git] / uct / uct.c
blobea0d25cdd93173c3609f2e51772578a8c3af0004
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 "distributed/distributed.h"
25 #include "uct/dynkomi.h"
26 #include "uct/internal.h"
27 #include "uct/prior.h"
28 #include "uct/tree.h"
29 #include "uct/uct.h"
30 #include "uct/walk.h"
32 struct uct_policy *policy_ucb1_init(struct uct *u, char *arg);
33 struct uct_policy *policy_ucb1amaf_init(struct uct *u, char *arg);
34 static void uct_pondering_stop(struct uct *u);
35 static void uct_pondering_start(struct uct *u, struct board *b0, struct tree *t, enum stone color);
38 /* Default number of simulations to perform per move.
39 * Note that this is now in total over all threads! (Unless TM_ROOT.) */
40 #define MC_GAMES 80000
41 #define MC_GAMELEN MAX_GAMELEN
42 static const struct time_info default_ti = {
43 .period = TT_MOVE,
44 .dim = TD_GAMES,
45 .len = { .games = MC_GAMES },
48 /* How big proportion of ownermap counts must be of one color to consider
49 * the point sure. */
50 #define GJ_THRES 0.8
51 /* How many games to consider at minimum before judging groups. */
52 #define GJ_MINGAMES 500
54 /* How often to inspect the tree from the main thread to check for playout
55 * stop, progress reports, etc. (in seconds) */
56 #define TREE_BUSYWAIT_INTERVAL 0.1 /* 100ms */
58 /* Once per how many simulations (per thread) to show a progress report line. */
59 #define TREE_SIMPROGRESS_INTERVAL 10000
61 /* When terminating uct_search() early, the safety margin to add to the
62 * remaining playout number estimate when deciding whether the result can
63 * still change. */
64 #define PLAYOUT_DELTA_SAFEMARGIN 1000
67 static void
68 setup_state(struct uct *u, struct board *b, enum stone color)
70 u->t = tree_init(b, color, u->fast_alloc ? u->max_tree_size : 0, u->local_tree_aging);
71 if (u->force_seed)
72 fast_srandom(u->force_seed);
73 if (UDEBUGL(0))
74 fprintf(stderr, "Fresh board with random seed %lu\n", fast_getseed());
75 //board_print(b, stderr);
76 if (!u->no_book && b->moves == 0) {
77 assert(color == S_BLACK);
78 tree_load(u->t, b);
82 static void
83 reset_state(struct uct *u)
85 assert(u->t);
86 tree_done(u->t); u->t = NULL;
89 static void
90 setup_dynkomi(struct uct *u, struct board *b, enum stone to_play)
92 if (u->t->use_extra_komi && u->dynkomi->permove)
93 u->t->extra_komi = u->dynkomi->permove(u->dynkomi, b, u->t);
96 static void
97 prepare_move(struct engine *e, struct board *b, enum stone color)
99 struct uct *u = e->data;
101 if (u->t) {
102 /* Verify that we have sane state. */
103 assert(b->es == u);
104 assert(u->t && b->moves);
105 if (color != stone_other(u->t->root_color)) {
106 fprintf(stderr, "Fatal: Non-alternating play detected %d %d\n",
107 color, u->t->root_color);
108 exit(1);
111 } else {
112 /* We need fresh state. */
113 b->es = u;
114 setup_state(u, b, color);
117 u->ownermap.playouts = 0;
118 memset(u->ownermap.map, 0, board_size2(b) * sizeof(u->ownermap.map[0]));
121 static void
122 dead_group_list(struct uct *u, struct board *b, struct move_queue *mq)
124 struct group_judgement gj;
125 gj.thres = GJ_THRES;
126 gj.gs = alloca(board_size2(b) * sizeof(gj.gs[0]));
127 board_ownermap_judge_group(b, &u->ownermap, &gj);
128 groups_of_status(b, &gj, GS_DEAD, mq);
131 bool
132 uct_pass_is_safe(struct uct *u, struct board *b, enum stone color, bool pass_all_alive)
134 if (u->ownermap.playouts < GJ_MINGAMES)
135 return false;
137 struct move_queue mq = { .moves = 0 };
138 if (!pass_all_alive)
139 dead_group_list(u, b, &mq);
140 return pass_is_safe(b, color, &mq);
143 /* This function is called only when running as slave in the distributed version. */
144 static enum parse_code
145 uct_notify(struct engine *e, struct board *b, int id, char *cmd, char *args, char **reply)
147 struct uct *u = e->data;
149 /* Force resending the whole command history if we are out of sync
150 * but do it only once, not if already getting the history. */
151 if (move_number(id) != b->moves && !reply_disabled(id) && !is_reset(cmd)) {
152 if (UDEBUGL(0))
153 fprintf(stderr, "Out of sync, id %d, move %d\n", id, b->moves);
154 static char buf[128];
155 snprintf(buf, sizeof(buf), "out of sync, move %d expected", b->moves);
156 *reply = buf;
157 return P_DONE_ERROR;
159 return reply_disabled(id) ? P_NOREPLY : P_OK;
162 static void
163 uct_printhook_ownermap(struct board *board, coord_t c, FILE *f)
165 struct uct *u = board->es;
166 assert(u);
167 const char chr[] = ":XO,"; // dame, black, white, unclear
168 const char chm[] = ":xo,";
169 char ch = chr[board_ownermap_judge_point(&u->ownermap, c, GJ_THRES)];
170 if (ch == ',') { // less precise estimate then?
171 ch = chm[board_ownermap_judge_point(&u->ownermap, c, 0.67)];
173 fprintf(f, "%c ", ch);
176 static char *
177 uct_notify_play(struct engine *e, struct board *b, struct move *m)
179 struct uct *u = e->data;
180 if (!u->t) {
181 /* No state, create one - this is probably game beginning
182 * and we need to load the opening book right now. */
183 prepare_move(e, b, m->color);
184 assert(u->t);
187 /* Stop pondering, required by tree_promote_at() */
188 uct_pondering_stop(u);
190 if (is_resign(m->coord)) {
191 /* Reset state. */
192 reset_state(u);
193 return NULL;
196 /* Promote node of the appropriate move to the tree root. */
197 assert(u->t->root);
198 if (!tree_promote_at(u->t, b, m->coord)) {
199 if (UDEBUGL(0))
200 fprintf(stderr, "Warning: Cannot promote move node! Several play commands in row?\n");
201 reset_state(u);
202 return NULL;
205 /* If we are a slave in a distributed engine, start pondering once
206 * we know which move we actually played. See uct_genmove() about
207 * the check for pass. */
208 if (u->pondering_opt && u->slave && m->color == u->my_color && !is_pass(m->coord))
209 uct_pondering_start(u, b, u->t, stone_other(m->color));
211 return NULL;
214 static char *
215 uct_chat(struct engine *e, struct board *b, char *cmd)
217 struct uct *u = e->data;
218 static char reply[1024];
220 cmd += strspn(cmd, " \n\t");
221 if (!strncasecmp(cmd, "winrate", 7)) {
222 if (!u->t)
223 return "no game context (yet?)";
224 enum stone color = u->t->root_color;
225 struct tree_node *n = u->t->root;
226 snprintf(reply, 1024, "In %d playouts at %d threads, %s %s can win with %.2f%% probability",
227 n->u.playouts, u->threads, stone2str(color), coord2sstr(n->coord, b),
228 tree_node_get_value(u->t, -1, n->u.value) * 100);
229 if (u->t->use_extra_komi && abs(u->t->extra_komi) >= 0.5) {
230 sprintf(reply + strlen(reply), ", while self-imposing extra komi %.1f",
231 u->t->extra_komi);
233 strcat(reply, ".");
234 return reply;
236 return NULL;
239 static void
240 uct_dead_group_list(struct engine *e, struct board *b, struct move_queue *mq)
242 struct uct *u = e->data;
244 /* This means the game is probably over, no use pondering on. */
245 uct_pondering_stop(u);
247 if (u->pass_all_alive)
248 return; // no dead groups
250 bool mock_state = false;
252 if (!u->t) {
253 /* No state, but we cannot just back out - we might
254 * have passed earlier, only assuming some stones are
255 * dead, and then re-connected, only to lose counting
256 * when all stones are assumed alive. */
257 /* Mock up some state and seed the ownermap by few
258 * simulations. */
259 prepare_move(e, b, S_BLACK); assert(u->t);
260 for (int i = 0; i < GJ_MINGAMES; i++)
261 uct_playout(u, b, S_BLACK, u->t);
262 mock_state = true;
265 dead_group_list(u, b, mq);
267 if (mock_state) {
268 /* Clean up the mock state in case we will receive
269 * a genmove; we could get a non-alternating-move
270 * error from prepare_move() in that case otherwise. */
271 reset_state(u);
275 static void
276 playout_policy_done(struct playout_policy *p)
278 if (p->done) p->done(p);
279 if (p->data) free(p->data);
280 free(p);
283 static void
284 uct_done(struct engine *e)
286 /* This is called on engine reset, especially when clear_board
287 * is received and new game should begin. */
288 struct uct *u = e->data;
289 uct_pondering_stop(u);
290 if (u->t) reset_state(u);
291 free(u->ownermap.map);
293 free(u->policy);
294 free(u->random_policy);
295 playout_policy_done(u->playout);
296 uct_prior_done(u->prior);
300 /* Pachi threading structure (if uct_playouts_parallel() is used):
302 * main thread
303 * | main(), GTP communication, ...
304 * | starts and stops the search managed by thread_manager
306 * thread_manager
307 * | spawns and collects worker threads
309 * worker0
310 * worker1
311 * ...
312 * workerK
313 * uct_playouts() loop, doing descend-playout until uct_halt
315 * Another way to look at it is by functions (lines denote thread boundaries):
317 * | uct_genmove()
318 * | uct_search() (uct_search_start() .. uct_search_stop())
319 * | -----------------------
320 * | spawn_thread_manager()
321 * | -----------------------
322 * | spawn_worker()
323 * V uct_playouts() */
325 /* Set in thread manager in case the workers should stop. */
326 volatile sig_atomic_t uct_halt = 0;
327 /* ID of the running worker thread. */
328 __thread int thread_id = -1;
329 /* ID of the thread manager. */
330 static pthread_t thread_manager;
331 static bool thread_manager_running;
333 static pthread_mutex_t finish_mutex = PTHREAD_MUTEX_INITIALIZER;
334 static pthread_cond_t finish_cond = PTHREAD_COND_INITIALIZER;
335 static volatile int finish_thread;
336 static pthread_mutex_t finish_serializer = PTHREAD_MUTEX_INITIALIZER;
338 struct spawn_ctx {
339 int tid;
340 struct uct *u;
341 struct board *b;
342 enum stone color;
343 struct tree *t;
344 unsigned long seed;
345 int games;
348 static void *
349 spawn_worker(void *ctx_)
351 struct spawn_ctx *ctx = ctx_;
352 /* Setup */
353 fast_srandom(ctx->seed);
354 thread_id = ctx->tid;
355 /* Run */
356 ctx->games = uct_playouts(ctx->u, ctx->b, ctx->color, ctx->t);
357 /* Finish */
358 pthread_mutex_lock(&finish_serializer);
359 pthread_mutex_lock(&finish_mutex);
360 finish_thread = ctx->tid;
361 pthread_cond_signal(&finish_cond);
362 pthread_mutex_unlock(&finish_mutex);
363 return ctx;
366 /* Thread manager, controlling worker threads. It must be called with
367 * finish_mutex lock held, but it will unlock it itself before exiting;
368 * this is necessary to be completely deadlock-free. */
369 /* The finish_cond can be signalled for it to stop; in that case,
370 * the caller should set finish_thread = -1. */
371 /* After it is started, it will update mctx->t to point at some tree
372 * used for the actual search (matters only for TM_ROOT), on return
373 * it will set mctx->games to the number of performed simulations. */
374 static void *
375 spawn_thread_manager(void *ctx_)
377 /* In thread_manager, we use only some of the ctx fields. */
378 struct spawn_ctx *mctx = ctx_;
379 struct uct *u = mctx->u;
380 struct tree *t = mctx->t;
381 bool shared_tree = u->parallel_tree;
382 fast_srandom(mctx->seed);
384 int played_games = 0;
385 pthread_t threads[u->threads];
386 int joined = 0;
388 uct_halt = 0;
390 /* Garbage collect the tree by preference when pondering. */
391 if (u->pondering && t->nodes && t->nodes_size > t->max_tree_size/2) {
392 unsigned long temp_size = (MIN_FREE_MEM_PERCENT * t->max_tree_size) / 100;
393 t->root = tree_garbage_collect(t, temp_size, t->root);
396 /* Spawn threads... */
397 for (int ti = 0; ti < u->threads; ti++) {
398 struct spawn_ctx *ctx = malloc(sizeof(*ctx));
399 ctx->u = u; ctx->b = mctx->b; ctx->color = mctx->color;
400 mctx->t = ctx->t = shared_tree ? t : tree_copy(t);
401 ctx->tid = ti; ctx->seed = fast_random(65536) + ti;
402 pthread_create(&threads[ti], NULL, spawn_worker, ctx);
403 if (UDEBUGL(3))
404 fprintf(stderr, "Spawned worker %d\n", ti);
407 /* ...and collect them back: */
408 while (joined < u->threads) {
409 /* Wait for some thread to finish... */
410 pthread_cond_wait(&finish_cond, &finish_mutex);
411 if (finish_thread < 0) {
412 /* Stop-by-caller. Tell the workers to wrap up. */
413 uct_halt = 1;
414 continue;
416 /* ...and gather its remnants. */
417 struct spawn_ctx *ctx;
418 pthread_join(threads[finish_thread], (void **) &ctx);
419 played_games += ctx->games;
420 joined++;
421 if (!shared_tree) {
422 if (ctx->t == mctx->t) mctx->t = t;
423 tree_merge(t, ctx->t);
424 tree_done(ctx->t);
426 free(ctx);
427 if (UDEBUGL(3))
428 fprintf(stderr, "Joined worker %d\n", finish_thread);
429 pthread_mutex_unlock(&finish_serializer);
432 pthread_mutex_unlock(&finish_mutex);
434 if (!shared_tree)
435 tree_normalize(mctx->t, u->threads);
437 mctx->games = played_games;
438 return mctx;
441 static struct spawn_ctx *
442 uct_search_start(struct uct *u, struct board *b, enum stone color, struct tree *t)
444 assert(u->threads > 0);
445 assert(!thread_manager_running);
447 struct spawn_ctx ctx = { .u = u, .b = b, .color = color, .t = t, .seed = fast_random(65536) };
448 static struct spawn_ctx mctx; mctx = ctx;
449 pthread_mutex_lock(&finish_mutex);
450 pthread_create(&thread_manager, NULL, spawn_thread_manager, &mctx);
451 thread_manager_running = true;
452 return &mctx;
455 static struct spawn_ctx *
456 uct_search_stop(void)
458 assert(thread_manager_running);
460 /* Signal thread manager to stop the workers. */
461 pthread_mutex_lock(&finish_mutex);
462 finish_thread = -1;
463 pthread_cond_signal(&finish_cond);
464 pthread_mutex_unlock(&finish_mutex);
466 /* Collect the thread manager. */
467 struct spawn_ctx *pctx;
468 thread_manager_running = false;
469 pthread_join(thread_manager, (void **) &pctx);
470 return pctx;
474 /* Determine whether we should terminate the search early. */
475 static bool
476 uct_search_stop_early(struct uct *u, struct tree *t, struct board *b,
477 struct time_info *ti, struct time_stop *stop,
478 struct tree_node *best, struct tree_node *best2,
479 int base_playouts, int i)
481 /* Early break in won situation. */
482 if (best->u.playouts >= 2000 && tree_node_get_value(t, 1, best->u.value) >= u->loss_threshold)
483 return true;
484 /* Earlier break in super-won situation. */
485 if (best->u.playouts >= 500 && tree_node_get_value(t, 1, best->u.value) >= 0.95)
486 return true;
488 /* Break early if we estimate the second-best move cannot
489 * catch up in assigned time anymore. We use all our time
490 * if we are in byoyomi with single stone remaining in our
491 * period, however - it's better to pre-ponder. */
492 bool time_indulgent = (!ti->len.t.main_time && ti->len.t.byoyomi_stones == 1);
493 if (best2 && ti->dim == TD_WALLTIME && !time_indulgent) {
494 double elapsed = time_now() - ti->len.t.timer_start;
495 double remaining = stop->worst.time - elapsed;
496 double pps = ((double)i - base_playouts) / elapsed;
497 double estplayouts = remaining * pps + PLAYOUT_DELTA_SAFEMARGIN;
498 if (best->u.playouts > best2->u.playouts + estplayouts) {
499 if (UDEBUGL(2))
500 fprintf(stderr, "Early stop, result cannot change: "
501 "best %d, best2 %d, estimated %f simulations to go\n",
502 best->u.playouts, best2->u.playouts, estplayouts);
503 return true;
507 return false;
510 /* Determine whether we should terminate the search later. */
511 static bool
512 uct_search_keep_looking(struct uct *u, struct tree *t, struct board *b,
513 struct tree_node *best, struct tree_node *best2,
514 struct tree_node *bestr, struct tree_node *winner, int i)
516 if (!best) {
517 if (UDEBUGL(2))
518 fprintf(stderr, "Did not find best move, still trying...\n");
519 return true;
522 if (u->best2_ratio > 0) {
523 /* Check best/best2 simulations ratio. If the
524 * two best moves give very similar results,
525 * keep simulating. */
526 if (best2 && best2->u.playouts
527 && (double)best->u.playouts / best2->u.playouts < u->best2_ratio) {
528 if (UDEBUGL(2))
529 fprintf(stderr, "Best2 ratio %f < threshold %f\n",
530 (double)best->u.playouts / best2->u.playouts,
531 u->best2_ratio);
532 return true;
536 if (u->bestr_ratio > 0) {
537 /* Check best, best_best value difference. If the best move
538 * and its best child do not give similar enough results,
539 * keep simulating. */
540 if (bestr && bestr->u.playouts
541 && fabs((double)best->u.value - bestr->u.value) > u->bestr_ratio) {
542 if (UDEBUGL(2))
543 fprintf(stderr, "Bestr delta %f > threshold %f\n",
544 fabs((double)best->u.value - bestr->u.value),
545 u->bestr_ratio);
546 return true;
550 if (winner && winner != best) {
551 /* Keep simulating if best explored
552 * does not have also highest value. */
553 if (UDEBUGL(2))
554 fprintf(stderr, "[%d] best %3s [%d] %f != winner %3s [%d] %f\n", i,
555 coord2sstr(best->coord, t->board),
556 best->u.playouts, tree_node_get_value(t, 1, best->u.value),
557 coord2sstr(winner->coord, t->board),
558 winner->u.playouts, tree_node_get_value(t, 1, winner->u.value));
559 return true;
562 /* No reason to keep simulating, bye. */
563 return false;
566 /* Run time-limited MCTS search on foreground. */
567 static int
568 uct_search(struct uct *u, struct board *b, struct time_info *ti, enum stone color, struct tree *t)
570 int base_playouts = u->t->root->u.playouts;
571 if (UDEBUGL(2) && base_playouts > 0)
572 fprintf(stderr, "<pre-simulated %d games skipped>\n", base_playouts);
574 /* Set up time conditions. */
575 if (ti->period == TT_NULL) *ti = default_ti;
576 struct time_stop stop;
577 time_stop_conditions(ti, b, u->fuseki_end, u->yose_start, &stop);
579 /* Number of last dynkomi adjustment. */
580 int last_dynkomi = t->root->u.playouts;
581 /* Number of last game with progress print. */
582 int last_print = t->root->u.playouts;
583 /* Number of simulations to wait before next print. */
584 int print_interval = TREE_SIMPROGRESS_INTERVAL * (u->thread_model == TM_ROOT ? 1 : u->threads);
585 /* Printed notification about full memory? */
586 bool print_fullmem = false;
588 struct spawn_ctx *ctx = uct_search_start(u, b, color, t);
590 /* The search tree is ctx->t. This is normally == t, but in case of
591 * TM_ROOT, it is one of the trees belonging to the independent
592 * workers. It is important to reference ctx->t directly since the
593 * thread manager will swap the tree pointer asynchronously. */
594 /* XXX: This means TM_ROOT support is suboptimal since single stalled
595 * thread can stall the others in case of limiting the search by game
596 * count. However, TM_ROOT just does not deserve any more extra code
597 * right now. */
599 struct tree_node *best = NULL;
600 struct tree_node *best2 = NULL; // Second-best move.
601 struct tree_node *bestr = NULL; // best's best child.
602 struct tree_node *winner = NULL;
604 double busywait_interval = TREE_BUSYWAIT_INTERVAL;
606 /* Now, just periodically poll the search tree. */
607 while (1) {
608 time_sleep(busywait_interval);
609 /* busywait_interval should never be less than desired time, or the
610 * time control is broken. But if it happens to be less, we still search
611 * at least 100ms otherwise the move is completely random. */
613 int i = ctx->t->root->u.playouts;
615 /* Adjust dynkomi? */
616 if (ctx->t->use_extra_komi && u->dynkomi->permove
617 && u->dynkomi_interval
618 && i > last_dynkomi + u->dynkomi_interval) {
619 float old_dynkomi = ctx->t->extra_komi;
620 ctx->t->extra_komi = u->dynkomi->permove(u->dynkomi, b, ctx->t);
621 if (UDEBUGL(3) && old_dynkomi != ctx->t->extra_komi)
622 fprintf(stderr, "dynkomi adjusted (%f -> %f)\n", old_dynkomi, ctx->t->extra_komi);
625 /* Print progress? */
626 if (i - last_print > print_interval) {
627 last_print += print_interval; // keep the numbers tidy
628 uct_progress_status(u, ctx->t, color, last_print);
630 if (!print_fullmem && ctx->t->nodes_size > u->max_tree_size) {
631 if (UDEBUGL(2))
632 fprintf(stderr, "memory limit hit (%lu > %lu)\n", ctx->t->nodes_size, u->max_tree_size);
633 print_fullmem = true;
636 best = u->policy->choose(u->policy, ctx->t->root, b, color, resign);
637 if (best) best2 = u->policy->choose(u->policy, ctx->t->root, b, color, best->coord);
639 /* Possibly stop search early if it's no use to try on. */
640 if (best && uct_search_stop_early(u, ctx->t, b, ti, &stop, best, best2, base_playouts, i))
641 break;
643 /* Check against time settings. */
644 bool desired_done = false;
645 if (ti->dim == TD_WALLTIME) {
646 double elapsed = time_now() - ti->len.t.timer_start;
647 if (elapsed > stop.worst.time) break;
648 desired_done = elapsed > stop.desired.time;
650 } else { assert(ti->dim == TD_GAMES);
651 if (i > stop.worst.playouts) break;
652 desired_done = i > stop.desired.playouts;
655 /* We want to stop simulating, but are willing to keep trying
656 * if we aren't completely sure about the winner yet. */
657 if (desired_done) {
658 if (u->policy->winner && u->policy->evaluate) {
659 struct uct_descent descent = { .node = ctx->t->root };
660 u->policy->winner(u->policy, ctx->t, &descent);
661 winner = descent.node;
663 if (best)
664 bestr = u->policy->choose(u->policy, best, b, stone_other(color), resign);
665 if (!uct_search_keep_looking(u, ctx->t, b, best, best2, bestr, winner, i))
666 break;
669 /* TODO: Early break if best->variance goes under threshold and we already
670 * have enough playouts (possibly thanks to book or to pondering)? */
673 ctx = uct_search_stop();
675 if (UDEBUGL(2))
676 tree_dump(t, u->dumpthres);
677 if (UDEBUGL(0))
678 uct_progress_status(u, t, color, ctx->games);
680 return ctx->games;
684 /* Start pondering background with @color to play. */
685 static void
686 uct_pondering_start(struct uct *u, struct board *b0, struct tree *t, enum stone color)
688 if (UDEBUGL(1))
689 fprintf(stderr, "Starting to ponder with color %s\n", stone2str(stone_other(color)));
690 u->pondering = true;
692 /* We need a local board copy to ponder upon. */
693 struct board *b = malloc(sizeof(*b)); board_copy(b, b0);
695 /* *b0 did not have the genmove'd move played yet. */
696 struct move m = { t->root->coord, t->root_color };
697 int res = board_play(b, &m);
698 assert(res >= 0);
699 setup_dynkomi(u, b, stone_other(m.color));
701 /* Start MCTS manager thread "headless". */
702 uct_search_start(u, b, color, t);
705 /* uct_search_stop() frontend for the pondering (non-genmove) mode. */
706 static void
707 uct_pondering_stop(struct uct *u)
709 u->pondering = false;
710 if (!thread_manager_running)
711 return;
713 /* Stop the thread manager. */
714 struct spawn_ctx *ctx = uct_search_stop();
715 if (UDEBUGL(1)) {
716 fprintf(stderr, "(pondering) ");
717 uct_progress_status(u, ctx->t, ctx->color, ctx->games);
719 free(ctx->b);
723 static coord_t *
724 uct_genmove(struct engine *e, struct board *b, struct time_info *ti, enum stone color, bool pass_all_alive)
726 double start_time = time_now();
727 struct uct *u = e->data;
729 if (b->superko_violation) {
730 fprintf(stderr, "!!! WARNING: SUPERKO VIOLATION OCCURED BEFORE THIS MOVE\n");
731 fprintf(stderr, "Maybe you play with situational instead of positional superko?\n");
732 fprintf(stderr, "I'm going to ignore the violation, but note that I may miss\n");
733 fprintf(stderr, "some moves valid under this ruleset because of this.\n");
734 b->superko_violation = false;
737 /* Seed the tree. */
738 uct_pondering_stop(u);
739 prepare_move(e, b, color);
740 assert(u->t);
741 u->my_color = color;
743 /* How to decide whether to use dynkomi in this game? Since we use
744 * pondering, it's not simple "who-to-play" matter. Decide based on
745 * the last genmove issued. */
746 u->t->use_extra_komi = !!(u->dynkomi_mask & color);
747 setup_dynkomi(u, b, color);
749 /* Make pessimistic assumption about komi for Japanese rules to
750 * avoid losing by 0.5 when winning by 0.5 with Chinese rules.
751 * The rules usually give the same winner if the integer part of komi
752 * is odd so we adjust the komi only if it is even (for a board of
753 * odd size). We are not trying to get an exact evaluation for rare
754 * cases of seki. For details see http://home.snafu.de/jasiek/parity.html
755 * TODO: Support the kgs-rules command once available. */
756 if (u->territory_scoring && (((int)floor(b->komi) + b->size) & 1)) {
757 b->komi += (color == S_BLACK ? 1.0 : -1.0);
758 if (UDEBUGL(0))
759 fprintf(stderr, "Setting komi to %.1f assuming Japanese rules\n",
760 b->komi);
763 int base_playouts = u->t->root->u.playouts;
764 /* Perform the Monte Carlo Tree Search! */
765 int played_games = uct_search(u, b, ti, color, u->t);
767 /* Choose the best move from the tree. */
768 struct tree_node *best = u->policy->choose(u->policy, u->t->root, b, color, resign);
769 if (!best) {
770 reset_state(u);
771 return coord_copy(pass);
773 if (UDEBUGL(1))
774 fprintf(stderr, "*** WINNER is %s (%d,%d) with score %1.4f (%d/%d:%d/%d games)\n",
775 coord2sstr(best->coord, b), coord_x(best->coord, b), coord_y(best->coord, b),
776 tree_node_get_value(u->t, 1, best->u.value), best->u.playouts,
777 u->t->root->u.playouts, u->t->root->u.playouts - base_playouts, played_games);
779 /* Do not resign if we're so short of time that evaluation of best move is completely
780 * unreliable, we might be winning actually. In this case best is almost random but
781 * still better than resign. */
782 if (tree_node_get_value(u->t, 1, best->u.value) < u->resign_ratio && !is_pass(best->coord)
783 && best->u.playouts > GJ_MINGAMES) {
784 reset_state(u);
785 return coord_copy(resign);
788 /* If the opponent just passed and we win counting, always
789 * pass as well. */
790 if (b->moves > 1 && is_pass(b->last_move.coord)) {
791 /* Make sure enough playouts are simulated. */
792 while (u->ownermap.playouts < GJ_MINGAMES)
793 uct_playout(u, b, color, u->t);
794 if (uct_pass_is_safe(u, b, color, u->pass_all_alive || pass_all_alive)) {
795 if (UDEBUGL(0))
796 fprintf(stderr, "<Will rather pass, looks safe enough.>\n");
797 best->coord = pass;
801 /* If we are a slave in the distributed engine, we'll soon get
802 * a "play" command later telling us which move was chosen,
803 * and pondering now will not gain much. */
804 if (!u->slave) {
805 tree_promote_node(u->t, &best);
807 /* After a pass, pondering is harmful for two reasons:
808 * (i) We might keep pondering even when the game is over.
809 * Of course this is the case for opponent resign as well.
810 * (ii) More importantly, the ownermap will get skewed since
811 * the UCT will start cutting off any playouts. */
812 if (u->pondering_opt && !is_pass(best->coord)) {
813 uct_pondering_start(u, b, u->t, stone_other(color));
816 if (UDEBUGL(2)) {
817 double time = time_now() - start_time + 0.000001; /* avoid divide by zero */
818 fprintf(stderr, "genmove in %0.2fs (%d games/s, %d games/s/thread)\n",
819 time, (int)(played_games/time), (int)(played_games/time/u->threads));
821 return coord_copy(best->coord);
825 static char *
826 uct_genmoves(struct engine *e, struct board *b, struct time_info *ti, enum stone color, bool pass_all_alive)
828 struct uct *u = e->data;
829 assert(u->slave);
831 coord_t *c = uct_genmove(e, b, ti, color, pass_all_alive);
833 /* Return a buffer with one line "total_playouts threads" then a list of lines
834 * "coord playouts value". Keep this code in sync with select_best_move(). */
835 static char reply[10240];
836 char *r = reply;
837 char *end = reply + sizeof(reply);
838 struct tree_node *root = u->t->root;
839 r += snprintf(r, end - r, "%d %d", root->u.playouts, u->threads);
840 int min_playouts = root->u.playouts / 100;
842 // Give a large weight to pass or resign, but still allow other moves.
843 if (is_pass(*c) || is_resign(*c))
844 r += snprintf(r, end - r, "\n%s %d %.1f", coord2sstr(*c, b), root->u.playouts,
845 (float)is_pass(*c));
846 coord_done(c);
848 for (struct tree_node *ni = root->children; ni; ni = ni->sibling) {
849 if (ni->u.playouts <= min_playouts
850 || ni->hints & TREE_HINT_INVALID
851 || is_pass(ni->coord))
852 continue;
853 char *coord = coord2sstr(ni->coord, b);
854 // We return the values as stored in the tree, so from black's view.
855 r += snprintf(r, end - r, "\n%s %d %.7f", coord, ni->u.playouts, ni->u.value);
857 return reply;
861 bool
862 uct_genbook(struct engine *e, struct board *b, struct time_info *ti, enum stone color)
864 struct uct *u = e->data;
865 if (!u->t) prepare_move(e, b, color);
866 assert(u->t);
868 if (ti->dim == TD_GAMES) {
869 /* Don't count in games that already went into the book. */
870 ti->len.games += u->t->root->u.playouts;
872 uct_search(u, b, ti, color, u->t);
874 assert(ti->dim == TD_GAMES);
875 tree_save(u->t, b, ti->len.games / 100);
877 return true;
880 void
881 uct_dumpbook(struct engine *e, struct board *b, enum stone color)
883 struct uct *u = e->data;
884 struct tree *t = tree_init(b, color, u->fast_alloc ? u->max_tree_size : 0, u->local_tree_aging);
885 tree_load(t, b);
886 tree_dump(t, 0);
887 tree_done(t);
891 struct uct *
892 uct_state_init(char *arg, struct board *b)
894 struct uct *u = calloc(1, sizeof(struct uct));
895 bool using_elo = false;
897 u->debug_level = debug_level;
898 u->gamelen = MC_GAMELEN;
899 u->mercymin = 0;
900 u->expand_p = 2;
901 u->dumpthres = 1000;
902 u->playout_amaf = true;
903 u->playout_amaf_nakade = false;
904 u->amaf_prior = false;
905 u->max_tree_size = 3072ULL * 1048576;
907 u->dynkomi_mask = S_BLACK;
909 u->threads = 1;
910 u->thread_model = TM_TREEVL;
911 u->parallel_tree = true;
912 u->virtual_loss = true;
914 u->fuseki_end = 20; // max time at 361*20% = 72 moves (our 36th move, still 99 to play)
915 u->yose_start = 40; // (100-40-25)*361/100/2 = 63 moves still to play by us then
916 u->bestr_ratio = 0.02;
917 // 2.5 is clearly too much, but seems to compensate well for overly stern time allocations.
918 // TODO: Further tuning and experiments with better time allocation schemes.
919 u->best2_ratio = 2.5;
921 u->val_scale = 0.04; u->val_points = 40;
923 u->tenuki_d = 4;
924 u->local_tree_aging = 2;
926 if (arg) {
927 char *optspec, *next = arg;
928 while (*next) {
929 optspec = next;
930 next += strcspn(next, ",");
931 if (*next) { *next++ = 0; } else { *next = 0; }
933 char *optname = optspec;
934 char *optval = strchr(optspec, '=');
935 if (optval) *optval++ = 0;
937 if (!strcasecmp(optname, "debug")) {
938 if (optval)
939 u->debug_level = atoi(optval);
940 else
941 u->debug_level++;
942 } else if (!strcasecmp(optname, "mercy") && optval) {
943 /* Minimal difference of black/white captures
944 * to stop playout - "Mercy Rule". Speeds up
945 * hopeless playouts at the expense of some
946 * accuracy. */
947 u->mercymin = atoi(optval);
948 } else if (!strcasecmp(optname, "gamelen") && optval) {
949 u->gamelen = atoi(optval);
950 } else if (!strcasecmp(optname, "expand_p") && optval) {
951 u->expand_p = atoi(optval);
952 } else if (!strcasecmp(optname, "dumpthres") && optval) {
953 u->dumpthres = atoi(optval);
954 } else if (!strcasecmp(optname, "best2_ratio") && optval) {
955 /* If set, prolong simulating while
956 * first_best/second_best playouts ratio
957 * is less than best2_ratio. */
958 u->best2_ratio = atof(optval);
959 } else if (!strcasecmp(optname, "bestr_ratio") && optval) {
960 /* If set, prolong simulating while
961 * best,best_best_child values delta
962 * is more than bestr_ratio. */
963 u->bestr_ratio = atof(optval);
964 } else if (!strcasecmp(optname, "playout_amaf")) {
965 /* Whether to include random playout moves in
966 * AMAF as well. (Otherwise, only tree moves
967 * are included in AMAF. Of course makes sense
968 * only in connection with an AMAF policy.) */
969 /* with-without: 55.5% (+-4.1) */
970 if (optval && *optval == '0')
971 u->playout_amaf = false;
972 else
973 u->playout_amaf = true;
974 } else if (!strcasecmp(optname, "playout_amaf_nakade")) {
975 /* Whether to include nakade moves from playouts
976 * in the AMAF statistics; this tends to nullify
977 * the playout_amaf effect by adding too much
978 * noise. */
979 if (optval && *optval == '0')
980 u->playout_amaf_nakade = false;
981 else
982 u->playout_amaf_nakade = true;
983 } else if (!strcasecmp(optname, "playout_amaf_cutoff") && optval) {
984 /* Keep only first N% of playout stage AMAF
985 * information. */
986 u->playout_amaf_cutoff = atoi(optval);
987 } else if ((!strcasecmp(optname, "policy") || !strcasecmp(optname, "random_policy")) && optval) {
988 char *policyarg = strchr(optval, ':');
989 struct uct_policy **p = !strcasecmp(optname, "policy") ? &u->policy : &u->random_policy;
990 if (policyarg)
991 *policyarg++ = 0;
992 if (!strcasecmp(optval, "ucb1")) {
993 *p = policy_ucb1_init(u, policyarg);
994 } else if (!strcasecmp(optval, "ucb1amaf")) {
995 *p = policy_ucb1amaf_init(u, policyarg);
996 } else {
997 fprintf(stderr, "UCT: Invalid tree policy %s\n", optval);
998 exit(1);
1000 } else if (!strcasecmp(optname, "playout") && optval) {
1001 char *playoutarg = strchr(optval, ':');
1002 if (playoutarg)
1003 *playoutarg++ = 0;
1004 if (!strcasecmp(optval, "moggy")) {
1005 u->playout = playout_moggy_init(playoutarg, b);
1006 } else if (!strcasecmp(optval, "light")) {
1007 u->playout = playout_light_init(playoutarg, b);
1008 } else if (!strcasecmp(optval, "elo")) {
1009 u->playout = playout_elo_init(playoutarg, b);
1010 using_elo = true;
1011 } else {
1012 fprintf(stderr, "UCT: Invalid playout policy %s\n", optval);
1013 exit(1);
1015 } else if (!strcasecmp(optname, "prior") && optval) {
1016 u->prior = uct_prior_init(optval, b);
1017 } else if (!strcasecmp(optname, "amaf_prior") && optval) {
1018 u->amaf_prior = atoi(optval);
1019 } else if (!strcasecmp(optname, "threads") && optval) {
1020 /* By default, Pachi will run with only single
1021 * tree search thread! */
1022 u->threads = atoi(optval);
1023 } else if (!strcasecmp(optname, "thread_model") && optval) {
1024 if (!strcasecmp(optval, "root")) {
1025 /* Root parallelization - each thread
1026 * does independent search, trees are
1027 * merged at the end. */
1028 u->thread_model = TM_ROOT;
1029 u->parallel_tree = false;
1030 u->virtual_loss = false;
1031 } else if (!strcasecmp(optval, "tree")) {
1032 /* Tree parallelization - all threads
1033 * grind on the same tree. */
1034 u->thread_model = TM_TREE;
1035 u->parallel_tree = true;
1036 u->virtual_loss = false;
1037 } else if (!strcasecmp(optval, "treevl")) {
1038 /* Tree parallelization, but also
1039 * with virtual losses - this discou-
1040 * rages most threads choosing the
1041 * same tree branches to read. */
1042 u->thread_model = TM_TREEVL;
1043 u->parallel_tree = true;
1044 u->virtual_loss = true;
1045 } else {
1046 fprintf(stderr, "UCT: Invalid thread model %s\n", optval);
1047 exit(1);
1049 } else if (!strcasecmp(optname, "pondering")) {
1050 /* Keep searching even during opponent's turn. */
1051 u->pondering_opt = !optval || atoi(optval);
1052 } else if (!strcasecmp(optname, "fuseki_end") && optval) {
1053 /* At the very beginning it's not worth thinking
1054 * too long because the playout evaluations are
1055 * very noisy. So gradually increase the thinking
1056 * time up to maximum when fuseki_end percent
1057 * of the board has been played.
1058 * This only applies if we are not in byoyomi. */
1059 u->fuseki_end = atoi(optval);
1060 } else if (!strcasecmp(optname, "yose_start") && optval) {
1061 /* When yose_start percent of the board has been
1062 * played, or if we are in byoyomi, stop spending
1063 * more time and spread the remaining time
1064 * uniformly.
1065 * Between fuseki_end and yose_start, we spend
1066 * a constant proportion of the remaining time
1067 * on each move. (yose_start should actually
1068 * be much earlier than when real yose start,
1069 * but "yose" is a good short name to convey
1070 * the idea.) */
1071 u->yose_start = atoi(optval);
1072 } else if (!strcasecmp(optname, "force_seed") && optval) {
1073 u->force_seed = atoi(optval);
1074 } else if (!strcasecmp(optname, "no_book")) {
1075 u->no_book = true;
1076 } else if (!strcasecmp(optname, "dynkomi") && optval) {
1077 /* Dynamic komi approach; there are multiple
1078 * ways to adjust komi dynamically throughout
1079 * play. We currently support two: */
1080 char *dynkomiarg = strchr(optval, ':');
1081 if (dynkomiarg)
1082 *dynkomiarg++ = 0;
1083 if (!strcasecmp(optval, "none")) {
1084 u->dynkomi = uct_dynkomi_init_none(u, dynkomiarg, b);
1085 } else if (!strcasecmp(optval, "linear")) {
1086 u->dynkomi = uct_dynkomi_init_linear(u, dynkomiarg, b);
1087 } else if (!strcasecmp(optval, "adaptive")) {
1088 u->dynkomi = uct_dynkomi_init_adaptive(u, dynkomiarg, b);
1089 } else {
1090 fprintf(stderr, "UCT: Invalid dynkomi mode %s\n", optval);
1091 exit(1);
1093 } else if (!strcasecmp(optname, "dynkomi_mask") && optval) {
1094 /* Bitmask of colors the player must be
1095 * for dynkomi be applied; you may want
1096 * to use dynkomi_mask=3 to allow dynkomi
1097 * even in games where Pachi is white. */
1098 u->dynkomi_mask = atoi(optval);
1099 } else if (!strcasecmp(optname, "dynkomi_interval") && optval) {
1100 /* If non-zero, re-adjust dynamic komi
1101 * throughout a single genmove reading,
1102 * roughly every N simulations. */
1103 u->dynkomi_interval = atoi(optval);
1104 } else if (!strcasecmp(optname, "val_scale") && optval) {
1105 /* How much of the game result value should be
1106 * influenced by win size. Zero means it isn't. */
1107 u->val_scale = atof(optval);
1108 } else if (!strcasecmp(optname, "val_points") && optval) {
1109 /* Maximum size of win to be scaled into game
1110 * result value. Zero means boardsize^2. */
1111 u->val_points = atoi(optval) * 2; // result values are doubled
1112 } else if (!strcasecmp(optname, "val_extra")) {
1113 /* If false, the score coefficient will be simply
1114 * added to the value, instead of scaling the result
1115 * coefficient because of it. */
1116 u->val_extra = !optval || atoi(optval);
1117 } else if (!strcasecmp(optname, "local_tree") && optval) {
1118 /* Whether to bias exploration by local tree values
1119 * (must be supported by the used policy).
1120 * 0: Don't.
1121 * 1: Do, value = result.
1122 * Try to temper the result:
1123 * 2: Do, value = 0.5+(result-expected)/2.
1124 * 3: Do, value = 0.5+bzz((result-expected)^2).
1125 * 4: Do, value = 0.5+sqrt(result-expected)/2. */
1126 u->local_tree = atoi(optval);
1127 } else if (!strcasecmp(optname, "tenuki_d") && optval) {
1128 /* Tenuki distance at which to break the local tree. */
1129 u->tenuki_d = atoi(optval);
1130 if (u->tenuki_d > TREE_NODE_D_MAX + 1) {
1131 fprintf(stderr, "uct: tenuki_d must not be larger than TREE_NODE_D_MAX+1 %d\n", TREE_NODE_D_MAX + 1);
1132 exit(1);
1134 } else if (!strcasecmp(optname, "local_tree_aging") && optval) {
1135 /* How much to reduce local tree values between moves. */
1136 u->local_tree_aging = atof(optval);
1137 } else if (!strcasecmp(optname, "local_tree_allseq")) {
1138 /* By default, only complete sequences are stored
1139 * in the local tree. If this is on, also
1140 * subsequences starting at each move are stored. */
1141 u->local_tree_allseq = !optval || atoi(optval);
1142 } else if (!strcasecmp(optname, "local_tree_playout")) {
1143 /* Whether to adjust ELO playout probability
1144 * distributions according to matched localtree
1145 * information. */
1146 u->local_tree_playout = !optval || atoi(optval);
1147 } else if (!strcasecmp(optname, "local_tree_pseqroot")) {
1148 /* By default, when we have no sequence move
1149 * to suggest in-playout, we give up. If this
1150 * is on, we make probability distribution from
1151 * sequences first moves instead. */
1152 u->local_tree_pseqroot = !optval || atoi(optval);
1153 } else if (!strcasecmp(optname, "pass_all_alive")) {
1154 /* Whether to consider all stones alive at the game
1155 * end instead of marking dead groupd. */
1156 u->pass_all_alive = !optval || atoi(optval);
1157 } else if (!strcasecmp(optname, "territory_scoring")) {
1158 /* Use territory scoring (default is area scoring).
1159 * An explicit kgs-rules command overrides this. */
1160 u->territory_scoring = !optval || atoi(optval);
1161 } else if (!strcasecmp(optname, "random_policy_chance") && optval) {
1162 /* If specified (N), with probability 1/N, random_policy policy
1163 * descend is used instead of main policy descend; useful
1164 * if specified policy (e.g. UCB1AMAF) can make unduly biased
1165 * choices sometimes, you can fall back to e.g.
1166 * random_policy=UCB1. */
1167 u->random_policy_chance = atoi(optval);
1168 } else if (!strcasecmp(optname, "max_tree_size") && optval) {
1169 /* Maximum amount of memory [MiB] consumed by the move tree.
1170 * For fast_alloc it includes the temp tree used for pruning.
1171 * Default is 3072 (3 GiB). Note that if you use TM_ROOT,
1172 * this limits size of only one of the trees, not all of them
1173 * together. */
1174 u->max_tree_size = atol(optval) * 1048576;
1175 } else if (!strcasecmp(optname, "fast_alloc")) {
1176 u->fast_alloc = !optval || atoi(optval);
1177 } else if (!strcasecmp(optname, "slave")) {
1178 /* Act as slave for the distributed engine. */
1179 u->slave = !optval || atoi(optval);
1180 } else if (!strcasecmp(optname, "banner") && optval) {
1181 /* Additional banner string. This must come as the
1182 * last engine parameter. */
1183 if (*next) *--next = ',';
1184 u->banner = strdup(optval);
1185 break;
1186 } else {
1187 fprintf(stderr, "uct: Invalid engine argument %s or missing value\n", optname);
1188 exit(1);
1193 u->resign_ratio = 0.2; /* Resign when most games are lost. */
1194 u->loss_threshold = 0.85; /* Stop reading if after at least 5000 playouts this is best value. */
1195 if (!u->policy)
1196 u->policy = policy_ucb1amaf_init(u, NULL);
1198 if (!!u->random_policy_chance ^ !!u->random_policy) {
1199 fprintf(stderr, "uct: Only one of random_policy and random_policy_chance is set\n");
1200 exit(1);
1203 if (!u->local_tree) {
1204 /* No ltree aging. */
1205 u->local_tree_aging = 1.0f;
1207 if (!using_elo)
1208 u->local_tree_playout = false;
1210 if (u->fast_alloc && !u->parallel_tree) {
1211 fprintf(stderr, "fast_alloc not supported with root parallelization.\n");
1212 exit(1);
1214 if (u->fast_alloc)
1215 u->max_tree_size = (100ULL * u->max_tree_size) / (100 + MIN_FREE_MEM_PERCENT);
1217 if (!u->prior)
1218 u->prior = uct_prior_init(NULL, b);
1220 if (!u->playout)
1221 u->playout = playout_moggy_init(NULL, b);
1222 u->playout->debug_level = u->debug_level;
1224 u->ownermap.map = malloc(board_size2(b) * sizeof(u->ownermap.map[0]));
1226 if (!u->dynkomi)
1227 u->dynkomi = uct_dynkomi_init_linear(u, NULL, b);
1229 /* Some things remain uninitialized for now - the opening book
1230 * is not loaded and the tree not set up. */
1231 /* This will be initialized in setup_state() at the first move
1232 * received/requested. This is because right now we are not aware
1233 * about any komi or handicap setup and such. */
1235 return u;
1238 struct engine *
1239 engine_uct_init(char *arg, struct board *b)
1241 struct uct *u = uct_state_init(arg, b);
1242 struct engine *e = calloc(1, sizeof(struct engine));
1243 e->name = "UCT Engine";
1244 e->printhook = uct_printhook_ownermap;
1245 e->notify_play = uct_notify_play;
1246 e->chat = uct_chat;
1247 e->genmove = uct_genmove;
1248 e->genmoves = uct_genmoves;
1249 e->dead_group_list = uct_dead_group_list;
1250 e->done = uct_done;
1251 e->data = u;
1252 if (u->slave)
1253 e->notify = uct_notify;
1255 const char banner[] = "I'm playing UCT. When I'm losing, I will resign, "
1256 "if I think I win, I play until you pass. "
1257 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
1258 if (!u->banner) u->banner = "";
1259 e->comment = malloc(sizeof(banner) + strlen(u->banner) + 1);
1260 sprintf(e->comment, "%s %s", banner, u->banner);
1262 return e;