예제 #1
0
 def get_leela_board_at(self, movenum=1, halfmoves=0):
     '''Get Leela board at given move number (*prior* to move)
     
     get_leela_board_at(12, 0): This will get the board on the 12th move, at white's turn
     get_leela_board_at(12, 1): This will get the board on the 12th move, at black's turn
     get_leela_board_at(halfmoves=3): This will return the 4th position (after 3 half-moves)
     '''
     halfmoves = 2 * (movenum - 1) + halfmoves
     if halfmoves > len(self.sans):
         raise Exception('Not that many moves in game')
     board = LeelaBoard()
     for idx, san in enumerate(self.sans):
         if idx < halfmoves:
             board.push_san(san)
     return board
예제 #2
0
class ClientTask(threading.Thread):
    """ClientTask"""
    def __init__(self, id):
        self.id = id
        threading.Thread.__init__(self)
        self.board = LeelaBoard()
        self.board.push_uci('d2d4')

    def run(self):
        context = zmq.Context()
        socket = context.socket(zmq.DEALER)
        identity = u'client-%d' % self.id
        socket.identity = identity.encode('ascii')
        socket.connect('ipc:///tmp/lcztools/network_0')
        socket.send(bytes([1]))  # Hi message
        socket.recv()
        message = self.board.serialize_features()
        for _ in range(20000):
            # print("Client {} sending message".format(identity))
            # message = self.board.serialize_features()
            for _ in range(32):
                socket.send(message)
                # print("Send:", self.id)

            for _ in range(32):
                response = memoryview(socket.recv())
                # print("Response:", self.id)
                # print ("Client {} received message of length {}".format(identity, len(response)))
                if len(response) == 7436:  # single precision
                    value = np.frombuffer(response[:4], dtype=np.float32)
                    policy = np.frombuffer(response[4:], dtype=np.float32)
                elif len(response) == 3718:  # half precision
                    value = np.frombuffer(response[:2], dtype=np.float16)
                    policy = np.frombuffer(response[2:], dtype=np.float16)
                # time.sleep(0.5)
        socket.close()
        context.term()
예제 #3
0
def process_position(tokens):
    board = LeelaBoard()

    offset = 0

    if tokens[1] == 'startpos':
        offset = 2
    elif tokens[1] == 'fen':
        fen = " ".join(tokens[2:8])
        board = LeelaBoard(fen=fen)
        offset = 8

    if offset >= len(tokens):
        return board

    if tokens[offset] == 'moves':
        for i in range(offset + 1, len(tokens)):
            board.push_uci(tokens[i])

    return board
예제 #4
0
                    default=default_engine)
parser.add_argument("-n",
                    "--nodes",
                    help="the engine to use for black",
                    type=int,
                    default=800)
parser.add_argument("-v", "--verbosity", action="count", default=0)
args = parser.parse_args()

backend = 'pytorch_cuda' if os.path.exists(
    '/opt/bin/nvidia-smi') else 'pytorch_cpu'
net = load_network(backend=backend,
                   filename=args.weights,
                   policy_softmax_temp=2.2)
nn = search.NeuralNet(net=net)
board = LeelaBoard()

players = [{
    'engine': args.white,
    'root': None,
    'resets': 0
}, {
    'engine': args.black,
    'root': None,
    'resets': 0
}]

turn = 0
while True:
    print(board)
    if players[turn] == "human":
예제 #5
0
if len(sys.argv) != 4:
    print("Usage: python3 engine.py <policy> <weights file> <nodes>")
    print(len(sys.argv))
    exit(1)

policy = sys.argv[1]
weights = sys.argv[2]
nodes = int(sys.argv[3])

backend = 'pytorch_cuda' if path.exists(
    '/opt/bin/nvidia-smi') else 'pytorch_cpu'
net = load_network(backend=backend, filename=weights, policy_softmax_temp=2.2)
nn = search.NeuralNet(net=net)

send("Leela Lite")
board = LeelaBoard()

while True:
    line = sys.stdin.readline()
    line = line.rstrip()
    log("<{}".format(line))
    tokens = line.split()
    if len(tokens) == 0:
        continue
    if tokens[0] == "uci":
        send('id name Leela Lite')
        send('id author Dietrich Kappe')
        send(
            'option name List of Syzygy tablebase directories type string default'
        )
        send('uciok')
예제 #6
0

def load_leela_network():
    global net, nn
    if network_id is not None:
        net = load_network(backend='net_client', network_id=network_id)
    else:
        net = load_network(backend='pytorch_cuda', filename=weights)
    nn = search.NeuralNet(net=net, lru_size=min(5000, nodes))


load_leela_network()

SELFPLAY = True

board = LeelaBoard()
while True:
    if not SELFPLAY:
        print(board.unicode())
        print("Enter move: ", end='')
        sys.stdout.flush()
        line = sys.stdin.readline()
        line = line.rstrip()
        board.push_uci(line)
    print(board.unicode())
    print("thinking...")
    start = time.time()
    best, node = search.UCT_search(board, nodes, net=nn, C=3.4)
    elapsed = time.time() - start
    print("best: ", best)
    print("Time: {:.3f} nps".format(nodes / elapsed))
예제 #7
0
import chess.pgn
import io
import pickle
import sys

# with shelve.open('web_pgn_data.shelf') as s:
#     df_matches = s['df_matches']
#     match_dfs = s['match_dfs']
#     df_pgn = s['df_pgn']

with open('web_pgn.data', 'rb') as f:
    df_matches, match_dfs, df_pgn = pickle.load(f)


for i, (idx, row) in enumerate(df_pgn.iterrows(), 1):
    lcz_board = LeelaBoard()
    pgn_game = chess.pgn.read_game(io.StringIO(row.pgn))
    moves = [move for move in pgn_game.main_line()]
    compressed = []
    features = lcz_board.lcz_features()
    compressed.append(lcz_board.compress_features(features))
    for move in moves[:-1]:
        # print(move)
        lcz_board.push(move)
        features = lcz_board.lcz_features()
        compressed_features = lcz_board.compress_features(features)
        compressed.append(compressed_features)
        # assert(check_compressed_features(lcz_board, compressed_features))
    training_game = (compressed, pgn_game.headers['Result'], row.pgn)
    with open(f'./training_data/match_game_{idx}.data', 'wb') as f:
        f.write(pickle.dumps(training_game))
예제 #8
0
 def leela_board(self):
     board = LeelaBoard()
     for san in self.sans:
         board.push_san(san)
     return board
예제 #9
0
 def __init__(self, id):
     self.id = id
     threading.Thread.__init__(self)
     self.board = LeelaBoard()
     self.board.push_uci('d2d4')