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
);
45 fast_srandom(u
->force_seed
);
47 fprintf(stderr
, "Fresh board with random seed %lu\n", fast_getseed());
48 //board_print(b, stderr);
49 if (!u
->no_tbook
&& b
->moves
== 0) {
50 assert(color
== S_BLACK
);
56 reset_state(struct uct
*u
)
59 tree_done(u
->t
); u
->t
= NULL
;
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
);
67 else if (!u
->t
->use_extra_komi
)
72 uct_prepare_move(struct uct
*u
, struct board
*b
, enum stone color
)
75 /* Verify that we have sane state. */
77 assert(u
->t
&& b
->moves
);
78 if (color
!= stone_other(u
->t
->root_color
)) {
79 fprintf(stderr
, "Fatal: Non-alternating play detected %d %d\n",
80 color
, u
->t
->root_color
);
83 uct_htable_reset(u
->t
);
86 /* We need fresh state. */
88 setup_state(u
, b
, color
);
91 u
->ownermap
.playouts
= 0;
92 memset(u
->ownermap
.map
, 0, board_size2(b
) * sizeof(u
->ownermap
.map
[0]));
93 u
->played_own
= u
->played_all
= 0;
97 dead_group_list(struct uct
*u
, struct board
*b
, struct move_queue
*mq
)
99 struct group_judgement gj
;
101 gj
.gs
= alloca(board_size2(b
) * sizeof(gj
.gs
[0]));
102 board_ownermap_judge_group(b
, &u
->ownermap
, &gj
);
103 groups_of_status(b
, &gj
, GS_DEAD
, mq
);
107 uct_pass_is_safe(struct uct
*u
, struct board
*b
, enum stone color
, bool pass_all_alive
)
109 if (u
->ownermap
.playouts
< GJ_MINGAMES
)
112 struct move_queue mq
= { .moves
= 0 };
113 dead_group_list(u
, b
, &mq
);
114 if (pass_all_alive
&& mq
.moves
> 0)
115 return false; // We need to remove some dead groups first.
116 return pass_is_safe(b
, color
, &mq
);
120 uct_printhook_ownermap(struct board
*board
, coord_t c
, char *s
, char *end
)
122 struct uct
*u
= board
->es
;
127 const char chr
[] = ":XO,"; // dame, black, white, unclear
128 const char chm
[] = ":xo,";
129 char ch
= chr
[board_ownermap_judge_point(&u
->ownermap
, c
, GJ_THRES
)];
130 if (ch
== ',') { // less precise estimate then?
131 ch
= chm
[board_ownermap_judge_point(&u
->ownermap
, c
, 0.67)];
133 s
+= snprintf(s
, end
- s
, "%c ", ch
);
138 uct_notify_play(struct engine
*e
, struct board
*b
, struct move
*m
)
140 struct uct
*u
= e
->data
;
142 /* No state, create one - this is probably game beginning
143 * and we need to load the opening tbook right now. */
144 uct_prepare_move(u
, b
, m
->color
);
148 /* Stop pondering, required by tree_promote_at() */
149 uct_pondering_stop(u
);
150 if (UDEBUGL(2) && u
->slave
)
151 tree_dump(u
->t
, u
->dumpthres
);
153 if (is_resign(m
->coord
)) {
159 /* Promote node of the appropriate move to the tree root. */
161 if (!tree_promote_at(u
->t
, b
, m
->coord
)) {
163 fprintf(stderr
, "Warning: Cannot promote move node! Several play commands in row?\n");
168 /* If we are a slave in a distributed engine, start pondering once
169 * we know which move we actually played. See uct_genmove() about
170 * the check for pass. */
171 if (u
->pondering_opt
&& u
->slave
&& m
->color
== u
->my_color
&& !is_pass(m
->coord
))
172 uct_pondering_start(u
, b
, u
->t
, stone_other(m
->color
));
178 uct_undo(struct engine
*e
, struct board
*b
)
180 struct uct
*u
= e
->data
;
182 if (!u
->t
) return NULL
;
183 uct_pondering_stop(u
);
189 uct_result(struct engine
*e
, struct board
*b
)
191 struct uct
*u
= e
->data
;
192 static char reply
[1024];
196 enum stone color
= u
->t
->root_color
;
197 struct tree_node
*n
= u
->t
->root
;
198 snprintf(reply
, 1024, "%s %s %d %.2f %.1f",
199 stone2str(color
), coord2sstr(n
->coord
, b
),
200 n
->u
.playouts
, tree_node_get_value(u
->t
, -1, n
->u
.value
),
201 u
->t
->use_extra_komi
? u
->t
->extra_komi
: 0);
206 uct_chat(struct engine
*e
, struct board
*b
, char *cmd
)
208 struct uct
*u
= e
->data
;
209 static char reply
[1024];
211 cmd
+= strspn(cmd
, " \n\t");
212 if (!strncasecmp(cmd
, "winrate", 7)) {
214 return "no game context (yet?)";
215 enum stone color
= u
->t
->root_color
;
216 struct tree_node
*n
= u
->t
->root
;
217 snprintf(reply
, 1024, "In %d playouts at %d threads, %s %s can win with %.2f%% probability",
218 n
->u
.playouts
, u
->threads
, stone2str(color
), coord2sstr(n
->coord
, b
),
219 tree_node_get_value(u
->t
, -1, n
->u
.value
) * 100);
220 if (u
->t
->use_extra_komi
&& abs(u
->t
->extra_komi
) >= 0.5) {
221 sprintf(reply
+ strlen(reply
), ", while self-imposing extra komi %.1f",
231 uct_dead_group_list(struct engine
*e
, struct board
*b
, struct move_queue
*mq
)
233 struct uct
*u
= e
->data
;
235 /* This means the game is probably over, no use pondering on. */
236 uct_pondering_stop(u
);
238 if (u
->pass_all_alive
)
239 return; // no dead groups
241 bool mock_state
= false;
244 /* No state, but we cannot just back out - we might
245 * have passed earlier, only assuming some stones are
246 * dead, and then re-connected, only to lose counting
247 * when all stones are assumed alive. */
248 uct_prepare_move(u
, b
, S_BLACK
); assert(u
->t
);
251 /* Make sure the ownermap is well-seeded. */
252 while (u
->ownermap
.playouts
< GJ_MINGAMES
)
253 uct_playout(u
, b
, S_BLACK
, u
->t
);
254 /* Show the ownermap: */
256 board_print_custom(b
, stderr
, uct_printhook_ownermap
);
258 dead_group_list(u
, b
, mq
);
261 /* Clean up the mock state in case we will receive
262 * a genmove; we could get a non-alternating-move
263 * error from uct_prepare_move() in that case otherwise. */
269 playout_policy_done(struct playout_policy
*p
)
271 if (p
->done
) p
->done(p
);
272 if (p
->data
) free(p
->data
);
277 uct_done(struct engine
*e
)
279 /* This is called on engine reset, especially when clear_board
280 * is received and new game should begin. */
281 struct uct
*u
= e
->data
;
282 uct_pondering_stop(u
);
283 if (u
->t
) reset_state(u
);
284 free(u
->ownermap
.map
);
287 free(u
->random_policy
);
288 playout_policy_done(u
->playout
);
289 uct_prior_done(u
->prior
);
290 joseki_done(u
->jdict
);
291 pluginset_done(u
->plugins
);
296 /* Run time-limited MCTS search on foreground. */
298 uct_search(struct uct
*u
, struct board
*b
, struct time_info
*ti
, enum stone color
, struct tree
*t
)
300 struct uct_search_state s
;
301 uct_search_start(u
, b
, color
, t
, ti
, &s
);
302 if (UDEBUGL(2) && s
.base_playouts
> 0)
303 fprintf(stderr
, "<pre-simulated %d games>\n", s
.base_playouts
);
305 /* The search tree is ctx->t. This is currently == . It is important
306 * to reference ctx->t directly since the
307 * thread manager will swap the tree pointer asynchronously. */
309 /* Now, just periodically poll the search tree. */
310 /* Note that in case of TD_GAMES, threads will terminate independently
311 * of the uct_search_check_stop() signalization. */
313 time_sleep(TREE_BUSYWAIT_INTERVAL
);
314 /* TREE_BUSYWAIT_INTERVAL should never be less than desired time, or the
315 * time control is broken. But if it happens to be less, we still search
316 * at least 100ms otherwise the move is completely random. */
318 int i
= uct_search_games(&s
);
319 /* Print notifications etc. */
320 uct_search_progress(u
, b
, color
, t
, ti
, &s
, i
);
321 /* Check if we should stop the search. */
322 if (uct_search_check_stop(u
, b
, color
, t
, ti
, &s
, i
))
326 struct uct_thread_ctx
*ctx
= uct_search_stop();
327 if (UDEBUGL(2)) tree_dump(t
, u
->dumpthres
);
329 fprintf(stderr
, "(avg score %f/%d value %f/%d)\n",
330 u
->dynkomi
->score
.value
, u
->dynkomi
->score
.playouts
,
331 u
->dynkomi
->value
.value
, u
->dynkomi
->value
.playouts
);
332 uct_progress_status(u
, t
, color
, ctx
->games
, true);
334 u
->played_own
+= ctx
->games
;
338 /* Start pondering background with @color to play. */
340 uct_pondering_start(struct uct
*u
, struct board
*b0
, struct tree
*t
, enum stone color
)
343 fprintf(stderr
, "Starting to ponder with color %s\n", stone2str(stone_other(color
)));
346 /* We need a local board copy to ponder upon. */
347 struct board
*b
= malloc2(sizeof(*b
)); board_copy(b
, b0
);
349 /* *b0 did not have the genmove'd move played yet. */
350 struct move m
= { t
->root
->coord
, t
->root_color
};
351 int res
= board_play(b
, &m
);
353 setup_dynkomi(u
, b
, stone_other(m
.color
));
355 /* Start MCTS manager thread "headless". */
356 static struct uct_search_state s
;
357 uct_search_start(u
, b
, color
, t
, NULL
, &s
);
360 /* uct_search_stop() frontend for the pondering (non-genmove) mode, and
361 * to stop the background search for a slave in the distributed engine. */
363 uct_pondering_stop(struct uct
*u
)
365 if (!thread_manager_running
)
368 /* Stop the thread manager. */
369 struct uct_thread_ctx
*ctx
= uct_search_stop();
371 if (u
->pondering
) fprintf(stderr
, "(pondering) ");
372 uct_progress_status(u
, ctx
->t
, ctx
->color
, ctx
->games
, true);
376 u
->pondering
= false;
382 uct_genmove_setup(struct uct
*u
, struct board
*b
, enum stone color
)
384 if (b
->superko_violation
) {
385 fprintf(stderr
, "!!! WARNING: SUPERKO VIOLATION OCCURED BEFORE THIS MOVE\n");
386 fprintf(stderr
, "Maybe you play with situational instead of positional superko?\n");
387 fprintf(stderr
, "I'm going to ignore the violation, but note that I may miss\n");
388 fprintf(stderr
, "some moves valid under this ruleset because of this.\n");
389 b
->superko_violation
= false;
392 uct_prepare_move(u
, b
, color
);
397 /* How to decide whether to use dynkomi in this game? Since we use
398 * pondering, it's not simple "who-to-play" matter. Decide based on
399 * the last genmove issued. */
400 u
->t
->use_extra_komi
= !!(u
->dynkomi_mask
& color
);
401 /* Moreover, we do not use extra komi at the game end - we are not
402 * to fool ourselves at this point. */
403 if (board_estimated_moves_left(b
) <= MIN_MOVES_LEFT
)
404 u
->t
->use_extra_komi
= false;
405 setup_dynkomi(u
, b
, color
);
407 if (b
->rules
== RULES_JAPANESE
)
408 u
->territory_scoring
= true;
410 /* Make pessimistic assumption about komi for Japanese rules to
411 * avoid losing by 0.5 when winning by 0.5 with Chinese rules.
412 * The rules usually give the same winner if the integer part of komi
413 * is odd so we adjust the komi only if it is even (for a board of
414 * odd size). We are not trying to get an exact evaluation for rare
415 * cases of seki. For details see http://home.snafu.de/jasiek/parity.html */
416 if (u
->territory_scoring
&& (((int)floor(b
->komi
) + board_size(b
)) & 1)) {
417 b
->komi
+= (color
== S_BLACK
? 1.0 : -1.0);
419 fprintf(stderr
, "Setting komi to %.1f assuming Japanese rules\n",
425 uct_genmove(struct engine
*e
, struct board
*b
, struct time_info
*ti
, enum stone color
, bool pass_all_alive
)
427 double start_time
= time_now();
428 struct uct
*u
= e
->data
;
429 uct_pondering_stop(u
);
430 uct_genmove_setup(u
, b
, color
);
432 /* Start the Monte Carlo Tree Search! */
433 int base_playouts
= u
->t
->root
->u
.playouts
;
434 int played_games
= uct_search(u
, b
, ti
, color
, u
->t
);
437 struct tree_node
*best
;
438 best
= uct_search_result(u
, b
, color
, pass_all_alive
, played_games
, base_playouts
, &best_coord
);
441 double time
= time_now() - start_time
+ 0.000001; /* avoid divide by zero */
442 fprintf(stderr
, "genmove in %0.2fs (%d games/s, %d games/s/thread)\n",
443 time
, (int)(played_games
/time
), (int)(played_games
/time
/u
->threads
));
447 /* Pass or resign. */
449 return coord_copy(best_coord
);
451 tree_promote_node(u
->t
, &best
);
453 /* After a pass, pondering is harmful for two reasons:
454 * (i) We might keep pondering even when the game is over.
455 * Of course this is the case for opponent resign as well.
456 * (ii) More importantly, the ownermap will get skewed since
457 * the UCT will start cutting off any playouts. */
458 if (u
->pondering_opt
&& !is_pass(best
->coord
)) {
459 uct_pondering_start(u
, b
, u
->t
, stone_other(color
));
461 return coord_copy(best_coord
);
466 uct_gentbook(struct engine
*e
, struct board
*b
, struct time_info
*ti
, enum stone color
)
468 struct uct
*u
= e
->data
;
469 if (!u
->t
) uct_prepare_move(u
, b
, color
);
472 if (ti
->dim
== TD_GAMES
) {
473 /* Don't count in games that already went into the tbook. */
474 ti
->len
.games
+= u
->t
->root
->u
.playouts
;
476 uct_search(u
, b
, ti
, color
, u
->t
);
478 assert(ti
->dim
== TD_GAMES
);
479 tree_save(u
->t
, b
, ti
->len
.games
/ 100);
485 uct_dumptbook(struct engine
*e
, struct board
*b
, enum stone color
)
487 struct uct
*u
= e
->data
;
488 struct tree
*t
= tree_init(b
, color
, u
->fast_alloc
? u
->max_tree_size
: 0,
489 u
->max_pruned_size
, u
->pruning_threshold
, u
->local_tree_aging
, 0);
497 uct_evaluate(struct engine
*e
, struct board
*b
, struct time_info
*ti
, coord_t c
, enum stone color
)
499 struct uct
*u
= e
->data
;
503 struct move m
= { c
, color
};
504 int res
= board_play(&b2
, &m
);
507 color
= stone_other(color
);
509 if (u
->t
) reset_state(u
);
510 uct_prepare_move(u
, &b2
, color
);
514 uct_search(u
, &b2
, ti
, color
, u
->t
);
515 struct tree_node
*best
= u
->policy
->choose(u
->policy
, u
->t
->root
, &b2
, color
, resign
);
517 bestval
= NAN
; // the opponent has no reply!
519 bestval
= tree_node_get_value(u
->t
, 1, best
->u
.value
);
522 reset_state(u
); // clean our junk
524 return isnan(bestval
) ? NAN
: 1.0f
- bestval
;
529 uct_state_init(char *arg
, struct board
*b
)
531 struct uct
*u
= calloc2(1, sizeof(struct uct
));
533 u
->debug_level
= debug_level
;
534 u
->gamelen
= MC_GAMELEN
;
535 u
->resign_threshold
= 0.2;
536 u
->sure_win_threshold
= 0.85;
538 u
->significant_threshold
= 50;
541 u
->playout_amaf
= true;
542 u
->playout_amaf_nakade
= false;
543 u
->amaf_prior
= false;
544 u
->max_tree_size
= 1408ULL * 1048576;
545 u
->fast_alloc
= true;
546 u
->pruning_threshold
= 0;
549 u
->thread_model
= TM_TREEVL
;
552 u
->fuseki_end
= 20; // max time at 361*20% = 72 moves (our 36th move, still 99 to play)
553 u
->yose_start
= 40; // (100-40-25)*361/100/2 = 63 moves still to play by us then
554 u
->bestr_ratio
= 0.02;
555 // 2.5 is clearly too much, but seems to compensate well for overly stern time allocations.
556 // TODO: Further tuning and experiments with better time allocation schemes.
557 u
->best2_ratio
= 2.5;
558 u
->max_maintime_ratio
= 8.0;
560 u
->val_scale
= 0.04; u
->val_points
= 40;
561 u
->dynkomi_interval
= 1000;
562 u
->dynkomi_mask
= S_BLACK
| S_WHITE
;
565 u
->local_tree_aging
= 80;
566 u
->local_tree_allseq
= 1;
567 u
->local_tree_rootseqval
= 1;
568 u
->local_tree_depth_decay
= 1.5;
570 u
->plugins
= pluginset_init(b
);
572 u
->jdict
= joseki_load(b
->size
);
575 char *optspec
, *next
= arg
;
578 next
+= strcspn(next
, ",");
579 if (*next
) { *next
++ = 0; } else { *next
= 0; }
581 char *optname
= optspec
;
582 char *optval
= strchr(optspec
, '=');
583 if (optval
) *optval
++ = 0;
587 if (!strcasecmp(optname
, "debug")) {
589 u
->debug_level
= atoi(optval
);
592 } else if (!strcasecmp(optname
, "reporting") && optval
) {
593 /* The format of output for detailed progress
594 * information (such as current best move and
595 * its value, etc.). */
596 if (!strcasecmp(optval
, "text")) {
597 /* Plaintext traditional output. */
598 u
->reporting
= UR_TEXT
;
599 } else if (!strcasecmp(optval
, "json")) {
600 /* JSON output. Implies debug=0. */
601 u
->reporting
= UR_JSON
;
604 fprintf(stderr
, "UCT: Invalid reporting format %s\n", optval
);
607 } else if (!strcasecmp(optname
, "dumpthres") && optval
) {
608 /* When dumping the UCT tree on output, include
609 * nodes with at least this many playouts.
610 * (This value is re-scaled "intelligently"
611 * in case of very large trees.) */
612 u
->dumpthres
= atoi(optval
);
613 } else if (!strcasecmp(optname
, "resign_threshold") && optval
) {
614 /* Resign when this ratio of games is lost
615 * after GJ_MINGAMES sample is taken. */
616 u
->resign_threshold
= atof(optval
);
617 } else if (!strcasecmp(optname
, "sure_win_threshold") && optval
) {
618 /* Stop reading when this ratio of games is won
619 * after PLAYOUT_EARLY_BREAK_MIN sample is
620 * taken. (Prevents stupid time losses,
621 * friendly to human opponents.) */
622 u
->sure_win_threshold
= atof(optval
);
623 } else if (!strcasecmp(optname
, "force_seed") && optval
) {
624 /* Set RNG seed at the tree setup. */
625 u
->force_seed
= atoi(optval
);
626 } else if (!strcasecmp(optname
, "no_tbook")) {
627 /* Disable UCT opening tbook. */
629 } else if (!strcasecmp(optname
, "pass_all_alive")) {
630 /* Whether to consider passing only after all
631 * dead groups were removed from the board;
632 * this is like all genmoves are in fact
633 * kgs-genmove_cleanup. */
634 u
->pass_all_alive
= !optval
|| atoi(optval
);
635 } else if (!strcasecmp(optname
, "territory_scoring")) {
636 /* Use territory scoring (default is area scoring).
637 * An explicit kgs-rules command overrides this. */
638 u
->territory_scoring
= !optval
|| atoi(optval
);
639 } else if (!strcasecmp(optname
, "banner") && optval
) {
640 /* Additional banner string. This must come as the
641 * last engine parameter. */
642 if (*next
) *--next
= ',';
643 u
->banner
= strdup(optval
);
645 } else if (!strcasecmp(optname
, "plugin") && optval
) {
646 /* Load an external plugin; filename goes before the colon,
647 * extra arguments after the colon. */
648 char *pluginarg
= strchr(optval
, ':');
651 plugin_load(u
->plugins
, optval
, pluginarg
);
653 /** UCT behavior and policies */
655 } else if ((!strcasecmp(optname
, "policy")
656 /* Node selection policy. ucb1amaf is the
657 * default policy implementing RAVE, while
658 * ucb1 is the simple exploration/exploitation
659 * policy. Policies can take further extra
661 || !strcasecmp(optname
, "random_policy")) && optval
) {
662 /* A policy to be used randomly with small
663 * chance instead of the default policy. */
664 char *policyarg
= strchr(optval
, ':');
665 struct uct_policy
**p
= !strcasecmp(optname
, "policy") ? &u
->policy
: &u
->random_policy
;
668 if (!strcasecmp(optval
, "ucb1")) {
669 *p
= policy_ucb1_init(u
, policyarg
);
670 } else if (!strcasecmp(optval
, "ucb1amaf")) {
671 *p
= policy_ucb1amaf_init(u
, policyarg
);
673 fprintf(stderr
, "UCT: Invalid tree policy %s\n", optval
);
676 } else if (!strcasecmp(optname
, "playout") && optval
) {
677 /* Random simulation (playout) policy.
678 * moggy is the default policy with large
679 * amount of domain-specific knowledge and
680 * heuristics. light is a simple uniformly
681 * random move selection policy. */
682 char *playoutarg
= strchr(optval
, ':');
685 if (!strcasecmp(optval
, "moggy")) {
686 u
->playout
= playout_moggy_init(playoutarg
, b
, u
->jdict
);
687 } else if (!strcasecmp(optval
, "light")) {
688 u
->playout
= playout_light_init(playoutarg
, b
);
690 fprintf(stderr
, "UCT: Invalid playout policy %s\n", optval
);
693 } else if (!strcasecmp(optname
, "prior") && optval
) {
694 /* Node priors policy. When expanding a node,
695 * it will seed node values heuristically
696 * (most importantly, based on playout policy
697 * opinion, but also with regard to other
698 * things). See uct/prior.c for details.
699 * Use prior=eqex=0 to disable priors. */
700 u
->prior
= uct_prior_init(optval
, b
);
701 } else if (!strcasecmp(optname
, "mercy") && optval
) {
702 /* Minimal difference of black/white captures
703 * to stop playout - "Mercy Rule". Speeds up
704 * hopeless playouts at the expense of some
706 u
->mercymin
= atoi(optval
);
707 } else if (!strcasecmp(optname
, "gamelen") && optval
) {
708 /* Maximum length of single simulation
710 u
->gamelen
= atoi(optval
);
711 } else if (!strcasecmp(optname
, "expand_p") && optval
) {
712 /* Expand UCT nodes after it has been
713 * visited this many times. */
714 u
->expand_p
= atoi(optval
);
715 } else if (!strcasecmp(optname
, "random_policy_chance") && optval
) {
716 /* If specified (N), with probability 1/N, random_policy policy
717 * descend is used instead of main policy descend; useful
718 * if specified policy (e.g. UCB1AMAF) can make unduly biased
719 * choices sometimes, you can fall back to e.g.
720 * random_policy=UCB1. */
721 u
->random_policy_chance
= atoi(optval
);
723 /** General AMAF behavior */
724 /* (Only relevant if the policy supports AMAF.
725 * More variables can be tuned as policy
728 } else if (!strcasecmp(optname
, "playout_amaf")) {
729 /* Whether to include random playout moves in
730 * AMAF as well. (Otherwise, only tree moves
731 * are included in AMAF. Of course makes sense
732 * only in connection with an AMAF policy.) */
733 /* with-without: 55.5% (+-4.1) */
734 if (optval
&& *optval
== '0')
735 u
->playout_amaf
= false;
737 u
->playout_amaf
= true;
738 } else if (!strcasecmp(optname
, "playout_amaf_nakade")) {
739 /* Whether to include nakade moves from playouts
740 * in the AMAF statistics; this tends to nullify
741 * the playout_amaf effect by adding too much
743 if (optval
&& *optval
== '0')
744 u
->playout_amaf_nakade
= false;
746 u
->playout_amaf_nakade
= true;
747 } else if (!strcasecmp(optname
, "playout_amaf_cutoff") && optval
) {
748 /* Keep only first N% of playout stage AMAF
750 u
->playout_amaf_cutoff
= atoi(optval
);
751 } else if (!strcasecmp(optname
, "amaf_prior") && optval
) {
752 /* In node policy, consider prior values
753 * part of the real result term or part
754 * of the AMAF term? */
755 u
->amaf_prior
= atoi(optval
);
757 /** Performance and memory management */
759 } else if (!strcasecmp(optname
, "threads") && optval
) {
760 /* By default, Pachi will run with only single
761 * tree search thread! */
762 u
->threads
= atoi(optval
);
763 } else if (!strcasecmp(optname
, "thread_model") && optval
) {
764 if (!strcasecmp(optval
, "tree")) {
765 /* Tree parallelization - all threads
766 * grind on the same tree. */
767 u
->thread_model
= TM_TREE
;
769 } else if (!strcasecmp(optval
, "treevl")) {
770 /* Tree parallelization, but also
771 * with virtual losses - this discou-
772 * rages most threads choosing the
773 * same tree branches to read. */
774 u
->thread_model
= TM_TREEVL
;
776 fprintf(stderr
, "UCT: Invalid thread model %s\n", optval
);
779 } else if (!strcasecmp(optname
, "virtual_loss")) {
780 /* Number of virtual losses added before evaluating a node. */
781 u
->virtual_loss
= !optval
|| atoi(optval
);
782 } else if (!strcasecmp(optname
, "pondering")) {
783 /* Keep searching even during opponent's turn. */
784 u
->pondering_opt
= !optval
|| atoi(optval
);
785 } else if (!strcasecmp(optname
, "max_tree_size") && optval
) {
786 /* Maximum amount of memory [MiB] consumed by the move tree.
787 * For fast_alloc it includes the temp tree used for pruning.
788 * Default is 3072 (3 GiB). */
789 u
->max_tree_size
= atol(optval
) * 1048576;
790 } else if (!strcasecmp(optname
, "fast_alloc")) {
791 u
->fast_alloc
= !optval
|| atoi(optval
);
792 } else if (!strcasecmp(optname
, "pruning_threshold") && optval
) {
793 /* Force pruning at beginning of a move if the tree consumes
794 * more than this [MiB]. Default is 10% of max_tree_size.
795 * Increase to reduce pruning time overhead if memory is plentiful.
796 * This option is meaningful only for fast_alloc. */
797 u
->pruning_threshold
= atol(optval
) * 1048576;
801 } else if (!strcasecmp(optname
, "best2_ratio") && optval
) {
802 /* If set, prolong simulating while
803 * first_best/second_best playouts ratio
804 * is less than best2_ratio. */
805 u
->best2_ratio
= atof(optval
);
806 } else if (!strcasecmp(optname
, "bestr_ratio") && optval
) {
807 /* If set, prolong simulating while
808 * best,best_best_child values delta
809 * is more than bestr_ratio. */
810 u
->bestr_ratio
= atof(optval
);
811 } else if (!strcasecmp(optname
, "max_maintime_ratio") && optval
) {
812 /* If set and while not in byoyomi, prolong simulating no more than
813 * max_maintime_ratio times the normal desired thinking time. */
814 u
->max_maintime_ratio
= atof(optval
);
815 } else if (!strcasecmp(optname
, "fuseki_end") && optval
) {
816 /* At the very beginning it's not worth thinking
817 * too long because the playout evaluations are
818 * very noisy. So gradually increase the thinking
819 * time up to maximum when fuseki_end percent
820 * of the board has been played.
821 * This only applies if we are not in byoyomi. */
822 u
->fuseki_end
= atoi(optval
);
823 } else if (!strcasecmp(optname
, "yose_start") && optval
) {
824 /* When yose_start percent of the board has been
825 * played, or if we are in byoyomi, stop spending
826 * more time and spread the remaining time
828 * Between fuseki_end and yose_start, we spend
829 * a constant proportion of the remaining time
830 * on each move. (yose_start should actually
831 * be much earlier than when real yose start,
832 * but "yose" is a good short name to convey
834 u
->yose_start
= atoi(optval
);
838 } else if (!strcasecmp(optname
, "dynkomi") && optval
) {
839 /* Dynamic komi approach; there are multiple
840 * ways to adjust komi dynamically throughout
841 * play. We currently support two: */
842 char *dynkomiarg
= strchr(optval
, ':');
845 if (!strcasecmp(optval
, "none")) {
846 u
->dynkomi
= uct_dynkomi_init_none(u
, dynkomiarg
, b
);
847 } else if (!strcasecmp(optval
, "linear")) {
848 /* You should set dynkomi_mask=1
849 * since this doesn't work well
850 * for white handicaps! */
851 u
->dynkomi
= uct_dynkomi_init_linear(u
, dynkomiarg
, b
);
852 } else if (!strcasecmp(optval
, "adaptive")) {
853 /* There are many more knobs to
854 * crank - see uct/dynkomi.c. */
855 u
->dynkomi
= uct_dynkomi_init_adaptive(u
, dynkomiarg
, b
);
857 fprintf(stderr
, "UCT: Invalid dynkomi mode %s\n", optval
);
860 } else if (!strcasecmp(optname
, "dynkomi_mask") && optval
) {
861 /* Bitmask of colors the player must be
862 * for dynkomi be applied; you may want
863 * to use dynkomi_mask=3 to allow dynkomi
864 * even in games where Pachi is white. */
865 u
->dynkomi_mask
= atoi(optval
);
866 } else if (!strcasecmp(optname
, "dynkomi_interval") && optval
) {
867 /* If non-zero, re-adjust dynamic komi
868 * throughout a single genmove reading,
869 * roughly every N simulations. */
870 /* XXX: Does not work with tree
871 * parallelization. */
872 u
->dynkomi_interval
= atoi(optval
);
874 /** Node value result scaling */
876 } else if (!strcasecmp(optname
, "val_scale") && optval
) {
877 /* How much of the game result value should be
878 * influenced by win size. Zero means it isn't. */
879 u
->val_scale
= atof(optval
);
880 } else if (!strcasecmp(optname
, "val_points") && optval
) {
881 /* Maximum size of win to be scaled into game
882 * result value. Zero means boardsize^2. */
883 u
->val_points
= atoi(optval
) * 2; // result values are doubled
884 } else if (!strcasecmp(optname
, "val_extra")) {
885 /* If false, the score coefficient will be simply
886 * added to the value, instead of scaling the result
887 * coefficient because of it. */
888 u
->val_extra
= !optval
|| atoi(optval
);
891 /* (Purely experimental. Does not work - yet!) */
893 } else if (!strcasecmp(optname
, "local_tree") && optval
) {
894 /* Whether to bias exploration by local tree values
895 * (must be supported by the used policy).
897 * 1: Do, value = result.
898 * Try to temper the result:
899 * 2: Do, value = 0.5+(result-expected)/2.
900 * 3: Do, value = 0.5+bzz((result-expected)^2).
901 * 4: Do, value = 0.5+sqrt(result-expected)/2. */
902 u
->local_tree
= atoi(optval
);
903 } else if (!strcasecmp(optname
, "tenuki_d") && optval
) {
904 /* Tenuki distance at which to break the local tree. */
905 u
->tenuki_d
= atoi(optval
);
906 if (u
->tenuki_d
> TREE_NODE_D_MAX
+ 1) {
907 fprintf(stderr
, "uct: tenuki_d must not be larger than TREE_NODE_D_MAX+1 %d\n", TREE_NODE_D_MAX
+ 1);
910 } else if (!strcasecmp(optname
, "local_tree_aging") && optval
) {
911 /* How much to reduce local tree values between moves. */
912 u
->local_tree_aging
= atof(optval
);
913 } else if (!strcasecmp(optname
, "local_tree_depth_decay") && optval
) {
914 /* With value x>0, during the descent the node
915 * contributes 1/x^depth playouts in
916 * the local tree. I.e., with x>1, nodes more
917 * distant from local situation contribute more
918 * than nodes near the root. */
919 u
->local_tree_depth_decay
= atof(optval
);
920 } else if (!strcasecmp(optname
, "local_tree_allseq")) {
921 /* If disabled, only complete sequences are stored
922 * in the local tree. If this is on, also
923 * subsequences starting at each move are stored. */
924 u
->local_tree_allseq
= !optval
|| atoi(optval
);
925 } else if (!strcasecmp(optname
, "local_tree_rootseqval")) {
926 /* If disabled, expected node value is computed by
927 * summing up values through the whole descent.
928 * If enabled, expected node value for
929 * each sequence is the value at the root of the
931 u
->local_tree_rootseqval
= !optval
|| atoi(optval
);
933 /** Other heuristics */
934 } else if (!strcasecmp(optname
, "significant_threshold") && optval
) {
935 /* Some heuristics (XXX: none in mainline) rely
936 * on the knowledge of the last "significant"
937 * node in the descent. Such a node is
938 * considered reasonably trustworthy to carry
939 * some meaningful information in the values
940 * of the node and its children. */
941 u
->significant_threshold
= atoi(optval
);
943 /** Distributed engine slaves setup */
945 } else if (!strcasecmp(optname
, "slave")) {
946 /* Act as slave for the distributed engine. */
947 u
->slave
= !optval
|| atoi(optval
);
948 } else if (!strcasecmp(optname
, "shared_nodes") && optval
) {
949 /* Share at most shared_nodes between master and slave at each genmoves.
950 * Must use the same value in master and slaves. */
951 u
->shared_nodes
= atoi(optval
);
952 } else if (!strcasecmp(optname
, "shared_levels") && optval
) {
953 /* Share only nodes of level <= shared_levels. */
954 u
->shared_levels
= atoi(optval
);
955 } else if (!strcasecmp(optname
, "stats_hbits") && optval
) {
956 /* Set hash table size to 2^stats_hbits for the shared stats. */
957 u
->stats_hbits
= atoi(optval
);
960 fprintf(stderr
, "uct: Invalid engine argument %s or missing value\n", optname
);
967 u
->policy
= policy_ucb1amaf_init(u
, NULL
);
969 if (!!u
->random_policy_chance
^ !!u
->random_policy
) {
970 fprintf(stderr
, "uct: Only one of random_policy and random_policy_chance is set\n");
974 if (!u
->local_tree
) {
975 /* No ltree aging. */
976 u
->local_tree_aging
= 1.0f
;
980 if (u
->pruning_threshold
< u
->max_tree_size
/ 10)
981 u
->pruning_threshold
= u
->max_tree_size
/ 10;
982 if (u
->pruning_threshold
> u
->max_tree_size
/ 2)
983 u
->pruning_threshold
= u
->max_tree_size
/ 2;
985 /* Limit pruning temp space to 20% of memory. Beyond this we discard
986 * the nodes and recompute them at the next move if necessary. */
987 u
->max_pruned_size
= u
->max_tree_size
/ 5;
988 u
->max_tree_size
-= u
->max_pruned_size
;
990 /* Reserve 5% memory in case the background free() are slower
991 * than the concurrent allocations. */
992 u
->max_tree_size
-= u
->max_tree_size
/ 20;
996 u
->prior
= uct_prior_init(NULL
, b
);
999 u
->playout
= playout_moggy_init(NULL
, b
, u
->jdict
);
1000 if (!u
->playout
->debug_level
)
1001 u
->playout
->debug_level
= u
->debug_level
;
1003 u
->ownermap
.map
= malloc2(board_size2(b
) * sizeof(u
->ownermap
.map
[0]));
1006 if (!u
->stats_hbits
) u
->stats_hbits
= DEFAULT_STATS_HBITS
;
1007 if (!u
->shared_nodes
) u
->shared_nodes
= DEFAULT_SHARED_NODES
;
1008 assert(u
->shared_levels
* board_bits2(b
) <= 8 * (int)sizeof(path_t
));
1012 u
->dynkomi
= uct_dynkomi_init_adaptive(u
, NULL
, b
);
1014 /* Some things remain uninitialized for now - the opening tbook
1015 * is not loaded and the tree not set up. */
1016 /* This will be initialized in setup_state() at the first move
1017 * received/requested. This is because right now we are not aware
1018 * about any komi or handicap setup and such. */
1024 engine_uct_init(char *arg
, struct board
*b
)
1026 struct uct
*u
= uct_state_init(arg
, b
);
1027 struct engine
*e
= calloc2(1, sizeof(struct engine
));
1028 e
->name
= "UCT Engine";
1029 e
->printhook
= uct_printhook_ownermap
;
1030 e
->notify_play
= uct_notify_play
;
1033 e
->result
= uct_result
;
1034 e
->genmove
= uct_genmove
;
1035 e
->genmoves
= uct_genmoves
;
1036 e
->dead_group_list
= uct_dead_group_list
;
1040 e
->notify
= uct_notify
;
1042 const char banner
[] = "I'm playing UCT. When I'm losing, I will resign, "
1043 "if I think I win, I play until you pass. "
1044 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
1045 if (!u
->banner
) u
->banner
= "";
1046 e
->comment
= malloc2(sizeof(banner
) + strlen(u
->banner
) + 1);
1047 sprintf(e
->comment
, "%s %s", banner
, u
->banner
);