UCT Threading: Split uct_playouts_threaded() to uct_pondering_start(), uct_pondering_...
[pachi.git] / uct / uct.c
blob401823508bfe362fa739fcd20026ee146f9ba783
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 "gtp.h"
13 #include "move.h"
14 #include "mq.h"
15 #include "playout.h"
16 #include "playout/elo.h"
17 #include "playout/moggy.h"
18 #include "playout/light.h"
19 #include "random.h"
20 #include "tactics.h"
21 #include "uct/internal.h"
22 #include "uct/prior.h"
23 #include "uct/tree.h"
24 #include "uct/uct.h"
25 #include "uct/walk.h"
27 struct uct_policy *policy_ucb1_init(struct uct *u, char *arg);
28 struct uct_policy *policy_ucb1amaf_init(struct uct *u, char *arg);
31 #define MC_GAMES 80000
32 #define MC_GAMELEN MAX_GAMELEN
34 /* How big proportion of ownermap counts must be of one color to consider
35 * the point sure. */
36 #define GJ_THRES 0.8
37 /* How many games to consider at minimum before judging groups. */
38 #define GJ_MINGAMES 500
41 static void
42 setup_state(struct uct *u, struct board *b, enum stone color)
44 u->t = tree_init(b, color);
45 if (u->force_seed)
46 fast_srandom(u->force_seed);
47 if (UDEBUGL(0))
48 fprintf(stderr, "Fresh board with random seed %lu\n", fast_getseed());
49 //board_print(b, stderr);
50 if (!u->no_book && b->moves == 0) {
51 assert(color == S_BLACK);
52 tree_load(u->t, b);
56 static void
57 reset_state(struct uct *u)
59 assert(u->t);
60 tree_done(u->t); u->t = NULL;
63 static void
64 prepare_move(struct engine *e, struct board *b, enum stone color)
66 struct uct *u = e->data;
68 if (u->t) {
69 /* Verify that we have sane state. */
70 assert(b->es == u);
71 assert(u->t && b->moves);
72 if (color != stone_other(u->t->root_color)) {
73 fprintf(stderr, "Fatal: Non-alternating play detected %d %d\n",
74 color, u->t->root_color);
75 exit(1);
78 } else {
79 /* We need fresh state. */
80 b->es = u;
81 setup_state(u, b, color);
84 if (u->dynkomi && u->dynkomi > b->moves && (color & u->dynkomi_mask))
85 u->t->extra_komi = uct_get_extra_komi(u, b);
87 u->ownermap.playouts = 0;
88 memset(u->ownermap.map, 0, board_size2(b) * sizeof(u->ownermap.map[0]));
91 static void
92 dead_group_list(struct uct *u, struct board *b, struct move_queue *mq)
94 struct group_judgement gj;
95 gj.thres = GJ_THRES;
96 gj.gs = alloca(board_size2(b) * sizeof(gj.gs[0]));
97 board_ownermap_judge_group(b, &u->ownermap, &gj);
98 groups_of_status(b, &gj, GS_DEAD, mq);
101 bool
102 uct_pass_is_safe(struct uct *u, struct board *b, enum stone color, bool pass_all_alive)
104 if (u->ownermap.playouts < GJ_MINGAMES)
105 return false;
107 struct move_queue mq = { .moves = 0 };
108 if (!pass_all_alive)
109 dead_group_list(u, b, &mq);
110 return pass_is_safe(b, color, &mq);
114 static void
115 uct_printhook_ownermap(struct board *board, coord_t c, FILE *f)
117 struct uct *u = board->es;
118 assert(u);
119 const char chr[] = ":XO,"; // dame, black, white, unclear
120 const char chm[] = ":xo,";
121 char ch = chr[board_ownermap_judge_point(&u->ownermap, c, GJ_THRES)];
122 if (ch == ',') { // less precise estimate then?
123 ch = chm[board_ownermap_judge_point(&u->ownermap, c, 0.67)];
125 fprintf(f, "%c ", ch);
128 static char *
129 uct_notify_play(struct engine *e, struct board *b, struct move *m)
131 struct uct *u = e->data;
132 if (!u->t) {
133 /* No state, create one - this is probably game beginning
134 * and we need to load the opening book right now. */
135 prepare_move(e, b, m->color);
136 assert(u->t);
139 if (is_resign(m->coord)) {
140 /* Reset state. */
141 reset_state(u);
142 return NULL;
145 /* Promote node of the appropriate move to the tree root. */
146 assert(u->t->root);
147 if (!tree_promote_at(u->t, b, m->coord)) {
148 if (UDEBUGL(0))
149 fprintf(stderr, "Warning: Cannot promote move node! Several play commands in row?\n");
150 reset_state(u);
151 return NULL;
154 return NULL;
157 static char *
158 uct_chat(struct engine *e, struct board *b, char *cmd)
160 struct uct *u = e->data;
161 static char reply[1024];
163 cmd += strspn(cmd, " \n\t");
164 if (!strncasecmp(cmd, "winrate", 7)) {
165 if (!u->t)
166 return "no game context (yet?)";
167 enum stone color = u->t->root_color;
168 struct tree_node *n = u->t->root;
169 snprintf(reply, 1024, "In %d*%d playouts, %s %s can win with %.2f%% probability",
170 n->u.playouts, u->threads, stone2str(color), coord2sstr(n->coord, b),
171 tree_node_get_value(u->t, -1, n->u.value) * 100);
172 if (abs(u->t->extra_komi) >= 0.5) {
173 sprintf(reply + strlen(reply), ", while self-imposing extra komi %.1f",
174 u->t->extra_komi);
176 strcat(reply, ".");
177 return reply;
179 return NULL;
182 static void
183 uct_dead_group_list(struct engine *e, struct board *b, struct move_queue *mq)
185 struct uct *u = e->data;
186 if (u->pass_all_alive)
187 return; // no dead groups
189 bool mock_state = false;
191 if (!u->t) {
192 /* No state, but we cannot just back out - we might
193 * have passed earlier, only assuming some stones are
194 * dead, and then re-connected, only to lose counting
195 * when all stones are assumed alive. */
196 /* Mock up some state and seed the ownermap by few
197 * simulations. */
198 prepare_move(e, b, S_BLACK); assert(u->t);
199 for (int i = 0; i < GJ_MINGAMES; i++)
200 uct_playout(u, b, S_BLACK, u->t);
201 mock_state = true;
204 dead_group_list(u, b, mq);
206 if (mock_state) {
207 /* Clean up the mock state in case we will receive
208 * a genmove; we could get a non-alternating-move
209 * error from prepare_move() in that case otherwise. */
210 reset_state(u);
214 static void
215 playout_policy_done(struct playout_policy *p)
217 if (p->done) p->done(p);
218 if (p->data) free(p->data);
219 free(p);
222 static void
223 uct_done(struct engine *e)
225 /* This is called on engine reset, especially when clear_board
226 * is received and new game should begin. */
227 struct uct *u = e->data;
228 if (u->t) reset_state(u);
229 free(u->ownermap.map);
231 free(u->policy);
232 free(u->random_policy);
233 playout_policy_done(u->playout);
234 uct_prior_done(u->prior);
238 /* Pachi threading structure (if uct_playouts_parallel() is used):
240 * main thread
241 * | main(), GTP communication, ...
243 * thread_manager
244 * | spawns and manages worker threads
246 * worker0
247 * worker1
248 * ...
249 * workerK
250 * uct_playouts() loop, doing descend-playout N=games times
253 /* Set in thread manager in case the workers should stop. */
254 volatile sig_atomic_t uct_halt = 0;
255 /* ID of the running worker thread. */
256 __thread int thread_id = -1;
257 /* ID of the thread manager. */
258 static pthread_t thread_manager;
259 static bool thread_manager_running;
261 static pthread_mutex_t finish_mutex = PTHREAD_MUTEX_INITIALIZER;
262 static pthread_cond_t finish_cond = PTHREAD_COND_INITIALIZER;
263 static volatile int finish_thread;
264 static pthread_mutex_t finish_serializer = PTHREAD_MUTEX_INITIALIZER;
266 struct spawn_ctx {
267 int tid;
268 struct uct *u;
269 struct board *b;
270 enum stone color;
271 struct tree *t;
272 unsigned long seed;
273 int games;
276 static void *
277 spawn_worker(void *ctx_)
279 struct spawn_ctx *ctx = ctx_;
280 /* Setup */
281 fast_srandom(ctx->seed);
282 thread_id = ctx->tid;
283 /* Run */
284 ctx->games = uct_playouts(ctx->u, ctx->b, ctx->color, ctx->t, ctx->games);
285 /* Finish */
286 pthread_mutex_lock(&finish_serializer);
287 pthread_mutex_lock(&finish_mutex);
288 finish_thread = ctx->tid;
289 pthread_cond_signal(&finish_cond);
290 pthread_mutex_unlock(&finish_mutex);
291 return ctx;
294 /* Thread manager, controlling worker threads. It must be called with
295 * finish_mutex lock held, and the finish_cond can be signalled for it
296 * to stop; in that case, the caller should set finish_thread = -1. */
297 static void *
298 spawn_thread_manager(void *ctx_)
300 /* In thread_manager, we use only some of the ctx fields. */
301 struct spawn_ctx *mctx = ctx_;
302 struct uct *u = mctx->u;
303 bool shared_tree = u->parallel_tree;
304 fast_srandom(mctx->seed);
306 int played_games = 0;
307 pthread_t threads[u->threads];
308 int joined = 0;
310 uct_halt = 0;
311 /* Spawn threads... */
312 for (int ti = 0; ti < u->threads; ti++) {
313 struct spawn_ctx *ctx = malloc(sizeof(*ctx));
314 ctx->u = u; ctx->b = mctx->b; ctx->color = mctx->color;
315 ctx->t = shared_tree ? mctx->t : tree_copy(mctx->t);
316 ctx->tid = ti; ctx->games = mctx->games;
317 ctx->seed = fast_random(65536) + ti;
318 pthread_create(&threads[ti], NULL, spawn_worker, ctx);
319 if (UDEBUGL(2))
320 fprintf(stderr, "Spawned worker %d\n", ti);
323 /* ...and collect them back: */
324 while (joined < u->threads) {
325 /* Wait for some thread to finish... */
326 pthread_cond_wait(&finish_cond, &finish_mutex);
327 if (finish_thread < 0) {
328 /* Stop-by-caller. Tell the workers to wrap up. */
329 uct_halt = 1;
330 continue;
332 /* ...and gather its remnants. */
333 struct spawn_ctx *ctx;
334 pthread_join(threads[finish_thread], (void **) &ctx);
335 played_games += ctx->games;
336 joined++;
337 if (!shared_tree) {
338 tree_merge(mctx->t, ctx->t);
339 tree_done(ctx->t);
341 free(ctx);
342 if (UDEBUGL(2))
343 fprintf(stderr, "Joined worker %d\n", finish_thread);
344 /* Do not get stalled by slow threads. */
345 if (joined >= u->threads / 2)
346 uct_halt = 1;
347 pthread_mutex_unlock(&finish_serializer);
350 if (!shared_tree)
351 tree_normalize(mctx->t, u->threads);
353 mctx->games = played_games;
354 return mctx;
357 static void
358 uct_pondering_start(struct uct *u, struct board *b0, enum stone color, struct tree *t, int games)
360 assert(u->threads > 0);
361 assert(!thread_manager_running);
363 /* *b0 can change in the meantime. */
364 struct board b; board_copy(&b, b0);
366 struct spawn_ctx ctx = { .u = u, .b = &b, .color = color, .t = t, .games = games, .seed = fast_random(65536) };
367 static struct spawn_ctx mctx; mctx = ctx;
368 pthread_mutex_lock(&finish_mutex);
369 pthread_create(&thread_manager, NULL, spawn_thread_manager, &mctx);
370 thread_manager_running = true;
373 static int
374 uct_pondering_stop(void)
376 assert(thread_manager_running);
378 struct spawn_ctx *pctx;
379 thread_manager_running = false;
380 pthread_join(thread_manager, (void **) &pctx);
381 pthread_mutex_unlock(&finish_mutex);
382 return pctx->games;
385 static int
386 uct_playouts_threaded(struct uct *u, struct board *b, enum stone color, struct tree *t, int games)
388 uct_pondering_start(u, b, color, t, games);
389 /* We just wait until the thread manager finishes. */
390 return uct_pondering_stop();
394 static coord_t *
395 uct_genmove(struct engine *e, struct board *b, enum stone color, bool pass_all_alive)
397 struct uct *u = e->data;
399 if (b->superko_violation) {
400 fprintf(stderr, "!!! WARNING: SUPERKO VIOLATION OCCURED BEFORE THIS MOVE\n");
401 fprintf(stderr, "Maybe you play with situational instead of positional superko?\n");
402 fprintf(stderr, "I'm going to ignore the violation, but note that I may miss\n");
403 fprintf(stderr, "some moves valid under this ruleset because of this.\n");
404 b->superko_violation = false;
407 /* Seed the tree. */
408 prepare_move(e, b, color);
409 assert(u->t);
411 /* Determine number of simulations. */
412 int games = u->games;
413 if (u->t->root->children) {
414 int delta = u->t->root->u.playouts * 2 / 3;
415 if (u->parallel_tree) delta /= u->threads;
416 games -= delta;
418 /* else this is highly read-out but dead-end branch of opening book;
419 * we need to start from scratch; XXX: Maybe actually base the readout
420 * count based on number of playouts of best node? */
421 if (games < u->games && UDEBUGL(2))
422 fprintf(stderr, "<pre-simulated %d games skipped>\n", u->games - games);
424 /* Perform the Monte Carlo Tree Search! */
425 int played_games = uct_playouts_threaded(u, b, color, u->t, games);
427 if (UDEBUGL(2))
428 tree_dump(u->t, u->dumpthres);
430 /* Choose the best move from the tree. */
431 struct tree_node *best = u->policy->choose(u->policy, u->t->root, b, color);
432 if (!best) {
433 reset_state(u);
434 return coord_copy(pass);
436 if (UDEBUGL(0)) {
437 uct_progress_status(u, u->t, color, played_games);
439 if (UDEBUGL(1))
440 fprintf(stderr, "*** WINNER is %s (%d,%d) with score %1.4f (%d/%d:%d games)\n",
441 coord2sstr(best->coord, b), coord_x(best->coord, b), coord_y(best->coord, b),
442 tree_node_get_value(u->t, 1, best->u.value),
443 best->u.playouts, u->t->root->u.playouts, played_games);
444 if (tree_node_get_value(u->t, 1, best->u.value) < u->resign_ratio && !is_pass(best->coord)) {
445 reset_state(u);
446 return coord_copy(resign);
449 /* If the opponent just passed and we win counting, always
450 * pass as well. */
451 if (b->moves > 1 && is_pass(b->last_move.coord)) {
452 /* Make sure enough playouts are simulated. */
453 while (u->ownermap.playouts < GJ_MINGAMES)
454 uct_playout(u, b, color, u->t);
455 if (uct_pass_is_safe(u, b, color, u->pass_all_alive || pass_all_alive)) {
456 if (UDEBUGL(0))
457 fprintf(stderr, "<Will rather pass, looks safe enough.>\n");
458 best->coord = pass;
462 tree_promote_node(u->t, best);
463 return coord_copy(best->coord);
467 bool
468 uct_genbook(struct engine *e, struct board *b, enum stone color)
470 struct uct *u = e->data;
471 if (!u->t) prepare_move(e, b, color);
472 assert(u->t);
474 uct_playouts_threaded(u, b, color, u->t, u->games);
476 tree_save(u->t, b, u->games / 100);
478 return true;
481 void
482 uct_dumpbook(struct engine *e, struct board *b, enum stone color)
484 struct tree *t = tree_init(b, color);
485 tree_load(t, b);
486 tree_dump(t, 0);
487 tree_done(t);
491 struct uct *
492 uct_state_init(char *arg, struct board *b)
494 struct uct *u = calloc(1, sizeof(struct uct));
496 u->debug_level = 1;
497 u->games = MC_GAMES;
498 u->gamelen = MC_GAMELEN;
499 u->mercymin = 0;
500 u->expand_p = 2;
501 u->dumpthres = 1000;
502 u->playout_amaf = true;
503 u->playout_amaf_nakade = false;
504 u->amaf_prior = false;
505 u->max_tree_size = 3072ULL * 1048576;
507 if (board_size(b) - 2 >= 19)
508 u->dynkomi = 200;
509 u->dynkomi_mask = S_BLACK;
511 u->threads = 1;
512 u->thread_model = TM_TREEVL;
513 u->parallel_tree = true;
514 u->virtual_loss = true;
516 u->val_scale = 0.02; u->val_points = 20;
518 if (arg) {
519 char *optspec, *next = arg;
520 while (*next) {
521 optspec = next;
522 next += strcspn(next, ",");
523 if (*next) { *next++ = 0; } else { *next = 0; }
525 char *optname = optspec;
526 char *optval = strchr(optspec, '=');
527 if (optval) *optval++ = 0;
529 if (!strcasecmp(optname, "debug")) {
530 if (optval)
531 u->debug_level = atoi(optval);
532 else
533 u->debug_level++;
534 } else if (!strcasecmp(optname, "games") && optval) {
535 u->games = atoi(optval);
536 } else if (!strcasecmp(optname, "mercy") && optval) {
537 /* Minimal difference of black/white captures
538 * to stop playout - "Mercy Rule". Speeds up
539 * hopeless playouts at the expense of some
540 * accuracy. */
541 u->mercymin = atoi(optval);
542 } else if (!strcasecmp(optname, "gamelen") && optval) {
543 u->gamelen = atoi(optval);
544 } else if (!strcasecmp(optname, "expand_p") && optval) {
545 u->expand_p = atoi(optval);
546 } else if (!strcasecmp(optname, "dumpthres") && optval) {
547 u->dumpthres = atoi(optval);
548 } else if (!strcasecmp(optname, "playout_amaf")) {
549 /* Whether to include random playout moves in
550 * AMAF as well. (Otherwise, only tree moves
551 * are included in AMAF. Of course makes sense
552 * only in connection with an AMAF policy.) */
553 /* with-without: 55.5% (+-4.1) */
554 if (optval && *optval == '0')
555 u->playout_amaf = false;
556 else
557 u->playout_amaf = true;
558 } else if (!strcasecmp(optname, "playout_amaf_nakade")) {
559 /* Whether to include nakade moves from playouts
560 * in the AMAF statistics; this tends to nullify
561 * the playout_amaf effect by adding too much
562 * noise. */
563 if (optval && *optval == '0')
564 u->playout_amaf_nakade = false;
565 else
566 u->playout_amaf_nakade = true;
567 } else if (!strcasecmp(optname, "playout_amaf_cutoff") && optval) {
568 /* Keep only first N% of playout stage AMAF
569 * information. */
570 u->playout_amaf_cutoff = atoi(optval);
571 } else if ((!strcasecmp(optname, "policy") || !strcasecmp(optname, "random_policy")) && optval) {
572 char *policyarg = strchr(optval, ':');
573 struct uct_policy **p = !strcasecmp(optname, "policy") ? &u->policy : &u->random_policy;
574 if (policyarg)
575 *policyarg++ = 0;
576 if (!strcasecmp(optval, "ucb1")) {
577 *p = policy_ucb1_init(u, policyarg);
578 } else if (!strcasecmp(optval, "ucb1amaf")) {
579 *p = policy_ucb1amaf_init(u, policyarg);
580 } else {
581 fprintf(stderr, "UCT: Invalid tree policy %s\n", optval);
582 exit(1);
584 } else if (!strcasecmp(optname, "playout") && optval) {
585 char *playoutarg = strchr(optval, ':');
586 if (playoutarg)
587 *playoutarg++ = 0;
588 if (!strcasecmp(optval, "moggy")) {
589 u->playout = playout_moggy_init(playoutarg);
590 } else if (!strcasecmp(optval, "light")) {
591 u->playout = playout_light_init(playoutarg);
592 } else if (!strcasecmp(optval, "elo")) {
593 u->playout = playout_elo_init(playoutarg);
594 } else {
595 fprintf(stderr, "UCT: Invalid playout policy %s\n", optval);
596 exit(1);
598 } else if (!strcasecmp(optname, "prior") && optval) {
599 u->prior = uct_prior_init(optval, b);
600 } else if (!strcasecmp(optname, "amaf_prior") && optval) {
601 u->amaf_prior = atoi(optval);
602 } else if (!strcasecmp(optname, "threads") && optval) {
603 /* By default, Pachi will run with only single
604 * tree search thread! */
605 u->threads = atoi(optval);
606 } else if (!strcasecmp(optname, "thread_model") && optval) {
607 if (!strcasecmp(optval, "root")) {
608 /* Root parallelization - each thread
609 * does independent search, trees are
610 * merged at the end. */
611 u->thread_model = TM_ROOT;
612 u->parallel_tree = false;
613 u->virtual_loss = false;
614 } else if (!strcasecmp(optval, "tree")) {
615 /* Tree parallelization - all threads
616 * grind on the same tree. */
617 u->thread_model = TM_TREE;
618 u->parallel_tree = true;
619 u->virtual_loss = false;
620 } else if (!strcasecmp(optval, "treevl")) {
621 /* Tree parallelization, but also
622 * with virtual losses - this discou-
623 * rages most threads choosing the
624 * same tree branches to read. */
625 u->thread_model = TM_TREEVL;
626 u->parallel_tree = true;
627 u->virtual_loss = true;
628 } else {
629 fprintf(stderr, "UCT: Invalid thread model %s\n", optval);
630 exit(1);
632 } else if (!strcasecmp(optname, "force_seed") && optval) {
633 u->force_seed = atoi(optval);
634 } else if (!strcasecmp(optname, "no_book")) {
635 u->no_book = true;
636 } else if (!strcasecmp(optname, "dynkomi")) {
637 /* Dynamic komi in handicap game; linearly
638 * decreases to basic settings until move
639 * #optval. */
640 u->dynkomi = optval ? atoi(optval) : 150;
641 } else if (!strcasecmp(optname, "dynkomi_mask") && optval) {
642 /* Bitmask of colors the player must be
643 * for dynkomi be applied; you may want
644 * to use dynkomi_mask=3 to allow dynkomi
645 * even in games where Pachi is white. */
646 u->dynkomi_mask = atoi(optval);
647 } else if (!strcasecmp(optname, "val_scale") && optval) {
648 /* How much of the game result value should be
649 * influenced by win size. Zero means it isn't. */
650 u->val_scale = atof(optval);
651 } else if (!strcasecmp(optname, "val_points") && optval) {
652 /* Maximum size of win to be scaled into game
653 * result value. Zero means boardsize^2. */
654 u->val_points = atoi(optval) * 2; // result values are doubled
655 } else if (!strcasecmp(optname, "val_extra")) {
656 /* If false, the score coefficient will be simply
657 * added to the value, instead of scaling the result
658 * coefficient because of it. */
659 u->val_extra = !optval || atoi(optval);
660 } else if (!strcasecmp(optname, "root_heuristic") && optval) {
661 /* Whether to bias exploration by root node values
662 * (must be supported by the used policy).
663 * 0: Don't.
664 * 1: Do, value = result.
665 * Try to temper the result:
666 * 2: Do, value = 0.5+(result-expected)/2.
667 * 3: Do, value = 0.5+bzz((result-expected)^2). */
668 u->root_heuristic = atoi(optval);
669 } else if (!strcasecmp(optname, "pass_all_alive")) {
670 /* Whether to consider all stones alive at the game
671 * end instead of marking dead groupd. */
672 u->pass_all_alive = !optval || atoi(optval);
673 } else if (!strcasecmp(optname, "random_policy_chance") && optval) {
674 /* If specified (N), with probability 1/N, random_policy policy
675 * descend is used instead of main policy descend; useful
676 * if specified policy (e.g. UCB1AMAF) can make unduly biased
677 * choices sometimes, you can fall back to e.g.
678 * random_policy=UCB1. */
679 u->random_policy_chance = atoi(optval);
680 } else if (!strcasecmp(optname, "max_tree_size") && optval) {
681 /* Maximum amount of memory [MiB] consumed by the move tree.
682 * Default is 3072 (3 GiB). Note that if you use TM_ROOT,
683 * this limits size of only one of the trees, not all of them
684 * together. */
685 u->max_tree_size = atol(optval) * 1048576;
686 } else if (!strcasecmp(optname, "banner") && optval) {
687 /* Additional banner string. This must come as the
688 * last engine parameter. */
689 if (*next) *--next = ',';
690 u->banner = strdup(optval);
691 break;
692 } else {
693 fprintf(stderr, "uct: Invalid engine argument %s or missing value\n", optname);
694 exit(1);
699 u->resign_ratio = 0.2; /* Resign when most games are lost. */
700 u->loss_threshold = 0.85; /* Stop reading if after at least 5000 playouts this is best value. */
701 if (!u->policy)
702 u->policy = policy_ucb1amaf_init(u, NULL);
704 if (!!u->random_policy_chance ^ !!u->random_policy) {
705 fprintf(stderr, "uct: Only one of random_policy and random_policy_chance is set\n");
706 exit(1);
709 if (!u->prior)
710 u->prior = uct_prior_init(NULL, b);
712 if (!u->playout)
713 u->playout = playout_moggy_init(NULL);
714 u->playout->debug_level = u->debug_level;
716 u->ownermap.map = malloc(board_size2(b) * sizeof(u->ownermap.map[0]));
718 /* Some things remain uninitialized for now - the opening book
719 * is not loaded and the tree not set up. */
720 /* This will be initialized in setup_state() at the first move
721 * received/requested. This is because right now we are not aware
722 * about any komi or handicap setup and such. */
724 return u;
727 struct engine *
728 engine_uct_init(char *arg, struct board *b)
730 struct uct *u = uct_state_init(arg, b);
731 struct engine *e = calloc(1, sizeof(struct engine));
732 e->name = "UCT Engine";
733 e->printhook = uct_printhook_ownermap;
734 e->notify_play = uct_notify_play;
735 e->chat = uct_chat;
736 e->genmove = uct_genmove;
737 e->dead_group_list = uct_dead_group_list;
738 e->done = uct_done;
739 e->data = u;
741 const char banner[] = "I'm playing UCT. When I'm losing, I will resign, "
742 "if I think I win, I play until you pass. "
743 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
744 if (!u->banner) u->banner = "";
745 e->comment = malloc(sizeof(banner) + strlen(u->banner) + 1);
746 sprintf(e->comment, "%s %s", banner, u->banner);
748 return e;