Probdist: Convert all values to newly introduced fixp_t
[pachi.git] / uct / walk.c
blob83a739f3b7ee3958b4e783837d5328a8380a6788
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 /* Max depth */
45 fprintf(stderr, "deepest % 2d ", t->max_depth - t->root->depth);
47 /* Best sequence */
48 fprintf(stderr, "| seq ");
49 for (int depth = 0; depth < 6; depth++) {
50 if (best && best->u.playouts >= 25) {
51 fprintf(stderr, "%3s ", coord2sstr(best->coord, t->board));
52 best = u->policy->choose(u->policy, best, t->board, color, resign);
53 } else {
54 fprintf(stderr, " ");
58 /* Best candidates */
59 fprintf(stderr, "| can ");
60 int cans = 4;
61 struct tree_node *can[cans];
62 memset(can, 0, sizeof(can));
63 best = t->root->children;
64 while (best) {
65 int c = 0;
66 while ((!can[c] || best->u.playouts > can[c]->u.playouts) && ++c < cans);
67 for (int d = 0; d < c; d++) can[d] = can[d + 1];
68 if (c > 0) can[c - 1] = best;
69 best = best->sibling;
71 while (--cans >= 0) {
72 if (can[cans]) {
73 fprintf(stderr, "%3s(%.3f) ",
74 coord2sstr(can[cans]->coord, t->board),
75 tree_node_get_value(t, 1, can[cans]->u.value));
76 } else {
77 fprintf(stderr, " ");
81 fprintf(stderr, "\n");
85 struct uct_playout_callback {
86 struct uct *uct;
87 struct tree *tree;
88 struct tree_node *lnode;
91 static void
92 uct_playout_probdist(void *data, struct board *b, enum stone to_play, struct probdist *pd)
94 /* Create probability distribution according to found local tree
95 * sequence. */
96 struct uct_playout_callback *upc = data;
97 assert(upc && upc->tree && pd && b);
98 coord_t c = b->last_move.coord;
99 enum stone color = b->last_move.color;
101 if (is_pass(c)) {
102 /* Break local sequence. */
103 upc->lnode = NULL;
104 } else if (upc->lnode) {
105 /* Try to follow local sequence. */
106 upc->lnode = tree_get_node(upc->tree, upc->lnode, c, false);
109 if (!upc->lnode || !upc->lnode->children) {
110 /* There's no local sequence, start new one! */
111 upc->lnode = color == S_BLACK ? upc->tree->ltree_black : upc->tree->ltree_white;
112 upc->lnode = tree_get_node(upc->tree, upc->lnode, c, false);
115 if (!upc->lnode || !upc->lnode->children) {
116 /* We have no local sequence and we cannot find any starting
117 * by node corresponding to last move. */
118 if (!upc->uct->local_tree_pseqroot) {
119 /* Give up then, we have nothing to contribute. */
120 return;
122 /* Construct probability distribution from possible first
123 * sequence move. Remember that @color is color of the
124 * *last* move. */
125 upc->lnode = color == S_BLACK ? upc->tree->ltree_white : upc->tree->ltree_black;
126 if (!upc->lnode->children) {
127 /* We don't even have anything in our tree yet. */
128 return;
132 /* The probdist has the right structure only if BOARD_GAMMA is defined. */
133 #ifndef BOARD_GAMMA
134 assert(0);
135 #endif
137 /* Construct probability distribution from lnode children. */
138 /* XXX: How to derive the appropriate gamma? */
139 #define li_value(color, li) (li->u.playouts * (color == S_BLACK ? li->u.value : (1 - li->u.value)))
140 #define li_gamma(color, li) (0.5 + li_value(color, li))
141 struct tree_node *li = upc->lnode->children;
142 assert(li);
143 if (is_pass(li->coord)) {
144 /* Tenuki. */
145 /* TODO: Spread tenuki gamma over all moves we don't touch. */
146 li = li->sibling;
148 for (; li; li = li->sibling) {
149 if (board_at(b, li->coord) != S_NONE)
150 continue;
151 probdist_set(pd, li->coord, double_to_fixp(pd->items[li->coord] * li_gamma(to_play, li)));
156 static int
157 uct_leaf_node(struct uct *u, struct board *b, enum stone player_color,
158 struct playout_amafmap *amaf,
159 struct tree *t, struct tree_node *n, enum stone node_color,
160 char *spaces)
162 enum stone next_color = stone_other(node_color);
163 int parity = (next_color == player_color ? 1 : -1);
165 /* If we don't anticipate well the opponent move during pondering
166 * (the played move has few playouts) we still need more memory
167 * during genmove to explore the tree actually played.
168 * For fast_alloc, the tree compaction will free enough memory
169 * immediately. */
170 unsigned long max_tree_size = u->max_tree_size;
171 if (u->pondering && !u->fast_alloc)
172 max_tree_size = (max_tree_size * (100 - MIN_FREE_MEM_PERCENT)) / 100;
174 /* We need to make sure only one thread expands the node. If
175 * we are unlucky enough for two threads to meet in the same
176 * node, the latter one will simply do another simulation from
177 * the node itself, no big deal. t->nodes_size may exceed
178 * the maximum in multi-threaded case but not by much so it's ok.
179 * The size test must be before the test&set not after, to allow
180 * expansion of the node later if enough nodes have been freed. */
181 if (n->u.playouts >= u->expand_p && t->nodes_size < max_tree_size
182 && !__sync_lock_test_and_set(&n->is_expanded, 1)) {
183 tree_expand_node(t, n, b, next_color, u, parity);
185 if (UDEBUGL(7))
186 fprintf(stderr, "%s*-- UCT playout #%d start [%s] %f\n",
187 spaces, n->u.playouts, coord2sstr(n->coord, t->board),
188 tree_node_get_value(t, parity, n->u.value));
190 /* TODO: Don't necessarily restart the sequence walk when entering
191 * playout. */
192 struct uct_playout_callback upc = { .uct = u, .tree = t, .lnode = NULL };
193 if (u->local_tree_playout) {
194 /* N.B.: We know this is ELO playout. */
195 playout_elo_callback(u->playout, uct_playout_probdist, &upc);
198 struct playout_setup ps = { .gamelen = u->gamelen, .mercymin = u->mercymin };
199 int result = play_random_game(&ps, b, next_color,
200 u->playout_amaf ? amaf : NULL,
201 &u->ownermap, u->playout);
202 if (next_color == S_WHITE) {
203 /* We need the result from black's perspective. */
204 result = - result;
206 if (UDEBUGL(7))
207 fprintf(stderr, "%s -- [%d..%d] %s random playout result %d\n",
208 spaces, player_color, next_color, coord2sstr(n->coord, t->board), result);
210 return result;
213 static float
214 scale_value(struct uct *u, struct board *b, int result)
216 float rval = result > 0;
217 if (u->val_scale) {
218 int vp = u->val_points;
219 if (!vp) {
220 vp = board_size(b) - 1; vp *= vp; vp *= 2;
223 float sval = (float) abs(result) / vp;
224 sval = sval > 1 ? 1 : sval;
225 if (result < 0) sval = 1 - sval;
226 if (u->val_extra)
227 rval += u->val_scale * sval;
228 else
229 rval = (1 - u->val_scale) * rval + u->val_scale * sval;
230 // fprintf(stderr, "score %d => sval %f, rval %f\n", result, sval, rval);
232 return rval;
235 static void
236 record_local_sequence(struct uct *u, struct tree *t,
237 struct uct_descent *descent, int dlen, int di,
238 enum stone seq_color, float rval)
240 /* Ignore pass sequences. */
241 if (is_pass(descent[di].node->coord))
242 return;
244 #define LTREE_DEBUG if (UDEBUGL(6))
245 LTREE_DEBUG fprintf(stderr, "recording result %f in local %s sequence: ",
246 rval, stone2str(seq_color));
247 int di0 = di;
249 /* Pick the right local tree root... */
250 struct tree_node *lnode = seq_color == S_BLACK ? t->ltree_black : t->ltree_white;
251 lnode->u.playouts++;
253 /* ...and record the sequence. */
254 while (di < dlen && (di == di0 || descent[di].node->d < u->tenuki_d)) {
255 LTREE_DEBUG fprintf(stderr, "%s[%d] ",
256 coord2sstr(descent[di].node->coord, t->board),
257 descent[di].node->d);
258 lnode = tree_get_node(t, lnode, descent[di++].node->coord, true);
259 assert(lnode);
260 stats_add_result(&lnode->u, rval, 1);
263 /* Add lnode for tenuki (pass) if we descended further. */
264 if (di < dlen) {
265 LTREE_DEBUG fprintf(stderr, "pass ");
266 lnode = tree_get_node(t, lnode, pass, true);
267 assert(lnode);
268 stats_add_result(&lnode->u, rval, 1);
271 LTREE_DEBUG fprintf(stderr, "\n");
276 uct_playout(struct uct *u, struct board *b, enum stone player_color, struct tree *t)
278 struct board b2;
279 board_copy(&b2, b);
281 struct playout_amafmap *amaf = NULL;
282 if (u->policy->wants_amaf) {
283 amaf = calloc2(1, sizeof(*amaf));
284 amaf->map = calloc2(board_size2(&b2) + 1, sizeof(*amaf->map));
285 amaf->map++; // -1 is pass
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 /* Tree descent history. */
295 /* XXX: This is somewhat messy since @n and descent[dlen-1].node are
296 * redundant. */
297 #define DLEN 512
298 struct uct_descent descent[DLEN];
299 descent[0].node = n; descent[0].lnode = NULL;
300 int dlen = 1;
301 /* Total value of the sequence. */
302 struct move_stats seq_value = { .playouts = 0 };
304 int result;
305 int pass_limit = (board_size(&b2) - 2) * (board_size(&b2) - 2) / 2;
306 int passes = is_pass(b->last_move.coord) && b->moves > 0;
308 /* debug */
309 int depth = 0;
310 static char spaces[] = "\0 ";
311 /* /debug */
312 if (UDEBUGL(8))
313 fprintf(stderr, "--- UCT walk with color %d\n", player_color);
315 while (!tree_leaf_node(n) && passes < 2) {
316 spaces[depth++] = ' '; spaces[depth] = 0;
319 /*** Choose a node to descend to: */
321 /* Parity is chosen already according to the child color, since
322 * it is applied to children. */
323 node_color = stone_other(node_color);
324 int parity = (node_color == player_color ? 1 : -1);
326 assert(dlen < DLEN);
327 descent[dlen] = descent[dlen - 1];
328 if (u->local_tree && (!descent[dlen].lnode || descent[dlen].node->d >= u->tenuki_d)) {
329 /* Start new local sequence. */
330 /* Remember that node_color already holds color of the
331 * to-be-found child. */
332 descent[dlen].lnode = node_color == S_BLACK ? t->ltree_black : t->ltree_white;
335 if (!u->random_policy_chance || fast_random(u->random_policy_chance))
336 u->policy->descend(u->policy, t, &descent[dlen], parity, b2.moves > pass_limit);
337 else
338 u->random_policy->descend(u->random_policy, t, &descent[dlen], parity, b2.moves > pass_limit);
341 /*** Perform the descent: */
343 seq_value.playouts += descent[dlen].value.playouts;
344 seq_value.value += descent[dlen].value.value * descent[dlen].value.playouts;
345 n = descent[dlen++].node;
346 assert(n == t->root || n->parent);
347 if (UDEBUGL(7))
348 fprintf(stderr, "%s+-- UCT sent us to [%s:%d] %f\n",
349 spaces, coord2sstr(n->coord, t->board), n->coord,
350 tree_node_get_value(t, parity, n->u.value));
352 /* Add virtual loss if we need to; this is used to discourage
353 * other threads from visiting this node in case of multiple
354 * threads doing the tree search. */
355 if (u->virtual_loss)
356 stats_add_result(&n->u, tree_parity(t, parity) > 0 ? 0 : 1, 1);
358 assert(n->coord >= -1);
359 if (amaf && !is_pass(n->coord)) {
360 if (amaf->map[n->coord] == S_NONE || amaf->map[n->coord] == node_color) {
361 amaf->map[n->coord] = node_color;
362 } else { // XXX: Respect amaf->record_nakade
363 amaf_op(amaf->map[n->coord], +);
365 amaf->game[amaf->gamelen].coord = n->coord;
366 amaf->game[amaf->gamelen].color = node_color;
367 amaf->gamelen++;
368 assert(amaf->gamelen < sizeof(amaf->game) / sizeof(amaf->game[0]));
371 struct move m = { n->coord, 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(ni->coord, 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(n->coord,b), coord_y(n->coord,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(n->coord))
389 passes++;
390 else
391 passes = 0;
394 if (amaf) {
395 amaf->game_baselen = amaf->gamelen;
396 amaf->record_nakade = u->playout_amaf_nakade;
399 if (t->use_extra_komi && u->dynkomi->persim) {
400 b2.komi += round(u->dynkomi->persim(u->dynkomi, &b2, t, n));
403 if (passes >= 2) {
404 /* XXX: No dead groups support. */
405 float score = board_official_score(&b2, NULL);
406 /* Result from black's perspective (no matter who
407 * the player; black's perspective is always
408 * what the tree stores. */
409 result = - (score * 2);
411 if (UDEBUGL(5))
412 fprintf(stderr, "[%d..%d] %s p-p scoring playout result %d (W %f)\n",
413 player_color, node_color, coord2sstr(n->coord, t->board), result, score);
414 if (UDEBUGL(6))
415 board_print(&b2, stderr);
417 board_ownermap_fill(&u->ownermap, &b2);
419 } else { // assert(tree_leaf_node(n));
420 /* In case of parallel tree search, the assertion might
421 * not hold if two threads chew on the same node. */
422 result = uct_leaf_node(u, &b2, player_color, amaf, t, n, node_color, spaces);
425 if (amaf && u->playout_amaf_cutoff) {
426 unsigned int cutoff = amaf->game_baselen;
427 cutoff += (amaf->gamelen - amaf->game_baselen) * u->playout_amaf_cutoff / 100;
428 /* Now, reconstruct the amaf map. */
429 memset(amaf->map, 0, board_size2(&b2) * sizeof(*amaf->map));
430 for (unsigned int i = 0; i < cutoff; i++) {
431 coord_t coord = amaf->game[i].coord;
432 enum stone color = amaf->game[i].color;
433 if (amaf->map[coord] == S_NONE || amaf->map[coord] == color) {
434 amaf->map[coord] = color;
435 /* Nakade always recorded for in-tree part */
436 } else if (amaf->record_nakade || i <= amaf->game_baselen) {
437 amaf_op(amaf->map[n->coord], +);
442 assert(n == t->root || n->parent);
443 if (result != 0) {
444 float rval = scale_value(u, b, result);
445 u->policy->update(u->policy, t, n, node_color, player_color, amaf, rval);
447 if (t->use_extra_komi) {
448 stats_add_result(&u->dynkomi->score, result / 2, 1);
449 stats_add_result(&u->dynkomi->value, rval, 1);
452 if (u->local_tree && n->parent && !is_pass(n->coord) && dlen > 0) {
453 /* Possibly transform the rval appropriately. */
454 float expval = seq_value.value / seq_value.playouts;
455 rval = stats_temper_value(rval, expval, u->local_tree);
457 /* Get the local sequences and record them in ltree. */
458 /* We will look for sequence starts in our descent
459 * history, then run record_local_sequence() for each
460 * found sequence start; record_local_sequence() may
461 * pick longer sequences from descent history then,
462 * which is expected as it will create new lnodes. */
463 enum stone seq_color = player_color;
464 /* First move always starts a sequence. */
465 record_local_sequence(u, t, descent, dlen, 1, seq_color, rval);
466 seq_color = stone_other(seq_color);
467 for (int dseqi = 2; dseqi < dlen; dseqi++, seq_color = stone_other(seq_color)) {
468 if (u->local_tree_allseq) {
469 /* We are configured to record all subsequences. */
470 record_local_sequence(u, t, descent, dlen, dseqi, seq_color, rval);
471 continue;
473 if (descent[dseqi].node->d >= u->tenuki_d) {
474 /* Tenuki! Record the fresh sequence. */
475 record_local_sequence(u, t, descent, dlen, dseqi, seq_color, rval);
476 continue;
478 if (descent[dseqi].lnode && !descent[dseqi].lnode) {
479 /* Record result for in-descent picked sequence. */
480 record_local_sequence(u, t, descent, dlen, dseqi, seq_color, rval);
481 continue;
487 end:
488 /* We need to undo the virtual loss we added during descend. */
489 if (u->virtual_loss) {
490 int parity = (node_color == player_color ? 1 : -1);
491 for (; n->parent; n = n->parent) {
492 stats_rm_result(&n->u, tree_parity(t, parity) > 0 ? 0 : 1, 1);
493 parity = -parity;
497 if (amaf) {
498 free(amaf->map - 1);
499 free(amaf);
501 board_done_noalloc(&b2);
502 return result;
506 uct_playouts(struct uct *u, struct board *b, enum stone color, struct tree *t)
508 int i;
509 for (i = 0; !uct_halt; i++)
510 uct_playout(u, b, color, t);
511 return i;