UCT: Fix scoring after pass-pass in tree
[pachi.git] / uct / uct.c
blob12be290e7785b9773d976b863fc313280ac1d09c
1 #include <assert.h>
2 #include <pthread.h>
3 #include <signal.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
8 #define DEBUG
10 #include "debug.h"
11 #include "board.h"
12 #include "move.h"
13 #include "playout.h"
14 #include "playout/moggy.h"
15 #include "playout/light.h"
16 #include "random.h"
17 #include "tactics.h"
18 #include "uct/internal.h"
19 #include "uct/prior.h"
20 #include "uct/tree.h"
21 #include "uct/uct.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
31 static bool
32 can_pass(struct board *b, enum stone color)
34 float score = board_official_score(b);
35 if (color == S_BLACK)
36 score = -score;
37 //fprintf(stderr, "%d score %f\n", color, score);
38 return (score > 0);
41 static float
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)
46 extra_komi *= -1;
47 return extra_komi;
50 static void
51 progress_status(struct uct *u, struct tree *t, enum stone color, int playouts)
53 if (!UDEBUGL(0))
54 return;
56 /* Best move */
57 struct tree_node *best = u->policy->choose(u->policy, t->root, t->board, color);
58 if (!best) {
59 fprintf(stderr, "... No moves left\n");
60 return;
62 fprintf(stderr, "[%d] ", playouts);
63 fprintf(stderr, "best %f ", tree_node_get_value(t, best, u, 1));
65 /* Max depth */
66 fprintf(stderr, "deepest % 2d ", t->max_depth - t->root->depth);
68 /* Best sequence */
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);
74 } else {
75 fprintf(stderr, " ");
79 /* Best candidates */
80 fprintf(stderr, "| can ");
81 int cans = 4;
82 struct tree_node *can[cans];
83 memset(can, 0, sizeof(can));
84 best = t->root->children;
85 while (best) {
86 int c = 0;
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;
90 best = best->sibling;
92 while (--cans >= 0) {
93 if (can[cans]) {
94 fprintf(stderr, "%3s(%.3f) ",
95 coord2sstr(can[cans]->coord, t->board),
96 tree_node_get_value(t, can[cans], u, 1));
97 } else {
98 fprintf(stderr, " ");
102 fprintf(stderr, "\n");
106 static int
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,
110 char *spaces)
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);
118 if (UDEBUGL(7))
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. */
126 result = - result;
128 if (UDEBUGL(7))
129 fprintf(stderr, "%s -- [%d..%d] %s random playout result %d\n",
130 spaces, player_color, next_color, coord2sstr(n->coord, t->board), result);
132 return result;
135 static int
136 uct_playout(struct uct *u, struct board *b, enum stone player_color, struct tree *t)
138 struct board b2;
139 board_copy(&b2, b);
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);
154 int result;
155 int pass_limit = (board_size(&b2) - 2) * (board_size(&b2) - 2) / 2;
156 int passes = is_pass(b->last_move.coord);
158 /* debug */
159 int depth = 0;
160 static char spaces[] = "\0 ";
161 /* /debug */
162 if (UDEBUGL(8))
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);
175 if (UDEBUGL(7))
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;
189 amaf->gamelen++;
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) {
198 if (UDEBUGL(3)) {
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);
206 result = 0;
207 goto end;
210 if (is_pass(n->coord))
211 passes++;
212 else
213 passes = 0;
216 if (amaf) {
217 amaf->game_baselen = amaf->gamelen;
218 amaf->record_nakade = u->playout_amaf_nakade;
221 if (passes >= 2) {
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);
228 if (UDEBUGL(5))
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);
231 if (UDEBUGL(6))
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);
258 if (result != 0) {
259 float rval = result > 0;
260 if (u->val_scale) {
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);
270 end:
271 if (amaf) {
272 free(amaf->map - 1);
273 free(amaf);
275 board_done_noalloc(&b2);
276 return result;
279 static void
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 */
286 tree_done(u->t);
287 u->t = NULL;
290 if (!u->t) {
291 u->t = tree_init(b, color);
292 if (u->force_seed)
293 fast_srandom(u->force_seed);
294 if (UDEBUGL(0))
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)
298 tree_load(u->t, b);
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)) {
304 if (UDEBUGL(2))
305 fprintf(stderr, "<cannot find node to promote>\n");
306 /* Reset tree */
307 tree_done(u->t);
308 u->t = tree_init(b, color);
311 if (u->dynkomi)
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;
318 static int
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);
329 if (result == 0) {
330 /* Tree descent has hit invalid move. */
331 continue;
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)))
342 break;
345 if (halt) {
346 if (UDEBUGL(2))
347 fprintf(stderr, "<halting early, %d games skipped>\n", games - i);
348 break;
352 progress_status(u, t, color, i);
353 if (UDEBUGL(3))
354 tree_dump(t, u->dumpthres);
355 return i;
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;
363 struct spawn_ctx {
364 int tid;
365 struct uct *u;
366 struct board *b;
367 enum stone color;
368 struct tree *t;
369 unsigned long seed;
370 int games;
373 static void *
374 spawn_helper(void *ctx_)
376 struct spawn_ctx *ctx = ctx_;
377 /* Setup */
378 fast_srandom(ctx->seed);
379 /* Run */
380 ctx->games = uct_playouts(ctx->u, ctx->b, ctx->color, ctx->t);
381 /* Finish */
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);
387 return ctx;
390 static void
391 uct_notify_play(struct engine *e, struct board *b, struct move *m)
393 prepare_move(e, b, m->color, m->coord);
396 static coord_t *
397 uct_genmove(struct engine *e, struct board *b, enum stone color)
399 struct uct *u = e->data;
401 /* Seed the tree. */
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
413 * pass as well. */
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;
418 if (!u->threads) {
419 played_games = uct_playouts(u, b, color, u->t);
420 } else {
421 pthread_t threads[u->threads];
422 int joined = 0;
423 halt = 0;
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);
432 if (UDEBUGL(2))
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;
443 joined++;
444 tree_merge(u->t, ctx->t);
445 tree_done(ctx->t);
446 free(ctx);
447 if (UDEBUGL(2))
448 fprintf(stderr, "Joined thread %d\n", finish_thread);
449 /* Do not get stalled by slow threads. */
450 if (joined >= u->threads / 2)
451 halt = 1;
452 pthread_mutex_unlock(&finish_serializer);
454 pthread_mutex_unlock(&finish_mutex);
456 tree_normalize(u->t, u->threads);
459 if (UDEBUGL(2))
460 tree_dump(u->t, u->dumpthres);
462 struct tree_node *best = u->policy->choose(u->policy, u->t->root, b, color);
463 if (!best) {
464 tree_done(u->t); u->t = NULL;
465 return coord_copy(pass);
467 if (UDEBUGL(0))
468 progress_status(u, u->t, color, played_games);
469 if (UDEBUGL(1))
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);
482 bool
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);
487 tree_load(u->t, b);
489 int i;
490 for (i = 0; i < u->games; i++) {
491 int result = uct_playout(u, b, color, u->t);
492 if (result == 0) {
493 /* Tree descent has hit invalid move. */
494 continue;
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);
505 tree_done(u->t);
507 return true;
510 void
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);
515 tree_load(u->t, b);
516 tree_dump(u->t, 0);
517 tree_done(u->t);
521 struct uct *
522 uct_state_init(char *arg)
524 struct uct *u = calloc(1, sizeof(struct uct));
526 u->debug_level = 1;
527 u->games = MC_GAMES;
528 u->gamelen = MC_GAMELEN;
529 u->expand_p = 2;
530 u->dumpthres = 1000;
531 u->playout_amaf = true;
532 u->playout_amaf_nakade = false;
533 u->amaf_prior = true;
535 if (arg) {
536 char *optspec, *next = arg;
537 while (*next) {
538 optspec = next;
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")) {
547 if (optval)
548 u->debug_level = atoi(optval);
549 else
550 u->debug_level++;
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;
570 else
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
576 * noise. */
577 if (optval && *optval == '0')
578 u->playout_amaf_nakade = false;
579 else
580 u->playout_amaf_nakade = true;
581 } else if (!strcasecmp(optname, "playout_amaf_cutoff") && optval) {
582 /* Keep only first N% of playout stage AMAF
583 * information. */
584 u->playout_amaf_cutoff = atoi(optval);
585 } else if (!strcasecmp(optname, "policy") && optval) {
586 char *policyarg = strchr(optval, ':');
587 if (policyarg)
588 *policyarg++ = 0;
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);
593 } else {
594 fprintf(stderr, "UCT: Invalid tree policy %s\n", optval);
596 } else if (!strcasecmp(optname, "playout") && optval) {
597 char *playoutarg = strchr(optval, ':');
598 if (playoutarg)
599 *playoutarg++ = 0;
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);
604 } else {
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")) {
616 u->no_book = true;
617 } else if (!strcasecmp(optname, "dynkomi")) {
618 /* Dynamic komi in handicap game; linearly
619 * decreases to basic settings until move
620 * #optval. */
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
628 * result value. */
629 u->val_points = atoi(optval) * 2; // result values are doubled
630 } else {
631 fprintf(stderr, "uct: Invalid engine argument %s or missing value\n", optname);
632 exit(1);
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. */
639 if (!u->policy)
640 u->policy = policy_ucb1amaf_init(u, NULL);
642 if (!u->prior)
643 u->prior = uct_prior_init(NULL);
645 if (!u->playout)
646 u->playout = playout_moggy_init(NULL);
647 u->playout->debug_level = u->debug_level;
649 return u;
653 struct engine *
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;
662 e->data = u;
664 return e;