UCT treepool_setup(): Fix finding best move
[pachi/ann.git] / uct / walk.c
blob648717bfe53b8c5a175925777f50bf676e027965
1 #include <assert.h>
2 #include <math.h>
3 #include <pthread.h>
4 #include <signal.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
9 #define DEBUG
11 #include "debug.h"
12 #include "board.h"
13 #include "move.h"
14 #include "playout.h"
15 #include "playout/elo.h"
16 #include "probdist.h"
17 #include "random.h"
18 #include "uct/dynkomi.h"
19 #include "uct/internal.h"
20 #include "uct/search.h"
21 #include "uct/tree.h"
22 #include "uct/uct.h"
23 #include "uct/walk.h"
25 void
26 uct_progress_status(struct uct *u, struct tree *t, enum stone color, int playouts)
28 if (!UDEBUGL(0))
29 return;
31 /* Best move */
32 struct tree_node *best = u->policy->choose(u->policy, t->root, t->board, color, resign);
33 if (!best) {
34 fprintf(stderr, "... No moves left\n");
35 return;
37 fprintf(stderr, "[%d] ", playouts);
38 fprintf(stderr, "best %f ", tree_node_get_value(t, 1, best->u.value));
40 /* Dynamic komi */
41 if (t->use_extra_komi)
42 fprintf(stderr, "komi %.1f ", t->extra_komi);
44 /* Best sequence */
45 fprintf(stderr, "| seq ");
46 for (int depth = 0; depth < 4; depth++) {
47 if (best && best->u.playouts >= 25) {
48 fprintf(stderr, "%3s ", coord2sstr(best->coord, t->board));
49 best = u->policy->choose(u->policy, best, t->board, color, resign);
50 } else {
51 fprintf(stderr, " ");
55 /* Best candidates */
56 fprintf(stderr, "| can ");
57 int cans = 4;
58 struct tree_node *can[cans];
59 memset(can, 0, sizeof(can));
60 best = t->root->children;
61 while (best) {
62 int c = 0;
63 while ((!can[c] || best->u.playouts > can[c]->u.playouts) && ++c < cans);
64 for (int d = 0; d < c; d++) can[d] = can[d + 1];
65 if (c > 0) can[c - 1] = best;
66 best = best->sibling;
68 while (--cans >= 0) {
69 if (can[cans]) {
70 fprintf(stderr, "%3s(%.3f) ",
71 coord2sstr(can[cans]->coord, t->board),
72 tree_node_get_value(t, 1, can[cans]->u.value));
73 } else {
74 fprintf(stderr, " ");
78 fprintf(stderr, "\n");
82 static void
83 record_amaf_move(struct playout_amafmap *amaf, coord_t coord, enum stone color)
85 if (amaf->map[coord] == S_NONE || amaf->map[coord] == color) {
86 amaf->map[coord] = color;
87 } else { // XXX: Respect amaf->record_nakade
88 amaf_op(amaf->map[coord], +);
90 amaf->game[amaf->gamelen].coord = coord;
91 amaf->game[amaf->gamelen].color = color;
92 amaf->gamelen++;
93 assert(amaf->gamelen < sizeof(amaf->game) / sizeof(amaf->game[0]));
96 static double
97 ltree_node_gamma(struct tree_node *li, enum stone color)
99 /* TODO: How to do this? */
100 #define li_value(color, li) (li->u.playouts * (color == S_BLACK ? li->u.value : (1 - li->u.value)))
101 return 0.5 + li_value(color, li);
105 struct uct_playout_callback {
106 struct uct *uct;
107 struct tree *tree;
108 struct tree_node *lnode;
110 coord_t *treepool[2];
111 int treepool_n[2];
114 static void
115 uct_playout_probdist(void *data, struct board *b, enum stone to_play, struct probdist *pd)
117 /* Create probability distribution according to found local tree
118 * sequence. */
119 struct uct_playout_callback *upc = data;
120 assert(upc && upc->tree && pd && b);
121 coord_t c = b->last_move.coord;
122 enum stone color = b->last_move.color;
124 if (is_pass(c)) {
125 /* Break local sequence. */
126 upc->lnode = NULL;
127 } else if (upc->lnode) {
128 /* Try to follow local sequence. */
129 upc->lnode = tree_get_node(upc->tree, upc->lnode, c, false);
132 if (!upc->lnode || !upc->lnode->children) {
133 /* There's no local sequence, start new one! */
134 upc->lnode = color == S_BLACK ? upc->tree->ltree_black : upc->tree->ltree_white;
135 upc->lnode = tree_get_node(upc->tree, upc->lnode, c, false);
138 if (!upc->lnode || !upc->lnode->children) {
139 /* We have no local sequence and we cannot find any starting
140 * by node corresponding to last move. */
141 if (!upc->uct->local_tree_pseqroot) {
142 /* Give up then, we have nothing to contribute. */
143 return;
145 /* Construct probability distribution from possible first
146 * sequence move. Remember that @color is color of the
147 * *last* move. */
148 upc->lnode = color == S_BLACK ? upc->tree->ltree_white : upc->tree->ltree_black;
149 if (!upc->lnode->children) {
150 /* We don't even have anything in our tree yet. */
151 return;
155 /* The probdist has the right structure only if BOARD_GAMMA is defined. */
156 #ifndef BOARD_GAMMA
157 assert(0);
158 #endif
160 /* Construct probability distribution from lnode children. */
161 struct tree_node *li = upc->lnode->children;
162 assert(li);
163 if (is_pass(li->coord)) {
164 /* Tenuki. */
165 /* TODO: Spread tenuki gamma over all moves we don't touch. */
166 li = li->sibling;
168 for (; li; li = li->sibling) {
169 if (board_at(b, li->coord) != S_NONE)
170 continue;
171 double gamma = fixp_to_double(pd->items[li->coord]) * ltree_node_gamma(li, to_play);
172 probdist_set(pd, li->coord, double_to_fixp(gamma));
177 static coord_t
178 uct_playout_hook(struct playout_policy *playout, struct playout_setup *setup, struct board *b, enum stone color, int mode)
180 struct uct_playout_callback *upc = setup->hook_data;
181 struct uct *u = upc->uct;
183 if (UDEBUGL(8))
184 fprintf(stderr, "treepool check [%d] %d, %p,%p\n", mode, u->treepool_chance[mode], upc->treepool[0], upc->treepool[1]);
185 if (u->treepool_chance[mode] > fast_random(100) && upc->treepool[color - 1]) {
186 assert(upc->treepool_n[color - 1] > 0);
187 coord_t treepool_move = upc->treepool[color - 1][fast_random(upc->treepool_n[color - 1])];
188 if (UDEBUGL(8)) {
189 fprintf(stderr, "Treepool: ");
190 for (int i = 0; i < upc->treepool_n[color - 1]; i++)
191 fprintf(stderr, "%s ", coord2sstr(upc->treepool[color - 1][i], b));
192 fprintf(stderr, "\n");
194 if (UDEBUGL(7))
195 fprintf(stderr, "Treepool pick <%d> %s,%s\n", upc->treepool_n[color - 1], stone2str(color), coord2sstr(treepool_move, b));
196 if (board_is_valid_play(b, color, treepool_move))
197 return treepool_move;
199 return pass;
202 static coord_t
203 uct_playout_prepolicy(struct playout_policy *playout, struct playout_setup *setup, struct board *b, enum stone color)
205 return uct_playout_hook(playout, setup, b, color, 0);
208 static coord_t
209 uct_playout_postpolicy(struct playout_policy *playout, struct playout_setup *setup, struct board *b, enum stone color)
211 return uct_playout_hook(playout, setup, b, color, 1);
214 double
215 treepool_node_value(struct uct *u, struct tree *tree, int parity, struct tree_node *node)
217 /* XXX: Playouts get cast to double */
218 switch (u->treepool_type) {
219 case UTT_RAVE_PLAYOUTS:
220 return node->amaf.playouts;
221 case UTT_RAVE_VALUE:
222 return tree_node_get_value(tree, parity, node->amaf.value);
223 case UTT_UCT_PLAYOUTS:
224 return node->u.playouts;
225 case UTT_UCT_VALUE:
226 return tree_node_get_value(tree, parity, node->u.value);
227 case UTT_EVALUATE:
229 struct uct_descent d = { .node = node };
230 assert(u->policy->evaluate);
231 return u->policy->evaluate(u->policy, tree, &d, parity);
233 default: assert(0);
235 return -1;
238 static void
239 treepool_setup(struct uct_playout_callback *upc, struct board *b, struct tree_node *node, int color)
241 struct uct *u = upc->uct;
242 int parity = ((node->depth ^ upc->tree->root->depth) & 1) ? -1 : 1;
244 /* XXX: Naive O(N^2) way. */
245 for (int i = 0; i < u->treepool_size; i++) {
246 /* For each item, find the highest
247 * node not in the pool yet. */
248 struct tree_node *best = NULL;
249 double best_val = -1;
251 assert(node->children && is_pass(node->children->coord));
252 for (struct tree_node *ni = node->children->sibling; ni; ni = ni->sibling) {
253 /* Do we already have it? */
254 bool have = false;
255 for (int j = 0; j < upc->treepool_n[color]; j++) {
256 if (upc->treepool[color][j] == ni->coord) {
257 have = true;
258 break;
261 if (have)
262 continue;
264 double i_val = treepool_node_value(u, upc->tree, parity, ni);
265 if (i_val > best_val) {
266 best = ni;
267 best_val = i_val;
271 if (!best) break;
272 upc->treepool[color][upc->treepool_n[color]++] = best->coord;
277 static int
278 uct_leaf_node(struct uct *u, struct board *b, enum stone player_color,
279 struct playout_amafmap *amaf, struct uct_descent *descent,
280 struct tree *t, struct tree_node *n, enum stone node_color,
281 char *spaces)
283 enum stone next_color = stone_other(node_color);
284 int parity = (next_color == player_color ? 1 : -1);
286 /* We need to make sure only one thread expands the node. If
287 * we are unlucky enough for two threads to meet in the same
288 * node, the latter one will simply do another simulation from
289 * the node itself, no big deal. t->nodes_size may exceed
290 * the maximum in multi-threaded case but not by much so it's ok.
291 * The size test must be before the test&set not after, to allow
292 * expansion of the node later if enough nodes have been freed. */
293 if (n->u.playouts >= u->expand_p && t->nodes_size < u->max_tree_size
294 && !__sync_lock_test_and_set(&n->is_expanded, 1)) {
295 tree_expand_node(t, n, b, next_color, u, parity);
297 if (UDEBUGL(7))
298 fprintf(stderr, "%s*-- UCT playout #%d start [%s] %f\n",
299 spaces, n->u.playouts, coord2sstr(n->coord, t->board),
300 tree_node_get_value(t, parity, n->u.value));
302 struct uct_playout_callback upc = {
303 .uct = u,
304 .tree = t,
305 /* TODO: Don't necessarily restart the sequence walk when
306 * entering playout. */
307 .lnode = NULL,
310 if (u->local_tree_playout) {
311 /* N.B.: We know this is ELO playout. */
312 playout_elo_callback(u->playout, uct_playout_probdist, &upc);
315 coord_t pool[2][u->treepool_size];
316 if (u->treepool_chance[0] + u->treepool_chance[1] > 0) {
317 for (int color = 0; color < 2; color++) {
318 /* Prepare tree-based pool of moves to try forcing
319 * during the playout. */
320 /* We consider the children of the last significant
321 * node, picking top N choices. */
322 struct tree_node *n = descent->significant[color];
323 if (!n || !n->children || !n->children->sibling) {
324 /* No significant node, or it's childless or has
325 * only pass as its child. */
326 upc.treepool[color] = NULL;
327 upc.treepool_n[color] = 0;
328 } else {
329 upc.treepool[color] = (coord_t *) &pool[color];
330 treepool_setup(&upc, b, n, color);
335 struct playout_setup ps = {
336 .gamelen = u->gamelen,
337 .mercymin = u->mercymin,
338 .prepolicy_hook = uct_playout_prepolicy,
339 .postpolicy_hook = uct_playout_postpolicy,
340 .hook_data = &upc,
342 int result = play_random_game(&ps, b, next_color,
343 u->playout_amaf ? amaf : NULL,
344 &u->ownermap, u->playout);
345 if (next_color == S_WHITE) {
346 /* We need the result from black's perspective. */
347 result = - result;
349 if (UDEBUGL(7))
350 fprintf(stderr, "%s -- [%d..%d] %s random playout result %d\n",
351 spaces, player_color, next_color, coord2sstr(n->coord, t->board), result);
353 return result;
356 static float
357 scale_value(struct uct *u, struct board *b, int result)
359 float rval = result > 0;
360 if (u->val_scale) {
361 int vp = u->val_points;
362 if (!vp) {
363 vp = board_size(b) - 1; vp *= vp; vp *= 2;
366 float sval = (float) abs(result) / vp;
367 sval = sval > 1 ? 1 : sval;
368 if (result < 0) sval = 1 - sval;
369 if (u->val_extra)
370 rval += u->val_scale * sval;
371 else
372 rval = (1 - u->val_scale) * rval + u->val_scale * sval;
373 // fprintf(stderr, "score %d => sval %f, rval %f\n", result, sval, rval);
375 return rval;
378 static void
379 record_local_sequence(struct uct *u, struct tree *t,
380 struct uct_descent *descent, int dlen, int di,
381 enum stone seq_color, float rval)
383 /* Ignore pass sequences. */
384 if (is_pass(descent[di].node->coord))
385 return;
387 #define LTREE_DEBUG if (UDEBUGL(6))
388 LTREE_DEBUG fprintf(stderr, "recording result %f in local %s sequence: ",
389 rval, stone2str(seq_color));
390 int di0 = di;
392 /* Pick the right local tree root... */
393 struct tree_node *lnode = seq_color == S_BLACK ? t->ltree_black : t->ltree_white;
394 lnode->u.playouts++;
396 /* ...and record the sequence. */
397 while (di < dlen && (di == di0 || descent[di].node->d < u->tenuki_d)) {
398 LTREE_DEBUG fprintf(stderr, "%s[%d] ",
399 coord2sstr(descent[di].node->coord, t->board),
400 descent[di].node->d);
401 lnode = tree_get_node(t, lnode, descent[di++].node->coord, true);
402 assert(lnode);
403 stats_add_result(&lnode->u, rval, 1);
406 /* Add lnode for tenuki (pass) if we descended further. */
407 if (di < dlen) {
408 LTREE_DEBUG fprintf(stderr, "pass ");
409 lnode = tree_get_node(t, lnode, pass, true);
410 assert(lnode);
411 stats_add_result(&lnode->u, rval, 1);
414 LTREE_DEBUG fprintf(stderr, "\n");
419 uct_playout(struct uct *u, struct board *b, enum stone player_color, struct tree *t)
421 struct board b2;
422 board_copy(&b2, b);
424 struct playout_amafmap *amaf = NULL;
425 if (u->policy->wants_amaf) {
426 amaf = calloc2(1, sizeof(*amaf));
427 amaf->map = calloc2(board_size2(&b2) + 1, sizeof(*amaf->map));
428 amaf->map++; // -1 is pass
431 /* Walk the tree until we find a leaf, then expand it and do
432 * a random playout. */
433 struct tree_node *n = t->root;
434 enum stone node_color = stone_other(player_color);
435 assert(node_color == t->root_color);
437 /* Tree descent history. */
438 /* XXX: This is somewhat messy since @n and descent[dlen-1].node are
439 * redundant. */
440 #define DLEN 512
441 struct uct_descent descent[DLEN];
442 descent[0].node = n; descent[0].lnode = NULL;
443 descent[0].significant[0] = descent[0].significant[1] = NULL;
444 int dlen = 1;
445 /* Total value of the sequence. */
446 struct move_stats seq_value = { .playouts = 0 };
448 int result;
449 int pass_limit = (board_size(&b2) - 2) * (board_size(&b2) - 2) / 2;
450 int passes = is_pass(b->last_move.coord) && b->moves > 0;
452 /* debug */
453 int depth = 0;
454 static char spaces[] = "\0 ";
455 /* /debug */
456 if (UDEBUGL(8))
457 fprintf(stderr, "--- UCT walk with color %d\n", player_color);
459 while (!tree_leaf_node(n) && passes < 2) {
460 spaces[depth++] = ' '; spaces[depth] = 0;
463 /*** Choose a node to descend to: */
465 /* Parity is chosen already according to the child color, since
466 * it is applied to children. */
467 node_color = stone_other(node_color);
468 int parity = (node_color == player_color ? 1 : -1);
470 assert(dlen < DLEN);
471 descent[dlen] = descent[dlen - 1];
472 if (u->local_tree && (!descent[dlen].lnode || descent[dlen].node->d >= u->tenuki_d)) {
473 /* Start new local sequence. */
474 /* Remember that node_color already holds color of the
475 * to-be-found child. */
476 descent[dlen].lnode = node_color == S_BLACK ? t->ltree_black : t->ltree_white;
479 if (!u->random_policy_chance || fast_random(u->random_policy_chance))
480 u->policy->descend(u->policy, t, &descent[dlen], parity, b2.moves > pass_limit);
481 else
482 u->random_policy->descend(u->random_policy, t, &descent[dlen], parity, b2.moves > pass_limit);
485 /*** Perform the descent: */
487 if (descent[dlen].node->u.playouts >= u->significant_threshold) {
488 descent[dlen].significant[node_color - 1] = n;
491 seq_value.playouts += descent[dlen].value.playouts;
492 seq_value.value += descent[dlen].value.value * descent[dlen].value.playouts;
493 n = descent[dlen++].node;
494 assert(n == t->root || n->parent);
495 if (UDEBUGL(7))
496 fprintf(stderr, "%s+-- UCT sent us to [%s:%d] %d,%f\n",
497 spaces, coord2sstr(n->coord, t->board),
498 n->coord, n->u.playouts,
499 tree_node_get_value(t, parity, n->u.value));
501 /* Add virtual loss if we need to; this is used to discourage
502 * other threads from visiting this node in case of multiple
503 * threads doing the tree search. */
504 if (u->virtual_loss)
505 stats_add_result(&n->u, tree_parity(t, parity) > 0 ? 0 : 1, 1);
507 assert(n->coord >= -1);
508 if (amaf && !is_pass(n->coord))
509 record_amaf_move(amaf, n->coord, node_color);
511 struct move m = { n->coord, node_color };
512 int res = board_play(&b2, &m);
514 if (res < 0 || (!is_pass(m.coord) && !group_at(&b2, m.coord)) /* suicide */
515 || b2.superko_violation) {
516 if (UDEBUGL(4)) {
517 for (struct tree_node *ni = n; ni; ni = ni->parent)
518 fprintf(stderr, "%s<%"PRIhash"> ", coord2sstr(ni->coord, t->board), ni->hash);
519 fprintf(stderr, "marking invalid %s node %d,%d res %d group %d spk %d\n",
520 stone2str(node_color), coord_x(n->coord,b), coord_y(n->coord,b),
521 res, group_at(&b2, m.coord), b2.superko_violation);
523 n->hints |= TREE_HINT_INVALID;
524 result = 0;
525 goto end;
528 if (is_pass(n->coord))
529 passes++;
530 else
531 passes = 0;
534 if (amaf) {
535 amaf->game_baselen = amaf->gamelen;
536 amaf->record_nakade = u->playout_amaf_nakade;
539 if (t->use_extra_komi && u->dynkomi->persim) {
540 b2.komi += round(u->dynkomi->persim(u->dynkomi, &b2, t, n));
543 if (passes >= 2) {
544 /* XXX: No dead groups support. */
545 float score = board_official_score(&b2, NULL);
546 /* Result from black's perspective (no matter who
547 * the player; black's perspective is always
548 * what the tree stores. */
549 result = - (score * 2);
551 if (UDEBUGL(5))
552 fprintf(stderr, "[%d..%d] %s p-p scoring playout result %d (W %f)\n",
553 player_color, node_color, coord2sstr(n->coord, t->board), result, score);
554 if (UDEBUGL(6))
555 board_print(&b2, stderr);
557 board_ownermap_fill(&u->ownermap, &b2);
559 } else { // assert(tree_leaf_node(n));
560 /* In case of parallel tree search, the assertion might
561 * not hold if two threads chew on the same node. */
562 result = uct_leaf_node(u, &b2, player_color, amaf, &descent[dlen - 1], t, n, node_color, spaces);
565 if (amaf && u->playout_amaf_cutoff) {
566 unsigned int cutoff = amaf->game_baselen;
567 cutoff += (amaf->gamelen - amaf->game_baselen) * u->playout_amaf_cutoff / 100;
568 /* Now, reconstruct the amaf map. */
569 memset(amaf->map, 0, board_size2(&b2) * sizeof(*amaf->map));
570 for (unsigned int i = 0; i < cutoff; i++) {
571 coord_t coord = amaf->game[i].coord;
572 enum stone color = amaf->game[i].color;
573 if (amaf->map[coord] == S_NONE || amaf->map[coord] == color) {
574 amaf->map[coord] = color;
575 /* Nakade always recorded for in-tree part */
576 } else if (amaf->record_nakade || i <= amaf->game_baselen) {
577 amaf_op(amaf->map[n->coord], +);
582 assert(n == t->root || n->parent);
583 if (result != 0) {
584 float rval = scale_value(u, b, result);
585 u->policy->update(u->policy, t, n, node_color, player_color, amaf, rval);
587 if (t->use_extra_komi) {
588 stats_add_result(&u->dynkomi->score, result / 2, 1);
589 stats_add_result(&u->dynkomi->value, rval, 1);
592 if (u->local_tree && n->parent && !is_pass(n->coord) && dlen > 0) {
593 /* Possibly transform the rval appropriately. */
594 float expval = seq_value.value / seq_value.playouts;
595 rval = stats_temper_value(rval, expval, u->local_tree);
597 /* Get the local sequences and record them in ltree. */
598 /* We will look for sequence starts in our descent
599 * history, then run record_local_sequence() for each
600 * found sequence start; record_local_sequence() may
601 * pick longer sequences from descent history then,
602 * which is expected as it will create new lnodes. */
603 enum stone seq_color = player_color;
604 /* First move always starts a sequence. */
605 record_local_sequence(u, t, descent, dlen, 1, seq_color, rval);
606 seq_color = stone_other(seq_color);
607 for (int dseqi = 2; dseqi < dlen; dseqi++, seq_color = stone_other(seq_color)) {
608 if (u->local_tree_allseq) {
609 /* We are configured to record all subsequences. */
610 record_local_sequence(u, t, descent, dlen, dseqi, seq_color, rval);
611 continue;
613 if (descent[dseqi].node->d >= u->tenuki_d) {
614 /* Tenuki! Record the fresh sequence. */
615 record_local_sequence(u, t, descent, dlen, dseqi, seq_color, rval);
616 continue;
618 if (descent[dseqi].lnode && !descent[dseqi].lnode) {
619 /* Record result for in-descent picked sequence. */
620 record_local_sequence(u, t, descent, dlen, dseqi, seq_color, rval);
621 continue;
627 end:
628 /* We need to undo the virtual loss we added during descend. */
629 if (u->virtual_loss) {
630 int parity = (node_color == player_color ? 1 : -1);
631 for (; n->parent; n = n->parent) {
632 stats_rm_result(&n->u, tree_parity(t, parity) > 0 ? 0 : 1, 1);
633 parity = -parity;
637 if (amaf) {
638 free(amaf->map - 1);
639 free(amaf);
641 board_done_noalloc(&b2);
642 return result;
646 uct_playouts(struct uct *u, struct board *b, enum stone color, struct tree *t, struct time_info *ti)
648 int i;
649 if (ti && ti->dim == TD_GAMES) {
650 for (i = 0; t->root->u.playouts <= ti->len.games; i++)
651 uct_playout(u, b, color, t);
652 } else {
653 for (i = 0; !uct_halt; i++)
654 uct_playout(u, b, color, t);
656 return i;