Merge branch 'master' of ssh://repo.or.cz/srv/git/pachi
[pachi/t.git] / uct / walk.c
blobaa58feacfe9db00a5765abf0bd0688fae8a80014
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 inline void
85 record_amaf_move(struct playout_amafmap *amaf, coord_t coord)
87 assert(amaf->gamelen < MAX_GAMELEN);
88 amaf->game[amaf->gamelen++] = coord;
92 struct uct_playout_callback {
93 struct uct *uct;
94 struct tree *tree;
95 struct tree_node *lnode;
99 static coord_t
100 uct_playout_hook(struct playout_policy *playout, struct playout_setup *setup, struct board *b, enum stone color, int mode)
102 /* XXX: This is used in some non-master branches. */
103 return pass;
106 static coord_t
107 uct_playout_prepolicy(struct playout_policy *playout, struct playout_setup *setup, struct board *b, enum stone color)
109 return uct_playout_hook(playout, setup, b, color, 0);
112 static coord_t
113 uct_playout_postpolicy(struct playout_policy *playout, struct playout_setup *setup, struct board *b, enum stone color)
115 return uct_playout_hook(playout, setup, b, color, 1);
119 static int
120 uct_leaf_node(struct uct *u, struct board *b, enum stone player_color,
121 struct playout_amafmap *amaf,
122 struct uct_descent *descent, int *dlen,
123 struct tree_node *significant[2],
124 struct tree *t, struct tree_node *n, enum stone node_color,
125 char *spaces)
127 enum stone next_color = stone_other(node_color);
128 int parity = (next_color == player_color ? 1 : -1);
130 if (UDEBUGL(7))
131 fprintf(stderr, "%s*-- UCT playout #%d start [%s] %f\n",
132 spaces, n->u.playouts, coord2sstr(node_coord(n), t->board),
133 tree_node_get_value(t, parity, n->u.value));
135 struct uct_playout_callback upc = {
136 .uct = u,
137 .tree = t,
138 /* TODO: Don't necessarily restart the sequence walk when
139 * entering playout. */
140 .lnode = NULL,
143 struct playout_setup ps = {
144 .gamelen = u->gamelen,
145 .mercymin = u->mercymin,
146 .prepolicy_hook = uct_playout_prepolicy,
147 .postpolicy_hook = uct_playout_postpolicy,
148 .hook_data = &upc,
150 int result = play_random_game(&ps, b, next_color,
151 u->playout_amaf ? amaf : NULL,
152 &u->ownermap, u->playout);
153 if (next_color == S_WHITE) {
154 /* We need the result from black's perspective. */
155 result = - result;
157 if (UDEBUGL(7))
158 fprintf(stderr, "%s -- [%d..%d] %s random playout result %d\n",
159 spaces, player_color, next_color, coord2sstr(node_coord(n), t->board), result);
161 return result;
164 static floating_t
165 scale_value(struct uct *u, struct board *b, int result)
167 floating_t rval = result > 0 ? 1.0 : result < 0 ? 0.0 : 0.5;
168 if (u->val_scale && result != 0) {
169 int vp = u->val_points;
170 if (!vp) {
171 vp = board_size(b) - 1; vp *= vp; vp *= 2;
174 floating_t sval = (floating_t) abs(result) / vp;
175 sval = sval > 1 ? 1 : sval;
176 if (result < 0) sval = 1 - sval;
177 if (u->val_extra)
178 rval += u->val_scale * sval;
179 else
180 rval = (1 - u->val_scale) * rval + u->val_scale * sval;
181 // fprintf(stderr, "score %d => sval %f, rval %f\n", result, sval, rval);
183 return rval;
186 static double
187 local_value(struct uct *u, struct board *b, coord_t coord, enum stone color)
189 /* Tactical evaluation of move @coord by color @color, given
190 * simulation end position @b. I.e., a move is tactically good
191 * if the resulting group stays on board until the game end. */
192 /* We can also take into account surrounding stones, e.g. to
193 * encourage taking off external liberties during a semeai. */
194 double val = board_local_value(u->local_tree_neival, b, coord, color);
195 return (color == S_WHITE) ? 1.f - val : val;
198 static void
199 record_local_sequence(struct uct *u, struct tree *t, struct board *endb,
200 struct uct_descent *descent, int dlen, int di,
201 enum stone seq_color)
203 #define LTREE_DEBUG if (UDEBUGL(6))
205 /* Ignore pass sequences. */
206 if (is_pass(node_coord(descent[di].node)))
207 return;
209 LTREE_DEBUG board_print(endb, stderr);
210 LTREE_DEBUG fprintf(stderr, "recording local %s sequence: ",
211 stone2str(seq_color));
213 /* Sequences starting deeper are less relevant in general. */
214 int pval = LTREE_PLAYOUTS_MULTIPLIER;
215 if (u->local_tree && u->local_tree_depth_decay > 0)
216 pval = ((floating_t) pval) / pow(u->local_tree_depth_decay, di - 1);
217 if (!pval) {
218 LTREE_DEBUG fprintf(stderr, "too deep @%d\n", di);
219 return;
222 /* Pick the right local tree root... */
223 struct tree_node *lnode = seq_color == S_BLACK ? t->ltree_black : t->ltree_white;
224 lnode->u.playouts++;
226 double sval = 0.5;
227 if (u->local_tree_rootgoal) {
228 sval = local_value(u, endb, node_coord(descent[di].node), seq_color);
229 LTREE_DEBUG fprintf(stderr, "(goal %s[%s %1.3f][%d]) ",
230 coord2sstr(node_coord(descent[di].node), t->board),
231 stone2str(seq_color), sval, descent[di].node->d);
234 /* ...and record the sequence. */
235 int di0 = di;
236 while (di < dlen && (di == di0 || descent[di].node->d < u->tenuki_d)) {
237 enum stone color = (di - di0) % 2 ? stone_other(seq_color) : seq_color;
238 double rval;
239 if (u->local_tree_rootgoal)
240 rval = sval;
241 else
242 rval = local_value(u, endb, node_coord(descent[di].node), color);
243 LTREE_DEBUG fprintf(stderr, "%s[%s %1.3f][%d] ",
244 coord2sstr(node_coord(descent[di].node), t->board),
245 stone2str(color), rval, descent[di].node->d);
246 lnode = tree_get_node(t, lnode, node_coord(descent[di++].node), true);
247 assert(lnode);
248 stats_add_result(&lnode->u, rval, pval);
251 /* Add lnode for tenuki (pass) if we descended further. */
252 if (di < dlen) {
253 double rval = u->local_tree_rootgoal ? sval : 0.5;
254 LTREE_DEBUG fprintf(stderr, "pass ");
255 lnode = tree_get_node(t, lnode, pass, true);
256 assert(lnode);
257 stats_add_result(&lnode->u, rval, pval);
260 LTREE_DEBUG fprintf(stderr, "\n");
265 uct_playout(struct uct *u, struct board *b, enum stone player_color, struct tree *t)
267 struct board b2;
268 board_copy(&b2, b);
270 struct playout_amafmap amaf;
271 amaf.gamelen = amaf.game_baselen = 0;
273 /* Walk the tree until we find a leaf, then expand it and do
274 * a random playout. */
275 struct tree_node *n = t->root;
276 enum stone node_color = stone_other(player_color);
277 assert(node_color == t->root_color);
279 /* Make sure the root node is expanded. */
280 if (tree_leaf_node(n) && !__sync_lock_test_and_set(&n->is_expanded, 1))
281 tree_expand_node(t, n, &b2, player_color, u, 1);
283 /* Tree descent history. */
284 /* XXX: This is somewhat messy since @n and descent[dlen-1].node are
285 * redundant. */
286 struct uct_descent descent[DESCENT_DLEN];
287 descent[0].node = n; descent[0].lnode = NULL;
288 int dlen = 1;
289 /* Total value of the sequence. */
290 struct move_stats seq_value = { .playouts = 0 };
291 /* The last "significant" node along the descent (i.e. node
292 * with higher than configured number of playouts). For black
293 * and white. */
294 struct tree_node *significant[2] = { NULL, NULL };
295 if (n->u.playouts >= u->significant_threshold)
296 significant[node_color - 1] = n;
298 int result;
299 int pass_limit = (board_size(&b2) - 2) * (board_size(&b2) - 2) / 2;
300 int passes = is_pass(b->last_move.coord) && b->moves > 0;
302 /* debug */
303 static char spaces[] = "\0 ";
304 /* /debug */
305 if (UDEBUGL(8))
306 fprintf(stderr, "--- UCT walk with color %d\n", player_color);
308 while (!tree_leaf_node(n) && passes < 2) {
309 spaces[dlen - 1] = ' '; spaces[dlen] = 0;
312 /*** Choose a node to descend to: */
314 /* Parity is chosen already according to the child color, since
315 * it is applied to children. */
316 node_color = stone_other(node_color);
317 int parity = (node_color == player_color ? 1 : -1);
319 assert(dlen < DESCENT_DLEN);
320 descent[dlen] = descent[dlen - 1];
321 if (u->local_tree && (!descent[dlen].lnode || descent[dlen].node->d >= u->tenuki_d)) {
322 /* Start new local sequence. */
323 /* Remember that node_color already holds color of the
324 * to-be-found child. */
325 descent[dlen].lnode = node_color == S_BLACK ? t->ltree_black : t->ltree_white;
328 if (!u->random_policy_chance || fast_random(u->random_policy_chance))
329 u->policy->descend(u->policy, t, &descent[dlen], parity, b2.moves > pass_limit);
330 else
331 u->random_policy->descend(u->random_policy, t, &descent[dlen], parity, b2.moves > pass_limit);
334 /*** Perform the descent: */
336 if (descent[dlen].node->u.playouts >= u->significant_threshold) {
337 significant[node_color - 1] = descent[dlen].node;
340 seq_value.playouts += descent[dlen].value.playouts;
341 seq_value.value += descent[dlen].value.value * descent[dlen].value.playouts;
342 n = descent[dlen++].node;
343 assert(n == t->root || n->parent);
344 if (UDEBUGL(7))
345 fprintf(stderr, "%s+-- UCT sent us to [%s:%d] %d,%f\n",
346 spaces, coord2sstr(node_coord(n), t->board),
347 node_coord(n), n->u.playouts,
348 tree_node_get_value(t, parity, n->u.value));
350 /* Add virtual loss if we need to; this is used to discourage
351 * other threads from visiting this node in case of multiple
352 * threads doing the tree search. */
353 if (u->virtual_loss)
354 stats_add_result(&n->u, node_color == S_BLACK ? 0.0 : 1.0, u->virtual_loss);
356 assert(node_coord(n) >= -1);
357 record_amaf_move(&amaf, node_coord(n));
359 struct move m = { node_coord(n), node_color };
360 int res = board_play(&b2, &m);
362 if (res < 0 || (!is_pass(m.coord) && !group_at(&b2, m.coord)) /* suicide */
363 || b2.superko_violation) {
364 if (UDEBUGL(4)) {
365 for (struct tree_node *ni = n; ni; ni = ni->parent)
366 fprintf(stderr, "%s<%"PRIhash"> ", coord2sstr(node_coord(ni), t->board), ni->hash);
367 fprintf(stderr, "marking invalid %s node %d,%d res %d group %d spk %d\n",
368 stone2str(node_color), coord_x(node_coord(n),b), coord_y(node_coord(n),b),
369 res, group_at(&b2, m.coord), b2.superko_violation);
371 n->hints |= TREE_HINT_INVALID;
372 result = 0;
373 goto end;
376 if (is_pass(node_coord(n)))
377 passes++;
378 else
379 passes = 0;
381 enum stone next_color = stone_other(node_color);
382 /* We need to make sure only one thread expands the node. If
383 * we are unlucky enough for two threads to meet in the same
384 * node, the latter one will simply do another simulation from
385 * the node itself, no big deal. t->nodes_size may exceed
386 * the maximum in multi-threaded case but not by much so it's ok.
387 * The size test must be before the test&set not after, to allow
388 * expansion of the node later if enough nodes have been freed. */
389 if (tree_leaf_node(n)
390 && n->u.playouts - u->virtual_loss >= u->expand_p && t->nodes_size < u->max_tree_size
391 && !__sync_lock_test_and_set(&n->is_expanded, 1))
392 tree_expand_node(t, n, &b2, next_color, u, -parity);
395 amaf.game_baselen = amaf.gamelen;
397 if (t->use_extra_komi && u->dynkomi->persim) {
398 b2.komi += round(u->dynkomi->persim(u->dynkomi, &b2, t, n));
401 if (passes >= 2) {
402 /* XXX: No dead groups support. */
403 floating_t score = board_official_score(&b2, NULL);
404 /* Result from black's perspective (no matter who
405 * the player; black's perspective is always
406 * what the tree stores. */
407 result = - (score * 2);
409 if (UDEBUGL(5))
410 fprintf(stderr, "[%d..%d] %s p-p scoring playout result %d (W %f)\n",
411 player_color, node_color, coord2sstr(node_coord(n), t->board), result, score);
412 if (UDEBUGL(6))
413 board_print(&b2, stderr);
415 board_ownermap_fill(&u->ownermap, &b2);
417 } else { // assert(tree_leaf_node(n));
418 /* In case of parallel tree search, the assertion might
419 * not hold if two threads chew on the same node. */
420 result = uct_leaf_node(u, &b2, player_color, &amaf, descent, &dlen, significant, t, n, node_color, spaces);
423 if (u->policy->wants_amaf && u->playout_amaf_cutoff) {
424 unsigned int cutoff = amaf.game_baselen;
425 cutoff += (amaf.gamelen - amaf.game_baselen) * u->playout_amaf_cutoff / 100;
426 amaf.gamelen = cutoff;
429 /* Record the result. */
431 assert(n == t->root || n->parent);
432 floating_t rval = scale_value(u, b, result);
433 u->policy->update(u->policy, t, n, node_color, player_color, &amaf, &b2, rval);
435 if (t->use_extra_komi) {
436 stats_add_result(&u->dynkomi->score, result / 2, 1);
437 stats_add_result(&u->dynkomi->value, rval, 1);
440 if (u->local_tree && n->parent && !is_pass(node_coord(n)) && dlen > 0) {
441 /* Get the local sequences and record them in ltree. */
442 /* We will look for sequence starts in our descent
443 * history, then run record_local_sequence() for each
444 * found sequence start; record_local_sequence() may
445 * pick longer sequences from descent history then,
446 * which is expected as it will create new lnodes. */
447 enum stone seq_color = player_color;
448 /* First move always starts a sequence. */
449 record_local_sequence(u, t, &b2, descent, dlen, 1, seq_color);
450 seq_color = stone_other(seq_color);
451 for (int dseqi = 2; dseqi < dlen; dseqi++, seq_color = stone_other(seq_color)) {
452 if (u->local_tree_allseq) {
453 /* We are configured to record all subsequences. */
454 record_local_sequence(u, t, &b2, descent, dlen, dseqi, seq_color);
455 continue;
457 if (descent[dseqi].node->d >= u->tenuki_d) {
458 /* Tenuki! Record the fresh sequence. */
459 record_local_sequence(u, t, &b2, descent, dlen, dseqi, seq_color);
460 continue;
462 if (descent[dseqi].lnode && !descent[dseqi].lnode) {
463 /* Record result for in-descent picked sequence. */
464 record_local_sequence(u, t, &b2, descent, dlen, dseqi, seq_color);
465 continue;
470 end:
471 /* We need to undo the virtual loss we added during descend. */
472 if (u->virtual_loss) {
473 floating_t loss = node_color == S_BLACK ? 0.0 : 1.0;
474 for (; n->parent; n = n->parent) {
475 stats_rm_result(&n->u, loss, u->virtual_loss);
476 loss = 1.0 - loss;
480 board_done_noalloc(&b2);
481 return result;
485 uct_playouts(struct uct *u, struct board *b, enum stone color, struct tree *t, struct time_info *ti)
487 int i;
488 if (ti && ti->dim == TD_GAMES) {
489 for (i = 0; t->root->u.playouts <= ti->len.games && !uct_halt; i++)
490 uct_playout(u, b, color, t);
491 } else {
492 for (i = 0; !uct_halt; i++)
493 uct_playout(u, b, color, t);
495 return i;