tree_merge(): Fix merging of priors
[pachi/peepo.git] / uct / uct.c
blob452ade13fa8c10c8eff2f42fd2e14fd8d02a6523
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_playout(struct uct *u, struct board *b, enum stone color, struct tree *t)
88 struct board b2;
89 board_copy(&b2, b);
91 struct playout_amafmap *amaf = NULL;
92 if (u->policy->wants_amaf) {
93 amaf = calloc(1, sizeof(*amaf));
94 amaf->map = calloc(board_size2(&b2) + 1, sizeof(*amaf->map));
95 amaf->map++; // -1 is pass
98 /* Walk the tree until we find a leaf, then expand it and do
99 * a random playout. */
100 struct tree_node *n = t->root;
101 enum stone orig_color = color;
102 int result;
103 int pass_limit = (board_size(&b2) - 2) * (board_size(&b2) - 2) / 2;
104 int passes = is_pass(b->last_move.coord);
105 if (UDEBUGL(8))
106 fprintf(stderr, "--- UCT walk with color %d\n", color);
107 for (; pass; color = stone_other(color)) {
108 if (tree_leaf_node(n)) {
109 if (n->u.playouts >= u->expand_p)
110 tree_expand_node(t, n, &b2, color, u->radar_d, u->policy, (color == orig_color ? 1 : -1));
112 result = play_random_game(&b2, color, u->gamelen, u->playout_amaf ? amaf : NULL, u->playout);
113 if (orig_color != color && result >= 0)
114 result = !result;
115 if (UDEBUGL(7))
116 fprintf(stderr, "[%d..%d] %s random playout result %d\n", orig_color, color, coord2sstr(n->coord, t->board), result);
118 /* Reset color to the @n color. */
119 color = stone_other(color);
120 break;
123 n = u->policy->descend(u->policy, t, n, (color == orig_color ? 1 : -1), pass_limit);
124 assert(n == t->root || n->parent);
125 if (UDEBUGL(7))
126 fprintf(stderr, "-- UCT sent us to [%s] %f\n", coord2sstr(n->coord, t->board), n->u.value);
127 if (amaf && n->coord >= -1)
128 amaf->map[n->coord] = color;
129 struct move m = { n->coord, color };
130 int res = board_play(&b2, &m);
132 if (res < 0 || (!is_pass(m.coord) && !group_at(&b2, m.coord)) /* suicide */
133 || b2.superko_violation) {
134 if (UDEBUGL(3)) {
135 for (struct tree_node *ni = n; ni; ni = ni->parent)
136 fprintf(stderr, "%s ", coord2sstr(ni->coord, t->board));
137 fprintf(stderr, "deleting invalid %s node %d,%d res %d group %d spk %d\n",
138 stone2str(color), coord_x(n->coord,b), coord_y(n->coord,b),
139 res, group_at(&b2, m.coord), b2.superko_violation);
141 tree_delete_node(t, n);
142 result = -1;
143 goto end;
146 if (is_pass(n->coord)) {
147 passes++;
148 if (passes >= 2) {
149 float score = board_official_score(&b2);
150 result = (orig_color == S_BLACK) ? score < 0 : score > 0;
151 if (UDEBUGL(5))
152 fprintf(stderr, "[%d..%d] %s p-p scoring playout result %d (W %f)\n", orig_color, color, coord2sstr(n->coord, t->board), result, score);
153 if (UDEBUGL(6))
154 board_print(&b2, stderr);
155 break;
157 } else {
158 passes = 0;
162 assert(n == t->root || n->parent);
163 if (result >= 0)
164 u->policy->update(u->policy, t, n, color, amaf, result);
166 end:
167 if (amaf) {
168 free(amaf->map - 1);
169 free(amaf);
171 board_done_noalloc(&b2);
172 return result;
175 static void
176 prepare_move(struct engine *e, struct board *b, enum stone color, coord_t promote)
178 struct uct *u = e->data;
180 if (!b->moves && u->t) {
181 /* Stale state from last game */
182 tree_done(u->t);
183 u->t = NULL;
186 if (!u->t) {
187 u->t = tree_init(b, color);
188 //board_print(b, stderr);
189 tree_load(u->t, b, color);
192 /* XXX: We hope that the opponent didn't suddenly play
193 * several moves in the row. */
194 if (!is_resign(promote) && !tree_promote_at(u->t, b, promote)) {
195 fprintf(stderr, "CANNOT FIND NODE TO PROMOTE!\n");
196 /* Reset tree */
197 tree_done(u->t);
198 u->t = tree_init(b, color);
202 /* Set in main thread in case the playouts should stop. */
203 static volatile sig_atomic_t halt = 0;
205 static int
206 uct_playouts(struct uct *u, struct board *b, enum stone color, struct tree *t)
208 int i, games = u->games - (t->root->u.playouts / 1.5);
209 for (i = 0; i < games; i++) {
210 int result = uct_playout(u, b, color, t);
211 if (result < 0) {
212 /* Tree descent has hit invalid move. */
213 continue;
216 if (i > 0 && !(i % 10000)) {
217 progress_status(u, t, color, i);
220 if (i > 0 && !(i % 500)) {
221 struct tree_node *best = u->policy->choose(u->policy, t->root, b, color);
222 if (best && best->u.playouts >= 1500 && best->u.value >= u->loss_threshold)
223 break;
226 if (halt) {
227 if (UDEBUGL(2))
228 fprintf(stderr, "<halting early, %d games skipped>\n", games - i);
229 break;
233 progress_status(u, t, color, i);
234 if (UDEBUGL(3))
235 tree_dump(t, u->dumpthres);
236 return i;
239 static pthread_mutex_t finish_mutex = PTHREAD_MUTEX_INITIALIZER;
240 static pthread_cond_t finish_cond = PTHREAD_COND_INITIALIZER;
241 static volatile int finish_thread;
242 static pthread_mutex_t finish_serializer = PTHREAD_MUTEX_INITIALIZER;
244 struct spawn_ctx {
245 int tid;
246 struct uct *u;
247 struct board *b;
248 enum stone color;
249 struct tree *t;
250 unsigned long seed;
251 int games;
254 static void *
255 spawn_helper(void *ctx_)
257 struct spawn_ctx *ctx = ctx_;
258 /* Setup */
259 fast_srandom(ctx->seed);
260 /* Run */
261 ctx->games = uct_playouts(ctx->u, ctx->b, ctx->color, ctx->t);
262 /* Finish */
263 pthread_mutex_lock(&finish_serializer);
264 pthread_mutex_lock(&finish_mutex);
265 finish_thread = ctx->tid;
266 pthread_cond_signal(&finish_cond);
267 pthread_mutex_unlock(&finish_mutex);
268 return ctx;
271 static void
272 uct_notify_play(struct engine *e, struct board *b, struct move *m)
274 prepare_move(e, b, stone_other(m->color), m->coord);
277 static coord_t *
278 uct_genmove(struct engine *e, struct board *b, enum stone color)
280 struct uct *u = e->data;
282 /* Seed the tree. */
283 prepare_move(e, b, color, resign);
285 int played_games = 0;
286 if (!u->threads) {
287 played_games = uct_playouts(u, b, color, u->t);
288 } else {
289 pthread_t threads[u->threads];
290 int joined = 0;
291 halt = 0;
292 pthread_mutex_lock(&finish_mutex);
293 /* Spawn threads... */
294 for (int ti = 0; ti < u->threads; ti++) {
295 struct spawn_ctx *ctx = malloc(sizeof(*ctx));
296 ctx->u = u; ctx->b = b; ctx->color = color;
297 ctx->t = tree_copy(u->t); ctx->tid = ti;
298 ctx->seed = fast_random(65536) + ti;
299 pthread_create(&threads[ti], NULL, spawn_helper, ctx);
300 if (UDEBUGL(2))
301 fprintf(stderr, "Spawned thread %d\n", ti);
303 /* ...and collect them back: */
304 while (joined < u->threads) {
305 /* Wait for some thread to finish... */
306 pthread_cond_wait(&finish_cond, &finish_mutex);
307 /* ...and gather its remnants. */
308 struct spawn_ctx *ctx;
309 pthread_join(threads[finish_thread], (void **) &ctx);
310 played_games += ctx->games;
311 joined++;
312 tree_merge(u->t, ctx->t);
313 tree_done(ctx->t);
314 free(ctx);
315 if (UDEBUGL(2))
316 fprintf(stderr, "Joined thread %d\n", finish_thread);
317 /* Do not get stalled by slow threads. */
318 if (joined >= u->threads / 2)
319 halt = 1;
320 pthread_mutex_unlock(&finish_serializer);
322 pthread_mutex_unlock(&finish_mutex);
325 if (UDEBUGL(2))
326 tree_dump(u->t, u->dumpthres);
328 struct tree_node *best = u->policy->choose(u->policy, u->t->root, b, color);
329 if (!best) {
330 tree_done(u->t); u->t = NULL;
331 return coord_copy(pass);
333 if (UDEBUGL(0))
334 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);
335 if (best->u.value < u->resign_ratio && !is_pass(best->coord)) {
336 tree_done(u->t); u->t = NULL;
337 return coord_copy(resign);
339 tree_promote_node(u->t, best);
340 return coord_copy(best->coord);
343 bool
344 uct_genbook(struct engine *e, struct board *b, enum stone color)
346 struct uct *u = e->data;
347 u->t = tree_init(b, color);
348 tree_load(u->t, b, color);
350 int i;
351 for (i = 0; i < u->games; i++) {
352 int result = uct_playout(u, b, color, u->t);
353 if (result < 0) {
354 /* Tree descent has hit invalid move. */
355 continue;
358 if (i > 0 && !(i % 10000)) {
359 progress_status(u, u->t, color, i);
362 progress_status(u, u->t, color, i);
364 tree_save(u->t, b, u->games / 100);
366 tree_done(u->t);
368 return true;
371 void
372 uct_dumpbook(struct engine *e, struct board *b, enum stone color)
374 struct uct *u = e->data;
375 u->t = tree_init(b, color);
376 tree_load(u->t, b, color);
377 tree_dump(u->t, 0);
378 tree_done(u->t);
382 struct uct *
383 uct_state_init(char *arg)
385 struct uct *u = calloc(1, sizeof(struct uct));
387 u->debug_level = 1;
388 u->games = MC_GAMES;
389 u->gamelen = MC_GAMELEN;
390 u->expand_p = 2;
391 u->dumpthres = 1000;
392 u->playout_amaf = true;
394 if (arg) {
395 char *optspec, *next = arg;
396 while (*next) {
397 optspec = next;
398 next += strcspn(next, ",");
399 if (*next) { *next++ = 0; } else { *next = 0; }
401 char *optname = optspec;
402 char *optval = strchr(optspec, '=');
403 if (optval) *optval++ = 0;
405 if (!strcasecmp(optname, "debug")) {
406 if (optval)
407 u->debug_level = atoi(optval);
408 else
409 u->debug_level++;
410 } else if (!strcasecmp(optname, "games") && optval) {
411 u->games = atoi(optval);
412 } else if (!strcasecmp(optname, "gamelen") && optval) {
413 u->gamelen = atoi(optval);
414 } else if (!strcasecmp(optname, "expand_p") && optval) {
415 u->expand_p = atoi(optval);
416 } else if (!strcasecmp(optname, "radar_d") && optval) {
417 /* For 19x19, it is good idea to set this to 3. */
418 u->radar_d = atoi(optval);
419 } else if (!strcasecmp(optname, "dumpthres") && optval) {
420 u->dumpthres = atoi(optval);
421 } else if (!strcasecmp(optname, "playout_amaf")) {
422 /* Whether to include random playout moves in
423 * AMAF as well. (Otherwise, only tree moves
424 * are included in AMAF. Of course makes sense
425 * only in connection with an AMAF policy.) */
426 /* with-without: 55.5% (+-4.1) */
427 if (optval && *optval == '0')
428 u->playout_amaf = false;
429 } else if (!strcasecmp(optname, "policy") && optval) {
430 char *policyarg = strchr(optval, ':');
431 if (policyarg)
432 *policyarg++ = 0;
433 if (!strcasecmp(optval, "ucb1")) {
434 u->policy = policy_ucb1_init(u, policyarg);
435 } else if (!strcasecmp(optval, "ucb1tuned")) {
436 u->policy = policy_ucb1tuned_init(u, policyarg);
437 } else if (!strcasecmp(optval, "ucb1amaf")) {
438 u->policy = policy_ucb1amaf_init(u, policyarg);
439 } else {
440 fprintf(stderr, "UCT: Invalid tree policy %s\n", optval);
442 } else if (!strcasecmp(optname, "playout") && optval) {
443 char *playoutarg = strchr(optval, ':');
444 if (playoutarg)
445 *playoutarg++ = 0;
446 if (!strcasecmp(optval, "old")) {
447 u->playout = playout_old_init(playoutarg);
448 } else if (!strcasecmp(optval, "moggy")) {
449 u->playout = playout_moggy_init(playoutarg);
450 } else if (!strcasecmp(optval, "light")) {
451 u->playout = playout_light_init(playoutarg);
452 } else {
453 fprintf(stderr, "UCT: Invalid playout policy %s\n", optval);
455 } else if (!strcasecmp(optname, "threads") && optval) {
456 u->threads = atoi(optval);
457 } else {
458 fprintf(stderr, "uct: Invalid engine argument %s or missing value\n", optname);
463 u->resign_ratio = 0.2; /* Resign when most games are lost. */
464 u->loss_threshold = 0.85; /* Stop reading if after at least 1500 playouts this is best value. */
465 if (!u->policy)
466 u->policy = policy_ucb1amaf_init(u, NULL);
468 if (!u->playout)
469 u->playout = playout_moggy_init(NULL);
470 u->playout->debug_level = u->debug_level;
472 return u;
476 struct engine *
477 engine_uct_init(char *arg)
479 struct uct *u = uct_state_init(arg);
480 struct engine *e = calloc(1, sizeof(struct engine));
481 e->name = "UCT Engine";
482 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).";
483 e->genmove = uct_genmove;
484 e->notify_play = uct_notify_play;
485 e->data = u;
487 return e;