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