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"
28 #include "uct/slave.h"
33 struct uct_policy
*policy_ucb1_init(struct uct
*u
, char *arg
);
34 struct uct_policy
*policy_ucb1amaf_init(struct uct
*u
, char *arg
);
35 static void uct_pondering_stop(struct uct
*u
);
36 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 /* 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 uct_prepare_move(struct uct
*u
, struct board
*b
, enum stone color
)
103 /* Verify that we have sane state. */
105 assert(u
->t
&& b
->moves
);
106 if (color
!= stone_other(u
->t
->root_color
)) {
107 fprintf(stderr
, "Fatal: Non-alternating play detected %d %d\n",
108 color
, u
->t
->root_color
);
113 /* We need fresh state. */
115 setup_state(u
, b
, color
);
118 u
->ownermap
.playouts
= 0;
119 memset(u
->ownermap
.map
, 0, board_size2(b
) * sizeof(u
->ownermap
.map
[0]));
120 memset(u
->stats
, 0, board_size2(b
) * sizeof(u
->stats
[0]));
121 u
->played_own
= u
->played_all
= 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
);
167 return reply_disabled(id
) ? P_NOREPLY
: P_OK
;
171 uct_printhook_ownermap(struct board
*board
, coord_t c
, char *s
, char *end
)
173 struct uct
*u
= board
->es
;
175 const char chr
[] = ":XO,"; // dame, black, white, unclear
176 const char chm
[] = ":xo,";
177 char ch
= chr
[board_ownermap_judge_point(&u
->ownermap
, c
, GJ_THRES
)];
178 if (ch
== ',') { // less precise estimate then?
179 ch
= chm
[board_ownermap_judge_point(&u
->ownermap
, c
, 0.67)];
181 s
+= snprintf(s
, end
- s
, "%c ", ch
);
186 uct_notify_play(struct engine
*e
, struct board
*b
, struct move
*m
)
188 struct uct
*u
= e
->data
;
190 /* No state, create one - this is probably game beginning
191 * and we need to load the opening book right now. */
192 uct_prepare_move(u
, b
, m
->color
);
196 /* Stop pondering, required by tree_promote_at() */
197 uct_pondering_stop(u
);
198 if (UDEBUGL(2) && u
->slave
)
199 tree_dump(u
->t
, u
->dumpthres
);
201 if (is_resign(m
->coord
)) {
207 /* Promote node of the appropriate move to the tree root. */
209 if (!tree_promote_at(u
->t
, b
, m
->coord
)) {
211 fprintf(stderr
, "Warning: Cannot promote move node! Several play commands in row?\n");
216 /* If we are a slave in a distributed engine, start pondering once
217 * we know which move we actually played. See uct_genmove() about
218 * the check for pass. */
219 if (u
->pondering_opt
&& u
->slave
&& m
->color
== u
->my_color
&& !is_pass(m
->coord
))
220 uct_pondering_start(u
, b
, u
->t
, stone_other(m
->color
));
226 uct_chat(struct engine
*e
, struct board
*b
, char *cmd
)
228 struct uct
*u
= e
->data
;
229 static char reply
[1024];
231 cmd
+= strspn(cmd
, " \n\t");
232 if (!strncasecmp(cmd
, "winrate", 7)) {
234 return "no game context (yet?)";
235 enum stone color
= u
->t
->root_color
;
236 struct tree_node
*n
= u
->t
->root
;
237 snprintf(reply
, 1024, "In %d playouts at %d threads, %s %s can win with %.2f%% probability",
238 n
->u
.playouts
, u
->threads
, stone2str(color
), coord2sstr(n
->coord
, b
),
239 tree_node_get_value(u
->t
, -1, n
->u
.value
) * 100);
240 if (u
->t
->use_extra_komi
&& abs(u
->t
->extra_komi
) >= 0.5) {
241 sprintf(reply
+ strlen(reply
), ", while self-imposing extra komi %.1f",
251 uct_dead_group_list(struct engine
*e
, struct board
*b
, struct move_queue
*mq
)
253 struct uct
*u
= e
->data
;
255 /* This means the game is probably over, no use pondering on. */
256 uct_pondering_stop(u
);
258 if (u
->pass_all_alive
)
259 return; // no dead groups
261 bool mock_state
= false;
264 /* No state, but we cannot just back out - we might
265 * have passed earlier, only assuming some stones are
266 * dead, and then re-connected, only to lose counting
267 * when all stones are assumed alive. */
268 /* Mock up some state and seed the ownermap by few
270 uct_prepare_move(u
, b
, S_BLACK
); assert(u
->t
);
271 for (int i
= 0; i
< GJ_MINGAMES
; i
++)
272 uct_playout(u
, b
, S_BLACK
, u
->t
);
276 dead_group_list(u
, b
, mq
);
279 /* Clean up the mock state in case we will receive
280 * a genmove; we could get a non-alternating-move
281 * error from uct_prepare_move() in that case otherwise. */
287 playout_policy_done(struct playout_policy
*p
)
289 if (p
->done
) p
->done(p
);
290 if (p
->data
) free(p
->data
);
295 uct_done(struct engine
*e
)
297 /* This is called on engine reset, especially when clear_board
298 * is received and new game should begin. */
299 struct uct
*u
= e
->data
;
300 uct_pondering_stop(u
);
301 if (u
->t
) reset_state(u
);
302 free(u
->ownermap
.map
);
306 free(u
->random_policy
);
307 playout_policy_done(u
->playout
);
308 uct_prior_done(u
->prior
);
312 /* Pachi threading structure (if uct_playouts_parallel() is used):
315 * | main(), GTP communication, ...
316 * | starts and stops the search managed by thread_manager
319 * | spawns and collects worker threads
325 * uct_playouts() loop, doing descend-playout until uct_halt
327 * Another way to look at it is by functions (lines denote thread boundaries):
330 * | uct_search() (uct_search_start() .. uct_search_stop())
331 * | -----------------------
332 * | spawn_thread_manager()
333 * | -----------------------
335 * V uct_playouts() */
337 /* Set in thread manager in case the workers should stop. */
338 volatile sig_atomic_t uct_halt
= 0;
339 /* ID of the running worker thread. */
340 __thread
int thread_id
= -1;
341 /* ID of the thread manager. */
342 static pthread_t thread_manager
;
343 bool thread_manager_running
;
345 static pthread_mutex_t finish_mutex
= PTHREAD_MUTEX_INITIALIZER
;
346 static pthread_cond_t finish_cond
= PTHREAD_COND_INITIALIZER
;
347 static volatile int finish_thread
;
348 static pthread_mutex_t finish_serializer
= PTHREAD_MUTEX_INITIALIZER
;
361 spawn_worker(void *ctx_
)
363 struct spawn_ctx
*ctx
= ctx_
;
365 fast_srandom(ctx
->seed
);
366 thread_id
= ctx
->tid
;
368 ctx
->games
= uct_playouts(ctx
->u
, ctx
->b
, ctx
->color
, ctx
->t
);
370 pthread_mutex_lock(&finish_serializer
);
371 pthread_mutex_lock(&finish_mutex
);
372 finish_thread
= ctx
->tid
;
373 pthread_cond_signal(&finish_cond
);
374 pthread_mutex_unlock(&finish_mutex
);
378 /* Thread manager, controlling worker threads. It must be called with
379 * finish_mutex lock held, but it will unlock it itself before exiting;
380 * this is necessary to be completely deadlock-free. */
381 /* The finish_cond can be signalled for it to stop; in that case,
382 * the caller should set finish_thread = -1. */
383 /* After it is started, it will update mctx->t to point at some tree
384 * used for the actual search (matters only for TM_ROOT), on return
385 * it will set mctx->games to the number of performed simulations. */
387 spawn_thread_manager(void *ctx_
)
389 /* In thread_manager, we use only some of the ctx fields. */
390 struct spawn_ctx
*mctx
= ctx_
;
391 struct uct
*u
= mctx
->u
;
392 struct tree
*t
= mctx
->t
;
393 bool shared_tree
= u
->parallel_tree
;
394 fast_srandom(mctx
->seed
);
396 int played_games
= 0;
397 pthread_t threads
[u
->threads
];
402 /* Garbage collect the tree by preference when pondering. */
403 if (u
->pondering
&& t
->nodes
&& t
->nodes_size
> t
->max_tree_size
/2) {
404 unsigned long temp_size
= (MIN_FREE_MEM_PERCENT
* t
->max_tree_size
) / 100;
405 t
->root
= tree_garbage_collect(t
, temp_size
, t
->root
);
408 /* Spawn threads... */
409 for (int ti
= 0; ti
< u
->threads
; ti
++) {
410 struct spawn_ctx
*ctx
= malloc2(sizeof(*ctx
));
411 ctx
->u
= u
; ctx
->b
= mctx
->b
; ctx
->color
= mctx
->color
;
412 mctx
->t
= ctx
->t
= shared_tree
? t
: tree_copy(t
);
413 ctx
->tid
= ti
; ctx
->seed
= fast_random(65536) + ti
;
414 pthread_create(&threads
[ti
], NULL
, spawn_worker
, ctx
);
416 fprintf(stderr
, "Spawned worker %d\n", ti
);
419 /* ...and collect them back: */
420 while (joined
< u
->threads
) {
421 /* Wait for some thread to finish... */
422 pthread_cond_wait(&finish_cond
, &finish_mutex
);
423 if (finish_thread
< 0) {
424 /* Stop-by-caller. Tell the workers to wrap up. */
428 /* ...and gather its remnants. */
429 struct spawn_ctx
*ctx
;
430 pthread_join(threads
[finish_thread
], (void **) &ctx
);
431 played_games
+= ctx
->games
;
434 if (ctx
->t
== mctx
->t
) mctx
->t
= t
;
435 tree_merge(t
, ctx
->t
);
440 fprintf(stderr
, "Joined worker %d\n", finish_thread
);
441 pthread_mutex_unlock(&finish_serializer
);
444 pthread_mutex_unlock(&finish_mutex
);
447 tree_normalize(mctx
->t
, u
->threads
);
449 mctx
->games
= played_games
;
454 /* Progress information of the on-going MCTS search - when did we
455 * last adjusted dynkomi, printed out stuff, etc. */
456 struct uct_search_state
{
457 /* Number of games simulated for this simulation before
458 * we started the search. (We have simulated them earlier.) */
460 /* Number of last dynkomi adjustment. */
462 /* Number of last game with progress print. */
464 /* Number of simulations to wait before next print. */
466 /* Printed notification about full memory? */
469 struct time_stop stop
;
470 struct spawn_ctx
*ctx
;
474 uct_search_games(struct uct_search_state
*s
)
476 return s
->ctx
->t
->root
->u
.playouts
;
480 uct_search_start(struct uct
*u
, struct board
*b
, enum stone color
,
481 struct tree
*t
, struct time_info
*ti
,
482 struct uct_search_state
*s
)
484 /* Set up search state. */
485 s
->base_playouts
= s
->last_dynkomi
= s
->last_print
= t
->root
->u
.playouts
;
486 s
->print_interval
= TREE_SIMPROGRESS_INTERVAL
* (u
->thread_model
== TM_ROOT
? 1 : u
->threads
);
487 s
->print_fullmem
= false;
490 if (ti
->period
== TT_NULL
) *ti
= default_ti
;
491 time_stop_conditions(ti
, b
, u
->fuseki_end
, u
->yose_start
, &s
->stop
);
494 /* Fire up the tree search thread manager, which will in turn
495 * spawn the searching threads. */
496 assert(u
->threads
> 0);
497 assert(!thread_manager_running
);
498 static struct spawn_ctx mctx
;
499 mctx
= (struct spawn_ctx
) { .u
= u
, .b
= b
, .color
= color
, .t
= t
, .seed
= fast_random(65536) };
501 pthread_mutex_lock(&finish_mutex
);
502 pthread_create(&thread_manager
, NULL
, spawn_thread_manager
, s
->ctx
);
503 thread_manager_running
= true;
506 static struct spawn_ctx
*
507 uct_search_stop(void)
509 assert(thread_manager_running
);
511 /* Signal thread manager to stop the workers. */
512 pthread_mutex_lock(&finish_mutex
);
514 pthread_cond_signal(&finish_cond
);
515 pthread_mutex_unlock(&finish_mutex
);
517 /* Collect the thread manager. */
518 struct spawn_ctx
*pctx
;
519 thread_manager_running
= false;
520 pthread_join(thread_manager
, (void **) &pctx
);
526 uct_search_progress(struct uct
*u
, struct board
*b
, enum stone color
,
527 struct tree
*t
, struct time_info
*ti
,
528 struct uct_search_state
*s
, int i
)
530 struct spawn_ctx
*ctx
= s
->ctx
;
532 /* Adjust dynkomi? */
533 if (ctx
->t
->use_extra_komi
&& u
->dynkomi
->permove
534 && u
->dynkomi_interval
535 && i
> s
->last_dynkomi
+ u
->dynkomi_interval
) {
536 s
->last_dynkomi
+= u
->dynkomi_interval
;
537 float old_dynkomi
= ctx
->t
->extra_komi
;
538 ctx
->t
->extra_komi
= u
->dynkomi
->permove(u
->dynkomi
, b
, ctx
->t
);
539 if (UDEBUGL(3) && old_dynkomi
!= ctx
->t
->extra_komi
)
540 fprintf(stderr
, "dynkomi adjusted (%f -> %f)\n",
541 old_dynkomi
, ctx
->t
->extra_komi
);
544 /* Print progress? */
545 if (i
- s
->last_print
> s
->print_interval
) {
546 s
->last_print
+= s
->print_interval
; // keep the numbers tidy
547 uct_progress_status(u
, ctx
->t
, color
, s
->last_print
);
550 if (!s
->print_fullmem
&& ctx
->t
->nodes_size
> u
->max_tree_size
) {
552 fprintf(stderr
, "memory limit hit (%lu > %lu)\n",
553 ctx
->t
->nodes_size
, u
->max_tree_size
);
554 s
->print_fullmem
= true;
558 /* Determine whether we should terminate the search early. */
560 uct_search_stop_early(struct uct
*u
, struct tree
*t
, struct board
*b
,
561 struct time_info
*ti
, struct time_stop
*stop
,
562 struct tree_node
*best
, struct tree_node
*best2
,
565 /* Always use at least half the desired time. It is silly
566 * to lose a won game because we played a bad move in 0.1s. */
568 if (ti
->dim
== TD_WALLTIME
) {
569 elapsed
= time_now() - ti
->len
.t
.timer_start
;
570 if (elapsed
< 0.5 * stop
->desired
.time
) return false;
573 /* Early break in won situation. */
574 if (best
->u
.playouts
>= 2000 && tree_node_get_value(t
, 1, best
->u
.value
) >= u
->loss_threshold
)
576 /* Earlier break in super-won situation. */
577 if (best
->u
.playouts
>= 500 && tree_node_get_value(t
, 1, best
->u
.value
) >= 0.95)
580 /* Break early if we estimate the second-best move cannot
581 * catch up in assigned time anymore. We use all our time
582 * if we are in byoyomi with single stone remaining in our
583 * period, however - it's better to pre-ponder. */
584 bool time_indulgent
= (!ti
->len
.t
.main_time
&& ti
->len
.t
.byoyomi_stones
== 1);
585 if (best2
&& ti
->dim
== TD_WALLTIME
&& !time_indulgent
) {
586 double remaining
= stop
->worst
.time
- elapsed
;
587 double pps
= ((double)played
) / elapsed
;
588 double estplayouts
= remaining
* pps
+ PLAYOUT_DELTA_SAFEMARGIN
;
589 if (best
->u
.playouts
> best2
->u
.playouts
+ estplayouts
) {
591 fprintf(stderr
, "Early stop, result cannot change: "
592 "best %d, best2 %d, estimated %f simulations to go\n",
593 best
->u
.playouts
, best2
->u
.playouts
, estplayouts
);
601 /* Determine whether we should terminate the search later than expected. */
603 uct_search_keep_looking(struct uct
*u
, struct tree
*t
, struct board
*b
,
604 struct time_info
*ti
, struct time_stop
*stop
,
605 struct tree_node
*best
, struct tree_node
*best2
,
606 struct tree_node
*bestr
, struct tree_node
*winner
, int i
)
610 fprintf(stderr
, "Did not find best move, still trying...\n");
614 /* Do not waste time if we are winning. Spend up to worst time if
615 * we are unsure, but only desired time if we are sure of winning. */
616 float beta
= 2 * (tree_node_get_value(t
, 1, best
->u
.value
) - 0.5);
617 if (ti
->dim
== TD_WALLTIME
&& beta
> 0) {
618 double good_enough
= stop
->desired
.time
* beta
+ stop
->worst
.time
* (1 - beta
);
619 double elapsed
= time_now() - ti
->len
.t
.timer_start
;
620 if (elapsed
> good_enough
) return false;
623 if (u
->best2_ratio
> 0) {
624 /* Check best/best2 simulations ratio. If the
625 * two best moves give very similar results,
626 * keep simulating. */
627 if (best2
&& best2
->u
.playouts
628 && (double)best
->u
.playouts
/ best2
->u
.playouts
< u
->best2_ratio
) {
630 fprintf(stderr
, "Best2 ratio %f < threshold %f\n",
631 (double)best
->u
.playouts
/ best2
->u
.playouts
,
637 if (u
->bestr_ratio
> 0) {
638 /* Check best, best_best value difference. If the best move
639 * and its best child do not give similar enough results,
640 * keep simulating. */
641 if (bestr
&& bestr
->u
.playouts
642 && fabs((double)best
->u
.value
- bestr
->u
.value
) > u
->bestr_ratio
) {
644 fprintf(stderr
, "Bestr delta %f > threshold %f\n",
645 fabs((double)best
->u
.value
- bestr
->u
.value
),
651 if (winner
&& winner
!= best
) {
652 /* Keep simulating if best explored
653 * does not have also highest value. */
655 fprintf(stderr
, "[%d] best %3s [%d] %f != winner %3s [%d] %f\n", i
,
656 coord2sstr(best
->coord
, t
->board
),
657 best
->u
.playouts
, tree_node_get_value(t
, 1, best
->u
.value
),
658 coord2sstr(winner
->coord
, t
->board
),
659 winner
->u
.playouts
, tree_node_get_value(t
, 1, winner
->u
.value
));
663 /* No reason to keep simulating, bye. */
668 uct_search_check_stop(struct uct
*u
, struct board
*b
, enum stone color
,
669 struct tree
*t
, struct time_info
*ti
,
670 struct uct_search_state
*s
, int i
)
672 struct spawn_ctx
*ctx
= s
->ctx
;
674 /* Never consider stopping if we played too few simulations.
675 * Maybe we risk losing on time when playing in super-extreme
676 * time pressure but the tree is going to be just too messed
677 * up otherwise - we might even play invalid suicides or pass
678 * when we mustn't. */
682 struct tree_node
*best
= NULL
;
683 struct tree_node
*best2
= NULL
; // Second-best move.
684 struct tree_node
*bestr
= NULL
; // best's best child.
685 struct tree_node
*winner
= NULL
;
687 best
= u
->policy
->choose(u
->policy
, ctx
->t
->root
, b
, color
, resign
);
688 if (best
) best2
= u
->policy
->choose(u
->policy
, ctx
->t
->root
, b
, color
, best
->coord
);
690 /* Possibly stop search early if it's no use to try on. */
691 int played
= u
->played_all
+ i
- s
->base_playouts
;
692 if (best
&& uct_search_stop_early(u
, ctx
->t
, b
, ti
, &s
->stop
, best
, best2
, played
))
695 /* Check against time settings. */
697 if (ti
->dim
== TD_WALLTIME
) {
698 double elapsed
= time_now() - ti
->len
.t
.timer_start
;
699 if (elapsed
> s
->stop
.worst
.time
) return true;
700 desired_done
= elapsed
> s
->stop
.desired
.time
;
702 } else { assert(ti
->dim
== TD_GAMES
);
703 if (i
> s
->stop
.worst
.playouts
) return true;
704 desired_done
= i
> s
->stop
.desired
.playouts
;
707 /* We want to stop simulating, but are willing to keep trying
708 * if we aren't completely sure about the winner yet. */
710 if (u
->policy
->winner
&& u
->policy
->evaluate
) {
711 struct uct_descent descent
= { .node
= ctx
->t
->root
};
712 u
->policy
->winner(u
->policy
, ctx
->t
, &descent
);
713 winner
= descent
.node
;
716 bestr
= u
->policy
->choose(u
->policy
, best
, b
, stone_other(color
), resign
);
717 if (!uct_search_keep_looking(u
, ctx
->t
, b
, ti
, &s
->stop
, best
, best2
, bestr
, winner
, i
))
721 /* TODO: Early break if best->variance goes under threshold
722 * and we already have enough playouts (possibly thanks to book
723 * or to pondering)? */
727 /* Run time-limited MCTS search. For a slave in the distributed
728 * engine, the search is done in background and will be stopped at
729 * the next uct_notify_play(); keep_looking is advice for the master. */
731 uct_search(struct uct
*u
, struct board
*b
, struct time_info
*ti
, enum stone color
,
732 struct tree
*t
, bool *keep_looking
)
734 *keep_looking
= false;
736 struct uct_search_state s
;
737 if (!thread_manager_running
) {
738 uct_search_start(u
, b
, color
, t
, ti
, &s
);
739 if (UDEBUGL(2) && s
.base_playouts
> 0)
740 fprintf(stderr
, "<pre-simulated %d games>\n", s
.base_playouts
);
742 /* Keep the search running. */
745 struct spawn_ctx
*ctx
= s
.ctx
;
747 /* The search tree is ctx->t. This is normally == t, but in case of
748 * TM_ROOT, it is one of the trees belonging to the independent
749 * workers. It is important to reference ctx->t directly since the
750 * thread manager will swap the tree pointer asynchronously. */
751 /* XXX: This means TM_ROOT support is suboptimal since single stalled
752 * thread can stall the others in case of limiting the search by game
753 * count. However, TM_ROOT just does not deserve any more extra code
756 /* Now, just periodically poll the search tree. */
758 time_sleep(TREE_BUSYWAIT_INTERVAL
);
759 /* TREE_BUSYWAIT_INTERVAL should never be less than desired time, or the
760 * time control is broken. But if it happens to be less, we still search
761 * at least 100ms otherwise the move is completely random. */
763 int i
= uct_search_games(&s
);
764 /* Print notifications etc. */
765 uct_search_progress(u
, b
, color
, t
, ti
, &s
, i
);
766 /* Check if we should stop the search. */
767 if (uct_search_check_stop(u
, b
, color
, t
, ti
, &s
, i
))
770 /* If running as slave in the distributed engine,
771 * let the search continue in background. */
773 *keep_looking
= true;
780 ctx
= uct_search_stop();
782 if (UDEBUGL(2)) tree_dump(t
, u
->dumpthres
);
784 /* We can only return an estimate here. */
785 games
= uct_search_games(&s
) - s
.base_playouts
;
788 fprintf(stderr
, "(avg score %f/%d value %f/%d)\n",
789 u
->dynkomi
->score
.value
, u
->dynkomi
->score
.playouts
,
790 u
->dynkomi
->value
.value
, u
->dynkomi
->value
.playouts
);
792 uct_progress_status(u
, t
, color
, games
);
794 u
->played_own
+= games
;
799 /* Start pondering background with @color to play. */
801 uct_pondering_start(struct uct
*u
, struct board
*b0
, struct tree
*t
, enum stone color
)
804 fprintf(stderr
, "Starting to ponder with color %s\n", stone2str(stone_other(color
)));
807 /* We need a local board copy to ponder upon. */
808 struct board
*b
= malloc2(sizeof(*b
)); board_copy(b
, b0
);
810 /* *b0 did not have the genmove'd move played yet. */
811 struct move m
= { t
->root
->coord
, t
->root_color
};
812 int res
= board_play(b
, &m
);
814 setup_dynkomi(u
, b
, stone_other(m
.color
));
816 /* Start MCTS manager thread "headless". */
817 static struct uct_search_state s
;
818 uct_search_start(u
, b
, color
, t
, NULL
, &s
);
821 /* uct_search_stop() frontend for the pondering (non-genmove) mode, and
822 * to stop the background search for a slave in the distributed engine. */
824 uct_pondering_stop(struct uct
*u
)
826 if (!thread_manager_running
)
829 /* Stop the thread manager. */
830 struct spawn_ctx
*ctx
= uct_search_stop();
832 if (u
->pondering
) fprintf(stderr
, "(pondering) ");
833 uct_progress_status(u
, ctx
->t
, ctx
->color
, ctx
->games
);
837 u
->pondering
= false;
842 uct_search_setup(struct uct
*u
, struct board
*b
, enum stone color
)
844 if (b
->superko_violation
) {
845 fprintf(stderr
, "!!! WARNING: SUPERKO VIOLATION OCCURED BEFORE THIS MOVE\n");
846 fprintf(stderr
, "Maybe you play with situational instead of positional superko?\n");
847 fprintf(stderr
, "I'm going to ignore the violation, but note that I may miss\n");
848 fprintf(stderr
, "some moves valid under this ruleset because of this.\n");
849 b
->superko_violation
= false;
852 uct_prepare_move(u
, b
, color
);
857 /* How to decide whether to use dynkomi in this game? Since we use
858 * pondering, it's not simple "who-to-play" matter. Decide based on
859 * the last genmove issued. */
860 u
->t
->use_extra_komi
= !!(u
->dynkomi_mask
& color
);
861 setup_dynkomi(u
, b
, color
);
863 if (b
->rules
== RULES_JAPANESE
)
864 u
->territory_scoring
= true;
866 /* Make pessimistic assumption about komi for Japanese rules to
867 * avoid losing by 0.5 when winning by 0.5 with Chinese rules.
868 * The rules usually give the same winner if the integer part of komi
869 * is odd so we adjust the komi only if it is even (for a board of
870 * odd size). We are not trying to get an exact evaluation for rare
871 * cases of seki. For details see http://home.snafu.de/jasiek/parity.html */
872 if (u
->territory_scoring
&& (((int)floor(b
->komi
) + board_size(b
)) & 1)) {
873 b
->komi
+= (color
== S_BLACK
? 1.0 : -1.0);
875 fprintf(stderr
, "Setting komi to %.1f assuming Japanese rules\n",
881 uct_search_best(struct uct
*u
, struct board
*b
, enum stone color
,
882 bool pass_all_alive
, int played_games
, int base_playouts
,
885 /* Choose the best move from the tree. */
886 struct tree_node
*best
= u
->policy
->choose(u
->policy
, u
->t
->root
, b
, color
, resign
);
891 *best_coord
= best
->coord
;
893 fprintf(stderr
, "*** WINNER is %s (%d,%d) with score %1.4f (%d/%d:%d/%d games), extra komi %f\n",
894 coord2sstr(best
->coord
, b
), coord_x(best
->coord
, b
), coord_y(best
->coord
, b
),
895 tree_node_get_value(u
->t
, 1, best
->u
.value
), best
->u
.playouts
,
896 u
->t
->root
->u
.playouts
, u
->t
->root
->u
.playouts
- base_playouts
, played_games
,
899 /* Do not resign if we're so short of time that evaluation of best
900 * move is completely unreliable, we might be winning actually.
901 * In this case best is almost random but still better than resign.
902 * Also do not resign if we are getting bad results while actually
903 * giving away extra komi points (dynkomi). */
904 if (tree_node_get_value(u
->t
, 1, best
->u
.value
) < u
->resign_ratio
905 && !is_pass(best
->coord
) && best
->u
.playouts
> GJ_MINGAMES
906 && u
->t
->extra_komi
< 0.5 /* XXX we assume dynamic komi == we are black */) {
907 *best_coord
= resign
;
911 /* If the opponent just passed and we win counting, always
913 if (b
->moves
> 1 && is_pass(b
->last_move
.coord
)) {
914 /* Make sure enough playouts are simulated. */
915 while (u
->ownermap
.playouts
< GJ_MINGAMES
)
916 uct_playout(u
, b
, color
, u
->t
);
917 if (uct_pass_is_safe(u
, b
, color
, u
->pass_all_alive
|| pass_all_alive
)) {
919 fprintf(stderr
, "<Will rather pass, looks safe enough; score %f>\n",
920 board_official_score(b
, NULL
) / 2);
930 uct_genmove(struct engine
*e
, struct board
*b
, struct time_info
*ti
, enum stone color
, bool pass_all_alive
)
932 double start_time
= time_now();
933 struct uct
*u
= e
->data
;
934 uct_pondering_stop(u
);
935 uct_search_setup(u
, b
, color
);
937 /* Start the Monte Carlo Tree Search! */
939 int base_playouts
= u
->t
->root
->u
.playouts
;
940 int played_games
= uct_search(u
, b
, ti
, color
, u
->t
, &keep_looking
);
943 struct tree_node
*best
;
944 best
= uct_search_best(u
, b
, color
, pass_all_alive
, played_games
, base_playouts
, &best_coord
);
947 double time
= time_now() - start_time
+ 0.000001; /* avoid divide by zero */
948 fprintf(stderr
, "genmove in %0.2fs (%d games/s, %d games/s/thread)\n",
949 time
, (int)(played_games
/time
), (int)(played_games
/time
/u
->threads
));
954 return coord_copy(best_coord
);
956 tree_promote_node(u
->t
, &best
);
958 /* After a pass, pondering is harmful for two reasons:
959 * (i) We might keep pondering even when the game is over.
960 * Of course this is the case for opponent resign as well.
961 * (ii) More importantly, the ownermap will get skewed since
962 * the UCT will start cutting off any playouts. */
963 if (u
->pondering_opt
&& !is_pass(best
->coord
)) {
964 uct_pondering_start(u
, b
, u
->t
, stone_other(color
));
966 return coord_copy(best_coord
);
971 uct_genbook(struct engine
*e
, struct board
*b
, struct time_info
*ti
, enum stone color
)
973 struct uct
*u
= e
->data
;
974 if (!u
->t
) uct_prepare_move(u
, b
, color
);
977 if (ti
->dim
== TD_GAMES
) {
978 /* Don't count in games that already went into the book. */
979 ti
->len
.games
+= u
->t
->root
->u
.playouts
;
982 uct_search(u
, b
, ti
, color
, u
->t
, &keep_looking
);
984 assert(ti
->dim
== TD_GAMES
);
985 tree_save(u
->t
, b
, ti
->len
.games
/ 100);
991 uct_dumpbook(struct engine
*e
, struct board
*b
, enum stone color
)
993 struct uct
*u
= e
->data
;
994 struct tree
*t
= tree_init(b
, color
, u
->fast_alloc
? u
->max_tree_size
: 0, u
->local_tree_aging
);
1002 uct_state_init(char *arg
, struct board
*b
)
1004 struct uct
*u
= calloc2(1, sizeof(struct uct
));
1005 bool using_elo
= false;
1007 u
->debug_level
= debug_level
;
1008 u
->gamelen
= MC_GAMELEN
;
1011 u
->dumpthres
= 1000;
1012 u
->playout_amaf
= true;
1013 u
->playout_amaf_nakade
= false;
1014 u
->amaf_prior
= false;
1015 u
->max_tree_size
= 3072ULL * 1048576;
1017 u
->dynkomi_mask
= S_BLACK
;
1020 u
->thread_model
= TM_TREEVL
;
1021 u
->parallel_tree
= true;
1022 u
->virtual_loss
= true;
1024 u
->fuseki_end
= 20; // max time at 361*20% = 72 moves (our 36th move, still 99 to play)
1025 u
->yose_start
= 40; // (100-40-25)*361/100/2 = 63 moves still to play by us then
1026 u
->bestr_ratio
= 0.02;
1027 // 2.5 is clearly too much, but seems to compensate well for overly stern time allocations.
1028 // TODO: Further tuning and experiments with better time allocation schemes.
1029 u
->best2_ratio
= 2.5;
1031 u
->val_scale
= 0.04; u
->val_points
= 40;
1034 u
->local_tree_aging
= 2;
1037 char *optspec
, *next
= arg
;
1040 next
+= strcspn(next
, ",");
1041 if (*next
) { *next
++ = 0; } else { *next
= 0; }
1043 char *optname
= optspec
;
1044 char *optval
= strchr(optspec
, '=');
1045 if (optval
) *optval
++ = 0;
1047 if (!strcasecmp(optname
, "debug")) {
1049 u
->debug_level
= atoi(optval
);
1052 } else if (!strcasecmp(optname
, "mercy") && optval
) {
1053 /* Minimal difference of black/white captures
1054 * to stop playout - "Mercy Rule". Speeds up
1055 * hopeless playouts at the expense of some
1057 u
->mercymin
= atoi(optval
);
1058 } else if (!strcasecmp(optname
, "gamelen") && optval
) {
1059 u
->gamelen
= atoi(optval
);
1060 } else if (!strcasecmp(optname
, "expand_p") && optval
) {
1061 u
->expand_p
= atoi(optval
);
1062 } else if (!strcasecmp(optname
, "dumpthres") && optval
) {
1063 u
->dumpthres
= atoi(optval
);
1064 } else if (!strcasecmp(optname
, "best2_ratio") && optval
) {
1065 /* If set, prolong simulating while
1066 * first_best/second_best playouts ratio
1067 * is less than best2_ratio. */
1068 u
->best2_ratio
= atof(optval
);
1069 } else if (!strcasecmp(optname
, "bestr_ratio") && optval
) {
1070 /* If set, prolong simulating while
1071 * best,best_best_child values delta
1072 * is more than bestr_ratio. */
1073 u
->bestr_ratio
= atof(optval
);
1074 } else if (!strcasecmp(optname
, "playout_amaf")) {
1075 /* Whether to include random playout moves in
1076 * AMAF as well. (Otherwise, only tree moves
1077 * are included in AMAF. Of course makes sense
1078 * only in connection with an AMAF policy.) */
1079 /* with-without: 55.5% (+-4.1) */
1080 if (optval
&& *optval
== '0')
1081 u
->playout_amaf
= false;
1083 u
->playout_amaf
= true;
1084 } else if (!strcasecmp(optname
, "playout_amaf_nakade")) {
1085 /* Whether to include nakade moves from playouts
1086 * in the AMAF statistics; this tends to nullify
1087 * the playout_amaf effect by adding too much
1089 if (optval
&& *optval
== '0')
1090 u
->playout_amaf_nakade
= false;
1092 u
->playout_amaf_nakade
= true;
1093 } else if (!strcasecmp(optname
, "playout_amaf_cutoff") && optval
) {
1094 /* Keep only first N% of playout stage AMAF
1096 u
->playout_amaf_cutoff
= atoi(optval
);
1097 } else if ((!strcasecmp(optname
, "policy") || !strcasecmp(optname
, "random_policy")) && optval
) {
1098 char *policyarg
= strchr(optval
, ':');
1099 struct uct_policy
**p
= !strcasecmp(optname
, "policy") ? &u
->policy
: &u
->random_policy
;
1102 if (!strcasecmp(optval
, "ucb1")) {
1103 *p
= policy_ucb1_init(u
, policyarg
);
1104 } else if (!strcasecmp(optval
, "ucb1amaf")) {
1105 *p
= policy_ucb1amaf_init(u
, policyarg
);
1107 fprintf(stderr
, "UCT: Invalid tree policy %s\n", optval
);
1110 } else if (!strcasecmp(optname
, "playout") && optval
) {
1111 char *playoutarg
= strchr(optval
, ':');
1114 if (!strcasecmp(optval
, "moggy")) {
1115 u
->playout
= playout_moggy_init(playoutarg
, b
);
1116 } else if (!strcasecmp(optval
, "light")) {
1117 u
->playout
= playout_light_init(playoutarg
, b
);
1118 } else if (!strcasecmp(optval
, "elo")) {
1119 u
->playout
= playout_elo_init(playoutarg
, b
);
1122 fprintf(stderr
, "UCT: Invalid playout policy %s\n", optval
);
1125 } else if (!strcasecmp(optname
, "prior") && optval
) {
1126 u
->prior
= uct_prior_init(optval
, b
);
1127 } else if (!strcasecmp(optname
, "amaf_prior") && optval
) {
1128 u
->amaf_prior
= atoi(optval
);
1129 } else if (!strcasecmp(optname
, "threads") && optval
) {
1130 /* By default, Pachi will run with only single
1131 * tree search thread! */
1132 u
->threads
= atoi(optval
);
1133 } else if (!strcasecmp(optname
, "thread_model") && optval
) {
1134 if (!strcasecmp(optval
, "root")) {
1135 /* Root parallelization - each thread
1136 * does independent search, trees are
1137 * merged at the end. */
1138 u
->thread_model
= TM_ROOT
;
1139 u
->parallel_tree
= false;
1140 u
->virtual_loss
= false;
1141 } else if (!strcasecmp(optval
, "tree")) {
1142 /* Tree parallelization - all threads
1143 * grind on the same tree. */
1144 u
->thread_model
= TM_TREE
;
1145 u
->parallel_tree
= true;
1146 u
->virtual_loss
= false;
1147 } else if (!strcasecmp(optval
, "treevl")) {
1148 /* Tree parallelization, but also
1149 * with virtual losses - this discou-
1150 * rages most threads choosing the
1151 * same tree branches to read. */
1152 u
->thread_model
= TM_TREEVL
;
1153 u
->parallel_tree
= true;
1154 u
->virtual_loss
= true;
1156 fprintf(stderr
, "UCT: Invalid thread model %s\n", optval
);
1159 } else if (!strcasecmp(optname
, "pondering")) {
1160 /* Keep searching even during opponent's turn. */
1161 u
->pondering_opt
= !optval
|| atoi(optval
);
1162 } else if (!strcasecmp(optname
, "fuseki_end") && optval
) {
1163 /* At the very beginning it's not worth thinking
1164 * too long because the playout evaluations are
1165 * very noisy. So gradually increase the thinking
1166 * time up to maximum when fuseki_end percent
1167 * of the board has been played.
1168 * This only applies if we are not in byoyomi. */
1169 u
->fuseki_end
= atoi(optval
);
1170 } else if (!strcasecmp(optname
, "yose_start") && optval
) {
1171 /* When yose_start percent of the board has been
1172 * played, or if we are in byoyomi, stop spending
1173 * more time and spread the remaining time
1175 * Between fuseki_end and yose_start, we spend
1176 * a constant proportion of the remaining time
1177 * on each move. (yose_start should actually
1178 * be much earlier than when real yose start,
1179 * but "yose" is a good short name to convey
1181 u
->yose_start
= atoi(optval
);
1182 } else if (!strcasecmp(optname
, "force_seed") && optval
) {
1183 u
->force_seed
= atoi(optval
);
1184 } else if (!strcasecmp(optname
, "no_book")) {
1186 } else if (!strcasecmp(optname
, "dynkomi") && optval
) {
1187 /* Dynamic komi approach; there are multiple
1188 * ways to adjust komi dynamically throughout
1189 * play. We currently support two: */
1190 char *dynkomiarg
= strchr(optval
, ':');
1193 if (!strcasecmp(optval
, "none")) {
1194 u
->dynkomi
= uct_dynkomi_init_none(u
, dynkomiarg
, b
);
1195 } else if (!strcasecmp(optval
, "linear")) {
1196 u
->dynkomi
= uct_dynkomi_init_linear(u
, dynkomiarg
, b
);
1197 } else if (!strcasecmp(optval
, "adaptive")) {
1198 u
->dynkomi
= uct_dynkomi_init_adaptive(u
, dynkomiarg
, b
);
1200 fprintf(stderr
, "UCT: Invalid dynkomi mode %s\n", optval
);
1203 } else if (!strcasecmp(optname
, "dynkomi_mask") && optval
) {
1204 /* Bitmask of colors the player must be
1205 * for dynkomi be applied; you may want
1206 * to use dynkomi_mask=3 to allow dynkomi
1207 * even in games where Pachi is white. */
1208 u
->dynkomi_mask
= atoi(optval
);
1209 } else if (!strcasecmp(optname
, "dynkomi_interval") && optval
) {
1210 /* If non-zero, re-adjust dynamic komi
1211 * throughout a single genmove reading,
1212 * roughly every N simulations. */
1213 /* XXX: Does not work with tree
1214 * parallelization. */
1215 u
->dynkomi_interval
= atoi(optval
);
1216 } else if (!strcasecmp(optname
, "val_scale") && optval
) {
1217 /* How much of the game result value should be
1218 * influenced by win size. Zero means it isn't. */
1219 u
->val_scale
= atof(optval
);
1220 } else if (!strcasecmp(optname
, "val_points") && optval
) {
1221 /* Maximum size of win to be scaled into game
1222 * result value. Zero means boardsize^2. */
1223 u
->val_points
= atoi(optval
) * 2; // result values are doubled
1224 } else if (!strcasecmp(optname
, "val_extra")) {
1225 /* If false, the score coefficient will be simply
1226 * added to the value, instead of scaling the result
1227 * coefficient because of it. */
1228 u
->val_extra
= !optval
|| atoi(optval
);
1229 } else if (!strcasecmp(optname
, "local_tree") && optval
) {
1230 /* Whether to bias exploration by local tree values
1231 * (must be supported by the used policy).
1233 * 1: Do, value = result.
1234 * Try to temper the result:
1235 * 2: Do, value = 0.5+(result-expected)/2.
1236 * 3: Do, value = 0.5+bzz((result-expected)^2).
1237 * 4: Do, value = 0.5+sqrt(result-expected)/2. */
1238 u
->local_tree
= atoi(optval
);
1239 } else if (!strcasecmp(optname
, "tenuki_d") && optval
) {
1240 /* Tenuki distance at which to break the local tree. */
1241 u
->tenuki_d
= atoi(optval
);
1242 if (u
->tenuki_d
> TREE_NODE_D_MAX
+ 1) {
1243 fprintf(stderr
, "uct: tenuki_d must not be larger than TREE_NODE_D_MAX+1 %d\n", TREE_NODE_D_MAX
+ 1);
1246 } else if (!strcasecmp(optname
, "local_tree_aging") && optval
) {
1247 /* How much to reduce local tree values between moves. */
1248 u
->local_tree_aging
= atof(optval
);
1249 } else if (!strcasecmp(optname
, "local_tree_allseq")) {
1250 /* By default, only complete sequences are stored
1251 * in the local tree. If this is on, also
1252 * subsequences starting at each move are stored. */
1253 u
->local_tree_allseq
= !optval
|| atoi(optval
);
1254 } else if (!strcasecmp(optname
, "local_tree_playout")) {
1255 /* Whether to adjust ELO playout probability
1256 * distributions according to matched localtree
1258 u
->local_tree_playout
= !optval
|| atoi(optval
);
1259 } else if (!strcasecmp(optname
, "local_tree_pseqroot")) {
1260 /* By default, when we have no sequence move
1261 * to suggest in-playout, we give up. If this
1262 * is on, we make probability distribution from
1263 * sequences first moves instead. */
1264 u
->local_tree_pseqroot
= !optval
|| atoi(optval
);
1265 } else if (!strcasecmp(optname
, "pass_all_alive")) {
1266 /* Whether to consider passing only after all
1267 * dead groups were removed from the board;
1268 * this is like all genmoves are in fact
1269 * kgs-genmove_cleanup. */
1270 u
->pass_all_alive
= !optval
|| atoi(optval
);
1271 } else if (!strcasecmp(optname
, "territory_scoring")) {
1272 /* Use territory scoring (default is area scoring).
1273 * An explicit kgs-rules command overrides this. */
1274 u
->territory_scoring
= !optval
|| atoi(optval
);
1275 } else if (!strcasecmp(optname
, "random_policy_chance") && optval
) {
1276 /* If specified (N), with probability 1/N, random_policy policy
1277 * descend is used instead of main policy descend; useful
1278 * if specified policy (e.g. UCB1AMAF) can make unduly biased
1279 * choices sometimes, you can fall back to e.g.
1280 * random_policy=UCB1. */
1281 u
->random_policy_chance
= atoi(optval
);
1282 } else if (!strcasecmp(optname
, "max_tree_size") && optval
) {
1283 /* Maximum amount of memory [MiB] consumed by the move tree.
1284 * For fast_alloc it includes the temp tree used for pruning.
1285 * Default is 3072 (3 GiB). Note that if you use TM_ROOT,
1286 * this limits size of only one of the trees, not all of them
1288 u
->max_tree_size
= atol(optval
) * 1048576;
1289 } else if (!strcasecmp(optname
, "fast_alloc")) {
1290 u
->fast_alloc
= !optval
|| atoi(optval
);
1291 } else if (!strcasecmp(optname
, "slave")) {
1292 /* Act as slave for the distributed engine. */
1293 u
->slave
= !optval
|| atoi(optval
);
1294 } else if (!strcasecmp(optname
, "banner") && optval
) {
1295 /* Additional banner string. This must come as the
1296 * last engine parameter. */
1297 if (*next
) *--next
= ',';
1298 u
->banner
= strdup(optval
);
1301 fprintf(stderr
, "uct: Invalid engine argument %s or missing value\n", optname
);
1307 u
->resign_ratio
= 0.2; /* Resign when most games are lost. */
1308 u
->loss_threshold
= 0.85; /* Stop reading if after at least 2000 playouts this is best value. */
1310 u
->policy
= policy_ucb1amaf_init(u
, NULL
);
1312 if (!!u
->random_policy_chance
^ !!u
->random_policy
) {
1313 fprintf(stderr
, "uct: Only one of random_policy and random_policy_chance is set\n");
1317 if (!u
->local_tree
) {
1318 /* No ltree aging. */
1319 u
->local_tree_aging
= 1.0f
;
1322 u
->local_tree_playout
= false;
1324 if (u
->fast_alloc
&& !u
->parallel_tree
) {
1325 fprintf(stderr
, "fast_alloc not supported with root parallelization.\n");
1329 u
->max_tree_size
= (100ULL * u
->max_tree_size
) / (100 + MIN_FREE_MEM_PERCENT
);
1332 u
->prior
= uct_prior_init(NULL
, b
);
1335 u
->playout
= playout_moggy_init(NULL
, b
);
1336 u
->playout
->debug_level
= u
->debug_level
;
1338 u
->ownermap
.map
= malloc2(board_size2(b
) * sizeof(u
->ownermap
.map
[0]));
1339 u
->stats
= malloc2(board_size2(b
) * sizeof(u
->stats
[0]));
1342 u
->dynkomi
= uct_dynkomi_init_linear(u
, NULL
, b
);
1344 /* Some things remain uninitialized for now - the opening book
1345 * is not loaded and the tree not set up. */
1346 /* This will be initialized in setup_state() at the first move
1347 * received/requested. This is because right now we are not aware
1348 * about any komi or handicap setup and such. */
1354 engine_uct_init(char *arg
, struct board
*b
)
1356 struct uct
*u
= uct_state_init(arg
, b
);
1357 struct engine
*e
= calloc2(1, sizeof(struct engine
));
1358 e
->name
= "UCT Engine";
1359 e
->printhook
= uct_printhook_ownermap
;
1360 e
->notify_play
= uct_notify_play
;
1362 e
->genmove
= uct_genmove
;
1363 e
->genmoves
= uct_genmoves
;
1364 e
->dead_group_list
= uct_dead_group_list
;
1368 e
->notify
= uct_notify
;
1370 const char banner
[] = "I'm playing UCT. When I'm losing, I will resign, "
1371 "if I think I win, I play until you pass. "
1372 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
1373 if (!u
->banner
) u
->banner
= "";
1374 e
->comment
= malloc2(sizeof(banner
) + strlen(u
->banner
) + 1);
1375 sprintf(e
->comment
, "%s %s", banner
, u
->banner
);