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 //board_print(b, stderr);
49 if (!u
->no_tbook
&& b
->moves
== 0) {
50 assert(color
== S_BLACK
);
56 reset_state(struct uct
*u
)
59 tree_done(u
->t
); u
->t
= NULL
;
63 setup_dynkomi(struct uct
*u
, struct board
*b
, enum stone to_play
)
65 if (u
->t
->use_extra_komi
&& !u
->pondering
&& u
->dynkomi
->permove
)
66 u
->t
->extra_komi
= u
->dynkomi
->permove(u
->dynkomi
, b
, u
->t
);
67 else if (!u
->t
->use_extra_komi
)
72 uct_prepare_move(struct uct
*u
, struct board
*b
, enum stone color
)
75 /* Verify that we have sane state. */
77 assert(u
->t
&& b
->moves
);
78 if (color
!= stone_other(u
->t
->root_color
)) {
79 fprintf(stderr
, "Fatal: Non-alternating play detected %d %d\n",
80 color
, u
->t
->root_color
);
83 uct_htable_reset(u
->t
);
86 /* We need fresh state. */
88 setup_state(u
, b
, color
);
91 u
->ownermap
.playouts
= 0;
92 memset(u
->ownermap
.map
, 0, board_size2(b
) * sizeof(u
->ownermap
.map
[0]));
93 u
->played_own
= u
->played_all
= 0;
97 dead_group_list(struct uct
*u
, struct board
*b
, struct move_queue
*mq
)
99 struct group_judgement gj
;
101 gj
.gs
= alloca(board_size2(b
) * sizeof(gj
.gs
[0]));
102 board_ownermap_judge_group(b
, &u
->ownermap
, &gj
);
103 groups_of_status(b
, &gj
, GS_DEAD
, mq
);
107 uct_pass_is_safe(struct uct
*u
, struct board
*b
, enum stone color
, bool pass_all_alive
)
109 /* Make sure enough playouts are simulated to get a reasonable dead group list. */
110 while (u
->ownermap
.playouts
< GJ_MINGAMES
)
111 uct_playout(u
, b
, color
, u
->t
);
113 struct move_queue mq
= { .moves
= 0 };
114 dead_group_list(u
, b
, &mq
);
115 if (pass_all_alive
&& mq
.moves
> 0)
116 return false; // We need to remove some dead groups first.
117 return pass_is_safe(b
, color
, &mq
);
121 uct_printhook_ownermap(struct board
*board
, coord_t c
, char *s
, char *end
)
123 struct uct
*u
= board
->es
;
128 const char chr
[] = ":XO,"; // dame, black, white, unclear
129 const char chm
[] = ":xo,";
130 char ch
= chr
[board_ownermap_judge_point(&u
->ownermap
, c
, GJ_THRES
)];
131 if (ch
== ',') { // less precise estimate then?
132 ch
= chm
[board_ownermap_judge_point(&u
->ownermap
, c
, 0.67)];
134 s
+= snprintf(s
, end
- s
, "%c ", ch
);
139 uct_notify_play(struct engine
*e
, struct board
*b
, struct move
*m
)
141 struct uct
*u
= e
->data
;
143 /* No state, create one - this is probably game beginning
144 * and we need to load the opening tbook right now. */
145 uct_prepare_move(u
, b
, m
->color
);
149 /* Stop pondering, required by tree_promote_at() */
150 uct_pondering_stop(u
);
151 if (UDEBUGL(2) && u
->slave
)
152 tree_dump(u
->t
, u
->dumpthres
);
154 if (is_resign(m
->coord
)) {
160 /* Promote node of the appropriate move to the tree root. */
162 if (!tree_promote_at(u
->t
, b
, m
->coord
)) {
164 fprintf(stderr
, "Warning: Cannot promote move node! Several play commands in row?\n");
169 /* If we are a slave in a distributed engine, start pondering once
170 * we know which move we actually played. See uct_genmove() about
171 * the check for pass. */
172 if (u
->pondering_opt
&& u
->slave
&& m
->color
== u
->my_color
&& !is_pass(m
->coord
))
173 uct_pondering_start(u
, b
, u
->t
, stone_other(m
->color
));
179 uct_undo(struct engine
*e
, struct board
*b
)
181 struct uct
*u
= e
->data
;
183 if (!u
->t
) return NULL
;
184 uct_pondering_stop(u
);
190 uct_result(struct engine
*e
, struct board
*b
)
192 struct uct
*u
= e
->data
;
193 static char reply
[1024];
197 enum stone color
= u
->t
->root_color
;
198 struct tree_node
*n
= u
->t
->root
;
199 snprintf(reply
, 1024, "%s %s %d %.2f %.1f",
200 stone2str(color
), coord2sstr(node_coord(n
), b
),
201 n
->u
.playouts
, tree_node_get_value(u
->t
, -1, n
->u
.value
),
202 u
->t
->use_extra_komi
? u
->t
->extra_komi
: 0);
207 uct_chat(struct engine
*e
, struct board
*b
, char *cmd
)
209 struct uct
*u
= e
->data
;
210 static char reply
[1024];
212 cmd
+= strspn(cmd
, " \n\t");
213 if (!strncasecmp(cmd
, "winrate", 7)) {
215 return "no game context (yet?)";
216 enum stone color
= u
->t
->root_color
;
217 struct tree_node
*n
= u
->t
->root
;
218 snprintf(reply
, 1024, "In %d playouts at %d threads, %s %s can win with %.2f%% probability",
219 n
->u
.playouts
, u
->threads
, stone2str(color
), coord2sstr(node_coord(n
), b
),
220 tree_node_get_value(u
->t
, -1, n
->u
.value
) * 100);
221 if (u
->t
->use_extra_komi
&& abs(u
->t
->extra_komi
) >= 0.5) {
222 sprintf(reply
+ strlen(reply
), ", while self-imposing extra komi %.1f",
232 uct_dead_group_list(struct engine
*e
, struct board
*b
, struct move_queue
*mq
)
234 struct uct
*u
= e
->data
;
236 /* This means the game is probably over, no use pondering on. */
237 uct_pondering_stop(u
);
239 if (u
->pass_all_alive
)
240 return; // no dead groups
242 bool mock_state
= false;
245 /* No state, but we cannot just back out - we might
246 * have passed earlier, only assuming some stones are
247 * dead, and then re-connected, only to lose counting
248 * when all stones are assumed alive. */
249 uct_prepare_move(u
, b
, S_BLACK
); assert(u
->t
);
252 /* Make sure the ownermap is well-seeded. */
253 while (u
->ownermap
.playouts
< GJ_MINGAMES
)
254 uct_playout(u
, b
, S_BLACK
, u
->t
);
255 /* Show the ownermap: */
257 board_print_custom(b
, stderr
, uct_printhook_ownermap
);
259 dead_group_list(u
, b
, mq
);
262 /* Clean up the mock state in case we will receive
263 * a genmove; we could get a non-alternating-move
264 * error from uct_prepare_move() in that case otherwise. */
270 playout_policy_done(struct playout_policy
*p
)
272 if (p
->done
) p
->done(p
);
273 if (p
->data
) free(p
->data
);
278 uct_done(struct engine
*e
)
280 /* This is called on engine reset, especially when clear_board
281 * is received and new game should begin. */
282 struct uct
*u
= e
->data
;
283 uct_pondering_stop(u
);
284 if (u
->t
) reset_state(u
);
285 free(u
->ownermap
.map
);
288 free(u
->random_policy
);
289 playout_policy_done(u
->playout
);
290 uct_prior_done(u
->prior
);
291 joseki_done(u
->jdict
);
292 pluginset_done(u
->plugins
);
297 /* Run time-limited MCTS search on foreground. */
299 uct_search(struct uct
*u
, struct board
*b
, struct time_info
*ti
, enum stone color
, struct tree
*t
)
301 struct uct_search_state s
;
302 uct_search_start(u
, b
, color
, t
, ti
, &s
);
303 if (UDEBUGL(2) && s
.base_playouts
> 0)
304 fprintf(stderr
, "<pre-simulated %d games>\n", s
.base_playouts
);
306 /* The search tree is ctx->t. This is currently == . It is important
307 * to reference ctx->t directly since the
308 * thread manager will swap the tree pointer asynchronously. */
310 /* Now, just periodically poll the search tree. */
311 /* Note that in case of TD_GAMES, threads will not wait for
312 * the uct_search_check_stop() signalization. */
314 time_sleep(TREE_BUSYWAIT_INTERVAL
);
315 /* TREE_BUSYWAIT_INTERVAL should never be less than desired time, or the
316 * time control is broken. But if it happens to be less, we still search
317 * at least 100ms otherwise the move is completely random. */
319 int i
= uct_search_games(&s
);
320 /* Print notifications etc. */
321 uct_search_progress(u
, b
, color
, t
, ti
, &s
, i
);
322 /* Check if we should stop the search. */
323 if (uct_search_check_stop(u
, b
, color
, t
, ti
, &s
, i
))
327 struct uct_thread_ctx
*ctx
= uct_search_stop();
328 if (UDEBUGL(2)) tree_dump(t
, u
->dumpthres
);
330 fprintf(stderr
, "(avg score %f/%d value %f/%d)\n",
331 u
->dynkomi
->score
.value
, u
->dynkomi
->score
.playouts
,
332 u
->dynkomi
->value
.value
, u
->dynkomi
->value
.playouts
);
334 uct_progress_status(u
, t
, color
, ctx
->games
);
336 u
->played_own
+= ctx
->games
;
340 /* Start pondering background with @color to play. */
342 uct_pondering_start(struct uct
*u
, struct board
*b0
, struct tree
*t
, enum stone color
)
345 fprintf(stderr
, "Starting to ponder with color %s\n", stone2str(stone_other(color
)));
348 /* We need a local board copy to ponder upon. */
349 struct board
*b
= malloc2(sizeof(*b
)); board_copy(b
, b0
);
351 /* *b0 did not have the genmove'd move played yet. */
352 struct move m
= { node_coord(t
->root
), t
->root_color
};
353 int res
= board_play(b
, &m
);
355 setup_dynkomi(u
, b
, stone_other(m
.color
));
357 /* Start MCTS manager thread "headless". */
358 static struct uct_search_state s
;
359 uct_search_start(u
, b
, color
, t
, NULL
, &s
);
362 /* uct_search_stop() frontend for the pondering (non-genmove) mode, and
363 * to stop the background search for a slave in the distributed engine. */
365 uct_pondering_stop(struct uct
*u
)
367 if (!thread_manager_running
)
370 /* Stop the thread manager. */
371 struct uct_thread_ctx
*ctx
= uct_search_stop();
373 if (u
->pondering
) fprintf(stderr
, "(pondering) ");
374 uct_progress_status(u
, ctx
->t
, ctx
->color
, ctx
->games
);
378 u
->pondering
= false;
384 uct_genmove_setup(struct uct
*u
, struct board
*b
, enum stone color
)
386 if (b
->superko_violation
) {
387 fprintf(stderr
, "!!! WARNING: SUPERKO VIOLATION OCCURED BEFORE THIS MOVE\n");
388 fprintf(stderr
, "Maybe you play with situational instead of positional superko?\n");
389 fprintf(stderr
, "I'm going to ignore the violation, but note that I may miss\n");
390 fprintf(stderr
, "some moves valid under this ruleset because of this.\n");
391 b
->superko_violation
= false;
394 uct_prepare_move(u
, b
, color
);
399 /* How to decide whether to use dynkomi in this game? Since we use
400 * pondering, it's not simple "who-to-play" matter. Decide based on
401 * the last genmove issued. */
402 u
->t
->use_extra_komi
= !!(u
->dynkomi_mask
& color
);
403 setup_dynkomi(u
, b
, color
);
405 if (b
->rules
== RULES_JAPANESE
)
406 u
->territory_scoring
= true;
408 /* Make pessimistic assumption about komi for Japanese rules to
409 * avoid losing by 0.5 when winning by 0.5 with Chinese rules.
410 * The rules usually give the same winner if the integer part of komi
411 * is odd so we adjust the komi only if it is even (for a board of
412 * odd size). We are not trying to get an exact evaluation for rare
413 * cases of seki. For details see http://home.snafu.de/jasiek/parity.html */
414 if (u
->territory_scoring
&& (((int)floor(b
->komi
) + board_size(b
)) & 1)) {
415 b
->komi
+= (color
== S_BLACK
? 1.0 : -1.0);
417 fprintf(stderr
, "Setting komi to %.1f assuming Japanese rules\n",
423 uct_genmove(struct engine
*e
, struct board
*b
, struct time_info
*ti
, enum stone color
, bool pass_all_alive
)
425 double start_time
= time_now();
426 struct uct
*u
= e
->data
;
427 u
->pass_all_alive
|= pass_all_alive
;
428 uct_pondering_stop(u
);
429 uct_genmove_setup(u
, b
, color
);
431 /* Start the Monte Carlo Tree Search! */
432 int base_playouts
= u
->t
->root
->u
.playouts
;
433 int played_games
= uct_search(u
, b
, ti
, color
, u
->t
);
436 struct tree_node
*best
;
437 best
= uct_search_result(u
, b
, color
, u
->pass_all_alive
, played_games
, base_playouts
, &best_coord
);
440 double time
= time_now() - start_time
+ 0.000001; /* avoid divide by zero */
441 fprintf(stderr
, "genmove in %0.2fs (%d games/s, %d games/s/thread)\n",
442 time
, (int)(played_games
/time
), (int)(played_games
/time
/u
->threads
));
446 /* Pass or resign. */
448 return coord_copy(best_coord
);
450 tree_promote_node(u
->t
, &best
);
452 /* After a pass, pondering is harmful for two reasons:
453 * (i) We might keep pondering even when the game is over.
454 * Of course this is the case for opponent resign as well.
455 * (ii) More importantly, the ownermap will get skewed since
456 * the UCT will start cutting off any playouts. */
457 if (u
->pondering_opt
&& !is_pass(node_coord(best
))) {
458 uct_pondering_start(u
, b
, u
->t
, stone_other(color
));
460 return coord_copy(best_coord
);
465 uct_gentbook(struct engine
*e
, struct board
*b
, struct time_info
*ti
, enum stone color
)
467 struct uct
*u
= e
->data
;
468 if (!u
->t
) uct_prepare_move(u
, b
, color
);
471 if (ti
->dim
== TD_GAMES
) {
472 /* Don't count in games that already went into the tbook. */
473 ti
->len
.games
+= u
->t
->root
->u
.playouts
;
475 uct_search(u
, b
, ti
, color
, u
->t
);
477 assert(ti
->dim
== TD_GAMES
);
478 tree_save(u
->t
, b
, ti
->len
.games
/ 100);
484 uct_dumptbook(struct engine
*e
, struct board
*b
, enum stone color
)
486 struct uct
*u
= e
->data
;
487 struct tree
*t
= tree_init(b
, color
, u
->fast_alloc
? u
->max_tree_size
: 0,
488 u
->max_pruned_size
, u
->pruning_threshold
, u
->local_tree_aging
, 0);
496 uct_evaluate(struct engine
*e
, struct board
*b
, struct time_info
*ti
, coord_t c
, enum stone color
)
498 struct uct
*u
= e
->data
;
502 struct move m
= { c
, color
};
503 int res
= board_play(&b2
, &m
);
506 color
= stone_other(color
);
508 if (u
->t
) reset_state(u
);
509 uct_prepare_move(u
, &b2
, color
);
513 uct_search(u
, &b2
, ti
, color
, u
->t
);
514 struct tree_node
*best
= u
->policy
->choose(u
->policy
, u
->t
->root
, &b2
, color
, resign
);
516 bestval
= NAN
; // the opponent has no reply!
518 bestval
= tree_node_get_value(u
->t
, 1, best
->u
.value
);
521 reset_state(u
); // clean our junk
523 return isnan(bestval
) ? NAN
: 1.0f
- bestval
;
528 uct_state_init(char *arg
, struct board
*b
)
530 struct uct
*u
= calloc2(1, sizeof(struct uct
));
532 u
->debug_level
= debug_level
;
533 u
->gamelen
= MC_GAMELEN
;
534 u
->resign_threshold
= 0.2;
535 u
->sure_win_threshold
= 0.9;
537 u
->significant_threshold
= 50;
540 u
->playout_amaf
= true;
541 u
->amaf_prior
= false;
542 u
->max_tree_size
= 1408ULL * 1048576;
543 u
->fast_alloc
= true;
544 u
->pruning_threshold
= 0;
547 u
->thread_model
= TM_TREEVL
;
550 u
->fuseki_end
= 20; // max time at 361*20% = 72 moves (our 36th move, still 99 to play)
551 u
->yose_start
= 40; // (100-40-25)*361/100/2 = 63 moves still to play by us then
552 u
->bestr_ratio
= 0.02;
553 // 2.5 is clearly too much, but seems to compensate well for overly stern time allocations.
554 // TODO: Further tuning and experiments with better time allocation schemes.
555 u
->best2_ratio
= 2.5;
556 u
->max_maintime_ratio
= 3.0;
558 u
->val_scale
= 0; u
->val_points
= 40;
559 u
->dynkomi_interval
= 1000;
560 u
->dynkomi_mask
= S_BLACK
| S_WHITE
;
563 u
->local_tree_aging
= 80;
564 u
->local_tree_depth_decay
= 1.5;
565 u
->local_tree_eval
= LTE_ROOT
;
566 u
->local_tree_neival
= true;
570 u
->stats_delay
= 0.01; // 10 ms
572 u
->plugins
= pluginset_init(b
);
574 u
->jdict
= joseki_load(b
->size
);
577 char *optspec
, *next
= arg
;
580 next
+= strcspn(next
, ",");
581 if (*next
) { *next
++ = 0; } else { *next
= 0; }
583 char *optname
= optspec
;
584 char *optval
= strchr(optspec
, '=');
585 if (optval
) *optval
++ = 0;
589 if (!strcasecmp(optname
, "debug")) {
591 u
->debug_level
= atoi(optval
);
594 } else if (!strcasecmp(optname
, "dumpthres") && optval
) {
595 /* When dumping the UCT tree on output, include
596 * nodes with at least this many playouts.
597 * (This value is re-scaled "intelligently"
598 * in case of very large trees.) */
599 u
->dumpthres
= atoi(optval
);
600 } else if (!strcasecmp(optname
, "resign_threshold") && optval
) {
601 /* Resign when this ratio of games is lost
602 * after GJ_MINGAMES sample is taken. */
603 u
->resign_threshold
= atof(optval
);
604 } else if (!strcasecmp(optname
, "sure_win_threshold") && optval
) {
605 /* Stop reading when this ratio of games is won
606 * after PLAYOUT_EARLY_BREAK_MIN sample is
607 * taken. (Prevents stupid time losses,
608 * friendly to human opponents.) */
609 u
->sure_win_threshold
= atof(optval
);
610 } else if (!strcasecmp(optname
, "force_seed") && optval
) {
611 /* Set RNG seed at the tree setup. */
612 u
->force_seed
= atoi(optval
);
613 } else if (!strcasecmp(optname
, "no_tbook")) {
614 /* Disable UCT opening tbook. */
616 } else if (!strcasecmp(optname
, "pass_all_alive")) {
617 /* Whether to consider passing only after all
618 * dead groups were removed from the board;
619 * this is like all genmoves are in fact
620 * kgs-genmove_cleanup. */
621 u
->pass_all_alive
= !optval
|| atoi(optval
);
622 } else if (!strcasecmp(optname
, "territory_scoring")) {
623 /* Use territory scoring (default is area scoring).
624 * An explicit kgs-rules command overrides this. */
625 u
->territory_scoring
= !optval
|| atoi(optval
);
626 } else if (!strcasecmp(optname
, "stones_only")) {
627 /* Do not count eyes. Nice to teach go to kids.
628 * http://strasbourg.jeudego.org/regle_strasbourgeoise.htm */
629 b
->rules
= RULES_STONES_ONLY
;
630 u
->pass_all_alive
= true;
631 } else if (!strcasecmp(optname
, "banner") && optval
) {
632 /* Additional banner string. This must come as the
633 * last engine parameter. */
634 if (*next
) *--next
= ',';
635 u
->banner
= strdup(optval
);
637 } else if (!strcasecmp(optname
, "plugin") && optval
) {
638 /* Load an external plugin; filename goes before the colon,
639 * extra arguments after the colon. */
640 char *pluginarg
= strchr(optval
, ':');
643 plugin_load(u
->plugins
, optval
, pluginarg
);
645 /** UCT behavior and policies */
647 } else if ((!strcasecmp(optname
, "policy")
648 /* Node selection policy. ucb1amaf is the
649 * default policy implementing RAVE, while
650 * ucb1 is the simple exploration/exploitation
651 * policy. Policies can take further extra
653 || !strcasecmp(optname
, "random_policy")) && optval
) {
654 /* A policy to be used randomly with small
655 * chance instead of the default policy. */
656 char *policyarg
= strchr(optval
, ':');
657 struct uct_policy
**p
= !strcasecmp(optname
, "policy") ? &u
->policy
: &u
->random_policy
;
660 if (!strcasecmp(optval
, "ucb1")) {
661 *p
= policy_ucb1_init(u
, policyarg
);
662 } else if (!strcasecmp(optval
, "ucb1amaf")) {
663 *p
= policy_ucb1amaf_init(u
, policyarg
, b
);
665 fprintf(stderr
, "UCT: Invalid tree policy %s\n", optval
);
668 } else if (!strcasecmp(optname
, "playout") && optval
) {
669 /* Random simulation (playout) policy.
670 * moggy is the default policy with large
671 * amount of domain-specific knowledge and
672 * heuristics. light is a simple uniformly
673 * random move selection policy. */
674 char *playoutarg
= strchr(optval
, ':');
677 if (!strcasecmp(optval
, "moggy")) {
678 u
->playout
= playout_moggy_init(playoutarg
, b
, u
->jdict
);
679 } else if (!strcasecmp(optval
, "light")) {
680 u
->playout
= playout_light_init(playoutarg
, b
);
682 fprintf(stderr
, "UCT: Invalid playout policy %s\n", optval
);
685 } else if (!strcasecmp(optname
, "prior") && optval
) {
686 /* Node priors policy. When expanding a node,
687 * it will seed node values heuristically
688 * (most importantly, based on playout policy
689 * opinion, but also with regard to other
690 * things). See uct/prior.c for details.
691 * Use prior=eqex=0 to disable priors. */
692 u
->prior
= uct_prior_init(optval
, b
);
693 } else if (!strcasecmp(optname
, "mercy") && optval
) {
694 /* Minimal difference of black/white captures
695 * to stop playout - "Mercy Rule". Speeds up
696 * hopeless playouts at the expense of some
698 u
->mercymin
= atoi(optval
);
699 } else if (!strcasecmp(optname
, "gamelen") && optval
) {
700 /* Maximum length of single simulation
702 u
->gamelen
= atoi(optval
);
703 } else if (!strcasecmp(optname
, "expand_p") && optval
) {
704 /* Expand UCT nodes after it has been
705 * visited this many times. */
706 u
->expand_p
= atoi(optval
);
707 } else if (!strcasecmp(optname
, "random_policy_chance") && optval
) {
708 /* If specified (N), with probability 1/N, random_policy policy
709 * descend is used instead of main policy descend; useful
710 * if specified policy (e.g. UCB1AMAF) can make unduly biased
711 * choices sometimes, you can fall back to e.g.
712 * random_policy=UCB1. */
713 u
->random_policy_chance
= atoi(optval
);
715 /** General AMAF behavior */
716 /* (Only relevant if the policy supports AMAF.
717 * More variables can be tuned as policy
720 } else if (!strcasecmp(optname
, "playout_amaf")) {
721 /* Whether to include random playout moves in
722 * AMAF as well. (Otherwise, only tree moves
723 * are included in AMAF. Of course makes sense
724 * only in connection with an AMAF policy.) */
725 /* with-without: 55.5% (+-4.1) */
726 if (optval
&& *optval
== '0')
727 u
->playout_amaf
= false;
729 u
->playout_amaf
= true;
730 } else if (!strcasecmp(optname
, "playout_amaf_cutoff") && optval
) {
731 /* Keep only first N% of playout stage AMAF
733 u
->playout_amaf_cutoff
= atoi(optval
);
734 } else if (!strcasecmp(optname
, "amaf_prior") && optval
) {
735 /* In node policy, consider prior values
736 * part of the real result term or part
737 * of the AMAF term? */
738 u
->amaf_prior
= atoi(optval
);
740 /** Performance and memory management */
742 } else if (!strcasecmp(optname
, "threads") && optval
) {
743 /* By default, Pachi will run with only single
744 * tree search thread! */
745 u
->threads
= atoi(optval
);
746 } else if (!strcasecmp(optname
, "thread_model") && optval
) {
747 if (!strcasecmp(optval
, "tree")) {
748 /* Tree parallelization - all threads
749 * grind on the same tree. */
750 u
->thread_model
= TM_TREE
;
752 } else if (!strcasecmp(optval
, "treevl")) {
753 /* Tree parallelization, but also
754 * with virtual losses - this discou-
755 * rages most threads choosing the
756 * same tree branches to read. */
757 u
->thread_model
= TM_TREEVL
;
759 fprintf(stderr
, "UCT: Invalid thread model %s\n", optval
);
762 } else if (!strcasecmp(optname
, "virtual_loss")) {
763 /* Number of virtual losses added before evaluating a node. */
764 u
->virtual_loss
= !optval
|| atoi(optval
);
765 } else if (!strcasecmp(optname
, "pondering")) {
766 /* Keep searching even during opponent's turn. */
767 u
->pondering_opt
= !optval
|| atoi(optval
);
768 } else if (!strcasecmp(optname
, "max_tree_size") && optval
) {
769 /* Maximum amount of memory [MiB] consumed by the move tree.
770 * For fast_alloc it includes the temp tree used for pruning.
771 * Default is 3072 (3 GiB). */
772 u
->max_tree_size
= atol(optval
) * 1048576;
773 } else if (!strcasecmp(optname
, "fast_alloc")) {
774 u
->fast_alloc
= !optval
|| atoi(optval
);
775 } else if (!strcasecmp(optname
, "pruning_threshold") && optval
) {
776 /* Force pruning at beginning of a move if the tree consumes
777 * more than this [MiB]. Default is 10% of max_tree_size.
778 * Increase to reduce pruning time overhead if memory is plentiful.
779 * This option is meaningful only for fast_alloc. */
780 u
->pruning_threshold
= atol(optval
) * 1048576;
784 } else if (!strcasecmp(optname
, "best2_ratio") && optval
) {
785 /* If set, prolong simulating while
786 * first_best/second_best playouts ratio
787 * is less than best2_ratio. */
788 u
->best2_ratio
= atof(optval
);
789 } else if (!strcasecmp(optname
, "bestr_ratio") && optval
) {
790 /* If set, prolong simulating while
791 * best,best_best_child values delta
792 * is more than bestr_ratio. */
793 u
->bestr_ratio
= atof(optval
);
794 } else if (!strcasecmp(optname
, "max_maintime_ratio") && optval
) {
795 /* If set and while not in byoyomi, prolong simulating no more than
796 * max_maintime_ratio times the normal desired thinking time. */
797 u
->max_maintime_ratio
= atof(optval
);
798 } else if (!strcasecmp(optname
, "fuseki_end") && optval
) {
799 /* At the very beginning it's not worth thinking
800 * too long because the playout evaluations are
801 * very noisy. So gradually increase the thinking
802 * time up to maximum when fuseki_end percent
803 * of the board has been played.
804 * This only applies if we are not in byoyomi. */
805 u
->fuseki_end
= atoi(optval
);
806 } else if (!strcasecmp(optname
, "yose_start") && optval
) {
807 /* When yose_start percent of the board has been
808 * played, or if we are in byoyomi, stop spending
809 * more time and spread the remaining time
811 * Between fuseki_end and yose_start, we spend
812 * a constant proportion of the remaining time
813 * on each move. (yose_start should actually
814 * be much earlier than when real yose start,
815 * but "yose" is a good short name to convey
817 u
->yose_start
= atoi(optval
);
821 } else if (!strcasecmp(optname
, "dynkomi") && optval
) {
822 /* Dynamic komi approach; there are multiple
823 * ways to adjust komi dynamically throughout
824 * play. We currently support two: */
825 char *dynkomiarg
= strchr(optval
, ':');
828 if (!strcasecmp(optval
, "none")) {
829 u
->dynkomi
= uct_dynkomi_init_none(u
, dynkomiarg
, b
);
830 } else if (!strcasecmp(optval
, "linear")) {
831 /* You should set dynkomi_mask=1 or a very low
832 * handicap_value for white. */
833 u
->dynkomi
= uct_dynkomi_init_linear(u
, dynkomiarg
, b
);
834 } else if (!strcasecmp(optval
, "adaptive")) {
835 /* There are many more knobs to
836 * crank - see uct/dynkomi.c. */
837 u
->dynkomi
= uct_dynkomi_init_adaptive(u
, dynkomiarg
, b
);
839 fprintf(stderr
, "UCT: Invalid dynkomi mode %s\n", optval
);
842 } else if (!strcasecmp(optname
, "dynkomi_mask") && optval
) {
843 /* Bitmask of colors the player must be
844 * for dynkomi be applied; the default dynkomi_mask=3 allows
845 * dynkomi even in games where Pachi is white. */
846 u
->dynkomi_mask
= atoi(optval
);
847 } else if (!strcasecmp(optname
, "dynkomi_interval") && optval
) {
848 /* If non-zero, re-adjust dynamic komi
849 * throughout a single genmove reading,
850 * roughly every N simulations. */
851 /* XXX: Does not work with tree
852 * parallelization. */
853 u
->dynkomi_interval
= atoi(optval
);
855 /** Node value result scaling */
857 } else if (!strcasecmp(optname
, "val_scale") && optval
) {
858 /* How much of the game result value should be
859 * influenced by win size. Zero means it isn't. */
860 u
->val_scale
= atof(optval
);
861 } else if (!strcasecmp(optname
, "val_points") && optval
) {
862 /* Maximum size of win to be scaled into game
863 * result value. Zero means boardsize^2. */
864 u
->val_points
= atoi(optval
) * 2; // result values are doubled
865 } else if (!strcasecmp(optname
, "val_extra")) {
866 /* If false, the score coefficient will be simply
867 * added to the value, instead of scaling the result
868 * coefficient because of it. */
869 u
->val_extra
= !optval
|| atoi(optval
);
872 /* (Purely experimental. Does not work - yet!) */
874 } else if (!strcasecmp(optname
, "local_tree")) {
875 /* Whether to bias exploration by local tree values. */
876 u
->local_tree
= !optval
|| atoi(optval
);
877 } else if (!strcasecmp(optname
, "tenuki_d") && optval
) {
878 /* Tenuki distance at which to break the local tree. */
879 u
->tenuki_d
= atoi(optval
);
880 if (u
->tenuki_d
> TREE_NODE_D_MAX
+ 1) {
881 fprintf(stderr
, "uct: tenuki_d must not be larger than TREE_NODE_D_MAX+1 %d\n", TREE_NODE_D_MAX
+ 1);
884 } else if (!strcasecmp(optname
, "local_tree_aging") && optval
) {
885 /* How much to reduce local tree values between moves. */
886 u
->local_tree_aging
= atof(optval
);
887 } else if (!strcasecmp(optname
, "local_tree_depth_decay") && optval
) {
888 /* With value x>0, during the descent the node
889 * contributes 1/x^depth playouts in
890 * the local tree. I.e., with x>1, nodes more
891 * distant from local situation contribute more
892 * than nodes near the root. */
893 u
->local_tree_depth_decay
= atof(optval
);
894 } else if (!strcasecmp(optname
, "local_tree_allseq")) {
895 /* If disabled, only complete sequences are stored
896 * in the local tree. If this is on, also
897 * subsequences starting at each move are stored. */
898 u
->local_tree_allseq
= !optval
|| atoi(optval
);
899 } else if (!strcasecmp(optname
, "local_tree_neival")) {
900 /* If disabled, local node value is not
901 * computed just based on terminal status
902 * of the coordinate, but also its neighbors. */
903 u
->local_tree_neival
= !optval
|| atoi(optval
);
904 } else if (!strcasecmp(optname
, "local_tree_eval")) {
905 /* How is the value inserted in the local tree
907 if (!strcasecmp(optval
, "root"))
908 /* All moves within a tree branch are
909 * considered wrt. their merit
910 * reaching tachtical goal of making
911 * the first move in the branch
913 u
->local_tree_eval
= LTE_ROOT
;
914 else if (!strcasecmp(optval
, "each"))
915 /* Each move is considered wrt.
916 * its own survival. */
917 u
->local_tree_eval
= LTE_EACH
;
918 else if (!strcasecmp(optval
, "total"))
919 /* The tactical goal is the survival
920 * of all the moves of my color and
921 * non-survival of all the opponent
922 * moves. Local values (and their
923 * inverses) are averaged. */
924 u
->local_tree_eval
= LTE_TOTAL
;
926 fprintf(stderr
, "uct: unknown local_tree_eval %s\n", optval
);
929 } else if (!strcasecmp(optname
, "local_tree_rootchoose")) {
930 /* If disabled, only moves within the local
931 * tree branch are considered; the values
932 * of the branch roots (i.e. root children)
933 * are ignored. This may make sense together
934 * with eval!=each, we consider only moves
935 * that influence the goal, not the "rating"
936 * of the goal itself. (The real solution
937 * will be probably using criticality to pick
938 * local tree branches.) */
939 u
->local_tree_rootchoose
= !optval
|| atoi(optval
);
941 /** Other heuristics */
942 } else if (!strcasecmp(optname
, "significant_threshold") && optval
) {
943 /* Some heuristics (XXX: none in mainline) rely
944 * on the knowledge of the last "significant"
945 * node in the descent. Such a node is
946 * considered reasonably trustworthy to carry
947 * some meaningful information in the values
948 * of the node and its children. */
949 u
->significant_threshold
= atoi(optval
);
951 /** Distributed engine slaves setup */
953 } else if (!strcasecmp(optname
, "slave")) {
954 /* Act as slave for the distributed engine. */
955 u
->slave
= !optval
|| atoi(optval
);
956 } else if (!strcasecmp(optname
, "slave_index") && optval
) {
957 /* Optional index if per-slave behavior is desired.
958 * Must be given as index/max */
959 u
->slave_index
= atoi(optval
);
960 char *p
= strchr(optval
, '/');
961 if (p
) u
->max_slaves
= atoi(++p
);
962 } else if (!strcasecmp(optname
, "shared_nodes") && optval
) {
963 /* Share at most shared_nodes between master and slave at each genmoves.
964 * Must use the same value in master and slaves. */
965 u
->shared_nodes
= atoi(optval
);
966 } else if (!strcasecmp(optname
, "shared_levels") && optval
) {
967 /* Share only nodes of level <= shared_levels. */
968 u
->shared_levels
= atoi(optval
);
969 } else if (!strcasecmp(optname
, "stats_hbits") && optval
) {
970 /* Set hash table size to 2^stats_hbits for the shared stats. */
971 u
->stats_hbits
= atoi(optval
);
972 } else if (!strcasecmp(optname
, "stats_delay") && optval
) {
973 /* How long to wait in slave for initial stats to build up before
974 * replying to the genmoves command (in ms) */
975 u
->stats_delay
= 0.001 * atof(optval
);
978 fprintf(stderr
, "uct: Invalid engine argument %s or missing value\n", optname
);
985 u
->policy
= policy_ucb1amaf_init(u
, NULL
, b
);
987 if (!!u
->random_policy_chance
^ !!u
->random_policy
) {
988 fprintf(stderr
, "uct: Only one of random_policy and random_policy_chance is set\n");
992 if (!u
->local_tree
) {
993 /* No ltree aging. */
994 u
->local_tree_aging
= 1.0f
;
998 if (u
->pruning_threshold
< u
->max_tree_size
/ 10)
999 u
->pruning_threshold
= u
->max_tree_size
/ 10;
1000 if (u
->pruning_threshold
> u
->max_tree_size
/ 2)
1001 u
->pruning_threshold
= u
->max_tree_size
/ 2;
1003 /* Limit pruning temp space to 20% of memory. Beyond this we discard
1004 * the nodes and recompute them at the next move if necessary. */
1005 u
->max_pruned_size
= u
->max_tree_size
/ 5;
1006 u
->max_tree_size
-= u
->max_pruned_size
;
1008 /* Reserve 5% memory in case the background free() are slower
1009 * than the concurrent allocations. */
1010 u
->max_tree_size
-= u
->max_tree_size
/ 20;
1014 u
->prior
= uct_prior_init(NULL
, b
);
1017 u
->playout
= playout_moggy_init(NULL
, b
, u
->jdict
);
1018 if (!u
->playout
->debug_level
)
1019 u
->playout
->debug_level
= u
->debug_level
;
1021 u
->ownermap
.map
= malloc2(board_size2(b
) * sizeof(u
->ownermap
.map
[0]));
1024 if (!u
->stats_hbits
) u
->stats_hbits
= DEFAULT_STATS_HBITS
;
1025 if (!u
->shared_nodes
) u
->shared_nodes
= DEFAULT_SHARED_NODES
;
1026 assert(u
->shared_levels
* board_bits2(b
) <= 8 * (int)sizeof(path_t
));
1030 u
->dynkomi
= uct_dynkomi_init_linear(u
, NULL
, b
);
1032 /* Some things remain uninitialized for now - the opening tbook
1033 * is not loaded and the tree not set up. */
1034 /* This will be initialized in setup_state() at the first move
1035 * received/requested. This is because right now we are not aware
1036 * about any komi or handicap setup and such. */
1042 engine_uct_init(char *arg
, struct board
*b
)
1044 struct uct
*u
= uct_state_init(arg
, b
);
1045 struct engine
*e
= calloc2(1, sizeof(struct engine
));
1046 e
->name
= "UCT Engine";
1047 e
->printhook
= uct_printhook_ownermap
;
1048 e
->notify_play
= uct_notify_play
;
1051 e
->result
= uct_result
;
1052 e
->genmove
= uct_genmove
;
1053 e
->genmoves
= uct_genmoves
;
1054 e
->dead_group_list
= uct_dead_group_list
;
1058 e
->notify
= uct_notify
;
1060 const char banner
[] = "I'm playing UCT. When I'm losing, I will resign, "
1061 "if I think I win, I play until you pass. "
1062 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
1063 if (!u
->banner
) u
->banner
= "";
1064 e
->comment
= malloc2(sizeof(banner
) + strlen(u
->banner
) + 1);
1065 sprintf(e
->comment
, "%s %s", banner
, u
->banner
);