UCT: Add basic support for graceful jigo handling (integer komi games)
[pachi/pachi-r6144.git] / uct / uct.c
blobbe2fcf90567197183c9037ba4ce4ccf9e07afe0f
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 "joseki/base.h"
16 #include "playout.h"
17 #include "playout/moggy.h"
18 #include "playout/light.h"
19 #include "tactics/util.h"
20 #include "timeinfo.h"
21 #include "uct/dynkomi.h"
22 #include "uct/internal.h"
23 #include "uct/plugins.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,
43 u->max_pruned_size, u->pruning_threshold, u->local_tree_aging, u->stats_hbits);
44 if (u->force_seed)
45 fast_srandom(u->force_seed);
46 if (UDEBUGL(0))
47 fprintf(stderr, "Fresh board with random seed %lu\n", fast_getseed());
48 //board_print(b, stderr);
49 if (!u->no_tbook && b->moves == 0) {
50 assert(color == S_BLACK);
51 tree_load(u->t, b);
55 static void
56 reset_state(struct uct *u)
58 assert(u->t);
59 tree_done(u->t); u->t = NULL;
62 static void
63 setup_dynkomi(struct uct *u, struct board *b, enum stone to_play)
65 if (u->t->use_extra_komi && !u->pondering && u->dynkomi->permove)
66 u->t->extra_komi = u->dynkomi->permove(u->dynkomi, b, u->t);
67 else if (!u->t->use_extra_komi)
68 u->t->extra_komi = 0;
71 void
72 uct_prepare_move(struct uct *u, struct board *b, enum stone color)
74 if (u->t) {
75 /* Verify that we have sane state. */
76 assert(b->es == u);
77 assert(u->t && b->moves);
78 if (color != stone_other(u->t->root_color)) {
79 fprintf(stderr, "Fatal: Non-alternating play detected %d %d\n",
80 color, u->t->root_color);
81 exit(1);
83 uct_htable_reset(u->t);
85 } else {
86 /* We need fresh state. */
87 b->es = u;
88 setup_state(u, b, color);
91 u->ownermap.playouts = 0;
92 memset(u->ownermap.map, 0, board_size2(b) * sizeof(u->ownermap.map[0]));
93 u->played_own = u->played_all = 0;
96 static void
97 dead_group_list(struct uct *u, struct board *b, struct move_queue *mq)
99 struct group_judgement gj;
100 gj.thres = GJ_THRES;
101 gj.gs = alloca(board_size2(b) * sizeof(gj.gs[0]));
102 board_ownermap_judge_group(b, &u->ownermap, &gj);
103 groups_of_status(b, &gj, GS_DEAD, mq);
106 bool
107 uct_pass_is_safe(struct uct *u, struct board *b, enum stone color, bool pass_all_alive)
109 if (u->ownermap.playouts < GJ_MINGAMES)
110 return false;
112 struct move_queue mq = { .moves = 0 };
113 dead_group_list(u, b, &mq);
114 if (pass_all_alive && mq.moves > 0)
115 return false; // We need to remove some dead groups first.
116 return pass_is_safe(b, color, &mq);
119 static char *
120 uct_printhook_ownermap(struct board *board, coord_t c, char *s, char *end)
122 struct uct *u = board->es;
123 if (!u) {
124 strcat(s, ". ");
125 return s + 2;
127 const char chr[] = ":XO,"; // dame, black, white, unclear
128 const char chm[] = ":xo,";
129 char ch = chr[board_ownermap_judge_point(&u->ownermap, c, GJ_THRES)];
130 if (ch == ',') { // less precise estimate then?
131 ch = chm[board_ownermap_judge_point(&u->ownermap, c, 0.67)];
133 s += snprintf(s, end - s, "%c ", ch);
134 return s;
137 static char *
138 uct_notify_play(struct engine *e, struct board *b, struct move *m)
140 struct uct *u = e->data;
141 if (!u->t) {
142 /* No state, create one - this is probably game beginning
143 * and we need to load the opening tbook right now. */
144 uct_prepare_move(u, b, m->color);
145 assert(u->t);
148 /* Stop pondering, required by tree_promote_at() */
149 uct_pondering_stop(u);
150 if (UDEBUGL(2) && u->slave)
151 tree_dump(u->t, u->dumpthres);
153 if (is_resign(m->coord)) {
154 /* Reset state. */
155 reset_state(u);
156 return NULL;
159 /* Promote node of the appropriate move to the tree root. */
160 assert(u->t->root);
161 if (!tree_promote_at(u->t, b, m->coord)) {
162 if (UDEBUGL(0))
163 fprintf(stderr, "Warning: Cannot promote move node! Several play commands in row?\n");
164 reset_state(u);
165 return NULL;
168 /* If we are a slave in a distributed engine, start pondering once
169 * we know which move we actually played. See uct_genmove() about
170 * the check for pass. */
171 if (u->pondering_opt && u->slave && m->color == u->my_color && !is_pass(m->coord))
172 uct_pondering_start(u, b, u->t, stone_other(m->color));
174 return NULL;
177 static char *
178 uct_result(struct engine *e, struct board *b)
180 struct uct *u = e->data;
181 static char reply[1024];
183 if (!u->t)
184 return NULL;
185 enum stone color = u->t->root_color;
186 struct tree_node *n = u->t->root;
187 snprintf(reply, 1024, "%s %s %d %.2f %.1f",
188 stone2str(color), coord2sstr(n->coord, b),
189 n->u.playouts, tree_node_get_value(u->t, -1, n->u.value),
190 u->t->use_extra_komi ? u->t->extra_komi : 0);
191 return reply;
194 static char *
195 uct_chat(struct engine *e, struct board *b, char *cmd)
197 struct uct *u = e->data;
198 static char reply[1024];
200 cmd += strspn(cmd, " \n\t");
201 if (!strncasecmp(cmd, "winrate", 7)) {
202 if (!u->t)
203 return "no game context (yet?)";
204 enum stone color = u->t->root_color;
205 struct tree_node *n = u->t->root;
206 snprintf(reply, 1024, "In %d playouts at %d threads, %s %s can win with %.2f%% probability",
207 n->u.playouts, u->threads, stone2str(color), coord2sstr(n->coord, b),
208 tree_node_get_value(u->t, -1, n->u.value) * 100);
209 if (u->t->use_extra_komi && abs(u->t->extra_komi) >= 0.5) {
210 sprintf(reply + strlen(reply), ", while self-imposing extra komi %.1f",
211 u->t->extra_komi);
213 strcat(reply, ".");
214 return reply;
216 return NULL;
219 static void
220 uct_dead_group_list(struct engine *e, struct board *b, struct move_queue *mq)
222 struct uct *u = e->data;
224 /* This means the game is probably over, no use pondering on. */
225 uct_pondering_stop(u);
227 if (u->pass_all_alive)
228 return; // no dead groups
230 bool mock_state = false;
232 if (!u->t) {
233 /* No state, but we cannot just back out - we might
234 * have passed earlier, only assuming some stones are
235 * dead, and then re-connected, only to lose counting
236 * when all stones are assumed alive. */
237 uct_prepare_move(u, b, S_BLACK); assert(u->t);
238 mock_state = true;
240 /* Make sure the ownermap is well-seeded. */
241 while (u->ownermap.playouts < GJ_MINGAMES)
242 uct_playout(u, b, S_BLACK, u->t);
243 /* Show the ownermap: */
244 if (DEBUGL(2))
245 board_print_custom(b, stderr, uct_printhook_ownermap);
247 dead_group_list(u, b, mq);
249 if (mock_state) {
250 /* Clean up the mock state in case we will receive
251 * a genmove; we could get a non-alternating-move
252 * error from uct_prepare_move() in that case otherwise. */
253 reset_state(u);
257 static void
258 playout_policy_done(struct playout_policy *p)
260 if (p->done) p->done(p);
261 if (p->data) free(p->data);
262 free(p);
265 static void
266 uct_done(struct engine *e)
268 /* This is called on engine reset, especially when clear_board
269 * is received and new game should begin. */
270 struct uct *u = e->data;
271 uct_pondering_stop(u);
272 if (u->t) reset_state(u);
273 free(u->ownermap.map);
275 free(u->policy);
276 free(u->random_policy);
277 playout_policy_done(u->playout);
278 uct_prior_done(u->prior);
279 joseki_done(u->jdict);
280 pluginset_done(u->plugins);
285 /* Run time-limited MCTS search on foreground. */
286 static int
287 uct_search(struct uct *u, struct board *b, struct time_info *ti, enum stone color, struct tree *t)
289 struct uct_search_state s;
290 uct_search_start(u, b, color, t, ti, &s);
291 if (UDEBUGL(2) && s.base_playouts > 0)
292 fprintf(stderr, "<pre-simulated %d games>\n", s.base_playouts);
294 /* The search tree is ctx->t. This is currently == . It is important
295 * to reference ctx->t directly since the
296 * thread manager will swap the tree pointer asynchronously. */
298 /* Now, just periodically poll the search tree. */
299 /* Note that in case of TD_GAMES, threads will terminate independently
300 * of the uct_search_check_stop() signalization. */
301 while (1) {
302 time_sleep(TREE_BUSYWAIT_INTERVAL);
303 /* TREE_BUSYWAIT_INTERVAL should never be less than desired time, or the
304 * time control is broken. But if it happens to be less, we still search
305 * at least 100ms otherwise the move is completely random. */
307 int i = uct_search_games(&s);
308 /* Print notifications etc. */
309 uct_search_progress(u, b, color, t, ti, &s, i);
310 /* Check if we should stop the search. */
311 if (uct_search_check_stop(u, b, color, t, ti, &s, i))
312 break;
315 struct uct_thread_ctx *ctx = uct_search_stop();
316 if (UDEBUGL(2)) tree_dump(t, u->dumpthres);
317 if (UDEBUGL(2))
318 fprintf(stderr, "(avg score %f/%d value %f/%d)\n",
319 u->dynkomi->score.value, u->dynkomi->score.playouts,
320 u->dynkomi->value.value, u->dynkomi->value.playouts);
321 if (UDEBUGL(0))
322 uct_progress_status(u, t, color, ctx->games);
324 u->played_own += ctx->games;
325 return ctx->games;
328 /* Start pondering background with @color to play. */
329 static void
330 uct_pondering_start(struct uct *u, struct board *b0, struct tree *t, enum stone color)
332 if (UDEBUGL(1))
333 fprintf(stderr, "Starting to ponder with color %s\n", stone2str(stone_other(color)));
334 u->pondering = true;
336 /* We need a local board copy to ponder upon. */
337 struct board *b = malloc2(sizeof(*b)); board_copy(b, b0);
339 /* *b0 did not have the genmove'd move played yet. */
340 struct move m = { t->root->coord, t->root_color };
341 int res = board_play(b, &m);
342 assert(res >= 0);
343 setup_dynkomi(u, b, stone_other(m.color));
345 /* Start MCTS manager thread "headless". */
346 static struct uct_search_state s;
347 uct_search_start(u, b, color, t, NULL, &s);
350 /* uct_search_stop() frontend for the pondering (non-genmove) mode, and
351 * to stop the background search for a slave in the distributed engine. */
352 void
353 uct_pondering_stop(struct uct *u)
355 if (!thread_manager_running)
356 return;
358 /* Stop the thread manager. */
359 struct uct_thread_ctx *ctx = uct_search_stop();
360 if (UDEBUGL(1)) {
361 if (u->pondering) fprintf(stderr, "(pondering) ");
362 uct_progress_status(u, ctx->t, ctx->color, ctx->games);
364 if (u->pondering) {
365 free(ctx->b);
366 u->pondering = false;
371 void
372 uct_genmove_setup(struct uct *u, struct board *b, enum stone color)
374 if (b->superko_violation) {
375 fprintf(stderr, "!!! WARNING: SUPERKO VIOLATION OCCURED BEFORE THIS MOVE\n");
376 fprintf(stderr, "Maybe you play with situational instead of positional superko?\n");
377 fprintf(stderr, "I'm going to ignore the violation, but note that I may miss\n");
378 fprintf(stderr, "some moves valid under this ruleset because of this.\n");
379 b->superko_violation = false;
382 uct_prepare_move(u, b, color);
384 assert(u->t);
385 u->my_color = color;
387 /* How to decide whether to use dynkomi in this game? Since we use
388 * pondering, it's not simple "who-to-play" matter. Decide based on
389 * the last genmove issued. */
390 u->t->use_extra_komi = !!(u->dynkomi_mask & color);
391 /* Moreover, we do not use extra komi at the game end - we are not
392 * to fool ourselves at this point. */
393 if (board_estimated_moves_left(b) <= MIN_MOVES_LEFT)
394 u->t->use_extra_komi = false;
395 setup_dynkomi(u, b, color);
397 if (b->rules == RULES_JAPANESE)
398 u->territory_scoring = true;
400 /* Make pessimistic assumption about komi for Japanese rules to
401 * avoid losing by 0.5 when winning by 0.5 with Chinese rules.
402 * The rules usually give the same winner if the integer part of komi
403 * is odd so we adjust the komi only if it is even (for a board of
404 * odd size). We are not trying to get an exact evaluation for rare
405 * cases of seki. For details see http://home.snafu.de/jasiek/parity.html */
406 if (u->territory_scoring && (((int)floor(b->komi) + board_size(b)) & 1)) {
407 b->komi += (color == S_BLACK ? 1.0 : -1.0);
408 if (UDEBUGL(0))
409 fprintf(stderr, "Setting komi to %.1f assuming Japanese rules\n",
410 b->komi);
414 static coord_t *
415 uct_genmove(struct engine *e, struct board *b, struct time_info *ti, enum stone color, bool pass_all_alive)
417 double start_time = time_now();
418 struct uct *u = e->data;
419 uct_pondering_stop(u);
420 uct_genmove_setup(u, b, color);
422 /* Start the Monte Carlo Tree Search! */
423 int base_playouts = u->t->root->u.playouts;
424 int played_games = uct_search(u, b, ti, color, u->t);
426 coord_t best_coord;
427 struct tree_node *best;
428 best = uct_search_result(u, b, color, pass_all_alive, played_games, base_playouts, &best_coord);
430 if (UDEBUGL(2)) {
431 double time = time_now() - start_time + 0.000001; /* avoid divide by zero */
432 fprintf(stderr, "genmove in %0.2fs (%d games/s, %d games/s/thread)\n",
433 time, (int)(played_games/time), (int)(played_games/time/u->threads));
436 if (!best) {
437 /* Pass or resign. */
438 reset_state(u);
439 return coord_copy(best_coord);
441 tree_promote_node(u->t, &best);
443 /* After a pass, pondering is harmful for two reasons:
444 * (i) We might keep pondering even when the game is over.
445 * Of course this is the case for opponent resign as well.
446 * (ii) More importantly, the ownermap will get skewed since
447 * the UCT will start cutting off any playouts. */
448 if (u->pondering_opt && !is_pass(best->coord)) {
449 uct_pondering_start(u, b, u->t, stone_other(color));
451 return coord_copy(best_coord);
455 bool
456 uct_gentbook(struct engine *e, struct board *b, struct time_info *ti, enum stone color)
458 struct uct *u = e->data;
459 if (!u->t) uct_prepare_move(u, b, color);
460 assert(u->t);
462 if (ti->dim == TD_GAMES) {
463 /* Don't count in games that already went into the tbook. */
464 ti->len.games += u->t->root->u.playouts;
466 uct_search(u, b, ti, color, u->t);
468 assert(ti->dim == TD_GAMES);
469 tree_save(u->t, b, ti->len.games / 100);
471 return true;
474 void
475 uct_dumptbook(struct engine *e, struct board *b, enum stone color)
477 struct uct *u = e->data;
478 struct tree *t = tree_init(b, color, u->fast_alloc ? u->max_tree_size : 0,
479 u->max_pruned_size, u->pruning_threshold, u->local_tree_aging, 0);
480 tree_load(t, b);
481 tree_dump(t, 0);
482 tree_done(t);
486 floating_t
487 uct_evaluate(struct engine *e, struct board *b, struct time_info *ti, coord_t c, enum stone color)
489 struct uct *u = e->data;
491 struct board b2;
492 board_copy(&b2, b);
493 struct move m = { c, color };
494 int res = board_play(&b2, &m);
495 if (res < 0)
496 return NAN;
497 color = stone_other(color);
499 if (u->t) reset_state(u);
500 uct_prepare_move(u, &b2, color);
501 assert(u->t);
503 floating_t bestval;
504 uct_search(u, &b2, ti, color, u->t);
505 struct tree_node *best = u->policy->choose(u->policy, u->t->root, &b2, color, resign);
506 if (!best) {
507 bestval = NAN; // the opponent has no reply!
508 } else {
509 bestval = tree_node_get_value(u->t, 1, best->u.value);
512 reset_state(u); // clean our junk
514 return isnan(bestval) ? NAN : 1.0f - bestval;
518 struct uct *
519 uct_state_init(char *arg, struct board *b)
521 struct uct *u = calloc2(1, sizeof(struct uct));
523 u->debug_level = debug_level;
524 u->gamelen = MC_GAMELEN;
525 u->resign_threshold = 0.2;
526 u->sure_win_threshold = 0.85;
527 u->mercymin = 0;
528 u->significant_threshold = 50;
529 u->expand_p = 2;
530 u->dumpthres = 1000;
531 u->playout_amaf = true;
532 u->playout_amaf_nakade = false;
533 u->amaf_prior = false;
534 u->max_tree_size = 3072ULL * 1048576;
535 u->pruning_threshold = 0;
537 u->threads = 1;
538 u->thread_model = TM_TREEVL;
539 u->virtual_loss = 1;
541 u->fuseki_end = 20; // max time at 361*20% = 72 moves (our 36th move, still 99 to play)
542 u->yose_start = 40; // (100-40-25)*361/100/2 = 63 moves still to play by us then
543 u->bestr_ratio = 0.02;
544 // 2.5 is clearly too much, but seems to compensate well for overly stern time allocations.
545 // TODO: Further tuning and experiments with better time allocation schemes.
546 u->best2_ratio = 2.5;
547 u->max_maintime_ratio = 8.0;
549 u->val_scale = 0.04; u->val_points = 40;
550 u->dynkomi_interval = 1000;
551 u->dynkomi_mask = S_BLACK | S_WHITE;
553 u->tenuki_d = 4;
554 u->local_tree_aging = 80;
555 u->local_tree_allseq = 1;
556 u->local_tree_rootseqval = 1;
557 u->local_tree_depth_decay = 1.5;
559 u->plugins = pluginset_init(b);
561 u->jdict = joseki_load(b->size);
563 if (arg) {
564 char *optspec, *next = arg;
565 while (*next) {
566 optspec = next;
567 next += strcspn(next, ",");
568 if (*next) { *next++ = 0; } else { *next = 0; }
570 char *optname = optspec;
571 char *optval = strchr(optspec, '=');
572 if (optval) *optval++ = 0;
574 /** Basic options */
576 if (!strcasecmp(optname, "debug")) {
577 if (optval)
578 u->debug_level = atoi(optval);
579 else
580 u->debug_level++;
581 } else if (!strcasecmp(optname, "dumpthres") && optval) {
582 /* When dumping the UCT tree on output, include
583 * nodes with at least this many playouts.
584 * (This value is re-scaled "intelligently"
585 * in case of very large trees.) */
586 u->dumpthres = atoi(optval);
587 } else if (!strcasecmp(optname, "resign_threshold") && optval) {
588 /* Resign when this ratio of games is lost
589 * after GJ_MINGAMES sample is taken. */
590 u->resign_threshold = atof(optval);
591 } else if (!strcasecmp(optname, "sure_win_threshold") && optval) {
592 /* Stop reading when this ratio of games is won
593 * after PLAYOUT_EARLY_BREAK_MIN sample is
594 * taken. (Prevents stupid time losses,
595 * friendly to human opponents.) */
596 u->sure_win_threshold = atof(optval);
597 } else if (!strcasecmp(optname, "force_seed") && optval) {
598 /* Set RNG seed at the tree setup. */
599 u->force_seed = atoi(optval);
600 } else if (!strcasecmp(optname, "no_tbook")) {
601 /* Disable UCT opening tbook. */
602 u->no_tbook = true;
603 } else if (!strcasecmp(optname, "pass_all_alive")) {
604 /* Whether to consider passing only after all
605 * dead groups were removed from the board;
606 * this is like all genmoves are in fact
607 * kgs-genmove_cleanup. */
608 u->pass_all_alive = !optval || atoi(optval);
609 } else if (!strcasecmp(optname, "territory_scoring")) {
610 /* Use territory scoring (default is area scoring).
611 * An explicit kgs-rules command overrides this. */
612 u->territory_scoring = !optval || atoi(optval);
613 } else if (!strcasecmp(optname, "banner") && optval) {
614 /* Additional banner string. This must come as the
615 * last engine parameter. */
616 if (*next) *--next = ',';
617 u->banner = strdup(optval);
618 break;
619 } else if (!strcasecmp(optname, "plugin") && optval) {
620 /* Load an external plugin; filename goes before the colon,
621 * extra arguments after the colon. */
622 char *pluginarg = strchr(optval, ':');
623 if (pluginarg)
624 *pluginarg++ = 0;
625 plugin_load(u->plugins, optval, pluginarg);
627 /** UCT behavior and policies */
629 } else if ((!strcasecmp(optname, "policy")
630 /* Node selection policy. ucb1amaf is the
631 * default policy implementing RAVE, while
632 * ucb1 is the simple exploration/exploitation
633 * policy. Policies can take further extra
634 * options. */
635 || !strcasecmp(optname, "random_policy")) && optval) {
636 /* A policy to be used randomly with small
637 * chance instead of the default policy. */
638 char *policyarg = strchr(optval, ':');
639 struct uct_policy **p = !strcasecmp(optname, "policy") ? &u->policy : &u->random_policy;
640 if (policyarg)
641 *policyarg++ = 0;
642 if (!strcasecmp(optval, "ucb1")) {
643 *p = policy_ucb1_init(u, policyarg);
644 } else if (!strcasecmp(optval, "ucb1amaf")) {
645 *p = policy_ucb1amaf_init(u, policyarg);
646 } else {
647 fprintf(stderr, "UCT: Invalid tree policy %s\n", optval);
648 exit(1);
650 } else if (!strcasecmp(optname, "playout") && optval) {
651 /* Random simulation (playout) policy.
652 * moggy is the default policy with large
653 * amount of domain-specific knowledge and
654 * heuristics. light is a simple uniformly
655 * random move selection policy. */
656 char *playoutarg = strchr(optval, ':');
657 if (playoutarg)
658 *playoutarg++ = 0;
659 if (!strcasecmp(optval, "moggy")) {
660 u->playout = playout_moggy_init(playoutarg, b, u->jdict);
661 } else if (!strcasecmp(optval, "light")) {
662 u->playout = playout_light_init(playoutarg, b);
663 } else {
664 fprintf(stderr, "UCT: Invalid playout policy %s\n", optval);
665 exit(1);
667 } else if (!strcasecmp(optname, "prior") && optval) {
668 /* Node priors policy. When expanding a node,
669 * it will seed node values heuristically
670 * (most importantly, based on playout policy
671 * opinion, but also with regard to other
672 * things). See uct/prior.c for details.
673 * Use prior=eqex=0 to disable priors. */
674 u->prior = uct_prior_init(optval, b);
675 } else if (!strcasecmp(optname, "mercy") && optval) {
676 /* Minimal difference of black/white captures
677 * to stop playout - "Mercy Rule". Speeds up
678 * hopeless playouts at the expense of some
679 * accuracy. */
680 u->mercymin = atoi(optval);
681 } else if (!strcasecmp(optname, "gamelen") && optval) {
682 /* Maximum length of single simulation
683 * in moves. */
684 u->gamelen = atoi(optval);
685 } else if (!strcasecmp(optname, "expand_p") && optval) {
686 /* Expand UCT nodes after it has been
687 * visited this many times. */
688 u->expand_p = atoi(optval);
689 } else if (!strcasecmp(optname, "random_policy_chance") && optval) {
690 /* If specified (N), with probability 1/N, random_policy policy
691 * descend is used instead of main policy descend; useful
692 * if specified policy (e.g. UCB1AMAF) can make unduly biased
693 * choices sometimes, you can fall back to e.g.
694 * random_policy=UCB1. */
695 u->random_policy_chance = atoi(optval);
697 /** General AMAF behavior */
698 /* (Only relevant if the policy supports AMAF.
699 * More variables can be tuned as policy
700 * parameters.) */
702 } else if (!strcasecmp(optname, "playout_amaf")) {
703 /* Whether to include random playout moves in
704 * AMAF as well. (Otherwise, only tree moves
705 * are included in AMAF. Of course makes sense
706 * only in connection with an AMAF policy.) */
707 /* with-without: 55.5% (+-4.1) */
708 if (optval && *optval == '0')
709 u->playout_amaf = false;
710 else
711 u->playout_amaf = true;
712 } else if (!strcasecmp(optname, "playout_amaf_nakade")) {
713 /* Whether to include nakade moves from playouts
714 * in the AMAF statistics; this tends to nullify
715 * the playout_amaf effect by adding too much
716 * noise. */
717 if (optval && *optval == '0')
718 u->playout_amaf_nakade = false;
719 else
720 u->playout_amaf_nakade = true;
721 } else if (!strcasecmp(optname, "playout_amaf_cutoff") && optval) {
722 /* Keep only first N% of playout stage AMAF
723 * information. */
724 u->playout_amaf_cutoff = atoi(optval);
725 } else if (!strcasecmp(optname, "amaf_prior") && optval) {
726 /* In node policy, consider prior values
727 * part of the real result term or part
728 * of the AMAF term? */
729 u->amaf_prior = atoi(optval);
731 /** Performance and memory management */
733 } else if (!strcasecmp(optname, "threads") && optval) {
734 /* By default, Pachi will run with only single
735 * tree search thread! */
736 u->threads = atoi(optval);
737 } else if (!strcasecmp(optname, "thread_model") && optval) {
738 if (!strcasecmp(optval, "tree")) {
739 /* Tree parallelization - all threads
740 * grind on the same tree. */
741 u->thread_model = TM_TREE;
742 u->virtual_loss = 0;
743 } else if (!strcasecmp(optval, "treevl")) {
744 /* Tree parallelization, but also
745 * with virtual losses - this discou-
746 * rages most threads choosing the
747 * same tree branches to read. */
748 u->thread_model = TM_TREEVL;
749 } else {
750 fprintf(stderr, "UCT: Invalid thread model %s\n", optval);
751 exit(1);
753 } else if (!strcasecmp(optname, "virtual_loss")) {
754 /* Number of virtual losses added before evaluating a node. */
755 u->virtual_loss = !optval || atoi(optval);
756 } else if (!strcasecmp(optname, "pondering")) {
757 /* Keep searching even during opponent's turn. */
758 u->pondering_opt = !optval || atoi(optval);
759 } else if (!strcasecmp(optname, "max_tree_size") && optval) {
760 /* Maximum amount of memory [MiB] consumed by the move tree.
761 * For fast_alloc it includes the temp tree used for pruning.
762 * Default is 3072 (3 GiB). */
763 u->max_tree_size = atol(optval) * 1048576;
764 } else if (!strcasecmp(optname, "fast_alloc")) {
765 u->fast_alloc = !optval || atoi(optval);
766 } else if (!strcasecmp(optname, "pruning_threshold") && optval) {
767 /* Force pruning at beginning of a move if the tree consumes
768 * more than this [MiB]. Default is 10% of max_tree_size.
769 * Increase to reduce pruning time overhead if memory is plentiful.
770 * This option is meaningful only for fast_alloc. */
771 u->pruning_threshold = atol(optval) * 1048576;
773 /** Time control */
775 } else if (!strcasecmp(optname, "best2_ratio") && optval) {
776 /* If set, prolong simulating while
777 * first_best/second_best playouts ratio
778 * is less than best2_ratio. */
779 u->best2_ratio = atof(optval);
780 } else if (!strcasecmp(optname, "bestr_ratio") && optval) {
781 /* If set, prolong simulating while
782 * best,best_best_child values delta
783 * is more than bestr_ratio. */
784 u->bestr_ratio = atof(optval);
785 } else if (!strcasecmp(optname, "max_maintime_ratio") && optval) {
786 /* If set and while not in byoyomi, prolong simulating no more than
787 * max_maintime_ratio times the normal desired thinking time. */
788 u->max_maintime_ratio = atof(optval);
789 } else if (!strcasecmp(optname, "fuseki_end") && optval) {
790 /* At the very beginning it's not worth thinking
791 * too long because the playout evaluations are
792 * very noisy. So gradually increase the thinking
793 * time up to maximum when fuseki_end percent
794 * of the board has been played.
795 * This only applies if we are not in byoyomi. */
796 u->fuseki_end = atoi(optval);
797 } else if (!strcasecmp(optname, "yose_start") && optval) {
798 /* When yose_start percent of the board has been
799 * played, or if we are in byoyomi, stop spending
800 * more time and spread the remaining time
801 * uniformly.
802 * Between fuseki_end and yose_start, we spend
803 * a constant proportion of the remaining time
804 * on each move. (yose_start should actually
805 * be much earlier than when real yose start,
806 * but "yose" is a good short name to convey
807 * the idea.) */
808 u->yose_start = atoi(optval);
810 /** Dynamic komi */
812 } else if (!strcasecmp(optname, "dynkomi") && optval) {
813 /* Dynamic komi approach; there are multiple
814 * ways to adjust komi dynamically throughout
815 * play. We currently support two: */
816 char *dynkomiarg = strchr(optval, ':');
817 if (dynkomiarg)
818 *dynkomiarg++ = 0;
819 if (!strcasecmp(optval, "none")) {
820 u->dynkomi = uct_dynkomi_init_none(u, dynkomiarg, b);
821 } else if (!strcasecmp(optval, "linear")) {
822 /* You should set dynkomi_mask=1
823 * since this doesn't work well
824 * for white handicaps! */
825 u->dynkomi = uct_dynkomi_init_linear(u, dynkomiarg, b);
826 } else if (!strcasecmp(optval, "adaptive")) {
827 /* There are many more knobs to
828 * crank - see uct/dynkomi.c. */
829 u->dynkomi = uct_dynkomi_init_adaptive(u, dynkomiarg, b);
830 } else {
831 fprintf(stderr, "UCT: Invalid dynkomi mode %s\n", optval);
832 exit(1);
834 } else if (!strcasecmp(optname, "dynkomi_mask") && optval) {
835 /* Bitmask of colors the player must be
836 * for dynkomi be applied; you may want
837 * to use dynkomi_mask=3 to allow dynkomi
838 * even in games where Pachi is white. */
839 u->dynkomi_mask = atoi(optval);
840 } else if (!strcasecmp(optname, "dynkomi_interval") && optval) {
841 /* If non-zero, re-adjust dynamic komi
842 * throughout a single genmove reading,
843 * roughly every N simulations. */
844 /* XXX: Does not work with tree
845 * parallelization. */
846 u->dynkomi_interval = atoi(optval);
848 /** Node value result scaling */
850 } else if (!strcasecmp(optname, "val_scale") && optval) {
851 /* How much of the game result value should be
852 * influenced by win size. Zero means it isn't. */
853 u->val_scale = atof(optval);
854 } else if (!strcasecmp(optname, "val_points") && optval) {
855 /* Maximum size of win to be scaled into game
856 * result value. Zero means boardsize^2. */
857 u->val_points = atoi(optval) * 2; // result values are doubled
858 } else if (!strcasecmp(optname, "val_extra")) {
859 /* If false, the score coefficient will be simply
860 * added to the value, instead of scaling the result
861 * coefficient because of it. */
862 u->val_extra = !optval || atoi(optval);
864 /** Local trees */
865 /* (Purely experimental. Does not work - yet!) */
867 } else if (!strcasecmp(optname, "local_tree") && optval) {
868 /* Whether to bias exploration by local tree values
869 * (must be supported by the used policy).
870 * 0: Don't.
871 * 1: Do, value = result.
872 * Try to temper the result:
873 * 2: Do, value = 0.5+(result-expected)/2.
874 * 3: Do, value = 0.5+bzz((result-expected)^2).
875 * 4: Do, value = 0.5+sqrt(result-expected)/2. */
876 u->local_tree = atoi(optval);
877 } else if (!strcasecmp(optname, "tenuki_d") && optval) {
878 /* Tenuki distance at which to break the local tree. */
879 u->tenuki_d = atoi(optval);
880 if (u->tenuki_d > TREE_NODE_D_MAX + 1) {
881 fprintf(stderr, "uct: tenuki_d must not be larger than TREE_NODE_D_MAX+1 %d\n", TREE_NODE_D_MAX + 1);
882 exit(1);
884 } else if (!strcasecmp(optname, "local_tree_aging") && optval) {
885 /* How much to reduce local tree values between moves. */
886 u->local_tree_aging = atof(optval);
887 } else if (!strcasecmp(optname, "local_tree_depth_decay") && optval) {
888 /* With value x>0, during the descent the node
889 * contributes 1/x^depth playouts in
890 * the local tree. I.e., with x>1, nodes more
891 * distant from local situation contribute more
892 * than nodes near the root. */
893 u->local_tree_depth_decay = atof(optval);
894 } else if (!strcasecmp(optname, "local_tree_allseq")) {
895 /* If disabled, only complete sequences are stored
896 * in the local tree. If this is on, also
897 * subsequences starting at each move are stored. */
898 u->local_tree_allseq = !optval || atoi(optval);
899 } else if (!strcasecmp(optname, "local_tree_pseqroot")) {
900 /* By default, when we have no sequence move
901 * to suggest in-playout, we give up. If this
902 * is on, we make probability distribution from
903 * sequences first moves instead. */
904 u->local_tree_pseqroot = !optval || atoi(optval);
905 } else if (!strcasecmp(optname, "local_tree_rootseqval")) {
906 /* If disabled, expected node value is computed by
907 * summing up values through the whole descent.
908 * If enabled, expected node value for
909 * each sequence is the value at the root of the
910 * sequence. */
911 u->local_tree_rootseqval = !optval || atoi(optval);
913 /** Other heuristics */
914 } else if (!strcasecmp(optname, "significant_threshold") && optval) {
915 /* Some heuristics (treepool) rely
916 * on the knowledge of the last "significant"
917 * node in the descent. Such a node is
918 * considered reasonably trustworthy to carry
919 * some meaningful information in the values
920 * of the node and its children. */
921 u->significant_threshold = atoi(optval);
922 } else if (!strcasecmp(optname, "treepool_chance") && optval) {
923 /* Chance of applying the treepool heuristic:
924 * one of the best N children of the last
925 * significant node is tried on each turn
926 * of the simulation. */
927 /* This is in form of two numbers:
928 * PREMOVE:POSTMOVE. Each is percentage
929 * value, one is the chance of the move
930 * tried before playout policy, one is the
931 * chance of it being applied if the policy
932 * has not picked anymove. */
933 char *optval2 = strchr(optval, ':');
934 if (!optval2) {
935 fprintf(stderr, "uct: treepool_chance takes two comma-separated numbers\n");
936 exit(1);
938 u->treepool_chance[0] = atoi(optval);
939 optval = ++optval2;
940 u->treepool_chance[1] = atoi(optval);
941 } else if (!strcasecmp(optname, "treepool_size") && optval) {
942 /* Number of top significant children
943 * to pick from. Too low means low effect,
944 * too high means even lousy moves are
945 * played. */
946 u->treepool_size = atoi(optval);
947 } else if (!strcasecmp(optname, "treepool_type") && optval) {
948 /* How to sort the children. */
949 if (!strcasecmp(optval, "rave_playouts"))
950 u->treepool_type = UTT_RAVE_PLAYOUTS;
951 else if (!strcasecmp(optval, "rave_value"))
952 u->treepool_type = UTT_RAVE_VALUE;
953 else if (!strcasecmp(optval, "uct_playouts"))
954 u->treepool_type = UTT_UCT_PLAYOUTS;
955 else if (!strcasecmp(optval, "uct_value"))
956 u->treepool_type = UTT_UCT_VALUE;
957 else if (!strcasecmp(optval, "evaluate"))
958 /* The proper combination of RAVE,
959 * UCT and prior, as used through
960 * descent. */
961 u->treepool_type = UTT_EVALUATE;
962 else {
963 fprintf(stderr, "uct: unknown treepool_type %s\n", optval);
964 exit(1);
966 } else if (!strcasecmp(optname, "treepool_pickfactor") && optval) {
967 /* Pick factor influencing children choice.
968 * By default (if this is 0 or 10), coords
969 * have uniform probability to be chosen;
970 * otherwise, children are tried from best
971 * to worst, each picked with probability
972 * (1/n * pickfactor/10).
973 * I.e., better children may be preferred
974 * if pickfactor > 10. */
975 u->treepool_pickfactor = atoi(optval);
977 /** Distributed engine slaves setup */
979 } else if (!strcasecmp(optname, "slave")) {
980 /* Act as slave for the distributed engine. */
981 u->slave = !optval || atoi(optval);
982 } else if (!strcasecmp(optname, "shared_nodes") && optval) {
983 /* Share at most shared_nodes between master and slave at each genmoves.
984 * Must use the same value in master and slaves. */
985 u->shared_nodes = atoi(optval);
986 } else if (!strcasecmp(optname, "shared_levels") && optval) {
987 /* Share only nodes of level <= shared_levels. */
988 u->shared_levels = atoi(optval);
989 } else if (!strcasecmp(optname, "stats_hbits") && optval) {
990 /* Set hash table size to 2^stats_hbits for the shared stats. */
991 u->stats_hbits = atoi(optval);
993 } else {
994 fprintf(stderr, "uct: Invalid engine argument %s or missing value\n", optname);
995 exit(1);
1000 if (!u->policy)
1001 u->policy = policy_ucb1amaf_init(u, NULL);
1003 if (!!u->random_policy_chance ^ !!u->random_policy) {
1004 fprintf(stderr, "uct: Only one of random_policy and random_policy_chance is set\n");
1005 exit(1);
1008 if (!u->local_tree) {
1009 /* No ltree aging. */
1010 u->local_tree_aging = 1.0f;
1013 if (u->fast_alloc) {
1014 if (u->pruning_threshold < u->max_tree_size / 10)
1015 u->pruning_threshold = u->max_tree_size / 10;
1016 if (u->pruning_threshold > u->max_tree_size / 2)
1017 u->pruning_threshold = u->max_tree_size / 2;
1019 /* Limit pruning temp space to 20% of memory. Beyond this we discard
1020 * the nodes and recompute them at the next move if necessary. */
1021 u->max_pruned_size = u->max_tree_size / 5;
1022 u->max_tree_size -= u->max_pruned_size;
1023 } else {
1024 /* Reserve 5% memory in case the background free() are slower
1025 * than the concurrent allocations. */
1026 u->max_tree_size -= u->max_tree_size / 20;
1029 if (!u->prior)
1030 u->prior = uct_prior_init(NULL, b);
1032 if (!u->playout)
1033 u->playout = playout_moggy_init(NULL, b, u->jdict);
1034 if (!u->playout->debug_level)
1035 u->playout->debug_level = u->debug_level;
1037 u->ownermap.map = malloc2(board_size2(b) * sizeof(u->ownermap.map[0]));
1039 if (u->slave) {
1040 if (!u->stats_hbits) u->stats_hbits = DEFAULT_STATS_HBITS;
1041 if (!u->shared_nodes) u->shared_nodes = DEFAULT_SHARED_NODES;
1042 assert(u->shared_levels * board_bits2(b) <= 8 * (int)sizeof(path_t));
1045 if (!u->dynkomi)
1046 u->dynkomi = uct_dynkomi_init_adaptive(u, NULL, b);
1048 /* Some things remain uninitialized for now - the opening tbook
1049 * is not loaded and the tree not set up. */
1050 /* This will be initialized in setup_state() at the first move
1051 * received/requested. This is because right now we are not aware
1052 * about any komi or handicap setup and such. */
1054 return u;
1057 struct engine *
1058 engine_uct_init(char *arg, struct board *b)
1060 struct uct *u = uct_state_init(arg, b);
1061 struct engine *e = calloc2(1, sizeof(struct engine));
1062 e->name = "UCT Engine";
1063 e->printhook = uct_printhook_ownermap;
1064 e->notify_play = uct_notify_play;
1065 e->chat = uct_chat;
1066 e->result = uct_result;
1067 e->genmove = uct_genmove;
1068 e->genmoves = uct_genmoves;
1069 e->dead_group_list = uct_dead_group_list;
1070 e->done = uct_done;
1071 e->data = u;
1072 if (u->slave)
1073 e->notify = uct_notify;
1075 const char banner[] = "I'm playing UCT. When I'm losing, I will resign, "
1076 "if I think I win, I play until you pass. "
1077 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
1078 if (!u->banner) u->banner = "";
1079 e->comment = malloc2(sizeof(banner) + strlen(u->banner) + 1);
1080 sprintf(e->comment, "%s %s", banner, u->banner);
1082 return e;