Introduce Joseki Scanner aux engine
[pachi.git] / uct / uct.c
blob60627797f041d05443913457369781e10199dd3a
1 #include <assert.h>
2 #include <math.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <string.h>
6 #include <time.h>
8 #define DEBUG
10 #include "debug.h"
11 #include "board.h"
12 #include "gtp.h"
13 #include "move.h"
14 #include "mq.h"
15 #include "playout.h"
16 #include "playout/elo.h"
17 #include "playout/moggy.h"
18 #include "playout/light.h"
19 #include "tactics.h"
20 #include "timeinfo.h"
21 #include "uct/dynkomi.h"
22 #include "uct/internal.h"
23 #include "uct/plugins.h"
24 #include "uct/prior.h"
25 #include "uct/search.h"
26 #include "uct/slave.h"
27 #include "uct/tree.h"
28 #include "uct/uct.h"
29 #include "uct/walk.h"
31 struct uct_policy *policy_ucb1_init(struct uct *u, char *arg);
32 struct uct_policy *policy_ucb1amaf_init(struct uct *u, char *arg);
33 static void uct_pondering_start(struct uct *u, struct board *b0, struct tree *t, enum stone color);
35 /* Maximal simulation length. */
36 #define MC_GAMELEN MAX_GAMELEN
39 static void
40 setup_state(struct uct *u, struct board *b, enum stone color)
42 u->t = tree_init(b, color, u->fast_alloc ? u->max_tree_size : 0,
43 u->local_tree_aging, u->stats_hbits);
44 if (u->force_seed)
45 fast_srandom(u->force_seed);
46 if (UDEBUGL(0))
47 fprintf(stderr, "Fresh board with random seed %lu\n", fast_getseed());
48 //board_print(b, stderr);
49 if (!u->no_book && b->moves == 0) {
50 assert(color == S_BLACK);
51 tree_load(u->t, b);
55 static void
56 reset_state(struct uct *u)
58 assert(u->t);
59 tree_done(u->t); u->t = NULL;
62 static void
63 setup_dynkomi(struct uct *u, struct board *b, enum stone to_play)
65 if (u->t->use_extra_komi && !u->pondering && u->dynkomi->permove)
66 u->t->extra_komi = u->dynkomi->permove(u->dynkomi, b, u->t);
69 void
70 uct_prepare_move(struct uct *u, struct board *b, enum stone color)
72 if (u->t) {
73 /* Verify that we have sane state. */
74 assert(b->es == u);
75 assert(u->t && b->moves);
76 if (color != stone_other(u->t->root_color)) {
77 fprintf(stderr, "Fatal: Non-alternating play detected %d %d\n",
78 color, u->t->root_color);
79 exit(1);
81 uct_htable_reset(u->t);
83 } else {
84 /* We need fresh state. */
85 b->es = u;
86 setup_state(u, b, color);
89 u->ownermap.playouts = 0;
90 memset(u->ownermap.map, 0, board_size2(b) * sizeof(u->ownermap.map[0]));
91 u->played_own = u->played_all = 0;
94 static void
95 dead_group_list(struct uct *u, struct board *b, struct move_queue *mq)
97 struct group_judgement gj;
98 gj.thres = GJ_THRES;
99 gj.gs = alloca(board_size2(b) * sizeof(gj.gs[0]));
100 board_ownermap_judge_group(b, &u->ownermap, &gj);
101 groups_of_status(b, &gj, GS_DEAD, mq);
104 bool
105 uct_pass_is_safe(struct uct *u, struct board *b, enum stone color, bool pass_all_alive)
107 if (u->ownermap.playouts < GJ_MINGAMES)
108 return false;
110 struct move_queue mq = { .moves = 0 };
111 dead_group_list(u, b, &mq);
112 if (pass_all_alive && mq.moves > 0)
113 return false; // We need to remove some dead groups first.
114 return pass_is_safe(b, color, &mq);
117 static char *
118 uct_printhook_ownermap(struct board *board, coord_t c, char *s, char *end)
120 struct uct *u = board->es;
121 assert(u);
122 const char chr[] = ":XO,"; // dame, black, white, unclear
123 const char chm[] = ":xo,";
124 char ch = chr[board_ownermap_judge_point(&u->ownermap, c, GJ_THRES)];
125 if (ch == ',') { // less precise estimate then?
126 ch = chm[board_ownermap_judge_point(&u->ownermap, c, 0.67)];
128 s += snprintf(s, end - s, "%c ", ch);
129 return s;
132 static char *
133 uct_notify_play(struct engine *e, struct board *b, struct move *m)
135 struct uct *u = e->data;
136 if (!u->t) {
137 /* No state, create one - this is probably game beginning
138 * and we need to load the opening book right now. */
139 uct_prepare_move(u, b, m->color);
140 assert(u->t);
143 /* Stop pondering, required by tree_promote_at() */
144 uct_pondering_stop(u);
145 if (UDEBUGL(2) && u->slave)
146 tree_dump(u->t, u->dumpthres);
148 if (is_resign(m->coord)) {
149 /* Reset state. */
150 reset_state(u);
151 return NULL;
154 /* Promote node of the appropriate move to the tree root. */
155 assert(u->t->root);
156 if (!tree_promote_at(u->t, b, m->coord)) {
157 if (UDEBUGL(0))
158 fprintf(stderr, "Warning: Cannot promote move node! Several play commands in row?\n");
159 reset_state(u);
160 return NULL;
163 /* If we are a slave in a distributed engine, start pondering once
164 * we know which move we actually played. See uct_genmove() about
165 * the check for pass. */
166 if (u->pondering_opt && u->slave && m->color == u->my_color && !is_pass(m->coord))
167 uct_pondering_start(u, b, u->t, stone_other(m->color));
169 return NULL;
172 static char *
173 uct_chat(struct engine *e, struct board *b, char *cmd)
175 struct uct *u = e->data;
176 static char reply[1024];
178 cmd += strspn(cmd, " \n\t");
179 if (!strncasecmp(cmd, "winrate", 7)) {
180 if (!u->t)
181 return "no game context (yet?)";
182 enum stone color = u->t->root_color;
183 struct tree_node *n = u->t->root;
184 snprintf(reply, 1024, "In %d playouts at %d threads, %s %s can win with %.2f%% probability",
185 n->u.playouts, u->threads, stone2str(color), coord2sstr(n->coord, b),
186 tree_node_get_value(u->t, -1, n->u.value) * 100);
187 if (u->t->use_extra_komi && abs(u->t->extra_komi) >= 0.5) {
188 sprintf(reply + strlen(reply), ", while self-imposing extra komi %.1f",
189 u->t->extra_komi);
191 strcat(reply, ".");
192 return reply;
194 return NULL;
197 static void
198 uct_dead_group_list(struct engine *e, struct board *b, struct move_queue *mq)
200 struct uct *u = e->data;
202 /* This means the game is probably over, no use pondering on. */
203 uct_pondering_stop(u);
205 if (u->pass_all_alive)
206 return; // no dead groups
208 bool mock_state = false;
210 if (!u->t) {
211 /* No state, but we cannot just back out - we might
212 * have passed earlier, only assuming some stones are
213 * dead, and then re-connected, only to lose counting
214 * when all stones are assumed alive. */
215 uct_prepare_move(u, b, S_BLACK); assert(u->t);
216 mock_state = true;
218 /* Make sure the ownermap is well-seeded. */
219 while (u->ownermap.playouts < GJ_MINGAMES)
220 uct_playout(u, b, S_BLACK, u->t);
221 /* Show the ownermap: */
222 if (DEBUGL(2))
223 board_print_custom(b, stderr, uct_printhook_ownermap);
225 dead_group_list(u, b, mq);
227 if (mock_state) {
228 /* Clean up the mock state in case we will receive
229 * a genmove; we could get a non-alternating-move
230 * error from uct_prepare_move() in that case otherwise. */
231 reset_state(u);
235 static void
236 playout_policy_done(struct playout_policy *p)
238 if (p->done) p->done(p);
239 if (p->data) free(p->data);
240 free(p);
243 static void
244 uct_done(struct engine *e)
246 /* This is called on engine reset, especially when clear_board
247 * is received and new game should begin. */
248 struct uct *u = e->data;
249 uct_pondering_stop(u);
250 if (u->t) reset_state(u);
251 free(u->ownermap.map);
253 free(u->policy);
254 free(u->random_policy);
255 playout_policy_done(u->playout);
256 uct_prior_done(u->prior);
257 pluginset_done(u->plugins);
262 /* Run time-limited MCTS search on foreground. */
263 static int
264 uct_search(struct uct *u, struct board *b, struct time_info *ti, enum stone color, struct tree *t)
266 struct uct_search_state s;
267 uct_search_start(u, b, color, t, ti, &s);
268 if (UDEBUGL(2) && s.base_playouts > 0)
269 fprintf(stderr, "<pre-simulated %d games>\n", s.base_playouts);
271 /* The search tree is ctx->t. This is currently == . It is important
272 * to reference ctx->t directly since the
273 * thread manager will swap the tree pointer asynchronously. */
275 /* Now, just periodically poll the search tree. */
276 while (1) {
277 time_sleep(TREE_BUSYWAIT_INTERVAL);
278 /* TREE_BUSYWAIT_INTERVAL should never be less than desired time, or the
279 * time control is broken. But if it happens to be less, we still search
280 * at least 100ms otherwise the move is completely random. */
282 int i = uct_search_games(&s);
283 /* Print notifications etc. */
284 uct_search_progress(u, b, color, t, ti, &s, i);
285 /* Check if we should stop the search. */
286 if (uct_search_check_stop(u, b, color, t, ti, &s, i))
287 break;
290 struct uct_thread_ctx *ctx = uct_search_stop();
291 if (UDEBUGL(2)) tree_dump(t, u->dumpthres);
292 if (UDEBUGL(2))
293 fprintf(stderr, "(avg score %f/%d value %f/%d)\n",
294 u->dynkomi->score.value, u->dynkomi->score.playouts,
295 u->dynkomi->value.value, u->dynkomi->value.playouts);
296 if (UDEBUGL(0))
297 uct_progress_status(u, t, color, ctx->games);
299 u->played_own += ctx->games;
300 return ctx->games;
303 /* Start pondering background with @color to play. */
304 static void
305 uct_pondering_start(struct uct *u, struct board *b0, struct tree *t, enum stone color)
307 if (UDEBUGL(1))
308 fprintf(stderr, "Starting to ponder with color %s\n", stone2str(stone_other(color)));
309 u->pondering = true;
311 /* We need a local board copy to ponder upon. */
312 struct board *b = malloc2(sizeof(*b)); board_copy(b, b0);
314 /* *b0 did not have the genmove'd move played yet. */
315 struct move m = { t->root->coord, t->root_color };
316 int res = board_play(b, &m);
317 assert(res >= 0);
318 setup_dynkomi(u, b, stone_other(m.color));
320 /* Start MCTS manager thread "headless". */
321 static struct uct_search_state s;
322 uct_search_start(u, b, color, t, NULL, &s);
325 /* uct_search_stop() frontend for the pondering (non-genmove) mode, and
326 * to stop the background search for a slave in the distributed engine. */
327 void
328 uct_pondering_stop(struct uct *u)
330 if (!thread_manager_running)
331 return;
333 /* Stop the thread manager. */
334 struct uct_thread_ctx *ctx = uct_search_stop();
335 if (UDEBUGL(1)) {
336 if (u->pondering) fprintf(stderr, "(pondering) ");
337 uct_progress_status(u, ctx->t, ctx->color, ctx->games);
339 if (u->pondering) {
340 free(ctx->b);
341 u->pondering = false;
346 void
347 uct_genmove_setup(struct uct *u, struct board *b, enum stone color)
349 if (b->superko_violation) {
350 fprintf(stderr, "!!! WARNING: SUPERKO VIOLATION OCCURED BEFORE THIS MOVE\n");
351 fprintf(stderr, "Maybe you play with situational instead of positional superko?\n");
352 fprintf(stderr, "I'm going to ignore the violation, but note that I may miss\n");
353 fprintf(stderr, "some moves valid under this ruleset because of this.\n");
354 b->superko_violation = false;
357 uct_prepare_move(u, b, color);
359 assert(u->t);
360 u->my_color = color;
362 /* How to decide whether to use dynkomi in this game? Since we use
363 * pondering, it's not simple "who-to-play" matter. Decide based on
364 * the last genmove issued. */
365 u->t->use_extra_komi = !!(u->dynkomi_mask & color);
366 setup_dynkomi(u, b, color);
368 if (b->rules == RULES_JAPANESE)
369 u->territory_scoring = true;
371 /* Make pessimistic assumption about komi for Japanese rules to
372 * avoid losing by 0.5 when winning by 0.5 with Chinese rules.
373 * The rules usually give the same winner if the integer part of komi
374 * is odd so we adjust the komi only if it is even (for a board of
375 * odd size). We are not trying to get an exact evaluation for rare
376 * cases of seki. For details see http://home.snafu.de/jasiek/parity.html */
377 if (u->territory_scoring && (((int)floor(b->komi) + board_size(b)) & 1)) {
378 b->komi += (color == S_BLACK ? 1.0 : -1.0);
379 if (UDEBUGL(0))
380 fprintf(stderr, "Setting komi to %.1f assuming Japanese rules\n",
381 b->komi);
385 static coord_t *
386 uct_genmove(struct engine *e, struct board *b, struct time_info *ti, enum stone color, bool pass_all_alive)
388 double start_time = time_now();
389 struct uct *u = e->data;
390 uct_pondering_stop(u);
391 uct_genmove_setup(u, b, color);
393 /* Start the Monte Carlo Tree Search! */
394 int base_playouts = u->t->root->u.playouts;
395 int played_games = uct_search(u, b, ti, color, u->t);
397 coord_t best_coord;
398 struct tree_node *best;
399 best = uct_search_result(u, b, color, pass_all_alive, played_games, base_playouts, &best_coord);
401 if (UDEBUGL(2)) {
402 double time = time_now() - start_time + 0.000001; /* avoid divide by zero */
403 fprintf(stderr, "genmove in %0.2fs (%d games/s, %d games/s/thread)\n",
404 time, (int)(played_games/time), (int)(played_games/time/u->threads));
407 if (!best) {
408 /* Pass or resign. */
409 reset_state(u);
410 return coord_copy(best_coord);
412 tree_promote_node(u->t, &best);
414 /* After a pass, pondering is harmful for two reasons:
415 * (i) We might keep pondering even when the game is over.
416 * Of course this is the case for opponent resign as well.
417 * (ii) More importantly, the ownermap will get skewed since
418 * the UCT will start cutting off any playouts. */
419 if (u->pondering_opt && !is_pass(best->coord)) {
420 uct_pondering_start(u, b, u->t, stone_other(color));
422 return coord_copy(best_coord);
426 bool
427 uct_genbook(struct engine *e, struct board *b, struct time_info *ti, enum stone color)
429 struct uct *u = e->data;
430 if (!u->t) uct_prepare_move(u, b, color);
431 assert(u->t);
433 if (ti->dim == TD_GAMES) {
434 /* Don't count in games that already went into the book. */
435 ti->len.games += u->t->root->u.playouts;
437 uct_search(u, b, ti, color, u->t);
439 assert(ti->dim == TD_GAMES);
440 tree_save(u->t, b, ti->len.games / 100);
442 return true;
445 void
446 uct_dumpbook(struct engine *e, struct board *b, enum stone color)
448 struct uct *u = e->data;
449 struct tree *t = tree_init(b, color, u->fast_alloc ? u->max_tree_size : 0, u->local_tree_aging, 0);
450 tree_load(t, b);
451 tree_dump(t, 0);
452 tree_done(t);
456 struct uct *
457 uct_state_init(char *arg, struct board *b)
459 struct uct *u = calloc2(1, sizeof(struct uct));
460 bool using_elo = false;
462 u->debug_level = debug_level;
463 u->gamelen = MC_GAMELEN;
464 u->mercymin = 0;
465 u->expand_p = 2;
466 u->dumpthres = 1000;
467 u->playout_amaf = true;
468 u->playout_amaf_nakade = false;
469 u->amaf_prior = false;
470 u->max_tree_size = 3072ULL * 1048576;
472 u->dynkomi_mask = S_BLACK;
474 u->threads = 1;
475 u->thread_model = TM_TREEVL;
476 u->virtual_loss = true;
478 u->fuseki_end = 20; // max time at 361*20% = 72 moves (our 36th move, still 99 to play)
479 u->yose_start = 40; // (100-40-25)*361/100/2 = 63 moves still to play by us then
480 u->bestr_ratio = 0.02;
481 // 2.5 is clearly too much, but seems to compensate well for overly stern time allocations.
482 // TODO: Further tuning and experiments with better time allocation schemes.
483 u->best2_ratio = 2.5;
485 u->val_scale = 0.04; u->val_points = 40;
486 u->dynkomi_interval = 250;
488 u->tenuki_d = 4;
489 u->local_tree_aging = 2;
491 u->plugins = pluginset_init(b);
493 if (arg) {
494 char *optspec, *next = arg;
495 while (*next) {
496 optspec = next;
497 next += strcspn(next, ",");
498 if (*next) { *next++ = 0; } else { *next = 0; }
500 char *optname = optspec;
501 char *optval = strchr(optspec, '=');
502 if (optval) *optval++ = 0;
504 if (!strcasecmp(optname, "debug")) {
505 if (optval)
506 u->debug_level = atoi(optval);
507 else
508 u->debug_level++;
509 } else if (!strcasecmp(optname, "mercy") && optval) {
510 /* Minimal difference of black/white captures
511 * to stop playout - "Mercy Rule". Speeds up
512 * hopeless playouts at the expense of some
513 * accuracy. */
514 u->mercymin = atoi(optval);
515 } else if (!strcasecmp(optname, "gamelen") && optval) {
516 u->gamelen = atoi(optval);
517 } else if (!strcasecmp(optname, "expand_p") && optval) {
518 u->expand_p = atoi(optval);
519 } else if (!strcasecmp(optname, "dumpthres") && optval) {
520 u->dumpthres = atoi(optval);
521 } else if (!strcasecmp(optname, "best2_ratio") && optval) {
522 /* If set, prolong simulating while
523 * first_best/second_best playouts ratio
524 * is less than best2_ratio. */
525 u->best2_ratio = atof(optval);
526 } else if (!strcasecmp(optname, "bestr_ratio") && optval) {
527 /* If set, prolong simulating while
528 * best,best_best_child values delta
529 * is more than bestr_ratio. */
530 u->bestr_ratio = atof(optval);
531 } else if (!strcasecmp(optname, "playout_amaf")) {
532 /* Whether to include random playout moves in
533 * AMAF as well. (Otherwise, only tree moves
534 * are included in AMAF. Of course makes sense
535 * only in connection with an AMAF policy.) */
536 /* with-without: 55.5% (+-4.1) */
537 if (optval && *optval == '0')
538 u->playout_amaf = false;
539 else
540 u->playout_amaf = true;
541 } else if (!strcasecmp(optname, "playout_amaf_nakade")) {
542 /* Whether to include nakade moves from playouts
543 * in the AMAF statistics; this tends to nullify
544 * the playout_amaf effect by adding too much
545 * noise. */
546 if (optval && *optval == '0')
547 u->playout_amaf_nakade = false;
548 else
549 u->playout_amaf_nakade = true;
550 } else if (!strcasecmp(optname, "playout_amaf_cutoff") && optval) {
551 /* Keep only first N% of playout stage AMAF
552 * information. */
553 u->playout_amaf_cutoff = atoi(optval);
554 } else if ((!strcasecmp(optname, "policy") || !strcasecmp(optname, "random_policy")) && optval) {
555 char *policyarg = strchr(optval, ':');
556 struct uct_policy **p = !strcasecmp(optname, "policy") ? &u->policy : &u->random_policy;
557 if (policyarg)
558 *policyarg++ = 0;
559 if (!strcasecmp(optval, "ucb1")) {
560 *p = policy_ucb1_init(u, policyarg);
561 } else if (!strcasecmp(optval, "ucb1amaf")) {
562 *p = policy_ucb1amaf_init(u, policyarg);
563 } else {
564 fprintf(stderr, "UCT: Invalid tree policy %s\n", optval);
565 exit(1);
567 } else if (!strcasecmp(optname, "playout") && optval) {
568 char *playoutarg = strchr(optval, ':');
569 if (playoutarg)
570 *playoutarg++ = 0;
571 if (!strcasecmp(optval, "moggy")) {
572 u->playout = playout_moggy_init(playoutarg, b);
573 } else if (!strcasecmp(optval, "light")) {
574 u->playout = playout_light_init(playoutarg, b);
575 } else if (!strcasecmp(optval, "elo")) {
576 u->playout = playout_elo_init(playoutarg, b);
577 using_elo = true;
578 } else {
579 fprintf(stderr, "UCT: Invalid playout policy %s\n", optval);
580 exit(1);
582 } else if (!strcasecmp(optname, "prior") && optval) {
583 u->prior = uct_prior_init(optval, b);
584 } else if (!strcasecmp(optname, "amaf_prior") && optval) {
585 u->amaf_prior = atoi(optval);
586 } else if (!strcasecmp(optname, "threads") && optval) {
587 /* By default, Pachi will run with only single
588 * tree search thread! */
589 u->threads = atoi(optval);
590 } else if (!strcasecmp(optname, "thread_model") && optval) {
591 if (!strcasecmp(optval, "tree")) {
592 /* Tree parallelization - all threads
593 * grind on the same tree. */
594 u->thread_model = TM_TREE;
595 u->virtual_loss = false;
596 } else if (!strcasecmp(optval, "treevl")) {
597 /* Tree parallelization, but also
598 * with virtual losses - this discou-
599 * rages most threads choosing the
600 * same tree branches to read. */
601 u->thread_model = TM_TREEVL;
602 u->virtual_loss = true;
603 } else {
604 fprintf(stderr, "UCT: Invalid thread model %s\n", optval);
605 exit(1);
607 } else if (!strcasecmp(optname, "pondering")) {
608 /* Keep searching even during opponent's turn. */
609 u->pondering_opt = !optval || atoi(optval);
610 } else if (!strcasecmp(optname, "fuseki_end") && optval) {
611 /* At the very beginning it's not worth thinking
612 * too long because the playout evaluations are
613 * very noisy. So gradually increase the thinking
614 * time up to maximum when fuseki_end percent
615 * of the board has been played.
616 * This only applies if we are not in byoyomi. */
617 u->fuseki_end = atoi(optval);
618 } else if (!strcasecmp(optname, "yose_start") && optval) {
619 /* When yose_start percent of the board has been
620 * played, or if we are in byoyomi, stop spending
621 * more time and spread the remaining time
622 * uniformly.
623 * Between fuseki_end and yose_start, we spend
624 * a constant proportion of the remaining time
625 * on each move. (yose_start should actually
626 * be much earlier than when real yose start,
627 * but "yose" is a good short name to convey
628 * the idea.) */
629 u->yose_start = atoi(optval);
630 } else if (!strcasecmp(optname, "force_seed") && optval) {
631 u->force_seed = atoi(optval);
632 } else if (!strcasecmp(optname, "no_book")) {
633 u->no_book = true;
634 } else if (!strcasecmp(optname, "dynkomi") && optval) {
635 /* Dynamic komi approach; there are multiple
636 * ways to adjust komi dynamically throughout
637 * play. We currently support two: */
638 char *dynkomiarg = strchr(optval, ':');
639 if (dynkomiarg)
640 *dynkomiarg++ = 0;
641 if (!strcasecmp(optval, "none")) {
642 u->dynkomi = uct_dynkomi_init_none(u, dynkomiarg, b);
643 } else if (!strcasecmp(optval, "linear")) {
644 u->dynkomi = uct_dynkomi_init_linear(u, dynkomiarg, b);
645 } else if (!strcasecmp(optval, "adaptive")) {
646 u->dynkomi = uct_dynkomi_init_adaptive(u, dynkomiarg, b);
647 } else {
648 fprintf(stderr, "UCT: Invalid dynkomi mode %s\n", optval);
649 exit(1);
651 } else if (!strcasecmp(optname, "dynkomi_mask") && optval) {
652 /* Bitmask of colors the player must be
653 * for dynkomi be applied; you may want
654 * to use dynkomi_mask=3 to allow dynkomi
655 * even in games where Pachi is white. */
656 u->dynkomi_mask = atoi(optval);
657 } else if (!strcasecmp(optname, "dynkomi_interval") && optval) {
658 /* If non-zero, re-adjust dynamic komi
659 * throughout a single genmove reading,
660 * roughly every N simulations. */
661 /* XXX: Does not work with tree
662 * parallelization. */
663 u->dynkomi_interval = atoi(optval);
664 } else if (!strcasecmp(optname, "val_scale") && optval) {
665 /* How much of the game result value should be
666 * influenced by win size. Zero means it isn't. */
667 u->val_scale = atof(optval);
668 } else if (!strcasecmp(optname, "val_points") && optval) {
669 /* Maximum size of win to be scaled into game
670 * result value. Zero means boardsize^2. */
671 u->val_points = atoi(optval) * 2; // result values are doubled
672 } else if (!strcasecmp(optname, "val_extra")) {
673 /* If false, the score coefficient will be simply
674 * added to the value, instead of scaling the result
675 * coefficient because of it. */
676 u->val_extra = !optval || atoi(optval);
677 } else if (!strcasecmp(optname, "local_tree") && optval) {
678 /* Whether to bias exploration by local tree values
679 * (must be supported by the used policy).
680 * 0: Don't.
681 * 1: Do, value = result.
682 * Try to temper the result:
683 * 2: Do, value = 0.5+(result-expected)/2.
684 * 3: Do, value = 0.5+bzz((result-expected)^2).
685 * 4: Do, value = 0.5+sqrt(result-expected)/2. */
686 u->local_tree = atoi(optval);
687 } else if (!strcasecmp(optname, "tenuki_d") && optval) {
688 /* Tenuki distance at which to break the local tree. */
689 u->tenuki_d = atoi(optval);
690 if (u->tenuki_d > TREE_NODE_D_MAX + 1) {
691 fprintf(stderr, "uct: tenuki_d must not be larger than TREE_NODE_D_MAX+1 %d\n", TREE_NODE_D_MAX + 1);
692 exit(1);
694 } else if (!strcasecmp(optname, "local_tree_aging") && optval) {
695 /* How much to reduce local tree values between moves. */
696 u->local_tree_aging = atof(optval);
697 } else if (!strcasecmp(optname, "local_tree_allseq")) {
698 /* By default, only complete sequences are stored
699 * in the local tree. If this is on, also
700 * subsequences starting at each move are stored. */
701 u->local_tree_allseq = !optval || atoi(optval);
702 } else if (!strcasecmp(optname, "local_tree_playout")) {
703 /* Whether to adjust ELO playout probability
704 * distributions according to matched localtree
705 * information. */
706 u->local_tree_playout = !optval || atoi(optval);
707 } else if (!strcasecmp(optname, "local_tree_pseqroot")) {
708 /* By default, when we have no sequence move
709 * to suggest in-playout, we give up. If this
710 * is on, we make probability distribution from
711 * sequences first moves instead. */
712 u->local_tree_pseqroot = !optval || atoi(optval);
713 } else if (!strcasecmp(optname, "pass_all_alive")) {
714 /* Whether to consider passing only after all
715 * dead groups were removed from the board;
716 * this is like all genmoves are in fact
717 * kgs-genmove_cleanup. */
718 u->pass_all_alive = !optval || atoi(optval);
719 } else if (!strcasecmp(optname, "territory_scoring")) {
720 /* Use territory scoring (default is area scoring).
721 * An explicit kgs-rules command overrides this. */
722 u->territory_scoring = !optval || atoi(optval);
723 } else if (!strcasecmp(optname, "random_policy_chance") && optval) {
724 /* If specified (N), with probability 1/N, random_policy policy
725 * descend is used instead of main policy descend; useful
726 * if specified policy (e.g. UCB1AMAF) can make unduly biased
727 * choices sometimes, you can fall back to e.g.
728 * random_policy=UCB1. */
729 u->random_policy_chance = atoi(optval);
730 } else if (!strcasecmp(optname, "max_tree_size") && optval) {
731 /* Maximum amount of memory [MiB] consumed by the move tree.
732 * For fast_alloc it includes the temp tree used for pruning.
733 * Default is 3072 (3 GiB). */
734 u->max_tree_size = atol(optval) * 1048576;
735 } else if (!strcasecmp(optname, "fast_alloc")) {
736 u->fast_alloc = !optval || atoi(optval);
737 } else if (!strcasecmp(optname, "slave")) {
738 /* Act as slave for the distributed engine. */
739 u->slave = !optval || atoi(optval);
740 } else if (!strcasecmp(optname, "shared_nodes") && optval) {
741 /* Share at most shared_nodes between master and slave at each genmoves.
742 * Must use the same value in master and slaves. */
743 u->shared_nodes = atoi(optval);
744 } else if (!strcasecmp(optname, "shared_levels") && optval) {
745 /* Share only nodes of level <= shared_levels. */
746 u->shared_levels = atoi(optval);
747 } else if (!strcasecmp(optname, "stats_hbits") && optval) {
748 /* Set hash table size to 2^stats_hbits for the shared stats. */
749 u->stats_hbits = atoi(optval);
750 } else if (!strcasecmp(optname, "banner") && optval) {
751 /* Additional banner string. This must come as the
752 * last engine parameter. */
753 if (*next) *--next = ',';
754 u->banner = strdup(optval);
755 break;
756 } else if (!strcasecmp(optname, "plugin") && optval) {
757 /* Load an external plugin; filename goes before the colon,
758 * extra arguments after the colon. */
759 char *pluginarg = strchr(optval, ':');
760 if (pluginarg)
761 *pluginarg++ = 0;
762 plugin_load(u->plugins, optval, pluginarg);
763 } else {
764 fprintf(stderr, "uct: Invalid engine argument %s or missing value\n", optname);
765 exit(1);
770 u->resign_ratio = 0.2; /* Resign when most games are lost. */
771 u->loss_threshold = 0.85; /* Stop reading if after at least 2000 playouts this is best value. */
772 if (!u->policy)
773 u->policy = policy_ucb1amaf_init(u, NULL);
775 if (!!u->random_policy_chance ^ !!u->random_policy) {
776 fprintf(stderr, "uct: Only one of random_policy and random_policy_chance is set\n");
777 exit(1);
780 if (!u->local_tree) {
781 /* No ltree aging. */
782 u->local_tree_aging = 1.0f;
784 if (!using_elo)
785 u->local_tree_playout = false;
787 if (u->fast_alloc)
788 u->max_tree_size = (100ULL * u->max_tree_size) / (100 + MIN_FREE_MEM_PERCENT);
790 if (!u->prior)
791 u->prior = uct_prior_init(NULL, b);
793 if (!u->playout)
794 u->playout = playout_moggy_init(NULL, b);
795 u->playout->debug_level = u->debug_level;
797 u->ownermap.map = malloc2(board_size2(b) * sizeof(u->ownermap.map[0]));
799 if (u->slave) {
800 if (!u->stats_hbits) u->stats_hbits = DEFAULT_STATS_HBITS;
801 if (!u->shared_nodes) u->shared_nodes = DEFAULT_SHARED_NODES;
802 if (!u->shared_levels) u->shared_levels = 1;
803 assert(u->shared_levels * board_bits2(b) <= 8 * (int)sizeof(path_t));
806 if (!u->dynkomi)
807 u->dynkomi = uct_dynkomi_init_linear(u, NULL, b);
809 /* Some things remain uninitialized for now - the opening book
810 * is not loaded and the tree not set up. */
811 /* This will be initialized in setup_state() at the first move
812 * received/requested. This is because right now we are not aware
813 * about any komi or handicap setup and such. */
815 return u;
818 struct engine *
819 engine_uct_init(char *arg, struct board *b)
821 struct uct *u = uct_state_init(arg, b);
822 struct engine *e = calloc2(1, sizeof(struct engine));
823 e->name = "UCT Engine";
824 e->printhook = uct_printhook_ownermap;
825 e->notify_play = uct_notify_play;
826 e->chat = uct_chat;
827 e->genmove = uct_genmove;
828 e->genmoves = uct_genmoves;
829 e->dead_group_list = uct_dead_group_list;
830 e->done = uct_done;
831 e->data = u;
832 if (u->slave)
833 e->notify = uct_notify;
835 const char banner[] = "I'm playing UCT. When I'm losing, I will resign, "
836 "if I think I win, I play until you pass. "
837 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
838 if (!u->banner) u->banner = "";
839 e->comment = malloc2(sizeof(banner) + strlen(u->banner) + 1);
840 sprintf(e->comment, "%s %s", banner, u->banner);
842 return e;