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
, struct board
*board
);
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 if (!u
->no_tbook
&& b
->moves
== 0) {
49 assert(color
== S_BLACK
);
55 reset_state(struct uct
*u
)
58 tree_done(u
->t
); u
->t
= NULL
;
62 setup_dynkomi(struct uct
*u
, struct board
*b
, enum stone to_play
)
64 if (u
->t
->use_extra_komi
&& !u
->pondering
&& u
->dynkomi
->permove
)
65 u
->t
->extra_komi
= u
->dynkomi
->permove(u
->dynkomi
, b
, u
->t
);
66 else if (!u
->t
->use_extra_komi
)
71 uct_prepare_move(struct uct
*u
, struct board
*b
, enum stone color
)
74 /* Verify that we have sane state. */
76 assert(u
->t
&& b
->moves
);
77 if (color
!= stone_other(u
->t
->root_color
)) {
78 fprintf(stderr
, "Fatal: Non-alternating play detected %d %d\n",
79 color
, u
->t
->root_color
);
82 uct_htable_reset(u
->t
);
85 /* We need fresh state. */
87 setup_state(u
, b
, color
);
90 u
->ownermap
.playouts
= 0;
91 memset(u
->ownermap
.map
, 0, board_size2(b
) * sizeof(u
->ownermap
.map
[0]));
92 u
->played_own
= u
->played_all
= 0;
96 dead_group_list(struct uct
*u
, struct board
*b
, struct move_queue
*mq
)
98 enum gj_state gs_array
[board_size2(b
)];
99 struct group_judgement gj
= { .thres
= GJ_THRES
, .gs
= gs_array
};
100 board_ownermap_judge_groups(b
, &u
->ownermap
, &gj
);
101 groups_of_status(b
, &gj
, GS_DEAD
, mq
);
105 uct_pass_is_safe(struct uct
*u
, struct board
*b
, enum stone color
, bool pass_all_alive
)
107 /* Make sure enough playouts are simulated to get a reasonable dead group list. */
108 while (u
->ownermap
.playouts
< GJ_MINGAMES
)
109 uct_playout(u
, b
, color
, u
->t
);
111 struct move_queue mq
= { .moves
= 0 };
112 dead_group_list(u
, b
, &mq
);
113 if (pass_all_alive
) {
114 for (unsigned int i
= 0; i
< mq
.moves
; i
++) {
115 if (board_at(b
, mq
.move
[i
]) == stone_other(color
)) {
116 return false; // We need to remove opponent dead groups first.
119 mq
.moves
= 0; // our dead stones are alive when pass_all_alive is true
121 return pass_is_safe(b
, color
, &mq
);
125 uct_printhook_ownermap(struct board
*board
, coord_t c
, char *s
, char *end
)
127 struct uct
*u
= board
->es
;
132 const char chr
[] = ":XO,"; // dame, black, white, unclear
133 const char chm
[] = ":xo,";
134 char ch
= chr
[board_ownermap_judge_point(&u
->ownermap
, c
, GJ_THRES
)];
135 if (ch
== ',') { // less precise estimate then?
136 ch
= chm
[board_ownermap_judge_point(&u
->ownermap
, c
, 0.67)];
138 s
+= snprintf(s
, end
- s
, "%c ", ch
);
143 uct_notify_play(struct engine
*e
, struct board
*b
, struct move
*m
, char *enginearg
)
145 struct uct
*u
= e
->data
;
147 /* No state, create one - this is probably game beginning
148 * and we need to load the opening tbook right now. */
149 uct_prepare_move(u
, b
, m
->color
);
153 /* Stop pondering, required by tree_promote_at() */
154 uct_pondering_stop(u
);
155 if (UDEBUGL(2) && u
->slave
)
156 tree_dump(u
->t
, u
->dumpthres
);
158 if (is_resign(m
->coord
)) {
164 /* Promote node of the appropriate move to the tree root. */
166 if (!tree_promote_at(u
->t
, b
, m
->coord
)) {
168 fprintf(stderr
, "Warning: Cannot promote move node! Several play commands in row?\n");
173 /* If we are a slave in a distributed engine, start pondering once
174 * we know which move we actually played. See uct_genmove() about
175 * the check for pass. */
176 if (u
->pondering_opt
&& u
->slave
&& m
->color
== u
->my_color
&& !is_pass(m
->coord
))
177 uct_pondering_start(u
, b
, u
->t
, stone_other(m
->color
));
183 uct_undo(struct engine
*e
, struct board
*b
)
185 struct uct
*u
= e
->data
;
187 if (!u
->t
) return NULL
;
188 uct_pondering_stop(u
);
194 uct_result(struct engine
*e
, struct board
*b
)
196 struct uct
*u
= e
->data
;
197 static char reply
[1024];
201 enum stone color
= u
->t
->root_color
;
202 struct tree_node
*n
= u
->t
->root
;
203 snprintf(reply
, 1024, "%s %s %d %.2f %.1f",
204 stone2str(color
), coord2sstr(node_coord(n
), b
),
205 n
->u
.playouts
, tree_node_get_value(u
->t
, -1, n
->u
.value
),
206 u
->t
->use_extra_komi
? u
->t
->extra_komi
: 0);
211 uct_chat(struct engine
*e
, struct board
*b
, char *cmd
)
213 struct uct
*u
= e
->data
;
214 static char reply
[1024];
216 cmd
+= strspn(cmd
, " \n\t");
217 if (!strncasecmp(cmd
, "winrate", 7)) {
219 return "no game context (yet?)";
220 enum stone color
= u
->t
->root_color
;
221 struct tree_node
*n
= u
->t
->root
;
222 snprintf(reply
, 1024, "In %d playouts at %d threads, %s %s can win with %.2f%% probability",
223 n
->u
.playouts
, u
->threads
, stone2str(color
), coord2sstr(node_coord(n
), b
),
224 tree_node_get_value(u
->t
, -1, n
->u
.value
) * 100);
225 if (u
->t
->use_extra_komi
&& abs(u
->t
->extra_komi
) >= 0.5) {
226 sprintf(reply
+ strlen(reply
), ", while self-imposing extra komi %.1f",
236 uct_dead_group_list(struct engine
*e
, struct board
*b
, struct move_queue
*mq
)
238 struct uct
*u
= e
->data
;
240 /* This means the game is probably over, no use pondering on. */
241 uct_pondering_stop(u
);
243 if (u
->pass_all_alive
)
244 return; // no dead groups
246 bool mock_state
= false;
249 /* No state, but we cannot just back out - we might
250 * have passed earlier, only assuming some stones are
251 * dead, and then re-connected, only to lose counting
252 * when all stones are assumed alive. */
253 uct_prepare_move(u
, b
, S_BLACK
); assert(u
->t
);
256 /* Make sure the ownermap is well-seeded. */
257 while (u
->ownermap
.playouts
< GJ_MINGAMES
)
258 uct_playout(u
, b
, S_BLACK
, u
->t
);
259 /* Show the ownermap: */
261 board_print_custom(b
, stderr
, uct_printhook_ownermap
);
263 dead_group_list(u
, b
, mq
);
266 /* Clean up the mock state in case we will receive
267 * a genmove; we could get a non-alternating-move
268 * error from uct_prepare_move() in that case otherwise. */
274 playout_policy_done(struct playout_policy
*p
)
276 if (p
->done
) p
->done(p
);
277 if (p
->data
) free(p
->data
);
282 uct_done(struct engine
*e
)
284 /* This is called on engine reset, especially when clear_board
285 * is received and new game should begin. */
286 struct uct
*u
= e
->data
;
287 uct_pondering_stop(u
);
288 if (u
->t
) reset_state(u
);
289 free(u
->ownermap
.map
);
292 free(u
->random_policy
);
293 playout_policy_done(u
->playout
);
294 uct_prior_done(u
->prior
);
295 joseki_done(u
->jdict
);
296 pluginset_done(u
->plugins
);
301 /* Run time-limited MCTS search on foreground. */
303 uct_search(struct uct
*u
, struct board
*b
, struct time_info
*ti
, enum stone color
, struct tree
*t
)
305 struct uct_search_state s
;
306 uct_search_start(u
, b
, color
, t
, ti
, &s
);
307 if (UDEBUGL(2) && s
.base_playouts
> 0)
308 fprintf(stderr
, "<pre-simulated %d games>\n", s
.base_playouts
);
310 /* The search tree is ctx->t. This is currently == . It is important
311 * to reference ctx->t directly since the
312 * thread manager will swap the tree pointer asynchronously. */
314 /* Now, just periodically poll the search tree. */
315 /* Note that in case of TD_GAMES, threads will not wait for
316 * the uct_search_check_stop() signalization. */
318 time_sleep(TREE_BUSYWAIT_INTERVAL
);
319 /* TREE_BUSYWAIT_INTERVAL should never be less than desired time, or the
320 * time control is broken. But if it happens to be less, we still search
321 * at least 100ms otherwise the move is completely random. */
323 int i
= uct_search_games(&s
);
324 /* Print notifications etc. */
325 uct_search_progress(u
, b
, color
, t
, ti
, &s
, i
);
326 /* Check if we should stop the search. */
327 if (uct_search_check_stop(u
, b
, color
, t
, ti
, &s
, i
))
331 struct uct_thread_ctx
*ctx
= uct_search_stop();
332 if (UDEBUGL(2)) tree_dump(t
, u
->dumpthres
);
334 fprintf(stderr
, "(avg score %f/%d; dynkomi's %f/%d value %f/%d)\n",
335 t
->avg_score
.value
, t
->avg_score
.playouts
,
336 u
->dynkomi
->score
.value
, u
->dynkomi
->score
.playouts
,
337 u
->dynkomi
->value
.value
, u
->dynkomi
->value
.playouts
);
338 uct_progress_status(u
, t
, color
, ctx
->games
, true);
340 u
->played_own
+= ctx
->games
;
344 /* Start pondering background with @color to play. */
346 uct_pondering_start(struct uct
*u
, struct board
*b0
, struct tree
*t
, enum stone color
)
349 fprintf(stderr
, "Starting to ponder with color %s\n", stone2str(stone_other(color
)));
352 /* We need a local board copy to ponder upon. */
353 struct board
*b
= malloc2(sizeof(*b
)); board_copy(b
, b0
);
355 /* *b0 did not have the genmove'd move played yet. */
356 struct move m
= { node_coord(t
->root
), t
->root_color
};
357 int res
= board_play(b
, &m
);
359 setup_dynkomi(u
, b
, stone_other(m
.color
));
361 /* Start MCTS manager thread "headless". */
362 static struct uct_search_state s
;
363 uct_search_start(u
, b
, color
, t
, NULL
, &s
);
366 /* uct_search_stop() frontend for the pondering (non-genmove) mode, and
367 * to stop the background search for a slave in the distributed engine. */
369 uct_pondering_stop(struct uct
*u
)
371 if (!thread_manager_running
)
374 /* Stop the thread manager. */
375 struct uct_thread_ctx
*ctx
= uct_search_stop();
377 if (u
->pondering
) fprintf(stderr
, "(pondering) ");
378 uct_progress_status(u
, ctx
->t
, ctx
->color
, ctx
->games
, true);
382 u
->pondering
= false;
388 uct_genmove_setup(struct uct
*u
, struct board
*b
, enum stone color
)
390 if (b
->superko_violation
) {
391 fprintf(stderr
, "!!! WARNING: SUPERKO VIOLATION OCCURED BEFORE THIS MOVE\n");
392 fprintf(stderr
, "Maybe you play with situational instead of positional superko?\n");
393 fprintf(stderr
, "I'm going to ignore the violation, but note that I may miss\n");
394 fprintf(stderr
, "some moves valid under this ruleset because of this.\n");
395 b
->superko_violation
= false;
398 uct_prepare_move(u
, b
, color
);
403 /* How to decide whether to use dynkomi in this game? Since we use
404 * pondering, it's not simple "who-to-play" matter. Decide based on
405 * the last genmove issued. */
406 u
->t
->use_extra_komi
= !!(u
->dynkomi_mask
& color
);
407 setup_dynkomi(u
, b
, color
);
409 if (b
->rules
== RULES_JAPANESE
)
410 u
->territory_scoring
= true;
412 /* Make pessimistic assumption about komi for Japanese rules to
413 * avoid losing by 0.5 when winning by 0.5 with Chinese rules.
414 * The rules usually give the same winner if the integer part of komi
415 * is odd so we adjust the komi only if it is even (for a board of
416 * odd size). We are not trying to get an exact evaluation for rare
417 * cases of seki. For details see http://home.snafu.de/jasiek/parity.html */
418 if (u
->territory_scoring
&& (((int)floor(b
->komi
) + board_size(b
)) & 1)) {
419 b
->komi
+= (color
== S_BLACK
? 1.0 : -1.0);
421 fprintf(stderr
, "Setting komi to %.1f assuming Japanese rules\n",
427 uct_genmove(struct engine
*e
, struct board
*b
, struct time_info
*ti
, enum stone color
, bool pass_all_alive
)
429 double start_time
= time_now();
430 struct uct
*u
= e
->data
;
431 u
->pass_all_alive
|= pass_all_alive
;
432 uct_pondering_stop(u
);
433 uct_genmove_setup(u
, b
, color
);
435 /* Start the Monte Carlo Tree Search! */
436 int base_playouts
= u
->t
->root
->u
.playouts
;
437 int played_games
= uct_search(u
, b
, ti
, color
, u
->t
);
440 struct tree_node
*best
;
441 best
= uct_search_result(u
, b
, color
, u
->pass_all_alive
, played_games
, base_playouts
, &best_coord
);
444 double time
= time_now() - start_time
+ 0.000001; /* avoid divide by zero */
445 fprintf(stderr
, "genmove in %0.2fs (%d games/s, %d games/s/thread)\n",
446 time
, (int)(played_games
/time
), (int)(played_games
/time
/u
->threads
));
450 /* Pass or resign. */
452 return coord_copy(best_coord
);
454 tree_promote_node(u
->t
, &best
);
456 /* After a pass, pondering is harmful for two reasons:
457 * (i) We might keep pondering even when the game is over.
458 * Of course this is the case for opponent resign as well.
459 * (ii) More importantly, the ownermap will get skewed since
460 * the UCT will start cutting off any playouts. */
461 if (u
->pondering_opt
&& !is_pass(node_coord(best
))) {
462 uct_pondering_start(u
, b
, u
->t
, stone_other(color
));
464 return coord_copy(best_coord
);
469 uct_gentbook(struct engine
*e
, struct board
*b
, struct time_info
*ti
, enum stone color
)
471 struct uct
*u
= e
->data
;
472 if (!u
->t
) uct_prepare_move(u
, b
, color
);
475 if (ti
->dim
== TD_GAMES
) {
476 /* Don't count in games that already went into the tbook. */
477 ti
->len
.games
+= u
->t
->root
->u
.playouts
;
479 uct_search(u
, b
, ti
, color
, u
->t
);
481 assert(ti
->dim
== TD_GAMES
);
482 tree_save(u
->t
, b
, ti
->len
.games
/ 100);
488 uct_dumptbook(struct engine
*e
, struct board
*b
, enum stone color
)
490 struct uct
*u
= e
->data
;
491 struct tree
*t
= tree_init(b
, color
, u
->fast_alloc
? u
->max_tree_size
: 0,
492 u
->max_pruned_size
, u
->pruning_threshold
, u
->local_tree_aging
, 0);
500 uct_evaluate_one(struct engine
*e
, struct board
*b
, struct time_info
*ti
, coord_t c
, enum stone color
)
502 struct uct
*u
= e
->data
;
506 struct move m
= { c
, color
};
507 int res
= board_play(&b2
, &m
);
510 color
= stone_other(color
);
512 if (u
->t
) reset_state(u
);
513 uct_prepare_move(u
, &b2
, color
);
517 uct_search(u
, &b2
, ti
, color
, u
->t
);
518 struct tree_node
*best
= u
->policy
->choose(u
->policy
, u
->t
->root
, &b2
, color
, resign
);
520 bestval
= NAN
; // the opponent has no reply!
522 bestval
= tree_node_get_value(u
->t
, 1, best
->u
.value
);
525 reset_state(u
); // clean our junk
527 return isnan(bestval
) ? NAN
: 1.0f
- bestval
;
531 uct_evaluate(struct engine
*e
, struct board
*b
, struct time_info
*ti
, floating_t
*vals
, enum stone color
)
533 for (int i
= 0; i
< b
->flen
; i
++) {
534 if (is_pass(b
->f
[i
]))
537 vals
[i
] = uct_evaluate_one(e
, b
, ti
, b
->f
[i
], color
);
543 uct_state_init(char *arg
, struct board
*b
)
545 struct uct
*u
= calloc2(1, sizeof(struct uct
));
546 bool pat_setup
= false;
548 u
->debug_level
= debug_level
;
549 u
->reportfreq
= 10000;
550 u
->gamelen
= MC_GAMELEN
;
551 u
->resign_threshold
= 0.2;
552 u
->sure_win_threshold
= 0.9;
554 u
->significant_threshold
= 50;
557 u
->playout_amaf
= true;
558 u
->amaf_prior
= false;
559 u
->max_tree_size
= 1408ULL * 1048576;
560 u
->fast_alloc
= true;
561 u
->pruning_threshold
= 0;
564 u
->thread_model
= TM_TREEVL
;
567 u
->fuseki_end
= 20; // max time at 361*20% = 72 moves (our 36th move, still 99 to play)
568 u
->yose_start
= 40; // (100-40-25)*361/100/2 = 63 moves still to play by us then
569 u
->bestr_ratio
= 0.02;
570 // 2.5 is clearly too much, but seems to compensate well for overly stern time allocations.
571 // TODO: Further tuning and experiments with better time allocation schemes.
572 u
->best2_ratio
= 2.5;
573 u
->max_maintime_ratio
= 3.0;
575 u
->val_scale
= 0; u
->val_points
= 40;
576 u
->dynkomi_interval
= 1000;
577 u
->dynkomi_mask
= S_BLACK
| S_WHITE
;
580 u
->local_tree_aging
= 80;
581 u
->local_tree_depth_decay
= 1.5;
582 u
->local_tree_eval
= LTE_ROOT
;
583 u
->local_tree_neival
= true;
587 u
->stats_delay
= 0.01; // 10 ms
589 u
->plugins
= pluginset_init(b
);
591 u
->jdict
= joseki_load(b
->size
);
594 char *optspec
, *next
= arg
;
597 next
+= strcspn(next
, ",");
598 if (*next
) { *next
++ = 0; } else { *next
= 0; }
600 char *optname
= optspec
;
601 char *optval
= strchr(optspec
, '=');
602 if (optval
) *optval
++ = 0;
606 if (!strcasecmp(optname
, "debug")) {
608 u
->debug_level
= atoi(optval
);
611 } else if (!strcasecmp(optname
, "reporting") && optval
) {
612 /* The format of output for detailed progress
613 * information (such as current best move and
614 * its value, etc.). */
615 if (!strcasecmp(optval
, "text")) {
616 /* Plaintext traditional output. */
617 u
->reporting
= UR_TEXT
;
618 } else if (!strcasecmp(optval
, "json")) {
619 /* JSON output. Implies debug=0. */
620 u
->reporting
= UR_JSON
;
622 } else if (!strcasecmp(optval
, "jsonbig")) {
623 /* JSON output, but much more detailed.
624 * Implies debug=0. */
625 u
->reporting
= UR_JSON_BIG
;
628 fprintf(stderr
, "UCT: Invalid reporting format %s\n", optval
);
631 } else if (!strcasecmp(optname
, "reportfreq") && optval
) {
632 /* The progress information line will be shown
633 * every <reportfreq> simulations. */
634 u
->reportfreq
= atoi(optval
);
635 } else if (!strcasecmp(optname
, "dumpthres") && optval
) {
636 /* When dumping the UCT tree on output, include
637 * nodes with at least this many playouts.
638 * (This value is re-scaled "intelligently"
639 * in case of very large trees.) */
640 u
->dumpthres
= atoi(optval
);
641 } else if (!strcasecmp(optname
, "resign_threshold") && optval
) {
642 /* Resign when this ratio of games is lost
643 * after GJ_MINGAMES sample is taken. */
644 u
->resign_threshold
= atof(optval
);
645 } else if (!strcasecmp(optname
, "sure_win_threshold") && optval
) {
646 /* Stop reading when this ratio of games is won
647 * after PLAYOUT_EARLY_BREAK_MIN sample is
648 * taken. (Prevents stupid time losses,
649 * friendly to human opponents.) */
650 u
->sure_win_threshold
= atof(optval
);
651 } else if (!strcasecmp(optname
, "force_seed") && optval
) {
652 /* Set RNG seed at the tree setup. */
653 u
->force_seed
= atoi(optval
);
654 } else if (!strcasecmp(optname
, "no_tbook")) {
655 /* Disable UCT opening tbook. */
657 } else if (!strcasecmp(optname
, "pass_all_alive")) {
658 /* Whether to consider passing only after all
659 * dead groups were removed from the board;
660 * this is like all genmoves are in fact
661 * kgs-genmove_cleanup. */
662 u
->pass_all_alive
= !optval
|| atoi(optval
);
663 } else if (!strcasecmp(optname
, "territory_scoring")) {
664 /* Use territory scoring (default is area scoring).
665 * An explicit kgs-rules command overrides this. */
666 u
->territory_scoring
= !optval
|| atoi(optval
);
667 } else if (!strcasecmp(optname
, "stones_only")) {
668 /* Do not count eyes. Nice to teach go to kids.
669 * http://strasbourg.jeudego.org/regle_strasbourgeoise.htm */
670 b
->rules
= RULES_STONES_ONLY
;
671 u
->pass_all_alive
= true;
672 } else if (!strcasecmp(optname
, "banner") && optval
) {
673 /* Additional banner string. This must come as the
674 * last engine parameter. */
675 if (*next
) *--next
= ',';
676 u
->banner
= strdup(optval
);
678 } else if (!strcasecmp(optname
, "plugin") && optval
) {
679 /* Load an external plugin; filename goes before the colon,
680 * extra arguments after the colon. */
681 char *pluginarg
= strchr(optval
, ':');
684 plugin_load(u
->plugins
, optval
, pluginarg
);
686 /** UCT behavior and policies */
688 } else if ((!strcasecmp(optname
, "policy")
689 /* Node selection policy. ucb1amaf is the
690 * default policy implementing RAVE, while
691 * ucb1 is the simple exploration/exploitation
692 * policy. Policies can take further extra
694 || !strcasecmp(optname
, "random_policy")) && optval
) {
695 /* A policy to be used randomly with small
696 * chance instead of the default policy. */
697 char *policyarg
= strchr(optval
, ':');
698 struct uct_policy
**p
= !strcasecmp(optname
, "policy") ? &u
->policy
: &u
->random_policy
;
701 if (!strcasecmp(optval
, "ucb1")) {
702 *p
= policy_ucb1_init(u
, policyarg
);
703 } else if (!strcasecmp(optval
, "ucb1amaf")) {
704 *p
= policy_ucb1amaf_init(u
, policyarg
, b
);
706 fprintf(stderr
, "UCT: Invalid tree policy %s\n", optval
);
709 } else if (!strcasecmp(optname
, "playout") && optval
) {
710 /* Random simulation (playout) policy.
711 * moggy is the default policy with large
712 * amount of domain-specific knowledge and
713 * heuristics. light is a simple uniformly
714 * random move selection policy. */
715 char *playoutarg
= strchr(optval
, ':');
718 if (!strcasecmp(optval
, "moggy")) {
719 u
->playout
= playout_moggy_init(playoutarg
, b
, u
->jdict
);
720 } else if (!strcasecmp(optval
, "light")) {
721 u
->playout
= playout_light_init(playoutarg
, b
);
723 fprintf(stderr
, "UCT: Invalid playout policy %s\n", optval
);
726 } else if (!strcasecmp(optname
, "prior") && optval
) {
727 /* Node priors policy. When expanding a node,
728 * it will seed node values heuristically
729 * (most importantly, based on playout policy
730 * opinion, but also with regard to other
731 * things). See uct/prior.c for details.
732 * Use prior=eqex=0 to disable priors. */
733 u
->prior
= uct_prior_init(optval
, b
, u
);
734 } else if (!strcasecmp(optname
, "mercy") && optval
) {
735 /* Minimal difference of black/white captures
736 * to stop playout - "Mercy Rule". Speeds up
737 * hopeless playouts at the expense of some
739 u
->mercymin
= atoi(optval
);
740 } else if (!strcasecmp(optname
, "gamelen") && optval
) {
741 /* Maximum length of single simulation
743 u
->gamelen
= atoi(optval
);
744 } else if (!strcasecmp(optname
, "expand_p") && optval
) {
745 /* Expand UCT nodes after it has been
746 * visited this many times. */
747 u
->expand_p
= atoi(optval
);
748 } else if (!strcasecmp(optname
, "random_policy_chance") && optval
) {
749 /* If specified (N), with probability 1/N, random_policy policy
750 * descend is used instead of main policy descend; useful
751 * if specified policy (e.g. UCB1AMAF) can make unduly biased
752 * choices sometimes, you can fall back to e.g.
753 * random_policy=UCB1. */
754 u
->random_policy_chance
= atoi(optval
);
756 /** General AMAF behavior */
757 /* (Only relevant if the policy supports AMAF.
758 * More variables can be tuned as policy
761 } else if (!strcasecmp(optname
, "playout_amaf")) {
762 /* Whether to include random playout moves in
763 * AMAF as well. (Otherwise, only tree moves
764 * are included in AMAF. Of course makes sense
765 * only in connection with an AMAF policy.) */
766 /* with-without: 55.5% (+-4.1) */
767 if (optval
&& *optval
== '0')
768 u
->playout_amaf
= false;
770 u
->playout_amaf
= true;
771 } else if (!strcasecmp(optname
, "playout_amaf_cutoff") && optval
) {
772 /* Keep only first N% of playout stage AMAF
774 u
->playout_amaf_cutoff
= atoi(optval
);
775 } else if (!strcasecmp(optname
, "amaf_prior") && optval
) {
776 /* In node policy, consider prior values
777 * part of the real result term or part
778 * of the AMAF term? */
779 u
->amaf_prior
= atoi(optval
);
781 /** Performance and memory management */
783 } else if (!strcasecmp(optname
, "threads") && optval
) {
784 /* By default, Pachi will run with only single
785 * tree search thread! */
786 u
->threads
= atoi(optval
);
787 } else if (!strcasecmp(optname
, "thread_model") && optval
) {
788 if (!strcasecmp(optval
, "tree")) {
789 /* Tree parallelization - all threads
790 * grind on the same tree. */
791 u
->thread_model
= TM_TREE
;
793 } else if (!strcasecmp(optval
, "treevl")) {
794 /* Tree parallelization, but also
795 * with virtual losses - this discou-
796 * rages most threads choosing the
797 * same tree branches to read. */
798 u
->thread_model
= TM_TREEVL
;
800 fprintf(stderr
, "UCT: Invalid thread model %s\n", optval
);
803 } else if (!strcasecmp(optname
, "virtual_loss")) {
804 /* Number of virtual losses added before evaluating a node. */
805 u
->virtual_loss
= !optval
|| atoi(optval
);
806 } else if (!strcasecmp(optname
, "pondering")) {
807 /* Keep searching even during opponent's turn. */
808 u
->pondering_opt
= !optval
|| atoi(optval
);
809 } else if (!strcasecmp(optname
, "max_tree_size") && optval
) {
810 /* Maximum amount of memory [MiB] consumed by the move tree.
811 * For fast_alloc it includes the temp tree used for pruning.
812 * Default is 3072 (3 GiB). */
813 u
->max_tree_size
= atol(optval
) * 1048576;
814 } else if (!strcasecmp(optname
, "fast_alloc")) {
815 u
->fast_alloc
= !optval
|| atoi(optval
);
816 } else if (!strcasecmp(optname
, "pruning_threshold") && optval
) {
817 /* Force pruning at beginning of a move if the tree consumes
818 * more than this [MiB]. Default is 10% of max_tree_size.
819 * Increase to reduce pruning time overhead if memory is plentiful.
820 * This option is meaningful only for fast_alloc. */
821 u
->pruning_threshold
= atol(optval
) * 1048576;
825 } else if (!strcasecmp(optname
, "best2_ratio") && optval
) {
826 /* If set, prolong simulating while
827 * first_best/second_best playouts ratio
828 * is less than best2_ratio. */
829 u
->best2_ratio
= atof(optval
);
830 } else if (!strcasecmp(optname
, "bestr_ratio") && optval
) {
831 /* If set, prolong simulating while
832 * best,best_best_child values delta
833 * is more than bestr_ratio. */
834 u
->bestr_ratio
= atof(optval
);
835 } else if (!strcasecmp(optname
, "max_maintime_ratio") && optval
) {
836 /* If set and while not in byoyomi, prolong simulating no more than
837 * max_maintime_ratio times the normal desired thinking time. */
838 u
->max_maintime_ratio
= atof(optval
);
839 } else if (!strcasecmp(optname
, "fuseki_end") && optval
) {
840 /* At the very beginning it's not worth thinking
841 * too long because the playout evaluations are
842 * very noisy. So gradually increase the thinking
843 * time up to maximum when fuseki_end percent
844 * of the board has been played.
845 * This only applies if we are not in byoyomi. */
846 u
->fuseki_end
= atoi(optval
);
847 } else if (!strcasecmp(optname
, "yose_start") && optval
) {
848 /* When yose_start percent of the board has been
849 * played, or if we are in byoyomi, stop spending
850 * more time and spread the remaining time
852 * Between fuseki_end and yose_start, we spend
853 * a constant proportion of the remaining time
854 * on each move. (yose_start should actually
855 * be much earlier than when real yose start,
856 * but "yose" is a good short name to convey
858 u
->yose_start
= atoi(optval
);
862 } else if (!strcasecmp(optname
, "dynkomi") && optval
) {
863 /* Dynamic komi approach; there are multiple
864 * ways to adjust komi dynamically throughout
865 * play. We currently support two: */
866 char *dynkomiarg
= strchr(optval
, ':');
869 if (!strcasecmp(optval
, "none")) {
870 u
->dynkomi
= uct_dynkomi_init_none(u
, dynkomiarg
, b
);
871 } else if (!strcasecmp(optval
, "linear")) {
872 /* You should set dynkomi_mask=1 or a very low
873 * handicap_value for white. */
874 u
->dynkomi
= uct_dynkomi_init_linear(u
, dynkomiarg
, b
);
875 } else if (!strcasecmp(optval
, "adaptive")) {
876 /* There are many more knobs to
877 * crank - see uct/dynkomi.c. */
878 u
->dynkomi
= uct_dynkomi_init_adaptive(u
, dynkomiarg
, b
);
880 fprintf(stderr
, "UCT: Invalid dynkomi mode %s\n", optval
);
883 } else if (!strcasecmp(optname
, "dynkomi_mask") && optval
) {
884 /* Bitmask of colors the player must be
885 * for dynkomi be applied; the default dynkomi_mask=3 allows
886 * dynkomi even in games where Pachi is white. */
887 u
->dynkomi_mask
= atoi(optval
);
888 } else if (!strcasecmp(optname
, "dynkomi_interval") && optval
) {
889 /* If non-zero, re-adjust dynamic komi
890 * throughout a single genmove reading,
891 * roughly every N simulations. */
892 /* XXX: Does not work with tree
893 * parallelization. */
894 u
->dynkomi_interval
= atoi(optval
);
896 /** Node value result scaling */
898 } else if (!strcasecmp(optname
, "val_scale") && optval
) {
899 /* How much of the game result value should be
900 * influenced by win size. Zero means it isn't. */
901 u
->val_scale
= atof(optval
);
902 } else if (!strcasecmp(optname
, "val_points") && optval
) {
903 /* Maximum size of win to be scaled into game
904 * result value. Zero means boardsize^2. */
905 u
->val_points
= atoi(optval
) * 2; // result values are doubled
906 } else if (!strcasecmp(optname
, "val_extra")) {
907 /* If false, the score coefficient will be simply
908 * added to the value, instead of scaling the result
909 * coefficient because of it. */
910 u
->val_extra
= !optval
|| atoi(optval
);
913 /* (Purely experimental. Does not work - yet!) */
915 } else if (!strcasecmp(optname
, "local_tree")) {
916 /* Whether to bias exploration by local tree values. */
917 u
->local_tree
= !optval
|| atoi(optval
);
918 } else if (!strcasecmp(optname
, "tenuki_d") && optval
) {
919 /* Tenuki distance at which to break the local tree. */
920 u
->tenuki_d
= atoi(optval
);
921 if (u
->tenuki_d
> TREE_NODE_D_MAX
+ 1) {
922 fprintf(stderr
, "uct: tenuki_d must not be larger than TREE_NODE_D_MAX+1 %d\n", TREE_NODE_D_MAX
+ 1);
925 } else if (!strcasecmp(optname
, "local_tree_aging") && optval
) {
926 /* How much to reduce local tree values between moves. */
927 u
->local_tree_aging
= atof(optval
);
928 } else if (!strcasecmp(optname
, "local_tree_depth_decay") && optval
) {
929 /* With value x>0, during the descent the node
930 * contributes 1/x^depth playouts in
931 * the local tree. I.e., with x>1, nodes more
932 * distant from local situation contribute more
933 * than nodes near the root. */
934 u
->local_tree_depth_decay
= atof(optval
);
935 } else if (!strcasecmp(optname
, "local_tree_allseq")) {
936 /* If disabled, only complete sequences are stored
937 * in the local tree. If this is on, also
938 * subsequences starting at each move are stored. */
939 u
->local_tree_allseq
= !optval
|| atoi(optval
);
940 } else if (!strcasecmp(optname
, "local_tree_neival")) {
941 /* If disabled, local node value is not
942 * computed just based on terminal status
943 * of the coordinate, but also its neighbors. */
944 u
->local_tree_neival
= !optval
|| atoi(optval
);
945 } else if (!strcasecmp(optname
, "local_tree_eval")) {
946 /* How is the value inserted in the local tree
948 if (!strcasecmp(optval
, "root"))
949 /* All moves within a tree branch are
950 * considered wrt. their merit
951 * reaching tachtical goal of making
952 * the first move in the branch
954 u
->local_tree_eval
= LTE_ROOT
;
955 else if (!strcasecmp(optval
, "each"))
956 /* Each move is considered wrt.
957 * its own survival. */
958 u
->local_tree_eval
= LTE_EACH
;
959 else if (!strcasecmp(optval
, "total"))
960 /* The tactical goal is the survival
961 * of all the moves of my color and
962 * non-survival of all the opponent
963 * moves. Local values (and their
964 * inverses) are averaged. */
965 u
->local_tree_eval
= LTE_TOTAL
;
967 fprintf(stderr
, "uct: unknown local_tree_eval %s\n", optval
);
970 } else if (!strcasecmp(optname
, "local_tree_rootchoose")) {
971 /* If disabled, only moves within the local
972 * tree branch are considered; the values
973 * of the branch roots (i.e. root children)
974 * are ignored. This may make sense together
975 * with eval!=each, we consider only moves
976 * that influence the goal, not the "rating"
977 * of the goal itself. (The real solution
978 * will be probably using criticality to pick
979 * local tree branches.) */
980 u
->local_tree_rootchoose
= !optval
|| atoi(optval
);
982 /** Other heuristics */
983 } else if (!strcasecmp(optname
, "patterns")) {
984 /* Load pattern database. Various modules
985 * (priors, policies etc.) may make use
986 * of this database. They will request
987 * it automatically in that case, but you
988 * can use this option to tweak the pattern
990 patterns_init(&u
->pat
, optval
, false, true);
991 u
->want_pat
= pat_setup
= true;
992 } else if (!strcasecmp(optname
, "significant_threshold") && optval
) {
993 /* Some heuristics (XXX: none in mainline) rely
994 * on the knowledge of the last "significant"
995 * node in the descent. Such a node is
996 * considered reasonably trustworthy to carry
997 * some meaningful information in the values
998 * of the node and its children. */
999 u
->significant_threshold
= atoi(optval
);
1001 /** Distributed engine slaves setup */
1003 } else if (!strcasecmp(optname
, "slave")) {
1004 /* Act as slave for the distributed engine. */
1005 u
->slave
= !optval
|| atoi(optval
);
1006 } else if (!strcasecmp(optname
, "slave_index") && optval
) {
1007 /* Optional index if per-slave behavior is desired.
1008 * Must be given as index/max */
1009 u
->slave_index
= atoi(optval
);
1010 char *p
= strchr(optval
, '/');
1011 if (p
) u
->max_slaves
= atoi(++p
);
1012 } else if (!strcasecmp(optname
, "shared_nodes") && optval
) {
1013 /* Share at most shared_nodes between master and slave at each genmoves.
1014 * Must use the same value in master and slaves. */
1015 u
->shared_nodes
= atoi(optval
);
1016 } else if (!strcasecmp(optname
, "shared_levels") && optval
) {
1017 /* Share only nodes of level <= shared_levels. */
1018 u
->shared_levels
= atoi(optval
);
1019 } else if (!strcasecmp(optname
, "stats_hbits") && optval
) {
1020 /* Set hash table size to 2^stats_hbits for the shared stats. */
1021 u
->stats_hbits
= atoi(optval
);
1022 } else if (!strcasecmp(optname
, "stats_delay") && optval
) {
1023 /* How long to wait in slave for initial stats to build up before
1024 * replying to the genmoves command (in ms) */
1025 u
->stats_delay
= 0.001 * atof(optval
);
1028 fprintf(stderr
, "uct: Invalid engine argument %s or missing value\n", optname
);
1035 u
->policy
= policy_ucb1amaf_init(u
, NULL
, b
);
1037 if (!!u
->random_policy_chance
^ !!u
->random_policy
) {
1038 fprintf(stderr
, "uct: Only one of random_policy and random_policy_chance is set\n");
1042 if (!u
->local_tree
) {
1043 /* No ltree aging. */
1044 u
->local_tree_aging
= 1.0f
;
1047 if (u
->fast_alloc
) {
1048 if (u
->pruning_threshold
< u
->max_tree_size
/ 10)
1049 u
->pruning_threshold
= u
->max_tree_size
/ 10;
1050 if (u
->pruning_threshold
> u
->max_tree_size
/ 2)
1051 u
->pruning_threshold
= u
->max_tree_size
/ 2;
1053 /* Limit pruning temp space to 20% of memory. Beyond this we discard
1054 * the nodes and recompute them at the next move if necessary. */
1055 u
->max_pruned_size
= u
->max_tree_size
/ 5;
1056 u
->max_tree_size
-= u
->max_pruned_size
;
1058 /* Reserve 5% memory in case the background free() are slower
1059 * than the concurrent allocations. */
1060 u
->max_tree_size
-= u
->max_tree_size
/ 20;
1064 u
->prior
= uct_prior_init(NULL
, b
, u
);
1067 u
->playout
= playout_moggy_init(NULL
, b
, u
->jdict
);
1068 if (!u
->playout
->debug_level
)
1069 u
->playout
->debug_level
= u
->debug_level
;
1071 if (u
->want_pat
&& !pat_setup
)
1072 patterns_init(&u
->pat
, NULL
, false, true);
1074 u
->ownermap
.map
= malloc2(board_size2(b
) * sizeof(u
->ownermap
.map
[0]));
1077 if (!u
->stats_hbits
) u
->stats_hbits
= DEFAULT_STATS_HBITS
;
1078 if (!u
->shared_nodes
) u
->shared_nodes
= DEFAULT_SHARED_NODES
;
1079 assert(u
->shared_levels
* board_bits2(b
) <= 8 * (int)sizeof(path_t
));
1083 u
->dynkomi
= uct_dynkomi_init_linear(u
, NULL
, b
);
1085 /* Some things remain uninitialized for now - the opening tbook
1086 * is not loaded and the tree not set up. */
1087 /* This will be initialized in setup_state() at the first move
1088 * received/requested. This is because right now we are not aware
1089 * about any komi or handicap setup and such. */
1095 engine_uct_init(char *arg
, struct board
*b
)
1097 struct uct
*u
= uct_state_init(arg
, b
);
1098 struct engine
*e
= calloc2(1, sizeof(struct engine
));
1100 e
->printhook
= uct_printhook_ownermap
;
1101 e
->notify_play
= uct_notify_play
;
1104 e
->result
= uct_result
;
1105 e
->genmove
= uct_genmove
;
1106 e
->genmoves
= uct_genmoves
;
1107 e
->evaluate
= uct_evaluate
;
1108 e
->dead_group_list
= uct_dead_group_list
;
1112 e
->notify
= uct_notify
;
1114 const char banner
[] = "If you believe you have won but I am still playing, "
1115 "please help me understand by capturing all dead stones. "
1116 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
1117 if (!u
->banner
) u
->banner
= "";
1118 e
->comment
= malloc2(sizeof(banner
) + strlen(u
->banner
) + 1);
1119 sprintf(e
->comment
, "%s %s", banner
, u
->banner
);