Define a memory limit for nodes to avoid crashing later.
[pachi/t.git] / uct / tree.c
blobb431d6b2235e68da5c4353f277756b8263c2f408
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 /* This function may be called by multiple threads in parallel */
22 static struct tree_node *
23 tree_init_node(struct tree *t, coord_t coord, int depth)
25 struct tree_node *n = calloc(1, sizeof(*n));
26 if (!n) {
27 fprintf(stderr, "tree_init_node(): OUT OF MEMORY\n");
28 exit(1);
30 __sync_fetch_and_add(&t->node_sizes, sizeof(*n));
31 n->coord = coord;
32 n->depth = depth;
33 volatile static long c = 1000000;
34 n->hash = __sync_fetch_and_add(&c, 1);
35 if (depth > t->max_depth)
36 t->max_depth = depth;
37 return n;
40 struct tree *
41 tree_init(struct board *board, enum stone color)
43 struct tree *t = calloc(1, sizeof(*t));
44 t->board = board;
45 /* The root PASS move is only virtual, we never play it. */
46 t->root = tree_init_node(t, pass, 0);
47 t->root_symmetry = board->symmetry;
48 t->root_color = stone_other(color); // to research black moves, root will be white
49 return t;
53 static void
54 tree_done_node(struct tree *t, struct tree_node *n)
56 struct tree_node *ni = n->children;
57 while (ni) {
58 struct tree_node *nj = ni->sibling;
59 tree_done_node(t, ni);
60 ni = nj;
62 free(n);
65 void
66 tree_done(struct tree *t)
68 tree_done_node(t, t->root);
69 if (t->chchvals) free(t->chchvals);
70 if (t->chvals) free(t->chvals);
71 free(t);
75 static void
76 tree_node_dump(struct tree *tree, struct tree_node *node, int l, int thres)
78 for (int i = 0; i < l; i++) fputc(' ', stderr);
79 int children = 0;
80 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
81 children++;
82 /* We use 1 as parity, since for all nodes we want to know the
83 * win probability of _us_, not the node color. */
84 fprintf(stderr, "[%s] %f %% %d [prior %f %% %d amaf %f %% %d]; hints %x; %d children <%"PRIhash">\n",
85 coord2sstr(node->coord, tree->board),
86 tree_node_get_value(tree, 1, node->u.value), node->u.playouts,
87 tree_node_get_value(tree, 1, node->prior.value), node->prior.playouts,
88 tree_node_get_value(tree, 1, node->amaf.value), node->amaf.playouts,
89 node->hints, children, node->hash);
91 /* Print nodes sorted by #playouts. */
93 struct tree_node *nbox[1000]; int nboxl = 0;
94 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
95 if (ni->u.playouts > thres)
96 nbox[nboxl++] = ni;
98 while (true) {
99 int best = -1;
100 for (int i = 0; i < nboxl; i++)
101 if (nbox[i] && (best < 0 || nbox[i]->u.playouts > nbox[best]->u.playouts))
102 best = i;
103 if (best < 0)
104 break;
105 tree_node_dump(tree, nbox[best], l + 1, /* node->u.value < 0.1 ? 0 : */ thres);
106 nbox[best] = NULL;
110 void
111 tree_dump_chval(struct tree *tree, struct move_stats *v)
113 for (int y = board_size(tree->board) - 2; y > 1; y--) {
114 for (int x = 1; x < board_size(tree->board) - 1; x++) {
115 coord_t c = coord_xy(tree->board, x, y);
116 fprintf(stderr, "%.2f%%%05d ", v[c].value, v[c].playouts);
118 fprintf(stderr, "\n");
122 void
123 tree_dump(struct tree *tree, int thres)
125 if (thres && tree->root->u.playouts / thres > 100) {
126 /* Be a bit sensible about this; the opening book can create
127 * huge dumps at first. */
128 thres = tree->root->u.playouts / 100 * (thres < 1000 ? 1 : thres / 1000);
130 fprintf(stderr, "(UCT tree; root %s; extra komi %f)\n",
131 stone2str(tree->root_color), tree->extra_komi);
132 tree_node_dump(tree, tree->root, 0, thres);
134 if (DEBUGL(3) && tree->chvals) {
135 fprintf(stderr, "children stats:\n");
136 tree_dump_chval(tree, tree->chvals);
137 fprintf(stderr, "grandchildren stats:\n");
138 tree_dump_chval(tree, tree->chchvals);
143 static char *
144 tree_book_name(struct board *b)
146 static char buf[256];
147 if (b->handicap > 0) {
148 sprintf(buf, "uctbook-%d-%02.01f-h%d.pachitree", b->size - 2, b->komi, b->handicap);
149 } else {
150 sprintf(buf, "uctbook-%d-%02.01f.pachitree", b->size - 2, b->komi);
152 return buf;
155 static void
156 tree_node_save(FILE *f, struct tree_node *node, int thres)
158 fputc(1, f);
159 fwrite(((void *) node) + offsetof(struct tree_node, depth),
160 sizeof(struct tree_node) - offsetof(struct tree_node, depth),
161 1, f);
163 if (node->u.playouts >= thres)
164 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
165 tree_node_save(f, ni, thres);
167 fputc(0, f);
170 void
171 tree_save(struct tree *tree, struct board *b, int thres)
173 char *filename = tree_book_name(b);
174 FILE *f = fopen(filename, "wb");
175 if (!f) {
176 perror("fopen");
177 return;
179 tree_node_save(f, tree->root, thres);
180 fputc(0, f);
181 fclose(f);
185 void
186 tree_node_load(FILE *f, struct tree_node *node, int *num)
188 (*num)++;
190 fread(((void *) node) + offsetof(struct tree_node, depth),
191 sizeof(struct tree_node) - offsetof(struct tree_node, depth),
192 1, f);
194 /* Keep values in sane scale, otherwise we start overflowing. */
195 #define MAX_PLAYOUTS 10000000
196 if (node->u.playouts > MAX_PLAYOUTS) {
197 node->u.playouts = MAX_PLAYOUTS;
199 if (node->amaf.playouts > MAX_PLAYOUTS) {
200 node->amaf.playouts = MAX_PLAYOUTS;
203 memcpy(&node->pamaf, &node->amaf, sizeof(node->amaf));
204 memcpy(&node->pu, &node->u, sizeof(node->u));
206 struct tree_node *ni = NULL, *ni_prev = NULL;
207 while (fgetc(f)) {
208 ni_prev = ni; ni = calloc(1, sizeof(*ni));
209 if (!node->children)
210 node->children = ni;
211 else
212 ni_prev->sibling = ni;
213 ni->parent = node;
214 tree_node_load(f, ni, num);
218 void
219 tree_load(struct tree *tree, struct board *b)
221 char *filename = tree_book_name(b);
222 FILE *f = fopen(filename, "rb");
223 if (!f)
224 return;
226 fprintf(stderr, "Loading opening book %s...\n", filename);
228 int num = 0;
229 if (fgetc(f))
230 tree_node_load(f, tree->root, &num);
231 fprintf(stderr, "Loaded %d nodes.\n", num);
233 fclose(f);
237 static struct tree_node *
238 tree_node_copy(struct tree_node *node)
240 struct tree_node *n2 = malloc(sizeof(*n2));
241 *n2 = *node;
242 if (!node->children)
243 return n2;
244 struct tree_node *ni = node->children;
245 struct tree_node *ni2 = tree_node_copy(ni);
246 n2->children = ni2; ni2->parent = n2;
247 while ((ni = ni->sibling)) {
248 ni2->sibling = tree_node_copy(ni);
249 ni2 = ni2->sibling; ni2->parent = n2;
251 return n2;
254 struct tree *
255 tree_copy(struct tree *tree)
257 struct tree *t2 = malloc(sizeof(*t2));
258 *t2 = *tree;
259 t2->root = tree_node_copy(tree->root);
260 return t2;
264 static void
265 tree_node_merge(struct tree_node *dest, struct tree_node *src)
267 /* Do not merge nodes that weren't touched at all. */
268 assert(dest->pamaf.playouts == src->pamaf.playouts);
269 assert(dest->pu.playouts == src->pu.playouts);
270 if (src->amaf.playouts - src->pamaf.playouts == 0
271 && src->u.playouts - src->pu.playouts == 0) {
272 return;
275 dest->hints |= src->hints;
277 /* Merge the children, both are coord-sorted lists. */
278 struct tree_node *di = dest->children, **dref = &dest->children;
279 struct tree_node *si = src->children, **sref = &src->children;
280 while (di && si) {
281 if (di->coord != si->coord) {
282 /* src has some extra items or misses di */
283 struct tree_node *si2 = si->sibling;
284 while (si2 && di->coord != si2->coord) {
285 si2 = si2->sibling;
287 if (!si2)
288 goto next_di; /* src misses di, move on */
289 /* chain the extra [si,si2) items before di */
290 (*dref) = si;
291 while (si->sibling != si2) {
292 si->parent = dest;
293 si = si->sibling;
295 si->parent = dest;
296 si->sibling = di;
297 si = si2;
298 (*sref) = si;
300 /* Matching nodes - recurse... */
301 tree_node_merge(di, si);
302 /* ...and move on. */
303 sref = &si->sibling; si = si->sibling;
304 next_di:
305 dref = &di->sibling; di = di->sibling;
307 if (si) {
308 /* Some outstanding nodes are left on src side, rechain
309 * them to dst. */
310 (*dref) = si;
311 while (si) {
312 si->parent = dest;
313 si = si->sibling;
315 (*sref) = NULL;
318 /* Priors should be constant. */
319 assert(dest->prior.playouts == src->prior.playouts && dest->prior.value == src->prior.value);
321 stats_merge(&dest->amaf, &src->amaf);
322 stats_merge(&dest->u, &src->u);
325 /* Merge two trees built upon the same board. Note that the operation is
326 * destructive on src. */
327 void
328 tree_merge(struct tree *dest, struct tree *src)
330 if (src->max_depth > dest->max_depth)
331 dest->max_depth = src->max_depth;
332 tree_node_merge(dest->root, src->root);
336 static void
337 tree_node_normalize(struct tree_node *node, int factor)
339 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
340 tree_node_normalize(ni, factor);
342 #define normalize(s1, s2, t) node->s2.t = node->s1.t + (node->s2.t - node->s1.t) / factor;
343 normalize(pamaf, amaf, playouts);
344 memcpy(&node->pamaf, &node->amaf, sizeof(node->amaf));
346 normalize(pu, u, playouts);
347 memcpy(&node->pu, &node->u, sizeof(node->u));
348 #undef normalize
351 /* Normalize a tree, dividing the amaf and u values by given
352 * factor; otherwise, simulations run in independent threads
353 * two trees built upon the same board. To correctly handle
354 * results taken from previous simulation run, they are backed
355 * up in tree. */
356 void
357 tree_normalize(struct tree *tree, int factor)
359 tree_node_normalize(tree->root, factor);
363 /* Get a node of given coordinate from within parent, possibly creating it
364 * if necessary - in a very raw form (no .d, priors, ...). */
365 /* FIXME: Adjust for board symmetry. */
366 struct tree_node *
367 tree_get_node(struct tree *t, struct tree_node *parent, coord_t c, bool create)
369 if (!parent->children || parent->children->coord >= c) {
370 /* Special case: Insertion at the beginning. */
371 if (parent->children && parent->children->coord == c)
372 return parent->children;
373 if (!create)
374 return NULL;
376 struct tree_node *nn = tree_init_node(t, c, parent->depth + 1);
377 nn->parent = parent; nn->sibling = parent->children;
378 parent->children = nn;
379 return nn;
382 /* No candidate at the beginning, look through all the children. */
384 struct tree_node *ni;
385 for (ni = parent->children; ni->sibling; ni = ni->sibling)
386 if (ni->sibling->coord >= c)
387 break;
389 if (ni->sibling && ni->sibling->coord == c)
390 return ni->sibling;
391 assert(ni->coord < c);
392 if (!create)
393 return NULL;
395 struct tree_node *nn = tree_init_node(t, c, parent->depth + 1);
396 nn->parent = parent; nn->sibling = ni->sibling; ni->sibling = nn;
397 return nn;
401 /* Tree symmetry: When possible, we will localize the tree to a single part
402 * of the board in tree_expand_node() and possibly flip along symmetry axes
403 * to another part of the board in tree_promote_at(). We follow b->symmetry
404 * guidelines here. */
407 void
408 tree_expand_node(struct tree *t, struct tree_node *node, struct board *b, enum stone color, struct uct *u, int parity)
410 /* Get a Common Fate Graph distance map from parent node. */
411 int distances[board_size2(b)];
412 if (!is_pass(b->last_move.coord) && !is_resign(b->last_move.coord)) {
413 cfg_distances(b, node->coord, distances, TREE_NODE_D_MAX);
414 } else {
415 // Pass or resign - everything is too far.
416 foreach_point(b) { distances[c] = TREE_NODE_D_MAX + 1; } foreach_point_end;
419 /* Get a map of prior values to initialize the new nodes with. */
420 struct prior_map map = {
421 .b = b,
422 .to_play = color,
423 .parity = tree_parity(t, parity),
424 .distances = distances,
426 // Include pass in the prior map.
427 struct move_stats map_prior[board_size2(b) + 1]; map.prior = &map_prior[1];
428 bool map_consider[board_size2(b) + 1]; map.consider = &map_consider[1];
429 memset(map_prior, 0, sizeof(map_prior));
430 memset(map_consider, 0, sizeof(map_consider));
431 struct move pm = { .color = color };
432 map.consider[pass] = true;
433 foreach_point(b) {
434 if (board_at(b, c) != S_NONE)
435 continue;
436 pm.coord = c;
437 if (!board_is_valid_move(b, &pm))
438 continue;
439 map.consider[c] = true;
440 } foreach_point_end;
441 uct_prior(u, node, &map);
443 /* Now, create the nodes. */
444 struct tree_node *ni = tree_init_node(t, pass, node->depth + 1);
445 struct tree_node *first_child = ni;
446 ni->parent = node;
447 ni->prior = map.prior[pass]; ni->d = TREE_NODE_D_MAX + 1;
449 /* The loop considers only the symmetry playground. */
450 if (UDEBUGL(6)) {
451 fprintf(stderr, "expanding %s within [%d,%d],[%d,%d] %d-%d\n",
452 coord2sstr(node->coord, b),
453 b->symmetry.x1, b->symmetry.y1,
454 b->symmetry.x2, b->symmetry.y2,
455 b->symmetry.type, b->symmetry.d);
457 for (int i = b->symmetry.x1; i <= b->symmetry.x2; i++) {
458 for (int j = b->symmetry.y1; j <= b->symmetry.y2; j++) {
459 if (b->symmetry.d) {
460 int x = b->symmetry.type == SYM_DIAG_DOWN ? board_size(b) - 1 - i : i;
461 if (x > j) {
462 if (UDEBUGL(7))
463 fprintf(stderr, "drop %d,%d\n", i, j);
464 continue;
468 coord_t c = coord_xy_otf(i, j, t->board);
469 if (!map.consider[c]) // Filter out invalid moves
470 continue;
471 assert(c != node->coord); // I have spotted "C3 C3" in some sequence...
473 struct tree_node *nj = tree_init_node(t, c, node->depth + 1);
474 nj->parent = node; ni->sibling = nj; ni = nj;
476 ni->prior = map.prior[c];
477 ni->d = distances[c];
480 node->children = first_child; // must be done at the end to avoid race
484 static coord_t
485 flip_coord(struct board *b, coord_t c,
486 bool flip_horiz, bool flip_vert, int flip_diag)
488 int x = coord_x(c, b), y = coord_y(c, b);
489 if (flip_diag) {
490 int z = x; x = y; y = z;
492 if (flip_horiz) {
493 x = board_size(b) - 1 - x;
495 if (flip_vert) {
496 y = board_size(b) - 1 - y;
498 return coord_xy_otf(x, y, b);
501 static void
502 tree_fix_node_symmetry(struct board *b, struct tree_node *node,
503 bool flip_horiz, bool flip_vert, int flip_diag)
505 if (!is_pass(node->coord))
506 node->coord = flip_coord(b, node->coord, flip_horiz, flip_vert, flip_diag);
508 for (struct tree_node *ni = node->children; ni; ni = ni->sibling)
509 tree_fix_node_symmetry(b, ni, flip_horiz, flip_vert, flip_diag);
512 static void
513 tree_fix_symmetry(struct tree *tree, struct board *b, coord_t c)
515 if (is_pass(c))
516 return;
518 struct board_symmetry *s = &tree->root_symmetry;
519 int cx = coord_x(c, b), cy = coord_y(c, b);
521 /* playground X->h->v->d normalization
522 * :::.. .d...
523 * .::.. v....
524 * ..:.. .....
525 * ..... h...X
526 * ..... ..... */
527 bool flip_horiz = cx < s->x1 || cx > s->x2;
528 bool flip_vert = cy < s->y1 || cy > s->y2;
530 bool flip_diag = 0;
531 if (s->d) {
532 bool dir = (s->type == SYM_DIAG_DOWN);
533 int x = dir ^ flip_horiz ^ flip_vert ? board_size(b) - 1 - cx : cx;
534 if (flip_vert ? x < cy : x > cy) {
535 flip_diag = 1;
539 if (DEBUGL(4)) {
540 fprintf(stderr, "%s [%d,%d -> %d,%d;%d,%d] will flip %d %d %d -> %s, sym %d (%d) -> %d (%d)\n",
541 coord2sstr(c, b),
542 cx, cy, s->x1, s->y1, s->x2, s->y2,
543 flip_horiz, flip_vert, flip_diag,
544 coord2sstr(flip_coord(b, c, flip_horiz, flip_vert, flip_diag), b),
545 s->type, s->d, b->symmetry.type, b->symmetry.d);
547 if (flip_horiz || flip_vert || flip_diag)
548 tree_fix_node_symmetry(b, tree->root, flip_horiz, flip_vert, flip_diag);
552 static void
553 tree_unlink_node(struct tree_node *node)
555 struct tree_node *ni = node->parent;
556 if (ni->children == node) {
557 ni->children = node->sibling;
558 } else {
559 ni = ni->children;
560 while (ni->sibling != node)
561 ni = ni->sibling;
562 ni->sibling = node->sibling;
564 node->sibling = NULL;
565 node->parent = NULL;
568 void
569 tree_delete_node(struct tree *tree, struct tree_node *node)
571 tree_unlink_node(node);
572 tree_done_node(tree, node);
575 void
576 tree_promote_node(struct tree *tree, struct tree_node *node)
578 assert(node->parent == tree->root);
579 tree_unlink_node(node);
580 tree_done_node(tree, tree->root);
581 tree->root = node;
582 tree->root_color = stone_other(tree->root_color);
583 board_symmetry_update(tree->board, &tree->root_symmetry, node->coord);
584 tree->max_depth--;
585 if (tree->chchvals) { free(tree->chchvals); tree->chchvals = NULL; }
586 if (tree->chvals) { free(tree->chvals); tree->chvals = NULL; }
589 bool
590 tree_promote_at(struct tree *tree, struct board *b, coord_t c)
592 tree_fix_symmetry(tree, b, c);
594 for (struct tree_node *ni = tree->root->children; ni; ni = ni->sibling) {
595 if (ni->coord == c) {
596 tree_promote_node(tree, ni);
597 return true;
600 return false;