Do not prevent node expansion later when more memory becomes available.
[pachi.git] / uct / walk.c
blob4b3fa55321b6cb0513389ba63e8d73f2fd477de8
1 #include <assert.h>
2 #include <pthread.h>
3 #include <signal.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
8 #define DEBUG
10 #include "debug.h"
11 #include "board.h"
12 #include "move.h"
13 #include "playout.h"
14 #include "probdist.h"
15 #include "random.h"
16 #include "tactics.h"
17 #include "uct/internal.h"
18 #include "uct/tree.h"
19 #include "uct/uct.h"
20 #include "uct/walk.h"
22 // This should become a dynamic parameter. 7G is suitable for 20k*23 threads.
23 #define MAX_NODE_SIZES (7L*1024*1024*1024)
25 float
26 uct_get_extra_komi(struct uct *u, struct board *b)
28 float extra_komi = board_effective_handicap(b) * (u->dynkomi - b->moves) / u->dynkomi;
29 return extra_komi;
32 void
33 uct_progress_status(struct uct *u, struct tree *t, enum stone color, int playouts)
35 if (!UDEBUGL(0))
36 return;
38 /* Best move */
39 struct tree_node *best = u->policy->choose(u->policy, t->root, t->board, color);
40 if (!best) {
41 fprintf(stderr, "... No moves left\n");
42 return;
44 fprintf(stderr, "[%d] ", playouts);
45 fprintf(stderr, "best %f ", tree_node_get_value(t, 1, best->u.value));
47 /* Max depth */
48 fprintf(stderr, "deepest % 2d ", t->max_depth - t->root->depth);
50 /* Best sequence */
51 fprintf(stderr, "| seq ");
52 for (int depth = 0; depth < 6; depth++) {
53 if (best && best->u.playouts >= 25) {
54 fprintf(stderr, "%3s ", coord2sstr(best->coord, t->board));
55 best = u->policy->choose(u->policy, best, t->board, color);
56 } else {
57 fprintf(stderr, " ");
61 /* Best candidates */
62 fprintf(stderr, "| can ");
63 int cans = 4;
64 struct tree_node *can[cans];
65 memset(can, 0, sizeof(can));
66 best = t->root->children;
67 while (best) {
68 int c = 0;
69 while ((!can[c] || best->u.playouts > can[c]->u.playouts) && ++c < cans);
70 for (int d = 0; d < c; d++) can[d] = can[d + 1];
71 if (c > 0) can[c - 1] = best;
72 best = best->sibling;
74 while (--cans >= 0) {
75 if (can[cans]) {
76 fprintf(stderr, "%3s(%.3f) ",
77 coord2sstr(can[cans]->coord, t->board),
78 tree_node_get_value(t, 1, can[cans]->u.value));
79 } else {
80 fprintf(stderr, " ");
84 fprintf(stderr, "\n");
88 static int
89 uct_leaf_node(struct uct *u, struct board *b, enum stone player_color,
90 struct playout_amafmap *amaf,
91 struct tree *t, struct tree_node *n, enum stone node_color,
92 char *spaces)
94 enum stone next_color = stone_other(node_color);
95 int parity = (next_color == player_color ? 1 : -1);
97 /* We need to make sure only one thread expands the node. If
98 * we are unlucky enough for two threads to meet in the same
99 * node, the latter one will simply do another simulation from
100 * the node itself, no big deal. t->node_sizes may exceed
101 * MAX_NODE_SIZES in multi-threaded case but not by much so it's ok.
102 * The size test must be before the test&set not after, to allow
103 * expansion of the node later if enough nodes have been freed. */
104 if (n->u.playouts >= u->expand_p && t->node_sizes < MAX_NODE_SIZES
105 && !__sync_lock_test_and_set(&n->is_expanded, 1)) {
106 tree_expand_node(t, n, b, next_color, u, parity);
108 if (UDEBUGL(7))
109 fprintf(stderr, "%s*-- UCT playout #%d start [%s] %f\n",
110 spaces, n->u.playouts, coord2sstr(n->coord, t->board),
111 tree_node_get_value(t, parity, n->u.value));
113 struct playout_setup ps = { .gamelen = u->gamelen };
114 int result = play_random_game(&ps, b, next_color,
115 u->playout_amaf ? amaf : NULL,
116 &u->ownermap, u->playout);
117 if (next_color == S_WHITE) {
118 /* We need the result from black's perspective. */
119 result = - result;
121 if (UDEBUGL(7))
122 fprintf(stderr, "%s -- [%d..%d] %s random playout result %d\n",
123 spaces, player_color, next_color, coord2sstr(n->coord, t->board), result);
125 return result;
128 static float
129 scale_value(struct uct *u, struct board *b, int result)
131 float rval = result > 0;
132 if (u->val_scale) {
133 int vp = u->val_points;
134 if (!vp) {
135 vp = board_size(b) - 1; vp *= vp; vp *= 2;
138 float sval = (float) abs(result) / vp;
139 sval = sval > 1 ? 1 : sval;
140 if (result < 0) sval = 1 - sval;
141 if (u->val_extra)
142 rval += u->val_scale * sval;
143 else
144 rval = (1 - u->val_scale) * rval + u->val_scale * sval;
145 // fprintf(stderr, "score %d => sval %f, rval %f\n", result, sval, rval);
147 return rval;
152 uct_playout(struct uct *u, struct board *b, enum stone player_color, struct tree *t)
154 struct board b2;
155 board_copy(&b2, b);
157 struct playout_amafmap *amaf = NULL;
158 if (u->policy->wants_amaf) {
159 amaf = calloc(1, sizeof(*amaf));
160 amaf->map = calloc(board_size2(&b2) + 1, sizeof(*amaf->map));
161 amaf->map++; // -1 is pass
164 /* Walk the tree until we find a leaf, then expand it and do
165 * a random playout. */
166 struct tree_node *n = t->root;
167 enum stone node_color = stone_other(player_color);
168 assert(node_color == t->root_color);
170 void *dstate = NULL, *dstater = NULL;
172 int result;
173 int pass_limit = (board_size(&b2) - 2) * (board_size(&b2) - 2) / 2;
174 int passes = is_pass(b->last_move.coord) && b->moves > 0;
176 /* debug */
177 int depth = 0;
178 static char spaces[] = "\0 ";
179 /* /debug */
180 if (UDEBUGL(8))
181 fprintf(stderr, "--- UCT walk with color %d\n", player_color);
183 while (!tree_leaf_node(n) && passes < 2) {
184 spaces[depth++] = ' '; spaces[depth] = 0;
186 /* Parity is chosen already according to the child color, since
187 * it is applied to children. */
188 node_color = stone_other(node_color);
189 int parity = (node_color == player_color ? 1 : -1);
190 n = (!u->random_policy_chance || fast_random(u->random_policy_chance))
191 ? u->policy->descend(u->policy, &dstate, t, n, parity, pass_limit)
192 : u->random_policy->descend(u->random_policy, &dstater, t, n, parity, pass_limit);
194 assert(n == t->root || n->parent);
195 if (UDEBUGL(7))
196 fprintf(stderr, "%s+-- UCT sent us to [%s:%d] %f\n",
197 spaces, coord2sstr(n->coord, t->board), n->coord,
198 tree_node_get_value(t, parity, n->u.value));
200 /* Add virtual loss if we need to; this is used to discourage
201 * other threads from visiting this node in case of multiple
202 * threads doing the tree search. */
203 if (u->virtual_loss)
204 stats_add_result(&n->u, tree_parity(t, parity) > 0 ? 0 : 1, 1);
206 assert(n->coord >= -1);
207 if (amaf && !is_pass(n->coord)) {
208 if (amaf->map[n->coord] == S_NONE || amaf->map[n->coord] == node_color) {
209 amaf->map[n->coord] = node_color;
210 } else { // XXX: Respect amaf->record_nakade
211 amaf_op(amaf->map[n->coord], +);
213 amaf->game[amaf->gamelen].coord = n->coord;
214 amaf->game[amaf->gamelen].color = node_color;
215 amaf->gamelen++;
216 assert(amaf->gamelen < sizeof(amaf->game) / sizeof(amaf->game[0]));
219 struct move m = { n->coord, node_color };
220 int res = board_play(&b2, &m);
222 if (res < 0 || (!is_pass(m.coord) && !group_at(&b2, m.coord)) /* suicide */
223 || b2.superko_violation) {
224 if (UDEBUGL(3)) {
225 for (struct tree_node *ni = n; ni; ni = ni->parent)
226 fprintf(stderr, "%s<%"PRIhash"> ", coord2sstr(ni->coord, t->board), ni->hash);
227 fprintf(stderr, "marking invalid %s node %d,%d res %d group %d spk %d\n",
228 stone2str(node_color), coord_x(n->coord,b), coord_y(n->coord,b),
229 res, group_at(&b2, m.coord), b2.superko_violation);
231 n->hints |= TREE_HINT_INVALID;
232 result = 0;
233 goto end;
236 if (is_pass(n->coord))
237 passes++;
238 else
239 passes = 0;
242 if (amaf) {
243 amaf->game_baselen = amaf->gamelen;
244 amaf->record_nakade = u->playout_amaf_nakade;
247 if (u->dynkomi > b2.moves && (player_color & u->dynkomi_mask))
248 b2.komi += uct_get_extra_komi(u, &b2);
250 if (passes >= 2) {
251 /* XXX: No dead groups support. */
252 float score = board_official_score(&b2, NULL);
253 /* Result from black's perspective (no matter who
254 * the player; black's perspective is always
255 * what the tree stores. */
256 result = - (score * 2);
258 if (UDEBUGL(5))
259 fprintf(stderr, "[%d..%d] %s p-p scoring playout result %d (W %f)\n",
260 player_color, node_color, coord2sstr(n->coord, t->board), result, score);
261 if (UDEBUGL(6))
262 board_print(&b2, stderr);
264 board_ownermap_fill(&u->ownermap, &b2);
266 } else { assert(u->parallel_tree || tree_leaf_node(n));
267 /* In case of parallel tree search, the assertion might
268 * not hold if two threads chew on the same node. */
269 result = uct_leaf_node(u, &b2, player_color, amaf, t, n, node_color, spaces);
272 if (amaf && u->playout_amaf_cutoff) {
273 int cutoff = amaf->game_baselen;
274 cutoff += (amaf->gamelen - amaf->game_baselen) * u->playout_amaf_cutoff / 100;
275 /* Now, reconstruct the amaf map. */
276 memset(amaf->map, 0, board_size2(&b2) * sizeof(*amaf->map));
277 for (int i = 0; i < cutoff; i++) {
278 coord_t coord = amaf->game[i].coord;
279 enum stone color = amaf->game[i].color;
280 if (amaf->map[coord] == S_NONE || amaf->map[coord] == color) {
281 amaf->map[coord] = color;
282 /* Nakade always recorded for in-tree part */
283 } else if (amaf->record_nakade || i <= amaf->game_baselen) {
284 amaf_op(amaf->map[n->coord], +);
289 assert(n == t->root || n->parent);
290 if (result != 0) {
291 float rval = scale_value(u, b, result);
293 u->policy->update(u->policy, t, n, node_color, player_color, amaf, rval);
295 if (u->root_heuristic && n->parent) {
296 if (!t->chvals) {
297 t->chvals = calloc(board_size2(b), sizeof(t->chvals[0]));
298 t->chchvals = calloc(board_size2(b), sizeof(t->chchvals[0]));
301 /* Possibly transform the rval appropriately. */
302 rval = stats_temper_value(rval, n->parent->u.value, u->root_heuristic);
304 struct tree_node *ni = n;
305 while (ni->parent->parent && ni->parent->parent->parent)
306 ni = ni->parent;
307 if (ni->parent->parent) {
308 if (likely(!is_pass(ni->coord)))
309 stats_add_result(&t->chchvals[ni->coord], rval, 1);
310 ni = ni->parent;
312 assert(ni->parent && !ni->parent->parent);
314 if (likely(!is_pass(ni->coord)))
315 stats_add_result(&t->chvals[ni->coord], rval, 1);
319 end:
320 /* We need to undo the virtual loss we added during descend. */
321 if (u->virtual_loss) {
322 int parity = (node_color == player_color ? 1 : -1);
323 for (; n->parent; n = n->parent) {
324 stats_rm_result(&n->u, tree_parity(t, parity) > 0 ? 0 : 1, 1);
325 parity = -parity;
329 if (dstater) free(dstater);
330 if (dstate) free(dstate);
331 if (amaf) {
332 free(amaf->map - 1);
333 free(amaf);
335 board_done_noalloc(&b2);
336 return result;
340 uct_playouts(struct uct *u, struct board *b, enum stone color, struct tree *t, int games)
342 /* Should we print progress info? In case all threads work on the same
343 * tree, only the first thread does. */
344 #define ok_to_talk (!u->parallel_tree || !thread_id)
346 int i;
347 for (i = 0; i < games; i++) {
348 int result = uct_playout(u, b, color, t);
349 if (result == 0) {
350 /* Tree descent has hit invalid move. */
351 continue;
354 if (unlikely(ok_to_talk && i > 0 && !(i % 10000))) {
355 uct_progress_status(u, t, color, i);
358 if (i > 0 && !(i % 500)) {
359 struct tree_node *best = u->policy->choose(u->policy, t->root, b, color);
360 if (best && ((best->u.playouts >= 2000 && tree_node_get_value(t, 1, best->u.value) >= u->loss_threshold)
361 || (best->u.playouts >= 500 && tree_node_get_value(t, 1, best->u.value) >= 0.95)))
362 break;
365 if (uct_halt) {
366 if (UDEBUGL(2))
367 fprintf(stderr, "<halting early, %d games skipped>\n", games - i);
368 break;
372 if (ok_to_talk) {
373 uct_progress_status(u, t, color, i);
374 if (UDEBUGL(3))
375 tree_dump(t, u->dumpthres);
377 return i;