Added the unlimited_tree_dump option so that reducing dumpthres actually becomes...
[pachi/pachi-r6144.git] / uct / uct.c
blob438f4e3cd15e21a72dfe186f235af6d401b32d79
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, u->unlimited_tree_dump);
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_undo(struct engine *e, struct board *b)
180 struct uct *u = e->data;
182 if (!u->t) return NULL;
183 uct_pondering_stop(u);
184 reset_state(u);
185 return NULL;
188 static char *
189 uct_result(struct engine *e, struct board *b)
191 struct uct *u = e->data;
192 static char reply[1024];
194 if (!u->t)
195 return NULL;
196 enum stone color = u->t->root_color;
197 struct tree_node *n = u->t->root;
198 snprintf(reply, 1024, "%s %s %d %.2f %.1f",
199 stone2str(color), coord2sstr(n->coord, b),
200 n->u.playouts, tree_node_get_value(u->t, -1, n->u.value),
201 u->t->use_extra_komi ? u->t->extra_komi : 0);
202 return reply;
205 static char *
206 uct_chat(struct engine *e, struct board *b, char *cmd)
208 struct uct *u = e->data;
209 static char reply[1024];
211 cmd += strspn(cmd, " \n\t");
212 if (!strncasecmp(cmd, "winrate", 7)) {
213 if (!u->t)
214 return "no game context (yet?)";
215 enum stone color = u->t->root_color;
216 struct tree_node *n = u->t->root;
217 snprintf(reply, 1024, "In %d playouts at %d threads, %s %s can win with %.2f%% probability",
218 n->u.playouts, u->threads, stone2str(color), coord2sstr(n->coord, b),
219 tree_node_get_value(u->t, -1, n->u.value) * 100);
220 if (u->t->use_extra_komi && abs(u->t->extra_komi) >= 0.5) {
221 sprintf(reply + strlen(reply), ", while self-imposing extra komi %.1f",
222 u->t->extra_komi);
224 strcat(reply, ".");
225 return reply;
227 return NULL;
230 static void
231 uct_dead_group_list(struct engine *e, struct board *b, struct move_queue *mq)
233 struct uct *u = e->data;
235 /* This means the game is probably over, no use pondering on. */
236 uct_pondering_stop(u);
238 if (u->pass_all_alive)
239 return; // no dead groups
241 bool mock_state = false;
243 if (!u->t) {
244 /* No state, but we cannot just back out - we might
245 * have passed earlier, only assuming some stones are
246 * dead, and then re-connected, only to lose counting
247 * when all stones are assumed alive. */
248 uct_prepare_move(u, b, S_BLACK); assert(u->t);
249 mock_state = true;
251 /* Make sure the ownermap is well-seeded. */
252 while (u->ownermap.playouts < GJ_MINGAMES)
253 uct_playout(u, b, S_BLACK, u->t);
254 /* Show the ownermap: */
255 if (DEBUGL(2))
256 board_print_custom(b, stderr, uct_printhook_ownermap);
258 dead_group_list(u, b, mq);
260 if (mock_state) {
261 /* Clean up the mock state in case we will receive
262 * a genmove; we could get a non-alternating-move
263 * error from uct_prepare_move() in that case otherwise. */
264 reset_state(u);
268 static void
269 playout_policy_done(struct playout_policy *p)
271 if (p->done) p->done(p);
272 if (p->data) free(p->data);
273 free(p);
276 static void
277 uct_done(struct engine *e)
279 /* This is called on engine reset, especially when clear_board
280 * is received and new game should begin. */
281 struct uct *u = e->data;
282 uct_pondering_stop(u);
283 if (u->t) reset_state(u);
284 free(u->ownermap.map);
286 free(u->policy);
287 free(u->random_policy);
288 playout_policy_done(u->playout);
289 uct_prior_done(u->prior);
290 joseki_done(u->jdict);
291 pluginset_done(u->plugins);
296 /* Run time-limited MCTS search on foreground. */
297 static int
298 uct_search(struct uct *u, struct board *b, struct time_info *ti, enum stone color, struct tree *t)
300 struct uct_search_state s;
301 uct_search_start(u, b, color, t, ti, &s);
302 if (UDEBUGL(2) && s.base_playouts > 0)
303 fprintf(stderr, "<pre-simulated %d games>\n", s.base_playouts);
305 /* The search tree is ctx->t. This is currently == . It is important
306 * to reference ctx->t directly since the
307 * thread manager will swap the tree pointer asynchronously. */
309 /* Now, just periodically poll the search tree. */
310 /* Note that in case of TD_GAMES, threads will terminate independently
311 * of the uct_search_check_stop() signalization. */
312 while (1) {
313 time_sleep(TREE_BUSYWAIT_INTERVAL);
314 /* TREE_BUSYWAIT_INTERVAL should never be less than desired time, or the
315 * time control is broken. But if it happens to be less, we still search
316 * at least 100ms otherwise the move is completely random. */
318 int i = uct_search_games(&s);
319 /* Print notifications etc. */
320 uct_search_progress(u, b, color, t, ti, &s, i);
321 /* Check if we should stop the search. */
322 if (uct_search_check_stop(u, b, color, t, ti, &s, i))
323 break;
326 struct uct_thread_ctx *ctx = uct_search_stop();
327 if (UDEBUGL(2)) tree_dump(t, u->dumpthres, u->unlimited_tree_dump);
328 if (UDEBUGL(2))
329 fprintf(stderr, "(avg score %f/%d value %f/%d)\n",
330 u->dynkomi->score.value, u->dynkomi->score.playouts,
331 u->dynkomi->value.value, u->dynkomi->value.playouts);
332 if (UDEBUGL(0))
333 uct_progress_status(u, t, color, ctx->games);
335 u->played_own += ctx->games;
336 return ctx->games;
339 /* Start pondering background with @color to play. */
340 static void
341 uct_pondering_start(struct uct *u, struct board *b0, struct tree *t, enum stone color)
343 if (UDEBUGL(1))
344 fprintf(stderr, "Starting to ponder with color %s\n", stone2str(stone_other(color)));
345 u->pondering = true;
347 /* We need a local board copy to ponder upon. */
348 struct board *b = malloc2(sizeof(*b)); board_copy(b, b0);
350 /* *b0 did not have the genmove'd move played yet. */
351 struct move m = { t->root->coord, t->root_color };
352 int res = board_play(b, &m);
353 assert(res >= 0);
354 setup_dynkomi(u, b, stone_other(m.color));
356 /* Start MCTS manager thread "headless". */
357 static struct uct_search_state s;
358 uct_search_start(u, b, color, t, NULL, &s);
361 /* uct_search_stop() frontend for the pondering (non-genmove) mode, and
362 * to stop the background search for a slave in the distributed engine. */
363 void
364 uct_pondering_stop(struct uct *u)
366 if (!thread_manager_running)
367 return;
369 /* Stop the thread manager. */
370 struct uct_thread_ctx *ctx = uct_search_stop();
371 if (UDEBUGL(1)) {
372 if (u->pondering) fprintf(stderr, "(pondering) ");
373 uct_progress_status(u, ctx->t, ctx->color, ctx->games);
375 if (u->pondering) {
376 free(ctx->b);
377 u->pondering = false;
382 void
383 uct_genmove_setup(struct uct *u, struct board *b, enum stone color)
385 if (b->superko_violation) {
386 fprintf(stderr, "!!! WARNING: SUPERKO VIOLATION OCCURED BEFORE THIS MOVE\n");
387 fprintf(stderr, "Maybe you play with situational instead of positional superko?\n");
388 fprintf(stderr, "I'm going to ignore the violation, but note that I may miss\n");
389 fprintf(stderr, "some moves valid under this ruleset because of this.\n");
390 b->superko_violation = false;
393 uct_prepare_move(u, b, color);
395 assert(u->t);
396 u->my_color = color;
398 /* How to decide whether to use dynkomi in this game? Since we use
399 * pondering, it's not simple "who-to-play" matter. Decide based on
400 * the last genmove issued. */
401 u->t->use_extra_komi = !!(u->dynkomi_mask & color);
402 /* Moreover, we do not use extra komi at the game end - we are not
403 * to fool ourselves at this point. */
404 if (board_estimated_moves_left(b) <= MIN_MOVES_LEFT)
405 u->t->use_extra_komi = false;
406 setup_dynkomi(u, b, color);
408 if (b->rules == RULES_JAPANESE)
409 u->territory_scoring = true;
411 /* Make pessimistic assumption about komi for Japanese rules to
412 * avoid losing by 0.5 when winning by 0.5 with Chinese rules.
413 * The rules usually give the same winner if the integer part of komi
414 * is odd so we adjust the komi only if it is even (for a board of
415 * odd size). We are not trying to get an exact evaluation for rare
416 * cases of seki. For details see http://home.snafu.de/jasiek/parity.html */
417 if (u->territory_scoring && (((int)floor(b->komi) + board_size(b)) & 1)) {
418 b->komi += (color == S_BLACK ? 1.0 : -1.0);
419 if (UDEBUGL(0))
420 fprintf(stderr, "Setting komi to %.1f assuming Japanese rules\n",
421 b->komi);
425 static coord_t *
426 uct_genmove(struct engine *e, struct board *b, struct time_info *ti, enum stone color, bool pass_all_alive)
428 double start_time = time_now();
429 struct uct *u = e->data;
430 uct_pondering_stop(u);
431 uct_genmove_setup(u, b, color);
433 /* Start the Monte Carlo Tree Search! */
434 int base_playouts = u->t->root->u.playouts;
435 int played_games = uct_search(u, b, ti, color, u->t);
437 coord_t best_coord;
438 struct tree_node *best;
439 best = uct_search_result(u, b, color, pass_all_alive, played_games, base_playouts, &best_coord);
441 if (UDEBUGL(2)) {
442 double time = time_now() - start_time + 0.000001; /* avoid divide by zero */
443 fprintf(stderr, "genmove in %0.2fs (%d games/s, %d games/s/thread)\n",
444 time, (int)(played_games/time), (int)(played_games/time/u->threads));
447 if (!best) {
448 /* Pass or resign. */
449 reset_state(u);
450 return coord_copy(best_coord);
452 tree_promote_node(u->t, &best);
454 /* After a pass, pondering is harmful for two reasons:
455 * (i) We might keep pondering even when the game is over.
456 * Of course this is the case for opponent resign as well.
457 * (ii) More importantly, the ownermap will get skewed since
458 * the UCT will start cutting off any playouts. */
459 if (u->pondering_opt && !is_pass(best->coord)) {
460 uct_pondering_start(u, b, u->t, stone_other(color));
462 return coord_copy(best_coord);
466 bool
467 uct_gentbook(struct engine *e, struct board *b, struct time_info *ti, enum stone color)
469 struct uct *u = e->data;
470 if (!u->t) uct_prepare_move(u, b, color);
471 assert(u->t);
473 if (ti->dim == TD_GAMES) {
474 /* Don't count in games that already went into the tbook. */
475 ti->len.games += u->t->root->u.playouts;
477 uct_search(u, b, ti, color, u->t);
479 assert(ti->dim == TD_GAMES);
480 tree_save(u->t, b, ti->len.games / 100);
482 return true;
485 void
486 uct_dumptbook(struct engine *e, struct board *b, enum stone color)
488 struct uct *u = e->data;
489 struct tree *t = tree_init(b, color, u->fast_alloc ? u->max_tree_size : 0,
490 u->max_pruned_size, u->pruning_threshold, u->local_tree_aging, 0);
491 tree_load(t, b);
492 tree_dump(t, 0, true);
493 tree_done(t);
497 floating_t
498 uct_evaluate(struct engine *e, struct board *b, struct time_info *ti, coord_t c, enum stone color)
500 struct uct *u = e->data;
502 struct board b2;
503 board_copy(&b2, b);
504 struct move m = { c, color };
505 int res = board_play(&b2, &m);
506 if (res < 0)
507 return NAN;
508 color = stone_other(color);
510 if (u->t) reset_state(u);
511 uct_prepare_move(u, &b2, color);
512 assert(u->t);
514 floating_t bestval;
515 uct_search(u, &b2, ti, color, u->t);
516 struct tree_node *best = u->policy->choose(u->policy, u->t->root, &b2, color, resign);
517 if (!best) {
518 bestval = NAN; // the opponent has no reply!
519 } else {
520 bestval = tree_node_get_value(u->t, 1, best->u.value);
523 reset_state(u); // clean our junk
525 return isnan(bestval) ? NAN : 1.0f - bestval;
529 struct uct *
530 uct_state_init(char *arg, struct board *b)
532 struct uct *u = calloc2(1, sizeof(struct uct));
534 u->debug_level = debug_level;
535 u->gamelen = MC_GAMELEN;
536 u->resign_threshold = 0.2;
537 u->sure_win_threshold = 0.85;
538 u->mercymin = 0;
539 u->significant_threshold = 50;
540 u->expand_p = 2;
541 u->dumpthres = 1000;
542 u->unlimited_tree_dump = false;
543 u->playout_amaf = true;
544 u->playout_amaf_nakade = false;
545 u->amaf_prior = false;
546 u->max_tree_size = 1408ULL * 1048576;
547 u->fast_alloc = true;
548 u->pruning_threshold = 0;
550 u->threads = 1;
551 u->thread_model = TM_TREEVL;
552 u->virtual_loss = 1;
554 u->fuseki_end = 20; // max time at 361*20% = 72 moves (our 36th move, still 99 to play)
555 u->yose_start = 40; // (100-40-25)*361/100/2 = 63 moves still to play by us then
556 u->bestr_ratio = 0.02;
557 // 2.5 is clearly too much, but seems to compensate well for overly stern time allocations.
558 // TODO: Further tuning and experiments with better time allocation schemes.
559 u->best2_ratio = 2.5;
560 u->max_maintime_ratio = 8.0;
562 u->val_scale = 0.04; u->val_points = 40;
563 u->dynkomi_interval = 1000;
564 u->dynkomi_mask = S_BLACK | S_WHITE;
566 u->tenuki_d = 4;
567 u->local_tree_aging = 80;
568 u->local_tree_allseq = 1;
569 u->local_tree_rootseqval = 1;
570 u->local_tree_depth_decay = 1.5;
572 u->stats_delay = 0.01; // 10 ms
574 u->plugins = pluginset_init(b);
576 u->jdict = joseki_load(b->size);
578 if (arg) {
579 char *optspec, *next = arg;
580 while (*next) {
581 optspec = next;
582 next += strcspn(next, ",");
583 if (*next) { *next++ = 0; } else { *next = 0; }
585 char *optname = optspec;
586 char *optval = strchr(optspec, '=');
587 if (optval) *optval++ = 0;
589 /** Basic options */
591 if (!strcasecmp(optname, "debug")) {
592 if (optval)
593 u->debug_level = atoi(optval);
594 else
595 u->debug_level++;
596 } else if (!strcasecmp(optname, "dumpthres") && optval) {
597 /* When dumping the UCT tree on output, include
598 * nodes with at least this many playouts.
599 * (This value is re-scaled "intelligently"
600 * in case of very large trees.) */
601 u->dumpthres = atoi(optval);
602 } else if (!strcasecmp(optname, "unlimited_tree_dump")) {
603 /* If true, dumpthres is not increased even if the number of
604 * playouts is much larger than it. Good for debugging, but could
605 * lead to too much verbosity in actual games. */
606 u->unlimited_tree_dump = true;
607 } else if (!strcasecmp(optname, "resign_threshold") && optval) {
608 /* Resign when this ratio of games is lost
609 * after GJ_MINGAMES sample is taken. */
610 u->resign_threshold = atof(optval);
611 } else if (!strcasecmp(optname, "sure_win_threshold") && optval) {
612 /* Stop reading when this ratio of games is won
613 * after PLAYOUT_EARLY_BREAK_MIN sample is
614 * taken. (Prevents stupid time losses,
615 * friendly to human opponents.) */
616 u->sure_win_threshold = atof(optval);
617 } else if (!strcasecmp(optname, "force_seed") && optval) {
618 /* Set RNG seed at the tree setup. */
619 u->force_seed = atoi(optval);
620 } else if (!strcasecmp(optname, "no_tbook")) {
621 /* Disable UCT opening tbook. */
622 u->no_tbook = true;
623 } else if (!strcasecmp(optname, "pass_all_alive")) {
624 /* Whether to consider passing only after all
625 * dead groups were removed from the board;
626 * this is like all genmoves are in fact
627 * kgs-genmove_cleanup. */
628 u->pass_all_alive = !optval || atoi(optval);
629 } else if (!strcasecmp(optname, "territory_scoring")) {
630 /* Use territory scoring (default is area scoring).
631 * An explicit kgs-rules command overrides this. */
632 u->territory_scoring = !optval || atoi(optval);
633 } else if (!strcasecmp(optname, "banner") && optval) {
634 /* Additional banner string. This must come as the
635 * last engine parameter. */
636 if (*next) *--next = ',';
637 u->banner = strdup(optval);
638 break;
639 } else if (!strcasecmp(optname, "plugin") && optval) {
640 /* Load an external plugin; filename goes before the colon,
641 * extra arguments after the colon. */
642 char *pluginarg = strchr(optval, ':');
643 if (pluginarg)
644 *pluginarg++ = 0;
645 plugin_load(u->plugins, optval, pluginarg);
647 /** UCT behavior and policies */
649 } else if ((!strcasecmp(optname, "policy")
650 /* Node selection policy. ucb1amaf is the
651 * default policy implementing RAVE, while
652 * ucb1 is the simple exploration/exploitation
653 * policy. Policies can take further extra
654 * options. */
655 || !strcasecmp(optname, "random_policy")) && optval) {
656 /* A policy to be used randomly with small
657 * chance instead of the default policy. */
658 char *policyarg = strchr(optval, ':');
659 struct uct_policy **p = !strcasecmp(optname, "policy") ? &u->policy : &u->random_policy;
660 if (policyarg)
661 *policyarg++ = 0;
662 if (!strcasecmp(optval, "ucb1")) {
663 *p = policy_ucb1_init(u, policyarg);
664 } else if (!strcasecmp(optval, "ucb1amaf")) {
665 *p = policy_ucb1amaf_init(u, policyarg);
666 } else {
667 fprintf(stderr, "UCT: Invalid tree policy %s\n", optval);
668 exit(1);
670 } else if (!strcasecmp(optname, "playout") && optval) {
671 /* Random simulation (playout) policy.
672 * moggy is the default policy with large
673 * amount of domain-specific knowledge and
674 * heuristics. light is a simple uniformly
675 * random move selection policy. */
676 char *playoutarg = strchr(optval, ':');
677 if (playoutarg)
678 *playoutarg++ = 0;
679 if (!strcasecmp(optval, "moggy")) {
680 u->playout = playout_moggy_init(playoutarg, b, u->jdict);
681 } else if (!strcasecmp(optval, "light")) {
682 u->playout = playout_light_init(playoutarg, b);
683 } else {
684 fprintf(stderr, "UCT: Invalid playout policy %s\n", optval);
685 exit(1);
687 } else if (!strcasecmp(optname, "prior") && optval) {
688 /* Node priors policy. When expanding a node,
689 * it will seed node values heuristically
690 * (most importantly, based on playout policy
691 * opinion, but also with regard to other
692 * things). See uct/prior.c for details.
693 * Use prior=eqex=0 to disable priors. */
694 u->prior = uct_prior_init(optval, b);
695 } else if (!strcasecmp(optname, "mercy") && optval) {
696 /* Minimal difference of black/white captures
697 * to stop playout - "Mercy Rule". Speeds up
698 * hopeless playouts at the expense of some
699 * accuracy. */
700 u->mercymin = atoi(optval);
701 } else if (!strcasecmp(optname, "gamelen") && optval) {
702 /* Maximum length of single simulation
703 * in moves. */
704 u->gamelen = atoi(optval);
705 } else if (!strcasecmp(optname, "expand_p") && optval) {
706 /* Expand UCT nodes after it has been
707 * visited this many times. */
708 u->expand_p = atoi(optval);
709 } else if (!strcasecmp(optname, "random_policy_chance") && optval) {
710 /* If specified (N), with probability 1/N, random_policy policy
711 * descend is used instead of main policy descend; useful
712 * if specified policy (e.g. UCB1AMAF) can make unduly biased
713 * choices sometimes, you can fall back to e.g.
714 * random_policy=UCB1. */
715 u->random_policy_chance = atoi(optval);
717 /** General AMAF behavior */
718 /* (Only relevant if the policy supports AMAF.
719 * More variables can be tuned as policy
720 * parameters.) */
722 } else if (!strcasecmp(optname, "playout_amaf")) {
723 /* Whether to include random playout moves in
724 * AMAF as well. (Otherwise, only tree moves
725 * are included in AMAF. Of course makes sense
726 * only in connection with an AMAF policy.) */
727 /* with-without: 55.5% (+-4.1) */
728 if (optval && *optval == '0')
729 u->playout_amaf = false;
730 else
731 u->playout_amaf = true;
732 } else if (!strcasecmp(optname, "playout_amaf_nakade")) {
733 /* Whether to include nakade moves from playouts
734 * in the AMAF statistics; this tends to nullify
735 * the playout_amaf effect by adding too much
736 * noise. */
737 if (optval && *optval == '0')
738 u->playout_amaf_nakade = false;
739 else
740 u->playout_amaf_nakade = true;
741 } else if (!strcasecmp(optname, "playout_amaf_cutoff") && optval) {
742 /* Keep only first N% of playout stage AMAF
743 * information. */
744 u->playout_amaf_cutoff = atoi(optval);
745 } else if (!strcasecmp(optname, "amaf_prior") && optval) {
746 /* In node policy, consider prior values
747 * part of the real result term or part
748 * of the AMAF term? */
749 u->amaf_prior = atoi(optval);
751 /** Performance and memory management */
753 } else if (!strcasecmp(optname, "threads") && optval) {
754 /* By default, Pachi will run with only single
755 * tree search thread! */
756 u->threads = atoi(optval);
757 } else if (!strcasecmp(optname, "thread_model") && optval) {
758 if (!strcasecmp(optval, "tree")) {
759 /* Tree parallelization - all threads
760 * grind on the same tree. */
761 u->thread_model = TM_TREE;
762 u->virtual_loss = 0;
763 } else if (!strcasecmp(optval, "treevl")) {
764 /* Tree parallelization, but also
765 * with virtual losses - this discou-
766 * rages most threads choosing the
767 * same tree branches to read. */
768 u->thread_model = TM_TREEVL;
769 } else {
770 fprintf(stderr, "UCT: Invalid thread model %s\n", optval);
771 exit(1);
773 } else if (!strcasecmp(optname, "virtual_loss")) {
774 /* Number of virtual losses added before evaluating a node. */
775 u->virtual_loss = !optval || atoi(optval);
776 } else if (!strcasecmp(optname, "pondering")) {
777 /* Keep searching even during opponent's turn. */
778 u->pondering_opt = !optval || atoi(optval);
779 } else if (!strcasecmp(optname, "max_tree_size") && optval) {
780 /* Maximum amount of memory [MiB] consumed by the move tree.
781 * For fast_alloc it includes the temp tree used for pruning.
782 * Default is 3072 (3 GiB). */
783 u->max_tree_size = atol(optval) * 1048576;
784 } else if (!strcasecmp(optname, "fast_alloc")) {
785 u->fast_alloc = !optval || atoi(optval);
786 } else if (!strcasecmp(optname, "pruning_threshold") && optval) {
787 /* Force pruning at beginning of a move if the tree consumes
788 * more than this [MiB]. Default is 10% of max_tree_size.
789 * Increase to reduce pruning time overhead if memory is plentiful.
790 * This option is meaningful only for fast_alloc. */
791 u->pruning_threshold = atol(optval) * 1048576;
793 /** Time control */
795 } else if (!strcasecmp(optname, "best2_ratio") && optval) {
796 /* If set, prolong simulating while
797 * first_best/second_best playouts ratio
798 * is less than best2_ratio. */
799 u->best2_ratio = atof(optval);
800 } else if (!strcasecmp(optname, "bestr_ratio") && optval) {
801 /* If set, prolong simulating while
802 * best,best_best_child values delta
803 * is more than bestr_ratio. */
804 u->bestr_ratio = atof(optval);
805 } else if (!strcasecmp(optname, "max_maintime_ratio") && optval) {
806 /* If set and while not in byoyomi, prolong simulating no more than
807 * max_maintime_ratio times the normal desired thinking time. */
808 u->max_maintime_ratio = atof(optval);
809 } else if (!strcasecmp(optname, "fuseki_end") && optval) {
810 /* At the very beginning it's not worth thinking
811 * too long because the playout evaluations are
812 * very noisy. So gradually increase the thinking
813 * time up to maximum when fuseki_end percent
814 * of the board has been played.
815 * This only applies if we are not in byoyomi. */
816 u->fuseki_end = atoi(optval);
817 } else if (!strcasecmp(optname, "yose_start") && optval) {
818 /* When yose_start percent of the board has been
819 * played, or if we are in byoyomi, stop spending
820 * more time and spread the remaining time
821 * uniformly.
822 * Between fuseki_end and yose_start, we spend
823 * a constant proportion of the remaining time
824 * on each move. (yose_start should actually
825 * be much earlier than when real yose start,
826 * but "yose" is a good short name to convey
827 * the idea.) */
828 u->yose_start = atoi(optval);
830 /** Dynamic komi */
832 } else if (!strcasecmp(optname, "dynkomi") && optval) {
833 /* Dynamic komi approach; there are multiple
834 * ways to adjust komi dynamically throughout
835 * play. We currently support two: */
836 char *dynkomiarg = strchr(optval, ':');
837 if (dynkomiarg)
838 *dynkomiarg++ = 0;
839 if (!strcasecmp(optval, "none")) {
840 u->dynkomi = uct_dynkomi_init_none(u, dynkomiarg, b);
841 } else if (!strcasecmp(optval, "linear")) {
842 /* You should set dynkomi_mask=1
843 * since this doesn't work well
844 * for white handicaps! */
845 u->dynkomi = uct_dynkomi_init_linear(u, dynkomiarg, b);
846 } else if (!strcasecmp(optval, "adaptive")) {
847 /* There are many more knobs to
848 * crank - see uct/dynkomi.c. */
849 u->dynkomi = uct_dynkomi_init_adaptive(u, dynkomiarg, b);
850 } else {
851 fprintf(stderr, "UCT: Invalid dynkomi mode %s\n", optval);
852 exit(1);
854 } else if (!strcasecmp(optname, "dynkomi_mask") && optval) {
855 /* Bitmask of colors the player must be
856 * for dynkomi be applied; you may want
857 * to use dynkomi_mask=3 to allow dynkomi
858 * even in games where Pachi is white. */
859 u->dynkomi_mask = atoi(optval);
860 } else if (!strcasecmp(optname, "dynkomi_interval") && optval) {
861 /* If non-zero, re-adjust dynamic komi
862 * throughout a single genmove reading,
863 * roughly every N simulations. */
864 /* XXX: Does not work with tree
865 * parallelization. */
866 u->dynkomi_interval = atoi(optval);
868 /** Node value result scaling */
870 } else if (!strcasecmp(optname, "val_scale") && optval) {
871 /* How much of the game result value should be
872 * influenced by win size. Zero means it isn't. */
873 u->val_scale = atof(optval);
874 } else if (!strcasecmp(optname, "val_points") && optval) {
875 /* Maximum size of win to be scaled into game
876 * result value. Zero means boardsize^2. */
877 u->val_points = atoi(optval) * 2; // result values are doubled
878 } else if (!strcasecmp(optname, "val_extra")) {
879 /* If false, the score coefficient will be simply
880 * added to the value, instead of scaling the result
881 * coefficient because of it. */
882 u->val_extra = !optval || atoi(optval);
884 /** Local trees */
885 /* (Purely experimental. Does not work - yet!) */
887 } else if (!strcasecmp(optname, "local_tree") && optval) {
888 /* Whether to bias exploration by local tree values
889 * (must be supported by the used policy).
890 * 0: Don't.
891 * 1: Do, value = result.
892 * Try to temper the result:
893 * 2: Do, value = 0.5+(result-expected)/2.
894 * 3: Do, value = 0.5+bzz((result-expected)^2).
895 * 4: Do, value = 0.5+sqrt(result-expected)/2. */
896 u->local_tree = atoi(optval);
897 } else if (!strcasecmp(optname, "tenuki_d") && optval) {
898 /* Tenuki distance at which to break the local tree. */
899 u->tenuki_d = atoi(optval);
900 if (u->tenuki_d > TREE_NODE_D_MAX + 1) {
901 fprintf(stderr, "uct: tenuki_d must not be larger than TREE_NODE_D_MAX+1 %d\n", TREE_NODE_D_MAX + 1);
902 exit(1);
904 } else if (!strcasecmp(optname, "local_tree_aging") && optval) {
905 /* How much to reduce local tree values between moves. */
906 u->local_tree_aging = atof(optval);
907 } else if (!strcasecmp(optname, "local_tree_depth_decay") && optval) {
908 /* With value x>0, during the descent the node
909 * contributes 1/x^depth playouts in
910 * the local tree. I.e., with x>1, nodes more
911 * distant from local situation contribute more
912 * than nodes near the root. */
913 u->local_tree_depth_decay = atof(optval);
914 } else if (!strcasecmp(optname, "local_tree_allseq")) {
915 /* If disabled, only complete sequences are stored
916 * in the local tree. If this is on, also
917 * subsequences starting at each move are stored. */
918 u->local_tree_allseq = !optval || atoi(optval);
919 } else if (!strcasecmp(optname, "local_tree_rootseqval")) {
920 /* If disabled, expected node value is computed by
921 * summing up values through the whole descent.
922 * If enabled, expected node value for
923 * each sequence is the value at the root of the
924 * sequence. */
925 u->local_tree_rootseqval = !optval || atoi(optval);
927 /** Other heuristics */
928 } else if (!strcasecmp(optname, "significant_threshold") && optval) {
929 /* Some heuristics (XXX: none in mainline) rely
930 * on the knowledge of the last "significant"
931 * node in the descent. Such a node is
932 * considered reasonably trustworthy to carry
933 * some meaningful information in the values
934 * of the node and its children. */
935 u->significant_threshold = atoi(optval);
937 /** Distributed engine slaves setup */
939 } else if (!strcasecmp(optname, "slave")) {
940 /* Act as slave for the distributed engine. */
941 u->slave = !optval || atoi(optval);
942 } else if (!strcasecmp(optname, "shared_nodes") && optval) {
943 /* Share at most shared_nodes between master and slave at each genmoves.
944 * Must use the same value in master and slaves. */
945 u->shared_nodes = atoi(optval);
946 } else if (!strcasecmp(optname, "shared_levels") && optval) {
947 /* Share only nodes of level <= shared_levels. */
948 u->shared_levels = atoi(optval);
949 } else if (!strcasecmp(optname, "stats_hbits") && optval) {
950 /* Set hash table size to 2^stats_hbits for the shared stats. */
951 u->stats_hbits = atoi(optval);
952 } else if (!strcasecmp(optname, "stats_delay") && optval) {
953 /* How long to wait in slave for initial stats to build up before
954 * replying to the genmoves command (in ms) */
955 u->stats_delay = 0.001 * atof(optval);
957 } else {
958 fprintf(stderr, "uct: Invalid engine argument %s or missing value\n", optname);
959 exit(1);
964 if (!u->policy)
965 u->policy = policy_ucb1amaf_init(u, NULL);
967 if (!!u->random_policy_chance ^ !!u->random_policy) {
968 fprintf(stderr, "uct: Only one of random_policy and random_policy_chance is set\n");
969 exit(1);
972 if (!u->local_tree) {
973 /* No ltree aging. */
974 u->local_tree_aging = 1.0f;
977 if (u->fast_alloc) {
978 if (u->pruning_threshold < u->max_tree_size / 10)
979 u->pruning_threshold = u->max_tree_size / 10;
980 if (u->pruning_threshold > u->max_tree_size / 2)
981 u->pruning_threshold = u->max_tree_size / 2;
983 /* Limit pruning temp space to 20% of memory. Beyond this we discard
984 * the nodes and recompute them at the next move if necessary. */
985 u->max_pruned_size = u->max_tree_size / 5;
986 u->max_tree_size -= u->max_pruned_size;
987 } else {
988 /* Reserve 5% memory in case the background free() are slower
989 * than the concurrent allocations. */
990 u->max_tree_size -= u->max_tree_size / 20;
993 if (!u->prior)
994 u->prior = uct_prior_init(NULL, b);
996 if (!u->playout)
997 u->playout = playout_moggy_init(NULL, b, u->jdict);
998 if (!u->playout->debug_level)
999 u->playout->debug_level = u->debug_level;
1001 u->ownermap.map = malloc2(board_size2(b) * sizeof(u->ownermap.map[0]));
1003 if (u->slave) {
1004 if (!u->stats_hbits) u->stats_hbits = DEFAULT_STATS_HBITS;
1005 if (!u->shared_nodes) u->shared_nodes = DEFAULT_SHARED_NODES;
1006 assert(u->shared_levels * board_bits2(b) <= 8 * (int)sizeof(path_t));
1009 if (!u->dynkomi)
1010 u->dynkomi = uct_dynkomi_init_adaptive(u, NULL, b);
1012 /* Some things remain uninitialized for now - the opening tbook
1013 * is not loaded and the tree not set up. */
1014 /* This will be initialized in setup_state() at the first move
1015 * received/requested. This is because right now we are not aware
1016 * about any komi or handicap setup and such. */
1018 return u;
1021 struct engine *
1022 engine_uct_init(char *arg, struct board *b)
1024 struct uct *u = uct_state_init(arg, b);
1025 struct engine *e = calloc2(1, sizeof(struct engine));
1026 e->name = "UCT Engine";
1027 e->printhook = uct_printhook_ownermap;
1028 e->notify_play = uct_notify_play;
1029 e->chat = uct_chat;
1030 e->undo = uct_undo;
1031 e->result = uct_result;
1032 e->genmove = uct_genmove;
1033 e->genmoves = uct_genmoves;
1034 e->dead_group_list = uct_dead_group_list;
1035 e->done = uct_done;
1036 e->data = u;
1037 if (u->slave)
1038 e->notify = uct_notify;
1040 const char banner[] = "I'm playing UCT. When I'm losing, I will resign, "
1041 "if I think I win, I play until you pass. "
1042 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
1043 if (!u->banner) u->banner = "";
1044 e->comment = malloc2(sizeof(banner) + strlen(u->banner) + 1);
1045 sprintf(e->comment, "%s %s", banner, u->banner);
1047 return e;