UCT: introduce val_scale_max
[pachi.git] / uct / walk.c
blob2da7218d9a0138167dd14869e523ff46abd0d307
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;
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 /* We need to make sure only one thread expands the node. If
137 * we are unlucky enough for two threads to meet in the same
138 * node, the latter one will simply do another simulation from
139 * the node itself, no big deal. t->nodes_size may exceed
140 * the maximum in multi-threaded case but not by much so it's ok.
141 * The size test must be before the test&set not after, to allow
142 * expansion of the node later if enough nodes have been freed. */
143 if (n->u.playouts >= u->expand_p && t->nodes_size < u->max_tree_size
144 && !__sync_lock_test_and_set(&n->is_expanded, 1)) {
145 tree_expand_node(t, n, b, next_color, u, parity);
147 if (UDEBUGL(7))
148 fprintf(stderr, "%s*-- UCT playout #%d start [%s] %f\n",
149 spaces, n->u.playouts, coord2sstr(n->coord, t->board),
150 tree_node_get_value(t, parity, n->u.value));
152 struct uct_playout_callback upc = {
153 .uct = u,
154 .tree = t,
155 /* TODO: Don't necessarily restart the sequence walk when
156 * entering playout. */
157 .lnode = NULL,
160 struct playout_setup ps = {
161 .gamelen = u->gamelen,
162 .mercymin = u->mercymin,
163 .prepolicy_hook = uct_playout_prepolicy,
164 .postpolicy_hook = uct_playout_postpolicy,
165 .hook_data = &upc,
167 int result = play_random_game(&ps, b, next_color,
168 u->playout_amaf ? amaf : NULL,
169 &u->ownermap, u->playout);
170 if (next_color == S_WHITE) {
171 /* We need the result from black's perspective. */
172 result = - result;
174 if (UDEBUGL(7))
175 fprintf(stderr, "%s -- [%d..%d] %s random playout result %d\n",
176 spaces, player_color, next_color, coord2sstr(n->coord, t->board), result);
178 return result;
181 static floating_t
182 scale_value(struct uct *u, struct board *b, int result)
184 if (result == 0) return 0.5;
185 floating_t rval = result > 0 ? 1.0 : 0.0;
187 floating_t scale = u->val_scale;
188 /* Give more weight to territory when winning big (maximize win). This reduces
189 * the number of silly moves and makes the game more enjoyable for humans. */
190 if (u->t->root->u.playouts > GJ_MINGAMES &&
191 tree_node_get_value(u->t, -1, u->t->root->u.value) >= u->sure_win_threshold) {
192 scale = u->val_scale_max;
194 if (scale == 0) return rval;
196 int vp = u->val_points;
197 /* By default do not try to win by more than 44 points on 19x19,
198 * 12 points on 9x9. Remember that result here is twice the score. */
199 if (!vp) vp = board_size2(b) / 5;
201 floating_t sval = (floating_t) abs(result) / vp;
202 sval = sval > 1 ? 1 : sval;
203 if (result < 0) sval = 1 - sval;
204 if (u->val_extra)
205 rval += scale * sval;
206 else
207 rval = (1 - scale) * rval + scale * sval;
208 // fprintf(stderr, "score %d => sval %f, rval %f\n", result, sval, rval);
209 return rval;
212 static double
213 local_value(struct uct *u, struct board *b, coord_t coord, enum stone color)
215 /* Tactical evaluation of move @coord by color @color, given
216 * simulation end position @b. I.e., a move is tactically good
217 * if the resulting group stays on board until the game end. */
218 /* We can also take into account surrounding stones, e.g. to
219 * encourage taking off external liberties during a semeai. */
220 double val;
221 if (u->local_tree_neival) {
222 int friends = neighbor_count_at(b, coord, color) + neighbor_count_at(b, coord, S_OFFBOARD);
223 if (immediate_liberty_count(b, coord) > 0) {
224 foreach_neighbor(b, coord, {
225 friends += board_is_one_point_eye(b, coord, color);
228 val = (double) (2 * (board_at(b, coord) == color) + friends) / 6.f;
229 } else {
230 val = (board_at(b, coord) == color) ? 1.f : 0.f;
232 return (color == S_WHITE) ? 1.f - val : val;
235 static void
236 record_local_sequence(struct uct *u, struct tree *t, struct board *endb,
237 struct uct_descent *descent, int dlen, int di,
238 enum stone seq_color)
240 #define LTREE_DEBUG if (UDEBUGL(6))
242 /* Ignore pass sequences. */
243 if (is_pass(descent[di].node->coord))
244 return;
246 LTREE_DEBUG board_print(endb, stderr);
247 LTREE_DEBUG fprintf(stderr, "recording local %s sequence: ",
248 stone2str(seq_color));
250 /* Sequences starting deeper are less relevant in general. */
251 int pval = LTREE_PLAYOUTS_MULTIPLIER;
252 if (u->local_tree && u->local_tree_depth_decay > 0)
253 pval = ((floating_t) pval) / pow(u->local_tree_depth_decay, di - 1);
254 if (!pval) {
255 LTREE_DEBUG fprintf(stderr, "too deep @%d\n", di);
256 return;
259 /* Pick the right local tree root... */
260 struct tree_node *lnode = seq_color == S_BLACK ? t->ltree_black : t->ltree_white;
261 lnode->u.playouts++;
263 double sval = 0.5;
264 if (u->local_tree_rootgoal) {
265 sval = local_value(u, endb, descent[di].node->coord, seq_color);
266 LTREE_DEBUG fprintf(stderr, "(goal %s[%s %1.3f][%d]) ",
267 coord2sstr(descent[di].node->coord, t->board),
268 stone2str(seq_color), sval, descent[di].node->d);
271 /* ...and record the sequence. */
272 int di0 = di;
273 while (di < dlen && (di == di0 || descent[di].node->d < u->tenuki_d)) {
274 enum stone color = (di - di0) % 2 ? stone_other(seq_color) : seq_color;
275 double rval;
276 if (u->local_tree_rootgoal)
277 rval = sval;
278 else
279 rval = local_value(u, endb, descent[di].node->coord, color);
280 LTREE_DEBUG fprintf(stderr, "%s[%s %1.3f][%d] ",
281 coord2sstr(descent[di].node->coord, t->board),
282 stone2str(color), rval, descent[di].node->d);
283 lnode = tree_get_node(t, lnode, descent[di++].node->coord, true);
284 assert(lnode);
285 stats_add_result(&lnode->u, rval, pval);
288 /* Add lnode for tenuki (pass) if we descended further. */
289 if (di < dlen) {
290 double rval = u->local_tree_rootgoal ? sval : 0.5;
291 LTREE_DEBUG fprintf(stderr, "pass ");
292 lnode = tree_get_node(t, lnode, pass, true);
293 assert(lnode);
294 stats_add_result(&lnode->u, rval, pval);
297 LTREE_DEBUG fprintf(stderr, "\n");
302 uct_playout(struct uct *u, struct board *b, enum stone player_color, struct tree *t)
304 struct board b2;
305 board_copy(&b2, b);
307 struct playout_amafmap *amaf = NULL;
308 if (u->policy->wants_amaf) {
309 amaf = calloc2(1, sizeof(*amaf));
310 amaf->map = calloc2(board_size2(&b2) + 1, sizeof(*amaf->map));
311 amaf->map++; // -1 is pass
314 /* Walk the tree until we find a leaf, then expand it and do
315 * a random playout. */
316 struct tree_node *n = t->root;
317 enum stone node_color = stone_other(player_color);
318 assert(node_color == t->root_color);
320 /* Tree descent history. */
321 /* XXX: This is somewhat messy since @n and descent[dlen-1].node are
322 * redundant. */
323 struct uct_descent descent[DESCENT_DLEN];
324 descent[0].node = n; descent[0].lnode = NULL;
325 int dlen = 1;
326 /* Total value of the sequence. */
327 struct move_stats seq_value = { .playouts = 0 };
328 /* The last "significant" node along the descent (i.e. node
329 * with higher than configured number of playouts). For black
330 * and white. */
331 struct tree_node *significant[2] = { NULL, NULL };
332 if (n->u.playouts >= u->significant_threshold)
333 significant[node_color - 1] = n;
335 int result;
336 int pass_limit = (board_size(&b2) - 2) * (board_size(&b2) - 2) / 2;
337 int passes = is_pass(b->last_move.coord) && b->moves > 0;
339 /* debug */
340 static char spaces[] = "\0 ";
341 /* /debug */
342 if (UDEBUGL(8))
343 fprintf(stderr, "--- UCT walk with color %d\n", player_color);
345 while (!tree_leaf_node(n) && passes < 2) {
346 spaces[dlen - 1] = ' '; spaces[dlen] = 0;
349 /*** Choose a node to descend to: */
351 /* Parity is chosen already according to the child color, since
352 * it is applied to children. */
353 node_color = stone_other(node_color);
354 int parity = (node_color == player_color ? 1 : -1);
356 assert(dlen < DESCENT_DLEN);
357 descent[dlen] = descent[dlen - 1];
358 if (u->local_tree && (!descent[dlen].lnode || descent[dlen].node->d >= u->tenuki_d)) {
359 /* Start new local sequence. */
360 /* Remember that node_color already holds color of the
361 * to-be-found child. */
362 descent[dlen].lnode = node_color == S_BLACK ? t->ltree_black : t->ltree_white;
365 if (!u->random_policy_chance || fast_random(u->random_policy_chance))
366 u->policy->descend(u->policy, t, &descent[dlen], parity, b2.moves > pass_limit);
367 else
368 u->random_policy->descend(u->random_policy, t, &descent[dlen], parity, b2.moves > pass_limit);
371 /*** Perform the descent: */
373 if (descent[dlen].node->u.playouts >= u->significant_threshold) {
374 significant[node_color - 1] = descent[dlen].node;
377 seq_value.playouts += descent[dlen].value.playouts;
378 seq_value.value += descent[dlen].value.value * descent[dlen].value.playouts;
379 n = descent[dlen++].node;
380 assert(n == t->root || n->parent);
381 if (UDEBUGL(7))
382 fprintf(stderr, "%s+-- UCT sent us to [%s:%d] %d,%f\n",
383 spaces, coord2sstr(n->coord, t->board),
384 n->coord, n->u.playouts,
385 tree_node_get_value(t, parity, n->u.value));
387 /* Add virtual loss if we need to; this is used to discourage
388 * other threads from visiting this node in case of multiple
389 * threads doing the tree search. */
390 if (u->virtual_loss)
391 stats_add_result(&n->u, node_color == S_BLACK ? 0.0 : 1.0, u->virtual_loss);
393 assert(n->coord >= -1);
394 if (amaf && !is_pass(n->coord))
395 record_amaf_move(amaf, n->coord, node_color);
397 struct move m = { n->coord, node_color };
398 int res = board_play(&b2, &m);
400 if (res < 0 || (!is_pass(m.coord) && !group_at(&b2, m.coord)) /* suicide */
401 || b2.superko_violation) {
402 if (UDEBUGL(4)) {
403 for (struct tree_node *ni = n; ni; ni = ni->parent)
404 fprintf(stderr, "%s<%"PRIhash"> ", coord2sstr(ni->coord, t->board), ni->hash);
405 fprintf(stderr, "marking invalid %s node %d,%d res %d group %d spk %d\n",
406 stone2str(node_color), coord_x(n->coord,b), coord_y(n->coord,b),
407 res, group_at(&b2, m.coord), b2.superko_violation);
409 n->hints |= TREE_HINT_INVALID;
410 result = 0;
411 goto end;
414 if (is_pass(n->coord))
415 passes++;
416 else
417 passes = 0;
420 if (amaf) {
421 amaf->game_baselen = amaf->gamelen;
422 amaf->record_nakade = u->playout_amaf_nakade;
425 if (t->use_extra_komi && u->dynkomi->persim) {
426 b2.komi += round(u->dynkomi->persim(u->dynkomi, &b2, t, n));
429 if (passes >= 2) {
430 /* XXX: No dead groups support. */
431 floating_t score = board_official_score(&b2, NULL);
432 /* Result from black's perspective (no matter who
433 * the player; black's perspective is always
434 * what the tree stores. */
435 result = - (score * 2);
437 if (UDEBUGL(5))
438 fprintf(stderr, "[%d..%d] %s p-p scoring playout result %d (W %f)\n",
439 player_color, node_color, coord2sstr(n->coord, t->board), result, score);
440 if (UDEBUGL(6))
441 board_print(&b2, stderr);
443 board_ownermap_fill(&u->ownermap, &b2);
445 } else { // assert(tree_leaf_node(n));
446 /* In case of parallel tree search, the assertion might
447 * not hold if two threads chew on the same node. */
448 result = uct_leaf_node(u, &b2, player_color, amaf, descent, &dlen, significant, t, n, node_color, spaces);
451 if (amaf && u->playout_amaf_cutoff) {
452 unsigned int cutoff = amaf->game_baselen;
453 cutoff += (amaf->gamelen - amaf->game_baselen) * u->playout_amaf_cutoff / 100;
454 /* Now, reconstruct the amaf map. */
455 memset(amaf->map, 0, board_size2(&b2) * sizeof(*amaf->map));
456 for (unsigned int i = 0; i < cutoff; i++) {
457 coord_t coord = amaf->game[i].coord;
458 enum stone color = amaf->game[i].color;
459 if (amaf->map[coord] == S_NONE || amaf->map[coord] == color) {
460 amaf->map[coord] = color;
461 /* Nakade always recorded for in-tree part */
462 } else if (amaf->record_nakade || i <= amaf->game_baselen) {
463 amaf_op(amaf->map[n->coord], +);
468 /* Record the result. */
470 assert(n == t->root || n->parent);
471 floating_t rval = scale_value(u, b, result);
472 u->policy->update(u->policy, t, n, node_color, player_color, amaf, &b2, rval);
474 if (t->use_extra_komi) {
475 stats_add_result(&u->dynkomi->score, result / 2, 1);
476 stats_add_result(&u->dynkomi->value, rval, 1);
479 if (u->local_tree && n->parent && !is_pass(n->coord) && dlen > 0) {
480 /* Get the local sequences and record them in ltree. */
481 /* We will look for sequence starts in our descent
482 * history, then run record_local_sequence() for each
483 * found sequence start; record_local_sequence() may
484 * pick longer sequences from descent history then,
485 * which is expected as it will create new lnodes. */
486 enum stone seq_color = player_color;
487 /* First move always starts a sequence. */
488 record_local_sequence(u, t, &b2, descent, dlen, 1, seq_color);
489 seq_color = stone_other(seq_color);
490 for (int dseqi = 2; dseqi < dlen; dseqi++, seq_color = stone_other(seq_color)) {
491 if (u->local_tree_allseq) {
492 /* We are configured to record all subsequences. */
493 record_local_sequence(u, t, &b2, descent, dlen, dseqi, seq_color);
494 continue;
496 if (descent[dseqi].node->d >= u->tenuki_d) {
497 /* Tenuki! Record the fresh sequence. */
498 record_local_sequence(u, t, &b2, descent, dlen, dseqi, seq_color);
499 continue;
501 if (descent[dseqi].lnode && !descent[dseqi].lnode) {
502 /* Record result for in-descent picked sequence. */
503 record_local_sequence(u, t, &b2, descent, dlen, dseqi, seq_color);
504 continue;
509 end:
510 /* We need to undo the virtual loss we added during descend. */
511 if (u->virtual_loss) {
512 floating_t loss = node_color == S_BLACK ? 0.0 : 1.0;
513 for (; n->parent; n = n->parent) {
514 stats_rm_result(&n->u, loss, u->virtual_loss);
515 loss = 1.0 - loss;
519 if (amaf) {
520 free(amaf->map - 1);
521 free(amaf);
523 board_done_noalloc(&b2);
524 return result;
528 uct_playouts(struct uct *u, struct board *b, enum stone color, struct tree *t, struct time_info *ti)
530 int i;
531 if (ti && ti->dim == TD_GAMES) {
532 for (i = 0; t->root->u.playouts <= ti->len.games; i++)
533 uct_playout(u, b, color, t);
534 } else {
535 for (i = 0; !uct_halt; i++)
536 uct_playout(u, b, color, t);
538 return i;