16 #include "joseki/base.h"
18 #include "playout/moggy.h"
19 #include "playout/light.h"
20 #include "tactics/util.h"
22 #include "uct/dynkomi.h"
23 #include "uct/internal.h"
24 #include "uct/plugins.h"
25 #include "uct/prior.h"
26 #include "uct/search.h"
27 #include "uct/slave.h"
32 struct uct_policy
*policy_ucb1_init(struct uct
*u
, char *arg
);
33 struct uct_policy
*policy_ucb1amaf_init(struct uct
*u
, char *arg
, struct board
*board
);
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
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,
44 u
->max_pruned_size
, u
->pruning_threshold
, u
->local_tree_aging
, u
->stats_hbits
);
45 if (u
->initial_extra_komi
)
46 u
->t
->extra_komi
= u
->initial_extra_komi
;
48 fast_srandom(u
->force_seed
);
50 fprintf(stderr
, "Fresh board with random seed %lu\n", fast_getseed());
51 if (!u
->no_tbook
&& b
->moves
== 0) {
52 if (color
== S_BLACK
) {
54 } else if (DEBUGL(0)) {
55 fprintf(stderr
, "Warning: First move appears to be white\n");
61 reset_state(struct uct
*u
)
64 tree_done(u
->t
); u
->t
= NULL
;
68 setup_dynkomi(struct uct
*u
, struct board
*b
, enum stone to_play
)
70 if (u
->t
->use_extra_komi
&& !u
->pondering
&& u
->dynkomi
->permove
)
71 u
->t
->extra_komi
= u
->dynkomi
->permove(u
->dynkomi
, b
, u
->t
);
72 else if (!u
->t
->use_extra_komi
)
77 uct_prepare_move(struct uct
*u
, struct board
*b
, enum stone color
)
80 /* Verify that we have sane state. */
82 assert(u
->t
&& b
->moves
);
83 if (color
!= stone_other(u
->t
->root_color
)) {
84 fprintf(stderr
, "Fatal: Non-alternating play detected %d %d\n",
85 color
, u
->t
->root_color
);
88 uct_htable_reset(u
->t
);
91 /* We need fresh state. */
93 setup_state(u
, b
, color
);
96 u
->ownermap
.playouts
= 0;
97 memset(u
->ownermap
.map
, 0, board_size2(b
) * sizeof(u
->ownermap
.map
[0]));
98 u
->played_own
= u
->played_all
= 0;
102 dead_group_list(struct uct
*u
, struct board
*b
, struct move_queue
*mq
)
104 enum gj_state gs_array
[board_size2(b
)];
105 struct group_judgement gj
= { .thres
= GJ_THRES
, .gs
= gs_array
};
106 board_ownermap_judge_groups(b
, &u
->ownermap
, &gj
);
107 groups_of_status(b
, &gj
, GS_DEAD
, mq
);
111 uct_pass_is_safe(struct uct
*u
, struct board
*b
, enum stone color
, bool pass_all_alive
)
113 /* Make sure enough playouts are simulated to get a reasonable dead group list. */
114 while (u
->ownermap
.playouts
< GJ_MINGAMES
)
115 uct_playout(u
, b
, color
, u
->t
);
117 struct move_queue mq
= { .moves
= 0 };
118 dead_group_list(u
, b
, &mq
);
119 if (pass_all_alive
) {
120 for (unsigned int i
= 0; i
< mq
.moves
; i
++) {
121 if (board_at(b
, mq
.move
[i
]) == stone_other(color
)) {
122 return false; // We need to remove opponent dead groups first.
125 mq
.moves
= 0; // our dead stones are alive when pass_all_alive is true
127 if (u
->allow_losing_pass
) {
129 if (board_at(b
, c
) == S_OFFBOARD
)
131 if (board_ownermap_judge_point(&u
->ownermap
, c
, GJ_THRES
) == PJ_UNKNOWN
) {
133 fprintf(stderr
, "uct_pass_is_safe fails at %s[%d]\n", coord2sstr(c
, b
), c
);
134 return false; // Unclear point, clarify first.
139 return pass_is_safe(b
, color
, &mq
);
143 uct_printhook_ownermap(struct board
*board
, coord_t c
, char *s
, char *end
)
145 struct uct
*u
= board
->es
;
150 const char chr
[] = ":XO,"; // dame, black, white, unclear
151 const char chm
[] = ":xo,";
152 char ch
= chr
[board_ownermap_judge_point(&u
->ownermap
, c
, GJ_THRES
)];
153 if (ch
== ',') { // less precise estimate then?
154 ch
= chm
[board_ownermap_judge_point(&u
->ownermap
, c
, 0.67)];
156 s
+= snprintf(s
, end
- s
, "%c ", ch
);
161 uct_notify_play(struct engine
*e
, struct board
*b
, struct move
*m
, char *enginearg
)
163 struct uct
*u
= e
->data
;
165 /* No state, create one - this is probably game beginning
166 * and we need to load the opening tbook right now. */
167 uct_prepare_move(u
, b
, m
->color
);
171 /* Stop pondering, required by tree_promote_at() */
172 uct_pondering_stop(u
);
173 if (UDEBUGL(2) && u
->slave
)
174 tree_dump(u
->t
, u
->dumpthres
);
176 if (is_resign(m
->coord
)) {
182 /* Promote node of the appropriate move to the tree root. */
184 if (!tree_promote_at(u
->t
, b
, m
->coord
)) {
186 fprintf(stderr
, "Warning: Cannot promote move node! Several play commands in row?\n");
187 /* Preserve dynamic komi information, though, that is important. */
188 u
->initial_extra_komi
= u
->t
->extra_komi
;
193 /* If we are a slave in a distributed engine, start pondering once
194 * we know which move we actually played. See uct_genmove() about
195 * the check for pass. */
196 if (u
->pondering_opt
&& u
->slave
&& m
->color
== u
->my_color
&& !is_pass(m
->coord
))
197 uct_pondering_start(u
, b
, u
->t
, stone_other(m
->color
));
203 uct_undo(struct engine
*e
, struct board
*b
)
205 struct uct
*u
= e
->data
;
207 if (!u
->t
) return NULL
;
208 uct_pondering_stop(u
);
209 u
->initial_extra_komi
= u
->t
->extra_komi
;
215 uct_result(struct engine
*e
, struct board
*b
)
217 struct uct
*u
= e
->data
;
218 static char reply
[1024];
222 enum stone color
= u
->t
->root_color
;
223 struct tree_node
*n
= u
->t
->root
;
224 snprintf(reply
, 1024, "%s %s %d %.2f %.1f",
225 stone2str(color
), coord2sstr(node_coord(n
), b
),
226 n
->u
.playouts
, tree_node_get_value(u
->t
, -1, n
->u
.value
),
227 u
->t
->use_extra_komi
? u
->t
->extra_komi
: 0);
232 uct_chat(struct engine
*e
, struct board
*b
, bool opponent
, char *from
, char *cmd
)
234 struct uct
*u
= e
->data
;
237 return generic_chat(b
, opponent
, from
, cmd
, S_NONE
, pass
, 0, 1, u
->threads
, 0.0, 0.0);
239 struct tree_node
*n
= u
->t
->root
;
240 double winrate
= tree_node_get_value(u
->t
, -1, n
->u
.value
);
241 double extra_komi
= u
->t
->use_extra_komi
&& abs(u
->t
->extra_komi
) >= 0.5 ? u
->t
->extra_komi
: 0;
243 return generic_chat(b
, opponent
, from
, cmd
, u
->t
->root_color
, node_coord(n
), n
->u
.playouts
, 1,
244 u
->threads
, winrate
, extra_komi
);
248 uct_dead_group_list(struct engine
*e
, struct board
*b
, struct move_queue
*mq
)
250 struct uct
*u
= e
->data
;
252 /* This means the game is probably over, no use pondering on. */
253 uct_pondering_stop(u
);
255 if (u
->pass_all_alive
)
256 return; // no dead groups
258 bool mock_state
= false;
261 /* No state, but we cannot just back out - we might
262 * have passed earlier, only assuming some stones are
263 * dead, and then re-connected, only to lose counting
264 * when all stones are assumed alive. */
265 uct_prepare_move(u
, b
, S_BLACK
); assert(u
->t
);
268 /* Make sure the ownermap is well-seeded. */
269 while (u
->ownermap
.playouts
< GJ_MINGAMES
)
270 uct_playout(u
, b
, S_BLACK
, u
->t
);
271 /* Show the ownermap: */
273 board_print_custom(b
, stderr
, uct_printhook_ownermap
);
275 dead_group_list(u
, b
, mq
);
278 /* Clean up the mock state in case we will receive
279 * a genmove; we could get a non-alternating-move
280 * error from uct_prepare_move() in that case otherwise. */
286 playout_policy_done(struct playout_policy
*p
)
288 if (p
->done
) p
->done(p
);
289 if (p
->data
) free(p
->data
);
294 uct_done(struct engine
*e
)
296 /* This is called on engine reset, especially when clear_board
297 * is received and new game should begin. */
298 struct uct
*u
= e
->data
;
299 uct_pondering_stop(u
);
300 if (u
->t
) reset_state(u
);
301 free(u
->ownermap
.map
);
304 free(u
->random_policy
);
305 playout_policy_done(u
->playout
);
306 uct_prior_done(u
->prior
);
307 joseki_done(u
->jdict
);
308 pluginset_done(u
->plugins
);
313 /* Run time-limited MCTS search on foreground. */
315 uct_search(struct uct
*u
, struct board
*b
, struct time_info
*ti
, enum stone color
, struct tree
*t
, bool print_progress
)
317 struct uct_search_state s
;
318 uct_search_start(u
, b
, color
, t
, ti
, &s
);
319 if (UDEBUGL(2) && s
.base_playouts
> 0)
320 fprintf(stderr
, "<pre-simulated %d games>\n", s
.base_playouts
);
322 /* The search tree is ctx->t. This is currently == . It is important
323 * to reference ctx->t directly since the
324 * thread manager will swap the tree pointer asynchronously. */
326 /* Now, just periodically poll the search tree. */
327 /* Note that in case of TD_GAMES, threads will not wait for
328 * the uct_search_check_stop() signalization. */
330 time_sleep(TREE_BUSYWAIT_INTERVAL
);
331 /* TREE_BUSYWAIT_INTERVAL should never be less than desired time, or the
332 * time control is broken. But if it happens to be less, we still search
333 * at least 100ms otherwise the move is completely random. */
335 int i
= uct_search_games(&s
);
336 /* Print notifications etc. */
337 uct_search_progress(u
, b
, color
, t
, ti
, &s
, i
);
338 /* Check if we should stop the search. */
339 if (uct_search_check_stop(u
, b
, color
, t
, ti
, &s
, i
))
343 struct uct_thread_ctx
*ctx
= uct_search_stop();
344 if (UDEBUGL(2)) tree_dump(t
, u
->dumpthres
);
346 fprintf(stderr
, "(avg score %f/%d; dynkomi's %f/%d value %f/%d)\n",
347 t
->avg_score
.value
, t
->avg_score
.playouts
,
348 u
->dynkomi
->score
.value
, u
->dynkomi
->score
.playouts
,
349 u
->dynkomi
->value
.value
, u
->dynkomi
->value
.playouts
);
351 uct_progress_status(u
, t
, color
, ctx
->games
, NULL
);
353 u
->played_own
+= ctx
->games
;
357 /* Start pondering background with @color to play. */
359 uct_pondering_start(struct uct
*u
, struct board
*b0
, struct tree
*t
, enum stone color
)
362 fprintf(stderr
, "Starting to ponder with color %s\n", stone2str(stone_other(color
)));
365 /* We need a local board copy to ponder upon. */
366 struct board
*b
= malloc2(sizeof(*b
)); board_copy(b
, b0
);
368 /* *b0 did not have the genmove'd move played yet. */
369 struct move m
= { node_coord(t
->root
), t
->root_color
};
370 int res
= board_play(b
, &m
);
372 setup_dynkomi(u
, b
, stone_other(m
.color
));
374 /* Start MCTS manager thread "headless". */
375 static struct uct_search_state s
;
376 uct_search_start(u
, b
, color
, t
, NULL
, &s
);
379 /* uct_search_stop() frontend for the pondering (non-genmove) mode, and
380 * to stop the background search for a slave in the distributed engine. */
382 uct_pondering_stop(struct uct
*u
)
384 if (!thread_manager_running
)
387 /* Stop the thread manager. */
388 struct uct_thread_ctx
*ctx
= uct_search_stop();
390 if (u
->pondering
) fprintf(stderr
, "(pondering) ");
391 uct_progress_status(u
, ctx
->t
, ctx
->color
, ctx
->games
, NULL
);
395 u
->pondering
= false;
401 uct_genmove_setup(struct uct
*u
, struct board
*b
, enum stone color
)
403 if (b
->superko_violation
) {
404 fprintf(stderr
, "!!! WARNING: SUPERKO VIOLATION OCCURED BEFORE THIS MOVE\n");
405 fprintf(stderr
, "Maybe you play with situational instead of positional superko?\n");
406 fprintf(stderr
, "I'm going to ignore the violation, but note that I may miss\n");
407 fprintf(stderr
, "some moves valid under this ruleset because of this.\n");
408 b
->superko_violation
= false;
411 uct_prepare_move(u
, b
, color
);
416 /* How to decide whether to use dynkomi in this game? Since we use
417 * pondering, it's not simple "who-to-play" matter. Decide based on
418 * the last genmove issued. */
419 u
->t
->use_extra_komi
= !!(u
->dynkomi_mask
& color
);
420 setup_dynkomi(u
, b
, color
);
422 if (b
->rules
== RULES_JAPANESE
)
423 u
->territory_scoring
= true;
425 /* Make pessimistic assumption about komi for Japanese rules to
426 * avoid losing by 0.5 when winning by 0.5 with Chinese rules.
427 * The rules usually give the same winner if the integer part of komi
428 * is odd so we adjust the komi only if it is even (for a board of
429 * odd size). We are not trying to get an exact evaluation for rare
430 * cases of seki. For details see http://home.snafu.de/jasiek/parity.html */
431 if (u
->territory_scoring
&& (((int)floor(b
->komi
) + board_size(b
)) & 1)) {
432 b
->komi
+= (color
== S_BLACK
? 1.0 : -1.0);
434 fprintf(stderr
, "Setting komi to %.1f assuming Japanese rules\n",
440 uct_genmove(struct engine
*e
, struct board
*b
, struct time_info
*ti
, enum stone color
, bool pass_all_alive
)
442 double start_time
= time_now();
443 struct uct
*u
= e
->data
;
444 u
->pass_all_alive
|= pass_all_alive
;
445 uct_pondering_stop(u
);
446 uct_genmove_setup(u
, b
, color
);
448 /* Start the Monte Carlo Tree Search! */
449 int base_playouts
= u
->t
->root
->u
.playouts
;
450 int played_games
= uct_search(u
, b
, ti
, color
, u
->t
, false);
453 struct tree_node
*best
;
454 best
= uct_search_result(u
, b
, color
, u
->pass_all_alive
, played_games
, base_playouts
, &best_coord
);
457 double time
= time_now() - start_time
+ 0.000001; /* avoid divide by zero */
458 fprintf(stderr
, "genmove in %0.2fs (%d games/s, %d games/s/thread)\n",
459 time
, (int)(played_games
/time
), (int)(played_games
/time
/u
->threads
));
462 uct_progress_status(u
, u
->t
, color
, played_games
, &best_coord
);
465 /* Pass or resign. */
466 if (is_pass(best_coord
))
467 u
->initial_extra_komi
= u
->t
->extra_komi
;
469 return coord_copy(best_coord
);
471 tree_promote_node(u
->t
, &best
);
473 /* After a pass, pondering is harmful for two reasons:
474 * (i) We might keep pondering even when the game is over.
475 * Of course this is the case for opponent resign as well.
476 * (ii) More importantly, the ownermap will get skewed since
477 * the UCT will start cutting off any playouts. */
478 if (u
->pondering_opt
&& !is_pass(node_coord(best
))) {
479 uct_pondering_start(u
, b
, u
->t
, stone_other(color
));
481 return coord_copy(best_coord
);
486 uct_gentbook(struct engine
*e
, struct board
*b
, struct time_info
*ti
, enum stone color
)
488 struct uct
*u
= e
->data
;
489 if (!u
->t
) uct_prepare_move(u
, b
, color
);
492 if (ti
->dim
== TD_GAMES
) {
493 /* Don't count in games that already went into the tbook. */
494 ti
->len
.games
+= u
->t
->root
->u
.playouts
;
496 uct_search(u
, b
, ti
, color
, u
->t
, true);
498 assert(ti
->dim
== TD_GAMES
);
499 tree_save(u
->t
, b
, ti
->len
.games
/ 100);
505 uct_dumptbook(struct engine
*e
, struct board
*b
, enum stone color
)
507 struct uct
*u
= e
->data
;
508 struct tree
*t
= tree_init(b
, color
, u
->fast_alloc
? u
->max_tree_size
: 0,
509 u
->max_pruned_size
, u
->pruning_threshold
, u
->local_tree_aging
, 0);
517 uct_evaluate_one(struct engine
*e
, struct board
*b
, struct time_info
*ti
, coord_t c
, enum stone color
)
519 struct uct
*u
= e
->data
;
523 struct move m
= { c
, color
};
524 int res
= board_play(&b2
, &m
);
527 color
= stone_other(color
);
529 if (u
->t
) reset_state(u
);
530 uct_prepare_move(u
, &b2
, color
);
534 uct_search(u
, &b2
, ti
, color
, u
->t
, true);
535 struct tree_node
*best
= u
->policy
->choose(u
->policy
, u
->t
->root
, &b2
, color
, resign
);
537 bestval
= NAN
; // the opponent has no reply!
539 bestval
= tree_node_get_value(u
->t
, 1, best
->u
.value
);
542 reset_state(u
); // clean our junk
544 return isnan(bestval
) ? NAN
: 1.0f
- bestval
;
548 uct_evaluate(struct engine
*e
, struct board
*b
, struct time_info
*ti
, floating_t
*vals
, enum stone color
)
550 for (int i
= 0; i
< b
->flen
; i
++) {
551 if (is_pass(b
->f
[i
]))
554 vals
[i
] = uct_evaluate_one(e
, b
, ti
, b
->f
[i
], color
);
560 uct_state_init(char *arg
, struct board
*b
)
562 struct uct
*u
= calloc2(1, sizeof(struct uct
));
563 bool pat_setup
= false;
565 u
->debug_level
= debug_level
;
566 u
->reportfreq
= 10000;
567 u
->gamelen
= MC_GAMELEN
;
568 u
->resign_threshold
= 0.2;
569 u
->sure_win_threshold
= 0.9;
571 u
->significant_threshold
= 50;
574 u
->playout_amaf
= true;
575 u
->amaf_prior
= false;
576 u
->max_tree_size
= 1408ULL * 1048576;
577 u
->fast_alloc
= true;
578 u
->pruning_threshold
= 0;
581 u
->thread_model
= TM_TREEVL
;
584 u
->fuseki_end
= 20; // max time at 361*20% = 72 moves (our 36th move, still 99 to play)
585 u
->yose_start
= 40; // (100-40-25)*361/100/2 = 63 moves still to play by us then
586 u
->bestr_ratio
= 0.02;
587 // 2.5 is clearly too much, but seems to compensate well for overly stern time allocations.
588 // TODO: Further tuning and experiments with better time allocation schemes.
589 u
->best2_ratio
= 2.5;
590 u
->max_maintime_ratio
= 3.0;
592 u
->val_scale
= 0; u
->val_points
= 40;
593 u
->dynkomi_interval
= 1000;
594 u
->dynkomi_mask
= S_BLACK
| S_WHITE
;
597 u
->local_tree_aging
= 80;
598 u
->local_tree_depth_decay
= 1.5;
599 u
->local_tree_eval
= LTE_ROOT
;
600 u
->local_tree_neival
= true;
604 u
->stats_delay
= 0.01; // 10 ms
606 u
->plugins
= pluginset_init(b
);
608 u
->jdict
= joseki_load(b
->size
);
611 char *optspec
, *next
= arg
;
614 next
+= strcspn(next
, ",");
615 if (*next
) { *next
++ = 0; } else { *next
= 0; }
617 char *optname
= optspec
;
618 char *optval
= strchr(optspec
, '=');
619 if (optval
) *optval
++ = 0;
623 if (!strcasecmp(optname
, "debug")) {
625 u
->debug_level
= atoi(optval
);
628 } else if (!strcasecmp(optname
, "reporting") && optval
) {
629 /* The format of output for detailed progress
630 * information (such as current best move and
631 * its value, etc.). */
632 if (!strcasecmp(optval
, "text")) {
633 /* Plaintext traditional output. */
634 u
->reporting
= UR_TEXT
;
635 } else if (!strcasecmp(optval
, "json")) {
636 /* JSON output. Implies debug=0. */
637 u
->reporting
= UR_JSON
;
639 } else if (!strcasecmp(optval
, "jsonbig")) {
640 /* JSON output, but much more detailed.
641 * Implies debug=0. */
642 u
->reporting
= UR_JSON_BIG
;
645 fprintf(stderr
, "UCT: Invalid reporting format %s\n", optval
);
648 } else if (!strcasecmp(optname
, "reportfreq") && optval
) {
649 /* The progress information line will be shown
650 * every <reportfreq> simulations. */
651 u
->reportfreq
= atoi(optval
);
652 } else if (!strcasecmp(optname
, "dumpthres") && optval
) {
653 /* When dumping the UCT tree on output, include
654 * nodes with at least this many playouts.
655 * (This value is re-scaled "intelligently"
656 * in case of very large trees.) */
657 u
->dumpthres
= atoi(optval
);
658 } else if (!strcasecmp(optname
, "resign_threshold") && optval
) {
659 /* Resign when this ratio of games is lost
660 * after GJ_MINGAMES sample is taken. */
661 u
->resign_threshold
= atof(optval
);
662 } else if (!strcasecmp(optname
, "sure_win_threshold") && optval
) {
663 /* Stop reading when this ratio of games is won
664 * after PLAYOUT_EARLY_BREAK_MIN sample is
665 * taken. (Prevents stupid time losses,
666 * friendly to human opponents.) */
667 u
->sure_win_threshold
= atof(optval
);
668 } else if (!strcasecmp(optname
, "force_seed") && optval
) {
669 /* Set RNG seed at the tree setup. */
670 u
->force_seed
= atoi(optval
);
671 } else if (!strcasecmp(optname
, "no_tbook")) {
672 /* Disable UCT opening tbook. */
674 } else if (!strcasecmp(optname
, "pass_all_alive")) {
675 /* Whether to consider passing only after all
676 * dead groups were removed from the board;
677 * this is like all genmoves are in fact
678 * kgs-genmove_cleanup. */
679 u
->pass_all_alive
= !optval
|| atoi(optval
);
680 } else if (!strcasecmp(optname
, "allow_losing_pass")) {
681 /* Whether to consider passing in a clear
682 * but losing situation, to be scored as a loss
684 u
->allow_losing_pass
= !optval
|| atoi(optval
);
685 } else if (!strcasecmp(optname
, "territory_scoring")) {
686 /* Use territory scoring (default is area scoring).
687 * An explicit kgs-rules command overrides this. */
688 u
->territory_scoring
= !optval
|| atoi(optval
);
689 } else if (!strcasecmp(optname
, "stones_only")) {
690 /* Do not count eyes. Nice to teach go to kids.
691 * http://strasbourg.jeudego.org/regle_strasbourgeoise.htm */
692 b
->rules
= RULES_STONES_ONLY
;
693 u
->pass_all_alive
= true;
694 } else if (!strcasecmp(optname
, "banner") && optval
) {
695 /* Additional banner string. This must come as the
696 * last engine parameter. */
697 if (*next
) *--next
= ',';
698 u
->banner
= strdup(optval
);
700 } else if (!strcasecmp(optname
, "plugin") && optval
) {
701 /* Load an external plugin; filename goes before the colon,
702 * extra arguments after the colon. */
703 char *pluginarg
= strchr(optval
, ':');
706 plugin_load(u
->plugins
, optval
, pluginarg
);
708 /** UCT behavior and policies */
710 } else if ((!strcasecmp(optname
, "policy")
711 /* Node selection policy. ucb1amaf is the
712 * default policy implementing RAVE, while
713 * ucb1 is the simple exploration/exploitation
714 * policy. Policies can take further extra
716 || !strcasecmp(optname
, "random_policy")) && optval
) {
717 /* A policy to be used randomly with small
718 * chance instead of the default policy. */
719 char *policyarg
= strchr(optval
, ':');
720 struct uct_policy
**p
= !strcasecmp(optname
, "policy") ? &u
->policy
: &u
->random_policy
;
723 if (!strcasecmp(optval
, "ucb1")) {
724 *p
= policy_ucb1_init(u
, policyarg
);
725 } else if (!strcasecmp(optval
, "ucb1amaf")) {
726 *p
= policy_ucb1amaf_init(u
, policyarg
, b
);
728 fprintf(stderr
, "UCT: Invalid tree policy %s\n", optval
);
731 } else if (!strcasecmp(optname
, "playout") && optval
) {
732 /* Random simulation (playout) policy.
733 * moggy is the default policy with large
734 * amount of domain-specific knowledge and
735 * heuristics. light is a simple uniformly
736 * random move selection policy. */
737 char *playoutarg
= strchr(optval
, ':');
740 if (!strcasecmp(optval
, "moggy")) {
741 u
->playout
= playout_moggy_init(playoutarg
, b
, u
->jdict
);
742 } else if (!strcasecmp(optval
, "light")) {
743 u
->playout
= playout_light_init(playoutarg
, b
);
745 fprintf(stderr
, "UCT: Invalid playout policy %s\n", optval
);
748 } else if (!strcasecmp(optname
, "prior") && optval
) {
749 /* Node priors policy. When expanding a node,
750 * it will seed node values heuristically
751 * (most importantly, based on playout policy
752 * opinion, but also with regard to other
753 * things). See uct/prior.c for details.
754 * Use prior=eqex=0 to disable priors. */
755 u
->prior
= uct_prior_init(optval
, b
, u
);
756 } else if (!strcasecmp(optname
, "mercy") && optval
) {
757 /* Minimal difference of black/white captures
758 * to stop playout - "Mercy Rule". Speeds up
759 * hopeless playouts at the expense of some
761 u
->mercymin
= atoi(optval
);
762 } else if (!strcasecmp(optname
, "gamelen") && optval
) {
763 /* Maximum length of single simulation
765 u
->gamelen
= atoi(optval
);
766 } else if (!strcasecmp(optname
, "expand_p") && optval
) {
767 /* Expand UCT nodes after it has been
768 * visited this many times. */
769 u
->expand_p
= atoi(optval
);
770 } else if (!strcasecmp(optname
, "random_policy_chance") && optval
) {
771 /* If specified (N), with probability 1/N, random_policy policy
772 * descend is used instead of main policy descend; useful
773 * if specified policy (e.g. UCB1AMAF) can make unduly biased
774 * choices sometimes, you can fall back to e.g.
775 * random_policy=UCB1. */
776 u
->random_policy_chance
= atoi(optval
);
778 /** General AMAF behavior */
779 /* (Only relevant if the policy supports AMAF.
780 * More variables can be tuned as policy
783 } else if (!strcasecmp(optname
, "playout_amaf")) {
784 /* Whether to include random playout moves in
785 * AMAF as well. (Otherwise, only tree moves
786 * are included in AMAF. Of course makes sense
787 * only in connection with an AMAF policy.) */
788 /* with-without: 55.5% (+-4.1) */
789 if (optval
&& *optval
== '0')
790 u
->playout_amaf
= false;
792 u
->playout_amaf
= true;
793 } else if (!strcasecmp(optname
, "playout_amaf_cutoff") && optval
) {
794 /* Keep only first N% of playout stage AMAF
796 u
->playout_amaf_cutoff
= atoi(optval
);
797 } else if (!strcasecmp(optname
, "amaf_prior") && optval
) {
798 /* In node policy, consider prior values
799 * part of the real result term or part
800 * of the AMAF term? */
801 u
->amaf_prior
= atoi(optval
);
803 /** Performance and memory management */
805 } else if (!strcasecmp(optname
, "threads") && optval
) {
806 /* By default, Pachi will run with only single
807 * tree search thread! */
808 u
->threads
= atoi(optval
);
809 } else if (!strcasecmp(optname
, "thread_model") && optval
) {
810 if (!strcasecmp(optval
, "tree")) {
811 /* Tree parallelization - all threads
812 * grind on the same tree. */
813 u
->thread_model
= TM_TREE
;
815 } else if (!strcasecmp(optval
, "treevl")) {
816 /* Tree parallelization, but also
817 * with virtual losses - this discou-
818 * rages most threads choosing the
819 * same tree branches to read. */
820 u
->thread_model
= TM_TREEVL
;
822 fprintf(stderr
, "UCT: Invalid thread model %s\n", optval
);
825 } else if (!strcasecmp(optname
, "virtual_loss")) {
826 /* Number of virtual losses added before evaluating a node. */
827 u
->virtual_loss
= !optval
|| atoi(optval
);
828 } else if (!strcasecmp(optname
, "pondering")) {
829 /* Keep searching even during opponent's turn. */
830 u
->pondering_opt
= !optval
|| atoi(optval
);
831 } else if (!strcasecmp(optname
, "max_tree_size") && optval
) {
832 /* Maximum amount of memory [MiB] consumed by the move tree.
833 * For fast_alloc it includes the temp tree used for pruning.
834 * Default is 3072 (3 GiB). */
835 u
->max_tree_size
= atol(optval
) * 1048576;
836 } else if (!strcasecmp(optname
, "fast_alloc")) {
837 u
->fast_alloc
= !optval
|| atoi(optval
);
838 } else if (!strcasecmp(optname
, "pruning_threshold") && optval
) {
839 /* Force pruning at beginning of a move if the tree consumes
840 * more than this [MiB]. Default is 10% of max_tree_size.
841 * Increase to reduce pruning time overhead if memory is plentiful.
842 * This option is meaningful only for fast_alloc. */
843 u
->pruning_threshold
= atol(optval
) * 1048576;
847 } else if (!strcasecmp(optname
, "best2_ratio") && optval
) {
848 /* If set, prolong simulating while
849 * first_best/second_best playouts ratio
850 * is less than best2_ratio. */
851 u
->best2_ratio
= atof(optval
);
852 } else if (!strcasecmp(optname
, "bestr_ratio") && optval
) {
853 /* If set, prolong simulating while
854 * best,best_best_child values delta
855 * is more than bestr_ratio. */
856 u
->bestr_ratio
= atof(optval
);
857 } else if (!strcasecmp(optname
, "max_maintime_ratio") && optval
) {
858 /* If set and while not in byoyomi, prolong simulating no more than
859 * max_maintime_ratio times the normal desired thinking time. */
860 u
->max_maintime_ratio
= atof(optval
);
861 } else if (!strcasecmp(optname
, "fuseki_end") && optval
) {
862 /* At the very beginning it's not worth thinking
863 * too long because the playout evaluations are
864 * very noisy. So gradually increase the thinking
865 * time up to maximum when fuseki_end percent
866 * of the board has been played.
867 * This only applies if we are not in byoyomi. */
868 u
->fuseki_end
= atoi(optval
);
869 } else if (!strcasecmp(optname
, "yose_start") && optval
) {
870 /* When yose_start percent of the board has been
871 * played, or if we are in byoyomi, stop spending
872 * more time and spread the remaining time
874 * Between fuseki_end and yose_start, we spend
875 * a constant proportion of the remaining time
876 * on each move. (yose_start should actually
877 * be much earlier than when real yose start,
878 * but "yose" is a good short name to convey
880 u
->yose_start
= atoi(optval
);
884 } else if (!strcasecmp(optname
, "dynkomi") && optval
) {
885 /* Dynamic komi approach; there are multiple
886 * ways to adjust komi dynamically throughout
887 * play. We currently support two: */
888 char *dynkomiarg
= strchr(optval
, ':');
891 if (!strcasecmp(optval
, "none")) {
892 u
->dynkomi
= uct_dynkomi_init_none(u
, dynkomiarg
, b
);
893 } else if (!strcasecmp(optval
, "linear")) {
894 /* You should set dynkomi_mask=1 or a very low
895 * handicap_value for white. */
896 u
->dynkomi
= uct_dynkomi_init_linear(u
, dynkomiarg
, b
);
897 } else if (!strcasecmp(optval
, "adaptive")) {
898 /* There are many more knobs to
899 * crank - see uct/dynkomi.c. */
900 u
->dynkomi
= uct_dynkomi_init_adaptive(u
, dynkomiarg
, b
);
902 fprintf(stderr
, "UCT: Invalid dynkomi mode %s\n", optval
);
905 } else if (!strcasecmp(optname
, "dynkomi_mask") && optval
) {
906 /* Bitmask of colors the player must be
907 * for dynkomi be applied; the default dynkomi_mask=3 allows
908 * dynkomi even in games where Pachi is white. */
909 u
->dynkomi_mask
= atoi(optval
);
910 } else if (!strcasecmp(optname
, "dynkomi_interval") && optval
) {
911 /* If non-zero, re-adjust dynamic komi
912 * throughout a single genmove reading,
913 * roughly every N simulations. */
914 /* XXX: Does not work with tree
915 * parallelization. */
916 u
->dynkomi_interval
= atoi(optval
);
917 } else if (!strcasecmp(optname
, "extra_komi") && optval
) {
918 /* Initial dynamic komi settings. This
919 * is useful for the adaptive dynkomi
920 * policy as the value to start with
921 * (this is NOT kept fixed) in case
922 * there is not enough time in the search
923 * to adjust the value properly (e.g. the
924 * game was interrupted). */
925 u
->initial_extra_komi
= atof(optval
);
927 /** Node value result scaling */
929 } else if (!strcasecmp(optname
, "val_scale") && optval
) {
930 /* How much of the game result value should be
931 * influenced by win size. Zero means it isn't. */
932 u
->val_scale
= atof(optval
);
933 } else if (!strcasecmp(optname
, "val_points") && optval
) {
934 /* Maximum size of win to be scaled into game
935 * result value. Zero means boardsize^2. */
936 u
->val_points
= atoi(optval
) * 2; // result values are doubled
937 } else if (!strcasecmp(optname
, "val_extra")) {
938 /* If false, the score coefficient will be simply
939 * added to the value, instead of scaling the result
940 * coefficient because of it. */
941 u
->val_extra
= !optval
|| atoi(optval
);
942 } else if (!strcasecmp(optname
, "val_byavg")) {
943 /* If true, the score included in the value will
944 * be relative to average score in the current
945 * search episode inst. of jigo. */
946 u
->val_byavg
= !optval
|| atoi(optval
);
947 } else if (!strcasecmp(optname
, "val_bytemp")) {
948 /* If true, the value scaling coefficient
949 * is different based on value extremity
950 * (dist. from 0.5), linear between
951 * val_bytemp_min, val_scale. */
952 u
->val_bytemp
= !optval
|| atoi(optval
);
953 } else if (!strcasecmp(optname
, "val_bytemp_min") && optval
) {
954 /* Minimum val_scale in case of val_bytemp. */
955 u
->val_bytemp_min
= atof(optval
);
958 /* (Purely experimental. Does not work - yet!) */
960 } else if (!strcasecmp(optname
, "local_tree")) {
961 /* Whether to bias exploration by local tree values. */
962 u
->local_tree
= !optval
|| atoi(optval
);
963 } else if (!strcasecmp(optname
, "tenuki_d") && optval
) {
964 /* Tenuki distance at which to break the local tree. */
965 u
->tenuki_d
= atoi(optval
);
966 if (u
->tenuki_d
> TREE_NODE_D_MAX
+ 1) {
967 fprintf(stderr
, "uct: tenuki_d must not be larger than TREE_NODE_D_MAX+1 %d\n", TREE_NODE_D_MAX
+ 1);
970 } else if (!strcasecmp(optname
, "local_tree_aging") && optval
) {
971 /* How much to reduce local tree values between moves. */
972 u
->local_tree_aging
= atof(optval
);
973 } else if (!strcasecmp(optname
, "local_tree_depth_decay") && optval
) {
974 /* With value x>0, during the descent the node
975 * contributes 1/x^depth playouts in
976 * the local tree. I.e., with x>1, nodes more
977 * distant from local situation contribute more
978 * than nodes near the root. */
979 u
->local_tree_depth_decay
= atof(optval
);
980 } else if (!strcasecmp(optname
, "local_tree_allseq")) {
981 /* If disabled, only complete sequences are stored
982 * in the local tree. If this is on, also
983 * subsequences starting at each move are stored. */
984 u
->local_tree_allseq
= !optval
|| atoi(optval
);
985 } else if (!strcasecmp(optname
, "local_tree_neival")) {
986 /* If disabled, local node value is not
987 * computed just based on terminal status
988 * of the coordinate, but also its neighbors. */
989 u
->local_tree_neival
= !optval
|| atoi(optval
);
990 } else if (!strcasecmp(optname
, "local_tree_eval")) {
991 /* How is the value inserted in the local tree
993 if (!strcasecmp(optval
, "root"))
994 /* All moves within a tree branch are
995 * considered wrt. their merit
996 * reaching tachtical goal of making
997 * the first move in the branch
999 u
->local_tree_eval
= LTE_ROOT
;
1000 else if (!strcasecmp(optval
, "each"))
1001 /* Each move is considered wrt.
1002 * its own survival. */
1003 u
->local_tree_eval
= LTE_EACH
;
1004 else if (!strcasecmp(optval
, "total"))
1005 /* The tactical goal is the survival
1006 * of all the moves of my color and
1007 * non-survival of all the opponent
1008 * moves. Local values (and their
1009 * inverses) are averaged. */
1010 u
->local_tree_eval
= LTE_TOTAL
;
1012 fprintf(stderr
, "uct: unknown local_tree_eval %s\n", optval
);
1015 } else if (!strcasecmp(optname
, "local_tree_rootchoose")) {
1016 /* If disabled, only moves within the local
1017 * tree branch are considered; the values
1018 * of the branch roots (i.e. root children)
1019 * are ignored. This may make sense together
1020 * with eval!=each, we consider only moves
1021 * that influence the goal, not the "rating"
1022 * of the goal itself. (The real solution
1023 * will be probably using criticality to pick
1024 * local tree branches.) */
1025 u
->local_tree_rootchoose
= !optval
|| atoi(optval
);
1027 /** Other heuristics */
1028 } else if (!strcasecmp(optname
, "patterns")) {
1029 /* Load pattern database. Various modules
1030 * (priors, policies etc.) may make use
1031 * of this database. They will request
1032 * it automatically in that case, but you
1033 * can use this option to tweak the pattern
1035 patterns_init(&u
->pat
, optval
, false, true);
1036 u
->want_pat
= pat_setup
= true;
1037 } else if (!strcasecmp(optname
, "significant_threshold") && optval
) {
1038 /* Some heuristics (XXX: none in mainline) rely
1039 * on the knowledge of the last "significant"
1040 * node in the descent. Such a node is
1041 * considered reasonably trustworthy to carry
1042 * some meaningful information in the values
1043 * of the node and its children. */
1044 u
->significant_threshold
= atoi(optval
);
1046 /** Distributed engine slaves setup */
1048 } else if (!strcasecmp(optname
, "slave")) {
1049 /* Act as slave for the distributed engine. */
1050 u
->slave
= !optval
|| atoi(optval
);
1051 } else if (!strcasecmp(optname
, "slave_index") && optval
) {
1052 /* Optional index if per-slave behavior is desired.
1053 * Must be given as index/max */
1054 u
->slave_index
= atoi(optval
);
1055 char *p
= strchr(optval
, '/');
1056 if (p
) u
->max_slaves
= atoi(++p
);
1057 } else if (!strcasecmp(optname
, "shared_nodes") && optval
) {
1058 /* Share at most shared_nodes between master and slave at each genmoves.
1059 * Must use the same value in master and slaves. */
1060 u
->shared_nodes
= atoi(optval
);
1061 } else if (!strcasecmp(optname
, "shared_levels") && optval
) {
1062 /* Share only nodes of level <= shared_levels. */
1063 u
->shared_levels
= atoi(optval
);
1064 } else if (!strcasecmp(optname
, "stats_hbits") && optval
) {
1065 /* Set hash table size to 2^stats_hbits for the shared stats. */
1066 u
->stats_hbits
= atoi(optval
);
1067 } else if (!strcasecmp(optname
, "stats_delay") && optval
) {
1068 /* How long to wait in slave for initial stats to build up before
1069 * replying to the genmoves command (in ms) */
1070 u
->stats_delay
= 0.001 * atof(optval
);
1074 } else if (!strcasecmp(optname
, "maximize_score")) {
1075 /* A combination of settings that will make
1076 * Pachi try to maximize his points (instead
1077 * of playing slack yose) or minimize his loss
1078 * (and proceed to counting even when losing). */
1079 /* Please note that this preset might be
1080 * somewhat weaker than normal Pachi, and the
1081 * score maximization is approximate; point size
1082 * of win/loss still should not be used to judge
1083 * strength of Pachi or the opponent. */
1084 /* See README for some further notes. */
1085 if (!optval
|| atoi(optval
)) {
1086 /* Allow scoring a lost game. */
1087 u
->allow_losing_pass
= true;
1088 /* Make Pachi keep his calm when losing
1089 * and/or maintain winning marging. */
1090 /* Do not play games that are losing
1092 /* XXX: komi_ratchet_age=40000 is necessary
1093 * with losing_komi_ratchet, but 40000
1094 * is somewhat arbitrary value. */
1095 char dynkomi_args
[] = "losing_komi_ratchet:komi_ratchet_age=60000:no_komi_at_game_end=0:max_losing_komi=30";
1096 u
->dynkomi
= uct_dynkomi_init_adaptive(u
, dynkomi_args
, b
);
1097 /* XXX: Values arbitrary so far. */
1098 /* XXX: Also, is bytemp sensible when
1099 * combined with dynamic komi?! */
1100 u
->val_scale
= 0.01;
1101 u
->val_bytemp
= true;
1102 u
->val_bytemp_min
= 0.001;
1103 u
->val_byavg
= true;
1107 fprintf(stderr
, "uct: Invalid engine argument %s or missing value\n", optname
);
1114 u
->policy
= policy_ucb1amaf_init(u
, NULL
, b
);
1116 if (!!u
->random_policy_chance
^ !!u
->random_policy
) {
1117 fprintf(stderr
, "uct: Only one of random_policy and random_policy_chance is set\n");
1121 if (!u
->local_tree
) {
1122 /* No ltree aging. */
1123 u
->local_tree_aging
= 1.0f
;
1126 if (u
->fast_alloc
) {
1127 if (u
->pruning_threshold
< u
->max_tree_size
/ 10)
1128 u
->pruning_threshold
= u
->max_tree_size
/ 10;
1129 if (u
->pruning_threshold
> u
->max_tree_size
/ 2)
1130 u
->pruning_threshold
= u
->max_tree_size
/ 2;
1132 /* Limit pruning temp space to 20% of memory. Beyond this we discard
1133 * the nodes and recompute them at the next move if necessary. */
1134 u
->max_pruned_size
= u
->max_tree_size
/ 5;
1135 u
->max_tree_size
-= u
->max_pruned_size
;
1137 /* Reserve 5% memory in case the background free() are slower
1138 * than the concurrent allocations. */
1139 u
->max_tree_size
-= u
->max_tree_size
/ 20;
1143 u
->prior
= uct_prior_init(NULL
, b
, u
);
1146 u
->playout
= playout_moggy_init(NULL
, b
, u
->jdict
);
1147 if (!u
->playout
->debug_level
)
1148 u
->playout
->debug_level
= u
->debug_level
;
1150 if (u
->want_pat
&& !pat_setup
)
1151 patterns_init(&u
->pat
, NULL
, false, true);
1153 u
->ownermap
.map
= malloc2(board_size2(b
) * sizeof(u
->ownermap
.map
[0]));
1156 if (!u
->stats_hbits
) u
->stats_hbits
= DEFAULT_STATS_HBITS
;
1157 if (!u
->shared_nodes
) u
->shared_nodes
= DEFAULT_SHARED_NODES
;
1158 assert(u
->shared_levels
* board_bits2(b
) <= 8 * (int)sizeof(path_t
));
1162 u
->dynkomi
= uct_dynkomi_init_linear(u
, NULL
, b
);
1164 /* Some things remain uninitialized for now - the opening tbook
1165 * is not loaded and the tree not set up. */
1166 /* This will be initialized in setup_state() at the first move
1167 * received/requested. This is because right now we are not aware
1168 * about any komi or handicap setup and such. */
1174 engine_uct_init(char *arg
, struct board
*b
)
1176 struct uct
*u
= uct_state_init(arg
, b
);
1177 struct engine
*e
= calloc2(1, sizeof(struct engine
));
1179 e
->printhook
= uct_printhook_ownermap
;
1180 e
->notify_play
= uct_notify_play
;
1183 e
->result
= uct_result
;
1184 e
->genmove
= uct_genmove
;
1185 e
->genmoves
= uct_genmoves
;
1186 e
->evaluate
= uct_evaluate
;
1187 e
->dead_group_list
= uct_dead_group_list
;
1191 e
->notify
= uct_notify
;
1193 const char banner
[] = "If you believe you have won but I am still playing, "
1194 "please help me understand by capturing all dead stones. "
1195 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
1196 if (!u
->banner
) u
->banner
= "";
1197 e
->comment
= malloc2(sizeof(banner
) + strlen(u
->banner
) + 1);
1198 sprintf(e
->comment
, "%s %s", banner
, u
->banner
);