UCT treepool_pickfactor: Introduce for non-uniform treepool selection
[pachi/ann.git] / uct / walk.c
blobc79ceef9ef56321a46332b2fbd98c16b16daa903
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]);
186 if (u->treepool_chance[mode] > fast_random(100) && upc->treepool[color - 1]) {
187 assert(upc->treepool_n[color - 1] > 0);
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");
195 coord_t treepool_move = pass;
196 if (u->treepool_pickfactor) {
197 /* With pickfactor=10, we get uniform distribution. */
198 int prob = 1000 * u->treepool_pickfactor / (upc->treepool_n[color - 1] * 10);
199 for (int i = 0; i < upc->treepool_n[color - 1]; i++) {
200 treepool_move = upc->treepool[color - 1][i];
201 if (prob > fast_random(1000)) break;
203 } else {
204 treepool_move = upc->treepool[color - 1][fast_random(upc->treepool_n[color - 1])];
206 if (UDEBUGL(7))
207 fprintf(stderr, "Treepool pick <%d> %s,%s\n",
208 upc->treepool_n[color - 1],
209 stone2str(color), coord2sstr(treepool_move, b));
211 if (board_is_valid_play(b, color, treepool_move))
212 return treepool_move;
214 return pass;
217 static coord_t
218 uct_playout_prepolicy(struct playout_policy *playout, struct playout_setup *setup, struct board *b, enum stone color)
220 return uct_playout_hook(playout, setup, b, color, 0);
223 static coord_t
224 uct_playout_postpolicy(struct playout_policy *playout, struct playout_setup *setup, struct board *b, enum stone color)
226 return uct_playout_hook(playout, setup, b, color, 1);
229 double
230 treepool_node_value(struct uct *u, struct tree *tree, int parity, struct tree_node *node)
232 /* XXX: Playouts get cast to double */
233 switch (u->treepool_type) {
234 case UTT_RAVE_PLAYOUTS:
235 return node->amaf.playouts;
236 case UTT_RAVE_VALUE:
237 return tree_node_get_value(tree, parity, node->amaf.value);
238 case UTT_UCT_PLAYOUTS:
239 return node->u.playouts;
240 case UTT_UCT_VALUE:
241 return tree_node_get_value(tree, parity, node->u.value);
242 case UTT_EVALUATE:
244 struct uct_descent d = { .node = node };
245 assert(u->policy->evaluate);
246 return u->policy->evaluate(u->policy, tree, &d, parity);
248 default: assert(0);
250 return -1;
253 static void
254 treepool_setup(struct uct_playout_callback *upc, struct board *b, struct tree_node *node, int color)
256 struct uct *u = upc->uct;
257 int parity = ((node->depth ^ upc->tree->root->depth) & 1) ? -1 : 1;
259 /* XXX: Naive O(N^2) way. */
260 for (int i = 0; i < u->treepool_size; i++) {
261 /* For each item, find the highest
262 * node not in the pool yet. */
263 struct tree_node *best = NULL;
264 double best_val = -1;
266 assert(node->children && is_pass(node->children->coord));
267 for (struct tree_node *ni = node->children->sibling; ni; ni = ni->sibling) {
268 /* Do we already have it? */
269 bool have = false;
270 for (int j = 0; j < upc->treepool_n[color]; j++) {
271 if (upc->treepool[color][j] == ni->coord) {
272 have = true;
273 break;
276 if (have)
277 continue;
279 double i_val = treepool_node_value(u, upc->tree, parity, ni);
280 if (i_val > best_val) {
281 best = ni;
282 best_val = i_val;
286 if (!best) break;
287 upc->treepool[color][upc->treepool_n[color]++] = best->coord;
292 static int
293 uct_leaf_node(struct uct *u, struct board *b, enum stone player_color,
294 struct playout_amafmap *amaf, struct uct_descent *descent,
295 struct tree_node *significant[2],
296 struct tree *t, struct tree_node *n, enum stone node_color,
297 char *spaces)
299 enum stone next_color = stone_other(node_color);
300 int parity = (next_color == player_color ? 1 : -1);
302 /* We need to make sure only one thread expands the node. If
303 * we are unlucky enough for two threads to meet in the same
304 * node, the latter one will simply do another simulation from
305 * the node itself, no big deal. t->nodes_size may exceed
306 * the maximum in multi-threaded case but not by much so it's ok.
307 * The size test must be before the test&set not after, to allow
308 * expansion of the node later if enough nodes have been freed. */
309 if (n->u.playouts >= u->expand_p && t->nodes_size < u->max_tree_size
310 && !__sync_lock_test_and_set(&n->is_expanded, 1)) {
311 tree_expand_node(t, n, b, next_color, u, parity);
313 if (UDEBUGL(7))
314 fprintf(stderr, "%s*-- UCT playout #%d start [%s] %f\n",
315 spaces, n->u.playouts, coord2sstr(n->coord, t->board),
316 tree_node_get_value(t, parity, n->u.value));
318 struct uct_playout_callback upc = {
319 .uct = u,
320 .tree = t,
321 /* TODO: Don't necessarily restart the sequence walk when
322 * entering playout. */
323 .lnode = NULL,
326 if (u->local_tree_playout) {
327 /* N.B.: We know this is ELO playout. */
328 playout_elo_callback(u->playout, uct_playout_probdist, &upc);
331 coord_t pool[2][u->treepool_size];
332 if (u->treepool_chance[0] + u->treepool_chance[1] > 0) {
333 for (int color = 0; color < 2; color++) {
334 /* Prepare tree-based pool of moves to try forcing
335 * during the playout. */
336 /* We consider the children of the last significant
337 * node, picking top N choices. */
338 struct tree_node *n = significant[color];
339 if (!n || !n->children || !n->children->sibling) {
340 /* No significant node, or it's childless or has
341 * only pass as its child. */
342 upc.treepool[color] = NULL;
343 upc.treepool_n[color] = 0;
344 } else {
345 upc.treepool[color] = (coord_t *) &pool[color];
346 treepool_setup(&upc, b, n, color);
351 struct playout_setup ps = {
352 .gamelen = u->gamelen,
353 .mercymin = u->mercymin,
354 .prepolicy_hook = uct_playout_prepolicy,
355 .postpolicy_hook = uct_playout_postpolicy,
356 .hook_data = &upc,
358 int result = play_random_game(&ps, b, next_color,
359 u->playout_amaf ? amaf : NULL,
360 &u->ownermap, u->playout);
361 if (next_color == S_WHITE) {
362 /* We need the result from black's perspective. */
363 result = - result;
365 if (UDEBUGL(7))
366 fprintf(stderr, "%s -- [%d..%d] %s random playout result %d\n",
367 spaces, player_color, next_color, coord2sstr(n->coord, t->board), result);
369 return result;
372 static float
373 scale_value(struct uct *u, struct board *b, int result)
375 float rval = result > 0;
376 if (u->val_scale) {
377 int vp = u->val_points;
378 if (!vp) {
379 vp = board_size(b) - 1; vp *= vp; vp *= 2;
382 float sval = (float) abs(result) / vp;
383 sval = sval > 1 ? 1 : sval;
384 if (result < 0) sval = 1 - sval;
385 if (u->val_extra)
386 rval += u->val_scale * sval;
387 else
388 rval = (1 - u->val_scale) * rval + u->val_scale * sval;
389 // fprintf(stderr, "score %d => sval %f, rval %f\n", result, sval, rval);
391 return rval;
394 static void
395 record_local_sequence(struct uct *u, struct tree *t,
396 struct uct_descent *descent, int dlen, int di,
397 enum stone seq_color, float rval)
399 /* Ignore pass sequences. */
400 if (is_pass(descent[di].node->coord))
401 return;
403 #define LTREE_DEBUG if (UDEBUGL(6))
404 LTREE_DEBUG fprintf(stderr, "recording result %f in local %s sequence: ",
405 rval, stone2str(seq_color));
406 int di0 = di;
408 /* Pick the right local tree root... */
409 struct tree_node *lnode = seq_color == S_BLACK ? t->ltree_black : t->ltree_white;
410 lnode->u.playouts++;
412 /* ...and record the sequence. */
413 while (di < dlen && (di == di0 || descent[di].node->d < u->tenuki_d)) {
414 LTREE_DEBUG fprintf(stderr, "%s[%d] ",
415 coord2sstr(descent[di].node->coord, t->board),
416 descent[di].node->d);
417 lnode = tree_get_node(t, lnode, descent[di++].node->coord, true);
418 assert(lnode);
419 stats_add_result(&lnode->u, rval, 1);
422 /* Add lnode for tenuki (pass) if we descended further. */
423 if (di < dlen) {
424 LTREE_DEBUG fprintf(stderr, "pass ");
425 lnode = tree_get_node(t, lnode, pass, true);
426 assert(lnode);
427 stats_add_result(&lnode->u, rval, 1);
430 LTREE_DEBUG fprintf(stderr, "\n");
435 uct_playout(struct uct *u, struct board *b, enum stone player_color, struct tree *t)
437 struct board b2;
438 board_copy(&b2, b);
440 struct playout_amafmap *amaf = NULL;
441 if (u->policy->wants_amaf) {
442 amaf = calloc2(1, sizeof(*amaf));
443 amaf->map = calloc2(board_size2(&b2) + 1, sizeof(*amaf->map));
444 amaf->map++; // -1 is pass
447 /* Walk the tree until we find a leaf, then expand it and do
448 * a random playout. */
449 struct tree_node *n = t->root;
450 enum stone node_color = stone_other(player_color);
451 assert(node_color == t->root_color);
453 /* Tree descent history. */
454 /* XXX: This is somewhat messy since @n and descent[dlen-1].node are
455 * redundant. */
456 #define DLEN 512
457 struct uct_descent descent[DLEN];
458 descent[0].node = n; descent[0].lnode = NULL;
459 int dlen = 1;
460 /* Total value of the sequence. */
461 struct move_stats seq_value = { .playouts = 0 };
462 /* The last "significant" node along the descent (i.e. node
463 * with higher than configured number of playouts). For black
464 * and white. */
465 struct tree_node *significant[2] = { NULL, NULL };
466 if (n->u.playouts >= u->significant_threshold)
467 significant[node_color - 1] = n;
469 int result;
470 int pass_limit = (board_size(&b2) - 2) * (board_size(&b2) - 2) / 2;
471 int passes = is_pass(b->last_move.coord) && b->moves > 0;
473 /* debug */
474 int depth = 0;
475 static char spaces[] = "\0 ";
476 /* /debug */
477 if (UDEBUGL(8))
478 fprintf(stderr, "--- UCT walk with color %d\n", player_color);
480 while (!tree_leaf_node(n) && passes < 2) {
481 spaces[depth++] = ' '; spaces[depth] = 0;
484 /*** Choose a node to descend to: */
486 /* Parity is chosen already according to the child color, since
487 * it is applied to children. */
488 node_color = stone_other(node_color);
489 int parity = (node_color == player_color ? 1 : -1);
491 assert(dlen < DLEN);
492 descent[dlen] = descent[dlen - 1];
493 if (u->local_tree && (!descent[dlen].lnode || descent[dlen].node->d >= u->tenuki_d)) {
494 /* Start new local sequence. */
495 /* Remember that node_color already holds color of the
496 * to-be-found child. */
497 descent[dlen].lnode = node_color == S_BLACK ? t->ltree_black : t->ltree_white;
500 if (!u->random_policy_chance || fast_random(u->random_policy_chance))
501 u->policy->descend(u->policy, t, &descent[dlen], parity, b2.moves > pass_limit);
502 else
503 u->random_policy->descend(u->random_policy, t, &descent[dlen], parity, b2.moves > pass_limit);
506 /*** Perform the descent: */
508 if (descent[dlen].node->u.playouts >= u->significant_threshold) {
509 significant[node_color - 1] = descent[dlen].node;
512 seq_value.playouts += descent[dlen].value.playouts;
513 seq_value.value += descent[dlen].value.value * descent[dlen].value.playouts;
514 n = descent[dlen++].node;
515 assert(n == t->root || n->parent);
516 if (UDEBUGL(7))
517 fprintf(stderr, "%s+-- UCT sent us to [%s:%d] %d,%f\n",
518 spaces, coord2sstr(n->coord, t->board),
519 n->coord, n->u.playouts,
520 tree_node_get_value(t, parity, n->u.value));
522 /* Add virtual loss if we need to; this is used to discourage
523 * other threads from visiting this node in case of multiple
524 * threads doing the tree search. */
525 if (u->virtual_loss)
526 stats_add_result(&n->u, tree_parity(t, parity) > 0 ? 0 : 1, 1);
528 assert(n->coord >= -1);
529 if (amaf && !is_pass(n->coord))
530 record_amaf_move(amaf, n->coord, node_color);
532 struct move m = { n->coord, node_color };
533 int res = board_play(&b2, &m);
535 if (res < 0 || (!is_pass(m.coord) && !group_at(&b2, m.coord)) /* suicide */
536 || b2.superko_violation) {
537 if (UDEBUGL(4)) {
538 for (struct tree_node *ni = n; ni; ni = ni->parent)
539 fprintf(stderr, "%s<%"PRIhash"> ", coord2sstr(ni->coord, t->board), ni->hash);
540 fprintf(stderr, "marking invalid %s node %d,%d res %d group %d spk %d\n",
541 stone2str(node_color), coord_x(n->coord,b), coord_y(n->coord,b),
542 res, group_at(&b2, m.coord), b2.superko_violation);
544 n->hints |= TREE_HINT_INVALID;
545 result = 0;
546 goto end;
549 if (is_pass(n->coord))
550 passes++;
551 else
552 passes = 0;
555 if (amaf) {
556 amaf->game_baselen = amaf->gamelen;
557 amaf->record_nakade = u->playout_amaf_nakade;
560 if (t->use_extra_komi && u->dynkomi->persim) {
561 b2.komi += round(u->dynkomi->persim(u->dynkomi, &b2, t, n));
564 if (passes >= 2) {
565 /* XXX: No dead groups support. */
566 float score = board_official_score(&b2, NULL);
567 /* Result from black's perspective (no matter who
568 * the player; black's perspective is always
569 * what the tree stores. */
570 result = - (score * 2);
572 if (UDEBUGL(5))
573 fprintf(stderr, "[%d..%d] %s p-p scoring playout result %d (W %f)\n",
574 player_color, node_color, coord2sstr(n->coord, t->board), result, score);
575 if (UDEBUGL(6))
576 board_print(&b2, stderr);
578 board_ownermap_fill(&u->ownermap, &b2);
580 } else { // assert(tree_leaf_node(n));
581 /* In case of parallel tree search, the assertion might
582 * not hold if two threads chew on the same node. */
583 result = uct_leaf_node(u, &b2, player_color, amaf, &descent[dlen - 1], significant, t, n, node_color, spaces);
586 if (amaf && u->playout_amaf_cutoff) {
587 unsigned int cutoff = amaf->game_baselen;
588 cutoff += (amaf->gamelen - amaf->game_baselen) * u->playout_amaf_cutoff / 100;
589 /* Now, reconstruct the amaf map. */
590 memset(amaf->map, 0, board_size2(&b2) * sizeof(*amaf->map));
591 for (unsigned int i = 0; i < cutoff; i++) {
592 coord_t coord = amaf->game[i].coord;
593 enum stone color = amaf->game[i].color;
594 if (amaf->map[coord] == S_NONE || amaf->map[coord] == color) {
595 amaf->map[coord] = color;
596 /* Nakade always recorded for in-tree part */
597 } else if (amaf->record_nakade || i <= amaf->game_baselen) {
598 amaf_op(amaf->map[n->coord], +);
603 assert(n == t->root || n->parent);
604 if (result != 0) {
605 float rval = scale_value(u, b, result);
606 u->policy->update(u->policy, t, n, node_color, player_color, amaf, rval);
608 if (t->use_extra_komi) {
609 stats_add_result(&u->dynkomi->score, result / 2, 1);
610 stats_add_result(&u->dynkomi->value, rval, 1);
613 if (u->local_tree && n->parent && !is_pass(n->coord) && dlen > 0) {
614 /* Possibly transform the rval appropriately. */
615 float expval = seq_value.value / seq_value.playouts;
616 rval = stats_temper_value(rval, expval, u->local_tree);
618 /* Get the local sequences and record them in ltree. */
619 /* We will look for sequence starts in our descent
620 * history, then run record_local_sequence() for each
621 * found sequence start; record_local_sequence() may
622 * pick longer sequences from descent history then,
623 * which is expected as it will create new lnodes. */
624 enum stone seq_color = player_color;
625 /* First move always starts a sequence. */
626 record_local_sequence(u, t, descent, dlen, 1, seq_color, rval);
627 seq_color = stone_other(seq_color);
628 for (int dseqi = 2; dseqi < dlen; dseqi++, seq_color = stone_other(seq_color)) {
629 if (u->local_tree_allseq) {
630 /* We are configured to record all subsequences. */
631 record_local_sequence(u, t, descent, dlen, dseqi, seq_color, rval);
632 continue;
634 if (descent[dseqi].node->d >= u->tenuki_d) {
635 /* Tenuki! Record the fresh sequence. */
636 record_local_sequence(u, t, descent, dlen, dseqi, seq_color, rval);
637 continue;
639 if (descent[dseqi].lnode && !descent[dseqi].lnode) {
640 /* Record result for in-descent picked sequence. */
641 record_local_sequence(u, t, descent, dlen, dseqi, seq_color, rval);
642 continue;
648 end:
649 /* We need to undo the virtual loss we added during descend. */
650 if (u->virtual_loss) {
651 int parity = (node_color == player_color ? 1 : -1);
652 for (; n->parent; n = n->parent) {
653 stats_rm_result(&n->u, tree_parity(t, parity) > 0 ? 0 : 1, 1);
654 parity = -parity;
658 if (amaf) {
659 free(amaf->map - 1);
660 free(amaf);
662 board_done_noalloc(&b2);
663 return result;
667 uct_playouts(struct uct *u, struct board *b, enum stone color, struct tree *t, struct time_info *ti)
669 int i;
670 if (ti && ti->dim == TD_GAMES) {
671 for (i = 0; t->root->u.playouts <= ti->len.games; i++)
672 uct_playout(u, b, color, t);
673 } else {
674 for (i = 0; !uct_halt; i++)
675 uct_playout(u, b, color, t);
677 return i;