UCT pondering: Enable by default
[pachi/nmclean.git] / uct / uct.c
blob8db9ff94206232e7206566eb802f1abe66ceab60
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->pondering_opt = true;
586 u->fuseki_end = 20; // max time at 361*20% = 72 moves (our 36th move, still 99 to play)
587 u->yose_start = 40; // (100-40-25)*361/100/2 = 63 moves still to play by us then
588 u->bestr_ratio = 0.02;
589 // 2.5 is clearly too much, but seems to compensate well for overly stern time allocations.
590 // TODO: Further tuning and experiments with better time allocation schemes.
591 u->best2_ratio = 2.5;
592 // Higher values of max_maintime_ratio sometimes cause severe time trouble in tournaments
593 // It might be necessary to reduce it to 1.5 on large board, but more tuning is needed.
594 u->max_maintime_ratio = 2.0;
596 u->val_scale = 0; u->val_points = 40;
597 u->dynkomi_interval = 1000;
598 u->dynkomi_mask = S_BLACK | S_WHITE;
600 u->tenuki_d = 4;
601 u->local_tree_aging = 80;
602 u->local_tree_depth_decay = 1.5;
603 u->local_tree_eval = LTE_ROOT;
604 u->local_tree_neival = true;
606 u->max_slaves = -1;
607 u->slave_index = -1;
608 u->stats_delay = 0.01; // 10 ms
609 u->shared_levels = 1;
611 u->plugins = pluginset_init(b);
613 u->jdict = joseki_load(b->size);
615 if (arg) {
616 char *optspec, *next = arg;
617 while (*next) {
618 optspec = next;
619 next += strcspn(next, ",");
620 if (*next) { *next++ = 0; } else { *next = 0; }
622 char *optname = optspec;
623 char *optval = strchr(optspec, '=');
624 if (optval) *optval++ = 0;
626 /** Basic options */
628 if (!strcasecmp(optname, "debug")) {
629 if (optval)
630 u->debug_level = atoi(optval);
631 else
632 u->debug_level++;
633 } else if (!strcasecmp(optname, "reporting") && optval) {
634 /* The format of output for detailed progress
635 * information (such as current best move and
636 * its value, etc.). */
637 if (!strcasecmp(optval, "text")) {
638 /* Plaintext traditional output. */
639 u->reporting = UR_TEXT;
640 } else if (!strcasecmp(optval, "json")) {
641 /* JSON output. Implies debug=0. */
642 u->reporting = UR_JSON;
643 u->debug_level = 0;
644 } else if (!strcasecmp(optval, "jsonbig")) {
645 /* JSON output, but much more detailed.
646 * Implies debug=0. */
647 u->reporting = UR_JSON_BIG;
648 u->debug_level = 0;
649 } else {
650 fprintf(stderr, "UCT: Invalid reporting format %s\n", optval);
651 exit(1);
653 } else if (!strcasecmp(optname, "reportfreq") && optval) {
654 /* The progress information line will be shown
655 * every <reportfreq> simulations. */
656 u->reportfreq = atoi(optval);
657 } else if (!strcasecmp(optname, "dumpthres") && optval) {
658 /* When dumping the UCT tree on output, include
659 * nodes with at least this many playouts.
660 * (This value is re-scaled "intelligently"
661 * in case of very large trees.) */
662 u->dumpthres = atoi(optval);
663 } else if (!strcasecmp(optname, "resign_threshold") && optval) {
664 /* Resign when this ratio of games is lost
665 * after GJ_MINGAMES sample is taken. */
666 u->resign_threshold = atof(optval);
667 } else if (!strcasecmp(optname, "sure_win_threshold") && optval) {
668 /* Stop reading when this ratio of games is won
669 * after PLAYOUT_EARLY_BREAK_MIN sample is
670 * taken. (Prevents stupid time losses,
671 * friendly to human opponents.) */
672 u->sure_win_threshold = atof(optval);
673 } else if (!strcasecmp(optname, "force_seed") && optval) {
674 /* Set RNG seed at the tree setup. */
675 u->force_seed = atoi(optval);
676 } else if (!strcasecmp(optname, "no_tbook")) {
677 /* Disable UCT opening tbook. */
678 u->no_tbook = true;
679 } else if (!strcasecmp(optname, "pass_all_alive")) {
680 /* Whether to consider passing only after all
681 * dead groups were removed from the board;
682 * this is like all genmoves are in fact
683 * kgs-genmove_cleanup. */
684 u->pass_all_alive = !optval || atoi(optval);
685 } else if (!strcasecmp(optname, "allow_losing_pass")) {
686 /* Whether to consider passing in a clear
687 * but losing situation, to be scored as a loss
688 * for us. */
689 u->allow_losing_pass = !optval || atoi(optval);
690 } else if (!strcasecmp(optname, "territory_scoring")) {
691 /* Use territory scoring (default is area scoring).
692 * An explicit kgs-rules command overrides this. */
693 u->territory_scoring = !optval || atoi(optval);
694 } else if (!strcasecmp(optname, "stones_only")) {
695 /* Do not count eyes. Nice to teach go to kids.
696 * http://strasbourg.jeudego.org/regle_strasbourgeoise.htm */
697 b->rules = RULES_STONES_ONLY;
698 u->pass_all_alive = true;
699 } else if (!strcasecmp(optname, "banner") && optval) {
700 /* Additional banner string. This must come as the
701 * last engine parameter. */
702 if (*next) *--next = ',';
703 u->banner = strdup(optval);
704 break;
705 } else if (!strcasecmp(optname, "plugin") && optval) {
706 /* Load an external plugin; filename goes before the colon,
707 * extra arguments after the colon. */
708 char *pluginarg = strchr(optval, ':');
709 if (pluginarg)
710 *pluginarg++ = 0;
711 plugin_load(u->plugins, optval, pluginarg);
713 /** UCT behavior and policies */
715 } else if ((!strcasecmp(optname, "policy")
716 /* Node selection policy. ucb1amaf is the
717 * default policy implementing RAVE, while
718 * ucb1 is the simple exploration/exploitation
719 * policy. Policies can take further extra
720 * options. */
721 || !strcasecmp(optname, "random_policy")) && optval) {
722 /* A policy to be used randomly with small
723 * chance instead of the default policy. */
724 char *policyarg = strchr(optval, ':');
725 struct uct_policy **p = !strcasecmp(optname, "policy") ? &u->policy : &u->random_policy;
726 if (policyarg)
727 *policyarg++ = 0;
728 if (!strcasecmp(optval, "ucb1")) {
729 *p = policy_ucb1_init(u, policyarg);
730 } else if (!strcasecmp(optval, "ucb1amaf")) {
731 *p = policy_ucb1amaf_init(u, policyarg, b);
732 } else {
733 fprintf(stderr, "UCT: Invalid tree policy %s\n", optval);
734 exit(1);
736 } else if (!strcasecmp(optname, "playout") && optval) {
737 /* Random simulation (playout) policy.
738 * moggy is the default policy with large
739 * amount of domain-specific knowledge and
740 * heuristics. light is a simple uniformly
741 * random move selection policy. */
742 char *playoutarg = strchr(optval, ':');
743 if (playoutarg)
744 *playoutarg++ = 0;
745 if (!strcasecmp(optval, "moggy")) {
746 u->playout = playout_moggy_init(playoutarg, b, u->jdict);
747 } else if (!strcasecmp(optval, "light")) {
748 u->playout = playout_light_init(playoutarg, b);
749 } else {
750 fprintf(stderr, "UCT: Invalid playout policy %s\n", optval);
751 exit(1);
753 } else if (!strcasecmp(optname, "prior") && optval) {
754 /* Node priors policy. When expanding a node,
755 * it will seed node values heuristically
756 * (most importantly, based on playout policy
757 * opinion, but also with regard to other
758 * things). See uct/prior.c for details.
759 * Use prior=eqex=0 to disable priors. */
760 u->prior = uct_prior_init(optval, b, u);
761 } else if (!strcasecmp(optname, "mercy") && optval) {
762 /* Minimal difference of black/white captures
763 * to stop playout - "Mercy Rule". Speeds up
764 * hopeless playouts at the expense of some
765 * accuracy. */
766 u->mercymin = atoi(optval);
767 } else if (!strcasecmp(optname, "gamelen") && optval) {
768 /* Maximum length of single simulation
769 * in moves. */
770 u->gamelen = atoi(optval);
771 } else if (!strcasecmp(optname, "expand_p") && optval) {
772 /* Expand UCT nodes after it has been
773 * visited this many times. */
774 u->expand_p = atoi(optval);
775 } else if (!strcasecmp(optname, "random_policy_chance") && optval) {
776 /* If specified (N), with probability 1/N, random_policy policy
777 * descend is used instead of main policy descend; useful
778 * if specified policy (e.g. UCB1AMAF) can make unduly biased
779 * choices sometimes, you can fall back to e.g.
780 * random_policy=UCB1. */
781 u->random_policy_chance = atoi(optval);
783 /** General AMAF behavior */
784 /* (Only relevant if the policy supports AMAF.
785 * More variables can be tuned as policy
786 * parameters.) */
788 } else if (!strcasecmp(optname, "playout_amaf")) {
789 /* Whether to include random playout moves in
790 * AMAF as well. (Otherwise, only tree moves
791 * are included in AMAF. Of course makes sense
792 * only in connection with an AMAF policy.) */
793 /* with-without: 55.5% (+-4.1) */
794 if (optval && *optval == '0')
795 u->playout_amaf = false;
796 else
797 u->playout_amaf = true;
798 } else if (!strcasecmp(optname, "playout_amaf_cutoff") && optval) {
799 /* Keep only first N% of playout stage AMAF
800 * information. */
801 u->playout_amaf_cutoff = atoi(optval);
802 } else if (!strcasecmp(optname, "amaf_prior") && optval) {
803 /* In node policy, consider prior values
804 * part of the real result term or part
805 * of the AMAF term? */
806 u->amaf_prior = atoi(optval);
808 /** Performance and memory management */
810 } else if (!strcasecmp(optname, "threads") && optval) {
811 /* By default, Pachi will run with only single
812 * tree search thread! */
813 u->threads = atoi(optval);
814 } else if (!strcasecmp(optname, "thread_model") && optval) {
815 if (!strcasecmp(optval, "tree")) {
816 /* Tree parallelization - all threads
817 * grind on the same tree. */
818 u->thread_model = TM_TREE;
819 u->virtual_loss = 0;
820 } else if (!strcasecmp(optval, "treevl")) {
821 /* Tree parallelization, but also
822 * with virtual losses - this discou-
823 * rages most threads choosing the
824 * same tree branches to read. */
825 u->thread_model = TM_TREEVL;
826 } else {
827 fprintf(stderr, "UCT: Invalid thread model %s\n", optval);
828 exit(1);
830 } else if (!strcasecmp(optname, "virtual_loss") && optval) {
831 /* Number of virtual losses added before evaluating a node. */
832 u->virtual_loss = atoi(optval);
833 } else if (!strcasecmp(optname, "pondering")) {
834 /* Keep searching even during opponent's turn. */
835 u->pondering_opt = !optval || atoi(optval);
836 } else if (!strcasecmp(optname, "max_tree_size") && optval) {
837 /* Maximum amount of memory [MiB] consumed by the move tree.
838 * For fast_alloc it includes the temp tree used for pruning.
839 * Default is 3072 (3 GiB). */
840 u->max_tree_size = atol(optval) * 1048576;
841 } else if (!strcasecmp(optname, "fast_alloc")) {
842 u->fast_alloc = !optval || atoi(optval);
843 } else if (!strcasecmp(optname, "pruning_threshold") && optval) {
844 /* Force pruning at beginning of a move if the tree consumes
845 * more than this [MiB]. Default is 10% of max_tree_size.
846 * Increase to reduce pruning time overhead if memory is plentiful.
847 * This option is meaningful only for fast_alloc. */
848 u->pruning_threshold = atol(optval) * 1048576;
850 /** Time control */
852 } else if (!strcasecmp(optname, "best2_ratio") && optval) {
853 /* If set, prolong simulating while
854 * first_best/second_best playouts ratio
855 * is less than best2_ratio. */
856 u->best2_ratio = atof(optval);
857 } else if (!strcasecmp(optname, "bestr_ratio") && optval) {
858 /* If set, prolong simulating while
859 * best,best_best_child values delta
860 * is more than bestr_ratio. */
861 u->bestr_ratio = atof(optval);
862 } else if (!strcasecmp(optname, "max_maintime_ratio") && optval) {
863 /* If set and while not in byoyomi, prolong simulating no more than
864 * max_maintime_ratio times the normal desired thinking time. */
865 u->max_maintime_ratio = atof(optval);
866 } else if (!strcasecmp(optname, "fuseki_end") && optval) {
867 /* At the very beginning it's not worth thinking
868 * too long because the playout evaluations are
869 * very noisy. So gradually increase the thinking
870 * time up to maximum when fuseki_end percent
871 * of the board has been played.
872 * This only applies if we are not in byoyomi. */
873 u->fuseki_end = atoi(optval);
874 } else if (!strcasecmp(optname, "yose_start") && optval) {
875 /* When yose_start percent of the board has been
876 * played, or if we are in byoyomi, stop spending
877 * more time and spread the remaining time
878 * uniformly.
879 * Between fuseki_end and yose_start, we spend
880 * a constant proportion of the remaining time
881 * on each move. (yose_start should actually
882 * be much earlier than when real yose start,
883 * but "yose" is a good short name to convey
884 * the idea.) */
885 u->yose_start = atoi(optval);
887 /** Dynamic komi */
889 } else if (!strcasecmp(optname, "dynkomi") && optval) {
890 /* Dynamic komi approach; there are multiple
891 * ways to adjust komi dynamically throughout
892 * play. We currently support two: */
893 char *dynkomiarg = strchr(optval, ':');
894 if (dynkomiarg)
895 *dynkomiarg++ = 0;
896 if (!strcasecmp(optval, "none")) {
897 u->dynkomi = uct_dynkomi_init_none(u, dynkomiarg, b);
898 } else if (!strcasecmp(optval, "linear")) {
899 /* You should set dynkomi_mask=1 or a very low
900 * handicap_value for white. */
901 u->dynkomi = uct_dynkomi_init_linear(u, dynkomiarg, b);
902 } else if (!strcasecmp(optval, "adaptive")) {
903 /* There are many more knobs to
904 * crank - see uct/dynkomi.c. */
905 u->dynkomi = uct_dynkomi_init_adaptive(u, dynkomiarg, b);
906 } else {
907 fprintf(stderr, "UCT: Invalid dynkomi mode %s\n", optval);
908 exit(1);
910 } else if (!strcasecmp(optname, "dynkomi_mask") && optval) {
911 /* Bitmask of colors the player must be
912 * for dynkomi be applied; the default dynkomi_mask=3 allows
913 * dynkomi even in games where Pachi is white. */
914 u->dynkomi_mask = atoi(optval);
915 } else if (!strcasecmp(optname, "dynkomi_interval") && optval) {
916 /* If non-zero, re-adjust dynamic komi
917 * throughout a single genmove reading,
918 * roughly every N simulations. */
919 /* XXX: Does not work with tree
920 * parallelization. */
921 u->dynkomi_interval = atoi(optval);
922 } else if (!strcasecmp(optname, "extra_komi") && optval) {
923 /* Initial dynamic komi settings. This
924 * is useful for the adaptive dynkomi
925 * policy as the value to start with
926 * (this is NOT kept fixed) in case
927 * there is not enough time in the search
928 * to adjust the value properly (e.g. the
929 * game was interrupted). */
930 u->initial_extra_komi = atof(optval);
932 /** Node value result scaling */
934 } else if (!strcasecmp(optname, "val_scale") && optval) {
935 /* How much of the game result value should be
936 * influenced by win size. Zero means it isn't. */
937 u->val_scale = atof(optval);
938 } else if (!strcasecmp(optname, "val_points") && optval) {
939 /* Maximum size of win to be scaled into game
940 * result value. Zero means boardsize^2. */
941 u->val_points = atoi(optval) * 2; // result values are doubled
942 } else if (!strcasecmp(optname, "val_extra")) {
943 /* If false, the score coefficient will be simply
944 * added to the value, instead of scaling the result
945 * coefficient because of it. */
946 u->val_extra = !optval || atoi(optval);
947 } else if (!strcasecmp(optname, "val_byavg")) {
948 /* If true, the score included in the value will
949 * be relative to average score in the current
950 * search episode inst. of jigo. */
951 u->val_byavg = !optval || atoi(optval);
952 } else if (!strcasecmp(optname, "val_bytemp")) {
953 /* If true, the value scaling coefficient
954 * is different based on value extremity
955 * (dist. from 0.5), linear between
956 * val_bytemp_min, val_scale. */
957 u->val_bytemp = !optval || atoi(optval);
958 } else if (!strcasecmp(optname, "val_bytemp_min") && optval) {
959 /* Minimum val_scale in case of val_bytemp. */
960 u->val_bytemp_min = atof(optval);
962 /** Local trees */
963 /* (Purely experimental. Does not work - yet!) */
965 } else if (!strcasecmp(optname, "local_tree")) {
966 /* Whether to bias exploration by local tree values. */
967 u->local_tree = !optval || atoi(optval);
968 } else if (!strcasecmp(optname, "tenuki_d") && optval) {
969 /* Tenuki distance at which to break the local tree. */
970 u->tenuki_d = atoi(optval);
971 if (u->tenuki_d > TREE_NODE_D_MAX + 1) {
972 fprintf(stderr, "uct: tenuki_d must not be larger than TREE_NODE_D_MAX+1 %d\n", TREE_NODE_D_MAX + 1);
973 exit(1);
975 } else if (!strcasecmp(optname, "local_tree_aging") && optval) {
976 /* How much to reduce local tree values between moves. */
977 u->local_tree_aging = atof(optval);
978 } else if (!strcasecmp(optname, "local_tree_depth_decay") && optval) {
979 /* With value x>0, during the descent the node
980 * contributes 1/x^depth playouts in
981 * the local tree. I.e., with x>1, nodes more
982 * distant from local situation contribute more
983 * than nodes near the root. */
984 u->local_tree_depth_decay = atof(optval);
985 } else if (!strcasecmp(optname, "local_tree_allseq")) {
986 /* If disabled, only complete sequences are stored
987 * in the local tree. If this is on, also
988 * subsequences starting at each move are stored. */
989 u->local_tree_allseq = !optval || atoi(optval);
990 } else if (!strcasecmp(optname, "local_tree_neival")) {
991 /* If disabled, local node value is not
992 * computed just based on terminal status
993 * of the coordinate, but also its neighbors. */
994 u->local_tree_neival = !optval || atoi(optval);
995 } else if (!strcasecmp(optname, "local_tree_eval")) {
996 /* How is the value inserted in the local tree
997 * determined. */
998 if (!strcasecmp(optval, "root"))
999 /* All moves within a tree branch are
1000 * considered wrt. their merit
1001 * reaching tachtical goal of making
1002 * the first move in the branch
1003 * survive. */
1004 u->local_tree_eval = LTE_ROOT;
1005 else if (!strcasecmp(optval, "each"))
1006 /* Each move is considered wrt.
1007 * its own survival. */
1008 u->local_tree_eval = LTE_EACH;
1009 else if (!strcasecmp(optval, "total"))
1010 /* The tactical goal is the survival
1011 * of all the moves of my color and
1012 * non-survival of all the opponent
1013 * moves. Local values (and their
1014 * inverses) are averaged. */
1015 u->local_tree_eval = LTE_TOTAL;
1016 else {
1017 fprintf(stderr, "uct: unknown local_tree_eval %s\n", optval);
1018 exit(1);
1020 } else if (!strcasecmp(optname, "local_tree_rootchoose")) {
1021 /* If disabled, only moves within the local
1022 * tree branch are considered; the values
1023 * of the branch roots (i.e. root children)
1024 * are ignored. This may make sense together
1025 * with eval!=each, we consider only moves
1026 * that influence the goal, not the "rating"
1027 * of the goal itself. (The real solution
1028 * will be probably using criticality to pick
1029 * local tree branches.) */
1030 u->local_tree_rootchoose = !optval || atoi(optval);
1032 /** Other heuristics */
1033 } else if (!strcasecmp(optname, "patterns")) {
1034 /* Load pattern database. Various modules
1035 * (priors, policies etc.) may make use
1036 * of this database. They will request
1037 * it automatically in that case, but you
1038 * can use this option to tweak the pattern
1039 * parameters. */
1040 patterns_init(&u->pat, optval, false, true);
1041 u->want_pat = pat_setup = true;
1042 } else if (!strcasecmp(optname, "significant_threshold") && optval) {
1043 /* Some heuristics (XXX: none in mainline) rely
1044 * on the knowledge of the last "significant"
1045 * node in the descent. Such a node is
1046 * considered reasonably trustworthy to carry
1047 * some meaningful information in the values
1048 * of the node and its children. */
1049 u->significant_threshold = atoi(optval);
1051 /** Distributed engine slaves setup */
1053 } else if (!strcasecmp(optname, "slave")) {
1054 /* Act as slave for the distributed engine. */
1055 u->slave = !optval || atoi(optval);
1056 } else if (!strcasecmp(optname, "slave_index") && optval) {
1057 /* Optional index if per-slave behavior is desired.
1058 * Must be given as index/max */
1059 u->slave_index = atoi(optval);
1060 char *p = strchr(optval, '/');
1061 if (p) u->max_slaves = atoi(++p);
1062 } else if (!strcasecmp(optname, "shared_nodes") && optval) {
1063 /* Share at most shared_nodes between master and slave at each genmoves.
1064 * Must use the same value in master and slaves. */
1065 u->shared_nodes = atoi(optval);
1066 } else if (!strcasecmp(optname, "shared_levels") && optval) {
1067 /* Share only nodes of level <= shared_levels. */
1068 u->shared_levels = atoi(optval);
1069 } else if (!strcasecmp(optname, "stats_hbits") && optval) {
1070 /* Set hash table size to 2^stats_hbits for the shared stats. */
1071 u->stats_hbits = atoi(optval);
1072 } else if (!strcasecmp(optname, "stats_delay") && optval) {
1073 /* How long to wait in slave for initial stats to build up before
1074 * replying to the genmoves command (in ms) */
1075 u->stats_delay = 0.001 * atof(optval);
1077 /** Presets */
1079 } else if (!strcasecmp(optname, "maximize_score")) {
1080 /* A combination of settings that will make
1081 * Pachi try to maximize his points (instead
1082 * of playing slack yose) or minimize his loss
1083 * (and proceed to counting even when losing). */
1084 /* Please note that this preset might be
1085 * somewhat weaker than normal Pachi, and the
1086 * score maximization is approximate; point size
1087 * of win/loss still should not be used to judge
1088 * strength of Pachi or the opponent. */
1089 /* See README for some further notes. */
1090 if (!optval || atoi(optval)) {
1091 /* Allow scoring a lost game. */
1092 u->allow_losing_pass = true;
1093 /* Make Pachi keep his calm when losing
1094 * and/or maintain winning marging. */
1095 /* Do not play games that are losing
1096 * by too much. */
1097 /* XXX: komi_ratchet_age=40000 is necessary
1098 * with losing_komi_ratchet, but 40000
1099 * is somewhat arbitrary value. */
1100 char dynkomi_args[] = "losing_komi_ratchet:komi_ratchet_age=60000:no_komi_at_game_end=0:max_losing_komi=30";
1101 u->dynkomi = uct_dynkomi_init_adaptive(u, dynkomi_args, b);
1102 /* XXX: Values arbitrary so far. */
1103 /* XXX: Also, is bytemp sensible when
1104 * combined with dynamic komi?! */
1105 u->val_scale = 0.01;
1106 u->val_bytemp = true;
1107 u->val_bytemp_min = 0.001;
1108 u->val_byavg = true;
1111 } else {
1112 fprintf(stderr, "uct: Invalid engine argument %s or missing value\n", optname);
1113 exit(1);
1118 if (!u->policy)
1119 u->policy = policy_ucb1amaf_init(u, NULL, b);
1121 if (!!u->random_policy_chance ^ !!u->random_policy) {
1122 fprintf(stderr, "uct: Only one of random_policy and random_policy_chance is set\n");
1123 exit(1);
1126 if (!u->local_tree) {
1127 /* No ltree aging. */
1128 u->local_tree_aging = 1.0f;
1131 if (u->fast_alloc) {
1132 if (u->pruning_threshold < u->max_tree_size / 10)
1133 u->pruning_threshold = u->max_tree_size / 10;
1134 if (u->pruning_threshold > u->max_tree_size / 2)
1135 u->pruning_threshold = u->max_tree_size / 2;
1137 /* Limit pruning temp space to 20% of memory. Beyond this we discard
1138 * the nodes and recompute them at the next move if necessary. */
1139 u->max_pruned_size = u->max_tree_size / 5;
1140 u->max_tree_size -= u->max_pruned_size;
1141 } else {
1142 /* Reserve 5% memory in case the background free() are slower
1143 * than the concurrent allocations. */
1144 u->max_tree_size -= u->max_tree_size / 20;
1147 if (!u->prior)
1148 u->prior = uct_prior_init(NULL, b, u);
1150 if (!u->playout)
1151 u->playout = playout_moggy_init(NULL, b, u->jdict);
1152 if (!u->playout->debug_level)
1153 u->playout->debug_level = u->debug_level;
1155 if (u->want_pat && !pat_setup)
1156 patterns_init(&u->pat, NULL, false, true);
1158 u->ownermap.map = malloc2(board_size2(b) * sizeof(u->ownermap.map[0]));
1160 if (u->slave) {
1161 if (!u->stats_hbits) u->stats_hbits = DEFAULT_STATS_HBITS;
1162 if (!u->shared_nodes) u->shared_nodes = DEFAULT_SHARED_NODES;
1163 assert(u->shared_levels * board_bits2(b) <= 8 * (int)sizeof(path_t));
1166 if (!u->dynkomi)
1167 u->dynkomi = board_small(b) ? uct_dynkomi_init_none(u, NULL, b)
1168 : uct_dynkomi_init_linear(u, NULL, b);
1170 /* Some things remain uninitialized for now - the opening tbook
1171 * is not loaded and the tree not set up. */
1172 /* This will be initialized in setup_state() at the first move
1173 * received/requested. This is because right now we are not aware
1174 * about any komi or handicap setup and such. */
1176 return u;
1179 struct engine *
1180 engine_uct_init(char *arg, struct board *b)
1182 struct uct *u = uct_state_init(arg, b);
1183 struct engine *e = calloc2(1, sizeof(struct engine));
1184 e->name = "UCT";
1185 e->printhook = uct_printhook_ownermap;
1186 e->notify_play = uct_notify_play;
1187 e->chat = uct_chat;
1188 e->undo = uct_undo;
1189 e->result = uct_result;
1190 e->genmove = uct_genmove;
1191 e->genmoves = uct_genmoves;
1192 e->evaluate = uct_evaluate;
1193 e->dead_group_list = uct_dead_group_list;
1194 e->done = uct_done;
1195 e->data = u;
1196 if (u->slave)
1197 e->notify = uct_notify;
1199 const char banner[] = "If you believe you have won but I am still playing, "
1200 "please help me understand by capturing all dead stones. "
1201 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
1202 if (!u->banner) u->banner = "";
1203 e->comment = malloc2(sizeof(banner) + strlen(u->banner) + 1);
1204 sprintf(e->comment, "%s %s", banner, u->banner);
1206 return e;