UCT max_maintime_ratio: Raise back to 2.0
[pachi.git] / uct / uct.c
blob3eac436b7e8c6a29c9fc9d03f2235ce90cf30c3d
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 "chat.h"
14 #include "move.h"
15 #include "mq.h"
16 #include "joseki/base.h"
17 #include "playout.h"
18 #include "playout/moggy.h"
19 #include "playout/light.h"
20 #include "tactics/util.h"
21 #include "timeinfo.h"
22 #include "uct/dynkomi.h"
23 #include "uct/internal.h"
24 #include "uct/plugins.h"
25 #include "uct/prior.h"
26 #include "uct/search.h"
27 #include "uct/slave.h"
28 #include "uct/tree.h"
29 #include "uct/uct.h"
30 #include "uct/walk.h"
32 struct uct_policy *policy_ucb1_init(struct uct *u, char *arg);
33 struct uct_policy *policy_ucb1amaf_init(struct uct *u, char *arg, struct board *board);
34 static void uct_pondering_start(struct uct *u, struct board *b0, struct tree *t, enum stone color);
36 /* Maximal simulation length. */
37 #define MC_GAMELEN MAX_GAMELEN
40 static void
41 setup_state(struct uct *u, struct board *b, enum stone color)
43 u->t = tree_init(b, color, u->fast_alloc ? u->max_tree_size : 0,
44 u->max_pruned_size, u->pruning_threshold, u->local_tree_aging, u->stats_hbits);
45 if (u->initial_extra_komi)
46 u->t->extra_komi = u->initial_extra_komi;
47 if (u->force_seed)
48 fast_srandom(u->force_seed);
49 if (UDEBUGL(3))
50 fprintf(stderr, "Fresh board with random seed %lu\n", fast_getseed());
51 if (!u->no_tbook && b->moves == 0) {
52 if (color == S_BLACK) {
53 tree_load(u->t, b);
54 } else if (DEBUGL(0)) {
55 fprintf(stderr, "Warning: First move appears to be white\n");
60 static void
61 reset_state(struct uct *u)
63 assert(u->t);
64 tree_done(u->t); u->t = NULL;
67 static void
68 setup_dynkomi(struct uct *u, struct board *b, enum stone to_play)
70 if (u->t->use_extra_komi && !u->pondering && u->dynkomi->permove)
71 u->t->extra_komi = u->dynkomi->permove(u->dynkomi, b, u->t);
72 else if (!u->t->use_extra_komi)
73 u->t->extra_komi = 0;
76 void
77 uct_prepare_move(struct uct *u, struct board *b, enum stone color)
79 if (u->t) {
80 /* Verify that we have sane state. */
81 assert(b->es == u);
82 assert(u->t && b->moves);
83 if (color != stone_other(u->t->root_color)) {
84 fprintf(stderr, "Fatal: Non-alternating play detected %d %d\n",
85 color, u->t->root_color);
86 exit(1);
88 uct_htable_reset(u->t);
90 } else {
91 /* We need fresh state. */
92 b->es = u;
93 setup_state(u, b, color);
96 u->ownermap.playouts = 0;
97 memset(u->ownermap.map, 0, board_size2(b) * sizeof(u->ownermap.map[0]));
98 u->played_own = u->played_all = 0;
101 static void
102 dead_group_list(struct uct *u, struct board *b, struct move_queue *mq)
104 enum gj_state gs_array[board_size2(b)];
105 struct group_judgement gj = { .thres = GJ_THRES, .gs = gs_array };
106 board_ownermap_judge_groups(b, &u->ownermap, &gj);
107 groups_of_status(b, &gj, GS_DEAD, mq);
110 bool
111 uct_pass_is_safe(struct uct *u, struct board *b, enum stone color, bool pass_all_alive)
113 /* Make sure enough playouts are simulated to get a reasonable dead group list. */
114 while (u->ownermap.playouts < GJ_MINGAMES)
115 uct_playout(u, b, color, u->t);
117 struct move_queue mq = { .moves = 0 };
118 dead_group_list(u, b, &mq);
119 if (pass_all_alive) {
120 for (unsigned int i = 0; i < mq.moves; i++) {
121 if (board_at(b, mq.move[i]) == stone_other(color)) {
122 return false; // We need to remove opponent dead groups first.
125 mq.moves = 0; // our dead stones are alive when pass_all_alive is true
127 if (u->allow_losing_pass) {
128 foreach_point(b) {
129 if (board_at(b, c) == S_OFFBOARD)
130 continue;
131 if (board_ownermap_judge_point(&u->ownermap, c, GJ_THRES) == PJ_UNKNOWN) {
132 if (UDEBUGL(3))
133 fprintf(stderr, "uct_pass_is_safe fails at %s[%d]\n", coord2sstr(c, b), c);
134 return false; // Unclear point, clarify first.
136 } foreach_point_end;
137 return true;
139 return pass_is_safe(b, color, &mq);
142 static char *
143 uct_printhook_ownermap(struct board *board, coord_t c, char *s, char *end)
145 struct uct *u = board->es;
146 if (!u) {
147 strcat(s, ". ");
148 return s + 2;
150 const char chr[] = ":XO,"; // dame, black, white, unclear
151 const char chm[] = ":xo,";
152 char ch = chr[board_ownermap_judge_point(&u->ownermap, c, GJ_THRES)];
153 if (ch == ',') { // less precise estimate then?
154 ch = chm[board_ownermap_judge_point(&u->ownermap, c, 0.67)];
156 s += snprintf(s, end - s, "%c ", ch);
157 return s;
160 static char *
161 uct_notify_play(struct engine *e, struct board *b, struct move *m, char *enginearg)
163 struct uct *u = e->data;
164 if (!u->t) {
165 /* No state, create one - this is probably game beginning
166 * and we need to load the opening tbook right now. */
167 uct_prepare_move(u, b, m->color);
168 assert(u->t);
171 /* Stop pondering, required by tree_promote_at() */
172 uct_pondering_stop(u);
173 if (UDEBUGL(2) && u->slave)
174 tree_dump(u->t, u->dumpthres);
176 if (is_resign(m->coord)) {
177 /* Reset state. */
178 reset_state(u);
179 return NULL;
182 /* Promote node of the appropriate move to the tree root. */
183 assert(u->t->root);
184 if (!tree_promote_at(u->t, b, m->coord)) {
185 if (UDEBUGL(3))
186 fprintf(stderr, "Warning: Cannot promote move node! Several play commands in row?\n");
187 /* Preserve dynamic komi information, though, that is important. */
188 u->initial_extra_komi = u->t->extra_komi;
189 reset_state(u);
190 return NULL;
193 /* If we are a slave in a distributed engine, start pondering once
194 * we know which move we actually played. See uct_genmove() about
195 * the check for pass. */
196 if (u->pondering_opt && u->slave && m->color == u->my_color && !is_pass(m->coord))
197 uct_pondering_start(u, b, u->t, stone_other(m->color));
199 return NULL;
202 static char *
203 uct_undo(struct engine *e, struct board *b)
205 struct uct *u = e->data;
207 if (!u->t) return NULL;
208 uct_pondering_stop(u);
209 u->initial_extra_komi = u->t->extra_komi;
210 reset_state(u);
211 return NULL;
214 static char *
215 uct_result(struct engine *e, struct board *b)
217 struct uct *u = e->data;
218 static char reply[1024];
220 if (!u->t)
221 return NULL;
222 enum stone color = u->t->root_color;
223 struct tree_node *n = u->t->root;
224 snprintf(reply, 1024, "%s %s %d %.2f %.1f",
225 stone2str(color), coord2sstr(node_coord(n), b),
226 n->u.playouts, tree_node_get_value(u->t, -1, n->u.value),
227 u->t->use_extra_komi ? u->t->extra_komi : 0);
228 return reply;
231 static char *
232 uct_chat(struct engine *e, struct board *b, bool opponent, char *from, char *cmd)
234 struct uct *u = e->data;
236 if (!u->t)
237 return generic_chat(b, opponent, from, cmd, S_NONE, pass, 0, 1, u->threads, 0.0, 0.0);
239 struct tree_node *n = u->t->root;
240 double winrate = tree_node_get_value(u->t, -1, n->u.value);
241 double extra_komi = u->t->use_extra_komi && abs(u->t->extra_komi) >= 0.5 ? u->t->extra_komi : 0;
243 return generic_chat(b, opponent, from, cmd, u->t->root_color, node_coord(n), n->u.playouts, 1,
244 u->threads, winrate, extra_komi);
247 static void
248 uct_dead_group_list(struct engine *e, struct board *b, struct move_queue *mq)
250 struct uct *u = e->data;
252 /* This means the game is probably over, no use pondering on. */
253 uct_pondering_stop(u);
255 if (u->pass_all_alive)
256 return; // no dead groups
258 bool mock_state = false;
260 if (!u->t) {
261 /* No state, but we cannot just back out - we might
262 * have passed earlier, only assuming some stones are
263 * dead, and then re-connected, only to lose counting
264 * when all stones are assumed alive. */
265 uct_prepare_move(u, b, S_BLACK); assert(u->t);
266 mock_state = true;
268 /* Make sure the ownermap is well-seeded. */
269 while (u->ownermap.playouts < GJ_MINGAMES)
270 uct_playout(u, b, S_BLACK, u->t);
271 /* Show the ownermap: */
272 if (DEBUGL(2))
273 board_print_custom(b, stderr, uct_printhook_ownermap);
275 dead_group_list(u, b, mq);
277 if (mock_state) {
278 /* Clean up the mock state in case we will receive
279 * a genmove; we could get a non-alternating-move
280 * error from uct_prepare_move() in that case otherwise. */
281 reset_state(u);
285 static void
286 playout_policy_done(struct playout_policy *p)
288 if (p->done) p->done(p);
289 if (p->data) free(p->data);
290 free(p);
293 static void
294 uct_done(struct engine *e)
296 /* This is called on engine reset, especially when clear_board
297 * is received and new game should begin. */
298 struct uct *u = e->data;
299 uct_pondering_stop(u);
300 if (u->t) reset_state(u);
301 free(u->ownermap.map);
303 free(u->policy);
304 free(u->random_policy);
305 playout_policy_done(u->playout);
306 uct_prior_done(u->prior);
307 joseki_done(u->jdict);
308 pluginset_done(u->plugins);
313 /* Run time-limited MCTS search on foreground. */
314 static int
315 uct_search(struct uct *u, struct board *b, struct time_info *ti, enum stone color, struct tree *t, bool print_progress)
317 struct uct_search_state s;
318 uct_search_start(u, b, color, t, ti, &s);
319 if (UDEBUGL(2) && s.base_playouts > 0)
320 fprintf(stderr, "<pre-simulated %d games>\n", s.base_playouts);
322 /* The search tree is ctx->t. This is currently == . It is important
323 * to reference ctx->t directly since the
324 * thread manager will swap the tree pointer asynchronously. */
326 /* Now, just periodically poll the search tree. */
327 /* Note that in case of TD_GAMES, threads will not wait for
328 * the uct_search_check_stop() signalization. */
329 while (1) {
330 time_sleep(TREE_BUSYWAIT_INTERVAL);
331 /* TREE_BUSYWAIT_INTERVAL should never be less than desired time, or the
332 * time control is broken. But if it happens to be less, we still search
333 * at least 100ms otherwise the move is completely random. */
335 int i = uct_search_games(&s);
336 /* Print notifications etc. */
337 uct_search_progress(u, b, color, t, ti, &s, i);
338 /* Check if we should stop the search. */
339 if (uct_search_check_stop(u, b, color, t, ti, &s, i))
340 break;
343 struct uct_thread_ctx *ctx = uct_search_stop();
344 if (UDEBUGL(2)) tree_dump(t, u->dumpthres);
345 if (UDEBUGL(2))
346 fprintf(stderr, "(avg score %f/%d; dynkomi's %f/%d value %f/%d)\n",
347 t->avg_score.value, t->avg_score.playouts,
348 u->dynkomi->score.value, u->dynkomi->score.playouts,
349 u->dynkomi->value.value, u->dynkomi->value.playouts);
350 if (print_progress)
351 uct_progress_status(u, t, color, ctx->games, NULL);
353 u->played_own += ctx->games;
354 return ctx->games;
357 /* Start pondering background with @color to play. */
358 static void
359 uct_pondering_start(struct uct *u, struct board *b0, struct tree *t, enum stone color)
361 if (UDEBUGL(1))
362 fprintf(stderr, "Starting to ponder with color %s\n", stone2str(stone_other(color)));
363 u->pondering = true;
365 /* We need a local board copy to ponder upon. */
366 struct board *b = malloc2(sizeof(*b)); board_copy(b, b0);
368 /* *b0 did not have the genmove'd move played yet. */
369 struct move m = { node_coord(t->root), t->root_color };
370 int res = board_play(b, &m);
371 assert(res >= 0);
372 setup_dynkomi(u, b, stone_other(m.color));
374 /* Start MCTS manager thread "headless". */
375 static struct uct_search_state s;
376 uct_search_start(u, b, color, t, NULL, &s);
379 /* uct_search_stop() frontend for the pondering (non-genmove) mode, and
380 * to stop the background search for a slave in the distributed engine. */
381 void
382 uct_pondering_stop(struct uct *u)
384 if (!thread_manager_running)
385 return;
387 /* Stop the thread manager. */
388 struct uct_thread_ctx *ctx = uct_search_stop();
389 if (UDEBUGL(1)) {
390 if (u->pondering) fprintf(stderr, "(pondering) ");
391 uct_progress_status(u, ctx->t, ctx->color, ctx->games, NULL);
393 if (u->pondering) {
394 free(ctx->b);
395 u->pondering = false;
400 void
401 uct_genmove_setup(struct uct *u, struct board *b, enum stone color)
403 if (b->superko_violation) {
404 fprintf(stderr, "!!! WARNING: SUPERKO VIOLATION OCCURED BEFORE THIS MOVE\n");
405 fprintf(stderr, "Maybe you play with situational instead of positional superko?\n");
406 fprintf(stderr, "I'm going to ignore the violation, but note that I may miss\n");
407 fprintf(stderr, "some moves valid under this ruleset because of this.\n");
408 b->superko_violation = false;
411 uct_prepare_move(u, b, color);
413 assert(u->t);
414 u->my_color = color;
416 /* How to decide whether to use dynkomi in this game? Since we use
417 * pondering, it's not simple "who-to-play" matter. Decide based on
418 * the last genmove issued. */
419 u->t->use_extra_komi = !!(u->dynkomi_mask & color);
420 setup_dynkomi(u, b, color);
422 if (b->rules == RULES_JAPANESE)
423 u->territory_scoring = true;
425 /* Make pessimistic assumption about komi for Japanese rules to
426 * avoid losing by 0.5 when winning by 0.5 with Chinese rules.
427 * The rules usually give the same winner if the integer part of komi
428 * is odd so we adjust the komi only if it is even (for a board of
429 * odd size). We are not trying to get an exact evaluation for rare
430 * cases of seki. For details see http://home.snafu.de/jasiek/parity.html */
431 if (u->territory_scoring && (((int)floor(b->komi) + board_size(b)) & 1)) {
432 b->komi += (color == S_BLACK ? 1.0 : -1.0);
433 if (UDEBUGL(0))
434 fprintf(stderr, "Setting komi to %.1f assuming Japanese rules\n",
435 b->komi);
439 static coord_t *
440 uct_genmove(struct engine *e, struct board *b, struct time_info *ti, enum stone color, bool pass_all_alive)
442 double start_time = time_now();
443 struct uct *u = e->data;
444 u->pass_all_alive |= pass_all_alive;
445 uct_pondering_stop(u);
446 uct_genmove_setup(u, b, color);
448 /* Start the Monte Carlo Tree Search! */
449 int base_playouts = u->t->root->u.playouts;
450 int played_games = uct_search(u, b, ti, color, u->t, false);
452 coord_t best_coord;
453 struct tree_node *best;
454 best = uct_search_result(u, b, color, u->pass_all_alive, played_games, base_playouts, &best_coord);
456 if (UDEBUGL(2)) {
457 double time = time_now() - start_time + 0.000001; /* avoid divide by zero */
458 fprintf(stderr, "genmove in %0.2fs (%d games/s, %d games/s/thread)\n",
459 time, (int)(played_games/time), (int)(played_games/time/u->threads));
462 uct_progress_status(u, u->t, color, played_games, &best_coord);
464 if (!best) {
465 /* Pass or resign. */
466 if (is_pass(best_coord))
467 u->initial_extra_komi = u->t->extra_komi;
468 reset_state(u);
469 return coord_copy(best_coord);
471 tree_promote_node(u->t, &best);
473 /* After a pass, pondering is harmful for two reasons:
474 * (i) We might keep pondering even when the game is over.
475 * Of course this is the case for opponent resign as well.
476 * (ii) More importantly, the ownermap will get skewed since
477 * the UCT will start cutting off any playouts. */
478 if (u->pondering_opt && !is_pass(node_coord(best))) {
479 uct_pondering_start(u, b, u->t, stone_other(color));
481 return coord_copy(best_coord);
485 bool
486 uct_gentbook(struct engine *e, struct board *b, struct time_info *ti, enum stone color)
488 struct uct *u = e->data;
489 if (!u->t) uct_prepare_move(u, b, color);
490 assert(u->t);
492 if (ti->dim == TD_GAMES) {
493 /* Don't count in games that already went into the tbook. */
494 ti->len.games += u->t->root->u.playouts;
496 uct_search(u, b, ti, color, u->t, true);
498 assert(ti->dim == TD_GAMES);
499 tree_save(u->t, b, ti->len.games / 100);
501 return true;
504 void
505 uct_dumptbook(struct engine *e, struct board *b, enum stone color)
507 struct uct *u = e->data;
508 struct tree *t = tree_init(b, color, u->fast_alloc ? u->max_tree_size : 0,
509 u->max_pruned_size, u->pruning_threshold, u->local_tree_aging, 0);
510 tree_load(t, b);
511 tree_dump(t, 0);
512 tree_done(t);
516 floating_t
517 uct_evaluate_one(struct engine *e, struct board *b, struct time_info *ti, coord_t c, enum stone color)
519 struct uct *u = e->data;
521 struct board b2;
522 board_copy(&b2, b);
523 struct move m = { c, color };
524 int res = board_play(&b2, &m);
525 if (res < 0)
526 return NAN;
527 color = stone_other(color);
529 if (u->t) reset_state(u);
530 uct_prepare_move(u, &b2, color);
531 assert(u->t);
533 floating_t bestval;
534 uct_search(u, &b2, ti, color, u->t, true);
535 struct tree_node *best = u->policy->choose(u->policy, u->t->root, &b2, color, resign);
536 if (!best) {
537 bestval = NAN; // the opponent has no reply!
538 } else {
539 bestval = tree_node_get_value(u->t, 1, best->u.value);
542 reset_state(u); // clean our junk
544 return isnan(bestval) ? NAN : 1.0f - bestval;
547 void
548 uct_evaluate(struct engine *e, struct board *b, struct time_info *ti, floating_t *vals, enum stone color)
550 for (int i = 0; i < b->flen; i++) {
551 if (is_pass(b->f[i]))
552 vals[i] = NAN;
553 else
554 vals[i] = uct_evaluate_one(e, b, ti, b->f[i], color);
559 struct uct *
560 uct_state_init(char *arg, struct board *b)
562 struct uct *u = calloc2(1, sizeof(struct uct));
563 bool pat_setup = false;
565 u->debug_level = debug_level;
566 u->reportfreq = 10000;
567 u->gamelen = MC_GAMELEN;
568 u->resign_threshold = 0.2;
569 u->sure_win_threshold = 0.95;
570 u->mercymin = 0;
571 u->significant_threshold = 50;
572 u->expand_p = 8;
573 u->dumpthres = 1000;
574 u->playout_amaf = true;
575 u->amaf_prior = false;
576 u->max_tree_size = 1408ULL * 1048576;
577 u->fast_alloc = true;
578 u->pruning_threshold = 0;
580 u->threads = 1;
581 u->thread_model = TM_TREEVL;
582 u->virtual_loss = 1;
584 u->fuseki_end = 20; // max time at 361*20% = 72 moves (our 36th move, still 99 to play)
585 u->yose_start = 40; // (100-40-25)*361/100/2 = 63 moves still to play by us then
586 u->bestr_ratio = 0.02;
587 // 2.5 is clearly too much, but seems to compensate well for overly stern time allocations.
588 // TODO: Further tuning and experiments with better time allocation schemes.
589 u->best2_ratio = 2.5;
590 // Higher values of max_maintime_ratio sometimes cause severe time trouble in tournaments
591 // It might be necessary to reduce it to 1.5 on large board, but more tuning is needed.
592 u->max_maintime_ratio = 2.0;
594 u->val_scale = 0; u->val_points = 40;
595 u->dynkomi_interval = 1000;
596 u->dynkomi_mask = S_BLACK | S_WHITE;
598 u->tenuki_d = 4;
599 u->local_tree_aging = 80;
600 u->local_tree_depth_decay = 1.5;
601 u->local_tree_eval = LTE_ROOT;
602 u->local_tree_neival = true;
604 u->max_slaves = -1;
605 u->slave_index = -1;
606 u->stats_delay = 0.01; // 10 ms
607 u->shared_levels = 1;
609 u->plugins = pluginset_init(b);
611 u->jdict = joseki_load(b->size);
613 if (arg) {
614 char *optspec, *next = arg;
615 while (*next) {
616 optspec = next;
617 next += strcspn(next, ",");
618 if (*next) { *next++ = 0; } else { *next = 0; }
620 char *optname = optspec;
621 char *optval = strchr(optspec, '=');
622 if (optval) *optval++ = 0;
624 /** Basic options */
626 if (!strcasecmp(optname, "debug")) {
627 if (optval)
628 u->debug_level = atoi(optval);
629 else
630 u->debug_level++;
631 } else if (!strcasecmp(optname, "reporting") && optval) {
632 /* The format of output for detailed progress
633 * information (such as current best move and
634 * its value, etc.). */
635 if (!strcasecmp(optval, "text")) {
636 /* Plaintext traditional output. */
637 u->reporting = UR_TEXT;
638 } else if (!strcasecmp(optval, "json")) {
639 /* JSON output. Implies debug=0. */
640 u->reporting = UR_JSON;
641 u->debug_level = 0;
642 } else if (!strcasecmp(optval, "jsonbig")) {
643 /* JSON output, but much more detailed.
644 * Implies debug=0. */
645 u->reporting = UR_JSON_BIG;
646 u->debug_level = 0;
647 } else {
648 fprintf(stderr, "UCT: Invalid reporting format %s\n", optval);
649 exit(1);
651 } else if (!strcasecmp(optname, "reportfreq") && optval) {
652 /* The progress information line will be shown
653 * every <reportfreq> simulations. */
654 u->reportfreq = atoi(optval);
655 } else if (!strcasecmp(optname, "dumpthres") && optval) {
656 /* When dumping the UCT tree on output, include
657 * nodes with at least this many playouts.
658 * (This value is re-scaled "intelligently"
659 * in case of very large trees.) */
660 u->dumpthres = atoi(optval);
661 } else if (!strcasecmp(optname, "resign_threshold") && optval) {
662 /* Resign when this ratio of games is lost
663 * after GJ_MINGAMES sample is taken. */
664 u->resign_threshold = atof(optval);
665 } else if (!strcasecmp(optname, "sure_win_threshold") && optval) {
666 /* Stop reading when this ratio of games is won
667 * after PLAYOUT_EARLY_BREAK_MIN sample is
668 * taken. (Prevents stupid time losses,
669 * friendly to human opponents.) */
670 u->sure_win_threshold = atof(optval);
671 } else if (!strcasecmp(optname, "force_seed") && optval) {
672 /* Set RNG seed at the tree setup. */
673 u->force_seed = atoi(optval);
674 } else if (!strcasecmp(optname, "no_tbook")) {
675 /* Disable UCT opening tbook. */
676 u->no_tbook = true;
677 } else if (!strcasecmp(optname, "pass_all_alive")) {
678 /* Whether to consider passing only after all
679 * dead groups were removed from the board;
680 * this is like all genmoves are in fact
681 * kgs-genmove_cleanup. */
682 u->pass_all_alive = !optval || atoi(optval);
683 } else if (!strcasecmp(optname, "allow_losing_pass")) {
684 /* Whether to consider passing in a clear
685 * but losing situation, to be scored as a loss
686 * for us. */
687 u->allow_losing_pass = !optval || atoi(optval);
688 } else if (!strcasecmp(optname, "territory_scoring")) {
689 /* Use territory scoring (default is area scoring).
690 * An explicit kgs-rules command overrides this. */
691 u->territory_scoring = !optval || atoi(optval);
692 } else if (!strcasecmp(optname, "stones_only")) {
693 /* Do not count eyes. Nice to teach go to kids.
694 * http://strasbourg.jeudego.org/regle_strasbourgeoise.htm */
695 b->rules = RULES_STONES_ONLY;
696 u->pass_all_alive = true;
697 } else if (!strcasecmp(optname, "banner") && optval) {
698 /* Additional banner string. This must come as the
699 * last engine parameter. */
700 if (*next) *--next = ',';
701 u->banner = strdup(optval);
702 break;
703 } else if (!strcasecmp(optname, "plugin") && optval) {
704 /* Load an external plugin; filename goes before the colon,
705 * extra arguments after the colon. */
706 char *pluginarg = strchr(optval, ':');
707 if (pluginarg)
708 *pluginarg++ = 0;
709 plugin_load(u->plugins, optval, pluginarg);
711 /** UCT behavior and policies */
713 } else if ((!strcasecmp(optname, "policy")
714 /* Node selection policy. ucb1amaf is the
715 * default policy implementing RAVE, while
716 * ucb1 is the simple exploration/exploitation
717 * policy. Policies can take further extra
718 * options. */
719 || !strcasecmp(optname, "random_policy")) && optval) {
720 /* A policy to be used randomly with small
721 * chance instead of the default policy. */
722 char *policyarg = strchr(optval, ':');
723 struct uct_policy **p = !strcasecmp(optname, "policy") ? &u->policy : &u->random_policy;
724 if (policyarg)
725 *policyarg++ = 0;
726 if (!strcasecmp(optval, "ucb1")) {
727 *p = policy_ucb1_init(u, policyarg);
728 } else if (!strcasecmp(optval, "ucb1amaf")) {
729 *p = policy_ucb1amaf_init(u, policyarg, b);
730 } else {
731 fprintf(stderr, "UCT: Invalid tree policy %s\n", optval);
732 exit(1);
734 } else if (!strcasecmp(optname, "playout") && optval) {
735 /* Random simulation (playout) policy.
736 * moggy is the default policy with large
737 * amount of domain-specific knowledge and
738 * heuristics. light is a simple uniformly
739 * random move selection policy. */
740 char *playoutarg = strchr(optval, ':');
741 if (playoutarg)
742 *playoutarg++ = 0;
743 if (!strcasecmp(optval, "moggy")) {
744 u->playout = playout_moggy_init(playoutarg, b, u->jdict);
745 } else if (!strcasecmp(optval, "light")) {
746 u->playout = playout_light_init(playoutarg, b);
747 } else {
748 fprintf(stderr, "UCT: Invalid playout policy %s\n", optval);
749 exit(1);
751 } else if (!strcasecmp(optname, "prior") && optval) {
752 /* Node priors policy. When expanding a node,
753 * it will seed node values heuristically
754 * (most importantly, based on playout policy
755 * opinion, but also with regard to other
756 * things). See uct/prior.c for details.
757 * Use prior=eqex=0 to disable priors. */
758 u->prior = uct_prior_init(optval, b, u);
759 } else if (!strcasecmp(optname, "mercy") && optval) {
760 /* Minimal difference of black/white captures
761 * to stop playout - "Mercy Rule". Speeds up
762 * hopeless playouts at the expense of some
763 * accuracy. */
764 u->mercymin = atoi(optval);
765 } else if (!strcasecmp(optname, "gamelen") && optval) {
766 /* Maximum length of single simulation
767 * in moves. */
768 u->gamelen = atoi(optval);
769 } else if (!strcasecmp(optname, "expand_p") && optval) {
770 /* Expand UCT nodes after it has been
771 * visited this many times. */
772 u->expand_p = atoi(optval);
773 } else if (!strcasecmp(optname, "random_policy_chance") && optval) {
774 /* If specified (N), with probability 1/N, random_policy policy
775 * descend is used instead of main policy descend; useful
776 * if specified policy (e.g. UCB1AMAF) can make unduly biased
777 * choices sometimes, you can fall back to e.g.
778 * random_policy=UCB1. */
779 u->random_policy_chance = atoi(optval);
781 /** General AMAF behavior */
782 /* (Only relevant if the policy supports AMAF.
783 * More variables can be tuned as policy
784 * parameters.) */
786 } else if (!strcasecmp(optname, "playout_amaf")) {
787 /* Whether to include random playout moves in
788 * AMAF as well. (Otherwise, only tree moves
789 * are included in AMAF. Of course makes sense
790 * only in connection with an AMAF policy.) */
791 /* with-without: 55.5% (+-4.1) */
792 if (optval && *optval == '0')
793 u->playout_amaf = false;
794 else
795 u->playout_amaf = true;
796 } else if (!strcasecmp(optname, "playout_amaf_cutoff") && optval) {
797 /* Keep only first N% of playout stage AMAF
798 * information. */
799 u->playout_amaf_cutoff = atoi(optval);
800 } else if (!strcasecmp(optname, "amaf_prior") && optval) {
801 /* In node policy, consider prior values
802 * part of the real result term or part
803 * of the AMAF term? */
804 u->amaf_prior = atoi(optval);
806 /** Performance and memory management */
808 } else if (!strcasecmp(optname, "threads") && optval) {
809 /* By default, Pachi will run with only single
810 * tree search thread! */
811 u->threads = atoi(optval);
812 } else if (!strcasecmp(optname, "thread_model") && optval) {
813 if (!strcasecmp(optval, "tree")) {
814 /* Tree parallelization - all threads
815 * grind on the same tree. */
816 u->thread_model = TM_TREE;
817 u->virtual_loss = 0;
818 } else if (!strcasecmp(optval, "treevl")) {
819 /* Tree parallelization, but also
820 * with virtual losses - this discou-
821 * rages most threads choosing the
822 * same tree branches to read. */
823 u->thread_model = TM_TREEVL;
824 } else {
825 fprintf(stderr, "UCT: Invalid thread model %s\n", optval);
826 exit(1);
828 } else if (!strcasecmp(optname, "virtual_loss") && optval) {
829 /* Number of virtual losses added before evaluating a node. */
830 u->virtual_loss = atoi(optval);
831 } else if (!strcasecmp(optname, "pondering")) {
832 /* Keep searching even during opponent's turn. */
833 u->pondering_opt = !optval || atoi(optval);
834 } else if (!strcasecmp(optname, "max_tree_size") && optval) {
835 /* Maximum amount of memory [MiB] consumed by the move tree.
836 * For fast_alloc it includes the temp tree used for pruning.
837 * Default is 3072 (3 GiB). */
838 u->max_tree_size = atol(optval) * 1048576;
839 } else if (!strcasecmp(optname, "fast_alloc")) {
840 u->fast_alloc = !optval || atoi(optval);
841 } else if (!strcasecmp(optname, "pruning_threshold") && optval) {
842 /* Force pruning at beginning of a move if the tree consumes
843 * more than this [MiB]. Default is 10% of max_tree_size.
844 * Increase to reduce pruning time overhead if memory is plentiful.
845 * This option is meaningful only for fast_alloc. */
846 u->pruning_threshold = atol(optval) * 1048576;
848 /** Time control */
850 } else if (!strcasecmp(optname, "best2_ratio") && optval) {
851 /* If set, prolong simulating while
852 * first_best/second_best playouts ratio
853 * is less than best2_ratio. */
854 u->best2_ratio = atof(optval);
855 } else if (!strcasecmp(optname, "bestr_ratio") && optval) {
856 /* If set, prolong simulating while
857 * best,best_best_child values delta
858 * is more than bestr_ratio. */
859 u->bestr_ratio = atof(optval);
860 } else if (!strcasecmp(optname, "max_maintime_ratio") && optval) {
861 /* If set and while not in byoyomi, prolong simulating no more than
862 * max_maintime_ratio times the normal desired thinking time. */
863 u->max_maintime_ratio = atof(optval);
864 } else if (!strcasecmp(optname, "fuseki_end") && optval) {
865 /* At the very beginning it's not worth thinking
866 * too long because the playout evaluations are
867 * very noisy. So gradually increase the thinking
868 * time up to maximum when fuseki_end percent
869 * of the board has been played.
870 * This only applies if we are not in byoyomi. */
871 u->fuseki_end = atoi(optval);
872 } else if (!strcasecmp(optname, "yose_start") && optval) {
873 /* When yose_start percent of the board has been
874 * played, or if we are in byoyomi, stop spending
875 * more time and spread the remaining time
876 * uniformly.
877 * Between fuseki_end and yose_start, we spend
878 * a constant proportion of the remaining time
879 * on each move. (yose_start should actually
880 * be much earlier than when real yose start,
881 * but "yose" is a good short name to convey
882 * the idea.) */
883 u->yose_start = atoi(optval);
885 /** Dynamic komi */
887 } else if (!strcasecmp(optname, "dynkomi") && optval) {
888 /* Dynamic komi approach; there are multiple
889 * ways to adjust komi dynamically throughout
890 * play. We currently support two: */
891 char *dynkomiarg = strchr(optval, ':');
892 if (dynkomiarg)
893 *dynkomiarg++ = 0;
894 if (!strcasecmp(optval, "none")) {
895 u->dynkomi = uct_dynkomi_init_none(u, dynkomiarg, b);
896 } else if (!strcasecmp(optval, "linear")) {
897 /* You should set dynkomi_mask=1 or a very low
898 * handicap_value for white. */
899 u->dynkomi = uct_dynkomi_init_linear(u, dynkomiarg, b);
900 } else if (!strcasecmp(optval, "adaptive")) {
901 /* There are many more knobs to
902 * crank - see uct/dynkomi.c. */
903 u->dynkomi = uct_dynkomi_init_adaptive(u, dynkomiarg, b);
904 } else {
905 fprintf(stderr, "UCT: Invalid dynkomi mode %s\n", optval);
906 exit(1);
908 } else if (!strcasecmp(optname, "dynkomi_mask") && optval) {
909 /* Bitmask of colors the player must be
910 * for dynkomi be applied; the default dynkomi_mask=3 allows
911 * dynkomi even in games where Pachi is white. */
912 u->dynkomi_mask = atoi(optval);
913 } else if (!strcasecmp(optname, "dynkomi_interval") && optval) {
914 /* If non-zero, re-adjust dynamic komi
915 * throughout a single genmove reading,
916 * roughly every N simulations. */
917 /* XXX: Does not work with tree
918 * parallelization. */
919 u->dynkomi_interval = atoi(optval);
920 } else if (!strcasecmp(optname, "extra_komi") && optval) {
921 /* Initial dynamic komi settings. This
922 * is useful for the adaptive dynkomi
923 * policy as the value to start with
924 * (this is NOT kept fixed) in case
925 * there is not enough time in the search
926 * to adjust the value properly (e.g. the
927 * game was interrupted). */
928 u->initial_extra_komi = atof(optval);
930 /** Node value result scaling */
932 } else if (!strcasecmp(optname, "val_scale") && optval) {
933 /* How much of the game result value should be
934 * influenced by win size. Zero means it isn't. */
935 u->val_scale = atof(optval);
936 } else if (!strcasecmp(optname, "val_points") && optval) {
937 /* Maximum size of win to be scaled into game
938 * result value. Zero means boardsize^2. */
939 u->val_points = atoi(optval) * 2; // result values are doubled
940 } else if (!strcasecmp(optname, "val_extra")) {
941 /* If false, the score coefficient will be simply
942 * added to the value, instead of scaling the result
943 * coefficient because of it. */
944 u->val_extra = !optval || atoi(optval);
945 } else if (!strcasecmp(optname, "val_byavg")) {
946 /* If true, the score included in the value will
947 * be relative to average score in the current
948 * search episode inst. of jigo. */
949 u->val_byavg = !optval || atoi(optval);
950 } else if (!strcasecmp(optname, "val_bytemp")) {
951 /* If true, the value scaling coefficient
952 * is different based on value extremity
953 * (dist. from 0.5), linear between
954 * val_bytemp_min, val_scale. */
955 u->val_bytemp = !optval || atoi(optval);
956 } else if (!strcasecmp(optname, "val_bytemp_min") && optval) {
957 /* Minimum val_scale in case of val_bytemp. */
958 u->val_bytemp_min = atof(optval);
960 /** Local trees */
961 /* (Purely experimental. Does not work - yet!) */
963 } else if (!strcasecmp(optname, "local_tree")) {
964 /* Whether to bias exploration by local tree values. */
965 u->local_tree = !optval || atoi(optval);
966 } else if (!strcasecmp(optname, "tenuki_d") && optval) {
967 /* Tenuki distance at which to break the local tree. */
968 u->tenuki_d = atoi(optval);
969 if (u->tenuki_d > TREE_NODE_D_MAX + 1) {
970 fprintf(stderr, "uct: tenuki_d must not be larger than TREE_NODE_D_MAX+1 %d\n", TREE_NODE_D_MAX + 1);
971 exit(1);
973 } else if (!strcasecmp(optname, "local_tree_aging") && optval) {
974 /* How much to reduce local tree values between moves. */
975 u->local_tree_aging = atof(optval);
976 } else if (!strcasecmp(optname, "local_tree_depth_decay") && optval) {
977 /* With value x>0, during the descent the node
978 * contributes 1/x^depth playouts in
979 * the local tree. I.e., with x>1, nodes more
980 * distant from local situation contribute more
981 * than nodes near the root. */
982 u->local_tree_depth_decay = atof(optval);
983 } else if (!strcasecmp(optname, "local_tree_allseq")) {
984 /* If disabled, only complete sequences are stored
985 * in the local tree. If this is on, also
986 * subsequences starting at each move are stored. */
987 u->local_tree_allseq = !optval || atoi(optval);
988 } else if (!strcasecmp(optname, "local_tree_neival")) {
989 /* If disabled, local node value is not
990 * computed just based on terminal status
991 * of the coordinate, but also its neighbors. */
992 u->local_tree_neival = !optval || atoi(optval);
993 } else if (!strcasecmp(optname, "local_tree_eval")) {
994 /* How is the value inserted in the local tree
995 * determined. */
996 if (!strcasecmp(optval, "root"))
997 /* All moves within a tree branch are
998 * considered wrt. their merit
999 * reaching tachtical goal of making
1000 * the first move in the branch
1001 * survive. */
1002 u->local_tree_eval = LTE_ROOT;
1003 else if (!strcasecmp(optval, "each"))
1004 /* Each move is considered wrt.
1005 * its own survival. */
1006 u->local_tree_eval = LTE_EACH;
1007 else if (!strcasecmp(optval, "total"))
1008 /* The tactical goal is the survival
1009 * of all the moves of my color and
1010 * non-survival of all the opponent
1011 * moves. Local values (and their
1012 * inverses) are averaged. */
1013 u->local_tree_eval = LTE_TOTAL;
1014 else {
1015 fprintf(stderr, "uct: unknown local_tree_eval %s\n", optval);
1016 exit(1);
1018 } else if (!strcasecmp(optname, "local_tree_rootchoose")) {
1019 /* If disabled, only moves within the local
1020 * tree branch are considered; the values
1021 * of the branch roots (i.e. root children)
1022 * are ignored. This may make sense together
1023 * with eval!=each, we consider only moves
1024 * that influence the goal, not the "rating"
1025 * of the goal itself. (The real solution
1026 * will be probably using criticality to pick
1027 * local tree branches.) */
1028 u->local_tree_rootchoose = !optval || atoi(optval);
1030 /** Other heuristics */
1031 } else if (!strcasecmp(optname, "patterns")) {
1032 /* Load pattern database. Various modules
1033 * (priors, policies etc.) may make use
1034 * of this database. They will request
1035 * it automatically in that case, but you
1036 * can use this option to tweak the pattern
1037 * parameters. */
1038 patterns_init(&u->pat, optval, false, true);
1039 u->want_pat = pat_setup = true;
1040 } else if (!strcasecmp(optname, "significant_threshold") && optval) {
1041 /* Some heuristics (XXX: none in mainline) rely
1042 * on the knowledge of the last "significant"
1043 * node in the descent. Such a node is
1044 * considered reasonably trustworthy to carry
1045 * some meaningful information in the values
1046 * of the node and its children. */
1047 u->significant_threshold = atoi(optval);
1049 /** Distributed engine slaves setup */
1051 } else if (!strcasecmp(optname, "slave")) {
1052 /* Act as slave for the distributed engine. */
1053 u->slave = !optval || atoi(optval);
1054 } else if (!strcasecmp(optname, "slave_index") && optval) {
1055 /* Optional index if per-slave behavior is desired.
1056 * Must be given as index/max */
1057 u->slave_index = atoi(optval);
1058 char *p = strchr(optval, '/');
1059 if (p) u->max_slaves = atoi(++p);
1060 } else if (!strcasecmp(optname, "shared_nodes") && optval) {
1061 /* Share at most shared_nodes between master and slave at each genmoves.
1062 * Must use the same value in master and slaves. */
1063 u->shared_nodes = atoi(optval);
1064 } else if (!strcasecmp(optname, "shared_levels") && optval) {
1065 /* Share only nodes of level <= shared_levels. */
1066 u->shared_levels = atoi(optval);
1067 } else if (!strcasecmp(optname, "stats_hbits") && optval) {
1068 /* Set hash table size to 2^stats_hbits for the shared stats. */
1069 u->stats_hbits = atoi(optval);
1070 } else if (!strcasecmp(optname, "stats_delay") && optval) {
1071 /* How long to wait in slave for initial stats to build up before
1072 * replying to the genmoves command (in ms) */
1073 u->stats_delay = 0.001 * atof(optval);
1075 /** Presets */
1077 } else if (!strcasecmp(optname, "maximize_score")) {
1078 /* A combination of settings that will make
1079 * Pachi try to maximize his points (instead
1080 * of playing slack yose) or minimize his loss
1081 * (and proceed to counting even when losing). */
1082 /* Please note that this preset might be
1083 * somewhat weaker than normal Pachi, and the
1084 * score maximization is approximate; point size
1085 * of win/loss still should not be used to judge
1086 * strength of Pachi or the opponent. */
1087 /* See README for some further notes. */
1088 if (!optval || atoi(optval)) {
1089 /* Allow scoring a lost game. */
1090 u->allow_losing_pass = true;
1091 /* Make Pachi keep his calm when losing
1092 * and/or maintain winning marging. */
1093 /* Do not play games that are losing
1094 * by too much. */
1095 /* XXX: komi_ratchet_age=40000 is necessary
1096 * with losing_komi_ratchet, but 40000
1097 * is somewhat arbitrary value. */
1098 char dynkomi_args[] = "losing_komi_ratchet:komi_ratchet_age=60000:no_komi_at_game_end=0:max_losing_komi=30";
1099 u->dynkomi = uct_dynkomi_init_adaptive(u, dynkomi_args, b);
1100 /* XXX: Values arbitrary so far. */
1101 /* XXX: Also, is bytemp sensible when
1102 * combined with dynamic komi?! */
1103 u->val_scale = 0.01;
1104 u->val_bytemp = true;
1105 u->val_bytemp_min = 0.001;
1106 u->val_byavg = true;
1109 } else {
1110 fprintf(stderr, "uct: Invalid engine argument %s or missing value\n", optname);
1111 exit(1);
1116 if (!u->policy)
1117 u->policy = policy_ucb1amaf_init(u, NULL, b);
1119 if (!!u->random_policy_chance ^ !!u->random_policy) {
1120 fprintf(stderr, "uct: Only one of random_policy and random_policy_chance is set\n");
1121 exit(1);
1124 if (!u->local_tree) {
1125 /* No ltree aging. */
1126 u->local_tree_aging = 1.0f;
1129 if (u->fast_alloc) {
1130 if (u->pruning_threshold < u->max_tree_size / 10)
1131 u->pruning_threshold = u->max_tree_size / 10;
1132 if (u->pruning_threshold > u->max_tree_size / 2)
1133 u->pruning_threshold = u->max_tree_size / 2;
1135 /* Limit pruning temp space to 20% of memory. Beyond this we discard
1136 * the nodes and recompute them at the next move if necessary. */
1137 u->max_pruned_size = u->max_tree_size / 5;
1138 u->max_tree_size -= u->max_pruned_size;
1139 } else {
1140 /* Reserve 5% memory in case the background free() are slower
1141 * than the concurrent allocations. */
1142 u->max_tree_size -= u->max_tree_size / 20;
1145 if (!u->prior)
1146 u->prior = uct_prior_init(NULL, b, u);
1148 if (!u->playout)
1149 u->playout = playout_moggy_init(NULL, b, u->jdict);
1150 if (!u->playout->debug_level)
1151 u->playout->debug_level = u->debug_level;
1153 if (u->want_pat && !pat_setup)
1154 patterns_init(&u->pat, NULL, false, true);
1156 u->ownermap.map = malloc2(board_size2(b) * sizeof(u->ownermap.map[0]));
1158 if (u->slave) {
1159 if (!u->stats_hbits) u->stats_hbits = DEFAULT_STATS_HBITS;
1160 if (!u->shared_nodes) u->shared_nodes = DEFAULT_SHARED_NODES;
1161 assert(u->shared_levels * board_bits2(b) <= 8 * (int)sizeof(path_t));
1164 if (!u->dynkomi)
1165 u->dynkomi = board_small(b) ? uct_dynkomi_init_none(u, NULL, b)
1166 : uct_dynkomi_init_linear(u, NULL, b);
1168 /* Some things remain uninitialized for now - the opening tbook
1169 * is not loaded and the tree not set up. */
1170 /* This will be initialized in setup_state() at the first move
1171 * received/requested. This is because right now we are not aware
1172 * about any komi or handicap setup and such. */
1174 return u;
1177 struct engine *
1178 engine_uct_init(char *arg, struct board *b)
1180 struct uct *u = uct_state_init(arg, b);
1181 struct engine *e = calloc2(1, sizeof(struct engine));
1182 e->name = "UCT";
1183 e->printhook = uct_printhook_ownermap;
1184 e->notify_play = uct_notify_play;
1185 e->chat = uct_chat;
1186 e->undo = uct_undo;
1187 e->result = uct_result;
1188 e->genmove = uct_genmove;
1189 e->genmoves = uct_genmoves;
1190 e->evaluate = uct_evaluate;
1191 e->dead_group_list = uct_dead_group_list;
1192 e->done = uct_done;
1193 e->data = u;
1194 if (u->slave)
1195 e->notify = uct_notify;
1197 const char banner[] = "If you believe you have won but I am still playing, "
1198 "please help me understand by capturing all dead stones. "
1199 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
1200 if (!u->banner) u->banner = "";
1201 e->comment = malloc2(sizeof(banner) + strlen(u->banner) + 1);
1202 sprintf(e->comment, "%s %s", banner, u->banner);
1204 return e;