uct_genmove(): In case of json reporting, print a JSON final_decision message
[pachi.git] / uct / uct.c
blob0a8245aeb00c54f1a6cf55af1b85f03f491ca8d3
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, struct board *board);
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(3))
47 fprintf(stderr, "Fresh board with random seed %lu\n", fast_getseed());
48 if (!u->no_tbook && b->moves == 0) {
49 if (color == S_BLACK) {
50 tree_load(u->t, b);
51 } else if (DEBUGL(0)) {
52 fprintf(stderr, "Warning: First move appears to be white\n");
57 static void
58 reset_state(struct uct *u)
60 assert(u->t);
61 tree_done(u->t); u->t = NULL;
64 static void
65 setup_dynkomi(struct uct *u, struct board *b, enum stone to_play)
67 if (u->t->use_extra_komi && !u->pondering && u->dynkomi->permove)
68 u->t->extra_komi = u->dynkomi->permove(u->dynkomi, b, u->t);
69 else if (!u->t->use_extra_komi)
70 u->t->extra_komi = 0;
73 void
74 uct_prepare_move(struct uct *u, struct board *b, enum stone color)
76 if (u->t) {
77 /* Verify that we have sane state. */
78 assert(b->es == u);
79 assert(u->t && b->moves);
80 if (color != stone_other(u->t->root_color)) {
81 fprintf(stderr, "Fatal: Non-alternating play detected %d %d\n",
82 color, u->t->root_color);
83 exit(1);
85 uct_htable_reset(u->t);
87 } else {
88 /* We need fresh state. */
89 b->es = u;
90 setup_state(u, b, color);
93 u->ownermap.playouts = 0;
94 memset(u->ownermap.map, 0, board_size2(b) * sizeof(u->ownermap.map[0]));
95 u->played_own = u->played_all = 0;
98 static void
99 dead_group_list(struct uct *u, struct board *b, struct move_queue *mq)
101 enum gj_state gs_array[board_size2(b)];
102 struct group_judgement gj = { .thres = GJ_THRES, .gs = gs_array };
103 board_ownermap_judge_groups(b, &u->ownermap, &gj);
104 groups_of_status(b, &gj, GS_DEAD, mq);
107 bool
108 uct_pass_is_safe(struct uct *u, struct board *b, enum stone color, bool pass_all_alive)
110 /* Make sure enough playouts are simulated to get a reasonable dead group list. */
111 while (u->ownermap.playouts < GJ_MINGAMES)
112 uct_playout(u, b, color, u->t);
114 struct move_queue mq = { .moves = 0 };
115 dead_group_list(u, b, &mq);
116 if (pass_all_alive) {
117 for (unsigned int i = 0; i < mq.moves; i++) {
118 if (board_at(b, mq.move[i]) == stone_other(color)) {
119 return false; // We need to remove opponent dead groups first.
122 mq.moves = 0; // our dead stones are alive when pass_all_alive is true
124 return pass_is_safe(b, color, &mq);
127 static char *
128 uct_printhook_ownermap(struct board *board, coord_t c, char *s, char *end)
130 struct uct *u = board->es;
131 if (!u) {
132 strcat(s, ". ");
133 return s + 2;
135 const char chr[] = ":XO,"; // dame, black, white, unclear
136 const char chm[] = ":xo,";
137 char ch = chr[board_ownermap_judge_point(&u->ownermap, c, GJ_THRES)];
138 if (ch == ',') { // less precise estimate then?
139 ch = chm[board_ownermap_judge_point(&u->ownermap, c, 0.67)];
141 s += snprintf(s, end - s, "%c ", ch);
142 return s;
145 static char *
146 uct_notify_play(struct engine *e, struct board *b, struct move *m, char *enginearg)
148 struct uct *u = e->data;
149 if (!u->t) {
150 /* No state, create one - this is probably game beginning
151 * and we need to load the opening tbook right now. */
152 uct_prepare_move(u, b, m->color);
153 assert(u->t);
156 /* Stop pondering, required by tree_promote_at() */
157 uct_pondering_stop(u);
158 if (UDEBUGL(2) && u->slave)
159 tree_dump(u->t, u->dumpthres);
161 if (is_resign(m->coord)) {
162 /* Reset state. */
163 reset_state(u);
164 return NULL;
167 /* Promote node of the appropriate move to the tree root. */
168 assert(u->t->root);
169 if (!tree_promote_at(u->t, b, m->coord)) {
170 if (UDEBUGL(3))
171 fprintf(stderr, "Warning: Cannot promote move node! Several play commands in row?\n");
172 reset_state(u);
173 return NULL;
176 /* If we are a slave in a distributed engine, start pondering once
177 * we know which move we actually played. See uct_genmove() about
178 * the check for pass. */
179 if (u->pondering_opt && u->slave && m->color == u->my_color && !is_pass(m->coord))
180 uct_pondering_start(u, b, u->t, stone_other(m->color));
182 return NULL;
185 static char *
186 uct_undo(struct engine *e, struct board *b)
188 struct uct *u = e->data;
190 if (!u->t) return NULL;
191 uct_pondering_stop(u);
192 reset_state(u);
193 return NULL;
196 static char *
197 uct_result(struct engine *e, struct board *b)
199 struct uct *u = e->data;
200 static char reply[1024];
202 if (!u->t)
203 return NULL;
204 enum stone color = u->t->root_color;
205 struct tree_node *n = u->t->root;
206 snprintf(reply, 1024, "%s %s %d %.2f %.1f",
207 stone2str(color), coord2sstr(node_coord(n), b),
208 n->u.playouts, tree_node_get_value(u->t, -1, n->u.value),
209 u->t->use_extra_komi ? u->t->extra_komi : 0);
210 return reply;
213 static char *
214 uct_chat(struct engine *e, struct board *b, char *cmd)
216 struct uct *u = e->data;
217 static char reply[1024];
219 cmd += strspn(cmd, " \n\t");
220 if (!strncasecmp(cmd, "winrate", 7)) {
221 if (!u->t)
222 return "no game context (yet?)";
223 enum stone color = u->t->root_color;
224 struct tree_node *n = u->t->root;
225 snprintf(reply, 1024, "In %d playouts at %d threads, %s %s can win with %.2f%% probability",
226 n->u.playouts, u->threads, stone2str(color), coord2sstr(node_coord(n), b),
227 tree_node_get_value(u->t, -1, n->u.value) * 100);
228 if (u->t->use_extra_komi && abs(u->t->extra_komi) >= 0.5) {
229 sprintf(reply + strlen(reply), ", while self-imposing extra komi %.1f",
230 u->t->extra_komi);
232 strcat(reply, ".");
233 return reply;
235 return NULL;
238 static void
239 uct_dead_group_list(struct engine *e, struct board *b, struct move_queue *mq)
241 struct uct *u = e->data;
243 /* This means the game is probably over, no use pondering on. */
244 uct_pondering_stop(u);
246 if (u->pass_all_alive)
247 return; // no dead groups
249 bool mock_state = false;
251 if (!u->t) {
252 /* No state, but we cannot just back out - we might
253 * have passed earlier, only assuming some stones are
254 * dead, and then re-connected, only to lose counting
255 * when all stones are assumed alive. */
256 uct_prepare_move(u, b, S_BLACK); assert(u->t);
257 mock_state = true;
259 /* Make sure the ownermap is well-seeded. */
260 while (u->ownermap.playouts < GJ_MINGAMES)
261 uct_playout(u, b, S_BLACK, u->t);
262 /* Show the ownermap: */
263 if (DEBUGL(2))
264 board_print_custom(b, stderr, uct_printhook_ownermap);
266 dead_group_list(u, b, mq);
268 if (mock_state) {
269 /* Clean up the mock state in case we will receive
270 * a genmove; we could get a non-alternating-move
271 * error from uct_prepare_move() in that case otherwise. */
272 reset_state(u);
276 static void
277 playout_policy_done(struct playout_policy *p)
279 if (p->done) p->done(p);
280 if (p->data) free(p->data);
281 free(p);
284 static void
285 uct_done(struct engine *e)
287 /* This is called on engine reset, especially when clear_board
288 * is received and new game should begin. */
289 struct uct *u = e->data;
290 uct_pondering_stop(u);
291 if (u->t) reset_state(u);
292 free(u->ownermap.map);
294 free(u->policy);
295 free(u->random_policy);
296 playout_policy_done(u->playout);
297 uct_prior_done(u->prior);
298 joseki_done(u->jdict);
299 pluginset_done(u->plugins);
304 /* Run time-limited MCTS search on foreground. */
305 static int
306 uct_search(struct uct *u, struct board *b, struct time_info *ti, enum stone color, struct tree *t)
308 struct uct_search_state s;
309 uct_search_start(u, b, color, t, ti, &s);
310 if (UDEBUGL(2) && s.base_playouts > 0)
311 fprintf(stderr, "<pre-simulated %d games>\n", s.base_playouts);
313 /* The search tree is ctx->t. This is currently == . It is important
314 * to reference ctx->t directly since the
315 * thread manager will swap the tree pointer asynchronously. */
317 /* Now, just periodically poll the search tree. */
318 /* Note that in case of TD_GAMES, threads will not wait for
319 * the uct_search_check_stop() signalization. */
320 while (1) {
321 time_sleep(TREE_BUSYWAIT_INTERVAL);
322 /* TREE_BUSYWAIT_INTERVAL should never be less than desired time, or the
323 * time control is broken. But if it happens to be less, we still search
324 * at least 100ms otherwise the move is completely random. */
326 int i = uct_search_games(&s);
327 /* Print notifications etc. */
328 uct_search_progress(u, b, color, t, ti, &s, i);
329 /* Check if we should stop the search. */
330 if (uct_search_check_stop(u, b, color, t, ti, &s, i))
331 break;
334 struct uct_thread_ctx *ctx = uct_search_stop();
335 if (UDEBUGL(2)) tree_dump(t, u->dumpthres);
336 if (UDEBUGL(2))
337 fprintf(stderr, "(avg score %f/%d; dynkomi's %f/%d value %f/%d)\n",
338 t->avg_score.value, t->avg_score.playouts,
339 u->dynkomi->score.value, u->dynkomi->score.playouts,
340 u->dynkomi->value.value, u->dynkomi->value.playouts);
341 uct_progress_status(u, t, color, ctx->games, true);
343 u->played_own += ctx->games;
344 return ctx->games;
347 /* Start pondering background with @color to play. */
348 static void
349 uct_pondering_start(struct uct *u, struct board *b0, struct tree *t, enum stone color)
351 if (UDEBUGL(1))
352 fprintf(stderr, "Starting to ponder with color %s\n", stone2str(stone_other(color)));
353 u->pondering = true;
355 /* We need a local board copy to ponder upon. */
356 struct board *b = malloc2(sizeof(*b)); board_copy(b, b0);
358 /* *b0 did not have the genmove'd move played yet. */
359 struct move m = { node_coord(t->root), t->root_color };
360 int res = board_play(b, &m);
361 assert(res >= 0);
362 setup_dynkomi(u, b, stone_other(m.color));
364 /* Start MCTS manager thread "headless". */
365 static struct uct_search_state s;
366 uct_search_start(u, b, color, t, NULL, &s);
369 /* uct_search_stop() frontend for the pondering (non-genmove) mode, and
370 * to stop the background search for a slave in the distributed engine. */
371 void
372 uct_pondering_stop(struct uct *u)
374 if (!thread_manager_running)
375 return;
377 /* Stop the thread manager. */
378 struct uct_thread_ctx *ctx = uct_search_stop();
379 if (UDEBUGL(1)) {
380 if (u->pondering) fprintf(stderr, "(pondering) ");
381 uct_progress_status(u, ctx->t, ctx->color, ctx->games, true);
383 if (u->pondering) {
384 free(ctx->b);
385 u->pondering = false;
390 void
391 uct_genmove_setup(struct uct *u, struct board *b, enum stone color)
393 if (b->superko_violation) {
394 fprintf(stderr, "!!! WARNING: SUPERKO VIOLATION OCCURED BEFORE THIS MOVE\n");
395 fprintf(stderr, "Maybe you play with situational instead of positional superko?\n");
396 fprintf(stderr, "I'm going to ignore the violation, but note that I may miss\n");
397 fprintf(stderr, "some moves valid under this ruleset because of this.\n");
398 b->superko_violation = false;
401 uct_prepare_move(u, b, color);
403 assert(u->t);
404 u->my_color = color;
406 /* How to decide whether to use dynkomi in this game? Since we use
407 * pondering, it's not simple "who-to-play" matter. Decide based on
408 * the last genmove issued. */
409 u->t->use_extra_komi = !!(u->dynkomi_mask & color);
410 setup_dynkomi(u, b, color);
412 if (b->rules == RULES_JAPANESE)
413 u->territory_scoring = true;
415 /* Make pessimistic assumption about komi for Japanese rules to
416 * avoid losing by 0.5 when winning by 0.5 with Chinese rules.
417 * The rules usually give the same winner if the integer part of komi
418 * is odd so we adjust the komi only if it is even (for a board of
419 * odd size). We are not trying to get an exact evaluation for rare
420 * cases of seki. For details see http://home.snafu.de/jasiek/parity.html */
421 if (u->territory_scoring && (((int)floor(b->komi) + board_size(b)) & 1)) {
422 b->komi += (color == S_BLACK ? 1.0 : -1.0);
423 if (UDEBUGL(0))
424 fprintf(stderr, "Setting komi to %.1f assuming Japanese rules\n",
425 b->komi);
429 static coord_t *
430 uct_genmove(struct engine *e, struct board *b, struct time_info *ti, enum stone color, bool pass_all_alive)
432 double start_time = time_now();
433 struct uct *u = e->data;
434 u->pass_all_alive |= pass_all_alive;
435 uct_pondering_stop(u);
436 uct_genmove_setup(u, b, color);
438 /* Start the Monte Carlo Tree Search! */
439 int base_playouts = u->t->root->u.playouts;
440 int played_games = uct_search(u, b, ti, color, u->t);
442 coord_t best_coord;
443 struct tree_node *best;
444 best = uct_search_result(u, b, color, u->pass_all_alive, played_games, base_playouts, &best_coord);
446 if (UDEBUGL(2)) {
447 double time = time_now() - start_time + 0.000001; /* avoid divide by zero */
448 fprintf(stderr, "genmove in %0.2fs (%d games/s, %d games/s/thread)\n",
449 time, (int)(played_games/time), (int)(played_games/time/u->threads));
452 if (!best) {
453 /* Pass or resign. */
454 reset_state(u);
455 goto best_coord;
457 tree_promote_node(u->t, &best);
459 /* After a pass, pondering is harmful for two reasons:
460 * (i) We might keep pondering even when the game is over.
461 * Of course this is the case for opponent resign as well.
462 * (ii) More importantly, the ownermap will get skewed since
463 * the UCT will start cutting off any playouts. */
464 if (u->pondering_opt && !is_pass(node_coord(best))) {
465 uct_pondering_start(u, b, u->t, stone_other(color));
467 best_coord:
468 if (u->reporting == UR_JSON || u->reporting == UR_JSON_BIG)
469 fprintf(stderr, "{\"final_decision\": \"%s\"}\n",
470 coord2sstr(best_coord, b));
471 return coord_copy(best_coord);
475 bool
476 uct_gentbook(struct engine *e, struct board *b, struct time_info *ti, enum stone color)
478 struct uct *u = e->data;
479 if (!u->t) uct_prepare_move(u, b, color);
480 assert(u->t);
482 if (ti->dim == TD_GAMES) {
483 /* Don't count in games that already went into the tbook. */
484 ti->len.games += u->t->root->u.playouts;
486 uct_search(u, b, ti, color, u->t);
488 assert(ti->dim == TD_GAMES);
489 tree_save(u->t, b, ti->len.games / 100);
491 return true;
494 void
495 uct_dumptbook(struct engine *e, struct board *b, enum stone color)
497 struct uct *u = e->data;
498 struct tree *t = tree_init(b, color, u->fast_alloc ? u->max_tree_size : 0,
499 u->max_pruned_size, u->pruning_threshold, u->local_tree_aging, 0);
500 tree_load(t, b);
501 tree_dump(t, 0);
502 tree_done(t);
506 floating_t
507 uct_evaluate_one(struct engine *e, struct board *b, struct time_info *ti, coord_t c, enum stone color)
509 struct uct *u = e->data;
511 struct board b2;
512 board_copy(&b2, b);
513 struct move m = { c, color };
514 int res = board_play(&b2, &m);
515 if (res < 0)
516 return NAN;
517 color = stone_other(color);
519 if (u->t) reset_state(u);
520 uct_prepare_move(u, &b2, color);
521 assert(u->t);
523 floating_t bestval;
524 uct_search(u, &b2, ti, color, u->t);
525 struct tree_node *best = u->policy->choose(u->policy, u->t->root, &b2, color, resign);
526 if (!best) {
527 bestval = NAN; // the opponent has no reply!
528 } else {
529 bestval = tree_node_get_value(u->t, 1, best->u.value);
532 reset_state(u); // clean our junk
534 return isnan(bestval) ? NAN : 1.0f - bestval;
537 void
538 uct_evaluate(struct engine *e, struct board *b, struct time_info *ti, floating_t *vals, enum stone color)
540 for (int i = 0; i < b->flen; i++) {
541 if (is_pass(b->f[i]))
542 vals[i] = NAN;
543 else
544 vals[i] = uct_evaluate_one(e, b, ti, b->f[i], color);
549 struct uct *
550 uct_state_init(char *arg, struct board *b)
552 struct uct *u = calloc2(1, sizeof(struct uct));
553 bool pat_setup = false;
555 u->debug_level = debug_level;
556 u->reportfreq = 10000;
557 u->gamelen = MC_GAMELEN;
558 u->resign_threshold = 0.2;
559 u->sure_win_threshold = 0.9;
560 u->mercymin = 0;
561 u->significant_threshold = 50;
562 u->expand_p = 8;
563 u->dumpthres = 1000;
564 u->playout_amaf = true;
565 u->amaf_prior = false;
566 u->max_tree_size = 1408ULL * 1048576;
567 u->fast_alloc = true;
568 u->pruning_threshold = 0;
570 u->threads = 1;
571 u->thread_model = TM_TREEVL;
572 u->virtual_loss = 1;
574 u->fuseki_end = 20; // max time at 361*20% = 72 moves (our 36th move, still 99 to play)
575 u->yose_start = 40; // (100-40-25)*361/100/2 = 63 moves still to play by us then
576 u->bestr_ratio = 0.02;
577 // 2.5 is clearly too much, but seems to compensate well for overly stern time allocations.
578 // TODO: Further tuning and experiments with better time allocation schemes.
579 u->best2_ratio = 2.5;
580 u->max_maintime_ratio = 3.0;
582 u->val_scale = 0; u->val_points = 40;
583 u->dynkomi_interval = 1000;
584 u->dynkomi_mask = S_BLACK | S_WHITE;
586 u->tenuki_d = 4;
587 u->local_tree_aging = 80;
588 u->local_tree_depth_decay = 1.5;
589 u->local_tree_eval = LTE_ROOT;
590 u->local_tree_neival = true;
592 u->max_slaves = -1;
593 u->slave_index = -1;
594 u->stats_delay = 0.01; // 10 ms
596 u->plugins = pluginset_init(b);
598 u->jdict = joseki_load(b->size);
600 if (arg) {
601 char *optspec, *next = arg;
602 while (*next) {
603 optspec = next;
604 next += strcspn(next, ",");
605 if (*next) { *next++ = 0; } else { *next = 0; }
607 char *optname = optspec;
608 char *optval = strchr(optspec, '=');
609 if (optval) *optval++ = 0;
611 /** Basic options */
613 if (!strcasecmp(optname, "debug")) {
614 if (optval)
615 u->debug_level = atoi(optval);
616 else
617 u->debug_level++;
618 } else if (!strcasecmp(optname, "reporting") && optval) {
619 /* The format of output for detailed progress
620 * information (such as current best move and
621 * its value, etc.). */
622 if (!strcasecmp(optval, "text")) {
623 /* Plaintext traditional output. */
624 u->reporting = UR_TEXT;
625 } else if (!strcasecmp(optval, "json")) {
626 /* JSON output. Implies debug=0. */
627 u->reporting = UR_JSON;
628 u->debug_level = 0;
629 } else if (!strcasecmp(optval, "jsonbig")) {
630 /* JSON output, but much more detailed.
631 * Implies debug=0. */
632 u->reporting = UR_JSON_BIG;
633 u->debug_level = 0;
634 } else {
635 fprintf(stderr, "UCT: Invalid reporting format %s\n", optval);
636 exit(1);
638 } else if (!strcasecmp(optname, "reportfreq") && optval) {
639 /* The progress information line will be shown
640 * every <reportfreq> simulations. */
641 u->reportfreq = atoi(optval);
642 } else if (!strcasecmp(optname, "dumpthres") && optval) {
643 /* When dumping the UCT tree on output, include
644 * nodes with at least this many playouts.
645 * (This value is re-scaled "intelligently"
646 * in case of very large trees.) */
647 u->dumpthres = atoi(optval);
648 } else if (!strcasecmp(optname, "resign_threshold") && optval) {
649 /* Resign when this ratio of games is lost
650 * after GJ_MINGAMES sample is taken. */
651 u->resign_threshold = atof(optval);
652 } else if (!strcasecmp(optname, "sure_win_threshold") && optval) {
653 /* Stop reading when this ratio of games is won
654 * after PLAYOUT_EARLY_BREAK_MIN sample is
655 * taken. (Prevents stupid time losses,
656 * friendly to human opponents.) */
657 u->sure_win_threshold = atof(optval);
658 } else if (!strcasecmp(optname, "force_seed") && optval) {
659 /* Set RNG seed at the tree setup. */
660 u->force_seed = atoi(optval);
661 } else if (!strcasecmp(optname, "no_tbook")) {
662 /* Disable UCT opening tbook. */
663 u->no_tbook = true;
664 } else if (!strcasecmp(optname, "pass_all_alive")) {
665 /* Whether to consider passing only after all
666 * dead groups were removed from the board;
667 * this is like all genmoves are in fact
668 * kgs-genmove_cleanup. */
669 u->pass_all_alive = !optval || atoi(optval);
670 } else if (!strcasecmp(optname, "territory_scoring")) {
671 /* Use territory scoring (default is area scoring).
672 * An explicit kgs-rules command overrides this. */
673 u->territory_scoring = !optval || atoi(optval);
674 } else if (!strcasecmp(optname, "stones_only")) {
675 /* Do not count eyes. Nice to teach go to kids.
676 * http://strasbourg.jeudego.org/regle_strasbourgeoise.htm */
677 b->rules = RULES_STONES_ONLY;
678 u->pass_all_alive = true;
679 } else if (!strcasecmp(optname, "banner") && optval) {
680 /* Additional banner string. This must come as the
681 * last engine parameter. */
682 if (*next) *--next = ',';
683 u->banner = strdup(optval);
684 break;
685 } else if (!strcasecmp(optname, "plugin") && optval) {
686 /* Load an external plugin; filename goes before the colon,
687 * extra arguments after the colon. */
688 char *pluginarg = strchr(optval, ':');
689 if (pluginarg)
690 *pluginarg++ = 0;
691 plugin_load(u->plugins, optval, pluginarg);
693 /** UCT behavior and policies */
695 } else if ((!strcasecmp(optname, "policy")
696 /* Node selection policy. ucb1amaf is the
697 * default policy implementing RAVE, while
698 * ucb1 is the simple exploration/exploitation
699 * policy. Policies can take further extra
700 * options. */
701 || !strcasecmp(optname, "random_policy")) && optval) {
702 /* A policy to be used randomly with small
703 * chance instead of the default policy. */
704 char *policyarg = strchr(optval, ':');
705 struct uct_policy **p = !strcasecmp(optname, "policy") ? &u->policy : &u->random_policy;
706 if (policyarg)
707 *policyarg++ = 0;
708 if (!strcasecmp(optval, "ucb1")) {
709 *p = policy_ucb1_init(u, policyarg);
710 } else if (!strcasecmp(optval, "ucb1amaf")) {
711 *p = policy_ucb1amaf_init(u, policyarg, b);
712 } else {
713 fprintf(stderr, "UCT: Invalid tree policy %s\n", optval);
714 exit(1);
716 } else if (!strcasecmp(optname, "playout") && optval) {
717 /* Random simulation (playout) policy.
718 * moggy is the default policy with large
719 * amount of domain-specific knowledge and
720 * heuristics. light is a simple uniformly
721 * random move selection policy. */
722 char *playoutarg = strchr(optval, ':');
723 if (playoutarg)
724 *playoutarg++ = 0;
725 if (!strcasecmp(optval, "moggy")) {
726 u->playout = playout_moggy_init(playoutarg, b, u->jdict);
727 } else if (!strcasecmp(optval, "light")) {
728 u->playout = playout_light_init(playoutarg, b);
729 } else {
730 fprintf(stderr, "UCT: Invalid playout policy %s\n", optval);
731 exit(1);
733 } else if (!strcasecmp(optname, "prior") && optval) {
734 /* Node priors policy. When expanding a node,
735 * it will seed node values heuristically
736 * (most importantly, based on playout policy
737 * opinion, but also with regard to other
738 * things). See uct/prior.c for details.
739 * Use prior=eqex=0 to disable priors. */
740 u->prior = uct_prior_init(optval, b, u);
741 } else if (!strcasecmp(optname, "mercy") && optval) {
742 /* Minimal difference of black/white captures
743 * to stop playout - "Mercy Rule". Speeds up
744 * hopeless playouts at the expense of some
745 * accuracy. */
746 u->mercymin = atoi(optval);
747 } else if (!strcasecmp(optname, "gamelen") && optval) {
748 /* Maximum length of single simulation
749 * in moves. */
750 u->gamelen = atoi(optval);
751 } else if (!strcasecmp(optname, "expand_p") && optval) {
752 /* Expand UCT nodes after it has been
753 * visited this many times. */
754 u->expand_p = atoi(optval);
755 } else if (!strcasecmp(optname, "random_policy_chance") && optval) {
756 /* If specified (N), with probability 1/N, random_policy policy
757 * descend is used instead of main policy descend; useful
758 * if specified policy (e.g. UCB1AMAF) can make unduly biased
759 * choices sometimes, you can fall back to e.g.
760 * random_policy=UCB1. */
761 u->random_policy_chance = atoi(optval);
763 /** General AMAF behavior */
764 /* (Only relevant if the policy supports AMAF.
765 * More variables can be tuned as policy
766 * parameters.) */
768 } else if (!strcasecmp(optname, "playout_amaf")) {
769 /* Whether to include random playout moves in
770 * AMAF as well. (Otherwise, only tree moves
771 * are included in AMAF. Of course makes sense
772 * only in connection with an AMAF policy.) */
773 /* with-without: 55.5% (+-4.1) */
774 if (optval && *optval == '0')
775 u->playout_amaf = false;
776 else
777 u->playout_amaf = true;
778 } else if (!strcasecmp(optname, "playout_amaf_cutoff") && optval) {
779 /* Keep only first N% of playout stage AMAF
780 * information. */
781 u->playout_amaf_cutoff = atoi(optval);
782 } else if (!strcasecmp(optname, "amaf_prior") && optval) {
783 /* In node policy, consider prior values
784 * part of the real result term or part
785 * of the AMAF term? */
786 u->amaf_prior = atoi(optval);
788 /** Performance and memory management */
790 } else if (!strcasecmp(optname, "threads") && optval) {
791 /* By default, Pachi will run with only single
792 * tree search thread! */
793 u->threads = atoi(optval);
794 } else if (!strcasecmp(optname, "thread_model") && optval) {
795 if (!strcasecmp(optval, "tree")) {
796 /* Tree parallelization - all threads
797 * grind on the same tree. */
798 u->thread_model = TM_TREE;
799 u->virtual_loss = 0;
800 } else if (!strcasecmp(optval, "treevl")) {
801 /* Tree parallelization, but also
802 * with virtual losses - this discou-
803 * rages most threads choosing the
804 * same tree branches to read. */
805 u->thread_model = TM_TREEVL;
806 } else {
807 fprintf(stderr, "UCT: Invalid thread model %s\n", optval);
808 exit(1);
810 } else if (!strcasecmp(optname, "virtual_loss")) {
811 /* Number of virtual losses added before evaluating a node. */
812 u->virtual_loss = !optval || atoi(optval);
813 } else if (!strcasecmp(optname, "pondering")) {
814 /* Keep searching even during opponent's turn. */
815 u->pondering_opt = !optval || atoi(optval);
816 } else if (!strcasecmp(optname, "max_tree_size") && optval) {
817 /* Maximum amount of memory [MiB] consumed by the move tree.
818 * For fast_alloc it includes the temp tree used for pruning.
819 * Default is 3072 (3 GiB). */
820 u->max_tree_size = atol(optval) * 1048576;
821 } else if (!strcasecmp(optname, "fast_alloc")) {
822 u->fast_alloc = !optval || atoi(optval);
823 } else if (!strcasecmp(optname, "pruning_threshold") && optval) {
824 /* Force pruning at beginning of a move if the tree consumes
825 * more than this [MiB]. Default is 10% of max_tree_size.
826 * Increase to reduce pruning time overhead if memory is plentiful.
827 * This option is meaningful only for fast_alloc. */
828 u->pruning_threshold = atol(optval) * 1048576;
830 /** Time control */
832 } else if (!strcasecmp(optname, "best2_ratio") && optval) {
833 /* If set, prolong simulating while
834 * first_best/second_best playouts ratio
835 * is less than best2_ratio. */
836 u->best2_ratio = atof(optval);
837 } else if (!strcasecmp(optname, "bestr_ratio") && optval) {
838 /* If set, prolong simulating while
839 * best,best_best_child values delta
840 * is more than bestr_ratio. */
841 u->bestr_ratio = atof(optval);
842 } else if (!strcasecmp(optname, "max_maintime_ratio") && optval) {
843 /* If set and while not in byoyomi, prolong simulating no more than
844 * max_maintime_ratio times the normal desired thinking time. */
845 u->max_maintime_ratio = atof(optval);
846 } else if (!strcasecmp(optname, "fuseki_end") && optval) {
847 /* At the very beginning it's not worth thinking
848 * too long because the playout evaluations are
849 * very noisy. So gradually increase the thinking
850 * time up to maximum when fuseki_end percent
851 * of the board has been played.
852 * This only applies if we are not in byoyomi. */
853 u->fuseki_end = atoi(optval);
854 } else if (!strcasecmp(optname, "yose_start") && optval) {
855 /* When yose_start percent of the board has been
856 * played, or if we are in byoyomi, stop spending
857 * more time and spread the remaining time
858 * uniformly.
859 * Between fuseki_end and yose_start, we spend
860 * a constant proportion of the remaining time
861 * on each move. (yose_start should actually
862 * be much earlier than when real yose start,
863 * but "yose" is a good short name to convey
864 * the idea.) */
865 u->yose_start = atoi(optval);
867 /** Dynamic komi */
869 } else if (!strcasecmp(optname, "dynkomi") && optval) {
870 /* Dynamic komi approach; there are multiple
871 * ways to adjust komi dynamically throughout
872 * play. We currently support two: */
873 char *dynkomiarg = strchr(optval, ':');
874 if (dynkomiarg)
875 *dynkomiarg++ = 0;
876 if (!strcasecmp(optval, "none")) {
877 u->dynkomi = uct_dynkomi_init_none(u, dynkomiarg, b);
878 } else if (!strcasecmp(optval, "linear")) {
879 /* You should set dynkomi_mask=1 or a very low
880 * handicap_value for white. */
881 u->dynkomi = uct_dynkomi_init_linear(u, dynkomiarg, b);
882 } else if (!strcasecmp(optval, "adaptive")) {
883 /* There are many more knobs to
884 * crank - see uct/dynkomi.c. */
885 u->dynkomi = uct_dynkomi_init_adaptive(u, dynkomiarg, b);
886 } else {
887 fprintf(stderr, "UCT: Invalid dynkomi mode %s\n", optval);
888 exit(1);
890 } else if (!strcasecmp(optname, "dynkomi_mask") && optval) {
891 /* Bitmask of colors the player must be
892 * for dynkomi be applied; the default dynkomi_mask=3 allows
893 * dynkomi even in games where Pachi is white. */
894 u->dynkomi_mask = atoi(optval);
895 } else if (!strcasecmp(optname, "dynkomi_interval") && optval) {
896 /* If non-zero, re-adjust dynamic komi
897 * throughout a single genmove reading,
898 * roughly every N simulations. */
899 /* XXX: Does not work with tree
900 * parallelization. */
901 u->dynkomi_interval = atoi(optval);
903 /** Node value result scaling */
905 } else if (!strcasecmp(optname, "val_scale") && optval) {
906 /* How much of the game result value should be
907 * influenced by win size. Zero means it isn't. */
908 u->val_scale = atof(optval);
909 } else if (!strcasecmp(optname, "val_points") && optval) {
910 /* Maximum size of win to be scaled into game
911 * result value. Zero means boardsize^2. */
912 u->val_points = atoi(optval) * 2; // result values are doubled
913 } else if (!strcasecmp(optname, "val_extra")) {
914 /* If false, the score coefficient will be simply
915 * added to the value, instead of scaling the result
916 * coefficient because of it. */
917 u->val_extra = !optval || atoi(optval);
919 /** Local trees */
920 /* (Purely experimental. Does not work - yet!) */
922 } else if (!strcasecmp(optname, "local_tree")) {
923 /* Whether to bias exploration by local tree values. */
924 u->local_tree = !optval || atoi(optval);
925 } else if (!strcasecmp(optname, "tenuki_d") && optval) {
926 /* Tenuki distance at which to break the local tree. */
927 u->tenuki_d = atoi(optval);
928 if (u->tenuki_d > TREE_NODE_D_MAX + 1) {
929 fprintf(stderr, "uct: tenuki_d must not be larger than TREE_NODE_D_MAX+1 %d\n", TREE_NODE_D_MAX + 1);
930 exit(1);
932 } else if (!strcasecmp(optname, "local_tree_aging") && optval) {
933 /* How much to reduce local tree values between moves. */
934 u->local_tree_aging = atof(optval);
935 } else if (!strcasecmp(optname, "local_tree_depth_decay") && optval) {
936 /* With value x>0, during the descent the node
937 * contributes 1/x^depth playouts in
938 * the local tree. I.e., with x>1, nodes more
939 * distant from local situation contribute more
940 * than nodes near the root. */
941 u->local_tree_depth_decay = atof(optval);
942 } else if (!strcasecmp(optname, "local_tree_allseq")) {
943 /* If disabled, only complete sequences are stored
944 * in the local tree. If this is on, also
945 * subsequences starting at each move are stored. */
946 u->local_tree_allseq = !optval || atoi(optval);
947 } else if (!strcasecmp(optname, "local_tree_neival")) {
948 /* If disabled, local node value is not
949 * computed just based on terminal status
950 * of the coordinate, but also its neighbors. */
951 u->local_tree_neival = !optval || atoi(optval);
952 } else if (!strcasecmp(optname, "local_tree_eval")) {
953 /* How is the value inserted in the local tree
954 * determined. */
955 if (!strcasecmp(optval, "root"))
956 /* All moves within a tree branch are
957 * considered wrt. their merit
958 * reaching tachtical goal of making
959 * the first move in the branch
960 * survive. */
961 u->local_tree_eval = LTE_ROOT;
962 else if (!strcasecmp(optval, "each"))
963 /* Each move is considered wrt.
964 * its own survival. */
965 u->local_tree_eval = LTE_EACH;
966 else if (!strcasecmp(optval, "total"))
967 /* The tactical goal is the survival
968 * of all the moves of my color and
969 * non-survival of all the opponent
970 * moves. Local values (and their
971 * inverses) are averaged. */
972 u->local_tree_eval = LTE_TOTAL;
973 else {
974 fprintf(stderr, "uct: unknown local_tree_eval %s\n", optval);
975 exit(1);
977 } else if (!strcasecmp(optname, "local_tree_rootchoose")) {
978 /* If disabled, only moves within the local
979 * tree branch are considered; the values
980 * of the branch roots (i.e. root children)
981 * are ignored. This may make sense together
982 * with eval!=each, we consider only moves
983 * that influence the goal, not the "rating"
984 * of the goal itself. (The real solution
985 * will be probably using criticality to pick
986 * local tree branches.) */
987 u->local_tree_rootchoose = !optval || atoi(optval);
989 /** Other heuristics */
990 } else if (!strcasecmp(optname, "patterns")) {
991 /* Load pattern database. Various modules
992 * (priors, policies etc.) may make use
993 * of this database. They will request
994 * it automatically in that case, but you
995 * can use this option to tweak the pattern
996 * parameters. */
997 patterns_init(&u->pat, optval, false, true);
998 u->want_pat = pat_setup = true;
999 } else if (!strcasecmp(optname, "significant_threshold") && optval) {
1000 /* Some heuristics (XXX: none in mainline) rely
1001 * on the knowledge of the last "significant"
1002 * node in the descent. Such a node is
1003 * considered reasonably trustworthy to carry
1004 * some meaningful information in the values
1005 * of the node and its children. */
1006 u->significant_threshold = atoi(optval);
1008 /** Distributed engine slaves setup */
1010 } else if (!strcasecmp(optname, "slave")) {
1011 /* Act as slave for the distributed engine. */
1012 u->slave = !optval || atoi(optval);
1013 } else if (!strcasecmp(optname, "slave_index") && optval) {
1014 /* Optional index if per-slave behavior is desired.
1015 * Must be given as index/max */
1016 u->slave_index = atoi(optval);
1017 char *p = strchr(optval, '/');
1018 if (p) u->max_slaves = atoi(++p);
1019 } else if (!strcasecmp(optname, "shared_nodes") && optval) {
1020 /* Share at most shared_nodes between master and slave at each genmoves.
1021 * Must use the same value in master and slaves. */
1022 u->shared_nodes = atoi(optval);
1023 } else if (!strcasecmp(optname, "shared_levels") && optval) {
1024 /* Share only nodes of level <= shared_levels. */
1025 u->shared_levels = atoi(optval);
1026 } else if (!strcasecmp(optname, "stats_hbits") && optval) {
1027 /* Set hash table size to 2^stats_hbits for the shared stats. */
1028 u->stats_hbits = atoi(optval);
1029 } else if (!strcasecmp(optname, "stats_delay") && optval) {
1030 /* How long to wait in slave for initial stats to build up before
1031 * replying to the genmoves command (in ms) */
1032 u->stats_delay = 0.001 * atof(optval);
1034 } else {
1035 fprintf(stderr, "uct: Invalid engine argument %s or missing value\n", optname);
1036 exit(1);
1041 if (!u->policy)
1042 u->policy = policy_ucb1amaf_init(u, NULL, b);
1044 if (!!u->random_policy_chance ^ !!u->random_policy) {
1045 fprintf(stderr, "uct: Only one of random_policy and random_policy_chance is set\n");
1046 exit(1);
1049 if (!u->local_tree) {
1050 /* No ltree aging. */
1051 u->local_tree_aging = 1.0f;
1054 if (u->fast_alloc) {
1055 if (u->pruning_threshold < u->max_tree_size / 10)
1056 u->pruning_threshold = u->max_tree_size / 10;
1057 if (u->pruning_threshold > u->max_tree_size / 2)
1058 u->pruning_threshold = u->max_tree_size / 2;
1060 /* Limit pruning temp space to 20% of memory. Beyond this we discard
1061 * the nodes and recompute them at the next move if necessary. */
1062 u->max_pruned_size = u->max_tree_size / 5;
1063 u->max_tree_size -= u->max_pruned_size;
1064 } else {
1065 /* Reserve 5% memory in case the background free() are slower
1066 * than the concurrent allocations. */
1067 u->max_tree_size -= u->max_tree_size / 20;
1070 if (!u->prior)
1071 u->prior = uct_prior_init(NULL, b, u);
1073 if (!u->playout)
1074 u->playout = playout_moggy_init(NULL, b, u->jdict);
1075 if (!u->playout->debug_level)
1076 u->playout->debug_level = u->debug_level;
1078 if (u->want_pat && !pat_setup)
1079 patterns_init(&u->pat, NULL, false, true);
1081 u->ownermap.map = malloc2(board_size2(b) * sizeof(u->ownermap.map[0]));
1083 if (u->slave) {
1084 if (!u->stats_hbits) u->stats_hbits = DEFAULT_STATS_HBITS;
1085 if (!u->shared_nodes) u->shared_nodes = DEFAULT_SHARED_NODES;
1086 assert(u->shared_levels * board_bits2(b) <= 8 * (int)sizeof(path_t));
1089 if (!u->dynkomi)
1090 u->dynkomi = uct_dynkomi_init_linear(u, NULL, b);
1092 /* Some things remain uninitialized for now - the opening tbook
1093 * is not loaded and the tree not set up. */
1094 /* This will be initialized in setup_state() at the first move
1095 * received/requested. This is because right now we are not aware
1096 * about any komi or handicap setup and such. */
1098 return u;
1101 struct engine *
1102 engine_uct_init(char *arg, struct board *b)
1104 struct uct *u = uct_state_init(arg, b);
1105 struct engine *e = calloc2(1, sizeof(struct engine));
1106 e->name = "UCT";
1107 e->printhook = uct_printhook_ownermap;
1108 e->notify_play = uct_notify_play;
1109 e->chat = uct_chat;
1110 e->undo = uct_undo;
1111 e->result = uct_result;
1112 e->genmove = uct_genmove;
1113 e->genmoves = uct_genmoves;
1114 e->evaluate = uct_evaluate;
1115 e->dead_group_list = uct_dead_group_list;
1116 e->done = uct_done;
1117 e->data = u;
1118 if (u->slave)
1119 e->notify = uct_notify;
1121 const char banner[] = "If you believe you have won but I am still playing, "
1122 "please help me understand by capturing all dead stones. "
1123 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
1124 if (!u->banner) u->banner = "";
1125 e->comment = malloc2(sizeof(banner) + strlen(u->banner) + 1);
1126 sprintf(e->comment, "%s %s", banner, u->banner);
1128 return e;