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