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
);
36 static char *uct_getstats(struct uct
*u
, struct board
*b
, coord_t
*c
);
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 /* How often to send stats updates for the distributed engine (in seconds). */
62 #define STATS_SEND_INTERVAL 0.5
64 /* When terminating uct_search() early, the safety margin to add to the
65 * remaining playout number estimate when deciding whether the result can
67 #define PLAYOUT_DELTA_SAFEMARGIN 1000
71 setup_state(struct uct
*u
, struct board
*b
, enum stone color
)
73 u
->t
= tree_init(b
, color
, u
->fast_alloc
? u
->max_tree_size
: 0, u
->local_tree_aging
);
75 fast_srandom(u
->force_seed
);
77 fprintf(stderr
, "Fresh board with random seed %lu\n", fast_getseed());
78 //board_print(b, stderr);
79 if (!u
->no_book
&& b
->moves
== 0) {
80 assert(color
== S_BLACK
);
86 reset_state(struct uct
*u
)
89 tree_done(u
->t
); u
->t
= NULL
;
93 setup_dynkomi(struct uct
*u
, struct board
*b
, enum stone to_play
)
95 if (u
->t
->use_extra_komi
&& u
->dynkomi
->permove
)
96 u
->t
->extra_komi
= u
->dynkomi
->permove(u
->dynkomi
, b
, u
->t
);
100 prepare_move(struct engine
*e
, struct board
*b
, enum stone color
)
102 struct uct
*u
= e
->data
;
105 /* Verify that we have sane state. */
107 assert(u
->t
&& b
->moves
);
108 if (color
!= stone_other(u
->t
->root_color
)) {
109 fprintf(stderr
, "Fatal: Non-alternating play detected %d %d\n",
110 color
, u
->t
->root_color
);
115 /* We need fresh state. */
117 setup_state(u
, b
, color
);
120 u
->ownermap
.playouts
= 0;
121 memset(u
->ownermap
.map
, 0, board_size2(b
) * sizeof(u
->ownermap
.map
[0]));
125 dead_group_list(struct uct
*u
, struct board
*b
, struct move_queue
*mq
)
127 struct group_judgement gj
;
129 gj
.gs
= alloca(board_size2(b
) * sizeof(gj
.gs
[0]));
130 board_ownermap_judge_group(b
, &u
->ownermap
, &gj
);
131 groups_of_status(b
, &gj
, GS_DEAD
, mq
);
135 uct_pass_is_safe(struct uct
*u
, struct board
*b
, enum stone color
, bool pass_all_alive
)
137 if (u
->ownermap
.playouts
< GJ_MINGAMES
)
140 struct move_queue mq
= { .moves
= 0 };
141 dead_group_list(u
, b
, &mq
);
142 if (pass_all_alive
&& mq
.moves
> 0)
143 return false; // We need to remove some dead groups first.
144 return pass_is_safe(b
, color
, &mq
);
147 /* This function is called only when running as slave in the distributed version. */
148 static enum parse_code
149 uct_notify(struct engine
*e
, struct board
*b
, int id
, char *cmd
, char *args
, char **reply
)
151 struct uct
*u
= e
->data
;
153 static bool board_resized
= false;
154 board_resized
|= is_gamestart(cmd
);
156 /* Force resending the whole command history if we are out of sync
157 * but do it only once, not if already getting the history. */
158 if ((move_number(id
) != b
->moves
|| !board_resized
)
159 && !reply_disabled(id
) && !is_reset(cmd
)) {
161 fprintf(stderr
, "Out of sync, id %d, move %d\n", id
, b
->moves
);
162 static char buf
[128];
163 snprintf(buf
, sizeof(buf
), "out of sync, move %d expected", b
->moves
);
168 return reply_disabled(id
) ? P_NOREPLY
: P_OK
;
172 uct_printhook_ownermap(struct board
*board
, coord_t c
, char *s
, char *end
)
174 struct uct
*u
= board
->es
;
176 const char chr
[] = ":XO,"; // dame, black, white, unclear
177 const char chm
[] = ":xo,";
178 char ch
= chr
[board_ownermap_judge_point(&u
->ownermap
, c
, GJ_THRES
)];
179 if (ch
== ',') { // less precise estimate then?
180 ch
= chm
[board_ownermap_judge_point(&u
->ownermap
, c
, 0.67)];
182 s
+= snprintf(s
, end
- s
, "%c ", ch
);
187 uct_notify_play(struct engine
*e
, struct board
*b
, struct move
*m
)
189 struct uct
*u
= e
->data
;
191 /* No state, create one - this is probably game beginning
192 * and we need to load the opening book right now. */
193 prepare_move(e
, b
, m
->color
);
197 /* Stop pondering, required by tree_promote_at() */
198 uct_pondering_stop(u
);
200 if (is_resign(m
->coord
)) {
206 /* Promote node of the appropriate move to the tree root. */
208 if (!tree_promote_at(u
->t
, b
, m
->coord
)) {
210 fprintf(stderr
, "Warning: Cannot promote move node! Several play commands in row?\n");
215 /* If we are a slave in a distributed engine, start pondering once
216 * we know which move we actually played. See uct_genmove() about
217 * the check for pass. */
218 if (u
->pondering_opt
&& u
->slave
&& m
->color
== u
->my_color
&& !is_pass(m
->coord
))
219 uct_pondering_start(u
, b
, u
->t
, stone_other(m
->color
));
225 uct_chat(struct engine
*e
, struct board
*b
, char *cmd
)
227 struct uct
*u
= e
->data
;
228 static char reply
[1024];
230 cmd
+= strspn(cmd
, " \n\t");
231 if (!strncasecmp(cmd
, "winrate", 7)) {
233 return "no game context (yet?)";
234 enum stone color
= u
->t
->root_color
;
235 struct tree_node
*n
= u
->t
->root
;
236 snprintf(reply
, 1024, "In %d playouts at %d threads, %s %s can win with %.2f%% probability",
237 n
->u
.playouts
, u
->threads
, stone2str(color
), coord2sstr(n
->coord
, b
),
238 tree_node_get_value(u
->t
, -1, n
->u
.value
) * 100);
239 if (u
->t
->use_extra_komi
&& abs(u
->t
->extra_komi
) >= 0.5) {
240 sprintf(reply
+ strlen(reply
), ", while self-imposing extra komi %.1f",
250 uct_dead_group_list(struct engine
*e
, struct board
*b
, struct move_queue
*mq
)
252 struct uct
*u
= e
->data
;
254 /* This means the game is probably over, no use pondering on. */
255 uct_pondering_stop(u
);
257 if (u
->pass_all_alive
)
258 return; // no dead groups
260 bool mock_state
= false;
263 /* No state, but we cannot just back out - we might
264 * have passed earlier, only assuming some stones are
265 * dead, and then re-connected, only to lose counting
266 * when all stones are assumed alive. */
267 /* Mock up some state and seed the ownermap by few
269 prepare_move(e
, b
, S_BLACK
); assert(u
->t
);
270 for (int i
= 0; i
< GJ_MINGAMES
; i
++)
271 uct_playout(u
, b
, S_BLACK
, u
->t
);
275 dead_group_list(u
, b
, mq
);
278 /* Clean up the mock state in case we will receive
279 * a genmove; we could get a non-alternating-move
280 * error from prepare_move() in that case otherwise. */
286 playout_policy_done(struct playout_policy
*p
)
288 if (p
->done
) p
->done(p
);
289 if (p
->data
) free(p
->data
);
294 uct_done(struct engine
*e
)
296 /* This is called on engine reset, especially when clear_board
297 * is received and new game should begin. */
298 struct uct
*u
= e
->data
;
299 uct_pondering_stop(u
);
300 if (u
->t
) reset_state(u
);
301 free(u
->ownermap
.map
);
304 free(u
->random_policy
);
305 playout_policy_done(u
->playout
);
306 uct_prior_done(u
->prior
);
310 /* Pachi threading structure (if uct_playouts_parallel() is used):
313 * | main(), GTP communication, ...
314 * | starts and stops the search managed by thread_manager
317 * | spawns and collects worker threads
323 * uct_playouts() loop, doing descend-playout until uct_halt
325 * Another way to look at it is by functions (lines denote thread boundaries):
328 * | uct_search() (uct_search_start() .. uct_search_stop())
329 * | -----------------------
330 * | spawn_thread_manager()
331 * | -----------------------
333 * V uct_playouts() */
335 /* Set in thread manager in case the workers should stop. */
336 volatile sig_atomic_t uct_halt
= 0;
337 /* ID of the running worker thread. */
338 __thread
int thread_id
= -1;
339 /* ID of the thread manager. */
340 static pthread_t thread_manager
;
341 static bool thread_manager_running
;
343 static pthread_mutex_t finish_mutex
= PTHREAD_MUTEX_INITIALIZER
;
344 static pthread_cond_t finish_cond
= PTHREAD_COND_INITIALIZER
;
345 static volatile int finish_thread
;
346 static pthread_mutex_t finish_serializer
= PTHREAD_MUTEX_INITIALIZER
;
359 spawn_worker(void *ctx_
)
361 struct spawn_ctx
*ctx
= ctx_
;
363 fast_srandom(ctx
->seed
);
364 thread_id
= ctx
->tid
;
366 ctx
->games
= uct_playouts(ctx
->u
, ctx
->b
, ctx
->color
, ctx
->t
);
368 pthread_mutex_lock(&finish_serializer
);
369 pthread_mutex_lock(&finish_mutex
);
370 finish_thread
= ctx
->tid
;
371 pthread_cond_signal(&finish_cond
);
372 pthread_mutex_unlock(&finish_mutex
);
376 /* Thread manager, controlling worker threads. It must be called with
377 * finish_mutex lock held, but it will unlock it itself before exiting;
378 * this is necessary to be completely deadlock-free. */
379 /* The finish_cond can be signalled for it to stop; in that case,
380 * the caller should set finish_thread = -1. */
381 /* After it is started, it will update mctx->t to point at some tree
382 * used for the actual search (matters only for TM_ROOT), on return
383 * it will set mctx->games to the number of performed simulations. */
385 spawn_thread_manager(void *ctx_
)
387 /* In thread_manager, we use only some of the ctx fields. */
388 struct spawn_ctx
*mctx
= ctx_
;
389 struct uct
*u
= mctx
->u
;
390 struct tree
*t
= mctx
->t
;
391 bool shared_tree
= u
->parallel_tree
;
392 fast_srandom(mctx
->seed
);
394 int played_games
= 0;
395 pthread_t threads
[u
->threads
];
400 /* Garbage collect the tree by preference when pondering. */
401 if (u
->pondering
&& t
->nodes
&& t
->nodes_size
> t
->max_tree_size
/2) {
402 unsigned long temp_size
= (MIN_FREE_MEM_PERCENT
* t
->max_tree_size
) / 100;
403 t
->root
= tree_garbage_collect(t
, temp_size
, t
->root
);
406 /* Spawn threads... */
407 for (int ti
= 0; ti
< u
->threads
; ti
++) {
408 struct spawn_ctx
*ctx
= malloc(sizeof(*ctx
));
409 ctx
->u
= u
; ctx
->b
= mctx
->b
; ctx
->color
= mctx
->color
;
410 mctx
->t
= ctx
->t
= shared_tree
? t
: tree_copy(t
);
411 ctx
->tid
= ti
; ctx
->seed
= fast_random(65536) + ti
;
412 pthread_create(&threads
[ti
], NULL
, spawn_worker
, ctx
);
414 fprintf(stderr
, "Spawned worker %d\n", ti
);
417 /* ...and collect them back: */
418 while (joined
< u
->threads
) {
419 /* Wait for some thread to finish... */
420 pthread_cond_wait(&finish_cond
, &finish_mutex
);
421 if (finish_thread
< 0) {
422 /* Stop-by-caller. Tell the workers to wrap up. */
426 /* ...and gather its remnants. */
427 struct spawn_ctx
*ctx
;
428 pthread_join(threads
[finish_thread
], (void **) &ctx
);
429 played_games
+= ctx
->games
;
432 if (ctx
->t
== mctx
->t
) mctx
->t
= t
;
433 tree_merge(t
, ctx
->t
);
438 fprintf(stderr
, "Joined worker %d\n", finish_thread
);
439 pthread_mutex_unlock(&finish_serializer
);
442 pthread_mutex_unlock(&finish_mutex
);
445 tree_normalize(mctx
->t
, u
->threads
);
447 mctx
->games
= played_games
;
451 static struct spawn_ctx
*
452 uct_search_start(struct uct
*u
, struct board
*b
, enum stone color
, struct tree
*t
)
454 assert(u
->threads
> 0);
455 assert(!thread_manager_running
);
457 struct spawn_ctx ctx
= { .u
= u
, .b
= b
, .color
= color
, .t
= t
, .seed
= fast_random(65536) };
458 static struct spawn_ctx mctx
; mctx
= ctx
;
459 pthread_mutex_lock(&finish_mutex
);
460 pthread_create(&thread_manager
, NULL
, spawn_thread_manager
, &mctx
);
461 thread_manager_running
= true;
465 static struct spawn_ctx
*
466 uct_search_stop(void)
468 assert(thread_manager_running
);
470 /* Signal thread manager to stop the workers. */
471 pthread_mutex_lock(&finish_mutex
);
473 pthread_cond_signal(&finish_cond
);
474 pthread_mutex_unlock(&finish_mutex
);
476 /* Collect the thread manager. */
477 struct spawn_ctx
*pctx
;
478 thread_manager_running
= false;
479 pthread_join(thread_manager
, (void **) &pctx
);
484 /* Determine whether we should terminate the search early. */
486 uct_search_stop_early(struct uct
*u
, struct tree
*t
, struct board
*b
,
487 struct time_info
*ti
, struct time_stop
*stop
,
488 struct tree_node
*best
, struct tree_node
*best2
,
489 int base_playouts
, int i
)
491 /* Always use at least half the desired time. It is silly
492 * to lose a won game because we played a bad move in 0.1s. */
494 if (ti
->dim
== TD_WALLTIME
) {
495 elapsed
= time_now() - ti
->len
.t
.timer_start
;
496 if (elapsed
< 0.5 * stop
->desired
.time
) return false;
499 /* Early break in won situation. */
500 if (best
->u
.playouts
>= 2000 && tree_node_get_value(t
, 1, best
->u
.value
) >= u
->loss_threshold
)
502 /* Earlier break in super-won situation. */
503 if (best
->u
.playouts
>= 500 && tree_node_get_value(t
, 1, best
->u
.value
) >= 0.95)
506 /* Break early if we estimate the second-best move cannot
507 * catch up in assigned time anymore. We use all our time
508 * if we are in byoyomi with single stone remaining in our
509 * period, however - it's better to pre-ponder. */
510 bool time_indulgent
= (!ti
->len
.t
.main_time
&& ti
->len
.t
.byoyomi_stones
== 1);
511 if (best2
&& ti
->dim
== TD_WALLTIME
&& !time_indulgent
) {
512 double remaining
= stop
->worst
.time
- elapsed
;
513 double pps
= ((double)i
- base_playouts
) / elapsed
;
514 double estplayouts
= remaining
* pps
+ PLAYOUT_DELTA_SAFEMARGIN
;
515 if (best
->u
.playouts
> best2
->u
.playouts
+ estplayouts
) {
517 fprintf(stderr
, "Early stop, result cannot change: "
518 "best %d, best2 %d, estimated %f simulations to go\n",
519 best
->u
.playouts
, best2
->u
.playouts
, estplayouts
);
527 /* Determine whether we should terminate the search later than expected. */
529 uct_search_keep_looking(struct uct
*u
, struct tree
*t
, struct board
*b
,
530 struct time_info
*ti
, struct time_stop
*stop
,
531 struct tree_node
*best
, struct tree_node
*best2
,
532 struct tree_node
*bestr
, struct tree_node
*winner
, int i
)
536 fprintf(stderr
, "Did not find best move, still trying...\n");
540 /* Do not waste time if we are winning. Spend up to worst time if
541 * we are unsure, but only desired time if we are sure of winning. */
542 float beta
= 2 * (tree_node_get_value(t
, 1, best
->u
.value
) - 0.5);
543 if (ti
->dim
== TD_WALLTIME
&& beta
> 0) {
544 double good_enough
= stop
->desired
.time
* beta
+ stop
->worst
.time
* (1 - beta
);
545 double elapsed
= time_now() - ti
->len
.t
.timer_start
;
546 if (elapsed
> good_enough
) return false;
549 if (u
->best2_ratio
> 0) {
550 /* Check best/best2 simulations ratio. If the
551 * two best moves give very similar results,
552 * keep simulating. */
553 if (best2
&& best2
->u
.playouts
554 && (double)best
->u
.playouts
/ best2
->u
.playouts
< u
->best2_ratio
) {
556 fprintf(stderr
, "Best2 ratio %f < threshold %f\n",
557 (double)best
->u
.playouts
/ best2
->u
.playouts
,
563 if (u
->bestr_ratio
> 0) {
564 /* Check best, best_best value difference. If the best move
565 * and its best child do not give similar enough results,
566 * keep simulating. */
567 if (bestr
&& bestr
->u
.playouts
568 && fabs((double)best
->u
.value
- bestr
->u
.value
) > u
->bestr_ratio
) {
570 fprintf(stderr
, "Bestr delta %f > threshold %f\n",
571 fabs((double)best
->u
.value
- bestr
->u
.value
),
577 if (winner
&& winner
!= best
) {
578 /* Keep simulating if best explored
579 * does not have also highest value. */
581 fprintf(stderr
, "[%d] best %3s [%d] %f != winner %3s [%d] %f\n", i
,
582 coord2sstr(best
->coord
, t
->board
),
583 best
->u
.playouts
, tree_node_get_value(t
, 1, best
->u
.value
),
584 coord2sstr(winner
->coord
, t
->board
),
585 winner
->u
.playouts
, tree_node_get_value(t
, 1, winner
->u
.value
));
589 /* No reason to keep simulating, bye. */
593 /* Run time-limited MCTS search on foreground. */
595 uct_search(struct uct
*u
, struct board
*b
, struct time_info
*ti
, enum stone color
, struct tree
*t
)
597 int base_playouts
= u
->t
->root
->u
.playouts
;
598 if (UDEBUGL(2) && base_playouts
> 0)
599 fprintf(stderr
, "<pre-simulated %d games skipped>\n", base_playouts
);
601 /* Set up time conditions. */
602 if (ti
->period
== TT_NULL
) *ti
= default_ti
;
603 struct time_stop stop
;
604 time_stop_conditions(ti
, b
, u
->fuseki_end
, u
->yose_start
, &stop
);
606 /* Number of last dynkomi adjustment. */
607 int last_dynkomi
= t
->root
->u
.playouts
;
608 /* Number of last game with progress print. */
609 int last_print
= t
->root
->u
.playouts
;
610 /* Number of simulations to wait before next print. */
611 int print_interval
= TREE_SIMPROGRESS_INTERVAL
* (u
->thread_model
== TM_ROOT
? 1 : u
->threads
);
612 /* Printed notification about full memory? */
613 bool print_fullmem
= false;
614 /* Absolute time of last distributed stats update. */
615 double last_stats_sent
= time_now();
616 /* Interval between distributed stats updates. */
617 double stats_interval
= STATS_SEND_INTERVAL
;
619 struct spawn_ctx
*ctx
= uct_search_start(u
, b
, color
, t
);
621 /* The search tree is ctx->t. This is normally == t, but in case of
622 * TM_ROOT, it is one of the trees belonging to the independent
623 * workers. It is important to reference ctx->t directly since the
624 * thread manager will swap the tree pointer asynchronously. */
625 /* XXX: This means TM_ROOT support is suboptimal since single stalled
626 * thread can stall the others in case of limiting the search by game
627 * count. However, TM_ROOT just does not deserve any more extra code
630 struct tree_node
*best
= NULL
;
631 struct tree_node
*best2
= NULL
; // Second-best move.
632 struct tree_node
*bestr
= NULL
; // best's best child.
633 struct tree_node
*winner
= NULL
;
635 double busywait_interval
= TREE_BUSYWAIT_INTERVAL
;
637 /* Now, just periodically poll the search tree. */
639 time_sleep(busywait_interval
);
640 /* busywait_interval should never be less than desired time, or the
641 * time control is broken. But if it happens to be less, we still search
642 * at least 100ms otherwise the move is completely random. */
644 int i
= ctx
->t
->root
->u
.playouts
;
646 /* Adjust dynkomi? */
647 if (ctx
->t
->use_extra_komi
&& u
->dynkomi
->permove
648 && u
->dynkomi_interval
649 && i
> last_dynkomi
+ u
->dynkomi_interval
) {
650 last_dynkomi
+= u
->dynkomi_interval
;
651 float old_dynkomi
= ctx
->t
->extra_komi
;
652 ctx
->t
->extra_komi
= u
->dynkomi
->permove(u
->dynkomi
, b
, ctx
->t
);
653 if (UDEBUGL(3) && old_dynkomi
!= ctx
->t
->extra_komi
)
654 fprintf(stderr
, "dynkomi adjusted (%f -> %f)\n", old_dynkomi
, ctx
->t
->extra_komi
);
657 /* Print progress? */
658 if (i
- last_print
> print_interval
) {
659 last_print
+= print_interval
; // keep the numbers tidy
660 uct_progress_status(u
, ctx
->t
, color
, last_print
);
662 if (!print_fullmem
&& ctx
->t
->nodes_size
> u
->max_tree_size
) {
664 fprintf(stderr
, "memory limit hit (%lu > %lu)\n", ctx
->t
->nodes_size
, u
->max_tree_size
);
665 print_fullmem
= true;
668 /* Never consider stopping if we played too few simulations.
669 * Maybe we risk losing on time when playing in super-extreme
670 * time pressure but the tree is going to be just too messed
671 * up otherwise - we might even play invalid suicides or pass
672 * when we mustn't. */
676 best
= u
->policy
->choose(u
->policy
, ctx
->t
->root
, b
, color
, resign
);
677 if (best
) best2
= u
->policy
->choose(u
->policy
, ctx
->t
->root
, b
, color
, best
->coord
);
679 /* Possibly stop search early if it's no use to try on. */
680 if (best
&& uct_search_stop_early(u
, ctx
->t
, b
, ti
, &stop
, best
, best2
, base_playouts
, i
))
683 /* Check against time settings. */
684 bool desired_done
= false;
685 double now
= time_now();
686 if (ti
->dim
== TD_WALLTIME
) {
687 double elapsed
= now
- ti
->len
.t
.timer_start
;
688 if (elapsed
> stop
.worst
.time
) break;
689 desired_done
= elapsed
> stop
.desired
.time
;
690 if (stats_interval
< 0.1 * stop
.desired
.time
)
691 stats_interval
= 0.1 * stop
.desired
.time
;
693 } else { assert(ti
->dim
== TD_GAMES
);
694 if (i
> stop
.worst
.playouts
) break;
695 desired_done
= i
> stop
.desired
.playouts
;
698 /* We want to stop simulating, but are willing to keep trying
699 * if we aren't completely sure about the winner yet. */
701 if (u
->policy
->winner
&& u
->policy
->evaluate
) {
702 struct uct_descent descent
= { .node
= ctx
->t
->root
};
703 u
->policy
->winner(u
->policy
, ctx
->t
, &descent
);
704 winner
= descent
.node
;
707 bestr
= u
->policy
->choose(u
->policy
, best
, b
, stone_other(color
), resign
);
708 if (!uct_search_keep_looking(u
, ctx
->t
, b
, ti
, &stop
, best
, best2
, bestr
, winner
, i
))
712 /* TODO: Early break if best->variance goes under threshold and we already
713 * have enough playouts (possibly thanks to book or to pondering)? */
715 /* Send new stats for the distributed engine.
716 * End with #\n (not \n\n) to indicate a temporary result. */
717 if (u
->slave
&& now
- last_stats_sent
> stats_interval
) {
718 printf("=%d %s\n#\n", u
->gtp_id
, uct_getstats(u
, b
, NULL
));
720 last_stats_sent
= now
;
724 ctx
= uct_search_stop();
727 fprintf(stderr
, "(avg score %f/%d value %f/%d)\n",
728 u
->dynkomi
->score
.value
, u
->dynkomi
->score
.playouts
,
729 u
->dynkomi
->value
.value
, u
->dynkomi
->value
.playouts
);
730 tree_dump(t
, u
->dumpthres
);
733 uct_progress_status(u
, t
, color
, ctx
->games
);
739 /* Start pondering background with @color to play. */
741 uct_pondering_start(struct uct
*u
, struct board
*b0
, struct tree
*t
, enum stone color
)
744 fprintf(stderr
, "Starting to ponder with color %s\n", stone2str(stone_other(color
)));
747 /* We need a local board copy to ponder upon. */
748 struct board
*b
= malloc(sizeof(*b
)); board_copy(b
, b0
);
750 /* *b0 did not have the genmove'd move played yet. */
751 struct move m
= { t
->root
->coord
, t
->root_color
};
752 int res
= board_play(b
, &m
);
754 setup_dynkomi(u
, b
, stone_other(m
.color
));
756 /* Start MCTS manager thread "headless". */
757 uct_search_start(u
, b
, color
, t
);
760 /* uct_search_stop() frontend for the pondering (non-genmove) mode. */
762 uct_pondering_stop(struct uct
*u
)
764 u
->pondering
= false;
765 if (!thread_manager_running
)
768 /* Stop the thread manager. */
769 struct spawn_ctx
*ctx
= uct_search_stop();
771 fprintf(stderr
, "(pondering) ");
772 uct_progress_status(u
, ctx
->t
, ctx
->color
, ctx
->games
);
779 uct_genmove(struct engine
*e
, struct board
*b
, struct time_info
*ti
, enum stone color
, bool pass_all_alive
)
781 double start_time
= time_now();
782 struct uct
*u
= e
->data
;
784 if (b
->superko_violation
) {
785 fprintf(stderr
, "!!! WARNING: SUPERKO VIOLATION OCCURED BEFORE THIS MOVE\n");
786 fprintf(stderr
, "Maybe you play with situational instead of positional superko?\n");
787 fprintf(stderr
, "I'm going to ignore the violation, but note that I may miss\n");
788 fprintf(stderr
, "some moves valid under this ruleset because of this.\n");
789 b
->superko_violation
= false;
793 uct_pondering_stop(u
);
794 prepare_move(e
, b
, color
);
798 /* How to decide whether to use dynkomi in this game? Since we use
799 * pondering, it's not simple "who-to-play" matter. Decide based on
800 * the last genmove issued. */
801 u
->t
->use_extra_komi
= !!(u
->dynkomi_mask
& color
);
802 setup_dynkomi(u
, b
, color
);
804 if (b
->rules
== RULES_JAPANESE
)
805 u
->territory_scoring
= true;
807 /* Make pessimistic assumption about komi for Japanese rules to
808 * avoid losing by 0.5 when winning by 0.5 with Chinese rules.
809 * The rules usually give the same winner if the integer part of komi
810 * is odd so we adjust the komi only if it is even (for a board of
811 * odd size). We are not trying to get an exact evaluation for rare
812 * cases of seki. For details see http://home.snafu.de/jasiek/parity.html */
813 if (u
->territory_scoring
&& (((int)floor(b
->komi
) + board_size(b
)) & 1)) {
814 b
->komi
+= (color
== S_BLACK
? 1.0 : -1.0);
816 fprintf(stderr
, "Setting komi to %.1f assuming Japanese rules\n",
820 int base_playouts
= u
->t
->root
->u
.playouts
;
821 /* Perform the Monte Carlo Tree Search! */
822 int played_games
= uct_search(u
, b
, ti
, color
, u
->t
);
824 /* Choose the best move from the tree. */
825 struct tree_node
*best
= u
->policy
->choose(u
->policy
, u
->t
->root
, b
, color
, resign
);
827 if (!u
->slave
) reset_state(u
);
828 return coord_copy(pass
);
831 fprintf(stderr
, "*** WINNER is %s (%d,%d) with score %1.4f (%d/%d:%d/%d games), extra komi %f\n",
832 coord2sstr(best
->coord
, b
), coord_x(best
->coord
, b
), coord_y(best
->coord
, b
),
833 tree_node_get_value(u
->t
, 1, best
->u
.value
), best
->u
.playouts
,
834 u
->t
->root
->u
.playouts
, u
->t
->root
->u
.playouts
- base_playouts
, played_games
,
837 /* Do not resign if we're so short of time that evaluation of best
838 * move is completely unreliable, we might be winning actually.
839 * In this case best is almost random but still better than resign.
840 * Also do not resign if we are getting bad results while actually
841 * giving away extra komi points (dynkomi). */
842 if (tree_node_get_value(u
->t
, 1, best
->u
.value
) < u
->resign_ratio
843 && !is_pass(best
->coord
) && best
->u
.playouts
> GJ_MINGAMES
844 && u
->t
->extra_komi
<= 1 /* XXX we assume dynamic komi == we are black */) {
845 if (!u
->slave
) reset_state(u
);
846 return coord_copy(resign
);
849 /* If the opponent just passed and we win counting, always
851 if (b
->moves
> 1 && is_pass(b
->last_move
.coord
)) {
852 /* Make sure enough playouts are simulated. */
853 while (u
->ownermap
.playouts
< GJ_MINGAMES
)
854 uct_playout(u
, b
, color
, u
->t
);
855 if (uct_pass_is_safe(u
, b
, color
, u
->pass_all_alive
|| pass_all_alive
)) {
857 fprintf(stderr
, "<Will rather pass, looks safe enough; score %f>\n",
858 board_official_score(b
, NULL
) / 2);
863 /* If we are a slave in the distributed engine, we'll soon get
864 * a "play" command later telling us which move was chosen,
865 * and pondering now will not gain much. */
867 tree_promote_node(u
->t
, &best
);
869 /* After a pass, pondering is harmful for two reasons:
870 * (i) We might keep pondering even when the game is over.
871 * Of course this is the case for opponent resign as well.
872 * (ii) More importantly, the ownermap will get skewed since
873 * the UCT will start cutting off any playouts. */
874 if (u
->pondering_opt
&& !is_pass(best
->coord
)) {
875 uct_pondering_start(u
, b
, u
->t
, stone_other(color
));
879 double time
= time_now() - start_time
+ 0.000001; /* avoid divide by zero */
880 fprintf(stderr
, "genmove in %0.2fs (%d games/s, %d games/s/thread)\n",
881 time
, (int)(played_games
/time
), (int)(played_games
/time
/u
->threads
));
883 return coord_copy(best
->coord
);
886 /* Get stats updates for the distributed engine. Return a buffer
887 * with one line "total_playouts threads" then a list of lines
888 * "coord playouts value". The last line must not end with \n.
889 * If c is not null, add this move with root->playouts weight.
890 * This function is called only by the main thread, but may be
891 * called while the tree is updated by the worker threads.
892 * Keep this code in sync with select_best_move(). */
894 uct_getstats(struct uct
*u
, struct board
*b
, coord_t
*c
)
896 static char reply
[10240];
898 char *end
= reply
+ sizeof(reply
);
899 struct tree_node
*root
= u
->t
->root
;
900 r
+= snprintf(r
, end
- r
, "%d %d", root
->u
.playouts
, u
->threads
);
901 int min_playouts
= root
->u
.playouts
/ 100;
903 // Give a large weight to pass or resign, but still allow other moves.
905 r
+= snprintf(r
, end
- r
, "\n%s %d %.1f", coord2sstr(*c
, b
), root
->u
.playouts
,
908 /* We rely on the fact that root->children is set only
909 * after all children are created. */
910 for (struct tree_node
*ni
= root
->children
; ni
; ni
= ni
->sibling
) {
911 if (ni
->u
.playouts
<= min_playouts
912 || ni
->hints
& TREE_HINT_INVALID
913 || is_pass(ni
->coord
))
915 char *coord
= coord2sstr(ni
->coord
, b
);
916 // We return the values as stored in the tree, so from black's view.
917 r
+= snprintf(r
, end
- r
, "\n%s %d %.7f", coord
, ni
->u
.playouts
, ni
->u
.value
);
923 uct_genmoves(struct engine
*e
, struct board
*b
, struct time_info
*ti
, enum stone color
, bool pass_all_alive
)
925 struct uct
*u
= e
->data
;
928 coord_t
*c
= uct_genmove(e
, b
, ti
, color
, pass_all_alive
);
930 char *reply
= uct_getstats(u
, b
, is_pass(*c
) || is_resign(*c
) ? c
: NULL
);
937 uct_genbook(struct engine
*e
, struct board
*b
, struct time_info
*ti
, enum stone color
)
939 struct uct
*u
= e
->data
;
940 if (!u
->t
) prepare_move(e
, b
, color
);
943 if (ti
->dim
== TD_GAMES
) {
944 /* Don't count in games that already went into the book. */
945 ti
->len
.games
+= u
->t
->root
->u
.playouts
;
947 uct_search(u
, b
, ti
, color
, u
->t
);
949 assert(ti
->dim
== TD_GAMES
);
950 tree_save(u
->t
, b
, ti
->len
.games
/ 100);
956 uct_dumpbook(struct engine
*e
, struct board
*b
, enum stone color
)
958 struct uct
*u
= e
->data
;
959 struct tree
*t
= tree_init(b
, color
, u
->fast_alloc
? u
->max_tree_size
: 0, u
->local_tree_aging
);
967 uct_state_init(char *arg
, struct board
*b
)
969 struct uct
*u
= calloc(1, sizeof(struct uct
));
970 bool using_elo
= false;
972 u
->debug_level
= debug_level
;
973 u
->gamelen
= MC_GAMELEN
;
977 u
->playout_amaf
= true;
978 u
->playout_amaf_nakade
= false;
979 u
->amaf_prior
= false;
980 u
->max_tree_size
= 3072ULL * 1048576;
982 u
->dynkomi_mask
= S_BLACK
;
985 u
->thread_model
= TM_TREEVL
;
986 u
->parallel_tree
= true;
987 u
->virtual_loss
= true;
989 u
->fuseki_end
= 20; // max time at 361*20% = 72 moves (our 36th move, still 99 to play)
990 u
->yose_start
= 40; // (100-40-25)*361/100/2 = 63 moves still to play by us then
991 u
->bestr_ratio
= 0.02;
992 // 2.5 is clearly too much, but seems to compensate well for overly stern time allocations.
993 // TODO: Further tuning and experiments with better time allocation schemes.
994 u
->best2_ratio
= 2.5;
996 u
->val_scale
= 0.04; u
->val_points
= 40;
999 u
->local_tree_aging
= 2;
1002 char *optspec
, *next
= arg
;
1005 next
+= strcspn(next
, ",");
1006 if (*next
) { *next
++ = 0; } else { *next
= 0; }
1008 char *optname
= optspec
;
1009 char *optval
= strchr(optspec
, '=');
1010 if (optval
) *optval
++ = 0;
1012 if (!strcasecmp(optname
, "debug")) {
1014 u
->debug_level
= atoi(optval
);
1017 } else if (!strcasecmp(optname
, "mercy") && optval
) {
1018 /* Minimal difference of black/white captures
1019 * to stop playout - "Mercy Rule". Speeds up
1020 * hopeless playouts at the expense of some
1022 u
->mercymin
= atoi(optval
);
1023 } else if (!strcasecmp(optname
, "gamelen") && optval
) {
1024 u
->gamelen
= atoi(optval
);
1025 } else if (!strcasecmp(optname
, "expand_p") && optval
) {
1026 u
->expand_p
= atoi(optval
);
1027 } else if (!strcasecmp(optname
, "dumpthres") && optval
) {
1028 u
->dumpthres
= atoi(optval
);
1029 } else if (!strcasecmp(optname
, "best2_ratio") && optval
) {
1030 /* If set, prolong simulating while
1031 * first_best/second_best playouts ratio
1032 * is less than best2_ratio. */
1033 u
->best2_ratio
= atof(optval
);
1034 } else if (!strcasecmp(optname
, "bestr_ratio") && optval
) {
1035 /* If set, prolong simulating while
1036 * best,best_best_child values delta
1037 * is more than bestr_ratio. */
1038 u
->bestr_ratio
= atof(optval
);
1039 } else if (!strcasecmp(optname
, "playout_amaf")) {
1040 /* Whether to include random playout moves in
1041 * AMAF as well. (Otherwise, only tree moves
1042 * are included in AMAF. Of course makes sense
1043 * only in connection with an AMAF policy.) */
1044 /* with-without: 55.5% (+-4.1) */
1045 if (optval
&& *optval
== '0')
1046 u
->playout_amaf
= false;
1048 u
->playout_amaf
= true;
1049 } else if (!strcasecmp(optname
, "playout_amaf_nakade")) {
1050 /* Whether to include nakade moves from playouts
1051 * in the AMAF statistics; this tends to nullify
1052 * the playout_amaf effect by adding too much
1054 if (optval
&& *optval
== '0')
1055 u
->playout_amaf_nakade
= false;
1057 u
->playout_amaf_nakade
= true;
1058 } else if (!strcasecmp(optname
, "playout_amaf_cutoff") && optval
) {
1059 /* Keep only first N% of playout stage AMAF
1061 u
->playout_amaf_cutoff
= atoi(optval
);
1062 } else if ((!strcasecmp(optname
, "policy") || !strcasecmp(optname
, "random_policy")) && optval
) {
1063 char *policyarg
= strchr(optval
, ':');
1064 struct uct_policy
**p
= !strcasecmp(optname
, "policy") ? &u
->policy
: &u
->random_policy
;
1067 if (!strcasecmp(optval
, "ucb1")) {
1068 *p
= policy_ucb1_init(u
, policyarg
);
1069 } else if (!strcasecmp(optval
, "ucb1amaf")) {
1070 *p
= policy_ucb1amaf_init(u
, policyarg
);
1072 fprintf(stderr
, "UCT: Invalid tree policy %s\n", optval
);
1075 } else if (!strcasecmp(optname
, "playout") && optval
) {
1076 char *playoutarg
= strchr(optval
, ':');
1079 if (!strcasecmp(optval
, "moggy")) {
1080 u
->playout
= playout_moggy_init(playoutarg
, b
);
1081 } else if (!strcasecmp(optval
, "light")) {
1082 u
->playout
= playout_light_init(playoutarg
, b
);
1083 } else if (!strcasecmp(optval
, "elo")) {
1084 u
->playout
= playout_elo_init(playoutarg
, b
);
1087 fprintf(stderr
, "UCT: Invalid playout policy %s\n", optval
);
1090 } else if (!strcasecmp(optname
, "prior") && optval
) {
1091 u
->prior
= uct_prior_init(optval
, b
);
1092 } else if (!strcasecmp(optname
, "amaf_prior") && optval
) {
1093 u
->amaf_prior
= atoi(optval
);
1094 } else if (!strcasecmp(optname
, "threads") && optval
) {
1095 /* By default, Pachi will run with only single
1096 * tree search thread! */
1097 u
->threads
= atoi(optval
);
1098 } else if (!strcasecmp(optname
, "thread_model") && optval
) {
1099 if (!strcasecmp(optval
, "root")) {
1100 /* Root parallelization - each thread
1101 * does independent search, trees are
1102 * merged at the end. */
1103 u
->thread_model
= TM_ROOT
;
1104 u
->parallel_tree
= false;
1105 u
->virtual_loss
= false;
1106 } else if (!strcasecmp(optval
, "tree")) {
1107 /* Tree parallelization - all threads
1108 * grind on the same tree. */
1109 u
->thread_model
= TM_TREE
;
1110 u
->parallel_tree
= true;
1111 u
->virtual_loss
= false;
1112 } else if (!strcasecmp(optval
, "treevl")) {
1113 /* Tree parallelization, but also
1114 * with virtual losses - this discou-
1115 * rages most threads choosing the
1116 * same tree branches to read. */
1117 u
->thread_model
= TM_TREEVL
;
1118 u
->parallel_tree
= true;
1119 u
->virtual_loss
= true;
1121 fprintf(stderr
, "UCT: Invalid thread model %s\n", optval
);
1124 } else if (!strcasecmp(optname
, "pondering")) {
1125 /* Keep searching even during opponent's turn. */
1126 u
->pondering_opt
= !optval
|| atoi(optval
);
1127 } else if (!strcasecmp(optname
, "fuseki_end") && optval
) {
1128 /* At the very beginning it's not worth thinking
1129 * too long because the playout evaluations are
1130 * very noisy. So gradually increase the thinking
1131 * time up to maximum when fuseki_end percent
1132 * of the board has been played.
1133 * This only applies if we are not in byoyomi. */
1134 u
->fuseki_end
= atoi(optval
);
1135 } else if (!strcasecmp(optname
, "yose_start") && optval
) {
1136 /* When yose_start percent of the board has been
1137 * played, or if we are in byoyomi, stop spending
1138 * more time and spread the remaining time
1140 * Between fuseki_end and yose_start, we spend
1141 * a constant proportion of the remaining time
1142 * on each move. (yose_start should actually
1143 * be much earlier than when real yose start,
1144 * but "yose" is a good short name to convey
1146 u
->yose_start
= atoi(optval
);
1147 } else if (!strcasecmp(optname
, "force_seed") && optval
) {
1148 u
->force_seed
= atoi(optval
);
1149 } else if (!strcasecmp(optname
, "no_book")) {
1151 } else if (!strcasecmp(optname
, "dynkomi") && optval
) {
1152 /* Dynamic komi approach; there are multiple
1153 * ways to adjust komi dynamically throughout
1154 * play. We currently support two: */
1155 char *dynkomiarg
= strchr(optval
, ':');
1158 if (!strcasecmp(optval
, "none")) {
1159 u
->dynkomi
= uct_dynkomi_init_none(u
, dynkomiarg
, b
);
1160 } else if (!strcasecmp(optval
, "linear")) {
1161 u
->dynkomi
= uct_dynkomi_init_linear(u
, dynkomiarg
, b
);
1162 } else if (!strcasecmp(optval
, "adaptive")) {
1163 u
->dynkomi
= uct_dynkomi_init_adaptive(u
, dynkomiarg
, b
);
1165 fprintf(stderr
, "UCT: Invalid dynkomi mode %s\n", optval
);
1168 } else if (!strcasecmp(optname
, "dynkomi_mask") && optval
) {
1169 /* Bitmask of colors the player must be
1170 * for dynkomi be applied; you may want
1171 * to use dynkomi_mask=3 to allow dynkomi
1172 * even in games where Pachi is white. */
1173 u
->dynkomi_mask
= atoi(optval
);
1174 } else if (!strcasecmp(optname
, "dynkomi_interval") && optval
) {
1175 /* If non-zero, re-adjust dynamic komi
1176 * throughout a single genmove reading,
1177 * roughly every N simulations. */
1178 /* XXX: Does not work with tree
1179 * parallelization. */
1180 u
->dynkomi_interval
= atoi(optval
);
1181 } else if (!strcasecmp(optname
, "val_scale") && optval
) {
1182 /* How much of the game result value should be
1183 * influenced by win size. Zero means it isn't. */
1184 u
->val_scale
= atof(optval
);
1185 } else if (!strcasecmp(optname
, "val_points") && optval
) {
1186 /* Maximum size of win to be scaled into game
1187 * result value. Zero means boardsize^2. */
1188 u
->val_points
= atoi(optval
) * 2; // result values are doubled
1189 } else if (!strcasecmp(optname
, "val_extra")) {
1190 /* If false, the score coefficient will be simply
1191 * added to the value, instead of scaling the result
1192 * coefficient because of it. */
1193 u
->val_extra
= !optval
|| atoi(optval
);
1194 } else if (!strcasecmp(optname
, "local_tree") && optval
) {
1195 /* Whether to bias exploration by local tree values
1196 * (must be supported by the used policy).
1198 * 1: Do, value = result.
1199 * Try to temper the result:
1200 * 2: Do, value = 0.5+(result-expected)/2.
1201 * 3: Do, value = 0.5+bzz((result-expected)^2).
1202 * 4: Do, value = 0.5+sqrt(result-expected)/2. */
1203 u
->local_tree
= atoi(optval
);
1204 } else if (!strcasecmp(optname
, "tenuki_d") && optval
) {
1205 /* Tenuki distance at which to break the local tree. */
1206 u
->tenuki_d
= atoi(optval
);
1207 if (u
->tenuki_d
> TREE_NODE_D_MAX
+ 1) {
1208 fprintf(stderr
, "uct: tenuki_d must not be larger than TREE_NODE_D_MAX+1 %d\n", TREE_NODE_D_MAX
+ 1);
1211 } else if (!strcasecmp(optname
, "local_tree_aging") && optval
) {
1212 /* How much to reduce local tree values between moves. */
1213 u
->local_tree_aging
= atof(optval
);
1214 } else if (!strcasecmp(optname
, "local_tree_allseq")) {
1215 /* By default, only complete sequences are stored
1216 * in the local tree. If this is on, also
1217 * subsequences starting at each move are stored. */
1218 u
->local_tree_allseq
= !optval
|| atoi(optval
);
1219 } else if (!strcasecmp(optname
, "local_tree_playout")) {
1220 /* Whether to adjust ELO playout probability
1221 * distributions according to matched localtree
1223 u
->local_tree_playout
= !optval
|| atoi(optval
);
1224 } else if (!strcasecmp(optname
, "local_tree_pseqroot")) {
1225 /* By default, when we have no sequence move
1226 * to suggest in-playout, we give up. If this
1227 * is on, we make probability distribution from
1228 * sequences first moves instead. */
1229 u
->local_tree_pseqroot
= !optval
|| atoi(optval
);
1230 } else if (!strcasecmp(optname
, "pass_all_alive")) {
1231 /* Whether to consider passing only after all
1232 * dead groups were removed from the board;
1233 * this is like all genmoves are in fact
1234 * kgs-genmove_cleanup. */
1235 u
->pass_all_alive
= !optval
|| atoi(optval
);
1236 } else if (!strcasecmp(optname
, "territory_scoring")) {
1237 /* Use territory scoring (default is area scoring).
1238 * An explicit kgs-rules command overrides this. */
1239 u
->territory_scoring
= !optval
|| atoi(optval
);
1240 } else if (!strcasecmp(optname
, "random_policy_chance") && optval
) {
1241 /* If specified (N), with probability 1/N, random_policy policy
1242 * descend is used instead of main policy descend; useful
1243 * if specified policy (e.g. UCB1AMAF) can make unduly biased
1244 * choices sometimes, you can fall back to e.g.
1245 * random_policy=UCB1. */
1246 u
->random_policy_chance
= atoi(optval
);
1247 } else if (!strcasecmp(optname
, "max_tree_size") && optval
) {
1248 /* Maximum amount of memory [MiB] consumed by the move tree.
1249 * For fast_alloc it includes the temp tree used for pruning.
1250 * Default is 3072 (3 GiB). Note that if you use TM_ROOT,
1251 * this limits size of only one of the trees, not all of them
1253 u
->max_tree_size
= atol(optval
) * 1048576;
1254 } else if (!strcasecmp(optname
, "fast_alloc")) {
1255 u
->fast_alloc
= !optval
|| atoi(optval
);
1256 } else if (!strcasecmp(optname
, "slave")) {
1257 /* Act as slave for the distributed engine. */
1258 u
->slave
= !optval
|| atoi(optval
);
1259 } else if (!strcasecmp(optname
, "banner") && optval
) {
1260 /* Additional banner string. This must come as the
1261 * last engine parameter. */
1262 if (*next
) *--next
= ',';
1263 u
->banner
= strdup(optval
);
1266 fprintf(stderr
, "uct: Invalid engine argument %s or missing value\n", optname
);
1272 u
->resign_ratio
= 0.2; /* Resign when most games are lost. */
1273 u
->loss_threshold
= 0.85; /* Stop reading if after at least 2000 playouts this is best value. */
1275 u
->policy
= policy_ucb1amaf_init(u
, NULL
);
1277 if (!!u
->random_policy_chance
^ !!u
->random_policy
) {
1278 fprintf(stderr
, "uct: Only one of random_policy and random_policy_chance is set\n");
1282 if (!u
->local_tree
) {
1283 /* No ltree aging. */
1284 u
->local_tree_aging
= 1.0f
;
1287 u
->local_tree_playout
= false;
1289 if (u
->fast_alloc
&& !u
->parallel_tree
) {
1290 fprintf(stderr
, "fast_alloc not supported with root parallelization.\n");
1294 u
->max_tree_size
= (100ULL * u
->max_tree_size
) / (100 + MIN_FREE_MEM_PERCENT
);
1297 u
->prior
= uct_prior_init(NULL
, b
);
1300 u
->playout
= playout_moggy_init(NULL
, b
);
1301 u
->playout
->debug_level
= u
->debug_level
;
1303 u
->ownermap
.map
= malloc(board_size2(b
) * sizeof(u
->ownermap
.map
[0]));
1306 u
->dynkomi
= uct_dynkomi_init_linear(u
, NULL
, b
);
1308 /* Some things remain uninitialized for now - the opening book
1309 * is not loaded and the tree not set up. */
1310 /* This will be initialized in setup_state() at the first move
1311 * received/requested. This is because right now we are not aware
1312 * about any komi or handicap setup and such. */
1318 engine_uct_init(char *arg
, struct board
*b
)
1320 struct uct
*u
= uct_state_init(arg
, b
);
1321 struct engine
*e
= calloc(1, sizeof(struct engine
));
1322 e
->name
= "UCT Engine";
1323 e
->printhook
= uct_printhook_ownermap
;
1324 e
->notify_play
= uct_notify_play
;
1326 e
->genmove
= uct_genmove
;
1327 e
->genmoves
= uct_genmoves
;
1328 e
->dead_group_list
= uct_dead_group_list
;
1332 e
->notify
= uct_notify
;
1334 const char banner
[] = "I'm playing UCT. When I'm losing, I will resign, "
1335 "if I think I win, I play until you pass. "
1336 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
1337 if (!u
->banner
) u
->banner
= "";
1338 e
->comment
= malloc(sizeof(banner
) + strlen(u
->banner
) + 1);
1339 sprintf(e
->comment
, "%s %s", banner
, u
->banner
);