uct_playout(): Move leaf node processing to uct_leaf_node()
[pachi.git] / uct / uct.c
blobc193c0123abd772e6e846b14a8023a2563cecd3f
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 "playout/moggy.h"
15 #include "playout/old.h"
16 #include "playout/light.h"
17 #include "random.h"
18 #include "uct/internal.h"
19 #include "uct/tree.h"
20 #include "uct/uct.h"
22 struct uct_policy *policy_ucb1_init(struct uct *u, char *arg);
23 struct uct_policy *policy_ucb1tuned_init(struct uct *u, char *arg);
24 struct uct_policy *policy_ucb1amaf_init(struct uct *u, char *arg);
27 #define MC_GAMES 80000
28 #define MC_GAMELEN 400
31 static void
32 progress_status(struct uct *u, struct tree *t, enum stone color, int playouts)
34 if (!UDEBUGL(0))
35 return;
37 /* Best move */
38 struct tree_node *best = u->policy->choose(u->policy, t->root, t->board, color);
39 if (!best) {
40 fprintf(stderr, "... No moves left\n");
41 return;
43 fprintf(stderr, "[%d] ", playouts);
44 fprintf(stderr, "best %f ", best->u.value);
46 /* Max depth */
47 fprintf(stderr, "deepest % 2d ", t->max_depth - t->root->depth);
49 /* Best sequence */
50 fprintf(stderr, "| seq ");
51 for (int depth = 0; depth < 6; depth++) {
52 if (best && best->u.playouts >= 25) {
53 fprintf(stderr, "%3s ", coord2sstr(best->coord, t->board));
54 best = u->policy->choose(u->policy, best, t->board, color);
55 } else {
56 fprintf(stderr, " ");
60 /* Best candidates */
61 fprintf(stderr, "| can ");
62 int cans = 4;
63 struct tree_node *can[cans];
64 memset(can, 0, sizeof(can));
65 best = t->root->children;
66 while (best) {
67 int c = 0;
68 while ((!can[c] || best->u.playouts > can[c]->u.playouts) && ++c < cans);
69 for (int d = 0; d < c; d++) can[d] = can[d + 1];
70 if (c > 0) can[c - 1] = best;
71 best = best->sibling;
73 while (--cans >= 0) {
74 if (can[cans]) {
75 fprintf(stderr, "%3s(%.3f) ", coord2sstr(can[cans]->coord, t->board), 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 if (n->u.playouts >= u->expand_p)
93 tree_expand_node(t, n, b, next_color, u->radar_d, u->policy,
94 (next_color == player_color ? 1 : -1));
95 if (UDEBUGL(7))
96 fprintf(stderr, "%s*-- UCT playout #%d start [%s] %f\n",
97 spaces, n->u.playouts, coord2sstr(n->coord, t->board), n->u.value);
99 int result = play_random_game(&b2, next_color, u->gamelen, u->playout_amaf ? amaf : NULL, u->playout);
100 if (player_color != next_color && result >= 0)
101 result = !result;
102 if (UDEBUGL(7))
103 fprintf(stderr, "%s -- [%d..%d] %s random playout result %d\n",
104 spaces, player_color, next_color, coord2sstr(n->coord, t->board), result);
106 return result;
109 static int
110 uct_playout(struct uct *u, struct board *b, enum stone player_color, struct tree *t)
112 struct board b2;
113 board_copy(&b2, b);
115 struct playout_amafmap *amaf = NULL;
116 if (u->policy->wants_amaf) {
117 amaf = calloc(1, sizeof(*amaf));
118 amaf->map = calloc(board_size2(&b2) + 1, sizeof(*amaf->map));
119 amaf->map++; // -1 is pass
122 /* Walk the tree until we find a leaf, then expand it and do
123 * a random playout. */
124 struct tree_node *n = t->root;
125 enum stone node_color = stone_other(player_color);
126 int result;
127 int pass_limit = (board_size(&b2) - 2) * (board_size(&b2) - 2) / 2;
128 int passes = is_pass(b->last_move.coord);
129 /* debug */
130 int depth = 0;
131 static char spaces[] = "\0 ";
132 /* /debug */
133 if (UDEBUGL(8))
134 fprintf(stderr, "--- UCT walk with color %d\n", player_color);
135 while (!tree_leaf_node(n)) {
136 spaces[depth++] = ' '; spaces[depth] = 0;
138 n = u->policy->descend(u->policy, t, n, (node_color == player_color ? -1 : 1), pass_limit);
139 node_color = stone_other(node_color);
140 assert(n == t->root || n->parent);
141 if (UDEBUGL(7))
142 fprintf(stderr, "%s+-- UCT sent us to [%s:%d] %f\n",
143 spaces, coord2sstr(n->coord, t->board), n->coord, n->u.value);
144 if (amaf && n->coord >= -1 && !is_pass(n->coord)) {
145 if (amaf->map[n->coord] == S_NONE) {
146 amaf->map[n->coord] = node_color;
147 } else {
148 amaf_op(amaf->map[n->coord], +);
151 struct move m = { n->coord, node_color };
152 int res = board_play(&b2, &m);
154 if (res < 0 || (!is_pass(m.coord) && !group_at(&b2, m.coord)) /* suicide */
155 || b2.superko_violation) {
156 if (UDEBUGL(3)) {
157 for (struct tree_node *ni = n; ni; ni = ni->parent)
158 fprintf(stderr, "%s ", coord2sstr(ni->coord, t->board));
159 fprintf(stderr, "deleting invalid %s node %d,%d res %d group %d spk %d\n",
160 stone2str(node_color), coord_x(n->coord,b), coord_y(n->coord,b),
161 res, group_at(&b2, m.coord), b2.superko_violation);
163 tree_delete_node(t, n);
164 result = -1;
165 goto end;
168 if (is_pass(n->coord)) {
169 passes++;
170 if (passes >= 2) {
171 float score = board_official_score(&b2);
172 result = (player_color == S_BLACK) ? score < 0 : score > 0;
173 if (UDEBUGL(5))
174 fprintf(stderr, "[%d..%d] %s p-p scoring playout result %d (W %f)\n",
175 player_color, node_color, coord2sstr(n->coord, t->board), result, score);
176 if (UDEBUGL(6))
177 board_print(&b2, stderr);
178 goto update;
180 } else {
181 passes = 0;
185 /* Found a leaf node! */
186 result = uct_leaf_node(u, &b2, player_color, amaf, t, n, node_color, spaces);
188 update:
189 assert(n == t->root || n->parent);
190 if (result >= 0)
191 u->policy->update(u->policy, t, n, node_color, player_color, amaf, result);
193 end:
194 if (amaf) {
195 free(amaf->map - 1);
196 free(amaf);
198 board_done_noalloc(&b2);
199 return result;
202 static void
203 prepare_move(struct engine *e, struct board *b, enum stone color, coord_t promote)
205 struct uct *u = e->data;
207 if (!b->moves && u->t) {
208 /* Stale state from last game */
209 tree_done(u->t);
210 u->t = NULL;
213 if (!u->t) {
214 u->t = tree_init(b, color);
215 if (u->force_seed)
216 fast_srandom(u->force_seed);
217 if (UDEBUGL(0))
218 fprintf(stderr, "Fresh board with random seed %lu\n", fast_getseed());
219 //board_print(b, stderr);
220 tree_load(u->t, b, color);
223 /* XXX: We hope that the opponent didn't suddenly play
224 * several moves in the row. */
225 if (!is_resign(promote) && !tree_promote_at(u->t, b, promote)) {
226 if (UDEBUGL(2))
227 fprintf(stderr, "<cannot find node to promote>\n");
228 /* Reset tree */
229 tree_done(u->t);
230 u->t = tree_init(b, color);
234 /* Set in main thread in case the playouts should stop. */
235 static volatile sig_atomic_t halt = 0;
237 static int
238 uct_playouts(struct uct *u, struct board *b, enum stone color, struct tree *t)
240 int i, games = u->games;
241 if (t->root->children)
242 games -= t->root->u.playouts / 1.5;
243 /* else this is highly read-out but dead-end branch of opening book;
244 * we need to start from scratch; XXX: Maybe actually base the readout
245 * count based on number of playouts of best node? */
246 for (i = 0; i < games; i++) {
247 int result = uct_playout(u, b, color, t);
248 if (result < 0) {
249 /* Tree descent has hit invalid move. */
250 continue;
253 if (i > 0 && !(i % 10000)) {
254 progress_status(u, t, color, i);
257 if (i > 0 && !(i % 500)) {
258 struct tree_node *best = u->policy->choose(u->policy, t->root, b, color);
259 if (best && best->u.playouts >= 1500 && best->u.value >= u->loss_threshold)
260 break;
263 if (halt) {
264 if (UDEBUGL(2))
265 fprintf(stderr, "<halting early, %d games skipped>\n", games - i);
266 break;
270 progress_status(u, t, color, i);
271 if (UDEBUGL(3))
272 tree_dump(t, u->dumpthres);
273 return i;
276 static pthread_mutex_t finish_mutex = PTHREAD_MUTEX_INITIALIZER;
277 static pthread_cond_t finish_cond = PTHREAD_COND_INITIALIZER;
278 static volatile int finish_thread;
279 static pthread_mutex_t finish_serializer = PTHREAD_MUTEX_INITIALIZER;
281 struct spawn_ctx {
282 int tid;
283 struct uct *u;
284 struct board *b;
285 enum stone color;
286 struct tree *t;
287 unsigned long seed;
288 int games;
291 static void *
292 spawn_helper(void *ctx_)
294 struct spawn_ctx *ctx = ctx_;
295 /* Setup */
296 fast_srandom(ctx->seed);
297 /* Run */
298 ctx->games = uct_playouts(ctx->u, ctx->b, ctx->color, ctx->t);
299 /* Finish */
300 pthread_mutex_lock(&finish_serializer);
301 pthread_mutex_lock(&finish_mutex);
302 finish_thread = ctx->tid;
303 pthread_cond_signal(&finish_cond);
304 pthread_mutex_unlock(&finish_mutex);
305 return ctx;
308 static void
309 uct_notify_play(struct engine *e, struct board *b, struct move *m)
311 prepare_move(e, b, stone_other(m->color), m->coord);
314 static coord_t *
315 uct_genmove(struct engine *e, struct board *b, enum stone color)
317 struct uct *u = e->data;
319 /* Seed the tree. */
320 prepare_move(e, b, color, resign);
322 int played_games = 0;
323 if (!u->threads) {
324 played_games = uct_playouts(u, b, color, u->t);
325 } else {
326 pthread_t threads[u->threads];
327 int joined = 0;
328 halt = 0;
329 pthread_mutex_lock(&finish_mutex);
330 /* Spawn threads... */
331 for (int ti = 0; ti < u->threads; ti++) {
332 struct spawn_ctx *ctx = malloc(sizeof(*ctx));
333 ctx->u = u; ctx->b = b; ctx->color = color;
334 ctx->t = tree_copy(u->t); ctx->tid = ti;
335 ctx->seed = fast_random(65536) + ti;
336 pthread_create(&threads[ti], NULL, spawn_helper, ctx);
337 if (UDEBUGL(2))
338 fprintf(stderr, "Spawned thread %d\n", ti);
340 /* ...and collect them back: */
341 while (joined < u->threads) {
342 /* Wait for some thread to finish... */
343 pthread_cond_wait(&finish_cond, &finish_mutex);
344 /* ...and gather its remnants. */
345 struct spawn_ctx *ctx;
346 pthread_join(threads[finish_thread], (void **) &ctx);
347 played_games += ctx->games;
348 joined++;
349 tree_merge(u->t, ctx->t);
350 tree_done(ctx->t);
351 free(ctx);
352 if (UDEBUGL(2))
353 fprintf(stderr, "Joined thread %d\n", finish_thread);
354 /* Do not get stalled by slow threads. */
355 if (joined >= u->threads / 2)
356 halt = 1;
357 pthread_mutex_unlock(&finish_serializer);
359 pthread_mutex_unlock(&finish_mutex);
362 if (UDEBUGL(2))
363 tree_dump(u->t, u->dumpthres);
365 struct tree_node *best = u->policy->choose(u->policy, u->t->root, b, color);
366 if (!best) {
367 tree_done(u->t); u->t = NULL;
368 return coord_copy(pass);
370 if (UDEBUGL(0))
371 fprintf(stderr, "*** WINNER is %s (%d,%d) with score %1.4f (%d/%d:%d games)\n", coord2sstr(best->coord, b), coord_x(best->coord, b), coord_y(best->coord, b), best->u.value, best->u.playouts, u->t->root->u.playouts, played_games);
372 if (best->u.value < u->resign_ratio && !is_pass(best->coord)) {
373 tree_done(u->t); u->t = NULL;
374 return coord_copy(resign);
376 tree_promote_node(u->t, best);
377 return coord_copy(best->coord);
380 bool
381 uct_genbook(struct engine *e, struct board *b, enum stone color)
383 struct uct *u = e->data;
384 u->t = tree_init(b, color);
385 tree_load(u->t, b, color);
387 int i;
388 for (i = 0; i < u->games; i++) {
389 int result = uct_playout(u, b, color, u->t);
390 if (result < 0) {
391 /* Tree descent has hit invalid move. */
392 continue;
395 if (i > 0 && !(i % 10000)) {
396 progress_status(u, u->t, color, i);
399 progress_status(u, u->t, color, i);
401 tree_save(u->t, b, u->games / 100);
403 tree_done(u->t);
405 return true;
408 void
409 uct_dumpbook(struct engine *e, struct board *b, enum stone color)
411 struct uct *u = e->data;
412 u->t = tree_init(b, color);
413 tree_load(u->t, b, color);
414 tree_dump(u->t, 0);
415 tree_done(u->t);
419 struct uct *
420 uct_state_init(char *arg)
422 struct uct *u = calloc(1, sizeof(struct uct));
424 u->debug_level = 1;
425 u->games = MC_GAMES;
426 u->gamelen = MC_GAMELEN;
427 u->expand_p = 2;
428 u->dumpthres = 1000;
429 u->playout_amaf = false;
431 if (arg) {
432 char *optspec, *next = arg;
433 while (*next) {
434 optspec = next;
435 next += strcspn(next, ",");
436 if (*next) { *next++ = 0; } else { *next = 0; }
438 char *optname = optspec;
439 char *optval = strchr(optspec, '=');
440 if (optval) *optval++ = 0;
442 if (!strcasecmp(optname, "debug")) {
443 if (optval)
444 u->debug_level = atoi(optval);
445 else
446 u->debug_level++;
447 } else if (!strcasecmp(optname, "games") && optval) {
448 u->games = atoi(optval);
449 } else if (!strcasecmp(optname, "gamelen") && optval) {
450 u->gamelen = atoi(optval);
451 } else if (!strcasecmp(optname, "expand_p") && optval) {
452 u->expand_p = atoi(optval);
453 } else if (!strcasecmp(optname, "radar_d") && optval) {
454 /* For 19x19, it is good idea to set this to 3. */
455 u->radar_d = atoi(optval);
456 } else if (!strcasecmp(optname, "dumpthres") && optval) {
457 u->dumpthres = atoi(optval);
458 } else if (!strcasecmp(optname, "playout_amaf")) {
459 /* Whether to include random playout moves in
460 * AMAF as well. (Otherwise, only tree moves
461 * are included in AMAF. Of course makes sense
462 * only in connection with an AMAF policy.) */
463 /* with-without: 55.5% (+-4.1) */
464 if (optval && *optval == '0')
465 u->playout_amaf = false;
466 else
467 u->playout_amaf = true;
468 } else if (!strcasecmp(optname, "policy") && optval) {
469 char *policyarg = strchr(optval, ':');
470 if (policyarg)
471 *policyarg++ = 0;
472 if (!strcasecmp(optval, "ucb1")) {
473 u->policy = policy_ucb1_init(u, policyarg);
474 } else if (!strcasecmp(optval, "ucb1tuned")) {
475 u->policy = policy_ucb1tuned_init(u, policyarg);
476 } else if (!strcasecmp(optval, "ucb1amaf")) {
477 u->policy = policy_ucb1amaf_init(u, policyarg);
478 } else {
479 fprintf(stderr, "UCT: Invalid tree policy %s\n", optval);
481 } else if (!strcasecmp(optname, "playout") && optval) {
482 char *playoutarg = strchr(optval, ':');
483 if (playoutarg)
484 *playoutarg++ = 0;
485 if (!strcasecmp(optval, "old")) {
486 u->playout = playout_old_init(playoutarg);
487 } else if (!strcasecmp(optval, "moggy")) {
488 u->playout = playout_moggy_init(playoutarg);
489 } else if (!strcasecmp(optval, "light")) {
490 u->playout = playout_light_init(playoutarg);
491 } else {
492 fprintf(stderr, "UCT: Invalid playout policy %s\n", optval);
494 } else if (!strcasecmp(optname, "threads") && optval) {
495 u->threads = atoi(optval);
496 } else if (!strcasecmp(optname, "force_seed") && optval) {
497 u->force_seed = atoi(optval);
498 } else {
499 fprintf(stderr, "uct: Invalid engine argument %s or missing value\n", optname);
504 u->resign_ratio = 0.2; /* Resign when most games are lost. */
505 u->loss_threshold = 0.85; /* Stop reading if after at least 1500 playouts this is best value. */
506 if (!u->policy)
507 u->policy = policy_ucb1amaf_init(u, NULL);
509 if (!u->playout)
510 u->playout = playout_moggy_init(NULL);
511 u->playout->debug_level = u->debug_level;
513 return u;
517 struct engine *
518 engine_uct_init(char *arg)
520 struct uct *u = uct_state_init(arg);
521 struct engine *e = calloc(1, sizeof(struct engine));
522 e->name = "UCT Engine";
523 e->comment = "I'm playing UCT. When we both pass, I will consider all the stones on the board alive. If you are reading this, write 'yes'. Please bear with me at the game end, I need to fill the whole board; if you help me, we will both be happier. Filling the board will not lose points (NZ rules).";
524 e->genmove = uct_genmove;
525 e->notify_play = uct_notify_play;
526 e->data = u;
528 return e;