uct_search_best() -> uct_search_result()
[pachi/derm.git] / uct / uct.c
blob0be072eca4222d8a356396c64837308f2c7f9f19
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 "distributed/distributed.h"
22 #include "uct/dynkomi.h"
23 #include "uct/internal.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_stop(struct uct *u);
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, u->local_tree_aging);
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->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);
82 } else {
83 /* We need fresh state. */
84 b->es = u;
85 setup_state(u, b, color);
88 u->ownermap.playouts = 0;
89 memset(u->ownermap.map, 0, board_size2(b) * sizeof(u->ownermap.map[0]));
90 memset(u->stats, 0, board_size2(b) * sizeof(u->stats[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 /* Mock up some state and seed the ownermap by few
216 * simulations. */
217 uct_prepare_move(u, b, S_BLACK); assert(u->t);
218 for (int i = 0; i < GJ_MINGAMES; i++)
219 uct_playout(u, b, S_BLACK, u->t);
220 mock_state = true;
223 dead_group_list(u, b, mq);
225 if (mock_state) {
226 /* Clean up the mock state in case we will receive
227 * a genmove; we could get a non-alternating-move
228 * error from uct_prepare_move() in that case otherwise. */
229 reset_state(u);
233 static void
234 playout_policy_done(struct playout_policy *p)
236 if (p->done) p->done(p);
237 if (p->data) free(p->data);
238 free(p);
241 static void
242 uct_done(struct engine *e)
244 /* This is called on engine reset, especially when clear_board
245 * is received and new game should begin. */
246 struct uct *u = e->data;
247 uct_pondering_stop(u);
248 if (u->t) reset_state(u);
249 free(u->ownermap.map);
250 free(u->stats);
252 free(u->policy);
253 free(u->random_policy);
254 playout_policy_done(u->playout);
255 uct_prior_done(u->prior);
260 /* Run time-limited MCTS search on foreground. */
261 static int
262 uct_search(struct uct *u, struct board *b, struct time_info *ti, enum stone color, struct tree *t)
264 struct uct_search_state s;
265 uct_search_start(u, b, color, t, ti, &s);
266 if (UDEBUGL(2) && s.base_playouts > 0)
267 fprintf(stderr, "<pre-simulated %d games>\n", s.base_playouts);
269 /* The search tree is ctx->t. This is normally == t, but in case of
270 * TM_ROOT, it is one of the trees belonging to the independent
271 * workers. It is important to reference ctx->t directly since the
272 * thread manager will swap the tree pointer asynchronously. */
273 /* XXX: This means TM_ROOT support is suboptimal since single stalled
274 * thread can stall the others in case of limiting the search by game
275 * count. However, TM_ROOT just does not deserve any more extra code
276 * right now. */
278 /* Now, just periodically poll the search tree. */
279 while (1) {
280 time_sleep(TREE_BUSYWAIT_INTERVAL);
281 /* TREE_BUSYWAIT_INTERVAL should never be less than desired time, or the
282 * time control is broken. But if it happens to be less, we still search
283 * at least 100ms otherwise the move is completely random. */
285 int i = uct_search_games(&s);
286 /* Print notifications etc. */
287 uct_search_progress(u, b, color, t, ti, &s, i);
288 /* Check if we should stop the search. */
289 if (uct_search_check_stop(u, b, color, t, ti, &s, i))
290 break;
293 struct uct_thread_ctx *ctx = uct_search_stop();
294 if (UDEBUGL(2)) tree_dump(t, u->dumpthres);
295 if (UDEBUGL(2))
296 fprintf(stderr, "(avg score %f/%d value %f/%d)\n",
297 u->dynkomi->score.value, u->dynkomi->score.playouts,
298 u->dynkomi->value.value, u->dynkomi->value.playouts);
299 if (UDEBUGL(0))
300 uct_progress_status(u, t, color, ctx->games);
302 u->played_own += ctx->games;
303 return ctx->games;
306 /* Start pondering background with @color to play. */
307 static void
308 uct_pondering_start(struct uct *u, struct board *b0, struct tree *t, enum stone color)
310 if (UDEBUGL(1))
311 fprintf(stderr, "Starting to ponder with color %s\n", stone2str(stone_other(color)));
312 u->pondering = true;
314 /* We need a local board copy to ponder upon. */
315 struct board *b = malloc2(sizeof(*b)); board_copy(b, b0);
317 /* *b0 did not have the genmove'd move played yet. */
318 struct move m = { t->root->coord, t->root_color };
319 int res = board_play(b, &m);
320 assert(res >= 0);
321 setup_dynkomi(u, b, stone_other(m.color));
323 /* Start MCTS manager thread "headless". */
324 static struct uct_search_state s;
325 uct_search_start(u, b, color, t, NULL, &s);
328 /* uct_search_stop() frontend for the pondering (non-genmove) mode, and
329 * to stop the background search for a slave in the distributed engine. */
330 static void
331 uct_pondering_stop(struct uct *u)
333 if (!thread_manager_running)
334 return;
336 /* Stop the thread manager. */
337 struct uct_thread_ctx *ctx = uct_search_stop();
338 if (UDEBUGL(1)) {
339 if (u->pondering) fprintf(stderr, "(pondering) ");
340 uct_progress_status(u, ctx->t, ctx->color, ctx->games);
342 if (u->pondering) {
343 free(ctx->b);
344 u->pondering = false;
349 void
350 uct_genmove_setup(struct uct *u, struct board *b, enum stone color)
352 if (b->superko_violation) {
353 fprintf(stderr, "!!! WARNING: SUPERKO VIOLATION OCCURED BEFORE THIS MOVE\n");
354 fprintf(stderr, "Maybe you play with situational instead of positional superko?\n");
355 fprintf(stderr, "I'm going to ignore the violation, but note that I may miss\n");
356 fprintf(stderr, "some moves valid under this ruleset because of this.\n");
357 b->superko_violation = false;
360 uct_prepare_move(u, b, color);
362 assert(u->t);
363 u->my_color = color;
365 /* How to decide whether to use dynkomi in this game? Since we use
366 * pondering, it's not simple "who-to-play" matter. Decide based on
367 * the last genmove issued. */
368 u->t->use_extra_komi = !!(u->dynkomi_mask & color);
369 setup_dynkomi(u, b, color);
371 if (b->rules == RULES_JAPANESE)
372 u->territory_scoring = true;
374 /* Make pessimistic assumption about komi for Japanese rules to
375 * avoid losing by 0.5 when winning by 0.5 with Chinese rules.
376 * The rules usually give the same winner if the integer part of komi
377 * is odd so we adjust the komi only if it is even (for a board of
378 * odd size). We are not trying to get an exact evaluation for rare
379 * cases of seki. For details see http://home.snafu.de/jasiek/parity.html */
380 if (u->territory_scoring && (((int)floor(b->komi) + board_size(b)) & 1)) {
381 b->komi += (color == S_BLACK ? 1.0 : -1.0);
382 if (UDEBUGL(0))
383 fprintf(stderr, "Setting komi to %.1f assuming Japanese rules\n",
384 b->komi);
388 static coord_t *
389 uct_genmove(struct engine *e, struct board *b, struct time_info *ti, enum stone color, bool pass_all_alive)
391 double start_time = time_now();
392 struct uct *u = e->data;
393 uct_pondering_stop(u);
394 uct_genmove_setup(u, b, color);
396 /* Start the Monte Carlo Tree Search! */
397 int base_playouts = u->t->root->u.playouts;
398 int played_games = uct_search(u, b, ti, color, u->t);
400 coord_t best_coord;
401 struct tree_node *best;
402 best = uct_search_result(u, b, color, pass_all_alive, played_games, base_playouts, &best_coord);
404 if (UDEBUGL(2)) {
405 double time = time_now() - start_time + 0.000001; /* avoid divide by zero */
406 fprintf(stderr, "genmove in %0.2fs (%d games/s, %d games/s/thread)\n",
407 time, (int)(played_games/time), (int)(played_games/time/u->threads));
410 if (!best) {
411 /* Pass or resign. */
412 reset_state(u);
413 return coord_copy(best_coord);
415 tree_promote_node(u->t, &best);
417 /* After a pass, pondering is harmful for two reasons:
418 * (i) We might keep pondering even when the game is over.
419 * Of course this is the case for opponent resign as well.
420 * (ii) More importantly, the ownermap will get skewed since
421 * the UCT will start cutting off any playouts. */
422 if (u->pondering_opt && !is_pass(best->coord)) {
423 uct_pondering_start(u, b, u->t, stone_other(color));
425 return coord_copy(best_coord);
429 bool
430 uct_genbook(struct engine *e, struct board *b, struct time_info *ti, enum stone color)
432 struct uct *u = e->data;
433 if (!u->t) uct_prepare_move(u, b, color);
434 assert(u->t);
436 if (ti->dim == TD_GAMES) {
437 /* Don't count in games that already went into the book. */
438 ti->len.games += u->t->root->u.playouts;
440 uct_search(u, b, ti, color, u->t);
442 assert(ti->dim == TD_GAMES);
443 tree_save(u->t, b, ti->len.games / 100);
445 return true;
448 void
449 uct_dumpbook(struct engine *e, struct board *b, enum stone color)
451 struct uct *u = e->data;
452 struct tree *t = tree_init(b, color, u->fast_alloc ? u->max_tree_size : 0, u->local_tree_aging);
453 tree_load(t, b);
454 tree_dump(t, 0);
455 tree_done(t);
459 struct uct *
460 uct_state_init(char *arg, struct board *b)
462 struct uct *u = calloc2(1, sizeof(struct uct));
463 bool using_elo = false;
465 u->debug_level = debug_level;
466 u->gamelen = MC_GAMELEN;
467 u->mercymin = 0;
468 u->expand_p = 2;
469 u->dumpthres = 1000;
470 u->playout_amaf = true;
471 u->playout_amaf_nakade = false;
472 u->amaf_prior = false;
473 u->max_tree_size = 3072ULL * 1048576;
475 u->dynkomi_mask = S_BLACK;
477 u->threads = 1;
478 u->thread_model = TM_TREEVL;
479 u->parallel_tree = true;
480 u->virtual_loss = true;
482 u->fuseki_end = 20; // max time at 361*20% = 72 moves (our 36th move, still 99 to play)
483 u->yose_start = 40; // (100-40-25)*361/100/2 = 63 moves still to play by us then
484 u->bestr_ratio = 0.02;
485 // 2.5 is clearly too much, but seems to compensate well for overly stern time allocations.
486 // TODO: Further tuning and experiments with better time allocation schemes.
487 u->best2_ratio = 2.5;
489 u->val_scale = 0.04; u->val_points = 40;
491 u->tenuki_d = 4;
492 u->local_tree_aging = 2;
494 if (arg) {
495 char *optspec, *next = arg;
496 while (*next) {
497 optspec = next;
498 next += strcspn(next, ",");
499 if (*next) { *next++ = 0; } else { *next = 0; }
501 char *optname = optspec;
502 char *optval = strchr(optspec, '=');
503 if (optval) *optval++ = 0;
505 if (!strcasecmp(optname, "debug")) {
506 if (optval)
507 u->debug_level = atoi(optval);
508 else
509 u->debug_level++;
510 } else if (!strcasecmp(optname, "mercy") && optval) {
511 /* Minimal difference of black/white captures
512 * to stop playout - "Mercy Rule". Speeds up
513 * hopeless playouts at the expense of some
514 * accuracy. */
515 u->mercymin = atoi(optval);
516 } else if (!strcasecmp(optname, "gamelen") && optval) {
517 u->gamelen = atoi(optval);
518 } else if (!strcasecmp(optname, "expand_p") && optval) {
519 u->expand_p = atoi(optval);
520 } else if (!strcasecmp(optname, "dumpthres") && optval) {
521 u->dumpthres = atoi(optval);
522 } else if (!strcasecmp(optname, "best2_ratio") && optval) {
523 /* If set, prolong simulating while
524 * first_best/second_best playouts ratio
525 * is less than best2_ratio. */
526 u->best2_ratio = atof(optval);
527 } else if (!strcasecmp(optname, "bestr_ratio") && optval) {
528 /* If set, prolong simulating while
529 * best,best_best_child values delta
530 * is more than bestr_ratio. */
531 u->bestr_ratio = atof(optval);
532 } else if (!strcasecmp(optname, "playout_amaf")) {
533 /* Whether to include random playout moves in
534 * AMAF as well. (Otherwise, only tree moves
535 * are included in AMAF. Of course makes sense
536 * only in connection with an AMAF policy.) */
537 /* with-without: 55.5% (+-4.1) */
538 if (optval && *optval == '0')
539 u->playout_amaf = false;
540 else
541 u->playout_amaf = true;
542 } else if (!strcasecmp(optname, "playout_amaf_nakade")) {
543 /* Whether to include nakade moves from playouts
544 * in the AMAF statistics; this tends to nullify
545 * the playout_amaf effect by adding too much
546 * noise. */
547 if (optval && *optval == '0')
548 u->playout_amaf_nakade = false;
549 else
550 u->playout_amaf_nakade = true;
551 } else if (!strcasecmp(optname, "playout_amaf_cutoff") && optval) {
552 /* Keep only first N% of playout stage AMAF
553 * information. */
554 u->playout_amaf_cutoff = atoi(optval);
555 } else if ((!strcasecmp(optname, "policy") || !strcasecmp(optname, "random_policy")) && optval) {
556 char *policyarg = strchr(optval, ':');
557 struct uct_policy **p = !strcasecmp(optname, "policy") ? &u->policy : &u->random_policy;
558 if (policyarg)
559 *policyarg++ = 0;
560 if (!strcasecmp(optval, "ucb1")) {
561 *p = policy_ucb1_init(u, policyarg);
562 } else if (!strcasecmp(optval, "ucb1amaf")) {
563 *p = policy_ucb1amaf_init(u, policyarg);
564 } else {
565 fprintf(stderr, "UCT: Invalid tree policy %s\n", optval);
566 exit(1);
568 } else if (!strcasecmp(optname, "playout") && optval) {
569 char *playoutarg = strchr(optval, ':');
570 if (playoutarg)
571 *playoutarg++ = 0;
572 if (!strcasecmp(optval, "moggy")) {
573 u->playout = playout_moggy_init(playoutarg, b);
574 } else if (!strcasecmp(optval, "light")) {
575 u->playout = playout_light_init(playoutarg, b);
576 } else if (!strcasecmp(optval, "elo")) {
577 u->playout = playout_elo_init(playoutarg, b);
578 using_elo = true;
579 } else {
580 fprintf(stderr, "UCT: Invalid playout policy %s\n", optval);
581 exit(1);
583 } else if (!strcasecmp(optname, "prior") && optval) {
584 u->prior = uct_prior_init(optval, b);
585 } else if (!strcasecmp(optname, "amaf_prior") && optval) {
586 u->amaf_prior = atoi(optval);
587 } else if (!strcasecmp(optname, "threads") && optval) {
588 /* By default, Pachi will run with only single
589 * tree search thread! */
590 u->threads = atoi(optval);
591 } else if (!strcasecmp(optname, "thread_model") && optval) {
592 if (!strcasecmp(optval, "root")) {
593 /* Root parallelization - each thread
594 * does independent search, trees are
595 * merged at the end. */
596 u->thread_model = TM_ROOT;
597 u->parallel_tree = false;
598 u->virtual_loss = false;
599 } else if (!strcasecmp(optval, "tree")) {
600 /* Tree parallelization - all threads
601 * grind on the same tree. */
602 u->thread_model = TM_TREE;
603 u->parallel_tree = true;
604 u->virtual_loss = false;
605 } else if (!strcasecmp(optval, "treevl")) {
606 /* Tree parallelization, but also
607 * with virtual losses - this discou-
608 * rages most threads choosing the
609 * same tree branches to read. */
610 u->thread_model = TM_TREEVL;
611 u->parallel_tree = true;
612 u->virtual_loss = true;
613 } else {
614 fprintf(stderr, "UCT: Invalid thread model %s\n", optval);
615 exit(1);
617 } else if (!strcasecmp(optname, "pondering")) {
618 /* Keep searching even during opponent's turn. */
619 u->pondering_opt = !optval || atoi(optval);
620 } else if (!strcasecmp(optname, "fuseki_end") && optval) {
621 /* At the very beginning it's not worth thinking
622 * too long because the playout evaluations are
623 * very noisy. So gradually increase the thinking
624 * time up to maximum when fuseki_end percent
625 * of the board has been played.
626 * This only applies if we are not in byoyomi. */
627 u->fuseki_end = atoi(optval);
628 } else if (!strcasecmp(optname, "yose_start") && optval) {
629 /* When yose_start percent of the board has been
630 * played, or if we are in byoyomi, stop spending
631 * more time and spread the remaining time
632 * uniformly.
633 * Between fuseki_end and yose_start, we spend
634 * a constant proportion of the remaining time
635 * on each move. (yose_start should actually
636 * be much earlier than when real yose start,
637 * but "yose" is a good short name to convey
638 * the idea.) */
639 u->yose_start = atoi(optval);
640 } else if (!strcasecmp(optname, "force_seed") && optval) {
641 u->force_seed = atoi(optval);
642 } else if (!strcasecmp(optname, "no_book")) {
643 u->no_book = true;
644 } else if (!strcasecmp(optname, "dynkomi") && optval) {
645 /* Dynamic komi approach; there are multiple
646 * ways to adjust komi dynamically throughout
647 * play. We currently support two: */
648 char *dynkomiarg = strchr(optval, ':');
649 if (dynkomiarg)
650 *dynkomiarg++ = 0;
651 if (!strcasecmp(optval, "none")) {
652 u->dynkomi = uct_dynkomi_init_none(u, dynkomiarg, b);
653 } else if (!strcasecmp(optval, "linear")) {
654 u->dynkomi = uct_dynkomi_init_linear(u, dynkomiarg, b);
655 } else if (!strcasecmp(optval, "adaptive")) {
656 u->dynkomi = uct_dynkomi_init_adaptive(u, dynkomiarg, b);
657 } else {
658 fprintf(stderr, "UCT: Invalid dynkomi mode %s\n", optval);
659 exit(1);
661 } else if (!strcasecmp(optname, "dynkomi_mask") && optval) {
662 /* Bitmask of colors the player must be
663 * for dynkomi be applied; you may want
664 * to use dynkomi_mask=3 to allow dynkomi
665 * even in games where Pachi is white. */
666 u->dynkomi_mask = atoi(optval);
667 } else if (!strcasecmp(optname, "dynkomi_interval") && optval) {
668 /* If non-zero, re-adjust dynamic komi
669 * throughout a single genmove reading,
670 * roughly every N simulations. */
671 /* XXX: Does not work with tree
672 * parallelization. */
673 u->dynkomi_interval = atoi(optval);
674 } else if (!strcasecmp(optname, "val_scale") && optval) {
675 /* How much of the game result value should be
676 * influenced by win size. Zero means it isn't. */
677 u->val_scale = atof(optval);
678 } else if (!strcasecmp(optname, "val_points") && optval) {
679 /* Maximum size of win to be scaled into game
680 * result value. Zero means boardsize^2. */
681 u->val_points = atoi(optval) * 2; // result values are doubled
682 } else if (!strcasecmp(optname, "val_extra")) {
683 /* If false, the score coefficient will be simply
684 * added to the value, instead of scaling the result
685 * coefficient because of it. */
686 u->val_extra = !optval || atoi(optval);
687 } else if (!strcasecmp(optname, "local_tree") && optval) {
688 /* Whether to bias exploration by local tree values
689 * (must be supported by the used policy).
690 * 0: Don't.
691 * 1: Do, value = result.
692 * Try to temper the result:
693 * 2: Do, value = 0.5+(result-expected)/2.
694 * 3: Do, value = 0.5+bzz((result-expected)^2).
695 * 4: Do, value = 0.5+sqrt(result-expected)/2. */
696 u->local_tree = atoi(optval);
697 } else if (!strcasecmp(optname, "tenuki_d") && optval) {
698 /* Tenuki distance at which to break the local tree. */
699 u->tenuki_d = atoi(optval);
700 if (u->tenuki_d > TREE_NODE_D_MAX + 1) {
701 fprintf(stderr, "uct: tenuki_d must not be larger than TREE_NODE_D_MAX+1 %d\n", TREE_NODE_D_MAX + 1);
702 exit(1);
704 } else if (!strcasecmp(optname, "local_tree_aging") && optval) {
705 /* How much to reduce local tree values between moves. */
706 u->local_tree_aging = atof(optval);
707 } else if (!strcasecmp(optname, "local_tree_allseq")) {
708 /* By default, only complete sequences are stored
709 * in the local tree. If this is on, also
710 * subsequences starting at each move are stored. */
711 u->local_tree_allseq = !optval || atoi(optval);
712 } else if (!strcasecmp(optname, "local_tree_playout")) {
713 /* Whether to adjust ELO playout probability
714 * distributions according to matched localtree
715 * information. */
716 u->local_tree_playout = !optval || atoi(optval);
717 } else if (!strcasecmp(optname, "local_tree_pseqroot")) {
718 /* By default, when we have no sequence move
719 * to suggest in-playout, we give up. If this
720 * is on, we make probability distribution from
721 * sequences first moves instead. */
722 u->local_tree_pseqroot = !optval || atoi(optval);
723 } else if (!strcasecmp(optname, "pass_all_alive")) {
724 /* Whether to consider passing only after all
725 * dead groups were removed from the board;
726 * this is like all genmoves are in fact
727 * kgs-genmove_cleanup. */
728 u->pass_all_alive = !optval || atoi(optval);
729 } else if (!strcasecmp(optname, "territory_scoring")) {
730 /* Use territory scoring (default is area scoring).
731 * An explicit kgs-rules command overrides this. */
732 u->territory_scoring = !optval || atoi(optval);
733 } else if (!strcasecmp(optname, "random_policy_chance") && optval) {
734 /* If specified (N), with probability 1/N, random_policy policy
735 * descend is used instead of main policy descend; useful
736 * if specified policy (e.g. UCB1AMAF) can make unduly biased
737 * choices sometimes, you can fall back to e.g.
738 * random_policy=UCB1. */
739 u->random_policy_chance = atoi(optval);
740 } else if (!strcasecmp(optname, "max_tree_size") && optval) {
741 /* Maximum amount of memory [MiB] consumed by the move tree.
742 * For fast_alloc it includes the temp tree used for pruning.
743 * Default is 3072 (3 GiB). Note that if you use TM_ROOT,
744 * this limits size of only one of the trees, not all of them
745 * together. */
746 u->max_tree_size = atol(optval) * 1048576;
747 } else if (!strcasecmp(optname, "fast_alloc")) {
748 u->fast_alloc = !optval || atoi(optval);
749 } else if (!strcasecmp(optname, "slave")) {
750 /* Act as slave for the distributed engine. */
751 u->slave = !optval || atoi(optval);
752 } else if (!strcasecmp(optname, "banner") && optval) {
753 /* Additional banner string. This must come as the
754 * last engine parameter. */
755 if (*next) *--next = ',';
756 u->banner = strdup(optval);
757 break;
758 } else {
759 fprintf(stderr, "uct: Invalid engine argument %s or missing value\n", optname);
760 exit(1);
765 u->resign_ratio = 0.2; /* Resign when most games are lost. */
766 u->loss_threshold = 0.85; /* Stop reading if after at least 2000 playouts this is best value. */
767 if (!u->policy)
768 u->policy = policy_ucb1amaf_init(u, NULL);
770 if (!!u->random_policy_chance ^ !!u->random_policy) {
771 fprintf(stderr, "uct: Only one of random_policy and random_policy_chance is set\n");
772 exit(1);
775 if (!u->local_tree) {
776 /* No ltree aging. */
777 u->local_tree_aging = 1.0f;
779 if (!using_elo)
780 u->local_tree_playout = false;
782 if (u->fast_alloc && !u->parallel_tree) {
783 fprintf(stderr, "fast_alloc not supported with root parallelization.\n");
784 exit(1);
786 if (u->fast_alloc)
787 u->max_tree_size = (100ULL * u->max_tree_size) / (100 + MIN_FREE_MEM_PERCENT);
789 if (!u->prior)
790 u->prior = uct_prior_init(NULL, b);
792 if (!u->playout)
793 u->playout = playout_moggy_init(NULL, b);
794 u->playout->debug_level = u->debug_level;
796 u->ownermap.map = malloc2(board_size2(b) * sizeof(u->ownermap.map[0]));
797 u->stats = malloc2(board_size2(b) * sizeof(u->stats[0]));
799 if (!u->dynkomi)
800 u->dynkomi = uct_dynkomi_init_linear(u, NULL, b);
802 /* Some things remain uninitialized for now - the opening book
803 * is not loaded and the tree not set up. */
804 /* This will be initialized in setup_state() at the first move
805 * received/requested. This is because right now we are not aware
806 * about any komi or handicap setup and such. */
808 return u;
811 struct engine *
812 engine_uct_init(char *arg, struct board *b)
814 struct uct *u = uct_state_init(arg, b);
815 struct engine *e = calloc2(1, sizeof(struct engine));
816 e->name = "UCT Engine";
817 e->printhook = uct_printhook_ownermap;
818 e->notify_play = uct_notify_play;
819 e->chat = uct_chat;
820 e->genmove = uct_genmove;
821 e->genmoves = uct_genmoves;
822 e->dead_group_list = uct_dead_group_list;
823 e->done = uct_done;
824 e->data = u;
825 if (u->slave)
826 e->notify = uct_notify;
828 const char banner[] = "I'm playing UCT. When I'm losing, I will resign, "
829 "if I think I win, I play until you pass. "
830 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
831 if (!u->banner) u->banner = "";
832 e->comment = malloc2(sizeof(banner) + strlen(u->banner) + 1);
833 sprintf(e->comment, "%s %s", banner, u->banner);
835 return e;