18 #include "playout/elo.h"
19 #include "playout/moggy.h"
20 #include "playout/light.h"
24 #include "distributed/distributed.h"
25 #include "uct/dynkomi.h"
26 #include "uct/internal.h"
27 #include "uct/prior.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
);
34 static void uct_pondering_stop(struct uct
*u
);
35 static void uct_pondering_start(struct uct
*u
, struct board
*b0
, struct tree
*t
, enum stone color
);
38 /* Default number of simulations to perform per move.
39 * Note that this is now in total over all threads! (Unless TM_ROOT.) */
40 #define MC_GAMES 80000
41 #define MC_GAMELEN MAX_GAMELEN
42 static const struct time_info default_ti
= {
45 .len
= { .games
= MC_GAMES
},
48 /* How big proportion of ownermap counts must be of one color to consider
51 /* How many games to consider at minimum before judging groups. */
52 #define GJ_MINGAMES 500
54 /* How often to inspect the tree from the main thread to check for playout
55 * stop, progress reports, etc. (in seconds) */
56 #define TREE_BUSYWAIT_INTERVAL 0.1 /* 100ms */
58 /* Once per how many simulations (per thread) to show a progress report line. */
59 #define TREE_SIMPROGRESS_INTERVAL 10000
61 /* When terminating uct_search() early, the safety margin to add to the
62 * remaining playout number estimate when deciding whether the result can
64 #define PLAYOUT_DELTA_SAFEMARGIN 1000
68 setup_state(struct uct
*u
, struct board
*b
, enum stone color
)
70 u
->t
= tree_init(b
, color
, u
->fast_alloc
? u
->max_tree_size
: 0, u
->local_tree_aging
);
72 fast_srandom(u
->force_seed
);
74 fprintf(stderr
, "Fresh board with random seed %lu\n", fast_getseed());
75 //board_print(b, stderr);
76 if (!u
->no_book
&& b
->moves
== 0) {
77 assert(color
== S_BLACK
);
83 reset_state(struct uct
*u
)
86 tree_done(u
->t
); u
->t
= NULL
;
90 setup_dynkomi(struct uct
*u
, struct board
*b
, enum stone to_play
)
92 if (u
->t
->use_extra_komi
&& u
->dynkomi
->permove
)
93 u
->t
->extra_komi
= u
->dynkomi
->permove(u
->dynkomi
, b
, u
->t
);
97 prepare_move(struct engine
*e
, struct board
*b
, enum stone color
)
99 struct uct
*u
= e
->data
;
102 /* Verify that we have sane state. */
104 assert(u
->t
&& b
->moves
);
105 if (color
!= stone_other(u
->t
->root_color
)) {
106 fprintf(stderr
, "Fatal: Non-alternating play detected %d %d\n",
107 color
, u
->t
->root_color
);
112 /* We need fresh state. */
114 setup_state(u
, b
, color
);
117 u
->ownermap
.playouts
= 0;
118 memset(u
->ownermap
.map
, 0, board_size2(b
) * sizeof(u
->ownermap
.map
[0]));
122 dead_group_list(struct uct
*u
, struct board
*b
, struct move_queue
*mq
)
124 struct group_judgement gj
;
126 gj
.gs
= alloca(board_size2(b
) * sizeof(gj
.gs
[0]));
127 board_ownermap_judge_group(b
, &u
->ownermap
, &gj
);
128 groups_of_status(b
, &gj
, GS_DEAD
, mq
);
132 uct_pass_is_safe(struct uct
*u
, struct board
*b
, enum stone color
, bool pass_all_alive
)
134 if (u
->ownermap
.playouts
< GJ_MINGAMES
)
137 struct move_queue mq
= { .moves
= 0 };
139 dead_group_list(u
, b
, &mq
);
140 return pass_is_safe(b
, color
, &mq
);
143 /* This function is called only when running as slave in the distributed version. */
144 static enum parse_code
145 uct_notify(struct engine
*e
, struct board
*b
, int id
, char *cmd
, char *args
, char **reply
)
147 struct uct
*u
= e
->data
;
149 /* Force resending the whole command history if we are out of sync
150 * but do it only once, not if already getting the history. */
151 if ((move_number(id
) != b
->moves
|| !b
->size
)
152 && !reply_disabled(id
) && !is_reset(cmd
)) {
154 fprintf(stderr
, "Out of sync, id %d, move %d\n", id
, b
->moves
);
155 static char buf
[128];
156 snprintf(buf
, sizeof(buf
), "out of sync, move %d expected", b
->moves
);
160 return reply_disabled(id
) ? P_NOREPLY
: P_OK
;
164 uct_printhook_ownermap(struct board
*board
, coord_t c
, char *s
, char *end
)
166 struct uct
*u
= board
->es
;
168 const char chr
[] = ":XO,"; // dame, black, white, unclear
169 const char chm
[] = ":xo,";
170 char ch
= chr
[board_ownermap_judge_point(&u
->ownermap
, c
, GJ_THRES
)];
171 if (ch
== ',') { // less precise estimate then?
172 ch
= chm
[board_ownermap_judge_point(&u
->ownermap
, c
, 0.67)];
174 s
+= snprintf(s
, end
- s
, "%c ", ch
);
179 uct_notify_play(struct engine
*e
, struct board
*b
, struct move
*m
)
181 struct uct
*u
= e
->data
;
183 /* No state, create one - this is probably game beginning
184 * and we need to load the opening book right now. */
185 prepare_move(e
, b
, m
->color
);
189 /* Stop pondering, required by tree_promote_at() */
190 uct_pondering_stop(u
);
192 if (is_resign(m
->coord
)) {
198 /* Promote node of the appropriate move to the tree root. */
200 if (!tree_promote_at(u
->t
, b
, m
->coord
)) {
202 fprintf(stderr
, "Warning: Cannot promote move node! Several play commands in row?\n");
207 /* If we are a slave in a distributed engine, start pondering once
208 * we know which move we actually played. See uct_genmove() about
209 * the check for pass. */
210 if (u
->pondering_opt
&& u
->slave
&& m
->color
== u
->my_color
&& !is_pass(m
->coord
))
211 uct_pondering_start(u
, b
, u
->t
, stone_other(m
->color
));
217 uct_chat(struct engine
*e
, struct board
*b
, char *cmd
)
219 struct uct
*u
= e
->data
;
220 static char reply
[1024];
222 cmd
+= strspn(cmd
, " \n\t");
223 if (!strncasecmp(cmd
, "winrate", 7)) {
225 return "no game context (yet?)";
226 enum stone color
= u
->t
->root_color
;
227 struct tree_node
*n
= u
->t
->root
;
228 snprintf(reply
, 1024, "In %d playouts at %d threads, %s %s can win with %.2f%% probability",
229 n
->u
.playouts
, u
->threads
, stone2str(color
), coord2sstr(n
->coord
, b
),
230 tree_node_get_value(u
->t
, -1, n
->u
.value
) * 100);
231 if (u
->t
->use_extra_komi
&& abs(u
->t
->extra_komi
) >= 0.5) {
232 sprintf(reply
+ strlen(reply
), ", while self-imposing extra komi %.1f",
242 uct_dead_group_list(struct engine
*e
, struct board
*b
, struct move_queue
*mq
)
244 struct uct
*u
= e
->data
;
246 /* This means the game is probably over, no use pondering on. */
247 uct_pondering_stop(u
);
249 if (u
->pass_all_alive
)
250 return; // no dead groups
252 bool mock_state
= false;
255 /* No state, but we cannot just back out - we might
256 * have passed earlier, only assuming some stones are
257 * dead, and then re-connected, only to lose counting
258 * when all stones are assumed alive. */
259 /* Mock up some state and seed the ownermap by few
261 prepare_move(e
, b
, S_BLACK
); assert(u
->t
);
262 for (int i
= 0; i
< GJ_MINGAMES
; i
++)
263 uct_playout(u
, b
, S_BLACK
, u
->t
);
267 dead_group_list(u
, b
, mq
);
270 /* Clean up the mock state in case we will receive
271 * a genmove; we could get a non-alternating-move
272 * error from prepare_move() in that case otherwise. */
278 playout_policy_done(struct playout_policy
*p
)
280 if (p
->done
) p
->done(p
);
281 if (p
->data
) free(p
->data
);
286 uct_done(struct engine
*e
)
288 /* This is called on engine reset, especially when clear_board
289 * is received and new game should begin. */
290 struct uct
*u
= e
->data
;
291 uct_pondering_stop(u
);
292 if (u
->t
) reset_state(u
);
293 free(u
->ownermap
.map
);
296 free(u
->random_policy
);
297 playout_policy_done(u
->playout
);
298 uct_prior_done(u
->prior
);
302 /* Pachi threading structure (if uct_playouts_parallel() is used):
305 * | main(), GTP communication, ...
306 * | starts and stops the search managed by thread_manager
309 * | spawns and collects worker threads
315 * uct_playouts() loop, doing descend-playout until uct_halt
317 * Another way to look at it is by functions (lines denote thread boundaries):
320 * | uct_search() (uct_search_start() .. uct_search_stop())
321 * | -----------------------
322 * | spawn_thread_manager()
323 * | -----------------------
325 * V uct_playouts() */
327 /* Set in thread manager in case the workers should stop. */
328 volatile sig_atomic_t uct_halt
= 0;
329 /* ID of the running worker thread. */
330 __thread
int thread_id
= -1;
331 /* ID of the thread manager. */
332 static pthread_t thread_manager
;
333 static bool thread_manager_running
;
335 static pthread_mutex_t finish_mutex
= PTHREAD_MUTEX_INITIALIZER
;
336 static pthread_cond_t finish_cond
= PTHREAD_COND_INITIALIZER
;
337 static volatile int finish_thread
;
338 static pthread_mutex_t finish_serializer
= PTHREAD_MUTEX_INITIALIZER
;
351 spawn_worker(void *ctx_
)
353 struct spawn_ctx
*ctx
= ctx_
;
355 fast_srandom(ctx
->seed
);
356 thread_id
= ctx
->tid
;
358 ctx
->games
= uct_playouts(ctx
->u
, ctx
->b
, ctx
->color
, ctx
->t
);
360 pthread_mutex_lock(&finish_serializer
);
361 pthread_mutex_lock(&finish_mutex
);
362 finish_thread
= ctx
->tid
;
363 pthread_cond_signal(&finish_cond
);
364 pthread_mutex_unlock(&finish_mutex
);
368 /* Thread manager, controlling worker threads. It must be called with
369 * finish_mutex lock held, but it will unlock it itself before exiting;
370 * this is necessary to be completely deadlock-free. */
371 /* The finish_cond can be signalled for it to stop; in that case,
372 * the caller should set finish_thread = -1. */
373 /* After it is started, it will update mctx->t to point at some tree
374 * used for the actual search (matters only for TM_ROOT), on return
375 * it will set mctx->games to the number of performed simulations. */
377 spawn_thread_manager(void *ctx_
)
379 /* In thread_manager, we use only some of the ctx fields. */
380 struct spawn_ctx
*mctx
= ctx_
;
381 struct uct
*u
= mctx
->u
;
382 struct tree
*t
= mctx
->t
;
383 bool shared_tree
= u
->parallel_tree
;
384 fast_srandom(mctx
->seed
);
386 int played_games
= 0;
387 pthread_t threads
[u
->threads
];
392 /* Garbage collect the tree by preference when pondering. */
393 if (u
->pondering
&& t
->nodes
&& t
->nodes_size
> t
->max_tree_size
/2) {
394 unsigned long temp_size
= (MIN_FREE_MEM_PERCENT
* t
->max_tree_size
) / 100;
395 t
->root
= tree_garbage_collect(t
, temp_size
, t
->root
);
398 /* Spawn threads... */
399 for (int ti
= 0; ti
< u
->threads
; ti
++) {
400 struct spawn_ctx
*ctx
= malloc(sizeof(*ctx
));
401 ctx
->u
= u
; ctx
->b
= mctx
->b
; ctx
->color
= mctx
->color
;
402 mctx
->t
= ctx
->t
= shared_tree
? t
: tree_copy(t
);
403 ctx
->tid
= ti
; ctx
->seed
= fast_random(65536) + ti
;
404 pthread_create(&threads
[ti
], NULL
, spawn_worker
, ctx
);
406 fprintf(stderr
, "Spawned worker %d\n", ti
);
409 /* ...and collect them back: */
410 while (joined
< u
->threads
) {
411 /* Wait for some thread to finish... */
412 pthread_cond_wait(&finish_cond
, &finish_mutex
);
413 if (finish_thread
< 0) {
414 /* Stop-by-caller. Tell the workers to wrap up. */
418 /* ...and gather its remnants. */
419 struct spawn_ctx
*ctx
;
420 pthread_join(threads
[finish_thread
], (void **) &ctx
);
421 played_games
+= ctx
->games
;
424 if (ctx
->t
== mctx
->t
) mctx
->t
= t
;
425 tree_merge(t
, ctx
->t
);
430 fprintf(stderr
, "Joined worker %d\n", finish_thread
);
431 pthread_mutex_unlock(&finish_serializer
);
434 pthread_mutex_unlock(&finish_mutex
);
437 tree_normalize(mctx
->t
, u
->threads
);
439 mctx
->games
= played_games
;
443 static struct spawn_ctx
*
444 uct_search_start(struct uct
*u
, struct board
*b
, enum stone color
, struct tree
*t
)
446 assert(u
->threads
> 0);
447 assert(!thread_manager_running
);
449 struct spawn_ctx ctx
= { .u
= u
, .b
= b
, .color
= color
, .t
= t
, .seed
= fast_random(65536) };
450 static struct spawn_ctx mctx
; mctx
= ctx
;
451 pthread_mutex_lock(&finish_mutex
);
452 pthread_create(&thread_manager
, NULL
, spawn_thread_manager
, &mctx
);
453 thread_manager_running
= true;
457 static struct spawn_ctx
*
458 uct_search_stop(void)
460 assert(thread_manager_running
);
462 /* Signal thread manager to stop the workers. */
463 pthread_mutex_lock(&finish_mutex
);
465 pthread_cond_signal(&finish_cond
);
466 pthread_mutex_unlock(&finish_mutex
);
468 /* Collect the thread manager. */
469 struct spawn_ctx
*pctx
;
470 thread_manager_running
= false;
471 pthread_join(thread_manager
, (void **) &pctx
);
476 /* Determine whether we should terminate the search early. */
478 uct_search_stop_early(struct uct
*u
, struct tree
*t
, struct board
*b
,
479 struct time_info
*ti
, struct time_stop
*stop
,
480 struct tree_node
*best
, struct tree_node
*best2
,
481 int base_playouts
, int i
)
483 /* Always use at least half the desired time. It is silly
484 * to lose a won game because we played a bad move in 0.1s. */
486 if (ti
->dim
== TD_WALLTIME
) {
487 elapsed
= time_now() - ti
->len
.t
.timer_start
;
488 if (elapsed
< 0.5 * stop
->desired
.time
) return false;
491 /* Early break in won situation. */
492 if (best
->u
.playouts
>= 2000 && tree_node_get_value(t
, 1, best
->u
.value
) >= u
->loss_threshold
)
494 /* Earlier break in super-won situation. */
495 if (best
->u
.playouts
>= 500 && tree_node_get_value(t
, 1, best
->u
.value
) >= 0.95)
498 /* Break early if we estimate the second-best move cannot
499 * catch up in assigned time anymore. We use all our time
500 * if we are in byoyomi with single stone remaining in our
501 * period, however - it's better to pre-ponder. */
502 bool time_indulgent
= (!ti
->len
.t
.main_time
&& ti
->len
.t
.byoyomi_stones
== 1);
503 if (best2
&& ti
->dim
== TD_WALLTIME
&& !time_indulgent
) {
504 double remaining
= stop
->worst
.time
- elapsed
;
505 double pps
= ((double)i
- base_playouts
) / elapsed
;
506 double estplayouts
= remaining
* pps
+ PLAYOUT_DELTA_SAFEMARGIN
;
507 if (best
->u
.playouts
> best2
->u
.playouts
+ estplayouts
) {
509 fprintf(stderr
, "Early stop, result cannot change: "
510 "best %d, best2 %d, estimated %f simulations to go\n",
511 best
->u
.playouts
, best2
->u
.playouts
, estplayouts
);
519 /* Determine whether we should terminate the search later. */
521 uct_search_keep_looking(struct uct
*u
, struct tree
*t
, struct board
*b
,
522 struct time_info
*ti
, struct time_stop
*stop
,
523 struct tree_node
*best
, struct tree_node
*best2
,
524 struct tree_node
*bestr
, struct tree_node
*winner
, int i
)
528 fprintf(stderr
, "Did not find best move, still trying...\n");
532 /* Do not waste time if we are winning. Spend up to worst time if
533 * we are unsure, but only desired time if we are sure of winning. */
534 float beta
= 2 * (tree_node_get_value(t
, 1, best
->u
.value
) - 0.5);
535 if (ti
->dim
== TD_WALLTIME
&& beta
> 0) {
536 double good_enough
= stop
->desired
.time
* beta
+ stop
->worst
.time
* (1 - beta
);
537 double elapsed
= time_now() - ti
->len
.t
.timer_start
;
538 if (elapsed
> good_enough
) return false;
541 if (u
->best2_ratio
> 0) {
542 /* Check best/best2 simulations ratio. If the
543 * two best moves give very similar results,
544 * keep simulating. */
545 if (best2
&& best2
->u
.playouts
546 && (double)best
->u
.playouts
/ best2
->u
.playouts
< u
->best2_ratio
) {
548 fprintf(stderr
, "Best2 ratio %f < threshold %f\n",
549 (double)best
->u
.playouts
/ best2
->u
.playouts
,
555 if (u
->bestr_ratio
> 0) {
556 /* Check best, best_best value difference. If the best move
557 * and its best child do not give similar enough results,
558 * keep simulating. */
559 if (bestr
&& bestr
->u
.playouts
560 && fabs((double)best
->u
.value
- bestr
->u
.value
) > u
->bestr_ratio
) {
562 fprintf(stderr
, "Bestr delta %f > threshold %f\n",
563 fabs((double)best
->u
.value
- bestr
->u
.value
),
569 if (winner
&& winner
!= best
) {
570 /* Keep simulating if best explored
571 * does not have also highest value. */
573 fprintf(stderr
, "[%d] best %3s [%d] %f != winner %3s [%d] %f\n", i
,
574 coord2sstr(best
->coord
, t
->board
),
575 best
->u
.playouts
, tree_node_get_value(t
, 1, best
->u
.value
),
576 coord2sstr(winner
->coord
, t
->board
),
577 winner
->u
.playouts
, tree_node_get_value(t
, 1, winner
->u
.value
));
581 /* No reason to keep simulating, bye. */
585 /* Run time-limited MCTS search on foreground. */
587 uct_search(struct uct
*u
, struct board
*b
, struct time_info
*ti
, enum stone color
, struct tree
*t
)
589 int base_playouts
= u
->t
->root
->u
.playouts
;
590 if (UDEBUGL(2) && base_playouts
> 0)
591 fprintf(stderr
, "<pre-simulated %d games skipped>\n", base_playouts
);
593 /* Set up time conditions. */
594 if (ti
->period
== TT_NULL
) *ti
= default_ti
;
595 struct time_stop stop
;
596 time_stop_conditions(ti
, b
, u
->fuseki_end
, u
->yose_start
, &stop
);
598 /* Number of last dynkomi adjustment. */
599 int last_dynkomi
= t
->root
->u
.playouts
;
600 /* Number of last game with progress print. */
601 int last_print
= t
->root
->u
.playouts
;
602 /* Number of simulations to wait before next print. */
603 int print_interval
= TREE_SIMPROGRESS_INTERVAL
* (u
->thread_model
== TM_ROOT
? 1 : u
->threads
);
604 /* Printed notification about full memory? */
605 bool print_fullmem
= false;
607 struct spawn_ctx
*ctx
= uct_search_start(u
, b
, color
, t
);
609 /* The search tree is ctx->t. This is normally == t, but in case of
610 * TM_ROOT, it is one of the trees belonging to the independent
611 * workers. It is important to reference ctx->t directly since the
612 * thread manager will swap the tree pointer asynchronously. */
613 /* XXX: This means TM_ROOT support is suboptimal since single stalled
614 * thread can stall the others in case of limiting the search by game
615 * count. However, TM_ROOT just does not deserve any more extra code
618 struct tree_node
*best
= NULL
;
619 struct tree_node
*best2
= NULL
; // Second-best move.
620 struct tree_node
*bestr
= NULL
; // best's best child.
621 struct tree_node
*winner
= NULL
;
623 double busywait_interval
= TREE_BUSYWAIT_INTERVAL
;
625 /* Now, just periodically poll the search tree. */
627 time_sleep(busywait_interval
);
628 /* busywait_interval should never be less than desired time, or the
629 * time control is broken. But if it happens to be less, we still search
630 * at least 100ms otherwise the move is completely random. */
632 int i
= ctx
->t
->root
->u
.playouts
;
634 /* Adjust dynkomi? */
635 if (ctx
->t
->use_extra_komi
&& u
->dynkomi
->permove
636 && u
->dynkomi_interval
637 && i
> last_dynkomi
+ u
->dynkomi_interval
) {
638 float old_dynkomi
= ctx
->t
->extra_komi
;
639 ctx
->t
->extra_komi
= u
->dynkomi
->permove(u
->dynkomi
, b
, ctx
->t
);
640 if (UDEBUGL(3) && old_dynkomi
!= ctx
->t
->extra_komi
)
641 fprintf(stderr
, "dynkomi adjusted (%f -> %f)\n", old_dynkomi
, ctx
->t
->extra_komi
);
644 /* Print progress? */
645 if (i
- last_print
> print_interval
) {
646 last_print
+= print_interval
; // keep the numbers tidy
647 uct_progress_status(u
, ctx
->t
, color
, last_print
);
649 if (!print_fullmem
&& ctx
->t
->nodes_size
> u
->max_tree_size
) {
651 fprintf(stderr
, "memory limit hit (%lu > %lu)\n", ctx
->t
->nodes_size
, u
->max_tree_size
);
652 print_fullmem
= true;
655 /* Never consider stopping if we played too few simulations.
656 * Maybe we risk losing on time when playing in super-extreme
657 * time pressure but the tree is going to be just too messed
658 * up otherwise - we might even play invalid suicides or pass
659 * when we mustn't. */
663 best
= u
->policy
->choose(u
->policy
, ctx
->t
->root
, b
, color
, resign
);
664 if (best
) best2
= u
->policy
->choose(u
->policy
, ctx
->t
->root
, b
, color
, best
->coord
);
666 /* Possibly stop search early if it's no use to try on. */
667 if (best
&& uct_search_stop_early(u
, ctx
->t
, b
, ti
, &stop
, best
, best2
, base_playouts
, i
))
670 /* Check against time settings. */
671 bool desired_done
= false;
672 if (ti
->dim
== TD_WALLTIME
) {
673 double elapsed
= time_now() - ti
->len
.t
.timer_start
;
674 if (elapsed
> stop
.worst
.time
) break;
675 desired_done
= elapsed
> stop
.desired
.time
;
677 } else { assert(ti
->dim
== TD_GAMES
);
678 if (i
> stop
.worst
.playouts
) break;
679 desired_done
= i
> stop
.desired
.playouts
;
682 /* We want to stop simulating, but are willing to keep trying
683 * if we aren't completely sure about the winner yet. */
685 if (u
->policy
->winner
&& u
->policy
->evaluate
) {
686 struct uct_descent descent
= { .node
= ctx
->t
->root
};
687 u
->policy
->winner(u
->policy
, ctx
->t
, &descent
);
688 winner
= descent
.node
;
691 bestr
= u
->policy
->choose(u
->policy
, best
, b
, stone_other(color
), resign
);
692 if (!uct_search_keep_looking(u
, ctx
->t
, b
, ti
, &stop
, best
, best2
, bestr
, winner
, i
))
696 /* TODO: Early break if best->variance goes under threshold and we already
697 * have enough playouts (possibly thanks to book or to pondering)? */
700 ctx
= uct_search_stop();
703 tree_dump(t
, u
->dumpthres
);
705 uct_progress_status(u
, t
, color
, ctx
->games
);
711 /* Start pondering background with @color to play. */
713 uct_pondering_start(struct uct
*u
, struct board
*b0
, struct tree
*t
, enum stone color
)
716 fprintf(stderr
, "Starting to ponder with color %s\n", stone2str(stone_other(color
)));
719 /* We need a local board copy to ponder upon. */
720 struct board
*b
= malloc(sizeof(*b
)); board_copy(b
, b0
);
722 /* *b0 did not have the genmove'd move played yet. */
723 struct move m
= { t
->root
->coord
, t
->root_color
};
724 int res
= board_play(b
, &m
);
726 setup_dynkomi(u
, b
, stone_other(m
.color
));
728 /* Start MCTS manager thread "headless". */
729 uct_search_start(u
, b
, color
, t
);
732 /* uct_search_stop() frontend for the pondering (non-genmove) mode. */
734 uct_pondering_stop(struct uct
*u
)
736 u
->pondering
= false;
737 if (!thread_manager_running
)
740 /* Stop the thread manager. */
741 struct spawn_ctx
*ctx
= uct_search_stop();
743 fprintf(stderr
, "(pondering) ");
744 uct_progress_status(u
, ctx
->t
, ctx
->color
, ctx
->games
);
751 uct_genmove(struct engine
*e
, struct board
*b
, struct time_info
*ti
, enum stone color
, bool pass_all_alive
)
753 double start_time
= time_now();
754 struct uct
*u
= e
->data
;
756 if (b
->superko_violation
) {
757 fprintf(stderr
, "!!! WARNING: SUPERKO VIOLATION OCCURED BEFORE THIS MOVE\n");
758 fprintf(stderr
, "Maybe you play with situational instead of positional superko?\n");
759 fprintf(stderr
, "I'm going to ignore the violation, but note that I may miss\n");
760 fprintf(stderr
, "some moves valid under this ruleset because of this.\n");
761 b
->superko_violation
= false;
765 uct_pondering_stop(u
);
766 prepare_move(e
, b
, color
);
770 /* How to decide whether to use dynkomi in this game? Since we use
771 * pondering, it's not simple "who-to-play" matter. Decide based on
772 * the last genmove issued. */
773 u
->t
->use_extra_komi
= !!(u
->dynkomi_mask
& color
);
774 setup_dynkomi(u
, b
, color
);
776 /* Make pessimistic assumption about komi for Japanese rules to
777 * avoid losing by 0.5 when winning by 0.5 with Chinese rules.
778 * The rules usually give the same winner if the integer part of komi
779 * is odd so we adjust the komi only if it is even (for a board of
780 * odd size). We are not trying to get an exact evaluation for rare
781 * cases of seki. For details see http://home.snafu.de/jasiek/parity.html
782 * TODO: Support the kgs-rules command once available. */
783 if (u
->territory_scoring
&& (((int)floor(b
->komi
) + board_size(b
)) & 1)) {
784 b
->komi
+= (color
== S_BLACK
? 1.0 : -1.0);
786 fprintf(stderr
, "Setting komi to %.1f assuming Japanese rules\n",
790 int base_playouts
= u
->t
->root
->u
.playouts
;
791 /* Perform the Monte Carlo Tree Search! */
792 int played_games
= uct_search(u
, b
, ti
, color
, u
->t
);
794 /* Choose the best move from the tree. */
795 struct tree_node
*best
= u
->policy
->choose(u
->policy
, u
->t
->root
, b
, color
, resign
);
797 if (!u
->slave
) reset_state(u
);
798 return coord_copy(pass
);
801 fprintf(stderr
, "*** WINNER is %s (%d,%d) with score %1.4f (%d/%d:%d/%d games), extra komi %f\n",
802 coord2sstr(best
->coord
, b
), coord_x(best
->coord
, b
), coord_y(best
->coord
, b
),
803 tree_node_get_value(u
->t
, 1, best
->u
.value
), best
->u
.playouts
,
804 u
->t
->root
->u
.playouts
, u
->t
->root
->u
.playouts
- base_playouts
, played_games
,
807 /* Do not resign if we're so short of time that evaluation of best
808 * move is completely unreliable, we might be winning actually.
809 * In this case best is almost random but still better than resign.
810 * Also do not resign if we are getting bad results while actually
811 * giving away extra komi points (dynkomi). */
812 if (tree_node_get_value(u
->t
, 1, best
->u
.value
) < u
->resign_ratio
813 && !is_pass(best
->coord
) && best
->u
.playouts
> GJ_MINGAMES
814 && u
->t
->extra_komi
<= 1 /* XXX we assume dynamic komi == we are black */) {
815 if (!u
->slave
) reset_state(u
);
816 return coord_copy(resign
);
819 /* If the opponent just passed and we win counting, always
821 if (b
->moves
> 1 && is_pass(b
->last_move
.coord
)) {
822 /* Make sure enough playouts are simulated. */
823 while (u
->ownermap
.playouts
< GJ_MINGAMES
)
824 uct_playout(u
, b
, color
, u
->t
);
825 if (uct_pass_is_safe(u
, b
, color
, u
->pass_all_alive
|| pass_all_alive
)) {
827 fprintf(stderr
, "<Will rather pass, looks safe enough.>\n");
832 /* If we are a slave in the distributed engine, we'll soon get
833 * a "play" command later telling us which move was chosen,
834 * and pondering now will not gain much. */
836 tree_promote_node(u
->t
, &best
);
838 /* After a pass, pondering is harmful for two reasons:
839 * (i) We might keep pondering even when the game is over.
840 * Of course this is the case for opponent resign as well.
841 * (ii) More importantly, the ownermap will get skewed since
842 * the UCT will start cutting off any playouts. */
843 if (u
->pondering_opt
&& !is_pass(best
->coord
)) {
844 uct_pondering_start(u
, b
, u
->t
, stone_other(color
));
848 double time
= time_now() - start_time
+ 0.000001; /* avoid divide by zero */
849 fprintf(stderr
, "genmove in %0.2fs (%d games/s, %d games/s/thread)\n",
850 time
, (int)(played_games
/time
), (int)(played_games
/time
/u
->threads
));
852 return coord_copy(best
->coord
);
857 uct_genmoves(struct engine
*e
, struct board
*b
, struct time_info
*ti
, enum stone color
, bool pass_all_alive
)
859 struct uct
*u
= e
->data
;
862 coord_t
*c
= uct_genmove(e
, b
, ti
, color
, pass_all_alive
);
864 /* Return a buffer with one line "total_playouts threads" then a list of lines
865 * "coord playouts value". Keep this code in sync with select_best_move(). */
866 static char reply
[10240];
868 char *end
= reply
+ sizeof(reply
);
869 struct tree_node
*root
= u
->t
->root
;
870 r
+= snprintf(r
, end
- r
, "%d %d", root
->u
.playouts
, u
->threads
);
871 int min_playouts
= root
->u
.playouts
/ 100;
873 // Give a large weight to pass or resign, but still allow other moves.
874 if (is_pass(*c
) || is_resign(*c
))
875 r
+= snprintf(r
, end
- r
, "\n%s %d %.1f", coord2sstr(*c
, b
), root
->u
.playouts
,
879 for (struct tree_node
*ni
= root
->children
; ni
; ni
= ni
->sibling
) {
880 if (ni
->u
.playouts
<= min_playouts
881 || ni
->hints
& TREE_HINT_INVALID
882 || is_pass(ni
->coord
))
884 char *coord
= coord2sstr(ni
->coord
, b
);
885 // We return the values as stored in the tree, so from black's view.
886 r
+= snprintf(r
, end
- r
, "\n%s %d %.7f", coord
, ni
->u
.playouts
, ni
->u
.value
);
893 uct_genbook(struct engine
*e
, struct board
*b
, struct time_info
*ti
, enum stone color
)
895 struct uct
*u
= e
->data
;
896 if (!u
->t
) prepare_move(e
, b
, color
);
899 if (ti
->dim
== TD_GAMES
) {
900 /* Don't count in games that already went into the book. */
901 ti
->len
.games
+= u
->t
->root
->u
.playouts
;
903 uct_search(u
, b
, ti
, color
, u
->t
);
905 assert(ti
->dim
== TD_GAMES
);
906 tree_save(u
->t
, b
, ti
->len
.games
/ 100);
912 uct_dumpbook(struct engine
*e
, struct board
*b
, enum stone color
)
914 struct uct
*u
= e
->data
;
915 struct tree
*t
= tree_init(b
, color
, u
->fast_alloc
? u
->max_tree_size
: 0, u
->local_tree_aging
);
923 uct_state_init(char *arg
, struct board
*b
)
925 struct uct
*u
= calloc(1, sizeof(struct uct
));
926 bool using_elo
= false;
928 u
->debug_level
= debug_level
;
929 u
->gamelen
= MC_GAMELEN
;
933 u
->playout_amaf
= true;
934 u
->playout_amaf_nakade
= false;
935 u
->amaf_prior
= false;
936 u
->max_tree_size
= 3072ULL * 1048576;
938 u
->dynkomi_mask
= S_BLACK
;
941 u
->thread_model
= TM_TREEVL
;
942 u
->parallel_tree
= true;
943 u
->virtual_loss
= true;
945 u
->fuseki_end
= 20; // max time at 361*20% = 72 moves (our 36th move, still 99 to play)
946 u
->yose_start
= 40; // (100-40-25)*361/100/2 = 63 moves still to play by us then
947 u
->bestr_ratio
= 0.02;
948 // 2.5 is clearly too much, but seems to compensate well for overly stern time allocations.
949 // TODO: Further tuning and experiments with better time allocation schemes.
950 u
->best2_ratio
= 2.5;
952 u
->val_scale
= 0.04; u
->val_points
= 40;
955 u
->local_tree_aging
= 2;
958 char *optspec
, *next
= arg
;
961 next
+= strcspn(next
, ",");
962 if (*next
) { *next
++ = 0; } else { *next
= 0; }
964 char *optname
= optspec
;
965 char *optval
= strchr(optspec
, '=');
966 if (optval
) *optval
++ = 0;
968 if (!strcasecmp(optname
, "debug")) {
970 u
->debug_level
= atoi(optval
);
973 } else if (!strcasecmp(optname
, "mercy") && optval
) {
974 /* Minimal difference of black/white captures
975 * to stop playout - "Mercy Rule". Speeds up
976 * hopeless playouts at the expense of some
978 u
->mercymin
= atoi(optval
);
979 } else if (!strcasecmp(optname
, "gamelen") && optval
) {
980 u
->gamelen
= atoi(optval
);
981 } else if (!strcasecmp(optname
, "expand_p") && optval
) {
982 u
->expand_p
= atoi(optval
);
983 } else if (!strcasecmp(optname
, "dumpthres") && optval
) {
984 u
->dumpthres
= atoi(optval
);
985 } else if (!strcasecmp(optname
, "best2_ratio") && optval
) {
986 /* If set, prolong simulating while
987 * first_best/second_best playouts ratio
988 * is less than best2_ratio. */
989 u
->best2_ratio
= atof(optval
);
990 } else if (!strcasecmp(optname
, "bestr_ratio") && optval
) {
991 /* If set, prolong simulating while
992 * best,best_best_child values delta
993 * is more than bestr_ratio. */
994 u
->bestr_ratio
= atof(optval
);
995 } else if (!strcasecmp(optname
, "playout_amaf")) {
996 /* Whether to include random playout moves in
997 * AMAF as well. (Otherwise, only tree moves
998 * are included in AMAF. Of course makes sense
999 * only in connection with an AMAF policy.) */
1000 /* with-without: 55.5% (+-4.1) */
1001 if (optval
&& *optval
== '0')
1002 u
->playout_amaf
= false;
1004 u
->playout_amaf
= true;
1005 } else if (!strcasecmp(optname
, "playout_amaf_nakade")) {
1006 /* Whether to include nakade moves from playouts
1007 * in the AMAF statistics; this tends to nullify
1008 * the playout_amaf effect by adding too much
1010 if (optval
&& *optval
== '0')
1011 u
->playout_amaf_nakade
= false;
1013 u
->playout_amaf_nakade
= true;
1014 } else if (!strcasecmp(optname
, "playout_amaf_cutoff") && optval
) {
1015 /* Keep only first N% of playout stage AMAF
1017 u
->playout_amaf_cutoff
= atoi(optval
);
1018 } else if ((!strcasecmp(optname
, "policy") || !strcasecmp(optname
, "random_policy")) && optval
) {
1019 char *policyarg
= strchr(optval
, ':');
1020 struct uct_policy
**p
= !strcasecmp(optname
, "policy") ? &u
->policy
: &u
->random_policy
;
1023 if (!strcasecmp(optval
, "ucb1")) {
1024 *p
= policy_ucb1_init(u
, policyarg
);
1025 } else if (!strcasecmp(optval
, "ucb1amaf")) {
1026 *p
= policy_ucb1amaf_init(u
, policyarg
);
1028 fprintf(stderr
, "UCT: Invalid tree policy %s\n", optval
);
1031 } else if (!strcasecmp(optname
, "playout") && optval
) {
1032 char *playoutarg
= strchr(optval
, ':');
1035 if (!strcasecmp(optval
, "moggy")) {
1036 u
->playout
= playout_moggy_init(playoutarg
, b
);
1037 } else if (!strcasecmp(optval
, "light")) {
1038 u
->playout
= playout_light_init(playoutarg
, b
);
1039 } else if (!strcasecmp(optval
, "elo")) {
1040 u
->playout
= playout_elo_init(playoutarg
, b
);
1043 fprintf(stderr
, "UCT: Invalid playout policy %s\n", optval
);
1046 } else if (!strcasecmp(optname
, "prior") && optval
) {
1047 u
->prior
= uct_prior_init(optval
, b
);
1048 } else if (!strcasecmp(optname
, "amaf_prior") && optval
) {
1049 u
->amaf_prior
= atoi(optval
);
1050 } else if (!strcasecmp(optname
, "threads") && optval
) {
1051 /* By default, Pachi will run with only single
1052 * tree search thread! */
1053 u
->threads
= atoi(optval
);
1054 } else if (!strcasecmp(optname
, "thread_model") && optval
) {
1055 if (!strcasecmp(optval
, "root")) {
1056 /* Root parallelization - each thread
1057 * does independent search, trees are
1058 * merged at the end. */
1059 u
->thread_model
= TM_ROOT
;
1060 u
->parallel_tree
= false;
1061 u
->virtual_loss
= false;
1062 } else if (!strcasecmp(optval
, "tree")) {
1063 /* Tree parallelization - all threads
1064 * grind on the same tree. */
1065 u
->thread_model
= TM_TREE
;
1066 u
->parallel_tree
= true;
1067 u
->virtual_loss
= false;
1068 } else if (!strcasecmp(optval
, "treevl")) {
1069 /* Tree parallelization, but also
1070 * with virtual losses - this discou-
1071 * rages most threads choosing the
1072 * same tree branches to read. */
1073 u
->thread_model
= TM_TREEVL
;
1074 u
->parallel_tree
= true;
1075 u
->virtual_loss
= true;
1077 fprintf(stderr
, "UCT: Invalid thread model %s\n", optval
);
1080 } else if (!strcasecmp(optname
, "pondering")) {
1081 /* Keep searching even during opponent's turn. */
1082 u
->pondering_opt
= !optval
|| atoi(optval
);
1083 } else if (!strcasecmp(optname
, "fuseki_end") && optval
) {
1084 /* At the very beginning it's not worth thinking
1085 * too long because the playout evaluations are
1086 * very noisy. So gradually increase the thinking
1087 * time up to maximum when fuseki_end percent
1088 * of the board has been played.
1089 * This only applies if we are not in byoyomi. */
1090 u
->fuseki_end
= atoi(optval
);
1091 } else if (!strcasecmp(optname
, "yose_start") && optval
) {
1092 /* When yose_start percent of the board has been
1093 * played, or if we are in byoyomi, stop spending
1094 * more time and spread the remaining time
1096 * Between fuseki_end and yose_start, we spend
1097 * a constant proportion of the remaining time
1098 * on each move. (yose_start should actually
1099 * be much earlier than when real yose start,
1100 * but "yose" is a good short name to convey
1102 u
->yose_start
= atoi(optval
);
1103 } else if (!strcasecmp(optname
, "force_seed") && optval
) {
1104 u
->force_seed
= atoi(optval
);
1105 } else if (!strcasecmp(optname
, "no_book")) {
1107 } else if (!strcasecmp(optname
, "dynkomi") && optval
) {
1108 /* Dynamic komi approach; there are multiple
1109 * ways to adjust komi dynamically throughout
1110 * play. We currently support two: */
1111 char *dynkomiarg
= strchr(optval
, ':');
1114 if (!strcasecmp(optval
, "none")) {
1115 u
->dynkomi
= uct_dynkomi_init_none(u
, dynkomiarg
, b
);
1116 } else if (!strcasecmp(optval
, "linear")) {
1117 u
->dynkomi
= uct_dynkomi_init_linear(u
, dynkomiarg
, b
);
1118 } else if (!strcasecmp(optval
, "adaptive")) {
1119 u
->dynkomi
= uct_dynkomi_init_adaptive(u
, dynkomiarg
, b
);
1121 fprintf(stderr
, "UCT: Invalid dynkomi mode %s\n", optval
);
1124 } else if (!strcasecmp(optname
, "dynkomi_mask") && optval
) {
1125 /* Bitmask of colors the player must be
1126 * for dynkomi be applied; you may want
1127 * to use dynkomi_mask=3 to allow dynkomi
1128 * even in games where Pachi is white. */
1129 u
->dynkomi_mask
= atoi(optval
);
1130 } else if (!strcasecmp(optname
, "dynkomi_interval") && optval
) {
1131 /* If non-zero, re-adjust dynamic komi
1132 * throughout a single genmove reading,
1133 * roughly every N simulations. */
1134 u
->dynkomi_interval
= atoi(optval
);
1135 } else if (!strcasecmp(optname
, "val_scale") && optval
) {
1136 /* How much of the game result value should be
1137 * influenced by win size. Zero means it isn't. */
1138 u
->val_scale
= atof(optval
);
1139 } else if (!strcasecmp(optname
, "val_points") && optval
) {
1140 /* Maximum size of win to be scaled into game
1141 * result value. Zero means boardsize^2. */
1142 u
->val_points
= atoi(optval
) * 2; // result values are doubled
1143 } else if (!strcasecmp(optname
, "val_extra")) {
1144 /* If false, the score coefficient will be simply
1145 * added to the value, instead of scaling the result
1146 * coefficient because of it. */
1147 u
->val_extra
= !optval
|| atoi(optval
);
1148 } else if (!strcasecmp(optname
, "local_tree") && optval
) {
1149 /* Whether to bias exploration by local tree values
1150 * (must be supported by the used policy).
1152 * 1: Do, value = result.
1153 * Try to temper the result:
1154 * 2: Do, value = 0.5+(result-expected)/2.
1155 * 3: Do, value = 0.5+bzz((result-expected)^2).
1156 * 4: Do, value = 0.5+sqrt(result-expected)/2. */
1157 u
->local_tree
= atoi(optval
);
1158 } else if (!strcasecmp(optname
, "tenuki_d") && optval
) {
1159 /* Tenuki distance at which to break the local tree. */
1160 u
->tenuki_d
= atoi(optval
);
1161 if (u
->tenuki_d
> TREE_NODE_D_MAX
+ 1) {
1162 fprintf(stderr
, "uct: tenuki_d must not be larger than TREE_NODE_D_MAX+1 %d\n", TREE_NODE_D_MAX
+ 1);
1165 } else if (!strcasecmp(optname
, "local_tree_aging") && optval
) {
1166 /* How much to reduce local tree values between moves. */
1167 u
->local_tree_aging
= atof(optval
);
1168 } else if (!strcasecmp(optname
, "local_tree_allseq")) {
1169 /* By default, only complete sequences are stored
1170 * in the local tree. If this is on, also
1171 * subsequences starting at each move are stored. */
1172 u
->local_tree_allseq
= !optval
|| atoi(optval
);
1173 } else if (!strcasecmp(optname
, "local_tree_playout")) {
1174 /* Whether to adjust ELO playout probability
1175 * distributions according to matched localtree
1177 u
->local_tree_playout
= !optval
|| atoi(optval
);
1178 } else if (!strcasecmp(optname
, "local_tree_pseqroot")) {
1179 /* By default, when we have no sequence move
1180 * to suggest in-playout, we give up. If this
1181 * is on, we make probability distribution from
1182 * sequences first moves instead. */
1183 u
->local_tree_pseqroot
= !optval
|| atoi(optval
);
1184 } else if (!strcasecmp(optname
, "pass_all_alive")) {
1185 /* Whether to consider all stones alive at the game
1186 * end instead of marking dead groupd. */
1187 u
->pass_all_alive
= !optval
|| atoi(optval
);
1188 } else if (!strcasecmp(optname
, "territory_scoring")) {
1189 /* Use territory scoring (default is area scoring).
1190 * An explicit kgs-rules command overrides this. */
1191 u
->territory_scoring
= !optval
|| atoi(optval
);
1192 } else if (!strcasecmp(optname
, "random_policy_chance") && optval
) {
1193 /* If specified (N), with probability 1/N, random_policy policy
1194 * descend is used instead of main policy descend; useful
1195 * if specified policy (e.g. UCB1AMAF) can make unduly biased
1196 * choices sometimes, you can fall back to e.g.
1197 * random_policy=UCB1. */
1198 u
->random_policy_chance
= atoi(optval
);
1199 } else if (!strcasecmp(optname
, "max_tree_size") && optval
) {
1200 /* Maximum amount of memory [MiB] consumed by the move tree.
1201 * For fast_alloc it includes the temp tree used for pruning.
1202 * Default is 3072 (3 GiB). Note that if you use TM_ROOT,
1203 * this limits size of only one of the trees, not all of them
1205 u
->max_tree_size
= atol(optval
) * 1048576;
1206 } else if (!strcasecmp(optname
, "fast_alloc")) {
1207 u
->fast_alloc
= !optval
|| atoi(optval
);
1208 } else if (!strcasecmp(optname
, "slave")) {
1209 /* Act as slave for the distributed engine. */
1210 u
->slave
= !optval
|| atoi(optval
);
1211 } else if (!strcasecmp(optname
, "banner") && optval
) {
1212 /* Additional banner string. This must come as the
1213 * last engine parameter. */
1214 if (*next
) *--next
= ',';
1215 u
->banner
= strdup(optval
);
1218 fprintf(stderr
, "uct: Invalid engine argument %s or missing value\n", optname
);
1224 u
->resign_ratio
= 0.2; /* Resign when most games are lost. */
1225 u
->loss_threshold
= 0.85; /* Stop reading if after at least 2000 playouts this is best value. */
1227 u
->policy
= policy_ucb1amaf_init(u
, NULL
);
1229 if (!!u
->random_policy_chance
^ !!u
->random_policy
) {
1230 fprintf(stderr
, "uct: Only one of random_policy and random_policy_chance is set\n");
1234 if (!u
->local_tree
) {
1235 /* No ltree aging. */
1236 u
->local_tree_aging
= 1.0f
;
1239 u
->local_tree_playout
= false;
1241 if (u
->fast_alloc
&& !u
->parallel_tree
) {
1242 fprintf(stderr
, "fast_alloc not supported with root parallelization.\n");
1246 u
->max_tree_size
= (100ULL * u
->max_tree_size
) / (100 + MIN_FREE_MEM_PERCENT
);
1249 u
->prior
= uct_prior_init(NULL
, b
);
1252 u
->playout
= playout_moggy_init(NULL
, b
);
1253 u
->playout
->debug_level
= u
->debug_level
;
1255 u
->ownermap
.map
= malloc(board_size2(b
) * sizeof(u
->ownermap
.map
[0]));
1258 u
->dynkomi
= uct_dynkomi_init_linear(u
, NULL
, b
);
1260 /* Some things remain uninitialized for now - the opening book
1261 * is not loaded and the tree not set up. */
1262 /* This will be initialized in setup_state() at the first move
1263 * received/requested. This is because right now we are not aware
1264 * about any komi or handicap setup and such. */
1270 engine_uct_init(char *arg
, struct board
*b
)
1272 struct uct
*u
= uct_state_init(arg
, b
);
1273 struct engine
*e
= calloc(1, sizeof(struct engine
));
1274 e
->name
= "UCT Engine";
1275 e
->printhook
= uct_printhook_ownermap
;
1276 e
->notify_play
= uct_notify_play
;
1278 e
->genmove
= uct_genmove
;
1279 e
->genmoves
= uct_genmoves
;
1280 e
->dead_group_list
= uct_dead_group_list
;
1284 e
->notify
= uct_notify
;
1286 const char banner
[] = "I'm playing UCT. When I'm losing, I will resign, "
1287 "if I think I win, I play until you pass. "
1288 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
1289 if (!u
->banner
) u
->banner
= "";
1290 e
->comment
= malloc(sizeof(banner
) + strlen(u
->banner
) + 1);
1291 sprintf(e
->comment
, "%s %s", banner
, u
->banner
);