uct_notify(): Stop background search on new game to avoid using deallocated board.
[pachi.git] / uct / uct.c
blobe88662a0db9bc564c08f8d34b96125706ab2eed5
1 #include <assert.h>
2 #include <math.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <string.h>
6 #include <time.h>
8 #define DEBUG
10 #include "debug.h"
11 #include "board.h"
12 #include "gtp.h"
13 #include "move.h"
14 #include "mq.h"
15 #include "playout.h"
16 #include "playout/elo.h"
17 #include "playout/moggy.h"
18 #include "playout/light.h"
19 #include "tactics.h"
20 #include "timeinfo.h"
21 #include "distributed/distributed.h"
22 #include "uct/dynkomi.h"
23 #include "uct/internal.h"
24 #include "uct/prior.h"
25 #include "uct/search.h"
26 #include "uct/slave.h"
27 #include "uct/tree.h"
28 #include "uct/uct.h"
29 #include "uct/walk.h"
31 struct uct_policy *policy_ucb1_init(struct uct *u, char *arg);
32 struct uct_policy *policy_ucb1amaf_init(struct uct *u, char *arg);
33 static void uct_pondering_start(struct uct *u, struct board *b0, struct tree *t, enum stone color);
35 /* Maximal simulation length. */
36 #define MC_GAMELEN MAX_GAMELEN
39 static void
40 setup_state(struct uct *u, struct board *b, enum stone color)
42 u->t = tree_init(b, color, u->fast_alloc ? u->max_tree_size : 0, u->local_tree_aging);
43 if (u->force_seed)
44 fast_srandom(u->force_seed);
45 if (UDEBUGL(0))
46 fprintf(stderr, "Fresh board with random seed %lu\n", fast_getseed());
47 //board_print(b, stderr);
48 if (!u->no_book && b->moves == 0) {
49 assert(color == S_BLACK);
50 tree_load(u->t, b);
54 static void
55 reset_state(struct uct *u)
57 assert(u->t);
58 tree_done(u->t); u->t = NULL;
61 static void
62 setup_dynkomi(struct uct *u, struct board *b, enum stone to_play)
64 if (u->t->use_extra_komi && u->dynkomi->permove)
65 u->t->extra_komi = u->dynkomi->permove(u->dynkomi, b, u->t);
68 void
69 uct_prepare_move(struct uct *u, struct board *b, enum stone color)
71 if (u->t) {
72 /* Verify that we have sane state. */
73 assert(b->es == u);
74 assert(u->t && b->moves);
75 if (color != stone_other(u->t->root_color)) {
76 fprintf(stderr, "Fatal: Non-alternating play detected %d %d\n",
77 color, u->t->root_color);
78 exit(1);
81 } else {
82 /* We need fresh state. */
83 b->es = u;
84 setup_state(u, b, color);
87 u->ownermap.playouts = 0;
88 memset(u->ownermap.map, 0, board_size2(b) * sizeof(u->ownermap.map[0]));
89 memset(u->stats, 0, board_size2(b) * sizeof(u->stats[0]));
90 u->played_own = u->played_all = 0;
93 static void
94 dead_group_list(struct uct *u, struct board *b, struct move_queue *mq)
96 struct group_judgement gj;
97 gj.thres = GJ_THRES;
98 gj.gs = alloca(board_size2(b) * sizeof(gj.gs[0]));
99 board_ownermap_judge_group(b, &u->ownermap, &gj);
100 groups_of_status(b, &gj, GS_DEAD, mq);
103 bool
104 uct_pass_is_safe(struct uct *u, struct board *b, enum stone color, bool pass_all_alive)
106 if (u->ownermap.playouts < GJ_MINGAMES)
107 return false;
109 struct move_queue mq = { .moves = 0 };
110 dead_group_list(u, b, &mq);
111 if (pass_all_alive && mq.moves > 0)
112 return false; // We need to remove some dead groups first.
113 return pass_is_safe(b, color, &mq);
116 static char *
117 uct_printhook_ownermap(struct board *board, coord_t c, char *s, char *end)
119 struct uct *u = board->es;
120 assert(u);
121 const char chr[] = ":XO,"; // dame, black, white, unclear
122 const char chm[] = ":xo,";
123 char ch = chr[board_ownermap_judge_point(&u->ownermap, c, GJ_THRES)];
124 if (ch == ',') { // less precise estimate then?
125 ch = chm[board_ownermap_judge_point(&u->ownermap, c, 0.67)];
127 s += snprintf(s, end - s, "%c ", ch);
128 return s;
131 static char *
132 uct_notify_play(struct engine *e, struct board *b, struct move *m)
134 struct uct *u = e->data;
135 if (!u->t) {
136 /* No state, create one - this is probably game beginning
137 * and we need to load the opening book right now. */
138 uct_prepare_move(u, b, m->color);
139 assert(u->t);
142 /* Stop pondering, required by tree_promote_at() */
143 uct_pondering_stop(u);
144 if (UDEBUGL(2) && u->slave)
145 tree_dump(u->t, u->dumpthres);
147 if (is_resign(m->coord)) {
148 /* Reset state. */
149 reset_state(u);
150 return NULL;
153 /* Promote node of the appropriate move to the tree root. */
154 assert(u->t->root);
155 if (!tree_promote_at(u->t, b, m->coord)) {
156 if (UDEBUGL(0))
157 fprintf(stderr, "Warning: Cannot promote move node! Several play commands in row?\n");
158 reset_state(u);
159 return NULL;
162 /* If we are a slave in a distributed engine, start pondering once
163 * we know which move we actually played. See uct_genmove() about
164 * the check for pass. */
165 if (u->pondering_opt && u->slave && m->color == u->my_color && !is_pass(m->coord))
166 uct_pondering_start(u, b, u->t, stone_other(m->color));
168 return NULL;
171 static char *
172 uct_chat(struct engine *e, struct board *b, char *cmd)
174 struct uct *u = e->data;
175 static char reply[1024];
177 cmd += strspn(cmd, " \n\t");
178 if (!strncasecmp(cmd, "winrate", 7)) {
179 if (!u->t)
180 return "no game context (yet?)";
181 enum stone color = u->t->root_color;
182 struct tree_node *n = u->t->root;
183 snprintf(reply, 1024, "In %d playouts at %d threads, %s %s can win with %.2f%% probability",
184 n->u.playouts, u->threads, stone2str(color), coord2sstr(n->coord, b),
185 tree_node_get_value(u->t, -1, n->u.value) * 100);
186 if (u->t->use_extra_komi && abs(u->t->extra_komi) >= 0.5) {
187 sprintf(reply + strlen(reply), ", while self-imposing extra komi %.1f",
188 u->t->extra_komi);
190 strcat(reply, ".");
191 return reply;
193 return NULL;
196 static void
197 uct_dead_group_list(struct engine *e, struct board *b, struct move_queue *mq)
199 struct uct *u = e->data;
201 /* This means the game is probably over, no use pondering on. */
202 uct_pondering_stop(u);
204 if (u->pass_all_alive)
205 return; // no dead groups
207 bool mock_state = false;
209 if (!u->t) {
210 /* No state, but we cannot just back out - we might
211 * have passed earlier, only assuming some stones are
212 * dead, and then re-connected, only to lose counting
213 * when all stones are assumed alive. */
214 /* Mock up some state and seed the ownermap by few
215 * simulations. */
216 uct_prepare_move(u, b, S_BLACK); assert(u->t);
217 for (int i = 0; i < GJ_MINGAMES; i++)
218 uct_playout(u, b, S_BLACK, u->t);
219 mock_state = true;
222 dead_group_list(u, b, mq);
224 if (mock_state) {
225 /* Clean up the mock state in case we will receive
226 * a genmove; we could get a non-alternating-move
227 * error from uct_prepare_move() in that case otherwise. */
228 reset_state(u);
232 static void
233 playout_policy_done(struct playout_policy *p)
235 if (p->done) p->done(p);
236 if (p->data) free(p->data);
237 free(p);
240 static void
241 uct_done(struct engine *e)
243 /* This is called on engine reset, especially when clear_board
244 * is received and new game should begin. */
245 struct uct *u = e->data;
246 uct_pondering_stop(u);
247 if (u->t) reset_state(u);
248 free(u->ownermap.map);
249 free(u->stats);
251 free(u->policy);
252 free(u->random_policy);
253 playout_policy_done(u->playout);
254 uct_prior_done(u->prior);
259 /* Run time-limited MCTS search on foreground. */
260 static int
261 uct_search(struct uct *u, struct board *b, struct time_info *ti, enum stone color, struct tree *t)
263 struct uct_search_state s;
264 uct_search_start(u, b, color, t, ti, &s);
265 if (UDEBUGL(2) && s.base_playouts > 0)
266 fprintf(stderr, "<pre-simulated %d games>\n", s.base_playouts);
268 /* The search tree is ctx->t. This is normally == t, but in case of
269 * TM_ROOT, it is one of the trees belonging to the independent
270 * workers. It is important to reference ctx->t directly since the
271 * thread manager will swap the tree pointer asynchronously. */
272 /* XXX: This means TM_ROOT support is suboptimal since single stalled
273 * thread can stall the others in case of limiting the search by game
274 * count. However, TM_ROOT just does not deserve any more extra code
275 * right now. */
277 /* Now, just periodically poll the search tree. */
278 while (1) {
279 time_sleep(TREE_BUSYWAIT_INTERVAL);
280 /* TREE_BUSYWAIT_INTERVAL should never be less than desired time, or the
281 * time control is broken. But if it happens to be less, we still search
282 * at least 100ms otherwise the move is completely random. */
284 int i = uct_search_games(&s);
285 /* Print notifications etc. */
286 uct_search_progress(u, b, color, t, ti, &s, i);
287 /* Check if we should stop the search. */
288 if (uct_search_check_stop(u, b, color, t, ti, &s, i))
289 break;
292 struct uct_thread_ctx *ctx = uct_search_stop();
293 if (UDEBUGL(2)) tree_dump(t, u->dumpthres);
294 if (UDEBUGL(2))
295 fprintf(stderr, "(avg score %f/%d value %f/%d)\n",
296 u->dynkomi->score.value, u->dynkomi->score.playouts,
297 u->dynkomi->value.value, u->dynkomi->value.playouts);
298 if (UDEBUGL(0))
299 uct_progress_status(u, t, color, ctx->games);
301 u->played_own += ctx->games;
302 return ctx->games;
305 /* Start pondering background with @color to play. */
306 static void
307 uct_pondering_start(struct uct *u, struct board *b0, struct tree *t, enum stone color)
309 if (UDEBUGL(1))
310 fprintf(stderr, "Starting to ponder with color %s\n", stone2str(stone_other(color)));
311 u->pondering = true;
313 /* We need a local board copy to ponder upon. */
314 struct board *b = malloc2(sizeof(*b)); board_copy(b, b0);
316 /* *b0 did not have the genmove'd move played yet. */
317 struct move m = { t->root->coord, t->root_color };
318 int res = board_play(b, &m);
319 assert(res >= 0);
320 setup_dynkomi(u, b, stone_other(m.color));
322 /* Start MCTS manager thread "headless". */
323 static struct uct_search_state s;
324 uct_search_start(u, b, color, t, NULL, &s);
327 /* uct_search_stop() frontend for the pondering (non-genmove) mode, and
328 * to stop the background search for a slave in the distributed engine. */
329 void
330 uct_pondering_stop(struct uct *u)
332 if (!thread_manager_running)
333 return;
335 /* Stop the thread manager. */
336 struct uct_thread_ctx *ctx = uct_search_stop();
337 if (UDEBUGL(1)) {
338 if (u->pondering) fprintf(stderr, "(pondering) ");
339 uct_progress_status(u, ctx->t, ctx->color, ctx->games);
341 if (u->pondering) {
342 free(ctx->b);
343 u->pondering = false;
348 void
349 uct_genmove_setup(struct uct *u, struct board *b, enum stone color)
351 if (b->superko_violation) {
352 fprintf(stderr, "!!! WARNING: SUPERKO VIOLATION OCCURED BEFORE THIS MOVE\n");
353 fprintf(stderr, "Maybe you play with situational instead of positional superko?\n");
354 fprintf(stderr, "I'm going to ignore the violation, but note that I may miss\n");
355 fprintf(stderr, "some moves valid under this ruleset because of this.\n");
356 b->superko_violation = false;
359 uct_prepare_move(u, b, color);
361 assert(u->t);
362 u->my_color = color;
364 /* How to decide whether to use dynkomi in this game? Since we use
365 * pondering, it's not simple "who-to-play" matter. Decide based on
366 * the last genmove issued. */
367 u->t->use_extra_komi = !!(u->dynkomi_mask & color);
368 setup_dynkomi(u, b, color);
370 if (b->rules == RULES_JAPANESE)
371 u->territory_scoring = true;
373 /* Make pessimistic assumption about komi for Japanese rules to
374 * avoid losing by 0.5 when winning by 0.5 with Chinese rules.
375 * The rules usually give the same winner if the integer part of komi
376 * is odd so we adjust the komi only if it is even (for a board of
377 * odd size). We are not trying to get an exact evaluation for rare
378 * cases of seki. For details see http://home.snafu.de/jasiek/parity.html */
379 if (u->territory_scoring && (((int)floor(b->komi) + board_size(b)) & 1)) {
380 b->komi += (color == S_BLACK ? 1.0 : -1.0);
381 if (UDEBUGL(0))
382 fprintf(stderr, "Setting komi to %.1f assuming Japanese rules\n",
383 b->komi);
387 static coord_t *
388 uct_genmove(struct engine *e, struct board *b, struct time_info *ti, enum stone color, bool pass_all_alive)
390 double start_time = time_now();
391 struct uct *u = e->data;
392 uct_pondering_stop(u);
393 uct_genmove_setup(u, b, color);
395 /* Start the Monte Carlo Tree Search! */
396 int base_playouts = u->t->root->u.playouts;
397 int played_games = uct_search(u, b, ti, color, u->t);
399 coord_t best_coord;
400 struct tree_node *best;
401 best = uct_search_result(u, b, color, pass_all_alive, played_games, base_playouts, &best_coord);
403 if (UDEBUGL(2)) {
404 double time = time_now() - start_time + 0.000001; /* avoid divide by zero */
405 fprintf(stderr, "genmove in %0.2fs (%d games/s, %d games/s/thread)\n",
406 time, (int)(played_games/time), (int)(played_games/time/u->threads));
409 if (!best) {
410 /* Pass or resign. */
411 reset_state(u);
412 return coord_copy(best_coord);
414 tree_promote_node(u->t, &best);
416 /* After a pass, pondering is harmful for two reasons:
417 * (i) We might keep pondering even when the game is over.
418 * Of course this is the case for opponent resign as well.
419 * (ii) More importantly, the ownermap will get skewed since
420 * the UCT will start cutting off any playouts. */
421 if (u->pondering_opt && !is_pass(best->coord)) {
422 uct_pondering_start(u, b, u->t, stone_other(color));
424 return coord_copy(best_coord);
428 bool
429 uct_genbook(struct engine *e, struct board *b, struct time_info *ti, enum stone color)
431 struct uct *u = e->data;
432 if (!u->t) uct_prepare_move(u, b, color);
433 assert(u->t);
435 if (ti->dim == TD_GAMES) {
436 /* Don't count in games that already went into the book. */
437 ti->len.games += u->t->root->u.playouts;
439 uct_search(u, b, ti, color, u->t);
441 assert(ti->dim == TD_GAMES);
442 tree_save(u->t, b, ti->len.games / 100);
444 return true;
447 void
448 uct_dumpbook(struct engine *e, struct board *b, enum stone color)
450 struct uct *u = e->data;
451 struct tree *t = tree_init(b, color, u->fast_alloc ? u->max_tree_size : 0, u->local_tree_aging);
452 tree_load(t, b);
453 tree_dump(t, 0);
454 tree_done(t);
458 struct uct *
459 uct_state_init(char *arg, struct board *b)
461 struct uct *u = calloc2(1, sizeof(struct uct));
462 bool using_elo = false;
464 u->debug_level = debug_level;
465 u->gamelen = MC_GAMELEN;
466 u->mercymin = 0;
467 u->expand_p = 2;
468 u->dumpthres = 1000;
469 u->playout_amaf = true;
470 u->playout_amaf_nakade = false;
471 u->amaf_prior = false;
472 u->max_tree_size = 3072ULL * 1048576;
474 u->dynkomi_mask = S_BLACK;
476 u->threads = 1;
477 u->thread_model = TM_TREEVL;
478 u->parallel_tree = true;
479 u->virtual_loss = true;
481 u->fuseki_end = 20; // max time at 361*20% = 72 moves (our 36th move, still 99 to play)
482 u->yose_start = 40; // (100-40-25)*361/100/2 = 63 moves still to play by us then
483 u->bestr_ratio = 0.02;
484 // 2.5 is clearly too much, but seems to compensate well for overly stern time allocations.
485 // TODO: Further tuning and experiments with better time allocation schemes.
486 u->best2_ratio = 2.5;
488 u->val_scale = 0.04; u->val_points = 40;
490 u->tenuki_d = 4;
491 u->local_tree_aging = 2;
493 if (arg) {
494 char *optspec, *next = arg;
495 while (*next) {
496 optspec = next;
497 next += strcspn(next, ",");
498 if (*next) { *next++ = 0; } else { *next = 0; }
500 char *optname = optspec;
501 char *optval = strchr(optspec, '=');
502 if (optval) *optval++ = 0;
504 if (!strcasecmp(optname, "debug")) {
505 if (optval)
506 u->debug_level = atoi(optval);
507 else
508 u->debug_level++;
509 } else if (!strcasecmp(optname, "mercy") && optval) {
510 /* Minimal difference of black/white captures
511 * to stop playout - "Mercy Rule". Speeds up
512 * hopeless playouts at the expense of some
513 * accuracy. */
514 u->mercymin = atoi(optval);
515 } else if (!strcasecmp(optname, "gamelen") && optval) {
516 u->gamelen = atoi(optval);
517 } else if (!strcasecmp(optname, "expand_p") && optval) {
518 u->expand_p = atoi(optval);
519 } else if (!strcasecmp(optname, "dumpthres") && optval) {
520 u->dumpthres = atoi(optval);
521 } else if (!strcasecmp(optname, "best2_ratio") && optval) {
522 /* If set, prolong simulating while
523 * first_best/second_best playouts ratio
524 * is less than best2_ratio. */
525 u->best2_ratio = atof(optval);
526 } else if (!strcasecmp(optname, "bestr_ratio") && optval) {
527 /* If set, prolong simulating while
528 * best,best_best_child values delta
529 * is more than bestr_ratio. */
530 u->bestr_ratio = atof(optval);
531 } else if (!strcasecmp(optname, "playout_amaf")) {
532 /* Whether to include random playout moves in
533 * AMAF as well. (Otherwise, only tree moves
534 * are included in AMAF. Of course makes sense
535 * only in connection with an AMAF policy.) */
536 /* with-without: 55.5% (+-4.1) */
537 if (optval && *optval == '0')
538 u->playout_amaf = false;
539 else
540 u->playout_amaf = true;
541 } else if (!strcasecmp(optname, "playout_amaf_nakade")) {
542 /* Whether to include nakade moves from playouts
543 * in the AMAF statistics; this tends to nullify
544 * the playout_amaf effect by adding too much
545 * noise. */
546 if (optval && *optval == '0')
547 u->playout_amaf_nakade = false;
548 else
549 u->playout_amaf_nakade = true;
550 } else if (!strcasecmp(optname, "playout_amaf_cutoff") && optval) {
551 /* Keep only first N% of playout stage AMAF
552 * information. */
553 u->playout_amaf_cutoff = atoi(optval);
554 } else if ((!strcasecmp(optname, "policy") || !strcasecmp(optname, "random_policy")) && optval) {
555 char *policyarg = strchr(optval, ':');
556 struct uct_policy **p = !strcasecmp(optname, "policy") ? &u->policy : &u->random_policy;
557 if (policyarg)
558 *policyarg++ = 0;
559 if (!strcasecmp(optval, "ucb1")) {
560 *p = policy_ucb1_init(u, policyarg);
561 } else if (!strcasecmp(optval, "ucb1amaf")) {
562 *p = policy_ucb1amaf_init(u, policyarg);
563 } else {
564 fprintf(stderr, "UCT: Invalid tree policy %s\n", optval);
565 exit(1);
567 } else if (!strcasecmp(optname, "playout") && optval) {
568 char *playoutarg = strchr(optval, ':');
569 if (playoutarg)
570 *playoutarg++ = 0;
571 if (!strcasecmp(optval, "moggy")) {
572 u->playout = playout_moggy_init(playoutarg, b);
573 } else if (!strcasecmp(optval, "light")) {
574 u->playout = playout_light_init(playoutarg, b);
575 } else if (!strcasecmp(optval, "elo")) {
576 u->playout = playout_elo_init(playoutarg, b);
577 using_elo = true;
578 } else {
579 fprintf(stderr, "UCT: Invalid playout policy %s\n", optval);
580 exit(1);
582 } else if (!strcasecmp(optname, "prior") && optval) {
583 u->prior = uct_prior_init(optval, b);
584 } else if (!strcasecmp(optname, "amaf_prior") && optval) {
585 u->amaf_prior = atoi(optval);
586 } else if (!strcasecmp(optname, "threads") && optval) {
587 /* By default, Pachi will run with only single
588 * tree search thread! */
589 u->threads = atoi(optval);
590 } else if (!strcasecmp(optname, "thread_model") && optval) {
591 if (!strcasecmp(optval, "root")) {
592 /* Root parallelization - each thread
593 * does independent search, trees are
594 * merged at the end. */
595 u->thread_model = TM_ROOT;
596 u->parallel_tree = false;
597 u->virtual_loss = false;
598 } else if (!strcasecmp(optval, "tree")) {
599 /* Tree parallelization - all threads
600 * grind on the same tree. */
601 u->thread_model = TM_TREE;
602 u->parallel_tree = true;
603 u->virtual_loss = false;
604 } else if (!strcasecmp(optval, "treevl")) {
605 /* Tree parallelization, but also
606 * with virtual losses - this discou-
607 * rages most threads choosing the
608 * same tree branches to read. */
609 u->thread_model = TM_TREEVL;
610 u->parallel_tree = true;
611 u->virtual_loss = true;
612 } else {
613 fprintf(stderr, "UCT: Invalid thread model %s\n", optval);
614 exit(1);
616 } else if (!strcasecmp(optname, "pondering")) {
617 /* Keep searching even during opponent's turn. */
618 u->pondering_opt = !optval || atoi(optval);
619 } else if (!strcasecmp(optname, "fuseki_end") && optval) {
620 /* At the very beginning it's not worth thinking
621 * too long because the playout evaluations are
622 * very noisy. So gradually increase the thinking
623 * time up to maximum when fuseki_end percent
624 * of the board has been played.
625 * This only applies if we are not in byoyomi. */
626 u->fuseki_end = atoi(optval);
627 } else if (!strcasecmp(optname, "yose_start") && optval) {
628 /* When yose_start percent of the board has been
629 * played, or if we are in byoyomi, stop spending
630 * more time and spread the remaining time
631 * uniformly.
632 * Between fuseki_end and yose_start, we spend
633 * a constant proportion of the remaining time
634 * on each move. (yose_start should actually
635 * be much earlier than when real yose start,
636 * but "yose" is a good short name to convey
637 * the idea.) */
638 u->yose_start = atoi(optval);
639 } else if (!strcasecmp(optname, "force_seed") && optval) {
640 u->force_seed = atoi(optval);
641 } else if (!strcasecmp(optname, "no_book")) {
642 u->no_book = true;
643 } else if (!strcasecmp(optname, "dynkomi") && optval) {
644 /* Dynamic komi approach; there are multiple
645 * ways to adjust komi dynamically throughout
646 * play. We currently support two: */
647 char *dynkomiarg = strchr(optval, ':');
648 if (dynkomiarg)
649 *dynkomiarg++ = 0;
650 if (!strcasecmp(optval, "none")) {
651 u->dynkomi = uct_dynkomi_init_none(u, dynkomiarg, b);
652 } else if (!strcasecmp(optval, "linear")) {
653 u->dynkomi = uct_dynkomi_init_linear(u, dynkomiarg, b);
654 } else if (!strcasecmp(optval, "adaptive")) {
655 u->dynkomi = uct_dynkomi_init_adaptive(u, dynkomiarg, b);
656 } else {
657 fprintf(stderr, "UCT: Invalid dynkomi mode %s\n", optval);
658 exit(1);
660 } else if (!strcasecmp(optname, "dynkomi_mask") && optval) {
661 /* Bitmask of colors the player must be
662 * for dynkomi be applied; you may want
663 * to use dynkomi_mask=3 to allow dynkomi
664 * even in games where Pachi is white. */
665 u->dynkomi_mask = atoi(optval);
666 } else if (!strcasecmp(optname, "dynkomi_interval") && optval) {
667 /* If non-zero, re-adjust dynamic komi
668 * throughout a single genmove reading,
669 * roughly every N simulations. */
670 /* XXX: Does not work with tree
671 * parallelization. */
672 u->dynkomi_interval = atoi(optval);
673 } else if (!strcasecmp(optname, "val_scale") && optval) {
674 /* How much of the game result value should be
675 * influenced by win size. Zero means it isn't. */
676 u->val_scale = atof(optval);
677 } else if (!strcasecmp(optname, "val_points") && optval) {
678 /* Maximum size of win to be scaled into game
679 * result value. Zero means boardsize^2. */
680 u->val_points = atoi(optval) * 2; // result values are doubled
681 } else if (!strcasecmp(optname, "val_extra")) {
682 /* If false, the score coefficient will be simply
683 * added to the value, instead of scaling the result
684 * coefficient because of it. */
685 u->val_extra = !optval || atoi(optval);
686 } else if (!strcasecmp(optname, "local_tree") && optval) {
687 /* Whether to bias exploration by local tree values
688 * (must be supported by the used policy).
689 * 0: Don't.
690 * 1: Do, value = result.
691 * Try to temper the result:
692 * 2: Do, value = 0.5+(result-expected)/2.
693 * 3: Do, value = 0.5+bzz((result-expected)^2).
694 * 4: Do, value = 0.5+sqrt(result-expected)/2. */
695 u->local_tree = atoi(optval);
696 } else if (!strcasecmp(optname, "tenuki_d") && optval) {
697 /* Tenuki distance at which to break the local tree. */
698 u->tenuki_d = atoi(optval);
699 if (u->tenuki_d > TREE_NODE_D_MAX + 1) {
700 fprintf(stderr, "uct: tenuki_d must not be larger than TREE_NODE_D_MAX+1 %d\n", TREE_NODE_D_MAX + 1);
701 exit(1);
703 } else if (!strcasecmp(optname, "local_tree_aging") && optval) {
704 /* How much to reduce local tree values between moves. */
705 u->local_tree_aging = atof(optval);
706 } else if (!strcasecmp(optname, "local_tree_allseq")) {
707 /* By default, only complete sequences are stored
708 * in the local tree. If this is on, also
709 * subsequences starting at each move are stored. */
710 u->local_tree_allseq = !optval || atoi(optval);
711 } else if (!strcasecmp(optname, "local_tree_playout")) {
712 /* Whether to adjust ELO playout probability
713 * distributions according to matched localtree
714 * information. */
715 u->local_tree_playout = !optval || atoi(optval);
716 } else if (!strcasecmp(optname, "local_tree_pseqroot")) {
717 /* By default, when we have no sequence move
718 * to suggest in-playout, we give up. If this
719 * is on, we make probability distribution from
720 * sequences first moves instead. */
721 u->local_tree_pseqroot = !optval || atoi(optval);
722 } else if (!strcasecmp(optname, "pass_all_alive")) {
723 /* Whether to consider passing only after all
724 * dead groups were removed from the board;
725 * this is like all genmoves are in fact
726 * kgs-genmove_cleanup. */
727 u->pass_all_alive = !optval || atoi(optval);
728 } else if (!strcasecmp(optname, "territory_scoring")) {
729 /* Use territory scoring (default is area scoring).
730 * An explicit kgs-rules command overrides this. */
731 u->territory_scoring = !optval || atoi(optval);
732 } else if (!strcasecmp(optname, "random_policy_chance") && optval) {
733 /* If specified (N), with probability 1/N, random_policy policy
734 * descend is used instead of main policy descend; useful
735 * if specified policy (e.g. UCB1AMAF) can make unduly biased
736 * choices sometimes, you can fall back to e.g.
737 * random_policy=UCB1. */
738 u->random_policy_chance = atoi(optval);
739 } else if (!strcasecmp(optname, "max_tree_size") && optval) {
740 /* Maximum amount of memory [MiB] consumed by the move tree.
741 * For fast_alloc it includes the temp tree used for pruning.
742 * Default is 3072 (3 GiB). Note that if you use TM_ROOT,
743 * this limits size of only one of the trees, not all of them
744 * together. */
745 u->max_tree_size = atol(optval) * 1048576;
746 } else if (!strcasecmp(optname, "fast_alloc")) {
747 u->fast_alloc = !optval || atoi(optval);
748 } else if (!strcasecmp(optname, "slave")) {
749 /* Act as slave for the distributed engine. */
750 u->slave = !optval || atoi(optval);
751 } else if (!strcasecmp(optname, "banner") && optval) {
752 /* Additional banner string. This must come as the
753 * last engine parameter. */
754 if (*next) *--next = ',';
755 u->banner = strdup(optval);
756 break;
757 } else {
758 fprintf(stderr, "uct: Invalid engine argument %s or missing value\n", optname);
759 exit(1);
764 u->resign_ratio = 0.2; /* Resign when most games are lost. */
765 u->loss_threshold = 0.85; /* Stop reading if after at least 2000 playouts this is best value. */
766 if (!u->policy)
767 u->policy = policy_ucb1amaf_init(u, NULL);
769 if (!!u->random_policy_chance ^ !!u->random_policy) {
770 fprintf(stderr, "uct: Only one of random_policy and random_policy_chance is set\n");
771 exit(1);
774 if (!u->local_tree) {
775 /* No ltree aging. */
776 u->local_tree_aging = 1.0f;
778 if (!using_elo)
779 u->local_tree_playout = false;
781 if (u->fast_alloc && !u->parallel_tree) {
782 fprintf(stderr, "fast_alloc not supported with root parallelization.\n");
783 exit(1);
785 if (u->fast_alloc)
786 u->max_tree_size = (100ULL * u->max_tree_size) / (100 + MIN_FREE_MEM_PERCENT);
788 if (!u->prior)
789 u->prior = uct_prior_init(NULL, b);
791 if (!u->playout)
792 u->playout = playout_moggy_init(NULL, b);
793 u->playout->debug_level = u->debug_level;
795 u->ownermap.map = malloc2(board_size2(b) * sizeof(u->ownermap.map[0]));
796 u->stats = malloc2(board_size2(b) * sizeof(u->stats[0]));
798 if (!u->dynkomi)
799 u->dynkomi = uct_dynkomi_init_linear(u, NULL, b);
801 /* Some things remain uninitialized for now - the opening book
802 * is not loaded and the tree not set up. */
803 /* This will be initialized in setup_state() at the first move
804 * received/requested. This is because right now we are not aware
805 * about any komi or handicap setup and such. */
807 return u;
810 struct engine *
811 engine_uct_init(char *arg, struct board *b)
813 struct uct *u = uct_state_init(arg, b);
814 struct engine *e = calloc2(1, sizeof(struct engine));
815 e->name = "UCT Engine";
816 e->printhook = uct_printhook_ownermap;
817 e->notify_play = uct_notify_play;
818 e->chat = uct_chat;
819 e->genmove = uct_genmove;
820 e->genmoves = uct_genmoves;
821 e->dead_group_list = uct_dead_group_list;
822 e->done = uct_done;
823 e->data = u;
824 if (u->slave)
825 e->notify = uct_notify;
827 const char banner[] = "I'm playing UCT. When I'm losing, I will resign, "
828 "if I think I win, I play until you pass. "
829 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
830 if (!u->banner) u->banner = "";
831 e->comment = malloc2(sizeof(banner) + strlen(u->banner) + 1);
832 sprintf(e->comment, "%s %s", banner, u->banner);
834 return e;