Better defaults for atari_def_no_hopeless, cfgd & local_tree_depth_decay
[pachi.git] / uct / walk.c
blob0974d8ecaeb68f9868f130cb4a27dba4cdc1d45e
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] ", playouts);
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;
103 coord_t *treepool[2];
104 int treepool_n[2];
108 static coord_t
109 uct_playout_hook(struct playout_policy *playout, struct playout_setup *setup, struct board *b, enum stone color, int mode)
111 struct uct_playout_callback *upc = setup->hook_data;
112 struct uct *u = upc->uct;
114 if (UDEBUGL(8))
115 fprintf(stderr, "treepool check [%d] %d, %p,%p\n", mode, u->treepool_chance[mode], upc->treepool[0], upc->treepool[1]);
117 if (u->treepool_chance[mode] > fast_random(100) && upc->treepool[color - 1]) {
118 assert(upc->treepool_n[color - 1] > 0);
119 if (UDEBUGL(8)) {
120 fprintf(stderr, "Treepool: ");
121 for (int i = 0; i < upc->treepool_n[color - 1]; i++)
122 fprintf(stderr, "%s ", coord2sstr(upc->treepool[color - 1][i], b));
123 fprintf(stderr, "\n");
126 coord_t treepool_move = pass;
127 if (u->treepool_pickfactor) {
128 /* With pickfactor=10, we get uniform distribution. */
129 int prob = 1000 * u->treepool_pickfactor / (upc->treepool_n[color - 1] * 10);
130 for (int i = 0; i < upc->treepool_n[color - 1]; i++) {
131 treepool_move = upc->treepool[color - 1][i];
132 if (prob > fast_random(1000)) break;
134 } else {
135 treepool_move = upc->treepool[color - 1][fast_random(upc->treepool_n[color - 1])];
137 if (UDEBUGL(7))
138 fprintf(stderr, "Treepool pick <%d> %s,%s\n",
139 upc->treepool_n[color - 1],
140 stone2str(color), coord2sstr(treepool_move, b));
142 if (board_is_valid_play(b, color, treepool_move))
143 return treepool_move;
145 return pass;
148 static coord_t
149 uct_playout_prepolicy(struct playout_policy *playout, struct playout_setup *setup, struct board *b, enum stone color)
151 return uct_playout_hook(playout, setup, b, color, 0);
154 static coord_t
155 uct_playout_postpolicy(struct playout_policy *playout, struct playout_setup *setup, struct board *b, enum stone color)
157 return uct_playout_hook(playout, setup, b, color, 1);
160 double
161 treepool_node_value(struct uct *u, struct tree *tree, int parity, struct tree_node *node)
163 /* XXX: Playouts get cast to double */
164 switch (u->treepool_type) {
165 case UTT_RAVE_PLAYOUTS:
166 return node->amaf.playouts;
167 case UTT_RAVE_VALUE:
168 return tree_node_get_value(tree, parity, node->amaf.value);
169 case UTT_UCT_PLAYOUTS:
170 return node->u.playouts;
171 case UTT_UCT_VALUE:
172 return tree_node_get_value(tree, parity, node->u.value);
173 case UTT_EVALUATE:
175 struct uct_descent d = { .node = node };
176 assert(u->policy->evaluate);
177 return u->policy->evaluate(u->policy, tree, &d, parity);
179 default: assert(0);
181 return -1;
184 static void
185 treepool_setup(struct uct_playout_callback *upc, struct board *b, struct tree_node *node, int color)
187 struct uct *u = upc->uct;
188 int parity = ((node->depth ^ upc->tree->root->depth) & 1) ? -1 : 1;
190 /* XXX: Naive O(N^2) way. */
191 for (int i = 0; i < u->treepool_size; i++) {
192 /* For each item, find the highest
193 * node not in the pool yet. */
194 struct tree_node *best = NULL;
195 double best_val = -1;
197 assert(node->children && is_pass(node->children->coord));
198 for (struct tree_node *ni = node->children->sibling; ni; ni = ni->sibling) {
199 /* Do we already have it? */
200 bool have = false;
201 for (int j = 0; j < upc->treepool_n[color]; j++) {
202 if (upc->treepool[color][j] == ni->coord) {
203 have = true;
204 break;
207 if (have)
208 continue;
210 double i_val = treepool_node_value(u, upc->tree, parity, ni);
211 if (i_val > best_val) {
212 best = ni;
213 best_val = i_val;
217 if (!best) break;
218 upc->treepool[color][upc->treepool_n[color]++] = best->coord;
223 static int
224 uct_leaf_node(struct uct *u, struct board *b, enum stone player_color,
225 struct playout_amafmap *amaf,
226 struct uct_descent *descent, int *dlen,
227 struct tree_node *significant[2],
228 struct tree *t, struct tree_node *n, enum stone node_color,
229 char *spaces)
231 enum stone next_color = stone_other(node_color);
232 int parity = (next_color == player_color ? 1 : -1);
234 /* We need to make sure only one thread expands the node. If
235 * we are unlucky enough for two threads to meet in the same
236 * node, the latter one will simply do another simulation from
237 * the node itself, no big deal. t->nodes_size may exceed
238 * the maximum in multi-threaded case but not by much so it's ok.
239 * The size test must be before the test&set not after, to allow
240 * expansion of the node later if enough nodes have been freed. */
241 if (n->u.playouts >= u->expand_p && t->nodes_size < u->max_tree_size
242 && !__sync_lock_test_and_set(&n->is_expanded, 1)) {
243 tree_expand_node(t, n, b, next_color, u, parity);
245 if (UDEBUGL(7))
246 fprintf(stderr, "%s*-- UCT playout #%d start [%s] %f\n",
247 spaces, n->u.playouts, coord2sstr(n->coord, t->board),
248 tree_node_get_value(t, parity, n->u.value));
250 struct uct_playout_callback upc = {
251 .uct = u,
252 .tree = t,
253 /* TODO: Don't necessarily restart the sequence walk when
254 * entering playout. */
255 .lnode = NULL,
258 coord_t pool[2][u->treepool_size];
259 if (u->treepool_chance[0] + u->treepool_chance[1] > 0) {
260 for (int color = 0; color < 2; color++) {
261 /* Prepare tree-based pool of moves to try forcing
262 * during the playout. */
263 /* We consider the children of the last significant
264 * node, picking top N choices. */
265 struct tree_node *n = significant[color];
266 if (!n || !n->children || !n->children->sibling) {
267 /* No significant node, or it's childless or has
268 * only pass as its child. */
269 upc.treepool[color] = NULL;
270 upc.treepool_n[color] = 0;
271 } else {
272 upc.treepool[color] = (coord_t *) &pool[color];
273 treepool_setup(&upc, b, n, color);
278 struct playout_setup ps = {
279 .gamelen = u->gamelen,
280 .mercymin = u->mercymin,
281 .prepolicy_hook = uct_playout_prepolicy,
282 .postpolicy_hook = uct_playout_postpolicy,
283 .hook_data = &upc,
285 int result = play_random_game(&ps, b, next_color,
286 u->playout_amaf ? amaf : NULL,
287 &u->ownermap, u->playout);
288 if (next_color == S_WHITE) {
289 /* We need the result from black's perspective. */
290 result = - result;
292 if (UDEBUGL(7))
293 fprintf(stderr, "%s -- [%d..%d] %s random playout result %d\n",
294 spaces, player_color, next_color, coord2sstr(n->coord, t->board), result);
296 return result;
299 static floating_t
300 scale_value(struct uct *u, struct board *b, int result)
302 floating_t rval = result > 0;
303 if (u->val_scale) {
304 int vp = u->val_points;
305 if (!vp) {
306 vp = board_size(b) - 1; vp *= vp; vp *= 2;
309 floating_t sval = (floating_t) abs(result) / vp;
310 sval = sval > 1 ? 1 : sval;
311 if (result < 0) sval = 1 - sval;
312 if (u->val_extra)
313 rval += u->val_scale * sval;
314 else
315 rval = (1 - u->val_scale) * rval + u->val_scale * sval;
316 // fprintf(stderr, "score %d => sval %f, rval %f\n", result, sval, rval);
318 return rval;
321 static void
322 record_local_sequence(struct uct *u, struct tree *t,
323 struct uct_descent *descent, int dlen, int di,
324 enum stone seq_color, floating_t rval, int pval)
326 /* Ignore pass sequences. */
327 if (is_pass(descent[di].node->coord))
328 return;
330 /* Transform the rval appropriately, based on the expected
331 * result at the root of the sequence. */
332 if (u->local_tree_rootseqval) {
333 float expval = descent[di - 1].value.value;
334 rval = stats_temper_value(rval, expval, u->local_tree);
337 #define LTREE_DEBUG if (UDEBUGL(6))
338 LTREE_DEBUG fprintf(stderr, "recording result %f in local %s sequence: ",
339 rval, stone2str(seq_color));
340 int di0 = di;
342 /* Pick the right local tree root... */
343 struct tree_node *lnode = seq_color == S_BLACK ? t->ltree_black : t->ltree_white;
344 lnode->u.playouts++;
346 /* ...and record the sequence. */
347 while (di < dlen && (di == di0 || descent[di].node->d < u->tenuki_d)) {
348 LTREE_DEBUG fprintf(stderr, "%s[%d] ",
349 coord2sstr(descent[di].node->coord, t->board),
350 descent[di].node->d);
351 lnode = tree_get_node(t, lnode, descent[di++].node->coord, true);
352 assert(lnode);
353 stats_add_result(&lnode->u, rval, pval);
356 /* Add lnode for tenuki (pass) if we descended further. */
357 if (di < dlen) {
358 LTREE_DEBUG fprintf(stderr, "pass ");
359 lnode = tree_get_node(t, lnode, pass, true);
360 assert(lnode);
361 stats_add_result(&lnode->u, rval, pval);
364 LTREE_DEBUG fprintf(stderr, "\n");
369 uct_playout(struct uct *u, struct board *b, enum stone player_color, struct tree *t)
371 struct board b2;
372 board_copy(&b2, b);
374 struct playout_amafmap *amaf = NULL;
375 if (u->policy->wants_amaf) {
376 amaf = calloc2(1, sizeof(*amaf));
377 amaf->map = calloc2(board_size2(&b2) + 1, sizeof(*amaf->map));
378 amaf->map++; // -1 is pass
381 /* Walk the tree until we find a leaf, then expand it and do
382 * a random playout. */
383 struct tree_node *n = t->root;
384 enum stone node_color = stone_other(player_color);
385 assert(node_color == t->root_color);
387 /* Tree descent history. */
388 /* XXX: This is somewhat messy since @n and descent[dlen-1].node are
389 * redundant. */
390 struct uct_descent descent[DESCENT_DLEN];
391 descent[0].node = n; descent[0].lnode = NULL;
392 int dlen = 1;
393 /* Total value of the sequence. */
394 struct move_stats seq_value = { .playouts = 0 };
395 /* The last "significant" node along the descent (i.e. node
396 * with higher than configured number of playouts). For black
397 * and white. */
398 struct tree_node *significant[2] = { NULL, NULL };
399 if (n->u.playouts >= u->significant_threshold)
400 significant[node_color - 1] = n;
402 int result;
403 int pass_limit = (board_size(&b2) - 2) * (board_size(&b2) - 2) / 2;
404 int passes = is_pass(b->last_move.coord) && b->moves > 0;
406 /* debug */
407 int depth = 0;
408 static char spaces[] = "\0 ";
409 /* /debug */
410 if (UDEBUGL(8))
411 fprintf(stderr, "--- UCT walk with color %d\n", player_color);
413 while (!tree_leaf_node(n) && passes < 2) {
414 spaces[depth++] = ' '; spaces[depth] = 0;
417 /*** Choose a node to descend to: */
419 /* Parity is chosen already according to the child color, since
420 * it is applied to children. */
421 node_color = stone_other(node_color);
422 int parity = (node_color == player_color ? 1 : -1);
424 assert(dlen < DESCENT_DLEN);
425 descent[dlen] = descent[dlen - 1];
426 if (u->local_tree && (!descent[dlen].lnode || descent[dlen].node->d >= u->tenuki_d)) {
427 /* Start new local sequence. */
428 /* Remember that node_color already holds color of the
429 * to-be-found child. */
430 descent[dlen].lnode = node_color == S_BLACK ? t->ltree_black : t->ltree_white;
433 if (!u->random_policy_chance || fast_random(u->random_policy_chance))
434 u->policy->descend(u->policy, t, &descent[dlen], parity, b2.moves > pass_limit);
435 else
436 u->random_policy->descend(u->random_policy, t, &descent[dlen], parity, b2.moves > pass_limit);
439 /*** Perform the descent: */
441 if (descent[dlen].node->u.playouts >= u->significant_threshold) {
442 significant[node_color - 1] = descent[dlen].node;
445 seq_value.playouts += descent[dlen].value.playouts;
446 seq_value.value += descent[dlen].value.value * descent[dlen].value.playouts;
447 n = descent[dlen++].node;
448 assert(n == t->root || n->parent);
449 if (UDEBUGL(7))
450 fprintf(stderr, "%s+-- UCT sent us to [%s:%d] %d,%f\n",
451 spaces, coord2sstr(n->coord, t->board),
452 n->coord, n->u.playouts,
453 tree_node_get_value(t, parity, n->u.value));
455 /* Add virtual loss if we need to; this is used to discourage
456 * other threads from visiting this node in case of multiple
457 * threads doing the tree search. */
458 if (u->virtual_loss)
459 stats_add_result(&n->u, node_color == S_BLACK ? 0.0 : 1.0, u->virtual_loss);
461 assert(n->coord >= -1);
462 if (amaf && !is_pass(n->coord))
463 record_amaf_move(amaf, n->coord, node_color);
465 struct move m = { n->coord, node_color };
466 int res = board_play(&b2, &m);
468 if (res < 0 || (!is_pass(m.coord) && !group_at(&b2, m.coord)) /* suicide */
469 || b2.superko_violation) {
470 if (UDEBUGL(4)) {
471 for (struct tree_node *ni = n; ni; ni = ni->parent)
472 fprintf(stderr, "%s<%"PRIhash"> ", coord2sstr(ni->coord, t->board), ni->hash);
473 fprintf(stderr, "marking invalid %s node %d,%d res %d group %d spk %d\n",
474 stone2str(node_color), coord_x(n->coord,b), coord_y(n->coord,b),
475 res, group_at(&b2, m.coord), b2.superko_violation);
477 n->hints |= TREE_HINT_INVALID;
478 result = 0;
479 goto end;
482 if (is_pass(n->coord))
483 passes++;
484 else
485 passes = 0;
488 if (amaf) {
489 amaf->game_baselen = amaf->gamelen;
490 amaf->record_nakade = u->playout_amaf_nakade;
493 if (t->use_extra_komi && u->dynkomi->persim) {
494 b2.komi += round(u->dynkomi->persim(u->dynkomi, &b2, t, n));
497 if (passes >= 2) {
498 /* XXX: No dead groups support. */
499 floating_t score = board_official_score(&b2, NULL);
500 /* Result from black's perspective (no matter who
501 * the player; black's perspective is always
502 * what the tree stores. */
503 result = - (score * 2);
505 if (UDEBUGL(5))
506 fprintf(stderr, "[%d..%d] %s p-p scoring playout result %d (W %f)\n",
507 player_color, node_color, coord2sstr(n->coord, t->board), result, score);
508 if (UDEBUGL(6))
509 board_print(&b2, stderr);
511 board_ownermap_fill(&u->ownermap, &b2);
513 } else { // assert(tree_leaf_node(n));
514 /* In case of parallel tree search, the assertion might
515 * not hold if two threads chew on the same node. */
516 result = uct_leaf_node(u, &b2, player_color, amaf, descent, &dlen, significant, t, n, node_color, spaces);
519 if (amaf && u->playout_amaf_cutoff) {
520 unsigned int cutoff = amaf->game_baselen;
521 cutoff += (amaf->gamelen - amaf->game_baselen) * u->playout_amaf_cutoff / 100;
522 /* Now, reconstruct the amaf map. */
523 memset(amaf->map, 0, board_size2(&b2) * sizeof(*amaf->map));
524 for (unsigned int i = 0; i < cutoff; i++) {
525 coord_t coord = amaf->game[i].coord;
526 enum stone color = amaf->game[i].color;
527 if (amaf->map[coord] == S_NONE || amaf->map[coord] == color) {
528 amaf->map[coord] = color;
529 /* Nakade always recorded for in-tree part */
530 } else if (amaf->record_nakade || i <= amaf->game_baselen) {
531 amaf_op(amaf->map[n->coord], +);
536 assert(n == t->root || n->parent);
537 if (result != 0) {
538 floating_t rval = scale_value(u, b, result);
539 u->policy->update(u->policy, t, n, node_color, player_color, amaf, rval);
541 int pval = LTREE_PLAYOUTS_MULTIPLIER;
542 if (u->local_tree && u->local_tree_depth_decay > 0)
543 pval = ((floating_t) pval) / pow(u->local_tree_depth_decay, depth);
545 if (t->use_extra_komi) {
546 stats_add_result(&u->dynkomi->score, result / 2, 1);
547 stats_add_result(&u->dynkomi->value, rval, 1);
550 if (u->local_tree && n->parent && !is_pass(n->coord) && dlen > 0) {
551 /* Possibly transform the rval appropriately. */
552 if (!u->local_tree_rootseqval) {
553 floating_t expval = seq_value.value / seq_value.playouts;
554 rval = stats_temper_value(rval, expval, u->local_tree);
557 /* Get the local sequences and record them in ltree. */
558 /* We will look for sequence starts in our descent
559 * history, then run record_local_sequence() for each
560 * found sequence start; record_local_sequence() may
561 * pick longer sequences from descent history then,
562 * which is expected as it will create new lnodes. */
563 enum stone seq_color = player_color;
564 /* First move always starts a sequence. */
565 record_local_sequence(u, t, descent, dlen, 1, seq_color, rval, pval);
566 seq_color = stone_other(seq_color);
567 for (int dseqi = 2; dseqi < dlen; dseqi++, seq_color = stone_other(seq_color)) {
568 if (u->local_tree_allseq) {
569 /* We are configured to record all subsequences. */
570 record_local_sequence(u, t, descent, dlen, dseqi, seq_color, rval, pval);
571 continue;
573 if (descent[dseqi].node->d >= u->tenuki_d) {
574 /* Tenuki! Record the fresh sequence. */
575 record_local_sequence(u, t, descent, dlen, dseqi, seq_color, rval, pval);
576 continue;
578 if (descent[dseqi].lnode && !descent[dseqi].lnode) {
579 /* Record result for in-descent picked sequence. */
580 record_local_sequence(u, t, descent, dlen, dseqi, seq_color, rval, pval);
581 continue;
587 end:
588 /* We need to undo the virtual loss we added during descend. */
589 if (u->virtual_loss) {
590 floating_t loss = node_color == S_BLACK ? 0.0 : 1.0;
591 for (; n->parent; n = n->parent) {
592 stats_rm_result(&n->u, loss, u->virtual_loss);
593 loss = 1.0 - loss;
597 if (amaf) {
598 free(amaf->map - 1);
599 free(amaf);
601 board_done_noalloc(&b2);
602 return result;
606 uct_playouts(struct uct *u, struct board *b, enum stone color, struct tree *t, struct time_info *ti)
608 int i;
609 if (ti && ti->dim == TD_GAMES) {
610 for (i = 0; t->root->u.playouts <= ti->len.games; i++)
611 uct_playout(u, b, color, t);
612 } else {
613 for (i = 0; !uct_halt; i++)
614 uct_playout(u, b, color, t);
616 return i;