uct_playout_hook(): Fix board_is_valid_play() parameter order
[pachi.git] / uct / walk.c
blobba22b06370567f11fbfb339294beec84b6751b2a
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 (u->treepool_chance[mode] > fast_random(100) && upc->treepool[color - 1]) {
184 assert(upc->treepool_n[color - 1] > 0);
185 coord_t treepool_move = upc->treepool[color - 1][fast_random(upc->treepool_n[color - 1])];
186 if (board_is_valid_play(b, color, treepool_move))
187 return treepool_move;
189 return pass;
192 static coord_t
193 uct_playout_prepolicy(struct playout_policy *playout, struct playout_setup *setup, struct board *b, enum stone color)
195 return uct_playout_hook(playout, setup, b, color, 0);
198 static coord_t
199 uct_playout_postpolicy(struct playout_policy *playout, struct playout_setup *setup, struct board *b, enum stone color)
201 return uct_playout_hook(playout, setup, b, color, 1);
204 double
205 treepool_node_value(struct uct *u, struct tree *tree, int parity, struct tree_node *node)
207 /* XXX: Playouts get cast to double */
208 switch (u->treepool_type) {
209 case UTT_RAVE_PLAYOUTS:
210 return node->amaf.playouts;
211 case UTT_RAVE_VALUE:
212 return tree_node_get_value(tree, parity, node->amaf.value);
213 case UTT_UCT_PLAYOUTS:
214 return node->u.playouts;
215 case UTT_UCT_VALUE:
216 return tree_node_get_value(tree, parity, node->u.value);
217 case UTT_EVALUATE:
219 struct uct_descent d = { .node = node };
220 assert(u->policy->evaluate);
221 return u->policy->evaluate(u->policy, tree, &d, parity);
223 default: assert(0);
225 return -1;
228 static void
229 treepool_setup(struct uct_playout_callback *upc, struct tree_node *node, int color)
231 struct uct *u = upc->uct;
232 int parity = ((node->depth ^ upc->tree->root->depth) & 1) ? -1 : 1;
234 /* XXX: Naive O(N^2) way. */
235 for (int i = 0; i < u->treepool_size; i++) {
236 /* For each item, find the highest
237 * node not in the pool yet. */
238 struct tree_node *best = NULL;
239 double best_val = -1;
241 // first comes pass which we skip
242 for (struct tree_node *ni = node->children->sibling; ni; ni = ni->sibling) {
243 /* Do we already have it? */
244 bool have = false;
245 for (int j = 0; j < upc->treepool_n[color]; j++)
246 if (upc->treepool[color][j] == ni->coord) {
247 have = true;
248 break;
250 if (have)
251 continue;
253 double i_val = treepool_node_value(u, upc->tree, parity, ni);
254 if (i_val > best_val) {
255 best = node;
256 best_val = i_val;
260 if (!best) break;
261 upc->treepool[color][upc->treepool_n[color]++] = best->coord;
266 static int
267 uct_leaf_node(struct uct *u, struct board *b, enum stone player_color,
268 struct playout_amafmap *amaf, struct uct_descent *descent,
269 struct tree *t, struct tree_node *n, enum stone node_color,
270 char *spaces)
272 enum stone next_color = stone_other(node_color);
273 int parity = (next_color == player_color ? 1 : -1);
275 /* We need to make sure only one thread expands the node. If
276 * we are unlucky enough for two threads to meet in the same
277 * node, the latter one will simply do another simulation from
278 * the node itself, no big deal. t->nodes_size may exceed
279 * the maximum in multi-threaded case but not by much so it's ok.
280 * The size test must be before the test&set not after, to allow
281 * expansion of the node later if enough nodes have been freed. */
282 if (n->u.playouts >= u->expand_p && t->nodes_size < u->max_tree_size
283 && !__sync_lock_test_and_set(&n->is_expanded, 1)) {
284 tree_expand_node(t, n, b, next_color, u, parity);
286 if (UDEBUGL(7))
287 fprintf(stderr, "%s*-- UCT playout #%d start [%s] %f\n",
288 spaces, n->u.playouts, coord2sstr(n->coord, t->board),
289 tree_node_get_value(t, parity, n->u.value));
291 struct uct_playout_callback upc = {
292 .uct = u,
293 .tree = t,
294 /* TODO: Don't necessarily restart the sequence walk when
295 * entering playout. */
296 .lnode = NULL,
299 if (u->local_tree_playout) {
300 /* N.B.: We know this is ELO playout. */
301 playout_elo_callback(u->playout, uct_playout_probdist, &upc);
304 coord_t pool[2][u->treepool_size];
305 if (u->treepool_chance[0] + u->treepool_chance[1] > 0) {
306 for (int color = 0; color < 2; color++) {
307 /* Prepare tree-based pool of moves to try forcing
308 * during the playout. */
309 /* We consider the children of the last significant
310 * node, picking top N choices. */
311 struct tree_node *n = descent->significant[color];
312 if (!n || !n->children || !n->children->sibling) {
313 /* No significant node, or it's childless or has
314 * only pass as its child. */
315 upc.treepool[color] = NULL;
316 upc.treepool_n[color] = 0;
317 } else {
318 upc.treepool[color] = (coord_t *) &pool[color];
319 treepool_setup(&upc, n, color);
324 struct playout_setup ps = {
325 .gamelen = u->gamelen,
326 .mercymin = u->mercymin,
327 .prepolicy_hook = uct_playout_prepolicy,
328 .postpolicy_hook = uct_playout_postpolicy,
329 .hook_data = &upc,
331 int result = play_random_game(&ps, b, next_color,
332 u->playout_amaf ? amaf : NULL,
333 &u->ownermap, u->playout);
334 if (next_color == S_WHITE) {
335 /* We need the result from black's perspective. */
336 result = - result;
338 if (UDEBUGL(7))
339 fprintf(stderr, "%s -- [%d..%d] %s random playout result %d\n",
340 spaces, player_color, next_color, coord2sstr(n->coord, t->board), result);
342 return result;
345 static float
346 scale_value(struct uct *u, struct board *b, int result)
348 float rval = result > 0;
349 if (u->val_scale) {
350 int vp = u->val_points;
351 if (!vp) {
352 vp = board_size(b) - 1; vp *= vp; vp *= 2;
355 float sval = (float) abs(result) / vp;
356 sval = sval > 1 ? 1 : sval;
357 if (result < 0) sval = 1 - sval;
358 if (u->val_extra)
359 rval += u->val_scale * sval;
360 else
361 rval = (1 - u->val_scale) * rval + u->val_scale * sval;
362 // fprintf(stderr, "score %d => sval %f, rval %f\n", result, sval, rval);
364 return rval;
367 static void
368 record_local_sequence(struct uct *u, struct tree *t,
369 struct uct_descent *descent, int dlen, int di,
370 enum stone seq_color, float rval)
372 /* Ignore pass sequences. */
373 if (is_pass(descent[di].node->coord))
374 return;
376 #define LTREE_DEBUG if (UDEBUGL(6))
377 LTREE_DEBUG fprintf(stderr, "recording result %f in local %s sequence: ",
378 rval, stone2str(seq_color));
379 int di0 = di;
381 /* Pick the right local tree root... */
382 struct tree_node *lnode = seq_color == S_BLACK ? t->ltree_black : t->ltree_white;
383 lnode->u.playouts++;
385 /* ...and record the sequence. */
386 while (di < dlen && (di == di0 || descent[di].node->d < u->tenuki_d)) {
387 LTREE_DEBUG fprintf(stderr, "%s[%d] ",
388 coord2sstr(descent[di].node->coord, t->board),
389 descent[di].node->d);
390 lnode = tree_get_node(t, lnode, descent[di++].node->coord, true);
391 assert(lnode);
392 stats_add_result(&lnode->u, rval, 1);
395 /* Add lnode for tenuki (pass) if we descended further. */
396 if (di < dlen) {
397 LTREE_DEBUG fprintf(stderr, "pass ");
398 lnode = tree_get_node(t, lnode, pass, true);
399 assert(lnode);
400 stats_add_result(&lnode->u, rval, 1);
403 LTREE_DEBUG fprintf(stderr, "\n");
408 uct_playout(struct uct *u, struct board *b, enum stone player_color, struct tree *t)
410 struct board b2;
411 board_copy(&b2, b);
413 struct playout_amafmap *amaf = NULL;
414 if (u->policy->wants_amaf) {
415 amaf = calloc2(1, sizeof(*amaf));
416 amaf->map = calloc2(board_size2(&b2) + 1, sizeof(*amaf->map));
417 amaf->map++; // -1 is pass
420 /* Walk the tree until we find a leaf, then expand it and do
421 * a random playout. */
422 struct tree_node *n = t->root;
423 enum stone node_color = stone_other(player_color);
424 assert(node_color == t->root_color);
426 /* Tree descent history. */
427 /* XXX: This is somewhat messy since @n and descent[dlen-1].node are
428 * redundant. */
429 #define DLEN 512
430 struct uct_descent descent[DLEN];
431 descent[0].node = n; descent[0].lnode = NULL;
432 descent[0].significant[0] = descent[0].significant[1] = NULL;
433 int dlen = 1;
434 /* Total value of the sequence. */
435 struct move_stats seq_value = { .playouts = 0 };
437 int result;
438 int pass_limit = (board_size(&b2) - 2) * (board_size(&b2) - 2) / 2;
439 int passes = is_pass(b->last_move.coord) && b->moves > 0;
441 /* debug */
442 int depth = 0;
443 static char spaces[] = "\0 ";
444 /* /debug */
445 if (UDEBUGL(8))
446 fprintf(stderr, "--- UCT walk with color %d\n", player_color);
448 while (!tree_leaf_node(n) && passes < 2) {
449 spaces[depth++] = ' '; spaces[depth] = 0;
452 /*** Choose a node to descend to: */
454 /* Parity is chosen already according to the child color, since
455 * it is applied to children. */
456 node_color = stone_other(node_color);
457 int parity = (node_color == player_color ? 1 : -1);
459 assert(dlen < DLEN);
460 descent[dlen] = descent[dlen - 1];
461 if (u->local_tree && (!descent[dlen].lnode || descent[dlen].node->d >= u->tenuki_d)) {
462 /* Start new local sequence. */
463 /* Remember that node_color already holds color of the
464 * to-be-found child. */
465 descent[dlen].lnode = node_color == S_BLACK ? t->ltree_black : t->ltree_white;
468 if (!u->random_policy_chance || fast_random(u->random_policy_chance))
469 u->policy->descend(u->policy, t, &descent[dlen], parity, b2.moves > pass_limit);
470 else
471 u->random_policy->descend(u->random_policy, t, &descent[dlen], parity, b2.moves > pass_limit);
474 /*** Perform the descent: */
476 if (descent[dlen].node->u.playouts >= u->significant_threshold) {
477 descent[dlen].significant[node_color - 1] = n;
480 seq_value.playouts += descent[dlen].value.playouts;
481 seq_value.value += descent[dlen].value.value * descent[dlen].value.playouts;
482 n = descent[dlen++].node;
483 assert(n == t->root || n->parent);
484 if (UDEBUGL(7))
485 fprintf(stderr, "%s+-- UCT sent us to [%s:%d] %f\n",
486 spaces, coord2sstr(n->coord, t->board), n->coord,
487 tree_node_get_value(t, parity, n->u.value));
489 /* Add virtual loss if we need to; this is used to discourage
490 * other threads from visiting this node in case of multiple
491 * threads doing the tree search. */
492 if (u->virtual_loss)
493 stats_add_result(&n->u, tree_parity(t, parity) > 0 ? 0 : 1, 1);
495 assert(n->coord >= -1);
496 if (amaf && !is_pass(n->coord))
497 record_amaf_move(amaf, n->coord, node_color);
499 struct move m = { n->coord, node_color };
500 int res = board_play(&b2, &m);
502 if (res < 0 || (!is_pass(m.coord) && !group_at(&b2, m.coord)) /* suicide */
503 || b2.superko_violation) {
504 if (UDEBUGL(4)) {
505 for (struct tree_node *ni = n; ni; ni = ni->parent)
506 fprintf(stderr, "%s<%"PRIhash"> ", coord2sstr(ni->coord, t->board), ni->hash);
507 fprintf(stderr, "marking invalid %s node %d,%d res %d group %d spk %d\n",
508 stone2str(node_color), coord_x(n->coord,b), coord_y(n->coord,b),
509 res, group_at(&b2, m.coord), b2.superko_violation);
511 n->hints |= TREE_HINT_INVALID;
512 result = 0;
513 goto end;
516 if (is_pass(n->coord))
517 passes++;
518 else
519 passes = 0;
522 if (amaf) {
523 amaf->game_baselen = amaf->gamelen;
524 amaf->record_nakade = u->playout_amaf_nakade;
527 if (t->use_extra_komi && u->dynkomi->persim) {
528 b2.komi += round(u->dynkomi->persim(u->dynkomi, &b2, t, n));
531 if (passes >= 2) {
532 /* XXX: No dead groups support. */
533 float score = board_official_score(&b2, NULL);
534 /* Result from black's perspective (no matter who
535 * the player; black's perspective is always
536 * what the tree stores. */
537 result = - (score * 2);
539 if (UDEBUGL(5))
540 fprintf(stderr, "[%d..%d] %s p-p scoring playout result %d (W %f)\n",
541 player_color, node_color, coord2sstr(n->coord, t->board), result, score);
542 if (UDEBUGL(6))
543 board_print(&b2, stderr);
545 board_ownermap_fill(&u->ownermap, &b2);
547 } else { // assert(tree_leaf_node(n));
548 /* In case of parallel tree search, the assertion might
549 * not hold if two threads chew on the same node. */
550 result = uct_leaf_node(u, &b2, player_color, amaf, &descent[dlen - 1], t, n, node_color, spaces);
553 if (amaf && u->playout_amaf_cutoff) {
554 unsigned int cutoff = amaf->game_baselen;
555 cutoff += (amaf->gamelen - amaf->game_baselen) * u->playout_amaf_cutoff / 100;
556 /* Now, reconstruct the amaf map. */
557 memset(amaf->map, 0, board_size2(&b2) * sizeof(*amaf->map));
558 for (unsigned int i = 0; i < cutoff; i++) {
559 coord_t coord = amaf->game[i].coord;
560 enum stone color = amaf->game[i].color;
561 if (amaf->map[coord] == S_NONE || amaf->map[coord] == color) {
562 amaf->map[coord] = color;
563 /* Nakade always recorded for in-tree part */
564 } else if (amaf->record_nakade || i <= amaf->game_baselen) {
565 amaf_op(amaf->map[n->coord], +);
570 assert(n == t->root || n->parent);
571 if (result != 0) {
572 float rval = scale_value(u, b, result);
573 u->policy->update(u->policy, t, n, node_color, player_color, amaf, rval);
575 if (t->use_extra_komi) {
576 stats_add_result(&u->dynkomi->score, result / 2, 1);
577 stats_add_result(&u->dynkomi->value, rval, 1);
580 if (u->local_tree && n->parent && !is_pass(n->coord) && dlen > 0) {
581 /* Possibly transform the rval appropriately. */
582 float expval = seq_value.value / seq_value.playouts;
583 rval = stats_temper_value(rval, expval, u->local_tree);
585 /* Get the local sequences and record them in ltree. */
586 /* We will look for sequence starts in our descent
587 * history, then run record_local_sequence() for each
588 * found sequence start; record_local_sequence() may
589 * pick longer sequences from descent history then,
590 * which is expected as it will create new lnodes. */
591 enum stone seq_color = player_color;
592 /* First move always starts a sequence. */
593 record_local_sequence(u, t, descent, dlen, 1, seq_color, rval);
594 seq_color = stone_other(seq_color);
595 for (int dseqi = 2; dseqi < dlen; dseqi++, seq_color = stone_other(seq_color)) {
596 if (u->local_tree_allseq) {
597 /* We are configured to record all subsequences. */
598 record_local_sequence(u, t, descent, dlen, dseqi, seq_color, rval);
599 continue;
601 if (descent[dseqi].node->d >= u->tenuki_d) {
602 /* Tenuki! Record the fresh sequence. */
603 record_local_sequence(u, t, descent, dlen, dseqi, seq_color, rval);
604 continue;
606 if (descent[dseqi].lnode && !descent[dseqi].lnode) {
607 /* Record result for in-descent picked sequence. */
608 record_local_sequence(u, t, descent, dlen, dseqi, seq_color, rval);
609 continue;
615 end:
616 /* We need to undo the virtual loss we added during descend. */
617 if (u->virtual_loss) {
618 int parity = (node_color == player_color ? 1 : -1);
619 for (; n->parent; n = n->parent) {
620 stats_rm_result(&n->u, tree_parity(t, parity) > 0 ? 0 : 1, 1);
621 parity = -parity;
625 if (amaf) {
626 free(amaf->map - 1);
627 free(amaf);
629 board_done_noalloc(&b2);
630 return result;
634 uct_playouts(struct uct *u, struct board *b, enum stone color, struct tree *t, struct time_info *ti)
636 int i;
637 if (ti && ti->dim == TD_GAMES) {
638 for (i = 0; t->root->u.playouts <= ti->len.games; i++)
639 uct_playout(u, b, color, t);
640 } else {
641 for (i = 0; !uct_halt; i++)
642 uct_playout(u, b, color, t);
644 return i;