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