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 /* Set in main thread in case the playouts should stop. */
239 volatile sig_atomic_t uct_halt
= 0;
240 /* ID of the running worker thread. */
241 __thread
int thread_id
= -1;
243 static pthread_mutex_t finish_mutex
= PTHREAD_MUTEX_INITIALIZER
;
244 static pthread_cond_t finish_cond
= PTHREAD_COND_INITIALIZER
;
245 static volatile int finish_thread
;
246 static pthread_mutex_t finish_serializer
= PTHREAD_MUTEX_INITIALIZER
;
259 spawn_helper(void *ctx_
)
261 struct spawn_ctx
*ctx
= ctx_
;
263 fast_srandom(ctx
->seed
);
264 thread_id
= ctx
->tid
;
266 ctx
->games
= uct_playouts(ctx
->u
, ctx
->b
, ctx
->color
, ctx
->t
, ctx
->games
);
268 pthread_mutex_lock(&finish_serializer
);
269 pthread_mutex_lock(&finish_mutex
);
270 finish_thread
= ctx
->tid
;
271 pthread_cond_signal(&finish_cond
);
272 pthread_mutex_unlock(&finish_mutex
);
277 uct_playouts_parallel(struct uct
*u
, struct board
*b
, enum stone color
, struct tree
*t
, int games
, bool shared_tree
)
279 assert(u
->threads
> 0);
280 assert(u
->parallel_tree
== shared_tree
);
282 int played_games
= 0;
283 pthread_t threads
[u
->threads
];
287 pthread_mutex_lock(&finish_mutex
);
288 /* Spawn threads... */
289 for (int ti
= 0; ti
< u
->threads
; ti
++) {
290 struct spawn_ctx
*ctx
= malloc(sizeof(*ctx
));
291 ctx
->u
= u
; ctx
->b
= b
; ctx
->color
= color
;
292 ctx
->t
= shared_tree
? t
: tree_copy(t
);
293 ctx
->tid
= ti
; ctx
->games
= games
;
294 ctx
->seed
= fast_random(65536) + ti
;
295 pthread_create(&threads
[ti
], NULL
, spawn_helper
, ctx
);
297 fprintf(stderr
, "Spawned thread %d\n", ti
);
300 /* ...and collect them back: */
301 while (joined
< u
->threads
) {
302 /* Wait for some thread to finish... */
303 pthread_cond_wait(&finish_cond
, &finish_mutex
);
304 /* ...and gather its remnants. */
305 struct spawn_ctx
*ctx
;
306 pthread_join(threads
[finish_thread
], (void **) &ctx
);
307 played_games
+= ctx
->games
;
310 tree_merge(t
, ctx
->t
);
315 fprintf(stderr
, "Joined thread %d\n", finish_thread
);
316 /* Do not get stalled by slow threads. */
317 if (joined
>= u
->threads
/ 2)
319 pthread_mutex_unlock(&finish_serializer
);
321 pthread_mutex_unlock(&finish_mutex
);
324 /* XXX: Should this be done in shared trees as well? */
325 tree_normalize(t
, u
->threads
);
331 typedef int (*uct_threaded_playouts
)(struct uct
*u
, struct board
*b
, enum stone color
, struct tree
*t
, int games
);
334 uct_playouts_none(struct uct
*u
, struct board
*b
, enum stone color
, struct tree
*t
, int games
)
336 return uct_playouts(u
, b
, color
, t
, games
);
340 uct_playouts_root(struct uct
*u
, struct board
*b
, enum stone color
, struct tree
*t
, int games
)
342 return uct_playouts_parallel(u
, b
, color
, t
, games
, false);
346 uct_playouts_tree(struct uct
*u
, struct board
*b
, enum stone color
, struct tree
*t
, int games
)
348 return uct_playouts_parallel(u
, b
, color
, t
, games
, true);
351 static uct_threaded_playouts threaded_playouts
[] = {
360 uct_genmove(struct engine
*e
, struct board
*b
, enum stone color
, bool pass_all_alive
)
362 struct uct
*u
= e
->data
;
364 if (b
->superko_violation
) {
365 fprintf(stderr
, "!!! WARNING: SUPERKO VIOLATION OCCURED BEFORE THIS MOVE\n");
366 fprintf(stderr
, "Maybe you play with situational instead of positional superko?\n");
367 fprintf(stderr
, "I'm going to ignore the violation, but note that I may miss\n");
368 fprintf(stderr
, "some moves valid under this ruleset because of this.\n");
369 b
->superko_violation
= false;
373 prepare_move(e
, b
, color
);
376 /* Run the simulations. */
377 int games
= u
->games
;
378 if (u
->t
->root
->children
) {
379 int delta
= u
->t
->root
->u
.playouts
* 2 / 3;
380 if (u
->parallel_tree
) delta
/= u
->threads
;
383 /* else this is highly read-out but dead-end branch of opening book;
384 * we need to start from scratch; XXX: Maybe actually base the readout
385 * count based on number of playouts of best node? */
386 if (games
< u
->games
&& UDEBUGL(2))
387 fprintf(stderr
, "<pre-simulated %d games skipped>\n", u
->games
- games
);
390 played_games
= threaded_playouts
[u
->thread_model
](u
, b
, color
, u
->t
, games
);
393 tree_dump(u
->t
, u
->dumpthres
);
395 /* Choose the best move from the tree. */
396 struct tree_node
*best
= u
->policy
->choose(u
->policy
, u
->t
->root
, b
, color
);
399 return coord_copy(pass
);
402 uct_progress_status(u
, u
->t
, color
, played_games
);
405 fprintf(stderr
, "*** WINNER is %s (%d,%d) with score %1.4f (%d/%d:%d games)\n",
406 coord2sstr(best
->coord
, b
), coord_x(best
->coord
, b
), coord_y(best
->coord
, b
),
407 tree_node_get_value(u
->t
, 1, best
->u
.value
),
408 best
->u
.playouts
, u
->t
->root
->u
.playouts
, played_games
);
409 if (tree_node_get_value(u
->t
, 1, best
->u
.value
) < u
->resign_ratio
&& !is_pass(best
->coord
)) {
411 return coord_copy(resign
);
414 /* If the opponent just passed and we win counting, always
416 if (b
->moves
> 1 && is_pass(b
->last_move
.coord
)) {
417 /* Make sure enough playouts are simulated. */
418 while (u
->ownermap
.playouts
< GJ_MINGAMES
)
419 uct_playout(u
, b
, color
, u
->t
);
420 if (uct_pass_is_safe(u
, b
, color
, u
->pass_all_alive
|| pass_all_alive
)) {
422 fprintf(stderr
, "<Will rather pass, looks safe enough.>\n");
427 tree_promote_node(u
->t
, best
);
428 return coord_copy(best
->coord
);
433 uct_genbook(struct engine
*e
, struct board
*b
, enum stone color
)
435 struct uct
*u
= e
->data
;
436 if (!u
->t
) prepare_move(e
, b
, color
);
439 threaded_playouts
[u
->thread_model
](u
, b
, color
, u
->t
, u
->games
);
441 tree_save(u
->t
, b
, u
->games
/ 100);
447 uct_dumpbook(struct engine
*e
, struct board
*b
, enum stone color
)
449 struct tree
*t
= tree_init(b
, color
);
457 uct_state_init(char *arg
, struct board
*b
)
459 struct uct
*u
= calloc(1, sizeof(struct uct
));
463 u
->gamelen
= MC_GAMELEN
;
466 u
->playout_amaf
= true;
467 u
->playout_amaf_nakade
= false;
468 u
->amaf_prior
= false;
470 if (board_size(b
) - 2 >= 19)
472 u
->dynkomi_mask
= S_BLACK
;
474 u
->thread_model
= TM_TREEVL
;
475 u
->parallel_tree
= true;
476 u
->virtual_loss
= true;
478 u
->val_scale
= 0.02; u
->val_points
= 20;
481 char *optspec
, *next
= arg
;
484 next
+= strcspn(next
, ",");
485 if (*next
) { *next
++ = 0; } else { *next
= 0; }
487 char *optname
= optspec
;
488 char *optval
= strchr(optspec
, '=');
489 if (optval
) *optval
++ = 0;
491 if (!strcasecmp(optname
, "debug")) {
493 u
->debug_level
= atoi(optval
);
496 } else if (!strcasecmp(optname
, "games") && optval
) {
497 u
->games
= atoi(optval
);
498 } else if (!strcasecmp(optname
, "gamelen") && optval
) {
499 u
->gamelen
= atoi(optval
);
500 } else if (!strcasecmp(optname
, "expand_p") && optval
) {
501 u
->expand_p
= atoi(optval
);
502 } else if (!strcasecmp(optname
, "dumpthres") && optval
) {
503 u
->dumpthres
= atoi(optval
);
504 } else if (!strcasecmp(optname
, "playout_amaf")) {
505 /* Whether to include random playout moves in
506 * AMAF as well. (Otherwise, only tree moves
507 * are included in AMAF. Of course makes sense
508 * only in connection with an AMAF policy.) */
509 /* with-without: 55.5% (+-4.1) */
510 if (optval
&& *optval
== '0')
511 u
->playout_amaf
= false;
513 u
->playout_amaf
= true;
514 } else if (!strcasecmp(optname
, "playout_amaf_nakade")) {
515 /* Whether to include nakade moves from playouts
516 * in the AMAF statistics; this tends to nullify
517 * the playout_amaf effect by adding too much
519 if (optval
&& *optval
== '0')
520 u
->playout_amaf_nakade
= false;
522 u
->playout_amaf_nakade
= true;
523 } else if (!strcasecmp(optname
, "playout_amaf_cutoff") && optval
) {
524 /* Keep only first N% of playout stage AMAF
526 u
->playout_amaf_cutoff
= atoi(optval
);
527 } else if ((!strcasecmp(optname
, "policy") || !strcasecmp(optname
, "random_policy")) && optval
) {
528 char *policyarg
= strchr(optval
, ':');
529 struct uct_policy
**p
= !strcasecmp(optname
, "policy") ? &u
->policy
: &u
->random_policy
;
532 if (!strcasecmp(optval
, "ucb1")) {
533 *p
= policy_ucb1_init(u
, policyarg
);
534 } else if (!strcasecmp(optval
, "ucb1amaf")) {
535 *p
= policy_ucb1amaf_init(u
, policyarg
);
537 fprintf(stderr
, "UCT: Invalid tree policy %s\n", optval
);
540 } else if (!strcasecmp(optname
, "playout") && optval
) {
541 char *playoutarg
= strchr(optval
, ':');
544 if (!strcasecmp(optval
, "moggy")) {
545 u
->playout
= playout_moggy_init(playoutarg
);
546 } else if (!strcasecmp(optval
, "light")) {
547 u
->playout
= playout_light_init(playoutarg
);
548 } else if (!strcasecmp(optval
, "elo")) {
549 u
->playout
= playout_elo_init(playoutarg
);
551 fprintf(stderr
, "UCT: Invalid playout policy %s\n", optval
);
554 } else if (!strcasecmp(optname
, "prior") && optval
) {
555 u
->prior
= uct_prior_init(optval
);
556 } else if (!strcasecmp(optname
, "amaf_prior") && optval
) {
557 u
->amaf_prior
= atoi(optval
);
558 } else if (!strcasecmp(optname
, "threads") && optval
) {
559 u
->threads
= atoi(optval
);
560 } else if (!strcasecmp(optname
, "thread_model") && optval
) {
561 if (!strcasecmp(optval
, "none")) {
562 /* Turn off multi-threaded reading. */
563 u
->thread_model
= TM_NONE
;
564 } else if (!strcasecmp(optval
, "root")) {
565 /* Root parallelization - each thread
566 * does independent search, trees are
567 * merged at the end. */
568 u
->thread_model
= TM_ROOT
;
569 u
->parallel_tree
= false;
570 u
->virtual_loss
= false;
571 } else if (!strcasecmp(optval
, "tree")) {
572 /* Tree parallelization - all threads
573 * grind on the same tree. */
574 u
->thread_model
= TM_TREE
;
575 u
->parallel_tree
= true;
576 u
->virtual_loss
= false;
577 } else if (!strcasecmp(optval
, "treevl")) {
578 /* Tree parallelization, but also
579 * with virtual losses - this discou-
580 * rages most threads choosing the
581 * same tree branches to read. */
582 u
->thread_model
= TM_TREEVL
;
583 u
->parallel_tree
= true;
584 u
->virtual_loss
= true;
586 fprintf(stderr
, "UCT: Invalid thread model %s\n", optval
);
589 } else if (!strcasecmp(optname
, "force_seed") && optval
) {
590 u
->force_seed
= atoi(optval
);
591 } else if (!strcasecmp(optname
, "no_book")) {
593 } else if (!strcasecmp(optname
, "dynkomi")) {
594 /* Dynamic komi in handicap game; linearly
595 * decreases to basic settings until move
597 u
->dynkomi
= optval
? atoi(optval
) : 150;
598 } else if (!strcasecmp(optname
, "dynkomi_mask") && optval
) {
599 /* Bitmask of colors the player must be
600 * for dynkomi be applied; you may want
601 * to use dynkomi_mask=3 to allow dynkomi
602 * even in games where Pachi is white. */
603 u
->dynkomi_mask
= atoi(optval
);
604 } else if (!strcasecmp(optname
, "val_scale") && optval
) {
605 /* How much of the game result value should be
606 * influenced by win size. Zero means it isn't. */
607 u
->val_scale
= atof(optval
);
608 } else if (!strcasecmp(optname
, "val_points") && optval
) {
609 /* Maximum size of win to be scaled into game
610 * result value. Zero means boardsize^2. */
611 u
->val_points
= atoi(optval
) * 2; // result values are doubled
612 } else if (!strcasecmp(optname
, "val_extra")) {
613 /* If false, the score coefficient will be simply
614 * added to the value, instead of scaling the result
615 * coefficient because of it. */
616 u
->val_extra
= !optval
|| atoi(optval
);
617 } else if (!strcasecmp(optname
, "root_heuristic") && optval
) {
618 /* Whether to bias exploration by root node values
619 * (must be supported by the used policy).
621 * 1: Do, value = result.
622 * Try to temper the result:
623 * 2: Do, value = 0.5+(result-expected)/2.
624 * 3: Do, value = 0.5+bzz((result-expected)^2). */
625 u
->root_heuristic
= atoi(optval
);
626 } else if (!strcasecmp(optname
, "pass_all_alive")) {
627 /* Whether to consider all stones alive at the game
628 * end instead of marking dead groupd. */
629 u
->pass_all_alive
= !optval
|| atoi(optval
);
630 } else if (!strcasecmp(optname
, "random_policy_chance") && optval
) {
631 /* If specified (N), with probability 1/N, random_policy policy
632 * descend is used instead of main policy descend; useful
633 * if specified policy (e.g. UCB1AMAF) can make unduly biased
634 * choices sometimes, you can fall back to e.g.
635 * random_policy=UCB1. */
636 u
->random_policy_chance
= atoi(optval
);
637 } else if (!strcasecmp(optname
, "banner") && optval
) {
638 /* Additional banner string. This must come as the
639 * last engine parameter. */
640 if (*next
) *--next
= ',';
641 u
->banner
= strdup(optval
);
644 fprintf(stderr
, "uct: Invalid engine argument %s or missing value\n", optname
);
650 u
->resign_ratio
= 0.2; /* Resign when most games are lost. */
651 u
->loss_threshold
= 0.85; /* Stop reading if after at least 5000 playouts this is best value. */
653 u
->policy
= policy_ucb1amaf_init(u
, NULL
);
655 u
->thread_model
= TM_NONE
;
656 u
->parallel_tree
= false;
659 if (!!u
->random_policy_chance
^ !!u
->random_policy
) {
660 fprintf(stderr
, "uct: Only one of random_policy and random_policy_chance is set\n");
665 u
->prior
= uct_prior_init(NULL
);
668 u
->playout
= playout_moggy_init(NULL
);
669 u
->playout
->debug_level
= u
->debug_level
;
671 u
->ownermap
.map
= malloc(board_size2(b
) * sizeof(u
->ownermap
.map
[0]));
673 /* Some things remain uninitialized for now - the opening book
674 * is not loaded and the tree not set up. */
675 /* This will be initialized in setup_state() at the first move
676 * received/requested. This is because right now we are not aware
677 * about any komi or handicap setup and such. */
683 engine_uct_init(char *arg
, struct board
*b
)
685 struct uct
*u
= uct_state_init(arg
, b
);
686 struct engine
*e
= calloc(1, sizeof(struct engine
));
687 e
->name
= "UCT Engine";
688 e
->printhook
= uct_printhook_ownermap
;
689 e
->notify_play
= uct_notify_play
;
691 e
->genmove
= uct_genmove
;
692 e
->dead_group_list
= uct_dead_group_list
;
696 const char banner
[] = "I'm playing UCT. When I'm losing, I will resign, "
697 "if I think I win, I play until you pass. "
698 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
699 if (!u
->banner
) u
->banner
= "";
700 e
->comment
= malloc(sizeof(banner
) + strlen(u
->banner
) + 1);
701 sprintf(e
->comment
, "%s %s", banner
, u
->banner
);