Merge pull request #28 from lemonsqueeze/dcnn
[pachi.git] / uct / uct.c
blob5587d6f9d991d5bf24e2bfa1c73a6d54c2abcc31
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 "dcnn.h"
17 #include "joseki/base.h"
18 #include "playout.h"
19 #include "playout/moggy.h"
20 #include "playout/light.h"
21 #include "tactics/util.h"
22 #include "timeinfo.h"
23 #include "uct/dynkomi.h"
24 #include "uct/internal.h"
25 #include "uct/plugins.h"
26 #include "uct/prior.h"
27 #include "uct/search.h"
28 #include "uct/slave.h"
29 #include "uct/tree.h"
30 #include "uct/uct.h"
31 #include "uct/walk.h"
33 struct uct_policy *policy_ucb1_init(struct uct *u, char *arg);
34 struct uct_policy *policy_ucb1amaf_init(struct uct *u, char *arg, struct board *board);
35 static void uct_pondering_start(struct uct *u, struct board *b0, struct tree *t, enum stone color);
37 /* Maximal simulation length. */
38 #define MC_GAMELEN MAX_GAMELEN
41 static void
42 setup_state(struct uct *u, struct board *b, enum stone color)
44 u->t = tree_init(b, color, u->fast_alloc ? u->max_tree_size : 0,
45 u->max_pruned_size, u->pruning_threshold, u->local_tree_aging, u->stats_hbits);
46 if (u->initial_extra_komi)
47 u->t->extra_komi = u->initial_extra_komi;
48 if (u->force_seed)
49 fast_srandom(u->force_seed);
50 if (UDEBUGL(3))
51 fprintf(stderr, "Fresh board with random seed %lu\n", fast_getseed());
52 if (!u->no_tbook && b->moves == 0) {
53 if (color == S_BLACK) {
54 tree_load(u->t, b);
55 } else if (DEBUGL(0)) {
56 fprintf(stderr, "Warning: First move appears to be white\n");
61 static void
62 reset_state(struct uct *u)
64 assert(u->t);
65 tree_done(u->t); u->t = NULL;
68 static void
69 setup_dynkomi(struct uct *u, struct board *b, enum stone to_play)
71 if (u->t->use_extra_komi && !u->pondering && u->dynkomi->permove)
72 u->t->extra_komi = u->dynkomi->permove(u->dynkomi, b, u->t);
73 else if (!u->t->use_extra_komi)
74 u->t->extra_komi = 0;
77 void
78 uct_prepare_move(struct uct *u, struct board *b, enum stone color)
80 if (u->t) {
81 /* Verify that we have sane state. */
82 assert(b->es == u);
83 assert(u->t && b->moves);
84 if (color != stone_other(u->t->root_color)) {
85 fprintf(stderr, "Fatal: Non-alternating play detected %d %d\n",
86 color, u->t->root_color);
87 exit(1);
89 uct_htable_reset(u->t);
91 } else {
92 /* We need fresh state. */
93 b->es = u;
94 setup_state(u, b, color);
97 u->ownermap.playouts = 0;
98 memset(u->ownermap.map, 0, board_size2(b) * sizeof(u->ownermap.map[0]));
99 u->played_own = u->played_all = 0;
102 static void
103 dead_group_list(struct uct *u, struct board *b, struct move_queue *mq)
105 enum gj_state gs_array[board_size2(b)];
106 struct group_judgement gj = { .thres = GJ_THRES, .gs = gs_array };
107 board_ownermap_judge_groups(b, &u->ownermap, &gj);
108 groups_of_status(b, &gj, GS_DEAD, mq);
111 bool
112 uct_pass_is_safe(struct uct *u, struct board *b, enum stone color, bool pass_all_alive)
114 /* Make sure enough playouts are simulated to get a reasonable dead group list. */
115 while (u->ownermap.playouts < GJ_MINGAMES)
116 uct_playout(u, b, color, u->t);
118 struct move_queue mq = { .moves = 0 };
119 dead_group_list(u, b, &mq);
120 if (pass_all_alive) {
121 for (unsigned int i = 0; i < mq.moves; i++) {
122 if (board_at(b, mq.move[i]) == stone_other(color)) {
123 return false; // We need to remove opponent dead groups first.
126 mq.moves = 0; // our dead stones are alive when pass_all_alive is true
128 if (u->allow_losing_pass) {
129 foreach_point(b) {
130 if (board_at(b, c) == S_OFFBOARD)
131 continue;
132 if (board_ownermap_judge_point(&u->ownermap, c, GJ_THRES) == PJ_UNKNOWN) {
133 if (UDEBUGL(3))
134 fprintf(stderr, "uct_pass_is_safe fails at %s[%d]\n", coord2sstr(c, b), c);
135 return false; // Unclear point, clarify first.
137 } foreach_point_end;
138 return true;
140 return pass_is_safe(b, color, &mq);
143 static char *
144 uct_printhook_ownermap(struct board *board, coord_t c, char *s, char *end)
146 struct uct *u = board->es;
147 if (!u) {
148 strcat(s, ". ");
149 return s + 2;
151 const char chr[] = ":XO,"; // dame, black, white, unclear
152 const char chm[] = ":xo,";
153 char ch = chr[board_ownermap_judge_point(&u->ownermap, c, GJ_THRES)];
154 if (ch == ',') { // less precise estimate then?
155 ch = chm[board_ownermap_judge_point(&u->ownermap, c, 0.67)];
157 s += snprintf(s, end - s, "%c ", ch);
158 return s;
161 static float
162 uct_owner_map(struct engine *e, struct board *b, coord_t c)
164 struct uct *u = b->es;
165 return board_ownermap_estimate_point(&u->ownermap, c);
168 static char *
169 uct_notify_play(struct engine *e, struct board *b, struct move *m, char *enginearg)
171 struct uct *u = e->data;
172 if (!u->t) {
173 /* No state, create one - this is probably game beginning
174 * and we need to load the opening tbook right now. */
175 uct_prepare_move(u, b, m->color);
176 assert(u->t);
179 /* Stop pondering, required by tree_promote_at() */
180 uct_pondering_stop(u);
181 if (UDEBUGL(2) && u->slave)
182 tree_dump(u->t, u->dumpthres);
184 if (is_resign(m->coord)) {
185 /* Reset state. */
186 reset_state(u);
187 return NULL;
190 /* Promote node of the appropriate move to the tree root. */
191 assert(u->t->root);
192 if (u->t->untrustworthy_tree | !tree_promote_at(u->t, b, m->coord)) {
193 if (UDEBUGL(3)) {
194 if (u->t->untrustworthy_tree)
195 fprintf(stderr, "Not promoting move node in untrustworthy tree.\n");
196 else
197 fprintf(stderr, "Warning: Cannot promote move node! Several play commands in row?\n");
199 /* Preserve dynamic komi information, though, that is important. */
200 u->initial_extra_komi = u->t->extra_komi;
201 reset_state(u);
202 return NULL;
205 /* If we are a slave in a distributed engine, start pondering once
206 * we know which move we actually played. See uct_genmove() about
207 * the check for pass. */
208 if (u->pondering_opt && u->slave && m->color == u->my_color && !is_pass(m->coord))
209 uct_pondering_start(u, b, u->t, stone_other(m->color));
211 return NULL;
214 static char *
215 uct_undo(struct engine *e, struct board *b)
217 struct uct *u = e->data;
219 if (!u->t) return NULL;
220 uct_pondering_stop(u);
221 u->initial_extra_komi = u->t->extra_komi;
222 reset_state(u);
223 return NULL;
226 static char *
227 uct_result(struct engine *e, struct board *b)
229 struct uct *u = e->data;
230 static char reply[1024];
232 if (!u->t)
233 return NULL;
234 enum stone color = u->t->root_color;
235 struct tree_node *n = u->t->root;
236 snprintf(reply, 1024, "%s %s %d %.2f %.1f",
237 stone2str(color), coord2sstr(node_coord(n), b),
238 n->u.playouts, tree_node_get_value(u->t, -1, n->u.value),
239 u->t->use_extra_komi ? u->t->extra_komi : 0);
240 return reply;
243 static char *
244 uct_chat(struct engine *e, struct board *b, bool opponent, char *from, char *cmd)
246 struct uct *u = e->data;
248 if (!u->t)
249 return generic_chat(b, opponent, from, cmd, S_NONE, pass, 0, 1, u->threads, 0.0, 0.0);
251 struct tree_node *n = u->t->root;
252 double winrate = tree_node_get_value(u->t, -1, n->u.value);
253 double extra_komi = u->t->use_extra_komi && fabs(u->t->extra_komi) >= 0.5 ? u->t->extra_komi : 0;
255 return generic_chat(b, opponent, from, cmd, u->t->root_color, node_coord(n), n->u.playouts, 1,
256 u->threads, winrate, extra_komi);
259 static void
260 uct_dead_group_list(struct engine *e, struct board *b, struct move_queue *mq)
262 struct uct *u = e->data;
264 /* This means the game is probably over, no use pondering on. */
265 uct_pondering_stop(u);
267 if (u->pass_all_alive)
268 return; // no dead groups
270 bool mock_state = false;
272 if (!u->t) {
273 /* No state, but we cannot just back out - we might
274 * have passed earlier, only assuming some stones are
275 * dead, and then re-connected, only to lose counting
276 * when all stones are assumed alive. */
277 uct_prepare_move(u, b, S_BLACK); assert(u->t);
278 mock_state = true;
280 /* Make sure the ownermap is well-seeded. */
281 while (u->ownermap.playouts < GJ_MINGAMES)
282 uct_playout(u, b, S_BLACK, u->t);
283 /* Show the ownermap: */
284 if (DEBUGL(2))
285 board_print_custom(b, stderr, uct_printhook_ownermap);
287 dead_group_list(u, b, mq);
289 if (mock_state) {
290 /* Clean up the mock state in case we will receive
291 * a genmove; we could get a non-alternating-move
292 * error from uct_prepare_move() in that case otherwise. */
293 reset_state(u);
297 static void
298 playout_policy_done(struct playout_policy *p)
300 if (p->done) p->done(p);
301 if (p->data) free(p->data);
302 free(p);
305 static void
306 uct_stop(struct engine *e)
308 /* This is called on game over notification. However, an undo
309 * and game resume can follow, so don't panic yet and just
310 * relax and stop thinking so that we don't waste CPU. */
311 struct uct *u = e->data;
312 uct_pondering_stop(u);
315 static void
316 uct_done(struct engine *e)
318 /* This is called on engine reset, especially when clear_board
319 * is received and new game should begin. */
320 free(e->comment);
322 struct uct *u = e->data;
323 uct_pondering_stop(u);
324 if (u->t) reset_state(u);
325 if (u->dynkomi) u->dynkomi->done(u->dynkomi);
326 free(u->ownermap.map);
328 if (u->policy) u->policy->done(u->policy);
329 if (u->random_policy) u->random_policy->done(u->random_policy);
330 playout_policy_done(u->playout);
331 uct_prior_done(u->prior);
332 joseki_done(u->jdict);
333 pluginset_done(u->plugins);
338 /* Run time-limited MCTS search on foreground. */
339 static int
340 uct_search(struct uct *u, struct board *b, struct time_info *ti, enum stone color, struct tree *t, bool print_progress)
342 struct uct_search_state s;
343 uct_search_start(u, b, color, t, ti, &s);
344 if (UDEBUGL(2) && s.base_playouts > 0)
345 fprintf(stderr, "<pre-simulated %d games>\n", s.base_playouts);
347 /* The search tree is ctx->t. This is currently == . It is important
348 * to reference ctx->t directly since the
349 * thread manager will swap the tree pointer asynchronously. */
351 /* Now, just periodically poll the search tree. */
352 /* Note that in case of TD_GAMES, threads will not wait for
353 * the uct_search_check_stop() signalization. */
354 while (1) {
355 time_sleep(TREE_BUSYWAIT_INTERVAL);
356 /* TREE_BUSYWAIT_INTERVAL should never be less than desired time, or the
357 * time control is broken. But if it happens to be less, we still search
358 * at least 100ms otherwise the move is completely random. */
360 int i = uct_search_games(&s);
361 /* Print notifications etc. */
362 uct_search_progress(u, b, color, t, ti, &s, i);
363 /* Check if we should stop the search. */
364 if (uct_search_check_stop(u, b, color, t, ti, &s, i))
365 break;
368 struct uct_thread_ctx *ctx = uct_search_stop();
369 if (UDEBUGL(2)) tree_dump(t, u->dumpthres);
370 if (UDEBUGL(2))
371 fprintf(stderr, "(avg score %f/%d; dynkomi's %f/%d value %f/%d)\n",
372 t->avg_score.value, t->avg_score.playouts,
373 u->dynkomi->score.value, u->dynkomi->score.playouts,
374 u->dynkomi->value.value, u->dynkomi->value.playouts);
375 if (print_progress)
376 uct_progress_status(u, t, color, ctx->games, NULL);
378 if (u->debug_after.playouts > 0) {
379 /* Now, start an additional run of playouts, single threaded. */
380 struct time_info debug_ti = {
381 .period = TT_MOVE,
382 .dim = TD_GAMES,
384 debug_ti.len.games = t->root->u.playouts + u->debug_after.playouts;
386 board_print_custom(b, stderr, uct_printhook_ownermap);
387 fprintf(stderr, "--8<-- UCT debug post-run begin (%d:%d) --8<--\n", u->debug_after.level, u->debug_after.playouts);
389 int debug_level_save = debug_level;
390 int u_debug_level_save = u->debug_level;
391 int p_debug_level_save = u->playout->debug_level;
392 debug_level = u->debug_after.level;
393 u->debug_level = u->debug_after.level;
394 u->playout->debug_level = u->debug_after.level;
395 uct_halt = false;
397 uct_playouts(u, b, color, t, &debug_ti);
398 tree_dump(t, u->dumpthres);
400 uct_halt = true;
401 debug_level = debug_level_save;
402 u->debug_level = u_debug_level_save;
403 u->playout->debug_level = p_debug_level_save;
405 fprintf(stderr, "--8<-- UCT debug post-run finished --8<--\n");
408 u->played_own += ctx->games;
409 return ctx->games;
412 /* Start pondering background with @color to play. */
413 static void
414 uct_pondering_start(struct uct *u, struct board *b0, struct tree *t, enum stone color)
416 if (UDEBUGL(1))
417 fprintf(stderr, "Starting to ponder with color %s\n", stone2str(stone_other(color)));
418 u->pondering = true;
420 /* We need a local board copy to ponder upon. */
421 struct board *b = malloc2(sizeof(*b)); board_copy(b, b0);
423 /* *b0 did not have the genmove'd move played yet. */
424 struct move m = { node_coord(t->root), t->root_color };
425 int res = board_play(b, &m);
426 assert(res >= 0);
427 setup_dynkomi(u, b, stone_other(m.color));
429 /* Start MCTS manager thread "headless". */
430 static struct uct_search_state s;
431 uct_search_start(u, b, color, t, NULL, &s);
434 /* uct_search_stop() frontend for the pondering (non-genmove) mode, and
435 * to stop the background search for a slave in the distributed engine. */
436 void
437 uct_pondering_stop(struct uct *u)
439 if (!thread_manager_running)
440 return;
442 /* Stop the thread manager. */
443 struct uct_thread_ctx *ctx = uct_search_stop();
444 if (UDEBUGL(1)) {
445 if (u->pondering) fprintf(stderr, "(pondering) ");
446 uct_progress_status(u, ctx->t, ctx->color, ctx->games, NULL);
448 if (u->pondering) {
449 free(ctx->b);
450 u->pondering = false;
455 void
456 uct_genmove_setup(struct uct *u, struct board *b, enum stone color)
458 if (b->superko_violation) {
459 fprintf(stderr, "!!! WARNING: SUPERKO VIOLATION OCCURED BEFORE THIS MOVE\n");
460 fprintf(stderr, "Maybe you play with situational instead of positional superko?\n");
461 fprintf(stderr, "I'm going to ignore the violation, but note that I may miss\n");
462 fprintf(stderr, "some moves valid under this ruleset because of this.\n");
463 b->superko_violation = false;
466 uct_prepare_move(u, b, color);
468 assert(u->t);
469 u->my_color = color;
471 /* How to decide whether to use dynkomi in this game? Since we use
472 * pondering, it's not simple "who-to-play" matter. Decide based on
473 * the last genmove issued. */
474 u->t->use_extra_komi = !!(u->dynkomi_mask & color);
475 setup_dynkomi(u, b, color);
477 if (b->rules == RULES_JAPANESE)
478 u->territory_scoring = true;
480 /* Make pessimistic assumption about komi for Japanese rules to
481 * avoid losing by 0.5 when winning by 0.5 with Chinese rules.
482 * The rules usually give the same winner if the integer part of komi
483 * is odd so we adjust the komi only if it is even (for a board of
484 * odd size). We are not trying to get an exact evaluation for rare
485 * cases of seki. For details see http://home.snafu.de/jasiek/parity.html */
486 if (u->territory_scoring && (((int)floor(b->komi) + board_size(b)) & 1)) {
487 b->komi += (color == S_BLACK ? 1.0 : -1.0);
488 if (UDEBUGL(0))
489 fprintf(stderr, "Setting komi to %.1f assuming Japanese rules\n",
490 b->komi);
494 static void
495 uct_live_gfx_hook(struct engine *e)
497 struct uct *u = e->data;
498 /* Hack: Override reportfreq to get decent update rates in GoGui */
499 u->reportfreq = 1000;
502 /* Kindof like uct_genmove() but just find the best candidates */
503 static void
504 uct_best_moves(struct engine *e, struct board *b, enum stone color)
506 struct time_info ti = { .period = TT_NULL };
507 double start_time = time_now();
508 struct uct *u = e->data;
509 uct_pondering_stop(u);
510 if (u->t)
511 reset_state(u);
512 uct_genmove_setup(u, b, color);
514 /* Start the Monte Carlo Tree Search! */
515 int base_playouts = u->t->root->u.playouts;
516 int played_games = uct_search(u, b, &ti, color, u->t, false);
518 coord_t best_coord;
519 uct_search_result(u, b, color, u->pass_all_alive, played_games, base_playouts, &best_coord);
521 if (UDEBUGL(2)) {
522 double time = time_now() - start_time + 0.000001; /* avoid divide by zero */
523 fprintf(stderr, "genmove in %0.2fs (%d games/s, %d games/s/thread)\n",
524 time, (int)(played_games/time), (int)(played_games/time/u->threads));
527 uct_progress_status(u, u->t, color, played_games, &best_coord);
528 reset_state(u);
531 static coord_t *
532 uct_genmove(struct engine *e, struct board *b, struct time_info *ti, enum stone color, bool pass_all_alive)
534 double start_time = time_now();
535 struct uct *u = e->data;
536 u->pass_all_alive |= pass_all_alive;
537 uct_pondering_stop(u);
539 if (using_dcnn(b)) {
540 // dcnn hack: reset state to make dcnn priors kick in.
541 // FIXME this makes pondering useless when using dcnn ...
542 if (u->t) {
543 u->initial_extra_komi = u->t->extra_komi;
544 reset_state(u);
548 uct_genmove_setup(u, b, color);
550 /* Start the Monte Carlo Tree Search! */
551 int base_playouts = u->t->root->u.playouts;
552 int played_games = uct_search(u, b, ti, color, u->t, false);
554 coord_t best_coord;
555 struct tree_node *best;
556 best = uct_search_result(u, b, color, u->pass_all_alive, played_games, base_playouts, &best_coord);
558 if (UDEBUGL(2)) {
559 double time = time_now() - start_time + 0.000001; /* avoid divide by zero */
560 fprintf(stderr, "genmove in %0.2fs (%d games/s, %d games/s/thread)\n",
561 time, (int)(played_games/time), (int)(played_games/time/u->threads));
564 uct_progress_status(u, u->t, color, played_games, &best_coord);
566 if (!best) {
567 /* Pass or resign. */
568 if (is_pass(best_coord))
569 u->initial_extra_komi = u->t->extra_komi;
570 reset_state(u);
571 return coord_copy(best_coord);
574 if (!u->t->untrustworthy_tree) {
575 tree_promote_node(u->t, &best);
576 } else {
577 /* Throw away an untrustworthy tree. */
578 /* Preserve dynamic komi information, though, that is important. */
579 u->initial_extra_komi = u->t->extra_komi;
580 reset_state(u);
583 /* After a pass, pondering is harmful for two reasons:
584 * (i) We might keep pondering even when the game is over.
585 * Of course this is the case for opponent resign as well.
586 * (ii) More importantly, the ownermap will get skewed since
587 * the UCT will start cutting off any playouts. */
588 if (u->pondering_opt && u->t && !is_pass(node_coord(best))) {
589 uct_pondering_start(u, b, u->t, stone_other(color));
591 return coord_copy(best_coord);
595 bool
596 uct_gentbook(struct engine *e, struct board *b, struct time_info *ti, enum stone color)
598 struct uct *u = e->data;
599 if (!u->t) uct_prepare_move(u, b, color);
600 assert(u->t);
602 if (ti->dim == TD_GAMES) {
603 /* Don't count in games that already went into the tbook. */
604 ti->len.games += u->t->root->u.playouts;
606 uct_search(u, b, ti, color, u->t, true);
608 assert(ti->dim == TD_GAMES);
609 tree_save(u->t, b, ti->len.games / 100);
611 return true;
614 void
615 uct_dumptbook(struct engine *e, struct board *b, enum stone color)
617 struct uct *u = e->data;
618 struct tree *t = tree_init(b, color, u->fast_alloc ? u->max_tree_size : 0,
619 u->max_pruned_size, u->pruning_threshold, u->local_tree_aging, 0);
620 tree_load(t, b);
621 tree_dump(t, 0);
622 tree_done(t);
626 floating_t
627 uct_evaluate_one(struct engine *e, struct board *b, struct time_info *ti, coord_t c, enum stone color)
629 struct uct *u = e->data;
631 struct board b2;
632 board_copy(&b2, b);
633 struct move m = { c, color };
634 int res = board_play(&b2, &m);
635 if (res < 0)
636 return NAN;
637 color = stone_other(color);
639 if (u->t) reset_state(u);
640 uct_prepare_move(u, &b2, color);
641 assert(u->t);
643 floating_t bestval;
644 uct_search(u, &b2, ti, color, u->t, true);
645 struct tree_node *best = u->policy->choose(u->policy, u->t->root, &b2, color, resign);
646 if (!best) {
647 bestval = NAN; // the opponent has no reply!
648 } else {
649 bestval = tree_node_get_value(u->t, 1, best->u.value);
652 reset_state(u); // clean our junk
654 return isnan(bestval) ? NAN : 1.0f - bestval;
657 void
658 uct_evaluate(struct engine *e, struct board *b, struct time_info *ti, floating_t *vals, enum stone color)
660 for (int i = 0; i < b->flen; i++) {
661 if (is_pass(b->f[i]))
662 vals[i] = NAN;
663 else
664 vals[i] = uct_evaluate_one(e, b, ti, b->f[i], color);
669 struct uct *
670 uct_state_init(char *arg, struct board *b)
672 struct uct *u = calloc2(1, sizeof(struct uct));
673 bool pat_setup = false;
675 u->debug_level = debug_level;
676 u->reportfreq = 10000;
677 u->gamelen = MC_GAMELEN;
678 u->resign_threshold = 0.2;
679 u->sure_win_threshold = 0.95;
680 u->mercymin = 0;
681 u->significant_threshold = 50;
682 u->expand_p = 8;
683 u->dumpthres = 0.01;
684 u->playout_amaf = true;
685 u->amaf_prior = false;
686 u->max_tree_size = 1408ULL * 1048576;
687 u->fast_alloc = true;
688 u->pruning_threshold = 0;
690 u->threads = 1;
691 u->thread_model = TM_TREEVL;
692 u->virtual_loss = 1;
694 u->pondering_opt = true;
696 u->fuseki_end = 20; // max time at 361*20% = 72 moves (our 36th move, still 99 to play)
697 u->yose_start = 40; // (100-40-25)*361/100/2 = 63 moves still to play by us then
698 u->bestr_ratio = 0.02;
699 // 2.5 is clearly too much, but seems to compensate well for overly stern time allocations.
700 // TODO: Further tuning and experiments with better time allocation schemes.
701 u->best2_ratio = 2.5;
702 // Higher values of max_maintime_ratio sometimes cause severe time trouble in tournaments
703 // It might be necessary to reduce it to 1.5 on large board, but more tuning is needed.
704 u->max_maintime_ratio = 2.0;
706 u->val_scale = 0; u->val_points = 40;
707 u->dynkomi_interval = 1000;
708 u->dynkomi_mask = S_BLACK | S_WHITE;
710 u->tenuki_d = 4;
711 u->local_tree_aging = 80;
712 u->local_tree_depth_decay = 1.5;
713 u->local_tree_eval = LTE_ROOT;
714 u->local_tree_neival = true;
716 u->max_slaves = -1;
717 u->slave_index = -1;
718 u->stats_delay = 0.01; // 10 ms
719 u->shared_levels = 1;
721 u->plugins = pluginset_init(b);
723 u->jdict = joseki_load(b->size);
725 if (arg) {
726 char *optspec, *next = arg;
727 while (*next) {
728 optspec = next;
729 next += strcspn(next, ",");
730 if (*next) { *next++ = 0; } else { *next = 0; }
732 char *optname = optspec;
733 char *optval = strchr(optspec, '=');
734 if (optval) *optval++ = 0;
736 /** Basic options */
738 if (!strcasecmp(optname, "debug")) {
739 if (optval)
740 u->debug_level = atoi(optval);
741 else
742 u->debug_level++;
743 } else if (!strcasecmp(optname, "reporting") && optval) {
744 /* The format of output for detailed progress
745 * information (such as current best move and
746 * its value, etc.). */
747 if (!strcasecmp(optval, "text")) {
748 /* Plaintext traditional output. */
749 u->reporting = UR_TEXT;
750 } else if (!strcasecmp(optval, "json")) {
751 /* JSON output. Implies debug=0. */
752 u->reporting = UR_JSON;
753 u->debug_level = 0;
754 } else if (!strcasecmp(optval, "jsonbig")) {
755 /* JSON output, but much more detailed.
756 * Implies debug=0. */
757 u->reporting = UR_JSON_BIG;
758 u->debug_level = 0;
759 } else {
760 fprintf(stderr, "UCT: Invalid reporting format %s\n", optval);
761 exit(1);
763 } else if (!strcasecmp(optname, "reportfreq") && optval) {
764 /* The progress information line will be shown
765 * every <reportfreq> simulations. */
766 u->reportfreq = atoi(optval);
767 } else if (!strcasecmp(optname, "dumpthres") && optval) {
768 /* When dumping the UCT tree on output, include
769 * nodes with at least this many playouts.
770 * (A fraction of the total # of playouts at the
771 * tree root.) */
772 /* Use 0 to list all nodes with at least one
773 * simulation, and -1 to list _all_ nodes. */
774 u->dumpthres = atof(optval);
775 } else if (!strcasecmp(optname, "resign_threshold") && optval) {
776 /* Resign when this ratio of games is lost
777 * after GJ_MINGAMES sample is taken. */
778 u->resign_threshold = atof(optval);
779 } else if (!strcasecmp(optname, "sure_win_threshold") && optval) {
780 /* Stop reading when this ratio of games is won
781 * after PLAYOUT_EARLY_BREAK_MIN sample is
782 * taken. (Prevents stupid time losses,
783 * friendly to human opponents.) */
784 u->sure_win_threshold = atof(optval);
785 } else if (!strcasecmp(optname, "force_seed") && optval) {
786 /* Set RNG seed at the tree setup. */
787 u->force_seed = atoi(optval);
788 } else if (!strcasecmp(optname, "no_tbook")) {
789 /* Disable UCT opening tbook. */
790 u->no_tbook = true;
791 } else if (!strcasecmp(optname, "pass_all_alive")) {
792 /* Whether to consider passing only after all
793 * dead groups were removed from the board;
794 * this is like all genmoves are in fact
795 * kgs-genmove_cleanup. */
796 u->pass_all_alive = !optval || atoi(optval);
797 } else if (!strcasecmp(optname, "allow_losing_pass")) {
798 /* Whether to consider passing in a clear
799 * but losing situation, to be scored as a loss
800 * for us. */
801 u->allow_losing_pass = !optval || atoi(optval);
802 } else if (!strcasecmp(optname, "territory_scoring")) {
803 /* Use territory scoring (default is area scoring).
804 * An explicit kgs-rules command overrides this. */
805 u->territory_scoring = !optval || atoi(optval);
806 } else if (!strcasecmp(optname, "stones_only")) {
807 /* Do not count eyes. Nice to teach go to kids.
808 * http://strasbourg.jeudego.org/regle_strasbourgeoise.htm */
809 b->rules = RULES_STONES_ONLY;
810 u->pass_all_alive = true;
811 } else if (!strcasecmp(optname, "debug_after")) {
812 /* debug_after=9:1000 will make Pachi think under
813 * the normal conditions, but at the point when
814 * a move is to be chosen, the tree is dumped and
815 * another 1000 simulations are run single-threaded
816 * with debug level 9, allowing inspection of Pachi's
817 * behavior after it has thought a lot. */
818 if (optval) {
819 u->debug_after.level = atoi(optval);
820 char *playouts = strchr(optval, ':');
821 if (playouts)
822 u->debug_after.playouts = atoi(playouts+1);
823 else
824 u->debug_after.playouts = 1000;
825 } else {
826 u->debug_after.level = 9;
827 u->debug_after.playouts = 1000;
829 } else if (!strcasecmp(optname, "banner") && optval) {
830 /* Additional banner string. This must come as the
831 * last engine parameter. You can use '+' instead
832 * of ' ' if you are wrestling with kgsGtp. */
833 if (*next) *--next = ',';
834 u->banner = strdup(optval);
835 for (char *b = u->banner; *b; b++) {
836 if (*b == '+') *b = ' ';
838 break;
839 } else if (!strcasecmp(optname, "plugin") && optval) {
840 /* Load an external plugin; filename goes before the colon,
841 * extra arguments after the colon. */
842 char *pluginarg = strchr(optval, ':');
843 if (pluginarg)
844 *pluginarg++ = 0;
845 plugin_load(u->plugins, optval, pluginarg);
847 /** UCT behavior and policies */
849 } else if ((!strcasecmp(optname, "policy")
850 /* Node selection policy. ucb1amaf is the
851 * default policy implementing RAVE, while
852 * ucb1 is the simple exploration/exploitation
853 * policy. Policies can take further extra
854 * options. */
855 || !strcasecmp(optname, "random_policy")) && optval) {
856 /* A policy to be used randomly with small
857 * chance instead of the default policy. */
858 char *policyarg = strchr(optval, ':');
859 struct uct_policy **p = !strcasecmp(optname, "policy") ? &u->policy : &u->random_policy;
860 if (policyarg)
861 *policyarg++ = 0;
862 if (!strcasecmp(optval, "ucb1")) {
863 *p = policy_ucb1_init(u, policyarg);
864 } else if (!strcasecmp(optval, "ucb1amaf")) {
865 *p = policy_ucb1amaf_init(u, policyarg, b);
866 } else {
867 fprintf(stderr, "UCT: Invalid tree policy %s\n", optval);
868 exit(1);
870 } else if (!strcasecmp(optname, "playout") && optval) {
871 /* Random simulation (playout) policy.
872 * moggy is the default policy with large
873 * amount of domain-specific knowledge and
874 * heuristics. light is a simple uniformly
875 * random move selection policy. */
876 char *playoutarg = strchr(optval, ':');
877 if (playoutarg)
878 *playoutarg++ = 0;
879 if (!strcasecmp(optval, "moggy")) {
880 u->playout = playout_moggy_init(playoutarg, b, u->jdict);
881 } else if (!strcasecmp(optval, "light")) {
882 u->playout = playout_light_init(playoutarg, b);
883 } else {
884 fprintf(stderr, "UCT: Invalid playout policy %s\n", optval);
885 exit(1);
887 } else if (!strcasecmp(optname, "prior") && optval) {
888 /* Node priors policy. When expanding a node,
889 * it will seed node values heuristically
890 * (most importantly, based on playout policy
891 * opinion, but also with regard to other
892 * things). See uct/prior.c for details.
893 * Use prior=eqex=0 to disable priors. */
894 u->prior = uct_prior_init(optval, b, u);
895 } else if (!strcasecmp(optname, "mercy") && optval) {
896 /* Minimal difference of black/white captures
897 * to stop playout - "Mercy Rule". Speeds up
898 * hopeless playouts at the expense of some
899 * accuracy. */
900 u->mercymin = atoi(optval);
901 } else if (!strcasecmp(optname, "gamelen") && optval) {
902 /* Maximum length of single simulation
903 * in moves. */
904 u->gamelen = atoi(optval);
905 } else if (!strcasecmp(optname, "expand_p") && optval) {
906 /* Expand UCT nodes after it has been
907 * visited this many times. */
908 u->expand_p = atoi(optval);
909 } else if (!strcasecmp(optname, "random_policy_chance") && optval) {
910 /* If specified (N), with probability 1/N, random_policy policy
911 * descend is used instead of main policy descend; useful
912 * if specified policy (e.g. UCB1AMAF) can make unduly biased
913 * choices sometimes, you can fall back to e.g.
914 * random_policy=UCB1. */
915 u->random_policy_chance = atoi(optval);
917 /** General AMAF behavior */
918 /* (Only relevant if the policy supports AMAF.
919 * More variables can be tuned as policy
920 * parameters.) */
922 } else if (!strcasecmp(optname, "playout_amaf")) {
923 /* Whether to include random playout moves in
924 * AMAF as well. (Otherwise, only tree moves
925 * are included in AMAF. Of course makes sense
926 * only in connection with an AMAF policy.) */
927 /* with-without: 55.5% (+-4.1) */
928 if (optval && *optval == '0')
929 u->playout_amaf = false;
930 else
931 u->playout_amaf = true;
932 } else if (!strcasecmp(optname, "playout_amaf_cutoff") && optval) {
933 /* Keep only first N% of playout stage AMAF
934 * information. */
935 u->playout_amaf_cutoff = atoi(optval);
936 } else if (!strcasecmp(optname, "amaf_prior") && optval) {
937 /* In node policy, consider prior values
938 * part of the real result term or part
939 * of the AMAF term? */
940 u->amaf_prior = atoi(optval);
942 /** Performance and memory management */
944 } else if (!strcasecmp(optname, "threads") && optval) {
945 /* By default, Pachi will run with only single
946 * tree search thread! */
947 u->threads = atoi(optval);
948 } else if (!strcasecmp(optname, "thread_model") && optval) {
949 if (!strcasecmp(optval, "tree")) {
950 /* Tree parallelization - all threads
951 * grind on the same tree. */
952 u->thread_model = TM_TREE;
953 u->virtual_loss = 0;
954 } else if (!strcasecmp(optval, "treevl")) {
955 /* Tree parallelization, but also
956 * with virtual losses - this discou-
957 * rages most threads choosing the
958 * same tree branches to read. */
959 u->thread_model = TM_TREEVL;
960 } else {
961 fprintf(stderr, "UCT: Invalid thread model %s\n", optval);
962 exit(1);
964 } else if (!strcasecmp(optname, "virtual_loss") && optval) {
965 /* Number of virtual losses added before evaluating a node. */
966 u->virtual_loss = atoi(optval);
967 } else if (!strcasecmp(optname, "pondering")) {
968 /* Keep searching even during opponent's turn. */
969 u->pondering_opt = !optval || atoi(optval);
970 } else if (!strcasecmp(optname, "max_tree_size") && optval) {
971 /* Maximum amount of memory [MiB] consumed by the move tree.
972 * For fast_alloc it includes the temp tree used for pruning.
973 * Default is 3072 (3 GiB). */
974 u->max_tree_size = atol(optval) * 1048576;
975 } else if (!strcasecmp(optname, "fast_alloc")) {
976 u->fast_alloc = !optval || atoi(optval);
977 } else if (!strcasecmp(optname, "pruning_threshold") && optval) {
978 /* Force pruning at beginning of a move if the tree consumes
979 * more than this [MiB]. Default is 10% of max_tree_size.
980 * Increase to reduce pruning time overhead if memory is plentiful.
981 * This option is meaningful only for fast_alloc. */
982 u->pruning_threshold = atol(optval) * 1048576;
984 /** Time control */
986 } else if (!strcasecmp(optname, "best2_ratio") && optval) {
987 /* If set, prolong simulating while
988 * first_best/second_best playouts ratio
989 * is less than best2_ratio. */
990 u->best2_ratio = atof(optval);
991 } else if (!strcasecmp(optname, "bestr_ratio") && optval) {
992 /* If set, prolong simulating while
993 * best,best_best_child values delta
994 * is more than bestr_ratio. */
995 u->bestr_ratio = atof(optval);
996 } else if (!strcasecmp(optname, "max_maintime_ratio") && optval) {
997 /* If set and while not in byoyomi, prolong simulating no more than
998 * max_maintime_ratio times the normal desired thinking time. */
999 u->max_maintime_ratio = atof(optval);
1000 } else if (!strcasecmp(optname, "fuseki_end") && optval) {
1001 /* At the very beginning it's not worth thinking
1002 * too long because the playout evaluations are
1003 * very noisy. So gradually increase the thinking
1004 * time up to maximum when fuseki_end percent
1005 * of the board has been played.
1006 * This only applies if we are not in byoyomi. */
1007 u->fuseki_end = atoi(optval);
1008 } else if (!strcasecmp(optname, "yose_start") && optval) {
1009 /* When yose_start percent of the board has been
1010 * played, or if we are in byoyomi, stop spending
1011 * more time and spread the remaining time
1012 * uniformly.
1013 * Between fuseki_end and yose_start, we spend
1014 * a constant proportion of the remaining time
1015 * on each move. (yose_start should actually
1016 * be much earlier than when real yose start,
1017 * but "yose" is a good short name to convey
1018 * the idea.) */
1019 u->yose_start = atoi(optval);
1021 /** Dynamic komi */
1023 } else if (!strcasecmp(optname, "dynkomi") && optval) {
1024 /* Dynamic komi approach; there are multiple
1025 * ways to adjust komi dynamically throughout
1026 * play. We currently support two: */
1027 char *dynkomiarg = strchr(optval, ':');
1028 if (dynkomiarg)
1029 *dynkomiarg++ = 0;
1030 if (!strcasecmp(optval, "none")) {
1031 u->dynkomi = uct_dynkomi_init_none(u, dynkomiarg, b);
1032 } else if (!strcasecmp(optval, "linear")) {
1033 /* You should set dynkomi_mask=1 or a very low
1034 * handicap_value for white. */
1035 u->dynkomi = uct_dynkomi_init_linear(u, dynkomiarg, b);
1036 } else if (!strcasecmp(optval, "adaptive")) {
1037 /* There are many more knobs to
1038 * crank - see uct/dynkomi.c. */
1039 u->dynkomi = uct_dynkomi_init_adaptive(u, dynkomiarg, b);
1040 } else {
1041 fprintf(stderr, "UCT: Invalid dynkomi mode %s\n", optval);
1042 exit(1);
1044 } else if (!strcasecmp(optname, "dynkomi_mask") && optval) {
1045 /* Bitmask of colors the player must be
1046 * for dynkomi be applied; the default dynkomi_mask=3 allows
1047 * dynkomi even in games where Pachi is white. */
1048 u->dynkomi_mask = atoi(optval);
1049 } else if (!strcasecmp(optname, "dynkomi_interval") && optval) {
1050 /* If non-zero, re-adjust dynamic komi
1051 * throughout a single genmove reading,
1052 * roughly every N simulations. */
1053 /* XXX: Does not work with tree
1054 * parallelization. */
1055 u->dynkomi_interval = atoi(optval);
1056 } else if (!strcasecmp(optname, "extra_komi") && optval) {
1057 /* Initial dynamic komi settings. This
1058 * is useful for the adaptive dynkomi
1059 * policy as the value to start with
1060 * (this is NOT kept fixed) in case
1061 * there is not enough time in the search
1062 * to adjust the value properly (e.g. the
1063 * game was interrupted). */
1064 u->initial_extra_komi = atof(optval);
1066 /** Node value result scaling */
1068 } else if (!strcasecmp(optname, "val_scale") && optval) {
1069 /* How much of the game result value should be
1070 * influenced by win size. Zero means it isn't. */
1071 u->val_scale = atof(optval);
1072 } else if (!strcasecmp(optname, "val_points") && optval) {
1073 /* Maximum size of win to be scaled into game
1074 * result value. Zero means boardsize^2. */
1075 u->val_points = atoi(optval) * 2; // result values are doubled
1076 } else if (!strcasecmp(optname, "val_extra")) {
1077 /* If false, the score coefficient will be simply
1078 * added to the value, instead of scaling the result
1079 * coefficient because of it. */
1080 u->val_extra = !optval || atoi(optval);
1081 } else if (!strcasecmp(optname, "val_byavg")) {
1082 /* If true, the score included in the value will
1083 * be relative to average score in the current
1084 * search episode inst. of jigo. */
1085 u->val_byavg = !optval || atoi(optval);
1086 } else if (!strcasecmp(optname, "val_bytemp")) {
1087 /* If true, the value scaling coefficient
1088 * is different based on value extremity
1089 * (dist. from 0.5), linear between
1090 * val_bytemp_min, val_scale. */
1091 u->val_bytemp = !optval || atoi(optval);
1092 } else if (!strcasecmp(optname, "val_bytemp_min") && optval) {
1093 /* Minimum val_scale in case of val_bytemp. */
1094 u->val_bytemp_min = atof(optval);
1096 /** Local trees */
1097 /* (Purely experimental. Does not work - yet!) */
1099 } else if (!strcasecmp(optname, "local_tree")) {
1100 /* Whether to bias exploration by local tree values. */
1101 u->local_tree = !optval || atoi(optval);
1102 } else if (!strcasecmp(optname, "tenuki_d") && optval) {
1103 /* Tenuki distance at which to break the local tree. */
1104 u->tenuki_d = atoi(optval);
1105 if (u->tenuki_d > TREE_NODE_D_MAX + 1) {
1106 fprintf(stderr, "uct: tenuki_d must not be larger than TREE_NODE_D_MAX+1 %d\n", TREE_NODE_D_MAX + 1);
1107 exit(1);
1109 } else if (!strcasecmp(optname, "local_tree_aging") && optval) {
1110 /* How much to reduce local tree values between moves. */
1111 u->local_tree_aging = atof(optval);
1112 } else if (!strcasecmp(optname, "local_tree_depth_decay") && optval) {
1113 /* With value x>0, during the descent the node
1114 * contributes 1/x^depth playouts in
1115 * the local tree. I.e., with x>1, nodes more
1116 * distant from local situation contribute more
1117 * than nodes near the root. */
1118 u->local_tree_depth_decay = atof(optval);
1119 } else if (!strcasecmp(optname, "local_tree_allseq")) {
1120 /* If disabled, only complete sequences are stored
1121 * in the local tree. If this is on, also
1122 * subsequences starting at each move are stored. */
1123 u->local_tree_allseq = !optval || atoi(optval);
1124 } else if (!strcasecmp(optname, "local_tree_neival")) {
1125 /* If disabled, local node value is not
1126 * computed just based on terminal status
1127 * of the coordinate, but also its neighbors. */
1128 u->local_tree_neival = !optval || atoi(optval);
1129 } else if (!strcasecmp(optname, "local_tree_eval")) {
1130 /* How is the value inserted in the local tree
1131 * determined. */
1132 if (!strcasecmp(optval, "root"))
1133 /* All moves within a tree branch are
1134 * considered wrt. their merit
1135 * reaching tachtical goal of making
1136 * the first move in the branch
1137 * survive. */
1138 u->local_tree_eval = LTE_ROOT;
1139 else if (!strcasecmp(optval, "each"))
1140 /* Each move is considered wrt.
1141 * its own survival. */
1142 u->local_tree_eval = LTE_EACH;
1143 else if (!strcasecmp(optval, "total"))
1144 /* The tactical goal is the survival
1145 * of all the moves of my color and
1146 * non-survival of all the opponent
1147 * moves. Local values (and their
1148 * inverses) are averaged. */
1149 u->local_tree_eval = LTE_TOTAL;
1150 else {
1151 fprintf(stderr, "uct: unknown local_tree_eval %s\n", optval);
1152 exit(1);
1154 } else if (!strcasecmp(optname, "local_tree_rootchoose")) {
1155 /* If disabled, only moves within the local
1156 * tree branch are considered; the values
1157 * of the branch roots (i.e. root children)
1158 * are ignored. This may make sense together
1159 * with eval!=each, we consider only moves
1160 * that influence the goal, not the "rating"
1161 * of the goal itself. (The real solution
1162 * will be probably using criticality to pick
1163 * local tree branches.) */
1164 u->local_tree_rootchoose = !optval || atoi(optval);
1166 /** Other heuristics */
1167 } else if (!strcasecmp(optname, "patterns")) {
1168 /* Load pattern database. Various modules
1169 * (priors, policies etc.) may make use
1170 * of this database. They will request
1171 * it automatically in that case, but you
1172 * can use this option to tweak the pattern
1173 * parameters. */
1174 patterns_init(&u->pat, optval, false, true);
1175 u->want_pat = pat_setup = true;
1176 } else if (!strcasecmp(optname, "significant_threshold") && optval) {
1177 /* Some heuristics (XXX: none in mainline) rely
1178 * on the knowledge of the last "significant"
1179 * node in the descent. Such a node is
1180 * considered reasonably trustworthy to carry
1181 * some meaningful information in the values
1182 * of the node and its children. */
1183 u->significant_threshold = atoi(optval);
1185 /** Distributed engine slaves setup */
1187 } else if (!strcasecmp(optname, "slave")) {
1188 /* Act as slave for the distributed engine. */
1189 u->slave = !optval || atoi(optval);
1190 } else if (!strcasecmp(optname, "slave_index") && optval) {
1191 /* Optional index if per-slave behavior is desired.
1192 * Must be given as index/max */
1193 u->slave_index = atoi(optval);
1194 char *p = strchr(optval, '/');
1195 if (p) u->max_slaves = atoi(++p);
1196 } else if (!strcasecmp(optname, "shared_nodes") && optval) {
1197 /* Share at most shared_nodes between master and slave at each genmoves.
1198 * Must use the same value in master and slaves. */
1199 u->shared_nodes = atoi(optval);
1200 } else if (!strcasecmp(optname, "shared_levels") && optval) {
1201 /* Share only nodes of level <= shared_levels. */
1202 u->shared_levels = atoi(optval);
1203 } else if (!strcasecmp(optname, "stats_hbits") && optval) {
1204 /* Set hash table size to 2^stats_hbits for the shared stats. */
1205 u->stats_hbits = atoi(optval);
1206 } else if (!strcasecmp(optname, "stats_delay") && optval) {
1207 /* How long to wait in slave for initial stats to build up before
1208 * replying to the genmoves command (in ms) */
1209 u->stats_delay = 0.001 * atof(optval);
1211 /** Presets */
1213 } else if (!strcasecmp(optname, "maximize_score")) {
1214 /* A combination of settings that will make
1215 * Pachi try to maximize his points (instead
1216 * of playing slack yose) or minimize his loss
1217 * (and proceed to counting even when losing). */
1218 /* Please note that this preset might be
1219 * somewhat weaker than normal Pachi, and the
1220 * score maximization is approximate; point size
1221 * of win/loss still should not be used to judge
1222 * strength of Pachi or the opponent. */
1223 /* See README for some further notes. */
1224 if (!optval || atoi(optval)) {
1225 /* Allow scoring a lost game. */
1226 u->allow_losing_pass = true;
1227 /* Make Pachi keep his calm when losing
1228 * and/or maintain winning marging. */
1229 /* Do not play games that are losing
1230 * by too much. */
1231 /* XXX: komi_ratchet_age=40000 is necessary
1232 * with losing_komi_ratchet, but 40000
1233 * is somewhat arbitrary value. */
1234 char dynkomi_args[] = "losing_komi_ratchet:komi_ratchet_age=60000:no_komi_at_game_end=0:max_losing_komi=30";
1235 u->dynkomi = uct_dynkomi_init_adaptive(u, dynkomi_args, b);
1236 /* XXX: Values arbitrary so far. */
1237 /* XXX: Also, is bytemp sensible when
1238 * combined with dynamic komi?! */
1239 u->val_scale = 0.01;
1240 u->val_bytemp = true;
1241 u->val_bytemp_min = 0.001;
1242 u->val_byavg = true;
1245 } else {
1246 fprintf(stderr, "uct: Invalid engine argument %s or missing value\n", optname);
1247 exit(1);
1252 if (!u->policy)
1253 u->policy = policy_ucb1amaf_init(u, NULL, b);
1255 if (!!u->random_policy_chance ^ !!u->random_policy) {
1256 fprintf(stderr, "uct: Only one of random_policy and random_policy_chance is set\n");
1257 exit(1);
1260 if (!u->local_tree) {
1261 /* No ltree aging. */
1262 u->local_tree_aging = 1.0f;
1265 if (u->fast_alloc) {
1266 if (u->pruning_threshold < u->max_tree_size / 10)
1267 u->pruning_threshold = u->max_tree_size / 10;
1268 if (u->pruning_threshold > u->max_tree_size / 2)
1269 u->pruning_threshold = u->max_tree_size / 2;
1271 /* Limit pruning temp space to 20% of memory. Beyond this we discard
1272 * the nodes and recompute them at the next move if necessary. */
1273 u->max_pruned_size = u->max_tree_size / 5;
1274 u->max_tree_size -= u->max_pruned_size;
1275 } else {
1276 /* Reserve 5% memory in case the background free() are slower
1277 * than the concurrent allocations. */
1278 u->max_tree_size -= u->max_tree_size / 20;
1281 if (!u->prior)
1282 u->prior = uct_prior_init(NULL, b, u);
1284 if (!u->playout)
1285 u->playout = playout_moggy_init(NULL, b, u->jdict);
1286 if (!u->playout->debug_level)
1287 u->playout->debug_level = u->debug_level;
1289 if (u->want_pat && !pat_setup)
1290 patterns_init(&u->pat, NULL, false, true);
1291 dcnn_init();
1293 u->ownermap.map = malloc2(board_size2(b) * sizeof(u->ownermap.map[0]));
1295 if (u->slave) {
1296 if (!u->stats_hbits) u->stats_hbits = DEFAULT_STATS_HBITS;
1297 if (!u->shared_nodes) u->shared_nodes = DEFAULT_SHARED_NODES;
1298 assert(u->shared_levels * board_bits2(b) <= 8 * (int)sizeof(path_t));
1301 if (!u->dynkomi)
1302 u->dynkomi = board_small(b) ? uct_dynkomi_init_none(u, NULL, b)
1303 : uct_dynkomi_init_linear(u, NULL, b);
1305 /* Some things remain uninitialized for now - the opening tbook
1306 * is not loaded and the tree not set up. */
1307 /* This will be initialized in setup_state() at the first move
1308 * received/requested. This is because right now we are not aware
1309 * about any komi or handicap setup and such. */
1311 return u;
1314 struct engine *
1315 engine_uct_init(char *arg, struct board *b)
1317 struct uct *u = uct_state_init(arg, b);
1318 struct engine *e = calloc2(1, sizeof(struct engine));
1319 e->name = "UCT";
1320 e->printhook = uct_printhook_ownermap;
1321 e->notify_play = uct_notify_play;
1322 e->chat = uct_chat;
1323 e->undo = uct_undo;
1324 e->result = uct_result;
1325 e->genmove = uct_genmove;
1326 e->genmoves = uct_genmoves;
1327 e->evaluate = uct_evaluate;
1328 e->dead_group_list = uct_dead_group_list;
1329 e->stop = uct_stop;
1330 e->done = uct_done;
1331 e->owner_map = uct_owner_map;
1332 e->best_moves = uct_best_moves;
1333 e->live_gfx_hook = uct_live_gfx_hook;
1334 e->data = u;
1335 if (u->slave)
1336 e->notify = uct_notify;
1338 const char banner[] = "If you believe you have won but I am still playing, "
1339 "please help me understand by capturing all dead stones. "
1340 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
1341 if (!u->banner) u->banner = "";
1342 e->comment = malloc2(sizeof(banner) + strlen(u->banner) + 1);
1343 sprintf(e->comment, "%s %s", banner, u->banner);
1345 return e;