Merge branch 'dist' into derm
[pachi.git] / uct / uct.c
blob023d3084526db0011d778281d87b5a586c5f7696
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);
37 /* Default number of simulations to perform per move.
38 * Note that this is now in total over all threads! (Unless TM_ROOT.) */
39 #define MC_GAMES 80000
40 #define MC_GAMELEN MAX_GAMELEN
41 static const struct time_info default_ti = {
42 .period = TT_MOVE,
43 .dim = TD_GAMES,
44 .len = { .games = MC_GAMES },
47 /* How big proportion of ownermap counts must be of one color to consider
48 * the point sure. */
49 #define GJ_THRES 0.8
50 /* How many games to consider at minimum before judging groups. */
51 #define GJ_MINGAMES 500
53 /* How often to inspect the tree from the main thread to check for playout
54 * stop, progress reports, etc. (in seconds) */
55 #define TREE_BUSYWAIT_INTERVAL 0.1 /* 100ms */
57 /* Once per how many simulations (per thread) to show a progress report line. */
58 #define TREE_SIMPROGRESS_INTERVAL 10000
60 /* How often to send stats updates for the distributed engine (in seconds). */
61 #define STATS_SEND_INTERVAL 0.5
63 /* When terminating uct_search() early, the safety margin to add to the
64 * remaining playout number estimate when deciding whether the result can
65 * still change. */
66 #define PLAYOUT_DELTA_SAFEMARGIN 1000
69 static void
70 setup_state(struct uct *u, struct board *b, enum stone color)
72 u->t = tree_init(b, color, u->fast_alloc ? u->max_tree_size : 0, u->local_tree_aging);
73 if (u->force_seed)
74 fast_srandom(u->force_seed);
75 if (UDEBUGL(0))
76 fprintf(stderr, "Fresh board with random seed %lu\n", fast_getseed());
77 //board_print(b, stderr);
78 if (!u->no_book && b->moves == 0) {
79 assert(color == S_BLACK);
80 tree_load(u->t, b);
84 static void
85 reset_state(struct uct *u)
87 assert(u->t);
88 tree_done(u->t); u->t = NULL;
91 static void
92 setup_dynkomi(struct uct *u, struct board *b, enum stone to_play)
94 if (u->t->use_extra_komi && u->dynkomi->permove)
95 u->t->extra_komi = u->dynkomi->permove(u->dynkomi, b, u->t);
98 static void
99 prepare_move(struct engine *e, struct board *b, enum stone color)
101 struct uct *u = e->data;
103 if (u->t) {
104 /* Verify that we have sane state. */
105 assert(b->es == u);
106 assert(u->t && b->moves);
107 if (color != stone_other(u->t->root_color)) {
108 fprintf(stderr, "Fatal: Non-alternating play detected %d %d\n",
109 color, u->t->root_color);
110 exit(1);
113 } else {
114 /* We need fresh state. */
115 b->es = u;
116 setup_state(u, b, color);
119 u->ownermap.playouts = 0;
120 memset(u->ownermap.map, 0, board_size2(b) * sizeof(u->ownermap.map[0]));
121 memset(u->stats, 0, board_size2(b) * sizeof(u->stats[0]));
122 u->played_own = u->played_all = 0;
125 static void
126 dead_group_list(struct uct *u, struct board *b, struct move_queue *mq)
128 struct group_judgement gj;
129 gj.thres = GJ_THRES;
130 gj.gs = alloca(board_size2(b) * sizeof(gj.gs[0]));
131 board_ownermap_judge_group(b, &u->ownermap, &gj);
132 groups_of_status(b, &gj, GS_DEAD, mq);
135 bool
136 uct_pass_is_safe(struct uct *u, struct board *b, enum stone color, bool pass_all_alive)
138 if (u->ownermap.playouts < GJ_MINGAMES)
139 return false;
141 struct move_queue mq = { .moves = 0 };
142 if (!pass_all_alive)
143 dead_group_list(u, b, &mq);
144 return pass_is_safe(b, color, &mq);
147 /* This function is called only when running as slave in the distributed version. */
148 static enum parse_code
149 uct_notify(struct engine *e, struct board *b, int id, char *cmd, char *args, char **reply)
151 struct uct *u = e->data;
153 static bool board_resized = false;
154 board_resized |= is_gamestart(cmd);
156 /* Force resending the whole command history if we are out of sync
157 * but do it only once, not if already getting the history. */
158 if ((move_number(id) != b->moves || !board_resized)
159 && !reply_disabled(id) && !is_reset(cmd)) {
160 if (UDEBUGL(0))
161 fprintf(stderr, "Out of sync, id %d, move %d\n", id, b->moves);
162 static char buf[128];
163 snprintf(buf, sizeof(buf), "out of sync, move %d expected", b->moves);
164 *reply = buf;
165 return P_DONE_ERROR;
167 u->gtp_id = id;
168 return reply_disabled(id) ? P_NOREPLY : P_OK;
171 static char *
172 uct_printhook_ownermap(struct board *board, coord_t c, char *s, char *end)
174 struct uct *u = board->es;
175 assert(u);
176 const char chr[] = ":XO,"; // dame, black, white, unclear
177 const char chm[] = ":xo,";
178 char ch = chr[board_ownermap_judge_point(&u->ownermap, c, GJ_THRES)];
179 if (ch == ',') { // less precise estimate then?
180 ch = chm[board_ownermap_judge_point(&u->ownermap, c, 0.67)];
182 s += snprintf(s, end - s, "%c ", ch);
183 return s;
186 static char *
187 uct_notify_play(struct engine *e, struct board *b, struct move *m)
189 struct uct *u = e->data;
190 if (!u->t) {
191 /* No state, create one - this is probably game beginning
192 * and we need to load the opening book right now. */
193 prepare_move(e, b, m->color);
194 assert(u->t);
197 /* Stop pondering, required by tree_promote_at() */
198 uct_pondering_stop(u);
199 if (UDEBUGL(2) && u->slave)
200 tree_dump(u->t, u->dumpthres);
202 if (is_resign(m->coord)) {
203 /* Reset state. */
204 reset_state(u);
205 return NULL;
208 /* Promote node of the appropriate move to the tree root. */
209 assert(u->t->root);
210 if (!tree_promote_at(u->t, b, m->coord)) {
211 if (UDEBUGL(0))
212 fprintf(stderr, "Warning: Cannot promote move node! Several play commands in row?\n");
213 reset_state(u);
214 return NULL;
217 /* If we are a slave in a distributed engine, start pondering once
218 * we know which move we actually played. See uct_genmove() about
219 * the check for pass. */
220 if (u->pondering_opt && u->slave && m->color == u->my_color && !is_pass(m->coord))
221 uct_pondering_start(u, b, u->t, stone_other(m->color));
223 return NULL;
226 static char *
227 uct_chat(struct engine *e, struct board *b, char *cmd)
229 struct uct *u = e->data;
230 static char reply[1024];
232 cmd += strspn(cmd, " \n\t");
233 if (!strncasecmp(cmd, "winrate", 7)) {
234 if (!u->t)
235 return "no game context (yet?)";
236 enum stone color = u->t->root_color;
237 struct tree_node *n = u->t->root;
238 snprintf(reply, 1024, "In %d playouts at %d threads, %s %s can win with %.2f%% probability",
239 n->u.playouts, u->threads, stone2str(color), coord2sstr(n->coord, b),
240 tree_node_get_value(u->t, -1, n->u.value) * 100);
241 if (u->t->use_extra_komi && abs(u->t->extra_komi) >= 0.5) {
242 sprintf(reply + strlen(reply), ", while self-imposing extra komi %.1f",
243 u->t->extra_komi);
245 strcat(reply, ".");
246 return reply;
248 return NULL;
251 static void
252 uct_dead_group_list(struct engine *e, struct board *b, struct move_queue *mq)
254 struct uct *u = e->data;
256 /* This means the game is probably over, no use pondering on. */
257 uct_pondering_stop(u);
259 if (u->pass_all_alive)
260 return; // no dead groups
262 bool mock_state = false;
264 if (!u->t) {
265 /* No state, but we cannot just back out - we might
266 * have passed earlier, only assuming some stones are
267 * dead, and then re-connected, only to lose counting
268 * when all stones are assumed alive. */
269 /* Mock up some state and seed the ownermap by few
270 * simulations. */
271 prepare_move(e, b, S_BLACK); assert(u->t);
272 for (int i = 0; i < GJ_MINGAMES; i++)
273 uct_playout(u, b, S_BLACK, u->t);
274 mock_state = true;
277 dead_group_list(u, b, mq);
279 if (mock_state) {
280 /* Clean up the mock state in case we will receive
281 * a genmove; we could get a non-alternating-move
282 * error from prepare_move() in that case otherwise. */
283 reset_state(u);
287 static void
288 playout_policy_done(struct playout_policy *p)
290 if (p->done) p->done(p);
291 if (p->data) free(p->data);
292 free(p);
295 static void
296 uct_done(struct engine *e)
298 /* This is called on engine reset, especially when clear_board
299 * is received and new game should begin. */
300 struct uct *u = e->data;
301 uct_pondering_stop(u);
302 if (u->t) reset_state(u);
303 free(u->ownermap.map);
304 free(u->stats);
306 free(u->policy);
307 free(u->random_policy);
308 playout_policy_done(u->playout);
309 uct_prior_done(u->prior);
313 /* Pachi threading structure (if uct_playouts_parallel() is used):
315 * main thread
316 * | main(), GTP communication, ...
317 * | starts and stops the search managed by thread_manager
319 * thread_manager
320 * | spawns and collects worker threads
322 * worker0
323 * worker1
324 * ...
325 * workerK
326 * uct_playouts() loop, doing descend-playout until uct_halt
328 * Another way to look at it is by functions (lines denote thread boundaries):
330 * | uct_genmove()
331 * | uct_search() (uct_search_start() .. uct_search_stop())
332 * | -----------------------
333 * | spawn_thread_manager()
334 * | -----------------------
335 * | spawn_worker()
336 * V uct_playouts() */
338 /* Set in thread manager in case the workers should stop. */
339 volatile sig_atomic_t uct_halt = 0;
340 /* ID of the running worker thread. */
341 __thread int thread_id = -1;
342 /* ID of the thread manager. */
343 static pthread_t thread_manager;
344 static bool thread_manager_running;
346 static pthread_mutex_t finish_mutex = PTHREAD_MUTEX_INITIALIZER;
347 static pthread_cond_t finish_cond = PTHREAD_COND_INITIALIZER;
348 static volatile int finish_thread;
349 static pthread_mutex_t finish_serializer = PTHREAD_MUTEX_INITIALIZER;
351 struct spawn_ctx {
352 int tid;
353 struct uct *u;
354 struct board *b;
355 enum stone color;
356 struct tree *t;
357 unsigned long seed;
358 int games;
361 static void *
362 spawn_worker(void *ctx_)
364 struct spawn_ctx *ctx = ctx_;
365 /* Setup */
366 fast_srandom(ctx->seed);
367 thread_id = ctx->tid;
368 /* Run */
369 ctx->games = uct_playouts(ctx->u, ctx->b, ctx->color, ctx->t);
370 /* Finish */
371 pthread_mutex_lock(&finish_serializer);
372 pthread_mutex_lock(&finish_mutex);
373 finish_thread = ctx->tid;
374 pthread_cond_signal(&finish_cond);
375 pthread_mutex_unlock(&finish_mutex);
376 return ctx;
379 /* Thread manager, controlling worker threads. It must be called with
380 * finish_mutex lock held, but it will unlock it itself before exiting;
381 * this is necessary to be completely deadlock-free. */
382 /* The finish_cond can be signalled for it to stop; in that case,
383 * the caller should set finish_thread = -1. */
384 /* After it is started, it will update mctx->t to point at some tree
385 * used for the actual search (matters only for TM_ROOT), on return
386 * it will set mctx->games to the number of performed simulations. */
387 static void *
388 spawn_thread_manager(void *ctx_)
390 /* In thread_manager, we use only some of the ctx fields. */
391 struct spawn_ctx *mctx = ctx_;
392 struct uct *u = mctx->u;
393 struct tree *t = mctx->t;
394 bool shared_tree = u->parallel_tree;
395 fast_srandom(mctx->seed);
397 int played_games = 0;
398 pthread_t threads[u->threads];
399 int joined = 0;
401 uct_halt = 0;
403 /* Garbage collect the tree by preference when pondering. */
404 if (u->pondering && t->nodes && t->nodes_size > t->max_tree_size/2) {
405 unsigned long temp_size = (MIN_FREE_MEM_PERCENT * t->max_tree_size) / 100;
406 t->root = tree_garbage_collect(t, temp_size, t->root);
409 /* Spawn threads... */
410 for (int ti = 0; ti < u->threads; ti++) {
411 struct spawn_ctx *ctx = malloc(sizeof(*ctx));
412 ctx->u = u; ctx->b = mctx->b; ctx->color = mctx->color;
413 mctx->t = ctx->t = shared_tree ? t : tree_copy(t);
414 ctx->tid = ti; ctx->seed = fast_random(65536) + ti;
415 pthread_create(&threads[ti], NULL, spawn_worker, ctx);
416 if (UDEBUGL(3))
417 fprintf(stderr, "Spawned worker %d\n", ti);
420 /* ...and collect them back: */
421 while (joined < u->threads) {
422 /* Wait for some thread to finish... */
423 pthread_cond_wait(&finish_cond, &finish_mutex);
424 if (finish_thread < 0) {
425 /* Stop-by-caller. Tell the workers to wrap up. */
426 uct_halt = 1;
427 continue;
429 /* ...and gather its remnants. */
430 struct spawn_ctx *ctx;
431 pthread_join(threads[finish_thread], (void **) &ctx);
432 played_games += ctx->games;
433 joined++;
434 if (!shared_tree) {
435 if (ctx->t == mctx->t) mctx->t = t;
436 tree_merge(t, ctx->t);
437 tree_done(ctx->t);
439 free(ctx);
440 if (UDEBUGL(3))
441 fprintf(stderr, "Joined worker %d\n", finish_thread);
442 pthread_mutex_unlock(&finish_serializer);
445 pthread_mutex_unlock(&finish_mutex);
447 if (!shared_tree)
448 tree_normalize(mctx->t, u->threads);
450 mctx->games = played_games;
451 return mctx;
454 static struct spawn_ctx *
455 uct_search_start(struct uct *u, struct board *b, enum stone color, struct tree *t)
457 assert(u->threads > 0);
458 assert(!thread_manager_running);
460 struct spawn_ctx ctx = { .u = u, .b = b, .color = color, .t = t, .seed = fast_random(65536) };
461 static struct spawn_ctx mctx; mctx = ctx;
462 pthread_mutex_lock(&finish_mutex);
463 pthread_create(&thread_manager, NULL, spawn_thread_manager, &mctx);
464 thread_manager_running = true;
465 return &mctx;
468 static struct spawn_ctx *
469 uct_search_stop(void)
471 assert(thread_manager_running);
473 /* Signal thread manager to stop the workers. */
474 pthread_mutex_lock(&finish_mutex);
475 finish_thread = -1;
476 pthread_cond_signal(&finish_cond);
477 pthread_mutex_unlock(&finish_mutex);
479 /* Collect the thread manager. */
480 struct spawn_ctx *pctx;
481 thread_manager_running = false;
482 pthread_join(thread_manager, (void **) &pctx);
483 return pctx;
487 /* Determine whether we should terminate the search early. */
488 static bool
489 uct_search_stop_early(struct uct *u, struct tree *t, struct board *b,
490 struct time_info *ti, struct time_stop *stop,
491 struct tree_node *best, struct tree_node *best2,
492 int played)
494 /* Always use at least half the desired time. It is silly
495 * to lose a won game because we played a bad move in 0.1s. */
496 double elapsed = 0;
497 if (ti->dim == TD_WALLTIME) {
498 elapsed = time_now() - ti->len.t.timer_start;
499 if (elapsed < 0.5 * stop->desired.time) return false;
502 /* Early break in won situation. */
503 if (best->u.playouts >= 2000 && tree_node_get_value(t, 1, best->u.value) >= u->loss_threshold)
504 return true;
505 /* Earlier break in super-won situation. */
506 if (best->u.playouts >= 500 && tree_node_get_value(t, 1, best->u.value) >= 0.95)
507 return true;
509 /* Break early if we estimate the second-best move cannot
510 * catch up in assigned time anymore. We use all our time
511 * if we are in byoyomi with single stone remaining in our
512 * period, however - it's better to pre-ponder. */
513 bool time_indulgent = (!ti->len.t.main_time && ti->len.t.byoyomi_stones == 1);
514 if (best2 && ti->dim == TD_WALLTIME && !time_indulgent) {
515 double remaining = stop->worst.time - elapsed;
516 double pps = ((double)played) / elapsed;
517 double estplayouts = remaining * pps + PLAYOUT_DELTA_SAFEMARGIN;
518 if (best->u.playouts > best2->u.playouts + estplayouts) {
519 if (UDEBUGL(2))
520 fprintf(stderr, "Early stop, result cannot change: "
521 "best %d, best2 %d, estimated %f simulations to go\n",
522 best->u.playouts, best2->u.playouts, estplayouts);
523 return true;
527 return false;
530 /* Determine whether we should terminate the search later than expected. */
531 static bool
532 uct_search_keep_looking(struct uct *u, struct tree *t, struct board *b,
533 struct time_info *ti, struct time_stop *stop,
534 struct tree_node *best, struct tree_node *best2,
535 struct tree_node *bestr, struct tree_node *winner, int i)
537 if (!best) {
538 if (UDEBUGL(2))
539 fprintf(stderr, "Did not find best move, still trying...\n");
540 return true;
543 /* Do not waste time if we are winning. Spend up to worst time if
544 * we are unsure, but only desired time if we are sure of winning. */
545 float beta = 2 * (tree_node_get_value(t, 1, best->u.value) - 0.5);
546 if (ti->dim == TD_WALLTIME && beta > 0) {
547 double good_enough = stop->desired.time * beta + stop->worst.time * (1 - beta);
548 double elapsed = time_now() - ti->len.t.timer_start;
549 if (elapsed > good_enough) return false;
552 if (u->best2_ratio > 0) {
553 /* Check best/best2 simulations ratio. If the
554 * two best moves give very similar results,
555 * keep simulating. */
556 if (best2 && best2->u.playouts
557 && (double)best->u.playouts / best2->u.playouts < u->best2_ratio) {
558 if (UDEBUGL(2))
559 fprintf(stderr, "Best2 ratio %f < threshold %f\n",
560 (double)best->u.playouts / best2->u.playouts,
561 u->best2_ratio);
562 return true;
566 if (u->bestr_ratio > 0) {
567 /* Check best, best_best value difference. If the best move
568 * and its best child do not give similar enough results,
569 * keep simulating. */
570 if (bestr && bestr->u.playouts
571 && fabs((double)best->u.value - bestr->u.value) > u->bestr_ratio) {
572 if (UDEBUGL(2))
573 fprintf(stderr, "Bestr delta %f > threshold %f\n",
574 fabs((double)best->u.value - bestr->u.value),
575 u->bestr_ratio);
576 return true;
580 if (winner && winner != best) {
581 /* Keep simulating if best explored
582 * does not have also highest value. */
583 if (UDEBUGL(2))
584 fprintf(stderr, "[%d] best %3s [%d] %f != winner %3s [%d] %f\n", i,
585 coord2sstr(best->coord, t->board),
586 best->u.playouts, tree_node_get_value(t, 1, best->u.value),
587 coord2sstr(winner->coord, t->board),
588 winner->u.playouts, tree_node_get_value(t, 1, winner->u.value));
589 return true;
592 /* No reason to keep simulating, bye. */
593 return false;
596 /* Run time-limited MCTS search. For a slave in the distributed
597 * engine, the search is done in background and will be stopped at
598 * the next uct_notify_play(); keep_looking is advice for the master. */
599 static int
600 uct_search(struct uct *u, struct board *b, struct time_info *ti, enum stone color,
601 struct tree *t, bool *keep_looking)
603 int base_playouts = u->t->root->u.playouts;
604 if (UDEBUGL(2) && base_playouts > 0)
605 fprintf(stderr, "<pre-simulated %d games skipped>\n", base_playouts);
607 *keep_looking = false;
609 /* Number of last dynkomi adjustment. */
610 int last_dynkomi = t->root->u.playouts;
611 /* Number of last game with progress print. */
612 int last_print = t->root->u.playouts;
613 /* Number of simulations to wait before next print. */
614 int print_interval = TREE_SIMPROGRESS_INTERVAL * (u->thread_model == TM_ROOT ? 1 : u->threads);
615 /* Printed notification about full memory? */
616 bool print_fullmem = false;
618 static struct time_stop stop;
619 static struct spawn_ctx *ctx;
620 if (!thread_manager_running) {
621 if (ti->period == TT_NULL) *ti = default_ti;
622 time_stop_conditions(ti, b, u->fuseki_end, u->yose_start, &stop);
624 ctx = uct_search_start(u, b, color, t);
625 } else {
626 /* Keep the search running. */
627 assert(u->slave);
630 /* The search tree is ctx->t. This is normally == t, but in case of
631 * TM_ROOT, it is one of the trees belonging to the independent
632 * workers. It is important to reference ctx->t directly since the
633 * thread manager will swap the tree pointer asynchronously. */
634 /* XXX: This means TM_ROOT support is suboptimal since single stalled
635 * thread can stall the others in case of limiting the search by game
636 * count. However, TM_ROOT just does not deserve any more extra code
637 * right now. */
639 struct tree_node *best = NULL;
640 struct tree_node *best2 = NULL; // Second-best move.
641 struct tree_node *bestr = NULL; // best's best child.
642 struct tree_node *winner = NULL;
644 double busywait_interval = TREE_BUSYWAIT_INTERVAL;
646 /* Now, just periodically poll the search tree. */
647 while (1) {
648 time_sleep(busywait_interval);
649 /* busywait_interval should never be less than desired time, or the
650 * time control is broken. But if it happens to be less, we still search
651 * at least 100ms otherwise the move is completely random. */
653 int i = ctx->t->root->u.playouts;
655 /* Adjust dynkomi? */
656 if (ctx->t->use_extra_komi && u->dynkomi->permove
657 && u->dynkomi_interval
658 && i > last_dynkomi + u->dynkomi_interval) {
659 last_dynkomi += u->dynkomi_interval;
660 float old_dynkomi = ctx->t->extra_komi;
661 ctx->t->extra_komi = u->dynkomi->permove(u->dynkomi, b, ctx->t);
662 if (UDEBUGL(3) && old_dynkomi != ctx->t->extra_komi)
663 fprintf(stderr, "dynkomi adjusted (%f -> %f)\n", old_dynkomi, ctx->t->extra_komi);
666 /* Print progress? */
667 if (i - last_print > print_interval) {
668 last_print += print_interval; // keep the numbers tidy
669 uct_progress_status(u, ctx->t, color, last_print);
671 if (!print_fullmem && ctx->t->nodes_size > u->max_tree_size) {
672 if (UDEBUGL(2))
673 fprintf(stderr, "memory limit hit (%lu > %lu)\n", ctx->t->nodes_size, u->max_tree_size);
674 print_fullmem = true;
677 /* Never consider stopping if we played too few simulations.
678 * Maybe we risk losing on time when playing in super-extreme
679 * time pressure but the tree is going to be just too messed
680 * up otherwise - we might even play invalid suicides or pass
681 * when we mustn't. */
682 if (i < GJ_MINGAMES)
683 continue;
685 best = u->policy->choose(u->policy, ctx->t->root, b, color, resign);
686 if (best) best2 = u->policy->choose(u->policy, ctx->t->root, b, color, best->coord);
688 /* Possibly stop search early if it's no use to try on. */
689 int played = u->played_all + i - base_playouts;
690 if (best && uct_search_stop_early(u, ctx->t, b, ti, &stop, best, best2, played))
691 break;
693 /* Check against time settings. */
694 bool desired_done;
695 if (ti->dim == TD_WALLTIME) {
696 double elapsed = time_now() - ti->len.t.timer_start;
697 if (elapsed > stop.worst.time) break;
698 desired_done = elapsed > stop.desired.time;
700 } else { assert(ti->dim == TD_GAMES);
701 if (i > stop.worst.playouts) break;
702 desired_done = i > stop.desired.playouts;
705 /* We want to stop simulating, but are willing to keep trying
706 * if we aren't completely sure about the winner yet. */
707 if (desired_done) {
708 if (u->policy->winner && u->policy->evaluate) {
709 struct uct_descent descent = { .node = ctx->t->root };
710 u->policy->winner(u->policy, ctx->t, &descent);
711 winner = descent.node;
713 if (best)
714 bestr = u->policy->choose(u->policy, best, b, stone_other(color), resign);
715 if (!uct_search_keep_looking(u, ctx->t, b, ti, &stop, best, best2, bestr, winner, i))
716 break;
719 /* TODO: Early break if best->variance goes under threshold and we already
720 * have enough playouts (possibly thanks to book or to pondering)? */
722 /* If running as slave in the distributed engine,
723 * let the search continue in background. */
724 if (u->slave) {
725 *keep_looking = true;
726 break;
730 int games;
731 if (!u->slave) {
732 ctx = uct_search_stop();
733 games = ctx->games;
734 if (UDEBUGL(2)) tree_dump(t, u->dumpthres);
735 } else {
736 /* We can only return an estimate here. */
737 games = ctx->t->root->u.playouts - base_playouts;
739 if (UDEBUGL(2))
740 fprintf(stderr, "(avg score %f/%d value %f/%d)\n",
741 u->dynkomi->score.value, u->dynkomi->score.playouts,
742 u->dynkomi->value.value, u->dynkomi->value.playouts);
743 if (UDEBUGL(0))
744 uct_progress_status(u, t, color, games);
746 return games;
750 /* Start pondering background with @color to play. */
751 static void
752 uct_pondering_start(struct uct *u, struct board *b0, struct tree *t, enum stone color)
754 if (UDEBUGL(1))
755 fprintf(stderr, "Starting to ponder with color %s\n", stone2str(stone_other(color)));
756 u->pondering = true;
758 /* We need a local board copy to ponder upon. */
759 struct board *b = malloc(sizeof(*b)); board_copy(b, b0);
761 /* *b0 did not have the genmove'd move played yet. */
762 struct move m = { t->root->coord, t->root_color };
763 int res = board_play(b, &m);
764 assert(res >= 0);
765 setup_dynkomi(u, b, stone_other(m.color));
767 /* Start MCTS manager thread "headless". */
768 uct_search_start(u, b, color, t);
771 /* uct_search_stop() frontend for the pondering (non-genmove) mode, and
772 * to stop the background search for a slave in the distributed engine. */
773 static void
774 uct_pondering_stop(struct uct *u)
776 if (!thread_manager_running)
777 return;
779 /* Stop the thread manager. */
780 struct spawn_ctx *ctx = uct_search_stop();
781 if (UDEBUGL(1)) {
782 if (u->pondering) fprintf(stderr, "(pondering) ");
783 uct_progress_status(u, ctx->t, ctx->color, ctx->games);
785 if (u->pondering) {
786 free(ctx->b);
787 u->pondering = false;
791 /* Common part of uct_genmove() and uct_genmoves().
792 * Returns the best node, or NULL if *best_coord is pass or resign. */
793 static struct tree_node *
794 uct_bestmove(struct engine *e, struct board *b, struct time_info *ti, enum stone color,
795 bool pass_all_alive, bool *keep_looking, coord_t *best_coord)
797 double start_time = time_now();
798 struct uct *u = e->data;
800 if (b->superko_violation) {
801 fprintf(stderr, "!!! WARNING: SUPERKO VIOLATION OCCURED BEFORE THIS MOVE\n");
802 fprintf(stderr, "Maybe you play with situational instead of positional superko?\n");
803 fprintf(stderr, "I'm going to ignore the violation, but note that I may miss\n");
804 fprintf(stderr, "some moves valid under this ruleset because of this.\n");
805 b->superko_violation = false;
808 /* Seed the tree. If we are a slave in the distributed engine,
809 * we keep thinking until the next "play" command. */
810 if (!thread_manager_running) prepare_move(e, b, color);
811 assert(u->t);
812 u->my_color = color;
814 /* How to decide whether to use dynkomi in this game? Since we use
815 * pondering, it's not simple "who-to-play" matter. Decide based on
816 * the last genmove issued. */
817 u->t->use_extra_komi = !!(u->dynkomi_mask & color);
818 setup_dynkomi(u, b, color);
820 if (b->rules == RULES_JAPANESE)
821 u->territory_scoring = true;
823 /* Make pessimistic assumption about komi for Japanese rules to
824 * avoid losing by 0.5 when winning by 0.5 with Chinese rules.
825 * The rules usually give the same winner if the integer part of komi
826 * is odd so we adjust the komi only if it is even (for a board of
827 * odd size). We are not trying to get an exact evaluation for rare
828 * cases of seki. For details see http://home.snafu.de/jasiek/parity.html */
829 if (u->territory_scoring && (((int)floor(b->komi) + board_size(b)) & 1)) {
830 b->komi += (color == S_BLACK ? 1.0 : -1.0);
831 if (UDEBUGL(0))
832 fprintf(stderr, "Setting komi to %.1f assuming Japanese rules\n",
833 b->komi);
836 int base_playouts = u->t->root->u.playouts;
837 /* Start or continue the Monte Carlo Tree Search! */
838 int played_games = uct_search(u, b, ti, color, u->t, keep_looking);
839 u->played_own += played_games;
841 /* Choose the best move from the tree. */
842 struct tree_node *best = u->policy->choose(u->policy, u->t->root, b, color, resign);
843 if (!best) {
844 *best_coord = pass;
845 return NULL;
847 *best_coord = best->coord;
848 if (UDEBUGL(1))
849 fprintf(stderr, "*** WINNER is %s (%d,%d) with score %1.4f (%d/%d:%d/%d games), extra komi %f\n",
850 coord2sstr(best->coord, b), coord_x(best->coord, b), coord_y(best->coord, b),
851 tree_node_get_value(u->t, 1, best->u.value), best->u.playouts,
852 u->t->root->u.playouts, u->t->root->u.playouts - base_playouts, played_games,
853 u->t->extra_komi);
855 /* Do not resign if we're so short of time that evaluation of best
856 * move is completely unreliable, we might be winning actually.
857 * In this case best is almost random but still better than resign.
858 * Also do not resign if we are getting bad results while actually
859 * giving away extra komi points (dynkomi). */
860 if (tree_node_get_value(u->t, 1, best->u.value) < u->resign_ratio
861 && !is_pass(best->coord) && best->u.playouts > GJ_MINGAMES
862 && u->t->extra_komi <= 1 /* XXX we assume dynamic komi == we are black */) {
863 *best_coord = resign;
864 return NULL;
867 /* If the opponent just passed and we win counting, always
868 * pass as well. */
869 if (b->moves > 1 && is_pass(b->last_move.coord)) {
870 /* Make sure enough playouts are simulated. */
871 while (u->ownermap.playouts < GJ_MINGAMES)
872 uct_playout(u, b, color, u->t);
873 if (uct_pass_is_safe(u, b, color, u->pass_all_alive || pass_all_alive)) {
874 if (UDEBUGL(0))
875 fprintf(stderr, "<Will rather pass, looks safe enough.>\n");
876 *best_coord = pass;
877 best = NULL;
881 if (UDEBUGL(2)) {
882 double time = time_now() - start_time + 0.000001; /* avoid divide by zero */
883 fprintf(stderr, "genmove in %0.2fs (%d games/s, %d games/s/thread)\n",
884 time, (int)(played_games/time), (int)(played_games/time/u->threads));
886 return best;
889 static coord_t *
890 uct_genmove(struct engine *e, struct board *b, struct time_info *ti, enum stone color, bool pass_all_alive)
892 struct uct *u = e->data;
893 uct_pondering_stop(u);
895 bool keep_looking;
896 coord_t best_coord;
897 struct tree_node *best;
898 best = uct_bestmove(e, b, ti, color, pass_all_alive, &keep_looking, &best_coord);
899 if (!best) {
900 reset_state(u);
901 return coord_copy(best_coord);
903 tree_promote_node(u->t, &best);
905 /* After a pass, pondering is harmful for two reasons:
906 * (i) We might keep pondering even when the game is over.
907 * Of course this is the case for opponent resign as well.
908 * (ii) More importantly, the ownermap will get skewed since
909 * the UCT will start cutting off any playouts. */
910 if (u->pondering_opt && !is_pass(best->coord)) {
911 uct_pondering_start(u, b, u->t, stone_other(color));
913 return coord_copy(best_coord);
916 /* Get stats updates for the distributed engine. Return a buffer
917 * with one line "total_playouts threads keep_looking" then a list of lines
918 * "coord playouts value". The last line must not end with \n.
919 * If c is pass or resign, add this move with root->playouts weight.
920 * This function is called only by the main thread, but may be
921 * called while the tree is updated by the worker threads.
922 * Keep this code in sync with select_best_move(). */
923 static char *
924 uct_getstats(struct uct *u, struct board *b, coord_t c, bool keep_looking)
926 static char reply[10240];
927 char *r = reply;
928 char *end = reply + sizeof(reply);
929 struct tree_node *root = u->t->root;
930 r += snprintf(r, end - r, "%d %d %d %d", u->played_own, root->u.playouts, u->threads, keep_looking);
931 int min_playouts = root->u.playouts / 100;
933 // Give a large weight to pass or resign, but still allow other moves.
934 if (is_pass(c) || is_resign(c))
935 r += snprintf(r, end - r, "\n%s %d %.1f", coord2sstr(c, b), root->u.playouts,
936 (float)is_pass(c));
938 /* We rely on the fact that root->children is set only
939 * after all children are created. */
940 for (struct tree_node *ni = root->children; ni; ni = ni->sibling) {
942 if (is_pass(ni->coord)) continue;
943 struct node_stats *ns = &u->stats[ni->coord];
944 ns->last_sent_own.playouts = 0;
945 ns->node = ni;
946 if (ni->u.playouts <= min_playouts || ni->hints & TREE_HINT_INVALID)
947 continue;
949 char *coord = coord2sstr(ni->coord, b);
950 /* We return the values as stored in the tree, so from black's view.
951 * own = total_in_tree - added_from_others */
952 struct move_stats s = ni->u;
953 struct move_stats others = ns->added_from_others;
954 if (s.playouts - others.playouts <= min_playouts)
955 continue;
956 if (others.playouts)
957 stats_rm_result(&s, others.value, others.playouts);
959 r += snprintf(r, end - r, "\n%s %d %.7f", coord, s.playouts, s.value);
960 ns->last_sent_own = s;
961 /* If the master discards these values because this slave
962 * is out of sync, u->stats will be reset anyway. */
964 return reply;
967 /* Set mapping from coordinates to children of the root node. */
968 static void
969 find_top_nodes(struct uct *u)
971 if (!u->t || !u->t->root) return;
973 for (struct tree_node *ni = u->t->root->children; ni; ni = ni->sibling) {
974 if (!is_pass(ni->coord))
975 u->stats[ni->coord].node = ni;
979 /* genmoves returns a line "=id total_playouts threads keep_looking[ reserved]"
980 * then a list of lines "coord playouts value" terminated by \n\n.
981 * It also takes as input a list of lines "coord playouts value" to get stats
982 * of other slaves, except for the first call at a given move number. */
983 static char *
984 uct_genmoves(struct engine *e, struct board *b, struct time_info *ti, enum stone color,
985 char *args, bool pass_all_alive)
987 struct uct *u = e->data;
988 assert(u->slave);
990 /* Get playouts and time information from master.
991 * Keep this code in sync with distributed_genmove(). */
992 if ((ti->dim == TD_WALLTIME
993 && sscanf(args, "%d %lf %lf %d %d", &u->played_all, &ti->len.t.main_time,
994 &ti->len.t.byoyomi_time, &ti->len.t.byoyomi_periods,
995 &ti->len.t.byoyomi_stones) != 5)
997 || (ti->dim == TD_GAMES && sscanf(args, "%d", &u->played_all) != 1)) {
998 return NULL;
1001 /* Get the move stats if they are present. They are
1002 * coord-sorted but the code here doesn't depend on this.
1003 * Keep this code in sync with select_best_move(). */
1005 char line[128];
1006 while (fgets(line, sizeof(line), stdin) && *line != '\n') {
1007 char move[64];
1008 struct move_stats s;
1009 if (sscanf(line, "%63s %d %f", move, &s.playouts, &s.value) != 3)
1010 return NULL;
1011 coord_t *c_ = str2coord(move, board_size(b));
1012 coord_t c = *c_;
1013 coord_done(c_);
1014 assert(!is_pass(c) && !is_resign(c));
1016 struct node_stats *ns = &u->stats[c];
1017 if (!ns->node) find_top_nodes(u);
1018 /* The node may not exist if this slave was behind
1019 * but this should be rare so it is not worth creating
1020 * the node here. */
1021 if (!ns->node) {
1022 if (DEBUGL(0))
1023 fprintf(stderr, "can't find node %s %d\n", move, c);
1024 continue;
1027 /* The master may not send moves below a certain threshold,
1028 * but if it sends one it includes the contributions from
1029 * all slaves including ours (last_sent_own):
1030 * received_others = received_total - last_sent_own */
1031 if (ns->last_sent_own.playouts)
1032 stats_rm_result(&s, ns->last_sent_own.value,
1033 ns->last_sent_own.playouts);
1035 /* others_delta = received_others - added_from_others */
1036 struct move_stats delta = s;
1037 if (ns->added_from_others.playouts)
1038 stats_rm_result(&delta, ns->added_from_others.value,
1039 ns->added_from_others.playouts);
1040 /* delta may be <= 0 if some slaves stopped sending this move
1041 * because it became below a playouts threshold. In this case
1042 * we just keep the old stats in our tree. */
1043 if (delta.playouts <= 0) continue;
1045 stats_add_result(&ns->node->u, delta.value, delta.playouts);
1046 ns->added_from_others = s;
1049 bool keep_looking;
1050 coord_t best_coord;
1051 uct_bestmove(e, b, ti, color, pass_all_alive, &keep_looking, &best_coord);
1053 char *reply = uct_getstats(u, b, best_coord, keep_looking);
1054 return reply;
1058 bool
1059 uct_genbook(struct engine *e, struct board *b, struct time_info *ti, enum stone color)
1061 struct uct *u = e->data;
1062 if (!u->t) prepare_move(e, b, color);
1063 assert(u->t);
1065 if (ti->dim == TD_GAMES) {
1066 /* Don't count in games that already went into the book. */
1067 ti->len.games += u->t->root->u.playouts;
1069 bool keep_looking;
1070 uct_search(u, b, ti, color, u->t, &keep_looking);
1072 assert(ti->dim == TD_GAMES);
1073 tree_save(u->t, b, ti->len.games / 100);
1075 return true;
1078 void
1079 uct_dumpbook(struct engine *e, struct board *b, enum stone color)
1081 struct uct *u = e->data;
1082 struct tree *t = tree_init(b, color, u->fast_alloc ? u->max_tree_size : 0, u->local_tree_aging);
1083 tree_load(t, b);
1084 tree_dump(t, 0);
1085 tree_done(t);
1089 struct uct *
1090 uct_state_init(char *arg, struct board *b)
1092 struct uct *u = calloc(1, sizeof(struct uct));
1093 bool using_elo = false;
1095 u->debug_level = debug_level;
1096 u->gamelen = MC_GAMELEN;
1097 u->mercymin = 0;
1098 u->expand_p = 2;
1099 u->dumpthres = 1000;
1100 u->playout_amaf = true;
1101 u->playout_amaf_nakade = false;
1102 u->amaf_prior = false;
1103 u->max_tree_size = 3072ULL * 1048576;
1105 u->dynkomi_mask = S_BLACK;
1107 u->threads = 1;
1108 u->thread_model = TM_TREEVL;
1109 u->parallel_tree = true;
1110 u->virtual_loss = true;
1112 u->fuseki_end = 20; // max time at 361*20% = 72 moves (our 36th move, still 99 to play)
1113 u->yose_start = 40; // (100-40-25)*361/100/2 = 63 moves still to play by us then
1114 u->bestr_ratio = 0.02;
1115 // 2.5 is clearly too much, but seems to compensate well for overly stern time allocations.
1116 // TODO: Further tuning and experiments with better time allocation schemes.
1117 u->best2_ratio = 2.5;
1119 u->val_scale = 0.04; u->val_points = 40;
1121 u->tenuki_d = 4;
1122 u->local_tree_aging = 2;
1124 if (arg) {
1125 char *optspec, *next = arg;
1126 while (*next) {
1127 optspec = next;
1128 next += strcspn(next, ",");
1129 if (*next) { *next++ = 0; } else { *next = 0; }
1131 char *optname = optspec;
1132 char *optval = strchr(optspec, '=');
1133 if (optval) *optval++ = 0;
1135 if (!strcasecmp(optname, "debug")) {
1136 if (optval)
1137 u->debug_level = atoi(optval);
1138 else
1139 u->debug_level++;
1140 } else if (!strcasecmp(optname, "mercy") && optval) {
1141 /* Minimal difference of black/white captures
1142 * to stop playout - "Mercy Rule". Speeds up
1143 * hopeless playouts at the expense of some
1144 * accuracy. */
1145 u->mercymin = atoi(optval);
1146 } else if (!strcasecmp(optname, "gamelen") && optval) {
1147 u->gamelen = atoi(optval);
1148 } else if (!strcasecmp(optname, "expand_p") && optval) {
1149 u->expand_p = atoi(optval);
1150 } else if (!strcasecmp(optname, "dumpthres") && optval) {
1151 u->dumpthres = atoi(optval);
1152 } else if (!strcasecmp(optname, "best2_ratio") && optval) {
1153 /* If set, prolong simulating while
1154 * first_best/second_best playouts ratio
1155 * is less than best2_ratio. */
1156 u->best2_ratio = atof(optval);
1157 } else if (!strcasecmp(optname, "bestr_ratio") && optval) {
1158 /* If set, prolong simulating while
1159 * best,best_best_child values delta
1160 * is more than bestr_ratio. */
1161 u->bestr_ratio = atof(optval);
1162 } else if (!strcasecmp(optname, "playout_amaf")) {
1163 /* Whether to include random playout moves in
1164 * AMAF as well. (Otherwise, only tree moves
1165 * are included in AMAF. Of course makes sense
1166 * only in connection with an AMAF policy.) */
1167 /* with-without: 55.5% (+-4.1) */
1168 if (optval && *optval == '0')
1169 u->playout_amaf = false;
1170 else
1171 u->playout_amaf = true;
1172 } else if (!strcasecmp(optname, "playout_amaf_nakade")) {
1173 /* Whether to include nakade moves from playouts
1174 * in the AMAF statistics; this tends to nullify
1175 * the playout_amaf effect by adding too much
1176 * noise. */
1177 if (optval && *optval == '0')
1178 u->playout_amaf_nakade = false;
1179 else
1180 u->playout_amaf_nakade = true;
1181 } else if (!strcasecmp(optname, "playout_amaf_cutoff") && optval) {
1182 /* Keep only first N% of playout stage AMAF
1183 * information. */
1184 u->playout_amaf_cutoff = atoi(optval);
1185 } else if ((!strcasecmp(optname, "policy") || !strcasecmp(optname, "random_policy")) && optval) {
1186 char *policyarg = strchr(optval, ':');
1187 struct uct_policy **p = !strcasecmp(optname, "policy") ? &u->policy : &u->random_policy;
1188 if (policyarg)
1189 *policyarg++ = 0;
1190 if (!strcasecmp(optval, "ucb1")) {
1191 *p = policy_ucb1_init(u, policyarg);
1192 } else if (!strcasecmp(optval, "ucb1amaf")) {
1193 *p = policy_ucb1amaf_init(u, policyarg);
1194 } else {
1195 fprintf(stderr, "UCT: Invalid tree policy %s\n", optval);
1196 exit(1);
1198 } else if (!strcasecmp(optname, "playout") && optval) {
1199 char *playoutarg = strchr(optval, ':');
1200 if (playoutarg)
1201 *playoutarg++ = 0;
1202 if (!strcasecmp(optval, "moggy")) {
1203 u->playout = playout_moggy_init(playoutarg, b);
1204 } else if (!strcasecmp(optval, "light")) {
1205 u->playout = playout_light_init(playoutarg, b);
1206 } else if (!strcasecmp(optval, "elo")) {
1207 u->playout = playout_elo_init(playoutarg, b);
1208 using_elo = true;
1209 } else {
1210 fprintf(stderr, "UCT: Invalid playout policy %s\n", optval);
1211 exit(1);
1213 } else if (!strcasecmp(optname, "prior") && optval) {
1214 u->prior = uct_prior_init(optval, b);
1215 } else if (!strcasecmp(optname, "amaf_prior") && optval) {
1216 u->amaf_prior = atoi(optval);
1217 } else if (!strcasecmp(optname, "threads") && optval) {
1218 /* By default, Pachi will run with only single
1219 * tree search thread! */
1220 u->threads = atoi(optval);
1221 } else if (!strcasecmp(optname, "thread_model") && optval) {
1222 if (!strcasecmp(optval, "root")) {
1223 /* Root parallelization - each thread
1224 * does independent search, trees are
1225 * merged at the end. */
1226 u->thread_model = TM_ROOT;
1227 u->parallel_tree = false;
1228 u->virtual_loss = false;
1229 } else if (!strcasecmp(optval, "tree")) {
1230 /* Tree parallelization - all threads
1231 * grind on the same tree. */
1232 u->thread_model = TM_TREE;
1233 u->parallel_tree = true;
1234 u->virtual_loss = false;
1235 } else if (!strcasecmp(optval, "treevl")) {
1236 /* Tree parallelization, but also
1237 * with virtual losses - this discou-
1238 * rages most threads choosing the
1239 * same tree branches to read. */
1240 u->thread_model = TM_TREEVL;
1241 u->parallel_tree = true;
1242 u->virtual_loss = true;
1243 } else {
1244 fprintf(stderr, "UCT: Invalid thread model %s\n", optval);
1245 exit(1);
1247 } else if (!strcasecmp(optname, "pondering")) {
1248 /* Keep searching even during opponent's turn. */
1249 u->pondering_opt = !optval || atoi(optval);
1250 } else if (!strcasecmp(optname, "fuseki_end") && optval) {
1251 /* At the very beginning it's not worth thinking
1252 * too long because the playout evaluations are
1253 * very noisy. So gradually increase the thinking
1254 * time up to maximum when fuseki_end percent
1255 * of the board has been played.
1256 * This only applies if we are not in byoyomi. */
1257 u->fuseki_end = atoi(optval);
1258 } else if (!strcasecmp(optname, "yose_start") && optval) {
1259 /* When yose_start percent of the board has been
1260 * played, or if we are in byoyomi, stop spending
1261 * more time and spread the remaining time
1262 * uniformly.
1263 * Between fuseki_end and yose_start, we spend
1264 * a constant proportion of the remaining time
1265 * on each move. (yose_start should actually
1266 * be much earlier than when real yose start,
1267 * but "yose" is a good short name to convey
1268 * the idea.) */
1269 u->yose_start = atoi(optval);
1270 } else if (!strcasecmp(optname, "force_seed") && optval) {
1271 u->force_seed = atoi(optval);
1272 } else if (!strcasecmp(optname, "no_book")) {
1273 u->no_book = true;
1274 } else if (!strcasecmp(optname, "dynkomi") && optval) {
1275 /* Dynamic komi approach; there are multiple
1276 * ways to adjust komi dynamically throughout
1277 * play. We currently support two: */
1278 char *dynkomiarg = strchr(optval, ':');
1279 if (dynkomiarg)
1280 *dynkomiarg++ = 0;
1281 if (!strcasecmp(optval, "none")) {
1282 u->dynkomi = uct_dynkomi_init_none(u, dynkomiarg, b);
1283 } else if (!strcasecmp(optval, "linear")) {
1284 u->dynkomi = uct_dynkomi_init_linear(u, dynkomiarg, b);
1285 } else if (!strcasecmp(optval, "adaptive")) {
1286 u->dynkomi = uct_dynkomi_init_adaptive(u, dynkomiarg, b);
1287 } else {
1288 fprintf(stderr, "UCT: Invalid dynkomi mode %s\n", optval);
1289 exit(1);
1291 } else if (!strcasecmp(optname, "dynkomi_mask") && optval) {
1292 /* Bitmask of colors the player must be
1293 * for dynkomi be applied; you may want
1294 * to use dynkomi_mask=3 to allow dynkomi
1295 * even in games where Pachi is white. */
1296 u->dynkomi_mask = atoi(optval);
1297 } else if (!strcasecmp(optname, "dynkomi_interval") && optval) {
1298 /* If non-zero, re-adjust dynamic komi
1299 * throughout a single genmove reading,
1300 * roughly every N simulations. */
1301 /* XXX: Does not work with tree
1302 * parallelization. */
1303 u->dynkomi_interval = atoi(optval);
1304 } else if (!strcasecmp(optname, "val_scale") && optval) {
1305 /* How much of the game result value should be
1306 * influenced by win size. Zero means it isn't. */
1307 u->val_scale = atof(optval);
1308 } else if (!strcasecmp(optname, "val_points") && optval) {
1309 /* Maximum size of win to be scaled into game
1310 * result value. Zero means boardsize^2. */
1311 u->val_points = atoi(optval) * 2; // result values are doubled
1312 } else if (!strcasecmp(optname, "val_extra")) {
1313 /* If false, the score coefficient will be simply
1314 * added to the value, instead of scaling the result
1315 * coefficient because of it. */
1316 u->val_extra = !optval || atoi(optval);
1317 } else if (!strcasecmp(optname, "local_tree") && optval) {
1318 /* Whether to bias exploration by local tree values
1319 * (must be supported by the used policy).
1320 * 0: Don't.
1321 * 1: Do, value = result.
1322 * Try to temper the result:
1323 * 2: Do, value = 0.5+(result-expected)/2.
1324 * 3: Do, value = 0.5+bzz((result-expected)^2).
1325 * 4: Do, value = 0.5+sqrt(result-expected)/2. */
1326 u->local_tree = atoi(optval);
1327 } else if (!strcasecmp(optname, "tenuki_d") && optval) {
1328 /* Tenuki distance at which to break the local tree. */
1329 u->tenuki_d = atoi(optval);
1330 if (u->tenuki_d > TREE_NODE_D_MAX + 1) {
1331 fprintf(stderr, "uct: tenuki_d must not be larger than TREE_NODE_D_MAX+1 %d\n", TREE_NODE_D_MAX + 1);
1332 exit(1);
1334 } else if (!strcasecmp(optname, "local_tree_aging") && optval) {
1335 /* How much to reduce local tree values between moves. */
1336 u->local_tree_aging = atof(optval);
1337 } else if (!strcasecmp(optname, "local_tree_allseq")) {
1338 /* By default, only complete sequences are stored
1339 * in the local tree. If this is on, also
1340 * subsequences starting at each move are stored. */
1341 u->local_tree_allseq = !optval || atoi(optval);
1342 } else if (!strcasecmp(optname, "local_tree_playout")) {
1343 /* Whether to adjust ELO playout probability
1344 * distributions according to matched localtree
1345 * information. */
1346 u->local_tree_playout = !optval || atoi(optval);
1347 } else if (!strcasecmp(optname, "local_tree_pseqroot")) {
1348 /* By default, when we have no sequence move
1349 * to suggest in-playout, we give up. If this
1350 * is on, we make probability distribution from
1351 * sequences first moves instead. */
1352 u->local_tree_pseqroot = !optval || atoi(optval);
1353 } else if (!strcasecmp(optname, "pass_all_alive")) {
1354 /* Whether to consider all stones alive at the game
1355 * end instead of marking dead groupd. */
1356 u->pass_all_alive = !optval || atoi(optval);
1357 } else if (!strcasecmp(optname, "territory_scoring")) {
1358 /* Use territory scoring (default is area scoring).
1359 * An explicit kgs-rules command overrides this. */
1360 u->territory_scoring = !optval || atoi(optval);
1361 } else if (!strcasecmp(optname, "random_policy_chance") && optval) {
1362 /* If specified (N), with probability 1/N, random_policy policy
1363 * descend is used instead of main policy descend; useful
1364 * if specified policy (e.g. UCB1AMAF) can make unduly biased
1365 * choices sometimes, you can fall back to e.g.
1366 * random_policy=UCB1. */
1367 u->random_policy_chance = atoi(optval);
1368 } else if (!strcasecmp(optname, "max_tree_size") && optval) {
1369 /* Maximum amount of memory [MiB] consumed by the move tree.
1370 * For fast_alloc it includes the temp tree used for pruning.
1371 * Default is 3072 (3 GiB). Note that if you use TM_ROOT,
1372 * this limits size of only one of the trees, not all of them
1373 * together. */
1374 u->max_tree_size = atol(optval) * 1048576;
1375 } else if (!strcasecmp(optname, "fast_alloc")) {
1376 u->fast_alloc = !optval || atoi(optval);
1377 } else if (!strcasecmp(optname, "slave")) {
1378 /* Act as slave for the distributed engine. */
1379 u->slave = !optval || atoi(optval);
1380 } else if (!strcasecmp(optname, "banner") && optval) {
1381 /* Additional banner string. This must come as the
1382 * last engine parameter. */
1383 if (*next) *--next = ',';
1384 u->banner = strdup(optval);
1385 break;
1386 } else {
1387 fprintf(stderr, "uct: Invalid engine argument %s or missing value\n", optname);
1388 exit(1);
1393 u->resign_ratio = 0.2; /* Resign when most games are lost. */
1394 u->loss_threshold = 0.85; /* Stop reading if after at least 2000 playouts this is best value. */
1395 if (!u->policy)
1396 u->policy = policy_ucb1amaf_init(u, NULL);
1398 if (!!u->random_policy_chance ^ !!u->random_policy) {
1399 fprintf(stderr, "uct: Only one of random_policy and random_policy_chance is set\n");
1400 exit(1);
1403 if (!u->local_tree) {
1404 /* No ltree aging. */
1405 u->local_tree_aging = 1.0f;
1407 if (!using_elo)
1408 u->local_tree_playout = false;
1410 if (u->fast_alloc && !u->parallel_tree) {
1411 fprintf(stderr, "fast_alloc not supported with root parallelization.\n");
1412 exit(1);
1414 if (u->fast_alloc)
1415 u->max_tree_size = (100ULL * u->max_tree_size) / (100 + MIN_FREE_MEM_PERCENT);
1417 if (!u->prior)
1418 u->prior = uct_prior_init(NULL, b);
1420 if (!u->playout)
1421 u->playout = playout_moggy_init(NULL, b);
1422 u->playout->debug_level = u->debug_level;
1424 u->ownermap.map = malloc(board_size2(b) * sizeof(u->ownermap.map[0]));
1425 u->stats = malloc(board_size2(b) * sizeof(u->stats[0]));
1427 if (!u->dynkomi)
1428 u->dynkomi = uct_dynkomi_init_linear(u, NULL, b);
1430 /* Some things remain uninitialized for now - the opening book
1431 * is not loaded and the tree not set up. */
1432 /* This will be initialized in setup_state() at the first move
1433 * received/requested. This is because right now we are not aware
1434 * about any komi or handicap setup and such. */
1436 return u;
1439 struct engine *
1440 engine_uct_init(char *arg, struct board *b)
1442 struct uct *u = uct_state_init(arg, b);
1443 struct engine *e = calloc(1, sizeof(struct engine));
1444 e->name = "UCT Engine";
1445 e->printhook = uct_printhook_ownermap;
1446 e->notify_play = uct_notify_play;
1447 e->chat = uct_chat;
1448 e->genmove = uct_genmove;
1449 e->genmoves = uct_genmoves;
1450 e->dead_group_list = uct_dead_group_list;
1451 e->done = uct_done;
1452 e->data = u;
1453 if (u->slave)
1454 e->notify = uct_notify;
1456 const char banner[] = "I'm playing UCT. When I'm losing, I will resign, "
1457 "if I think I win, I play until you pass. "
1458 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
1459 if (!u->banner) u->banner = "";
1460 e->comment = malloc(sizeof(banner) + strlen(u->banner) + 1);
1461 sprintf(e->comment, "%s %s", banner, u->banner);
1463 return e;