uct_genmoves(): Slight declarations reorder
[pachi/derm.git] / uct / uct.c
blobf83a6306deabd4fd2c49562e10fd4f5cb2f762c2
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/slave.h"
29 #include "uct/tree.h"
30 #include "uct/uct.h"
31 #include "uct/walk.h"
33 struct uct_policy *policy_ucb1_init(struct uct *u, char *arg);
34 struct uct_policy *policy_ucb1amaf_init(struct uct *u, char *arg);
35 static void uct_pondering_stop(struct uct *u);
36 static void uct_pondering_start(struct uct *u, struct board *b0, struct tree *t, enum stone color);
38 /* Default number of simulations to perform per move.
39 * Note that this is now in total over all threads! (Unless TM_ROOT.) */
40 #define MC_GAMES 80000
41 #define MC_GAMELEN MAX_GAMELEN
42 static const struct time_info default_ti = {
43 .period = TT_MOVE,
44 .dim = TD_GAMES,
45 .len = { .games = MC_GAMES },
48 /* How big proportion of ownermap counts must be of one color to consider
49 * the point sure. */
50 #define GJ_THRES 0.8
51 /* How many games to consider at minimum before judging groups. */
52 #define GJ_MINGAMES 500
54 /* How often to inspect the tree from the main thread to check for playout
55 * stop, progress reports, etc. (in seconds) */
56 #define TREE_BUSYWAIT_INTERVAL 0.1 /* 100ms */
58 /* Once per how many simulations (per thread) to show a progress report line. */
59 #define TREE_SIMPROGRESS_INTERVAL 10000
61 /* 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 void
100 uct_prepare_move(struct uct *u, struct board *b, enum stone color)
102 if (u->t) {
103 /* Verify that we have sane state. */
104 assert(b->es == u);
105 assert(u->t && b->moves);
106 if (color != stone_other(u->t->root_color)) {
107 fprintf(stderr, "Fatal: Non-alternating play detected %d %d\n",
108 color, u->t->root_color);
109 exit(1);
112 } else {
113 /* We need fresh state. */
114 b->es = u;
115 setup_state(u, b, color);
118 u->ownermap.playouts = 0;
119 memset(u->ownermap.map, 0, board_size2(b) * sizeof(u->ownermap.map[0]));
120 memset(u->stats, 0, board_size2(b) * sizeof(u->stats[0]));
121 u->played_own = u->played_all = 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 static bool board_resized = false;
153 board_resized |= is_gamestart(cmd);
155 /* Force resending the whole command history if we are out of sync
156 * but do it only once, not if already getting the history. */
157 if ((move_number(id) != b->moves || !board_resized)
158 && !reply_disabled(id) && !is_reset(cmd)) {
159 if (UDEBUGL(0))
160 fprintf(stderr, "Out of sync, id %d, move %d\n", id, b->moves);
161 static char buf[128];
162 snprintf(buf, sizeof(buf), "out of sync, move %d expected", b->moves);
163 *reply = buf;
164 return P_DONE_ERROR;
166 return reply_disabled(id) ? P_NOREPLY : P_OK;
169 static char *
170 uct_printhook_ownermap(struct board *board, coord_t c, char *s, char *end)
172 struct uct *u = board->es;
173 assert(u);
174 const char chr[] = ":XO,"; // dame, black, white, unclear
175 const char chm[] = ":xo,";
176 char ch = chr[board_ownermap_judge_point(&u->ownermap, c, GJ_THRES)];
177 if (ch == ',') { // less precise estimate then?
178 ch = chm[board_ownermap_judge_point(&u->ownermap, c, 0.67)];
180 s += snprintf(s, end - s, "%c ", ch);
181 return s;
184 static char *
185 uct_notify_play(struct engine *e, struct board *b, struct move *m)
187 struct uct *u = e->data;
188 if (!u->t) {
189 /* No state, create one - this is probably game beginning
190 * and we need to load the opening book right now. */
191 uct_prepare_move(u, b, m->color);
192 assert(u->t);
195 /* Stop pondering, required by tree_promote_at() */
196 uct_pondering_stop(u);
197 if (UDEBUGL(2) && u->slave)
198 tree_dump(u->t, u->dumpthres);
200 if (is_resign(m->coord)) {
201 /* Reset state. */
202 reset_state(u);
203 return NULL;
206 /* Promote node of the appropriate move to the tree root. */
207 assert(u->t->root);
208 if (!tree_promote_at(u->t, b, m->coord)) {
209 if (UDEBUGL(0))
210 fprintf(stderr, "Warning: Cannot promote move node! Several play commands in row?\n");
211 reset_state(u);
212 return NULL;
215 /* If we are a slave in a distributed engine, start pondering once
216 * we know which move we actually played. See uct_genmove() about
217 * the check for pass. */
218 if (u->pondering_opt && u->slave && m->color == u->my_color && !is_pass(m->coord))
219 uct_pondering_start(u, b, u->t, stone_other(m->color));
221 return NULL;
224 static char *
225 uct_chat(struct engine *e, struct board *b, char *cmd)
227 struct uct *u = e->data;
228 static char reply[1024];
230 cmd += strspn(cmd, " \n\t");
231 if (!strncasecmp(cmd, "winrate", 7)) {
232 if (!u->t)
233 return "no game context (yet?)";
234 enum stone color = u->t->root_color;
235 struct tree_node *n = u->t->root;
236 snprintf(reply, 1024, "In %d playouts at %d threads, %s %s can win with %.2f%% probability",
237 n->u.playouts, u->threads, stone2str(color), coord2sstr(n->coord, b),
238 tree_node_get_value(u->t, -1, n->u.value) * 100);
239 if (u->t->use_extra_komi && abs(u->t->extra_komi) >= 0.5) {
240 sprintf(reply + strlen(reply), ", while self-imposing extra komi %.1f",
241 u->t->extra_komi);
243 strcat(reply, ".");
244 return reply;
246 return NULL;
249 static void
250 uct_dead_group_list(struct engine *e, struct board *b, struct move_queue *mq)
252 struct uct *u = e->data;
254 /* This means the game is probably over, no use pondering on. */
255 uct_pondering_stop(u);
257 if (u->pass_all_alive)
258 return; // no dead groups
260 bool mock_state = false;
262 if (!u->t) {
263 /* No state, but we cannot just back out - we might
264 * have passed earlier, only assuming some stones are
265 * dead, and then re-connected, only to lose counting
266 * when all stones are assumed alive. */
267 /* Mock up some state and seed the ownermap by few
268 * simulations. */
269 uct_prepare_move(u, b, S_BLACK); assert(u->t);
270 for (int i = 0; i < GJ_MINGAMES; i++)
271 uct_playout(u, b, S_BLACK, u->t);
272 mock_state = true;
275 dead_group_list(u, b, mq);
277 if (mock_state) {
278 /* Clean up the mock state in case we will receive
279 * a genmove; we could get a non-alternating-move
280 * error from uct_prepare_move() in that case otherwise. */
281 reset_state(u);
285 static void
286 playout_policy_done(struct playout_policy *p)
288 if (p->done) p->done(p);
289 if (p->data) free(p->data);
290 free(p);
293 static void
294 uct_done(struct engine *e)
296 /* This is called on engine reset, especially when clear_board
297 * is received and new game should begin. */
298 struct uct *u = e->data;
299 uct_pondering_stop(u);
300 if (u->t) reset_state(u);
301 free(u->ownermap.map);
302 free(u->stats);
304 free(u->policy);
305 free(u->random_policy);
306 playout_policy_done(u->playout);
307 uct_prior_done(u->prior);
311 /* Pachi threading structure (if uct_playouts_parallel() is used):
313 * main thread
314 * | main(), GTP communication, ...
315 * | starts and stops the search managed by thread_manager
317 * thread_manager
318 * | spawns and collects worker threads
320 * worker0
321 * worker1
322 * ...
323 * workerK
324 * uct_playouts() loop, doing descend-playout until uct_halt
326 * Another way to look at it is by functions (lines denote thread boundaries):
328 * | uct_genmove()
329 * | uct_search() (uct_search_start() .. uct_search_stop())
330 * | -----------------------
331 * | spawn_thread_manager()
332 * | -----------------------
333 * | spawn_worker()
334 * V uct_playouts() */
336 /* Set in thread manager in case the workers should stop. */
337 volatile sig_atomic_t uct_halt = 0;
338 /* ID of the running worker thread. */
339 __thread int thread_id = -1;
340 /* ID of the thread manager. */
341 static pthread_t thread_manager;
342 bool thread_manager_running;
344 static pthread_mutex_t finish_mutex = PTHREAD_MUTEX_INITIALIZER;
345 static pthread_cond_t finish_cond = PTHREAD_COND_INITIALIZER;
346 static volatile int finish_thread;
347 static pthread_mutex_t finish_serializer = PTHREAD_MUTEX_INITIALIZER;
349 struct spawn_ctx {
350 int tid;
351 struct uct *u;
352 struct board *b;
353 enum stone color;
354 struct tree *t;
355 unsigned long seed;
356 int games;
359 static void *
360 spawn_worker(void *ctx_)
362 struct spawn_ctx *ctx = ctx_;
363 /* Setup */
364 fast_srandom(ctx->seed);
365 thread_id = ctx->tid;
366 /* Run */
367 ctx->games = uct_playouts(ctx->u, ctx->b, ctx->color, ctx->t);
368 /* Finish */
369 pthread_mutex_lock(&finish_serializer);
370 pthread_mutex_lock(&finish_mutex);
371 finish_thread = ctx->tid;
372 pthread_cond_signal(&finish_cond);
373 pthread_mutex_unlock(&finish_mutex);
374 return ctx;
377 /* Thread manager, controlling worker threads. It must be called with
378 * finish_mutex lock held, but it will unlock it itself before exiting;
379 * this is necessary to be completely deadlock-free. */
380 /* The finish_cond can be signalled for it to stop; in that case,
381 * the caller should set finish_thread = -1. */
382 /* After it is started, it will update mctx->t to point at some tree
383 * used for the actual search (matters only for TM_ROOT), on return
384 * it will set mctx->games to the number of performed simulations. */
385 static void *
386 spawn_thread_manager(void *ctx_)
388 /* In thread_manager, we use only some of the ctx fields. */
389 struct spawn_ctx *mctx = ctx_;
390 struct uct *u = mctx->u;
391 struct tree *t = mctx->t;
392 bool shared_tree = u->parallel_tree;
393 fast_srandom(mctx->seed);
395 int played_games = 0;
396 pthread_t threads[u->threads];
397 int joined = 0;
399 uct_halt = 0;
401 /* Garbage collect the tree by preference when pondering. */
402 if (u->pondering && t->nodes && t->nodes_size > t->max_tree_size/2) {
403 unsigned long temp_size = (MIN_FREE_MEM_PERCENT * t->max_tree_size) / 100;
404 t->root = tree_garbage_collect(t, temp_size, t->root);
407 /* Spawn threads... */
408 for (int ti = 0; ti < u->threads; ti++) {
409 struct spawn_ctx *ctx = malloc2(sizeof(*ctx));
410 ctx->u = u; ctx->b = mctx->b; ctx->color = mctx->color;
411 mctx->t = ctx->t = shared_tree ? t : tree_copy(t);
412 ctx->tid = ti; ctx->seed = fast_random(65536) + ti;
413 pthread_create(&threads[ti], NULL, spawn_worker, ctx);
414 if (UDEBUGL(3))
415 fprintf(stderr, "Spawned worker %d\n", ti);
418 /* ...and collect them back: */
419 while (joined < u->threads) {
420 /* Wait for some thread to finish... */
421 pthread_cond_wait(&finish_cond, &finish_mutex);
422 if (finish_thread < 0) {
423 /* Stop-by-caller. Tell the workers to wrap up. */
424 uct_halt = 1;
425 continue;
427 /* ...and gather its remnants. */
428 struct spawn_ctx *ctx;
429 pthread_join(threads[finish_thread], (void **) &ctx);
430 played_games += ctx->games;
431 joined++;
432 if (!shared_tree) {
433 if (ctx->t == mctx->t) mctx->t = t;
434 tree_merge(t, ctx->t);
435 tree_done(ctx->t);
437 free(ctx);
438 if (UDEBUGL(3))
439 fprintf(stderr, "Joined worker %d\n", finish_thread);
440 pthread_mutex_unlock(&finish_serializer);
443 pthread_mutex_unlock(&finish_mutex);
445 if (!shared_tree)
446 tree_normalize(mctx->t, u->threads);
448 mctx->games = played_games;
449 return mctx;
452 static struct spawn_ctx *
453 uct_search_start(struct uct *u, struct board *b, enum stone color, struct tree *t)
455 assert(u->threads > 0);
456 assert(!thread_manager_running);
458 struct spawn_ctx ctx = { .u = u, .b = b, .color = color, .t = t, .seed = fast_random(65536) };
459 static struct spawn_ctx mctx; mctx = ctx;
460 pthread_mutex_lock(&finish_mutex);
461 pthread_create(&thread_manager, NULL, spawn_thread_manager, &mctx);
462 thread_manager_running = true;
463 return &mctx;
466 static struct spawn_ctx *
467 uct_search_stop(void)
469 assert(thread_manager_running);
471 /* Signal thread manager to stop the workers. */
472 pthread_mutex_lock(&finish_mutex);
473 finish_thread = -1;
474 pthread_cond_signal(&finish_cond);
475 pthread_mutex_unlock(&finish_mutex);
477 /* Collect the thread manager. */
478 struct spawn_ctx *pctx;
479 thread_manager_running = false;
480 pthread_join(thread_manager, (void **) &pctx);
481 return pctx;
485 /* Determine whether we should terminate the search early. */
486 static bool
487 uct_search_stop_early(struct uct *u, struct tree *t, struct board *b,
488 struct time_info *ti, struct time_stop *stop,
489 struct tree_node *best, struct tree_node *best2,
490 int played)
492 /* Always use at least half the desired time. It is silly
493 * to lose a won game because we played a bad move in 0.1s. */
494 double elapsed = 0;
495 if (ti->dim == TD_WALLTIME) {
496 elapsed = time_now() - ti->len.t.timer_start;
497 if (elapsed < 0.5 * stop->desired.time) return false;
500 /* Early break in won situation. */
501 if (best->u.playouts >= 2000 && tree_node_get_value(t, 1, best->u.value) >= u->loss_threshold)
502 return true;
503 /* Earlier break in super-won situation. */
504 if (best->u.playouts >= 500 && tree_node_get_value(t, 1, best->u.value) >= 0.95)
505 return true;
507 /* Break early if we estimate the second-best move cannot
508 * catch up in assigned time anymore. We use all our time
509 * if we are in byoyomi with single stone remaining in our
510 * period, however - it's better to pre-ponder. */
511 bool time_indulgent = (!ti->len.t.main_time && ti->len.t.byoyomi_stones == 1);
512 if (best2 && ti->dim == TD_WALLTIME && !time_indulgent) {
513 double remaining = stop->worst.time - elapsed;
514 double pps = ((double)played) / elapsed;
515 double estplayouts = remaining * pps + PLAYOUT_DELTA_SAFEMARGIN;
516 if (best->u.playouts > best2->u.playouts + estplayouts) {
517 if (UDEBUGL(2))
518 fprintf(stderr, "Early stop, result cannot change: "
519 "best %d, best2 %d, estimated %f simulations to go\n",
520 best->u.playouts, best2->u.playouts, estplayouts);
521 return true;
525 return false;
528 /* Determine whether we should terminate the search later than expected. */
529 static bool
530 uct_search_keep_looking(struct uct *u, struct tree *t, struct board *b,
531 struct time_info *ti, struct time_stop *stop,
532 struct tree_node *best, struct tree_node *best2,
533 struct tree_node *bestr, struct tree_node *winner, int i)
535 if (!best) {
536 if (UDEBUGL(2))
537 fprintf(stderr, "Did not find best move, still trying...\n");
538 return true;
541 /* Do not waste time if we are winning. Spend up to worst time if
542 * we are unsure, but only desired time if we are sure of winning. */
543 float beta = 2 * (tree_node_get_value(t, 1, best->u.value) - 0.5);
544 if (ti->dim == TD_WALLTIME && beta > 0) {
545 double good_enough = stop->desired.time * beta + stop->worst.time * (1 - beta);
546 double elapsed = time_now() - ti->len.t.timer_start;
547 if (elapsed > good_enough) return false;
550 if (u->best2_ratio > 0) {
551 /* Check best/best2 simulations ratio. If the
552 * two best moves give very similar results,
553 * keep simulating. */
554 if (best2 && best2->u.playouts
555 && (double)best->u.playouts / best2->u.playouts < u->best2_ratio) {
556 if (UDEBUGL(2))
557 fprintf(stderr, "Best2 ratio %f < threshold %f\n",
558 (double)best->u.playouts / best2->u.playouts,
559 u->best2_ratio);
560 return true;
564 if (u->bestr_ratio > 0) {
565 /* Check best, best_best value difference. If the best move
566 * and its best child do not give similar enough results,
567 * keep simulating. */
568 if (bestr && bestr->u.playouts
569 && fabs((double)best->u.value - bestr->u.value) > u->bestr_ratio) {
570 if (UDEBUGL(2))
571 fprintf(stderr, "Bestr delta %f > threshold %f\n",
572 fabs((double)best->u.value - bestr->u.value),
573 u->bestr_ratio);
574 return true;
578 if (winner && winner != best) {
579 /* Keep simulating if best explored
580 * does not have also highest value. */
581 if (UDEBUGL(2))
582 fprintf(stderr, "[%d] best %3s [%d] %f != winner %3s [%d] %f\n", i,
583 coord2sstr(best->coord, t->board),
584 best->u.playouts, tree_node_get_value(t, 1, best->u.value),
585 coord2sstr(winner->coord, t->board),
586 winner->u.playouts, tree_node_get_value(t, 1, winner->u.value));
587 return true;
590 /* No reason to keep simulating, bye. */
591 return false;
594 /* Run time-limited MCTS search. For a slave in the distributed
595 * engine, the search is done in background and will be stopped at
596 * the next uct_notify_play(); keep_looking is advice for the master. */
598 uct_search(struct uct *u, struct board *b, struct time_info *ti, enum stone color,
599 struct tree *t, bool *keep_looking)
601 int base_playouts = u->t->root->u.playouts;
602 if (UDEBUGL(2) && base_playouts > 0)
603 fprintf(stderr, "<pre-simulated %d games skipped>\n", base_playouts);
605 *keep_looking = false;
607 /* Number of last dynkomi adjustment. */
608 int last_dynkomi = t->root->u.playouts;
609 /* Number of last game with progress print. */
610 int last_print = t->root->u.playouts;
611 /* Number of simulations to wait before next print. */
612 int print_interval = TREE_SIMPROGRESS_INTERVAL * (u->thread_model == TM_ROOT ? 1 : u->threads);
613 /* Printed notification about full memory? */
614 bool print_fullmem = false;
616 static struct time_stop stop;
617 static struct spawn_ctx *ctx;
618 if (!thread_manager_running) {
619 if (ti->period == TT_NULL) *ti = default_ti;
620 time_stop_conditions(ti, b, u->fuseki_end, u->yose_start, &stop);
622 ctx = uct_search_start(u, b, color, t);
623 } else {
624 /* Keep the search running. */
625 assert(u->slave);
628 /* The search tree is ctx->t. This is normally == t, but in case of
629 * TM_ROOT, it is one of the trees belonging to the independent
630 * workers. It is important to reference ctx->t directly since the
631 * thread manager will swap the tree pointer asynchronously. */
632 /* XXX: This means TM_ROOT support is suboptimal since single stalled
633 * thread can stall the others in case of limiting the search by game
634 * count. However, TM_ROOT just does not deserve any more extra code
635 * right now. */
637 /* Now, just periodically poll the search tree. */
638 while (1) {
639 time_sleep(TREE_BUSYWAIT_INTERVAL);
640 /* TREE_BUSYWAIT_INTERVAL should never be less than desired time, or the
641 * time control is broken. But if it happens to be less, we still search
642 * at least 100ms otherwise the move is completely random. */
644 int i = ctx->t->root->u.playouts;
646 /* Adjust dynkomi? */
647 if (ctx->t->use_extra_komi && u->dynkomi->permove
648 && u->dynkomi_interval
649 && i > last_dynkomi + u->dynkomi_interval) {
650 last_dynkomi += u->dynkomi_interval;
651 float old_dynkomi = ctx->t->extra_komi;
652 ctx->t->extra_komi = u->dynkomi->permove(u->dynkomi, b, ctx->t);
653 if (UDEBUGL(3) && old_dynkomi != ctx->t->extra_komi)
654 fprintf(stderr, "dynkomi adjusted (%f -> %f)\n", old_dynkomi, ctx->t->extra_komi);
657 /* Print progress? */
658 if (i - last_print > print_interval) {
659 last_print += print_interval; // keep the numbers tidy
660 uct_progress_status(u, ctx->t, color, last_print);
662 if (!print_fullmem && ctx->t->nodes_size > u->max_tree_size) {
663 if (UDEBUGL(2))
664 fprintf(stderr, "memory limit hit (%lu > %lu)\n", ctx->t->nodes_size, u->max_tree_size);
665 print_fullmem = true;
668 /* Never consider stopping if we played too few simulations.
669 * Maybe we risk losing on time when playing in super-extreme
670 * time pressure but the tree is going to be just too messed
671 * up otherwise - we might even play invalid suicides or pass
672 * when we mustn't. */
673 if (i < GJ_MINGAMES)
674 continue;
676 struct tree_node *best = NULL;
677 struct tree_node *best2 = NULL; // Second-best move.
678 struct tree_node *bestr = NULL; // best's best child.
679 struct tree_node *winner = NULL;
681 best = u->policy->choose(u->policy, ctx->t->root, b, color, resign);
682 if (best) best2 = u->policy->choose(u->policy, ctx->t->root, b, color, best->coord);
684 /* Possibly stop search early if it's no use to try on. */
685 int played = u->played_all + i - base_playouts;
686 if (best && uct_search_stop_early(u, ctx->t, b, ti, &stop, best, best2, played))
687 break;
689 /* Check against time settings. */
690 bool desired_done;
691 if (ti->dim == TD_WALLTIME) {
692 double elapsed = time_now() - ti->len.t.timer_start;
693 if (elapsed > stop.worst.time) break;
694 desired_done = elapsed > stop.desired.time;
696 } else { assert(ti->dim == TD_GAMES);
697 if (i > stop.worst.playouts) break;
698 desired_done = i > stop.desired.playouts;
701 /* We want to stop simulating, but are willing to keep trying
702 * if we aren't completely sure about the winner yet. */
703 if (desired_done) {
704 if (u->policy->winner && u->policy->evaluate) {
705 struct uct_descent descent = { .node = ctx->t->root };
706 u->policy->winner(u->policy, ctx->t, &descent);
707 winner = descent.node;
709 if (best)
710 bestr = u->policy->choose(u->policy, best, b, stone_other(color), resign);
711 if (!uct_search_keep_looking(u, ctx->t, b, ti, &stop, best, best2, bestr, winner, i))
712 break;
715 /* TODO: Early break if best->variance goes under threshold and we already
716 * have enough playouts (possibly thanks to book or to pondering)? */
718 /* If running as slave in the distributed engine,
719 * let the search continue in background. */
720 if (u->slave) {
721 *keep_looking = true;
722 break;
726 int games;
727 if (!u->slave) {
728 ctx = uct_search_stop();
729 games = ctx->games;
730 if (UDEBUGL(2)) tree_dump(t, u->dumpthres);
731 } else {
732 /* We can only return an estimate here. */
733 games = ctx->t->root->u.playouts - base_playouts;
735 if (UDEBUGL(2))
736 fprintf(stderr, "(avg score %f/%d value %f/%d)\n",
737 u->dynkomi->score.value, u->dynkomi->score.playouts,
738 u->dynkomi->value.value, u->dynkomi->value.playouts);
739 if (UDEBUGL(0))
740 uct_progress_status(u, t, color, games);
742 return games;
746 /* Start pondering background with @color to play. */
747 static void
748 uct_pondering_start(struct uct *u, struct board *b0, struct tree *t, enum stone color)
750 if (UDEBUGL(1))
751 fprintf(stderr, "Starting to ponder with color %s\n", stone2str(stone_other(color)));
752 u->pondering = true;
754 /* We need a local board copy to ponder upon. */
755 struct board *b = malloc2(sizeof(*b)); board_copy(b, b0);
757 /* *b0 did not have the genmove'd move played yet. */
758 struct move m = { t->root->coord, t->root_color };
759 int res = board_play(b, &m);
760 assert(res >= 0);
761 setup_dynkomi(u, b, stone_other(m.color));
763 /* Start MCTS manager thread "headless". */
764 uct_search_start(u, b, color, t);
767 /* uct_search_stop() frontend for the pondering (non-genmove) mode, and
768 * to stop the background search for a slave in the distributed engine. */
769 static void
770 uct_pondering_stop(struct uct *u)
772 if (!thread_manager_running)
773 return;
775 /* Stop the thread manager. */
776 struct spawn_ctx *ctx = uct_search_stop();
777 if (UDEBUGL(1)) {
778 if (u->pondering) fprintf(stderr, "(pondering) ");
779 uct_progress_status(u, ctx->t, ctx->color, ctx->games);
781 if (u->pondering) {
782 free(ctx->b);
783 u->pondering = false;
787 void
788 uct_search_setup(struct uct *u, struct board *b, enum stone color)
790 if (b->superko_violation) {
791 fprintf(stderr, "!!! WARNING: SUPERKO VIOLATION OCCURED BEFORE THIS MOVE\n");
792 fprintf(stderr, "Maybe you play with situational instead of positional superko?\n");
793 fprintf(stderr, "I'm going to ignore the violation, but note that I may miss\n");
794 fprintf(stderr, "some moves valid under this ruleset because of this.\n");
795 b->superko_violation = false;
798 uct_prepare_move(u, b, color);
800 assert(u->t);
801 u->my_color = color;
803 /* How to decide whether to use dynkomi in this game? Since we use
804 * pondering, it's not simple "who-to-play" matter. Decide based on
805 * the last genmove issued. */
806 u->t->use_extra_komi = !!(u->dynkomi_mask & color);
807 setup_dynkomi(u, b, color);
809 if (b->rules == RULES_JAPANESE)
810 u->territory_scoring = true;
812 /* Make pessimistic assumption about komi for Japanese rules to
813 * avoid losing by 0.5 when winning by 0.5 with Chinese rules.
814 * The rules usually give the same winner if the integer part of komi
815 * is odd so we adjust the komi only if it is even (for a board of
816 * odd size). We are not trying to get an exact evaluation for rare
817 * cases of seki. For details see http://home.snafu.de/jasiek/parity.html */
818 if (u->territory_scoring && (((int)floor(b->komi) + board_size(b)) & 1)) {
819 b->komi += (color == S_BLACK ? 1.0 : -1.0);
820 if (UDEBUGL(0))
821 fprintf(stderr, "Setting komi to %.1f assuming Japanese rules\n",
822 b->komi);
826 struct tree_node *
827 uct_search_best(struct uct *u, struct board *b, enum stone color,
828 bool pass_all_alive, int played_games, int base_playouts,
829 coord_t *best_coord)
831 /* Choose the best move from the tree. */
832 struct tree_node *best = u->policy->choose(u->policy, u->t->root, b, color, resign);
833 if (!best) {
834 *best_coord = pass;
835 return NULL;
837 *best_coord = best->coord;
838 if (UDEBUGL(1))
839 fprintf(stderr, "*** WINNER is %s (%d,%d) with score %1.4f (%d/%d:%d/%d games), extra komi %f\n",
840 coord2sstr(best->coord, b), coord_x(best->coord, b), coord_y(best->coord, b),
841 tree_node_get_value(u->t, 1, best->u.value), best->u.playouts,
842 u->t->root->u.playouts, u->t->root->u.playouts - base_playouts, played_games,
843 u->t->extra_komi);
845 /* Do not resign if we're so short of time that evaluation of best
846 * move is completely unreliable, we might be winning actually.
847 * In this case best is almost random but still better than resign.
848 * Also do not resign if we are getting bad results while actually
849 * giving away extra komi points (dynkomi). */
850 if (tree_node_get_value(u->t, 1, best->u.value) < u->resign_ratio
851 && !is_pass(best->coord) && best->u.playouts > GJ_MINGAMES
852 && u->t->extra_komi < 0.5 /* XXX we assume dynamic komi == we are black */) {
853 *best_coord = resign;
854 return NULL;
857 /* If the opponent just passed and we win counting, always
858 * pass as well. */
859 if (b->moves > 1 && is_pass(b->last_move.coord)) {
860 /* Make sure enough playouts are simulated. */
861 while (u->ownermap.playouts < GJ_MINGAMES)
862 uct_playout(u, b, color, u->t);
863 if (uct_pass_is_safe(u, b, color, u->pass_all_alive || pass_all_alive)) {
864 if (UDEBUGL(0))
865 fprintf(stderr, "<Will rather pass, looks safe enough.>\n");
866 *best_coord = pass;
867 return NULL;
871 return best;
874 /* Common part of uct_genmove() and uct_genmoves().
875 * Returns the best node, or NULL if *best_coord is pass or resign. */
876 static struct tree_node *
877 uct_bestmove(struct engine *e, struct board *b, struct time_info *ti, enum stone color,
878 bool pass_all_alive, bool *keep_looking, coord_t *best_coord)
880 double start_time = time_now();
881 struct uct *u = e->data;
883 uct_search_setup(u, b, color);
885 int base_playouts = u->t->root->u.playouts;
886 /* Start the Monte Carlo Tree Search! */
887 int played_games = uct_search(u, b, ti, color, u->t, keep_looking);
888 u->played_own += played_games;
890 if (UDEBUGL(2)) {
891 double time = time_now() - start_time + 0.000001; /* avoid divide by zero */
892 fprintf(stderr, "genmove in %0.2fs (%d games/s, %d games/s/thread)\n",
893 time, (int)(played_games/time), (int)(played_games/time/u->threads));
896 return uct_search_best(u, b, color, pass_all_alive, played_games, base_playouts, best_coord);
899 static coord_t *
900 uct_genmove(struct engine *e, struct board *b, struct time_info *ti, enum stone color, bool pass_all_alive)
902 struct uct *u = e->data;
903 uct_pondering_stop(u);
905 bool keep_looking;
906 coord_t best_coord;
907 struct tree_node *best;
908 best = uct_bestmove(e, b, ti, color, pass_all_alive, &keep_looking, &best_coord);
909 if (!best) {
910 reset_state(u);
911 return coord_copy(best_coord);
913 tree_promote_node(u->t, &best);
915 /* After a pass, pondering is harmful for two reasons:
916 * (i) We might keep pondering even when the game is over.
917 * Of course this is the case for opponent resign as well.
918 * (ii) More importantly, the ownermap will get skewed since
919 * the UCT will start cutting off any playouts. */
920 if (u->pondering_opt && !is_pass(best->coord)) {
921 uct_pondering_start(u, b, u->t, stone_other(color));
923 return coord_copy(best_coord);
927 bool
928 uct_genbook(struct engine *e, struct board *b, struct time_info *ti, enum stone color)
930 struct uct *u = e->data;
931 if (!u->t) uct_prepare_move(u, b, color);
932 assert(u->t);
934 if (ti->dim == TD_GAMES) {
935 /* Don't count in games that already went into the book. */
936 ti->len.games += u->t->root->u.playouts;
938 bool keep_looking;
939 uct_search(u, b, ti, color, u->t, &keep_looking);
941 assert(ti->dim == TD_GAMES);
942 tree_save(u->t, b, ti->len.games / 100);
944 return true;
947 void
948 uct_dumpbook(struct engine *e, struct board *b, enum stone color)
950 struct uct *u = e->data;
951 struct tree *t = tree_init(b, color, u->fast_alloc ? u->max_tree_size : 0, u->local_tree_aging);
952 tree_load(t, b);
953 tree_dump(t, 0);
954 tree_done(t);
958 struct uct *
959 uct_state_init(char *arg, struct board *b)
961 struct uct *u = calloc2(1, sizeof(struct uct));
962 bool using_elo = false;
964 u->debug_level = debug_level;
965 u->gamelen = MC_GAMELEN;
966 u->mercymin = 0;
967 u->expand_p = 2;
968 u->dumpthres = 1000;
969 u->playout_amaf = true;
970 u->playout_amaf_nakade = false;
971 u->amaf_prior = false;
972 u->max_tree_size = 3072ULL * 1048576;
974 u->dynkomi_mask = S_BLACK;
976 u->threads = 1;
977 u->thread_model = TM_TREEVL;
978 u->parallel_tree = true;
979 u->virtual_loss = true;
981 u->fuseki_end = 20; // max time at 361*20% = 72 moves (our 36th move, still 99 to play)
982 u->yose_start = 40; // (100-40-25)*361/100/2 = 63 moves still to play by us then
983 u->bestr_ratio = 0.02;
984 // 2.5 is clearly too much, but seems to compensate well for overly stern time allocations.
985 // TODO: Further tuning and experiments with better time allocation schemes.
986 u->best2_ratio = 2.5;
988 u->val_scale = 0.04; u->val_points = 40;
990 u->tenuki_d = 4;
991 u->local_tree_aging = 2;
993 if (arg) {
994 char *optspec, *next = arg;
995 while (*next) {
996 optspec = next;
997 next += strcspn(next, ",");
998 if (*next) { *next++ = 0; } else { *next = 0; }
1000 char *optname = optspec;
1001 char *optval = strchr(optspec, '=');
1002 if (optval) *optval++ = 0;
1004 if (!strcasecmp(optname, "debug")) {
1005 if (optval)
1006 u->debug_level = atoi(optval);
1007 else
1008 u->debug_level++;
1009 } else if (!strcasecmp(optname, "mercy") && optval) {
1010 /* Minimal difference of black/white captures
1011 * to stop playout - "Mercy Rule". Speeds up
1012 * hopeless playouts at the expense of some
1013 * accuracy. */
1014 u->mercymin = atoi(optval);
1015 } else if (!strcasecmp(optname, "gamelen") && optval) {
1016 u->gamelen = atoi(optval);
1017 } else if (!strcasecmp(optname, "expand_p") && optval) {
1018 u->expand_p = atoi(optval);
1019 } else if (!strcasecmp(optname, "dumpthres") && optval) {
1020 u->dumpthres = atoi(optval);
1021 } else if (!strcasecmp(optname, "best2_ratio") && optval) {
1022 /* If set, prolong simulating while
1023 * first_best/second_best playouts ratio
1024 * is less than best2_ratio. */
1025 u->best2_ratio = atof(optval);
1026 } else if (!strcasecmp(optname, "bestr_ratio") && optval) {
1027 /* If set, prolong simulating while
1028 * best,best_best_child values delta
1029 * is more than bestr_ratio. */
1030 u->bestr_ratio = atof(optval);
1031 } else if (!strcasecmp(optname, "playout_amaf")) {
1032 /* Whether to include random playout moves in
1033 * AMAF as well. (Otherwise, only tree moves
1034 * are included in AMAF. Of course makes sense
1035 * only in connection with an AMAF policy.) */
1036 /* with-without: 55.5% (+-4.1) */
1037 if (optval && *optval == '0')
1038 u->playout_amaf = false;
1039 else
1040 u->playout_amaf = true;
1041 } else if (!strcasecmp(optname, "playout_amaf_nakade")) {
1042 /* Whether to include nakade moves from playouts
1043 * in the AMAF statistics; this tends to nullify
1044 * the playout_amaf effect by adding too much
1045 * noise. */
1046 if (optval && *optval == '0')
1047 u->playout_amaf_nakade = false;
1048 else
1049 u->playout_amaf_nakade = true;
1050 } else if (!strcasecmp(optname, "playout_amaf_cutoff") && optval) {
1051 /* Keep only first N% of playout stage AMAF
1052 * information. */
1053 u->playout_amaf_cutoff = atoi(optval);
1054 } else if ((!strcasecmp(optname, "policy") || !strcasecmp(optname, "random_policy")) && optval) {
1055 char *policyarg = strchr(optval, ':');
1056 struct uct_policy **p = !strcasecmp(optname, "policy") ? &u->policy : &u->random_policy;
1057 if (policyarg)
1058 *policyarg++ = 0;
1059 if (!strcasecmp(optval, "ucb1")) {
1060 *p = policy_ucb1_init(u, policyarg);
1061 } else if (!strcasecmp(optval, "ucb1amaf")) {
1062 *p = policy_ucb1amaf_init(u, policyarg);
1063 } else {
1064 fprintf(stderr, "UCT: Invalid tree policy %s\n", optval);
1065 exit(1);
1067 } else if (!strcasecmp(optname, "playout") && optval) {
1068 char *playoutarg = strchr(optval, ':');
1069 if (playoutarg)
1070 *playoutarg++ = 0;
1071 if (!strcasecmp(optval, "moggy")) {
1072 u->playout = playout_moggy_init(playoutarg, b);
1073 } else if (!strcasecmp(optval, "light")) {
1074 u->playout = playout_light_init(playoutarg, b);
1075 } else if (!strcasecmp(optval, "elo")) {
1076 u->playout = playout_elo_init(playoutarg, b);
1077 using_elo = true;
1078 } else {
1079 fprintf(stderr, "UCT: Invalid playout policy %s\n", optval);
1080 exit(1);
1082 } else if (!strcasecmp(optname, "prior") && optval) {
1083 u->prior = uct_prior_init(optval, b);
1084 } else if (!strcasecmp(optname, "amaf_prior") && optval) {
1085 u->amaf_prior = atoi(optval);
1086 } else if (!strcasecmp(optname, "threads") && optval) {
1087 /* By default, Pachi will run with only single
1088 * tree search thread! */
1089 u->threads = atoi(optval);
1090 } else if (!strcasecmp(optname, "thread_model") && optval) {
1091 if (!strcasecmp(optval, "root")) {
1092 /* Root parallelization - each thread
1093 * does independent search, trees are
1094 * merged at the end. */
1095 u->thread_model = TM_ROOT;
1096 u->parallel_tree = false;
1097 u->virtual_loss = false;
1098 } else if (!strcasecmp(optval, "tree")) {
1099 /* Tree parallelization - all threads
1100 * grind on the same tree. */
1101 u->thread_model = TM_TREE;
1102 u->parallel_tree = true;
1103 u->virtual_loss = false;
1104 } else if (!strcasecmp(optval, "treevl")) {
1105 /* Tree parallelization, but also
1106 * with virtual losses - this discou-
1107 * rages most threads choosing the
1108 * same tree branches to read. */
1109 u->thread_model = TM_TREEVL;
1110 u->parallel_tree = true;
1111 u->virtual_loss = true;
1112 } else {
1113 fprintf(stderr, "UCT: Invalid thread model %s\n", optval);
1114 exit(1);
1116 } else if (!strcasecmp(optname, "pondering")) {
1117 /* Keep searching even during opponent's turn. */
1118 u->pondering_opt = !optval || atoi(optval);
1119 } else if (!strcasecmp(optname, "fuseki_end") && optval) {
1120 /* At the very beginning it's not worth thinking
1121 * too long because the playout evaluations are
1122 * very noisy. So gradually increase the thinking
1123 * time up to maximum when fuseki_end percent
1124 * of the board has been played.
1125 * This only applies if we are not in byoyomi. */
1126 u->fuseki_end = atoi(optval);
1127 } else if (!strcasecmp(optname, "yose_start") && optval) {
1128 /* When yose_start percent of the board has been
1129 * played, or if we are in byoyomi, stop spending
1130 * more time and spread the remaining time
1131 * uniformly.
1132 * Between fuseki_end and yose_start, we spend
1133 * a constant proportion of the remaining time
1134 * on each move. (yose_start should actually
1135 * be much earlier than when real yose start,
1136 * but "yose" is a good short name to convey
1137 * the idea.) */
1138 u->yose_start = atoi(optval);
1139 } else if (!strcasecmp(optname, "force_seed") && optval) {
1140 u->force_seed = atoi(optval);
1141 } else if (!strcasecmp(optname, "no_book")) {
1142 u->no_book = true;
1143 } else if (!strcasecmp(optname, "dynkomi") && optval) {
1144 /* Dynamic komi approach; there are multiple
1145 * ways to adjust komi dynamically throughout
1146 * play. We currently support two: */
1147 char *dynkomiarg = strchr(optval, ':');
1148 if (dynkomiarg)
1149 *dynkomiarg++ = 0;
1150 if (!strcasecmp(optval, "none")) {
1151 u->dynkomi = uct_dynkomi_init_none(u, dynkomiarg, b);
1152 } else if (!strcasecmp(optval, "linear")) {
1153 u->dynkomi = uct_dynkomi_init_linear(u, dynkomiarg, b);
1154 } else if (!strcasecmp(optval, "adaptive")) {
1155 u->dynkomi = uct_dynkomi_init_adaptive(u, dynkomiarg, b);
1156 } else {
1157 fprintf(stderr, "UCT: Invalid dynkomi mode %s\n", optval);
1158 exit(1);
1160 } else if (!strcasecmp(optname, "dynkomi_mask") && optval) {
1161 /* Bitmask of colors the player must be
1162 * for dynkomi be applied; you may want
1163 * to use dynkomi_mask=3 to allow dynkomi
1164 * even in games where Pachi is white. */
1165 u->dynkomi_mask = atoi(optval);
1166 } else if (!strcasecmp(optname, "dynkomi_interval") && optval) {
1167 /* If non-zero, re-adjust dynamic komi
1168 * throughout a single genmove reading,
1169 * roughly every N simulations. */
1170 /* XXX: Does not work with tree
1171 * parallelization. */
1172 u->dynkomi_interval = atoi(optval);
1173 } else if (!strcasecmp(optname, "val_scale") && optval) {
1174 /* How much of the game result value should be
1175 * influenced by win size. Zero means it isn't. */
1176 u->val_scale = atof(optval);
1177 } else if (!strcasecmp(optname, "val_points") && optval) {
1178 /* Maximum size of win to be scaled into game
1179 * result value. Zero means boardsize^2. */
1180 u->val_points = atoi(optval) * 2; // result values are doubled
1181 } else if (!strcasecmp(optname, "val_extra")) {
1182 /* If false, the score coefficient will be simply
1183 * added to the value, instead of scaling the result
1184 * coefficient because of it. */
1185 u->val_extra = !optval || atoi(optval);
1186 } else if (!strcasecmp(optname, "local_tree") && optval) {
1187 /* Whether to bias exploration by local tree values
1188 * (must be supported by the used policy).
1189 * 0: Don't.
1190 * 1: Do, value = result.
1191 * Try to temper the result:
1192 * 2: Do, value = 0.5+(result-expected)/2.
1193 * 3: Do, value = 0.5+bzz((result-expected)^2).
1194 * 4: Do, value = 0.5+sqrt(result-expected)/2. */
1195 u->local_tree = atoi(optval);
1196 } else if (!strcasecmp(optname, "tenuki_d") && optval) {
1197 /* Tenuki distance at which to break the local tree. */
1198 u->tenuki_d = atoi(optval);
1199 if (u->tenuki_d > TREE_NODE_D_MAX + 1) {
1200 fprintf(stderr, "uct: tenuki_d must not be larger than TREE_NODE_D_MAX+1 %d\n", TREE_NODE_D_MAX + 1);
1201 exit(1);
1203 } else if (!strcasecmp(optname, "local_tree_aging") && optval) {
1204 /* How much to reduce local tree values between moves. */
1205 u->local_tree_aging = atof(optval);
1206 } else if (!strcasecmp(optname, "local_tree_allseq")) {
1207 /* By default, only complete sequences are stored
1208 * in the local tree. If this is on, also
1209 * subsequences starting at each move are stored. */
1210 u->local_tree_allseq = !optval || atoi(optval);
1211 } else if (!strcasecmp(optname, "local_tree_playout")) {
1212 /* Whether to adjust ELO playout probability
1213 * distributions according to matched localtree
1214 * information. */
1215 u->local_tree_playout = !optval || atoi(optval);
1216 } else if (!strcasecmp(optname, "local_tree_pseqroot")) {
1217 /* By default, when we have no sequence move
1218 * to suggest in-playout, we give up. If this
1219 * is on, we make probability distribution from
1220 * sequences first moves instead. */
1221 u->local_tree_pseqroot = !optval || atoi(optval);
1222 } else if (!strcasecmp(optname, "pass_all_alive")) {
1223 /* Whether to consider all stones alive at the game
1224 * end instead of marking dead groupd. */
1225 u->pass_all_alive = !optval || atoi(optval);
1226 } else if (!strcasecmp(optname, "territory_scoring")) {
1227 /* Use territory scoring (default is area scoring).
1228 * An explicit kgs-rules command overrides this. */
1229 u->territory_scoring = !optval || atoi(optval);
1230 } else if (!strcasecmp(optname, "random_policy_chance") && optval) {
1231 /* If specified (N), with probability 1/N, random_policy policy
1232 * descend is used instead of main policy descend; useful
1233 * if specified policy (e.g. UCB1AMAF) can make unduly biased
1234 * choices sometimes, you can fall back to e.g.
1235 * random_policy=UCB1. */
1236 u->random_policy_chance = atoi(optval);
1237 } else if (!strcasecmp(optname, "max_tree_size") && optval) {
1238 /* Maximum amount of memory [MiB] consumed by the move tree.
1239 * For fast_alloc it includes the temp tree used for pruning.
1240 * Default is 3072 (3 GiB). Note that if you use TM_ROOT,
1241 * this limits size of only one of the trees, not all of them
1242 * together. */
1243 u->max_tree_size = atol(optval) * 1048576;
1244 } else if (!strcasecmp(optname, "fast_alloc")) {
1245 u->fast_alloc = !optval || atoi(optval);
1246 } else if (!strcasecmp(optname, "slave")) {
1247 /* Act as slave for the distributed engine. */
1248 u->slave = !optval || atoi(optval);
1249 } else if (!strcasecmp(optname, "banner") && optval) {
1250 /* Additional banner string. This must come as the
1251 * last engine parameter. */
1252 if (*next) *--next = ',';
1253 u->banner = strdup(optval);
1254 break;
1255 } else {
1256 fprintf(stderr, "uct: Invalid engine argument %s or missing value\n", optname);
1257 exit(1);
1262 u->resign_ratio = 0.2; /* Resign when most games are lost. */
1263 u->loss_threshold = 0.85; /* Stop reading if after at least 2000 playouts this is best value. */
1264 if (!u->policy)
1265 u->policy = policy_ucb1amaf_init(u, NULL);
1267 if (!!u->random_policy_chance ^ !!u->random_policy) {
1268 fprintf(stderr, "uct: Only one of random_policy and random_policy_chance is set\n");
1269 exit(1);
1272 if (!u->local_tree) {
1273 /* No ltree aging. */
1274 u->local_tree_aging = 1.0f;
1276 if (!using_elo)
1277 u->local_tree_playout = false;
1279 if (u->fast_alloc && !u->parallel_tree) {
1280 fprintf(stderr, "fast_alloc not supported with root parallelization.\n");
1281 exit(1);
1283 if (u->fast_alloc)
1284 u->max_tree_size = (100ULL * u->max_tree_size) / (100 + MIN_FREE_MEM_PERCENT);
1286 if (!u->prior)
1287 u->prior = uct_prior_init(NULL, b);
1289 if (!u->playout)
1290 u->playout = playout_moggy_init(NULL, b);
1291 u->playout->debug_level = u->debug_level;
1293 u->ownermap.map = malloc2(board_size2(b) * sizeof(u->ownermap.map[0]));
1294 u->stats = malloc2(board_size2(b) * sizeof(u->stats[0]));
1296 if (!u->dynkomi)
1297 u->dynkomi = uct_dynkomi_init_linear(u, NULL, b);
1299 /* Some things remain uninitialized for now - the opening book
1300 * is not loaded and the tree not set up. */
1301 /* This will be initialized in setup_state() at the first move
1302 * received/requested. This is because right now we are not aware
1303 * about any komi or handicap setup and such. */
1305 return u;
1308 struct engine *
1309 engine_uct_init(char *arg, struct board *b)
1311 struct uct *u = uct_state_init(arg, b);
1312 struct engine *e = calloc2(1, sizeof(struct engine));
1313 e->name = "UCT Engine";
1314 e->printhook = uct_printhook_ownermap;
1315 e->notify_play = uct_notify_play;
1316 e->chat = uct_chat;
1317 e->genmove = uct_genmove;
1318 e->genmoves = uct_genmoves;
1319 e->dead_group_list = uct_dead_group_list;
1320 e->done = uct_done;
1321 e->data = u;
1322 if (u->slave)
1323 e->notify = uct_notify;
1325 const char banner[] = "I'm playing UCT. When I'm losing, I will resign, "
1326 "if I think I win, I play until you pass. "
1327 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
1328 if (!u->banner) u->banner = "";
1329 e->comment = malloc2(sizeof(banner) + strlen(u->banner) + 1);
1330 sprintf(e->comment, "%s %s", banner, u->banner);
1332 return e;