Distributed engine: always send the right history, not just the latest command.
[pachi/json.git] / distributed / distributed.c
blob9b016633da74475db754f08113c955b7da0c19a0
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 <pthread.h>
57 #include <limits.h>
58 #include <ctype.h>
59 #include <time.h>
60 #include <alloca.h>
61 #include <sys/types.h>
62 #include <sys/socket.h>
63 #include <arpa/inet.h>
65 #define DEBUG
67 #include "board.h"
68 #include "engine.h"
69 #include "move.h"
70 #include "timeinfo.h"
71 #include "network.h"
72 #include "playout.h"
73 #include "random.h"
74 #include "stats.h"
75 #include "mq.h"
76 #include "debug.h"
77 #include "distributed/distributed.h"
79 /* Internal engine state. */
80 struct distributed {
81 char *slave_port;
82 char *proxy_port;
83 int max_slaves;
84 bool slaves_quit;
85 struct move my_last_move;
86 struct move_stats my_last_stats;
89 /* Default number of simulations to perform per move.
90 * Note that this is in total over all slaves! */
91 #define DIST_GAMES 80000
92 static const struct time_info default_ti = {
93 .period = TT_MOVE,
94 .dim = TD_GAMES,
95 .len = { .games = DIST_GAMES },
98 #define get_value(value, color) \
99 ((color) == S_BLACK ? (value) : 1 - (value))
101 /* Max size for one line of reply or slave log. */
102 #define BSIZE 4096
104 /* Max size of all gtp commands for one game.
105 * 60 chars for the first line of genmoves plus 100 lines
106 * of 30 chars each for the stats at last move. */
107 #define CMDS_SIZE (60*MAX_GAMELEN + 30*100)
109 /* All gtp commands for current game separated by \n */
110 static char gtp_cmds[CMDS_SIZE];
112 /* Latest gtp command sent to slaves. */
113 static char *gtp_cmd = NULL;
115 /* Slaves send gtp_cmd when cmd_count changes. */
116 static int cmd_count = 0;
118 /* Remember at most 10 gtp ids per move: kgs-rules, boardsize, clear_board,
119 * time_settings, komi, handicap, genmoves, play pass, play pass, final_status_list */
120 #define MAX_CMDS_PER_MOVE 10
122 /* History of gtp commands sent for current game, indexed by move. */
123 struct cmd_history {
124 int gtp_id;
125 char *next_cmd;
126 } history[MAX_GAMELEN][MAX_CMDS_PER_MOVE];
128 /* Number of active slave machines working for this master. */
129 static int active_slaves = 0;
131 /* Number of replies to last gtp command already received. */
132 static int reply_count = 0;
134 /* All replies to latest gtp command are in gtp_replies[0..reply_count-1]. */
135 static char **gtp_replies;
137 /* Mutex protecting gtp_cmds, gtp_cmd, history,
138 * cmd_count, active_slaves, reply_count & gtp_replies */
139 static pthread_mutex_t slave_lock = PTHREAD_MUTEX_INITIALIZER;
141 /* Condition signaled when a new gtp command is available. */
142 static pthread_cond_t cmd_cond = PTHREAD_COND_INITIALIZER;
144 /* Condition signaled when reply_count increases. */
145 static pthread_cond_t reply_cond = PTHREAD_COND_INITIALIZER;
147 /* Mutex protecting stderr. Must not be held at same time as slave_lock. */
148 static pthread_mutex_t log_lock = PTHREAD_MUTEX_INITIALIZER;
150 /* Absolute time when this program was started.
151 * For debugging only. */
152 static double start_time;
154 /* Write the time, client address, prefix, and string s to stderr atomically.
155 * s should end with a \n */
156 static void
157 logline(struct in_addr *client, char *prefix, char *s)
159 double now = time_now();
160 char addr[INET_ADDRSTRLEN];
161 if (client) {
162 inet_ntop(AF_INET, client, addr, sizeof(addr));
163 } else {
164 addr[0] = '\0';
166 pthread_mutex_lock(&log_lock);
167 fprintf(stderr, "%s%15s %9.3f: %s", prefix, addr, now - start_time, s);
168 pthread_mutex_unlock(&log_lock);
171 /* Thread opening a connection on the given socket and copying input
172 * from there to stderr. */
173 static void *
174 proxy_thread(void *arg)
176 int proxy_sock = (long)arg;
177 assert(proxy_sock >= 0);
178 for (;;) {
179 struct in_addr client;
180 int conn = open_server_connection(proxy_sock, &client);
181 FILE *f = fdopen(conn, "r");
182 char buf[BSIZE];
183 while (fgets(buf, BSIZE, f)) {
184 logline(&client, "< ", buf);
186 fclose(f);
190 /* Get a reply to one gtp command. Return the gtp command id,
191 * or -1 if error. reply must have at least CMDS_SIZE bytes.
192 * slave_lock is not held on either entry or exit of this function. */
193 static int
194 get_reply(FILE *f, struct in_addr client, char *reply)
196 int reply_id = -1;
197 *reply = '\0';
198 char *line = reply;
199 while (fgets(line, reply + CMDS_SIZE - line, f) && *line != '\n') {
200 if (DEBUGL(3) || (DEBUGL(2) && line == reply))
201 logline(&client, "<<", line);
202 if (reply_id < 0 && (*line == '=' || *line == '?') && isdigit(line[1]))
203 reply_id = atoi(line+1);
204 line += strlen(line);
206 if (*line != '\n') return -1;
207 return reply_id;
210 /* Send one gtp command and get a reply from the slave machine.
211 * Write the reply in buf which must have at least CMDS_SIZE bytes.
212 * Return the gtp command id, or -1 if error.
213 * slave_lock is held on both entry and exit of this function. */
214 static int
215 send_command(char *to_send, FILE *f, struct in_addr client, char *buf)
217 assert(to_send && gtp_cmd);
218 strncpy(buf, to_send, CMDS_SIZE);
219 bool resend = to_send != gtp_cmd;
221 pthread_mutex_unlock(&slave_lock);
223 if (DEBUGL(1) && resend)
224 logline(&client, "? ",
225 to_send == gtp_cmds ? "resend all\n" : "partial resend\n");
226 fputs(buf, f);
227 fflush(f);
228 if (DEBUGL(2)) {
229 if (!DEBUGL(3)) {
230 char *s = strchr(buf, '\n');
231 if (s) s[1] = '\0';
233 logline(&client, ">>", buf);
236 int reply_id = get_reply(f, client, buf);
238 pthread_mutex_lock(&slave_lock);
239 return reply_id;
242 /* Return the command sent after that with the given gtp id,
243 * or gtp_cmds if the id wasn't used in this game. If a play command
244 * has overwritten a genmoves command, return the play command.
245 * slave_lock is held on both entry and exit of this function. */
246 static char *
247 next_command(int cmd_id)
249 if (cmd_id == -1) return gtp_cmds;
251 int last_id = atoi(gtp_cmd);
252 int reply_move = move_number(cmd_id);
253 if (reply_move > move_number(last_id)) return gtp_cmds;
255 int slot;
256 for (slot = 0; slot < MAX_CMDS_PER_MOVE; slot++) {
257 if (cmd_id == history[reply_move][slot].gtp_id) break;
259 if (slot == MAX_CMDS_PER_MOVE) return gtp_cmds;
261 char *next = history[reply_move][slot].next_cmd;
262 assert(next);
263 return next;
266 /* Process the reply received from a slave machine.
267 * Copy it to reply_buf and return false if ok, or return
268 * true if the slave is out of sync.
269 * slave_lock is held on both entry and exit of this function. */
270 static bool
271 process_reply(int reply_id, char *reply, char *reply_buf,
272 int *last_reply_id, int *reply_slot)
274 bool resend = true;
275 /* For resend everything if slave returned an error. */
276 if (*reply != '=') {
277 *last_reply_id = -1;
278 return resend;
280 /* Make sure we are still in sync. cmd_count may have
281 * changed but the reply is valid as long as cmd_id didn't
282 * change (this only occurs for consecutive genmoves). */
283 int cmd_id = atoi(gtp_cmd);
284 if (reply_id == cmd_id) {
285 strncpy(reply_buf, reply, CMDS_SIZE);
286 if (reply_id != *last_reply_id)
287 *reply_slot = reply_count++;
288 gtp_replies[*reply_slot] = reply_buf;
290 pthread_cond_signal(&reply_cond);
291 resend = false;
293 *last_reply_id = reply_id;
294 return resend;
297 /* Main loop of a slave thread.
298 * Send the current command to the slave machine and wait for a reply.
299 * Resend command history if the slave machine is out of sync.
300 * Returns when the connection with the slave machine is cut.
301 * slave_lock is held on both entry and exit of this function. */
302 static void
303 slave_loop(FILE *f, struct in_addr client, char *reply_buf, bool resend)
305 char *to_send;
306 int last_cmd_sent = 0;
307 int last_reply_id = -1;
308 int reply_slot = -1;
309 for (;;) {
310 if (resend) {
311 /* Resend complete or partial history */
312 to_send = next_command(last_reply_id);
313 } else {
314 /* Wait for a new command. */
315 while (last_cmd_sent == cmd_count)
316 pthread_cond_wait(&cmd_cond, &slave_lock);
317 to_send = gtp_cmd;
320 /* Command available, send it to slave machine.
321 * If slave was out of sync, send the history. */
322 char buf[CMDS_SIZE];
323 last_cmd_sent = cmd_count;
325 /* Send the command and get the reply, which always ends with \n\n
326 * The slave machine sends "=id reply" or "?id reply"
327 * with id == cmd_id if it is in sync. */
328 int reply_id = send_command(to_send, f, client, buf);
329 if (reply_id == -1) return;
331 resend = process_reply(reply_id, buf, reply_buf,
332 &last_reply_id, &reply_slot);
333 if (!resend)
334 /* Good reply. Force waiting for a new command.
335 * The next genmoves stats we send must include those
336 * just received (this is assumed by the slave). */
337 last_cmd_sent = cmd_count;
341 /* Thread sending gtp commands to one slave machine, and
342 * reading replies. If a slave machine dies, this thread waits
343 * for a connection from another slave. */
344 static void *
345 slave_thread(void *arg)
347 int slave_sock = (long)arg;
348 assert(slave_sock >= 0);
349 char reply_buf[CMDS_SIZE];
350 bool resend = false;
352 for (;;) {
353 /* Wait for a connection from any slave. */
354 struct in_addr client;
355 int conn = open_server_connection(slave_sock, &client);
357 FILE *f = fdopen(conn, "r+");
358 if (DEBUGL(2))
359 logline(&client, "= ", "new slave\n");
361 /* Minimal check of the slave identity. */
362 fputs("name\n", f);
363 if (!fgets(reply_buf, sizeof(reply_buf), f)
364 || strncasecmp(reply_buf, "= Pachi", 7)
365 || !fgets(reply_buf, sizeof(reply_buf), f)
366 || strcmp(reply_buf, "\n")) {
367 logline(&client, "? ", "bad slave\n");
368 fclose(f);
369 continue;
372 pthread_mutex_lock(&slave_lock);
373 active_slaves++;
374 slave_loop(f, client, reply_buf, resend);
376 assert(active_slaves > 0);
377 active_slaves--;
378 // Unblock main thread if it was waiting for this slave.
379 pthread_cond_signal(&reply_cond);
380 pthread_mutex_unlock(&slave_lock);
382 resend = true;
383 if (DEBUGL(2))
384 logline(&client, "= ", "lost slave\n");
385 fclose(f);
389 /* Create a new gtp command for all slaves. The slave lock is held
390 * upon entry and upon return, so the command will actually be
391 * sent when the lock is released. The last command is overwritten
392 * if gtp_cmd points to a non-empty string. cmd is a single word;
393 * args has all arguments and is empty or has a trailing \n */
394 static void
395 update_cmd(struct board *b, char *cmd, char *args, bool new_id)
397 assert(gtp_cmd);
398 /* To make sure the slaves are in sync, we ignore the original id
399 * and use the board number plus some random bits as gtp id. */
400 static int gtp_id = -1;
401 int moves = is_reset(cmd) ? 0 : b->moves;
402 if (new_id) {
403 /* fast_random() is 16-bit only so the multiplication can't overflow. */
404 gtp_id = force_reply(moves + fast_random(65535) * DIST_GAMELEN);
405 reply_count = 0;
407 snprintf(gtp_cmd, gtp_cmds + CMDS_SIZE - gtp_cmd, "%d %s %s",
408 gtp_id, cmd, *args ? args : "\n");
409 cmd_count++;
411 /* Remember history for out-of-sync slaves. */
412 static int slot = 0;
413 static struct cmd_history *last = NULL;
414 if (new_id) {
415 if (last) last->next_cmd = gtp_cmd;
416 slot = (slot + 1) % MAX_CMDS_PER_MOVE;
417 last = &history[moves][slot];
418 last->gtp_id = gtp_id;
419 last->next_cmd = NULL;
421 // Notify the slave threads about the new command.
422 pthread_cond_broadcast(&cmd_cond);
425 /* Update the command history, then create a new gtp command
426 * for all slaves. The slave lock is held upon entry and
427 * upon return, so the command will actually be sent when the
428 * lock is released. cmd is a single word; args has all
429 * arguments and is empty or has a trailing \n */
430 static void
431 new_cmd(struct board *b, char *cmd, char *args)
433 // Clear the history when a new game starts:
434 if (!gtp_cmd || is_gamestart(cmd)) {
435 gtp_cmd = gtp_cmds;
436 memset(history, 0, sizeof(history));
437 } else {
438 /* Preserve command history for new slaves.
439 * To indicate that the slave should only reply to
440 * the last command we force the id of previous
441 * commands to be just the move number. */
442 int id = prevent_reply(atoi(gtp_cmd));
443 int len = strspn(gtp_cmd, "0123456789");
444 char buf[32];
445 snprintf(buf, sizeof(buf), "%0*d", len, id);
446 memcpy(gtp_cmd, buf, len);
448 gtp_cmd += strlen(gtp_cmd);
451 // Let the slave threads send the new gtp command:
452 update_cmd(b, cmd, args, true);
455 /* Wait for at least one new reply. Return when all slaves have
456 * replied, or when the given absolute time is passed.
457 * The replies are returned in gtp_replies[0..reply_count-1]
458 * slave_lock is held on entry and on return. */
459 static void
460 get_replies(double time_limit)
462 for (;;) {
463 if (reply_count > 0) {
464 struct timespec ts;
465 double sec;
466 ts.tv_nsec = (int)(modf(time_limit, &sec)*1000000000.0);
467 ts.tv_sec = (int)sec;
468 pthread_cond_timedwait(&reply_cond, &slave_lock, &ts);
469 } else {
470 pthread_cond_wait(&reply_cond, &slave_lock);
472 if (reply_count == 0) continue;
473 if (reply_count >= active_slaves) return;
474 if (time_now() >= time_limit) break;
476 if (DEBUGL(1)) {
477 char buf[1024];
478 snprintf(buf, sizeof(buf),
479 "get_replies timeout %.3f >= %.3f, replies %d < active %d\n",
480 time_now() - start_time, time_limit - start_time,
481 reply_count, active_slaves);
482 logline(NULL, "? ", buf);
484 assert(reply_count > 0);
487 /* Maximum time (seconds) to wait for answers to fast gtp commands
488 * (all commands except pachi-genmoves and final_status_list). */
489 #define MAX_FAST_CMD_WAIT 1.0
491 /* How often to send a stats update to slaves (seconds) */
492 #define STATS_UPDATE_INTERVAL 0.1 /* 100ms */
494 /* Maximum time (seconds) to wait between genmoves
495 * (all commands except pachi-genmoves and final_status_list). */
496 #define MAX_FAST_CMD_WAIT 1.0
498 /* Dispatch a new gtp command to all slaves.
499 * The slave lock must not be held upon entry and is released upon return.
500 * args is empty or ends with '\n' */
501 static enum parse_code
502 distributed_notify(struct engine *e, struct board *b, int id, char *cmd, char *args, char **reply)
504 struct distributed *dist = e->data;
506 /* Commands that should not be sent to slaves.
507 * time_left will be part of next pachi-genmoves,
508 * we reduce latency by not forwarding it here. */
509 if ((!strcasecmp(cmd, "quit") && !dist->slaves_quit)
510 || !strcasecmp(cmd, "uct_genbook")
511 || !strcasecmp(cmd, "uct_dumpbook")
512 || !strcasecmp(cmd, "kgs-chat")
513 || !strcasecmp(cmd, "time_left")
515 /* and commands that will be sent to slaves later */
516 || !strcasecmp(cmd, "genmove")
517 || !strcasecmp(cmd, "kgs-genmove_cleanup")
518 || !strcasecmp(cmd, "final_score")
519 || !strcasecmp(cmd, "final_status_list"))
520 return P_OK;
522 pthread_mutex_lock(&slave_lock);
524 // Create a new command to be sent by the slave threads.
525 new_cmd(b, cmd, args);
527 /* Wait for replies here. If we don't wait, we run the
528 * risk of getting out of sync with most slaves and
529 * sending command history too frequently. */
530 get_replies(time_now() + MAX_FAST_CMD_WAIT);
532 pthread_mutex_unlock(&slave_lock);
533 return P_OK;
536 /* genmoves returns a line "=id played_own total_playouts threads keep_looking[ reserved]"
537 * then a list of lines "coord playouts value amaf_playouts amaf_value".
538 * Return the move with most playouts, and additional stats.
539 * Keep this code in sync with uct/slave.c:report_stats().
540 * slave_lock is held on entry and on return. */
541 static coord_t
542 select_best_move(struct board *b, struct move_stats2 *stats, int *played,
543 int *total_playouts, int *total_threads, bool *keep_looking)
545 assert(reply_count > 0);
547 /* +2 for pass and resign */
548 memset(stats-2, 0, (board_size2(b)+2) * sizeof(*stats));
550 coord_t best_move = pass;
551 int best_playouts = -1;
552 *played = 0;
553 *total_playouts = 0;
554 *total_threads = 0;
555 int keep = 0;
557 for (int reply = 0; reply < reply_count; reply++) {
558 char *r = gtp_replies[reply];
559 int id, o, p, t, k;
560 if (sscanf(r, "=%d %d %d %d %d", &id, &o, &p, &t, &k) != 5) continue;
561 *played += o;
562 *total_playouts += p;
563 *total_threads += t;
564 keep += k;
565 // Skip the rest of the firt line if any (allow future extensions)
566 r = strchr(r, '\n');
568 char move[64];
569 struct move_stats2 s;
570 while (r && sscanf(++r, "%63s %d %f %d %f", move, &s.u.playouts,
571 &s.u.value, &s.amaf.playouts, &s.amaf.value) == 5) {
572 coord_t *c = str2coord(move, board_size(b));
573 stats_add_result(&stats[*c].u, s.u.value, s.u.playouts);
574 stats_add_result(&stats[*c].amaf, s.amaf.value, s.amaf.playouts);
576 if (stats[*c].u.playouts > best_playouts) {
577 best_playouts = stats[*c].u.playouts;
578 best_move = *c;
580 coord_done(c);
581 r = strchr(r, '\n');
584 *keep_looking = keep > reply_count / 2;
585 return best_move;
588 /* Set the args for the genmoves command. If stats is not null,
589 * append the stats from all slaves above min_playouts, except
590 * for pass and resign. args must have CMDS_SIZE bytes and
591 * upon return ends with an empty line.
592 * Keep this code in sync with uct_genmoves().
593 * slave_lock is held on entry and on return. */
594 static void
595 genmoves_args(char *args, struct board *b, enum stone color, int played,
596 struct time_info *ti, struct move_stats2 *stats, int min_playouts)
598 char *end = args + CMDS_SIZE;
599 char *s = args + snprintf(args, CMDS_SIZE, "%s %d", stone2str(color), played);
601 if (ti->dim == TD_WALLTIME) {
602 s += snprintf(s, end - s, " %.3f %.3f %d %d",
603 ti->len.t.main_time, ti->len.t.byoyomi_time,
604 ti->len.t.byoyomi_periods, ti->len.t.byoyomi_stones);
606 s += snprintf(s, end - s, "\n");
607 if (stats) {
608 foreach_point(b) {
609 if (stats[c].u.playouts <= min_playouts) continue;
610 s += snprintf(s, end - s, "%s %d %.7f %d %.7f\n",
611 coord2sstr(c, b),
612 stats[c].u.playouts, stats[c].u.value,
613 stats[c].amaf.playouts, stats[c].amaf.value);
614 } foreach_point_end;
616 s += snprintf(s, end - s, "\n");
619 /* Time control is mostly done by the slaves, so we use default values here. */
620 #define FUSEKI_END 20
621 #define YOSE_START 40
623 static coord_t *
624 distributed_genmove(struct engine *e, struct board *b, struct time_info *ti,
625 enum stone color, bool pass_all_alive)
627 struct distributed *dist = e->data;
628 double now = time_now();
629 double first = now;
631 char *cmd = pass_all_alive ? "pachi-genmoves_cleanup" : "pachi-genmoves";
632 char args[CMDS_SIZE];
634 coord_t best;
635 int played, playouts, threads;
637 if (ti->period == TT_NULL) *ti = default_ti;
638 struct time_stop stop;
639 time_stop_conditions(ti, b, FUSEKI_END, YOSE_START, &stop);
640 struct time_info saved_ti = *ti;
642 /* Send the first genmoves without stats. */
643 genmoves_args(args, b, color, 0, ti, NULL, 0);
645 /* Combined move stats from all slaves, only for children
646 * of the root node, plus 2 for pass and resign. */
647 struct move_stats2 *stats = alloca((board_size2(b)+2) * sizeof(struct move_stats2));
648 stats += 2;
650 pthread_mutex_lock(&slave_lock);
651 new_cmd(b, cmd, args);
653 /* Loop until most slaves want to quit or time elapsed. */
654 for (;;) {
655 double start = now;
656 get_replies(now + STATS_UPDATE_INTERVAL);
657 now = time_now();
658 if (ti->dim == TD_WALLTIME)
659 time_sub(ti, now - start);
661 bool keep_looking;
662 best = select_best_move(b, stats, &played, &playouts, &threads, &keep_looking);
664 if (!keep_looking) break;
665 if (ti->dim == TD_WALLTIME) {
666 if (now - ti->len.t.timer_start >= stop.worst.time) break;
667 } else {
668 if (played >= stop.worst.playouts) break;
670 if (DEBUGL(2)) {
671 char buf[BSIZE];
672 char *coord = coord2sstr(best, b);
673 snprintf(buf, sizeof(buf),
674 "temp winner is %s %s with score %1.4f (%d/%d games)"
675 " %d slaves %d threads\n",
676 stone2str(color), coord, get_value(stats[best].u.value, color),
677 stats[best].u.playouts, playouts, reply_count, threads);
678 logline(NULL, "* ", buf);
680 /* Send the command with the same gtp id, to avoid discarding
681 * a reply to a previous genmoves at the same move. */
682 genmoves_args(args, b, color, played, ti, stats, stats[best].u.playouts / 100);
683 update_cmd(b, cmd, args, false);
685 int replies = reply_count;
687 /* Do not subtract time spent twice (see gtp_parse). */
688 *ti = saved_ti;
690 dist->my_last_move.color = color;
691 dist->my_last_move.coord = best;
692 dist->my_last_stats = stats[best].u;
694 /* Tell the slaves to commit to the selected move, overwriting
695 * the last "pachi-genmoves" in the command history. */
696 char *coord = coord2str(best, b);
697 snprintf(args, sizeof(args), "%s %s\n", stone2str(color), coord);
698 update_cmd(b, "play", args, true);
699 pthread_mutex_unlock(&slave_lock);
701 if (DEBUGL(1)) {
702 char buf[BSIZE];
703 double time = now - first + 0.000001; /* avoid divide by zero */
704 snprintf(buf, sizeof(buf),
705 "GLOBAL WINNER is %s %s with score %1.4f (%d/%d games)\n"
706 "genmove %d games in %0.2fs %d slaves %d threads (%d games/s,"
707 " %d games/s/slave, %d games/s/thread)\n",
708 stone2str(color), coord, get_value(stats[best].u.value, color),
709 stats[best].u.playouts, playouts, played, time, replies, threads,
710 (int)(played/time), (int)(played/time/replies),
711 (int)(played/time/threads));
712 logline(NULL, "* ", buf);
714 free(coord);
715 return coord_copy(best);
718 static char *
719 distributed_chat(struct engine *e, struct board *b, char *cmd)
721 struct distributed *dist = e->data;
722 static char reply[BSIZE];
724 cmd += strspn(cmd, " \n\t");
725 if (!strncasecmp(cmd, "winrate", 7)) {
726 enum stone color = dist->my_last_move.color;
727 snprintf(reply, BSIZE, "In %d playouts at %d machines, %s %s can win with %.2f%% probability.",
728 dist->my_last_stats.playouts, active_slaves, stone2str(color),
729 coord2sstr(dist->my_last_move.coord, b),
730 100 * get_value(dist->my_last_stats.value, color));
731 return reply;
733 return NULL;
736 static int
737 scmp(const void *p1, const void *p2)
739 return strcasecmp(*(char * const *)p1, *(char * const *)p2);
742 static void
743 distributed_dead_group_list(struct engine *e, struct board *b, struct move_queue *mq)
745 pthread_mutex_lock(&slave_lock);
747 new_cmd(b, "final_status_list", "dead\n");
748 get_replies(time_now() + MAX_FAST_CMD_WAIT);
750 /* Find the most popular reply. */
751 qsort(gtp_replies, reply_count, sizeof(char *), scmp);
752 int best_reply = 0;
753 int best_count = 1;
754 int count = 1;
755 for (int reply = 1; reply < reply_count; reply++) {
756 if (!strcmp(gtp_replies[reply], gtp_replies[reply-1])) {
757 count++;
758 } else {
759 count = 1;
761 if (count > best_count) {
762 best_count = count;
763 best_reply = reply;
767 /* Pick the first move of each line as group. */
768 char *dead = gtp_replies[best_reply];
769 dead = strchr(dead, ' '); // skip "id "
770 while (dead && *++dead != '\n') {
771 coord_t *c = str2coord(dead, board_size(b));
772 mq_add(mq, *c);
773 coord_done(c);
774 dead = strchr(dead, '\n');
776 pthread_mutex_unlock(&slave_lock);
779 static struct distributed *
780 distributed_state_init(char *arg, struct board *b)
782 struct distributed *dist = calloc2(1, sizeof(struct distributed));
784 dist->max_slaves = 100;
785 if (arg) {
786 char *optspec, *next = arg;
787 while (*next) {
788 optspec = next;
789 next += strcspn(next, ",");
790 if (*next) { *next++ = 0; } else { *next = 0; }
792 char *optname = optspec;
793 char *optval = strchr(optspec, '=');
794 if (optval) *optval++ = 0;
796 if (!strcasecmp(optname, "slave_port") && optval) {
797 dist->slave_port = strdup(optval);
798 } else if (!strcasecmp(optname, "proxy_port") && optval) {
799 dist->proxy_port = strdup(optval);
800 } else if (!strcasecmp(optname, "max_slaves") && optval) {
801 dist->max_slaves = atoi(optval);
802 } else if (!strcasecmp(optname, "slaves_quit")) {
803 dist->slaves_quit = !optval || atoi(optval);
804 } else {
805 fprintf(stderr, "distributed: Invalid engine argument %s or missing value\n", optname);
810 gtp_replies = calloc2(dist->max_slaves, sizeof(char *));
812 if (!dist->slave_port) {
813 fprintf(stderr, "distributed: missing slave_port\n");
814 exit(1);
816 int slave_sock = port_listen(dist->slave_port, dist->max_slaves);
817 pthread_t thread;
818 for (int id = 0; id < dist->max_slaves; id++) {
819 pthread_create(&thread, NULL, slave_thread, (void *)(long)slave_sock);
822 if (dist->proxy_port) {
823 int proxy_sock = port_listen(dist->proxy_port, dist->max_slaves);
824 for (int id = 0; id < dist->max_slaves; id++) {
825 pthread_create(&thread, NULL, proxy_thread, (void *)(long)proxy_sock);
828 return dist;
831 struct engine *
832 engine_distributed_init(char *arg, struct board *b)
834 start_time = time_now();
835 struct distributed *dist = distributed_state_init(arg, b);
836 struct engine *e = calloc2(1, sizeof(struct engine));
837 e->name = "Distributed Engine";
838 e->comment = "I'm playing the distributed engine. When I'm losing, I will resign, "
839 "if I think I win, I play until you pass. "
840 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
841 e->notify = distributed_notify;
842 e->genmove = distributed_genmove;
843 e->dead_group_list = distributed_dead_group_list;
844 e->chat = distributed_chat;
845 e->data = dist;
846 // Keep the threads and the open socket connections:
847 e->keep_on_clear = true;
849 return e;