Do not subtract several byoyomi stones within the same move.
[pachi.git] / distributed / distributed.c
blob9829a3e16f3a178778ee7e4847eca6f2dd26f3c3
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 candidate moves, their number of playouts
7 * and their value. The master then picks the most popular move. */
9 /* With time control, the master waits for all slaves, except
10 * when the allowed time is already passed. In this case the
11 * master picks among the available replies, or waits for just
12 * one reply if there is none yet.
13 * Without time control, the master waits until the desired
14 * number of games have been simulated. In this case the -t
15 * parameter for the master should be the sum of the parameters
16 * for all slaves. */
18 /* The master sends updated statistics for the best moves
19 * in each genmoves command. In this version only the
20 * children of the root node are updated. The slaves
21 * reply with just their own stats; they remember what was
22 * previously received from or sent to the master, to
23 * distinguish their own contribution from that of other slaves. */
25 /* The master-slave protocol has has fault tolerance. If a slave is
26 * out of sync, the master sends it the appropriate command history. */
28 /* Pass me arguments like a=b,c=d,...
29 * Supported arguments:
30 * slave_port=SLAVE_PORT slaves connect to this port; this parameter is mandatory.
31 * max_slaves=MAX_SLAVES default 100
32 * slaves_quit=0|1 quit gtp command also sent to slaves, default false.
33 * proxy_port=PROXY_PORT slaves optionally send their logs to this port.
34 * Warning: with proxy_port, the master stderr mixes the logs of all
35 * machines but you can separate them again:
36 * slave logs: sed -n '/< .*:/s/.*< /< /p' logfile
37 * master logs: perl -0777 -pe 's/<[ <].*:.*\n//g' logfile
40 /* A configuration without proxy would have one master run on masterhost as:
41 * zzgo -e distributed slave_port=1234
42 * and N slaves running as:
43 * zzgo -e uct -g masterhost:1234 slave
44 * With log proxy:
45 * zzgo -e distributed slave_port=1234,proxy_port=1235
46 * zzgo -e uct -g masterhost:1234 -l masterhost:1235 slave
47 * If the master itself runs on a machine other than that running gogui,
48 * gogui-twogtp, kgsGtp or cgosGtp, it can redirect its gtp port:
49 * zzgo -e distributed -g 10000 slave_port=1234,proxy_port=1235
52 #include <assert.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <limits.h>
57 #include <time.h>
58 #include <alloca.h>
59 #include <sys/types.h>
61 #define DEBUG
63 #include "engine.h"
64 #include "move.h"
65 #include "timeinfo.h"
66 #include "playout.h"
67 #include "stats.h"
68 #include "mq.h"
69 #include "debug.h"
70 #include "distributed/distributed.h"
71 #include "distributed/protocol.h"
73 /* Internal engine state. */
74 struct distributed {
75 char *slave_port;
76 char *proxy_port;
77 int max_slaves;
78 bool slaves_quit;
79 struct move my_last_move;
80 struct move_stats my_last_stats;
83 /* Default number of simulations to perform per move.
84 * Note that this is in total over all slaves! */
85 #define DIST_GAMES 80000
86 static const struct time_info default_ti = {
87 .period = TT_MOVE,
88 .dim = TD_GAMES,
89 .len = { .games = DIST_GAMES },
92 #define get_value(value, color) \
93 ((color) == S_BLACK ? (value) : 1 - (value))
96 /* Maximum time (seconds) to wait for answers to fast gtp commands
97 * (all commands except pachi-genmoves and final_status_list). */
98 #define MAX_FAST_CMD_WAIT 1.0
100 /* How often to send a stats update to slaves (seconds) */
101 #define STATS_UPDATE_INTERVAL 0.1 /* 100ms */
103 /* Maximum time (seconds) to wait between genmoves
104 * (all commands except pachi-genmoves and final_status_list). */
105 #define MAX_FAST_CMD_WAIT 1.0
107 /* Dispatch a new gtp command to all slaves.
108 * The slave lock must not be held upon entry and is released upon return.
109 * args is empty or ends with '\n' */
110 static enum parse_code
111 distributed_notify(struct engine *e, struct board *b, int id, char *cmd, char *args, char **reply)
113 struct distributed *dist = e->data;
115 /* Commands that should not be sent to slaves.
116 * time_left will be part of next pachi-genmoves,
117 * we reduce latency by not forwarding it here. */
118 if ((!strcasecmp(cmd, "quit") && !dist->slaves_quit)
119 || !strcasecmp(cmd, "uct_genbook")
120 || !strcasecmp(cmd, "uct_dumpbook")
121 || !strcasecmp(cmd, "kgs-chat")
122 || !strcasecmp(cmd, "time_left")
124 /* and commands that will be sent to slaves later */
125 || !strcasecmp(cmd, "genmove")
126 || !strcasecmp(cmd, "kgs-genmove_cleanup")
127 || !strcasecmp(cmd, "final_score")
128 || !strcasecmp(cmd, "final_status_list"))
129 return P_OK;
131 protocol_lock();
133 // Create a new command to be sent by the slave threads.
134 new_cmd(b, cmd, args);
136 /* Wait for replies here. If we don't wait, we run the
137 * risk of getting out of sync with most slaves and
138 * sending command history too frequently. */
139 get_replies(time_now() + MAX_FAST_CMD_WAIT);
141 protocol_unlock();
142 return P_OK;
145 /* genmoves returns a line "=id played_own total_playouts threads keep_looking[ reserved]"
146 * then a list of lines "coord playouts value amaf_playouts amaf_value".
147 * Return the move with most playouts, and additional stats.
148 * Keep this code in sync with uct/slave.c:report_stats().
149 * slave_lock is held on entry and on return. */
150 static coord_t
151 select_best_move(struct board *b, struct move_stats2 *stats, int *played,
152 int *total_playouts, int *total_threads, bool *keep_looking)
154 assert(reply_count > 0);
156 /* +2 for pass and resign */
157 memset(stats-2, 0, (board_size2(b)+2) * sizeof(*stats));
159 coord_t best_move = pass;
160 int best_playouts = -1;
161 *played = 0;
162 *total_playouts = 0;
163 *total_threads = 0;
164 int keep = 0;
166 for (int reply = 0; reply < reply_count; reply++) {
167 char *r = gtp_replies[reply];
168 int id, o, p, t, k;
169 if (sscanf(r, "=%d %d %d %d %d", &id, &o, &p, &t, &k) != 5) continue;
170 *played += o;
171 *total_playouts += p;
172 *total_threads += t;
173 keep += k;
174 // Skip the rest of the firt line if any (allow future extensions)
175 r = strchr(r, '\n');
177 char move[64];
178 struct move_stats2 s;
179 while (r && sscanf(++r, "%63s %d %f %d %f", move, &s.u.playouts,
180 &s.u.value, &s.amaf.playouts, &s.amaf.value) == 5) {
181 coord_t *c = str2coord(move, board_size(b));
182 stats_add_result(&stats[*c].u, s.u.value, s.u.playouts);
183 stats_add_result(&stats[*c].amaf, s.amaf.value, s.amaf.playouts);
185 if (stats[*c].u.playouts > best_playouts) {
186 best_playouts = stats[*c].u.playouts;
187 best_move = *c;
189 coord_done(c);
190 r = strchr(r, '\n');
193 *keep_looking = keep > reply_count / 2;
194 return best_move;
197 /* Set the args for the genmoves command. If stats is not null,
198 * append the stats from all slaves above min_playouts, except
199 * for pass and resign. args must have CMDS_SIZE bytes and
200 * upon return ends with an empty line.
201 * Keep this code in sync with uct_genmoves().
202 * slave_lock is held on entry and on return. */
203 static void
204 genmoves_args(char *args, struct board *b, enum stone color, int played,
205 struct time_info *ti, struct move_stats2 *stats, int min_playouts)
207 char *end = args + CMDS_SIZE;
208 char *s = args + snprintf(args, CMDS_SIZE, "%s %d", stone2str(color), played);
210 if (ti->dim == TD_WALLTIME) {
211 s += snprintf(s, end - s, " %.3f %.3f %d %d",
212 ti->len.t.main_time, ti->len.t.byoyomi_time,
213 ti->len.t.byoyomi_periods, ti->len.t.byoyomi_stones);
215 s += snprintf(s, end - s, "\n");
216 if (stats) {
217 foreach_point(b) {
218 if (stats[c].u.playouts <= min_playouts) continue;
219 s += snprintf(s, end - s, "%s %d %.7f %d %.7f\n",
220 coord2sstr(c, b),
221 stats[c].u.playouts, stats[c].u.value,
222 stats[c].amaf.playouts, stats[c].amaf.value);
223 } foreach_point_end;
225 s += snprintf(s, end - s, "\n");
228 /* Time control is mostly done by the slaves, so we use default values here. */
229 #define FUSEKI_END 20
230 #define YOSE_START 40
232 static coord_t *
233 distributed_genmove(struct engine *e, struct board *b, struct time_info *ti,
234 enum stone color, bool pass_all_alive)
236 struct distributed *dist = e->data;
237 double now = time_now();
238 double first = now;
240 char *cmd = pass_all_alive ? "pachi-genmoves_cleanup" : "pachi-genmoves";
241 char args[CMDS_SIZE];
243 coord_t best;
244 int played, playouts, threads;
246 if (ti->period == TT_NULL) *ti = default_ti;
247 struct time_stop stop;
248 time_stop_conditions(ti, b, FUSEKI_END, YOSE_START, &stop);
249 struct time_info saved_ti = *ti;
251 /* Send the first genmoves without stats. */
252 genmoves_args(args, b, color, 0, ti, NULL, 0);
254 /* Combined move stats from all slaves, only for children
255 * of the root node, plus 2 for pass and resign. */
256 struct move_stats2 *stats = alloca((board_size2(b)+2) * sizeof(struct move_stats2));
257 stats += 2;
259 protocol_lock();
260 new_cmd(b, cmd, args);
262 /* Loop until most slaves want to quit or time elapsed. */
263 for (;;) {
264 double start = now;
265 get_replies(now + STATS_UPDATE_INTERVAL);
266 now = time_now();
267 if (ti->dim == TD_WALLTIME)
268 time_sub(ti, now - start, false);
270 bool keep_looking;
271 best = select_best_move(b, stats, &played, &playouts, &threads, &keep_looking);
273 if (!keep_looking) break;
274 if (ti->dim == TD_WALLTIME) {
275 if (now - ti->len.t.timer_start >= stop.worst.time) break;
276 } else {
277 if (played >= stop.worst.playouts) break;
279 if (DEBUGL(2)) {
280 char buf[BSIZE];
281 char *coord = coord2sstr(best, b);
282 snprintf(buf, sizeof(buf),
283 "temp winner is %s %s with score %1.4f (%d/%d games)"
284 " %d slaves %d threads\n",
285 stone2str(color), coord, get_value(stats[best].u.value, color),
286 stats[best].u.playouts, playouts, reply_count, threads);
287 logline(NULL, "* ", buf);
289 /* Send the command with the same gtp id, to avoid discarding
290 * a reply to a previous genmoves at the same move. */
291 genmoves_args(args, b, color, played, ti, stats, stats[best].u.playouts / 100);
292 update_cmd(b, cmd, args, false);
294 int replies = reply_count;
296 /* Do not subtract time spent twice (see gtp_parse). */
297 *ti = saved_ti;
299 dist->my_last_move.color = color;
300 dist->my_last_move.coord = best;
301 dist->my_last_stats = stats[best].u;
303 /* Tell the slaves to commit to the selected move, overwriting
304 * the last "pachi-genmoves" in the command history. */
305 char *coord = coord2str(best, b);
306 snprintf(args, sizeof(args), "%s %s\n", stone2str(color), coord);
307 update_cmd(b, "play", args, true);
308 protocol_unlock();
310 if (DEBUGL(1)) {
311 char buf[BSIZE];
312 double time = now - first + 0.000001; /* avoid divide by zero */
313 snprintf(buf, sizeof(buf),
314 "GLOBAL WINNER is %s %s with score %1.4f (%d/%d games)\n"
315 "genmove %d games in %0.2fs %d slaves %d threads (%d games/s,"
316 " %d games/s/slave, %d games/s/thread)\n",
317 stone2str(color), coord, get_value(stats[best].u.value, color),
318 stats[best].u.playouts, playouts, played, time, replies, threads,
319 (int)(played/time), (int)(played/time/replies),
320 (int)(played/time/threads));
321 logline(NULL, "* ", buf);
323 free(coord);
324 return coord_copy(best);
327 static char *
328 distributed_chat(struct engine *e, struct board *b, char *cmd)
330 struct distributed *dist = e->data;
331 static char reply[BSIZE];
333 cmd += strspn(cmd, " \n\t");
334 if (!strncasecmp(cmd, "winrate", 7)) {
335 enum stone color = dist->my_last_move.color;
336 snprintf(reply, BSIZE, "In %d playouts at %d machines, %s %s can win with %.2f%% probability.",
337 dist->my_last_stats.playouts, active_slaves, stone2str(color),
338 coord2sstr(dist->my_last_move.coord, b),
339 100 * get_value(dist->my_last_stats.value, color));
340 return reply;
342 return NULL;
345 static int
346 scmp(const void *p1, const void *p2)
348 return strcasecmp(*(char * const *)p1, *(char * const *)p2);
351 static void
352 distributed_dead_group_list(struct engine *e, struct board *b, struct move_queue *mq)
354 protocol_lock();
356 new_cmd(b, "final_status_list", "dead\n");
357 get_replies(time_now() + MAX_FAST_CMD_WAIT);
359 /* Find the most popular reply. */
360 qsort(gtp_replies, reply_count, sizeof(char *), scmp);
361 int best_reply = 0;
362 int best_count = 1;
363 int count = 1;
364 for (int reply = 1; reply < reply_count; reply++) {
365 if (!strcmp(gtp_replies[reply], gtp_replies[reply-1])) {
366 count++;
367 } else {
368 count = 1;
370 if (count > best_count) {
371 best_count = count;
372 best_reply = reply;
376 /* Pick the first move of each line as group. */
377 char *dead = gtp_replies[best_reply];
378 dead = strchr(dead, ' '); // skip "id "
379 while (dead && *++dead != '\n') {
380 coord_t *c = str2coord(dead, board_size(b));
381 mq_add(mq, *c);
382 coord_done(c);
383 dead = strchr(dead, '\n');
385 protocol_unlock();
388 static struct distributed *
389 distributed_state_init(char *arg, struct board *b)
391 struct distributed *dist = calloc2(1, sizeof(struct distributed));
393 dist->max_slaves = 100;
394 if (arg) {
395 char *optspec, *next = arg;
396 while (*next) {
397 optspec = next;
398 next += strcspn(next, ",");
399 if (*next) { *next++ = 0; } else { *next = 0; }
401 char *optname = optspec;
402 char *optval = strchr(optspec, '=');
403 if (optval) *optval++ = 0;
405 if (!strcasecmp(optname, "slave_port") && optval) {
406 dist->slave_port = strdup(optval);
407 } else if (!strcasecmp(optname, "proxy_port") && optval) {
408 dist->proxy_port = strdup(optval);
409 } else if (!strcasecmp(optname, "max_slaves") && optval) {
410 dist->max_slaves = atoi(optval);
411 } else if (!strcasecmp(optname, "slaves_quit")) {
412 dist->slaves_quit = !optval || atoi(optval);
413 } else {
414 fprintf(stderr, "distributed: Invalid engine argument %s or missing value\n", optname);
419 gtp_replies = calloc2(dist->max_slaves, sizeof(char *));
421 if (!dist->slave_port) {
422 fprintf(stderr, "distributed: missing slave_port\n");
423 exit(1);
425 protocol_init(dist->slave_port, dist->proxy_port, dist->max_slaves);
426 return dist;
429 struct engine *
430 engine_distributed_init(char *arg, struct board *b)
432 struct distributed *dist = distributed_state_init(arg, b);
433 struct engine *e = calloc2(1, sizeof(struct engine));
434 e->name = "Distributed Engine";
435 e->comment = "I'm playing the distributed engine. When I'm losing, I will resign, "
436 "if I think I win, I play until you pass. "
437 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
438 e->notify = distributed_notify;
439 e->genmove = distributed_genmove;
440 e->dead_group_list = distributed_dead_group_list;
441 e->chat = distributed_chat;
442 e->data = dist;
443 // Keep the threads and the open socket connections:
444 e->keep_on_clear = true;
446 return e;