UCT local_tree_eval=total: Introduce
[pachi/t.git] / uct / walk.c
blob0d5ac6df9441738e0559515fcd382f6142036c4b
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 /* ...determine the sequence value... */
227 double sval = 0.5;
228 if (u->local_tree_eval != LTE_EACH) {
229 sval = local_value(u, endb, node_coord(descent[di].node), seq_color);
230 LTREE_DEBUG fprintf(stderr, "(goal %s[%s %1.3f][%d]) ",
231 coord2sstr(node_coord(descent[di].node), t->board),
232 stone2str(seq_color), sval, descent[di].node->d);
234 if (u->local_tree_eval == LTE_TOTAL) {
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 = local_value(u, endb, node_coord(descent[di].node), color);
239 if ((di - di0) % 2)
240 rval = 1 - rval;
241 sval += rval;
242 di++;
244 sval /= (di - di0 + 1);
245 di = di0;
249 /* ...and record the sequence. */
250 int di0 = di;
251 while (di < dlen && (di == di0 || descent[di].node->d < u->tenuki_d)) {
252 enum stone color = (di - di0) % 2 ? stone_other(seq_color) : seq_color;
253 double rval;
254 if (u->local_tree_eval != LTE_EACH)
255 rval = sval;
256 else
257 rval = local_value(u, endb, node_coord(descent[di].node), color);
258 LTREE_DEBUG fprintf(stderr, "%s[%s %1.3f][%d] ",
259 coord2sstr(node_coord(descent[di].node), t->board),
260 stone2str(color), rval, descent[di].node->d);
261 lnode = tree_get_node(t, lnode, node_coord(descent[di++].node), true);
262 assert(lnode);
263 stats_add_result(&lnode->u, rval, pval);
266 /* Add lnode for tenuki (pass) if we descended further. */
267 if (di < dlen) {
268 double rval = u->local_tree_eval != LTE_EACH ? sval : 0.5;
269 LTREE_DEBUG fprintf(stderr, "pass ");
270 lnode = tree_get_node(t, lnode, pass, true);
271 assert(lnode);
272 stats_add_result(&lnode->u, rval, pval);
275 LTREE_DEBUG fprintf(stderr, "\n");
280 uct_playout(struct uct *u, struct board *b, enum stone player_color, struct tree *t)
282 struct board b2;
283 board_copy(&b2, b);
285 struct playout_amafmap amaf;
286 amaf.gamelen = amaf.game_baselen = 0;
288 /* Walk the tree until we find a leaf, then expand it and do
289 * a random playout. */
290 struct tree_node *n = t->root;
291 enum stone node_color = stone_other(player_color);
292 assert(node_color == t->root_color);
294 /* Make sure the root node is expanded. */
295 if (tree_leaf_node(n) && !__sync_lock_test_and_set(&n->is_expanded, 1))
296 tree_expand_node(t, n, &b2, player_color, u, 1);
298 /* Tree descent history. */
299 /* XXX: This is somewhat messy since @n and descent[dlen-1].node are
300 * redundant. */
301 struct uct_descent descent[DESCENT_DLEN];
302 descent[0].node = n; descent[0].lnode = NULL;
303 int dlen = 1;
304 /* Total value of the sequence. */
305 struct move_stats seq_value = { .playouts = 0 };
306 /* The last "significant" node along the descent (i.e. node
307 * with higher than configured number of playouts). For black
308 * and white. */
309 struct tree_node *significant[2] = { NULL, NULL };
310 if (n->u.playouts >= u->significant_threshold)
311 significant[node_color - 1] = n;
313 int result;
314 int pass_limit = (board_size(&b2) - 2) * (board_size(&b2) - 2) / 2;
315 int passes = is_pass(b->last_move.coord) && b->moves > 0;
317 /* debug */
318 static char spaces[] = "\0 ";
319 /* /debug */
320 if (UDEBUGL(8))
321 fprintf(stderr, "--- UCT walk with color %d\n", player_color);
323 while (!tree_leaf_node(n) && passes < 2) {
324 spaces[dlen - 1] = ' '; spaces[dlen] = 0;
327 /*** Choose a node to descend to: */
329 /* Parity is chosen already according to the child color, since
330 * it is applied to children. */
331 node_color = stone_other(node_color);
332 int parity = (node_color == player_color ? 1 : -1);
334 assert(dlen < DESCENT_DLEN);
335 descent[dlen] = descent[dlen - 1];
336 if (u->local_tree && (!descent[dlen].lnode || descent[dlen].node->d >= u->tenuki_d)) {
337 /* Start new local sequence. */
338 /* Remember that node_color already holds color of the
339 * to-be-found child. */
340 descent[dlen].lnode = node_color == S_BLACK ? t->ltree_black : t->ltree_white;
343 if (!u->random_policy_chance || fast_random(u->random_policy_chance))
344 u->policy->descend(u->policy, t, &descent[dlen], parity, b2.moves > pass_limit);
345 else
346 u->random_policy->descend(u->random_policy, t, &descent[dlen], parity, b2.moves > pass_limit);
349 /*** Perform the descent: */
351 if (descent[dlen].node->u.playouts >= u->significant_threshold) {
352 significant[node_color - 1] = descent[dlen].node;
355 seq_value.playouts += descent[dlen].value.playouts;
356 seq_value.value += descent[dlen].value.value * descent[dlen].value.playouts;
357 n = descent[dlen++].node;
358 assert(n == t->root || n->parent);
359 if (UDEBUGL(7))
360 fprintf(stderr, "%s+-- UCT sent us to [%s:%d] %d,%f\n",
361 spaces, coord2sstr(node_coord(n), t->board),
362 node_coord(n), n->u.playouts,
363 tree_node_get_value(t, parity, n->u.value));
365 /* Add virtual loss if we need to; this is used to discourage
366 * other threads from visiting this node in case of multiple
367 * threads doing the tree search. */
368 if (u->virtual_loss)
369 stats_add_result(&n->u, node_color == S_BLACK ? 0.0 : 1.0, u->virtual_loss);
371 assert(node_coord(n) >= -1);
372 record_amaf_move(&amaf, node_coord(n));
374 struct move m = { node_coord(n), node_color };
375 int res = board_play(&b2, &m);
377 if (res < 0 || (!is_pass(m.coord) && !group_at(&b2, m.coord)) /* suicide */
378 || b2.superko_violation) {
379 if (UDEBUGL(4)) {
380 for (struct tree_node *ni = n; ni; ni = ni->parent)
381 fprintf(stderr, "%s<%"PRIhash"> ", coord2sstr(node_coord(ni), t->board), ni->hash);
382 fprintf(stderr, "marking invalid %s node %d,%d res %d group %d spk %d\n",
383 stone2str(node_color), coord_x(node_coord(n),b), coord_y(node_coord(n),b),
384 res, group_at(&b2, m.coord), b2.superko_violation);
386 n->hints |= TREE_HINT_INVALID;
387 result = 0;
388 goto end;
391 if (is_pass(node_coord(n)))
392 passes++;
393 else
394 passes = 0;
396 enum stone next_color = stone_other(node_color);
397 /* We need to make sure only one thread expands the node. If
398 * we are unlucky enough for two threads to meet in the same
399 * node, the latter one will simply do another simulation from
400 * the node itself, no big deal. t->nodes_size may exceed
401 * the maximum in multi-threaded case but not by much so it's ok.
402 * The size test must be before the test&set not after, to allow
403 * expansion of the node later if enough nodes have been freed. */
404 if (tree_leaf_node(n)
405 && n->u.playouts - u->virtual_loss >= u->expand_p && t->nodes_size < u->max_tree_size
406 && !__sync_lock_test_and_set(&n->is_expanded, 1))
407 tree_expand_node(t, n, &b2, next_color, u, -parity);
410 amaf.game_baselen = amaf.gamelen;
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 (u->policy->wants_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 amaf.gamelen = cutoff;
444 /* Record the result. */
446 assert(n == t->root || n->parent);
447 floating_t rval = scale_value(u, b, result);
448 u->policy->update(u->policy, t, n, node_color, player_color, &amaf, &b2, rval);
450 if (t->use_extra_komi) {
451 stats_add_result(&u->dynkomi->score, result / 2, 1);
452 stats_add_result(&u->dynkomi->value, rval, 1);
455 if (u->local_tree && n->parent && !is_pass(node_coord(n)) && dlen > 0) {
456 /* Get the local sequences and record them in ltree. */
457 /* We will look for sequence starts in our descent
458 * history, then run record_local_sequence() for each
459 * found sequence start; record_local_sequence() may
460 * pick longer sequences from descent history then,
461 * which is expected as it will create new lnodes. */
462 enum stone seq_color = player_color;
463 /* First move always starts a sequence. */
464 record_local_sequence(u, t, &b2, descent, dlen, 1, seq_color);
465 seq_color = stone_other(seq_color);
466 for (int dseqi = 2; dseqi < dlen; dseqi++, seq_color = stone_other(seq_color)) {
467 if (u->local_tree_allseq) {
468 /* We are configured to record all subsequences. */
469 record_local_sequence(u, t, &b2, descent, dlen, dseqi, seq_color);
470 continue;
472 if (descent[dseqi].node->d >= u->tenuki_d) {
473 /* Tenuki! Record the fresh sequence. */
474 record_local_sequence(u, t, &b2, descent, dlen, dseqi, seq_color);
475 continue;
477 if (descent[dseqi].lnode && !descent[dseqi].lnode) {
478 /* Record result for in-descent picked sequence. */
479 record_local_sequence(u, t, &b2, descent, dlen, dseqi, seq_color);
480 continue;
485 end:
486 /* We need to undo the virtual loss we added during descend. */
487 if (u->virtual_loss) {
488 floating_t loss = node_color == S_BLACK ? 0.0 : 1.0;
489 for (; n->parent; n = n->parent) {
490 stats_rm_result(&n->u, loss, u->virtual_loss);
491 loss = 1.0 - loss;
495 board_done_noalloc(&b2);
496 return result;
500 uct_playouts(struct uct *u, struct board *b, enum stone color, struct tree *t, struct time_info *ti)
502 int i;
503 if (ti && ti->dim == TD_GAMES) {
504 for (i = 0; t->root->u.playouts <= ti->len.games && !uct_halt; i++)
505 uct_playout(u, b, color, t);
506 } else {
507 for (i = 0; !uct_halt; i++)
508 uct_playout(u, b, color, t);
510 return i;