uct_state_init(): Major rearrangement of command-line options to topical sections
[pachi/derm.git] / uct / uct.c
blob46823c509d7341794bf356f0f1afcd58d85cb028
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/elo.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);
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(0))
48 fprintf(stderr, "Fresh board with random seed %lu\n", fast_getseed());
49 //board_print(b, stderr);
50 if (!u->no_book && b->moves == 0) {
51 assert(color == S_BLACK);
52 tree_load(u->t, b);
56 static void
57 reset_state(struct uct *u)
59 assert(u->t);
60 tree_done(u->t); u->t = NULL;
63 static void
64 setup_dynkomi(struct uct *u, struct board *b, enum stone to_play)
66 if (u->t->use_extra_komi && !u->pondering && u->dynkomi->permove)
67 u->t->extra_komi = u->dynkomi->permove(u->dynkomi, b, u->t);
68 else if (!u->t->use_extra_komi)
69 u->t->extra_komi = 0;
72 void
73 uct_prepare_move(struct uct *u, struct board *b, enum stone color)
75 if (u->t) {
76 /* Verify that we have sane state. */
77 assert(b->es == u);
78 assert(u->t && b->moves);
79 if (color != stone_other(u->t->root_color)) {
80 fprintf(stderr, "Fatal: Non-alternating play detected %d %d\n",
81 color, u->t->root_color);
82 exit(1);
84 uct_htable_reset(u->t);
86 } else {
87 /* We need fresh state. */
88 b->es = u;
89 setup_state(u, b, color);
92 u->ownermap.playouts = 0;
93 memset(u->ownermap.map, 0, board_size2(b) * sizeof(u->ownermap.map[0]));
94 u->played_own = u->played_all = 0;
97 static void
98 dead_group_list(struct uct *u, struct board *b, struct move_queue *mq)
100 struct group_judgement gj;
101 gj.thres = GJ_THRES;
102 gj.gs = alloca(board_size2(b) * sizeof(gj.gs[0]));
103 board_ownermap_judge_group(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 if (u->ownermap.playouts < GJ_MINGAMES)
111 return false;
113 struct move_queue mq = { .moves = 0 };
114 dead_group_list(u, b, &mq);
115 if (pass_all_alive && mq.moves > 0)
116 return false; // We need to remove some dead groups first.
117 return pass_is_safe(b, color, &mq);
120 static char *
121 uct_printhook_ownermap(struct board *board, coord_t c, char *s, char *end)
123 struct uct *u = board->es;
124 assert(u);
125 const char chr[] = ":XO,"; // dame, black, white, unclear
126 const char chm[] = ":xo,";
127 char ch = chr[board_ownermap_judge_point(&u->ownermap, c, GJ_THRES)];
128 if (ch == ',') { // less precise estimate then?
129 ch = chm[board_ownermap_judge_point(&u->ownermap, c, 0.67)];
131 s += snprintf(s, end - s, "%c ", ch);
132 return s;
135 static char *
136 uct_notify_play(struct engine *e, struct board *b, struct move *m)
138 struct uct *u = e->data;
139 if (!u->t) {
140 /* No state, create one - this is probably game beginning
141 * and we need to load the opening book right now. */
142 uct_prepare_move(u, b, m->color);
143 assert(u->t);
146 /* Stop pondering, required by tree_promote_at() */
147 uct_pondering_stop(u);
148 if (UDEBUGL(2) && u->slave)
149 tree_dump(u->t, u->dumpthres);
151 if (is_resign(m->coord)) {
152 /* Reset state. */
153 reset_state(u);
154 return NULL;
157 /* Promote node of the appropriate move to the tree root. */
158 assert(u->t->root);
159 if (!tree_promote_at(u->t, b, m->coord)) {
160 if (UDEBUGL(0))
161 fprintf(stderr, "Warning: Cannot promote move node! Several play commands in row?\n");
162 reset_state(u);
163 return NULL;
166 /* If we are a slave in a distributed engine, start pondering once
167 * we know which move we actually played. See uct_genmove() about
168 * the check for pass. */
169 if (u->pondering_opt && u->slave && m->color == u->my_color && !is_pass(m->coord))
170 uct_pondering_start(u, b, u->t, stone_other(m->color));
172 return NULL;
175 static char *
176 uct_result(struct engine *e, struct board *b)
178 struct uct *u = e->data;
179 static char reply[1024];
181 if (!u->t)
182 return NULL;
183 enum stone color = u->t->root_color;
184 struct tree_node *n = u->t->root;
185 snprintf(reply, 1024, "%s %s %d %.2f %.1f",
186 stone2str(color), coord2sstr(n->coord, b),
187 n->u.playouts, tree_node_get_value(u->t, -1, n->u.value),
188 u->t->use_extra_komi ? u->t->extra_komi : 0);
189 return reply;
192 static char *
193 uct_chat(struct engine *e, struct board *b, char *cmd)
195 struct uct *u = e->data;
196 static char reply[1024];
198 cmd += strspn(cmd, " \n\t");
199 if (!strncasecmp(cmd, "winrate", 7)) {
200 if (!u->t)
201 return "no game context (yet?)";
202 enum stone color = u->t->root_color;
203 struct tree_node *n = u->t->root;
204 snprintf(reply, 1024, "In %d playouts at %d threads, %s %s can win with %.2f%% probability",
205 n->u.playouts, u->threads, stone2str(color), coord2sstr(n->coord, b),
206 tree_node_get_value(u->t, -1, n->u.value) * 100);
207 if (u->t->use_extra_komi && abs(u->t->extra_komi) >= 0.5) {
208 sprintf(reply + strlen(reply), ", while self-imposing extra komi %.1f",
209 u->t->extra_komi);
211 strcat(reply, ".");
212 return reply;
214 return NULL;
217 static void
218 uct_dead_group_list(struct engine *e, struct board *b, struct move_queue *mq)
220 struct uct *u = e->data;
222 /* This means the game is probably over, no use pondering on. */
223 uct_pondering_stop(u);
225 if (u->pass_all_alive)
226 return; // no dead groups
228 bool mock_state = false;
230 if (!u->t) {
231 /* No state, but we cannot just back out - we might
232 * have passed earlier, only assuming some stones are
233 * dead, and then re-connected, only to lose counting
234 * when all stones are assumed alive. */
235 uct_prepare_move(u, b, S_BLACK); assert(u->t);
236 mock_state = true;
238 /* Make sure the ownermap is well-seeded. */
239 while (u->ownermap.playouts < GJ_MINGAMES)
240 uct_playout(u, b, S_BLACK, u->t);
241 /* Show the ownermap: */
242 if (DEBUGL(2))
243 board_print_custom(b, stderr, uct_printhook_ownermap);
245 dead_group_list(u, b, mq);
247 if (mock_state) {
248 /* Clean up the mock state in case we will receive
249 * a genmove; we could get a non-alternating-move
250 * error from uct_prepare_move() in that case otherwise. */
251 reset_state(u);
255 static void
256 playout_policy_done(struct playout_policy *p)
258 if (p->done) p->done(p);
259 if (p->data) free(p->data);
260 free(p);
263 static void
264 uct_done(struct engine *e)
266 /* This is called on engine reset, especially when clear_board
267 * is received and new game should begin. */
268 struct uct *u = e->data;
269 uct_pondering_stop(u);
270 if (u->t) reset_state(u);
271 free(u->ownermap.map);
273 free(u->policy);
274 free(u->random_policy);
275 playout_policy_done(u->playout);
276 uct_prior_done(u->prior);
277 joseki_done(u->jdict);
278 pluginset_done(u->plugins);
283 /* Run time-limited MCTS search on foreground. */
284 static int
285 uct_search(struct uct *u, struct board *b, struct time_info *ti, enum stone color, struct tree *t)
287 struct uct_search_state s;
288 uct_search_start(u, b, color, t, ti, &s);
289 if (UDEBUGL(2) && s.base_playouts > 0)
290 fprintf(stderr, "<pre-simulated %d games>\n", s.base_playouts);
292 /* The search tree is ctx->t. This is currently == . It is important
293 * to reference ctx->t directly since the
294 * thread manager will swap the tree pointer asynchronously. */
296 /* Now, just periodically poll the search tree. */
297 while (1) {
298 time_sleep(TREE_BUSYWAIT_INTERVAL);
299 /* TREE_BUSYWAIT_INTERVAL should never be less than desired time, or the
300 * time control is broken. But if it happens to be less, we still search
301 * at least 100ms otherwise the move is completely random. */
303 int i = uct_search_games(&s);
304 /* Print notifications etc. */
305 uct_search_progress(u, b, color, t, ti, &s, i);
306 /* Check if we should stop the search. */
307 if (uct_search_check_stop(u, b, color, t, ti, &s, i))
308 break;
311 struct uct_thread_ctx *ctx = uct_search_stop();
312 if (UDEBUGL(2)) tree_dump(t, u->dumpthres);
313 if (UDEBUGL(2))
314 fprintf(stderr, "(avg score %f/%d value %f/%d)\n",
315 u->dynkomi->score.value, u->dynkomi->score.playouts,
316 u->dynkomi->value.value, u->dynkomi->value.playouts);
317 if (UDEBUGL(0))
318 uct_progress_status(u, t, color, ctx->games);
320 u->played_own += ctx->games;
321 return ctx->games;
324 /* Start pondering background with @color to play. */
325 static void
326 uct_pondering_start(struct uct *u, struct board *b0, struct tree *t, enum stone color)
328 if (UDEBUGL(1))
329 fprintf(stderr, "Starting to ponder with color %s\n", stone2str(stone_other(color)));
330 u->pondering = true;
332 /* We need a local board copy to ponder upon. */
333 struct board *b = malloc2(sizeof(*b)); board_copy(b, b0);
335 /* *b0 did not have the genmove'd move played yet. */
336 struct move m = { t->root->coord, t->root_color };
337 int res = board_play(b, &m);
338 assert(res >= 0);
339 setup_dynkomi(u, b, stone_other(m.color));
341 /* Start MCTS manager thread "headless". */
342 static struct uct_search_state s;
343 uct_search_start(u, b, color, t, NULL, &s);
346 /* uct_search_stop() frontend for the pondering (non-genmove) mode, and
347 * to stop the background search for a slave in the distributed engine. */
348 void
349 uct_pondering_stop(struct uct *u)
351 if (!thread_manager_running)
352 return;
354 /* Stop the thread manager. */
355 struct uct_thread_ctx *ctx = uct_search_stop();
356 if (UDEBUGL(1)) {
357 if (u->pondering) fprintf(stderr, "(pondering) ");
358 uct_progress_status(u, ctx->t, ctx->color, ctx->games);
360 if (u->pondering) {
361 free(ctx->b);
362 u->pondering = false;
367 void
368 uct_genmove_setup(struct uct *u, struct board *b, enum stone color)
370 if (b->superko_violation) {
371 fprintf(stderr, "!!! WARNING: SUPERKO VIOLATION OCCURED BEFORE THIS MOVE\n");
372 fprintf(stderr, "Maybe you play with situational instead of positional superko?\n");
373 fprintf(stderr, "I'm going to ignore the violation, but note that I may miss\n");
374 fprintf(stderr, "some moves valid under this ruleset because of this.\n");
375 b->superko_violation = false;
378 uct_prepare_move(u, b, color);
380 assert(u->t);
381 u->my_color = color;
383 /* How to decide whether to use dynkomi in this game? Since we use
384 * pondering, it's not simple "who-to-play" matter. Decide based on
385 * the last genmove issued. */
386 u->t->use_extra_komi = !!(u->dynkomi_mask & color);
387 /* Moreover, we do not use extra komi at the game end - we are not
388 * to fool ourselves at this point. */
389 if (board_estimated_moves_left(b) <= MIN_MOVES_LEFT)
390 u->t->use_extra_komi = false;
391 setup_dynkomi(u, b, color);
393 if (b->rules == RULES_JAPANESE)
394 u->territory_scoring = true;
396 /* Make pessimistic assumption about komi for Japanese rules to
397 * avoid losing by 0.5 when winning by 0.5 with Chinese rules.
398 * The rules usually give the same winner if the integer part of komi
399 * is odd so we adjust the komi only if it is even (for a board of
400 * odd size). We are not trying to get an exact evaluation for rare
401 * cases of seki. For details see http://home.snafu.de/jasiek/parity.html */
402 if (u->territory_scoring && (((int)floor(b->komi) + board_size(b)) & 1)) {
403 b->komi += (color == S_BLACK ? 1.0 : -1.0);
404 if (UDEBUGL(0))
405 fprintf(stderr, "Setting komi to %.1f assuming Japanese rules\n",
406 b->komi);
410 static coord_t *
411 uct_genmove(struct engine *e, struct board *b, struct time_info *ti, enum stone color, bool pass_all_alive)
413 double start_time = time_now();
414 struct uct *u = e->data;
415 uct_pondering_stop(u);
416 uct_genmove_setup(u, b, color);
418 /* Start the Monte Carlo Tree Search! */
419 int base_playouts = u->t->root->u.playouts;
420 int played_games = uct_search(u, b, ti, color, u->t);
422 coord_t best_coord;
423 struct tree_node *best;
424 best = uct_search_result(u, b, color, pass_all_alive, played_games, base_playouts, &best_coord);
426 if (UDEBUGL(2)) {
427 double time = time_now() - start_time + 0.000001; /* avoid divide by zero */
428 fprintf(stderr, "genmove in %0.2fs (%d games/s, %d games/s/thread)\n",
429 time, (int)(played_games/time), (int)(played_games/time/u->threads));
432 if (!best) {
433 /* Pass or resign. */
434 reset_state(u);
435 return coord_copy(best_coord);
437 tree_promote_node(u->t, &best);
439 /* After a pass, pondering is harmful for two reasons:
440 * (i) We might keep pondering even when the game is over.
441 * Of course this is the case for opponent resign as well.
442 * (ii) More importantly, the ownermap will get skewed since
443 * the UCT will start cutting off any playouts. */
444 if (u->pondering_opt && !is_pass(best->coord)) {
445 uct_pondering_start(u, b, u->t, stone_other(color));
447 return coord_copy(best_coord);
451 bool
452 uct_genbook(struct engine *e, struct board *b, struct time_info *ti, enum stone color)
454 struct uct *u = e->data;
455 if (!u->t) uct_prepare_move(u, b, color);
456 assert(u->t);
458 if (ti->dim == TD_GAMES) {
459 /* Don't count in games that already went into the book. */
460 ti->len.games += u->t->root->u.playouts;
462 uct_search(u, b, ti, color, u->t);
464 assert(ti->dim == TD_GAMES);
465 tree_save(u->t, b, ti->len.games / 100);
467 return true;
470 void
471 uct_dumpbook(struct engine *e, struct board *b, enum stone color)
473 struct uct *u = e->data;
474 struct tree *t = tree_init(b, color, u->fast_alloc ? u->max_tree_size : 0,
475 u->max_pruned_size, u->pruning_threshold, u->local_tree_aging, 0);
476 tree_load(t, b);
477 tree_dump(t, 0);
478 tree_done(t);
482 float
483 uct_evaluate(struct engine *e, struct board *b, struct time_info *ti, coord_t c, enum stone color)
485 struct uct *u = e->data;
487 struct board b2;
488 board_copy(&b2, b);
489 struct move m = { c, color };
490 int res = board_play(&b2, &m);
491 if (res < 0)
492 return NAN;
493 color = stone_other(color);
495 if (u->t) reset_state(u);
496 uct_prepare_move(u, &b2, color);
497 assert(u->t);
499 float bestval;
500 uct_search(u, &b2, ti, color, u->t);
501 struct tree_node *best = u->policy->choose(u->policy, u->t->root, &b2, color, resign);
502 if (!best) {
503 bestval = NAN; // the opponent has no reply!
504 } else {
505 bestval = tree_node_get_value(u->t, 1, best->u.value);
508 reset_state(u); // clean our junk
510 return isnan(bestval) ? NAN : 1.0f - bestval;
514 struct uct *
515 uct_state_init(char *arg, struct board *b)
517 struct uct *u = calloc2(1, sizeof(struct uct));
518 bool using_elo = false;
520 u->debug_level = debug_level;
521 u->gamelen = MC_GAMELEN;
522 u->resign_threshold = 0.2;
523 u->sure_win_threshold = 0.85;
524 u->mercymin = 0;
525 u->expand_p = 2;
526 u->dumpthres = 1000;
527 u->playout_amaf = true;
528 u->playout_amaf_nakade = false;
529 u->amaf_prior = false;
530 u->max_tree_size = 3072ULL * 1048576;
531 u->pruning_threshold = 0;
533 u->threads = 1;
534 u->thread_model = TM_TREEVL;
535 u->virtual_loss = true;
537 u->fuseki_end = 20; // max time at 361*20% = 72 moves (our 36th move, still 99 to play)
538 u->yose_start = 40; // (100-40-25)*361/100/2 = 63 moves still to play by us then
539 u->bestr_ratio = 0.02;
540 // 2.5 is clearly too much, but seems to compensate well for overly stern time allocations.
541 // TODO: Further tuning and experiments with better time allocation schemes.
542 u->best2_ratio = 2.5;
544 u->val_scale = 0.04; u->val_points = 40;
545 u->dynkomi_interval = 1000;
546 u->dynkomi_mask = S_BLACK | S_WHITE;
548 u->tenuki_d = 4;
549 u->local_tree_aging = 2;
551 u->plugins = pluginset_init(b);
553 u->jdict = joseki_load(b->size);
555 if (arg) {
556 char *optspec, *next = arg;
557 while (*next) {
558 optspec = next;
559 next += strcspn(next, ",");
560 if (*next) { *next++ = 0; } else { *next = 0; }
562 char *optname = optspec;
563 char *optval = strchr(optspec, '=');
564 if (optval) *optval++ = 0;
566 /** Basic options */
568 if (!strcasecmp(optname, "debug")) {
569 if (optval)
570 u->debug_level = atoi(optval);
571 else
572 u->debug_level++;
573 } else if (!strcasecmp(optname, "dumpthres") && optval) {
574 /* When dumping the UCT tree on output, include
575 * nodes with at least this many playouts.
576 * (This value is re-scaled "intelligently"
577 * in case of very large trees.) */
578 u->dumpthres = atoi(optval);
579 } else if (!strcasecmp(optname, "resign_threshold") && optval) {
580 /* Resign when this ratio of games is lost
581 * after GJ_MINGAMES sample is taken. */
582 u->resign_threshold = atof(optval);
583 } else if (!strcasecmp(optname, "sure_win_threshold") && optval) {
584 /* Stop reading when this ratio of games is won
585 * after PLAYOUT_EARLY_BREAK_MIN sample is
586 * taken. (Prevents stupid time losses,
587 * friendly to human opponents.) */
588 u->sure_win_threshold = atof(optval);
589 } else if (!strcasecmp(optname, "force_seed") && optval) {
590 /* Set RNG seed at the tree setup. */
591 u->force_seed = atoi(optval);
592 } else if (!strcasecmp(optname, "no_book")) {
593 /* Disable UCT opening book. */
594 u->no_book = true;
595 } else if (!strcasecmp(optname, "pass_all_alive")) {
596 /* Whether to consider passing only after all
597 * dead groups were removed from the board;
598 * this is like all genmoves are in fact
599 * kgs-genmove_cleanup. */
600 u->pass_all_alive = !optval || atoi(optval);
601 } else if (!strcasecmp(optname, "territory_scoring")) {
602 /* Use territory scoring (default is area scoring).
603 * An explicit kgs-rules command overrides this. */
604 u->territory_scoring = !optval || atoi(optval);
605 } else if (!strcasecmp(optname, "banner") && optval) {
606 /* Additional banner string. This must come as the
607 * last engine parameter. */
608 if (*next) *--next = ',';
609 u->banner = strdup(optval);
610 break;
611 } else if (!strcasecmp(optname, "plugin") && optval) {
612 /* Load an external plugin; filename goes before the colon,
613 * extra arguments after the colon. */
614 char *pluginarg = strchr(optval, ':');
615 if (pluginarg)
616 *pluginarg++ = 0;
617 plugin_load(u->plugins, optval, pluginarg);
619 /** UCT behavior and policies */
621 } else if ((!strcasecmp(optname, "policy")
622 /* Node selection policy. ucb1amaf is the
623 * default policy implementing RAVE, while
624 * ucb1 is the simple exploration/exploitation
625 * policy. Policies can take further extra
626 * options. */
627 || !strcasecmp(optname, "random_policy")) && optval) {
628 /* A policy to be used randomly with small
629 * chance instead of the default policy. */
630 char *policyarg = strchr(optval, ':');
631 struct uct_policy **p = !strcasecmp(optname, "policy") ? &u->policy : &u->random_policy;
632 if (policyarg)
633 *policyarg++ = 0;
634 if (!strcasecmp(optval, "ucb1")) {
635 *p = policy_ucb1_init(u, policyarg);
636 } else if (!strcasecmp(optval, "ucb1amaf")) {
637 *p = policy_ucb1amaf_init(u, policyarg);
638 } else {
639 fprintf(stderr, "UCT: Invalid tree policy %s\n", optval);
640 exit(1);
642 } else if (!strcasecmp(optname, "playout") && optval) {
643 /* Random simulation (playout) policy.
644 * moggy is the default policy with large
645 * amount of domain-specific knowledge and
646 * heuristics. light is a simple uniformly
647 * random move selection policy. */
648 char *playoutarg = strchr(optval, ':');
649 if (playoutarg)
650 *playoutarg++ = 0;
651 if (!strcasecmp(optval, "moggy")) {
652 u->playout = playout_moggy_init(playoutarg, b, u->jdict);
653 } else if (!strcasecmp(optval, "light")) {
654 u->playout = playout_light_init(playoutarg, b);
655 } else if (!strcasecmp(optval, "elo")) {
656 u->playout = playout_elo_init(playoutarg, b);
657 using_elo = true;
658 } else {
659 fprintf(stderr, "UCT: Invalid playout policy %s\n", optval);
660 exit(1);
662 } else if (!strcasecmp(optname, "prior") && optval) {
663 /* Node priors policy. When expanding a node,
664 * it will seed node values heuristically
665 * (most importantly, based on playout policy
666 * opinion, but also with regard to other
667 * things). See uct/prior.c for details.
668 * Use prior=eqex=0 to disable priors. */
669 u->prior = uct_prior_init(optval, b);
670 } else if (!strcasecmp(optname, "mercy") && optval) {
671 /* Minimal difference of black/white captures
672 * to stop playout - "Mercy Rule". Speeds up
673 * hopeless playouts at the expense of some
674 * accuracy. */
675 u->mercymin = atoi(optval);
676 } else if (!strcasecmp(optname, "gamelen") && optval) {
677 /* Maximum length of single simulation
678 * in moves. */
679 u->gamelen = atoi(optval);
680 } else if (!strcasecmp(optname, "expand_p") && optval) {
681 /* Expand UCT nodes after it has been
682 * visited this many times. */
683 u->expand_p = atoi(optval);
684 } else if (!strcasecmp(optname, "random_policy_chance") && optval) {
685 /* If specified (N), with probability 1/N, random_policy policy
686 * descend is used instead of main policy descend; useful
687 * if specified policy (e.g. UCB1AMAF) can make unduly biased
688 * choices sometimes, you can fall back to e.g.
689 * random_policy=UCB1. */
690 u->random_policy_chance = atoi(optval);
692 /** General AMAF behavior */
693 /* (Only relevant if the policy supports AMAF.
694 * More variables can be tuned as policy
695 * parameters.) */
697 } else if (!strcasecmp(optname, "playout_amaf")) {
698 /* Whether to include random playout moves in
699 * AMAF as well. (Otherwise, only tree moves
700 * are included in AMAF. Of course makes sense
701 * only in connection with an AMAF policy.) */
702 /* with-without: 55.5% (+-4.1) */
703 if (optval && *optval == '0')
704 u->playout_amaf = false;
705 else
706 u->playout_amaf = true;
707 } else if (!strcasecmp(optname, "playout_amaf_nakade")) {
708 /* Whether to include nakade moves from playouts
709 * in the AMAF statistics; this tends to nullify
710 * the playout_amaf effect by adding too much
711 * noise. */
712 if (optval && *optval == '0')
713 u->playout_amaf_nakade = false;
714 else
715 u->playout_amaf_nakade = true;
716 } else if (!strcasecmp(optname, "playout_amaf_cutoff") && optval) {
717 /* Keep only first N% of playout stage AMAF
718 * information. */
719 u->playout_amaf_cutoff = atoi(optval);
720 } else if (!strcasecmp(optname, "amaf_prior") && optval) {
721 /* In node policy, consider prior values
722 * part of the real result term or part
723 * of the AMAF term? */
724 u->amaf_prior = atoi(optval);
726 /** Performance and memory management */
728 } else if (!strcasecmp(optname, "threads") && optval) {
729 /* By default, Pachi will run with only single
730 * tree search thread! */
731 u->threads = atoi(optval);
732 } else if (!strcasecmp(optname, "thread_model") && optval) {
733 if (!strcasecmp(optval, "tree")) {
734 /* Tree parallelization - all threads
735 * grind on the same tree. */
736 u->thread_model = TM_TREE;
737 u->virtual_loss = false;
738 } else if (!strcasecmp(optval, "treevl")) {
739 /* Tree parallelization, but also
740 * with virtual losses - this discou-
741 * rages most threads choosing the
742 * same tree branches to read. */
743 u->thread_model = TM_TREEVL;
744 u->virtual_loss = true;
745 } else {
746 fprintf(stderr, "UCT: Invalid thread model %s\n", optval);
747 exit(1);
749 } else if (!strcasecmp(optname, "pondering")) {
750 /* Keep searching even during opponent's turn. */
751 u->pondering_opt = !optval || atoi(optval);
752 } else if (!strcasecmp(optname, "max_tree_size") && optval) {
753 /* Maximum amount of memory [MiB] consumed by the move tree.
754 * For fast_alloc it includes the temp tree used for pruning.
755 * Default is 3072 (3 GiB). */
756 u->max_tree_size = atol(optval) * 1048576;
757 } else if (!strcasecmp(optname, "fast_alloc")) {
758 u->fast_alloc = !optval || atoi(optval);
759 } else if (!strcasecmp(optname, "pruning_threshold") && optval) {
760 /* Force pruning at beginning of a move if the tree consumes
761 * more than this [MiB]. Default is 10% of max_tree_size.
762 * Increase to reduce pruning time overhead if memory is plentiful.
763 * This option is meaningful only for fast_alloc. */
764 u->pruning_threshold = atol(optval) * 1048576;
766 /** Time control */
768 } else if (!strcasecmp(optname, "best2_ratio") && optval) {
769 /* If set, prolong simulating while
770 * first_best/second_best playouts ratio
771 * is less than best2_ratio. */
772 u->best2_ratio = atof(optval);
773 } else if (!strcasecmp(optname, "bestr_ratio") && optval) {
774 /* If set, prolong simulating while
775 * best,best_best_child values delta
776 * is more than bestr_ratio. */
777 u->bestr_ratio = atof(optval);
778 } else if (!strcasecmp(optname, "fuseki_end") && optval) {
779 /* At the very beginning it's not worth thinking
780 * too long because the playout evaluations are
781 * very noisy. So gradually increase the thinking
782 * time up to maximum when fuseki_end percent
783 * of the board has been played.
784 * This only applies if we are not in byoyomi. */
785 u->fuseki_end = atoi(optval);
786 } else if (!strcasecmp(optname, "yose_start") && optval) {
787 /* When yose_start percent of the board has been
788 * played, or if we are in byoyomi, stop spending
789 * more time and spread the remaining time
790 * uniformly.
791 * Between fuseki_end and yose_start, we spend
792 * a constant proportion of the remaining time
793 * on each move. (yose_start should actually
794 * be much earlier than when real yose start,
795 * but "yose" is a good short name to convey
796 * the idea.) */
797 u->yose_start = atoi(optval);
799 /** Dynamic komi */
801 } else if (!strcasecmp(optname, "dynkomi") && optval) {
802 /* Dynamic komi approach; there are multiple
803 * ways to adjust komi dynamically throughout
804 * play. We currently support two: */
805 char *dynkomiarg = strchr(optval, ':');
806 if (dynkomiarg)
807 *dynkomiarg++ = 0;
808 if (!strcasecmp(optval, "none")) {
809 u->dynkomi = uct_dynkomi_init_none(u, dynkomiarg, b);
810 } else if (!strcasecmp(optval, "linear")) {
811 /* You should set dynkomi_mask=1
812 * since this doesn't work well
813 * for white handicaps! */
814 u->dynkomi = uct_dynkomi_init_linear(u, dynkomiarg, b);
815 } else if (!strcasecmp(optval, "adaptive")) {
816 /* There are many more knobs to
817 * crank - see uct/dynkomi.c. */
818 u->dynkomi = uct_dynkomi_init_adaptive(u, dynkomiarg, b);
819 } else {
820 fprintf(stderr, "UCT: Invalid dynkomi mode %s\n", optval);
821 exit(1);
823 } else if (!strcasecmp(optname, "dynkomi_mask") && optval) {
824 /* Bitmask of colors the player must be
825 * for dynkomi be applied; you may want
826 * to use dynkomi_mask=3 to allow dynkomi
827 * even in games where Pachi is white. */
828 u->dynkomi_mask = atoi(optval);
829 } else if (!strcasecmp(optname, "dynkomi_interval") && optval) {
830 /* If non-zero, re-adjust dynamic komi
831 * throughout a single genmove reading,
832 * roughly every N simulations. */
833 /* XXX: Does not work with tree
834 * parallelization. */
835 u->dynkomi_interval = atoi(optval);
837 /** Node value result scaling */
839 } else if (!strcasecmp(optname, "val_scale") && optval) {
840 /* How much of the game result value should be
841 * influenced by win size. Zero means it isn't. */
842 u->val_scale = atof(optval);
843 } else if (!strcasecmp(optname, "val_points") && optval) {
844 /* Maximum size of win to be scaled into game
845 * result value. Zero means boardsize^2. */
846 u->val_points = atoi(optval) * 2; // result values are doubled
847 } else if (!strcasecmp(optname, "val_extra")) {
848 /* If false, the score coefficient will be simply
849 * added to the value, instead of scaling the result
850 * coefficient because of it. */
851 u->val_extra = !optval || atoi(optval);
853 /** Local trees */
854 /* (Purely experimental. Does not work - yet!) */
856 } else if (!strcasecmp(optname, "local_tree") && optval) {
857 /* Whether to bias exploration by local tree values
858 * (must be supported by the used policy).
859 * 0: Don't.
860 * 1: Do, value = result.
861 * Try to temper the result:
862 * 2: Do, value = 0.5+(result-expected)/2.
863 * 3: Do, value = 0.5+bzz((result-expected)^2).
864 * 4: Do, value = 0.5+sqrt(result-expected)/2. */
865 u->local_tree = atoi(optval);
866 } else if (!strcasecmp(optname, "tenuki_d") && optval) {
867 /* Tenuki distance at which to break the local tree. */
868 u->tenuki_d = atoi(optval);
869 if (u->tenuki_d > TREE_NODE_D_MAX + 1) {
870 fprintf(stderr, "uct: tenuki_d must not be larger than TREE_NODE_D_MAX+1 %d\n", TREE_NODE_D_MAX + 1);
871 exit(1);
873 } else if (!strcasecmp(optname, "local_tree_aging") && optval) {
874 /* How much to reduce local tree values between moves. */
875 u->local_tree_aging = atof(optval);
876 } else if (!strcasecmp(optname, "local_tree_allseq")) {
877 /* By default, only complete sequences are stored
878 * in the local tree. If this is on, also
879 * subsequences starting at each move are stored. */
880 u->local_tree_allseq = !optval || atoi(optval);
881 } else if (!strcasecmp(optname, "local_tree_playout")) {
882 /* Whether to adjust ELO playout probability
883 * distributions according to matched localtree
884 * information. */
885 u->local_tree_playout = !optval || atoi(optval);
886 } else if (!strcasecmp(optname, "local_tree_pseqroot")) {
887 /* By default, when we have no sequence move
888 * to suggest in-playout, we give up. If this
889 * is on, we make probability distribution from
890 * sequences first moves instead. */
891 u->local_tree_pseqroot = !optval || atoi(optval);
893 /** Distributed engine slaves setup */
895 } else if (!strcasecmp(optname, "slave")) {
896 /* Act as slave for the distributed engine. */
897 u->slave = !optval || atoi(optval);
898 } else if (!strcasecmp(optname, "shared_nodes") && optval) {
899 /* Share at most shared_nodes between master and slave at each genmoves.
900 * Must use the same value in master and slaves. */
901 u->shared_nodes = atoi(optval);
902 } else if (!strcasecmp(optname, "shared_levels") && optval) {
903 /* Share only nodes of level <= shared_levels. */
904 u->shared_levels = atoi(optval);
905 } else if (!strcasecmp(optname, "stats_hbits") && optval) {
906 /* Set hash table size to 2^stats_hbits for the shared stats. */
907 u->stats_hbits = atoi(optval);
909 } else {
910 fprintf(stderr, "uct: Invalid engine argument %s or missing value\n", optname);
911 exit(1);
916 if (!u->policy)
917 u->policy = policy_ucb1amaf_init(u, NULL);
919 if (!!u->random_policy_chance ^ !!u->random_policy) {
920 fprintf(stderr, "uct: Only one of random_policy and random_policy_chance is set\n");
921 exit(1);
924 if (!u->local_tree) {
925 /* No ltree aging. */
926 u->local_tree_aging = 1.0f;
928 if (!using_elo)
929 u->local_tree_playout = false;
931 if (u->fast_alloc) {
932 if (u->pruning_threshold < u->max_tree_size / 10)
933 u->pruning_threshold = u->max_tree_size / 10;
934 if (u->pruning_threshold > u->max_tree_size / 2)
935 u->pruning_threshold = u->max_tree_size / 2;
937 /* Limit pruning temp space to 20% of memory. Beyond this we discard
938 * the nodes and recompute them at the next move if necessary. */
939 u->max_pruned_size = u->max_tree_size / 5;
940 u->max_tree_size -= u->max_pruned_size;
941 } else {
942 /* Reserve 5% memory in case the background free() are slower
943 * than the concurrent allocations. */
944 u->max_tree_size -= u->max_tree_size / 20;
947 if (!u->prior)
948 u->prior = uct_prior_init(NULL, b);
950 if (!u->playout)
951 u->playout = playout_moggy_init(NULL, b, u->jdict);
952 if (!u->playout->debug_level)
953 u->playout->debug_level = u->debug_level;
955 u->ownermap.map = malloc2(board_size2(b) * sizeof(u->ownermap.map[0]));
957 if (u->slave) {
958 if (!u->stats_hbits) u->stats_hbits = DEFAULT_STATS_HBITS;
959 if (!u->shared_nodes) u->shared_nodes = DEFAULT_SHARED_NODES;
960 assert(u->shared_levels * board_bits2(b) <= 8 * (int)sizeof(path_t));
963 if (!u->dynkomi)
964 u->dynkomi = uct_dynkomi_init_adaptive(u, NULL, b);
966 /* Some things remain uninitialized for now - the opening book
967 * is not loaded and the tree not set up. */
968 /* This will be initialized in setup_state() at the first move
969 * received/requested. This is because right now we are not aware
970 * about any komi or handicap setup and such. */
972 return u;
975 struct engine *
976 engine_uct_init(char *arg, struct board *b)
978 struct uct *u = uct_state_init(arg, b);
979 struct engine *e = calloc2(1, sizeof(struct engine));
980 e->name = "UCT Engine";
981 e->printhook = uct_printhook_ownermap;
982 e->notify_play = uct_notify_play;
983 e->chat = uct_chat;
984 e->result = uct_result;
985 e->genmove = uct_genmove;
986 e->genmoves = uct_genmoves;
987 e->dead_group_list = uct_dead_group_list;
988 e->done = uct_done;
989 e->data = u;
990 if (u->slave)
991 e->notify = uct_notify;
993 const char banner[] = "I'm playing UCT. When I'm losing, I will resign, "
994 "if I think I win, I play until you pass. "
995 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
996 if (!u->banner) u->banner = "";
997 e->comment = malloc2(sizeof(banner) + strlen(u->banner) + 1);
998 sprintf(e->comment, "%s %s", banner, u->banner);
1000 return e;