Fix race condition when expanding a node.
[pachi.git] / uct / tree.c
blobdb32b625070327f3560c333cffa1300fe031037f
1 #include <assert.h>
2 #include <math.h>
3 #include <stddef.h>
4 #include <stdint.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
9 #define DEBUG
10 #include "board.h"
11 #include "debug.h"
12 #include "engine.h"
13 #include "move.h"
14 #include "playout.h"
15 #include "tactics.h"
16 #include "uct/internal.h"
17 #include "uct/prior.h"
18 #include "uct/tree.h"
21 static struct tree_node *
22 tree_init_node(struct tree *t, coord_t coord, int depth)
24 struct tree_node *n = calloc(1, sizeof(*n));
25 if (!n) {
26 fprintf(stderr, "tree_init_node(): OUT OF MEMORY\n");
27 exit(1);
29 n->coord = coord;
30 n->depth = depth;
31 static long c = 1000000;
32 n->hash = c++;
33 if (depth > t->max_depth)
34 t->max_depth = depth;
35 return n;
38 struct tree *
39 tree_init(struct board *board, enum stone color)
41 struct tree *t = calloc(1, sizeof(*t));
42 t->board = board;
43 /* The root PASS move is only virtual, we never play it. */
44 t->root = tree_init_node(t, pass, 0);
45 t->root_symmetry = board->symmetry;
46 t->root_color = stone_other(color); // to research black moves, root will be white
47 pthread_mutex_init(&t->expansion_mutex, NULL);
48 return t;
52 static void
53 tree_done_node(struct tree *t, struct tree_node *n)
55 struct tree_node *ni = n->children;
56 while (ni) {
57 struct tree_node *nj = ni->sibling;
58 tree_done_node(t, ni);
59 ni = nj;
61 free(n);
64 void
65 tree_done(struct tree *t)
67 tree_done_node(t, t->root);
68 if (t->chchvals) free(t->chchvals);
69 if (t->chvals) free(t->chvals);
70 free(t);
74 static void
75 tree_node_dump(struct tree *tree, struct tree_node *node, int l, int thres)
77 for (int i = 0; i < l; i++) fputc(' ', stderr);
78 int children = 0;
79 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
80 children++;
81 /* We use 1 as parity, since for all nodes we want to know the
82 * win probability of _us_, not the node color. */
83 fprintf(stderr, "[%s] %f %% %d [prior %f %% %d amaf %f %% %d]; hints %x; %d children <%"PRIhash">\n",
84 coord2sstr(node->coord, tree->board),
85 tree_node_get_value(tree, 1, node->u.value), node->u.playouts,
86 tree_node_get_value(tree, 1, node->prior.value), node->prior.playouts,
87 tree_node_get_value(tree, 1, node->amaf.value), node->amaf.playouts,
88 node->hints, children, node->hash);
90 /* Print nodes sorted by #playouts. */
92 struct tree_node *nbox[1000]; int nboxl = 0;
93 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
94 if (ni->u.playouts > thres)
95 nbox[nboxl++] = ni;
97 while (true) {
98 int best = -1;
99 for (int i = 0; i < nboxl; i++)
100 if (nbox[i] && (best < 0 || nbox[i]->u.playouts > nbox[best]->u.playouts))
101 best = i;
102 if (best < 0)
103 break;
104 tree_node_dump(tree, nbox[best], l + 1, /* node->u.value < 0.1 ? 0 : */ thres);
105 nbox[best] = NULL;
109 void
110 tree_dump_chval(struct tree *tree, struct move_stats *v)
112 for (int y = board_size(tree->board) - 2; y > 1; y--) {
113 for (int x = 1; x < board_size(tree->board) - 1; x++) {
114 coord_t c = coord_xy(tree->board, x, y);
115 fprintf(stderr, "%.2f%%%05d ", v[c].value, v[c].playouts);
117 fprintf(stderr, "\n");
121 void
122 tree_dump(struct tree *tree, int thres)
124 if (thres && tree->root->u.playouts / thres > 100) {
125 /* Be a bit sensible about this; the opening book can create
126 * huge dumps at first. */
127 thres = tree->root->u.playouts / 100 * (thres < 1000 ? 1 : thres / 1000);
129 fprintf(stderr, "(UCT tree; root %s; extra komi %f)\n",
130 stone2str(tree->root_color), tree->extra_komi);
131 tree_node_dump(tree, tree->root, 0, thres);
133 if (DEBUGL(3) && tree->chvals) {
134 fprintf(stderr, "children stats:\n");
135 tree_dump_chval(tree, tree->chvals);
136 fprintf(stderr, "grandchildren stats:\n");
137 tree_dump_chval(tree, tree->chchvals);
142 static char *
143 tree_book_name(struct board *b)
145 static char buf[256];
146 if (b->handicap > 0) {
147 sprintf(buf, "uctbook-%d-%02.01f-h%d.pachitree", b->size - 2, b->komi, b->handicap);
148 } else {
149 sprintf(buf, "uctbook-%d-%02.01f.pachitree", b->size - 2, b->komi);
151 return buf;
154 static void
155 tree_node_save(FILE *f, struct tree_node *node, int thres)
157 fputc(1, f);
158 fwrite(((void *) node) + offsetof(struct tree_node, depth),
159 sizeof(struct tree_node) - offsetof(struct tree_node, depth),
160 1, f);
162 if (node->u.playouts >= thres)
163 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
164 tree_node_save(f, ni, thres);
166 fputc(0, f);
169 void
170 tree_save(struct tree *tree, struct board *b, int thres)
172 char *filename = tree_book_name(b);
173 FILE *f = fopen(filename, "wb");
174 if (!f) {
175 perror("fopen");
176 return;
178 tree_node_save(f, tree->root, thres);
179 fputc(0, f);
180 fclose(f);
184 void
185 tree_node_load(FILE *f, struct tree_node *node, int *num)
187 (*num)++;
189 fread(((void *) node) + offsetof(struct tree_node, depth),
190 sizeof(struct tree_node) - offsetof(struct tree_node, depth),
191 1, f);
193 /* Keep values in sane scale, otherwise we start overflowing. */
194 #define MAX_PLAYOUTS 10000000
195 if (node->u.playouts > MAX_PLAYOUTS) {
196 node->u.playouts = MAX_PLAYOUTS;
198 if (node->amaf.playouts > MAX_PLAYOUTS) {
199 node->amaf.playouts = MAX_PLAYOUTS;
202 memcpy(&node->pamaf, &node->amaf, sizeof(node->amaf));
203 memcpy(&node->pu, &node->u, sizeof(node->u));
205 struct tree_node *ni = NULL, *ni_prev = NULL;
206 while (fgetc(f)) {
207 ni_prev = ni; ni = calloc(1, sizeof(*ni));
208 if (!node->children)
209 node->children = ni;
210 else
211 ni_prev->sibling = ni;
212 ni->parent = node;
213 tree_node_load(f, ni, num);
217 void
218 tree_load(struct tree *tree, struct board *b)
220 char *filename = tree_book_name(b);
221 FILE *f = fopen(filename, "rb");
222 if (!f)
223 return;
225 fprintf(stderr, "Loading opening book %s...\n", filename);
227 int num = 0;
228 if (fgetc(f))
229 tree_node_load(f, tree->root, &num);
230 fprintf(stderr, "Loaded %d nodes.\n", num);
232 fclose(f);
236 static struct tree_node *
237 tree_node_copy(struct tree_node *node)
239 struct tree_node *n2 = malloc(sizeof(*n2));
240 *n2 = *node;
241 if (!node->children)
242 return n2;
243 struct tree_node *ni = node->children;
244 struct tree_node *ni2 = tree_node_copy(ni);
245 n2->children = ni2; ni2->parent = n2;
246 while ((ni = ni->sibling)) {
247 ni2->sibling = tree_node_copy(ni);
248 ni2 = ni2->sibling; ni2->parent = n2;
250 return n2;
253 struct tree *
254 tree_copy(struct tree *tree)
256 struct tree *t2 = malloc(sizeof(*t2));
257 *t2 = *tree;
258 t2->root = tree_node_copy(tree->root);
259 return t2;
263 static void
264 tree_node_merge(struct tree_node *dest, struct tree_node *src)
266 /* Do not merge nodes that weren't touched at all. */
267 assert(dest->pamaf.playouts == src->pamaf.playouts);
268 assert(dest->pu.playouts == src->pu.playouts);
269 if (src->amaf.playouts - src->pamaf.playouts == 0
270 && src->u.playouts - src->pu.playouts == 0) {
271 return;
274 dest->hints |= src->hints;
276 /* Merge the children, both are coord-sorted lists. */
277 struct tree_node *di = dest->children, **dref = &dest->children;
278 struct tree_node *si = src->children, **sref = &src->children;
279 while (di && si) {
280 if (di->coord != si->coord) {
281 /* src has some extra items or misses di */
282 struct tree_node *si2 = si->sibling;
283 while (si2 && di->coord != si2->coord) {
284 si2 = si2->sibling;
286 if (!si2)
287 goto next_di; /* src misses di, move on */
288 /* chain the extra [si,si2) items before di */
289 (*dref) = si;
290 while (si->sibling != si2) {
291 si->parent = dest;
292 si = si->sibling;
294 si->parent = dest;
295 si->sibling = di;
296 si = si2;
297 (*sref) = si;
299 /* Matching nodes - recurse... */
300 tree_node_merge(di, si);
301 /* ...and move on. */
302 sref = &si->sibling; si = si->sibling;
303 next_di:
304 dref = &di->sibling; di = di->sibling;
306 if (si) {
307 /* Some outstanding nodes are left on src side, rechain
308 * them to dst. */
309 (*dref) = si;
310 while (si) {
311 si->parent = dest;
312 si = si->sibling;
314 (*sref) = NULL;
317 /* Priors should be constant. */
318 assert(dest->prior.playouts == src->prior.playouts && dest->prior.value == src->prior.value);
320 stats_merge(&dest->amaf, &src->amaf);
321 stats_merge(&dest->u, &src->u);
324 /* Merge two trees built upon the same board. Note that the operation is
325 * destructive on src. */
326 void
327 tree_merge(struct tree *dest, struct tree *src)
329 if (src->max_depth > dest->max_depth)
330 dest->max_depth = src->max_depth;
331 tree_node_merge(dest->root, src->root);
335 static void
336 tree_node_normalize(struct tree_node *node, int factor)
338 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
339 tree_node_normalize(ni, factor);
341 #define normalize(s1, s2, t) node->s2.t = node->s1.t + (node->s2.t - node->s1.t) / factor;
342 normalize(pamaf, amaf, playouts);
343 memcpy(&node->pamaf, &node->amaf, sizeof(node->amaf));
345 normalize(pu, u, playouts);
346 memcpy(&node->pu, &node->u, sizeof(node->u));
347 #undef normalize
350 /* Normalize a tree, dividing the amaf and u values by given
351 * factor; otherwise, simulations run in independent threads
352 * two trees built upon the same board. To correctly handle
353 * results taken from previous simulation run, they are backed
354 * up in tree. */
355 void
356 tree_normalize(struct tree *tree, int factor)
358 tree_node_normalize(tree->root, factor);
362 /* Get a node of given coordinate from within parent, possibly creating it
363 * if necessary - in a very raw form (no .d, priors, ...). */
364 /* FIXME: Adjust for board symmetry. */
365 struct tree_node *
366 tree_get_node(struct tree *t, struct tree_node *parent, coord_t c, bool create)
368 if (!parent->children || parent->children->coord >= c) {
369 /* Special case: Insertion at the beginning. */
370 if (parent->children && parent->children->coord == c)
371 return parent->children;
372 if (!create)
373 return NULL;
375 struct tree_node *nn = tree_init_node(t, c, parent->depth + 1);
376 nn->parent = parent; nn->sibling = parent->children;
377 parent->children = nn;
378 return nn;
381 /* No candidate at the beginning, look through all the children. */
383 struct tree_node *ni;
384 for (ni = parent->children; ni->sibling; ni = ni->sibling)
385 if (ni->sibling->coord >= c)
386 break;
388 if (ni->sibling && ni->sibling->coord == c)
389 return ni->sibling;
390 assert(ni->coord < c);
391 if (!create)
392 return NULL;
394 struct tree_node *nn = tree_init_node(t, c, parent->depth + 1);
395 nn->parent = parent; nn->sibling = ni->sibling; ni->sibling = nn;
396 return nn;
400 /* Tree symmetry: When possible, we will localize the tree to a single part
401 * of the board in tree_expand_node() and possibly flip along symmetry axes
402 * to another part of the board in tree_promote_at(). We follow b->symmetry
403 * guidelines here. */
406 void
407 tree_expand_node(struct tree *t, struct tree_node *node, struct board *b, enum stone color, struct uct *u, int parity)
409 /* Get a Common Fate Graph distance map from parent node. */
410 int distances[board_size2(b)];
411 if (!is_pass(b->last_move.coord) && !is_resign(b->last_move.coord)) {
412 cfg_distances(b, node->coord, distances, TREE_NODE_D_MAX);
413 } else {
414 // Pass or resign - everything is too far.
415 foreach_point(b) { distances[c] = TREE_NODE_D_MAX + 1; } foreach_point_end;
418 /* Get a map of prior values to initialize the new nodes with. */
419 struct prior_map map = {
420 .b = b,
421 .to_play = color,
422 .parity = tree_parity(t, parity),
423 .distances = distances,
425 // Include pass in the prior map.
426 struct move_stats map_prior[board_size2(b) + 1]; map.prior = &map_prior[1];
427 bool map_consider[board_size2(b) + 1]; map.consider = &map_consider[1];
428 memset(map_prior, 0, sizeof(map_prior));
429 memset(map_consider, 0, sizeof(map_consider));
430 struct move pm = { .color = color };
431 map.consider[pass] = true;
432 foreach_point(b) {
433 if (board_at(b, c) != S_NONE)
434 continue;
435 pm.coord = c;
436 if (!board_is_valid_move(b, &pm))
437 continue;
438 map.consider[c] = true;
439 } foreach_point_end;
440 uct_prior(u, node, &map);
442 /* Now, create the nodes. */
443 struct tree_node *ni = tree_init_node(t, pass, node->depth + 1);
444 struct tree_node *first_child = ni;
445 ni->parent = node;
446 ni->prior = map.prior[pass]; ni->d = TREE_NODE_D_MAX + 1;
448 /* The loop considers only the symmetry playground. */
449 if (UDEBUGL(6)) {
450 fprintf(stderr, "expanding %s within [%d,%d],[%d,%d] %d-%d\n",
451 coord2sstr(node->coord, b),
452 b->symmetry.x1, b->symmetry.y1,
453 b->symmetry.x2, b->symmetry.y2,
454 b->symmetry.type, b->symmetry.d);
456 for (int i = b->symmetry.x1; i <= b->symmetry.x2; i++) {
457 for (int j = b->symmetry.y1; j <= b->symmetry.y2; j++) {
458 if (b->symmetry.d) {
459 int x = b->symmetry.type == SYM_DIAG_DOWN ? board_size(b) - 1 - i : i;
460 if (x > j) {
461 if (UDEBUGL(7))
462 fprintf(stderr, "drop %d,%d\n", i, j);
463 continue;
467 coord_t c = coord_xy_otf(i, j, t->board);
468 if (!map.consider[c]) // Filter out invalid moves
469 continue;
470 assert(c != node->coord); // I have spotted "C3 C3" in some sequence...
472 struct tree_node *nj = tree_init_node(t, c, node->depth + 1);
473 nj->parent = node; ni->sibling = nj; ni = nj;
475 ni->prior = map.prior[c];
476 ni->d = distances[c];
479 node->children = first_child; // must be done at the end to avoid race
483 static coord_t
484 flip_coord(struct board *b, coord_t c,
485 bool flip_horiz, bool flip_vert, int flip_diag)
487 int x = coord_x(c, b), y = coord_y(c, b);
488 if (flip_diag) {
489 int z = x; x = y; y = z;
491 if (flip_horiz) {
492 x = board_size(b) - 1 - x;
494 if (flip_vert) {
495 y = board_size(b) - 1 - y;
497 return coord_xy_otf(x, y, b);
500 static void
501 tree_fix_node_symmetry(struct board *b, struct tree_node *node,
502 bool flip_horiz, bool flip_vert, int flip_diag)
504 if (!is_pass(node->coord))
505 node->coord = flip_coord(b, node->coord, flip_horiz, flip_vert, flip_diag);
507 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
508 tree_fix_node_symmetry(b, ni, flip_horiz, flip_vert, flip_diag);
511 static void
512 tree_fix_symmetry(struct tree *tree, struct board *b, coord_t c)
514 if (is_pass(c))
515 return;
517 struct board_symmetry *s = &tree->root_symmetry;
518 int cx = coord_x(c, b), cy = coord_y(c, b);
520 /* playground X->h->v->d normalization
521 * :::.. .d...
522 * .::.. v....
523 * ..:.. .....
524 * ..... h...X
525 * ..... ..... */
526 bool flip_horiz = cx < s->x1 || cx > s->x2;
527 bool flip_vert = cy < s->y1 || cy > s->y2;
529 bool flip_diag = 0;
530 if (s->d) {
531 bool dir = (s->type == SYM_DIAG_DOWN);
532 int x = dir ^ flip_horiz ^ flip_vert ? board_size(b) - 1 - cx : cx;
533 if (flip_vert ? x < cy : x > cy) {
534 flip_diag = 1;
538 if (DEBUGL(4)) {
539 fprintf(stderr, "%s [%d,%d -> %d,%d;%d,%d] will flip %d %d %d -> %s, sym %d (%d) -> %d (%d)\n",
540 coord2sstr(c, b),
541 cx, cy, s->x1, s->y1, s->x2, s->y2,
542 flip_horiz, flip_vert, flip_diag,
543 coord2sstr(flip_coord(b, c, flip_horiz, flip_vert, flip_diag), b),
544 s->type, s->d, b->symmetry.type, b->symmetry.d);
546 if (flip_horiz || flip_vert || flip_diag)
547 tree_fix_node_symmetry(b, tree->root, flip_horiz, flip_vert, flip_diag);
551 static void
552 tree_unlink_node(struct tree_node *node)
554 struct tree_node *ni = node->parent;
555 if (ni->children == node) {
556 ni->children = node->sibling;
557 } else {
558 ni = ni->children;
559 while (ni->sibling != node)
560 ni = ni->sibling;
561 ni->sibling = node->sibling;
563 node->sibling = NULL;
564 node->parent = NULL;
567 void
568 tree_delete_node(struct tree *tree, struct tree_node *node)
570 tree_unlink_node(node);
571 tree_done_node(tree, node);
574 void
575 tree_promote_node(struct tree *tree, struct tree_node *node)
577 assert(node->parent == tree->root);
578 tree_unlink_node(node);
579 tree_done_node(tree, tree->root);
580 tree->root = node;
581 tree->root_color = stone_other(tree->root_color);
582 board_symmetry_update(tree->board, &tree->root_symmetry, node->coord);
583 tree->max_depth--;
584 if (tree->chchvals) { free(tree->chchvals); tree->chchvals = NULL; }
585 if (tree->chvals) { free(tree->chvals); tree->chvals = NULL; }
588 bool
589 tree_promote_at(struct tree *tree, struct board *b, coord_t c)
591 tree_fix_symmetry(tree, b, c);
593 for (struct tree_node *ni = tree->root->children; ni; ni = ni->sibling) {
594 if (ni->coord == c) {
595 tree_promote_node(tree, ni);
596 return true;
599 return false;