Support the "kgs-rules" gtp command.
[pachi/json.git] / uct / uct.c
blob7d36d2089891f0e15b872ad0b837fd7cbd1e42bd
1 #include <assert.h>
2 #include <math.h>
3 #include <pthread.h>
4 #include <signal.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <time.h>
10 #define DEBUG
12 #include "debug.h"
13 #include "board.h"
14 #include "gtp.h"
15 #include "move.h"
16 #include "mq.h"
17 #include "playout.h"
18 #include "playout/elo.h"
19 #include "playout/moggy.h"
20 #include "playout/light.h"
21 #include "random.h"
22 #include "tactics.h"
23 #include "timeinfo.h"
24 #include "distributed/distributed.h"
25 #include "uct/dynkomi.h"
26 #include "uct/internal.h"
27 #include "uct/prior.h"
28 #include "uct/tree.h"
29 #include "uct/uct.h"
30 #include "uct/walk.h"
32 struct uct_policy *policy_ucb1_init(struct uct *u, char *arg);
33 struct uct_policy *policy_ucb1amaf_init(struct uct *u, char *arg);
34 static void uct_pondering_stop(struct uct *u);
35 static void uct_pondering_start(struct uct *u, struct board *b0, struct tree *t, enum stone color);
36 static char *uct_getstats(struct uct *u, struct board *b, coord_t *c);
38 /* Default number of simulations to perform per move.
39 * Note that this is now in total over all threads! (Unless TM_ROOT.) */
40 #define MC_GAMES 80000
41 #define MC_GAMELEN MAX_GAMELEN
42 static const struct time_info default_ti = {
43 .period = TT_MOVE,
44 .dim = TD_GAMES,
45 .len = { .games = MC_GAMES },
48 /* How big proportion of ownermap counts must be of one color to consider
49 * the point sure. */
50 #define GJ_THRES 0.8
51 /* How many games to consider at minimum before judging groups. */
52 #define GJ_MINGAMES 500
54 /* How often to inspect the tree from the main thread to check for playout
55 * stop, progress reports, etc. (in seconds) */
56 #define TREE_BUSYWAIT_INTERVAL 0.1 /* 100ms */
58 /* Once per how many simulations (per thread) to show a progress report line. */
59 #define TREE_SIMPROGRESS_INTERVAL 10000
61 /* How often to send stats updates for the distributed engine (in seconds). */
62 #define STATS_SEND_INTERVAL 0.5
64 /* When terminating uct_search() early, the safety margin to add to the
65 * remaining playout number estimate when deciding whether the result can
66 * still change. */
67 #define PLAYOUT_DELTA_SAFEMARGIN 1000
70 static void
71 setup_state(struct uct *u, struct board *b, enum stone color)
73 u->t = tree_init(b, color, u->fast_alloc ? u->max_tree_size : 0, u->local_tree_aging);
74 if (u->force_seed)
75 fast_srandom(u->force_seed);
76 if (UDEBUGL(0))
77 fprintf(stderr, "Fresh board with random seed %lu\n", fast_getseed());
78 //board_print(b, stderr);
79 if (!u->no_book && b->moves == 0) {
80 assert(color == S_BLACK);
81 tree_load(u->t, b);
85 static void
86 reset_state(struct uct *u)
88 assert(u->t);
89 tree_done(u->t); u->t = NULL;
92 static void
93 setup_dynkomi(struct uct *u, struct board *b, enum stone to_play)
95 if (u->t->use_extra_komi && u->dynkomi->permove)
96 u->t->extra_komi = u->dynkomi->permove(u->dynkomi, b, u->t);
99 static void
100 prepare_move(struct engine *e, struct board *b, enum stone color)
102 struct uct *u = e->data;
104 if (u->t) {
105 /* Verify that we have sane state. */
106 assert(b->es == u);
107 assert(u->t && b->moves);
108 if (color != stone_other(u->t->root_color)) {
109 fprintf(stderr, "Fatal: Non-alternating play detected %d %d\n",
110 color, u->t->root_color);
111 exit(1);
114 } else {
115 /* We need fresh state. */
116 b->es = u;
117 setup_state(u, b, color);
120 u->ownermap.playouts = 0;
121 memset(u->ownermap.map, 0, board_size2(b) * sizeof(u->ownermap.map[0]));
124 static void
125 dead_group_list(struct uct *u, struct board *b, struct move_queue *mq)
127 struct group_judgement gj;
128 gj.thres = GJ_THRES;
129 gj.gs = alloca(board_size2(b) * sizeof(gj.gs[0]));
130 board_ownermap_judge_group(b, &u->ownermap, &gj);
131 groups_of_status(b, &gj, GS_DEAD, mq);
134 bool
135 uct_pass_is_safe(struct uct *u, struct board *b, enum stone color, bool pass_all_alive)
137 if (u->ownermap.playouts < GJ_MINGAMES)
138 return false;
140 struct move_queue mq = { .moves = 0 };
141 if (!pass_all_alive)
142 dead_group_list(u, b, &mq);
143 return pass_is_safe(b, color, &mq);
146 /* This function is called only when running as slave in the distributed version. */
147 static enum parse_code
148 uct_notify(struct engine *e, struct board *b, int id, char *cmd, char *args, char **reply)
150 struct uct *u = e->data;
152 /* Force resending the whole command history if we are out of sync
153 * but do it only once, not if already getting the history. */
154 if ((move_number(id) != b->moves || !b->size)
155 && !reply_disabled(id) && !is_reset(cmd)) {
156 if (UDEBUGL(0))
157 fprintf(stderr, "Out of sync, id %d, move %d\n", id, b->moves);
158 static char buf[128];
159 snprintf(buf, sizeof(buf), "out of sync, move %d expected", b->moves);
160 *reply = buf;
161 return P_DONE_ERROR;
163 u->gtp_id = id;
164 return reply_disabled(id) ? P_NOREPLY : P_OK;
167 static char *
168 uct_printhook_ownermap(struct board *board, coord_t c, char *s, char *end)
170 struct uct *u = board->es;
171 assert(u);
172 const char chr[] = ":XO,"; // dame, black, white, unclear
173 const char chm[] = ":xo,";
174 char ch = chr[board_ownermap_judge_point(&u->ownermap, c, GJ_THRES)];
175 if (ch == ',') { // less precise estimate then?
176 ch = chm[board_ownermap_judge_point(&u->ownermap, c, 0.67)];
178 s += snprintf(s, end - s, "%c ", ch);
179 return s;
182 static char *
183 uct_notify_play(struct engine *e, struct board *b, struct move *m)
185 struct uct *u = e->data;
186 if (!u->t) {
187 /* No state, create one - this is probably game beginning
188 * and we need to load the opening book right now. */
189 prepare_move(e, b, m->color);
190 assert(u->t);
193 /* Stop pondering, required by tree_promote_at() */
194 uct_pondering_stop(u);
196 if (is_resign(m->coord)) {
197 /* Reset state. */
198 reset_state(u);
199 return NULL;
202 /* Promote node of the appropriate move to the tree root. */
203 assert(u->t->root);
204 if (!tree_promote_at(u->t, b, m->coord)) {
205 if (UDEBUGL(0))
206 fprintf(stderr, "Warning: Cannot promote move node! Several play commands in row?\n");
207 reset_state(u);
208 return NULL;
211 /* If we are a slave in a distributed engine, start pondering once
212 * we know which move we actually played. See uct_genmove() about
213 * the check for pass. */
214 if (u->pondering_opt && u->slave && m->color == u->my_color && !is_pass(m->coord))
215 uct_pondering_start(u, b, u->t, stone_other(m->color));
217 return NULL;
220 static char *
221 uct_chat(struct engine *e, struct board *b, char *cmd)
223 struct uct *u = e->data;
224 static char reply[1024];
226 cmd += strspn(cmd, " \n\t");
227 if (!strncasecmp(cmd, "winrate", 7)) {
228 if (!u->t)
229 return "no game context (yet?)";
230 enum stone color = u->t->root_color;
231 struct tree_node *n = u->t->root;
232 snprintf(reply, 1024, "In %d playouts at %d threads, %s %s can win with %.2f%% probability",
233 n->u.playouts, u->threads, stone2str(color), coord2sstr(n->coord, b),
234 tree_node_get_value(u->t, -1, n->u.value) * 100);
235 if (u->t->use_extra_komi && abs(u->t->extra_komi) >= 0.5) {
236 sprintf(reply + strlen(reply), ", while self-imposing extra komi %.1f",
237 u->t->extra_komi);
239 strcat(reply, ".");
240 return reply;
242 return NULL;
245 static void
246 uct_dead_group_list(struct engine *e, struct board *b, struct move_queue *mq)
248 struct uct *u = e->data;
250 /* This means the game is probably over, no use pondering on. */
251 uct_pondering_stop(u);
253 if (u->pass_all_alive)
254 return; // no dead groups
256 bool mock_state = false;
258 if (!u->t) {
259 /* No state, but we cannot just back out - we might
260 * have passed earlier, only assuming some stones are
261 * dead, and then re-connected, only to lose counting
262 * when all stones are assumed alive. */
263 /* Mock up some state and seed the ownermap by few
264 * simulations. */
265 prepare_move(e, b, S_BLACK); assert(u->t);
266 for (int i = 0; i < GJ_MINGAMES; i++)
267 uct_playout(u, b, S_BLACK, u->t);
268 mock_state = true;
271 dead_group_list(u, b, mq);
273 if (mock_state) {
274 /* Clean up the mock state in case we will receive
275 * a genmove; we could get a non-alternating-move
276 * error from prepare_move() in that case otherwise. */
277 reset_state(u);
281 static void
282 playout_policy_done(struct playout_policy *p)
284 if (p->done) p->done(p);
285 if (p->data) free(p->data);
286 free(p);
289 static void
290 uct_done(struct engine *e)
292 /* This is called on engine reset, especially when clear_board
293 * is received and new game should begin. */
294 struct uct *u = e->data;
295 uct_pondering_stop(u);
296 if (u->t) reset_state(u);
297 free(u->ownermap.map);
299 free(u->policy);
300 free(u->random_policy);
301 playout_policy_done(u->playout);
302 uct_prior_done(u->prior);
306 /* Pachi threading structure (if uct_playouts_parallel() is used):
308 * main thread
309 * | main(), GTP communication, ...
310 * | starts and stops the search managed by thread_manager
312 * thread_manager
313 * | spawns and collects worker threads
315 * worker0
316 * worker1
317 * ...
318 * workerK
319 * uct_playouts() loop, doing descend-playout until uct_halt
321 * Another way to look at it is by functions (lines denote thread boundaries):
323 * | uct_genmove()
324 * | uct_search() (uct_search_start() .. uct_search_stop())
325 * | -----------------------
326 * | spawn_thread_manager()
327 * | -----------------------
328 * | spawn_worker()
329 * V uct_playouts() */
331 /* Set in thread manager in case the workers should stop. */
332 volatile sig_atomic_t uct_halt = 0;
333 /* ID of the running worker thread. */
334 __thread int thread_id = -1;
335 /* ID of the thread manager. */
336 static pthread_t thread_manager;
337 static bool thread_manager_running;
339 static pthread_mutex_t finish_mutex = PTHREAD_MUTEX_INITIALIZER;
340 static pthread_cond_t finish_cond = PTHREAD_COND_INITIALIZER;
341 static volatile int finish_thread;
342 static pthread_mutex_t finish_serializer = PTHREAD_MUTEX_INITIALIZER;
344 struct spawn_ctx {
345 int tid;
346 struct uct *u;
347 struct board *b;
348 enum stone color;
349 struct tree *t;
350 unsigned long seed;
351 int games;
354 static void *
355 spawn_worker(void *ctx_)
357 struct spawn_ctx *ctx = ctx_;
358 /* Setup */
359 fast_srandom(ctx->seed);
360 thread_id = ctx->tid;
361 /* Run */
362 ctx->games = uct_playouts(ctx->u, ctx->b, ctx->color, ctx->t);
363 /* Finish */
364 pthread_mutex_lock(&finish_serializer);
365 pthread_mutex_lock(&finish_mutex);
366 finish_thread = ctx->tid;
367 pthread_cond_signal(&finish_cond);
368 pthread_mutex_unlock(&finish_mutex);
369 return ctx;
372 /* Thread manager, controlling worker threads. It must be called with
373 * finish_mutex lock held, but it will unlock it itself before exiting;
374 * this is necessary to be completely deadlock-free. */
375 /* The finish_cond can be signalled for it to stop; in that case,
376 * the caller should set finish_thread = -1. */
377 /* After it is started, it will update mctx->t to point at some tree
378 * used for the actual search (matters only for TM_ROOT), on return
379 * it will set mctx->games to the number of performed simulations. */
380 static void *
381 spawn_thread_manager(void *ctx_)
383 /* In thread_manager, we use only some of the ctx fields. */
384 struct spawn_ctx *mctx = ctx_;
385 struct uct *u = mctx->u;
386 struct tree *t = mctx->t;
387 bool shared_tree = u->parallel_tree;
388 fast_srandom(mctx->seed);
390 int played_games = 0;
391 pthread_t threads[u->threads];
392 int joined = 0;
394 uct_halt = 0;
396 /* Garbage collect the tree by preference when pondering. */
397 if (u->pondering && t->nodes && t->nodes_size > t->max_tree_size/2) {
398 unsigned long temp_size = (MIN_FREE_MEM_PERCENT * t->max_tree_size) / 100;
399 t->root = tree_garbage_collect(t, temp_size, t->root);
402 /* Spawn threads... */
403 for (int ti = 0; ti < u->threads; ti++) {
404 struct spawn_ctx *ctx = malloc(sizeof(*ctx));
405 ctx->u = u; ctx->b = mctx->b; ctx->color = mctx->color;
406 mctx->t = ctx->t = shared_tree ? t : tree_copy(t);
407 ctx->tid = ti; ctx->seed = fast_random(65536) + ti;
408 pthread_create(&threads[ti], NULL, spawn_worker, ctx);
409 if (UDEBUGL(3))
410 fprintf(stderr, "Spawned worker %d\n", ti);
413 /* ...and collect them back: */
414 while (joined < u->threads) {
415 /* Wait for some thread to finish... */
416 pthread_cond_wait(&finish_cond, &finish_mutex);
417 if (finish_thread < 0) {
418 /* Stop-by-caller. Tell the workers to wrap up. */
419 uct_halt = 1;
420 continue;
422 /* ...and gather its remnants. */
423 struct spawn_ctx *ctx;
424 pthread_join(threads[finish_thread], (void **) &ctx);
425 played_games += ctx->games;
426 joined++;
427 if (!shared_tree) {
428 if (ctx->t == mctx->t) mctx->t = t;
429 tree_merge(t, ctx->t);
430 tree_done(ctx->t);
432 free(ctx);
433 if (UDEBUGL(3))
434 fprintf(stderr, "Joined worker %d\n", finish_thread);
435 pthread_mutex_unlock(&finish_serializer);
438 pthread_mutex_unlock(&finish_mutex);
440 if (!shared_tree)
441 tree_normalize(mctx->t, u->threads);
443 mctx->games = played_games;
444 return mctx;
447 static struct spawn_ctx *
448 uct_search_start(struct uct *u, struct board *b, enum stone color, struct tree *t)
450 assert(u->threads > 0);
451 assert(!thread_manager_running);
453 struct spawn_ctx ctx = { .u = u, .b = b, .color = color, .t = t, .seed = fast_random(65536) };
454 static struct spawn_ctx mctx; mctx = ctx;
455 pthread_mutex_lock(&finish_mutex);
456 pthread_create(&thread_manager, NULL, spawn_thread_manager, &mctx);
457 thread_manager_running = true;
458 return &mctx;
461 static struct spawn_ctx *
462 uct_search_stop(void)
464 assert(thread_manager_running);
466 /* Signal thread manager to stop the workers. */
467 pthread_mutex_lock(&finish_mutex);
468 finish_thread = -1;
469 pthread_cond_signal(&finish_cond);
470 pthread_mutex_unlock(&finish_mutex);
472 /* Collect the thread manager. */
473 struct spawn_ctx *pctx;
474 thread_manager_running = false;
475 pthread_join(thread_manager, (void **) &pctx);
476 return pctx;
480 /* Determine whether we should terminate the search early. */
481 static bool
482 uct_search_stop_early(struct uct *u, struct tree *t, struct board *b,
483 struct time_info *ti, struct time_stop *stop,
484 struct tree_node *best, struct tree_node *best2,
485 int base_playouts, int i)
487 /* Always use at least half the desired time. It is silly
488 * to lose a won game because we played a bad move in 0.1s. */
489 double elapsed = 0;
490 if (ti->dim == TD_WALLTIME) {
491 elapsed = time_now() - ti->len.t.timer_start;
492 if (elapsed < 0.5 * stop->desired.time) return false;
495 /* Early break in won situation. */
496 if (best->u.playouts >= 2000 && tree_node_get_value(t, 1, best->u.value) >= u->loss_threshold)
497 return true;
498 /* Earlier break in super-won situation. */
499 if (best->u.playouts >= 500 && tree_node_get_value(t, 1, best->u.value) >= 0.95)
500 return true;
502 /* Break early if we estimate the second-best move cannot
503 * catch up in assigned time anymore. We use all our time
504 * if we are in byoyomi with single stone remaining in our
505 * period, however - it's better to pre-ponder. */
506 bool time_indulgent = (!ti->len.t.main_time && ti->len.t.byoyomi_stones == 1);
507 if (best2 && ti->dim == TD_WALLTIME && !time_indulgent) {
508 double remaining = stop->worst.time - elapsed;
509 double pps = ((double)i - base_playouts) / elapsed;
510 double estplayouts = remaining * pps + PLAYOUT_DELTA_SAFEMARGIN;
511 if (best->u.playouts > best2->u.playouts + estplayouts) {
512 if (UDEBUGL(2))
513 fprintf(stderr, "Early stop, result cannot change: "
514 "best %d, best2 %d, estimated %f simulations to go\n",
515 best->u.playouts, best2->u.playouts, estplayouts);
516 return true;
520 return false;
523 /* Determine whether we should terminate the search later. */
524 static bool
525 uct_search_keep_looking(struct uct *u, struct tree *t, struct board *b,
526 struct time_info *ti, struct time_stop *stop,
527 struct tree_node *best, struct tree_node *best2,
528 struct tree_node *bestr, struct tree_node *winner, int i)
530 if (!best) {
531 if (UDEBUGL(2))
532 fprintf(stderr, "Did not find best move, still trying...\n");
533 return true;
536 /* Do not waste time if we are winning. Spend up to worst time if
537 * we are unsure, but only desired time if we are sure of winning. */
538 float beta = 2 * (tree_node_get_value(t, 1, best->u.value) - 0.5);
539 if (ti->dim == TD_WALLTIME && beta > 0) {
540 double good_enough = stop->desired.time * beta + stop->worst.time * (1 - beta);
541 double elapsed = time_now() - ti->len.t.timer_start;
542 if (elapsed > good_enough) return false;
545 if (u->best2_ratio > 0) {
546 /* Check best/best2 simulations ratio. If the
547 * two best moves give very similar results,
548 * keep simulating. */
549 if (best2 && best2->u.playouts
550 && (double)best->u.playouts / best2->u.playouts < u->best2_ratio) {
551 if (UDEBUGL(2))
552 fprintf(stderr, "Best2 ratio %f < threshold %f\n",
553 (double)best->u.playouts / best2->u.playouts,
554 u->best2_ratio);
555 return true;
559 if (u->bestr_ratio > 0) {
560 /* Check best, best_best value difference. If the best move
561 * and its best child do not give similar enough results,
562 * keep simulating. */
563 if (bestr && bestr->u.playouts
564 && fabs((double)best->u.value - bestr->u.value) > u->bestr_ratio) {
565 if (UDEBUGL(2))
566 fprintf(stderr, "Bestr delta %f > threshold %f\n",
567 fabs((double)best->u.value - bestr->u.value),
568 u->bestr_ratio);
569 return true;
573 if (winner && winner != best) {
574 /* Keep simulating if best explored
575 * does not have also highest value. */
576 if (UDEBUGL(2))
577 fprintf(stderr, "[%d] best %3s [%d] %f != winner %3s [%d] %f\n", i,
578 coord2sstr(best->coord, t->board),
579 best->u.playouts, tree_node_get_value(t, 1, best->u.value),
580 coord2sstr(winner->coord, t->board),
581 winner->u.playouts, tree_node_get_value(t, 1, winner->u.value));
582 return true;
585 /* No reason to keep simulating, bye. */
586 return false;
589 /* Run time-limited MCTS search on foreground. */
590 static int
591 uct_search(struct uct *u, struct board *b, struct time_info *ti, enum stone color, struct tree *t)
593 int base_playouts = u->t->root->u.playouts;
594 if (UDEBUGL(2) && base_playouts > 0)
595 fprintf(stderr, "<pre-simulated %d games skipped>\n", base_playouts);
597 /* Set up time conditions. */
598 if (ti->period == TT_NULL) *ti = default_ti;
599 struct time_stop stop;
600 time_stop_conditions(ti, b, u->fuseki_end, u->yose_start, &stop);
602 /* Number of last dynkomi adjustment. */
603 int last_dynkomi = t->root->u.playouts;
604 /* Number of last game with progress print. */
605 int last_print = t->root->u.playouts;
606 /* Number of simulations to wait before next print. */
607 int print_interval = TREE_SIMPROGRESS_INTERVAL * (u->thread_model == TM_ROOT ? 1 : u->threads);
608 /* Printed notification about full memory? */
609 bool print_fullmem = false;
610 /* Absolute time of last distributed stats update. */
611 double last_stats_sent = time_now();
612 /* Interval between distributed stats updates. */
613 double stats_interval = STATS_SEND_INTERVAL;
615 struct spawn_ctx *ctx = uct_search_start(u, b, color, t);
617 /* The search tree is ctx->t. This is normally == t, but in case of
618 * TM_ROOT, it is one of the trees belonging to the independent
619 * workers. It is important to reference ctx->t directly since the
620 * thread manager will swap the tree pointer asynchronously. */
621 /* XXX: This means TM_ROOT support is suboptimal since single stalled
622 * thread can stall the others in case of limiting the search by game
623 * count. However, TM_ROOT just does not deserve any more extra code
624 * right now. */
626 struct tree_node *best = NULL;
627 struct tree_node *best2 = NULL; // Second-best move.
628 struct tree_node *bestr = NULL; // best's best child.
629 struct tree_node *winner = NULL;
631 double busywait_interval = TREE_BUSYWAIT_INTERVAL;
633 /* Now, just periodically poll the search tree. */
634 while (1) {
635 time_sleep(busywait_interval);
636 /* busywait_interval should never be less than desired time, or the
637 * time control is broken. But if it happens to be less, we still search
638 * at least 100ms otherwise the move is completely random. */
640 int i = ctx->t->root->u.playouts;
642 /* Adjust dynkomi? */
643 if (ctx->t->use_extra_komi && u->dynkomi->permove
644 && u->dynkomi_interval
645 && i > last_dynkomi + u->dynkomi_interval) {
646 float old_dynkomi = ctx->t->extra_komi;
647 ctx->t->extra_komi = u->dynkomi->permove(u->dynkomi, b, ctx->t);
648 if (UDEBUGL(3) && old_dynkomi != ctx->t->extra_komi)
649 fprintf(stderr, "dynkomi adjusted (%f -> %f)\n", old_dynkomi, ctx->t->extra_komi);
652 /* Print progress? */
653 if (i - last_print > print_interval) {
654 last_print += print_interval; // keep the numbers tidy
655 uct_progress_status(u, ctx->t, color, last_print);
657 if (!print_fullmem && ctx->t->nodes_size > u->max_tree_size) {
658 if (UDEBUGL(2))
659 fprintf(stderr, "memory limit hit (%lu > %lu)\n", ctx->t->nodes_size, u->max_tree_size);
660 print_fullmem = true;
663 /* Never consider stopping if we played too few simulations.
664 * Maybe we risk losing on time when playing in super-extreme
665 * time pressure but the tree is going to be just too messed
666 * up otherwise - we might even play invalid suicides or pass
667 * when we mustn't. */
668 if (i < GJ_MINGAMES)
669 continue;
671 best = u->policy->choose(u->policy, ctx->t->root, b, color, resign);
672 if (best) best2 = u->policy->choose(u->policy, ctx->t->root, b, color, best->coord);
674 /* Possibly stop search early if it's no use to try on. */
675 if (best && uct_search_stop_early(u, ctx->t, b, ti, &stop, best, best2, base_playouts, i))
676 break;
678 /* Check against time settings. */
679 bool desired_done = false;
680 double now = time_now();
681 if (ti->dim == TD_WALLTIME) {
682 double elapsed = now - ti->len.t.timer_start;
683 if (elapsed > stop.worst.time) break;
684 desired_done = elapsed > stop.desired.time;
685 if (stats_interval < 0.1 * stop.desired.time)
686 stats_interval = 0.1 * stop.desired.time;
688 } else { assert(ti->dim == TD_GAMES);
689 if (i > stop.worst.playouts) break;
690 desired_done = i > stop.desired.playouts;
693 /* We want to stop simulating, but are willing to keep trying
694 * if we aren't completely sure about the winner yet. */
695 if (desired_done) {
696 if (u->policy->winner && u->policy->evaluate) {
697 struct uct_descent descent = { .node = ctx->t->root };
698 u->policy->winner(u->policy, ctx->t, &descent);
699 winner = descent.node;
701 if (best)
702 bestr = u->policy->choose(u->policy, best, b, stone_other(color), resign);
703 if (!uct_search_keep_looking(u, ctx->t, b, ti, &stop, best, best2, bestr, winner, i))
704 break;
707 /* TODO: Early break if best->variance goes under threshold and we already
708 * have enough playouts (possibly thanks to book or to pondering)? */
710 /* Send new stats for the distributed engine.
711 * End with #\n (not \n\n) to indicate a temporary result. */
712 if (u->slave && now - last_stats_sent > stats_interval) {
713 printf("=%d %s\n#\n", u->gtp_id, uct_getstats(u, b, NULL));
714 fflush(stdout);
715 last_stats_sent = now;
719 ctx = uct_search_stop();
721 if (UDEBUGL(2))
722 tree_dump(t, u->dumpthres);
723 if (UDEBUGL(0))
724 uct_progress_status(u, t, color, ctx->games);
726 return ctx->games;
730 /* Start pondering background with @color to play. */
731 static void
732 uct_pondering_start(struct uct *u, struct board *b0, struct tree *t, enum stone color)
734 if (UDEBUGL(1))
735 fprintf(stderr, "Starting to ponder with color %s\n", stone2str(stone_other(color)));
736 u->pondering = true;
738 /* We need a local board copy to ponder upon. */
739 struct board *b = malloc(sizeof(*b)); board_copy(b, b0);
741 /* *b0 did not have the genmove'd move played yet. */
742 struct move m = { t->root->coord, t->root_color };
743 int res = board_play(b, &m);
744 assert(res >= 0);
745 setup_dynkomi(u, b, stone_other(m.color));
747 /* Start MCTS manager thread "headless". */
748 uct_search_start(u, b, color, t);
751 /* uct_search_stop() frontend for the pondering (non-genmove) mode. */
752 static void
753 uct_pondering_stop(struct uct *u)
755 u->pondering = false;
756 if (!thread_manager_running)
757 return;
759 /* Stop the thread manager. */
760 struct spawn_ctx *ctx = uct_search_stop();
761 if (UDEBUGL(1)) {
762 fprintf(stderr, "(pondering) ");
763 uct_progress_status(u, ctx->t, ctx->color, ctx->games);
765 free(ctx->b);
769 static coord_t *
770 uct_genmove(struct engine *e, struct board *b, struct time_info *ti, enum stone color, bool pass_all_alive)
772 double start_time = time_now();
773 struct uct *u = e->data;
775 if (b->superko_violation) {
776 fprintf(stderr, "!!! WARNING: SUPERKO VIOLATION OCCURED BEFORE THIS MOVE\n");
777 fprintf(stderr, "Maybe you play with situational instead of positional superko?\n");
778 fprintf(stderr, "I'm going to ignore the violation, but note that I may miss\n");
779 fprintf(stderr, "some moves valid under this ruleset because of this.\n");
780 b->superko_violation = false;
783 /* Seed the tree. */
784 uct_pondering_stop(u);
785 prepare_move(e, b, color);
786 assert(u->t);
787 u->my_color = color;
789 /* How to decide whether to use dynkomi in this game? Since we use
790 * pondering, it's not simple "who-to-play" matter. Decide based on
791 * the last genmove issued. */
792 u->t->use_extra_komi = !!(u->dynkomi_mask & color);
793 setup_dynkomi(u, b, color);
795 if (b->rules == RULES_JAPANESE)
796 u->territory_scoring = true;
798 /* Make pessimistic assumption about komi for Japanese rules to
799 * avoid losing by 0.5 when winning by 0.5 with Chinese rules.
800 * The rules usually give the same winner if the integer part of komi
801 * is odd so we adjust the komi only if it is even (for a board of
802 * odd size). We are not trying to get an exact evaluation for rare
803 * cases of seki. For details see http://home.snafu.de/jasiek/parity.html */
804 if (u->territory_scoring && (((int)floor(b->komi) + board_size(b)) & 1)) {
805 b->komi += (color == S_BLACK ? 1.0 : -1.0);
806 if (UDEBUGL(0))
807 fprintf(stderr, "Setting komi to %.1f assuming Japanese rules\n",
808 b->komi);
811 int base_playouts = u->t->root->u.playouts;
812 /* Perform the Monte Carlo Tree Search! */
813 int played_games = uct_search(u, b, ti, color, u->t);
815 /* Choose the best move from the tree. */
816 struct tree_node *best = u->policy->choose(u->policy, u->t->root, b, color, resign);
817 if (!best) {
818 if (!u->slave) reset_state(u);
819 return coord_copy(pass);
821 if (UDEBUGL(1))
822 fprintf(stderr, "*** WINNER is %s (%d,%d) with score %1.4f (%d/%d:%d/%d games), extra komi %f\n",
823 coord2sstr(best->coord, b), coord_x(best->coord, b), coord_y(best->coord, b),
824 tree_node_get_value(u->t, 1, best->u.value), best->u.playouts,
825 u->t->root->u.playouts, u->t->root->u.playouts - base_playouts, played_games,
826 u->t->extra_komi);
828 /* Do not resign if we're so short of time that evaluation of best
829 * move is completely unreliable, we might be winning actually.
830 * In this case best is almost random but still better than resign.
831 * Also do not resign if we are getting bad results while actually
832 * giving away extra komi points (dynkomi). */
833 if (tree_node_get_value(u->t, 1, best->u.value) < u->resign_ratio
834 && !is_pass(best->coord) && best->u.playouts > GJ_MINGAMES
835 && u->t->extra_komi <= 1 /* XXX we assume dynamic komi == we are black */) {
836 if (!u->slave) reset_state(u);
837 return coord_copy(resign);
840 /* If the opponent just passed and we win counting, always
841 * pass as well. */
842 if (b->moves > 1 && is_pass(b->last_move.coord)) {
843 /* Make sure enough playouts are simulated. */
844 while (u->ownermap.playouts < GJ_MINGAMES)
845 uct_playout(u, b, color, u->t);
846 if (uct_pass_is_safe(u, b, color, u->pass_all_alive || pass_all_alive)) {
847 if (UDEBUGL(0))
848 fprintf(stderr, "<Will rather pass, looks safe enough.>\n");
849 best->coord = pass;
853 /* If we are a slave in the distributed engine, we'll soon get
854 * a "play" command later telling us which move was chosen,
855 * and pondering now will not gain much. */
856 if (!u->slave) {
857 tree_promote_node(u->t, &best);
859 /* After a pass, pondering is harmful for two reasons:
860 * (i) We might keep pondering even when the game is over.
861 * Of course this is the case for opponent resign as well.
862 * (ii) More importantly, the ownermap will get skewed since
863 * the UCT will start cutting off any playouts. */
864 if (u->pondering_opt && !is_pass(best->coord)) {
865 uct_pondering_start(u, b, u->t, stone_other(color));
868 if (UDEBUGL(2)) {
869 double time = time_now() - start_time + 0.000001; /* avoid divide by zero */
870 fprintf(stderr, "genmove in %0.2fs (%d games/s, %d games/s/thread)\n",
871 time, (int)(played_games/time), (int)(played_games/time/u->threads));
873 return coord_copy(best->coord);
876 /* Get stats updates for the distributed engine. Return a buffer
877 * with one line "total_playouts threads" then a list of lines
878 * "coord playouts value". The last line must not end with \n.
879 * If c is not null, add this move with root->playouts weight.
880 * This function is called only by the main thread, but may be
881 * called while the tree is updated by the worker threads.
882 * Keep this code in sync with select_best_move(). */
883 static char *
884 uct_getstats(struct uct *u, struct board *b, coord_t *c)
886 static char reply[10240];
887 char *r = reply;
888 char *end = reply + sizeof(reply);
889 struct tree_node *root = u->t->root;
890 r += snprintf(r, end - r, "%d %d", root->u.playouts, u->threads);
891 int min_playouts = root->u.playouts / 100;
893 // Give a large weight to pass or resign, but still allow other moves.
894 if (c)
895 r += snprintf(r, end - r, "\n%s %d %.1f", coord2sstr(*c, b), root->u.playouts,
896 (float)is_pass(*c));
898 /* We rely on the fact that root->children is set only
899 * after all children are created. */
900 for (struct tree_node *ni = root->children; ni; ni = ni->sibling) {
901 if (ni->u.playouts <= min_playouts
902 || ni->hints & TREE_HINT_INVALID
903 || is_pass(ni->coord))
904 continue;
905 char *coord = coord2sstr(ni->coord, b);
906 // We return the values as stored in the tree, so from black's view.
907 r += snprintf(r, end - r, "\n%s %d %.7f", coord, ni->u.playouts, ni->u.value);
909 return reply;
912 static char *
913 uct_genmoves(struct engine *e, struct board *b, struct time_info *ti, enum stone color, bool pass_all_alive)
915 struct uct *u = e->data;
916 assert(u->slave);
918 coord_t *c = uct_genmove(e, b, ti, color, pass_all_alive);
920 char *reply = uct_getstats(u, b, is_pass(*c) || is_resign(*c) ? c : NULL);
921 coord_done(c);
922 return reply;
926 bool
927 uct_genbook(struct engine *e, struct board *b, struct time_info *ti, enum stone color)
929 struct uct *u = e->data;
930 if (!u->t) prepare_move(e, b, color);
931 assert(u->t);
933 if (ti->dim == TD_GAMES) {
934 /* Don't count in games that already went into the book. */
935 ti->len.games += u->t->root->u.playouts;
937 uct_search(u, b, ti, color, u->t);
939 assert(ti->dim == TD_GAMES);
940 tree_save(u->t, b, ti->len.games / 100);
942 return true;
945 void
946 uct_dumpbook(struct engine *e, struct board *b, enum stone color)
948 struct uct *u = e->data;
949 struct tree *t = tree_init(b, color, u->fast_alloc ? u->max_tree_size : 0, u->local_tree_aging);
950 tree_load(t, b);
951 tree_dump(t, 0);
952 tree_done(t);
956 struct uct *
957 uct_state_init(char *arg, struct board *b)
959 struct uct *u = calloc(1, sizeof(struct uct));
960 bool using_elo = false;
962 u->debug_level = debug_level;
963 u->gamelen = MC_GAMELEN;
964 u->mercymin = 0;
965 u->expand_p = 2;
966 u->dumpthres = 1000;
967 u->playout_amaf = true;
968 u->playout_amaf_nakade = false;
969 u->amaf_prior = false;
970 u->max_tree_size = 3072ULL * 1048576;
972 u->dynkomi_mask = S_BLACK;
974 u->threads = 1;
975 u->thread_model = TM_TREEVL;
976 u->parallel_tree = true;
977 u->virtual_loss = true;
979 u->fuseki_end = 20; // max time at 361*20% = 72 moves (our 36th move, still 99 to play)
980 u->yose_start = 40; // (100-40-25)*361/100/2 = 63 moves still to play by us then
981 u->bestr_ratio = 0.02;
982 // 2.5 is clearly too much, but seems to compensate well for overly stern time allocations.
983 // TODO: Further tuning and experiments with better time allocation schemes.
984 u->best2_ratio = 2.5;
986 u->val_scale = 0.04; u->val_points = 40;
988 u->tenuki_d = 4;
989 u->local_tree_aging = 2;
991 if (arg) {
992 char *optspec, *next = arg;
993 while (*next) {
994 optspec = next;
995 next += strcspn(next, ",");
996 if (*next) { *next++ = 0; } else { *next = 0; }
998 char *optname = optspec;
999 char *optval = strchr(optspec, '=');
1000 if (optval) *optval++ = 0;
1002 if (!strcasecmp(optname, "debug")) {
1003 if (optval)
1004 u->debug_level = atoi(optval);
1005 else
1006 u->debug_level++;
1007 } else if (!strcasecmp(optname, "mercy") && optval) {
1008 /* Minimal difference of black/white captures
1009 * to stop playout - "Mercy Rule". Speeds up
1010 * hopeless playouts at the expense of some
1011 * accuracy. */
1012 u->mercymin = atoi(optval);
1013 } else if (!strcasecmp(optname, "gamelen") && optval) {
1014 u->gamelen = atoi(optval);
1015 } else if (!strcasecmp(optname, "expand_p") && optval) {
1016 u->expand_p = atoi(optval);
1017 } else if (!strcasecmp(optname, "dumpthres") && optval) {
1018 u->dumpthres = atoi(optval);
1019 } else if (!strcasecmp(optname, "best2_ratio") && optval) {
1020 /* If set, prolong simulating while
1021 * first_best/second_best playouts ratio
1022 * is less than best2_ratio. */
1023 u->best2_ratio = atof(optval);
1024 } else if (!strcasecmp(optname, "bestr_ratio") && optval) {
1025 /* If set, prolong simulating while
1026 * best,best_best_child values delta
1027 * is more than bestr_ratio. */
1028 u->bestr_ratio = atof(optval);
1029 } else if (!strcasecmp(optname, "playout_amaf")) {
1030 /* Whether to include random playout moves in
1031 * AMAF as well. (Otherwise, only tree moves
1032 * are included in AMAF. Of course makes sense
1033 * only in connection with an AMAF policy.) */
1034 /* with-without: 55.5% (+-4.1) */
1035 if (optval && *optval == '0')
1036 u->playout_amaf = false;
1037 else
1038 u->playout_amaf = true;
1039 } else if (!strcasecmp(optname, "playout_amaf_nakade")) {
1040 /* Whether to include nakade moves from playouts
1041 * in the AMAF statistics; this tends to nullify
1042 * the playout_amaf effect by adding too much
1043 * noise. */
1044 if (optval && *optval == '0')
1045 u->playout_amaf_nakade = false;
1046 else
1047 u->playout_amaf_nakade = true;
1048 } else if (!strcasecmp(optname, "playout_amaf_cutoff") && optval) {
1049 /* Keep only first N% of playout stage AMAF
1050 * information. */
1051 u->playout_amaf_cutoff = atoi(optval);
1052 } else if ((!strcasecmp(optname, "policy") || !strcasecmp(optname, "random_policy")) && optval) {
1053 char *policyarg = strchr(optval, ':');
1054 struct uct_policy **p = !strcasecmp(optname, "policy") ? &u->policy : &u->random_policy;
1055 if (policyarg)
1056 *policyarg++ = 0;
1057 if (!strcasecmp(optval, "ucb1")) {
1058 *p = policy_ucb1_init(u, policyarg);
1059 } else if (!strcasecmp(optval, "ucb1amaf")) {
1060 *p = policy_ucb1amaf_init(u, policyarg);
1061 } else {
1062 fprintf(stderr, "UCT: Invalid tree policy %s\n", optval);
1063 exit(1);
1065 } else if (!strcasecmp(optname, "playout") && optval) {
1066 char *playoutarg = strchr(optval, ':');
1067 if (playoutarg)
1068 *playoutarg++ = 0;
1069 if (!strcasecmp(optval, "moggy")) {
1070 u->playout = playout_moggy_init(playoutarg, b);
1071 } else if (!strcasecmp(optval, "light")) {
1072 u->playout = playout_light_init(playoutarg, b);
1073 } else if (!strcasecmp(optval, "elo")) {
1074 u->playout = playout_elo_init(playoutarg, b);
1075 using_elo = true;
1076 } else {
1077 fprintf(stderr, "UCT: Invalid playout policy %s\n", optval);
1078 exit(1);
1080 } else if (!strcasecmp(optname, "prior") && optval) {
1081 u->prior = uct_prior_init(optval, b);
1082 } else if (!strcasecmp(optname, "amaf_prior") && optval) {
1083 u->amaf_prior = atoi(optval);
1084 } else if (!strcasecmp(optname, "threads") && optval) {
1085 /* By default, Pachi will run with only single
1086 * tree search thread! */
1087 u->threads = atoi(optval);
1088 } else if (!strcasecmp(optname, "thread_model") && optval) {
1089 if (!strcasecmp(optval, "root")) {
1090 /* Root parallelization - each thread
1091 * does independent search, trees are
1092 * merged at the end. */
1093 u->thread_model = TM_ROOT;
1094 u->parallel_tree = false;
1095 u->virtual_loss = false;
1096 } else if (!strcasecmp(optval, "tree")) {
1097 /* Tree parallelization - all threads
1098 * grind on the same tree. */
1099 u->thread_model = TM_TREE;
1100 u->parallel_tree = true;
1101 u->virtual_loss = false;
1102 } else if (!strcasecmp(optval, "treevl")) {
1103 /* Tree parallelization, but also
1104 * with virtual losses - this discou-
1105 * rages most threads choosing the
1106 * same tree branches to read. */
1107 u->thread_model = TM_TREEVL;
1108 u->parallel_tree = true;
1109 u->virtual_loss = true;
1110 } else {
1111 fprintf(stderr, "UCT: Invalid thread model %s\n", optval);
1112 exit(1);
1114 } else if (!strcasecmp(optname, "pondering")) {
1115 /* Keep searching even during opponent's turn. */
1116 u->pondering_opt = !optval || atoi(optval);
1117 } else if (!strcasecmp(optname, "fuseki_end") && optval) {
1118 /* At the very beginning it's not worth thinking
1119 * too long because the playout evaluations are
1120 * very noisy. So gradually increase the thinking
1121 * time up to maximum when fuseki_end percent
1122 * of the board has been played.
1123 * This only applies if we are not in byoyomi. */
1124 u->fuseki_end = atoi(optval);
1125 } else if (!strcasecmp(optname, "yose_start") && optval) {
1126 /* When yose_start percent of the board has been
1127 * played, or if we are in byoyomi, stop spending
1128 * more time and spread the remaining time
1129 * uniformly.
1130 * Between fuseki_end and yose_start, we spend
1131 * a constant proportion of the remaining time
1132 * on each move. (yose_start should actually
1133 * be much earlier than when real yose start,
1134 * but "yose" is a good short name to convey
1135 * the idea.) */
1136 u->yose_start = atoi(optval);
1137 } else if (!strcasecmp(optname, "force_seed") && optval) {
1138 u->force_seed = atoi(optval);
1139 } else if (!strcasecmp(optname, "no_book")) {
1140 u->no_book = true;
1141 } else if (!strcasecmp(optname, "dynkomi") && optval) {
1142 /* Dynamic komi approach; there are multiple
1143 * ways to adjust komi dynamically throughout
1144 * play. We currently support two: */
1145 char *dynkomiarg = strchr(optval, ':');
1146 if (dynkomiarg)
1147 *dynkomiarg++ = 0;
1148 if (!strcasecmp(optval, "none")) {
1149 u->dynkomi = uct_dynkomi_init_none(u, dynkomiarg, b);
1150 } else if (!strcasecmp(optval, "linear")) {
1151 u->dynkomi = uct_dynkomi_init_linear(u, dynkomiarg, b);
1152 } else if (!strcasecmp(optval, "adaptive")) {
1153 u->dynkomi = uct_dynkomi_init_adaptive(u, dynkomiarg, b);
1154 } else {
1155 fprintf(stderr, "UCT: Invalid dynkomi mode %s\n", optval);
1156 exit(1);
1158 } else if (!strcasecmp(optname, "dynkomi_mask") && optval) {
1159 /* Bitmask of colors the player must be
1160 * for dynkomi be applied; you may want
1161 * to use dynkomi_mask=3 to allow dynkomi
1162 * even in games where Pachi is white. */
1163 u->dynkomi_mask = atoi(optval);
1164 } else if (!strcasecmp(optname, "dynkomi_interval") && optval) {
1165 /* If non-zero, re-adjust dynamic komi
1166 * throughout a single genmove reading,
1167 * roughly every N simulations. */
1168 u->dynkomi_interval = atoi(optval);
1169 } else if (!strcasecmp(optname, "val_scale") && optval) {
1170 /* How much of the game result value should be
1171 * influenced by win size. Zero means it isn't. */
1172 u->val_scale = atof(optval);
1173 } else if (!strcasecmp(optname, "val_points") && optval) {
1174 /* Maximum size of win to be scaled into game
1175 * result value. Zero means boardsize^2. */
1176 u->val_points = atoi(optval) * 2; // result values are doubled
1177 } else if (!strcasecmp(optname, "val_extra")) {
1178 /* If false, the score coefficient will be simply
1179 * added to the value, instead of scaling the result
1180 * coefficient because of it. */
1181 u->val_extra = !optval || atoi(optval);
1182 } else if (!strcasecmp(optname, "local_tree") && optval) {
1183 /* Whether to bias exploration by local tree values
1184 * (must be supported by the used policy).
1185 * 0: Don't.
1186 * 1: Do, value = result.
1187 * Try to temper the result:
1188 * 2: Do, value = 0.5+(result-expected)/2.
1189 * 3: Do, value = 0.5+bzz((result-expected)^2).
1190 * 4: Do, value = 0.5+sqrt(result-expected)/2. */
1191 u->local_tree = atoi(optval);
1192 } else if (!strcasecmp(optname, "tenuki_d") && optval) {
1193 /* Tenuki distance at which to break the local tree. */
1194 u->tenuki_d = atoi(optval);
1195 if (u->tenuki_d > TREE_NODE_D_MAX + 1) {
1196 fprintf(stderr, "uct: tenuki_d must not be larger than TREE_NODE_D_MAX+1 %d\n", TREE_NODE_D_MAX + 1);
1197 exit(1);
1199 } else if (!strcasecmp(optname, "local_tree_aging") && optval) {
1200 /* How much to reduce local tree values between moves. */
1201 u->local_tree_aging = atof(optval);
1202 } else if (!strcasecmp(optname, "local_tree_allseq")) {
1203 /* By default, only complete sequences are stored
1204 * in the local tree. If this is on, also
1205 * subsequences starting at each move are stored. */
1206 u->local_tree_allseq = !optval || atoi(optval);
1207 } else if (!strcasecmp(optname, "local_tree_playout")) {
1208 /* Whether to adjust ELO playout probability
1209 * distributions according to matched localtree
1210 * information. */
1211 u->local_tree_playout = !optval || atoi(optval);
1212 } else if (!strcasecmp(optname, "local_tree_pseqroot")) {
1213 /* By default, when we have no sequence move
1214 * to suggest in-playout, we give up. If this
1215 * is on, we make probability distribution from
1216 * sequences first moves instead. */
1217 u->local_tree_pseqroot = !optval || atoi(optval);
1218 } else if (!strcasecmp(optname, "pass_all_alive")) {
1219 /* Whether to consider all stones alive at the game
1220 * end instead of marking dead groupd. */
1221 u->pass_all_alive = !optval || atoi(optval);
1222 } else if (!strcasecmp(optname, "territory_scoring")) {
1223 /* Use territory scoring (default is area scoring).
1224 * An explicit kgs-rules command overrides this. */
1225 u->territory_scoring = !optval || atoi(optval);
1226 } else if (!strcasecmp(optname, "random_policy_chance") && optval) {
1227 /* If specified (N), with probability 1/N, random_policy policy
1228 * descend is used instead of main policy descend; useful
1229 * if specified policy (e.g. UCB1AMAF) can make unduly biased
1230 * choices sometimes, you can fall back to e.g.
1231 * random_policy=UCB1. */
1232 u->random_policy_chance = atoi(optval);
1233 } else if (!strcasecmp(optname, "max_tree_size") && optval) {
1234 /* Maximum amount of memory [MiB] consumed by the move tree.
1235 * For fast_alloc it includes the temp tree used for pruning.
1236 * Default is 3072 (3 GiB). Note that if you use TM_ROOT,
1237 * this limits size of only one of the trees, not all of them
1238 * together. */
1239 u->max_tree_size = atol(optval) * 1048576;
1240 } else if (!strcasecmp(optname, "fast_alloc")) {
1241 u->fast_alloc = !optval || atoi(optval);
1242 } else if (!strcasecmp(optname, "slave")) {
1243 /* Act as slave for the distributed engine. */
1244 u->slave = !optval || atoi(optval);
1245 } else if (!strcasecmp(optname, "banner") && optval) {
1246 /* Additional banner string. This must come as the
1247 * last engine parameter. */
1248 if (*next) *--next = ',';
1249 u->banner = strdup(optval);
1250 break;
1251 } else {
1252 fprintf(stderr, "uct: Invalid engine argument %s or missing value\n", optname);
1253 exit(1);
1258 u->resign_ratio = 0.2; /* Resign when most games are lost. */
1259 u->loss_threshold = 0.85; /* Stop reading if after at least 2000 playouts this is best value. */
1260 if (!u->policy)
1261 u->policy = policy_ucb1amaf_init(u, NULL);
1263 if (!!u->random_policy_chance ^ !!u->random_policy) {
1264 fprintf(stderr, "uct: Only one of random_policy and random_policy_chance is set\n");
1265 exit(1);
1268 if (!u->local_tree) {
1269 /* No ltree aging. */
1270 u->local_tree_aging = 1.0f;
1272 if (!using_elo)
1273 u->local_tree_playout = false;
1275 if (u->fast_alloc && !u->parallel_tree) {
1276 fprintf(stderr, "fast_alloc not supported with root parallelization.\n");
1277 exit(1);
1279 if (u->fast_alloc)
1280 u->max_tree_size = (100ULL * u->max_tree_size) / (100 + MIN_FREE_MEM_PERCENT);
1282 if (!u->prior)
1283 u->prior = uct_prior_init(NULL, b);
1285 if (!u->playout)
1286 u->playout = playout_moggy_init(NULL, b);
1287 u->playout->debug_level = u->debug_level;
1289 u->ownermap.map = malloc(board_size2(b) * sizeof(u->ownermap.map[0]));
1291 if (!u->dynkomi)
1292 u->dynkomi = uct_dynkomi_init_linear(u, NULL, b);
1294 /* Some things remain uninitialized for now - the opening book
1295 * is not loaded and the tree not set up. */
1296 /* This will be initialized in setup_state() at the first move
1297 * received/requested. This is because right now we are not aware
1298 * about any komi or handicap setup and such. */
1300 return u;
1303 struct engine *
1304 engine_uct_init(char *arg, struct board *b)
1306 struct uct *u = uct_state_init(arg, b);
1307 struct engine *e = calloc(1, sizeof(struct engine));
1308 e->name = "UCT Engine";
1309 e->printhook = uct_printhook_ownermap;
1310 e->notify_play = uct_notify_play;
1311 e->chat = uct_chat;
1312 e->genmove = uct_genmove;
1313 e->genmoves = uct_genmoves;
1314 e->dead_group_list = uct_dead_group_list;
1315 e->done = uct_done;
1316 e->data = u;
1317 if (u->slave)
1318 e->notify = uct_notify;
1320 const char banner[] = "I'm playing UCT. When I'm losing, I will resign, "
1321 "if I think I win, I play until you pass. "
1322 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
1323 if (!u->banner) u->banner = "";
1324 e->comment = malloc(sizeof(banner) + strlen(u->banner) + 1);
1325 sprintf(e->comment, "%s %s", banner, u->banner);
1327 return e;