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