Distributed engine: move time parsing to uct_genmoves to reduce
[pachi.git] / uct / uct.c
blob658d71e8e72b733a9c46eccb47620cf20b8844c2
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 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 u->gtp_id = id;
167 return reply_disabled(id) ? P_NOREPLY : P_OK;
170 static char *
171 uct_printhook_ownermap(struct board *board, coord_t c, char *s, char *end)
173 struct uct *u = board->es;
174 assert(u);
175 const char chr[] = ":XO,"; // dame, black, white, unclear
176 const char chm[] = ":xo,";
177 char ch = chr[board_ownermap_judge_point(&u->ownermap, c, GJ_THRES)];
178 if (ch == ',') { // less precise estimate then?
179 ch = chm[board_ownermap_judge_point(&u->ownermap, c, 0.67)];
181 s += snprintf(s, end - s, "%c ", ch);
182 return s;
185 static char *
186 uct_notify_play(struct engine *e, struct board *b, struct move *m)
188 struct uct *u = e->data;
189 if (!u->t) {
190 /* No state, create one - this is probably game beginning
191 * and we need to load the opening book right now. */
192 prepare_move(e, b, m->color);
193 assert(u->t);
196 /* Stop pondering, required by tree_promote_at() */
197 uct_pondering_stop(u);
199 if (is_resign(m->coord)) {
200 /* Reset state. */
201 reset_state(u);
202 return NULL;
205 /* Promote node of the appropriate move to the tree root. */
206 assert(u->t->root);
207 if (!tree_promote_at(u->t, b, m->coord)) {
208 if (UDEBUGL(0))
209 fprintf(stderr, "Warning: Cannot promote move node! Several play commands in row?\n");
210 reset_state(u);
211 return NULL;
214 /* If we are a slave in a distributed engine, start pondering once
215 * we know which move we actually played. See uct_genmove() about
216 * the check for pass. */
217 if (u->pondering_opt && u->slave && m->color == u->my_color && !is_pass(m->coord))
218 uct_pondering_start(u, b, u->t, stone_other(m->color));
220 return NULL;
223 static char *
224 uct_chat(struct engine *e, struct board *b, char *cmd)
226 struct uct *u = e->data;
227 static char reply[1024];
229 cmd += strspn(cmd, " \n\t");
230 if (!strncasecmp(cmd, "winrate", 7)) {
231 if (!u->t)
232 return "no game context (yet?)";
233 enum stone color = u->t->root_color;
234 struct tree_node *n = u->t->root;
235 snprintf(reply, 1024, "In %d playouts at %d threads, %s %s can win with %.2f%% probability",
236 n->u.playouts, u->threads, stone2str(color), coord2sstr(n->coord, b),
237 tree_node_get_value(u->t, -1, n->u.value) * 100);
238 if (u->t->use_extra_komi && abs(u->t->extra_komi) >= 0.5) {
239 sprintf(reply + strlen(reply), ", while self-imposing extra komi %.1f",
240 u->t->extra_komi);
242 strcat(reply, ".");
243 return reply;
245 return NULL;
248 static void
249 uct_dead_group_list(struct engine *e, struct board *b, struct move_queue *mq)
251 struct uct *u = e->data;
253 /* This means the game is probably over, no use pondering on. */
254 uct_pondering_stop(u);
256 if (u->pass_all_alive)
257 return; // no dead groups
259 bool mock_state = false;
261 if (!u->t) {
262 /* No state, but we cannot just back out - we might
263 * have passed earlier, only assuming some stones are
264 * dead, and then re-connected, only to lose counting
265 * when all stones are assumed alive. */
266 /* Mock up some state and seed the ownermap by few
267 * simulations. */
268 prepare_move(e, b, S_BLACK); assert(u->t);
269 for (int i = 0; i < GJ_MINGAMES; i++)
270 uct_playout(u, b, S_BLACK, u->t);
271 mock_state = true;
274 dead_group_list(u, b, mq);
276 if (mock_state) {
277 /* Clean up the mock state in case we will receive
278 * a genmove; we could get a non-alternating-move
279 * error from prepare_move() in that case otherwise. */
280 reset_state(u);
284 static void
285 playout_policy_done(struct playout_policy *p)
287 if (p->done) p->done(p);
288 if (p->data) free(p->data);
289 free(p);
292 static void
293 uct_done(struct engine *e)
295 /* This is called on engine reset, especially when clear_board
296 * is received and new game should begin. */
297 struct uct *u = e->data;
298 uct_pondering_stop(u);
299 if (u->t) reset_state(u);
300 free(u->ownermap.map);
302 free(u->policy);
303 free(u->random_policy);
304 playout_policy_done(u->playout);
305 uct_prior_done(u->prior);
309 /* Pachi threading structure (if uct_playouts_parallel() is used):
311 * main thread
312 * | main(), GTP communication, ...
313 * | starts and stops the search managed by thread_manager
315 * thread_manager
316 * | spawns and collects worker threads
318 * worker0
319 * worker1
320 * ...
321 * workerK
322 * uct_playouts() loop, doing descend-playout until uct_halt
324 * Another way to look at it is by functions (lines denote thread boundaries):
326 * | uct_genmove()
327 * | uct_search() (uct_search_start() .. uct_search_stop())
328 * | -----------------------
329 * | spawn_thread_manager()
330 * | -----------------------
331 * | spawn_worker()
332 * V uct_playouts() */
334 /* Set in thread manager in case the workers should stop. */
335 volatile sig_atomic_t uct_halt = 0;
336 /* ID of the running worker thread. */
337 __thread int thread_id = -1;
338 /* ID of the thread manager. */
339 static pthread_t thread_manager;
340 static bool thread_manager_running;
342 static pthread_mutex_t finish_mutex = PTHREAD_MUTEX_INITIALIZER;
343 static pthread_cond_t finish_cond = PTHREAD_COND_INITIALIZER;
344 static volatile int finish_thread;
345 static pthread_mutex_t finish_serializer = PTHREAD_MUTEX_INITIALIZER;
347 struct spawn_ctx {
348 int tid;
349 struct uct *u;
350 struct board *b;
351 enum stone color;
352 struct tree *t;
353 unsigned long seed;
354 int games;
357 static void *
358 spawn_worker(void *ctx_)
360 struct spawn_ctx *ctx = ctx_;
361 /* Setup */
362 fast_srandom(ctx->seed);
363 thread_id = ctx->tid;
364 /* Run */
365 ctx->games = uct_playouts(ctx->u, ctx->b, ctx->color, ctx->t);
366 /* Finish */
367 pthread_mutex_lock(&finish_serializer);
368 pthread_mutex_lock(&finish_mutex);
369 finish_thread = ctx->tid;
370 pthread_cond_signal(&finish_cond);
371 pthread_mutex_unlock(&finish_mutex);
372 return ctx;
375 /* Thread manager, controlling worker threads. It must be called with
376 * finish_mutex lock held, but it will unlock it itself before exiting;
377 * this is necessary to be completely deadlock-free. */
378 /* The finish_cond can be signalled for it to stop; in that case,
379 * the caller should set finish_thread = -1. */
380 /* After it is started, it will update mctx->t to point at some tree
381 * used for the actual search (matters only for TM_ROOT), on return
382 * it will set mctx->games to the number of performed simulations. */
383 static void *
384 spawn_thread_manager(void *ctx_)
386 /* In thread_manager, we use only some of the ctx fields. */
387 struct spawn_ctx *mctx = ctx_;
388 struct uct *u = mctx->u;
389 struct tree *t = mctx->t;
390 bool shared_tree = u->parallel_tree;
391 fast_srandom(mctx->seed);
393 int played_games = 0;
394 pthread_t threads[u->threads];
395 int joined = 0;
397 uct_halt = 0;
399 /* Garbage collect the tree by preference when pondering. */
400 if (u->pondering && t->nodes && t->nodes_size > t->max_tree_size/2) {
401 unsigned long temp_size = (MIN_FREE_MEM_PERCENT * t->max_tree_size) / 100;
402 t->root = tree_garbage_collect(t, temp_size, t->root);
405 /* Spawn threads... */
406 for (int ti = 0; ti < u->threads; ti++) {
407 struct spawn_ctx *ctx = malloc(sizeof(*ctx));
408 ctx->u = u; ctx->b = mctx->b; ctx->color = mctx->color;
409 mctx->t = ctx->t = shared_tree ? t : tree_copy(t);
410 ctx->tid = ti; ctx->seed = fast_random(65536) + ti;
411 pthread_create(&threads[ti], NULL, spawn_worker, ctx);
412 if (UDEBUGL(3))
413 fprintf(stderr, "Spawned worker %d\n", ti);
416 /* ...and collect them back: */
417 while (joined < u->threads) {
418 /* Wait for some thread to finish... */
419 pthread_cond_wait(&finish_cond, &finish_mutex);
420 if (finish_thread < 0) {
421 /* Stop-by-caller. Tell the workers to wrap up. */
422 uct_halt = 1;
423 continue;
425 /* ...and gather its remnants. */
426 struct spawn_ctx *ctx;
427 pthread_join(threads[finish_thread], (void **) &ctx);
428 played_games += ctx->games;
429 joined++;
430 if (!shared_tree) {
431 if (ctx->t == mctx->t) mctx->t = t;
432 tree_merge(t, ctx->t);
433 tree_done(ctx->t);
435 free(ctx);
436 if (UDEBUGL(3))
437 fprintf(stderr, "Joined worker %d\n", finish_thread);
438 pthread_mutex_unlock(&finish_serializer);
441 pthread_mutex_unlock(&finish_mutex);
443 if (!shared_tree)
444 tree_normalize(mctx->t, u->threads);
446 mctx->games = played_games;
447 return mctx;
450 static struct spawn_ctx *
451 uct_search_start(struct uct *u, struct board *b, enum stone color, struct tree *t)
453 assert(u->threads > 0);
454 assert(!thread_manager_running);
456 struct spawn_ctx ctx = { .u = u, .b = b, .color = color, .t = t, .seed = fast_random(65536) };
457 static struct spawn_ctx mctx; mctx = ctx;
458 pthread_mutex_lock(&finish_mutex);
459 pthread_create(&thread_manager, NULL, spawn_thread_manager, &mctx);
460 thread_manager_running = true;
461 return &mctx;
464 static struct spawn_ctx *
465 uct_search_stop(void)
467 assert(thread_manager_running);
469 /* Signal thread manager to stop the workers. */
470 pthread_mutex_lock(&finish_mutex);
471 finish_thread = -1;
472 pthread_cond_signal(&finish_cond);
473 pthread_mutex_unlock(&finish_mutex);
475 /* Collect the thread manager. */
476 struct spawn_ctx *pctx;
477 thread_manager_running = false;
478 pthread_join(thread_manager, (void **) &pctx);
479 return pctx;
483 /* Determine whether we should terminate the search early. */
484 static bool
485 uct_search_stop_early(struct uct *u, struct tree *t, struct board *b,
486 struct time_info *ti, struct time_stop *stop,
487 struct tree_node *best, struct tree_node *best2,
488 int base_playouts, int i)
490 /* Always use at least half the desired time. It is silly
491 * to lose a won game because we played a bad move in 0.1s. */
492 double elapsed = 0;
493 if (ti->dim == TD_WALLTIME) {
494 elapsed = time_now() - ti->len.t.timer_start;
495 if (elapsed < 0.5 * stop->desired.time) return false;
498 /* Early break in won situation. */
499 if (best->u.playouts >= 2000 && tree_node_get_value(t, 1, best->u.value) >= u->loss_threshold)
500 return true;
501 /* Earlier break in super-won situation. */
502 if (best->u.playouts >= 500 && tree_node_get_value(t, 1, best->u.value) >= 0.95)
503 return true;
505 /* Break early if we estimate the second-best move cannot
506 * catch up in assigned time anymore. We use all our time
507 * if we are in byoyomi with single stone remaining in our
508 * period, however - it's better to pre-ponder. */
509 bool time_indulgent = (!ti->len.t.main_time && ti->len.t.byoyomi_stones == 1);
510 if (best2 && ti->dim == TD_WALLTIME && !time_indulgent) {
511 double remaining = stop->worst.time - elapsed;
512 double pps = ((double)i - base_playouts) / elapsed;
513 double estplayouts = remaining * pps + PLAYOUT_DELTA_SAFEMARGIN;
514 if (best->u.playouts > best2->u.playouts + estplayouts) {
515 if (UDEBUGL(2))
516 fprintf(stderr, "Early stop, result cannot change: "
517 "best %d, best2 %d, estimated %f simulations to go\n",
518 best->u.playouts, best2->u.playouts, estplayouts);
519 return true;
523 return false;
526 /* Determine whether we should terminate the search later than expected. */
527 static bool
528 uct_search_keep_looking(struct uct *u, struct tree *t, struct board *b,
529 struct time_info *ti, struct time_stop *stop,
530 struct tree_node *best, struct tree_node *best2,
531 struct tree_node *bestr, struct tree_node *winner, int i)
533 if (!best) {
534 if (UDEBUGL(2))
535 fprintf(stderr, "Did not find best move, still trying...\n");
536 return true;
539 /* Do not waste time if we are winning. Spend up to worst time if
540 * we are unsure, but only desired time if we are sure of winning. */
541 float beta = 2 * (tree_node_get_value(t, 1, best->u.value) - 0.5);
542 if (ti->dim == TD_WALLTIME && beta > 0) {
543 double good_enough = stop->desired.time * beta + stop->worst.time * (1 - beta);
544 double elapsed = time_now() - ti->len.t.timer_start;
545 if (elapsed > good_enough) return false;
548 if (u->best2_ratio > 0) {
549 /* Check best/best2 simulations ratio. If the
550 * two best moves give very similar results,
551 * keep simulating. */
552 if (best2 && best2->u.playouts
553 && (double)best->u.playouts / best2->u.playouts < u->best2_ratio) {
554 if (UDEBUGL(2))
555 fprintf(stderr, "Best2 ratio %f < threshold %f\n",
556 (double)best->u.playouts / best2->u.playouts,
557 u->best2_ratio);
558 return true;
562 if (u->bestr_ratio > 0) {
563 /* Check best, best_best value difference. If the best move
564 * and its best child do not give similar enough results,
565 * keep simulating. */
566 if (bestr && bestr->u.playouts
567 && fabs((double)best->u.value - bestr->u.value) > u->bestr_ratio) {
568 if (UDEBUGL(2))
569 fprintf(stderr, "Bestr delta %f > threshold %f\n",
570 fabs((double)best->u.value - bestr->u.value),
571 u->bestr_ratio);
572 return true;
576 if (winner && winner != best) {
577 /* Keep simulating if best explored
578 * does not have also highest value. */
579 if (UDEBUGL(2))
580 fprintf(stderr, "[%d] best %3s [%d] %f != winner %3s [%d] %f\n", i,
581 coord2sstr(best->coord, t->board),
582 best->u.playouts, tree_node_get_value(t, 1, best->u.value),
583 coord2sstr(winner->coord, t->board),
584 winner->u.playouts, tree_node_get_value(t, 1, winner->u.value));
585 return true;
588 /* No reason to keep simulating, bye. */
589 return false;
592 /* Run time-limited MCTS search on foreground. */
593 static int
594 uct_search(struct uct *u, struct board *b, struct time_info *ti, enum stone color, struct tree *t)
596 int base_playouts = u->t->root->u.playouts;
597 if (UDEBUGL(2) && base_playouts > 0)
598 fprintf(stderr, "<pre-simulated %d games skipped>\n", base_playouts);
600 /* Set up time conditions. */
601 if (ti->period == TT_NULL) *ti = default_ti;
602 struct time_stop stop;
603 time_stop_conditions(ti, b, u->fuseki_end, u->yose_start, &stop);
605 /* Number of last dynkomi adjustment. */
606 int last_dynkomi = t->root->u.playouts;
607 /* Number of last game with progress print. */
608 int last_print = t->root->u.playouts;
609 /* Number of simulations to wait before next print. */
610 int print_interval = TREE_SIMPROGRESS_INTERVAL * (u->thread_model == TM_ROOT ? 1 : u->threads);
611 /* Printed notification about full memory? */
612 bool print_fullmem = false;
613 /* Absolute time of last distributed stats update. */
614 double last_stats_sent = time_now();
615 /* Interval between distributed stats updates. */
616 double stats_interval = STATS_SEND_INTERVAL;
618 struct spawn_ctx *ctx = uct_search_start(u, b, color, t);
620 /* The search tree is ctx->t. This is normally == t, but in case of
621 * TM_ROOT, it is one of the trees belonging to the independent
622 * workers. It is important to reference ctx->t directly since the
623 * thread manager will swap the tree pointer asynchronously. */
624 /* XXX: This means TM_ROOT support is suboptimal since single stalled
625 * thread can stall the others in case of limiting the search by game
626 * count. However, TM_ROOT just does not deserve any more extra code
627 * right now. */
629 struct tree_node *best = NULL;
630 struct tree_node *best2 = NULL; // Second-best move.
631 struct tree_node *bestr = NULL; // best's best child.
632 struct tree_node *winner = NULL;
634 double busywait_interval = TREE_BUSYWAIT_INTERVAL;
636 /* Now, just periodically poll the search tree. */
637 while (1) {
638 time_sleep(busywait_interval);
639 /* busywait_interval should never be less than desired time, or the
640 * time control is broken. But if it happens to be less, we still search
641 * at least 100ms otherwise the move is completely random. */
643 int i = ctx->t->root->u.playouts;
645 /* Adjust dynkomi? */
646 if (ctx->t->use_extra_komi && u->dynkomi->permove
647 && u->dynkomi_interval
648 && i > last_dynkomi + u->dynkomi_interval) {
649 last_dynkomi += u->dynkomi_interval;
650 float old_dynkomi = ctx->t->extra_komi;
651 ctx->t->extra_komi = u->dynkomi->permove(u->dynkomi, b, ctx->t);
652 if (UDEBUGL(3) && old_dynkomi != ctx->t->extra_komi)
653 fprintf(stderr, "dynkomi adjusted (%f -> %f)\n", old_dynkomi, ctx->t->extra_komi);
656 /* Print progress? */
657 if (i - last_print > print_interval) {
658 last_print += print_interval; // keep the numbers tidy
659 uct_progress_status(u, ctx->t, color, last_print);
661 if (!print_fullmem && ctx->t->nodes_size > u->max_tree_size) {
662 if (UDEBUGL(2))
663 fprintf(stderr, "memory limit hit (%lu > %lu)\n", ctx->t->nodes_size, u->max_tree_size);
664 print_fullmem = true;
667 /* Never consider stopping if we played too few simulations.
668 * Maybe we risk losing on time when playing in super-extreme
669 * time pressure but the tree is going to be just too messed
670 * up otherwise - we might even play invalid suicides or pass
671 * when we mustn't. */
672 if (i < GJ_MINGAMES)
673 continue;
675 best = u->policy->choose(u->policy, ctx->t->root, b, color, resign);
676 if (best) best2 = u->policy->choose(u->policy, ctx->t->root, b, color, best->coord);
678 /* Possibly stop search early if it's no use to try on. */
679 if (best && uct_search_stop_early(u, ctx->t, b, ti, &stop, best, best2, base_playouts, i))
680 break;
682 /* Check against time settings. */
683 bool desired_done = false;
684 double now = time_now();
685 if (ti->dim == TD_WALLTIME) {
686 double elapsed = now - ti->len.t.timer_start;
687 if (elapsed > stop.worst.time) break;
688 desired_done = elapsed > stop.desired.time;
689 if (stats_interval < 0.1 * stop.desired.time)
690 stats_interval = 0.1 * stop.desired.time;
692 } else { assert(ti->dim == TD_GAMES);
693 if (i > stop.worst.playouts) break;
694 desired_done = i > stop.desired.playouts;
697 /* We want to stop simulating, but are willing to keep trying
698 * if we aren't completely sure about the winner yet. */
699 if (desired_done) {
700 if (u->policy->winner && u->policy->evaluate) {
701 struct uct_descent descent = { .node = ctx->t->root };
702 u->policy->winner(u->policy, ctx->t, &descent);
703 winner = descent.node;
705 if (best)
706 bestr = u->policy->choose(u->policy, best, b, stone_other(color), resign);
707 if (!uct_search_keep_looking(u, ctx->t, b, ti, &stop, best, best2, bestr, winner, i))
708 break;
711 /* TODO: Early break if best->variance goes under threshold and we already
712 * have enough playouts (possibly thanks to book or to pondering)? */
714 /* Send new stats for the distributed engine.
715 * End with #\n (not \n\n) to indicate a temporary result. */
716 if (u->slave && now - last_stats_sent > stats_interval) {
717 printf("=%d %s\n#\n", u->gtp_id, uct_getstats(u, b, NULL));
718 fflush(stdout);
719 last_stats_sent = now;
723 ctx = uct_search_stop();
725 if (UDEBUGL(2))
726 tree_dump(t, u->dumpthres);
727 if (UDEBUGL(0))
728 uct_progress_status(u, t, color, ctx->games);
730 return ctx->games;
734 /* Start pondering background with @color to play. */
735 static void
736 uct_pondering_start(struct uct *u, struct board *b0, struct tree *t, enum stone color)
738 if (UDEBUGL(1))
739 fprintf(stderr, "Starting to ponder with color %s\n", stone2str(stone_other(color)));
740 u->pondering = true;
742 /* We need a local board copy to ponder upon. */
743 struct board *b = malloc(sizeof(*b)); board_copy(b, b0);
745 /* *b0 did not have the genmove'd move played yet. */
746 struct move m = { t->root->coord, t->root_color };
747 int res = board_play(b, &m);
748 assert(res >= 0);
749 setup_dynkomi(u, b, stone_other(m.color));
751 /* Start MCTS manager thread "headless". */
752 uct_search_start(u, b, color, t);
755 /* uct_search_stop() frontend for the pondering (non-genmove) mode. */
756 static void
757 uct_pondering_stop(struct uct *u)
759 u->pondering = false;
760 if (!thread_manager_running)
761 return;
763 /* Stop the thread manager. */
764 struct spawn_ctx *ctx = uct_search_stop();
765 if (UDEBUGL(1)) {
766 fprintf(stderr, "(pondering) ");
767 uct_progress_status(u, ctx->t, ctx->color, ctx->games);
769 free(ctx->b);
773 static coord_t *
774 uct_genmove(struct engine *e, struct board *b, struct time_info *ti, enum stone color, bool pass_all_alive)
776 double start_time = time_now();
777 struct uct *u = e->data;
779 if (b->superko_violation) {
780 fprintf(stderr, "!!! WARNING: SUPERKO VIOLATION OCCURED BEFORE THIS MOVE\n");
781 fprintf(stderr, "Maybe you play with situational instead of positional superko?\n");
782 fprintf(stderr, "I'm going to ignore the violation, but note that I may miss\n");
783 fprintf(stderr, "some moves valid under this ruleset because of this.\n");
784 b->superko_violation = false;
787 /* Seed the tree. */
788 uct_pondering_stop(u);
789 prepare_move(e, b, color);
790 assert(u->t);
791 u->my_color = color;
793 /* How to decide whether to use dynkomi in this game? Since we use
794 * pondering, it's not simple "who-to-play" matter. Decide based on
795 * the last genmove issued. */
796 u->t->use_extra_komi = !!(u->dynkomi_mask & color);
797 setup_dynkomi(u, b, color);
799 if (b->rules == RULES_JAPANESE)
800 u->territory_scoring = true;
802 /* Make pessimistic assumption about komi for Japanese rules to
803 * avoid losing by 0.5 when winning by 0.5 with Chinese rules.
804 * The rules usually give the same winner if the integer part of komi
805 * is odd so we adjust the komi only if it is even (for a board of
806 * odd size). We are not trying to get an exact evaluation for rare
807 * cases of seki. For details see http://home.snafu.de/jasiek/parity.html */
808 if (u->territory_scoring && (((int)floor(b->komi) + board_size(b)) & 1)) {
809 b->komi += (color == S_BLACK ? 1.0 : -1.0);
810 if (UDEBUGL(0))
811 fprintf(stderr, "Setting komi to %.1f assuming Japanese rules\n",
812 b->komi);
815 int base_playouts = u->t->root->u.playouts;
816 /* Perform the Monte Carlo Tree Search! */
817 int played_games = uct_search(u, b, ti, color, u->t);
819 /* Choose the best move from the tree. */
820 struct tree_node *best = u->policy->choose(u->policy, u->t->root, b, color, resign);
821 if (!best) {
822 if (!u->slave) reset_state(u);
823 return coord_copy(pass);
825 if (UDEBUGL(1))
826 fprintf(stderr, "*** WINNER is %s (%d,%d) with score %1.4f (%d/%d:%d/%d games), extra komi %f\n",
827 coord2sstr(best->coord, b), coord_x(best->coord, b), coord_y(best->coord, b),
828 tree_node_get_value(u->t, 1, best->u.value), best->u.playouts,
829 u->t->root->u.playouts, u->t->root->u.playouts - base_playouts, played_games,
830 u->t->extra_komi);
832 /* Do not resign if we're so short of time that evaluation of best
833 * move is completely unreliable, we might be winning actually.
834 * In this case best is almost random but still better than resign.
835 * Also do not resign if we are getting bad results while actually
836 * giving away extra komi points (dynkomi). */
837 if (tree_node_get_value(u->t, 1, best->u.value) < u->resign_ratio
838 && !is_pass(best->coord) && best->u.playouts > GJ_MINGAMES
839 && u->t->extra_komi <= 1 /* XXX we assume dynamic komi == we are black */) {
840 if (!u->slave) reset_state(u);
841 return coord_copy(resign);
844 /* If the opponent just passed and we win counting, always
845 * pass as well. */
846 if (b->moves > 1 && is_pass(b->last_move.coord)) {
847 /* Make sure enough playouts are simulated. */
848 while (u->ownermap.playouts < GJ_MINGAMES)
849 uct_playout(u, b, color, u->t);
850 if (uct_pass_is_safe(u, b, color, u->pass_all_alive || pass_all_alive)) {
851 if (UDEBUGL(0))
852 fprintf(stderr, "<Will rather pass, looks safe enough.>\n");
853 best->coord = pass;
857 /* If we are a slave in the distributed engine, we'll soon get
858 * a "play" command later telling us which move was chosen,
859 * and pondering now will not gain much. */
860 if (!u->slave) {
861 tree_promote_node(u->t, &best);
863 /* After a pass, pondering is harmful for two reasons:
864 * (i) We might keep pondering even when the game is over.
865 * Of course this is the case for opponent resign as well.
866 * (ii) More importantly, the ownermap will get skewed since
867 * the UCT will start cutting off any playouts. */
868 if (u->pondering_opt && !is_pass(best->coord)) {
869 uct_pondering_start(u, b, u->t, stone_other(color));
872 if (UDEBUGL(2)) {
873 double time = time_now() - start_time + 0.000001; /* avoid divide by zero */
874 fprintf(stderr, "genmove in %0.2fs (%d games/s, %d games/s/thread)\n",
875 time, (int)(played_games/time), (int)(played_games/time/u->threads));
877 return coord_copy(best->coord);
880 /* Get stats updates for the distributed engine. Return a buffer
881 * with one line "total_playouts threads" then a list of lines
882 * "coord playouts value". The last line must not end with \n.
883 * If c is not null, add this move with root->playouts weight.
884 * This function is called only by the main thread, but may be
885 * called while the tree is updated by the worker threads.
886 * Keep this code in sync with select_best_move(). */
887 static char *
888 uct_getstats(struct uct *u, struct board *b, coord_t *c)
890 static char reply[10240];
891 char *r = reply;
892 char *end = reply + sizeof(reply);
893 struct tree_node *root = u->t->root;
894 r += snprintf(r, end - r, "%d %d", root->u.playouts, u->threads);
895 int min_playouts = root->u.playouts / 100;
897 // Give a large weight to pass or resign, but still allow other moves.
898 if (c)
899 r += snprintf(r, end - r, "\n%s %d %.1f", coord2sstr(*c, b), root->u.playouts,
900 (float)is_pass(*c));
902 /* We rely on the fact that root->children is set only
903 * after all children are created. */
904 for (struct tree_node *ni = root->children; ni; ni = ni->sibling) {
905 if (ni->u.playouts <= min_playouts
906 || ni->hints & TREE_HINT_INVALID
907 || is_pass(ni->coord))
908 continue;
909 char *coord = coord2sstr(ni->coord, b);
910 // We return the values as stored in the tree, so from black's view.
911 r += snprintf(r, end - r, "\n%s %d %.7f", coord, ni->u.playouts, ni->u.value);
913 return reply;
916 static char *
917 uct_genmoves(struct engine *e, struct board *b, struct time_info *ti, enum stone color,
918 char *args, bool pass_all_alive)
920 struct uct *u = e->data;
921 assert(u->slave);
923 coord_t *c = uct_genmove(e, b, ti, color, pass_all_alive);
925 /* Get correct time from master. Keep this code in sync with time_info(). */
926 if (ti->dim == TD_WALLTIME
927 && sscanf(args, "%lf %lf %d %d", &ti->len.t.main_time,
928 &ti->len.t.byoyomi_time, &ti->len.t.byoyomi_periods,
929 &ti->len.t.byoyomi_stones) != 4) {
930 return NULL;
933 char *reply = uct_getstats(u, b, is_pass(*c) || is_resign(*c) ? c : NULL);
934 coord_done(c);
935 return reply;
939 bool
940 uct_genbook(struct engine *e, struct board *b, struct time_info *ti, enum stone color)
942 struct uct *u = e->data;
943 if (!u->t) prepare_move(e, b, color);
944 assert(u->t);
946 if (ti->dim == TD_GAMES) {
947 /* Don't count in games that already went into the book. */
948 ti->len.games += u->t->root->u.playouts;
950 uct_search(u, b, ti, color, u->t);
952 assert(ti->dim == TD_GAMES);
953 tree_save(u->t, b, ti->len.games / 100);
955 return true;
958 void
959 uct_dumpbook(struct engine *e, struct board *b, enum stone color)
961 struct uct *u = e->data;
962 struct tree *t = tree_init(b, color, u->fast_alloc ? u->max_tree_size : 0, u->local_tree_aging);
963 tree_load(t, b);
964 tree_dump(t, 0);
965 tree_done(t);
969 struct uct *
970 uct_state_init(char *arg, struct board *b)
972 struct uct *u = calloc(1, sizeof(struct uct));
973 bool using_elo = false;
975 u->debug_level = debug_level;
976 u->gamelen = MC_GAMELEN;
977 u->mercymin = 0;
978 u->expand_p = 2;
979 u->dumpthres = 1000;
980 u->playout_amaf = true;
981 u->playout_amaf_nakade = false;
982 u->amaf_prior = false;
983 u->max_tree_size = 3072ULL * 1048576;
985 u->dynkomi_mask = S_BLACK;
987 u->threads = 1;
988 u->thread_model = TM_TREEVL;
989 u->parallel_tree = true;
990 u->virtual_loss = true;
992 u->fuseki_end = 20; // max time at 361*20% = 72 moves (our 36th move, still 99 to play)
993 u->yose_start = 40; // (100-40-25)*361/100/2 = 63 moves still to play by us then
994 u->bestr_ratio = 0.02;
995 // 2.5 is clearly too much, but seems to compensate well for overly stern time allocations.
996 // TODO: Further tuning and experiments with better time allocation schemes.
997 u->best2_ratio = 2.5;
999 u->val_scale = 0.04; u->val_points = 40;
1001 u->tenuki_d = 4;
1002 u->local_tree_aging = 2;
1004 if (arg) {
1005 char *optspec, *next = arg;
1006 while (*next) {
1007 optspec = next;
1008 next += strcspn(next, ",");
1009 if (*next) { *next++ = 0; } else { *next = 0; }
1011 char *optname = optspec;
1012 char *optval = strchr(optspec, '=');
1013 if (optval) *optval++ = 0;
1015 if (!strcasecmp(optname, "debug")) {
1016 if (optval)
1017 u->debug_level = atoi(optval);
1018 else
1019 u->debug_level++;
1020 } else if (!strcasecmp(optname, "mercy") && optval) {
1021 /* Minimal difference of black/white captures
1022 * to stop playout - "Mercy Rule". Speeds up
1023 * hopeless playouts at the expense of some
1024 * accuracy. */
1025 u->mercymin = atoi(optval);
1026 } else if (!strcasecmp(optname, "gamelen") && optval) {
1027 u->gamelen = atoi(optval);
1028 } else if (!strcasecmp(optname, "expand_p") && optval) {
1029 u->expand_p = atoi(optval);
1030 } else if (!strcasecmp(optname, "dumpthres") && optval) {
1031 u->dumpthres = atoi(optval);
1032 } else if (!strcasecmp(optname, "best2_ratio") && optval) {
1033 /* If set, prolong simulating while
1034 * first_best/second_best playouts ratio
1035 * is less than best2_ratio. */
1036 u->best2_ratio = atof(optval);
1037 } else if (!strcasecmp(optname, "bestr_ratio") && optval) {
1038 /* If set, prolong simulating while
1039 * best,best_best_child values delta
1040 * is more than bestr_ratio. */
1041 u->bestr_ratio = atof(optval);
1042 } else if (!strcasecmp(optname, "playout_amaf")) {
1043 /* Whether to include random playout moves in
1044 * AMAF as well. (Otherwise, only tree moves
1045 * are included in AMAF. Of course makes sense
1046 * only in connection with an AMAF policy.) */
1047 /* with-without: 55.5% (+-4.1) */
1048 if (optval && *optval == '0')
1049 u->playout_amaf = false;
1050 else
1051 u->playout_amaf = true;
1052 } else if (!strcasecmp(optname, "playout_amaf_nakade")) {
1053 /* Whether to include nakade moves from playouts
1054 * in the AMAF statistics; this tends to nullify
1055 * the playout_amaf effect by adding too much
1056 * noise. */
1057 if (optval && *optval == '0')
1058 u->playout_amaf_nakade = false;
1059 else
1060 u->playout_amaf_nakade = true;
1061 } else if (!strcasecmp(optname, "playout_amaf_cutoff") && optval) {
1062 /* Keep only first N% of playout stage AMAF
1063 * information. */
1064 u->playout_amaf_cutoff = atoi(optval);
1065 } else if ((!strcasecmp(optname, "policy") || !strcasecmp(optname, "random_policy")) && optval) {
1066 char *policyarg = strchr(optval, ':');
1067 struct uct_policy **p = !strcasecmp(optname, "policy") ? &u->policy : &u->random_policy;
1068 if (policyarg)
1069 *policyarg++ = 0;
1070 if (!strcasecmp(optval, "ucb1")) {
1071 *p = policy_ucb1_init(u, policyarg);
1072 } else if (!strcasecmp(optval, "ucb1amaf")) {
1073 *p = policy_ucb1amaf_init(u, policyarg);
1074 } else {
1075 fprintf(stderr, "UCT: Invalid tree policy %s\n", optval);
1076 exit(1);
1078 } else if (!strcasecmp(optname, "playout") && optval) {
1079 char *playoutarg = strchr(optval, ':');
1080 if (playoutarg)
1081 *playoutarg++ = 0;
1082 if (!strcasecmp(optval, "moggy")) {
1083 u->playout = playout_moggy_init(playoutarg, b);
1084 } else if (!strcasecmp(optval, "light")) {
1085 u->playout = playout_light_init(playoutarg, b);
1086 } else if (!strcasecmp(optval, "elo")) {
1087 u->playout = playout_elo_init(playoutarg, b);
1088 using_elo = true;
1089 } else {
1090 fprintf(stderr, "UCT: Invalid playout policy %s\n", optval);
1091 exit(1);
1093 } else if (!strcasecmp(optname, "prior") && optval) {
1094 u->prior = uct_prior_init(optval, b);
1095 } else if (!strcasecmp(optname, "amaf_prior") && optval) {
1096 u->amaf_prior = atoi(optval);
1097 } else if (!strcasecmp(optname, "threads") && optval) {
1098 /* By default, Pachi will run with only single
1099 * tree search thread! */
1100 u->threads = atoi(optval);
1101 } else if (!strcasecmp(optname, "thread_model") && optval) {
1102 if (!strcasecmp(optval, "root")) {
1103 /* Root parallelization - each thread
1104 * does independent search, trees are
1105 * merged at the end. */
1106 u->thread_model = TM_ROOT;
1107 u->parallel_tree = false;
1108 u->virtual_loss = false;
1109 } else if (!strcasecmp(optval, "tree")) {
1110 /* Tree parallelization - all threads
1111 * grind on the same tree. */
1112 u->thread_model = TM_TREE;
1113 u->parallel_tree = true;
1114 u->virtual_loss = false;
1115 } else if (!strcasecmp(optval, "treevl")) {
1116 /* Tree parallelization, but also
1117 * with virtual losses - this discou-
1118 * rages most threads choosing the
1119 * same tree branches to read. */
1120 u->thread_model = TM_TREEVL;
1121 u->parallel_tree = true;
1122 u->virtual_loss = true;
1123 } else {
1124 fprintf(stderr, "UCT: Invalid thread model %s\n", optval);
1125 exit(1);
1127 } else if (!strcasecmp(optname, "pondering")) {
1128 /* Keep searching even during opponent's turn. */
1129 u->pondering_opt = !optval || atoi(optval);
1130 } else if (!strcasecmp(optname, "fuseki_end") && optval) {
1131 /* At the very beginning it's not worth thinking
1132 * too long because the playout evaluations are
1133 * very noisy. So gradually increase the thinking
1134 * time up to maximum when fuseki_end percent
1135 * of the board has been played.
1136 * This only applies if we are not in byoyomi. */
1137 u->fuseki_end = atoi(optval);
1138 } else if (!strcasecmp(optname, "yose_start") && optval) {
1139 /* When yose_start percent of the board has been
1140 * played, or if we are in byoyomi, stop spending
1141 * more time and spread the remaining time
1142 * uniformly.
1143 * Between fuseki_end and yose_start, we spend
1144 * a constant proportion of the remaining time
1145 * on each move. (yose_start should actually
1146 * be much earlier than when real yose start,
1147 * but "yose" is a good short name to convey
1148 * the idea.) */
1149 u->yose_start = atoi(optval);
1150 } else if (!strcasecmp(optname, "force_seed") && optval) {
1151 u->force_seed = atoi(optval);
1152 } else if (!strcasecmp(optname, "no_book")) {
1153 u->no_book = true;
1154 } else if (!strcasecmp(optname, "dynkomi") && optval) {
1155 /* Dynamic komi approach; there are multiple
1156 * ways to adjust komi dynamically throughout
1157 * play. We currently support two: */
1158 char *dynkomiarg = strchr(optval, ':');
1159 if (dynkomiarg)
1160 *dynkomiarg++ = 0;
1161 if (!strcasecmp(optval, "none")) {
1162 u->dynkomi = uct_dynkomi_init_none(u, dynkomiarg, b);
1163 } else if (!strcasecmp(optval, "linear")) {
1164 u->dynkomi = uct_dynkomi_init_linear(u, dynkomiarg, b);
1165 } else if (!strcasecmp(optval, "adaptive")) {
1166 u->dynkomi = uct_dynkomi_init_adaptive(u, dynkomiarg, b);
1167 } else {
1168 fprintf(stderr, "UCT: Invalid dynkomi mode %s\n", optval);
1169 exit(1);
1171 } else if (!strcasecmp(optname, "dynkomi_mask") && optval) {
1172 /* Bitmask of colors the player must be
1173 * for dynkomi be applied; you may want
1174 * to use dynkomi_mask=3 to allow dynkomi
1175 * even in games where Pachi is white. */
1176 u->dynkomi_mask = atoi(optval);
1177 } else if (!strcasecmp(optname, "dynkomi_interval") && optval) {
1178 /* If non-zero, re-adjust dynamic komi
1179 * throughout a single genmove reading,
1180 * roughly every N simulations. */
1181 /* XXX: Does not work with tree
1182 * parallelization. */
1183 u->dynkomi_interval = atoi(optval);
1184 } else if (!strcasecmp(optname, "val_scale") && optval) {
1185 /* How much of the game result value should be
1186 * influenced by win size. Zero means it isn't. */
1187 u->val_scale = atof(optval);
1188 } else if (!strcasecmp(optname, "val_points") && optval) {
1189 /* Maximum size of win to be scaled into game
1190 * result value. Zero means boardsize^2. */
1191 u->val_points = atoi(optval) * 2; // result values are doubled
1192 } else if (!strcasecmp(optname, "val_extra")) {
1193 /* If false, the score coefficient will be simply
1194 * added to the value, instead of scaling the result
1195 * coefficient because of it. */
1196 u->val_extra = !optval || atoi(optval);
1197 } else if (!strcasecmp(optname, "local_tree") && optval) {
1198 /* Whether to bias exploration by local tree values
1199 * (must be supported by the used policy).
1200 * 0: Don't.
1201 * 1: Do, value = result.
1202 * Try to temper the result:
1203 * 2: Do, value = 0.5+(result-expected)/2.
1204 * 3: Do, value = 0.5+bzz((result-expected)^2).
1205 * 4: Do, value = 0.5+sqrt(result-expected)/2. */
1206 u->local_tree = atoi(optval);
1207 } else if (!strcasecmp(optname, "tenuki_d") && optval) {
1208 /* Tenuki distance at which to break the local tree. */
1209 u->tenuki_d = atoi(optval);
1210 if (u->tenuki_d > TREE_NODE_D_MAX + 1) {
1211 fprintf(stderr, "uct: tenuki_d must not be larger than TREE_NODE_D_MAX+1 %d\n", TREE_NODE_D_MAX + 1);
1212 exit(1);
1214 } else if (!strcasecmp(optname, "local_tree_aging") && optval) {
1215 /* How much to reduce local tree values between moves. */
1216 u->local_tree_aging = atof(optval);
1217 } else if (!strcasecmp(optname, "local_tree_allseq")) {
1218 /* By default, only complete sequences are stored
1219 * in the local tree. If this is on, also
1220 * subsequences starting at each move are stored. */
1221 u->local_tree_allseq = !optval || atoi(optval);
1222 } else if (!strcasecmp(optname, "local_tree_playout")) {
1223 /* Whether to adjust ELO playout probability
1224 * distributions according to matched localtree
1225 * information. */
1226 u->local_tree_playout = !optval || atoi(optval);
1227 } else if (!strcasecmp(optname, "local_tree_pseqroot")) {
1228 /* By default, when we have no sequence move
1229 * to suggest in-playout, we give up. If this
1230 * is on, we make probability distribution from
1231 * sequences first moves instead. */
1232 u->local_tree_pseqroot = !optval || atoi(optval);
1233 } else if (!strcasecmp(optname, "pass_all_alive")) {
1234 /* Whether to consider all stones alive at the game
1235 * end instead of marking dead groupd. */
1236 u->pass_all_alive = !optval || atoi(optval);
1237 } else if (!strcasecmp(optname, "territory_scoring")) {
1238 /* Use territory scoring (default is area scoring).
1239 * An explicit kgs-rules command overrides this. */
1240 u->territory_scoring = !optval || atoi(optval);
1241 } else if (!strcasecmp(optname, "random_policy_chance") && optval) {
1242 /* If specified (N), with probability 1/N, random_policy policy
1243 * descend is used instead of main policy descend; useful
1244 * if specified policy (e.g. UCB1AMAF) can make unduly biased
1245 * choices sometimes, you can fall back to e.g.
1246 * random_policy=UCB1. */
1247 u->random_policy_chance = atoi(optval);
1248 } else if (!strcasecmp(optname, "max_tree_size") && optval) {
1249 /* Maximum amount of memory [MiB] consumed by the move tree.
1250 * For fast_alloc it includes the temp tree used for pruning.
1251 * Default is 3072 (3 GiB). Note that if you use TM_ROOT,
1252 * this limits size of only one of the trees, not all of them
1253 * together. */
1254 u->max_tree_size = atol(optval) * 1048576;
1255 } else if (!strcasecmp(optname, "fast_alloc")) {
1256 u->fast_alloc = !optval || atoi(optval);
1257 } else if (!strcasecmp(optname, "slave")) {
1258 /* Act as slave for the distributed engine. */
1259 u->slave = !optval || atoi(optval);
1260 } else if (!strcasecmp(optname, "banner") && optval) {
1261 /* Additional banner string. This must come as the
1262 * last engine parameter. */
1263 if (*next) *--next = ',';
1264 u->banner = strdup(optval);
1265 break;
1266 } else {
1267 fprintf(stderr, "uct: Invalid engine argument %s or missing value\n", optname);
1268 exit(1);
1273 u->resign_ratio = 0.2; /* Resign when most games are lost. */
1274 u->loss_threshold = 0.85; /* Stop reading if after at least 2000 playouts this is best value. */
1275 if (!u->policy)
1276 u->policy = policy_ucb1amaf_init(u, NULL);
1278 if (!!u->random_policy_chance ^ !!u->random_policy) {
1279 fprintf(stderr, "uct: Only one of random_policy and random_policy_chance is set\n");
1280 exit(1);
1283 if (!u->local_tree) {
1284 /* No ltree aging. */
1285 u->local_tree_aging = 1.0f;
1287 if (!using_elo)
1288 u->local_tree_playout = false;
1290 if (u->fast_alloc && !u->parallel_tree) {
1291 fprintf(stderr, "fast_alloc not supported with root parallelization.\n");
1292 exit(1);
1294 if (u->fast_alloc)
1295 u->max_tree_size = (100ULL * u->max_tree_size) / (100 + MIN_FREE_MEM_PERCENT);
1297 if (!u->prior)
1298 u->prior = uct_prior_init(NULL, b);
1300 if (!u->playout)
1301 u->playout = playout_moggy_init(NULL, b);
1302 u->playout->debug_level = u->debug_level;
1304 u->ownermap.map = malloc(board_size2(b) * sizeof(u->ownermap.map[0]));
1306 if (!u->dynkomi)
1307 u->dynkomi = uct_dynkomi_init_linear(u, NULL, b);
1309 /* Some things remain uninitialized for now - the opening book
1310 * is not loaded and the tree not set up. */
1311 /* This will be initialized in setup_state() at the first move
1312 * received/requested. This is because right now we are not aware
1313 * about any komi or handicap setup and such. */
1315 return u;
1318 struct engine *
1319 engine_uct_init(char *arg, struct board *b)
1321 struct uct *u = uct_state_init(arg, b);
1322 struct engine *e = calloc(1, sizeof(struct engine));
1323 e->name = "UCT Engine";
1324 e->printhook = uct_printhook_ownermap;
1325 e->notify_play = uct_notify_play;
1326 e->chat = uct_chat;
1327 e->genmove = uct_genmove;
1328 e->genmoves = uct_genmoves;
1329 e->dead_group_list = uct_dead_group_list;
1330 e->done = uct_done;
1331 e->data = u;
1332 if (u->slave)
1333 e->notify = uct_notify;
1335 const char banner[] = "I'm playing UCT. When I'm losing, I will resign, "
1336 "if I think I win, I play until you pass. "
1337 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
1338 if (!u->banner) u->banner = "";
1339 e->comment = malloc(sizeof(banner) + strlen(u->banner) + 1);
1340 sprintf(e->comment, "%s %s", banner, u->banner);
1342 return e;