Revert "uct_genmove(): In case of json reporting, print a JSON final_decision message"
[pachi.git] / uct / uct.c
blobd3a74348dfec09d40096321af4f30a61bfb60967
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)
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 uct_progress_status(u, t, color, ctx->games, true);
335 u->played_own += ctx->games;
336 return ctx->games;
339 /* Start pondering background with @color to play. */
340 static void
341 uct_pondering_start(struct uct *u, struct board *b0, struct tree *t, enum stone color)
343 if (UDEBUGL(1))
344 fprintf(stderr, "Starting to ponder with color %s\n", stone2str(stone_other(color)));
345 u->pondering = true;
347 /* We need a local board copy to ponder upon. */
348 struct board *b = malloc2(sizeof(*b)); board_copy(b, b0);
350 /* *b0 did not have the genmove'd move played yet. */
351 struct move m = { node_coord(t->root), t->root_color };
352 int res = board_play(b, &m);
353 assert(res >= 0);
354 setup_dynkomi(u, b, stone_other(m.color));
356 /* Start MCTS manager thread "headless". */
357 static struct uct_search_state s;
358 uct_search_start(u, b, color, t, NULL, &s);
361 /* uct_search_stop() frontend for the pondering (non-genmove) mode, and
362 * to stop the background search for a slave in the distributed engine. */
363 void
364 uct_pondering_stop(struct uct *u)
366 if (!thread_manager_running)
367 return;
369 /* Stop the thread manager. */
370 struct uct_thread_ctx *ctx = uct_search_stop();
371 if (UDEBUGL(1)) {
372 if (u->pondering) fprintf(stderr, "(pondering) ");
373 uct_progress_status(u, ctx->t, ctx->color, ctx->games, true);
375 if (u->pondering) {
376 free(ctx->b);
377 u->pondering = false;
382 void
383 uct_genmove_setup(struct uct *u, struct board *b, enum stone color)
385 if (b->superko_violation) {
386 fprintf(stderr, "!!! WARNING: SUPERKO VIOLATION OCCURED BEFORE THIS MOVE\n");
387 fprintf(stderr, "Maybe you play with situational instead of positional superko?\n");
388 fprintf(stderr, "I'm going to ignore the violation, but note that I may miss\n");
389 fprintf(stderr, "some moves valid under this ruleset because of this.\n");
390 b->superko_violation = false;
393 uct_prepare_move(u, b, color);
395 assert(u->t);
396 u->my_color = color;
398 /* How to decide whether to use dynkomi in this game? Since we use
399 * pondering, it's not simple "who-to-play" matter. Decide based on
400 * the last genmove issued. */
401 u->t->use_extra_komi = !!(u->dynkomi_mask & color);
402 setup_dynkomi(u, b, color);
404 if (b->rules == RULES_JAPANESE)
405 u->territory_scoring = true;
407 /* Make pessimistic assumption about komi for Japanese rules to
408 * avoid losing by 0.5 when winning by 0.5 with Chinese rules.
409 * The rules usually give the same winner if the integer part of komi
410 * is odd so we adjust the komi only if it is even (for a board of
411 * odd size). We are not trying to get an exact evaluation for rare
412 * cases of seki. For details see http://home.snafu.de/jasiek/parity.html */
413 if (u->territory_scoring && (((int)floor(b->komi) + board_size(b)) & 1)) {
414 b->komi += (color == S_BLACK ? 1.0 : -1.0);
415 if (UDEBUGL(0))
416 fprintf(stderr, "Setting komi to %.1f assuming Japanese rules\n",
417 b->komi);
421 static coord_t *
422 uct_genmove(struct engine *e, struct board *b, struct time_info *ti, enum stone color, bool pass_all_alive)
424 double start_time = time_now();
425 struct uct *u = e->data;
426 u->pass_all_alive |= pass_all_alive;
427 uct_pondering_stop(u);
428 uct_genmove_setup(u, b, color);
430 /* Start the Monte Carlo Tree Search! */
431 int base_playouts = u->t->root->u.playouts;
432 int played_games = uct_search(u, b, ti, color, u->t);
434 coord_t best_coord;
435 struct tree_node *best;
436 best = uct_search_result(u, b, color, u->pass_all_alive, played_games, base_playouts, &best_coord);
438 if (UDEBUGL(2)) {
439 double time = time_now() - start_time + 0.000001; /* avoid divide by zero */
440 fprintf(stderr, "genmove in %0.2fs (%d games/s, %d games/s/thread)\n",
441 time, (int)(played_games/time), (int)(played_games/time/u->threads));
444 if (!best) {
445 /* Pass or resign. */
446 reset_state(u);
447 return coord_copy(best_coord);
449 tree_promote_node(u->t, &best);
451 /* After a pass, pondering is harmful for two reasons:
452 * (i) We might keep pondering even when the game is over.
453 * Of course this is the case for opponent resign as well.
454 * (ii) More importantly, the ownermap will get skewed since
455 * the UCT will start cutting off any playouts. */
456 if (u->pondering_opt && !is_pass(node_coord(best))) {
457 uct_pondering_start(u, b, u->t, stone_other(color));
459 return coord_copy(best_coord);
463 bool
464 uct_gentbook(struct engine *e, struct board *b, struct time_info *ti, enum stone color)
466 struct uct *u = e->data;
467 if (!u->t) uct_prepare_move(u, b, color);
468 assert(u->t);
470 if (ti->dim == TD_GAMES) {
471 /* Don't count in games that already went into the tbook. */
472 ti->len.games += u->t->root->u.playouts;
474 uct_search(u, b, ti, color, u->t);
476 assert(ti->dim == TD_GAMES);
477 tree_save(u->t, b, ti->len.games / 100);
479 return true;
482 void
483 uct_dumptbook(struct engine *e, struct board *b, enum stone color)
485 struct uct *u = e->data;
486 struct tree *t = tree_init(b, color, u->fast_alloc ? u->max_tree_size : 0,
487 u->max_pruned_size, u->pruning_threshold, u->local_tree_aging, 0);
488 tree_load(t, b);
489 tree_dump(t, 0);
490 tree_done(t);
494 floating_t
495 uct_evaluate_one(struct engine *e, struct board *b, struct time_info *ti, coord_t c, enum stone color)
497 struct uct *u = e->data;
499 struct board b2;
500 board_copy(&b2, b);
501 struct move m = { c, color };
502 int res = board_play(&b2, &m);
503 if (res < 0)
504 return NAN;
505 color = stone_other(color);
507 if (u->t) reset_state(u);
508 uct_prepare_move(u, &b2, color);
509 assert(u->t);
511 floating_t bestval;
512 uct_search(u, &b2, ti, color, u->t);
513 struct tree_node *best = u->policy->choose(u->policy, u->t->root, &b2, color, resign);
514 if (!best) {
515 bestval = NAN; // the opponent has no reply!
516 } else {
517 bestval = tree_node_get_value(u->t, 1, best->u.value);
520 reset_state(u); // clean our junk
522 return isnan(bestval) ? NAN : 1.0f - bestval;
525 void
526 uct_evaluate(struct engine *e, struct board *b, struct time_info *ti, floating_t *vals, enum stone color)
528 for (int i = 0; i < b->flen; i++) {
529 if (is_pass(b->f[i]))
530 vals[i] = NAN;
531 else
532 vals[i] = uct_evaluate_one(e, b, ti, b->f[i], color);
537 struct uct *
538 uct_state_init(char *arg, struct board *b)
540 struct uct *u = calloc2(1, sizeof(struct uct));
541 bool pat_setup = false;
543 u->debug_level = debug_level;
544 u->reportfreq = 10000;
545 u->gamelen = MC_GAMELEN;
546 u->resign_threshold = 0.2;
547 u->sure_win_threshold = 0.9;
548 u->mercymin = 0;
549 u->significant_threshold = 50;
550 u->expand_p = 8;
551 u->dumpthres = 1000;
552 u->playout_amaf = true;
553 u->amaf_prior = false;
554 u->max_tree_size = 1408ULL * 1048576;
555 u->fast_alloc = true;
556 u->pruning_threshold = 0;
558 u->threads = 1;
559 u->thread_model = TM_TREEVL;
560 u->virtual_loss = 1;
562 u->fuseki_end = 20; // max time at 361*20% = 72 moves (our 36th move, still 99 to play)
563 u->yose_start = 40; // (100-40-25)*361/100/2 = 63 moves still to play by us then
564 u->bestr_ratio = 0.02;
565 // 2.5 is clearly too much, but seems to compensate well for overly stern time allocations.
566 // TODO: Further tuning and experiments with better time allocation schemes.
567 u->best2_ratio = 2.5;
568 u->max_maintime_ratio = 3.0;
570 u->val_scale = 0; u->val_points = 40;
571 u->dynkomi_interval = 1000;
572 u->dynkomi_mask = S_BLACK | S_WHITE;
574 u->tenuki_d = 4;
575 u->local_tree_aging = 80;
576 u->local_tree_depth_decay = 1.5;
577 u->local_tree_eval = LTE_ROOT;
578 u->local_tree_neival = true;
580 u->max_slaves = -1;
581 u->slave_index = -1;
582 u->stats_delay = 0.01; // 10 ms
584 u->plugins = pluginset_init(b);
586 u->jdict = joseki_load(b->size);
588 if (arg) {
589 char *optspec, *next = arg;
590 while (*next) {
591 optspec = next;
592 next += strcspn(next, ",");
593 if (*next) { *next++ = 0; } else { *next = 0; }
595 char *optname = optspec;
596 char *optval = strchr(optspec, '=');
597 if (optval) *optval++ = 0;
599 /** Basic options */
601 if (!strcasecmp(optname, "debug")) {
602 if (optval)
603 u->debug_level = atoi(optval);
604 else
605 u->debug_level++;
606 } else if (!strcasecmp(optname, "reporting") && optval) {
607 /* The format of output for detailed progress
608 * information (such as current best move and
609 * its value, etc.). */
610 if (!strcasecmp(optval, "text")) {
611 /* Plaintext traditional output. */
612 u->reporting = UR_TEXT;
613 } else if (!strcasecmp(optval, "json")) {
614 /* JSON output. Implies debug=0. */
615 u->reporting = UR_JSON;
616 u->debug_level = 0;
617 } else if (!strcasecmp(optval, "jsonbig")) {
618 /* JSON output, but much more detailed.
619 * Implies debug=0. */
620 u->reporting = UR_JSON_BIG;
621 u->debug_level = 0;
622 } else {
623 fprintf(stderr, "UCT: Invalid reporting format %s\n", optval);
624 exit(1);
626 } else if (!strcasecmp(optname, "reportfreq") && optval) {
627 /* The progress information line will be shown
628 * every <reportfreq> simulations. */
629 u->reportfreq = atoi(optval);
630 } else if (!strcasecmp(optname, "dumpthres") && optval) {
631 /* When dumping the UCT tree on output, include
632 * nodes with at least this many playouts.
633 * (This value is re-scaled "intelligently"
634 * in case of very large trees.) */
635 u->dumpthres = atoi(optval);
636 } else if (!strcasecmp(optname, "resign_threshold") && optval) {
637 /* Resign when this ratio of games is lost
638 * after GJ_MINGAMES sample is taken. */
639 u->resign_threshold = atof(optval);
640 } else if (!strcasecmp(optname, "sure_win_threshold") && optval) {
641 /* Stop reading when this ratio of games is won
642 * after PLAYOUT_EARLY_BREAK_MIN sample is
643 * taken. (Prevents stupid time losses,
644 * friendly to human opponents.) */
645 u->sure_win_threshold = atof(optval);
646 } else if (!strcasecmp(optname, "force_seed") && optval) {
647 /* Set RNG seed at the tree setup. */
648 u->force_seed = atoi(optval);
649 } else if (!strcasecmp(optname, "no_tbook")) {
650 /* Disable UCT opening tbook. */
651 u->no_tbook = true;
652 } else if (!strcasecmp(optname, "pass_all_alive")) {
653 /* Whether to consider passing only after all
654 * dead groups were removed from the board;
655 * this is like all genmoves are in fact
656 * kgs-genmove_cleanup. */
657 u->pass_all_alive = !optval || atoi(optval);
658 } else if (!strcasecmp(optname, "territory_scoring")) {
659 /* Use territory scoring (default is area scoring).
660 * An explicit kgs-rules command overrides this. */
661 u->territory_scoring = !optval || atoi(optval);
662 } else if (!strcasecmp(optname, "stones_only")) {
663 /* Do not count eyes. Nice to teach go to kids.
664 * http://strasbourg.jeudego.org/regle_strasbourgeoise.htm */
665 b->rules = RULES_STONES_ONLY;
666 u->pass_all_alive = true;
667 } else if (!strcasecmp(optname, "banner") && optval) {
668 /* Additional banner string. This must come as the
669 * last engine parameter. */
670 if (*next) *--next = ',';
671 u->banner = strdup(optval);
672 break;
673 } else if (!strcasecmp(optname, "plugin") && optval) {
674 /* Load an external plugin; filename goes before the colon,
675 * extra arguments after the colon. */
676 char *pluginarg = strchr(optval, ':');
677 if (pluginarg)
678 *pluginarg++ = 0;
679 plugin_load(u->plugins, optval, pluginarg);
681 /** UCT behavior and policies */
683 } else if ((!strcasecmp(optname, "policy")
684 /* Node selection policy. ucb1amaf is the
685 * default policy implementing RAVE, while
686 * ucb1 is the simple exploration/exploitation
687 * policy. Policies can take further extra
688 * options. */
689 || !strcasecmp(optname, "random_policy")) && optval) {
690 /* A policy to be used randomly with small
691 * chance instead of the default policy. */
692 char *policyarg = strchr(optval, ':');
693 struct uct_policy **p = !strcasecmp(optname, "policy") ? &u->policy : &u->random_policy;
694 if (policyarg)
695 *policyarg++ = 0;
696 if (!strcasecmp(optval, "ucb1")) {
697 *p = policy_ucb1_init(u, policyarg);
698 } else if (!strcasecmp(optval, "ucb1amaf")) {
699 *p = policy_ucb1amaf_init(u, policyarg, b);
700 } else {
701 fprintf(stderr, "UCT: Invalid tree policy %s\n", optval);
702 exit(1);
704 } else if (!strcasecmp(optname, "playout") && optval) {
705 /* Random simulation (playout) policy.
706 * moggy is the default policy with large
707 * amount of domain-specific knowledge and
708 * heuristics. light is a simple uniformly
709 * random move selection policy. */
710 char *playoutarg = strchr(optval, ':');
711 if (playoutarg)
712 *playoutarg++ = 0;
713 if (!strcasecmp(optval, "moggy")) {
714 u->playout = playout_moggy_init(playoutarg, b, u->jdict);
715 } else if (!strcasecmp(optval, "light")) {
716 u->playout = playout_light_init(playoutarg, b);
717 } else {
718 fprintf(stderr, "UCT: Invalid playout policy %s\n", optval);
719 exit(1);
721 } else if (!strcasecmp(optname, "prior") && optval) {
722 /* Node priors policy. When expanding a node,
723 * it will seed node values heuristically
724 * (most importantly, based on playout policy
725 * opinion, but also with regard to other
726 * things). See uct/prior.c for details.
727 * Use prior=eqex=0 to disable priors. */
728 u->prior = uct_prior_init(optval, b, u);
729 } else if (!strcasecmp(optname, "mercy") && optval) {
730 /* Minimal difference of black/white captures
731 * to stop playout - "Mercy Rule". Speeds up
732 * hopeless playouts at the expense of some
733 * accuracy. */
734 u->mercymin = atoi(optval);
735 } else if (!strcasecmp(optname, "gamelen") && optval) {
736 /* Maximum length of single simulation
737 * in moves. */
738 u->gamelen = atoi(optval);
739 } else if (!strcasecmp(optname, "expand_p") && optval) {
740 /* Expand UCT nodes after it has been
741 * visited this many times. */
742 u->expand_p = atoi(optval);
743 } else if (!strcasecmp(optname, "random_policy_chance") && optval) {
744 /* If specified (N), with probability 1/N, random_policy policy
745 * descend is used instead of main policy descend; useful
746 * if specified policy (e.g. UCB1AMAF) can make unduly biased
747 * choices sometimes, you can fall back to e.g.
748 * random_policy=UCB1. */
749 u->random_policy_chance = atoi(optval);
751 /** General AMAF behavior */
752 /* (Only relevant if the policy supports AMAF.
753 * More variables can be tuned as policy
754 * parameters.) */
756 } else if (!strcasecmp(optname, "playout_amaf")) {
757 /* Whether to include random playout moves in
758 * AMAF as well. (Otherwise, only tree moves
759 * are included in AMAF. Of course makes sense
760 * only in connection with an AMAF policy.) */
761 /* with-without: 55.5% (+-4.1) */
762 if (optval && *optval == '0')
763 u->playout_amaf = false;
764 else
765 u->playout_amaf = true;
766 } else if (!strcasecmp(optname, "playout_amaf_cutoff") && optval) {
767 /* Keep only first N% of playout stage AMAF
768 * information. */
769 u->playout_amaf_cutoff = atoi(optval);
770 } else if (!strcasecmp(optname, "amaf_prior") && optval) {
771 /* In node policy, consider prior values
772 * part of the real result term or part
773 * of the AMAF term? */
774 u->amaf_prior = atoi(optval);
776 /** Performance and memory management */
778 } else if (!strcasecmp(optname, "threads") && optval) {
779 /* By default, Pachi will run with only single
780 * tree search thread! */
781 u->threads = atoi(optval);
782 } else if (!strcasecmp(optname, "thread_model") && optval) {
783 if (!strcasecmp(optval, "tree")) {
784 /* Tree parallelization - all threads
785 * grind on the same tree. */
786 u->thread_model = TM_TREE;
787 u->virtual_loss = 0;
788 } else if (!strcasecmp(optval, "treevl")) {
789 /* Tree parallelization, but also
790 * with virtual losses - this discou-
791 * rages most threads choosing the
792 * same tree branches to read. */
793 u->thread_model = TM_TREEVL;
794 } else {
795 fprintf(stderr, "UCT: Invalid thread model %s\n", optval);
796 exit(1);
798 } else if (!strcasecmp(optname, "virtual_loss")) {
799 /* Number of virtual losses added before evaluating a node. */
800 u->virtual_loss = !optval || atoi(optval);
801 } else if (!strcasecmp(optname, "pondering")) {
802 /* Keep searching even during opponent's turn. */
803 u->pondering_opt = !optval || atoi(optval);
804 } else if (!strcasecmp(optname, "max_tree_size") && optval) {
805 /* Maximum amount of memory [MiB] consumed by the move tree.
806 * For fast_alloc it includes the temp tree used for pruning.
807 * Default is 3072 (3 GiB). */
808 u->max_tree_size = atol(optval) * 1048576;
809 } else if (!strcasecmp(optname, "fast_alloc")) {
810 u->fast_alloc = !optval || atoi(optval);
811 } else if (!strcasecmp(optname, "pruning_threshold") && optval) {
812 /* Force pruning at beginning of a move if the tree consumes
813 * more than this [MiB]. Default is 10% of max_tree_size.
814 * Increase to reduce pruning time overhead if memory is plentiful.
815 * This option is meaningful only for fast_alloc. */
816 u->pruning_threshold = atol(optval) * 1048576;
818 /** Time control */
820 } else if (!strcasecmp(optname, "best2_ratio") && optval) {
821 /* If set, prolong simulating while
822 * first_best/second_best playouts ratio
823 * is less than best2_ratio. */
824 u->best2_ratio = atof(optval);
825 } else if (!strcasecmp(optname, "bestr_ratio") && optval) {
826 /* If set, prolong simulating while
827 * best,best_best_child values delta
828 * is more than bestr_ratio. */
829 u->bestr_ratio = atof(optval);
830 } else if (!strcasecmp(optname, "max_maintime_ratio") && optval) {
831 /* If set and while not in byoyomi, prolong simulating no more than
832 * max_maintime_ratio times the normal desired thinking time. */
833 u->max_maintime_ratio = atof(optval);
834 } else if (!strcasecmp(optname, "fuseki_end") && optval) {
835 /* At the very beginning it's not worth thinking
836 * too long because the playout evaluations are
837 * very noisy. So gradually increase the thinking
838 * time up to maximum when fuseki_end percent
839 * of the board has been played.
840 * This only applies if we are not in byoyomi. */
841 u->fuseki_end = atoi(optval);
842 } else if (!strcasecmp(optname, "yose_start") && optval) {
843 /* When yose_start percent of the board has been
844 * played, or if we are in byoyomi, stop spending
845 * more time and spread the remaining time
846 * uniformly.
847 * Between fuseki_end and yose_start, we spend
848 * a constant proportion of the remaining time
849 * on each move. (yose_start should actually
850 * be much earlier than when real yose start,
851 * but "yose" is a good short name to convey
852 * the idea.) */
853 u->yose_start = atoi(optval);
855 /** Dynamic komi */
857 } else if (!strcasecmp(optname, "dynkomi") && optval) {
858 /* Dynamic komi approach; there are multiple
859 * ways to adjust komi dynamically throughout
860 * play. We currently support two: */
861 char *dynkomiarg = strchr(optval, ':');
862 if (dynkomiarg)
863 *dynkomiarg++ = 0;
864 if (!strcasecmp(optval, "none")) {
865 u->dynkomi = uct_dynkomi_init_none(u, dynkomiarg, b);
866 } else if (!strcasecmp(optval, "linear")) {
867 /* You should set dynkomi_mask=1 or a very low
868 * handicap_value for white. */
869 u->dynkomi = uct_dynkomi_init_linear(u, dynkomiarg, b);
870 } else if (!strcasecmp(optval, "adaptive")) {
871 /* There are many more knobs to
872 * crank - see uct/dynkomi.c. */
873 u->dynkomi = uct_dynkomi_init_adaptive(u, dynkomiarg, b);
874 } else {
875 fprintf(stderr, "UCT: Invalid dynkomi mode %s\n", optval);
876 exit(1);
878 } else if (!strcasecmp(optname, "dynkomi_mask") && optval) {
879 /* Bitmask of colors the player must be
880 * for dynkomi be applied; the default dynkomi_mask=3 allows
881 * dynkomi even in games where Pachi is white. */
882 u->dynkomi_mask = atoi(optval);
883 } else if (!strcasecmp(optname, "dynkomi_interval") && optval) {
884 /* If non-zero, re-adjust dynamic komi
885 * throughout a single genmove reading,
886 * roughly every N simulations. */
887 /* XXX: Does not work with tree
888 * parallelization. */
889 u->dynkomi_interval = atoi(optval);
891 /** Node value result scaling */
893 } else if (!strcasecmp(optname, "val_scale") && optval) {
894 /* How much of the game result value should be
895 * influenced by win size. Zero means it isn't. */
896 u->val_scale = atof(optval);
897 } else if (!strcasecmp(optname, "val_points") && optval) {
898 /* Maximum size of win to be scaled into game
899 * result value. Zero means boardsize^2. */
900 u->val_points = atoi(optval) * 2; // result values are doubled
901 } else if (!strcasecmp(optname, "val_extra")) {
902 /* If false, the score coefficient will be simply
903 * added to the value, instead of scaling the result
904 * coefficient because of it. */
905 u->val_extra = !optval || atoi(optval);
907 /** Local trees */
908 /* (Purely experimental. Does not work - yet!) */
910 } else if (!strcasecmp(optname, "local_tree")) {
911 /* Whether to bias exploration by local tree values. */
912 u->local_tree = !optval || atoi(optval);
913 } else if (!strcasecmp(optname, "tenuki_d") && optval) {
914 /* Tenuki distance at which to break the local tree. */
915 u->tenuki_d = atoi(optval);
916 if (u->tenuki_d > TREE_NODE_D_MAX + 1) {
917 fprintf(stderr, "uct: tenuki_d must not be larger than TREE_NODE_D_MAX+1 %d\n", TREE_NODE_D_MAX + 1);
918 exit(1);
920 } else if (!strcasecmp(optname, "local_tree_aging") && optval) {
921 /* How much to reduce local tree values between moves. */
922 u->local_tree_aging = atof(optval);
923 } else if (!strcasecmp(optname, "local_tree_depth_decay") && optval) {
924 /* With value x>0, during the descent the node
925 * contributes 1/x^depth playouts in
926 * the local tree. I.e., with x>1, nodes more
927 * distant from local situation contribute more
928 * than nodes near the root. */
929 u->local_tree_depth_decay = atof(optval);
930 } else if (!strcasecmp(optname, "local_tree_allseq")) {
931 /* If disabled, only complete sequences are stored
932 * in the local tree. If this is on, also
933 * subsequences starting at each move are stored. */
934 u->local_tree_allseq = !optval || atoi(optval);
935 } else if (!strcasecmp(optname, "local_tree_neival")) {
936 /* If disabled, local node value is not
937 * computed just based on terminal status
938 * of the coordinate, but also its neighbors. */
939 u->local_tree_neival = !optval || atoi(optval);
940 } else if (!strcasecmp(optname, "local_tree_eval")) {
941 /* How is the value inserted in the local tree
942 * determined. */
943 if (!strcasecmp(optval, "root"))
944 /* All moves within a tree branch are
945 * considered wrt. their merit
946 * reaching tachtical goal of making
947 * the first move in the branch
948 * survive. */
949 u->local_tree_eval = LTE_ROOT;
950 else if (!strcasecmp(optval, "each"))
951 /* Each move is considered wrt.
952 * its own survival. */
953 u->local_tree_eval = LTE_EACH;
954 else if (!strcasecmp(optval, "total"))
955 /* The tactical goal is the survival
956 * of all the moves of my color and
957 * non-survival of all the opponent
958 * moves. Local values (and their
959 * inverses) are averaged. */
960 u->local_tree_eval = LTE_TOTAL;
961 else {
962 fprintf(stderr, "uct: unknown local_tree_eval %s\n", optval);
963 exit(1);
965 } else if (!strcasecmp(optname, "local_tree_rootchoose")) {
966 /* If disabled, only moves within the local
967 * tree branch are considered; the values
968 * of the branch roots (i.e. root children)
969 * are ignored. This may make sense together
970 * with eval!=each, we consider only moves
971 * that influence the goal, not the "rating"
972 * of the goal itself. (The real solution
973 * will be probably using criticality to pick
974 * local tree branches.) */
975 u->local_tree_rootchoose = !optval || atoi(optval);
977 /** Other heuristics */
978 } else if (!strcasecmp(optname, "patterns")) {
979 /* Load pattern database. Various modules
980 * (priors, policies etc.) may make use
981 * of this database. They will request
982 * it automatically in that case, but you
983 * can use this option to tweak the pattern
984 * parameters. */
985 patterns_init(&u->pat, optval, false, true);
986 u->want_pat = pat_setup = true;
987 } else if (!strcasecmp(optname, "significant_threshold") && optval) {
988 /* Some heuristics (XXX: none in mainline) rely
989 * on the knowledge of the last "significant"
990 * node in the descent. Such a node is
991 * considered reasonably trustworthy to carry
992 * some meaningful information in the values
993 * of the node and its children. */
994 u->significant_threshold = atoi(optval);
996 /** Distributed engine slaves setup */
998 } else if (!strcasecmp(optname, "slave")) {
999 /* Act as slave for the distributed engine. */
1000 u->slave = !optval || atoi(optval);
1001 } else if (!strcasecmp(optname, "slave_index") && optval) {
1002 /* Optional index if per-slave behavior is desired.
1003 * Must be given as index/max */
1004 u->slave_index = atoi(optval);
1005 char *p = strchr(optval, '/');
1006 if (p) u->max_slaves = atoi(++p);
1007 } else if (!strcasecmp(optname, "shared_nodes") && optval) {
1008 /* Share at most shared_nodes between master and slave at each genmoves.
1009 * Must use the same value in master and slaves. */
1010 u->shared_nodes = atoi(optval);
1011 } else if (!strcasecmp(optname, "shared_levels") && optval) {
1012 /* Share only nodes of level <= shared_levels. */
1013 u->shared_levels = atoi(optval);
1014 } else if (!strcasecmp(optname, "stats_hbits") && optval) {
1015 /* Set hash table size to 2^stats_hbits for the shared stats. */
1016 u->stats_hbits = atoi(optval);
1017 } else if (!strcasecmp(optname, "stats_delay") && optval) {
1018 /* How long to wait in slave for initial stats to build up before
1019 * replying to the genmoves command (in ms) */
1020 u->stats_delay = 0.001 * atof(optval);
1022 } else {
1023 fprintf(stderr, "uct: Invalid engine argument %s or missing value\n", optname);
1024 exit(1);
1029 if (!u->policy)
1030 u->policy = policy_ucb1amaf_init(u, NULL, b);
1032 if (!!u->random_policy_chance ^ !!u->random_policy) {
1033 fprintf(stderr, "uct: Only one of random_policy and random_policy_chance is set\n");
1034 exit(1);
1037 if (!u->local_tree) {
1038 /* No ltree aging. */
1039 u->local_tree_aging = 1.0f;
1042 if (u->fast_alloc) {
1043 if (u->pruning_threshold < u->max_tree_size / 10)
1044 u->pruning_threshold = u->max_tree_size / 10;
1045 if (u->pruning_threshold > u->max_tree_size / 2)
1046 u->pruning_threshold = u->max_tree_size / 2;
1048 /* Limit pruning temp space to 20% of memory. Beyond this we discard
1049 * the nodes and recompute them at the next move if necessary. */
1050 u->max_pruned_size = u->max_tree_size / 5;
1051 u->max_tree_size -= u->max_pruned_size;
1052 } else {
1053 /* Reserve 5% memory in case the background free() are slower
1054 * than the concurrent allocations. */
1055 u->max_tree_size -= u->max_tree_size / 20;
1058 if (!u->prior)
1059 u->prior = uct_prior_init(NULL, b, u);
1061 if (!u->playout)
1062 u->playout = playout_moggy_init(NULL, b, u->jdict);
1063 if (!u->playout->debug_level)
1064 u->playout->debug_level = u->debug_level;
1066 if (u->want_pat && !pat_setup)
1067 patterns_init(&u->pat, NULL, false, true);
1069 u->ownermap.map = malloc2(board_size2(b) * sizeof(u->ownermap.map[0]));
1071 if (u->slave) {
1072 if (!u->stats_hbits) u->stats_hbits = DEFAULT_STATS_HBITS;
1073 if (!u->shared_nodes) u->shared_nodes = DEFAULT_SHARED_NODES;
1074 assert(u->shared_levels * board_bits2(b) <= 8 * (int)sizeof(path_t));
1077 if (!u->dynkomi)
1078 u->dynkomi = uct_dynkomi_init_linear(u, NULL, b);
1080 /* Some things remain uninitialized for now - the opening tbook
1081 * is not loaded and the tree not set up. */
1082 /* This will be initialized in setup_state() at the first move
1083 * received/requested. This is because right now we are not aware
1084 * about any komi or handicap setup and such. */
1086 return u;
1089 struct engine *
1090 engine_uct_init(char *arg, struct board *b)
1092 struct uct *u = uct_state_init(arg, b);
1093 struct engine *e = calloc2(1, sizeof(struct engine));
1094 e->name = "UCT";
1095 e->printhook = uct_printhook_ownermap;
1096 e->notify_play = uct_notify_play;
1097 e->chat = uct_chat;
1098 e->undo = uct_undo;
1099 e->result = uct_result;
1100 e->genmove = uct_genmove;
1101 e->genmoves = uct_genmoves;
1102 e->evaluate = uct_evaluate;
1103 e->dead_group_list = uct_dead_group_list;
1104 e->done = uct_done;
1105 e->data = u;
1106 if (u->slave)
1107 e->notify = uct_notify;
1109 const char banner[] = "If you believe you have won but I am still playing, "
1110 "please help me understand by capturing all dead stones. "
1111 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
1112 if (!u->banner) u->banner = "";
1113 e->comment = malloc2(sizeof(banner) + strlen(u->banner) + 1);
1114 sprintf(e->comment, "%s %s", banner, u->banner);
1116 return e;