15 #include "joseki/base.h"
17 #include "playout/moggy.h"
18 #include "playout/light.h"
19 #include "tactics/util.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"
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
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
->max_pruned_size
, u
->pruning_threshold
, u
->local_tree_aging
, u
->stats_hbits
);
44 u
->t
->extra_komi
= u
->saved_extra_komi
;
46 fast_srandom(u
->force_seed
);
48 fprintf(stderr
, "Fresh board with random seed %lu\n", fast_getseed());
49 //board_print(b, stderr);
50 if (!u
->no_tbook
&& b
->moves
== 0) {
51 assert(color
== S_BLACK
);
57 remove_tree(struct uct
*u
)
60 tree_done(u
->t
); u
->t
= NULL
;
64 reset_state(struct uct
*u
)
66 u
->saved_extra_komi
= 0.0;
71 reset_state_keep_komi(struct uct
*u
)
73 u
->saved_extra_komi
= u
->t
->extra_komi
;
78 setup_dynkomi(struct uct
*u
, struct board
*b
, enum stone to_play
)
80 if (u
->t
->use_extra_komi
&& !u
->pondering
&& u
->dynkomi
->permove
)
81 u
->t
->extra_komi
= u
->dynkomi
->permove(u
->dynkomi
, b
, u
->t
);
82 else if (!u
->t
->use_extra_komi
)
87 uct_prepare_move(struct uct
*u
, struct board
*b
, enum stone color
)
90 /* Verify that we have sane state. */
92 assert(u
->t
&& b
->moves
);
93 if (color
!= stone_other(u
->t
->root_color
)) {
94 fprintf(stderr
, "Fatal: Non-alternating play detected %d %d\n",
95 color
, u
->t
->root_color
);
98 uct_htable_reset(u
->t
);
101 /* We need fresh state. */
103 setup_state(u
, b
, color
);
106 u
->ownermap
.playouts
= 0;
107 memset(u
->ownermap
.map
, 0, board_size2(b
) * sizeof(u
->ownermap
.map
[0]));
108 u
->played_own
= u
->played_all
= 0;
112 dead_group_list(struct uct
*u
, struct board
*b
, struct move_queue
*mq
)
114 struct group_judgement gj
;
116 gj
.gs
= alloca(board_size2(b
) * sizeof(gj
.gs
[0]));
117 board_ownermap_judge_group(b
, &u
->ownermap
, &gj
);
118 groups_of_status(b
, &gj
, GS_DEAD
, mq
);
122 uct_pass_is_safe(struct uct
*u
, struct board
*b
, enum stone color
, bool pass_all_alive
)
124 if (u
->ownermap
.playouts
< GJ_MINGAMES
)
127 struct move_queue mq
= { .moves
= 0 };
128 dead_group_list(u
, b
, &mq
);
129 if (pass_all_alive
&& mq
.moves
> 0)
130 return false; // We need to remove some dead groups first.
131 return pass_is_safe(b
, color
, &mq
);
135 uct_printhook_ownermap(struct board
*board
, coord_t c
, char *s
, char *end
)
137 struct uct
*u
= board
->es
;
142 const char chr
[] = ":XO,"; // dame, black, white, unclear
143 const char chm
[] = ":xo,";
144 char ch
= chr
[board_ownermap_judge_point(&u
->ownermap
, c
, GJ_THRES
)];
145 if (ch
== ',') { // less precise estimate then?
146 ch
= chm
[board_ownermap_judge_point(&u
->ownermap
, c
, 0.67)];
148 s
+= snprintf(s
, end
- s
, "%c ", ch
);
153 uct_notify_play(struct engine
*e
, struct board
*b
, struct move
*m
)
155 struct uct
*u
= e
->data
;
157 /* No state, create one - this is probably game beginning
158 * and we need to load the opening tbook right now. */
159 uct_prepare_move(u
, b
, m
->color
);
163 /* Stop pondering, required by tree_promote_at() */
164 uct_pondering_stop(u
);
165 if (UDEBUGL(2) && u
->slave
) /* remove the u->slave test to show the pruned tree */
166 tree_dump(u
->t
, u
->dumpthres
, u
->unlimited_tree_dump
);
168 if (is_resign(m
->coord
)) {
174 /* Promote node of the appropriate move to the tree root. */
176 if (!tree_promote_at(u
->t
, b
, m
->coord
)) {
177 /* The opponent move does not exist in the tree. Maybe the playout count of our
178 * previous move node is so small that it did not get expanded to yield the opponent
179 * moves, or more likely, the pruning process done at the end of our previous move
180 * removed the opponent node; indeed, since the expansion process in pruning is
181 * depth-first, and any children failing allocation will cause the parent not to be
182 * expanded, upon a temp-tree overflow we often have only a root node left. */
184 fprintf(stderr
, "Warning: Cannot promote move node!\n");
185 reset_state_keep_komi(u
);
189 /* If we are a slave in a distributed engine, start pondering once
190 * we know which move we actually played. See uct_genmove() about
191 * the check for pass. */
192 if (u
->pondering_opt
&& u
->slave
&& m
->color
== u
->my_color
&& !is_pass(m
->coord
))
193 uct_pondering_start(u
, b
, u
->t
, stone_other(m
->color
));
199 uct_undo(struct engine
*e
, struct board
*b
)
201 struct uct
*u
= e
->data
;
203 if (!u
->t
) return NULL
;
204 uct_pondering_stop(u
);
210 uct_result(struct engine
*e
, struct board
*b
)
212 struct uct
*u
= e
->data
;
213 static char reply
[1024];
217 enum stone color
= u
->t
->root_color
;
218 struct tree_node
*n
= u
->t
->root
;
219 snprintf(reply
, 1024, "%s %s %d %.2f %.1f",
220 stone2str(color
), coord2sstr(n
->coord
, b
),
221 n
->u
.playouts
, tree_node_get_value(u
->t
, -1, n
->u
.value
),
222 u
->t
->use_extra_komi
? u
->t
->extra_komi
: 0);
227 uct_chat(struct engine
*e
, struct board
*b
, char *cmd
)
229 struct uct
*u
= e
->data
;
230 static char reply
[1024];
232 cmd
+= strspn(cmd
, " \n\t");
233 if (!strncasecmp(cmd
, "winrate", 7)) {
235 return "no game context (yet?)";
236 enum stone color
= u
->t
->root_color
;
237 struct tree_node
*n
= u
->t
->root
;
238 snprintf(reply
, 1024, "In %d playouts at %d threads, %s %s can win with %.2f%% probability",
239 n
->u
.playouts
, u
->threads
, stone2str(color
), coord2sstr(n
->coord
, b
),
240 tree_node_get_value(u
->t
, -1, n
->u
.value
) * 100);
241 if (u
->t
->use_extra_komi
&& abs(u
->t
->extra_komi
) >= 0.5) {
242 sprintf(reply
+ strlen(reply
), ", while self-imposing extra komi %.1f",
252 uct_dead_group_list(struct engine
*e
, struct board
*b
, struct move_queue
*mq
)
254 struct uct
*u
= e
->data
;
256 /* This means the game is probably over, no use pondering on. */
257 uct_pondering_stop(u
);
259 if (u
->pass_all_alive
)
260 return; // no dead groups
262 bool mock_state
= false;
265 /* No state, but we cannot just back out - we might
266 * have passed earlier, only assuming some stones are
267 * dead, and then re-connected, only to lose counting
268 * when all stones are assumed alive. */
269 uct_prepare_move(u
, b
, S_BLACK
); assert(u
->t
);
272 /* Make sure the ownermap is well-seeded. */
273 while (u
->ownermap
.playouts
< GJ_MINGAMES
)
274 uct_playout(u
, b
, S_BLACK
, u
->t
);
275 /* Show the ownermap: */
277 board_print_custom(b
, stderr
, uct_printhook_ownermap
);
279 dead_group_list(u
, b
, mq
);
282 /* Clean up the mock state in case we will receive
283 * a genmove; we could get a non-alternating-move
284 * error from uct_prepare_move() in that case otherwise. */
290 playout_policy_done(struct playout_policy
*p
)
292 if (p
->done
) p
->done(p
);
293 if (p
->data
) free(p
->data
);
298 uct_done(struct engine
*e
)
300 /* This is called on engine reset, especially when clear_board
301 * is received and new game should begin. */
302 struct uct
*u
= e
->data
;
303 uct_pondering_stop(u
);
304 if (u
->t
) reset_state(u
);
305 free(u
->ownermap
.map
);
308 free(u
->random_policy
);
309 playout_policy_done(u
->playout
);
310 uct_prior_done(u
->prior
);
311 joseki_done(u
->jdict
);
312 pluginset_done(u
->plugins
);
317 /* Run time-limited MCTS search on foreground. */
319 uct_search(struct uct
*u
, struct board
*b
, struct time_info
*ti
, enum stone color
, struct tree
*t
)
321 struct uct_search_state s
;
322 uct_search_start(u
, b
, color
, t
, ti
, &s
);
323 if (UDEBUGL(2) && s
.base_playouts
> 0)
324 fprintf(stderr
, "<pre-simulated %d games>\n", s
.base_playouts
);
326 /* The search tree is ctx->t. This is currently == . It is important
327 * to reference ctx->t directly since the
328 * thread manager will swap the tree pointer asynchronously. */
330 /* Now, just periodically poll the search tree. */
331 /* Note that in case of TD_GAMES, threads will terminate independently
332 * of the uct_search_check_stop() signalization. */
334 time_sleep(TREE_BUSYWAIT_INTERVAL
);
335 /* TREE_BUSYWAIT_INTERVAL should never be less than desired time, or the
336 * time control is broken. But if it happens to be less, we still search
337 * at least 100ms otherwise the move is completely random. */
339 int i
= uct_search_games(&s
);
340 /* Print notifications etc. */
341 uct_search_progress(u
, b
, color
, t
, ti
, &s
, i
);
342 /* Check if we should stop the search. */
343 if (uct_search_check_stop(u
, b
, color
, t
, ti
, &s
, i
))
347 struct uct_thread_ctx
*ctx
= uct_search_stop();
348 if (UDEBUGL(2)) tree_dump(t
, u
->dumpthres
, u
->unlimited_tree_dump
);
350 fprintf(stderr
, "(avg score %f/%d value %f/%d)\n",
351 u
->dynkomi
->score
.value
, u
->dynkomi
->score
.playouts
,
352 u
->dynkomi
->value
.value
, u
->dynkomi
->value
.playouts
);
354 uct_progress_status(u
, t
, color
, ctx
->games
);
356 u
->played_own
+= ctx
->games
;
360 /* Start pondering background with @color to play. */
362 uct_pondering_start(struct uct
*u
, struct board
*b0
, struct tree
*t
, enum stone color
)
365 fprintf(stderr
, "Starting to ponder with color %s\n", stone2str(stone_other(color
)));
368 /* We need a local board copy to ponder upon. */
369 struct board
*b
= malloc2(sizeof(*b
)); board_copy(b
, b0
);
371 /* *b0 did not have the genmove'd move played yet. */
372 struct move m
= { t
->root
->coord
, t
->root_color
};
373 int res
= board_play(b
, &m
);
375 setup_dynkomi(u
, b
, stone_other(m
.color
));
377 /* Start MCTS manager thread "headless". */
378 static struct uct_search_state s
;
379 uct_search_start(u
, b
, color
, t
, NULL
, &s
);
382 /* uct_search_stop() frontend for the pondering (non-genmove) mode, and
383 * to stop the background search for a slave in the distributed engine. */
385 uct_pondering_stop(struct uct
*u
)
387 if (!thread_manager_running
)
390 /* Stop the thread manager. */
391 struct uct_thread_ctx
*ctx
= uct_search_stop();
393 if (u
->pondering
) fprintf(stderr
, "(pondering) ");
394 uct_progress_status(u
, ctx
->t
, ctx
->color
, ctx
->games
);
398 u
->pondering
= false;
404 uct_genmove_setup(struct uct
*u
, struct board
*b
, enum stone color
)
406 if (b
->superko_violation
) {
407 fprintf(stderr
, "!!! WARNING: SUPERKO VIOLATION OCCURED BEFORE THIS MOVE\n");
408 fprintf(stderr
, "Maybe you play with situational instead of positional superko?\n");
409 fprintf(stderr
, "I'm going to ignore the violation, but note that I may miss\n");
410 fprintf(stderr
, "some moves valid under this ruleset because of this.\n");
411 b
->superko_violation
= false;
414 uct_prepare_move(u
, b
, color
);
419 /* How to decide whether to use dynkomi in this game? Since we use
420 * pondering, it's not simple "who-to-play" matter. Decide based on
421 * the last genmove issued. */
422 u
->t
->use_extra_komi
= !!(u
->dynkomi_mask
& color
);
424 /* Moreover, we do not use extra komi at the game end - we are not
425 * to fool ourselves at this point. */
426 /* NOTE: But board_estimated_moves_left() is really too rough for this. On a 19x19 board,
427 * we would just stop using extra komi after move 210 plus the number of captured stones,
428 * leading to extremely conservative moves. */
429 if (board_estimated_moves_left(b
) <= MIN_MOVES_LEFT
)
430 u
->t
->use_extra_komi
= false;
432 setup_dynkomi(u
, b
, color
);
434 if (b
->rules
== RULES_JAPANESE
)
435 u
->territory_scoring
= true;
437 /* Make pessimistic assumption about komi for Japanese rules to
438 * avoid losing by 0.5 when winning by 0.5 with Chinese rules.
439 * The rules usually give the same winner if the integer part of komi
440 * is odd so we adjust the komi only if it is even (for a board of
441 * odd size). We are not trying to get an exact evaluation for rare
442 * cases of seki. For details see http://home.snafu.de/jasiek/parity.html */
443 if (u
->territory_scoring
&& (((int)floor(b
->komi
) + board_size(b
)) & 1)) {
444 b
->komi
+= (color
== S_BLACK
? 1.0 : -1.0);
446 fprintf(stderr
, "Setting komi to %.1f assuming Japanese rules\n",
452 uct_genmove(struct engine
*e
, struct board
*b
, struct time_info
*ti
, enum stone color
, bool pass_all_alive
)
454 double start_time
= time_now();
455 struct uct
*u
= e
->data
;
456 uct_pondering_stop(u
);
457 uct_genmove_setup(u
, b
, color
);
459 /* Start the Monte Carlo Tree Search! */
460 int base_playouts
= u
->t
->root
->u
.playouts
;
461 int played_games
= uct_search(u
, b
, ti
, color
, u
->t
);
464 struct tree_node
*best
;
465 best
= uct_search_result(u
, b
, color
, pass_all_alive
, played_games
, base_playouts
, &best_coord
);
468 double time
= time_now() - start_time
+ 0.000001; /* avoid divide by zero */
469 fprintf(stderr
, "genmove in %0.2fs (%d games/s, %d games/s/thread)\n",
470 time
, (int)(played_games
/time
), (int)(played_games
/time
/u
->threads
));
474 /* Pass or resign. Probably not a well-considered pass either. */
476 return coord_copy(best_coord
);
478 tree_promote_node(u
->t
, &best
);
480 /* After a pass, pondering is harmful for two reasons:
481 * (i) We might keep pondering even when the game is over.
482 * Of course this is the case for opponent resign as well.
483 * (ii) More importantly, the ownermap will get skewed since
484 * the UCT will start cutting off any playouts. */
485 if (u
->pondering_opt
&& !is_pass(best
->coord
)) {
486 uct_pondering_start(u
, b
, u
->t
, stone_other(color
));
488 return coord_copy(best_coord
);
493 uct_gentbook(struct engine
*e
, struct board
*b
, struct time_info
*ti
, enum stone color
)
495 struct uct
*u
= e
->data
;
496 if (!u
->t
) uct_prepare_move(u
, b
, color
);
499 if (ti
->dim
== TD_GAMES
) {
500 /* Don't count in games that already went into the tbook. */
501 ti
->len
.games
+= u
->t
->root
->u
.playouts
;
503 uct_search(u
, b
, ti
, color
, u
->t
);
505 assert(ti
->dim
== TD_GAMES
);
506 tree_save(u
->t
, b
, ti
->len
.games
/ 100);
512 uct_dumptbook(struct engine
*e
, struct board
*b
, enum stone color
)
514 struct uct
*u
= e
->data
;
515 struct tree
*t
= tree_init(b
, color
, u
->fast_alloc
? u
->max_tree_size
: 0,
516 u
->max_pruned_size
, u
->pruning_threshold
, u
->local_tree_aging
, 0);
518 tree_dump(t
, 0, true);
524 uct_evaluate(struct engine
*e
, struct board
*b
, struct time_info
*ti
, coord_t c
, enum stone color
)
526 struct uct
*u
= e
->data
;
530 struct move m
= { c
, color
};
531 int res
= board_play(&b2
, &m
);
534 color
= stone_other(color
);
536 if (u
->t
) reset_state(u
);
537 uct_prepare_move(u
, &b2
, color
);
541 uct_search(u
, &b2
, ti
, color
, u
->t
);
542 struct tree_node
*best
= u
->policy
->choose(u
->policy
, u
->t
->root
, &b2
, color
, resign
);
544 bestval
= NAN
; // the opponent has no reply!
546 bestval
= tree_node_get_value(u
->t
, 1, best
->u
.value
);
549 reset_state(u
); // clean our junk
551 return isnan(bestval
) ? NAN
: 1.0f
- bestval
;
556 uct_state_init(char *arg
, struct board
*b
)
558 struct uct
*u
= calloc2(1, sizeof(struct uct
));
560 u
->debug_level
= debug_level
;
561 u
->gamelen
= MC_GAMELEN
;
562 u
->resign_threshold
= 0.2;
563 u
->sure_win_threshold
= 0.85;
565 u
->significant_threshold
= 50;
568 u
->unlimited_tree_dump
= false;
569 u
->playout_amaf
= true;
570 u
->playout_amaf_nakade
= false;
571 u
->amaf_prior
= false;
572 u
->max_tree_size
= 1408ULL * 1048576;
573 u
->fast_alloc
= true;
574 u
->pruning_threshold
= 0;
577 u
->thread_model
= TM_TREEVL
;
580 u
->fuseki_end
= 20; // max time at 361*20% = 72 moves (our 36th move, still 99 to play)
581 u
->yose_start
= 40; // (100-40-25)*361/100/2 = 63 moves still to play by us then
582 u
->bestr_ratio
= 0.02;
583 // 2.5 is clearly too much, but seems to compensate well for overly stern time allocations.
584 // TODO: Further tuning and experiments with better time allocation schemes.
585 u
->best2_ratio
= 2.5;
586 u
->max_maintime_ratio
= 8.0;
588 u
->val_scale
= 0.04; u
->val_points
= 40;
589 u
->dynkomi_interval
= 1000;
590 u
->dynkomi_mask
= S_BLACK
| S_WHITE
;
593 u
->local_tree_aging
= 80;
594 u
->local_tree_allseq
= 1;
595 u
->local_tree_rootseqval
= 1;
596 u
->local_tree_depth_decay
= 1.5;
598 u
->stats_delay
= 0.01; // 10 ms
600 u
->plugins
= pluginset_init(b
);
602 u
->jdict
= joseki_load(b
->size
);
605 char *optspec
, *next
= arg
;
608 next
+= strcspn(next
, ",");
609 if (*next
) { *next
++ = 0; } else { *next
= 0; }
611 char *optname
= optspec
;
612 char *optval
= strchr(optspec
, '=');
613 if (optval
) *optval
++ = 0;
617 if (!strcasecmp(optname
, "debug")) {
619 u
->debug_level
= atoi(optval
);
622 } else if (!strcasecmp(optname
, "dumpthres") && optval
) {
623 /* When dumping the UCT tree on output, include
624 * nodes with at least this many playouts.
625 * (This value is re-scaled "intelligently"
626 * in case of very large trees.) */
627 u
->dumpthres
= atoi(optval
);
628 } else if (!strcasecmp(optname
, "unlimited_tree_dump")) {
629 /* If true, dumpthres is not increased even if the number of
630 * playouts is much larger than it. Good for debugging, but could
631 * lead to too much verbosity in actual games. */
632 u
->unlimited_tree_dump
= true;
633 } else if (!strcasecmp(optname
, "resign_threshold") && optval
) {
634 /* Resign when this ratio of games is lost
635 * after GJ_MINGAMES sample is taken. */
636 u
->resign_threshold
= atof(optval
);
637 } else if (!strcasecmp(optname
, "sure_win_threshold") && optval
) {
638 /* Stop reading when this ratio of games is won
639 * after PLAYOUT_EARLY_BREAK_MIN sample is
640 * taken. (Prevents stupid time losses,
641 * friendly to human opponents.) */
642 u
->sure_win_threshold
= atof(optval
);
643 } else if (!strcasecmp(optname
, "force_seed") && optval
) {
644 /* Set RNG seed at the tree setup. */
645 u
->force_seed
= atoi(optval
);
646 } else if (!strcasecmp(optname
, "no_tbook")) {
647 /* Disable UCT opening tbook. */
649 } else if (!strcasecmp(optname
, "pass_all_alive")) {
650 /* Whether to consider passing only after all
651 * dead groups were removed from the board;
652 * this is like all genmoves are in fact
653 * kgs-genmove_cleanup. */
654 u
->pass_all_alive
= !optval
|| atoi(optval
);
655 } else if (!strcasecmp(optname
, "territory_scoring")) {
656 /* Use territory scoring (default is area scoring).
657 * An explicit kgs-rules command overrides this. */
658 u
->territory_scoring
= !optval
|| atoi(optval
);
659 } else if (!strcasecmp(optname
, "banner") && optval
) {
660 /* Additional banner string. This must come as the
661 * last engine parameter. */
662 if (*next
) *--next
= ',';
663 u
->banner
= strdup(optval
);
665 } else if (!strcasecmp(optname
, "plugin") && optval
) {
666 /* Load an external plugin; filename goes before the colon,
667 * extra arguments after the colon. */
668 char *pluginarg
= strchr(optval
, ':');
671 plugin_load(u
->plugins
, optval
, pluginarg
);
673 /** UCT behavior and policies */
675 } else if ((!strcasecmp(optname
, "policy")
676 /* Node selection policy. ucb1amaf is the
677 * default policy implementing RAVE, while
678 * ucb1 is the simple exploration/exploitation
679 * policy. Policies can take further extra
681 || !strcasecmp(optname
, "random_policy")) && optval
) {
682 /* A policy to be used randomly with small
683 * chance instead of the default policy. */
684 char *policyarg
= strchr(optval
, ':');
685 struct uct_policy
**p
= !strcasecmp(optname
, "policy") ? &u
->policy
: &u
->random_policy
;
688 if (!strcasecmp(optval
, "ucb1")) {
689 *p
= policy_ucb1_init(u
, policyarg
);
690 } else if (!strcasecmp(optval
, "ucb1amaf")) {
691 *p
= policy_ucb1amaf_init(u
, policyarg
);
693 fprintf(stderr
, "UCT: Invalid tree policy %s\n", optval
);
696 } else if (!strcasecmp(optname
, "playout") && optval
) {
697 /* Random simulation (playout) policy.
698 * moggy is the default policy with large
699 * amount of domain-specific knowledge and
700 * heuristics. light is a simple uniformly
701 * random move selection policy. */
702 char *playoutarg
= strchr(optval
, ':');
705 if (!strcasecmp(optval
, "moggy")) {
706 u
->playout
= playout_moggy_init(playoutarg
, b
, u
->jdict
);
707 } else if (!strcasecmp(optval
, "light")) {
708 u
->playout
= playout_light_init(playoutarg
, b
);
710 fprintf(stderr
, "UCT: Invalid playout policy %s\n", optval
);
713 } else if (!strcasecmp(optname
, "prior") && optval
) {
714 /* Node priors policy. When expanding a node,
715 * it will seed node values heuristically
716 * (most importantly, based on playout policy
717 * opinion, but also with regard to other
718 * things). See uct/prior.c for details.
719 * Use prior=eqex=0 to disable priors. */
720 u
->prior
= uct_prior_init(optval
, b
);
721 } else if (!strcasecmp(optname
, "mercy") && optval
) {
722 /* Minimal difference of black/white captures
723 * to stop playout - "Mercy Rule". Speeds up
724 * hopeless playouts at the expense of some
726 u
->mercymin
= atoi(optval
);
727 } else if (!strcasecmp(optname
, "gamelen") && optval
) {
728 /* Maximum length of single simulation
730 u
->gamelen
= atoi(optval
);
731 } else if (!strcasecmp(optname
, "expand_p") && optval
) {
732 /* Expand UCT nodes after it has been
733 * visited this many times (NOTE: disabled for now). */
734 u
->expand_p
= atoi(optval
);
735 } else if (!strcasecmp(optname
, "random_policy_chance") && optval
) {
736 /* If specified (N), with probability 1/N, random_policy policy
737 * descend is used instead of main policy descend; useful
738 * if specified policy (e.g. UCB1AMAF) can make unduly biased
739 * choices sometimes, you can fall back to e.g.
740 * random_policy=UCB1. */
741 u
->random_policy_chance
= atoi(optval
);
743 /** General AMAF behavior */
744 /* (Only relevant if the policy supports AMAF.
745 * More variables can be tuned as policy
748 } else if (!strcasecmp(optname
, "playout_amaf")) {
749 /* Whether to include random playout moves in
750 * AMAF as well. (Otherwise, only tree moves
751 * are included in AMAF. Of course makes sense
752 * only in connection with an AMAF policy.) */
753 /* with-without: 55.5% (+-4.1) */
754 if (optval
&& *optval
== '0')
755 u
->playout_amaf
= false;
757 u
->playout_amaf
= true;
758 } else if (!strcasecmp(optname
, "playout_amaf_nakade")) {
759 /* Whether to include nakade moves from playouts
760 * in the AMAF statistics; this tends to nullify
761 * the playout_amaf effect by adding too much
763 if (optval
&& *optval
== '0')
764 u
->playout_amaf_nakade
= false;
766 u
->playout_amaf_nakade
= true;
767 } else if (!strcasecmp(optname
, "playout_amaf_cutoff") && optval
) {
768 /* Keep only first N% of playout stage AMAF
770 u
->playout_amaf_cutoff
= atoi(optval
);
771 } else if (!strcasecmp(optname
, "amaf_prior") && optval
) {
772 /* In node policy, consider prior values
773 * part of the real result term or part
774 * of the AMAF term? */
775 u
->amaf_prior
= atoi(optval
);
777 /** Performance and memory management */
779 } else if (!strcasecmp(optname
, "threads") && optval
) {
780 /* By default, Pachi will run with only single
781 * tree search thread! */
782 u
->threads
= atoi(optval
);
783 } else if (!strcasecmp(optname
, "thread_model") && optval
) {
784 if (!strcasecmp(optval
, "tree")) {
785 /* Tree parallelization - all threads
786 * grind on the same tree. */
787 u
->thread_model
= TM_TREE
;
789 } else if (!strcasecmp(optval
, "treevl")) {
790 /* Tree parallelization, but also
791 * with virtual losses - this discou-
792 * rages most threads choosing the
793 * same tree branches to read. */
794 u
->thread_model
= TM_TREEVL
;
796 fprintf(stderr
, "UCT: Invalid thread model %s\n", optval
);
799 } else if (!strcasecmp(optname
, "virtual_loss")) {
800 /* Number of virtual losses added before evaluating a node. */
801 u
->virtual_loss
= !optval
|| atoi(optval
);
802 } else if (!strcasecmp(optname
, "pondering")) {
803 /* Keep searching even during opponent's turn. */
804 u
->pondering_opt
= !optval
|| atoi(optval
);
805 } else if (!strcasecmp(optname
, "max_tree_size") && optval
) {
806 /* Maximum amount of memory [MiB] consumed by the move tree.
807 * For fast_alloc it includes the temp tree used for pruning.
808 * Default is 3072 (3 GiB). */
809 u
->max_tree_size
= atol(optval
) * 1048576;
810 } else if (!strcasecmp(optname
, "fast_alloc")) {
811 u
->fast_alloc
= !optval
|| atoi(optval
);
812 } else if (!strcasecmp(optname
, "pruning_threshold") && optval
) {
813 /* Force pruning at beginning of a move if the tree consumes
814 * more than this [MiB]. Default is 10% of max_tree_size.
815 * Increase to reduce pruning time overhead if memory is plentiful.
816 * This option is meaningful only for fast_alloc. */
817 u
->pruning_threshold
= atol(optval
) * 1048576;
821 } else if (!strcasecmp(optname
, "best2_ratio") && optval
) {
822 /* If set, prolong simulating while
823 * first_best/second_best playouts ratio
824 * is less than best2_ratio. */
825 u
->best2_ratio
= atof(optval
);
826 } else if (!strcasecmp(optname
, "bestr_ratio") && optval
) {
827 /* If set, prolong simulating while
828 * best,best_best_child values delta
829 * is more than bestr_ratio. */
830 u
->bestr_ratio
= atof(optval
);
831 } else if (!strcasecmp(optname
, "max_maintime_ratio") && optval
) {
832 /* If set and while not in byoyomi, prolong simulating no more than
833 * max_maintime_ratio times the normal desired thinking time. */
834 u
->max_maintime_ratio
= atof(optval
);
835 } else if (!strcasecmp(optname
, "fuseki_end") && optval
) {
836 /* At the very beginning it's not worth thinking
837 * too long because the playout evaluations are
838 * very noisy. So gradually increase the thinking
839 * time up to maximum when fuseki_end percent
840 * of the board has been played.
841 * This only applies if we are not in byoyomi. */
842 u
->fuseki_end
= atoi(optval
);
843 } else if (!strcasecmp(optname
, "yose_start") && optval
) {
844 /* When yose_start percent of the board has been
845 * played, or if we are in byoyomi, stop spending
846 * more time and spread the remaining time
848 * Between fuseki_end and yose_start, we spend
849 * a constant proportion of the remaining time
850 * on each move. (yose_start should actually
851 * be much earlier than when real yose start,
852 * but "yose" is a good short name to convey
854 u
->yose_start
= atoi(optval
);
858 } else if (!strcasecmp(optname
, "dynkomi") && optval
) {
859 /* Dynamic komi approach; there are multiple
860 * ways to adjust komi dynamically throughout
861 * play. We currently support two: */
862 char *dynkomiarg
= strchr(optval
, ':');
865 if (!strcasecmp(optval
, "none")) {
866 u
->dynkomi
= uct_dynkomi_init_none(u
, dynkomiarg
, b
);
867 } else if (!strcasecmp(optval
, "linear")) {
868 /* You should set dynkomi_mask=1
869 * since this doesn't work well
870 * for white handicaps! */
871 u
->dynkomi
= uct_dynkomi_init_linear(u
, dynkomiarg
, b
);
872 } else if (!strcasecmp(optval
, "adaptive")) {
873 /* There are many more knobs to
874 * crank - see uct/dynkomi.c. */
875 u
->dynkomi
= uct_dynkomi_init_adaptive(u
, dynkomiarg
, b
);
877 fprintf(stderr
, "UCT: Invalid dynkomi mode %s\n", optval
);
880 } else if (!strcasecmp(optname
, "dynkomi_mask") && optval
) {
881 /* Bitmask of colors the player must be
882 * for dynkomi be applied; you may want
883 * to use dynkomi_mask=3 to allow dynkomi
884 * even in games where Pachi is white. */
885 u
->dynkomi_mask
= atoi(optval
);
886 } else if (!strcasecmp(optname
, "dynkomi_interval") && optval
) {
887 /* If non-zero, re-adjust dynamic komi
888 * throughout a single genmove reading,
889 * roughly every N simulations. */
890 /* XXX: Does not work with tree
891 * parallelization. */
892 u
->dynkomi_interval
= atoi(optval
);
894 /** Node value result scaling */
896 } else if (!strcasecmp(optname
, "val_scale") && optval
) {
897 /* How much of the game result value should be
898 * influenced by win size. Zero means it isn't. */
899 u
->val_scale
= atof(optval
);
900 } else if (!strcasecmp(optname
, "val_points") && optval
) {
901 /* Maximum size of win to be scaled into game
902 * result value. Zero means boardsize^2. */
903 u
->val_points
= atoi(optval
) * 2; // result values are doubled
904 } else if (!strcasecmp(optname
, "val_extra")) {
905 /* If false, the score coefficient will be simply
906 * added to the value, instead of scaling the result
907 * coefficient because of it. */
908 u
->val_extra
= !optval
|| atoi(optval
);
911 /* (Purely experimental. Does not work - yet!) */
913 } else if (!strcasecmp(optname
, "local_tree") && optval
) {
914 /* Whether to bias exploration by local tree values
915 * (must be supported by the used policy).
917 * 1: Do, value = result.
918 * Try to temper the result:
919 * 2: Do, value = 0.5+(result-expected)/2.
920 * 3: Do, value = 0.5+bzz((result-expected)^2).
921 * 4: Do, value = 0.5+sqrt(result-expected)/2. */
922 u
->local_tree
= atoi(optval
);
923 } else if (!strcasecmp(optname
, "tenuki_d") && optval
) {
924 /* Tenuki distance at which to break the local tree. */
925 u
->tenuki_d
= atoi(optval
);
926 if (u
->tenuki_d
> TREE_NODE_D_MAX
+ 1) {
927 fprintf(stderr
, "uct: tenuki_d must not be larger than TREE_NODE_D_MAX+1 %d\n", TREE_NODE_D_MAX
+ 1);
930 } else if (!strcasecmp(optname
, "local_tree_aging") && optval
) {
931 /* How much to reduce local tree values between moves. */
932 u
->local_tree_aging
= atof(optval
);
933 } else if (!strcasecmp(optname
, "local_tree_depth_decay") && optval
) {
934 /* With value x>0, during the descent the node
935 * contributes 1/x^depth playouts in
936 * the local tree. I.e., with x>1, nodes more
937 * distant from local situation contribute more
938 * than nodes near the root. */
939 u
->local_tree_depth_decay
= atof(optval
);
940 } else if (!strcasecmp(optname
, "local_tree_allseq")) {
941 /* If disabled, only complete sequences are stored
942 * in the local tree. If this is on, also
943 * subsequences starting at each move are stored. */
944 u
->local_tree_allseq
= !optval
|| atoi(optval
);
945 } else if (!strcasecmp(optname
, "local_tree_rootseqval")) {
946 /* If disabled, expected node value is computed by
947 * summing up values through the whole descent.
948 * If enabled, expected node value for
949 * each sequence is the value at the root of the
951 u
->local_tree_rootseqval
= !optval
|| atoi(optval
);
953 /** Other heuristics */
954 } else if (!strcasecmp(optname
, "significant_threshold") && optval
) {
955 /* Some heuristics (XXX: none in mainline) rely
956 * on the knowledge of the last "significant"
957 * node in the descent. Such a node is
958 * considered reasonably trustworthy to carry
959 * some meaningful information in the values
960 * of the node and its children. */
961 u
->significant_threshold
= atoi(optval
);
963 /** Distributed engine slaves setup */
965 } else if (!strcasecmp(optname
, "slave")) {
966 /* Act as slave for the distributed engine. */
967 u
->slave
= !optval
|| atoi(optval
);
968 } else if (!strcasecmp(optname
, "shared_nodes") && optval
) {
969 /* Share at most shared_nodes between master and slave at each genmoves.
970 * Must use the same value in master and slaves. */
971 u
->shared_nodes
= atoi(optval
);
972 } else if (!strcasecmp(optname
, "shared_levels") && optval
) {
973 /* Share only nodes of level <= shared_levels. */
974 u
->shared_levels
= atoi(optval
);
975 } else if (!strcasecmp(optname
, "stats_hbits") && optval
) {
976 /* Set hash table size to 2^stats_hbits for the shared stats. */
977 u
->stats_hbits
= atoi(optval
);
978 } else if (!strcasecmp(optname
, "stats_delay") && optval
) {
979 /* How long to wait in slave for initial stats to build up before
980 * replying to the genmoves command (in ms) */
981 u
->stats_delay
= 0.001 * atof(optval
);
984 fprintf(stderr
, "uct: Invalid engine argument %s or missing value\n", optname
);
991 u
->policy
= policy_ucb1amaf_init(u
, NULL
);
993 if (!!u
->random_policy_chance
^ !!u
->random_policy
) {
994 fprintf(stderr
, "uct: Only one of random_policy and random_policy_chance is set\n");
998 if (!u
->local_tree
) {
999 /* No ltree aging. */
1000 u
->local_tree_aging
= 1.0f
;
1003 if (u
->fast_alloc
) {
1004 if (u
->pruning_threshold
< u
->max_tree_size
/ 10)
1005 u
->pruning_threshold
= u
->max_tree_size
/ 10;
1006 if (u
->pruning_threshold
> u
->max_tree_size
/ 2)
1007 u
->pruning_threshold
= u
->max_tree_size
/ 2;
1009 /* Limit pruning temp space to 20% of memory. Beyond this we discard
1010 * the nodes and recompute them at the next move if necessary. */
1011 u
->max_pruned_size
= u
->max_tree_size
/ 5;
1012 u
->max_tree_size
-= u
->max_pruned_size
;
1014 /* Reserve 5% memory in case the background free() are slower
1015 * than the concurrent allocations. */
1016 u
->max_tree_size
-= u
->max_tree_size
/ 20;
1020 u
->prior
= uct_prior_init(NULL
, b
);
1023 u
->playout
= playout_moggy_init(NULL
, b
, u
->jdict
);
1024 if (!u
->playout
->debug_level
)
1025 u
->playout
->debug_level
= u
->debug_level
;
1027 u
->ownermap
.map
= malloc2(board_size2(b
) * sizeof(u
->ownermap
.map
[0]));
1030 if (!u
->stats_hbits
) u
->stats_hbits
= DEFAULT_STATS_HBITS
;
1031 if (!u
->shared_nodes
) u
->shared_nodes
= DEFAULT_SHARED_NODES
;
1032 assert(u
->shared_levels
* board_bits2(b
) <= 8 * (int)sizeof(path_t
));
1036 u
->dynkomi
= uct_dynkomi_init_adaptive(u
, NULL
, b
);
1038 /* Some things remain uninitialized for now - the opening tbook
1039 * is not loaded and the tree not set up. */
1040 /* This will be initialized in setup_state() at the first move
1041 * received/requested. This is because right now we are not aware
1042 * about any komi or handicap setup and such. */
1048 engine_uct_init(char *arg
, struct board
*b
)
1050 struct uct
*u
= uct_state_init(arg
, b
);
1051 struct engine
*e
= calloc2(1, sizeof(struct engine
));
1052 e
->name
= "UCT Engine";
1053 e
->printhook
= uct_printhook_ownermap
;
1054 e
->notify_play
= uct_notify_play
;
1057 e
->result
= uct_result
;
1058 e
->genmove
= uct_genmove
;
1059 e
->genmoves
= uct_genmoves
;
1060 e
->dead_group_list
= uct_dead_group_list
;
1064 e
->notify
= uct_notify
;
1066 const char banner
[] = "I'm playing UCT. When I'm losing, I will resign, "
1067 "if I think I win, I play until you pass. "
1068 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
1069 if (!u
->banner
) u
->banner
= "";
1070 e
->comment
= malloc2(sizeof(banner
) + strlen(u
->banner
) + 1);
1071 sprintf(e
->comment
, "%s %s", banner
, u
->banner
);