book.dat: Introduce fbook data file, from Fuego r1174
[pachi/pachi-r6144.git] / uct / search.c
blob0edbdc316aba3b65deb8a2a329f01b81d72b88fe
1 #include <assert.h>
2 #include <math.h>
3 #include <pthread.h>
4 #include <signal.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <time.h>
10 #define DEBUG
12 #include "debug.h"
13 #include "distributed/distributed.h"
14 #include "move.h"
15 #include "random.h"
16 #include "timeinfo.h"
17 #include "uct/dynkomi.h"
18 #include "uct/internal.h"
19 #include "uct/search.h"
20 #include "uct/tree.h"
21 #include "uct/uct.h"
22 #include "uct/walk.h"
25 /* Default number of simulations to perform per move.
26 * Note that this is now in total over all threads!. */
27 #define MC_GAMES 80000
28 static const struct time_info default_ti = {
29 .period = TT_MOVE,
30 .dim = TD_GAMES,
31 .len = { .games = MC_GAMES },
34 /* Once per how many simulations (per thread) to show a progress report line. */
35 #define TREE_SIMPROGRESS_INTERVAL 10000
37 /* When terminating UCT search early, the safety margin to add to the
38 * remaining playout number estimate when deciding whether the result can
39 * still change. */
40 #define PLAYOUT_DELTA_SAFEMARGIN 1000
42 /* Minimal number of simulations to consider early break. */
43 #define PLAYOUT_EARLY_BREAK_MIN 5000
46 /* Pachi threading structure:
48 * main thread
49 * | main(), GTP communication, ...
50 * | starts and stops the search managed by thread_manager
51 * |
52 * thread_manager
53 * | spawns and collects worker threads
54 * |
55 * worker0
56 * worker1
57 * ...
58 * workerK
59 * uct_playouts() loop, doing descend-playout until uct_halt
61 * Another way to look at it is by functions (lines denote thread boundaries):
63 * | uct_genmove()
64 * | uct_search() (uct_search_start() .. uct_search_stop())
65 * | -----------------------
66 * | spawn_thread_manager()
67 * | -----------------------
68 * | spawn_worker()
69 * V uct_playouts() */
71 /* Set in thread manager in case the workers should stop. */
72 volatile sig_atomic_t uct_halt = 0;
73 /* ID of the thread manager. */
74 static pthread_t thread_manager;
75 bool thread_manager_running;
77 static pthread_mutex_t finish_mutex = PTHREAD_MUTEX_INITIALIZER;
78 static pthread_cond_t finish_cond = PTHREAD_COND_INITIALIZER;
79 static volatile int finish_thread;
80 static pthread_mutex_t finish_serializer = PTHREAD_MUTEX_INITIALIZER;
82 static void *
83 spawn_worker(void *ctx_)
85 struct uct_thread_ctx *ctx = ctx_;
86 /* Setup */
87 fast_srandom(ctx->seed);
88 /* Run */
89 ctx->games = uct_playouts(ctx->u, ctx->b, ctx->color, ctx->t);
90 /* Finish */
91 pthread_mutex_lock(&finish_serializer);
92 pthread_mutex_lock(&finish_mutex);
93 finish_thread = ctx->tid;
94 pthread_cond_signal(&finish_cond);
95 pthread_mutex_unlock(&finish_mutex);
96 return ctx;
99 /* Thread manager, controlling worker threads. It must be called with
100 * finish_mutex lock held, but it will unlock it itself before exiting;
101 * this is necessary to be completely deadlock-free. */
102 /* The finish_cond can be signalled for it to stop; in that case,
103 * the caller should set finish_thread = -1. */
104 /* After it is started, it will update mctx->t to point at some tree
105 * used for the actual search, on return
106 * it will set mctx->games to the number of performed simulations. */
107 static void *
108 spawn_thread_manager(void *ctx_)
110 /* In thread_manager, we use only some of the ctx fields. */
111 struct uct_thread_ctx *mctx = ctx_;
112 struct uct *u = mctx->u;
113 struct tree *t = mctx->t;
114 fast_srandom(mctx->seed);
116 int played_games = 0;
117 pthread_t threads[u->threads];
118 int joined = 0;
120 uct_halt = 0;
122 /* Garbage collect the tree by preference when pondering. */
123 if (u->pondering && t->nodes && t->nodes_size >= t->pruning_threshold) {
124 t->root = tree_garbage_collect(t, t->root);
127 /* Spawn threads... */
128 for (int ti = 0; ti < u->threads; ti++) {
129 struct uct_thread_ctx *ctx = malloc2(sizeof(*ctx));
130 ctx->u = u; ctx->b = mctx->b; ctx->color = mctx->color;
131 mctx->t = ctx->t = t;
132 ctx->tid = ti; ctx->seed = fast_random(65536) + ti;
133 pthread_create(&threads[ti], NULL, spawn_worker, ctx);
134 if (UDEBUGL(3))
135 fprintf(stderr, "Spawned worker %d\n", ti);
138 /* ...and collect them back: */
139 while (joined < u->threads) {
140 /* Wait for some thread to finish... */
141 pthread_cond_wait(&finish_cond, &finish_mutex);
142 if (finish_thread < 0) {
143 /* Stop-by-caller. Tell the workers to wrap up. */
144 uct_halt = 1;
145 continue;
147 /* ...and gather its remnants. */
148 struct uct_thread_ctx *ctx;
149 pthread_join(threads[finish_thread], (void **) &ctx);
150 played_games += ctx->games;
151 joined++;
152 free(ctx);
153 if (UDEBUGL(3))
154 fprintf(stderr, "Joined worker %d\n", finish_thread);
155 pthread_mutex_unlock(&finish_serializer);
158 pthread_mutex_unlock(&finish_mutex);
160 mctx->games = played_games;
161 return mctx;
165 /*** THREAD MANAGER end */
167 /*** Search infrastructure: */
171 uct_search_games(struct uct_search_state *s)
173 return s->ctx->t->root->u.playouts;
176 void
177 uct_search_start(struct uct *u, struct board *b, enum stone color,
178 struct tree *t, struct time_info *ti,
179 struct uct_search_state *s)
181 /* Set up search state. */
182 s->base_playouts = s->last_dynkomi = s->last_print = t->root->u.playouts;
183 s->print_interval = TREE_SIMPROGRESS_INTERVAL * u->threads;
184 s->fullmem = false;
186 if (ti) {
187 if (ti->period == TT_NULL) *ti = default_ti;
188 time_stop_conditions(ti, b, u->fuseki_end, u->yose_start, &s->stop);
191 /* Fire up the tree search thread manager, which will in turn
192 * spawn the searching threads. */
193 assert(u->threads > 0);
194 assert(!thread_manager_running);
195 static struct uct_thread_ctx mctx;
196 mctx = (struct uct_thread_ctx) { .u = u, .b = b, .color = color, .t = t, .seed = fast_random(65536) };
197 s->ctx = &mctx;
198 pthread_mutex_lock(&finish_mutex);
199 pthread_create(&thread_manager, NULL, spawn_thread_manager, s->ctx);
200 thread_manager_running = true;
203 struct uct_thread_ctx *
204 uct_search_stop(void)
206 assert(thread_manager_running);
208 /* Signal thread manager to stop the workers. */
209 pthread_mutex_lock(&finish_mutex);
210 finish_thread = -1;
211 pthread_cond_signal(&finish_cond);
212 pthread_mutex_unlock(&finish_mutex);
214 /* Collect the thread manager. */
215 struct uct_thread_ctx *pctx;
216 thread_manager_running = false;
217 pthread_join(thread_manager, (void **) &pctx);
218 return pctx;
222 void
223 uct_search_progress(struct uct *u, struct board *b, enum stone color,
224 struct tree *t, struct time_info *ti,
225 struct uct_search_state *s, int i)
227 struct uct_thread_ctx *ctx = s->ctx;
229 /* Adjust dynkomi? */
230 int di = u->dynkomi_interval * u->threads;
231 if (ctx->t->use_extra_komi && u->dynkomi->permove
232 && !u->pondering && di
233 && i > s->last_dynkomi + di) {
234 s->last_dynkomi += di;
235 float old_dynkomi = ctx->t->extra_komi;
236 ctx->t->extra_komi = u->dynkomi->permove(u->dynkomi, b, ctx->t);
237 if (UDEBUGL(3) && old_dynkomi != ctx->t->extra_komi)
238 fprintf(stderr, "dynkomi adjusted (%f -> %f)\n",
239 old_dynkomi, ctx->t->extra_komi);
242 /* Print progress? */
243 if (i - s->last_print > s->print_interval) {
244 s->last_print += s->print_interval; // keep the numbers tidy
245 uct_progress_status(u, ctx->t, color, s->last_print);
248 if (!s->fullmem && ctx->t->nodes_size > u->max_tree_size) {
249 if (UDEBUGL(2))
250 fprintf(stderr, "memory limit hit (%lu > %lu)\n",
251 ctx->t->nodes_size, u->max_tree_size);
252 s->fullmem = true;
257 /* Determine whether we should terminate the search early. */
258 static bool
259 uct_search_stop_early(struct uct *u, struct tree *t, struct board *b,
260 struct time_info *ti, struct time_stop *stop,
261 struct tree_node *best, struct tree_node *best2,
262 int played, bool fullmem)
264 /* If the memory is full, stop immediately. Since the tree
265 * cannot grow anymore, some non-well-expanded nodes will
266 * quickly take over with extremely high ratio since the
267 * counters are not properly simulated (just as if we use
268 * non-UCT MonteCarlo). */
269 /* (XXX: A proper solution would be to prune the tree
270 * on the spot.) */
271 if (fullmem)
272 return true;
274 /* Think at least 100ms to avoid a random move. This is particularly
275 * important in distributed mode, where this function is called frequently. */
276 double elapsed = 0.0;
277 if (ti->dim == TD_WALLTIME) {
278 elapsed = time_now() - ti->len.t.timer_start;
279 if (elapsed < TREE_BUSYWAIT_INTERVAL) return false;
282 /* Break early if we estimate the second-best move cannot
283 * catch up in assigned time anymore. We use all our time
284 * if we are in byoyomi with single stone remaining in our
285 * period, however - it's better to pre-ponder. */
286 bool time_indulgent = (!ti->len.t.main_time && ti->len.t.byoyomi_stones == 1);
287 if (best2 && ti->dim == TD_WALLTIME && !time_indulgent) {
288 double remaining = stop->worst.time - elapsed;
289 double pps = ((double)played) / elapsed;
290 double estplayouts = remaining * pps + PLAYOUT_DELTA_SAFEMARGIN;
291 if (best->u.playouts > best2->u.playouts + estplayouts) {
292 if (UDEBUGL(2))
293 fprintf(stderr, "Early stop, result cannot change: "
294 "best %d, best2 %d, estimated %f simulations to go\n",
295 best->u.playouts, best2->u.playouts, estplayouts);
296 return true;
300 /* Early break in won situation. */
301 if (best->u.playouts >= PLAYOUT_EARLY_BREAK_MIN
302 && tree_node_get_value(t, 1, best->u.value) >= u->sure_win_threshold) {
303 return true;
306 return false;
309 /* Determine whether we should terminate the search later than expected. */
310 static bool
311 uct_search_keep_looking(struct uct *u, struct tree *t, struct board *b,
312 struct time_info *ti, struct time_stop *stop,
313 struct tree_node *best, struct tree_node *best2,
314 struct tree_node *bestr, struct tree_node *winner, int i)
316 if (!best) {
317 if (UDEBUGL(2))
318 fprintf(stderr, "Did not find best move, still trying...\n");
319 return true;
322 /* Do not waste time if we are winning. Spend up to worst time if
323 * we are unsure, but only desired time if we are sure of winning. */
324 float beta = 2 * (tree_node_get_value(t, 1, best->u.value) - 0.5);
325 if (ti->dim == TD_WALLTIME && beta > 0) {
326 double good_enough = stop->desired.time * beta + stop->worst.time * (1 - beta);
327 double elapsed = time_now() - ti->len.t.timer_start;
328 if (elapsed > good_enough) return false;
331 if (u->best2_ratio > 0) {
332 /* Check best/best2 simulations ratio. If the
333 * two best moves give very similar results,
334 * keep simulating. */
335 if (best2 && best2->u.playouts
336 && (double)best->u.playouts / best2->u.playouts < u->best2_ratio) {
337 if (UDEBUGL(2))
338 fprintf(stderr, "Best2 ratio %f < threshold %f\n",
339 (double)best->u.playouts / best2->u.playouts,
340 u->best2_ratio);
341 return true;
345 if (u->bestr_ratio > 0) {
346 /* Check best, best_best value difference. If the best move
347 * and its best child do not give similar enough results,
348 * keep simulating. */
349 if (bestr && bestr->u.playouts
350 && fabs((double)best->u.value - bestr->u.value) > u->bestr_ratio) {
351 if (UDEBUGL(2))
352 fprintf(stderr, "Bestr delta %f > threshold %f\n",
353 fabs((double)best->u.value - bestr->u.value),
354 u->bestr_ratio);
355 return true;
359 if (winner && winner != best) {
360 /* Keep simulating if best explored
361 * does not have also highest value. */
362 if (UDEBUGL(2))
363 fprintf(stderr, "[%d] best %3s [%d] %f != winner %3s [%d] %f\n", i,
364 coord2sstr(best->coord, t->board),
365 best->u.playouts, tree_node_get_value(t, 1, best->u.value),
366 coord2sstr(winner->coord, t->board),
367 winner->u.playouts, tree_node_get_value(t, 1, winner->u.value));
368 return true;
371 /* No reason to keep simulating, bye. */
372 return false;
375 bool
376 uct_search_check_stop(struct uct *u, struct board *b, enum stone color,
377 struct tree *t, struct time_info *ti,
378 struct uct_search_state *s, int i)
380 struct uct_thread_ctx *ctx = s->ctx;
382 /* Never consider stopping if we played too few simulations.
383 * Maybe we risk losing on time when playing in super-extreme
384 * time pressure but the tree is going to be just too messed
385 * up otherwise - we might even play invalid suicides or pass
386 * when we mustn't. */
387 if (i < GJ_MINGAMES)
388 return false;
390 struct tree_node *best = NULL;
391 struct tree_node *best2 = NULL; // Second-best move.
392 struct tree_node *bestr = NULL; // best's best child.
393 struct tree_node *winner = NULL;
395 best = u->policy->choose(u->policy, ctx->t->root, b, color, resign);
396 if (best) best2 = u->policy->choose(u->policy, ctx->t->root, b, color, best->coord);
398 /* Possibly stop search early if it's no use to try on. */
399 int played = u->played_all + i - s->base_playouts;
400 if (best && uct_search_stop_early(u, ctx->t, b, ti, &s->stop, best, best2, played, s->fullmem))
401 return true;
403 /* Check against time settings. */
404 bool desired_done;
405 if (ti->dim == TD_WALLTIME) {
406 double elapsed = time_now() - ti->len.t.timer_start;
407 if (elapsed > s->stop.worst.time) return true;
408 desired_done = elapsed > s->stop.desired.time;
410 } else { assert(ti->dim == TD_GAMES);
411 if (i > s->stop.worst.playouts) return true;
412 desired_done = i > s->stop.desired.playouts;
415 /* We want to stop simulating, but are willing to keep trying
416 * if we aren't completely sure about the winner yet. */
417 if (desired_done) {
418 if (u->policy->winner && u->policy->evaluate) {
419 struct uct_descent descent = { .node = ctx->t->root };
420 u->policy->winner(u->policy, ctx->t, &descent);
421 winner = descent.node;
423 if (best)
424 bestr = u->policy->choose(u->policy, best, b, stone_other(color), resign);
425 if (!uct_search_keep_looking(u, ctx->t, b, ti, &s->stop, best, best2, bestr, winner, i))
426 return true;
429 /* TODO: Early break if best->variance goes under threshold
430 * and we already have enough playouts (possibly thanks to tbook
431 * or to pondering)? */
432 return false;
436 struct tree_node *
437 uct_search_result(struct uct *u, struct board *b, enum stone color,
438 bool pass_all_alive, int played_games, int base_playouts,
439 coord_t *best_coord)
441 /* Choose the best move from the tree. */
442 struct tree_node *best = u->policy->choose(u->policy, u->t->root, b, color, resign);
443 if (!best) {
444 *best_coord = pass;
445 return NULL;
447 *best_coord = best->coord;
448 if (UDEBUGL(1))
449 fprintf(stderr, "*** WINNER is %s (%d,%d) with score %1.4f (%d/%d:%d/%d games), extra komi %f\n",
450 coord2sstr(best->coord, b), coord_x(best->coord, b), coord_y(best->coord, b),
451 tree_node_get_value(u->t, 1, best->u.value), best->u.playouts,
452 u->t->root->u.playouts, u->t->root->u.playouts - base_playouts, played_games,
453 u->t->extra_komi);
455 /* Do not resign if we're so short of time that evaluation of best
456 * move is completely unreliable, we might be winning actually.
457 * In this case best is almost random but still better than resign.
458 * Also do not resign if we are getting bad results while actually
459 * giving away extra komi points (dynkomi). */
460 if (tree_node_get_value(u->t, 1, best->u.value) < u->resign_threshold
461 && !is_pass(best->coord) && best->u.playouts > GJ_MINGAMES
462 && (!u->t->use_extra_komi || komi_by_color(u->t->extra_komi, color) < 0.5)) {
463 *best_coord = resign;
464 return NULL;
467 /* If the opponent just passed and we win counting, always
468 * pass as well. */
469 if (b->moves > 1 && is_pass(b->last_move.coord)) {
470 /* Make sure enough playouts are simulated. */
471 while (u->ownermap.playouts < GJ_MINGAMES)
472 uct_playout(u, b, color, u->t);
473 if (uct_pass_is_safe(u, b, color, u->pass_all_alive || pass_all_alive)) {
474 if (UDEBUGL(0))
475 fprintf(stderr, "<Will rather pass, looks safe enough; score %f>\n",
476 board_official_score(b, NULL) / 2);
477 *best_coord = pass;
478 best = u->t->root->children; // pass is the first child
479 assert(is_pass(best->coord));
480 return best;
484 return best;