14 #include "playout/moggy.h"
15 #include "playout/light.h"
18 #include "uct/internal.h"
19 #include "uct/prior.h"
23 struct uct_policy
*policy_ucb1_init(struct uct
*u
, char *arg
);
24 struct uct_policy
*policy_ucb1amaf_init(struct uct
*u
, char *arg
);
27 #define MC_GAMES 80000
28 #define MC_GAMELEN MAX_GAMELEN
32 can_pass(struct board
*b
, enum stone color
)
34 float score
= board_official_score(b
);
37 //fprintf(stderr, "%d score %f\n", color, score);
42 get_extra_komi(struct uct
*u
, struct board
*b
, enum stone player_color
)
44 float extra_komi
= board_effective_handicap(b
) * (u
->dynkomi
- b
->moves
) / u
->dynkomi
;
45 if (player_color
== S_WHITE
)
51 progress_status(struct uct
*u
, struct tree
*t
, enum stone color
, int playouts
)
57 struct tree_node
*best
= u
->policy
->choose(u
->policy
, t
->root
, t
->board
, color
);
59 fprintf(stderr
, "... No moves left\n");
62 fprintf(stderr
, "[%d] ", playouts
);
63 fprintf(stderr
, "best %f ", tree_node_get_value(t
, best
, u
, 1));
66 fprintf(stderr
, "deepest % 2d ", t
->max_depth
- t
->root
->depth
);
69 fprintf(stderr
, "| seq ");
70 for (int depth
= 0; depth
< 6; depth
++) {
71 if (best
&& best
->u
.playouts
>= 25) {
72 fprintf(stderr
, "%3s ", coord2sstr(best
->coord
, t
->board
));
73 best
= u
->policy
->choose(u
->policy
, best
, t
->board
, color
);
80 fprintf(stderr
, "| can ");
82 struct tree_node
*can
[cans
];
83 memset(can
, 0, sizeof(can
));
84 best
= t
->root
->children
;
87 while ((!can
[c
] || best
->u
.playouts
> can
[c
]->u
.playouts
) && ++c
< cans
);
88 for (int d
= 0; d
< c
; d
++) can
[d
] = can
[d
+ 1];
89 if (c
> 0) can
[c
- 1] = best
;
94 fprintf(stderr
, "%3s(%.3f) ",
95 coord2sstr(can
[cans
]->coord
, t
->board
),
96 tree_node_get_value(t
, can
[cans
], u
, 1));
102 fprintf(stderr
, "\n");
107 uct_leaf_node(struct uct
*u
, struct board
*b
, enum stone player_color
,
108 struct playout_amafmap
*amaf
,
109 struct tree
*t
, struct tree_node
*n
, enum stone node_color
,
112 enum stone next_color
= stone_other(node_color
);
113 int parity
= (next_color
== player_color
? 1 : -1);
114 if (n
->u
.playouts
>= u
->expand_p
) {
115 // fprintf(stderr, "expanding %s (%p ^-%p)\n", coord2sstr(n->coord, b), n, n->parent);
116 tree_expand_node(t
, n
, b
, next_color
, u
->radar_d
, u
, parity
);
119 fprintf(stderr
, "%s*-- UCT playout #%d start [%s] %f\n",
120 spaces
, n
->u
.playouts
, coord2sstr(n
->coord
, t
->board
),
121 tree_node_get_value(t
, n
, u
, parity
));
123 int result
= play_random_game(b
, next_color
, u
->gamelen
, u
->playout_amaf
? amaf
: NULL
, NULL
, u
->playout
);
124 if (next_color
== S_WHITE
) {
125 /* We need the result from black's perspective. */
129 fprintf(stderr
, "%s -- [%d..%d] %s random playout result %d\n",
130 spaces
, player_color
, next_color
, coord2sstr(n
->coord
, t
->board
), result
);
136 uct_playout(struct uct
*u
, struct board
*b
, enum stone player_color
, struct tree
*t
)
141 struct playout_amafmap
*amaf
= NULL
;
142 if (u
->policy
->wants_amaf
) {
143 amaf
= calloc(1, sizeof(*amaf
));
144 amaf
->map
= calloc(board_size2(&b2
) + 1, sizeof(*amaf
->map
));
145 amaf
->map
++; // -1 is pass
148 /* Walk the tree until we find a leaf, then expand it and do
149 * a random playout. */
150 struct tree_node
*n
= t
->root
;
151 enum stone node_color
= stone_other(player_color
);
152 assert(node_color
== t
->root_color
);
155 int pass_limit
= (board_size(&b2
) - 2) * (board_size(&b2
) - 2) / 2;
156 int passes
= is_pass(b
->last_move
.coord
);
160 static char spaces
[] = "\0 ";
163 fprintf(stderr
, "--- UCT walk with color %d\n", player_color
);
165 while (!tree_leaf_node(n
) && passes
< 2) {
166 spaces
[depth
++] = ' '; spaces
[depth
] = 0;
168 /* Parity is chosen already according to the child color, since
169 * it is applied to children. */
170 node_color
= stone_other(node_color
);
171 int parity
= (node_color
== player_color
? 1 : -1);
172 n
= u
->policy
->descend(u
->policy
, t
, n
, parity
, pass_limit
);
174 assert(n
== t
->root
|| n
->parent
);
176 fprintf(stderr
, "%s+-- UCT sent us to [%s:%d] %f\n",
177 spaces
, coord2sstr(n
->coord
, t
->board
), n
->coord
,
178 tree_node_get_value(t
, n
, u
, parity
));
180 assert(n
->coord
>= -1);
181 if (amaf
&& !is_pass(n
->coord
)) {
182 if (amaf
->map
[n
->coord
] == S_NONE
|| amaf
->map
[n
->coord
] == node_color
) {
183 amaf
->map
[n
->coord
] = node_color
;
184 } else { // XXX: Respect amaf->record_nakade
185 amaf_op(amaf
->map
[n
->coord
], +);
187 amaf
->game
[amaf
->gamelen
].coord
= n
->coord
;
188 amaf
->game
[amaf
->gamelen
].color
= node_color
;
190 assert(amaf
->gamelen
< sizeof(amaf
->game
) / sizeof(amaf
->game
[0]));
193 struct move m
= { n
->coord
, node_color
};
194 int res
= board_play(&b2
, &m
);
196 if (res
< 0 || (!is_pass(m
.coord
) && !group_at(&b2
, m
.coord
)) /* suicide */
197 || b2
.superko_violation
) {
199 for (struct tree_node
*ni
= n
; ni
; ni
= ni
->parent
)
200 fprintf(stderr
, "%s<%lld> ", coord2sstr(ni
->coord
, t
->board
), ni
->hash
);
201 fprintf(stderr
, "deleting invalid %s node %d,%d res %d group %d spk %d\n",
202 stone2str(node_color
), coord_x(n
->coord
,b
), coord_y(n
->coord
,b
),
203 res
, group_at(&b2
, m
.coord
), b2
.superko_violation
);
205 tree_delete_node(t
, n
);
210 if (is_pass(n
->coord
))
217 amaf
->game_baselen
= amaf
->gamelen
;
218 amaf
->record_nakade
= u
->playout_amaf_nakade
;
222 float score
= board_official_score(&b2
);
223 /* Result from black's perspective (no matter who
224 * the player; black's perspective is always
225 * what the tree stores. */
226 result
= - (score
* 2);
229 fprintf(stderr
, "[%d..%d] %s p-p scoring playout result %d (W %f)\n",
230 player_color
, node_color
, coord2sstr(n
->coord
, t
->board
), result
, score
);
232 board_print(&b2
, stderr
);
234 } else { assert(tree_leaf_node(n
));
235 if (u
->dynkomi
> b2
.moves
)
236 b2
.komi
+= get_extra_komi(u
, &b2
, player_color
);
237 result
= uct_leaf_node(u
, &b2
, player_color
, amaf
, t
, n
, node_color
, spaces
);
240 if (amaf
&& u
->playout_amaf_cutoff
) {
241 int cutoff
= amaf
->game_baselen
;
242 cutoff
+= (amaf
->gamelen
- amaf
->game_baselen
) * u
->playout_amaf_cutoff
/ 100;
243 /* Now, reconstruct the amaf map. */
244 memset(amaf
->map
, 0, board_size2(&b2
) * sizeof(*amaf
->map
));
245 for (int i
= 0; i
< cutoff
; i
++) {
246 coord_t coord
= amaf
->game
[i
].coord
;
247 enum stone color
= amaf
->game
[i
].color
;
248 if (amaf
->map
[coord
] == S_NONE
|| amaf
->map
[coord
] == color
) {
249 amaf
->map
[coord
] = color
;
250 /* Nakade always recorded for in-tree part */
251 } else if (amaf
->record_nakade
|| i
<= amaf
->game_baselen
) {
252 amaf_op(amaf
->map
[n
->coord
], +);
257 assert(n
== t
->root
|| n
->parent
);
259 float rval
= result
> 0;
261 float sval
= (float) abs(result
) / u
->val_points
;
262 sval
= sval
> 1 ? 1 : sval
;
263 if (result
< 0) sval
= 1 - sval
;
264 rval
= (1 - u
->val_scale
) * rval
+ u
->val_scale
* sval
;
265 // fprintf(stderr, "score %d => sval %f, rval %f\n", result, sval, rval);
267 u
->policy
->update(u
->policy
, t
, n
, node_color
, player_color
, amaf
, rval
);
275 board_done_noalloc(&b2
);
280 prepare_move(struct engine
*e
, struct board
*b
, enum stone color
, coord_t promote
)
282 struct uct
*u
= e
->data
;
284 if (u
->t
&& (!b
->moves
|| color
!= stone_other(u
->t
->root_color
))) {
285 /* Stale state from last game */
291 u
->t
= tree_init(b
, color
);
293 fast_srandom(u
->force_seed
);
295 fprintf(stderr
, "Fresh board with random seed %lu\n", fast_getseed());
296 //board_print(b, stderr);
297 if (!u
->no_book
&& b
->moves
< 2)
301 /* XXX: We hope that the opponent didn't suddenly play
302 * several moves in the row. */
303 if (!is_resign(promote
) && !tree_promote_at(u
->t
, b
, promote
)) {
305 fprintf(stderr
, "<cannot find node to promote>\n");
308 u
->t
= tree_init(b
, color
);
312 u
->t
->extra_komi
= get_extra_komi(u
, b
, color
);
315 /* Set in main thread in case the playouts should stop. */
316 static volatile sig_atomic_t halt
= 0;
319 uct_playouts(struct uct
*u
, struct board
*b
, enum stone color
, struct tree
*t
)
321 int i
, games
= u
->games
;
322 if (t
->root
->children
)
323 games
-= t
->root
->u
.playouts
/ 1.5;
324 /* else this is highly read-out but dead-end branch of opening book;
325 * we need to start from scratch; XXX: Maybe actually base the readout
326 * count based on number of playouts of best node? */
327 for (i
= 0; i
< games
; i
++) {
328 int result
= uct_playout(u
, b
, color
, t
);
330 /* Tree descent has hit invalid move. */
334 if (i
> 0 && !(i
% 10000)) {
335 progress_status(u
, t
, color
, i
);
338 if (i
> 0 && !(i
% 500)) {
339 struct tree_node
*best
= u
->policy
->choose(u
->policy
, t
->root
, b
, color
);
340 if (best
&& ((best
->u
.playouts
>= 5000 && tree_node_get_value(t
, best
, u
, 1) >= u
->loss_threshold
)
341 || (best
->u
.playouts
>= 500 && tree_node_get_value(t
, best
, u
, 1) >= 0.95)))
347 fprintf(stderr
, "<halting early, %d games skipped>\n", games
- i
);
352 progress_status(u
, t
, color
, i
);
354 tree_dump(t
, u
->dumpthres
);
358 static pthread_mutex_t finish_mutex
= PTHREAD_MUTEX_INITIALIZER
;
359 static pthread_cond_t finish_cond
= PTHREAD_COND_INITIALIZER
;
360 static volatile int finish_thread
;
361 static pthread_mutex_t finish_serializer
= PTHREAD_MUTEX_INITIALIZER
;
374 spawn_helper(void *ctx_
)
376 struct spawn_ctx
*ctx
= ctx_
;
378 fast_srandom(ctx
->seed
);
380 ctx
->games
= uct_playouts(ctx
->u
, ctx
->b
, ctx
->color
, ctx
->t
);
382 pthread_mutex_lock(&finish_serializer
);
383 pthread_mutex_lock(&finish_mutex
);
384 finish_thread
= ctx
->tid
;
385 pthread_cond_signal(&finish_cond
);
386 pthread_mutex_unlock(&finish_mutex
);
391 uct_notify_play(struct engine
*e
, struct board
*b
, struct move
*m
)
393 prepare_move(e
, b
, m
->color
, m
->coord
);
397 uct_genmove(struct engine
*e
, struct board
*b
, enum stone color
)
399 struct uct
*u
= e
->data
;
402 prepare_move(e
, b
, color
, resign
);
404 if (b
->superko_violation
) {
405 fprintf(stderr
, "!!! WARNING: SUPERKO VIOLATION OCCURED BEFORE THIS MOVE\n");
406 fprintf(stderr
, "Maybe you play with situational instead of positional superko?\n");
407 fprintf(stderr
, "I'm going to ignore the violation, but note that I may miss\n");
408 fprintf(stderr
, "some moves valid under this ruleset because of this.\n");
409 b
->superko_violation
= false;
412 /* If the opponent just passes and we win counting, just
414 if (b
->moves
> 1 && is_pass(b
->last_move
.coord
) && can_pass(b
, color
))
415 return coord_copy(pass
);
417 int played_games
= 0;
419 played_games
= uct_playouts(u
, b
, color
, u
->t
);
421 pthread_t threads
[u
->threads
];
424 pthread_mutex_lock(&finish_mutex
);
425 /* Spawn threads... */
426 for (int ti
= 0; ti
< u
->threads
; ti
++) {
427 struct spawn_ctx
*ctx
= malloc(sizeof(*ctx
));
428 ctx
->u
= u
; ctx
->b
= b
; ctx
->color
= color
;
429 ctx
->t
= tree_copy(u
->t
); ctx
->tid
= ti
;
430 ctx
->seed
= fast_random(65536) + ti
;
431 pthread_create(&threads
[ti
], NULL
, spawn_helper
, ctx
);
433 fprintf(stderr
, "Spawned thread %d\n", ti
);
435 /* ...and collect them back: */
436 while (joined
< u
->threads
) {
437 /* Wait for some thread to finish... */
438 pthread_cond_wait(&finish_cond
, &finish_mutex
);
439 /* ...and gather its remnants. */
440 struct spawn_ctx
*ctx
;
441 pthread_join(threads
[finish_thread
], (void **) &ctx
);
442 played_games
+= ctx
->games
;
444 tree_merge(u
->t
, ctx
->t
);
448 fprintf(stderr
, "Joined thread %d\n", finish_thread
);
449 /* Do not get stalled by slow threads. */
450 if (joined
>= u
->threads
/ 2)
452 pthread_mutex_unlock(&finish_serializer
);
454 pthread_mutex_unlock(&finish_mutex
);
456 tree_normalize(u
->t
, u
->threads
);
460 tree_dump(u
->t
, u
->dumpthres
);
462 struct tree_node
*best
= u
->policy
->choose(u
->policy
, u
->t
->root
, b
, color
);
464 tree_done(u
->t
); u
->t
= NULL
;
465 return coord_copy(pass
);
468 progress_status(u
, u
->t
, color
, played_games
);
470 fprintf(stderr
, "*** WINNER is %s (%d,%d) with score %1.4f (%d/%d:%d games)\n",
471 coord2sstr(best
->coord
, b
), coord_x(best
->coord
, b
), coord_y(best
->coord
, b
),
472 tree_node_get_value(u
->t
, best
, u
, 1),
473 best
->u
.playouts
, u
->t
->root
->u
.playouts
, played_games
);
474 if (tree_node_get_value(u
->t
, best
, u
, 1) < u
->resign_ratio
&& !is_pass(best
->coord
)) {
475 tree_done(u
->t
); u
->t
= NULL
;
476 return coord_copy(resign
);
478 tree_promote_node(u
->t
, best
);
479 return coord_copy(best
->coord
);
483 uct_genbook(struct engine
*e
, struct board
*b
, enum stone color
)
485 struct uct
*u
= e
->data
;
486 u
->t
= tree_init(b
, color
);
490 for (i
= 0; i
< u
->games
; i
++) {
491 int result
= uct_playout(u
, b
, color
, u
->t
);
493 /* Tree descent has hit invalid move. */
497 if (i
> 0 && !(i
% 10000)) {
498 progress_status(u
, u
->t
, color
, i
);
501 progress_status(u
, u
->t
, color
, i
);
503 tree_save(u
->t
, b
, u
->games
/ 100);
511 uct_dumpbook(struct engine
*e
, struct board
*b
, enum stone color
)
513 struct uct
*u
= e
->data
;
514 u
->t
= tree_init(b
, color
);
522 uct_state_init(char *arg
)
524 struct uct
*u
= calloc(1, sizeof(struct uct
));
528 u
->gamelen
= MC_GAMELEN
;
531 u
->playout_amaf
= true;
532 u
->playout_amaf_nakade
= false;
533 u
->amaf_prior
= true;
536 char *optspec
, *next
= arg
;
539 next
+= strcspn(next
, ",");
540 if (*next
) { *next
++ = 0; } else { *next
= 0; }
542 char *optname
= optspec
;
543 char *optval
= strchr(optspec
, '=');
544 if (optval
) *optval
++ = 0;
546 if (!strcasecmp(optname
, "debug")) {
548 u
->debug_level
= atoi(optval
);
551 } else if (!strcasecmp(optname
, "games") && optval
) {
552 u
->games
= atoi(optval
);
553 } else if (!strcasecmp(optname
, "gamelen") && optval
) {
554 u
->gamelen
= atoi(optval
);
555 } else if (!strcasecmp(optname
, "expand_p") && optval
) {
556 u
->expand_p
= atoi(optval
);
557 } else if (!strcasecmp(optname
, "radar_d") && optval
) {
558 /* For 19x19, it is good idea to set this to 3. */
559 u
->radar_d
= atoi(optval
);
560 } else if (!strcasecmp(optname
, "dumpthres") && optval
) {
561 u
->dumpthres
= atoi(optval
);
562 } else if (!strcasecmp(optname
, "playout_amaf")) {
563 /* Whether to include random playout moves in
564 * AMAF as well. (Otherwise, only tree moves
565 * are included in AMAF. Of course makes sense
566 * only in connection with an AMAF policy.) */
567 /* with-without: 55.5% (+-4.1) */
568 if (optval
&& *optval
== '0')
569 u
->playout_amaf
= false;
571 u
->playout_amaf
= true;
572 } else if (!strcasecmp(optname
, "playout_amaf_nakade")) {
573 /* Whether to include nakade moves from playouts
574 * in the AMAF statistics; this tends to nullify
575 * the playout_amaf effect by adding too much
577 if (optval
&& *optval
== '0')
578 u
->playout_amaf_nakade
= false;
580 u
->playout_amaf_nakade
= true;
581 } else if (!strcasecmp(optname
, "playout_amaf_cutoff") && optval
) {
582 /* Keep only first N% of playout stage AMAF
584 u
->playout_amaf_cutoff
= atoi(optval
);
585 } else if (!strcasecmp(optname
, "policy") && optval
) {
586 char *policyarg
= strchr(optval
, ':');
589 if (!strcasecmp(optval
, "ucb1")) {
590 u
->policy
= policy_ucb1_init(u
, policyarg
);
591 } else if (!strcasecmp(optval
, "ucb1amaf")) {
592 u
->policy
= policy_ucb1amaf_init(u
, policyarg
);
594 fprintf(stderr
, "UCT: Invalid tree policy %s\n", optval
);
596 } else if (!strcasecmp(optname
, "playout") && optval
) {
597 char *playoutarg
= strchr(optval
, ':');
600 if (!strcasecmp(optval
, "moggy")) {
601 u
->playout
= playout_moggy_init(playoutarg
);
602 } else if (!strcasecmp(optval
, "light")) {
603 u
->playout
= playout_light_init(playoutarg
);
605 fprintf(stderr
, "UCT: Invalid playout policy %s\n", optval
);
607 } else if (!strcasecmp(optname
, "prior") && optval
) {
608 u
->prior
= uct_prior_init(optval
);
609 } else if (!strcasecmp(optname
, "amaf_prior") && optval
) {
610 u
->amaf_prior
= atoi(optval
);
611 } else if (!strcasecmp(optname
, "threads") && optval
) {
612 u
->threads
= atoi(optval
);
613 } else if (!strcasecmp(optname
, "force_seed") && optval
) {
614 u
->force_seed
= atoi(optval
);
615 } else if (!strcasecmp(optname
, "no_book")) {
617 } else if (!strcasecmp(optname
, "dynkomi")) {
618 /* Dynamic komi in handicap game; linearly
619 * decreases to basic settings until move
621 u
->dynkomi
= optval
? atoi(optval
) : 150;
622 } else if (!strcasecmp(optname
, "val_scale") && optval
) {
623 /* How much of the game result value should be
624 * influenced by win size. */
625 u
->val_scale
= atof(optval
);
626 } else if (!strcasecmp(optname
, "val_points") && optval
) {
627 /* Maximum size of win to be scaled into game
629 u
->val_points
= atoi(optval
) * 2; // result values are doubled
631 fprintf(stderr
, "uct: Invalid engine argument %s or missing value\n", optname
);
637 u
->resign_ratio
= 0.2; /* Resign when most games are lost. */
638 u
->loss_threshold
= 0.85; /* Stop reading if after at least 5000 playouts this is best value. */
640 u
->policy
= policy_ucb1amaf_init(u
, NULL
);
643 u
->prior
= uct_prior_init(NULL
);
646 u
->playout
= playout_moggy_init(NULL
);
647 u
->playout
->debug_level
= u
->debug_level
;
654 engine_uct_init(char *arg
)
656 struct uct
*u
= uct_state_init(arg
);
657 struct engine
*e
= calloc(1, sizeof(struct engine
));
658 e
->name
= "UCT Engine";
659 e
->comment
= "I'm playing UCT. When we both pass, I will consider all the stones on the board alive. If you are reading this, write 'yes'. Please capture all dead stones before passing; it will not cost you points (area scoring is used).";
660 e
->genmove
= uct_genmove
;
661 e
->notify_play
= uct_notify_play
;