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