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
)
104 if (u
->ownermap
.playouts
< GJ_MINGAMES
)
107 struct move_queue mq
= { .moves
= 0 };
108 if (!u
->pass_all_alive
)
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 playouts, %s %s can win with %.2f%% probability",
170 n
->u
.playouts
* (u
->thread_model
== TM_ROOT
? u
->threads
: 1),
171 stone2str(color
), coord2sstr(n
->coord
, b
),
172 tree_node_get_value(u
->t
, -1, n
->u
.value
) * 100);
173 if (abs(u
->t
->extra_komi
) >= 0.5) {
174 sprintf(reply
+ strlen(reply
), ", while self-imposing extra komi %.1f",
184 uct_dead_group_list(struct engine
*e
, struct board
*b
, struct move_queue
*mq
)
186 struct uct
*u
= e
->data
;
187 if (u
->pass_all_alive
)
188 return; // no dead groups
190 bool mock_state
= false;
193 /* No state, but we cannot just back out - we might
194 * have passed earlier, only assuming some stones are
195 * dead, and then re-connected, only to lose counting
196 * when all stones are assumed alive. */
197 /* Mock up some state and seed the ownermap by few
199 prepare_move(e
, b
, S_BLACK
); assert(u
->t
);
200 for (int i
= 0; i
< GJ_MINGAMES
; i
++)
201 uct_playout(u
, b
, S_BLACK
, u
->t
);
205 dead_group_list(u
, b
, mq
);
208 /* Clean up the mock state in case we will receive
209 * a genmove; we could get a non-alternating-move
210 * error from prepare_move() in that case otherwise. */
216 playout_policy_done(struct playout_policy
*p
)
218 if (p
->done
) p
->done(p
);
219 if (p
->data
) free(p
->data
);
224 uct_done(struct engine
*e
)
226 /* This is called on engine reset, especially when clear_board
227 * is received and new game should begin. */
228 struct uct
*u
= e
->data
;
229 if (u
->t
) reset_state(u
);
230 free(u
->ownermap
.map
);
233 free(u
->random_policy
);
234 playout_policy_done(u
->playout
);
235 uct_prior_done(u
->prior
);
239 /* Set in main thread in case the playouts should stop. */
240 volatile sig_atomic_t uct_halt
= 0;
241 /* ID of the running worker thread. */
242 __thread
int thread_id
= -1;
244 static pthread_mutex_t finish_mutex
= PTHREAD_MUTEX_INITIALIZER
;
245 static pthread_cond_t finish_cond
= PTHREAD_COND_INITIALIZER
;
246 static volatile int finish_thread
;
247 static pthread_mutex_t finish_serializer
= PTHREAD_MUTEX_INITIALIZER
;
260 spawn_helper(void *ctx_
)
262 struct spawn_ctx
*ctx
= ctx_
;
264 fast_srandom(ctx
->seed
);
265 thread_id
= ctx
->tid
;
267 ctx
->games
= uct_playouts(ctx
->u
, ctx
->b
, ctx
->color
, ctx
->t
, ctx
->games
);
269 pthread_mutex_lock(&finish_serializer
);
270 pthread_mutex_lock(&finish_mutex
);
271 finish_thread
= ctx
->tid
;
272 pthread_cond_signal(&finish_cond
);
273 pthread_mutex_unlock(&finish_mutex
);
278 uct_playouts_parallel(struct uct
*u
, struct board
*b
, enum stone color
, struct tree
*t
, int games
, bool shared_tree
)
280 assert(u
->threads
> 0);
281 assert(u
->parallel_tree
== shared_tree
);
283 int played_games
= 0;
284 pthread_t threads
[u
->threads
];
288 pthread_mutex_lock(&finish_mutex
);
289 /* Spawn threads... */
290 for (int ti
= 0; ti
< u
->threads
; ti
++) {
291 struct spawn_ctx
*ctx
= malloc(sizeof(*ctx
));
292 ctx
->u
= u
; ctx
->b
= b
; ctx
->color
= color
;
293 ctx
->t
= shared_tree
? t
: tree_copy(t
);
294 ctx
->tid
= ti
; ctx
->games
= games
;
295 ctx
->seed
= fast_random(65536) + ti
;
296 pthread_create(&threads
[ti
], NULL
, spawn_helper
, ctx
);
298 fprintf(stderr
, "Spawned thread %d\n", ti
);
301 /* ...and collect them back: */
302 while (joined
< u
->threads
) {
303 /* Wait for some thread to finish... */
304 pthread_cond_wait(&finish_cond
, &finish_mutex
);
305 /* ...and gather its remnants. */
306 struct spawn_ctx
*ctx
;
307 pthread_join(threads
[finish_thread
], (void **) &ctx
);
308 played_games
+= ctx
->games
;
312 tree_merge(t
, ctx
->t
);
318 fprintf(stderr
, "Joined thread %d\n", finish_thread
);
319 /* Do not get stalled by slow threads. */
320 if (joined
>= u
->threads
/ 2)
322 pthread_mutex_unlock(&finish_serializer
);
324 pthread_mutex_unlock(&finish_mutex
);
328 /* XXX: Should this be done in shared trees as well? */
329 tree_normalize(t
, u
->threads
);
336 typedef int (*uct_threaded_playouts
)(struct uct
*u
, struct board
*b
, enum stone color
, struct tree
*t
, int games
);
339 uct_playouts_none(struct uct
*u
, struct board
*b
, enum stone color
, struct tree
*t
, int games
)
341 return uct_playouts(u
, b
, color
, t
, games
);
345 uct_playouts_root(struct uct
*u
, struct board
*b
, enum stone color
, struct tree
*t
, int games
)
347 return uct_playouts_parallel(u
, b
, color
, t
, games
, false);
351 uct_playouts_tree(struct uct
*u
, struct board
*b
, enum stone color
, struct tree
*t
, int games
)
353 return uct_playouts_parallel(u
, b
, color
, t
, games
, true);
356 static uct_threaded_playouts threaded_playouts
[] = {
365 uct_genmove(struct engine
*e
, struct board
*b
, enum stone color
)
367 struct uct
*u
= e
->data
;
369 if (b
->superko_violation
) {
370 fprintf(stderr
, "!!! WARNING: SUPERKO VIOLATION OCCURED BEFORE THIS MOVE\n");
371 fprintf(stderr
, "Maybe you play with situational instead of positional superko?\n");
372 fprintf(stderr
, "I'm going to ignore the violation, but note that I may miss\n");
373 fprintf(stderr
, "some moves valid under this ruleset because of this.\n");
374 b
->superko_violation
= false;
378 prepare_move(e
, b
, color
);
381 /* Run the simulations. */
382 int games
= u
->games
;
383 if (u
->t
->root
->children
) {
384 int delta
= u
->t
->root
->u
.playouts
* 2 / 3;
385 if (u
->parallel_tree
) delta
/= u
->threads
;
388 /* else this is highly read-out but dead-end branch of opening book;
389 * we need to start from scratch; XXX: Maybe actually base the readout
390 * count based on number of playouts of best node? */
391 if (games
< u
->games
&& UDEBUGL(2))
392 fprintf(stderr
, "<pre-simulated %d games skipped>\n", u
->games
- games
);
395 played_games
= threaded_playouts
[u
->thread_model
](u
, b
, color
, u
->t
, games
);
398 tree_dump(u
->t
, u
->dumpthres
);
400 /* Choose the best move from the tree. */
401 struct tree_node
*best
= u
->policy
->choose(u
->policy
, u
->t
->root
, b
, color
);
404 return coord_copy(pass
);
407 uct_progress_status(u
, u
->t
, color
, played_games
);
410 fprintf(stderr
, "*** WINNER is %s (%d,%d) with score %1.4f (%d/%d:%d games)\n",
411 coord2sstr(best
->coord
, b
), coord_x(best
->coord
, b
), coord_y(best
->coord
, b
),
412 tree_node_get_value(u
->t
, 1, best
->u
.value
),
413 best
->u
.playouts
, u
->t
->root
->u
.playouts
, played_games
);
414 if (tree_node_get_value(u
->t
, 1, best
->u
.value
) < u
->resign_ratio
&& !is_pass(best
->coord
)) {
416 return coord_copy(resign
);
419 /* If the opponent just passed and we win counting, always
421 if (b
->moves
> 1 && is_pass(b
->last_move
.coord
)) {
422 /* Make sure enough playouts are simulated. */
423 while (u
->ownermap
.playouts
< GJ_MINGAMES
)
424 uct_playout(u
, b
, color
, u
->t
);
425 if (uct_pass_is_safe(u
, b
, color
)) {
427 fprintf(stderr
, "<Will rather pass, looks safe enough.>\n");
432 tree_promote_node(u
->t
, best
);
433 return coord_copy(best
->coord
);
438 uct_genbook(struct engine
*e
, struct board
*b
, enum stone color
)
440 struct uct
*u
= e
->data
;
441 if (!u
->t
) prepare_move(e
, b
, color
);
444 threaded_playouts
[u
->thread_model
](u
, b
, color
, u
->t
, u
->games
);
446 tree_save(u
->t
, b
, u
->games
/ 100);
452 uct_dumpbook(struct engine
*e
, struct board
*b
, enum stone color
)
454 struct tree
*t
= tree_init(b
, color
);
462 uct_state_init(char *arg
, struct board
*b
)
464 struct uct
*u
= calloc(1, sizeof(struct uct
));
468 u
->gamelen
= MC_GAMELEN
;
471 u
->playout_amaf
= true;
472 u
->playout_amaf_nakade
= false;
473 u
->amaf_prior
= false;
475 if (board_size(b
) - 2 >= 19)
477 u
->dynkomi_mask
= S_BLACK
;
479 u
->thread_model
= TM_TREEVL
;
480 u
->parallel_tree
= true;
481 u
->virtual_loss
= true;
483 u
->val_scale
= 0.02; u
->val_points
= 20;
486 char *optspec
, *next
= arg
;
489 next
+= strcspn(next
, ",");
490 if (*next
) { *next
++ = 0; } else { *next
= 0; }
492 char *optname
= optspec
;
493 char *optval
= strchr(optspec
, '=');
494 if (optval
) *optval
++ = 0;
496 if (!strcasecmp(optname
, "debug")) {
498 u
->debug_level
= atoi(optval
);
501 } else if (!strcasecmp(optname
, "games") && optval
) {
502 u
->games
= atoi(optval
);
503 } else if (!strcasecmp(optname
, "gamelen") && optval
) {
504 u
->gamelen
= atoi(optval
);
505 } else if (!strcasecmp(optname
, "expand_p") && optval
) {
506 u
->expand_p
= atoi(optval
);
507 } else if (!strcasecmp(optname
, "dumpthres") && optval
) {
508 u
->dumpthres
= atoi(optval
);
509 } else if (!strcasecmp(optname
, "playout_amaf")) {
510 /* Whether to include random playout moves in
511 * AMAF as well. (Otherwise, only tree moves
512 * are included in AMAF. Of course makes sense
513 * only in connection with an AMAF policy.) */
514 /* with-without: 55.5% (+-4.1) */
515 if (optval
&& *optval
== '0')
516 u
->playout_amaf
= false;
518 u
->playout_amaf
= true;
519 } else if (!strcasecmp(optname
, "playout_amaf_nakade")) {
520 /* Whether to include nakade moves from playouts
521 * in the AMAF statistics; this tends to nullify
522 * the playout_amaf effect by adding too much
524 if (optval
&& *optval
== '0')
525 u
->playout_amaf_nakade
= false;
527 u
->playout_amaf_nakade
= true;
528 } else if (!strcasecmp(optname
, "playout_amaf_cutoff") && optval
) {
529 /* Keep only first N% of playout stage AMAF
531 u
->playout_amaf_cutoff
= atoi(optval
);
532 } else if ((!strcasecmp(optname
, "policy") || !strcasecmp(optname
, "random_policy")) && optval
) {
533 char *policyarg
= strchr(optval
, ':');
534 struct uct_policy
**p
= !strcasecmp(optname
, "policy") ? &u
->policy
: &u
->random_policy
;
537 if (!strcasecmp(optval
, "ucb1")) {
538 *p
= policy_ucb1_init(u
, policyarg
);
539 } else if (!strcasecmp(optval
, "ucb1amaf")) {
540 *p
= policy_ucb1amaf_init(u
, policyarg
);
542 fprintf(stderr
, "UCT: Invalid tree policy %s\n", optval
);
545 } else if (!strcasecmp(optname
, "playout") && optval
) {
546 char *playoutarg
= strchr(optval
, ':');
549 if (!strcasecmp(optval
, "moggy")) {
550 u
->playout
= playout_moggy_init(playoutarg
);
551 } else if (!strcasecmp(optval
, "light")) {
552 u
->playout
= playout_light_init(playoutarg
);
553 } else if (!strcasecmp(optval
, "elo")) {
554 u
->playout
= playout_elo_init(playoutarg
);
556 fprintf(stderr
, "UCT: Invalid playout policy %s\n", optval
);
559 } else if (!strcasecmp(optname
, "prior") && optval
) {
560 u
->prior
= uct_prior_init(optval
);
561 } else if (!strcasecmp(optname
, "amaf_prior") && optval
) {
562 u
->amaf_prior
= atoi(optval
);
563 } else if (!strcasecmp(optname
, "threads") && optval
) {
564 u
->threads
= atoi(optval
);
565 } else if (!strcasecmp(optname
, "thread_model") && optval
) {
566 if (!strcasecmp(optval
, "none")) {
567 /* Turn off multi-threaded reading. */
568 u
->thread_model
= TM_NONE
;
570 } else if (!strcasecmp(optval
, "root")) {
571 /* Root parallelization - each thread
572 * does independent search, trees are
573 * merged at the end. */
574 u
->thread_model
= TM_ROOT
;
575 u
->parallel_tree
= false;
576 u
->virtual_loss
= false;
578 } else if (!strcasecmp(optval
, "tree")) {
579 /* Tree parallelization - all threads
580 * grind on the same tree. */
581 u
->thread_model
= TM_TREE
;
582 u
->parallel_tree
= true;
583 u
->virtual_loss
= false;
584 } else if (!strcasecmp(optval
, "treevl")) {
585 /* Tree parallelization, but also
586 * with virtual losses - this discou-
587 * rages most threads choosing the
588 * same tree branches to read. */
589 u
->thread_model
= TM_TREEVL
;
590 u
->parallel_tree
= true;
591 u
->virtual_loss
= true;
593 fprintf(stderr
, "UCT: Invalid thread model %s\n", optval
);
596 } else if (!strcasecmp(optname
, "force_seed") && optval
) {
597 u
->force_seed
= atoi(optval
);
598 } else if (!strcasecmp(optname
, "no_book")) {
600 } else if (!strcasecmp(optname
, "dynkomi")) {
601 /* Dynamic komi in handicap game; linearly
602 * decreases to basic settings until move
604 u
->dynkomi
= optval
? atoi(optval
) : 150;
605 } else if (!strcasecmp(optname
, "dynkomi_mask") && optval
) {
606 /* Bitmask of colors the player must be
607 * for dynkomi be applied; you may want
608 * to use dynkomi_mask=3 to allow dynkomi
609 * even in games where Pachi is white. */
610 u
->dynkomi_mask
= atoi(optval
);
611 } else if (!strcasecmp(optname
, "val_scale") && optval
) {
612 /* How much of the game result value should be
613 * influenced by win size. Zero means it isn't. */
614 u
->val_scale
= atof(optval
);
615 } else if (!strcasecmp(optname
, "val_points") && optval
) {
616 /* Maximum size of win to be scaled into game
617 * result value. Zero means boardsize^2. */
618 u
->val_points
= atoi(optval
) * 2; // result values are doubled
619 } else if (!strcasecmp(optname
, "val_extra")) {
620 /* If false, the score coefficient will be simply
621 * added to the value, instead of scaling the result
622 * coefficient because of it. */
623 u
->val_extra
= !optval
|| atoi(optval
);
624 } else if (!strcasecmp(optname
, "root_heuristic") && optval
) {
625 /* Whether to bias exploration by root node values
626 * (must be supported by the used policy).
628 * 1: Do, value = result.
629 * Try to temper the result:
630 * 2: Do, value = 0.5+(result-expected)/2.
631 * 3: Do, value = 0.5+bzz((result-expected)^2). */
632 u
->root_heuristic
= atoi(optval
);
633 } else if (!strcasecmp(optname
, "pass_all_alive")) {
634 /* Whether to consider all stones alive at the game
635 * end instead of marking dead groupd. */
636 u
->pass_all_alive
= !optval
|| atoi(optval
);
637 } else if (!strcasecmp(optname
, "random_policy_chance") && optval
) {
638 /* If specified (N), with probability 1/N, random_policy policy
639 * descend is used instead of main policy descend; useful
640 * if specified policy (e.g. UCB1AMAF) can make unduly biased
641 * choices sometimes, you can fall back to e.g.
642 * random_policy=UCB1. */
643 u
->random_policy_chance
= atoi(optval
);
644 } else if (!strcasecmp(optname
, "banner") && optval
) {
645 /* Additional banner string. This must come as the
646 * last engine parameter. */
647 if (*next
) *--next
= ',';
648 u
->banner
= strdup(optval
);
651 fprintf(stderr
, "uct: Invalid engine argument %s or missing value\n", optname
);
657 u
->resign_ratio
= 0.2; /* Resign when most games are lost. */
658 u
->loss_threshold
= 0.85; /* Stop reading if after at least 5000 playouts this is best value. */
660 u
->policy
= policy_ucb1amaf_init(u
, NULL
);
662 u
->thread_model
= TM_NONE
;
663 u
->parallel_tree
= false;
666 if (!!u
->random_policy_chance
^ !!u
->random_policy
) {
667 fprintf(stderr
, "uct: Only one of random_policy and random_policy_chance is set\n");
672 u
->prior
= uct_prior_init(NULL
);
675 u
->playout
= playout_moggy_init(NULL
);
676 u
->playout
->debug_level
= u
->debug_level
;
678 u
->ownermap
.map
= malloc(board_size2(b
) * sizeof(u
->ownermap
.map
[0]));
680 /* Some things remain uninitialized for now - the opening book
681 * is not loaded and the tree not set up. */
682 /* This will be initialized in setup_state() at the first move
683 * received/requested. This is because right now we are not aware
684 * about any komi or handicap setup and such. */
690 engine_uct_init(char *arg
, struct board
*b
)
692 struct uct
*u
= uct_state_init(arg
, b
);
693 struct engine
*e
= calloc(1, sizeof(struct engine
));
694 e
->name
= "UCT Engine";
695 e
->printhook
= uct_printhook_ownermap
;
696 e
->notify_play
= uct_notify_play
;
698 e
->genmove
= uct_genmove
;
699 e
->dead_group_list
= uct_dead_group_list
;
703 const char banner
[] = "I'm playing UCT. When I'm losing, I will resign, "
704 "if I think I win, I play until you pass. "
705 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
706 if (!u
->banner
) u
->banner
= "";
707 e
->comment
= malloc(sizeof(banner
) + strlen(u
->banner
) + 1);
708 sprintf(e
->comment
, "%s %s", banner
, u
->banner
);