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