More notes on the possible min/max method.
[pachi/pachi-r6144.git] / uct / walk.c
blob8d4df2db4dedf0e1ef400538dfb167dcf88ea7fd
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 "uct/dynkomi.h"
18 #include "uct/internal.h"
19 #include "uct/search.h"
20 #include "uct/tree.h"
21 #include "uct/uct.h"
22 #include "uct/walk.h"
24 #define DESCENT_DLEN 512
26 void
27 uct_progress_status(struct uct *u, struct tree *t, enum stone color, int playouts)
29 if (!UDEBUGL(0))
30 return;
32 /* Best move */
33 struct tree_node *best = u->policy->choose(u->policy, t->root, t->board, color, resign);
34 if (!best) {
35 fprintf(stderr, "... No moves left\n");
36 return;
38 fprintf(stderr, "[%d] size=%lu/%lu ", playouts, t->nodes_size, t->max_tree_size);
39 fprintf(stderr, "best %f ", tree_node_get_value(t, 1, best->u.value));
41 /* Dynamic komi */
42 if (t->use_extra_komi)
43 fprintf(stderr, "komi %.1f ", t->extra_komi);
45 /* Best sequence */
46 fprintf(stderr, "| seq ");
47 for (int depth = 0; depth < 4; depth++) {
48 if (best && best->u.playouts >= 25) {
49 fprintf(stderr, "%3s ", coord2sstr(best->coord, t->board));
50 best = u->policy->choose(u->policy, best, t->board, color, resign);
51 } else {
52 fprintf(stderr, " ");
56 /* Best candidates */
57 fprintf(stderr, "| can ");
58 int cans = 4;
59 struct tree_node *can[cans];
60 memset(can, 0, sizeof(can));
61 best = t->root->children;
62 while (best) {
63 int c = 0;
64 while ((!can[c] || best->u.playouts > can[c]->u.playouts) && ++c < cans);
65 for (int d = 0; d < c; d++) can[d] = can[d + 1];
66 if (c > 0) can[c - 1] = best;
67 best = best->sibling;
69 while (--cans >= 0) {
70 if (can[cans]) {
71 fprintf(stderr, "%3s(%.3f) ",
72 coord2sstr(can[cans]->coord, t->board),
73 tree_node_get_value(t, 1, can[cans]->u.value));
74 } else {
75 fprintf(stderr, " ");
79 fprintf(stderr, "\n");
83 static void
84 record_amaf_move(struct playout_amafmap *amaf, coord_t coord, enum stone color)
86 if (amaf->map[coord] == S_NONE || amaf->map[coord] == color) {
87 amaf->map[coord] = color;
88 } else { // XXX: Respect amaf->record_nakade
89 amaf_op(amaf->map[coord], +);
91 amaf->game[amaf->gamelen].coord = coord;
92 amaf->game[amaf->gamelen].color = color;
93 amaf->gamelen++;
94 assert(amaf->gamelen < sizeof(amaf->game) / sizeof(amaf->game[0]));
98 struct uct_playout_callback {
99 struct uct *uct;
100 struct tree *tree;
101 struct tree_node *lnode;
105 static coord_t
106 uct_playout_hook(struct playout_policy *playout, struct playout_setup *setup, struct board *b, enum stone color, int mode)
108 /* XXX: This is used in some non-master branches. */
109 return pass;
112 static coord_t
113 uct_playout_prepolicy(struct playout_policy *playout, struct playout_setup *setup, struct board *b, enum stone color)
115 return uct_playout_hook(playout, setup, b, color, 0);
118 static coord_t
119 uct_playout_postpolicy(struct playout_policy *playout, struct playout_setup *setup, struct board *b, enum stone color)
121 return uct_playout_hook(playout, setup, b, color, 1);
125 static int
126 uct_leaf_node(struct uct *u, struct board *b, enum stone player_color,
127 struct playout_amafmap *amaf,
128 struct uct_descent *descent, int *dlen,
129 struct tree_node *significant[2],
130 struct tree *t, struct tree_node *n, enum stone node_color,
131 char *spaces)
133 enum stone next_color = stone_other(node_color);
134 int parity = (next_color == player_color ? 1 : -1);
136 /* Since filling all memory would cause the Monte-Carlo simulations to terminate, we try to
137 * avoid it by increasing the effective expand_p. */
138 unsigned long cur_size = t->nodes_size; /* it is volatile and can change at any time, so we must cache its value */
139 if (cur_size < u->max_tree_size && (unsigned long) n->u.playouts >= u->max_tree_size / (u->max_tree_size - cur_size) + 1) {
140 /* We need to make sure only one thread expands the node. If
141 * we are unlucky enough for two threads to meet in the same
142 * node, the latter one will simply do another simulation from
143 * the node itself, no big deal. t->nodes_size may exceed
144 * the maximum in multi-threaded case but not by much so it's ok.
145 * The size test must be before the test&set not after, to allow
146 * expansion of the node later if enough nodes have been freed. */
147 if (!__sync_lock_test_and_set(&n->is_expanded, 1)) {
148 tree_expand_node(t, n, b, next_color, u, parity);
151 if (UDEBUGL(7))
152 fprintf(stderr, "%s*-- UCT playout #%d start [%s] %f\n",
153 spaces, n->u.playouts, coord2sstr(n->coord, t->board),
154 tree_node_get_value(t, parity, n->u.value));
156 struct uct_playout_callback upc = {
157 .uct = u,
158 .tree = t,
159 /* TODO: Don't necessarily restart the sequence walk when
160 * entering playout. */
161 .lnode = NULL,
164 struct playout_setup ps = {
165 .gamelen = u->gamelen,
166 .mercymin = u->mercymin,
167 .prepolicy_hook = uct_playout_prepolicy,
168 .postpolicy_hook = uct_playout_postpolicy,
169 .hook_data = &upc,
171 int result = play_random_game(&ps, b, next_color,
172 u->playout_amaf ? amaf : NULL,
173 &u->ownermap, u->playout);
174 if (next_color == S_WHITE) {
175 /* We need the result from black's perspective. */
176 result = - result;
178 if (UDEBUGL(7))
179 fprintf(stderr, "%s -- [%d..%d] %s random playout result %d\n",
180 spaces, player_color, next_color, coord2sstr(n->coord, t->board), result);
182 return result;
185 static floating_t
186 scale_value(struct uct *u, struct board *b, int result)
188 floating_t rval = result > 0 ? 1.0 : result < 0 ? 0.0 : 0.5;
189 if (u->val_scale && result != 0) {
190 int vp = u->val_points;
191 if (!vp) {
192 vp = board_size(b) - 1; vp *= vp; vp *= 2;
195 floating_t sval = (floating_t) abs(result) / vp;
196 sval = sval > 1 ? 1 : sval;
197 if (result < 0) sval = 1 - sval;
198 if (u->val_extra)
199 rval += u->val_scale * sval;
200 else
201 rval = (1 - u->val_scale) * rval + u->val_scale * sval;
202 // fprintf(stderr, "score %d => sval %f, rval %f\n", result, sval, rval);
204 return rval;
207 static void
208 record_local_sequence(struct uct *u, struct tree *t,
209 struct uct_descent *descent, int dlen, int di,
210 enum stone seq_color, floating_t rval)
212 #define LTREE_DEBUG if (UDEBUGL(6))
214 /* Ignore pass sequences. */
215 if (is_pass(descent[di].node->coord))
216 return;
218 /* Transform the rval appropriately, based on the expected
219 * result at the root of the sequence. */
220 if (u->local_tree_rootseqval) {
221 float expval = descent[di - 1].value.value;
222 rval = stats_temper_value(rval, expval, u->local_tree);
225 LTREE_DEBUG fprintf(stderr, "recording result %f in local %s sequence: ",
226 rval, stone2str(seq_color));
228 /* Sequences starting deeper are less relevant in general. */
229 int pval = LTREE_PLAYOUTS_MULTIPLIER;
230 if (u->local_tree && u->local_tree_depth_decay > 0)
231 pval = ((floating_t) pval) / pow(u->local_tree_depth_decay, di - 1);
232 if (!pval) {
233 LTREE_DEBUG fprintf(stderr, "too deep @%d\n", di);
234 return;
237 /* Pick the right local tree root... */
238 struct tree_node *lnode = seq_color == S_BLACK ? t->ltree_black : t->ltree_white;
239 lnode->u.playouts++;
241 /* ...and record the sequence. */
242 int di0 = di;
243 while (di < dlen && (di == di0 || descent[di].node->d < u->tenuki_d)) {
244 LTREE_DEBUG fprintf(stderr, "%s[%d] ",
245 coord2sstr(descent[di].node->coord, t->board),
246 descent[di].node->d);
247 lnode = tree_get_node(t, lnode, descent[di++].node->coord, true);
248 assert(lnode);
249 stats_add_result(&lnode->u, rval, pval);
252 /* Add lnode for tenuki (pass) if we descended further. */
253 if (di < dlen) {
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 = NULL;
271 if (u->policy->wants_amaf) {
272 amaf = calloc2(1, sizeof(*amaf));
273 amaf->map = calloc2(board_size2(&b2) + 1, sizeof(*amaf->map));
274 amaf->map++; // -1 is pass
277 /* Walk the tree until we find a leaf, then expand it and do
278 * a random playout. */
279 struct tree_node *n = t->root;
280 enum stone node_color = stone_other(player_color);
281 assert(node_color == t->root_color);
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[DESCENT_DLEN];
304 spaces[0] = 0;
305 /* /debug */
306 if (UDEBUGL(8))
307 fprintf(stderr, "--- UCT walk with color %d\n", player_color);
309 while (!tree_leaf_node(n) && passes < 2) {
310 /*** Choose a node to descend to: */
312 /* Parity is chosen already according to the child color, since
313 * it is applied to children. */
314 node_color = stone_other(node_color);
315 int parity = (node_color == player_color ? 1 : -1);
317 assert(dlen < DESCENT_DLEN);
318 spaces[dlen - 1] = ' '; spaces[dlen] = 0;
319 descent[dlen] = descent[dlen - 1];
320 if (u->local_tree && (!descent[dlen].lnode || descent[dlen].node->d >= u->tenuki_d)) {
321 /* Start new local sequence. */
322 /* Remember that node_color already holds color of the
323 * to-be-found child. */
324 descent[dlen].lnode = node_color == S_BLACK ? t->ltree_black : t->ltree_white;
327 if (!u->random_policy_chance || fast_random(u->random_policy_chance))
328 u->policy->descend(u->policy, t, &descent[dlen], parity, b2.moves > pass_limit);
329 else
330 u->random_policy->descend(u->random_policy, t, &descent[dlen], parity, b2.moves > pass_limit);
333 /*** Perform the descent: */
335 if (descent[dlen].node->u.playouts >= u->significant_threshold) {
336 significant[node_color - 1] = descent[dlen].node;
339 seq_value.playouts += descent[dlen].value.playouts;
340 seq_value.value += descent[dlen].value.value * descent[dlen].value.playouts;
341 n = descent[dlen++].node;
342 assert(n == t->root || n->parent);
343 if (UDEBUGL(7))
344 fprintf(stderr, "%s+-- UCT sent us to [%s:%d] %d,%f\n",
345 spaces, coord2sstr(n->coord, t->board),
346 n->coord, n->u.playouts,
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, node_color == S_BLACK ? 0.0 : 1.0, u->virtual_loss);
355 assert(n->coord >= -1);
356 if (amaf && !is_pass(n->coord))
357 record_amaf_move(amaf, n->coord, node_color);
359 struct move m = { n->coord, 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(ni->coord, 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(n->coord,b), coord_y(n->coord,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(n->coord))
377 passes++;
378 else
379 passes = 0;
382 if (amaf) {
383 amaf->game_baselen = amaf->gamelen;
384 amaf->record_nakade = u->playout_amaf_nakade;
387 if (t->use_extra_komi && u->dynkomi->persim) {
388 b2.komi += round(u->dynkomi->persim(u->dynkomi, &b2, t, n));
391 if (passes >= 2) {
392 /* XXX: No dead groups support. */
393 floating_t score = board_official_score(&b2, NULL);
394 /* Result from black's perspective (no matter who
395 * the player; black's perspective is always
396 * what the tree stores. */
397 result = - (score * 2);
399 if (UDEBUGL(5))
400 fprintf(stderr, "[%d..%d] %s p-p scoring playout result %d (W %f)\n",
401 player_color, node_color, coord2sstr(n->coord, t->board), result, score);
402 if (UDEBUGL(6))
403 board_print(&b2, stderr);
405 board_ownermap_fill(&u->ownermap, &b2);
407 } else { // assert(tree_leaf_node(n));
408 /* In case of parallel tree search, the assertion might
409 * not hold if two threads chew on the same node. */
410 result = uct_leaf_node(u, &b2, player_color, amaf, descent, &dlen, significant, t, n, node_color, spaces);
413 if (amaf && u->playout_amaf_cutoff) {
414 unsigned int cutoff = amaf->game_baselen;
415 cutoff += (amaf->gamelen - amaf->game_baselen) * u->playout_amaf_cutoff / 100;
416 /* Now, reconstruct the amaf map. */
417 memset(amaf->map, 0, board_size2(&b2) * sizeof(*amaf->map));
418 for (unsigned int i = 0; i < cutoff; i++) {
419 coord_t coord = amaf->game[i].coord;
420 enum stone color = amaf->game[i].color;
421 if (amaf->map[coord] == S_NONE || amaf->map[coord] == color) {
422 amaf->map[coord] = color;
423 /* Nakade always recorded for in-tree part */
424 } else if (amaf->record_nakade || i <= amaf->game_baselen) {
425 amaf_op(amaf->map[n->coord], +);
430 /* Record the result. */
432 assert(n == t->root || n->parent);
433 floating_t rval = scale_value(u, b, result);
434 u->policy->update(u->policy, t, n, node_color, player_color, amaf, &b2, rval);
436 if (t->use_extra_komi) {
437 stats_add_result(&u->dynkomi->score, (floating_t) 0.5 * result, 1);
438 stats_add_result(&u->dynkomi->value, rval, 1);
441 if (u->local_tree && n->parent && !is_pass(n->coord) && dlen > 0) {
442 /* Possibly transform the rval appropriately. */
443 if (!u->local_tree_rootseqval) {
444 floating_t expval = seq_value.value / seq_value.playouts;
445 rval = stats_temper_value(rval, expval, u->local_tree);
448 /* Get the local sequences and record them in ltree. */
449 /* We will look for sequence starts in our descent
450 * history, then run record_local_sequence() for each
451 * found sequence start; record_local_sequence() may
452 * pick longer sequences from descent history then,
453 * which is expected as it will create new lnodes. */
454 enum stone seq_color = player_color;
455 /* First move always starts a sequence. */
456 record_local_sequence(u, t, descent, dlen, 1, seq_color, rval);
457 seq_color = stone_other(seq_color);
458 for (int dseqi = 2; dseqi < dlen; dseqi++, seq_color = stone_other(seq_color)) {
459 if (u->local_tree_allseq) {
460 /* We are configured to record all subsequences. */
461 record_local_sequence(u, t, descent, dlen, dseqi, seq_color, rval);
462 continue;
464 if (descent[dseqi].node->d >= u->tenuki_d) {
465 /* Tenuki! Record the fresh sequence. */
466 record_local_sequence(u, t, descent, dlen, dseqi, seq_color, rval);
467 continue;
469 if (descent[dseqi].lnode && !descent[dseqi].lnode) {
470 /* Record result for in-descent picked sequence. */
471 record_local_sequence(u, t, descent, dlen, dseqi, seq_color, rval);
472 continue;
477 end:
478 /* We need to undo the virtual loss we added during descend. */
479 if (u->virtual_loss) {
480 floating_t loss = node_color == S_BLACK ? 0.0 : 1.0;
481 for (; n->parent; n = n->parent) {
482 stats_rm_result(&n->u, loss, u->virtual_loss);
483 loss = 1.0 - loss;
487 if (amaf) {
488 free(amaf->map - 1);
489 free(amaf);
491 board_done_noalloc(&b2);
492 return result;
496 uct_playouts(struct uct *u, struct board *b, enum stone color, struct tree *t, struct time_info *ti)
498 int i;
499 if (ti && ti->dim == TD_GAMES) {
500 /* We must halt if uct_search_check_stop() decides that it is time to stop. For
501 * example, if memory gets full, we may well have to stop early; in any case since
502 * uct_search_progress() is no longer called to update the dynkomi information and
503 * show progress information, continuing might well give strange results. Normally
504 * uct_search_check_stop() will stop at s->stop.worst.playouts, which is equal to
505 * ti->len.games according to timeinfo.c:time_stop_conditions(). */
506 for (i = 0; !uct_halt && t->root->u.playouts <= ti->len.games; i++)
507 uct_playout(u, b, color, t);
508 } else {
509 for (i = 0; !uct_halt; i++)
510 uct_playout(u, b, color, t);
512 return i;