uct_playout(): Further simplify the main loop
[pachi.git] / uct / uct.c
blob3d390c3c7c40d5ee46d95416fe82bfb2dba183c1
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);
136 while (!tree_leaf_node(n) && passes < 2) {
137 spaces[depth++] = ' '; spaces[depth] = 0;
139 n = u->policy->descend(u->policy, t, n, (node_color == player_color ? -1 : 1), pass_limit);
140 node_color = stone_other(node_color);
141 assert(n == t->root || n->parent);
142 if (UDEBUGL(7))
143 fprintf(stderr, "%s+-- UCT sent us to [%s:%d] %f\n",
144 spaces, coord2sstr(n->coord, t->board), n->coord, n->u.value);
146 if (amaf && n->coord >= -1 && !is_pass(n->coord)) {
147 if (amaf->map[n->coord] == S_NONE) {
148 amaf->map[n->coord] = node_color;
149 } else {
150 amaf_op(amaf->map[n->coord], +);
154 struct move m = { n->coord, node_color };
155 int res = board_play(&b2, &m);
157 if (res < 0 || (!is_pass(m.coord) && !group_at(&b2, m.coord)) /* suicide */
158 || b2.superko_violation) {
159 if (UDEBUGL(3)) {
160 for (struct tree_node *ni = n; ni; ni = ni->parent)
161 fprintf(stderr, "%s ", coord2sstr(ni->coord, t->board));
162 fprintf(stderr, "deleting invalid %s node %d,%d res %d group %d spk %d\n",
163 stone2str(node_color), coord_x(n->coord,b), coord_y(n->coord,b),
164 res, group_at(&b2, m.coord), b2.superko_violation);
166 tree_delete_node(t, n);
167 result = -1;
168 goto end;
171 if (is_pass(n->coord))
172 passes++;
173 else
174 passes = 0;
177 if (tree_leaf_node(n)) {
178 result = uct_leaf_node(u, &b2, player_color, amaf, t, n, node_color, spaces);
180 } else { assert(passes >= 2);
182 float score = board_official_score(&b2);
183 result = (player_color == S_BLACK) ? score < 0 : score > 0;
185 if (UDEBUGL(5))
186 fprintf(stderr, "[%d..%d] %s p-p scoring playout result %d (W %f)\n",
187 player_color, node_color, coord2sstr(n->coord, t->board), result, score);
188 if (UDEBUGL(6))
189 board_print(&b2, stderr);
192 assert(n == t->root || n->parent);
193 if (result >= 0)
194 u->policy->update(u->policy, t, n, node_color, player_color, amaf, result);
196 end:
197 if (amaf) {
198 free(amaf->map - 1);
199 free(amaf);
201 board_done_noalloc(&b2);
202 return result;
205 static void
206 prepare_move(struct engine *e, struct board *b, enum stone color, coord_t promote)
208 struct uct *u = e->data;
210 if (!b->moves && u->t) {
211 /* Stale state from last game */
212 tree_done(u->t);
213 u->t = NULL;
216 if (!u->t) {
217 u->t = tree_init(b, color);
218 if (u->force_seed)
219 fast_srandom(u->force_seed);
220 if (UDEBUGL(0))
221 fprintf(stderr, "Fresh board with random seed %lu\n", fast_getseed());
222 //board_print(b, stderr);
223 tree_load(u->t, b, color);
226 /* XXX: We hope that the opponent didn't suddenly play
227 * several moves in the row. */
228 if (!is_resign(promote) && !tree_promote_at(u->t, b, promote)) {
229 if (UDEBUGL(2))
230 fprintf(stderr, "<cannot find node to promote>\n");
231 /* Reset tree */
232 tree_done(u->t);
233 u->t = tree_init(b, color);
237 /* Set in main thread in case the playouts should stop. */
238 static volatile sig_atomic_t halt = 0;
240 static int
241 uct_playouts(struct uct *u, struct board *b, enum stone color, struct tree *t)
243 int i, games = u->games;
244 if (t->root->children)
245 games -= t->root->u.playouts / 1.5;
246 /* else this is highly read-out but dead-end branch of opening book;
247 * we need to start from scratch; XXX: Maybe actually base the readout
248 * count based on number of playouts of best node? */
249 for (i = 0; i < games; i++) {
250 int result = uct_playout(u, b, color, t);
251 if (result < 0) {
252 /* Tree descent has hit invalid move. */
253 continue;
256 if (i > 0 && !(i % 10000)) {
257 progress_status(u, t, color, i);
260 if (i > 0 && !(i % 500)) {
261 struct tree_node *best = u->policy->choose(u->policy, t->root, b, color);
262 if (best && best->u.playouts >= 1500 && best->u.value >= u->loss_threshold)
263 break;
266 if (halt) {
267 if (UDEBUGL(2))
268 fprintf(stderr, "<halting early, %d games skipped>\n", games - i);
269 break;
273 progress_status(u, t, color, i);
274 if (UDEBUGL(3))
275 tree_dump(t, u->dumpthres);
276 return i;
279 static pthread_mutex_t finish_mutex = PTHREAD_MUTEX_INITIALIZER;
280 static pthread_cond_t finish_cond = PTHREAD_COND_INITIALIZER;
281 static volatile int finish_thread;
282 static pthread_mutex_t finish_serializer = PTHREAD_MUTEX_INITIALIZER;
284 struct spawn_ctx {
285 int tid;
286 struct uct *u;
287 struct board *b;
288 enum stone color;
289 struct tree *t;
290 unsigned long seed;
291 int games;
294 static void *
295 spawn_helper(void *ctx_)
297 struct spawn_ctx *ctx = ctx_;
298 /* Setup */
299 fast_srandom(ctx->seed);
300 /* Run */
301 ctx->games = uct_playouts(ctx->u, ctx->b, ctx->color, ctx->t);
302 /* Finish */
303 pthread_mutex_lock(&finish_serializer);
304 pthread_mutex_lock(&finish_mutex);
305 finish_thread = ctx->tid;
306 pthread_cond_signal(&finish_cond);
307 pthread_mutex_unlock(&finish_mutex);
308 return ctx;
311 static void
312 uct_notify_play(struct engine *e, struct board *b, struct move *m)
314 prepare_move(e, b, stone_other(m->color), m->coord);
317 static coord_t *
318 uct_genmove(struct engine *e, struct board *b, enum stone color)
320 struct uct *u = e->data;
322 /* Seed the tree. */
323 prepare_move(e, b, color, resign);
325 int played_games = 0;
326 if (!u->threads) {
327 played_games = uct_playouts(u, b, color, u->t);
328 } else {
329 pthread_t threads[u->threads];
330 int joined = 0;
331 halt = 0;
332 pthread_mutex_lock(&finish_mutex);
333 /* Spawn threads... */
334 for (int ti = 0; ti < u->threads; ti++) {
335 struct spawn_ctx *ctx = malloc(sizeof(*ctx));
336 ctx->u = u; ctx->b = b; ctx->color = color;
337 ctx->t = tree_copy(u->t); ctx->tid = ti;
338 ctx->seed = fast_random(65536) + ti;
339 pthread_create(&threads[ti], NULL, spawn_helper, ctx);
340 if (UDEBUGL(2))
341 fprintf(stderr, "Spawned thread %d\n", ti);
343 /* ...and collect them back: */
344 while (joined < u->threads) {
345 /* Wait for some thread to finish... */
346 pthread_cond_wait(&finish_cond, &finish_mutex);
347 /* ...and gather its remnants. */
348 struct spawn_ctx *ctx;
349 pthread_join(threads[finish_thread], (void **) &ctx);
350 played_games += ctx->games;
351 joined++;
352 tree_merge(u->t, ctx->t);
353 tree_done(ctx->t);
354 free(ctx);
355 if (UDEBUGL(2))
356 fprintf(stderr, "Joined thread %d\n", finish_thread);
357 /* Do not get stalled by slow threads. */
358 if (joined >= u->threads / 2)
359 halt = 1;
360 pthread_mutex_unlock(&finish_serializer);
362 pthread_mutex_unlock(&finish_mutex);
365 if (UDEBUGL(2))
366 tree_dump(u->t, u->dumpthres);
368 struct tree_node *best = u->policy->choose(u->policy, u->t->root, b, color);
369 if (!best) {
370 tree_done(u->t); u->t = NULL;
371 return coord_copy(pass);
373 if (UDEBUGL(0))
374 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);
375 if (best->u.value < u->resign_ratio && !is_pass(best->coord)) {
376 tree_done(u->t); u->t = NULL;
377 return coord_copy(resign);
379 tree_promote_node(u->t, best);
380 return coord_copy(best->coord);
383 bool
384 uct_genbook(struct engine *e, struct board *b, enum stone color)
386 struct uct *u = e->data;
387 u->t = tree_init(b, color);
388 tree_load(u->t, b, color);
390 int i;
391 for (i = 0; i < u->games; i++) {
392 int result = uct_playout(u, b, color, u->t);
393 if (result < 0) {
394 /* Tree descent has hit invalid move. */
395 continue;
398 if (i > 0 && !(i % 10000)) {
399 progress_status(u, u->t, color, i);
402 progress_status(u, u->t, color, i);
404 tree_save(u->t, b, u->games / 100);
406 tree_done(u->t);
408 return true;
411 void
412 uct_dumpbook(struct engine *e, struct board *b, enum stone color)
414 struct uct *u = e->data;
415 u->t = tree_init(b, color);
416 tree_load(u->t, b, color);
417 tree_dump(u->t, 0);
418 tree_done(u->t);
422 struct uct *
423 uct_state_init(char *arg)
425 struct uct *u = calloc(1, sizeof(struct uct));
427 u->debug_level = 1;
428 u->games = MC_GAMES;
429 u->gamelen = MC_GAMELEN;
430 u->expand_p = 2;
431 u->dumpthres = 1000;
432 u->playout_amaf = false;
434 if (arg) {
435 char *optspec, *next = arg;
436 while (*next) {
437 optspec = next;
438 next += strcspn(next, ",");
439 if (*next) { *next++ = 0; } else { *next = 0; }
441 char *optname = optspec;
442 char *optval = strchr(optspec, '=');
443 if (optval) *optval++ = 0;
445 if (!strcasecmp(optname, "debug")) {
446 if (optval)
447 u->debug_level = atoi(optval);
448 else
449 u->debug_level++;
450 } else if (!strcasecmp(optname, "games") && optval) {
451 u->games = atoi(optval);
452 } else if (!strcasecmp(optname, "gamelen") && optval) {
453 u->gamelen = atoi(optval);
454 } else if (!strcasecmp(optname, "expand_p") && optval) {
455 u->expand_p = atoi(optval);
456 } else if (!strcasecmp(optname, "radar_d") && optval) {
457 /* For 19x19, it is good idea to set this to 3. */
458 u->radar_d = atoi(optval);
459 } else if (!strcasecmp(optname, "dumpthres") && optval) {
460 u->dumpthres = atoi(optval);
461 } else if (!strcasecmp(optname, "playout_amaf")) {
462 /* Whether to include random playout moves in
463 * AMAF as well. (Otherwise, only tree moves
464 * are included in AMAF. Of course makes sense
465 * only in connection with an AMAF policy.) */
466 /* with-without: 55.5% (+-4.1) */
467 if (optval && *optval == '0')
468 u->playout_amaf = false;
469 else
470 u->playout_amaf = true;
471 } else if (!strcasecmp(optname, "policy") && optval) {
472 char *policyarg = strchr(optval, ':');
473 if (policyarg)
474 *policyarg++ = 0;
475 if (!strcasecmp(optval, "ucb1")) {
476 u->policy = policy_ucb1_init(u, policyarg);
477 } else if (!strcasecmp(optval, "ucb1tuned")) {
478 u->policy = policy_ucb1tuned_init(u, policyarg);
479 } else if (!strcasecmp(optval, "ucb1amaf")) {
480 u->policy = policy_ucb1amaf_init(u, policyarg);
481 } else {
482 fprintf(stderr, "UCT: Invalid tree policy %s\n", optval);
484 } else if (!strcasecmp(optname, "playout") && optval) {
485 char *playoutarg = strchr(optval, ':');
486 if (playoutarg)
487 *playoutarg++ = 0;
488 if (!strcasecmp(optval, "old")) {
489 u->playout = playout_old_init(playoutarg);
490 } else if (!strcasecmp(optval, "moggy")) {
491 u->playout = playout_moggy_init(playoutarg);
492 } else if (!strcasecmp(optval, "light")) {
493 u->playout = playout_light_init(playoutarg);
494 } else {
495 fprintf(stderr, "UCT: Invalid playout policy %s\n", optval);
497 } else if (!strcasecmp(optname, "threads") && optval) {
498 u->threads = atoi(optval);
499 } else if (!strcasecmp(optname, "force_seed") && optval) {
500 u->force_seed = atoi(optval);
501 } else {
502 fprintf(stderr, "uct: Invalid engine argument %s or missing value\n", optname);
507 u->resign_ratio = 0.2; /* Resign when most games are lost. */
508 u->loss_threshold = 0.85; /* Stop reading if after at least 1500 playouts this is best value. */
509 if (!u->policy)
510 u->policy = policy_ucb1amaf_init(u, NULL);
512 if (!u->playout)
513 u->playout = playout_moggy_init(NULL);
514 u->playout->debug_level = u->debug_level;
516 return u;
520 struct engine *
521 engine_uct_init(char *arg)
523 struct uct *u = uct_state_init(arg);
524 struct engine *e = calloc(1, sizeof(struct engine));
525 e->name = "UCT Engine";
526 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).";
527 e->genmove = uct_genmove;
528 e->notify_play = uct_notify_play;
529 e->data = u;
531 return e;