UCT significant node: Make per-color, drop redundant color info
[pachi.git] / uct / walk.c
blob24321751c99ec0f05290ce30c02fedfa622d6c8d
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;
111 static void
112 uct_playout_probdist(void *data, struct board *b, enum stone to_play, struct probdist *pd)
114 /* Create probability distribution according to found local tree
115 * sequence. */
116 struct uct_playout_callback *upc = data;
117 assert(upc && upc->tree && pd && b);
118 coord_t c = b->last_move.coord;
119 enum stone color = b->last_move.color;
121 if (is_pass(c)) {
122 /* Break local sequence. */
123 upc->lnode = NULL;
124 } else if (upc->lnode) {
125 /* Try to follow local sequence. */
126 upc->lnode = tree_get_node(upc->tree, upc->lnode, c, false);
129 if (!upc->lnode || !upc->lnode->children) {
130 /* There's no local sequence, start new one! */
131 upc->lnode = color == S_BLACK ? upc->tree->ltree_black : upc->tree->ltree_white;
132 upc->lnode = tree_get_node(upc->tree, upc->lnode, c, false);
135 if (!upc->lnode || !upc->lnode->children) {
136 /* We have no local sequence and we cannot find any starting
137 * by node corresponding to last move. */
138 if (!upc->uct->local_tree_pseqroot) {
139 /* Give up then, we have nothing to contribute. */
140 return;
142 /* Construct probability distribution from possible first
143 * sequence move. Remember that @color is color of the
144 * *last* move. */
145 upc->lnode = color == S_BLACK ? upc->tree->ltree_white : upc->tree->ltree_black;
146 if (!upc->lnode->children) {
147 /* We don't even have anything in our tree yet. */
148 return;
152 /* The probdist has the right structure only if BOARD_GAMMA is defined. */
153 #ifndef BOARD_GAMMA
154 assert(0);
155 #endif
157 /* Construct probability distribution from lnode children. */
158 struct tree_node *li = upc->lnode->children;
159 assert(li);
160 if (is_pass(li->coord)) {
161 /* Tenuki. */
162 /* TODO: Spread tenuki gamma over all moves we don't touch. */
163 li = li->sibling;
165 for (; li; li = li->sibling) {
166 if (board_at(b, li->coord) != S_NONE)
167 continue;
168 double gamma = fixp_to_double(pd->items[li->coord]) * ltree_node_gamma(li, to_play);
169 probdist_set(pd, li->coord, double_to_fixp(gamma));
174 static coord_t
175 uct_playout_hook(struct playout_policy *playout, struct playout_setup *setup, struct board *b, enum stone color, int mode)
177 struct uct_playout_callback *upc = setup->hook_data;
179 /* TODO: Fill me. */
180 return pass;
183 static coord_t
184 uct_playout_prepolicy(struct playout_policy *playout, struct playout_setup *setup, struct board *b, enum stone color)
186 return uct_playout_hook(playout, setup, b, color, 0);
189 static coord_t
190 uct_playout_postpolicy(struct playout_policy *playout, struct playout_setup *setup, struct board *b, enum stone color)
192 return uct_playout_hook(playout, setup, b, color, 1);
196 static int
197 uct_leaf_node(struct uct *u, struct board *b, enum stone player_color,
198 struct playout_amafmap *amaf,
199 struct tree *t, struct tree_node *n, enum stone node_color,
200 char *spaces)
202 enum stone next_color = stone_other(node_color);
203 int parity = (next_color == player_color ? 1 : -1);
205 /* We need to make sure only one thread expands the node. If
206 * we are unlucky enough for two threads to meet in the same
207 * node, the latter one will simply do another simulation from
208 * the node itself, no big deal. t->nodes_size may exceed
209 * the maximum in multi-threaded case but not by much so it's ok.
210 * The size test must be before the test&set not after, to allow
211 * expansion of the node later if enough nodes have been freed. */
212 if (n->u.playouts >= u->expand_p && t->nodes_size < u->max_tree_size
213 && !__sync_lock_test_and_set(&n->is_expanded, 1)) {
214 tree_expand_node(t, n, b, next_color, u, parity);
216 if (UDEBUGL(7))
217 fprintf(stderr, "%s*-- UCT playout #%d start [%s] %f\n",
218 spaces, n->u.playouts, coord2sstr(n->coord, t->board),
219 tree_node_get_value(t, parity, n->u.value));
221 /* TODO: Don't necessarily restart the sequence walk when entering
222 * playout. */
223 struct uct_playout_callback upc = { .uct = u, .tree = t, .lnode = NULL };
224 if (u->local_tree_playout) {
225 /* N.B.: We know this is ELO playout. */
226 playout_elo_callback(u->playout, uct_playout_probdist, &upc);
229 struct playout_setup ps = {
230 .gamelen = u->gamelen,
231 .mercymin = u->mercymin,
232 .prepolicy_hook = uct_playout_prepolicy,
233 .postpolicy_hook = uct_playout_postpolicy,
234 .hook_data = &upc,
236 int result = play_random_game(&ps, b, next_color,
237 u->playout_amaf ? amaf : NULL,
238 &u->ownermap, u->playout);
239 if (next_color == S_WHITE) {
240 /* We need the result from black's perspective. */
241 result = - result;
243 if (UDEBUGL(7))
244 fprintf(stderr, "%s -- [%d..%d] %s random playout result %d\n",
245 spaces, player_color, next_color, coord2sstr(n->coord, t->board), result);
247 return result;
250 static float
251 scale_value(struct uct *u, struct board *b, int result)
253 float rval = result > 0;
254 if (u->val_scale) {
255 int vp = u->val_points;
256 if (!vp) {
257 vp = board_size(b) - 1; vp *= vp; vp *= 2;
260 float sval = (float) abs(result) / vp;
261 sval = sval > 1 ? 1 : sval;
262 if (result < 0) sval = 1 - sval;
263 if (u->val_extra)
264 rval += u->val_scale * sval;
265 else
266 rval = (1 - u->val_scale) * rval + u->val_scale * sval;
267 // fprintf(stderr, "score %d => sval %f, rval %f\n", result, sval, rval);
269 return rval;
272 static void
273 record_local_sequence(struct uct *u, struct tree *t,
274 struct uct_descent *descent, int dlen, int di,
275 enum stone seq_color, float rval)
277 /* Ignore pass sequences. */
278 if (is_pass(descent[di].node->coord))
279 return;
281 #define LTREE_DEBUG if (UDEBUGL(6))
282 LTREE_DEBUG fprintf(stderr, "recording result %f in local %s sequence: ",
283 rval, stone2str(seq_color));
284 int di0 = di;
286 /* Pick the right local tree root... */
287 struct tree_node *lnode = seq_color == S_BLACK ? t->ltree_black : t->ltree_white;
288 lnode->u.playouts++;
290 /* ...and record the sequence. */
291 while (di < dlen && (di == di0 || descent[di].node->d < u->tenuki_d)) {
292 LTREE_DEBUG fprintf(stderr, "%s[%d] ",
293 coord2sstr(descent[di].node->coord, t->board),
294 descent[di].node->d);
295 lnode = tree_get_node(t, lnode, descent[di++].node->coord, true);
296 assert(lnode);
297 stats_add_result(&lnode->u, rval, 1);
300 /* Add lnode for tenuki (pass) if we descended further. */
301 if (di < dlen) {
302 LTREE_DEBUG fprintf(stderr, "pass ");
303 lnode = tree_get_node(t, lnode, pass, true);
304 assert(lnode);
305 stats_add_result(&lnode->u, rval, 1);
308 LTREE_DEBUG fprintf(stderr, "\n");
313 uct_playout(struct uct *u, struct board *b, enum stone player_color, struct tree *t)
315 struct board b2;
316 board_copy(&b2, b);
318 struct playout_amafmap *amaf = NULL;
319 if (u->policy->wants_amaf) {
320 amaf = calloc2(1, sizeof(*amaf));
321 amaf->map = calloc2(board_size2(&b2) + 1, sizeof(*amaf->map));
322 amaf->map++; // -1 is pass
325 /* Walk the tree until we find a leaf, then expand it and do
326 * a random playout. */
327 struct tree_node *n = t->root;
328 enum stone node_color = stone_other(player_color);
329 assert(node_color == t->root_color);
331 /* Tree descent history. */
332 /* XXX: This is somewhat messy since @n and descent[dlen-1].node are
333 * redundant. */
334 #define DLEN 512
335 struct uct_descent descent[DLEN];
336 descent[0].node = n; descent[0].lnode = NULL;
337 descent[0].significant[0] = descent[0].significant[1] = NULL;
338 int dlen = 1;
339 /* Total value of the sequence. */
340 struct move_stats seq_value = { .playouts = 0 };
342 int result;
343 int pass_limit = (board_size(&b2) - 2) * (board_size(&b2) - 2) / 2;
344 int passes = is_pass(b->last_move.coord) && b->moves > 0;
346 /* debug */
347 int depth = 0;
348 static char spaces[] = "\0 ";
349 /* /debug */
350 if (UDEBUGL(8))
351 fprintf(stderr, "--- UCT walk with color %d\n", player_color);
353 while (!tree_leaf_node(n) && passes < 2) {
354 spaces[depth++] = ' '; spaces[depth] = 0;
357 /*** Choose a node to descend to: */
359 /* Parity is chosen already according to the child color, since
360 * it is applied to children. */
361 node_color = stone_other(node_color);
362 int parity = (node_color == player_color ? 1 : -1);
364 assert(dlen < DLEN);
365 descent[dlen] = descent[dlen - 1];
366 if (u->local_tree && (!descent[dlen].lnode || descent[dlen].node->d >= u->tenuki_d)) {
367 /* Start new local sequence. */
368 /* Remember that node_color already holds color of the
369 * to-be-found child. */
370 descent[dlen].lnode = node_color == S_BLACK ? t->ltree_black : t->ltree_white;
373 if (!u->random_policy_chance || fast_random(u->random_policy_chance))
374 u->policy->descend(u->policy, t, &descent[dlen], parity, b2.moves > pass_limit);
375 else
376 u->random_policy->descend(u->random_policy, t, &descent[dlen], parity, b2.moves > pass_limit);
379 /*** Perform the descent: */
381 if (descent[dlen].node->u.playouts >= u->significant_threshold) {
382 descent[dlen].significant[node_color - 1] = n;
385 seq_value.playouts += descent[dlen].value.playouts;
386 seq_value.value += descent[dlen].value.value * descent[dlen].value.playouts;
387 n = descent[dlen++].node;
388 assert(n == t->root || n->parent);
389 if (UDEBUGL(7))
390 fprintf(stderr, "%s+-- UCT sent us to [%s:%d] %f\n",
391 spaces, coord2sstr(n->coord, t->board), n->coord,
392 tree_node_get_value(t, parity, n->u.value));
394 /* Add virtual loss if we need to; this is used to discourage
395 * other threads from visiting this node in case of multiple
396 * threads doing the tree search. */
397 if (u->virtual_loss)
398 stats_add_result(&n->u, tree_parity(t, parity) > 0 ? 0 : 1, 1);
400 assert(n->coord >= -1);
401 if (amaf && !is_pass(n->coord))
402 record_amaf_move(amaf, n->coord, node_color);
404 struct move m = { n->coord, node_color };
405 int res = board_play(&b2, &m);
407 if (res < 0 || (!is_pass(m.coord) && !group_at(&b2, m.coord)) /* suicide */
408 || b2.superko_violation) {
409 if (UDEBUGL(4)) {
410 for (struct tree_node *ni = n; ni; ni = ni->parent)
411 fprintf(stderr, "%s<%"PRIhash"> ", coord2sstr(ni->coord, t->board), ni->hash);
412 fprintf(stderr, "marking invalid %s node %d,%d res %d group %d spk %d\n",
413 stone2str(node_color), coord_x(n->coord,b), coord_y(n->coord,b),
414 res, group_at(&b2, m.coord), b2.superko_violation);
416 n->hints |= TREE_HINT_INVALID;
417 result = 0;
418 goto end;
421 if (is_pass(n->coord))
422 passes++;
423 else
424 passes = 0;
427 if (amaf) {
428 amaf->game_baselen = amaf->gamelen;
429 amaf->record_nakade = u->playout_amaf_nakade;
432 if (t->use_extra_komi && u->dynkomi->persim) {
433 b2.komi += round(u->dynkomi->persim(u->dynkomi, &b2, t, n));
436 if (passes >= 2) {
437 /* XXX: No dead groups support. */
438 float score = board_official_score(&b2, NULL);
439 /* Result from black's perspective (no matter who
440 * the player; black's perspective is always
441 * what the tree stores. */
442 result = - (score * 2);
444 if (UDEBUGL(5))
445 fprintf(stderr, "[%d..%d] %s p-p scoring playout result %d (W %f)\n",
446 player_color, node_color, coord2sstr(n->coord, t->board), result, score);
447 if (UDEBUGL(6))
448 board_print(&b2, stderr);
450 board_ownermap_fill(&u->ownermap, &b2);
452 } else { // assert(tree_leaf_node(n));
453 /* In case of parallel tree search, the assertion might
454 * not hold if two threads chew on the same node. */
455 result = uct_leaf_node(u, &b2, player_color, amaf, &descent[dlen - 1], t, n, node_color, spaces);
458 if (amaf && u->playout_amaf_cutoff) {
459 unsigned int cutoff = amaf->game_baselen;
460 cutoff += (amaf->gamelen - amaf->game_baselen) * u->playout_amaf_cutoff / 100;
461 /* Now, reconstruct the amaf map. */
462 memset(amaf->map, 0, board_size2(&b2) * sizeof(*amaf->map));
463 for (unsigned int i = 0; i < cutoff; i++) {
464 coord_t coord = amaf->game[i].coord;
465 enum stone color = amaf->game[i].color;
466 if (amaf->map[coord] == S_NONE || amaf->map[coord] == color) {
467 amaf->map[coord] = color;
468 /* Nakade always recorded for in-tree part */
469 } else if (amaf->record_nakade || i <= amaf->game_baselen) {
470 amaf_op(amaf->map[n->coord], +);
475 assert(n == t->root || n->parent);
476 if (result != 0) {
477 float rval = scale_value(u, b, result);
478 u->policy->update(u->policy, t, n, node_color, player_color, amaf, rval);
480 if (t->use_extra_komi) {
481 stats_add_result(&u->dynkomi->score, result / 2, 1);
482 stats_add_result(&u->dynkomi->value, rval, 1);
485 if (u->local_tree && n->parent && !is_pass(n->coord) && dlen > 0) {
486 /* Possibly transform the rval appropriately. */
487 float expval = seq_value.value / seq_value.playouts;
488 rval = stats_temper_value(rval, expval, u->local_tree);
490 /* Get the local sequences and record them in ltree. */
491 /* We will look for sequence starts in our descent
492 * history, then run record_local_sequence() for each
493 * found sequence start; record_local_sequence() may
494 * pick longer sequences from descent history then,
495 * which is expected as it will create new lnodes. */
496 enum stone seq_color = player_color;
497 /* First move always starts a sequence. */
498 record_local_sequence(u, t, descent, dlen, 1, seq_color, rval);
499 seq_color = stone_other(seq_color);
500 for (int dseqi = 2; dseqi < dlen; dseqi++, seq_color = stone_other(seq_color)) {
501 if (u->local_tree_allseq) {
502 /* We are configured to record all subsequences. */
503 record_local_sequence(u, t, descent, dlen, dseqi, seq_color, rval);
504 continue;
506 if (descent[dseqi].node->d >= u->tenuki_d) {
507 /* Tenuki! Record the fresh sequence. */
508 record_local_sequence(u, t, descent, dlen, dseqi, seq_color, rval);
509 continue;
511 if (descent[dseqi].lnode && !descent[dseqi].lnode) {
512 /* Record result for in-descent picked sequence. */
513 record_local_sequence(u, t, descent, dlen, dseqi, seq_color, rval);
514 continue;
520 end:
521 /* We need to undo the virtual loss we added during descend. */
522 if (u->virtual_loss) {
523 int parity = (node_color == player_color ? 1 : -1);
524 for (; n->parent; n = n->parent) {
525 stats_rm_result(&n->u, tree_parity(t, parity) > 0 ? 0 : 1, 1);
526 parity = -parity;
530 if (amaf) {
531 free(amaf->map - 1);
532 free(amaf);
534 board_done_noalloc(&b2);
535 return result;
539 uct_playouts(struct uct *u, struct board *b, enum stone color, struct tree *t, struct time_info *ti)
541 int i;
542 if (ti->dim == TD_GAMES) {
543 for (i = 0; t->root->u.playouts <= ti->len.games; i++)
544 uct_playout(u, b, color, t);
545 } else {
546 for (i = 0; !uct_halt; i++)
547 uct_playout(u, b, color, t);
549 return i;