HACKING: network.[ch] is a core file, cannot be in aux library
[pachi/t.git] / uct / walk.c
blob56c0bf57853a5254fd9a300da56f137a6d97f3ba
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
27 void
28 uct_progress_status(struct uct *u, struct tree *t, enum stone color, int playouts)
30 if (!UDEBUGL(0))
31 return;
33 /* Best move */
34 struct tree_node *best = u->policy->choose(u->policy, t->root, t->board, color, resign);
35 if (!best) {
36 fprintf(stderr, "... No moves left\n");
37 return;
39 fprintf(stderr, "[%d] ", playouts);
40 fprintf(stderr, "best %f ", tree_node_get_value(t, 1, best->u.value));
42 /* Dynamic komi */
43 if (t->use_extra_komi)
44 fprintf(stderr, "komi %.1f ", t->extra_komi);
46 /* Best sequence */
47 fprintf(stderr, "| seq ");
48 for (int depth = 0; depth < 4; depth++) {
49 if (best && best->u.playouts >= 25) {
50 fprintf(stderr, "%3s ", coord2sstr(node_coord(best), t->board));
51 best = u->policy->choose(u->policy, best, t->board, color, resign);
52 } else {
53 fprintf(stderr, " ");
57 /* Best candidates */
58 fprintf(stderr, "| can ");
59 int cans = 4;
60 struct tree_node *can[cans];
61 memset(can, 0, sizeof(can));
62 best = t->root->children;
63 while (best) {
64 int c = 0;
65 while ((!can[c] || best->u.playouts > can[c]->u.playouts) && ++c < cans);
66 for (int d = 0; d < c; d++) can[d] = can[d + 1];
67 if (c > 0) can[c - 1] = best;
68 best = best->sibling;
70 while (--cans >= 0) {
71 if (can[cans]) {
72 fprintf(stderr, "%3s(%.3f) ",
73 coord2sstr(node_coord(can[cans]), t->board),
74 tree_node_get_value(t, 1, can[cans]->u.value));
75 } else {
76 fprintf(stderr, " ");
80 fprintf(stderr, "\n");
84 static void
85 record_amaf_move(struct playout_amafmap *amaf, coord_t coord, enum stone color)
87 if (amaf->map[coord] == S_NONE || amaf->map[coord] == color) {
88 amaf->map[coord] = color;
89 } else { // XXX: Respect amaf->record_nakade
90 amaf_op(amaf->map[coord], +);
92 amaf->game[amaf->gamelen].coord = coord;
93 amaf->game[amaf->gamelen].color = color;
94 amaf->gamelen++;
95 assert(amaf->gamelen < sizeof(amaf->game) / sizeof(amaf->game[0]));
99 struct uct_playout_callback {
100 struct uct *uct;
101 struct tree *tree;
102 struct tree_node *lnode;
106 static coord_t
107 uct_playout_hook(struct playout_policy *playout, struct playout_setup *setup, struct board *b, enum stone color, int mode)
109 /* XXX: This is used in some non-master branches. */
110 return pass;
113 static coord_t
114 uct_playout_prepolicy(struct playout_policy *playout, struct playout_setup *setup, struct board *b, enum stone color)
116 return uct_playout_hook(playout, setup, b, color, 0);
119 static coord_t
120 uct_playout_postpolicy(struct playout_policy *playout, struct playout_setup *setup, struct board *b, enum stone color)
122 return uct_playout_hook(playout, setup, b, color, 1);
126 static int
127 uct_leaf_node(struct uct *u, struct board *b, enum stone player_color,
128 struct playout_amafmap *amaf,
129 struct uct_descent *descent, int *dlen,
130 struct tree_node *significant[2],
131 struct tree *t, struct tree_node *n, enum stone node_color,
132 char *spaces)
134 enum stone next_color = stone_other(node_color);
135 int parity = (next_color == player_color ? 1 : -1);
137 if (UDEBUGL(7))
138 fprintf(stderr, "%s*-- UCT playout #%d start [%s] %f\n",
139 spaces, n->u.playouts, coord2sstr(node_coord(n), t->board),
140 tree_node_get_value(t, parity, n->u.value));
142 struct uct_playout_callback upc = {
143 .uct = u,
144 .tree = t,
145 /* TODO: Don't necessarily restart the sequence walk when
146 * entering playout. */
147 .lnode = NULL,
150 struct playout_setup ps = {
151 .gamelen = u->gamelen,
152 .mercymin = u->mercymin,
153 .prepolicy_hook = uct_playout_prepolicy,
154 .postpolicy_hook = uct_playout_postpolicy,
155 .hook_data = &upc,
157 int result = play_random_game(&ps, b, next_color,
158 u->playout_amaf ? amaf : NULL,
159 &u->ownermap, u->playout);
160 if (next_color == S_WHITE) {
161 /* We need the result from black's perspective. */
162 result = - result;
164 if (UDEBUGL(7))
165 fprintf(stderr, "%s -- [%d..%d] %s random playout result %d\n",
166 spaces, player_color, next_color, coord2sstr(node_coord(n), t->board), result);
168 return result;
171 static floating_t
172 scale_value(struct uct *u, struct board *b, int result)
174 floating_t rval = result > 0 ? 1.0 : result < 0 ? 0.0 : 0.5;
175 if (u->val_scale && result != 0) {
176 int vp = u->val_points;
177 if (!vp) {
178 vp = board_size(b) - 1; vp *= vp; vp *= 2;
181 floating_t sval = (floating_t) abs(result) / vp;
182 sval = sval > 1 ? 1 : sval;
183 if (result < 0) sval = 1 - sval;
184 if (u->val_extra)
185 rval += u->val_scale * sval;
186 else
187 rval = (1 - u->val_scale) * rval + u->val_scale * sval;
188 // fprintf(stderr, "score %d => sval %f, rval %f\n", result, sval, rval);
190 return rval;
193 static double
194 local_value(struct uct *u, struct board *b, coord_t coord, enum stone color)
196 /* Tactical evaluation of move @coord by color @color, given
197 * simulation end position @b. I.e., a move is tactically good
198 * if the resulting group stays on board until the game end. */
199 /* We can also take into account surrounding stones, e.g. to
200 * encourage taking off external liberties during a semeai. */
201 double val = board_local_value(u->local_tree_neival, b, coord, color);
202 return (color == S_WHITE) ? 1.f - val : val;
205 static void
206 record_local_sequence(struct uct *u, struct tree *t, struct board *endb,
207 struct uct_descent *descent, int dlen, int di,
208 enum stone seq_color)
210 #define LTREE_DEBUG if (UDEBUGL(6))
212 /* Ignore pass sequences. */
213 if (is_pass(node_coord(descent[di].node)))
214 return;
216 LTREE_DEBUG board_print(endb, stderr);
217 LTREE_DEBUG fprintf(stderr, "recording local %s sequence: ",
218 stone2str(seq_color));
220 /* Sequences starting deeper are less relevant in general. */
221 int pval = LTREE_PLAYOUTS_MULTIPLIER;
222 if (u->local_tree && u->local_tree_depth_decay > 0)
223 pval = ((floating_t) pval) / pow(u->local_tree_depth_decay, di - 1);
224 if (!pval) {
225 LTREE_DEBUG fprintf(stderr, "too deep @%d\n", di);
226 return;
229 /* Pick the right local tree root... */
230 struct tree_node *lnode = seq_color == S_BLACK ? t->ltree_black : t->ltree_white;
231 lnode->u.playouts++;
233 double sval = 0.5;
234 if (u->local_tree_rootgoal) {
235 sval = local_value(u, endb, node_coord(descent[di].node), seq_color);
236 LTREE_DEBUG fprintf(stderr, "(goal %s[%s %1.3f][%d]) ",
237 coord2sstr(node_coord(descent[di].node), t->board),
238 stone2str(seq_color), sval, descent[di].node->d);
241 /* ...and record the sequence. */
242 int di0 = di;
243 while (di < dlen && (di == di0 || descent[di].node->d < u->tenuki_d)) {
244 enum stone color = (di - di0) % 2 ? stone_other(seq_color) : seq_color;
245 double rval;
246 if (u->local_tree_rootgoal)
247 rval = sval;
248 else
249 rval = local_value(u, endb, node_coord(descent[di].node), color);
250 LTREE_DEBUG fprintf(stderr, "%s[%s %1.3f][%d] ",
251 coord2sstr(node_coord(descent[di].node), t->board),
252 stone2str(color), rval, descent[di].node->d);
253 lnode = tree_get_node(t, lnode, node_coord(descent[di++].node), true);
254 assert(lnode);
255 stats_add_result(&lnode->u, rval, pval);
258 /* Add lnode for tenuki (pass) if we descended further. */
259 if (di < dlen) {
260 double rval = u->local_tree_rootgoal ? sval : 0.5;
261 LTREE_DEBUG fprintf(stderr, "pass ");
262 lnode = tree_get_node(t, lnode, pass, true);
263 assert(lnode);
264 stats_add_result(&lnode->u, rval, pval);
267 LTREE_DEBUG fprintf(stderr, "\n");
272 uct_playout(struct uct *u, struct board *b, enum stone player_color, struct tree *t)
274 struct board b2;
275 board_copy(&b2, b);
277 struct playout_amafmap *amaf = NULL;
278 if (u->policy->wants_amaf) {
279 amaf = calloc2(1, sizeof(*amaf));
280 amaf->map = calloc2(board_size2(&b2) + 1, sizeof(*amaf->map));
281 amaf->map++; // -1 is pass
284 /* Walk the tree until we find a leaf, then expand it and do
285 * a random playout. */
286 struct tree_node *n = t->root;
287 enum stone node_color = stone_other(player_color);
288 assert(node_color == t->root_color);
290 /* Make sure the root node is expanded. */
291 if (tree_leaf_node(n) && !__sync_lock_test_and_set(&n->is_expanded, 1))
292 tree_expand_node(t, n, &b2, player_color, u, 1);
294 /* Tree descent history. */
295 /* XXX: This is somewhat messy since @n and descent[dlen-1].node are
296 * redundant. */
297 struct uct_descent descent[DESCENT_DLEN];
298 descent[0].node = n; descent[0].lnode = NULL;
299 int dlen = 1;
300 /* Total value of the sequence. */
301 struct move_stats seq_value = { .playouts = 0 };
302 /* The last "significant" node along the descent (i.e. node
303 * with higher than configured number of playouts). For black
304 * and white. */
305 struct tree_node *significant[2] = { NULL, NULL };
306 if (n->u.playouts >= u->significant_threshold)
307 significant[node_color - 1] = n;
309 int result;
310 int pass_limit = (board_size(&b2) - 2) * (board_size(&b2) - 2) / 2;
311 int passes = is_pass(b->last_move.coord) && b->moves > 0;
313 /* debug */
314 static char spaces[] = "\0 ";
315 /* /debug */
316 if (UDEBUGL(8))
317 fprintf(stderr, "--- UCT walk with color %d\n", player_color);
319 while (!tree_leaf_node(n) && passes < 2) {
320 spaces[dlen - 1] = ' '; spaces[dlen] = 0;
323 /*** Choose a node to descend to: */
325 /* Parity is chosen already according to the child color, since
326 * it is applied to children. */
327 node_color = stone_other(node_color);
328 int parity = (node_color == player_color ? 1 : -1);
330 assert(dlen < DESCENT_DLEN);
331 descent[dlen] = descent[dlen - 1];
332 if (u->local_tree && (!descent[dlen].lnode || descent[dlen].node->d >= u->tenuki_d)) {
333 /* Start new local sequence. */
334 /* Remember that node_color already holds color of the
335 * to-be-found child. */
336 descent[dlen].lnode = node_color == S_BLACK ? t->ltree_black : t->ltree_white;
339 if (!u->random_policy_chance || fast_random(u->random_policy_chance))
340 u->policy->descend(u->policy, t, &descent[dlen], parity, b2.moves > pass_limit);
341 else
342 u->random_policy->descend(u->random_policy, t, &descent[dlen], parity, b2.moves > pass_limit);
345 /*** Perform the descent: */
347 if (descent[dlen].node->u.playouts >= u->significant_threshold) {
348 significant[node_color - 1] = descent[dlen].node;
351 seq_value.playouts += descent[dlen].value.playouts;
352 seq_value.value += descent[dlen].value.value * descent[dlen].value.playouts;
353 n = descent[dlen++].node;
354 assert(n == t->root || n->parent);
355 if (UDEBUGL(7))
356 fprintf(stderr, "%s+-- UCT sent us to [%s:%d] %d,%f\n",
357 spaces, coord2sstr(node_coord(n), t->board),
358 node_coord(n), n->u.playouts,
359 tree_node_get_value(t, parity, n->u.value));
361 /* Add virtual loss if we need to; this is used to discourage
362 * other threads from visiting this node in case of multiple
363 * threads doing the tree search. */
364 if (u->virtual_loss)
365 stats_add_result(&n->u, node_color == S_BLACK ? 0.0 : 1.0, u->virtual_loss);
367 assert(node_coord(n) >= -1);
368 if (amaf && !is_pass(node_coord(n)))
369 record_amaf_move(amaf, node_coord(n), node_color);
371 struct move m = { node_coord(n), node_color };
372 int res = board_play(&b2, &m);
374 if (res < 0 || (!is_pass(m.coord) && !group_at(&b2, m.coord)) /* suicide */
375 || b2.superko_violation) {
376 if (UDEBUGL(4)) {
377 for (struct tree_node *ni = n; ni; ni = ni->parent)
378 fprintf(stderr, "%s<%"PRIhash"> ", coord2sstr(node_coord(ni), t->board), ni->hash);
379 fprintf(stderr, "marking invalid %s node %d,%d res %d group %d spk %d\n",
380 stone2str(node_color), coord_x(node_coord(n),b), coord_y(node_coord(n),b),
381 res, group_at(&b2, m.coord), b2.superko_violation);
383 n->hints |= TREE_HINT_INVALID;
384 result = 0;
385 goto end;
388 if (is_pass(node_coord(n)))
389 passes++;
390 else
391 passes = 0;
393 enum stone next_color = stone_other(node_color);
394 /* We need to make sure only one thread expands the node. If
395 * we are unlucky enough for two threads to meet in the same
396 * node, the latter one will simply do another simulation from
397 * the node itself, no big deal. t->nodes_size may exceed
398 * the maximum in multi-threaded case but not by much so it's ok.
399 * The size test must be before the test&set not after, to allow
400 * expansion of the node later if enough nodes have been freed. */
401 if (tree_leaf_node(n)
402 && n->u.playouts - u->virtual_loss >= u->expand_p && t->nodes_size < u->max_tree_size
403 && !__sync_lock_test_and_set(&n->is_expanded, 1))
404 tree_expand_node(t, n, &b2, next_color, u, -parity);
407 if (amaf) {
408 amaf->game_baselen = amaf->gamelen;
409 amaf->record_nakade = u->playout_amaf_nakade;
412 if (t->use_extra_komi && u->dynkomi->persim) {
413 b2.komi += round(u->dynkomi->persim(u->dynkomi, &b2, t, n));
416 if (passes >= 2) {
417 /* XXX: No dead groups support. */
418 floating_t score = board_official_score(&b2, NULL);
419 /* Result from black's perspective (no matter who
420 * the player; black's perspective is always
421 * what the tree stores. */
422 result = - (score * 2);
424 if (UDEBUGL(5))
425 fprintf(stderr, "[%d..%d] %s p-p scoring playout result %d (W %f)\n",
426 player_color, node_color, coord2sstr(node_coord(n), t->board), result, score);
427 if (UDEBUGL(6))
428 board_print(&b2, stderr);
430 board_ownermap_fill(&u->ownermap, &b2);
432 } else { // assert(tree_leaf_node(n));
433 /* In case of parallel tree search, the assertion might
434 * not hold if two threads chew on the same node. */
435 result = uct_leaf_node(u, &b2, player_color, amaf, descent, &dlen, significant, t, n, node_color, spaces);
438 if (amaf && u->playout_amaf_cutoff) {
439 unsigned int cutoff = amaf->game_baselen;
440 cutoff += (amaf->gamelen - amaf->game_baselen) * u->playout_amaf_cutoff / 100;
441 /* Now, reconstruct the amaf map. */
442 memset(amaf->map, 0, board_size2(&b2) * sizeof(*amaf->map));
443 for (unsigned int i = 0; i < cutoff; i++) {
444 coord_t coord = amaf->game[i].coord;
445 enum stone color = amaf->game[i].color;
446 if (amaf->map[coord] == S_NONE || amaf->map[coord] == color) {
447 amaf->map[coord] = color;
448 /* Nakade always recorded for in-tree part */
449 } else if (amaf->record_nakade || i <= amaf->game_baselen) {
450 amaf_op(amaf->map[node_coord(n)], +);
455 /* Record the result. */
457 assert(n == t->root || n->parent);
458 floating_t rval = scale_value(u, b, result);
459 u->policy->update(u->policy, t, n, node_color, player_color, amaf, &b2, rval);
461 if (t->use_extra_komi) {
462 stats_add_result(&u->dynkomi->score, result / 2, 1);
463 stats_add_result(&u->dynkomi->value, rval, 1);
466 if (u->local_tree && n->parent && !is_pass(node_coord(n)) && dlen > 0) {
467 /* Get the local sequences and record them in ltree. */
468 /* We will look for sequence starts in our descent
469 * history, then run record_local_sequence() for each
470 * found sequence start; record_local_sequence() may
471 * pick longer sequences from descent history then,
472 * which is expected as it will create new lnodes. */
473 enum stone seq_color = player_color;
474 /* First move always starts a sequence. */
475 record_local_sequence(u, t, &b2, descent, dlen, 1, seq_color);
476 seq_color = stone_other(seq_color);
477 for (int dseqi = 2; dseqi < dlen; dseqi++, seq_color = stone_other(seq_color)) {
478 if (u->local_tree_allseq) {
479 /* We are configured to record all subsequences. */
480 record_local_sequence(u, t, &b2, descent, dlen, dseqi, seq_color);
481 continue;
483 if (descent[dseqi].node->d >= u->tenuki_d) {
484 /* Tenuki! Record the fresh sequence. */
485 record_local_sequence(u, t, &b2, descent, dlen, dseqi, seq_color);
486 continue;
488 if (descent[dseqi].lnode && !descent[dseqi].lnode) {
489 /* Record result for in-descent picked sequence. */
490 record_local_sequence(u, t, &b2, descent, dlen, dseqi, seq_color);
491 continue;
496 end:
497 /* We need to undo the virtual loss we added during descend. */
498 if (u->virtual_loss) {
499 floating_t loss = node_color == S_BLACK ? 0.0 : 1.0;
500 for (; n->parent; n = n->parent) {
501 stats_rm_result(&n->u, loss, u->virtual_loss);
502 loss = 1.0 - loss;
506 if (amaf) {
507 free(amaf->map - 1);
508 free(amaf);
510 board_done_noalloc(&b2);
511 return result;
515 uct_playouts(struct uct *u, struct board *b, enum stone color, struct tree *t, struct time_info *ti)
517 int i;
518 if (ti && ti->dim == TD_GAMES) {
519 for (i = 0; t->root->u.playouts <= ti->len.games && !uct_halt; i++)
520 uct_playout(u, b, color, t);
521 } else {
522 for (i = 0; !uct_halt; i++)
523 uct_playout(u, b, color, t);
525 return i;