UCT node.coord: Access using node_coord()
[pachi/t.git] / uct / walk.c
blob45f0bbfd7fe3cce9c004c42650db3a3d8e44703b
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 "uct/dynkomi.h"
18 #include "uct/internal.h"
19 #include "uct/search.h"
20 #include "uct/tree.h"
21 #include "uct/uct.h"
22 #include "uct/walk.h"
24 #define DESCENT_DLEN 512
26 void
27 uct_progress_status(struct uct *u, struct tree *t, enum stone color, int playouts)
29 if (!UDEBUGL(0))
30 return;
32 /* Best move */
33 struct tree_node *best = u->policy->choose(u->policy, t->root, t->board, color, resign);
34 if (!best) {
35 fprintf(stderr, "... No moves left\n");
36 return;
38 fprintf(stderr, "[%d] ", playouts);
39 fprintf(stderr, "best %f ", tree_node_get_value(t, 1, best->u.value));
41 /* Dynamic komi */
42 if (t->use_extra_komi)
43 fprintf(stderr, "komi %.1f ", t->extra_komi);
45 /* Best sequence */
46 fprintf(stderr, "| seq ");
47 for (int depth = 0; depth < 4; depth++) {
48 if (best && best->u.playouts >= 25) {
49 fprintf(stderr, "%3s ", coord2sstr(node_coord(best), t->board));
50 best = u->policy->choose(u->policy, best, t->board, color, resign);
51 } else {
52 fprintf(stderr, " ");
56 /* Best candidates */
57 fprintf(stderr, "| can ");
58 int cans = 4;
59 struct tree_node *can[cans];
60 memset(can, 0, sizeof(can));
61 best = t->root->children;
62 while (best) {
63 int c = 0;
64 while ((!can[c] || best->u.playouts > can[c]->u.playouts) && ++c < cans);
65 for (int d = 0; d < c; d++) can[d] = can[d + 1];
66 if (c > 0) can[c - 1] = best;
67 best = best->sibling;
69 while (--cans >= 0) {
70 if (can[cans]) {
71 fprintf(stderr, "%3s(%.3f) ",
72 coord2sstr(node_coord(can[cans]), t->board),
73 tree_node_get_value(t, 1, can[cans]->u.value));
74 } else {
75 fprintf(stderr, " ");
79 fprintf(stderr, "\n");
83 static void
84 record_amaf_move(struct playout_amafmap *amaf, coord_t coord, enum stone color)
86 if (amaf->map[coord] == S_NONE || amaf->map[coord] == color) {
87 amaf->map[coord] = color;
88 } else { // XXX: Respect amaf->record_nakade
89 amaf_op(amaf->map[coord], +);
91 amaf->game[amaf->gamelen].coord = coord;
92 amaf->game[amaf->gamelen].color = color;
93 amaf->gamelen++;
94 assert(amaf->gamelen < sizeof(amaf->game) / sizeof(amaf->game[0]));
98 struct uct_playout_callback {
99 struct uct *uct;
100 struct tree *tree;
101 struct tree_node *lnode;
105 static coord_t
106 uct_playout_hook(struct playout_policy *playout, struct playout_setup *setup, struct board *b, enum stone color, int mode)
108 /* XXX: This is used in some non-master branches. */
109 return pass;
112 static coord_t
113 uct_playout_prepolicy(struct playout_policy *playout, struct playout_setup *setup, struct board *b, enum stone color)
115 return uct_playout_hook(playout, setup, b, color, 0);
118 static coord_t
119 uct_playout_postpolicy(struct playout_policy *playout, struct playout_setup *setup, struct board *b, enum stone color)
121 return uct_playout_hook(playout, setup, b, color, 1);
125 static int
126 uct_leaf_node(struct uct *u, struct board *b, enum stone player_color,
127 struct playout_amafmap *amaf,
128 struct uct_descent *descent, int *dlen,
129 struct tree_node *significant[2],
130 struct tree *t, struct tree_node *n, enum stone node_color,
131 char *spaces)
133 enum stone next_color = stone_other(node_color);
134 int parity = (next_color == player_color ? 1 : -1);
136 if (UDEBUGL(7))
137 fprintf(stderr, "%s*-- UCT playout #%d start [%s] %f\n",
138 spaces, n->u.playouts, coord2sstr(node_coord(n), t->board),
139 tree_node_get_value(t, parity, n->u.value));
141 struct uct_playout_callback upc = {
142 .uct = u,
143 .tree = t,
144 /* TODO: Don't necessarily restart the sequence walk when
145 * entering playout. */
146 .lnode = NULL,
149 struct playout_setup ps = {
150 .gamelen = u->gamelen,
151 .mercymin = u->mercymin,
152 .prepolicy_hook = uct_playout_prepolicy,
153 .postpolicy_hook = uct_playout_postpolicy,
154 .hook_data = &upc,
156 int result = play_random_game(&ps, b, next_color,
157 u->playout_amaf ? amaf : NULL,
158 &u->ownermap, u->playout);
159 if (next_color == S_WHITE) {
160 /* We need the result from black's perspective. */
161 result = - result;
163 if (UDEBUGL(7))
164 fprintf(stderr, "%s -- [%d..%d] %s random playout result %d\n",
165 spaces, player_color, next_color, coord2sstr(node_coord(n), t->board), result);
167 return result;
170 static floating_t
171 scale_value(struct uct *u, struct board *b, int result)
173 floating_t rval = result > 0 ? 1.0 : result < 0 ? 0.0 : 0.5;
174 if (u->val_scale && result != 0) {
175 int vp = u->val_points;
176 if (!vp) {
177 vp = board_size(b) - 1; vp *= vp; vp *= 2;
180 floating_t sval = (floating_t) abs(result) / vp;
181 sval = sval > 1 ? 1 : sval;
182 if (result < 0) sval = 1 - sval;
183 if (u->val_extra)
184 rval += u->val_scale * sval;
185 else
186 rval = (1 - u->val_scale) * rval + u->val_scale * sval;
187 // fprintf(stderr, "score %d => sval %f, rval %f\n", result, sval, rval);
189 return rval;
192 static double
193 local_value(struct uct *u, struct board *b, coord_t coord, enum stone color)
195 /* Tactical evaluation of move @coord by color @color, given
196 * simulation end position @b. I.e., a move is tactically good
197 * if the resulting group stays on board until the game end. */
198 /* We can also take into account surrounding stones, e.g. to
199 * encourage taking off external liberties during a semeai. */
200 double val;
201 if (u->local_tree_neival) {
202 int friends = neighbor_count_at(b, coord, color) + neighbor_count_at(b, coord, S_OFFBOARD);
203 if (immediate_liberty_count(b, coord) > 0) {
204 foreach_neighbor(b, coord, {
205 friends += board_is_one_point_eye(b, coord, color);
208 val = (double) (2 * (board_at(b, coord) == color) + friends) / 6.f;
209 } else {
210 val = (board_at(b, coord) == color) ? 1.f : 0.f;
212 return (color == S_WHITE) ? 1.f - val : val;
215 static void
216 record_local_sequence(struct uct *u, struct tree *t, struct board *endb,
217 struct uct_descent *descent, int dlen, int di,
218 enum stone seq_color)
220 #define LTREE_DEBUG if (UDEBUGL(6))
222 /* Ignore pass sequences. */
223 if (is_pass(node_coord(descent[di].node)))
224 return;
226 LTREE_DEBUG board_print(endb, stderr);
227 LTREE_DEBUG fprintf(stderr, "recording local %s sequence: ",
228 stone2str(seq_color));
230 /* Sequences starting deeper are less relevant in general. */
231 int pval = LTREE_PLAYOUTS_MULTIPLIER;
232 if (u->local_tree && u->local_tree_depth_decay > 0)
233 pval = ((floating_t) pval) / pow(u->local_tree_depth_decay, di - 1);
234 if (!pval) {
235 LTREE_DEBUG fprintf(stderr, "too deep @%d\n", di);
236 return;
239 /* Pick the right local tree root... */
240 struct tree_node *lnode = seq_color == S_BLACK ? t->ltree_black : t->ltree_white;
241 lnode->u.playouts++;
243 double sval = 0.5;
244 if (u->local_tree_rootgoal) {
245 sval = local_value(u, endb, node_coord(descent[di].node), seq_color);
246 LTREE_DEBUG fprintf(stderr, "(goal %s[%s %1.3f][%d]) ",
247 coord2sstr(node_coord(descent[di].node), t->board),
248 stone2str(seq_color), sval, descent[di].node->d);
251 /* ...and record the sequence. */
252 int di0 = di;
253 while (di < dlen && (di == di0 || descent[di].node->d < u->tenuki_d)) {
254 enum stone color = (di - di0) % 2 ? stone_other(seq_color) : seq_color;
255 double rval;
256 if (u->local_tree_rootgoal)
257 rval = sval;
258 else
259 rval = local_value(u, endb, node_coord(descent[di].node), color);
260 LTREE_DEBUG fprintf(stderr, "%s[%s %1.3f][%d] ",
261 coord2sstr(node_coord(descent[di].node), t->board),
262 stone2str(color), rval, descent[di].node->d);
263 lnode = tree_get_node(t, lnode, node_coord(descent[di++].node), true);
264 assert(lnode);
265 stats_add_result(&lnode->u, rval, pval);
268 /* Add lnode for tenuki (pass) if we descended further. */
269 if (di < dlen) {
270 double rval = u->local_tree_rootgoal ? sval : 0.5;
271 LTREE_DEBUG fprintf(stderr, "pass ");
272 lnode = tree_get_node(t, lnode, pass, true);
273 assert(lnode);
274 stats_add_result(&lnode->u, rval, pval);
277 LTREE_DEBUG fprintf(stderr, "\n");
282 uct_playout(struct uct *u, struct board *b, enum stone player_color, struct tree *t)
284 struct board b2;
285 board_copy(&b2, b);
287 struct playout_amafmap *amaf = NULL;
288 if (u->policy->wants_amaf) {
289 amaf = calloc2(1, sizeof(*amaf));
290 amaf->map = calloc2(board_size2(&b2) + 1, sizeof(*amaf->map));
291 amaf->map++; // -1 is pass
294 /* Walk the tree until we find a leaf, then expand it and do
295 * a random playout. */
296 struct tree_node *n = t->root;
297 enum stone node_color = stone_other(player_color);
298 assert(node_color == t->root_color);
300 /* Make sure the root node is expanded. */
301 if (tree_leaf_node(n) && !__sync_lock_test_and_set(&n->is_expanded, 1))
302 tree_expand_node(t, n, &b2, player_color, u, 1);
304 /* Tree descent history. */
305 /* XXX: This is somewhat messy since @n and descent[dlen-1].node are
306 * redundant. */
307 struct uct_descent descent[DESCENT_DLEN];
308 descent[0].node = n; descent[0].lnode = NULL;
309 int dlen = 1;
310 /* Total value of the sequence. */
311 struct move_stats seq_value = { .playouts = 0 };
312 /* The last "significant" node along the descent (i.e. node
313 * with higher than configured number of playouts). For black
314 * and white. */
315 struct tree_node *significant[2] = { NULL, NULL };
316 if (n->u.playouts >= u->significant_threshold)
317 significant[node_color - 1] = n;
319 int result;
320 int pass_limit = (board_size(&b2) - 2) * (board_size(&b2) - 2) / 2;
321 int passes = is_pass(b->last_move.coord) && b->moves > 0;
323 /* debug */
324 static char spaces[] = "\0 ";
325 /* /debug */
326 if (UDEBUGL(8))
327 fprintf(stderr, "--- UCT walk with color %d\n", player_color);
329 while (!tree_leaf_node(n) && passes < 2) {
330 spaces[dlen - 1] = ' '; spaces[dlen] = 0;
333 /*** Choose a node to descend to: */
335 /* Parity is chosen already according to the child color, since
336 * it is applied to children. */
337 node_color = stone_other(node_color);
338 int parity = (node_color == player_color ? 1 : -1);
340 assert(dlen < DESCENT_DLEN);
341 descent[dlen] = descent[dlen - 1];
342 if (u->local_tree && (!descent[dlen].lnode || descent[dlen].node->d >= u->tenuki_d)) {
343 /* Start new local sequence. */
344 /* Remember that node_color already holds color of the
345 * to-be-found child. */
346 descent[dlen].lnode = node_color == S_BLACK ? t->ltree_black : t->ltree_white;
349 if (!u->random_policy_chance || fast_random(u->random_policy_chance))
350 u->policy->descend(u->policy, t, &descent[dlen], parity, b2.moves > pass_limit);
351 else
352 u->random_policy->descend(u->random_policy, t, &descent[dlen], parity, b2.moves > pass_limit);
355 /*** Perform the descent: */
357 if (descent[dlen].node->u.playouts >= u->significant_threshold) {
358 significant[node_color - 1] = descent[dlen].node;
361 seq_value.playouts += descent[dlen].value.playouts;
362 seq_value.value += descent[dlen].value.value * descent[dlen].value.playouts;
363 n = descent[dlen++].node;
364 assert(n == t->root || n->parent);
365 if (UDEBUGL(7))
366 fprintf(stderr, "%s+-- UCT sent us to [%s:%d] %d,%f\n",
367 spaces, coord2sstr(node_coord(n), t->board),
368 node_coord(n), n->u.playouts,
369 tree_node_get_value(t, parity, n->u.value));
371 /* Add virtual loss if we need to; this is used to discourage
372 * other threads from visiting this node in case of multiple
373 * threads doing the tree search. */
374 if (u->virtual_loss)
375 stats_add_result(&n->u, node_color == S_BLACK ? 0.0 : 1.0, u->virtual_loss);
377 assert(node_coord(n) >= -1);
378 if (amaf && !is_pass(node_coord(n)))
379 record_amaf_move(amaf, node_coord(n), node_color);
381 struct move m = { node_coord(n), node_color };
382 int res = board_play(&b2, &m);
384 if (res < 0 || (!is_pass(m.coord) && !group_at(&b2, m.coord)) /* suicide */
385 || b2.superko_violation) {
386 if (UDEBUGL(4)) {
387 for (struct tree_node *ni = n; ni; ni = ni->parent)
388 fprintf(stderr, "%s<%"PRIhash"> ", coord2sstr(node_coord(ni), t->board), ni->hash);
389 fprintf(stderr, "marking invalid %s node %d,%d res %d group %d spk %d\n",
390 stone2str(node_color), coord_x(node_coord(n),b), coord_y(node_coord(n),b),
391 res, group_at(&b2, m.coord), b2.superko_violation);
393 n->hints |= TREE_HINT_INVALID;
394 result = 0;
395 goto end;
398 if (is_pass(node_coord(n)))
399 passes++;
400 else
401 passes = 0;
403 enum stone next_color = stone_other(node_color);
404 /* We need to make sure only one thread expands the node. If
405 * we are unlucky enough for two threads to meet in the same
406 * node, the latter one will simply do another simulation from
407 * the node itself, no big deal. t->nodes_size may exceed
408 * the maximum in multi-threaded case but not by much so it's ok.
409 * The size test must be before the test&set not after, to allow
410 * expansion of the node later if enough nodes have been freed. */
411 if (tree_leaf_node(n)
412 && n->u.playouts - u->virtual_loss >= u->expand_p && t->nodes_size < u->max_tree_size
413 && !__sync_lock_test_and_set(&n->is_expanded, 1))
414 tree_expand_node(t, n, &b2, next_color, u, -parity);
417 if (amaf) {
418 amaf->game_baselen = amaf->gamelen;
419 amaf->record_nakade = u->playout_amaf_nakade;
422 if (t->use_extra_komi && u->dynkomi->persim) {
423 b2.komi += round(u->dynkomi->persim(u->dynkomi, &b2, t, n));
426 if (passes >= 2) {
427 /* XXX: No dead groups support. */
428 floating_t score = board_official_score(&b2, NULL);
429 /* Result from black's perspective (no matter who
430 * the player; black's perspective is always
431 * what the tree stores. */
432 result = - (score * 2);
434 if (UDEBUGL(5))
435 fprintf(stderr, "[%d..%d] %s p-p scoring playout result %d (W %f)\n",
436 player_color, node_color, coord2sstr(node_coord(n), t->board), result, score);
437 if (UDEBUGL(6))
438 board_print(&b2, stderr);
440 board_ownermap_fill(&u->ownermap, &b2);
442 } else { // assert(tree_leaf_node(n));
443 /* In case of parallel tree search, the assertion might
444 * not hold if two threads chew on the same node. */
445 result = uct_leaf_node(u, &b2, player_color, amaf, descent, &dlen, significant, t, n, node_color, spaces);
448 if (amaf && u->playout_amaf_cutoff) {
449 unsigned int cutoff = amaf->game_baselen;
450 cutoff += (amaf->gamelen - amaf->game_baselen) * u->playout_amaf_cutoff / 100;
451 /* Now, reconstruct the amaf map. */
452 memset(amaf->map, 0, board_size2(&b2) * sizeof(*amaf->map));
453 for (unsigned int i = 0; i < cutoff; i++) {
454 coord_t coord = amaf->game[i].coord;
455 enum stone color = amaf->game[i].color;
456 if (amaf->map[coord] == S_NONE || amaf->map[coord] == color) {
457 amaf->map[coord] = color;
458 /* Nakade always recorded for in-tree part */
459 } else if (amaf->record_nakade || i <= amaf->game_baselen) {
460 amaf_op(amaf->map[node_coord(n)], +);
465 /* Record the result. */
467 assert(n == t->root || n->parent);
468 floating_t rval = scale_value(u, b, result);
469 u->policy->update(u->policy, t, n, node_color, player_color, amaf, &b2, rval);
471 if (t->use_extra_komi) {
472 stats_add_result(&u->dynkomi->score, result / 2, 1);
473 stats_add_result(&u->dynkomi->value, rval, 1);
476 if (u->local_tree && n->parent && !is_pass(node_coord(n)) && dlen > 0) {
477 /* Get the local sequences and record them in ltree. */
478 /* We will look for sequence starts in our descent
479 * history, then run record_local_sequence() for each
480 * found sequence start; record_local_sequence() may
481 * pick longer sequences from descent history then,
482 * which is expected as it will create new lnodes. */
483 enum stone seq_color = player_color;
484 /* First move always starts a sequence. */
485 record_local_sequence(u, t, &b2, descent, dlen, 1, seq_color);
486 seq_color = stone_other(seq_color);
487 for (int dseqi = 2; dseqi < dlen; dseqi++, seq_color = stone_other(seq_color)) {
488 if (u->local_tree_allseq) {
489 /* We are configured to record all subsequences. */
490 record_local_sequence(u, t, &b2, descent, dlen, dseqi, seq_color);
491 continue;
493 if (descent[dseqi].node->d >= u->tenuki_d) {
494 /* Tenuki! Record the fresh sequence. */
495 record_local_sequence(u, t, &b2, descent, dlen, dseqi, seq_color);
496 continue;
498 if (descent[dseqi].lnode && !descent[dseqi].lnode) {
499 /* Record result for in-descent picked sequence. */
500 record_local_sequence(u, t, &b2, descent, dlen, dseqi, seq_color);
501 continue;
506 end:
507 /* We need to undo the virtual loss we added during descend. */
508 if (u->virtual_loss) {
509 floating_t loss = node_color == S_BLACK ? 0.0 : 1.0;
510 for (; n->parent; n = n->parent) {
511 stats_rm_result(&n->u, loss, u->virtual_loss);
512 loss = 1.0 - loss;
516 if (amaf) {
517 free(amaf->map - 1);
518 free(amaf);
520 board_done_noalloc(&b2);
521 return result;
525 uct_playouts(struct uct *u, struct board *b, enum stone color, struct tree *t, struct time_info *ti)
527 int i;
528 if (ti && ti->dim == TD_GAMES) {
529 for (i = 0; t->root->u.playouts <= ti->len.games && !uct_halt; i++)
530 uct_playout(u, b, color, t);
531 } else {
532 for (i = 0; !uct_halt; i++)
533 uct_playout(u, b, color, t);
535 return i;