forked from LeelaChessZero/lczero-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lc0_main.go
551 lines (500 loc) · 13.6 KB
/
lc0_main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
// A new client to work with the lc0 binary.
//
//
package main
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"path"
"path/filepath"
"strconv"
"strings"
"time"
"client"
"github.com/Tilps/chess"
)
var (
startTime time.Time
totalGames int
hostname = flag.String("hostname", "http://testserver.lczero.org", "Address of the server")
user = flag.String("user", "", "Username")
password = flag.String("password", "", "Password")
gpu = flag.Int("gpu", -1, "ID of the OpenCL device to use (-1 for default, or no GPU)")
debug = flag.Bool("debug", false, "Enable debug mode to see verbose output and save logs")
lc0Args = flag.String("lc0args", "", `Extra args to pass to the backend. example: --lc0args="--parallelism=10 --threads=2"`)
)
// Settings holds username and password.
type Settings struct {
User string
Pass string
}
/*
Reads the user and password from a config file and returns empty strings if anything went wrong.
If the config file does not exists, it prompts the user for a username and password and creates the config file.
*/
func readSettings(path string) (string, string) {
settings := Settings{}
file, err := os.Open(path)
if err != nil {
// File was not found
fmt.Printf("Please enter your username and password, an account will be automatically created.\n")
fmt.Printf("Note that this password will be stored in plain text, so avoid a password that is\n")
fmt.Printf("also used for sensitive applications. It also cannot be recovered.\n")
fmt.Printf("Enter username : ")
fmt.Scanf("%s\n", &settings.User)
fmt.Printf("Enter password : ")
fmt.Scanf("%s\n", &settings.Pass)
jsonSettings, err := json.Marshal(settings)
if err != nil {
log.Fatal("Cannot encode settings to JSON ", err)
return "", ""
}
settingsFile, err := os.Create(path)
defer settingsFile.Close()
if err != nil {
log.Fatal("Could not create output file ", err)
return "", ""
}
settingsFile.Write(jsonSettings)
return settings.User, settings.Pass
}
defer file.Close()
decoder := json.NewDecoder(file)
err = decoder.Decode(&settings)
if err != nil {
log.Fatal("Error decoding JSON ", err)
return "", ""
}
return settings.User, settings.Pass
}
func getExtraParams() map[string]string {
return map[string]string{
"user": *user,
"password": *password,
"version": "10",
}
}
func uploadGame(httpClient *http.Client, path string, pgn string,
nextGame client.NextGameResponse, version string, retryCount uint) error {
elapsed := time.Since(startTime)
totalGames++
log.Printf("Completed %d games in %s time", totalGames, elapsed)
extraParams := getExtraParams()
extraParams["training_id"] = strconv.Itoa(int(nextGame.TrainingId))
extraParams["network_id"] = strconv.Itoa(int(nextGame.NetworkId))
extraParams["pgn"] = pgn
extraParams["engineVersion"] = version
request, err := client.BuildUploadRequest(*hostname+"/upload_game", extraParams, "file", path)
if err != nil {
log.Printf("BUR: %v", err)
return err
}
resp, err := httpClient.Do(request)
if err != nil {
log.Printf("http.Do: %v", err)
return err
}
body := &bytes.Buffer{}
_, err = body.ReadFrom(resp.Body)
if err != nil {
log.Print(err)
log.Print("Error uploading, retrying...")
time.Sleep(time.Second * (2 << retryCount))
err = uploadGame(httpClient, path, pgn, nextGame, version, retryCount+1)
return err
}
resp.Body.Close()
fmt.Println(resp.StatusCode)
fmt.Println(resp.Header)
fmt.Println(body)
trainDir := filepath.Dir(path)
if _, err := os.Stat(trainDir); err == nil {
files, err := ioutil.ReadDir(trainDir)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Cleanup training files:\n")
for _, f := range files {
fmt.Printf("%s/%s\n", trainDir, f.Name())
}
err = os.RemoveAll(trainDir)
if err != nil {
log.Fatal(err)
}
}
return nil
}
type gameInfo struct {
pgn string
fname string
}
type cmdWrapper struct {
Cmd *exec.Cmd
Pgn string
Input io.WriteCloser
BestMove chan string
gi chan gameInfo
Version string
}
func (c *cmdWrapper) openInput() {
var err error
c.Input, err = c.Cmd.StdinPipe()
if err != nil {
log.Fatal(err)
}
}
func convertMovesToPGN(moves []string) string {
game := chess.NewGame(chess.UseNotation(chess.LongAlgebraicNotation{}))
for _, m := range moves {
err := game.MoveStr(m)
if err != nil {
log.Fatalf("movstr: %v", err)
}
}
game2 := chess.NewGame()
b, err := game.MarshalText()
if err != nil {
log.Fatalf("MarshalText failed: %v", err)
}
game2.UnmarshalText(b)
return game2.String()
}
func createCmdWrapper() *cmdWrapper {
c := &cmdWrapper{
gi: make(chan gameInfo),
BestMove: make(chan string),
}
return c
}
func (c *cmdWrapper) launch(networkPath string, args []string, input bool) {
dir, _ := os.Getwd()
c.Cmd = exec.Command(path.Join(dir, "lc0"))
c.Cmd.Args = append(c.Cmd.Args, args...)
c.Cmd.Args = append(c.Cmd.Args, fmt.Sprintf("--weights=%s", networkPath))
if *lc0Args != "" {
// TODO: We might want to inspect these to prevent someone
// from passing a different visits or batch size for example.
// Possibly just exposts exact args we want to passthrough like
// backend. For testing right now this is probably useful to not
// need to rebuild the client to change lc0 args.
parts := strings.Split(*lc0Args, " ")
c.Cmd.Args = append(c.Cmd.Args, parts...)
}
if !*debug {
// c.Cmd.Args = append(c.Cmd.Args, "--quiet")
fmt.Println("lc0 is never quiet.")
}
fmt.Printf("Args: %v\n", c.Cmd.Args)
stdout, err := c.Cmd.StdoutPipe()
if err != nil {
log.Fatal(err)
}
stderr, err := c.Cmd.StderrPipe()
if err != nil {
log.Fatal(err)
}
go func() {
defer close(c.BestMove)
defer close(c.gi)
stdoutScanner := bufio.NewScanner(stdout)
for stdoutScanner.Scan() {
line := stdoutScanner.Text()
// fmt.Printf("lc0: %s\n", line)
switch {
case strings.HasPrefix(line, "gameready"):
parts := strings.Split(line, " ")
if parts[1] != "trainingfile" ||
parts[3] != "gameid" ||
parts[5] != "player1" ||
parts[7] != "result" ||
parts[9] != "moves" {
log.Printf("Malformed gameready: %q", line)
break
}
file := parts[2]
//gameid := parts[4]
//result := parts[8]
pgn := convertMovesToPGN(parts[10:])
fmt.Printf("PGN: %s\n", pgn)
c.gi <- gameInfo{pgn: pgn, fname: file}
case strings.HasPrefix(line, "bestmove "):
fmt.Println(line)
c.BestMove <- strings.Split(line, " ")[1]
case strings.HasPrefix(line, "id name lczero "):
c.Version = strings.Split(line, " ")[3]
case strings.HasPrefix(line, "info"):
break
fallthrough
default:
fmt.Println(line)
}
}
}()
go func() {
stderrScanner := bufio.NewScanner(stderr)
for stderrScanner.Scan() {
fmt.Printf("%s\n", stderrScanner.Text())
}
}()
if input {
c.openInput()
}
err = c.Cmd.Start()
if err != nil {
log.Fatal(err)
}
}
func playMatch(baselinePath string, candidatePath string, params []string, flip bool) (int, string, string, error) {
baseline := createCmdWrapper()
params = append([]string{"uci"}, params...)
log.Println("launching 1")
baseline.launch(baselinePath, params, true)
defer baseline.Input.Close()
candidate := createCmdWrapper()
log.Println("launching 2")
candidate.launch(candidatePath, params, true)
defer candidate.Input.Close()
p1 := candidate
p2 := baseline
if flip {
p2, p1 = p1, p2
}
log.Println("writign uci")
io.WriteString(baseline.Input, "uci\n")
io.WriteString(candidate.Input, "uci\n")
// Play a game using UCI
var result int
game := chess.NewGame(chess.UseNotation(chess.LongAlgebraicNotation{}))
moveHistory := ""
turn := 0
for {
if turn >= 450 || game.Outcome() != chess.NoOutcome || len(game.EligibleDraws()) > 1 {
if game.Outcome() == chess.WhiteWon {
result = 1
} else if game.Outcome() == chess.BlackWon {
result = -1
} else {
result = 0
}
// Always report the result relative to the candidate engine
// (which defaults to white, unless flip = true)
if flip {
result = -result
}
log.Printf("result: %d\n", result)
break
}
var p *cmdWrapper
if game.Position().Turn() == chess.White {
p = p1
} else {
p = p2
}
io.WriteString(p.Input, "position startpos"+moveHistory+"\n")
io.WriteString(p.Input, "go nodes 800\n")
log.Println("sent go")
select {
case bestMove, ok := <-p.BestMove:
if !ok {
log.Println("engine failed")
p.BestMove = nil
break
}
err := game.MoveStr(bestMove)
if err != nil {
log.Println("Error decoding: " + bestMove + " for game:\n" + game.String())
return 0, "", "", err
}
if len(moveHistory) == 0 {
moveHistory = " moves"
}
moveHistory += " " + bestMove
turn++
case <-time.After(60 * time.Second):
log.Println("Bestmove has timed out, aborting match")
return 0, "", "", errors.New("timeout")
}
}
chess.UseNotation(chess.AlgebraicNotation{})(game)
fmt.Printf("PGN: %s\n", game.String())
return result, game.String(), candidate.Version, nil
}
func train(httpClient *http.Client, ngr client.NextGameResponse,
networkPath string, count int, params []string, doneCh chan bool) {
// pid is intended for use in multi-threaded training
pid := os.Getpid()
dir, _ := os.Getwd()
if *debug {
logsDir := path.Join(dir, fmt.Sprintf("logs-%v", pid))
os.MkdirAll(logsDir, os.ModePerm)
logfile := path.Join(logsDir, fmt.Sprintf("%s.log", time.Now().Format("20060102150405")))
params = append(params, "-l"+logfile)
}
// lc0 needs selfplay first in the argument list.
params = append([]string{"selfplay"}, params...)
params = append(params, "--training=true")
c := createCmdWrapper()
c.Version = "v0.10"
c.launch(networkPath, params /* input= */, false)
for done := false; !done; {
numGames := 1
select {
case <-doneCh:
done = true
log.Println("Received message to end training, killing lc0")
c.Cmd.Process.Kill()
case _, ok := <-c.BestMove:
// Just swallow the best moves, only needed for match play.
if !ok {
log.Printf("BestMove channel closed unexpectedly, exiting train loop")
break
}
case gi, ok := <-c.gi:
if !ok {
log.Printf("GameInfo channel closed, exiting train loop")
done = true
break
}
fmt.Printf("Uploading game: %d\n", numGames)
numGames++
go uploadGame(httpClient, gi.fname, gi.pgn, ngr, c.Version, 0)
}
}
log.Println("Waiting for lc0 to stop")
err := c.Cmd.Wait()
if err != nil {
log.Fatal(err)
}
log.Println("lc0 stopped")
}
func getNetwork(httpClient *http.Client, sha string, clearOld bool) (string, error) {
// Sha already exists?
path := filepath.Join("networks", sha)
if stat, err := os.Stat(path); err == nil {
if stat.Size() != 0 {
return path, nil
}
}
if clearOld {
// Clean out any old networks
os.RemoveAll("networks")
}
os.MkdirAll("networks", os.ModePerm)
fmt.Printf("Downloading network...\n")
// Otherwise, let's download it
err := client.DownloadNetwork(httpClient, *hostname, path, sha)
if err != nil {
log.Printf("Network download failed: %v", err)
return "", err
}
return path, nil
}
func validateParams(args []string) []string {
validArgs := []string{}
for _, arg := range args {
if strings.HasPrefix(arg, "--tempdecay") {
continue
}
validArgs = append(validArgs, arg)
}
return validArgs
}
func nextGame(httpClient *http.Client, count int) error {
nextGame, err := client.NextGame(httpClient, *hostname, getExtraParams())
if err != nil {
return err
}
var serverParams []string
err = json.Unmarshal([]byte(nextGame.Params), &serverParams)
if err != nil {
return err
}
log.Printf("serverParams: %s", serverParams)
serverParams = validateParams(serverParams)
if nextGame.Type == "match" {
log.Println("Starting match")
networkPath, err := getNetwork(httpClient, nextGame.Sha, false)
if err != nil {
return err
}
candidatePath, err := getNetwork(httpClient, nextGame.CandidateSha, false)
if err != nil {
return err
}
log.Println("Starting match")
result, pgn, version, err := playMatch(networkPath, candidatePath, serverParams, nextGame.Flip)
if err != nil {
log.Fatalf("playMatch: %v", err)
return err
}
extraParams := getExtraParams()
extraParams["engineVersion"] = version
log.Println("uploading match result")
go client.UploadMatchResult(httpClient, *hostname, nextGame.MatchGameId, result, pgn, extraParams)
return nil
}
if nextGame.Type == "train" {
networkPath, err := getNetwork(httpClient, nextGame.Sha, true)
if err != nil {
return err
}
doneCh := make(chan bool)
go func() {
errCount := 0
for {
time.Sleep(60 * time.Second)
ng, err := client.NextGame(httpClient, *hostname, getExtraParams())
if err != nil {
fmt.Printf("Error talking to server: %v\n", err)
errCount++
if errCount < 10 {
continue
}
}
if err != nil || ng.Type != nextGame.Type || ng.Sha != nextGame.Sha {
doneCh <- true
close(doneCh)
return
}
errCount = 0
}
}()
train(httpClient, nextGame, networkPath, count, serverParams, doneCh)
//train(httpClient, nextGame, networkPath, count, []string{"--visits=800"}, doneCh)
return nil
}
return errors.New("Unknown game type: " + nextGame.Type)
}
func main() {
flag.Parse()
if len(*user) == 0 || len(*password) == 0 {
*user, *password = readSettings("settings.json")
}
if len(*user) == 0 {
log.Fatal("You must specify a username")
}
if len(*password) == 0 {
log.Fatal("You must specify a non-empty password")
}
httpClient := &http.Client{}
startTime = time.Now()
for i := 0; ; i++ {
err := nextGame(httpClient, i)
if err != nil {
log.Print(err)
log.Print("Sleeping for 30 seconds...")
time.Sleep(30 * time.Second)
continue
}
}
}