Moggy Joseki: Remove stray debug print
[pachi/peepo.git] / uct / walk.c
blobc4ae634fb2a02dc35f8dc3875195610575c08b9d
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 "playout/elo.h"
16 #include "probdist.h"
17 #include "random.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 void
26 uct_progress_status(struct uct *u, struct tree *t, enum stone color, int playouts)
28 if (!UDEBUGL(0))
29 return;
31 /* Best move */
32 struct tree_node *best = u->policy->choose(u->policy, t->root, t->board, color, resign);
33 if (!best) {
34 fprintf(stderr, "... No moves left\n");
35 return;
37 fprintf(stderr, "[%d] ", playouts);
38 fprintf(stderr, "best %f ", tree_node_get_value(t, 1, best->u.value));
40 /* Dynamic komi */
41 if (t->use_extra_komi)
42 fprintf(stderr, "komi %.1f ", t->extra_komi);
44 /* Best sequence */
45 fprintf(stderr, "| seq ");
46 for (int depth = 0; depth < 4; depth++) {
47 if (best && best->u.playouts >= 25) {
48 fprintf(stderr, "%3s ", coord2sstr(best->coord, t->board));
49 best = u->policy->choose(u->policy, best, t->board, color, resign);
50 } else {
51 fprintf(stderr, " ");
55 /* Best candidates */
56 fprintf(stderr, "| can ");
57 int cans = 4;
58 struct tree_node *can[cans];
59 memset(can, 0, sizeof(can));
60 best = t->root->children;
61 while (best) {
62 int c = 0;
63 while ((!can[c] || best->u.playouts > can[c]->u.playouts) && ++c < cans);
64 for (int d = 0; d < c; d++) can[d] = can[d + 1];
65 if (c > 0) can[c - 1] = best;
66 best = best->sibling;
68 while (--cans >= 0) {
69 if (can[cans]) {
70 fprintf(stderr, "%3s(%.3f) ",
71 coord2sstr(can[cans]->coord, t->board),
72 tree_node_get_value(t, 1, can[cans]->u.value));
73 } else {
74 fprintf(stderr, " ");
78 fprintf(stderr, "\n");
82 struct uct_playout_callback {
83 struct uct *uct;
84 struct tree *tree;
85 struct tree_node *lnode;
88 static void
89 uct_playout_probdist(void *data, struct board *b, enum stone to_play, struct probdist *pd)
91 /* Create probability distribution according to found local tree
92 * sequence. */
93 struct uct_playout_callback *upc = data;
94 assert(upc && upc->tree && pd && b);
95 coord_t c = b->last_move.coord;
96 enum stone color = b->last_move.color;
98 if (is_pass(c)) {
99 /* Break local sequence. */
100 upc->lnode = NULL;
101 } else if (upc->lnode) {
102 /* Try to follow local sequence. */
103 upc->lnode = tree_get_node(upc->tree, upc->lnode, c, false);
106 if (!upc->lnode || !upc->lnode->children) {
107 /* There's no local sequence, start new one! */
108 upc->lnode = color == S_BLACK ? upc->tree->ltree_black : upc->tree->ltree_white;
109 upc->lnode = tree_get_node(upc->tree, upc->lnode, c, false);
112 if (!upc->lnode || !upc->lnode->children) {
113 /* We have no local sequence and we cannot find any starting
114 * by node corresponding to last move. */
115 if (!upc->uct->local_tree_pseqroot) {
116 /* Give up then, we have nothing to contribute. */
117 return;
119 /* Construct probability distribution from possible first
120 * sequence move. Remember that @color is color of the
121 * *last* move. */
122 upc->lnode = color == S_BLACK ? upc->tree->ltree_white : upc->tree->ltree_black;
123 if (!upc->lnode->children) {
124 /* We don't even have anything in our tree yet. */
125 return;
129 /* The probdist has the right structure only if BOARD_GAMMA is defined. */
130 #ifndef BOARD_GAMMA
131 assert(0);
132 #endif
134 /* Construct probability distribution from lnode children. */
135 /* XXX: How to derive the appropriate gamma? */
136 #define li_value(color, li) (li->u.playouts * (color == S_BLACK ? li->u.value : (1 - li->u.value)))
137 #define li_gamma(color, li) (0.5 + li_value(color, li))
138 struct tree_node *li = upc->lnode->children;
139 assert(li);
140 if (is_pass(li->coord)) {
141 /* Tenuki. */
142 /* TODO: Spread tenuki gamma over all moves we don't touch. */
143 li = li->sibling;
145 for (; li; li = li->sibling) {
146 if (board_at(b, li->coord) != S_NONE)
147 continue;
148 probdist_set(pd, li->coord, double_to_fixp(pd->items[li->coord] * li_gamma(to_play, li)));
153 static int
154 uct_leaf_node(struct uct *u, struct board *b, enum stone player_color,
155 struct playout_amafmap *amaf,
156 struct tree *t, struct tree_node *n, enum stone node_color,
157 char *spaces)
159 enum stone next_color = stone_other(node_color);
160 int parity = (next_color == player_color ? 1 : -1);
162 /* If we don't anticipate well the opponent move during pondering
163 * (the played move has few playouts) we still need more memory
164 * during genmove to explore the tree actually played.
165 * For fast_alloc, the tree compaction will free enough memory
166 * immediately. */
167 unsigned long max_tree_size = u->max_tree_size;
168 if (u->pondering && !u->fast_alloc)
169 max_tree_size = (max_tree_size * (100 - MIN_FREE_MEM_PERCENT)) / 100;
171 /* We need to make sure only one thread expands the node. If
172 * we are unlucky enough for two threads to meet in the same
173 * node, the latter one will simply do another simulation from
174 * the node itself, no big deal. t->nodes_size may exceed
175 * the maximum in multi-threaded case but not by much so it's ok.
176 * The size test must be before the test&set not after, to allow
177 * expansion of the node later if enough nodes have been freed. */
178 if (n->u.playouts >= u->expand_p && t->nodes_size < max_tree_size
179 && !__sync_lock_test_and_set(&n->is_expanded, 1)) {
180 tree_expand_node(t, n, b, next_color, u, parity);
182 if (UDEBUGL(7))
183 fprintf(stderr, "%s*-- UCT playout #%d start [%s] %f\n",
184 spaces, n->u.playouts, coord2sstr(n->coord, t->board),
185 tree_node_get_value(t, parity, n->u.value));
187 /* TODO: Don't necessarily restart the sequence walk when entering
188 * playout. */
189 struct uct_playout_callback upc = { .uct = u, .tree = t, .lnode = NULL };
190 if (u->local_tree_playout) {
191 /* N.B.: We know this is ELO playout. */
192 playout_elo_callback(u->playout, uct_playout_probdist, &upc);
195 struct playout_setup ps = { .gamelen = u->gamelen, .mercymin = u->mercymin };
196 int result = play_random_game(&ps, b, next_color,
197 u->playout_amaf ? amaf : NULL,
198 &u->ownermap, u->playout);
199 if (next_color == S_WHITE) {
200 /* We need the result from black's perspective. */
201 result = - result;
203 if (UDEBUGL(7))
204 fprintf(stderr, "%s -- [%d..%d] %s random playout result %d\n",
205 spaces, player_color, next_color, coord2sstr(n->coord, t->board), result);
207 return result;
210 static float
211 scale_value(struct uct *u, struct board *b, int result)
213 float rval = result > 0;
214 if (u->val_scale) {
215 int vp = u->val_points;
216 if (!vp) {
217 vp = board_size(b) - 1; vp *= vp; vp *= 2;
220 float sval = (float) abs(result) / vp;
221 sval = sval > 1 ? 1 : sval;
222 if (result < 0) sval = 1 - sval;
223 if (u->val_extra)
224 rval += u->val_scale * sval;
225 else
226 rval = (1 - u->val_scale) * rval + u->val_scale * sval;
227 // fprintf(stderr, "score %d => sval %f, rval %f\n", result, sval, rval);
229 return rval;
232 static void
233 record_local_sequence(struct uct *u, struct tree *t,
234 struct uct_descent *descent, int dlen, int di,
235 enum stone seq_color, float rval)
237 /* Ignore pass sequences. */
238 if (is_pass(descent[di].node->coord))
239 return;
241 #define LTREE_DEBUG if (UDEBUGL(6))
242 LTREE_DEBUG fprintf(stderr, "recording result %f in local %s sequence: ",
243 rval, stone2str(seq_color));
244 int di0 = di;
246 /* Pick the right local tree root... */
247 struct tree_node *lnode = seq_color == S_BLACK ? t->ltree_black : t->ltree_white;
248 lnode->u.playouts++;
250 /* ...and record the sequence. */
251 while (di < dlen && (di == di0 || descent[di].node->d < u->tenuki_d)) {
252 LTREE_DEBUG fprintf(stderr, "%s[%d] ",
253 coord2sstr(descent[di].node->coord, t->board),
254 descent[di].node->d);
255 lnode = tree_get_node(t, lnode, descent[di++].node->coord, true);
256 assert(lnode);
257 stats_add_result(&lnode->u, rval, 1);
260 /* Add lnode for tenuki (pass) if we descended further. */
261 if (di < dlen) {
262 LTREE_DEBUG fprintf(stderr, "pass ");
263 lnode = tree_get_node(t, lnode, pass, true);
264 assert(lnode);
265 stats_add_result(&lnode->u, rval, 1);
268 LTREE_DEBUG fprintf(stderr, "\n");
273 uct_playout(struct uct *u, struct board *b, enum stone player_color, struct tree *t)
275 struct board b2;
276 board_copy(&b2, b);
278 struct playout_amafmap *amaf = NULL;
279 if (u->policy->wants_amaf) {
280 amaf = calloc2(1, sizeof(*amaf));
281 amaf->map = calloc2(board_size2(&b2) + 1, sizeof(*amaf->map));
282 amaf->map++; // -1 is pass
285 /* Walk the tree until we find a leaf, then expand it and do
286 * a random playout. */
287 struct tree_node *n = t->root;
288 enum stone node_color = stone_other(player_color);
289 assert(node_color == t->root_color);
291 /* Tree descent history. */
292 /* XXX: This is somewhat messy since @n and descent[dlen-1].node are
293 * redundant. */
294 #define DLEN 512
295 struct uct_descent descent[DLEN];
296 descent[0].node = n; descent[0].lnode = NULL;
297 int dlen = 1;
298 /* Total value of the sequence. */
299 struct move_stats seq_value = { .playouts = 0 };
301 int result;
302 int pass_limit = (board_size(&b2) - 2) * (board_size(&b2) - 2) / 2;
303 int passes = is_pass(b->last_move.coord) && b->moves > 0;
305 /* debug */
306 int depth = 0;
307 static char spaces[] = "\0 ";
308 /* /debug */
309 if (UDEBUGL(8))
310 fprintf(stderr, "--- UCT walk with color %d\n", player_color);
312 while (!tree_leaf_node(n) && passes < 2) {
313 spaces[depth++] = ' '; spaces[depth] = 0;
316 /*** Choose a node to descend to: */
318 /* Parity is chosen already according to the child color, since
319 * it is applied to children. */
320 node_color = stone_other(node_color);
321 int parity = (node_color == player_color ? 1 : -1);
323 assert(dlen < DLEN);
324 descent[dlen] = descent[dlen - 1];
325 if (u->local_tree && (!descent[dlen].lnode || descent[dlen].node->d >= u->tenuki_d)) {
326 /* Start new local sequence. */
327 /* Remember that node_color already holds color of the
328 * to-be-found child. */
329 descent[dlen].lnode = node_color == S_BLACK ? t->ltree_black : t->ltree_white;
332 if (!u->random_policy_chance || fast_random(u->random_policy_chance))
333 u->policy->descend(u->policy, t, &descent[dlen], parity, b2.moves > pass_limit);
334 else
335 u->random_policy->descend(u->random_policy, t, &descent[dlen], parity, b2.moves > pass_limit);
338 /*** Perform the descent: */
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] %f\n",
346 spaces, coord2sstr(n->coord, t->board), n->coord,
347 tree_node_get_value(t, parity, n->u.value));
349 /* Add virtual loss if we need to; this is used to discourage
350 * other threads from visiting this node in case of multiple
351 * threads doing the tree search. */
352 if (u->virtual_loss)
353 stats_add_result(&n->u, tree_parity(t, parity) > 0 ? 0 : 1, 1);
355 assert(n->coord >= -1);
356 if (amaf && !is_pass(n->coord)) {
357 if (amaf->map[n->coord] == S_NONE || amaf->map[n->coord] == node_color) {
358 amaf->map[n->coord] = node_color;
359 } else { // XXX: Respect amaf->record_nakade
360 amaf_op(amaf->map[n->coord], +);
362 amaf->game[amaf->gamelen].coord = n->coord;
363 amaf->game[amaf->gamelen].color = node_color;
364 amaf->gamelen++;
365 assert(amaf->gamelen < sizeof(amaf->game) / sizeof(amaf->game[0]));
368 struct move m = { n->coord, node_color };
369 int res = board_play(&b2, &m);
371 if (res < 0 || (!is_pass(m.coord) && !group_at(&b2, m.coord)) /* suicide */
372 || b2.superko_violation) {
373 if (UDEBUGL(4)) {
374 for (struct tree_node *ni = n; ni; ni = ni->parent)
375 fprintf(stderr, "%s<%"PRIhash"> ", coord2sstr(ni->coord, t->board), ni->hash);
376 fprintf(stderr, "marking invalid %s node %d,%d res %d group %d spk %d\n",
377 stone2str(node_color), coord_x(n->coord,b), coord_y(n->coord,b),
378 res, group_at(&b2, m.coord), b2.superko_violation);
380 n->hints |= TREE_HINT_INVALID;
381 result = 0;
382 goto end;
385 if (is_pass(n->coord))
386 passes++;
387 else
388 passes = 0;
391 if (amaf) {
392 amaf->game_baselen = amaf->gamelen;
393 amaf->record_nakade = u->playout_amaf_nakade;
396 if (t->use_extra_komi && u->dynkomi->persim) {
397 b2.komi += round(u->dynkomi->persim(u->dynkomi, &b2, t, n));
400 if (passes >= 2) {
401 /* XXX: No dead groups support. */
402 float score = board_official_score(&b2, NULL);
403 /* Result from black's perspective (no matter who
404 * the player; black's perspective is always
405 * what the tree stores. */
406 result = - (score * 2);
408 if (UDEBUGL(5))
409 fprintf(stderr, "[%d..%d] %s p-p scoring playout result %d (W %f)\n",
410 player_color, node_color, coord2sstr(n->coord, t->board), result, score);
411 if (UDEBUGL(6))
412 board_print(&b2, stderr);
414 board_ownermap_fill(&u->ownermap, &b2);
416 } else { // assert(tree_leaf_node(n));
417 /* In case of parallel tree search, the assertion might
418 * not hold if two threads chew on the same node. */
419 result = uct_leaf_node(u, &b2, player_color, amaf, t, n, node_color, spaces);
422 if (amaf && u->playout_amaf_cutoff) {
423 unsigned int cutoff = amaf->game_baselen;
424 cutoff += (amaf->gamelen - amaf->game_baselen) * u->playout_amaf_cutoff / 100;
425 /* Now, reconstruct the amaf map. */
426 memset(amaf->map, 0, board_size2(&b2) * sizeof(*amaf->map));
427 for (unsigned int i = 0; i < cutoff; i++) {
428 coord_t coord = amaf->game[i].coord;
429 enum stone color = amaf->game[i].color;
430 if (amaf->map[coord] == S_NONE || amaf->map[coord] == color) {
431 amaf->map[coord] = color;
432 /* Nakade always recorded for in-tree part */
433 } else if (amaf->record_nakade || i <= amaf->game_baselen) {
434 amaf_op(amaf->map[n->coord], +);
439 assert(n == t->root || n->parent);
440 if (result != 0) {
441 float rval = scale_value(u, b, result);
442 u->policy->update(u->policy, t, n, node_color, player_color, amaf, rval);
444 if (t->use_extra_komi) {
445 stats_add_result(&u->dynkomi->score, result / 2, 1);
446 stats_add_result(&u->dynkomi->value, rval, 1);
449 if (u->local_tree && n->parent && !is_pass(n->coord) && dlen > 0) {
450 /* Possibly transform the rval appropriately. */
451 float expval = seq_value.value / seq_value.playouts;
452 rval = stats_temper_value(rval, expval, u->local_tree);
454 /* Get the local sequences and record them in ltree. */
455 /* We will look for sequence starts in our descent
456 * history, then run record_local_sequence() for each
457 * found sequence start; record_local_sequence() may
458 * pick longer sequences from descent history then,
459 * which is expected as it will create new lnodes. */
460 enum stone seq_color = player_color;
461 /* First move always starts a sequence. */
462 record_local_sequence(u, t, descent, dlen, 1, seq_color, rval);
463 seq_color = stone_other(seq_color);
464 for (int dseqi = 2; dseqi < dlen; dseqi++, seq_color = stone_other(seq_color)) {
465 if (u->local_tree_allseq) {
466 /* We are configured to record all subsequences. */
467 record_local_sequence(u, t, descent, dlen, dseqi, seq_color, rval);
468 continue;
470 if (descent[dseqi].node->d >= u->tenuki_d) {
471 /* Tenuki! Record the fresh sequence. */
472 record_local_sequence(u, t, descent, dlen, dseqi, seq_color, rval);
473 continue;
475 if (descent[dseqi].lnode && !descent[dseqi].lnode) {
476 /* Record result for in-descent picked sequence. */
477 record_local_sequence(u, t, descent, dlen, dseqi, seq_color, rval);
478 continue;
484 end:
485 /* We need to undo the virtual loss we added during descend. */
486 if (u->virtual_loss) {
487 int parity = (node_color == player_color ? 1 : -1);
488 for (; n->parent; n = n->parent) {
489 stats_rm_result(&n->u, tree_parity(t, parity) > 0 ? 0 : 1, 1);
490 parity = -parity;
494 if (amaf) {
495 free(amaf->map - 1);
496 free(amaf);
498 board_done_noalloc(&b2);
499 return result;
503 uct_playouts(struct uct *u, struct board *b, enum stone color, struct tree *t)
505 int i;
506 for (i = 0; !uct_halt; i++)
507 uct_playout(u, b, color, t);
508 return i;