fast_frandom() always returns float, not floating_t
[pachi/t.git] / uct / walk.c
blob9d338b4b370a0c2626c6e3425709492b98874dc9
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 "probdist.h"
16 #include "random.h"
17 #include "tactics/util.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 #define DESCENT_DLEN 512
28 void
29 uct_progress_text(struct uct *u, struct tree *t, enum stone color, int playouts)
31 if (!UDEBUGL(0))
32 return;
34 /* Best move */
35 struct tree_node *best = u->policy->choose(u->policy, t->root, t->board, color, resign);
36 if (!best) {
37 fprintf(stderr, "... No moves left\n");
38 return;
40 fprintf(stderr, "[%d] ", playouts);
41 fprintf(stderr, "best %f ", tree_node_get_value(t, 1, best->u.value));
43 /* Dynamic komi */
44 if (t->use_extra_komi)
45 fprintf(stderr, "komi %.1f ", t->extra_komi);
47 /* Best sequence */
48 fprintf(stderr, "| seq ");
49 for (int depth = 0; depth < 4; depth++) {
50 if (best && best->u.playouts >= 25) {
51 fprintf(stderr, "%3s ", coord2sstr(node_coord(best), t->board));
52 best = u->policy->choose(u->policy, best, t->board, color, resign);
53 } else {
54 fprintf(stderr, " ");
58 /* Best candidates */
59 fprintf(stderr, "| can ");
60 int cans = 4;
61 struct tree_node *can[cans];
62 memset(can, 0, sizeof(can));
63 best = t->root->children;
64 while (best) {
65 int c = 0;
66 while ((!can[c] || best->u.playouts > can[c]->u.playouts) && ++c < cans);
67 for (int d = 0; d < c; d++) can[d] = can[d + 1];
68 if (c > 0) can[c - 1] = best;
69 best = best->sibling;
71 while (--cans >= 0) {
72 if (can[cans]) {
73 fprintf(stderr, "%3s(%.3f) ",
74 coord2sstr(node_coord(can[cans]), t->board),
75 tree_node_get_value(t, 1, can[cans]->u.value));
76 } else {
77 fprintf(stderr, " ");
81 fprintf(stderr, "\n");
84 void
85 uct_progress_json(struct uct *u, struct tree *t, enum stone color, int playouts, coord_t *final, bool big)
87 /* Prefix indicating JSON line. */
88 fprintf(stderr, "{\"%s\": {", final ? "move" : "frame");
90 /* Plaout count */
91 fprintf(stderr, "\"playouts\": %d", playouts);
93 /* Dynamic komi */
94 if (t->use_extra_komi)
95 fprintf(stderr, ", \"extrakomi\": %.1f", t->extra_komi);
97 if (final) {
98 /* Final move choice */
99 fprintf(stderr, ", \"choice\": {\"%s\"}",
100 coord2sstr(*final, t->board));
101 } else {
102 struct tree_node *best = u->policy->choose(u->policy, t->root, t->board, color, resign);
103 if (best) {
104 /* Best move */
105 fprintf(stderr, ", \"best\": {\"%s\": %f}",
106 coord2sstr(best->coord, t->board),
107 tree_node_get_value(t, 1, best->u.value));
111 /* Best candidates */
112 int cans = 4;
113 struct tree_node *can[cans];
114 memset(can, 0, sizeof(can));
115 struct tree_node *best = t->root->children;
116 while (best) {
117 int c = 0;
118 while ((!can[c] || best->u.playouts > can[c]->u.playouts) && ++c < cans);
119 for (int d = 0; d < c; d++) can[d] = can[d + 1];
120 if (c > 0) can[c - 1] = best;
121 best = best->sibling;
123 fprintf(stderr, ", \"can\": [");
124 while (--cans >= 0) {
125 if (!can[cans]) break;
126 /* Best sequence */
127 fprintf(stderr, "%s[", cans < 3 ? ", " : "");
128 best = can[cans];
129 for (int depth = 0; depth < 4; depth++) {
130 if (!best || best->u.playouts < 25) break;
131 fprintf(stderr, "%s{\"%s\":%.3f}", depth > 0 ? "," : "",
132 coord2sstr(best->coord, t->board),
133 tree_node_get_value(t, 1, best->u.value));
134 best = u->policy->choose(u->policy, best, t->board, color, resign);
136 fprintf(stderr, "]");
138 fprintf(stderr, "]");
140 if (big) {
141 /* Average score. */
142 if (t->avg_score.playouts > 0)
143 fprintf(stderr, ", \"avg\": {\"score\": %.3f}", t->avg_score.value);
144 /* Per-intersection information. */
145 fprintf(stderr, ", \"boards\": {");
146 /* Position coloring information. */
147 fprintf(stderr, "\"colors\": [");
148 int f = 0;
149 foreach_point(t->board) {
150 if (board_at(t->board, c) == S_OFFBOARD) continue;
151 fprintf(stderr, "%s%d", f++ > 0 ? "," : "", board_at(t->board, c));
152 } foreach_point_end;
153 fprintf(stderr, "]");
154 /* Ownership statistics. Value (0..1000) for each possible
155 * point describes likelihood of this point becoming black.
156 * Normally, white rate is 1000-value; exception are possible
157 * seki points, but these should be rare. */
158 fprintf(stderr, ", \"territory\": [");
159 f = 0;
160 foreach_point(t->board) {
161 if (board_at(t->board, c) == S_OFFBOARD) continue;
162 int rate = u->ownermap.map[c][S_BLACK] * 1000 / u->ownermap.playouts;
163 fprintf(stderr, "%s%d", f++ > 0 ? "," : "", rate);
164 } foreach_point_end;
165 fprintf(stderr, "]");
166 fprintf(stderr, "}");
169 fprintf(stderr, "}}\n");
172 void
173 uct_progress_status(struct uct *u, struct tree *t, enum stone color, int playouts, coord_t *final)
175 switch (u->reporting) {
176 case UR_TEXT:
177 uct_progress_text(u, t, color, playouts);
178 break;
179 case UR_JSON:
180 case UR_JSON_BIG:
181 uct_progress_json(u, t, color, playouts, final,
182 u->reporting == UR_JSON_BIG);
183 break;
184 default: assert(0);
189 static inline void
190 record_amaf_move(struct playout_amafmap *amaf, coord_t coord, bool is_ko_capture)
192 assert(amaf->gamelen < MAX_GAMELEN);
193 amaf->is_ko_capture[amaf->gamelen] = is_ko_capture;
194 amaf->game[amaf->gamelen++] = coord;
198 struct uct_playout_callback {
199 struct uct *uct;
200 struct tree *tree;
201 struct tree_node *lnode;
205 static coord_t
206 uct_playout_hook(struct playout_policy *playout, struct playout_setup *setup, struct board *b, enum stone color, int mode)
208 /* XXX: This is used in some non-master branches. */
209 return pass;
212 static coord_t
213 uct_playout_prepolicy(struct playout_policy *playout, struct playout_setup *setup, struct board *b, enum stone color)
215 return uct_playout_hook(playout, setup, b, color, 0);
218 static coord_t
219 uct_playout_postpolicy(struct playout_policy *playout, struct playout_setup *setup, struct board *b, enum stone color)
221 return uct_playout_hook(playout, setup, b, color, 1);
225 static int
226 uct_leaf_node(struct uct *u, struct board *b, enum stone player_color,
227 struct playout_amafmap *amaf,
228 struct uct_descent *descent, int *dlen,
229 struct tree_node *significant[2],
230 struct tree *t, struct tree_node *n, enum stone node_color,
231 char *spaces)
233 enum stone next_color = stone_other(node_color);
234 int parity = (next_color == player_color ? 1 : -1);
236 if (UDEBUGL(7))
237 fprintf(stderr, "%s*-- UCT playout #%d start [%s] %f\n",
238 spaces, n->u.playouts, coord2sstr(node_coord(n), t->board),
239 tree_node_get_value(t, parity, n->u.value));
241 struct uct_playout_callback upc = {
242 .uct = u,
243 .tree = t,
244 /* TODO: Don't necessarily restart the sequence walk when
245 * entering playout. */
246 .lnode = NULL,
249 struct playout_setup ps = {
250 .gamelen = u->gamelen,
251 .mercymin = u->mercymin,
252 .prepolicy_hook = uct_playout_prepolicy,
253 .postpolicy_hook = uct_playout_postpolicy,
254 .hook_data = &upc,
256 int result = play_random_game(&ps, b, next_color,
257 u->playout_amaf ? amaf : NULL,
258 &u->ownermap, u->playout);
259 if (next_color == S_WHITE) {
260 /* We need the result from black's perspective. */
261 result = - result;
263 if (UDEBUGL(7))
264 fprintf(stderr, "%s -- [%d..%d] %s random playout result %d\n",
265 spaces, player_color, next_color, coord2sstr(node_coord(n), t->board), result);
267 return result;
270 static floating_t
271 scale_value(struct uct *u, struct board *b, int result)
273 floating_t rval = result > 0 ? 1.0 : result < 0 ? 0.0 : 0.5;
274 if (u->val_scale && result != 0) {
275 int vp = u->val_points;
276 if (!vp) {
277 vp = board_size(b) - 1; vp *= vp; vp *= 2;
280 floating_t sval = (floating_t) abs(result) / vp;
281 sval = sval > 1 ? 1 : sval;
282 if (result < 0) sval = 1 - sval;
283 if (u->val_extra)
284 rval += u->val_scale * sval;
285 else
286 rval = (1 - u->val_scale) * rval + u->val_scale * sval;
287 // fprintf(stderr, "score %d => sval %f, rval %f\n", result, sval, rval);
289 return rval;
292 static double
293 local_value(struct uct *u, struct board *b, coord_t coord, enum stone color)
295 /* Tactical evaluation of move @coord by color @color, given
296 * simulation end position @b. I.e., a move is tactically good
297 * if the resulting group stays on board until the game end. */
298 /* We can also take into account surrounding stones, e.g. to
299 * encourage taking off external liberties during a semeai. */
300 double val = board_local_value(u->local_tree_neival, b, coord, color);
301 return (color == S_WHITE) ? 1.f - val : val;
304 static void
305 record_local_sequence(struct uct *u, struct tree *t, struct board *endb,
306 struct uct_descent *descent, int dlen, int di,
307 enum stone seq_color)
309 #define LTREE_DEBUG if (UDEBUGL(6))
311 /* Ignore pass sequences. */
312 if (is_pass(node_coord(descent[di].node)))
313 return;
315 LTREE_DEBUG board_print(endb, stderr);
316 LTREE_DEBUG fprintf(stderr, "recording local %s sequence: ",
317 stone2str(seq_color));
319 /* Sequences starting deeper are less relevant in general. */
320 int pval = LTREE_PLAYOUTS_MULTIPLIER;
321 if (u->local_tree && u->local_tree_depth_decay > 0)
322 pval = ((floating_t) pval) / pow(u->local_tree_depth_decay, di - 1);
323 if (!pval) {
324 LTREE_DEBUG fprintf(stderr, "too deep @%d\n", di);
325 return;
328 /* Pick the right local tree root... */
329 struct tree_node *lnode = seq_color == S_BLACK ? t->ltree_black : t->ltree_white;
330 lnode->u.playouts++;
332 /* ...determine the sequence value... */
333 double sval = 0.5;
334 if (u->local_tree_eval != LTE_EACH) {
335 sval = local_value(u, endb, node_coord(descent[di].node), seq_color);
336 LTREE_DEBUG fprintf(stderr, "(goal %s[%s %1.3f][%d]) ",
337 coord2sstr(node_coord(descent[di].node), t->board),
338 stone2str(seq_color), sval, descent[di].node->d);
340 if (u->local_tree_eval == LTE_TOTAL) {
341 int di0 = di;
342 while (di < dlen && (di == di0 || descent[di].node->d < u->tenuki_d)) {
343 enum stone color = (di - di0) % 2 ? stone_other(seq_color) : seq_color;
344 double rval = local_value(u, endb, node_coord(descent[di].node), color);
345 if ((di - di0) % 2)
346 rval = 1 - rval;
347 sval += rval;
348 di++;
350 sval /= (di - di0 + 1);
351 di = di0;
355 /* ...and record the sequence. */
356 int di0 = di;
357 while (di < dlen && !is_pass(node_coord(descent[di].node))
358 && (di == di0 || descent[di].node->d < u->tenuki_d)) {
359 enum stone color = (di - di0) % 2 ? stone_other(seq_color) : seq_color;
360 double rval;
361 if (u->local_tree_eval != LTE_EACH)
362 rval = sval;
363 else
364 rval = local_value(u, endb, node_coord(descent[di].node), color);
365 LTREE_DEBUG fprintf(stderr, "%s[%s %1.3f][%d] ",
366 coord2sstr(node_coord(descent[di].node), t->board),
367 stone2str(color), rval, descent[di].node->d);
368 lnode = tree_get_node(t, lnode, node_coord(descent[di++].node), true);
369 assert(lnode);
370 stats_add_result(&lnode->u, rval, pval);
373 /* Add lnode for tenuki (pass) if we descended further. */
374 if (di < dlen) {
375 double rval = u->local_tree_eval != LTE_EACH ? sval : 0.5;
376 LTREE_DEBUG fprintf(stderr, "pass ");
377 lnode = tree_get_node(t, lnode, pass, true);
378 assert(lnode);
379 stats_add_result(&lnode->u, rval, pval);
382 LTREE_DEBUG fprintf(stderr, "\n");
387 uct_playout(struct uct *u, struct board *b, enum stone player_color, struct tree *t)
389 struct board b2;
390 board_copy(&b2, b);
392 struct playout_amafmap amaf;
393 amaf.gamelen = amaf.game_baselen = 0;
395 /* Walk the tree until we find a leaf, then expand it and do
396 * a random playout. */
397 struct tree_node *n = t->root;
398 enum stone node_color = stone_other(player_color);
399 assert(node_color == t->root_color);
401 /* Make sure the root node is expanded. */
402 if (tree_leaf_node(n) && !__sync_lock_test_and_set(&n->is_expanded, 1))
403 tree_expand_node(t, n, &b2, player_color, u, 1);
405 /* Tree descent history. */
406 /* XXX: This is somewhat messy since @n and descent[dlen-1].node are
407 * redundant. */
408 struct uct_descent descent[DESCENT_DLEN];
409 descent[0].node = n; descent[0].lnode = NULL;
410 int dlen = 1;
411 /* Total value of the sequence. */
412 struct move_stats seq_value = { .playouts = 0 };
413 /* The last "significant" node along the descent (i.e. node
414 * with higher than configured number of playouts). For black
415 * and white. */
416 struct tree_node *significant[2] = { NULL, NULL };
417 if (n->u.playouts >= u->significant_threshold)
418 significant[node_color - 1] = n;
420 int result;
421 int pass_limit = (board_size(&b2) - 2) * (board_size(&b2) - 2) / 2;
422 int passes = is_pass(b->last_move.coord) && b->moves > 0;
424 /* debug */
425 static char spaces[] = "\0 ";
426 /* /debug */
427 if (UDEBUGL(8))
428 fprintf(stderr, "--- UCT walk with color %d\n", player_color);
430 while (!tree_leaf_node(n) && passes < 2) {
431 spaces[dlen - 1] = ' '; spaces[dlen] = 0;
434 /*** Choose a node to descend to: */
436 /* Parity is chosen already according to the child color, since
437 * it is applied to children. */
438 node_color = stone_other(node_color);
439 int parity = (node_color == player_color ? 1 : -1);
441 assert(dlen < DESCENT_DLEN);
442 descent[dlen] = descent[dlen - 1];
443 if (u->local_tree && (!descent[dlen].lnode || descent[dlen].node->d >= u->tenuki_d)) {
444 /* Start new local sequence. */
445 /* Remember that node_color already holds color of the
446 * to-be-found child. */
447 descent[dlen].lnode = node_color == S_BLACK ? t->ltree_black : t->ltree_white;
450 if (!u->random_policy_chance || fast_random(u->random_policy_chance))
451 u->policy->descend(u->policy, t, &descent[dlen], parity, b2.moves > pass_limit);
452 else
453 u->random_policy->descend(u->random_policy, t, &descent[dlen], parity, b2.moves > pass_limit);
456 /*** Perform the descent: */
458 if (descent[dlen].node->u.playouts >= u->significant_threshold) {
459 significant[node_color - 1] = descent[dlen].node;
462 seq_value.playouts += descent[dlen].value.playouts;
463 seq_value.value += descent[dlen].value.value * descent[dlen].value.playouts;
464 n = descent[dlen++].node;
465 assert(n == t->root || n->parent);
466 if (UDEBUGL(7))
467 fprintf(stderr, "%s+-- UCT sent us to [%s:%d] %d,%f\n",
468 spaces, coord2sstr(node_coord(n), t->board),
469 node_coord(n), n->u.playouts,
470 tree_node_get_value(t, parity, n->u.value));
472 /* Add virtual loss if we need to; this is used to discourage
473 * other threads from visiting this node in case of multiple
474 * threads doing the tree search. */
475 if (u->virtual_loss)
476 stats_add_result(&n->u, node_color == S_BLACK ? 0.0 : 1.0, u->virtual_loss);
478 struct move m = { node_coord(n), node_color };
479 int res = board_play(&b2, &m);
481 if (res < 0 || (!is_pass(m.coord) && !group_at(&b2, m.coord)) /* suicide */
482 || b2.superko_violation) {
483 if (UDEBUGL(4)) {
484 for (struct tree_node *ni = n; ni; ni = ni->parent)
485 fprintf(stderr, "%s<%"PRIhash"> ", coord2sstr(node_coord(ni), t->board), ni->hash);
486 fprintf(stderr, "marking invalid %s node %d,%d res %d group %d spk %d\n",
487 stone2str(node_color), coord_x(node_coord(n),b), coord_y(node_coord(n),b),
488 res, group_at(&b2, m.coord), b2.superko_violation);
490 n->hints |= TREE_HINT_INVALID;
491 result = 0;
492 goto end;
495 assert(node_coord(n) >= -1);
496 record_amaf_move(&amaf, node_coord(n), board_playing_ko_threat(&b2));
498 if (is_pass(node_coord(n)))
499 passes++;
500 else
501 passes = 0;
503 enum stone next_color = stone_other(node_color);
504 /* We need to make sure only one thread expands the node. If
505 * we are unlucky enough for two threads to meet in the same
506 * node, the latter one will simply do another simulation from
507 * the node itself, no big deal. t->nodes_size may exceed
508 * the maximum in multi-threaded case but not by much so it's ok.
509 * The size test must be before the test&set not after, to allow
510 * expansion of the node later if enough nodes have been freed. */
511 if (tree_leaf_node(n)
512 && n->u.playouts - u->virtual_loss >= u->expand_p && t->nodes_size < u->max_tree_size
513 && !__sync_lock_test_and_set(&n->is_expanded, 1))
514 tree_expand_node(t, n, &b2, next_color, u, -parity);
517 amaf.game_baselen = amaf.gamelen;
519 if (t->use_extra_komi && u->dynkomi->persim) {
520 b2.komi += round(u->dynkomi->persim(u->dynkomi, &b2, t, n));
523 if (passes >= 2) {
524 /* XXX: No dead groups support. */
525 floating_t score = board_official_score(&b2, NULL);
526 /* Result from black's perspective (no matter who
527 * the player; black's perspective is always
528 * what the tree stores. */
529 result = - (score * 2);
531 if (UDEBUGL(5))
532 fprintf(stderr, "[%d..%d] %s p-p scoring playout result %d (W %f)\n",
533 player_color, node_color, coord2sstr(node_coord(n), t->board), result, score);
534 if (UDEBUGL(6))
535 board_print(&b2, stderr);
537 board_ownermap_fill(&u->ownermap, &b2);
539 } else { // assert(tree_leaf_node(n));
540 /* In case of parallel tree search, the assertion might
541 * not hold if two threads chew on the same node. */
542 result = uct_leaf_node(u, &b2, player_color, &amaf, descent, &dlen, significant, t, n, node_color, spaces);
545 if (u->policy->wants_amaf && u->playout_amaf_cutoff) {
546 unsigned int cutoff = amaf.game_baselen;
547 cutoff += (amaf.gamelen - amaf.game_baselen) * u->playout_amaf_cutoff / 100;
548 amaf.gamelen = cutoff;
551 /* Record the result. */
553 assert(n == t->root || n->parent);
554 floating_t rval = scale_value(u, b, result);
555 u->policy->update(u->policy, t, n, node_color, player_color, &amaf, &b2, rval);
557 stats_add_result(&t->avg_score, result / 2, 1);
558 if (t->use_extra_komi) {
559 stats_add_result(&u->dynkomi->score, result / 2, 1);
560 stats_add_result(&u->dynkomi->value, rval, 1);
563 if (u->local_tree && n->parent && !is_pass(node_coord(n)) && dlen > 0) {
564 /* Get the local sequences and record them in ltree. */
565 /* We will look for sequence starts in our descent
566 * history, then run record_local_sequence() for each
567 * found sequence start; record_local_sequence() may
568 * pick longer sequences from descent history then,
569 * which is expected as it will create new lnodes. */
570 enum stone seq_color = player_color;
571 /* First move always starts a sequence. */
572 record_local_sequence(u, t, &b2, descent, dlen, 1, seq_color);
573 seq_color = stone_other(seq_color);
574 for (int dseqi = 2; dseqi < dlen; dseqi++, seq_color = stone_other(seq_color)) {
575 if (u->local_tree_allseq) {
576 /* We are configured to record all subsequences. */
577 record_local_sequence(u, t, &b2, descent, dlen, dseqi, seq_color);
578 continue;
580 if (descent[dseqi].node->d >= u->tenuki_d) {
581 /* Tenuki! Record the fresh sequence. */
582 record_local_sequence(u, t, &b2, descent, dlen, dseqi, seq_color);
583 continue;
585 if (descent[dseqi].lnode && !descent[dseqi].lnode) {
586 /* Record result for in-descent picked sequence. */
587 record_local_sequence(u, t, &b2, descent, dlen, dseqi, seq_color);
588 continue;
593 end:
594 /* We need to undo the virtual loss we added during descend. */
595 if (u->virtual_loss) {
596 floating_t loss = node_color == S_BLACK ? 0.0 : 1.0;
597 for (; n->parent; n = n->parent) {
598 stats_rm_result(&n->u, loss, u->virtual_loss);
599 loss = 1.0 - loss;
603 board_done_noalloc(&b2);
604 return result;
608 uct_playouts(struct uct *u, struct board *b, enum stone color, struct tree *t, struct time_info *ti)
610 int i;
611 if (ti && ti->dim == TD_GAMES) {
612 for (i = 0; t->root->u.playouts <= ti->len.games && !uct_halt; i++)
613 uct_playout(u, b, color, t);
614 } else {
615 for (i = 0; !uct_halt; i++)
616 uct_playout(u, b, color, t);
618 return i;