18 #include "playout/elo.h"
19 #include "playout/moggy.h"
20 #include "playout/light.h"
24 #include "uct/internal.h"
25 #include "uct/prior.h"
30 struct uct_policy
*policy_ucb1_init(struct uct
*u
, char *arg
);
31 struct uct_policy
*policy_ucb1amaf_init(struct uct
*u
, char *arg
);
32 static void uct_pondering_stop(struct uct
*u
);
35 /* Default number of simulations to perform per move.
36 * Note that this is now in total over all threads! (Unless TM_ROOT.) */
37 #define MC_GAMES 80000
38 #define MC_GAMELEN MAX_GAMELEN
39 static const struct time_info default_ti
= {
42 .len
= { .games
= MC_GAMES
},
45 /* How big proportion of ownermap counts must be of one color to consider
48 /* How many games to consider at minimum before judging groups. */
49 #define GJ_MINGAMES 500
51 /* How often to inspect the tree from the main thread to check for playout
52 * stop, progress reports, etc. (in seconds) */
53 #define TREE_BUSYWAIT_INTERVAL 0.1 /* 100ms */
55 /* Once per how many simulations (per thread) to show a progress report line. */
56 #define TREE_SIMPROGRESS_INTERVAL 10000
58 /* When terminating uct_search() early, the safety margin to add to the
59 * remaining playout number estimate when deciding whether the result can
61 #define PLAYOUT_DELTA_SAFEMARGIN 1000
65 setup_state(struct uct
*u
, struct board
*b
, enum stone color
)
67 u
->t
= tree_init(b
, color
, u
->fast_alloc
? u
->max_tree_size
: 0, u
->local_tree_aging
);
69 fast_srandom(u
->force_seed
);
71 fprintf(stderr
, "Fresh board with random seed %lu\n", fast_getseed());
72 //board_print(b, stderr);
73 if (!u
->no_book
&& b
->moves
== 0) {
74 assert(color
== S_BLACK
);
80 reset_state(struct uct
*u
)
83 tree_done(u
->t
); u
->t
= NULL
;
87 setup_dynkomi(struct uct
*u
, struct board
*b
, enum stone to_play
)
89 if (u
->dynkomi
> b
->moves
&& u
->t
->use_extra_komi
)
90 u
->t
->extra_komi
= uct_get_extra_komi(u
, b
);
96 prepare_move(struct engine
*e
, struct board
*b
, enum stone color
)
98 struct uct
*u
= e
->data
;
101 /* Verify that we have sane state. */
103 assert(u
->t
&& b
->moves
);
104 if (color
!= stone_other(u
->t
->root_color
)) {
105 fprintf(stderr
, "Fatal: Non-alternating play detected %d %d\n",
106 color
, u
->t
->root_color
);
111 /* We need fresh state. */
113 setup_state(u
, b
, color
);
116 u
->ownermap
.playouts
= 0;
117 memset(u
->ownermap
.map
, 0, board_size2(b
) * sizeof(u
->ownermap
.map
[0]));
121 dead_group_list(struct uct
*u
, struct board
*b
, struct move_queue
*mq
)
123 struct group_judgement gj
;
125 gj
.gs
= alloca(board_size2(b
) * sizeof(gj
.gs
[0]));
126 board_ownermap_judge_group(b
, &u
->ownermap
, &gj
);
127 groups_of_status(b
, &gj
, GS_DEAD
, mq
);
131 uct_pass_is_safe(struct uct
*u
, struct board
*b
, enum stone color
, bool pass_all_alive
)
133 if (u
->ownermap
.playouts
< GJ_MINGAMES
)
136 struct move_queue mq
= { .moves
= 0 };
138 dead_group_list(u
, b
, &mq
);
139 return pass_is_safe(b
, color
, &mq
);
144 uct_printhook_ownermap(struct board
*board
, coord_t c
, FILE *f
)
146 struct uct
*u
= board
->es
;
148 const char chr
[] = ":XO,"; // dame, black, white, unclear
149 const char chm
[] = ":xo,";
150 char ch
= chr
[board_ownermap_judge_point(&u
->ownermap
, c
, GJ_THRES
)];
151 if (ch
== ',') { // less precise estimate then?
152 ch
= chm
[board_ownermap_judge_point(&u
->ownermap
, c
, 0.67)];
154 fprintf(f
, "%c ", ch
);
158 uct_notify_play(struct engine
*e
, struct board
*b
, struct move
*m
)
160 struct uct
*u
= e
->data
;
162 /* No state, create one - this is probably game beginning
163 * and we need to load the opening book right now. */
164 prepare_move(e
, b
, m
->color
);
168 /* Stop pondering. */
169 /* XXX: If we are about to receive multiple 'play' commands,
170 * e.g. in a rengo, we will not ponder during the rest of them. */
171 uct_pondering_stop(u
);
173 if (is_resign(m
->coord
)) {
179 /* Promote node of the appropriate move to the tree root. */
181 if (!tree_promote_at(u
->t
, b
, m
->coord
)) {
183 fprintf(stderr
, "Warning: Cannot promote move node! Several play commands in row?\n");
187 /* Setting up dynkomi is not necessary here, probably, but we
188 * better do it anyway for consistency reasons. */
189 setup_dynkomi(u
, b
, stone_other(m
->color
));
194 uct_chat(struct engine
*e
, struct board
*b
, char *cmd
)
196 struct uct
*u
= e
->data
;
197 static char reply
[1024];
199 cmd
+= strspn(cmd
, " \n\t");
200 if (!strncasecmp(cmd
, "winrate", 7)) {
202 return "no game context (yet?)";
203 enum stone color
= u
->t
->root_color
;
204 struct tree_node
*n
= u
->t
->root
;
205 snprintf(reply
, 1024, "In %d playouts at %d threads, %s %s can win with %.2f%% probability",
206 n
->u
.playouts
, u
->threads
, stone2str(color
), coord2sstr(n
->coord
, b
),
207 tree_node_get_value(u
->t
, -1, n
->u
.value
) * 100);
208 if (u
->t
->use_extra_komi
&& abs(u
->t
->extra_komi
) >= 0.5) {
209 sprintf(reply
+ strlen(reply
), ", while self-imposing extra komi %.1f",
219 uct_dead_group_list(struct engine
*e
, struct board
*b
, struct move_queue
*mq
)
221 struct uct
*u
= e
->data
;
223 /* This means the game is probably over, no use pondering on. */
224 uct_pondering_stop(u
);
226 if (u
->pass_all_alive
)
227 return; // no dead groups
229 bool mock_state
= false;
232 /* No state, but we cannot just back out - we might
233 * have passed earlier, only assuming some stones are
234 * dead, and then re-connected, only to lose counting
235 * when all stones are assumed alive. */
236 /* Mock up some state and seed the ownermap by few
238 prepare_move(e
, b
, S_BLACK
); assert(u
->t
);
239 for (int i
= 0; i
< GJ_MINGAMES
; i
++)
240 uct_playout(u
, b
, S_BLACK
, u
->t
);
244 dead_group_list(u
, b
, mq
);
247 /* Clean up the mock state in case we will receive
248 * a genmove; we could get a non-alternating-move
249 * error from prepare_move() in that case otherwise. */
255 playout_policy_done(struct playout_policy
*p
)
257 if (p
->done
) p
->done(p
);
258 if (p
->data
) free(p
->data
);
263 uct_done(struct engine
*e
)
265 /* This is called on engine reset, especially when clear_board
266 * is received and new game should begin. */
267 struct uct
*u
= e
->data
;
268 uct_pondering_stop(u
);
269 if (u
->t
) reset_state(u
);
270 free(u
->ownermap
.map
);
273 free(u
->random_policy
);
274 playout_policy_done(u
->playout
);
275 uct_prior_done(u
->prior
);
279 /* Pachi threading structure (if uct_playouts_parallel() is used):
282 * | main(), GTP communication, ...
283 * | starts and stops the search managed by thread_manager
286 * | spawns and collects worker threads
292 * uct_playouts() loop, doing descend-playout until uct_halt
294 * Another way to look at it is by functions (lines denote thread boundaries):
297 * | uct_search() (uct_search_start() .. uct_search_stop())
298 * | -----------------------
299 * | spawn_thread_manager()
300 * | -----------------------
302 * V uct_playouts() */
304 /* Set in thread manager in case the workers should stop. */
305 volatile sig_atomic_t uct_halt
= 0;
306 /* ID of the running worker thread. */
307 __thread
int thread_id
= -1;
308 /* ID of the thread manager. */
309 static pthread_t thread_manager
;
310 static bool thread_manager_running
;
312 static pthread_mutex_t finish_mutex
= PTHREAD_MUTEX_INITIALIZER
;
313 static pthread_cond_t finish_cond
= PTHREAD_COND_INITIALIZER
;
314 static volatile int finish_thread
;
315 static pthread_mutex_t finish_serializer
= PTHREAD_MUTEX_INITIALIZER
;
328 spawn_worker(void *ctx_
)
330 struct spawn_ctx
*ctx
= ctx_
;
332 fast_srandom(ctx
->seed
);
333 thread_id
= ctx
->tid
;
335 ctx
->games
= uct_playouts(ctx
->u
, ctx
->b
, ctx
->color
, ctx
->t
);
337 pthread_mutex_lock(&finish_serializer
);
338 pthread_mutex_lock(&finish_mutex
);
339 finish_thread
= ctx
->tid
;
340 pthread_cond_signal(&finish_cond
);
341 pthread_mutex_unlock(&finish_mutex
);
345 /* Thread manager, controlling worker threads. It must be called with
346 * finish_mutex lock held, but it will unlock it itself before exiting;
347 * this is necessary to be completely deadlock-free. */
348 /* The finish_cond can be signalled for it to stop; in that case,
349 * the caller should set finish_thread = -1. */
350 /* After it is started, it will update mctx->t to point at some tree
351 * used for the actual search (matters only for TM_ROOT), on return
352 * it will set mctx->games to the number of performed simulations. */
354 spawn_thread_manager(void *ctx_
)
356 /* In thread_manager, we use only some of the ctx fields. */
357 struct spawn_ctx
*mctx
= ctx_
;
358 struct uct
*u
= mctx
->u
;
359 struct tree
*t
= mctx
->t
;
360 bool shared_tree
= u
->parallel_tree
;
361 fast_srandom(mctx
->seed
);
363 int played_games
= 0;
364 pthread_t threads
[u
->threads
];
369 /* Garbage collect the tree by preference when pondering. */
370 if (u
->pondering
&& t
->nodes
&& t
->nodes_size
> t
->max_tree_size
/2) {
371 unsigned long temp_size
= (MIN_FREE_MEM_PERCENT
* t
->max_tree_size
) / 100;
372 t
->root
= tree_garbage_collect(t
, temp_size
, t
->root
);
375 /* Spawn threads... */
376 for (int ti
= 0; ti
< u
->threads
; ti
++) {
377 struct spawn_ctx
*ctx
= malloc(sizeof(*ctx
));
378 ctx
->u
= u
; ctx
->b
= mctx
->b
; ctx
->color
= mctx
->color
;
379 mctx
->t
= ctx
->t
= shared_tree
? t
: tree_copy(t
);
380 ctx
->tid
= ti
; ctx
->seed
= fast_random(65536) + ti
;
381 pthread_create(&threads
[ti
], NULL
, spawn_worker
, ctx
);
383 fprintf(stderr
, "Spawned worker %d\n", ti
);
386 /* ...and collect them back: */
387 while (joined
< u
->threads
) {
388 /* Wait for some thread to finish... */
389 pthread_cond_wait(&finish_cond
, &finish_mutex
);
390 if (finish_thread
< 0) {
391 /* Stop-by-caller. Tell the workers to wrap up. */
395 /* ...and gather its remnants. */
396 struct spawn_ctx
*ctx
;
397 pthread_join(threads
[finish_thread
], (void **) &ctx
);
398 played_games
+= ctx
->games
;
401 if (ctx
->t
== mctx
->t
) mctx
->t
= t
;
402 tree_merge(t
, ctx
->t
);
407 fprintf(stderr
, "Joined worker %d\n", finish_thread
);
408 pthread_mutex_unlock(&finish_serializer
);
411 pthread_mutex_unlock(&finish_mutex
);
414 tree_normalize(mctx
->t
, u
->threads
);
416 mctx
->games
= played_games
;
420 static struct spawn_ctx
*
421 uct_search_start(struct uct
*u
, struct board
*b
, enum stone color
, struct tree
*t
)
423 assert(u
->threads
> 0);
424 assert(!thread_manager_running
);
426 struct spawn_ctx ctx
= { .u
= u
, .b
= b
, .color
= color
, .t
= t
, .seed
= fast_random(65536) };
427 static struct spawn_ctx mctx
; mctx
= ctx
;
428 pthread_mutex_lock(&finish_mutex
);
429 pthread_create(&thread_manager
, NULL
, spawn_thread_manager
, &mctx
);
430 thread_manager_running
= true;
434 static struct spawn_ctx
*
435 uct_search_stop(void)
437 assert(thread_manager_running
);
439 /* Signal thread manager to stop the workers. */
440 pthread_mutex_lock(&finish_mutex
);
442 pthread_cond_signal(&finish_cond
);
443 pthread_mutex_unlock(&finish_mutex
);
445 /* Collect the thread manager. */
446 struct spawn_ctx
*pctx
;
447 thread_manager_running
= false;
448 pthread_join(thread_manager
, (void **) &pctx
);
453 /* Determine whether we should terminate the search early. */
455 uct_search_stop_early(struct uct
*u
, struct tree
*t
, struct board
*b
,
456 struct time_info
*ti
, struct time_stop
*stop
,
457 struct tree_node
*best
, struct tree_node
*best2
,
458 int base_playouts
, int i
)
460 /* Early break in won situation. */
461 if (best
->u
.playouts
>= 2000 && tree_node_get_value(t
, 1, best
->u
.value
) >= u
->loss_threshold
)
463 /* Earlier break in super-won situation. */
464 if (best
->u
.playouts
>= 500 && tree_node_get_value(t
, 1, best
->u
.value
) >= 0.95)
467 /* Break early if we estimate the second-best move cannot
468 * catch up in assigned time anymore. We use all our time
469 * if we are in byoyomi with single stone remaining in our
470 * period, however - it's better to pre-ponder. */
471 bool time_indulgent
= (!ti
->len
.t
.main_time
&& ti
->len
.t
.byoyomi_stones
== 1);
472 if (best2
&& ti
->dim
== TD_WALLTIME
&& !time_indulgent
) {
473 double elapsed
= time_now() - ti
->len
.t
.timer_start
;
474 double remaining
= stop
->worst
.time
- elapsed
;
475 double pps
= ((double)i
- base_playouts
) / elapsed
;
476 double estplayouts
= remaining
* pps
+ PLAYOUT_DELTA_SAFEMARGIN
;
477 if (best
->u
.playouts
> best2
->u
.playouts
+ estplayouts
) {
479 fprintf(stderr
, "Early stop, result cannot change: "
480 "best %d, best2 %d, estimated %f simulations to go\n",
481 best
->u
.playouts
, best2
->u
.playouts
, estplayouts
);
489 /* Determine whether we should terminate the search later. */
491 uct_search_keep_looking(struct uct
*u
, struct tree
*t
, struct board
*b
,
492 struct tree_node
*best
, struct tree_node
*best2
,
493 struct tree_node
*bestr
, struct tree_node
*winner
, int i
)
497 fprintf(stderr
, "Did not find best move, still trying...\n");
501 if (u
->best2_ratio
> 0) {
502 /* Check best/best2 simulations ratio. If the
503 * two best moves give very similar results,
504 * keep simulating. */
505 if (best2
&& best2
->u
.playouts
506 && (double)best
->u
.playouts
/ best2
->u
.playouts
< u
->best2_ratio
) {
508 fprintf(stderr
, "Best2 ratio %f < threshold %f\n",
509 (double)best
->u
.playouts
/ best2
->u
.playouts
,
515 if (u
->bestr_ratio
> 0) {
516 /* Check best, best_best value difference. If the best move
517 * and its best child do not give similar enough results,
518 * keep simulating. */
519 if (bestr
&& bestr
->u
.playouts
520 && fabs((double)best
->u
.value
- bestr
->u
.value
) > u
->bestr_ratio
) {
522 fprintf(stderr
, "Bestr delta %f > threshold %f\n",
523 fabs((double)best
->u
.value
- bestr
->u
.value
),
529 if (winner
&& winner
!= best
) {
530 /* Keep simulating if best explored
531 * does not have also highest value. */
533 fprintf(stderr
, "[%d] best %3s [%d] %f != winner %3s [%d] %f\n", i
,
534 coord2sstr(best
->coord
, t
->board
),
535 best
->u
.playouts
, tree_node_get_value(t
, 1, best
->u
.value
),
536 coord2sstr(winner
->coord
, t
->board
),
537 winner
->u
.playouts
, tree_node_get_value(t
, 1, winner
->u
.value
));
541 /* No reason to keep simulating, bye. */
545 /* Run time-limited MCTS search on foreground. */
547 uct_search(struct uct
*u
, struct board
*b
, struct time_info
*ti
, enum stone color
, struct tree
*t
)
549 int base_playouts
= u
->t
->root
->u
.playouts
;
550 if (UDEBUGL(2) && base_playouts
> 0)
551 fprintf(stderr
, "<pre-simulated %d games skipped>\n", base_playouts
);
553 /* Set up time conditions. */
554 if (ti
->period
== TT_NULL
) *ti
= default_ti
;
555 struct time_stop stop
;
556 time_stop_conditions(ti
, b
, u
->fuseki_end
, u
->yose_start
, &stop
);
558 /* Number of last game with progress print. */
559 int last_print
= t
->root
->u
.playouts
;
560 /* Number of simulations to wait before next print. */
561 int print_interval
= TREE_SIMPROGRESS_INTERVAL
* (u
->thread_model
== TM_ROOT
? 1 : u
->threads
);
562 /* Printed notification about full memory? */
563 bool print_fullmem
= false;
565 struct spawn_ctx
*ctx
= uct_search_start(u
, b
, color
, t
);
567 /* The search tree is ctx->t. This is normally == t, but in case of
568 * TM_ROOT, it is one of the trees belonging to the independent
569 * workers. It is important to reference ctx->t directly since the
570 * thread manager will swap the tree pointer asynchronously. */
571 /* XXX: This means TM_ROOT support is suboptimal since single stalled
572 * thread can stall the others in case of limiting the search by game
573 * count. However, TM_ROOT just does not deserve any more extra code
576 struct tree_node
*best
= NULL
;
577 struct tree_node
*best2
= NULL
; // Second-best move.
578 struct tree_node
*bestr
= NULL
; // best's best child.
579 struct tree_node
*winner
= NULL
;
581 double busywait_interval
= TREE_BUSYWAIT_INTERVAL
;
583 /* Now, just periodically poll the search tree. */
585 time_sleep(busywait_interval
);
586 /* busywait_interval should never be less than desired time, or the
587 * time control is broken. But if it happens to be less, we still search
588 * at least 100ms otherwise the move is completely random. */
590 int i
= ctx
->t
->root
->u
.playouts
;
592 /* Print progress? */
593 if (i
- last_print
> print_interval
) {
594 last_print
+= print_interval
; // keep the numbers tidy
595 uct_progress_status(u
, ctx
->t
, color
, last_print
);
597 if (!print_fullmem
&& ctx
->t
->nodes_size
> u
->max_tree_size
) {
599 fprintf(stderr
, "memory limit hit (%lu > %lu)\n", ctx
->t
->nodes_size
, u
->max_tree_size
);
600 print_fullmem
= true;
603 best
= u
->policy
->choose(u
->policy
, ctx
->t
->root
, b
, color
, resign
);
604 if (best
) best2
= u
->policy
->choose(u
->policy
, ctx
->t
->root
, b
, color
, best
->coord
);
606 /* Possibly stop search early if it's no use to try on. */
607 if (best
&& uct_search_stop_early(u
, ctx
->t
, b
, ti
, &stop
, best
, best2
, base_playouts
, i
))
610 /* Check against time settings. */
611 bool desired_done
= false;
612 if (ti
->dim
== TD_WALLTIME
) {
613 double elapsed
= time_now() - ti
->len
.t
.timer_start
;
614 if (elapsed
> stop
.worst
.time
) break;
615 desired_done
= elapsed
> stop
.desired
.time
;
617 } else { assert(ti
->dim
== TD_GAMES
);
618 if (i
> stop
.worst
.playouts
) break;
619 desired_done
= i
> stop
.desired
.playouts
;
622 /* We want to stop simulating, but are willing to keep trying
623 * if we aren't completely sure about the winner yet. */
625 if (u
->policy
->winner
&& u
->policy
->evaluate
) {
626 struct uct_descent descent
= { .node
= ctx
->t
->root
};
627 u
->policy
->winner(u
->policy
, ctx
->t
, &descent
);
628 winner
= descent
.node
;
631 bestr
= u
->policy
->choose(u
->policy
, best
, b
, stone_other(color
), resign
);
632 if (!uct_search_keep_looking(u
, ctx
->t
, b
, best
, best2
, bestr
, winner
, i
))
636 /* TODO: Early break if best->variance goes under threshold and we already
637 * have enough playouts (possibly thanks to book or to pondering)? */
640 ctx
= uct_search_stop();
643 tree_dump(t
, u
->dumpthres
);
645 uct_progress_status(u
, t
, color
, ctx
->games
);
651 /* Start pondering background with @color to play. */
653 uct_pondering_start(struct uct
*u
, struct board
*b0
, struct tree
*t
, enum stone color
)
656 fprintf(stderr
, "Starting to ponder with color %s\n", stone2str(stone_other(color
)));
659 /* We need a local board copy to ponder upon. */
660 struct board
*b
= malloc(sizeof(*b
)); board_copy(b
, b0
);
662 /* *b0 did not have the genmove'd move played yet. */
663 struct move m
= { t
->root
->coord
, t
->root_color
};
664 int res
= board_play(b
, &m
);
666 setup_dynkomi(u
, b
, stone_other(m
.color
));
668 /* Start MCTS manager thread "headless". */
669 uct_search_start(u
, b
, color
, t
);
672 /* uct_search_stop() frontend for the pondering (non-genmove) mode. */
674 uct_pondering_stop(struct uct
*u
)
676 u
->pondering
= false;
677 if (!thread_manager_running
)
680 /* Stop the thread manager. */
681 struct spawn_ctx
*ctx
= uct_search_stop();
683 fprintf(stderr
, "(pondering) ");
684 uct_progress_status(u
, ctx
->t
, ctx
->color
, ctx
->games
);
691 uct_genmove(struct engine
*e
, struct board
*b
, struct time_info
*ti
, enum stone color
, bool pass_all_alive
)
693 double start_time
= time_now();
694 struct uct
*u
= e
->data
;
696 if (b
->superko_violation
) {
697 fprintf(stderr
, "!!! WARNING: SUPERKO VIOLATION OCCURED BEFORE THIS MOVE\n");
698 fprintf(stderr
, "Maybe you play with situational instead of positional superko?\n");
699 fprintf(stderr
, "I'm going to ignore the violation, but note that I may miss\n");
700 fprintf(stderr
, "some moves valid under this ruleset because of this.\n");
701 b
->superko_violation
= false;
705 uct_pondering_stop(u
);
706 prepare_move(e
, b
, color
);
709 /* How to decide whether to use dynkomi in this game? Since we use
710 * pondering, it's not simple "who-to-play" matter. Decide based on
711 * the last genmove issued. */
712 u
->t
->use_extra_komi
= !!(u
->dynkomi_mask
& color
);
713 setup_dynkomi(u
, b
, color
);
715 /* Make pessimistic assumption about komi for Japanese rules to
716 * avoid losing by 0.5 when winning by 0.5 with Chinese rules.
717 * The rules usually give the same winner if the integer part of komi
718 * is odd so we adjust the komi only if it is even (for a board of
719 * odd size). We are not trying to get an exact evaluation for rare
720 * cases of seki. For details see http://home.snafu.de/jasiek/parity.html
721 * TODO: Support the kgs-rules command once available. */
722 if (u
->territory_scoring
&& (((int)floor(b
->komi
) + b
->size
) & 1)) {
723 b
->komi
+= (color
== S_BLACK
? 1.0 : -1.0);
725 fprintf(stderr
, "Setting komi to %.1f assuming Japanese rules\n",
729 int base_playouts
= u
->t
->root
->u
.playouts
;
730 /* Perform the Monte Carlo Tree Search! */
731 int played_games
= uct_search(u
, b
, ti
, color
, u
->t
);
733 /* Choose the best move from the tree. */
734 struct tree_node
*best
= u
->policy
->choose(u
->policy
, u
->t
->root
, b
, color
, resign
);
737 return coord_copy(pass
);
740 fprintf(stderr
, "*** WINNER is %s (%d,%d) with score %1.4f (%d/%d:%d/%d games)\n",
741 coord2sstr(best
->coord
, b
), coord_x(best
->coord
, b
), coord_y(best
->coord
, b
),
742 tree_node_get_value(u
->t
, 1, best
->u
.value
), best
->u
.playouts
,
743 u
->t
->root
->u
.playouts
, u
->t
->root
->u
.playouts
- base_playouts
, played_games
);
745 /* Do not resign if we're so short of time that evaluation of best move is completely
746 * unreliable, we might be winning actually. In this case best is almost random but
747 * still better than resign. */
748 if (tree_node_get_value(u
->t
, 1, best
->u
.value
) < u
->resign_ratio
&& !is_pass(best
->coord
)
749 && best
->u
.playouts
> GJ_MINGAMES
) {
751 return coord_copy(resign
);
754 /* If the opponent just passed and we win counting, always
756 if (b
->moves
> 1 && is_pass(b
->last_move
.coord
)) {
757 /* Make sure enough playouts are simulated. */
758 while (u
->ownermap
.playouts
< GJ_MINGAMES
)
759 uct_playout(u
, b
, color
, u
->t
);
760 if (uct_pass_is_safe(u
, b
, color
, u
->pass_all_alive
|| pass_all_alive
)) {
762 fprintf(stderr
, "<Will rather pass, looks safe enough.>\n");
767 tree_promote_node(u
->t
, &best
);
768 /* After a pass, pondering is harmful for two reasons:
769 * (i) We might keep pondering even when the game is over.
770 * Of course this is the case for opponent resign as well.
771 * (ii) More importantly, the ownermap will get skewed since
772 * the UCT will start cutting off any playouts. */
773 if (u
->pondering_opt
&& !is_pass(best
->coord
)) {
774 uct_pondering_start(u
, b
, u
->t
, stone_other(color
));
777 double time
= time_now() - start_time
+ 0.000001; /* avoid divide by zero */
778 fprintf(stderr
, "genmove in %0.2fs (%d games/s, %d games/s/thread)\n",
779 time
, (int)(played_games
/time
), (int)(played_games
/time
/u
->threads
));
781 return coord_copy(best
->coord
);
786 uct_genbook(struct engine
*e
, struct board
*b
, struct time_info
*ti
, enum stone color
)
788 struct uct
*u
= e
->data
;
789 if (!u
->t
) prepare_move(e
, b
, color
);
792 if (ti
->dim
== TD_GAMES
) {
793 /* Don't count in games that already went into the book. */
794 ti
->len
.games
+= u
->t
->root
->u
.playouts
;
796 uct_search(u
, b
, ti
, color
, u
->t
);
798 assert(ti
->dim
== TD_GAMES
);
799 tree_save(u
->t
, b
, ti
->len
.games
/ 100);
805 uct_dumpbook(struct engine
*e
, struct board
*b
, enum stone color
)
807 struct uct
*u
= e
->data
;
808 struct tree
*t
= tree_init(b
, color
, u
->fast_alloc
? u
->max_tree_size
: 0, u
->local_tree_aging
);
816 uct_state_init(char *arg
, struct board
*b
)
818 struct uct
*u
= calloc(1, sizeof(struct uct
));
819 bool using_elo
= false;
821 u
->debug_level
= debug_level
;
822 u
->gamelen
= MC_GAMELEN
;
826 u
->playout_amaf
= true;
827 u
->playout_amaf_nakade
= false;
828 u
->amaf_prior
= false;
829 u
->max_tree_size
= 3072ULL * 1048576;
831 if (board_size(b
) - 2 >= 19)
833 u
->dynkomi_mask
= S_BLACK
;
834 u
->handicap_value
= 7;
837 u
->thread_model
= TM_TREEVL
;
838 u
->parallel_tree
= true;
839 u
->virtual_loss
= true;
841 u
->fuseki_end
= 20; // max time at 361*20% = 72 moves (our 36th move, still 99 to play)
842 u
->yose_start
= 40; // (100-40-25)*361/100/2 = 63 moves still to play by us then
843 u
->bestr_ratio
= 0.02;
844 // 2.5 is clearly too much, but seems to compensate well for overly stern time allocations.
845 // TODO: Further tuning and experiments with better time allocation schemes.
846 u
->best2_ratio
= 2.5;
848 u
->val_scale
= 0.04; u
->val_points
= 40;
851 u
->local_tree_aging
= 2;
854 char *optspec
, *next
= arg
;
857 next
+= strcspn(next
, ",");
858 if (*next
) { *next
++ = 0; } else { *next
= 0; }
860 char *optname
= optspec
;
861 char *optval
= strchr(optspec
, '=');
862 if (optval
) *optval
++ = 0;
864 if (!strcasecmp(optname
, "debug")) {
866 u
->debug_level
= atoi(optval
);
869 } else if (!strcasecmp(optname
, "mercy") && optval
) {
870 /* Minimal difference of black/white captures
871 * to stop playout - "Mercy Rule". Speeds up
872 * hopeless playouts at the expense of some
874 u
->mercymin
= atoi(optval
);
875 } else if (!strcasecmp(optname
, "gamelen") && optval
) {
876 u
->gamelen
= atoi(optval
);
877 } else if (!strcasecmp(optname
, "expand_p") && optval
) {
878 u
->expand_p
= atoi(optval
);
879 } else if (!strcasecmp(optname
, "dumpthres") && optval
) {
880 u
->dumpthres
= atoi(optval
);
881 } else if (!strcasecmp(optname
, "best2_ratio") && optval
) {
882 /* If set, prolong simulating while
883 * first_best/second_best playouts ratio
884 * is less than best2_ratio. */
885 u
->best2_ratio
= atof(optval
);
886 } else if (!strcasecmp(optname
, "bestr_ratio") && optval
) {
887 /* If set, prolong simulating while
888 * best,best_best_child values delta
889 * is more than bestr_ratio. */
890 u
->bestr_ratio
= atof(optval
);
891 } else if (!strcasecmp(optname
, "playout_amaf")) {
892 /* Whether to include random playout moves in
893 * AMAF as well. (Otherwise, only tree moves
894 * are included in AMAF. Of course makes sense
895 * only in connection with an AMAF policy.) */
896 /* with-without: 55.5% (+-4.1) */
897 if (optval
&& *optval
== '0')
898 u
->playout_amaf
= false;
900 u
->playout_amaf
= true;
901 } else if (!strcasecmp(optname
, "playout_amaf_nakade")) {
902 /* Whether to include nakade moves from playouts
903 * in the AMAF statistics; this tends to nullify
904 * the playout_amaf effect by adding too much
906 if (optval
&& *optval
== '0')
907 u
->playout_amaf_nakade
= false;
909 u
->playout_amaf_nakade
= true;
910 } else if (!strcasecmp(optname
, "playout_amaf_cutoff") && optval
) {
911 /* Keep only first N% of playout stage AMAF
913 u
->playout_amaf_cutoff
= atoi(optval
);
914 } else if ((!strcasecmp(optname
, "policy") || !strcasecmp(optname
, "random_policy")) && optval
) {
915 char *policyarg
= strchr(optval
, ':');
916 struct uct_policy
**p
= !strcasecmp(optname
, "policy") ? &u
->policy
: &u
->random_policy
;
919 if (!strcasecmp(optval
, "ucb1")) {
920 *p
= policy_ucb1_init(u
, policyarg
);
921 } else if (!strcasecmp(optval
, "ucb1amaf")) {
922 *p
= policy_ucb1amaf_init(u
, policyarg
);
924 fprintf(stderr
, "UCT: Invalid tree policy %s\n", optval
);
927 } else if (!strcasecmp(optname
, "playout") && optval
) {
928 char *playoutarg
= strchr(optval
, ':');
931 if (!strcasecmp(optval
, "moggy")) {
932 u
->playout
= playout_moggy_init(playoutarg
, b
);
933 } else if (!strcasecmp(optval
, "light")) {
934 u
->playout
= playout_light_init(playoutarg
, b
);
935 } else if (!strcasecmp(optval
, "elo")) {
936 u
->playout
= playout_elo_init(playoutarg
, b
);
939 fprintf(stderr
, "UCT: Invalid playout policy %s\n", optval
);
942 } else if (!strcasecmp(optname
, "prior") && optval
) {
943 u
->prior
= uct_prior_init(optval
, b
);
944 } else if (!strcasecmp(optname
, "amaf_prior") && optval
) {
945 u
->amaf_prior
= atoi(optval
);
946 } else if (!strcasecmp(optname
, "threads") && optval
) {
947 /* By default, Pachi will run with only single
948 * tree search thread! */
949 u
->threads
= atoi(optval
);
950 } else if (!strcasecmp(optname
, "thread_model") && optval
) {
951 if (!strcasecmp(optval
, "root")) {
952 /* Root parallelization - each thread
953 * does independent search, trees are
954 * merged at the end. */
955 u
->thread_model
= TM_ROOT
;
956 u
->parallel_tree
= false;
957 u
->virtual_loss
= false;
958 } else if (!strcasecmp(optval
, "tree")) {
959 /* Tree parallelization - all threads
960 * grind on the same tree. */
961 u
->thread_model
= TM_TREE
;
962 u
->parallel_tree
= true;
963 u
->virtual_loss
= false;
964 } else if (!strcasecmp(optval
, "treevl")) {
965 /* Tree parallelization, but also
966 * with virtual losses - this discou-
967 * rages most threads choosing the
968 * same tree branches to read. */
969 u
->thread_model
= TM_TREEVL
;
970 u
->parallel_tree
= true;
971 u
->virtual_loss
= true;
973 fprintf(stderr
, "UCT: Invalid thread model %s\n", optval
);
976 } else if (!strcasecmp(optname
, "pondering")) {
977 /* Keep searching even during opponent's turn. */
978 u
->pondering_opt
= !optval
|| atoi(optval
);
979 } else if (!strcasecmp(optname
, "fuseki_end") && optval
) {
980 /* At the very beginning it's not worth thinking
981 * too long because the playout evaluations are
982 * very noisy. So gradually increase the thinking
983 * time up to maximum when fuseki_end percent
984 * of the board has been played.
985 * This only applies if we are not in byoyomi. */
986 u
->fuseki_end
= atoi(optval
);
987 } else if (!strcasecmp(optname
, "yose_start") && optval
) {
988 /* When yose_start percent of the board has been
989 * played, or if we are in byoyomi, stop spending
990 * more time and spread the remaining time
992 * Between fuseki_end and yose_start, we spend
993 * a constant proportion of the remaining time
994 * on each move. (yose_start should actually
995 * be much earlier than when real yose start,
996 * but "yose" is a good short name to convey
998 u
->yose_start
= atoi(optval
);
999 } else if (!strcasecmp(optname
, "force_seed") && optval
) {
1000 u
->force_seed
= atoi(optval
);
1001 } else if (!strcasecmp(optname
, "no_book")) {
1003 } else if (!strcasecmp(optname
, "dynkomi")) {
1004 /* Dynamic komi in handicap game; linearly
1005 * decreases to basic settings until move
1007 u
->dynkomi
= optval
? atoi(optval
) : 200;
1008 } else if (!strcasecmp(optname
, "dynkomi_mask") && optval
) {
1009 /* Bitmask of colors the player must be
1010 * for dynkomi be applied; you may want
1011 * to use dynkomi_mask=3 to allow dynkomi
1012 * even in games where Pachi is white. */
1013 u
->dynkomi_mask
= atoi(optval
);
1014 } else if (!strcasecmp(optname
, "handicap_value") && optval
) {
1015 /* Point value of single handicap stone,
1016 * for dynkomi computation. */
1017 u
->handicap_value
= atoi(optval
);
1018 } else if (!strcasecmp(optname
, "val_scale") && optval
) {
1019 /* How much of the game result value should be
1020 * influenced by win size. Zero means it isn't. */
1021 u
->val_scale
= atof(optval
);
1022 } else if (!strcasecmp(optname
, "val_points") && optval
) {
1023 /* Maximum size of win to be scaled into game
1024 * result value. Zero means boardsize^2. */
1025 u
->val_points
= atoi(optval
) * 2; // result values are doubled
1026 } else if (!strcasecmp(optname
, "val_extra")) {
1027 /* If false, the score coefficient will be simply
1028 * added to the value, instead of scaling the result
1029 * coefficient because of it. */
1030 u
->val_extra
= !optval
|| atoi(optval
);
1031 } else if (!strcasecmp(optname
, "local_tree") && optval
) {
1032 /* Whether to bias exploration by local tree values
1033 * (must be supported by the used policy).
1035 * 1: Do, value = result.
1036 * Try to temper the result:
1037 * 2: Do, value = 0.5+(result-expected)/2.
1038 * 3: Do, value = 0.5+bzz((result-expected)^2).
1039 * 4: Do, value = 0.5+sqrt(result-expected)/2. */
1040 u
->local_tree
= atoi(optval
);
1041 } else if (!strcasecmp(optname
, "tenuki_d") && optval
) {
1042 /* Tenuki distance at which to break the local tree. */
1043 u
->tenuki_d
= atoi(optval
);
1044 if (u
->tenuki_d
> TREE_NODE_D_MAX
+ 1) {
1045 fprintf(stderr
, "uct: tenuki_d must not be larger than TREE_NODE_D_MAX+1 %d\n", TREE_NODE_D_MAX
+ 1);
1048 } else if (!strcasecmp(optname
, "local_tree_aging") && optval
) {
1049 /* How much to reduce local tree values between moves. */
1050 u
->local_tree_aging
= atof(optval
);
1051 } else if (!strcasecmp(optname
, "local_tree_allseq")) {
1052 /* By default, only complete sequences are stored
1053 * in the local tree. If this is on, also
1054 * subsequences starting at each move are stored. */
1055 u
->local_tree_allseq
= !optval
|| atoi(optval
);
1056 } else if (!strcasecmp(optname
, "local_tree_playout")) {
1057 /* Whether to adjust ELO playout probability
1058 * distributions according to matched localtree
1060 u
->local_tree_playout
= !optval
|| atoi(optval
);
1061 } else if (!strcasecmp(optname
, "local_tree_pseqroot")) {
1062 /* By default, when we have no sequence move
1063 * to suggest in-playout, we give up. If this
1064 * is on, we make probability distribution from
1065 * sequences first moves instead. */
1066 u
->local_tree_pseqroot
= !optval
|| atoi(optval
);
1067 } else if (!strcasecmp(optname
, "pass_all_alive")) {
1068 /* Whether to consider all stones alive at the game
1069 * end instead of marking dead groupd. */
1070 u
->pass_all_alive
= !optval
|| atoi(optval
);
1071 } else if (!strcasecmp(optname
, "territory_scoring")) {
1072 /* Use territory scoring (default is area scoring).
1073 * An explicit kgs-rules command overrides this. */
1074 u
->territory_scoring
= !optval
|| atoi(optval
);
1075 } else if (!strcasecmp(optname
, "random_policy_chance") && optval
) {
1076 /* If specified (N), with probability 1/N, random_policy policy
1077 * descend is used instead of main policy descend; useful
1078 * if specified policy (e.g. UCB1AMAF) can make unduly biased
1079 * choices sometimes, you can fall back to e.g.
1080 * random_policy=UCB1. */
1081 u
->random_policy_chance
= atoi(optval
);
1082 } else if (!strcasecmp(optname
, "max_tree_size") && optval
) {
1083 /* Maximum amount of memory [MiB] consumed by the move tree.
1084 * Default is 3072 (3 GiB). Note that if you use TM_ROOT,
1085 * this limits size of only one of the trees, not all of them
1087 u
->max_tree_size
= atol(optval
) * 1048576;
1088 } else if (!strcasecmp(optname
, "fast_alloc")) {
1089 u
->fast_alloc
= !optval
|| atoi(optval
);
1090 } else if (!strcasecmp(optname
, "banner") && optval
) {
1091 /* Additional banner string. This must come as the
1092 * last engine parameter. */
1093 if (*next
) *--next
= ',';
1094 u
->banner
= strdup(optval
);
1097 fprintf(stderr
, "uct: Invalid engine argument %s or missing value\n", optname
);
1103 u
->resign_ratio
= 0.2; /* Resign when most games are lost. */
1104 u
->loss_threshold
= 0.85; /* Stop reading if after at least 5000 playouts this is best value. */
1106 u
->policy
= policy_ucb1amaf_init(u
, NULL
);
1108 if (!!u
->random_policy_chance
^ !!u
->random_policy
) {
1109 fprintf(stderr
, "uct: Only one of random_policy and random_policy_chance is set\n");
1113 if (!u
->local_tree
) {
1114 /* No ltree aging. */
1115 u
->local_tree_aging
= 1.0f
;
1118 u
->local_tree_playout
= false;
1120 if (u
->fast_alloc
&& !u
->parallel_tree
) {
1121 fprintf(stderr
, "fast_alloc not supported with root parallelization.\n");
1126 u
->prior
= uct_prior_init(NULL
, b
);
1129 u
->playout
= playout_moggy_init(NULL
, b
);
1130 u
->playout
->debug_level
= u
->debug_level
;
1132 u
->ownermap
.map
= malloc(board_size2(b
) * sizeof(u
->ownermap
.map
[0]));
1134 /* Some things remain uninitialized for now - the opening book
1135 * is not loaded and the tree not set up. */
1136 /* This will be initialized in setup_state() at the first move
1137 * received/requested. This is because right now we are not aware
1138 * about any komi or handicap setup and such. */
1144 engine_uct_init(char *arg
, struct board
*b
)
1146 struct uct
*u
= uct_state_init(arg
, b
);
1147 struct engine
*e
= calloc(1, sizeof(struct engine
));
1148 e
->name
= "UCT Engine";
1149 e
->printhook
= uct_printhook_ownermap
;
1150 e
->notify_play
= uct_notify_play
;
1152 e
->genmove
= uct_genmove
;
1153 e
->dead_group_list
= uct_dead_group_list
;
1157 const char banner
[] = "I'm playing UCT. When I'm losing, I will resign, "
1158 "if I think I win, I play until you pass. "
1159 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
1160 if (!u
->banner
) u
->banner
= "";
1161 e
->comment
= malloc(sizeof(banner
) + strlen(u
->banner
) + 1);
1162 sprintf(e
->comment
, "%s %s", banner
, u
->banner
);