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 (u
->t
->untrustworthy_tree
| !tree_promote_at(u
->t
, b
, m
->coord
)) {
186 if (u
->t
->untrustworthy_tree
)
187 fprintf(stderr
, "Not promoting move node in untrustworthy tree.\n");
189 fprintf(stderr
, "Warning: Cannot promote move node! Several play commands in row?\n");
191 /* Preserve dynamic komi information, though, that is important. */
192 u
->initial_extra_komi
= u
->t
->extra_komi
;
197 /* If we are a slave in a distributed engine, start pondering once
198 * we know which move we actually played. See uct_genmove() about
199 * the check for pass. */
200 if (u
->pondering_opt
&& u
->slave
&& m
->color
== u
->my_color
&& !is_pass(m
->coord
))
201 uct_pondering_start(u
, b
, u
->t
, stone_other(m
->color
));
207 uct_undo(struct engine
*e
, struct board
*b
)
209 struct uct
*u
= e
->data
;
211 if (!u
->t
) return NULL
;
212 uct_pondering_stop(u
);
213 u
->initial_extra_komi
= u
->t
->extra_komi
;
219 uct_result(struct engine
*e
, struct board
*b
)
221 struct uct
*u
= e
->data
;
222 static char reply
[1024];
226 enum stone color
= u
->t
->root_color
;
227 struct tree_node
*n
= u
->t
->root
;
228 snprintf(reply
, 1024, "%s %s %d %.2f %.1f",
229 stone2str(color
), coord2sstr(node_coord(n
), b
),
230 n
->u
.playouts
, tree_node_get_value(u
->t
, -1, n
->u
.value
),
231 u
->t
->use_extra_komi
? u
->t
->extra_komi
: 0);
236 uct_chat(struct engine
*e
, struct board
*b
, bool opponent
, char *from
, char *cmd
)
238 struct uct
*u
= e
->data
;
241 return generic_chat(b
, opponent
, from
, cmd
, S_NONE
, pass
, 0, 1, u
->threads
, 0.0, 0.0);
243 struct tree_node
*n
= u
->t
->root
;
244 double winrate
= tree_node_get_value(u
->t
, -1, n
->u
.value
);
245 double extra_komi
= u
->t
->use_extra_komi
&& abs(u
->t
->extra_komi
) >= 0.5 ? u
->t
->extra_komi
: 0;
247 return generic_chat(b
, opponent
, from
, cmd
, u
->t
->root_color
, node_coord(n
), n
->u
.playouts
, 1,
248 u
->threads
, winrate
, extra_komi
);
252 uct_dead_group_list(struct engine
*e
, struct board
*b
, struct move_queue
*mq
)
254 struct uct
*u
= e
->data
;
256 /* This means the game is probably over, no use pondering on. */
257 uct_pondering_stop(u
);
259 if (u
->pass_all_alive
)
260 return; // no dead groups
262 bool mock_state
= false;
265 /* No state, but we cannot just back out - we might
266 * have passed earlier, only assuming some stones are
267 * dead, and then re-connected, only to lose counting
268 * when all stones are assumed alive. */
269 uct_prepare_move(u
, b
, S_BLACK
); assert(u
->t
);
272 /* Make sure the ownermap is well-seeded. */
273 while (u
->ownermap
.playouts
< GJ_MINGAMES
)
274 uct_playout(u
, b
, S_BLACK
, u
->t
);
275 /* Show the ownermap: */
277 board_print_custom(b
, stderr
, uct_printhook_ownermap
);
279 dead_group_list(u
, b
, mq
);
282 /* Clean up the mock state in case we will receive
283 * a genmove; we could get a non-alternating-move
284 * error from uct_prepare_move() in that case otherwise. */
290 playout_policy_done(struct playout_policy
*p
)
292 if (p
->done
) p
->done(p
);
293 if (p
->data
) free(p
->data
);
298 uct_stop(struct engine
*e
)
300 /* This is called on game over notification. However, an undo
301 * and game resume can follow, so don't panic yet and just
302 * relax and stop thinking so that we don't waste CPU. */
303 struct uct
*u
= e
->data
;
304 uct_pondering_stop(u
);
308 uct_done(struct engine
*e
)
310 /* This is called on engine reset, especially when clear_board
311 * is received and new game should begin. */
312 struct uct
*u
= e
->data
;
313 uct_pondering_stop(u
);
314 if (u
->t
) reset_state(u
);
315 free(u
->ownermap
.map
);
318 free(u
->random_policy
);
319 playout_policy_done(u
->playout
);
320 uct_prior_done(u
->prior
);
321 joseki_done(u
->jdict
);
322 pluginset_done(u
->plugins
);
327 /* Run time-limited MCTS search on foreground. */
329 uct_search(struct uct
*u
, struct board
*b
, struct time_info
*ti
, enum stone color
, struct tree
*t
, bool print_progress
)
331 struct uct_search_state s
;
332 uct_search_start(u
, b
, color
, t
, ti
, &s
);
333 if (UDEBUGL(2) && s
.base_playouts
> 0)
334 fprintf(stderr
, "<pre-simulated %d games>\n", s
.base_playouts
);
336 /* The search tree is ctx->t. This is currently == . It is important
337 * to reference ctx->t directly since the
338 * thread manager will swap the tree pointer asynchronously. */
340 /* Now, just periodically poll the search tree. */
341 /* Note that in case of TD_GAMES, threads will not wait for
342 * the uct_search_check_stop() signalization. */
344 time_sleep(TREE_BUSYWAIT_INTERVAL
);
345 /* TREE_BUSYWAIT_INTERVAL should never be less than desired time, or the
346 * time control is broken. But if it happens to be less, we still search
347 * at least 100ms otherwise the move is completely random. */
349 int i
= uct_search_games(&s
);
350 /* Print notifications etc. */
351 uct_search_progress(u
, b
, color
, t
, ti
, &s
, i
);
352 /* Check if we should stop the search. */
353 if (uct_search_check_stop(u
, b
, color
, t
, ti
, &s
, i
))
357 struct uct_thread_ctx
*ctx
= uct_search_stop();
358 if (UDEBUGL(2)) tree_dump(t
, u
->dumpthres
);
360 fprintf(stderr
, "(avg score %f/%d; dynkomi's %f/%d value %f/%d)\n",
361 t
->avg_score
.value
, t
->avg_score
.playouts
,
362 u
->dynkomi
->score
.value
, u
->dynkomi
->score
.playouts
,
363 u
->dynkomi
->value
.value
, u
->dynkomi
->value
.playouts
);
365 uct_progress_status(u
, t
, color
, ctx
->games
, NULL
);
367 if (u
->debug_after
.playouts
> 0) {
368 /* Now, start an additional run of playouts, single threaded. */
369 struct time_info debug_ti
= {
373 debug_ti
.len
.games
= t
->root
->u
.playouts
+ u
->debug_after
.playouts
;
375 board_print_custom(b
, stderr
, uct_printhook_ownermap
);
376 fprintf(stderr
, "--8<-- UCT debug post-run begin (%d:%d) --8<--\n", u
->debug_after
.level
, u
->debug_after
.playouts
);
378 int debug_level_save
= debug_level
;
379 int u_debug_level_save
= u
->debug_level
;
380 int p_debug_level_save
= u
->playout
->debug_level
;
381 debug_level
= u
->debug_after
.level
;
382 u
->debug_level
= u
->debug_after
.level
;
383 u
->playout
->debug_level
= u
->debug_after
.level
;
386 uct_playouts(u
, b
, color
, t
, &debug_ti
);
387 tree_dump(t
, u
->dumpthres
);
390 debug_level
= debug_level_save
;
391 u
->debug_level
= u_debug_level_save
;
392 u
->playout
->debug_level
= p_debug_level_save
;
394 fprintf(stderr
, "--8<-- UCT debug post-run finished --8<--\n");
397 u
->played_own
+= ctx
->games
;
401 /* Start pondering background with @color to play. */
403 uct_pondering_start(struct uct
*u
, struct board
*b0
, struct tree
*t
, enum stone color
)
406 fprintf(stderr
, "Starting to ponder with color %s\n", stone2str(stone_other(color
)));
409 /* We need a local board copy to ponder upon. */
410 struct board
*b
= malloc2(sizeof(*b
)); board_copy(b
, b0
);
412 /* *b0 did not have the genmove'd move played yet. */
413 struct move m
= { node_coord(t
->root
), t
->root_color
};
414 int res
= board_play(b
, &m
);
416 setup_dynkomi(u
, b
, stone_other(m
.color
));
418 /* Start MCTS manager thread "headless". */
419 static struct uct_search_state s
;
420 uct_search_start(u
, b
, color
, t
, NULL
, &s
);
423 /* uct_search_stop() frontend for the pondering (non-genmove) mode, and
424 * to stop the background search for a slave in the distributed engine. */
426 uct_pondering_stop(struct uct
*u
)
428 if (!thread_manager_running
)
431 /* Stop the thread manager. */
432 struct uct_thread_ctx
*ctx
= uct_search_stop();
434 if (u
->pondering
) fprintf(stderr
, "(pondering) ");
435 uct_progress_status(u
, ctx
->t
, ctx
->color
, ctx
->games
, NULL
);
439 u
->pondering
= false;
445 uct_genmove_setup(struct uct
*u
, struct board
*b
, enum stone color
)
447 if (b
->superko_violation
) {
448 fprintf(stderr
, "!!! WARNING: SUPERKO VIOLATION OCCURED BEFORE THIS MOVE\n");
449 fprintf(stderr
, "Maybe you play with situational instead of positional superko?\n");
450 fprintf(stderr
, "I'm going to ignore the violation, but note that I may miss\n");
451 fprintf(stderr
, "some moves valid under this ruleset because of this.\n");
452 b
->superko_violation
= false;
455 uct_prepare_move(u
, b
, color
);
460 /* How to decide whether to use dynkomi in this game? Since we use
461 * pondering, it's not simple "who-to-play" matter. Decide based on
462 * the last genmove issued. */
463 u
->t
->use_extra_komi
= !!(u
->dynkomi_mask
& color
);
464 setup_dynkomi(u
, b
, color
);
466 if (b
->rules
== RULES_JAPANESE
)
467 u
->territory_scoring
= true;
469 /* Make pessimistic assumption about komi for Japanese rules to
470 * avoid losing by 0.5 when winning by 0.5 with Chinese rules.
471 * The rules usually give the same winner if the integer part of komi
472 * is odd so we adjust the komi only if it is even (for a board of
473 * odd size). We are not trying to get an exact evaluation for rare
474 * cases of seki. For details see http://home.snafu.de/jasiek/parity.html */
475 if (u
->territory_scoring
&& (((int)floor(b
->komi
) + board_size(b
)) & 1)) {
476 b
->komi
+= (color
== S_BLACK
? 1.0 : -1.0);
478 fprintf(stderr
, "Setting komi to %.1f assuming Japanese rules\n",
484 uct_genmove(struct engine
*e
, struct board
*b
, struct time_info
*ti
, enum stone color
, bool pass_all_alive
)
486 double start_time
= time_now();
487 struct uct
*u
= e
->data
;
488 u
->pass_all_alive
|= pass_all_alive
;
489 uct_pondering_stop(u
);
490 uct_genmove_setup(u
, b
, color
);
492 /* Start the Monte Carlo Tree Search! */
493 int base_playouts
= u
->t
->root
->u
.playouts
;
494 int played_games
= uct_search(u
, b
, ti
, color
, u
->t
, false);
497 struct tree_node
*best
;
498 best
= uct_search_result(u
, b
, color
, u
->pass_all_alive
, played_games
, base_playouts
, &best_coord
);
501 double time
= time_now() - start_time
+ 0.000001; /* avoid divide by zero */
502 fprintf(stderr
, "genmove in %0.2fs (%d games/s, %d games/s/thread)\n",
503 time
, (int)(played_games
/time
), (int)(played_games
/time
/u
->threads
));
506 uct_progress_status(u
, u
->t
, color
, played_games
, &best_coord
);
509 /* Pass or resign. */
510 if (is_pass(best_coord
))
511 u
->initial_extra_komi
= u
->t
->extra_komi
;
513 return coord_copy(best_coord
);
516 if (!u
->t
->untrustworthy_tree
) {
517 tree_promote_node(u
->t
, &best
);
519 /* Throw away an untrustworthy tree. */
520 /* Preserve dynamic komi information, though, that is important. */
521 u
->initial_extra_komi
= u
->t
->extra_komi
;
525 /* After a pass, pondering is harmful for two reasons:
526 * (i) We might keep pondering even when the game is over.
527 * Of course this is the case for opponent resign as well.
528 * (ii) More importantly, the ownermap will get skewed since
529 * the UCT will start cutting off any playouts. */
530 if (u
->pondering_opt
&& u
->t
&& !is_pass(node_coord(best
))) {
531 uct_pondering_start(u
, b
, u
->t
, stone_other(color
));
533 return coord_copy(best_coord
);
538 uct_gentbook(struct engine
*e
, struct board
*b
, struct time_info
*ti
, enum stone color
)
540 struct uct
*u
= e
->data
;
541 if (!u
->t
) uct_prepare_move(u
, b
, color
);
544 if (ti
->dim
== TD_GAMES
) {
545 /* Don't count in games that already went into the tbook. */
546 ti
->len
.games
+= u
->t
->root
->u
.playouts
;
548 uct_search(u
, b
, ti
, color
, u
->t
, true);
550 assert(ti
->dim
== TD_GAMES
);
551 tree_save(u
->t
, b
, ti
->len
.games
/ 100);
557 uct_dumptbook(struct engine
*e
, struct board
*b
, enum stone color
)
559 struct uct
*u
= e
->data
;
560 struct tree
*t
= tree_init(b
, color
, u
->fast_alloc
? u
->max_tree_size
: 0,
561 u
->max_pruned_size
, u
->pruning_threshold
, u
->local_tree_aging
, 0);
569 uct_evaluate_one(struct engine
*e
, struct board
*b
, struct time_info
*ti
, coord_t c
, enum stone color
)
571 struct uct
*u
= e
->data
;
575 struct move m
= { c
, color
};
576 int res
= board_play(&b2
, &m
);
579 color
= stone_other(color
);
581 if (u
->t
) reset_state(u
);
582 uct_prepare_move(u
, &b2
, color
);
586 uct_search(u
, &b2
, ti
, color
, u
->t
, true);
587 struct tree_node
*best
= u
->policy
->choose(u
->policy
, u
->t
->root
, &b2
, color
, resign
);
589 bestval
= NAN
; // the opponent has no reply!
591 bestval
= tree_node_get_value(u
->t
, 1, best
->u
.value
);
594 reset_state(u
); // clean our junk
596 return isnan(bestval
) ? NAN
: 1.0f
- bestval
;
600 uct_evaluate(struct engine
*e
, struct board
*b
, struct time_info
*ti
, floating_t
*vals
, enum stone color
)
602 for (int i
= 0; i
< b
->flen
; i
++) {
603 if (is_pass(b
->f
[i
]))
606 vals
[i
] = uct_evaluate_one(e
, b
, ti
, b
->f
[i
], color
);
612 uct_state_init(char *arg
, struct board
*b
)
614 struct uct
*u
= calloc2(1, sizeof(struct uct
));
615 bool pat_setup
= false;
617 u
->debug_level
= debug_level
;
618 u
->reportfreq
= 10000;
619 u
->gamelen
= MC_GAMELEN
;
620 u
->resign_threshold
= 0.2;
621 u
->sure_win_threshold
= 0.95;
623 u
->significant_threshold
= 50;
626 u
->playout_amaf
= true;
627 u
->amaf_prior
= false;
628 u
->max_tree_size
= 1408ULL * 1048576;
629 u
->fast_alloc
= true;
630 u
->pruning_threshold
= 0;
633 u
->thread_model
= TM_TREEVL
;
636 u
->pondering_opt
= true;
638 u
->fuseki_end
= 20; // max time at 361*20% = 72 moves (our 36th move, still 99 to play)
639 u
->yose_start
= 40; // (100-40-25)*361/100/2 = 63 moves still to play by us then
640 u
->bestr_ratio
= 0.02;
641 // 2.5 is clearly too much, but seems to compensate well for overly stern time allocations.
642 // TODO: Further tuning and experiments with better time allocation schemes.
643 u
->best2_ratio
= 2.5;
644 // Higher values of max_maintime_ratio sometimes cause severe time trouble in tournaments
645 // It might be necessary to reduce it to 1.5 on large board, but more tuning is needed.
646 u
->max_maintime_ratio
= 2.0;
648 u
->val_scale
= 0; u
->val_points
= 40;
649 u
->dynkomi_interval
= 1000;
650 u
->dynkomi_mask
= S_BLACK
| S_WHITE
;
653 u
->local_tree_aging
= 80;
654 u
->local_tree_depth_decay
= 1.5;
655 u
->local_tree_eval
= LTE_ROOT
;
656 u
->local_tree_neival
= true;
660 u
->stats_delay
= 0.01; // 10 ms
661 u
->shared_levels
= 1;
663 u
->plugins
= pluginset_init(b
);
665 u
->jdict
= joseki_load(b
->size
);
668 char *optspec
, *next
= arg
;
671 next
+= strcspn(next
, ",");
672 if (*next
) { *next
++ = 0; } else { *next
= 0; }
674 char *optname
= optspec
;
675 char *optval
= strchr(optspec
, '=');
676 if (optval
) *optval
++ = 0;
680 if (!strcasecmp(optname
, "debug")) {
682 u
->debug_level
= atoi(optval
);
685 } else if (!strcasecmp(optname
, "reporting") && optval
) {
686 /* The format of output for detailed progress
687 * information (such as current best move and
688 * its value, etc.). */
689 if (!strcasecmp(optval
, "text")) {
690 /* Plaintext traditional output. */
691 u
->reporting
= UR_TEXT
;
692 } else if (!strcasecmp(optval
, "json")) {
693 /* JSON output. Implies debug=0. */
694 u
->reporting
= UR_JSON
;
696 } else if (!strcasecmp(optval
, "jsonbig")) {
697 /* JSON output, but much more detailed.
698 * Implies debug=0. */
699 u
->reporting
= UR_JSON_BIG
;
702 fprintf(stderr
, "UCT: Invalid reporting format %s\n", optval
);
705 } else if (!strcasecmp(optname
, "reportfreq") && optval
) {
706 /* The progress information line will be shown
707 * every <reportfreq> simulations. */
708 u
->reportfreq
= atoi(optval
);
709 } else if (!strcasecmp(optname
, "dumpthres") && optval
) {
710 /* When dumping the UCT tree on output, include
711 * nodes with at least this many playouts.
712 * (A fraction of the total # of playouts at the
714 /* Use 0 to list all nodes with at least one
715 * simulation, and -1 to list _all_ nodes. */
716 u
->dumpthres
= atof(optval
);
717 } else if (!strcasecmp(optname
, "resign_threshold") && optval
) {
718 /* Resign when this ratio of games is lost
719 * after GJ_MINGAMES sample is taken. */
720 u
->resign_threshold
= atof(optval
);
721 } else if (!strcasecmp(optname
, "sure_win_threshold") && optval
) {
722 /* Stop reading when this ratio of games is won
723 * after PLAYOUT_EARLY_BREAK_MIN sample is
724 * taken. (Prevents stupid time losses,
725 * friendly to human opponents.) */
726 u
->sure_win_threshold
= atof(optval
);
727 } else if (!strcasecmp(optname
, "force_seed") && optval
) {
728 /* Set RNG seed at the tree setup. */
729 u
->force_seed
= atoi(optval
);
730 } else if (!strcasecmp(optname
, "no_tbook")) {
731 /* Disable UCT opening tbook. */
733 } else if (!strcasecmp(optname
, "pass_all_alive")) {
734 /* Whether to consider passing only after all
735 * dead groups were removed from the board;
736 * this is like all genmoves are in fact
737 * kgs-genmove_cleanup. */
738 u
->pass_all_alive
= !optval
|| atoi(optval
);
739 } else if (!strcasecmp(optname
, "allow_losing_pass")) {
740 /* Whether to consider passing in a clear
741 * but losing situation, to be scored as a loss
743 u
->allow_losing_pass
= !optval
|| atoi(optval
);
744 } else if (!strcasecmp(optname
, "territory_scoring")) {
745 /* Use territory scoring (default is area scoring).
746 * An explicit kgs-rules command overrides this. */
747 u
->territory_scoring
= !optval
|| atoi(optval
);
748 } else if (!strcasecmp(optname
, "stones_only")) {
749 /* Do not count eyes. Nice to teach go to kids.
750 * http://strasbourg.jeudego.org/regle_strasbourgeoise.htm */
751 b
->rules
= RULES_STONES_ONLY
;
752 u
->pass_all_alive
= true;
753 } else if (!strcasecmp(optname
, "debug_after")) {
754 /* debug_after=9:1000 will make Pachi think under
755 * the normal conditions, but at the point when
756 * a move is to be chosen, the tree is dumped and
757 * another 1000 simulations are run single-threaded
758 * with debug level 9, allowing inspection of Pachi's
759 * behavior after it has thought a lot. */
761 u
->debug_after
.level
= atoi(optval
);
762 char *playouts
= strchr(optval
, ':');
764 u
->debug_after
.playouts
= atoi(playouts
+1);
766 u
->debug_after
.playouts
= 1000;
768 u
->debug_after
.level
= 9;
769 u
->debug_after
.playouts
= 1000;
771 } else if (!strcasecmp(optname
, "banner") && optval
) {
772 /* Additional banner string. This must come as the
773 * last engine parameter. You can use '+' instead
774 * of ' ' if you are wrestling with kgsGtp. */
775 if (*next
) *--next
= ',';
776 u
->banner
= strdup(optval
);
777 for (char *b
= u
->banner
; *b
; b
++) {
778 if (*b
== '+') *b
= ' ';
781 } else if (!strcasecmp(optname
, "plugin") && optval
) {
782 /* Load an external plugin; filename goes before the colon,
783 * extra arguments after the colon. */
784 char *pluginarg
= strchr(optval
, ':');
787 plugin_load(u
->plugins
, optval
, pluginarg
);
789 /** UCT behavior and policies */
791 } else if ((!strcasecmp(optname
, "policy")
792 /* Node selection policy. ucb1amaf is the
793 * default policy implementing RAVE, while
794 * ucb1 is the simple exploration/exploitation
795 * policy. Policies can take further extra
797 || !strcasecmp(optname
, "random_policy")) && optval
) {
798 /* A policy to be used randomly with small
799 * chance instead of the default policy. */
800 char *policyarg
= strchr(optval
, ':');
801 struct uct_policy
**p
= !strcasecmp(optname
, "policy") ? &u
->policy
: &u
->random_policy
;
804 if (!strcasecmp(optval
, "ucb1")) {
805 *p
= policy_ucb1_init(u
, policyarg
);
806 } else if (!strcasecmp(optval
, "ucb1amaf")) {
807 *p
= policy_ucb1amaf_init(u
, policyarg
, b
);
809 fprintf(stderr
, "UCT: Invalid tree policy %s\n", optval
);
812 } else if (!strcasecmp(optname
, "playout") && optval
) {
813 /* Random simulation (playout) policy.
814 * moggy is the default policy with large
815 * amount of domain-specific knowledge and
816 * heuristics. light is a simple uniformly
817 * random move selection policy. */
818 char *playoutarg
= strchr(optval
, ':');
821 if (!strcasecmp(optval
, "moggy")) {
822 u
->playout
= playout_moggy_init(playoutarg
, b
, u
->jdict
);
823 } else if (!strcasecmp(optval
, "light")) {
824 u
->playout
= playout_light_init(playoutarg
, b
);
826 fprintf(stderr
, "UCT: Invalid playout policy %s\n", optval
);
829 } else if (!strcasecmp(optname
, "prior") && optval
) {
830 /* Node priors policy. When expanding a node,
831 * it will seed node values heuristically
832 * (most importantly, based on playout policy
833 * opinion, but also with regard to other
834 * things). See uct/prior.c for details.
835 * Use prior=eqex=0 to disable priors. */
836 u
->prior
= uct_prior_init(optval
, b
, u
);
837 } else if (!strcasecmp(optname
, "mercy") && optval
) {
838 /* Minimal difference of black/white captures
839 * to stop playout - "Mercy Rule". Speeds up
840 * hopeless playouts at the expense of some
842 u
->mercymin
= atoi(optval
);
843 } else if (!strcasecmp(optname
, "gamelen") && optval
) {
844 /* Maximum length of single simulation
846 u
->gamelen
= atoi(optval
);
847 } else if (!strcasecmp(optname
, "expand_p") && optval
) {
848 /* Expand UCT nodes after it has been
849 * visited this many times. */
850 u
->expand_p
= atoi(optval
);
851 } else if (!strcasecmp(optname
, "random_policy_chance") && optval
) {
852 /* If specified (N), with probability 1/N, random_policy policy
853 * descend is used instead of main policy descend; useful
854 * if specified policy (e.g. UCB1AMAF) can make unduly biased
855 * choices sometimes, you can fall back to e.g.
856 * random_policy=UCB1. */
857 u
->random_policy_chance
= atoi(optval
);
859 /** General AMAF behavior */
860 /* (Only relevant if the policy supports AMAF.
861 * More variables can be tuned as policy
864 } else if (!strcasecmp(optname
, "playout_amaf")) {
865 /* Whether to include random playout moves in
866 * AMAF as well. (Otherwise, only tree moves
867 * are included in AMAF. Of course makes sense
868 * only in connection with an AMAF policy.) */
869 /* with-without: 55.5% (+-4.1) */
870 if (optval
&& *optval
== '0')
871 u
->playout_amaf
= false;
873 u
->playout_amaf
= true;
874 } else if (!strcasecmp(optname
, "playout_amaf_cutoff") && optval
) {
875 /* Keep only first N% of playout stage AMAF
877 u
->playout_amaf_cutoff
= atoi(optval
);
878 } else if (!strcasecmp(optname
, "amaf_prior") && optval
) {
879 /* In node policy, consider prior values
880 * part of the real result term or part
881 * of the AMAF term? */
882 u
->amaf_prior
= atoi(optval
);
884 /** Performance and memory management */
886 } else if (!strcasecmp(optname
, "threads") && optval
) {
887 /* By default, Pachi will run with only single
888 * tree search thread! */
889 u
->threads
= atoi(optval
);
890 } else if (!strcasecmp(optname
, "thread_model") && optval
) {
891 if (!strcasecmp(optval
, "tree")) {
892 /* Tree parallelization - all threads
893 * grind on the same tree. */
894 u
->thread_model
= TM_TREE
;
896 } else if (!strcasecmp(optval
, "treevl")) {
897 /* Tree parallelization, but also
898 * with virtual losses - this discou-
899 * rages most threads choosing the
900 * same tree branches to read. */
901 u
->thread_model
= TM_TREEVL
;
903 fprintf(stderr
, "UCT: Invalid thread model %s\n", optval
);
906 } else if (!strcasecmp(optname
, "virtual_loss") && optval
) {
907 /* Number of virtual losses added before evaluating a node. */
908 u
->virtual_loss
= atoi(optval
);
909 } else if (!strcasecmp(optname
, "pondering")) {
910 /* Keep searching even during opponent's turn. */
911 u
->pondering_opt
= !optval
|| atoi(optval
);
912 } else if (!strcasecmp(optname
, "max_tree_size") && optval
) {
913 /* Maximum amount of memory [MiB] consumed by the move tree.
914 * For fast_alloc it includes the temp tree used for pruning.
915 * Default is 3072 (3 GiB). */
916 u
->max_tree_size
= atol(optval
) * 1048576;
917 } else if (!strcasecmp(optname
, "fast_alloc")) {
918 u
->fast_alloc
= !optval
|| atoi(optval
);
919 } else if (!strcasecmp(optname
, "pruning_threshold") && optval
) {
920 /* Force pruning at beginning of a move if the tree consumes
921 * more than this [MiB]. Default is 10% of max_tree_size.
922 * Increase to reduce pruning time overhead if memory is plentiful.
923 * This option is meaningful only for fast_alloc. */
924 u
->pruning_threshold
= atol(optval
) * 1048576;
928 } else if (!strcasecmp(optname
, "best2_ratio") && optval
) {
929 /* If set, prolong simulating while
930 * first_best/second_best playouts ratio
931 * is less than best2_ratio. */
932 u
->best2_ratio
= atof(optval
);
933 } else if (!strcasecmp(optname
, "bestr_ratio") && optval
) {
934 /* If set, prolong simulating while
935 * best,best_best_child values delta
936 * is more than bestr_ratio. */
937 u
->bestr_ratio
= atof(optval
);
938 } else if (!strcasecmp(optname
, "max_maintime_ratio") && optval
) {
939 /* If set and while not in byoyomi, prolong simulating no more than
940 * max_maintime_ratio times the normal desired thinking time. */
941 u
->max_maintime_ratio
= atof(optval
);
942 } else if (!strcasecmp(optname
, "fuseki_end") && optval
) {
943 /* At the very beginning it's not worth thinking
944 * too long because the playout evaluations are
945 * very noisy. So gradually increase the thinking
946 * time up to maximum when fuseki_end percent
947 * of the board has been played.
948 * This only applies if we are not in byoyomi. */
949 u
->fuseki_end
= atoi(optval
);
950 } else if (!strcasecmp(optname
, "yose_start") && optval
) {
951 /* When yose_start percent of the board has been
952 * played, or if we are in byoyomi, stop spending
953 * more time and spread the remaining time
955 * Between fuseki_end and yose_start, we spend
956 * a constant proportion of the remaining time
957 * on each move. (yose_start should actually
958 * be much earlier than when real yose start,
959 * but "yose" is a good short name to convey
961 u
->yose_start
= atoi(optval
);
965 } else if (!strcasecmp(optname
, "dynkomi") && optval
) {
966 /* Dynamic komi approach; there are multiple
967 * ways to adjust komi dynamically throughout
968 * play. We currently support two: */
969 char *dynkomiarg
= strchr(optval
, ':');
972 if (!strcasecmp(optval
, "none")) {
973 u
->dynkomi
= uct_dynkomi_init_none(u
, dynkomiarg
, b
);
974 } else if (!strcasecmp(optval
, "linear")) {
975 /* You should set dynkomi_mask=1 or a very low
976 * handicap_value for white. */
977 u
->dynkomi
= uct_dynkomi_init_linear(u
, dynkomiarg
, b
);
978 } else if (!strcasecmp(optval
, "adaptive")) {
979 /* There are many more knobs to
980 * crank - see uct/dynkomi.c. */
981 u
->dynkomi
= uct_dynkomi_init_adaptive(u
, dynkomiarg
, b
);
983 fprintf(stderr
, "UCT: Invalid dynkomi mode %s\n", optval
);
986 } else if (!strcasecmp(optname
, "dynkomi_mask") && optval
) {
987 /* Bitmask of colors the player must be
988 * for dynkomi be applied; the default dynkomi_mask=3 allows
989 * dynkomi even in games where Pachi is white. */
990 u
->dynkomi_mask
= atoi(optval
);
991 } else if (!strcasecmp(optname
, "dynkomi_interval") && optval
) {
992 /* If non-zero, re-adjust dynamic komi
993 * throughout a single genmove reading,
994 * roughly every N simulations. */
995 /* XXX: Does not work with tree
996 * parallelization. */
997 u
->dynkomi_interval
= atoi(optval
);
998 } else if (!strcasecmp(optname
, "extra_komi") && optval
) {
999 /* Initial dynamic komi settings. This
1000 * is useful for the adaptive dynkomi
1001 * policy as the value to start with
1002 * (this is NOT kept fixed) in case
1003 * there is not enough time in the search
1004 * to adjust the value properly (e.g. the
1005 * game was interrupted). */
1006 u
->initial_extra_komi
= atof(optval
);
1008 /** Node value result scaling */
1010 } else if (!strcasecmp(optname
, "val_scale") && optval
) {
1011 /* How much of the game result value should be
1012 * influenced by win size. Zero means it isn't. */
1013 u
->val_scale
= atof(optval
);
1014 } else if (!strcasecmp(optname
, "val_points") && optval
) {
1015 /* Maximum size of win to be scaled into game
1016 * result value. Zero means boardsize^2. */
1017 u
->val_points
= atoi(optval
) * 2; // result values are doubled
1018 } else if (!strcasecmp(optname
, "val_extra")) {
1019 /* If false, the score coefficient will be simply
1020 * added to the value, instead of scaling the result
1021 * coefficient because of it. */
1022 u
->val_extra
= !optval
|| atoi(optval
);
1023 } else if (!strcasecmp(optname
, "val_byavg")) {
1024 /* If true, the score included in the value will
1025 * be relative to average score in the current
1026 * search episode inst. of jigo. */
1027 u
->val_byavg
= !optval
|| atoi(optval
);
1028 } else if (!strcasecmp(optname
, "val_bytemp")) {
1029 /* If true, the value scaling coefficient
1030 * is different based on value extremity
1031 * (dist. from 0.5), linear between
1032 * val_bytemp_min, val_scale. */
1033 u
->val_bytemp
= !optval
|| atoi(optval
);
1034 } else if (!strcasecmp(optname
, "val_bytemp_min") && optval
) {
1035 /* Minimum val_scale in case of val_bytemp. */
1036 u
->val_bytemp_min
= atof(optval
);
1039 /* (Purely experimental. Does not work - yet!) */
1041 } else if (!strcasecmp(optname
, "local_tree")) {
1042 /* Whether to bias exploration by local tree values. */
1043 u
->local_tree
= !optval
|| atoi(optval
);
1044 } else if (!strcasecmp(optname
, "tenuki_d") && optval
) {
1045 /* Tenuki distance at which to break the local tree. */
1046 u
->tenuki_d
= atoi(optval
);
1047 if (u
->tenuki_d
> TREE_NODE_D_MAX
+ 1) {
1048 fprintf(stderr
, "uct: tenuki_d must not be larger than TREE_NODE_D_MAX+1 %d\n", TREE_NODE_D_MAX
+ 1);
1051 } else if (!strcasecmp(optname
, "local_tree_aging") && optval
) {
1052 /* How much to reduce local tree values between moves. */
1053 u
->local_tree_aging
= atof(optval
);
1054 } else if (!strcasecmp(optname
, "local_tree_depth_decay") && optval
) {
1055 /* With value x>0, during the descent the node
1056 * contributes 1/x^depth playouts in
1057 * the local tree. I.e., with x>1, nodes more
1058 * distant from local situation contribute more
1059 * than nodes near the root. */
1060 u
->local_tree_depth_decay
= atof(optval
);
1061 } else if (!strcasecmp(optname
, "local_tree_allseq")) {
1062 /* If disabled, only complete sequences are stored
1063 * in the local tree. If this is on, also
1064 * subsequences starting at each move are stored. */
1065 u
->local_tree_allseq
= !optval
|| atoi(optval
);
1066 } else if (!strcasecmp(optname
, "local_tree_neival")) {
1067 /* If disabled, local node value is not
1068 * computed just based on terminal status
1069 * of the coordinate, but also its neighbors. */
1070 u
->local_tree_neival
= !optval
|| atoi(optval
);
1071 } else if (!strcasecmp(optname
, "local_tree_eval")) {
1072 /* How is the value inserted in the local tree
1074 if (!strcasecmp(optval
, "root"))
1075 /* All moves within a tree branch are
1076 * considered wrt. their merit
1077 * reaching tachtical goal of making
1078 * the first move in the branch
1080 u
->local_tree_eval
= LTE_ROOT
;
1081 else if (!strcasecmp(optval
, "each"))
1082 /* Each move is considered wrt.
1083 * its own survival. */
1084 u
->local_tree_eval
= LTE_EACH
;
1085 else if (!strcasecmp(optval
, "total"))
1086 /* The tactical goal is the survival
1087 * of all the moves of my color and
1088 * non-survival of all the opponent
1089 * moves. Local values (and their
1090 * inverses) are averaged. */
1091 u
->local_tree_eval
= LTE_TOTAL
;
1093 fprintf(stderr
, "uct: unknown local_tree_eval %s\n", optval
);
1096 } else if (!strcasecmp(optname
, "local_tree_rootchoose")) {
1097 /* If disabled, only moves within the local
1098 * tree branch are considered; the values
1099 * of the branch roots (i.e. root children)
1100 * are ignored. This may make sense together
1101 * with eval!=each, we consider only moves
1102 * that influence the goal, not the "rating"
1103 * of the goal itself. (The real solution
1104 * will be probably using criticality to pick
1105 * local tree branches.) */
1106 u
->local_tree_rootchoose
= !optval
|| atoi(optval
);
1108 /** Other heuristics */
1109 } else if (!strcasecmp(optname
, "patterns")) {
1110 /* Load pattern database. Various modules
1111 * (priors, policies etc.) may make use
1112 * of this database. They will request
1113 * it automatically in that case, but you
1114 * can use this option to tweak the pattern
1116 patterns_init(&u
->pat
, optval
, false, true);
1117 u
->want_pat
= pat_setup
= true;
1118 } else if (!strcasecmp(optname
, "significant_threshold") && optval
) {
1119 /* Some heuristics (XXX: none in mainline) rely
1120 * on the knowledge of the last "significant"
1121 * node in the descent. Such a node is
1122 * considered reasonably trustworthy to carry
1123 * some meaningful information in the values
1124 * of the node and its children. */
1125 u
->significant_threshold
= atoi(optval
);
1127 /** Distributed engine slaves setup */
1129 } else if (!strcasecmp(optname
, "slave")) {
1130 /* Act as slave for the distributed engine. */
1131 u
->slave
= !optval
|| atoi(optval
);
1132 } else if (!strcasecmp(optname
, "slave_index") && optval
) {
1133 /* Optional index if per-slave behavior is desired.
1134 * Must be given as index/max */
1135 u
->slave_index
= atoi(optval
);
1136 char *p
= strchr(optval
, '/');
1137 if (p
) u
->max_slaves
= atoi(++p
);
1138 } else if (!strcasecmp(optname
, "shared_nodes") && optval
) {
1139 /* Share at most shared_nodes between master and slave at each genmoves.
1140 * Must use the same value in master and slaves. */
1141 u
->shared_nodes
= atoi(optval
);
1142 } else if (!strcasecmp(optname
, "shared_levels") && optval
) {
1143 /* Share only nodes of level <= shared_levels. */
1144 u
->shared_levels
= atoi(optval
);
1145 } else if (!strcasecmp(optname
, "stats_hbits") && optval
) {
1146 /* Set hash table size to 2^stats_hbits for the shared stats. */
1147 u
->stats_hbits
= atoi(optval
);
1148 } else if (!strcasecmp(optname
, "stats_delay") && optval
) {
1149 /* How long to wait in slave for initial stats to build up before
1150 * replying to the genmoves command (in ms) */
1151 u
->stats_delay
= 0.001 * atof(optval
);
1155 } else if (!strcasecmp(optname
, "maximize_score")) {
1156 /* A combination of settings that will make
1157 * Pachi try to maximize his points (instead
1158 * of playing slack yose) or minimize his loss
1159 * (and proceed to counting even when losing). */
1160 /* Please note that this preset might be
1161 * somewhat weaker than normal Pachi, and the
1162 * score maximization is approximate; point size
1163 * of win/loss still should not be used to judge
1164 * strength of Pachi or the opponent. */
1165 /* See README for some further notes. */
1166 if (!optval
|| atoi(optval
)) {
1167 /* Allow scoring a lost game. */
1168 u
->allow_losing_pass
= true;
1169 /* Make Pachi keep his calm when losing
1170 * and/or maintain winning marging. */
1171 /* Do not play games that are losing
1173 /* XXX: komi_ratchet_age=40000 is necessary
1174 * with losing_komi_ratchet, but 40000
1175 * is somewhat arbitrary value. */
1176 char dynkomi_args
[] = "losing_komi_ratchet:komi_ratchet_age=60000:no_komi_at_game_end=0:max_losing_komi=30";
1177 u
->dynkomi
= uct_dynkomi_init_adaptive(u
, dynkomi_args
, b
);
1178 /* XXX: Values arbitrary so far. */
1179 /* XXX: Also, is bytemp sensible when
1180 * combined with dynamic komi?! */
1181 u
->val_scale
= 0.01;
1182 u
->val_bytemp
= true;
1183 u
->val_bytemp_min
= 0.001;
1184 u
->val_byavg
= true;
1188 fprintf(stderr
, "uct: Invalid engine argument %s or missing value\n", optname
);
1195 u
->policy
= policy_ucb1amaf_init(u
, NULL
, b
);
1197 if (!!u
->random_policy_chance
^ !!u
->random_policy
) {
1198 fprintf(stderr
, "uct: Only one of random_policy and random_policy_chance is set\n");
1202 if (!u
->local_tree
) {
1203 /* No ltree aging. */
1204 u
->local_tree_aging
= 1.0f
;
1207 if (u
->fast_alloc
) {
1208 if (u
->pruning_threshold
< u
->max_tree_size
/ 10)
1209 u
->pruning_threshold
= u
->max_tree_size
/ 10;
1210 if (u
->pruning_threshold
> u
->max_tree_size
/ 2)
1211 u
->pruning_threshold
= u
->max_tree_size
/ 2;
1213 /* Limit pruning temp space to 20% of memory. Beyond this we discard
1214 * the nodes and recompute them at the next move if necessary. */
1215 u
->max_pruned_size
= u
->max_tree_size
/ 5;
1216 u
->max_tree_size
-= u
->max_pruned_size
;
1218 /* Reserve 5% memory in case the background free() are slower
1219 * than the concurrent allocations. */
1220 u
->max_tree_size
-= u
->max_tree_size
/ 20;
1224 u
->prior
= uct_prior_init(NULL
, b
, u
);
1227 u
->playout
= playout_moggy_init(NULL
, b
, u
->jdict
);
1228 if (!u
->playout
->debug_level
)
1229 u
->playout
->debug_level
= u
->debug_level
;
1231 if (u
->want_pat
&& !pat_setup
)
1232 patterns_init(&u
->pat
, NULL
, false, true);
1234 u
->ownermap
.map
= malloc2(board_size2(b
) * sizeof(u
->ownermap
.map
[0]));
1237 if (!u
->stats_hbits
) u
->stats_hbits
= DEFAULT_STATS_HBITS
;
1238 if (!u
->shared_nodes
) u
->shared_nodes
= DEFAULT_SHARED_NODES
;
1239 assert(u
->shared_levels
* board_bits2(b
) <= 8 * (int)sizeof(path_t
));
1243 u
->dynkomi
= board_small(b
) ? uct_dynkomi_init_none(u
, NULL
, b
)
1244 : uct_dynkomi_init_linear(u
, NULL
, b
);
1246 /* Some things remain uninitialized for now - the opening tbook
1247 * is not loaded and the tree not set up. */
1248 /* This will be initialized in setup_state() at the first move
1249 * received/requested. This is because right now we are not aware
1250 * about any komi or handicap setup and such. */
1256 engine_uct_init(char *arg
, struct board
*b
)
1258 struct uct
*u
= uct_state_init(arg
, b
);
1259 struct engine
*e
= calloc2(1, sizeof(struct engine
));
1261 e
->printhook
= uct_printhook_ownermap
;
1262 e
->notify_play
= uct_notify_play
;
1265 e
->result
= uct_result
;
1266 e
->genmove
= uct_genmove
;
1267 e
->genmoves
= uct_genmoves
;
1268 e
->evaluate
= uct_evaluate
;
1269 e
->dead_group_list
= uct_dead_group_list
;
1274 e
->notify
= uct_notify
;
1276 const char banner
[] = "If you believe you have won but I am still playing, "
1277 "please help me understand by capturing all dead stones. "
1278 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
1279 if (!u
->banner
) u
->banner
= "";
1280 e
->comment
= malloc2(sizeof(banner
) + strlen(u
->banner
) + 1);
1281 sprintf(e
->comment
, "%s %s", banner
, u
->banner
);