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