UCT dynkomi: Decide whether to use on last-genmove-color inst. of to-play-color
[pachi.git] / uct / uct.c
blob55c94e0c837eaf25dd908aece13c66095b0c3f0f
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
58 static void
59 setup_state(struct uct *u, struct board *b, enum stone color)
61 u->t = tree_init(b, color, u->fast_alloc ? u->max_tree_size: 0);
62 if (u->force_seed)
63 fast_srandom(u->force_seed);
64 if (UDEBUGL(0))
65 fprintf(stderr, "Fresh board with random seed %lu\n", fast_getseed());
66 //board_print(b, stderr);
67 if (!u->no_book && b->moves == 0) {
68 assert(color == S_BLACK);
69 tree_load(u->t, b);
73 static void
74 reset_state(struct uct *u)
76 assert(u->t);
77 tree_done(u->t); u->t = NULL;
80 static void
81 setup_dynkomi(struct uct *u, struct board *b, enum stone to_play)
83 if (u->dynkomi > b->moves && u->t->use_extra_komi)
84 u->t->extra_komi = uct_get_extra_komi(u, b);
85 else
86 u->t->extra_komi = 0;
89 static void
90 prepare_move(struct engine *e, struct board *b, enum stone color)
92 struct uct *u = e->data;
94 if (u->t) {
95 /* Verify that we have sane state. */
96 assert(b->es == u);
97 assert(u->t && b->moves);
98 if (color != stone_other(u->t->root_color)) {
99 fprintf(stderr, "Fatal: Non-alternating play detected %d %d\n",
100 color, u->t->root_color);
101 exit(1);
104 } else {
105 /* We need fresh state. */
106 b->es = u;
107 setup_state(u, b, color);
110 u->ownermap.playouts = 0;
111 memset(u->ownermap.map, 0, board_size2(b) * sizeof(u->ownermap.map[0]));
114 static void
115 dead_group_list(struct uct *u, struct board *b, struct move_queue *mq)
117 struct group_judgement gj;
118 gj.thres = GJ_THRES;
119 gj.gs = alloca(board_size2(b) * sizeof(gj.gs[0]));
120 board_ownermap_judge_group(b, &u->ownermap, &gj);
121 groups_of_status(b, &gj, GS_DEAD, mq);
124 bool
125 uct_pass_is_safe(struct uct *u, struct board *b, enum stone color, bool pass_all_alive)
127 if (u->ownermap.playouts < GJ_MINGAMES)
128 return false;
130 struct move_queue mq = { .moves = 0 };
131 if (!pass_all_alive)
132 dead_group_list(u, b, &mq);
133 return pass_is_safe(b, color, &mq);
137 static void
138 uct_printhook_ownermap(struct board *board, coord_t c, FILE *f)
140 struct uct *u = board->es;
141 assert(u);
142 const char chr[] = ":XO,"; // dame, black, white, unclear
143 const char chm[] = ":xo,";
144 char ch = chr[board_ownermap_judge_point(&u->ownermap, c, GJ_THRES)];
145 if (ch == ',') { // less precise estimate then?
146 ch = chm[board_ownermap_judge_point(&u->ownermap, c, 0.67)];
148 fprintf(f, "%c ", ch);
151 static char *
152 uct_notify_play(struct engine *e, struct board *b, struct move *m)
154 struct uct *u = e->data;
155 if (!u->t) {
156 /* No state, create one - this is probably game beginning
157 * and we need to load the opening book right now. */
158 prepare_move(e, b, m->color);
159 assert(u->t);
162 /* Stop pondering. */
163 /* XXX: If we are about to receive multiple 'play' commands,
164 * e.g. in a rengo, we will not ponder during the rest of them. */
165 uct_pondering_stop(u);
167 if (is_resign(m->coord)) {
168 /* Reset state. */
169 reset_state(u);
170 return NULL;
173 /* Promote node of the appropriate move to the tree root. */
174 assert(u->t->root);
175 if (!tree_promote_at(u->t, b, m->coord)) {
176 if (UDEBUGL(0))
177 fprintf(stderr, "Warning: Cannot promote move node! Several play commands in row?\n");
178 reset_state(u);
179 return NULL;
181 /* Setting up dynkomi is not necessary here, probably, but we
182 * better do it anyway for consistency reasons. */
183 setup_dynkomi(u, b, stone_other(m->color));
184 return NULL;
187 static char *
188 uct_chat(struct engine *e, struct board *b, char *cmd)
190 struct uct *u = e->data;
191 static char reply[1024];
193 cmd += strspn(cmd, " \n\t");
194 if (!strncasecmp(cmd, "winrate", 7)) {
195 if (!u->t)
196 return "no game context (yet?)";
197 enum stone color = u->t->root_color;
198 struct tree_node *n = u->t->root;
199 snprintf(reply, 1024, "In %d playouts at %d threads, %s %s can win with %.2f%% probability",
200 n->u.playouts, u->threads, stone2str(color), coord2sstr(n->coord, b),
201 tree_node_get_value(u->t, -1, n->u.value) * 100);
202 if (u->t->use_extra_komi && abs(u->t->extra_komi) >= 0.5) {
203 sprintf(reply + strlen(reply), ", while self-imposing extra komi %.1f",
204 u->t->extra_komi);
206 strcat(reply, ".");
207 return reply;
209 return NULL;
212 static void
213 uct_dead_group_list(struct engine *e, struct board *b, struct move_queue *mq)
215 struct uct *u = e->data;
217 /* This means the game is probably over, no use pondering on. */
218 uct_pondering_stop(u);
220 if (u->pass_all_alive)
221 return; // no dead groups
223 bool mock_state = false;
225 if (!u->t) {
226 /* No state, but we cannot just back out - we might
227 * have passed earlier, only assuming some stones are
228 * dead, and then re-connected, only to lose counting
229 * when all stones are assumed alive. */
230 /* Mock up some state and seed the ownermap by few
231 * simulations. */
232 prepare_move(e, b, S_BLACK); assert(u->t);
233 for (int i = 0; i < GJ_MINGAMES; i++)
234 uct_playout(u, b, S_BLACK, u->t);
235 mock_state = true;
238 dead_group_list(u, b, mq);
240 if (mock_state) {
241 /* Clean up the mock state in case we will receive
242 * a genmove; we could get a non-alternating-move
243 * error from prepare_move() in that case otherwise. */
244 reset_state(u);
248 static void
249 playout_policy_done(struct playout_policy *p)
251 if (p->done) p->done(p);
252 if (p->data) free(p->data);
253 free(p);
256 static void
257 uct_done(struct engine *e)
259 /* This is called on engine reset, especially when clear_board
260 * is received and new game should begin. */
261 struct uct *u = e->data;
262 uct_pondering_stop(u);
263 if (u->t) reset_state(u);
264 free(u->ownermap.map);
266 free(u->policy);
267 free(u->random_policy);
268 playout_policy_done(u->playout);
269 uct_prior_done(u->prior);
273 /* Pachi threading structure (if uct_playouts_parallel() is used):
275 * main thread
276 * | main(), GTP communication, ...
277 * | starts and stops the search managed by thread_manager
279 * thread_manager
280 * | spawns and collects worker threads
282 * worker0
283 * worker1
284 * ...
285 * workerK
286 * uct_playouts() loop, doing descend-playout until uct_halt
288 * Another way to look at it is by functions (lines denote thread boundaries):
290 * | uct_genmove()
291 * | uct_search() (uct_search_start() .. uct_search_stop())
292 * | -----------------------
293 * | spawn_thread_manager()
294 * | -----------------------
295 * | spawn_worker()
296 * V uct_playouts() */
298 /* Set in thread manager in case the workers should stop. */
299 volatile sig_atomic_t uct_halt = 0;
300 /* ID of the running worker thread. */
301 __thread int thread_id = -1;
302 /* ID of the thread manager. */
303 static pthread_t thread_manager;
304 static bool thread_manager_running;
306 static pthread_mutex_t finish_mutex = PTHREAD_MUTEX_INITIALIZER;
307 static pthread_cond_t finish_cond = PTHREAD_COND_INITIALIZER;
308 static volatile int finish_thread;
309 static pthread_mutex_t finish_serializer = PTHREAD_MUTEX_INITIALIZER;
311 struct spawn_ctx {
312 int tid;
313 struct uct *u;
314 struct board *b;
315 enum stone color;
316 struct tree *t;
317 unsigned long seed;
318 int games;
321 static void *
322 spawn_worker(void *ctx_)
324 struct spawn_ctx *ctx = ctx_;
325 /* Setup */
326 fast_srandom(ctx->seed);
327 thread_id = ctx->tid;
328 /* Run */
329 ctx->games = uct_playouts(ctx->u, ctx->b, ctx->color, ctx->t);
330 /* Finish */
331 pthread_mutex_lock(&finish_serializer);
332 pthread_mutex_lock(&finish_mutex);
333 finish_thread = ctx->tid;
334 pthread_cond_signal(&finish_cond);
335 pthread_mutex_unlock(&finish_mutex);
336 return ctx;
339 /* Thread manager, controlling worker threads. It must be called with
340 * finish_mutex lock held, but it will unlock it itself before exiting;
341 * this is necessary to be completely deadlock-free. */
342 /* The finish_cond can be signalled for it to stop; in that case,
343 * the caller should set finish_thread = -1. */
344 /* After it is started, it will update mctx->t to point at some tree
345 * used for the actual search (matters only for TM_ROOT), on return
346 * it will set mctx->games to the number of performed simulations. */
347 static void *
348 spawn_thread_manager(void *ctx_)
350 /* In thread_manager, we use only some of the ctx fields. */
351 struct spawn_ctx *mctx = ctx_;
352 struct uct *u = mctx->u;
353 struct tree *t = mctx->t;
354 bool shared_tree = u->parallel_tree;
355 fast_srandom(mctx->seed);
357 int played_games = 0;
358 pthread_t threads[u->threads];
359 int joined = 0;
361 uct_halt = 0;
363 /* Spawn threads... */
364 for (int ti = 0; ti < u->threads; ti++) {
365 struct spawn_ctx *ctx = malloc(sizeof(*ctx));
366 ctx->u = u; ctx->b = mctx->b; ctx->color = mctx->color;
367 mctx->t = ctx->t = shared_tree ? t : tree_copy(t);
368 ctx->tid = ti; ctx->seed = fast_random(65536) + ti;
369 pthread_create(&threads[ti], NULL, spawn_worker, ctx);
370 if (UDEBUGL(2))
371 fprintf(stderr, "Spawned worker %d\n", ti);
374 /* ...and collect them back: */
375 while (joined < u->threads) {
376 /* Wait for some thread to finish... */
377 pthread_cond_wait(&finish_cond, &finish_mutex);
378 if (finish_thread < 0) {
379 /* Stop-by-caller. Tell the workers to wrap up. */
380 uct_halt = 1;
381 continue;
383 /* ...and gather its remnants. */
384 struct spawn_ctx *ctx;
385 pthread_join(threads[finish_thread], (void **) &ctx);
386 played_games += ctx->games;
387 joined++;
388 if (!shared_tree) {
389 if (ctx->t == mctx->t) mctx->t = t;
390 tree_merge(t, ctx->t);
391 tree_done(ctx->t);
393 free(ctx);
394 if (UDEBUGL(2))
395 fprintf(stderr, "Joined worker %d\n", finish_thread);
396 pthread_mutex_unlock(&finish_serializer);
399 pthread_mutex_unlock(&finish_mutex);
401 if (!shared_tree)
402 tree_normalize(mctx->t, u->threads);
404 mctx->games = played_games;
405 return mctx;
408 static struct spawn_ctx *
409 uct_search_start(struct uct *u, struct board *b, enum stone color, struct tree *t)
411 assert(u->threads > 0);
412 assert(!thread_manager_running);
414 struct spawn_ctx ctx = { .u = u, .b = b, .color = color, .t = t, .seed = fast_random(65536) };
415 static struct spawn_ctx mctx; mctx = ctx;
416 pthread_mutex_lock(&finish_mutex);
417 pthread_create(&thread_manager, NULL, spawn_thread_manager, &mctx);
418 thread_manager_running = true;
419 return &mctx;
422 static struct spawn_ctx *
423 uct_search_stop(void)
425 assert(thread_manager_running);
427 /* Signal thread manager to stop the workers. */
428 pthread_mutex_lock(&finish_mutex);
429 finish_thread = -1;
430 pthread_cond_signal(&finish_cond);
431 pthread_mutex_unlock(&finish_mutex);
433 /* Collect the thread manager. */
434 struct spawn_ctx *pctx;
435 thread_manager_running = false;
436 pthread_join(thread_manager, (void **) &pctx);
437 return pctx;
441 /* Run time-limited MCTS search on foreground. */
442 static int
443 uct_search(struct uct *u, struct board *b, struct time_info *ti, enum stone color, struct tree *t)
445 if (UDEBUGL(2) && u->t->root->u.playouts > 0)
446 fprintf(stderr, "<pre-simulated %d games skipped>\n", u->t->root->u.playouts);
448 /* Set up time conditions. */
449 if (ti->period == TT_NULL) *ti = default_ti;
450 struct time_stop stop;
451 time_stop_conditions(ti, b, u->fuseki_end, u->yose_start, &stop);
453 /* Number of last game with progress print. */
454 int last_print = t->root->u.playouts;
455 /* Number of simulations to wait before next print. */
456 int print_interval = TREE_SIMPROGRESS_INTERVAL * (u->thread_model == TM_ROOT ? 1 : u->threads);
457 /* Printed notification about full memory? */
458 bool print_fullmem = false;
460 struct spawn_ctx *ctx = uct_search_start(u, b, color, t);
462 /* The search tree is ctx->t. This is normally == t, but in case of
463 * TM_ROOT, it is one of the trees belonging to the independent
464 * workers. It is important to reference ctx->t directly since the
465 * thread manager will swap the tree pointer asynchronously. */
466 /* XXX: This means TM_ROOT support is suboptimal since single stalled
467 * thread can stall the others in case of limiting the search by game
468 * count. However, TM_ROOT just does not deserve any more extra code
469 * right now. */
471 struct tree_node *best = NULL, *prev_best;
472 struct tree_node *winner = NULL, *prev_winner;
474 double busywait_interval = TREE_BUSYWAIT_INTERVAL;
476 /* Now, just periodically poll the search tree. */
477 while (1) {
478 time_sleep(busywait_interval);
479 /* busywait_interval should never be less than desired time, or the
480 * time control is broken. But if it happens to be less, we still search
481 * at least 100ms otherwise the move is completely random. */
483 int i = ctx->t->root->u.playouts;
485 /* Print progress? */
486 if (i - last_print > print_interval) {
487 last_print += print_interval; // keep the numbers tidy
488 uct_progress_status(u, ctx->t, color, last_print);
490 if (!print_fullmem && ctx->t->nodes_size > u->max_tree_size) {
491 if (UDEBUGL(2))
492 fprintf(stderr, "memory limit hit (%ld > %lu)\n", ctx->t->nodes_size, u->max_tree_size);
493 print_fullmem = true;
496 /* Check against time settings. */
497 bool desired_done = false;
498 if (ti->dim == TD_WALLTIME) {
499 double elapsed = time_now() - ti->len.t.timer_start;
500 if (elapsed > stop.worst.time) break;
501 desired_done = elapsed > stop.desired.time;
502 } else {
503 assert(ti->dim == TD_GAMES);
504 if (i > stop.worst.playouts) break;
505 desired_done = i > stop.desired.playouts;
508 /* Early break in won situation. */
509 prev_best = best;
510 best = u->policy->choose(u->policy, ctx->t->root, b, color);
511 if (best && ((best->u.playouts >= 2000 && tree_node_get_value(ctx->t, 1, best->u.value) >= u->loss_threshold)
512 || (best->u.playouts >= 500 && tree_node_get_value(ctx->t, 1, best->u.value) >= 0.95)))
513 break;
515 if (desired_done) {
516 if (!u->policy->winner || !u->policy->evaluate)
517 break;
518 /* Stop only if best explored has also highest value: */
519 prev_winner = winner;
520 winner = u->policy->winner(u->policy, ctx->t, ctx->t->root);
521 if (best && best == winner)
522 break;
523 if (UDEBUGL(3) && (best != prev_best || winner != prev_winner)) {
524 fprintf(stderr, "[%d] best", i);
525 if (best)
526 fprintf(stderr, " %3s [%d] %f", coord2sstr(best->coord, ctx->t->board),
527 best->u.playouts, tree_node_get_value(ctx->t, 1, best->u.value));
528 fprintf(stderr, " != winner");
529 if (winner)
530 fprintf(stderr, " %3s [%d] %f ", coord2sstr(winner->coord, ctx->t->board),
531 winner->u.playouts, tree_node_get_value(ctx->t, 1, winner->u.value));
532 fprintf(stderr, "\n");
536 /* TODO: Early break if best->variance goes under threshold and we already
537 * have enough playouts (possibly thanks to book or to pondering). */
538 /* TODO: Early break if second best has no chance to catch up. */
541 ctx = uct_search_stop();
543 if (UDEBUGL(2))
544 tree_dump(t, u->dumpthres);
545 if (UDEBUGL(0))
546 uct_progress_status(u, t, color, ctx->games);
548 return ctx->games;
552 /* Start pondering background with @color to play. */
553 static void
554 uct_pondering_start(struct uct *u, struct board *b0, struct tree *t, enum stone color)
556 if (UDEBUGL(1))
557 fprintf(stderr, "Starting to ponder with color %s\n", stone2str(stone_other(color)));
558 u->pondering = true;
560 /* We need a local board copy to ponder upon. */
561 struct board *b = malloc(sizeof(*b)); board_copy(b, b0);
563 /* *b0 did not have the genmove'd move played yet. */
564 struct move m = { t->root->coord, t->root_color };
565 int res = board_play(b, &m);
566 assert(res >= 0);
567 setup_dynkomi(u, b, stone_other(m.color));
569 /* Start MCTS manager thread "headless". */
570 uct_search_start(u, b, color, t);
573 /* uct_search_stop() frontend for the pondering (non-genmove) mode. */
574 static void
575 uct_pondering_stop(struct uct *u)
577 u->pondering = false;
578 if (!thread_manager_running)
579 return;
581 /* Stop the thread manager. */
582 struct spawn_ctx *ctx = uct_search_stop();
583 if (UDEBUGL(1)) {
584 fprintf(stderr, "(pondering) ");
585 uct_progress_status(u, ctx->t, ctx->color, ctx->games);
587 free(ctx->b);
591 static coord_t *
592 uct_genmove(struct engine *e, struct board *b, struct time_info *ti, enum stone color, bool pass_all_alive)
594 double start_time = time_now();
595 struct uct *u = e->data;
597 if (b->superko_violation) {
598 fprintf(stderr, "!!! WARNING: SUPERKO VIOLATION OCCURED BEFORE THIS MOVE\n");
599 fprintf(stderr, "Maybe you play with situational instead of positional superko?\n");
600 fprintf(stderr, "I'm going to ignore the violation, but note that I may miss\n");
601 fprintf(stderr, "some moves valid under this ruleset because of this.\n");
602 b->superko_violation = false;
605 /* Seed the tree. */
606 uct_pondering_stop(u);
607 prepare_move(e, b, color);
608 assert(u->t);
610 /* How to decide whether to use dynkomi in this game? Since we use
611 * pondering, it's not simple "who-to-play" matter. Decide based on
612 * the last genmove issued. */
613 u->t->use_extra_komi = !!(u->dynkomi_mask & color);
614 setup_dynkomi(u, b, color);
616 /* Perform the Monte Carlo Tree Search! */
617 int played_games = uct_search(u, b, ti, color, u->t);
619 /* Choose the best move from the tree. */
620 struct tree_node *best = u->policy->choose(u->policy, u->t->root, b, color);
621 if (!best) {
622 reset_state(u);
623 return coord_copy(pass);
625 if (UDEBUGL(1))
626 fprintf(stderr, "*** WINNER is %s (%d,%d) with score %1.4f (%d/%d:%d games)\n",
627 coord2sstr(best->coord, b), coord_x(best->coord, b), coord_y(best->coord, b),
628 tree_node_get_value(u->t, 1, best->u.value),
629 best->u.playouts, u->t->root->u.playouts, played_games);
631 /* Do not resign if we're so short of time that evaluation of best move is completely
632 * unreliable, we might be winning actually. In this case best is almost random but
633 * still better than resign. */
634 if (tree_node_get_value(u->t, 1, best->u.value) < u->resign_ratio && !is_pass(best->coord)
635 && best->u.playouts > GJ_MINGAMES) {
636 reset_state(u);
637 return coord_copy(resign);
640 /* If the opponent just passed and we win counting, always
641 * pass as well. */
642 if (b->moves > 1 && is_pass(b->last_move.coord)) {
643 /* Make sure enough playouts are simulated. */
644 while (u->ownermap.playouts < GJ_MINGAMES)
645 uct_playout(u, b, color, u->t);
646 if (uct_pass_is_safe(u, b, color, u->pass_all_alive || pass_all_alive)) {
647 if (UDEBUGL(0))
648 fprintf(stderr, "<Will rather pass, looks safe enough.>\n");
649 best->coord = pass;
653 tree_promote_node(u->t, &best);
654 /* After a pass, pondering is harmful for two reasons:
655 * (i) We might keep pondering even when the game is over.
656 * Of course this is the case for opponent resign as well.
657 * (ii) More importantly, the ownermap will get skewed since
658 * the UCT will start cutting off any playouts. */
659 if (u->pondering_opt && !is_pass(best->coord)) {
660 uct_pondering_start(u, b, u->t, stone_other(color));
662 if (UDEBUGL(2)) {
663 double time = time_now() - start_time + 0.000001; /* avoid divide by zero */
664 fprintf(stderr, "genmove in %0.2fs (%d games/s, %d games/s/thread)\n",
665 time, (int)(played_games/time), (int)(played_games/time/u->threads));
667 return coord_copy(best->coord);
671 bool
672 uct_genbook(struct engine *e, struct board *b, struct time_info *ti, enum stone color)
674 struct uct *u = e->data;
675 if (!u->t) prepare_move(e, b, color);
676 assert(u->t);
678 if (ti->dim == TD_GAMES) {
679 /* Don't count in games that already went into the book. */
680 ti->len.games += u->t->root->u.playouts;
682 uct_search(u, b, ti, color, u->t);
684 assert(ti->dim == TD_GAMES);
685 tree_save(u->t, b, ti->len.games / 100);
687 return true;
690 void
691 uct_dumpbook(struct engine *e, struct board *b, enum stone color)
693 struct uct *u = e->data;
694 struct tree *t = tree_init(b, color, u->fast_alloc ? u->max_tree_size: 0);
695 tree_load(t, b);
696 tree_dump(t, 0);
697 tree_done(t);
701 struct uct *
702 uct_state_init(char *arg, struct board *b)
704 struct uct *u = calloc(1, sizeof(struct uct));
706 u->debug_level = 3;
707 u->gamelen = MC_GAMELEN;
708 u->mercymin = 0;
709 u->expand_p = 2;
710 u->dumpthres = 1000;
711 u->playout_amaf = true;
712 u->playout_amaf_nakade = false;
713 u->amaf_prior = false;
714 u->max_tree_size = 3072ULL * 1048576;
716 if (board_size(b) - 2 >= 19)
717 u->dynkomi = 200;
718 u->dynkomi_mask = S_BLACK;
720 u->threads = 1;
721 u->thread_model = TM_TREEVL;
722 u->parallel_tree = true;
723 u->virtual_loss = true;
724 u->fuseki_end = 20; // max time at 361*20% = 72 moves (our 36th move, still 99 to play)
725 u->yose_start = 40; // (100-40-25)*361/100/2 = 63 moves still to play by us then
727 u->val_scale = 0.04; u->val_points = 40;
729 if (arg) {
730 char *optspec, *next = arg;
731 while (*next) {
732 optspec = next;
733 next += strcspn(next, ",");
734 if (*next) { *next++ = 0; } else { *next = 0; }
736 char *optname = optspec;
737 char *optval = strchr(optspec, '=');
738 if (optval) *optval++ = 0;
740 if (!strcasecmp(optname, "debug")) {
741 if (optval)
742 u->debug_level = atoi(optval);
743 else
744 u->debug_level++;
745 } else if (!strcasecmp(optname, "mercy") && optval) {
746 /* Minimal difference of black/white captures
747 * to stop playout - "Mercy Rule". Speeds up
748 * hopeless playouts at the expense of some
749 * accuracy. */
750 u->mercymin = atoi(optval);
751 } else if (!strcasecmp(optname, "gamelen") && optval) {
752 u->gamelen = atoi(optval);
753 } else if (!strcasecmp(optname, "expand_p") && optval) {
754 u->expand_p = atoi(optval);
755 } else if (!strcasecmp(optname, "dumpthres") && optval) {
756 u->dumpthres = atoi(optval);
757 } else if (!strcasecmp(optname, "playout_amaf")) {
758 /* Whether to include random playout moves in
759 * AMAF as well. (Otherwise, only tree moves
760 * are included in AMAF. Of course makes sense
761 * only in connection with an AMAF policy.) */
762 /* with-without: 55.5% (+-4.1) */
763 if (optval && *optval == '0')
764 u->playout_amaf = false;
765 else
766 u->playout_amaf = true;
767 } else if (!strcasecmp(optname, "playout_amaf_nakade")) {
768 /* Whether to include nakade moves from playouts
769 * in the AMAF statistics; this tends to nullify
770 * the playout_amaf effect by adding too much
771 * noise. */
772 if (optval && *optval == '0')
773 u->playout_amaf_nakade = false;
774 else
775 u->playout_amaf_nakade = true;
776 } else if (!strcasecmp(optname, "playout_amaf_cutoff") && optval) {
777 /* Keep only first N% of playout stage AMAF
778 * information. */
779 u->playout_amaf_cutoff = atoi(optval);
780 } else if ((!strcasecmp(optname, "policy") || !strcasecmp(optname, "random_policy")) && optval) {
781 char *policyarg = strchr(optval, ':');
782 struct uct_policy **p = !strcasecmp(optname, "policy") ? &u->policy : &u->random_policy;
783 if (policyarg)
784 *policyarg++ = 0;
785 if (!strcasecmp(optval, "ucb1")) {
786 *p = policy_ucb1_init(u, policyarg);
787 } else if (!strcasecmp(optval, "ucb1amaf")) {
788 *p = policy_ucb1amaf_init(u, policyarg);
789 } else {
790 fprintf(stderr, "UCT: Invalid tree policy %s\n", optval);
791 exit(1);
793 } else if (!strcasecmp(optname, "playout") && optval) {
794 char *playoutarg = strchr(optval, ':');
795 if (playoutarg)
796 *playoutarg++ = 0;
797 if (!strcasecmp(optval, "moggy")) {
798 u->playout = playout_moggy_init(playoutarg);
799 } else if (!strcasecmp(optval, "light")) {
800 u->playout = playout_light_init(playoutarg);
801 } else if (!strcasecmp(optval, "elo")) {
802 u->playout = playout_elo_init(playoutarg);
803 } else {
804 fprintf(stderr, "UCT: Invalid playout policy %s\n", optval);
805 exit(1);
807 } else if (!strcasecmp(optname, "prior") && optval) {
808 u->prior = uct_prior_init(optval, b);
809 } else if (!strcasecmp(optname, "amaf_prior") && optval) {
810 u->amaf_prior = atoi(optval);
811 } else if (!strcasecmp(optname, "threads") && optval) {
812 /* By default, Pachi will run with only single
813 * tree search thread! */
814 u->threads = atoi(optval);
815 } else if (!strcasecmp(optname, "thread_model") && optval) {
816 if (!strcasecmp(optval, "root")) {
817 /* Root parallelization - each thread
818 * does independent search, trees are
819 * merged at the end. */
820 u->thread_model = TM_ROOT;
821 u->parallel_tree = false;
822 u->virtual_loss = false;
823 } else if (!strcasecmp(optval, "tree")) {
824 /* Tree parallelization - all threads
825 * grind on the same tree. */
826 u->thread_model = TM_TREE;
827 u->parallel_tree = true;
828 u->virtual_loss = false;
829 } else if (!strcasecmp(optval, "treevl")) {
830 /* Tree parallelization, but also
831 * with virtual losses - this discou-
832 * rages most threads choosing the
833 * same tree branches to read. */
834 u->thread_model = TM_TREEVL;
835 u->parallel_tree = true;
836 u->virtual_loss = true;
837 } else {
838 fprintf(stderr, "UCT: Invalid thread model %s\n", optval);
839 exit(1);
841 } else if (!strcasecmp(optname, "pondering")) {
842 /* Keep searching even during opponent's turn. */
843 u->pondering_opt = !optval || atoi(optval);
844 } else if (!strcasecmp(optname, "fuseki_end") && optval) {
845 /* At the very beginning it's not worth thinking
846 * too long because the playout evaluations are
847 * very noisy. So gradually increase the thinking
848 * time up to maximum when fuseki_end percent
849 * of the board has been played.
850 * This only applies if we are not in byoyomi. */
851 u->fuseki_end = atoi(optval);
852 } else if (!strcasecmp(optname, "yose_start") && optval) {
853 /* When yose_start percent of the board has been
854 * played, or if we are in byoyomi, stop spending
855 * more time and spread the remaining time
856 * uniformly.
857 * Between fuseki_end and yose_start, we spend
858 * a constant proportion of the remaining time
859 * on each move. (yose_start should actually
860 * be much earlier than when real yose start,
861 * but "yose" is a good short name to convey
862 * the idea.) */
863 u->yose_start = atoi(optval);
864 } else if (!strcasecmp(optname, "force_seed") && optval) {
865 u->force_seed = atoi(optval);
866 } else if (!strcasecmp(optname, "no_book")) {
867 u->no_book = true;
868 } else if (!strcasecmp(optname, "dynkomi")) {
869 /* Dynamic komi in handicap game; linearly
870 * decreases to basic settings until move
871 * #optval. */
872 u->dynkomi = optval ? atoi(optval) : 150;
873 } else if (!strcasecmp(optname, "dynkomi_mask") && optval) {
874 /* Bitmask of colors the player must be
875 * for dynkomi be applied; you may want
876 * to use dynkomi_mask=3 to allow dynkomi
877 * even in games where Pachi is white. */
878 u->dynkomi_mask = atoi(optval);
879 } else if (!strcasecmp(optname, "val_scale") && optval) {
880 /* How much of the game result value should be
881 * influenced by win size. Zero means it isn't. */
882 u->val_scale = atof(optval);
883 } else if (!strcasecmp(optname, "val_points") && optval) {
884 /* Maximum size of win to be scaled into game
885 * result value. Zero means boardsize^2. */
886 u->val_points = atoi(optval) * 2; // result values are doubled
887 } else if (!strcasecmp(optname, "val_extra")) {
888 /* If false, the score coefficient will be simply
889 * added to the value, instead of scaling the result
890 * coefficient because of it. */
891 u->val_extra = !optval || atoi(optval);
892 } else if (!strcasecmp(optname, "root_heuristic") && optval) {
893 /* Whether to bias exploration by root node values
894 * (must be supported by the used policy).
895 * 0: Don't.
896 * 1: Do, value = result.
897 * Try to temper the result:
898 * 2: Do, value = 0.5+(result-expected)/2.
899 * 3: Do, value = 0.5+bzz((result-expected)^2). */
900 u->root_heuristic = atoi(optval);
901 } else if (!strcasecmp(optname, "pass_all_alive")) {
902 /* Whether to consider all stones alive at the game
903 * end instead of marking dead groupd. */
904 u->pass_all_alive = !optval || atoi(optval);
905 } else if (!strcasecmp(optname, "random_policy_chance") && optval) {
906 /* If specified (N), with probability 1/N, random_policy policy
907 * descend is used instead of main policy descend; useful
908 * if specified policy (e.g. UCB1AMAF) can make unduly biased
909 * choices sometimes, you can fall back to e.g.
910 * random_policy=UCB1. */
911 u->random_policy_chance = atoi(optval);
912 } else if (!strcasecmp(optname, "max_tree_size") && optval) {
913 /* Maximum amount of memory [MiB] consumed by the move tree.
914 * Default is 3072 (3 GiB). Note that if you use TM_ROOT,
915 * this limits size of only one of the trees, not all of them
916 * together. */
917 u->max_tree_size = atol(optval) * 1048576;
918 } else if (!strcasecmp(optname, "banner") && optval) {
919 /* Additional banner string. This must come as the
920 * last engine parameter. */
921 if (*next) *--next = ',';
922 u->banner = strdup(optval);
923 break;
924 } else {
925 fprintf(stderr, "uct: Invalid engine argument %s or missing value\n", optname);
926 exit(1);
931 u->resign_ratio = 0.2; /* Resign when most games are lost. */
932 u->loss_threshold = 0.85; /* Stop reading if after at least 5000 playouts this is best value. */
933 if (!u->policy)
934 u->policy = policy_ucb1amaf_init(u, NULL);
936 if (!!u->random_policy_chance ^ !!u->random_policy) {
937 fprintf(stderr, "uct: Only one of random_policy and random_policy_chance is set\n");
938 exit(1);
941 if (u->fast_alloc && !u->parallel_tree) {
942 fprintf(stderr, "fast_alloc not supported with root parallelization.\n");
943 exit(1);
946 if (!u->prior)
947 u->prior = uct_prior_init(NULL, b);
949 if (!u->playout)
950 u->playout = playout_moggy_init(NULL);
951 u->playout->debug_level = u->debug_level;
953 u->ownermap.map = malloc(board_size2(b) * sizeof(u->ownermap.map[0]));
955 /* Some things remain uninitialized for now - the opening book
956 * is not loaded and the tree not set up. */
957 /* This will be initialized in setup_state() at the first move
958 * received/requested. This is because right now we are not aware
959 * about any komi or handicap setup and such. */
961 return u;
964 struct engine *
965 engine_uct_init(char *arg, struct board *b)
967 struct uct *u = uct_state_init(arg, b);
968 struct engine *e = calloc(1, sizeof(struct engine));
969 e->name = "UCT Engine";
970 e->printhook = uct_printhook_ownermap;
971 e->notify_play = uct_notify_play;
972 e->chat = uct_chat;
973 e->genmove = uct_genmove;
974 e->dead_group_list = uct_dead_group_list;
975 e->done = uct_done;
976 e->data = u;
978 const char banner[] = "I'm playing UCT. When I'm losing, I will resign, "
979 "if I think I win, I play until you pass. "
980 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
981 if (!u->banner) u->banner = "";
982 e->comment = malloc(sizeof(banner) + strlen(u->banner) + 1);
983 sprintf(e->comment, "%s %s", banner, u->banner);
985 return e;