Merge branch 'json'
[pachi/nmclean.git] / uct / walk.c
blob8f879570a2b248e60c1377b624b11096836a31eb
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, bool final)
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, bool 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 struct tree_node *best = u->policy->choose(u->policy, t->root, t->board, color, resign);
98 if (best) {
99 /* Best move */
100 fprintf(stderr, ", \"best\": {\"%s\": %f}",
101 coord2sstr(best->coord, t->board),
102 tree_node_get_value(t, 1, best->u.value));
104 /* Best sequence */
105 fprintf(stderr, ", \"seq\": [");
106 for (int depth = 0; depth < 4; depth++) {
107 if (!best || best->u.playouts < 25) break;
108 fprintf(stderr, "%s\"%s\"", depth > 0 ? "," : "",
109 coord2sstr(best->coord, t->board));
110 best = u->policy->choose(u->policy, best, t->board, color, resign);
112 fprintf(stderr, "]");
115 /* Best candidates */
116 int cans = 4;
117 struct tree_node *can[cans];
118 memset(can, 0, sizeof(can));
119 best = t->root->children;
120 while (best) {
121 int c = 0;
122 while ((!can[c] || best->u.playouts > can[c]->u.playouts) && ++c < cans);
123 for (int d = 0; d < c; d++) can[d] = can[d + 1];
124 if (c > 0) can[c - 1] = best;
125 best = best->sibling;
127 fprintf(stderr, ", \"can\": [");
128 while (--cans >= 0) {
129 if (!can[cans]) break;
130 fprintf(stderr, "%s{\"%s\":%.3f}",
131 cans < 3 ? "," : "",
132 coord2sstr(can[cans]->coord, t->board),
133 tree_node_get_value(t, 1, can[cans]->u.value));
135 fprintf(stderr, "]");
137 if (big) {
138 /* Ownership statistics. Value (0..1000) for each possible
139 * point describes likelihood of this point becoming black.
140 * Normally, white rate is 1000-value; exception are possible
141 * seki points, but these should be rare. */
142 fprintf(stderr, ", \"boards\": {\"territory\": [");
143 int f = 0;
144 foreach_point(t->board) {
145 if (board_at(t->board, c) == S_OFFBOARD) continue;
146 int rate = u->ownermap.map[c][S_BLACK] * 1000 / u->ownermap.playouts;
147 fprintf(stderr, "%s%d", f++ > 0 ? "," : "", rate);
148 } foreach_point_end;
149 fprintf(stderr, "]}");
153 fprintf(stderr, "}}\n");
156 void
157 uct_progress_status(struct uct *u, struct tree *t, enum stone color, int playouts, bool final)
159 switch (u->reporting) {
160 case UR_TEXT:
161 uct_progress_text(u, t, color, playouts, final);
162 break;
163 case UR_JSON:
164 case UR_JSON_BIG:
165 uct_progress_json(u, t, color, playouts, final,
166 u->reporting == UR_JSON_BIG);
167 break;
168 default: assert(0);
173 static inline void
174 record_amaf_move(struct playout_amafmap *amaf, coord_t coord)
176 assert(amaf->gamelen < MAX_GAMELEN);
177 amaf->game[amaf->gamelen++] = coord;
181 struct uct_playout_callback {
182 struct uct *uct;
183 struct tree *tree;
184 struct tree_node *lnode;
188 static coord_t
189 uct_playout_hook(struct playout_policy *playout, struct playout_setup *setup, struct board *b, enum stone color, int mode)
191 /* XXX: This is used in some non-master branches. */
192 return pass;
195 static coord_t
196 uct_playout_prepolicy(struct playout_policy *playout, struct playout_setup *setup, struct board *b, enum stone color)
198 return uct_playout_hook(playout, setup, b, color, 0);
201 static coord_t
202 uct_playout_postpolicy(struct playout_policy *playout, struct playout_setup *setup, struct board *b, enum stone color)
204 return uct_playout_hook(playout, setup, b, color, 1);
208 static int
209 uct_leaf_node(struct uct *u, struct board *b, enum stone player_color,
210 struct playout_amafmap *amaf,
211 struct uct_descent *descent, int *dlen,
212 struct tree_node *significant[2],
213 struct tree *t, struct tree_node *n, enum stone node_color,
214 char *spaces)
216 enum stone next_color = stone_other(node_color);
217 int parity = (next_color == player_color ? 1 : -1);
219 if (UDEBUGL(7))
220 fprintf(stderr, "%s*-- UCT playout #%d start [%s] %f\n",
221 spaces, n->u.playouts, coord2sstr(node_coord(n), t->board),
222 tree_node_get_value(t, parity, n->u.value));
224 struct uct_playout_callback upc = {
225 .uct = u,
226 .tree = t,
227 /* TODO: Don't necessarily restart the sequence walk when
228 * entering playout. */
229 .lnode = NULL,
232 struct playout_setup ps = {
233 .gamelen = u->gamelen,
234 .mercymin = u->mercymin,
235 .prepolicy_hook = uct_playout_prepolicy,
236 .postpolicy_hook = uct_playout_postpolicy,
237 .hook_data = &upc,
239 int result = play_random_game(&ps, b, next_color,
240 u->playout_amaf ? amaf : NULL,
241 &u->ownermap, u->playout);
242 if (next_color == S_WHITE) {
243 /* We need the result from black's perspective. */
244 result = - result;
246 if (UDEBUGL(7))
247 fprintf(stderr, "%s -- [%d..%d] %s random playout result %d\n",
248 spaces, player_color, next_color, coord2sstr(node_coord(n), t->board), result);
250 return result;
253 static floating_t
254 scale_value(struct uct *u, struct board *b, int result)
256 floating_t rval = result > 0 ? 1.0 : result < 0 ? 0.0 : 0.5;
257 if (u->val_scale && result != 0) {
258 int vp = u->val_points;
259 if (!vp) {
260 vp = board_size(b) - 1; vp *= vp; vp *= 2;
263 floating_t sval = (floating_t) abs(result) / vp;
264 sval = sval > 1 ? 1 : sval;
265 if (result < 0) sval = 1 - sval;
266 if (u->val_extra)
267 rval += u->val_scale * sval;
268 else
269 rval = (1 - u->val_scale) * rval + u->val_scale * sval;
270 // fprintf(stderr, "score %d => sval %f, rval %f\n", result, sval, rval);
272 return rval;
275 static double
276 local_value(struct uct *u, struct board *b, coord_t coord, enum stone color)
278 /* Tactical evaluation of move @coord by color @color, given
279 * simulation end position @b. I.e., a move is tactically good
280 * if the resulting group stays on board until the game end. */
281 /* We can also take into account surrounding stones, e.g. to
282 * encourage taking off external liberties during a semeai. */
283 double val = board_local_value(u->local_tree_neival, b, coord, color);
284 return (color == S_WHITE) ? 1.f - val : val;
287 static void
288 record_local_sequence(struct uct *u, struct tree *t, struct board *endb,
289 struct uct_descent *descent, int dlen, int di,
290 enum stone seq_color)
292 #define LTREE_DEBUG if (UDEBUGL(6))
294 /* Ignore pass sequences. */
295 if (is_pass(node_coord(descent[di].node)))
296 return;
298 LTREE_DEBUG board_print(endb, stderr);
299 LTREE_DEBUG fprintf(stderr, "recording local %s sequence: ",
300 stone2str(seq_color));
302 /* Sequences starting deeper are less relevant in general. */
303 int pval = LTREE_PLAYOUTS_MULTIPLIER;
304 if (u->local_tree && u->local_tree_depth_decay > 0)
305 pval = ((floating_t) pval) / pow(u->local_tree_depth_decay, di - 1);
306 if (!pval) {
307 LTREE_DEBUG fprintf(stderr, "too deep @%d\n", di);
308 return;
311 /* Pick the right local tree root... */
312 struct tree_node *lnode = seq_color == S_BLACK ? t->ltree_black : t->ltree_white;
313 lnode->u.playouts++;
315 /* ...determine the sequence value... */
316 double sval = 0.5;
317 if (u->local_tree_eval != LTE_EACH) {
318 sval = local_value(u, endb, node_coord(descent[di].node), seq_color);
319 LTREE_DEBUG fprintf(stderr, "(goal %s[%s %1.3f][%d]) ",
320 coord2sstr(node_coord(descent[di].node), t->board),
321 stone2str(seq_color), sval, descent[di].node->d);
323 if (u->local_tree_eval == LTE_TOTAL) {
324 int di0 = di;
325 while (di < dlen && (di == di0 || descent[di].node->d < u->tenuki_d)) {
326 enum stone color = (di - di0) % 2 ? stone_other(seq_color) : seq_color;
327 double rval = local_value(u, endb, node_coord(descent[di].node), color);
328 if ((di - di0) % 2)
329 rval = 1 - rval;
330 sval += rval;
331 di++;
333 sval /= (di - di0 + 1);
334 di = di0;
338 /* ...and record the sequence. */
339 int di0 = di;
340 while (di < dlen && !is_pass(node_coord(descent[di].node))
341 && (di == di0 || descent[di].node->d < u->tenuki_d)) {
342 enum stone color = (di - di0) % 2 ? stone_other(seq_color) : seq_color;
343 double rval;
344 if (u->local_tree_eval != LTE_EACH)
345 rval = sval;
346 else
347 rval = local_value(u, endb, node_coord(descent[di].node), color);
348 LTREE_DEBUG fprintf(stderr, "%s[%s %1.3f][%d] ",
349 coord2sstr(node_coord(descent[di].node), t->board),
350 stone2str(color), rval, descent[di].node->d);
351 lnode = tree_get_node(t, lnode, node_coord(descent[di++].node), true);
352 assert(lnode);
353 stats_add_result(&lnode->u, rval, pval);
356 /* Add lnode for tenuki (pass) if we descended further. */
357 if (di < dlen) {
358 double rval = u->local_tree_eval != LTE_EACH ? sval : 0.5;
359 LTREE_DEBUG fprintf(stderr, "pass ");
360 lnode = tree_get_node(t, lnode, pass, true);
361 assert(lnode);
362 stats_add_result(&lnode->u, rval, pval);
365 LTREE_DEBUG fprintf(stderr, "\n");
370 uct_playout(struct uct *u, struct board *b, enum stone player_color, struct tree *t)
372 struct board b2;
373 board_copy(&b2, b);
375 struct playout_amafmap amaf;
376 amaf.gamelen = amaf.game_baselen = 0;
378 /* Walk the tree until we find a leaf, then expand it and do
379 * a random playout. */
380 struct tree_node *n = t->root;
381 enum stone node_color = stone_other(player_color);
382 assert(node_color == t->root_color);
384 /* Make sure the root node is expanded. */
385 if (tree_leaf_node(n) && !__sync_lock_test_and_set(&n->is_expanded, 1))
386 tree_expand_node(t, n, &b2, player_color, u, 1);
388 /* Tree descent history. */
389 /* XXX: This is somewhat messy since @n and descent[dlen-1].node are
390 * redundant. */
391 struct uct_descent descent[DESCENT_DLEN];
392 descent[0].node = n; descent[0].lnode = NULL;
393 int dlen = 1;
394 /* Total value of the sequence. */
395 struct move_stats seq_value = { .playouts = 0 };
396 /* The last "significant" node along the descent (i.e. node
397 * with higher than configured number of playouts). For black
398 * and white. */
399 struct tree_node *significant[2] = { NULL, NULL };
400 if (n->u.playouts >= u->significant_threshold)
401 significant[node_color - 1] = n;
403 int result;
404 int pass_limit = (board_size(&b2) - 2) * (board_size(&b2) - 2) / 2;
405 int passes = is_pass(b->last_move.coord) && b->moves > 0;
407 /* debug */
408 static char spaces[] = "\0 ";
409 /* /debug */
410 if (UDEBUGL(8))
411 fprintf(stderr, "--- UCT walk with color %d\n", player_color);
413 while (!tree_leaf_node(n) && passes < 2) {
414 spaces[dlen - 1] = ' '; spaces[dlen] = 0;
417 /*** Choose a node to descend to: */
419 /* Parity is chosen already according to the child color, since
420 * it is applied to children. */
421 node_color = stone_other(node_color);
422 int parity = (node_color == player_color ? 1 : -1);
424 assert(dlen < DESCENT_DLEN);
425 descent[dlen] = descent[dlen - 1];
426 if (u->local_tree && (!descent[dlen].lnode || descent[dlen].node->d >= u->tenuki_d)) {
427 /* Start new local sequence. */
428 /* Remember that node_color already holds color of the
429 * to-be-found child. */
430 descent[dlen].lnode = node_color == S_BLACK ? t->ltree_black : t->ltree_white;
433 if (!u->random_policy_chance || fast_random(u->random_policy_chance))
434 u->policy->descend(u->policy, t, &descent[dlen], parity, b2.moves > pass_limit);
435 else
436 u->random_policy->descend(u->random_policy, t, &descent[dlen], parity, b2.moves > pass_limit);
439 /*** Perform the descent: */
441 if (descent[dlen].node->u.playouts >= u->significant_threshold) {
442 significant[node_color - 1] = descent[dlen].node;
445 seq_value.playouts += descent[dlen].value.playouts;
446 seq_value.value += descent[dlen].value.value * descent[dlen].value.playouts;
447 n = descent[dlen++].node;
448 assert(n == t->root || n->parent);
449 if (UDEBUGL(7))
450 fprintf(stderr, "%s+-- UCT sent us to [%s:%d] %d,%f\n",
451 spaces, coord2sstr(node_coord(n), t->board),
452 node_coord(n), n->u.playouts,
453 tree_node_get_value(t, parity, n->u.value));
455 /* Add virtual loss if we need to; this is used to discourage
456 * other threads from visiting this node in case of multiple
457 * threads doing the tree search. */
458 if (u->virtual_loss)
459 stats_add_result(&n->u, node_color == S_BLACK ? 0.0 : 1.0, u->virtual_loss);
461 assert(node_coord(n) >= -1);
462 record_amaf_move(&amaf, node_coord(n));
464 struct move m = { node_coord(n), node_color };
465 int res = board_play(&b2, &m);
467 if (res < 0 || (!is_pass(m.coord) && !group_at(&b2, m.coord)) /* suicide */
468 || b2.superko_violation) {
469 if (UDEBUGL(4)) {
470 for (struct tree_node *ni = n; ni; ni = ni->parent)
471 fprintf(stderr, "%s<%"PRIhash"> ", coord2sstr(node_coord(ni), t->board), ni->hash);
472 fprintf(stderr, "marking invalid %s node %d,%d res %d group %d spk %d\n",
473 stone2str(node_color), coord_x(node_coord(n),b), coord_y(node_coord(n),b),
474 res, group_at(&b2, m.coord), b2.superko_violation);
476 n->hints |= TREE_HINT_INVALID;
477 result = 0;
478 goto end;
481 if (is_pass(node_coord(n)))
482 passes++;
483 else
484 passes = 0;
486 enum stone next_color = stone_other(node_color);
487 /* We need to make sure only one thread expands the node. If
488 * we are unlucky enough for two threads to meet in the same
489 * node, the latter one will simply do another simulation from
490 * the node itself, no big deal. t->nodes_size may exceed
491 * the maximum in multi-threaded case but not by much so it's ok.
492 * The size test must be before the test&set not after, to allow
493 * expansion of the node later if enough nodes have been freed. */
494 if (tree_leaf_node(n)
495 && n->u.playouts - u->virtual_loss >= u->expand_p && t->nodes_size < u->max_tree_size
496 && !__sync_lock_test_and_set(&n->is_expanded, 1))
497 tree_expand_node(t, n, &b2, next_color, u, -parity);
500 amaf.game_baselen = amaf.gamelen;
502 if (t->use_extra_komi && u->dynkomi->persim) {
503 b2.komi += round(u->dynkomi->persim(u->dynkomi, &b2, t, n));
506 if (passes >= 2) {
507 /* XXX: No dead groups support. */
508 floating_t score = board_official_score(&b2, NULL);
509 /* Result from black's perspective (no matter who
510 * the player; black's perspective is always
511 * what the tree stores. */
512 result = - (score * 2);
514 if (UDEBUGL(5))
515 fprintf(stderr, "[%d..%d] %s p-p scoring playout result %d (W %f)\n",
516 player_color, node_color, coord2sstr(node_coord(n), t->board), result, score);
517 if (UDEBUGL(6))
518 board_print(&b2, stderr);
520 board_ownermap_fill(&u->ownermap, &b2);
522 } else { // assert(tree_leaf_node(n));
523 /* In case of parallel tree search, the assertion might
524 * not hold if two threads chew on the same node. */
525 result = uct_leaf_node(u, &b2, player_color, &amaf, descent, &dlen, significant, t, n, node_color, spaces);
528 if (u->policy->wants_amaf && u->playout_amaf_cutoff) {
529 unsigned int cutoff = amaf.game_baselen;
530 cutoff += (amaf.gamelen - amaf.game_baselen) * u->playout_amaf_cutoff / 100;
531 amaf.gamelen = cutoff;
534 /* Record the result. */
536 assert(n == t->root || n->parent);
537 floating_t rval = scale_value(u, b, result);
538 u->policy->update(u->policy, t, n, node_color, player_color, &amaf, &b2, rval);
540 if (t->use_extra_komi) {
541 stats_add_result(&u->dynkomi->score, result / 2, 1);
542 stats_add_result(&u->dynkomi->value, rval, 1);
545 if (u->local_tree && n->parent && !is_pass(node_coord(n)) && dlen > 0) {
546 /* Get the local sequences and record them in ltree. */
547 /* We will look for sequence starts in our descent
548 * history, then run record_local_sequence() for each
549 * found sequence start; record_local_sequence() may
550 * pick longer sequences from descent history then,
551 * which is expected as it will create new lnodes. */
552 enum stone seq_color = player_color;
553 /* First move always starts a sequence. */
554 record_local_sequence(u, t, &b2, descent, dlen, 1, seq_color);
555 seq_color = stone_other(seq_color);
556 for (int dseqi = 2; dseqi < dlen; dseqi++, seq_color = stone_other(seq_color)) {
557 if (u->local_tree_allseq) {
558 /* We are configured to record all subsequences. */
559 record_local_sequence(u, t, &b2, descent, dlen, dseqi, seq_color);
560 continue;
562 if (descent[dseqi].node->d >= u->tenuki_d) {
563 /* Tenuki! Record the fresh sequence. */
564 record_local_sequence(u, t, &b2, descent, dlen, dseqi, seq_color);
565 continue;
567 if (descent[dseqi].lnode && !descent[dseqi].lnode) {
568 /* Record result for in-descent picked sequence. */
569 record_local_sequence(u, t, &b2, descent, dlen, dseqi, seq_color);
570 continue;
575 end:
576 /* We need to undo the virtual loss we added during descend. */
577 if (u->virtual_loss) {
578 floating_t loss = node_color == S_BLACK ? 0.0 : 1.0;
579 for (; n->parent; n = n->parent) {
580 stats_rm_result(&n->u, loss, u->virtual_loss);
581 loss = 1.0 - loss;
585 board_done_noalloc(&b2);
586 return result;
590 uct_playouts(struct uct *u, struct board *b, enum stone color, struct tree *t, struct time_info *ti)
592 int i;
593 if (ti && ti->dim == TD_GAMES) {
594 for (i = 0; t->root->u.playouts <= ti->len.games && !uct_halt; i++)
595 uct_playout(u, b, color, t);
596 } else {
597 for (i = 0; !uct_halt; i++)
598 uct_playout(u, b, color, t);
600 return i;