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