More notes on the possible min/max method.
[pachi/pachi-r6144.git] / distributed / distributed.c
blobbcb528ad5683c82c6074f541c133cee38fffb3db
1 /* This is a master for the "distributed" engine. It receives connections
2 * from slave machines, sends them gtp commands, then aggregates the
3 * results. It can also act as a proxy for the logs of all slave machines.
4 * The slave machines must run with engine "uct" (not "distributed").
5 * The master sends pachi-genmoves gtp commands regularly to each slave,
6 * gets as replies a list of nodes, their number of playouts
7 * and their value. The master then picks the most popular move
8 * among the top level nodes. */
10 /* With time control, the master waits for all slaves, except
11 * when the allowed time is already passed. In this case the
12 * master picks among the available replies, or waits for just
13 * one reply if there is none yet.
14 * Without time control, the master waits until the desired
15 * number of games have been simulated. In this case the -t
16 * parameter for the master should be the sum of the parameters
17 * for all slaves. */
19 /* The master sends updated statistics for the best nodes in each
20 * genmoves command. They are incremental updates from all other
21 * slaves (so they exclude contributions from the target slave).
22 * The slaves reply with just their own stats. So both master and
23 * slave remember what was previously sent. A slave remembers in
24 * the tree ("pu" field), which is stable across moves. The slave
25 * also has a temporary hash table to map received coord paths
26 * to tree nodes; the hash table is cleared at each new move.
27 * The master remembers stats in a queue of received buffers that
28 * are merged together, plus one hash table per slave. The master
29 * queue and the hash tables are cleared at each new move. */
31 /* To allow the master to select the best move, slaves also send
32 * absolute playout counts for the best top level nodes (children
33 * of the root node), including contributions from other slaves.
34 * The master sums these counts and picks the best sum, which is
35 * equivalent to picking the best average. (The master cannot
36 * use the incremental stats sent in binary form because they
37 * are not maintained across moves, so playouts from previous
38 * moves would be lost.) */
40 /* The master-slave protocol has fault tolerance. If a slave is
41 * out of sync, the master sends it the appropriate command history. */
43 /* Pass me arguments like a=b,c=d,...
44 * Supported arguments:
45 * slave_port=SLAVE_PORT slaves connect to this port; this parameter is mandatory.
46 * max_slaves=MAX_SLAVES default 24
47 * shared_nodes=SHARED_NODES default 10K
48 * stats_hbits=STATS_HBITS default 21. 2^stats_bits = hash table size
49 * slaves_quit=0|1 quit gtp command also sent to slaves, default false.
50 * proxy_port=PROXY_PORT slaves optionally send their logs to this port.
51 * Warning: with proxy_port, the master stderr mixes the logs of all
52 * machines but you can separate them again:
53 * slave logs: sed -n '/< .*:/s/.*< /< /p' logfile
54 * master logs: perl -0777 -pe 's/<[ <].*:.*\n//g' logfile
57 /* A configuration without proxy would have one master run on masterhost as:
58 * pachi -e distributed slave_port=1234
59 * and N slaves running as:
60 * pachi -e uct -g masterhost:1234 slave
61 * With log proxy:
62 * pachi -e distributed slave_port=1234,proxy_port=1235
63 * pachi -e uct -g masterhost:1234 -l masterhost:1235 slave
64 * If the master itself runs on a machine other than that running gogui,
65 * gogui-twogtp, kgsGtp or cgosGtp, it can redirect its gtp port:
66 * pachi -e distributed -g 10000 slave_port=1234,proxy_port=1235
69 #include <assert.h>
70 #include <stdio.h>
71 #include <stdlib.h>
72 #include <string.h>
73 #include <time.h>
74 #include <alloca.h>
75 #include <unistd.h>
76 #include <sys/types.h>
78 #define DEBUG
80 #include "engine.h"
81 #include "move.h"
82 #include "timeinfo.h"
83 #include "playout.h"
84 #include "stats.h"
85 #include "mq.h"
86 #include "debug.h"
87 #include "distributed/distributed.h"
88 #include "distributed/merge.h"
90 /* Internal engine state. */
91 struct distributed {
92 char *slave_port;
93 char *proxy_port;
94 int max_slaves;
95 int shared_nodes;
96 int stats_hbits;
97 bool slaves_quit;
98 struct move my_last_move;
99 struct move_stats my_last_stats;
102 /* Default number of simulations to perform per move.
103 * Note that this is in total over all slaves! */
104 #define DIST_GAMES 80000
105 static const struct time_info default_ti = {
106 .period = TT_MOVE,
107 .dim = TD_GAMES,
108 .len = { .games = DIST_GAMES },
111 #define get_value(value, color) \
112 ((color) == S_BLACK ? (value) : 1 - (value))
115 /* Maximum time (seconds) to wait for answers to fast gtp commands
116 * (all commands except pachi-genmoves and final_status_list). */
117 #define MAX_FAST_CMD_WAIT 0.5
119 /* Maximum time (seconds) to wait for answers to genmoves. */
120 #define MAX_GENMOVES_WAIT 0.1 /* 100 ms */
122 /* Minimum time (seconds) to wait before we stop early. This should
123 * ensure that most slaves have replied at least once. */
124 #define MIN_EARLY_STOP_WAIT 0.3 /* 300 ms */
126 /* Display a path as leaf<parent<grandparent...
127 * Returns the path string in a static buffer; it is NOT safe for
128 * anything but debugging - in particular, it is NOT thread-safe! */
129 char *
130 path2sstr(path_t path, struct board *b)
132 /* Special case for pass and resign. */
133 if (path < 0) return coord2sstr((coord_t)path, b);
135 static char buf[16][64];
136 static int bi = 0;
137 char *b2;
138 b2 = buf[bi++ & 15];
139 *b2 = '\0';
140 char *s = b2;
141 char *end = b2 + 64;
142 coord_t leaf;
143 while ((leaf = leaf_coord(path, b)) != 0) {
144 s += snprintf(s, end - s, "%s<", coord2sstr(leaf, b));
145 path = parent_path(path, b);
147 if (s != b2) s[-1] = '\0';
148 return b2;
151 /* Dispatch a new gtp command to all slaves.
152 * The slave lock must not be held upon entry and is released upon return.
153 * args is empty or ends with '\n' */
154 static enum parse_code
155 distributed_notify(struct engine *e, struct board *b, int id, char *cmd, char *args, char **reply)
157 struct distributed *dist = e->data;
159 /* Commands that should not be sent to slaves.
160 * time_left will be part of next pachi-genmoves,
161 * we reduce latency by not forwarding it here. */
162 if ((!strcasecmp(cmd, "quit") && !dist->slaves_quit)
163 || !strcasecmp(cmd, "uct_gentbook")
164 || !strcasecmp(cmd, "uct_dumptbook")
165 || !strcasecmp(cmd, "kgs-chat")
166 || !strcasecmp(cmd, "time_left")
168 /* and commands that will be sent to slaves later */
169 || !strcasecmp(cmd, "genmove")
170 || !strcasecmp(cmd, "kgs-genmove_cleanup")
171 || !strcasecmp(cmd, "final_score")
172 || !strcasecmp(cmd, "final_status_list"))
173 return P_OK;
175 protocol_lock();
177 // Create a new command to be sent by the slave threads.
178 new_cmd(b, cmd, args);
180 /* Wait for replies here. If we don't wait, we run the
181 * risk of getting out of sync with most slaves and
182 * sending command history too frequently. But don't wait
183 * for all slaves otherwise we can lose on time because of
184 * a single slow slave when replaying a whole game. */
185 int min_slaves = active_slaves > 1 ? 3 * active_slaves / 4 : 1;
186 get_replies(time_now() + MAX_FAST_CMD_WAIT, min_slaves);
188 protocol_unlock();
190 // At the beginning wait even more for late slaves.
191 if (b->moves == 0) sleep(1);
192 return P_OK;
195 /* The playouts sent by slaves for the children of the root node
196 * include contributions from other slaves. To avoid 32-bit overflow on
197 * large configurations with many slaves we must average the playouts. */
198 struct large_stats {
199 long playouts; // # of playouts
200 floating_t value; // BLACK wins/playouts
203 static void
204 large_stats_add_result(struct large_stats *s, floating_t result, long playouts)
206 s->playouts += playouts;
207 s->value += (result - s->value) * playouts / s->playouts;
210 /* genmoves returns "=id played_own total_playouts threads keep_looking @size"
211 * then a list of lines "coord playouts value" with absolute counts for
212 * children of the root node, then a binary array of incr_stats structs.
213 * To simplify the code, we assume that master and slave have the same architecture
214 * (store values identically).
215 * Return the move with most playouts, and additional stats.
216 * keep_looking is set from a majority vote of the slaves seen so far for this
217 * move but should not be trusted if too few slaves have been seen.
218 * Keep this code in sync with uct/slave.c:report_stats().
219 * slave_lock is held on entry and on return. */
220 static coord_t
221 select_best_move(struct board *b, struct large_stats *stats, int *played,
222 int *total_playouts, int *total_threads, bool *keep_looking)
224 assert(reply_count > 0);
226 /* +2 for pass and resign */
227 memset(stats-2, 0, (board_size2(b)+2) * sizeof(*stats));
229 coord_t best_move = pass;
230 long best_playouts = -1;
231 *played = 0;
232 *total_playouts = 0;
233 *total_threads = 0;
234 int keep = 0;
236 for (int reply = 0; reply < reply_count; reply++) {
237 char *r = gtp_replies[reply];
238 int id, o, p, t, k;
239 if (sscanf(r, "=%d %d %d %d %d", &id, &o, &p, &t, &k) != 5) continue;
240 *played += o;
241 *total_playouts += p;
242 *total_threads += t;
243 keep += k;
244 // Skip the rest of the firt line in particular @size
245 r = strchr(r, '\n');
247 char move[64];
248 struct move_stats s;
249 while (r && sscanf(++r, "%63s %d " PRIfloating, move, &s.playouts, &s.value) == 3) {
250 coord_t c = str2scoord(move, board_size(b));
251 assert (c >= resign && c < board_size2(b) && s.playouts >= 0);
253 large_stats_add_result(&stats[c], s.value, (long)s.playouts);
255 if (stats[c].playouts > best_playouts) {
256 best_playouts = stats[c].playouts;
257 best_move = c;
259 r = strchr(r, '\n');
262 for (coord_t c = resign; c < board_size2(b); c++)
263 stats[c].playouts /= reply_count;
264 *keep_looking = keep > reply_count / 2;
265 return best_move;
268 /* Set the args for the genmoves command. If binary_args is set,
269 * each slave thred will add the correct binary size when sending
270 * (see get_binary_arg()). args must have CMDS_SIZE bytes and
271 * upon return ends with a single \n.
272 * Keep this code in sync with uct/slave.c:uct_genmoves().
273 * slave_lock is held on entry and on return but we don't
274 * rely on the lock here. */
275 static void
276 genmoves_args(char *args, enum stone color, int played,
277 struct time_info *ti, bool binary_args)
279 char *end = args + CMDS_SIZE;
280 char *s = args + snprintf(args, CMDS_SIZE, "%s %d", stone2str(color), played);
282 if (ti->dim == TD_WALLTIME) {
283 s += snprintf(s, end - s, " %.3f %.3f %d %d",
284 ti->len.t.main_time, ti->len.t.byoyomi_time,
285 ti->len.t.byoyomi_periods, ti->len.t.byoyomi_stones);
287 s += snprintf(s, end - s, binary_args ? " @0\n" : "\n");
290 /* Time control is mostly done by the slaves, so we use default values here. */
291 #define FUSEKI_END 20
292 #define YOSE_START 40
293 #define MAX_MAINTIME_RATIO 3.0
295 /* Regularly send genmoves command to the slaves, and select the best move. */
296 static coord_t *
297 distributed_genmove(struct engine *e, struct board *b, struct time_info *ti,
298 enum stone color, bool pass_all_alive)
300 struct distributed *dist = e->data;
301 double now = time_now();
302 double first = now;
303 char buf[BSIZE]; // debug only
305 char *cmd = pass_all_alive ? "pachi-genmoves_cleanup" : "pachi-genmoves";
306 char args[CMDS_SIZE];
308 coord_t best;
309 int played, playouts, threads;
311 if (ti->period == TT_NULL) *ti = default_ti;
312 struct time_stop stop;
313 time_stop_conditions(ti, b, FUSEKI_END, YOSE_START, MAX_MAINTIME_RATIO, &stop);
314 struct time_info saved_ti = *ti;
316 /* Combined move stats from all slaves, only for children
317 * of the root node, plus 2 for pass and resign. */
318 struct large_stats *stats = alloca((board_size2(b)+2) * sizeof(struct large_stats));
319 stats += 2;
321 protocol_lock();
322 clear_receive_queue();
324 /* Send the first genmoves without stats. */
325 genmoves_args(args, color, 0, ti, false);
326 new_cmd(b, cmd, args);
328 /* Loop until most slaves want to quit or time elapsed. */
329 int iterations;
330 for (iterations = 1; ; iterations++) {
331 double start = now;
332 /* Wait for just one slave to get stats as fresh as possible,
333 * or at most 100ms to check if we run out of time. */
334 get_replies(now + MAX_GENMOVES_WAIT, 1);
335 now = time_now();
336 if (ti->dim == TD_WALLTIME)
337 time_sub(ti, now - start, false);
339 bool keep_looking;
340 best = select_best_move(b, stats, &played, &playouts, &threads, &keep_looking);
342 if (ti->dim == TD_WALLTIME) {
343 if (now - ti->len.t.timer_start >= stop.worst.time) break;
344 if (!keep_looking && now - first >= MIN_EARLY_STOP_WAIT) break;
345 } else {
346 if (!keep_looking || played >= stop.worst.playouts) break;
348 if (DEBUGVV(2)) {
349 char *coord = coord2sstr(best, b);
350 snprintf(buf, sizeof(buf),
351 "temp winner is %s %s with score %1.4f (%d/%d games)"
352 " %d slaves %d threads\n",
353 stone2str(color), coord, get_value(stats[best].value, color),
354 (int)stats[best].playouts, playouts, reply_count, threads);
355 logline(NULL, "* ", buf);
357 /* Send the command with the same gtp id, to avoid discarding
358 * a reply to a previous genmoves at the same move. */
359 genmoves_args(args, color, played, ti, true);
360 update_cmd(b, cmd, args, false);
362 int replies = reply_count;
364 /* Do not subtract time spent twice (see gtp_parse). */
365 *ti = saved_ti;
367 dist->my_last_move.color = color;
368 dist->my_last_move.coord = best;
369 dist->my_last_stats.value = stats[best].value;
370 dist->my_last_stats.playouts = (int)stats[best].playouts;
372 /* Tell the slaves to commit to the selected move, overwriting
373 * the last "pachi-genmoves" in the command history. */
374 clear_receive_queue();
375 char coordbuf[4];
376 char *coord = coord2bstr(coordbuf, best, b);
377 snprintf(args, sizeof(args), "%s %s\n", stone2str(color), coord);
378 update_cmd(b, "play", args, true);
379 protocol_unlock();
381 if (DEBUGL(1)) {
382 double time = now - first + 0.000001; /* avoid divide by zero */
383 snprintf(buf, sizeof(buf),
384 "GLOBAL WINNER is %s %s with score %1.4f (%d/%d games)\n"
385 "genmove %d games in %0.2fs %d slaves %d threads (%d games/s,"
386 " %d games/s/slave, %d games/s/thread, %.3f ms/iter)\n",
387 stone2str(color), coord, get_value(stats[best].value, color),
388 (int)stats[best].playouts, playouts, played, time, replies, threads,
389 (int)(played/time), (int)(played/time/replies),
390 (int)(played/time/threads), 1000*time/iterations);
391 logline(NULL, "* ", buf);
393 if (DEBUGL(3)) {
394 int total_hnodes = replies * (1 << dist->stats_hbits);
395 merge_print_stats(total_hnodes);
397 return coord_copy(best);
400 static char *
401 distributed_chat(struct engine *e, struct board *b, char *cmd)
403 struct distributed *dist = e->data;
404 static char reply[BSIZE];
406 cmd += strspn(cmd, " \n\t");
407 if (!strncasecmp(cmd, "winrate", 7)) {
408 enum stone color = dist->my_last_move.color;
409 snprintf(reply, BSIZE, "In %d playouts at %d machines, %s %s can win with %.2f%% probability.",
410 dist->my_last_stats.playouts, active_slaves, stone2str(color),
411 coord2sstr(dist->my_last_move.coord, b),
412 100 * get_value(dist->my_last_stats.value, color));
413 return reply;
415 return NULL;
418 static int
419 scmp(const void *p1, const void *p2)
421 return strcasecmp(*(char * const *)p1, *(char * const *)p2);
424 static void
425 distributed_dead_group_list(struct engine *e, struct board *b, struct move_queue *mq)
427 protocol_lock();
429 new_cmd(b, "final_status_list", "dead\n");
430 get_replies(time_now() + MAX_FAST_CMD_WAIT, active_slaves);
432 /* Find the most popular reply. */
433 qsort(gtp_replies, reply_count, sizeof(char *), scmp);
434 int best_reply = 0;
435 int best_count = 1;
436 int count = 1;
437 for (int reply = 1; reply < reply_count; reply++) {
438 if (!strcmp(gtp_replies[reply], gtp_replies[reply-1])) {
439 count++;
440 } else {
441 count = 1;
443 if (count > best_count) {
444 best_count = count;
445 best_reply = reply;
449 /* Pick the first move of each line as group. */
450 char *dead = gtp_replies[best_reply];
451 dead = strchr(dead, ' '); // skip "id "
452 while (dead && *++dead != '\n') {
453 mq_add(mq, str2scoord(dead, board_size(b)), 0);
454 dead = strchr(dead, '\n');
456 protocol_unlock();
459 static struct distributed *
460 distributed_state_init(char *arg, struct board *b)
462 struct distributed *dist = calloc2(1, sizeof(struct distributed));
464 dist->stats_hbits = DEFAULT_STATS_HBITS;
465 dist->max_slaves = DEFAULT_MAX_SLAVES;
466 dist->shared_nodes = DEFAULT_SHARED_NODES;
467 if (arg) {
468 char *optspec, *next = arg;
469 while (*next) {
470 optspec = next;
471 next += strcspn(next, ",");
472 if (*next) { *next++ = 0; } else { *next = 0; }
474 char *optname = optspec;
475 char *optval = strchr(optspec, '=');
476 if (optval) *optval++ = 0;
478 if (!strcasecmp(optname, "slave_port") && optval) {
479 dist->slave_port = strdup(optval);
480 } else if (!strcasecmp(optname, "proxy_port") && optval) {
481 dist->proxy_port = strdup(optval);
482 } else if (!strcasecmp(optname, "max_slaves") && optval) {
483 dist->max_slaves = atoi(optval);
484 } else if (!strcasecmp(optname, "shared_nodes") && optval) {
485 /* Share at most shared_nodes between master and slave at each genmoves.
486 * Must use the same value in master and slaves. */
487 dist->shared_nodes = atoi(optval);
488 } else if (!strcasecmp(optname, "stats_hbits") && optval) {
489 /* Set hash table size to 2^stats_hbits for the shared stats. */
490 dist->stats_hbits = atoi(optval);
491 } else if (!strcasecmp(optname, "slaves_quit")) {
492 dist->slaves_quit = !optval || atoi(optval);
493 } else {
494 fprintf(stderr, "distributed: Invalid engine argument %s or missing value\n", optname);
499 gtp_replies = calloc2(dist->max_slaves, sizeof(char *));
501 if (!dist->slave_port) {
502 fprintf(stderr, "distributed: missing slave_port\n");
503 exit(1);
506 merge_init(&default_sstate, dist->shared_nodes, dist->stats_hbits, dist->max_slaves);
507 protocol_init(dist->slave_port, dist->proxy_port, dist->max_slaves);
509 return dist;
512 struct engine *
513 engine_distributed_init(char *arg, struct board *b)
515 struct distributed *dist = distributed_state_init(arg, b);
516 struct engine *e = calloc2(1, sizeof(struct engine));
517 e->name = "Distributed Engine";
518 e->comment = "I'm playing the distributed engine. When I'm losing, I will resign, "
519 "if I think I win, I play until you pass. "
520 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
521 e->notify = distributed_notify;
522 e->genmove = distributed_genmove;
523 e->dead_group_list = distributed_dead_group_list;
524 e->chat = distributed_chat;
525 e->data = dist;
526 // Keep the threads and the open socket connections:
527 e->keep_on_clear = true;
529 return e;