UCB1AMAF: Rationale for zero gp_eqex
[pachi.git] / uct / uct.c
blobd4501947e15bb4cae55829700897cbf0211174fe
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 /* debug */
106 int depth = 0;
107 static char spaces[] = "\0 ";
108 /* /debug */
109 if (UDEBUGL(8))
110 fprintf(stderr, "--- UCT walk with color %d\n", color);
111 for (; pass; color = stone_other(color)) {
112 if (tree_leaf_node(n)) {
113 if (n->u.playouts >= u->expand_p)
114 tree_expand_node(t, n, &b2, color, u->radar_d, u->policy, (color == orig_color ? 1 : -1));
115 if (UDEBUGL(7))
116 fprintf(stderr, "%s*-- UCT playout #%d start [%s] %f\n", spaces, n->u.playouts, coord2sstr(n->coord, t->board), n->u.value);
118 result = play_random_game(&b2, color, u->gamelen, u->playout_amaf ? amaf : NULL, u->playout);
119 if (orig_color != color && result >= 0)
120 result = !result;
121 if (UDEBUGL(7))
122 fprintf(stderr, "%s -- [%d..%d] %s random playout result %d\n", spaces, orig_color, color, coord2sstr(n->coord, t->board), result);
124 /* Reset color to the @n color. */
125 color = stone_other(color);
126 break;
128 spaces[depth++] = ' '; spaces[depth] = 0;
130 n = u->policy->descend(u->policy, t, n, (color == orig_color ? 1 : -1), pass_limit);
131 assert(n == t->root || n->parent);
132 if (UDEBUGL(7))
133 fprintf(stderr, "%s+-- UCT sent us to [%s:%d] %f\n", spaces, coord2sstr(n->coord, t->board), n->coord, n->u.value);
134 if (amaf && n->coord >= -1 && !is_pass(n->coord)) {
135 if (amaf->map[n->coord] == S_NONE) {
136 amaf->map[n->coord] = color;
137 } else {
138 amaf_op(amaf->map[n->coord], +);
141 struct move m = { n->coord, color };
142 int res = board_play(&b2, &m);
144 if (res < 0 || (!is_pass(m.coord) && !group_at(&b2, m.coord)) /* suicide */
145 || b2.superko_violation) {
146 if (UDEBUGL(3)) {
147 for (struct tree_node *ni = n; ni; ni = ni->parent)
148 fprintf(stderr, "%s ", coord2sstr(ni->coord, t->board));
149 fprintf(stderr, "deleting invalid %s node %d,%d res %d group %d spk %d\n",
150 stone2str(color), coord_x(n->coord,b), coord_y(n->coord,b),
151 res, group_at(&b2, m.coord), b2.superko_violation);
153 tree_delete_node(t, n);
154 result = -1;
155 goto end;
158 if (is_pass(n->coord)) {
159 passes++;
160 if (passes >= 2) {
161 float score = board_official_score(&b2);
162 result = (orig_color == S_BLACK) ? score < 0 : score > 0;
163 if (UDEBUGL(5))
164 fprintf(stderr, "[%d..%d] %s p-p scoring playout result %d (W %f)\n", orig_color, color, coord2sstr(n->coord, t->board), result, score);
165 if (UDEBUGL(6))
166 board_print(&b2, stderr);
167 break;
169 } else {
170 passes = 0;
174 assert(n == t->root || n->parent);
175 if (result >= 0)
176 u->policy->update(u->policy, t, n, color, amaf, result);
178 end:
179 if (amaf) {
180 free(amaf->map - 1);
181 free(amaf);
183 board_done_noalloc(&b2);
184 return result;
187 static void
188 prepare_move(struct engine *e, struct board *b, enum stone color, coord_t promote)
190 struct uct *u = e->data;
192 if (!b->moves && u->t) {
193 /* Stale state from last game */
194 tree_done(u->t);
195 u->t = NULL;
198 if (!u->t) {
199 u->t = tree_init(b, color);
200 if (UDEBUGL(2))
201 fprintf(stderr, "Fresh board with random seed %lu\n", fast_getseed());
202 //board_print(b, stderr);
203 tree_load(u->t, b, color);
206 /* XXX: We hope that the opponent didn't suddenly play
207 * several moves in the row. */
208 if (!is_resign(promote) && !tree_promote_at(u->t, b, promote)) {
209 fprintf(stderr, "CANNOT FIND NODE TO PROMOTE!\n");
210 /* Reset tree */
211 tree_done(u->t);
212 u->t = tree_init(b, color);
216 /* Set in main thread in case the playouts should stop. */
217 static volatile sig_atomic_t halt = 0;
219 static int
220 uct_playouts(struct uct *u, struct board *b, enum stone color, struct tree *t)
222 int i, games = u->games - (t->root->u.playouts / 1.5);
223 for (i = 0; i < games; i++) {
224 int result = uct_playout(u, b, color, t);
225 if (result < 0) {
226 /* Tree descent has hit invalid move. */
227 continue;
230 if (i > 0 && !(i % 10000)) {
231 progress_status(u, t, color, i);
234 if (i > 0 && !(i % 500)) {
235 struct tree_node *best = u->policy->choose(u->policy, t->root, b, color);
236 if (best && best->u.playouts >= 1500 && best->u.value >= u->loss_threshold)
237 break;
240 if (halt) {
241 if (UDEBUGL(2))
242 fprintf(stderr, "<halting early, %d games skipped>\n", games - i);
243 break;
247 progress_status(u, t, color, i);
248 if (UDEBUGL(3))
249 tree_dump(t, u->dumpthres);
250 return i;
253 static pthread_mutex_t finish_mutex = PTHREAD_MUTEX_INITIALIZER;
254 static pthread_cond_t finish_cond = PTHREAD_COND_INITIALIZER;
255 static volatile int finish_thread;
256 static pthread_mutex_t finish_serializer = PTHREAD_MUTEX_INITIALIZER;
258 struct spawn_ctx {
259 int tid;
260 struct uct *u;
261 struct board *b;
262 enum stone color;
263 struct tree *t;
264 unsigned long seed;
265 int games;
268 static void *
269 spawn_helper(void *ctx_)
271 struct spawn_ctx *ctx = ctx_;
272 /* Setup */
273 fast_srandom(ctx->seed);
274 /* Run */
275 ctx->games = uct_playouts(ctx->u, ctx->b, ctx->color, ctx->t);
276 /* Finish */
277 pthread_mutex_lock(&finish_serializer);
278 pthread_mutex_lock(&finish_mutex);
279 finish_thread = ctx->tid;
280 pthread_cond_signal(&finish_cond);
281 pthread_mutex_unlock(&finish_mutex);
282 return ctx;
285 static void
286 uct_notify_play(struct engine *e, struct board *b, struct move *m)
288 prepare_move(e, b, stone_other(m->color), m->coord);
291 static coord_t *
292 uct_genmove(struct engine *e, struct board *b, enum stone color)
294 struct uct *u = e->data;
296 /* Seed the tree. */
297 prepare_move(e, b, color, resign);
299 int played_games = 0;
300 if (!u->threads) {
301 played_games = uct_playouts(u, b, color, u->t);
302 } else {
303 pthread_t threads[u->threads];
304 int joined = 0;
305 halt = 0;
306 pthread_mutex_lock(&finish_mutex);
307 /* Spawn threads... */
308 for (int ti = 0; ti < u->threads; ti++) {
309 struct spawn_ctx *ctx = malloc(sizeof(*ctx));
310 ctx->u = u; ctx->b = b; ctx->color = color;
311 ctx->t = tree_copy(u->t); ctx->tid = ti;
312 ctx->seed = fast_random(65536) + ti;
313 pthread_create(&threads[ti], NULL, spawn_helper, ctx);
314 if (UDEBUGL(2))
315 fprintf(stderr, "Spawned thread %d\n", ti);
317 /* ...and collect them back: */
318 while (joined < u->threads) {
319 /* Wait for some thread to finish... */
320 pthread_cond_wait(&finish_cond, &finish_mutex);
321 /* ...and gather its remnants. */
322 struct spawn_ctx *ctx;
323 pthread_join(threads[finish_thread], (void **) &ctx);
324 played_games += ctx->games;
325 joined++;
326 tree_merge(u->t, ctx->t);
327 tree_done(ctx->t);
328 free(ctx);
329 if (UDEBUGL(2))
330 fprintf(stderr, "Joined thread %d\n", finish_thread);
331 /* Do not get stalled by slow threads. */
332 if (joined >= u->threads / 2)
333 halt = 1;
334 pthread_mutex_unlock(&finish_serializer);
336 pthread_mutex_unlock(&finish_mutex);
339 if (UDEBUGL(2))
340 tree_dump(u->t, u->dumpthres);
342 struct tree_node *best = u->policy->choose(u->policy, u->t->root, b, color);
343 if (!best) {
344 tree_done(u->t); u->t = NULL;
345 return coord_copy(pass);
347 if (UDEBUGL(0))
348 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);
349 if (best->u.value < u->resign_ratio && !is_pass(best->coord)) {
350 tree_done(u->t); u->t = NULL;
351 return coord_copy(resign);
353 tree_promote_node(u->t, best);
354 return coord_copy(best->coord);
357 bool
358 uct_genbook(struct engine *e, struct board *b, enum stone color)
360 struct uct *u = e->data;
361 u->t = tree_init(b, color);
362 tree_load(u->t, b, color);
364 int i;
365 for (i = 0; i < u->games; i++) {
366 int result = uct_playout(u, b, color, u->t);
367 if (result < 0) {
368 /* Tree descent has hit invalid move. */
369 continue;
372 if (i > 0 && !(i % 10000)) {
373 progress_status(u, u->t, color, i);
376 progress_status(u, u->t, color, i);
378 tree_save(u->t, b, u->games / 100);
380 tree_done(u->t);
382 return true;
385 void
386 uct_dumpbook(struct engine *e, struct board *b, enum stone color)
388 struct uct *u = e->data;
389 u->t = tree_init(b, color);
390 tree_load(u->t, b, color);
391 tree_dump(u->t, 0);
392 tree_done(u->t);
396 struct uct *
397 uct_state_init(char *arg)
399 struct uct *u = calloc(1, sizeof(struct uct));
401 u->debug_level = 1;
402 u->games = MC_GAMES;
403 u->gamelen = MC_GAMELEN;
404 u->expand_p = 2;
405 u->dumpthres = 1000;
406 u->playout_amaf = false;
408 if (arg) {
409 char *optspec, *next = arg;
410 while (*next) {
411 optspec = next;
412 next += strcspn(next, ",");
413 if (*next) { *next++ = 0; } else { *next = 0; }
415 char *optname = optspec;
416 char *optval = strchr(optspec, '=');
417 if (optval) *optval++ = 0;
419 if (!strcasecmp(optname, "debug")) {
420 if (optval)
421 u->debug_level = atoi(optval);
422 else
423 u->debug_level++;
424 } else if (!strcasecmp(optname, "games") && optval) {
425 u->games = atoi(optval);
426 } else if (!strcasecmp(optname, "gamelen") && optval) {
427 u->gamelen = atoi(optval);
428 } else if (!strcasecmp(optname, "expand_p") && optval) {
429 u->expand_p = atoi(optval);
430 } else if (!strcasecmp(optname, "radar_d") && optval) {
431 /* For 19x19, it is good idea to set this to 3. */
432 u->radar_d = atoi(optval);
433 } else if (!strcasecmp(optname, "dumpthres") && optval) {
434 u->dumpthres = atoi(optval);
435 } else if (!strcasecmp(optname, "playout_amaf")) {
436 /* Whether to include random playout moves in
437 * AMAF as well. (Otherwise, only tree moves
438 * are included in AMAF. Of course makes sense
439 * only in connection with an AMAF policy.) */
440 /* with-without: 55.5% (+-4.1) */
441 if (optval && *optval == '0')
442 u->playout_amaf = false;
443 } else if (!strcasecmp(optname, "policy") && optval) {
444 char *policyarg = strchr(optval, ':');
445 if (policyarg)
446 *policyarg++ = 0;
447 if (!strcasecmp(optval, "ucb1")) {
448 u->policy = policy_ucb1_init(u, policyarg);
449 } else if (!strcasecmp(optval, "ucb1tuned")) {
450 u->policy = policy_ucb1tuned_init(u, policyarg);
451 } else if (!strcasecmp(optval, "ucb1amaf")) {
452 u->policy = policy_ucb1amaf_init(u, policyarg);
453 } else {
454 fprintf(stderr, "UCT: Invalid tree policy %s\n", optval);
456 } else if (!strcasecmp(optname, "playout") && optval) {
457 char *playoutarg = strchr(optval, ':');
458 if (playoutarg)
459 *playoutarg++ = 0;
460 if (!strcasecmp(optval, "old")) {
461 u->playout = playout_old_init(playoutarg);
462 } else if (!strcasecmp(optval, "moggy")) {
463 u->playout = playout_moggy_init(playoutarg);
464 } else if (!strcasecmp(optval, "light")) {
465 u->playout = playout_light_init(playoutarg);
466 } else {
467 fprintf(stderr, "UCT: Invalid playout policy %s\n", optval);
469 } else if (!strcasecmp(optname, "threads") && optval) {
470 u->threads = atoi(optval);
471 } else {
472 fprintf(stderr, "uct: Invalid engine argument %s or missing value\n", optname);
477 u->resign_ratio = 0.2; /* Resign when most games are lost. */
478 u->loss_threshold = 0.85; /* Stop reading if after at least 1500 playouts this is best value. */
479 if (!u->policy)
480 u->policy = policy_ucb1amaf_init(u, NULL);
482 if (!u->playout)
483 u->playout = playout_moggy_init(NULL);
484 u->playout->debug_level = u->debug_level;
486 return u;
490 struct engine *
491 engine_uct_init(char *arg)
493 struct uct *u = uct_state_init(arg);
494 struct engine *e = calloc(1, sizeof(struct engine));
495 e->name = "UCT Engine";
496 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).";
497 e->genmove = uct_genmove;
498 e->notify_play = uct_notify_play;
499 e->data = u;
501 return e;