Merge branch 'master' into win2
[pachi/nmclean.git] / uct / search.c
blobc66cc160e7bb9948d9b57b0b0900ed0cefcbfdcd
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
45 /* Minimal time to consider early break (in seconds). */
46 #define TIME_EARLY_BREAK_MIN 1.0
49 /* Pachi threading structure:
51 * main thread
52 * | main(), GTP communication, ...
53 * | starts and stops the search managed by thread_manager
54 * |
55 * thread_manager
56 * | spawns and collects worker threads
57 * |
58 * worker0
59 * worker1
60 * ...
61 * workerK
62 * uct_playouts() loop, doing descend-playout until uct_halt
64 * Another way to look at it is by functions (lines denote thread boundaries):
66 * | uct_genmove()
67 * | uct_search() (uct_search_start() .. uct_search_stop())
68 * | -----------------------
69 * | spawn_thread_manager()
70 * | -----------------------
71 * | spawn_worker()
72 * V uct_playouts() */
74 /* Set in thread manager in case the workers should stop. */
75 volatile sig_atomic_t uct_halt = 0;
76 /* ID of the thread manager. */
77 static pthread_t thread_manager;
78 bool thread_manager_running;
80 static pthread_mutex_t finish_mutex = PTHREAD_MUTEX_INITIALIZER;
81 static pthread_cond_t finish_cond = PTHREAD_COND_INITIALIZER;
82 static volatile int finish_thread;
83 static pthread_mutex_t finish_serializer = PTHREAD_MUTEX_INITIALIZER;
85 static void *
86 spawn_worker(void *ctx_)
88 struct uct_thread_ctx *ctx = ctx_;
89 /* Setup */
90 fast_srandom(ctx->seed);
91 /* Run */
92 ctx->games = uct_playouts(ctx->u, ctx->b, ctx->color, ctx->t, ctx->ti);
93 /* Finish */
94 pthread_mutex_lock(&finish_serializer);
95 pthread_mutex_lock(&finish_mutex);
96 finish_thread = ctx->tid;
97 pthread_cond_signal(&finish_cond);
98 pthread_mutex_unlock(&finish_mutex);
99 return ctx;
102 /* Thread manager, controlling worker threads. It must be called with
103 * finish_mutex lock held, but it will unlock it itself before exiting;
104 * this is necessary to be completely deadlock-free. */
105 /* The finish_cond can be signalled for it to stop; in that case,
106 * the caller should set finish_thread = -1. */
107 /* After it is started, it will update mctx->t to point at some tree
108 * used for the actual search, on return
109 * it will set mctx->games to the number of performed simulations. */
110 static void *
111 spawn_thread_manager(void *ctx_)
113 /* In thread_manager, we use only some of the ctx fields. */
114 struct uct_thread_ctx *mctx = ctx_;
115 struct uct *u = mctx->u;
116 struct tree *t = mctx->t;
117 fast_srandom(mctx->seed);
119 int played_games = 0;
120 pthread_t threads[u->threads];
121 int joined = 0;
123 uct_halt = 0;
125 /* Garbage collect the tree by preference when pondering. */
126 if (u->pondering && t->nodes && t->nodes_size >= t->pruning_threshold) {
127 t->root = tree_garbage_collect(t, t->root);
130 /* Spawn threads... */
131 for (int ti = 0; ti < u->threads; ti++) {
132 struct uct_thread_ctx *ctx = malloc2(sizeof(*ctx));
133 ctx->u = u; ctx->b = mctx->b; ctx->color = mctx->color;
134 mctx->t = ctx->t = t;
135 ctx->tid = ti; ctx->seed = fast_random(65536) + ti;
136 ctx->ti = mctx->ti;
137 pthread_create(&threads[ti], NULL, spawn_worker, ctx);
138 if (UDEBUGL(3))
139 fprintf(stderr, "Spawned worker %d\n", ti);
142 /* ...and collect them back: */
143 while (joined < u->threads) {
144 /* Wait for some thread to finish... */
145 pthread_cond_wait(&finish_cond, &finish_mutex);
146 if (finish_thread < 0) {
147 /* Stop-by-caller. Tell the workers to wrap up
148 * and unblock them from terminating. */
149 uct_halt = 1;
150 /* We need to make sure the workers do not complete
151 * the termination sequence before we get officially
152 * stopped - their wake and the stop wake could get
153 * coalesced. */
154 pthread_mutex_unlock(&finish_serializer);
155 continue;
157 /* ...and gather its remnants. */
158 struct uct_thread_ctx *ctx;
159 pthread_join(threads[finish_thread], (void **) &ctx);
160 played_games += ctx->games;
161 joined++;
162 free(ctx);
163 if (UDEBUGL(3))
164 fprintf(stderr, "Joined worker %d\n", finish_thread);
165 pthread_mutex_unlock(&finish_serializer);
168 pthread_mutex_unlock(&finish_mutex);
170 mctx->games = played_games;
171 return mctx;
175 /*** THREAD MANAGER end */
177 /*** Search infrastructure: */
181 uct_search_games(struct uct_search_state *s)
183 return s->ctx->t->root->u.playouts;
186 void
187 uct_search_start(struct uct *u, struct board *b, enum stone color,
188 struct tree *t, struct time_info *ti,
189 struct uct_search_state *s)
191 /* Set up search state. */
192 s->base_playouts = s->last_dynkomi = s->last_print = t->root->u.playouts;
193 s->print_interval = TREE_SIMPROGRESS_INTERVAL * u->threads;
194 s->fullmem = false;
196 if (ti) {
197 if (ti->period == TT_NULL) *ti = default_ti;
198 time_stop_conditions(ti, b, u->fuseki_end, u->yose_start, u->max_maintime_ratio, &s->stop);
201 /* Fire up the tree search thread manager, which will in turn
202 * spawn the searching threads. */
203 assert(u->threads > 0);
204 assert(!thread_manager_running);
205 static struct uct_thread_ctx mctx;
206 mctx = (struct uct_thread_ctx) { .u = u, .b = b, .color = color, .t = t, .seed = fast_random(65536), .ti = ti };
207 s->ctx = &mctx;
208 pthread_mutex_lock(&finish_serializer);
209 pthread_mutex_lock(&finish_mutex);
210 pthread_create(&thread_manager, NULL, spawn_thread_manager, s->ctx);
211 thread_manager_running = true;
214 struct uct_thread_ctx *
215 uct_search_stop(void)
217 assert(thread_manager_running);
219 /* Signal thread manager to stop the workers. */
220 pthread_mutex_lock(&finish_mutex);
221 finish_thread = -1;
222 pthread_cond_signal(&finish_cond);
223 pthread_mutex_unlock(&finish_mutex);
225 /* Collect the thread manager. */
226 struct uct_thread_ctx *pctx;
227 thread_manager_running = false;
228 pthread_join(thread_manager, (void **) &pctx);
229 return pctx;
233 void
234 uct_search_progress(struct uct *u, struct board *b, enum stone color,
235 struct tree *t, struct time_info *ti,
236 struct uct_search_state *s, int i)
238 struct uct_thread_ctx *ctx = s->ctx;
240 /* Adjust dynkomi? */
241 int di = u->dynkomi_interval * u->threads;
242 if (ctx->t->use_extra_komi && u->dynkomi->permove
243 && !u->pondering && di
244 && i > s->last_dynkomi + di) {
245 s->last_dynkomi += di;
246 floating_t old_dynkomi = ctx->t->extra_komi;
247 ctx->t->extra_komi = u->dynkomi->permove(u->dynkomi, b, ctx->t);
248 if (UDEBUGL(3) && old_dynkomi != ctx->t->extra_komi)
249 fprintf(stderr, "dynkomi adjusted (%f -> %f)\n",
250 old_dynkomi, ctx->t->extra_komi);
253 /* Print progress? */
254 if (i - s->last_print > s->print_interval) {
255 s->last_print += s->print_interval; // keep the numbers tidy
256 uct_progress_status(u, ctx->t, color, s->last_print);
259 if (!s->fullmem && ctx->t->nodes_size > u->max_tree_size) {
260 if (UDEBUGL(2))
261 fprintf(stderr, "memory limit hit (%lu > %lu)\n",
262 ctx->t->nodes_size, u->max_tree_size);
263 s->fullmem = true;
268 /* Determine whether we should terminate the search early. */
269 static bool
270 uct_search_stop_early(struct uct *u, struct tree *t, struct board *b,
271 struct time_info *ti, struct time_stop *stop,
272 struct tree_node *best, struct tree_node *best2,
273 int played, bool fullmem)
275 /* If the memory is full, stop immediately. Since the tree
276 * cannot grow anymore, some non-well-expanded nodes will
277 * quickly take over with extremely high ratio since the
278 * counters are not properly simulated (just as if we use
279 * non-UCT MonteCarlo). */
280 /* (XXX: A proper solution would be to prune the tree
281 * on the spot.) */
282 if (fullmem)
283 return true;
285 /* Think at least 100ms to avoid a random move. This is particularly
286 * important in distributed mode, where this function is called frequently. */
287 double elapsed = 0.0;
288 if (ti->dim == TD_WALLTIME) {
289 elapsed = time_now() - ti->len.t.timer_start;
290 if (elapsed < TREE_BUSYWAIT_INTERVAL) return false;
293 /* Break early if we estimate the second-best move cannot
294 * catch up in assigned time anymore. We use all our time
295 * if we are in byoyomi with single stone remaining in our
296 * period, however - it's better to pre-ponder. */
297 bool time_indulgent = (!ti->len.t.main_time && ti->len.t.byoyomi_stones == 1);
298 if (best2 && ti->dim == TD_WALLTIME
299 && played >= PLAYOUT_EARLY_BREAK_MIN && !time_indulgent) {
300 double remaining = stop->worst.time - elapsed;
301 double pps = ((double)played) / elapsed;
302 double estplayouts = remaining * pps + PLAYOUT_DELTA_SAFEMARGIN;
303 if (best->u.playouts > best2->u.playouts + estplayouts) {
304 if (UDEBUGL(2))
305 fprintf(stderr, "Early stop, result cannot change: "
306 "best %d, best2 %d, estimated %f simulations to go (%d/%f=%f pps)\n",
307 best->u.playouts, best2->u.playouts, estplayouts, played, elapsed, pps);
308 return true;
312 /* Early break in won situation. */
313 if (best->u.playouts >= PLAYOUT_EARLY_BREAK_MIN
314 && (ti->dim != TD_WALLTIME || elapsed > TIME_EARLY_BREAK_MIN)
315 && tree_node_get_value(t, 1, best->u.value) >= u->sure_win_threshold) {
316 return true;
319 return false;
322 /* Determine whether we should terminate the search later than expected. */
323 static bool
324 uct_search_keep_looking(struct uct *u, struct tree *t, struct board *b,
325 struct time_info *ti, struct time_stop *stop,
326 struct tree_node *best, struct tree_node *best2,
327 struct tree_node *bestr, struct tree_node *winner, int i)
329 if (!best) {
330 if (UDEBUGL(2))
331 fprintf(stderr, "Did not find best move, still trying...\n");
332 return true;
335 /* Do not waste time if we are winning. Spend up to worst time if
336 * we are unsure, but only desired time if we are sure of winning. */
337 floating_t beta = 2 * (tree_node_get_value(t, 1, best->u.value) - 0.5);
338 if (ti->dim == TD_WALLTIME && beta > 0) {
339 double good_enough = stop->desired.time * beta + stop->worst.time * (1 - beta);
340 double elapsed = time_now() - ti->len.t.timer_start;
341 if (elapsed > good_enough) return false;
344 if (u->best2_ratio > 0) {
345 /* Check best/best2 simulations ratio. If the
346 * two best moves give very similar results,
347 * keep simulating. */
348 if (best2 && best2->u.playouts
349 && (double)best->u.playouts / best2->u.playouts < u->best2_ratio) {
350 if (UDEBUGL(2))
351 fprintf(stderr, "Best2 ratio %f < threshold %f\n",
352 (double)best->u.playouts / best2->u.playouts,
353 u->best2_ratio);
354 return true;
358 if (u->bestr_ratio > 0) {
359 /* Check best, best_best value difference. If the best move
360 * and its best child do not give similar enough results,
361 * keep simulating. */
362 if (bestr && bestr->u.playouts
363 && fabs((double)best->u.value - bestr->u.value) > u->bestr_ratio) {
364 if (UDEBUGL(2))
365 fprintf(stderr, "Bestr delta %f > threshold %f\n",
366 fabs((double)best->u.value - bestr->u.value),
367 u->bestr_ratio);
368 return true;
372 if (winner && winner != best) {
373 /* Keep simulating if best explored
374 * does not have also highest value. */
375 if (UDEBUGL(2))
376 fprintf(stderr, "[%d] best %3s [%d] %f != winner %3s [%d] %f\n", i,
377 coord2sstr(node_coord(best), t->board),
378 best->u.playouts, tree_node_get_value(t, 1, best->u.value),
379 coord2sstr(node_coord(winner), t->board),
380 winner->u.playouts, tree_node_get_value(t, 1, winner->u.value));
381 return true;
384 /* No reason to keep simulating, bye. */
385 return false;
388 bool
389 uct_search_check_stop(struct uct *u, struct board *b, enum stone color,
390 struct tree *t, struct time_info *ti,
391 struct uct_search_state *s, int i)
393 struct uct_thread_ctx *ctx = s->ctx;
395 /* Never consider stopping if we played too few simulations.
396 * Maybe we risk losing on time when playing in super-extreme
397 * time pressure but the tree is going to be just too messed
398 * up otherwise - we might even play invalid suicides or pass
399 * when we mustn't. */
400 assert(!(ti->dim == TD_GAMES && ti->len.games < GJ_MINGAMES));
401 if (i < GJ_MINGAMES)
402 return false;
404 struct tree_node *best = NULL;
405 struct tree_node *best2 = NULL; // Second-best move.
406 struct tree_node *bestr = NULL; // best's best child.
407 struct tree_node *winner = NULL;
409 best = u->policy->choose(u->policy, ctx->t->root, b, color, resign);
410 if (best) best2 = u->policy->choose(u->policy, ctx->t->root, b, color, node_coord(best));
412 /* Possibly stop search early if it's no use to try on. */
413 int played = u->played_all + i - s->base_playouts;
414 if (best && uct_search_stop_early(u, ctx->t, b, ti, &s->stop, best, best2, played, s->fullmem))
415 return true;
417 /* Check against time settings. */
418 bool desired_done;
419 if (ti->dim == TD_WALLTIME) {
420 double elapsed = time_now() - ti->len.t.timer_start;
421 if (elapsed > s->stop.worst.time) return true;
422 desired_done = elapsed > s->stop.desired.time;
424 } else { assert(ti->dim == TD_GAMES);
425 if (i > s->stop.worst.playouts) return true;
426 desired_done = i > s->stop.desired.playouts;
429 /* We want to stop simulating, but are willing to keep trying
430 * if we aren't completely sure about the winner yet. */
431 if (desired_done) {
432 if (u->policy->winner && u->policy->evaluate) {
433 struct uct_descent descent = { .node = ctx->t->root };
434 u->policy->winner(u->policy, ctx->t, &descent);
435 winner = descent.node;
437 if (best)
438 bestr = u->policy->choose(u->policy, best, b, stone_other(color), resign);
439 if (!uct_search_keep_looking(u, ctx->t, b, ti, &s->stop, best, best2, bestr, winner, i))
440 return true;
443 /* TODO: Early break if best->variance goes under threshold
444 * and we already have enough playouts (possibly thanks to tbook
445 * or to pondering)? */
446 return false;
450 struct tree_node *
451 uct_search_result(struct uct *u, struct board *b, enum stone color,
452 bool pass_all_alive, int played_games, int base_playouts,
453 coord_t *best_coord)
455 /* Choose the best move from the tree. */
456 struct tree_node *best = u->policy->choose(u->policy, u->t->root, b, color, resign);
457 if (!best) {
458 *best_coord = pass;
459 return NULL;
461 *best_coord = node_coord(best);
462 if (UDEBUGL(1))
463 fprintf(stderr, "*** WINNER is %s (%d,%d) with score %1.4f (%d/%d:%d/%d games), extra komi %f\n",
464 coord2sstr(node_coord(best), b), coord_x(node_coord(best), b), coord_y(node_coord(best), b),
465 tree_node_get_value(u->t, 1, best->u.value), best->u.playouts,
466 u->t->root->u.playouts, u->t->root->u.playouts - base_playouts, played_games,
467 u->t->extra_komi);
469 /* Do not resign if we're so short of time that evaluation of best
470 * move is completely unreliable, we might be winning actually.
471 * In this case best is almost random but still better than resign.
472 * Also do not resign if we are getting bad results while actually
473 * giving away extra komi points (dynkomi). */
474 if (tree_node_get_value(u->t, 1, best->u.value) < u->resign_threshold
475 && !is_pass(node_coord(best)) && best->u.playouts > GJ_MINGAMES
476 && (!u->t->use_extra_komi || komi_by_color(u->t->extra_komi, color) < 0.5)) {
477 *best_coord = resign;
478 return NULL;
481 /* If the opponent just passed and we win counting, always
482 * pass as well. For option stones_only, we pass only when there
483 * there is nothing else to do, to show how to maximize score. */
484 if (b->moves > 1 && is_pass(b->last_move.coord) && b->rules != RULES_STONES_ONLY
485 && uct_pass_is_safe(u, b, color, pass_all_alive)) {
486 if (UDEBUGL(0))
487 fprintf(stderr, "<Will rather pass, looks safe enough; score %f>\n",
488 board_official_score(b, NULL) / 2);
489 *best_coord = pass;
490 best = u->t->root->children; // pass is the first child
491 assert(is_pass(node_coord(best)));
492 return best;
495 return best;