uct_playouts(): Just loop until uct_halt if games==0
[pachi.git] / uct / walk.c
blobd0f60aa83cd37df8b18b2f2ae07ea551048cf152
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 float
23 uct_get_extra_komi(struct uct *u, struct board *b)
25 float extra_komi = board_effective_handicap(b) * (u->dynkomi - b->moves) / u->dynkomi;
26 return extra_komi;
29 void
30 uct_progress_status(struct uct *u, struct tree *t, enum stone color, int playouts)
32 if (!UDEBUGL(0))
33 return;
35 /* Best move */
36 struct tree_node *best = u->policy->choose(u->policy, t->root, t->board, color);
37 if (!best) {
38 fprintf(stderr, "... No moves left\n");
39 return;
41 fprintf(stderr, "[%d] ", playouts);
42 fprintf(stderr, "best %f ", tree_node_get_value(t, 1, best->u.value));
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);
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 static int
86 uct_leaf_node(struct uct *u, struct board *b, enum stone player_color,
87 struct playout_amafmap *amaf,
88 struct tree *t, struct tree_node *n, enum stone node_color,
89 char *spaces)
91 enum stone next_color = stone_other(node_color);
92 int parity = (next_color == player_color ? 1 : -1);
94 /* We need to make sure only one thread expands the node. If
95 * we are unlucky enough for two threads to meet in the same
96 * node, the latter one will simply do another simulation from
97 * the node itself, no big deal. t->nodes_size may exceed
98 * the maximum in multi-threaded case but not by much so it's ok.
99 * The size test must be before the test&set not after, to allow
100 * expansion of the node later if enough nodes have been freed. */
101 if (n->u.playouts >= u->expand_p && t->nodes_size < u->max_tree_size
102 && !__sync_lock_test_and_set(&n->is_expanded, 1)) {
103 tree_expand_node(t, n, b, next_color, u, parity);
105 if (UDEBUGL(7))
106 fprintf(stderr, "%s*-- UCT playout #%d start [%s] %f\n",
107 spaces, n->u.playouts, coord2sstr(n->coord, t->board),
108 tree_node_get_value(t, parity, n->u.value));
110 struct playout_setup ps = { .gamelen = u->gamelen, .mercymin = u->mercymin };
111 int result = play_random_game(&ps, b, next_color,
112 u->playout_amaf ? amaf : NULL,
113 &u->ownermap, u->playout);
114 if (next_color == S_WHITE) {
115 /* We need the result from black's perspective. */
116 result = - result;
118 if (UDEBUGL(7))
119 fprintf(stderr, "%s -- [%d..%d] %s random playout result %d\n",
120 spaces, player_color, next_color, coord2sstr(n->coord, t->board), result);
122 return result;
125 static float
126 scale_value(struct uct *u, struct board *b, int result)
128 float rval = result > 0;
129 if (u->val_scale) {
130 int vp = u->val_points;
131 if (!vp) {
132 vp = board_size(b) - 1; vp *= vp; vp *= 2;
135 float sval = (float) abs(result) / vp;
136 sval = sval > 1 ? 1 : sval;
137 if (result < 0) sval = 1 - sval;
138 if (u->val_extra)
139 rval += u->val_scale * sval;
140 else
141 rval = (1 - u->val_scale) * rval + u->val_scale * sval;
142 // fprintf(stderr, "score %d => sval %f, rval %f\n", result, sval, rval);
144 return rval;
149 uct_playout(struct uct *u, struct board *b, enum stone player_color, struct tree *t)
151 struct board b2;
152 board_copy(&b2, b);
154 struct playout_amafmap *amaf = NULL;
155 if (u->policy->wants_amaf) {
156 amaf = calloc(1, sizeof(*amaf));
157 amaf->map = calloc(board_size2(&b2) + 1, sizeof(*amaf->map));
158 amaf->map++; // -1 is pass
161 /* Walk the tree until we find a leaf, then expand it and do
162 * a random playout. */
163 struct tree_node *n = t->root;
164 enum stone node_color = stone_other(player_color);
165 assert(node_color == t->root_color);
167 void *dstate = NULL, *dstater = NULL;
169 int result;
170 int pass_limit = (board_size(&b2) - 2) * (board_size(&b2) - 2) / 2;
171 int passes = is_pass(b->last_move.coord) && b->moves > 0;
173 /* debug */
174 int depth = 0;
175 static char spaces[] = "\0 ";
176 /* /debug */
177 if (UDEBUGL(8))
178 fprintf(stderr, "--- UCT walk with color %d\n", player_color);
180 while (!tree_leaf_node(n) && passes < 2) {
181 spaces[depth++] = ' '; spaces[depth] = 0;
183 /* Parity is chosen already according to the child color, since
184 * it is applied to children. */
185 node_color = stone_other(node_color);
186 int parity = (node_color == player_color ? 1 : -1);
187 n = (!u->random_policy_chance || fast_random(u->random_policy_chance))
188 ? u->policy->descend(u->policy, &dstate, t, n, parity, pass_limit)
189 : u->random_policy->descend(u->random_policy, &dstater, t, n, parity, pass_limit);
191 assert(n == t->root || n->parent);
192 if (UDEBUGL(7))
193 fprintf(stderr, "%s+-- UCT sent us to [%s:%d] %f\n",
194 spaces, coord2sstr(n->coord, t->board), n->coord,
195 tree_node_get_value(t, parity, n->u.value));
197 /* Add virtual loss if we need to; this is used to discourage
198 * other threads from visiting this node in case of multiple
199 * threads doing the tree search. */
200 if (u->virtual_loss)
201 stats_add_result(&n->u, tree_parity(t, parity) > 0 ? 0 : 1, 1);
203 assert(n->coord >= -1);
204 if (amaf && !is_pass(n->coord)) {
205 if (amaf->map[n->coord] == S_NONE || amaf->map[n->coord] == node_color) {
206 amaf->map[n->coord] = node_color;
207 } else { // XXX: Respect amaf->record_nakade
208 amaf_op(amaf->map[n->coord], +);
210 amaf->game[amaf->gamelen].coord = n->coord;
211 amaf->game[amaf->gamelen].color = node_color;
212 amaf->gamelen++;
213 assert(amaf->gamelen < sizeof(amaf->game) / sizeof(amaf->game[0]));
216 struct move m = { n->coord, node_color };
217 int res = board_play(&b2, &m);
219 if (res < 0 || (!is_pass(m.coord) && !group_at(&b2, m.coord)) /* suicide */
220 || b2.superko_violation) {
221 if (UDEBUGL(3)) {
222 for (struct tree_node *ni = n; ni; ni = ni->parent)
223 fprintf(stderr, "%s<%"PRIhash"> ", coord2sstr(ni->coord, t->board), ni->hash);
224 fprintf(stderr, "marking invalid %s node %d,%d res %d group %d spk %d\n",
225 stone2str(node_color), coord_x(n->coord,b), coord_y(n->coord,b),
226 res, group_at(&b2, m.coord), b2.superko_violation);
228 n->hints |= TREE_HINT_INVALID;
229 result = 0;
230 goto end;
233 if (is_pass(n->coord))
234 passes++;
235 else
236 passes = 0;
239 if (amaf) {
240 amaf->game_baselen = amaf->gamelen;
241 amaf->record_nakade = u->playout_amaf_nakade;
244 if (u->dynkomi > b2.moves && (player_color & u->dynkomi_mask))
245 b2.komi += uct_get_extra_komi(u, &b2);
247 if (passes >= 2) {
248 /* XXX: No dead groups support. */
249 float score = board_official_score(&b2, NULL);
250 /* Result from black's perspective (no matter who
251 * the player; black's perspective is always
252 * what the tree stores. */
253 result = - (score * 2);
255 if (UDEBUGL(5))
256 fprintf(stderr, "[%d..%d] %s p-p scoring playout result %d (W %f)\n",
257 player_color, node_color, coord2sstr(n->coord, t->board), result, score);
258 if (UDEBUGL(6))
259 board_print(&b2, stderr);
261 board_ownermap_fill(&u->ownermap, &b2);
263 } else { assert(u->parallel_tree || tree_leaf_node(n));
264 /* In case of parallel tree search, the assertion might
265 * not hold if two threads chew on the same node. */
266 result = uct_leaf_node(u, &b2, player_color, amaf, t, n, node_color, spaces);
269 if (amaf && u->playout_amaf_cutoff) {
270 int cutoff = amaf->game_baselen;
271 cutoff += (amaf->gamelen - amaf->game_baselen) * u->playout_amaf_cutoff / 100;
272 /* Now, reconstruct the amaf map. */
273 memset(amaf->map, 0, board_size2(&b2) * sizeof(*amaf->map));
274 for (int i = 0; i < cutoff; i++) {
275 coord_t coord = amaf->game[i].coord;
276 enum stone color = amaf->game[i].color;
277 if (amaf->map[coord] == S_NONE || amaf->map[coord] == color) {
278 amaf->map[coord] = color;
279 /* Nakade always recorded for in-tree part */
280 } else if (amaf->record_nakade || i <= amaf->game_baselen) {
281 amaf_op(amaf->map[n->coord], +);
286 assert(n == t->root || n->parent);
287 if (result != 0) {
288 float rval = scale_value(u, b, result);
290 u->policy->update(u->policy, t, n, node_color, player_color, amaf, rval);
292 if (u->root_heuristic && n->parent) {
293 if (!t->chvals) {
294 t->chvals = calloc(board_size2(b), sizeof(t->chvals[0]));
295 t->chchvals = calloc(board_size2(b), sizeof(t->chchvals[0]));
298 /* Possibly transform the rval appropriately. */
299 rval = stats_temper_value(rval, n->parent->u.value, u->root_heuristic);
301 struct tree_node *ni = n;
302 while (ni->parent->parent && ni->parent->parent->parent)
303 ni = ni->parent;
304 if (ni->parent->parent) {
305 if (likely(!is_pass(ni->coord)))
306 stats_add_result(&t->chchvals[ni->coord], rval, 1);
307 ni = ni->parent;
309 assert(ni->parent && !ni->parent->parent);
311 if (likely(!is_pass(ni->coord)))
312 stats_add_result(&t->chvals[ni->coord], rval, 1);
316 end:
317 /* We need to undo the virtual loss we added during descend. */
318 if (u->virtual_loss) {
319 int parity = (node_color == player_color ? 1 : -1);
320 for (; n->parent; n = n->parent) {
321 stats_rm_result(&n->u, tree_parity(t, parity) > 0 ? 0 : 1, 1);
322 parity = -parity;
326 if (dstater) free(dstater);
327 if (dstate) free(dstate);
328 if (amaf) {
329 free(amaf->map - 1);
330 free(amaf);
332 board_done_noalloc(&b2);
333 return result;
337 uct_playouts(struct uct *u, struct board *b, enum stone color, struct tree *t, int games)
339 /* Should we print progress info? In case all threads work on the same
340 * tree, only the first thread does. */
341 /* XXX: The thread manager should do things like this. */
342 #define ok_to_talk (!u->parallel_tree || !thread_id)
344 int i;
345 for (i = 0; !uct_halt && (!games || i < games); i++) {
346 int result = uct_playout(u, b, color, t);
347 if (result == 0) {
348 /* Tree descent has hit invalid move. */
349 continue;
352 if (unlikely(ok_to_talk && i > 0 && !(i % 10000))) {
353 uct_progress_status(u, t, color, i);
356 if (i > 0 && !(i % 500)) {
357 struct tree_node *best = u->policy->choose(u->policy, t->root, b, color);
358 if (best && ((best->u.playouts >= 2000 && tree_node_get_value(t, 1, best->u.value) >= u->loss_threshold)
359 || (best->u.playouts >= 500 && tree_node_get_value(t, 1, best->u.value) >= 0.95)))
360 break;
364 if (ok_to_talk) {
365 uct_progress_status(u, t, color, i);
366 if (UDEBUGL(3))
367 tree_dump(t, u->dumpthres);
369 return i;