16 #include "playout/elo.h"
17 #include "playout/moggy.h"
18 #include "playout/light.h"
21 #include "uct/internal.h"
22 #include "uct/prior.h"
27 struct uct_policy
*policy_ucb1_init(struct uct
*u
, char *arg
);
28 struct uct_policy
*policy_ucb1amaf_init(struct uct
*u
, char *arg
);
31 #define MC_GAMES 80000
32 #define MC_GAMELEN MAX_GAMELEN
34 /* How big proportion of ownermap counts must be of one color to consider
37 /* How many games to consider at minimum before judging groups. */
38 #define GJ_MINGAMES 500
42 setup_state(struct uct
*u
, struct board
*b
, enum stone color
)
44 u
->t
= tree_init(b
, color
);
46 fast_srandom(u
->force_seed
);
48 fprintf(stderr
, "Fresh board with random seed %lu\n", fast_getseed());
49 //board_print(b, stderr);
50 if (!u
->no_book
&& b
->moves
== 0) {
51 assert(color
== S_BLACK
);
57 reset_state(struct uct
*u
)
60 tree_done(u
->t
); u
->t
= NULL
;
64 prepare_move(struct engine
*e
, struct board
*b
, enum stone color
)
66 struct uct
*u
= e
->data
;
69 /* Verify that we have sane state. */
71 assert(u
->t
&& b
->moves
);
72 if (color
!= stone_other(u
->t
->root_color
)) {
73 fprintf(stderr
, "Fatal: Non-alternating play detected %d %d\n",
74 color
, u
->t
->root_color
);
79 /* We need fresh state. */
81 setup_state(u
, b
, color
);
84 if (u
->dynkomi
&& u
->dynkomi
> b
->moves
&& (color
& u
->dynkomi_mask
))
85 u
->t
->extra_komi
= uct_get_extra_komi(u
, b
);
87 u
->ownermap
.playouts
= 0;
88 memset(u
->ownermap
.map
, 0, board_size2(b
) * sizeof(u
->ownermap
.map
[0]));
92 dead_group_list(struct uct
*u
, struct board
*b
, struct move_queue
*mq
)
94 struct group_judgement gj
;
96 gj
.gs
= alloca(board_size2(b
) * sizeof(gj
.gs
[0]));
97 board_ownermap_judge_group(b
, &u
->ownermap
, &gj
);
98 groups_of_status(b
, &gj
, GS_DEAD
, mq
);
102 uct_pass_is_safe(struct uct
*u
, struct board
*b
, enum stone color
, bool pass_all_alive
)
104 if (u
->ownermap
.playouts
< GJ_MINGAMES
)
107 struct move_queue mq
= { .moves
= 0 };
109 dead_group_list(u
, b
, &mq
);
110 return pass_is_safe(b
, color
, &mq
);
115 uct_printhook_ownermap(struct board
*board
, coord_t c
, FILE *f
)
117 struct uct
*u
= board
->es
;
119 const char chr
[] = ":XO,"; // dame, black, white, unclear
120 const char chm
[] = ":xo,";
121 char ch
= chr
[board_ownermap_judge_point(&u
->ownermap
, c
, GJ_THRES
)];
122 if (ch
== ',') { // less precise estimate then?
123 ch
= chm
[board_ownermap_judge_point(&u
->ownermap
, c
, 0.67)];
125 fprintf(f
, "%c ", ch
);
129 uct_notify_play(struct engine
*e
, struct board
*b
, struct move
*m
)
131 struct uct
*u
= e
->data
;
133 /* No state, create one - this is probably game beginning
134 * and we need to load the opening book right now. */
135 prepare_move(e
, b
, m
->color
);
139 if (is_resign(m
->coord
)) {
145 /* Promote node of the appropriate move to the tree root. */
147 if (!tree_promote_at(u
->t
, b
, m
->coord
)) {
149 fprintf(stderr
, "Warning: Cannot promote move node! Several play commands in row?\n");
158 uct_chat(struct engine
*e
, struct board
*b
, char *cmd
)
160 struct uct
*u
= e
->data
;
161 static char reply
[1024];
163 cmd
+= strspn(cmd
, " \n\t");
164 if (!strncasecmp(cmd
, "winrate", 7)) {
166 return "no game context (yet?)";
167 enum stone color
= u
->t
->root_color
;
168 struct tree_node
*n
= u
->t
->root
;
169 snprintf(reply
, 1024, "In %d*%d playouts, %s %s can win with %.2f%% probability",
170 n
->u
.playouts
, u
->threads
, stone2str(color
), coord2sstr(n
->coord
, b
),
171 tree_node_get_value(u
->t
, -1, n
->u
.value
) * 100);
172 if (abs(u
->t
->extra_komi
) >= 0.5) {
173 sprintf(reply
+ strlen(reply
), ", while self-imposing extra komi %.1f",
183 uct_dead_group_list(struct engine
*e
, struct board
*b
, struct move_queue
*mq
)
185 struct uct
*u
= e
->data
;
186 if (u
->pass_all_alive
)
187 return; // no dead groups
189 bool mock_state
= false;
192 /* No state, but we cannot just back out - we might
193 * have passed earlier, only assuming some stones are
194 * dead, and then re-connected, only to lose counting
195 * when all stones are assumed alive. */
196 /* Mock up some state and seed the ownermap by few
198 prepare_move(e
, b
, S_BLACK
); assert(u
->t
);
199 for (int i
= 0; i
< GJ_MINGAMES
; i
++)
200 uct_playout(u
, b
, S_BLACK
, u
->t
);
204 dead_group_list(u
, b
, mq
);
207 /* Clean up the mock state in case we will receive
208 * a genmove; we could get a non-alternating-move
209 * error from prepare_move() in that case otherwise. */
215 playout_policy_done(struct playout_policy
*p
)
217 if (p
->done
) p
->done(p
);
218 if (p
->data
) free(p
->data
);
223 uct_done(struct engine
*e
)
225 /* This is called on engine reset, especially when clear_board
226 * is received and new game should begin. */
227 struct uct
*u
= e
->data
;
228 if (u
->t
) reset_state(u
);
229 free(u
->ownermap
.map
);
232 free(u
->random_policy
);
233 playout_policy_done(u
->playout
);
234 uct_prior_done(u
->prior
);
238 /* Pachi threading structure (if uct_playouts_parallel() is used):
241 * | main(), GTP communication, ...
244 * | spawns and manages worker threads
250 * uct_playouts() loop, doing descend-playout N=games times
253 /* Set in thread manager in case the workers should stop. */
254 volatile sig_atomic_t uct_halt
= 0;
255 /* ID of the running worker thread. */
256 __thread
int thread_id
= -1;
257 /* ID of the thread manager. */
258 static pthread_t thread_manager
;
259 static bool thread_manager_running
;
261 static pthread_mutex_t finish_mutex
= PTHREAD_MUTEX_INITIALIZER
;
262 static pthread_cond_t finish_cond
= PTHREAD_COND_INITIALIZER
;
263 static volatile int finish_thread
;
264 static pthread_mutex_t finish_serializer
= PTHREAD_MUTEX_INITIALIZER
;
277 spawn_worker(void *ctx_
)
279 struct spawn_ctx
*ctx
= ctx_
;
281 fast_srandom(ctx
->seed
);
282 thread_id
= ctx
->tid
;
284 ctx
->games
= uct_playouts(ctx
->u
, ctx
->b
, ctx
->color
, ctx
->t
, ctx
->games
);
286 pthread_mutex_lock(&finish_serializer
);
287 pthread_mutex_lock(&finish_mutex
);
288 finish_thread
= ctx
->tid
;
289 pthread_cond_signal(&finish_cond
);
290 pthread_mutex_unlock(&finish_mutex
);
294 /* Thread manager, controlling worker threads. It must be called with
295 * finish_mutex lock held, and the finish_cond can be signalled for it
296 * to stop; in that case, the caller should set finish_thread = -1. */
298 spawn_thread_manager(void *ctx_
)
300 /* In thread_manager, we use only some of the ctx fields. */
301 struct spawn_ctx
*mctx
= ctx_
;
302 struct uct
*u
= mctx
->u
;
303 bool shared_tree
= u
->parallel_tree
;
304 fast_srandom(mctx
->seed
);
306 int played_games
= 0;
307 pthread_t threads
[u
->threads
];
311 /* Spawn threads... */
312 for (int ti
= 0; ti
< u
->threads
; ti
++) {
313 struct spawn_ctx
*ctx
= malloc(sizeof(*ctx
));
314 ctx
->u
= u
; ctx
->b
= mctx
->b
; ctx
->color
= mctx
->color
;
315 ctx
->t
= shared_tree
? mctx
->t
: tree_copy(mctx
->t
);
316 ctx
->tid
= ti
; ctx
->games
= mctx
->games
;
317 ctx
->seed
= fast_random(65536) + ti
;
318 pthread_create(&threads
[ti
], NULL
, spawn_worker
, ctx
);
320 fprintf(stderr
, "Spawned worker %d\n", ti
);
323 /* ...and collect them back: */
324 while (joined
< u
->threads
) {
325 /* Wait for some thread to finish... */
326 pthread_cond_wait(&finish_cond
, &finish_mutex
);
327 if (finish_thread
< 0) {
328 /* Stop-by-caller. Tell the workers to wrap up. */
332 /* ...and gather its remnants. */
333 struct spawn_ctx
*ctx
;
334 pthread_join(threads
[finish_thread
], (void **) &ctx
);
335 played_games
+= ctx
->games
;
338 tree_merge(mctx
->t
, ctx
->t
);
343 fprintf(stderr
, "Joined worker %d\n", finish_thread
);
344 /* Do not get stalled by slow threads. */
345 if (joined
>= u
->threads
/ 2)
347 pthread_mutex_unlock(&finish_serializer
);
351 tree_normalize(mctx
->t
, u
->threads
);
353 mctx
->games
= played_games
;
358 uct_pondering_start(struct uct
*u
, struct board
*b0
, enum stone color
, struct tree
*t
, int games
)
360 assert(u
->threads
> 0);
361 assert(!thread_manager_running
);
363 /* *b0 can change in the meantime. */
364 struct board b
; board_copy(&b
, b0
);
366 struct spawn_ctx ctx
= { .u
= u
, .b
= &b
, .color
= color
, .t
= t
, .games
= games
, .seed
= fast_random(65536) };
367 static struct spawn_ctx mctx
; mctx
= ctx
;
368 pthread_mutex_lock(&finish_mutex
);
369 pthread_create(&thread_manager
, NULL
, spawn_thread_manager
, &mctx
);
370 thread_manager_running
= true;
374 uct_pondering_stop(void)
376 assert(thread_manager_running
);
378 struct spawn_ctx
*pctx
;
379 thread_manager_running
= false;
380 pthread_join(thread_manager
, (void **) &pctx
);
381 pthread_mutex_unlock(&finish_mutex
);
386 uct_playouts_threaded(struct uct
*u
, struct board
*b
, enum stone color
, struct tree
*t
, int games
)
388 uct_pondering_start(u
, b
, color
, t
, games
);
389 /* We just wait until the thread manager finishes. */
390 return uct_pondering_stop();
395 uct_genmove(struct engine
*e
, struct board
*b
, enum stone color
, bool pass_all_alive
)
397 struct uct
*u
= e
->data
;
399 if (b
->superko_violation
) {
400 fprintf(stderr
, "!!! WARNING: SUPERKO VIOLATION OCCURED BEFORE THIS MOVE\n");
401 fprintf(stderr
, "Maybe you play with situational instead of positional superko?\n");
402 fprintf(stderr
, "I'm going to ignore the violation, but note that I may miss\n");
403 fprintf(stderr
, "some moves valid under this ruleset because of this.\n");
404 b
->superko_violation
= false;
408 prepare_move(e
, b
, color
);
411 /* Determine number of simulations. */
412 int games
= u
->games
;
413 if (u
->t
->root
->children
) {
414 int delta
= u
->t
->root
->u
.playouts
* 2 / 3;
415 if (u
->parallel_tree
) delta
/= u
->threads
;
418 /* else this is highly read-out but dead-end branch of opening book;
419 * we need to start from scratch; XXX: Maybe actually base the readout
420 * count based on number of playouts of best node? */
421 if (games
< u
->games
&& UDEBUGL(2))
422 fprintf(stderr
, "<pre-simulated %d games skipped>\n", u
->games
- games
);
424 /* Perform the Monte Carlo Tree Search! */
425 int played_games
= uct_playouts_threaded(u
, b
, color
, u
->t
, games
);
428 tree_dump(u
->t
, u
->dumpthres
);
430 /* Choose the best move from the tree. */
431 struct tree_node
*best
= u
->policy
->choose(u
->policy
, u
->t
->root
, b
, color
);
434 return coord_copy(pass
);
437 uct_progress_status(u
, u
->t
, color
, played_games
);
440 fprintf(stderr
, "*** WINNER is %s (%d,%d) with score %1.4f (%d/%d:%d games)\n",
441 coord2sstr(best
->coord
, b
), coord_x(best
->coord
, b
), coord_y(best
->coord
, b
),
442 tree_node_get_value(u
->t
, 1, best
->u
.value
),
443 best
->u
.playouts
, u
->t
->root
->u
.playouts
, played_games
);
444 if (tree_node_get_value(u
->t
, 1, best
->u
.value
) < u
->resign_ratio
&& !is_pass(best
->coord
)) {
446 return coord_copy(resign
);
449 /* If the opponent just passed and we win counting, always
451 if (b
->moves
> 1 && is_pass(b
->last_move
.coord
)) {
452 /* Make sure enough playouts are simulated. */
453 while (u
->ownermap
.playouts
< GJ_MINGAMES
)
454 uct_playout(u
, b
, color
, u
->t
);
455 if (uct_pass_is_safe(u
, b
, color
, u
->pass_all_alive
|| pass_all_alive
)) {
457 fprintf(stderr
, "<Will rather pass, looks safe enough.>\n");
462 tree_promote_node(u
->t
, best
);
463 return coord_copy(best
->coord
);
468 uct_genbook(struct engine
*e
, struct board
*b
, enum stone color
)
470 struct uct
*u
= e
->data
;
471 if (!u
->t
) prepare_move(e
, b
, color
);
474 uct_playouts_threaded(u
, b
, color
, u
->t
, u
->games
);
476 tree_save(u
->t
, b
, u
->games
/ 100);
482 uct_dumpbook(struct engine
*e
, struct board
*b
, enum stone color
)
484 struct tree
*t
= tree_init(b
, color
);
492 uct_state_init(char *arg
, struct board
*b
)
494 struct uct
*u
= calloc(1, sizeof(struct uct
));
498 u
->gamelen
= MC_GAMELEN
;
502 u
->playout_amaf
= true;
503 u
->playout_amaf_nakade
= false;
504 u
->amaf_prior
= false;
505 u
->max_tree_size
= 3072ULL * 1048576;
507 if (board_size(b
) - 2 >= 19)
509 u
->dynkomi_mask
= S_BLACK
;
512 u
->thread_model
= TM_TREEVL
;
513 u
->parallel_tree
= true;
514 u
->virtual_loss
= true;
516 u
->val_scale
= 0.02; u
->val_points
= 20;
519 char *optspec
, *next
= arg
;
522 next
+= strcspn(next
, ",");
523 if (*next
) { *next
++ = 0; } else { *next
= 0; }
525 char *optname
= optspec
;
526 char *optval
= strchr(optspec
, '=');
527 if (optval
) *optval
++ = 0;
529 if (!strcasecmp(optname
, "debug")) {
531 u
->debug_level
= atoi(optval
);
534 } else if (!strcasecmp(optname
, "games") && optval
) {
535 u
->games
= atoi(optval
);
536 } else if (!strcasecmp(optname
, "mercy") && optval
) {
537 /* Minimal difference of black/white captures
538 * to stop playout - "Mercy Rule". Speeds up
539 * hopeless playouts at the expense of some
541 u
->mercymin
= atoi(optval
);
542 } else if (!strcasecmp(optname
, "gamelen") && optval
) {
543 u
->gamelen
= atoi(optval
);
544 } else if (!strcasecmp(optname
, "expand_p") && optval
) {
545 u
->expand_p
= atoi(optval
);
546 } else if (!strcasecmp(optname
, "dumpthres") && optval
) {
547 u
->dumpthres
= atoi(optval
);
548 } else if (!strcasecmp(optname
, "playout_amaf")) {
549 /* Whether to include random playout moves in
550 * AMAF as well. (Otherwise, only tree moves
551 * are included in AMAF. Of course makes sense
552 * only in connection with an AMAF policy.) */
553 /* with-without: 55.5% (+-4.1) */
554 if (optval
&& *optval
== '0')
555 u
->playout_amaf
= false;
557 u
->playout_amaf
= true;
558 } else if (!strcasecmp(optname
, "playout_amaf_nakade")) {
559 /* Whether to include nakade moves from playouts
560 * in the AMAF statistics; this tends to nullify
561 * the playout_amaf effect by adding too much
563 if (optval
&& *optval
== '0')
564 u
->playout_amaf_nakade
= false;
566 u
->playout_amaf_nakade
= true;
567 } else if (!strcasecmp(optname
, "playout_amaf_cutoff") && optval
) {
568 /* Keep only first N% of playout stage AMAF
570 u
->playout_amaf_cutoff
= atoi(optval
);
571 } else if ((!strcasecmp(optname
, "policy") || !strcasecmp(optname
, "random_policy")) && optval
) {
572 char *policyarg
= strchr(optval
, ':');
573 struct uct_policy
**p
= !strcasecmp(optname
, "policy") ? &u
->policy
: &u
->random_policy
;
576 if (!strcasecmp(optval
, "ucb1")) {
577 *p
= policy_ucb1_init(u
, policyarg
);
578 } else if (!strcasecmp(optval
, "ucb1amaf")) {
579 *p
= policy_ucb1amaf_init(u
, policyarg
);
581 fprintf(stderr
, "UCT: Invalid tree policy %s\n", optval
);
584 } else if (!strcasecmp(optname
, "playout") && optval
) {
585 char *playoutarg
= strchr(optval
, ':');
588 if (!strcasecmp(optval
, "moggy")) {
589 u
->playout
= playout_moggy_init(playoutarg
);
590 } else if (!strcasecmp(optval
, "light")) {
591 u
->playout
= playout_light_init(playoutarg
);
592 } else if (!strcasecmp(optval
, "elo")) {
593 u
->playout
= playout_elo_init(playoutarg
);
595 fprintf(stderr
, "UCT: Invalid playout policy %s\n", optval
);
598 } else if (!strcasecmp(optname
, "prior") && optval
) {
599 u
->prior
= uct_prior_init(optval
, b
);
600 } else if (!strcasecmp(optname
, "amaf_prior") && optval
) {
601 u
->amaf_prior
= atoi(optval
);
602 } else if (!strcasecmp(optname
, "threads") && optval
) {
603 /* By default, Pachi will run with only single
604 * tree search thread! */
605 u
->threads
= atoi(optval
);
606 } else if (!strcasecmp(optname
, "thread_model") && optval
) {
607 if (!strcasecmp(optval
, "root")) {
608 /* Root parallelization - each thread
609 * does independent search, trees are
610 * merged at the end. */
611 u
->thread_model
= TM_ROOT
;
612 u
->parallel_tree
= false;
613 u
->virtual_loss
= false;
614 } else if (!strcasecmp(optval
, "tree")) {
615 /* Tree parallelization - all threads
616 * grind on the same tree. */
617 u
->thread_model
= TM_TREE
;
618 u
->parallel_tree
= true;
619 u
->virtual_loss
= false;
620 } else if (!strcasecmp(optval
, "treevl")) {
621 /* Tree parallelization, but also
622 * with virtual losses - this discou-
623 * rages most threads choosing the
624 * same tree branches to read. */
625 u
->thread_model
= TM_TREEVL
;
626 u
->parallel_tree
= true;
627 u
->virtual_loss
= true;
629 fprintf(stderr
, "UCT: Invalid thread model %s\n", optval
);
632 } else if (!strcasecmp(optname
, "force_seed") && optval
) {
633 u
->force_seed
= atoi(optval
);
634 } else if (!strcasecmp(optname
, "no_book")) {
636 } else if (!strcasecmp(optname
, "dynkomi")) {
637 /* Dynamic komi in handicap game; linearly
638 * decreases to basic settings until move
640 u
->dynkomi
= optval
? atoi(optval
) : 150;
641 } else if (!strcasecmp(optname
, "dynkomi_mask") && optval
) {
642 /* Bitmask of colors the player must be
643 * for dynkomi be applied; you may want
644 * to use dynkomi_mask=3 to allow dynkomi
645 * even in games where Pachi is white. */
646 u
->dynkomi_mask
= atoi(optval
);
647 } else if (!strcasecmp(optname
, "val_scale") && optval
) {
648 /* How much of the game result value should be
649 * influenced by win size. Zero means it isn't. */
650 u
->val_scale
= atof(optval
);
651 } else if (!strcasecmp(optname
, "val_points") && optval
) {
652 /* Maximum size of win to be scaled into game
653 * result value. Zero means boardsize^2. */
654 u
->val_points
= atoi(optval
) * 2; // result values are doubled
655 } else if (!strcasecmp(optname
, "val_extra")) {
656 /* If false, the score coefficient will be simply
657 * added to the value, instead of scaling the result
658 * coefficient because of it. */
659 u
->val_extra
= !optval
|| atoi(optval
);
660 } else if (!strcasecmp(optname
, "root_heuristic") && optval
) {
661 /* Whether to bias exploration by root node values
662 * (must be supported by the used policy).
664 * 1: Do, value = result.
665 * Try to temper the result:
666 * 2: Do, value = 0.5+(result-expected)/2.
667 * 3: Do, value = 0.5+bzz((result-expected)^2). */
668 u
->root_heuristic
= atoi(optval
);
669 } else if (!strcasecmp(optname
, "pass_all_alive")) {
670 /* Whether to consider all stones alive at the game
671 * end instead of marking dead groupd. */
672 u
->pass_all_alive
= !optval
|| atoi(optval
);
673 } else if (!strcasecmp(optname
, "random_policy_chance") && optval
) {
674 /* If specified (N), with probability 1/N, random_policy policy
675 * descend is used instead of main policy descend; useful
676 * if specified policy (e.g. UCB1AMAF) can make unduly biased
677 * choices sometimes, you can fall back to e.g.
678 * random_policy=UCB1. */
679 u
->random_policy_chance
= atoi(optval
);
680 } else if (!strcasecmp(optname
, "max_tree_size") && optval
) {
681 /* Maximum amount of memory [MiB] consumed by the move tree.
682 * Default is 3072 (3 GiB). Note that if you use TM_ROOT,
683 * this limits size of only one of the trees, not all of them
685 u
->max_tree_size
= atol(optval
) * 1048576;
686 } else if (!strcasecmp(optname
, "banner") && optval
) {
687 /* Additional banner string. This must come as the
688 * last engine parameter. */
689 if (*next
) *--next
= ',';
690 u
->banner
= strdup(optval
);
693 fprintf(stderr
, "uct: Invalid engine argument %s or missing value\n", optname
);
699 u
->resign_ratio
= 0.2; /* Resign when most games are lost. */
700 u
->loss_threshold
= 0.85; /* Stop reading if after at least 5000 playouts this is best value. */
702 u
->policy
= policy_ucb1amaf_init(u
, NULL
);
704 if (!!u
->random_policy_chance
^ !!u
->random_policy
) {
705 fprintf(stderr
, "uct: Only one of random_policy and random_policy_chance is set\n");
710 u
->prior
= uct_prior_init(NULL
, b
);
713 u
->playout
= playout_moggy_init(NULL
);
714 u
->playout
->debug_level
= u
->debug_level
;
716 u
->ownermap
.map
= malloc(board_size2(b
) * sizeof(u
->ownermap
.map
[0]));
718 /* Some things remain uninitialized for now - the opening book
719 * is not loaded and the tree not set up. */
720 /* This will be initialized in setup_state() at the first move
721 * received/requested. This is because right now we are not aware
722 * about any komi or handicap setup and such. */
728 engine_uct_init(char *arg
, struct board
*b
)
730 struct uct
*u
= uct_state_init(arg
, b
);
731 struct engine
*e
= calloc(1, sizeof(struct engine
));
732 e
->name
= "UCT Engine";
733 e
->printhook
= uct_printhook_ownermap
;
734 e
->notify_play
= uct_notify_play
;
736 e
->genmove
= uct_genmove
;
737 e
->dead_group_list
= uct_dead_group_list
;
741 const char banner
[] = "I'm playing UCT. When I'm losing, I will resign, "
742 "if I think I win, I play until you pass. "
743 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
744 if (!u
->banner
) u
->banner
= "";
745 e
->comment
= malloc(sizeof(banner
) + strlen(u
->banner
) + 1);
746 sprintf(e
->comment
, "%s %s", banner
, u
->banner
);