# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # OpenBench is a chess engine testing framework by Andrew Grant. # # # # # # OpenBench is free software: you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # OpenBench is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see . # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # import argparse import cpuinfo import json import multiprocessing import os import platform import psutil import queue import re import requests import subprocess import sys import threading import time import traceback import uuid import zipfile from subprocess import PIPE, Popen, call, STDOUT from itertools import combinations_with_replacement from concurrent.futures import ThreadPoolExecutor ## Local imports import bench from client import BadVersionException from client import url_join from client import try_forever from utils import * from pgn_util import compress_list_of_pgns ## Basic configuration of the Client. These timeouts can be changed at will CLIENT_VERSION = 26 # Client version to send to the Server TIMEOUT_HTTP = 30 # Timeout in seconds for HTTP requests TIMEOUT_ERROR = 10 # Timeout in seconds when any errors are thrown TIMEOUT_WORKLOAD = 30 # Timeout in seconds between workload requests REPORT_INTERVAL = 30 # Seconds between reports to the Server IS_WINDOWS = platform.system() == 'Windows' # Don't touch this IS_LINUX = platform.system() != 'Windows' # Don't touch this class Configuration: ## Handles configuring the worker with the server. This means collecting ## information about the system, as well as holding any of the command line ## arguments provided. Lastly, a Configuration() object holds the Workload def __init__(self, args): # Basic init of every piece of System specific information self.compilers = {} self.git_tokens = {} self.cpu_flags = [] self.cpu_name = '' self.os_name = platform.system() self.os_ver = platform.release() self.python_ver = platform.python_version() self.mac_address = hex(uuid.getnode()).upper()[2:] self.logical_cores = psutil.cpu_count(logical=True) self.physical_cores = psutil.cpu_count(logical=False) self.ram_total_mb = psutil.virtual_memory().total // (1024 ** 2) self.machine_name = 'None' self.machine_id = 'None' self.secret_token = 'None' self.syzygy_max = 2 self.process_args(args) # Rest of the command line settings self.init_client() # Create folder structure and verify Syzygy self.validate_setup() # Check the threads and sockets values provided def process_args(self, args): # Extract all of the options self.username = args.username self.password = args.password self.server = args.server self.threads = int(args.threads) self.sockets = int(args.nsockets) self.identity = args.identity if args.identity else 'None' self.syzygy_path = args.syzygy if args.syzygy else None self.fleet = args.fleet if args.fleet else False self.focus = args.focus if args.focus else [] def init_client(self): # Verify that we have make installed print('\nLooking for Make... [v%s]' % locate_utility('make')) # Use Client.py's path as the base pathway os.chdir(os.path.dirname(os.path.abspath(__file__))) # Ensure the folder structure for ease of coding for folder in ['PGNs', 'Engines', 'Networks', 'Books']: if not os.path.isdir(folder): os.mkdir(folder) # Check until we stop finding valid N-man tables if self.syzygy_path: while validate_syzygy_exists(self, self.syzygy_max+1): self.syzygy_max = self.syzygy_max + 1 # 1-man and 2-man tables are not a thing if self.syzygy_max < 3: self.syzygy_max = 0 # Report highest complete depth that we found print('Looking for Syzygy... [%d-Man]' % (self.syzygy_max)) def validate_setup(self): assert self.threads >= self.sockets assert self.threads % self.sockets == 0 assert min(self.threads, self.sockets) >= 1 def scan_for_compilers(self, data): print ('\nScanning for Compilers...') # For each engine, attempt to find a valid compiler for engine, build_info in data.items(): # Private engines don't need to be compiled if build_info['private']: continue # Try to find at least one working compiler for compiler in build_info['compilers']: # Compilers may require a specific version if '>=' in compiler: compiler, version = compiler.split('>=') version = tuple(map(int, version.split('.'))) else: version = (0, 0, 0) # Try to confirm this compiler is present, and new enough try: match = get_version(compiler) if tuple(map(int, match.split('.'))) >= version: print('%-16s | %-8s (%s)' % (engine, compiler, match)) self.compilers[engine] = (compiler, match) break except: continue # Unable to execute compiler # Report missing engines in case the User is not expecting it if engine not in self.compilers: print('%-16s | Missing %s' % (engine, data[engine]['compilers'])) def scan_for_private_tokens(self, data): print ('\nScanning for Private Tokens...') # For each engine, attempt to find a valid compiler for engine, build_info in data.items(): # Public engines don't need access tokens if not build_info['private']: continue # Private engines expect a credentials.engine file for the main repo has_token = os.path.exists('credentials.%s' % (engine.replace(' ', '').lower())) print('%-16s | %s' % (engine, ['Missing', 'Found'][has_token])) if has_token: self.git_tokens[engine] = True def scan_for_cpu_flags(self, data): print('\nScanning for CPU Flags...') # Get all flags, and for sanity uppercase them info = cpuinfo.get_cpu_info() actual = [x.replace("_", "").replace(".", "").upper() for x in info.get('flags', [])] # Set the CPU name which has to be done via global self.cpu_name = info.get('brand_raw', info.get('brand', 'Unknown')) # This should cover virtually all compiler flags that we would care about desired = ['POPCNT', 'BMI2'] desired += ['SSSE3', 'SSE41', 'SSE42', 'SSE4A', 'AVX', 'AVX2', 'FMA'] desired += ['AVX512VNNI', 'AVX512BW', 'AVX512DQ', 'AVX512F'] # Add any custom flags from the OpenBench configs, just in case we missed one requested = set(sum([info['cpuflags'] for engine, info in data.items()], [])) for flag in [x for x in requested if x not in desired]: desired.append(flag) self.cpu_flags = [x for x in desired if x in actual] # Report the results of our search, including any "missing flags print ('Found |', ' '.join(self.cpu_flags)) print ('Missing |', ' '.join([x for x in desired if x not in actual])) def scan_for_machine_id(self): if os.path.isfile('machine.txt'): with open('machine.txt') as fin: self.machine_id = fin.readlines()[0] class ServerReporter: ## Handles reporting things to the server, which are not intended to send a great ## deal of information back. Reports to the server can hit various endpoints, with ## differing payloads. Payloads must always include the machine id, and secret token @staticmethod def report(config, endpoint, payload, files=None): payload['machine_id'] = config.machine_id payload['secret'] = config.secret_token target = url_join(config.server, endpoint) response = requests.post(target, data=payload, files=files, timeout=TIMEOUT_HTTP) # Check for a json repsone, to look for Client Version Errors try: as_json = response.json() except: return response # Throw all the way back to the client.py if 'Bad Client Version' in as_json.get('error', ''): raise BadVersionException() return response @staticmethod def report_nps(config, dev_nps, base_nps): payload = { 'nps' : (dev_nps + base_nps) // 2, 'dev_nps' : int(dev_nps), 'base_nps' : int(base_nps), } return ServerReporter.report(config, 'clientSubmitNPS', payload) @staticmethod def report_missing_artifact(config, artifact_name, artifact_json): payload = { 'test_id' : config.workload['test']['id'], 'error' : 'Artifact %s missing' % (artifact_name), 'logs' : json.dumps(artifact_json, indent=2), } return ServerReporter.report(config, 'clientSubmitError', payload) @staticmethod def report_build_fail(config, branch, output): branch_name = config.workload['test'][branch]['name'] engine_name = config.workload['test'][branch]['engine'] final_name = '[%s] %s' % (engine_name, branch_name) payload = { 'test_id' : config.workload['test']['id'], 'error' : '%s build failed' % (final_name), 'logs' : output, } return ServerReporter.report(config, 'clientSubmitError', payload) @staticmethod def report_engine_error(config, error, pgn): payload = { 'test_id' : config.workload['test']['id'], 'error' : error, 'logs' : pgn, } return ServerReporter.report(config, 'clientSubmitError', payload) @staticmethod def report_bad_bench(config, error): payload = { 'test_id' : config.workload['test']['id'], 'error' : error, } return ServerReporter.report(config, 'clientBenchError', payload) @staticmethod def report_results(config, batches): payload = { 'test_id' : config.workload['test']['id'], 'result_id' : config.workload['result']['id'], 'trinomial' : [0, 0, 0], # LDW 'pentanomial' : [0, 0, 0, 0, 0], # LL DL DD DW WW 'crashes' : 0, # " disconnect" or "connection stalls" 'timelosses' : 0, # " loses on time " 'illegals' : 0, # " illegal move " } for batch in batches: payload['trinomial' ] = [x+y for x,y in zip(payload['trinomial' ], batch['trinomial' ])] payload['pentanomial'] = [x+y for x,y in zip(payload['pentanomial'], batch['pentanomial'])] payload['crashes' ] += batch['crashes' ] payload['timelosses'] += batch['timelosses'] payload['illegals' ] += batch['illegals' ] if config.workload['test']['type'] == 'SPSA': # Pairs can be added one at a time, or in bulk result = batch['trinomial'][2] - batch['trinomial'][0] # For each param compute the update step for the Server for name, param in config.workload['spsa'].items(): delta = param['r'] * param['c'] * result * param['flip'][batch['cutechess_idx']] payload['spsa_%s' % (name)] = payload.get('spsa_%s' % (name), 0.0) + delta # Collapse into a JSON friendly format for Django payload['trinomial' ] = ' '.join(map(str, payload['trinomial' ])) payload['pentanomial'] = ' '.join(map(str, payload['pentanomial'])) print (payload) return ServerReporter.report(config, 'clientSubmitResults', payload) @staticmethod def report_heartbeat(config): payload = { 'test_id' : config.workload['test']['id'] } return ServerReporter.report(config, 'clientHeartbeat', payload) @staticmethod def report_pgn(config, compressed_pgn_text): payload = { 'test_id' : config.workload['test']['id'], 'result_id' : config.workload['result']['id'], 'book_index' : config.workload['test']['book_index'], 'Content-Type' : 'application/octet-stream', } files = { 'file' : ('games.pgn', compressed_pgn_text) } return ServerReporter.report(config, 'clientSubmitPGN', payload, files) class Cutechess: ## Handles building the very long string of arguments that need to be passed ## to cutechess in order to launch a set of games. Operates on the Configuration, ## and a small number of secondary arguments that are not housed in the Configuration @staticmethod def basic_settings(config): # Assume Fischer if FRC, 960, or FISCHER appears in the Opening Book book_name = config.workload['test']['book']['name'].upper() is_frc = 'FRC' in book_name or '960' in book_name or 'FISCHER' in book_name variant = ['standard', 'fischerandom'][is_frc] # Always include -repeat and -recover return '-repeat -recover -variant %s' % (variant) @staticmethod def concurrency_settings(config): # Already computed for us by the Server return '-concurrency %d -games %d' % ( config.workload['distribution']['concurrency-per'], config.workload['distribution']['games-per-cutechess'], ) @staticmethod def adjudication_settings(config): # All three possible adjudication settings win_adj = config.workload['test']['win_adj' ] draw_adj = config.workload['test']['draw_adj' ] syzygy_adj = config.workload['test']['syzygy_adj'] # Empty, unless specified in the settings win_flags = ['', '-resign ' + win_adj ][win_adj != 'None'] draw_flags = ['', '-draw ' + draw_adj][draw_adj != 'None'] syzygy_flags = '' # Set the tb path if we have them, and are allowed to use them if syzygy_adj != 'DISABLED' and config.syzygy_max: syzygy_flags = '-tb %s' % (config.syzygy_path.replace('\\', '\\\\')) # We would only get a test we can do; specify a limit if needed if syzygy_adj != 'DISABLED' and syzygy_adj != 'OPTIONAL': syzygy_flags += ' -tbpieces %s' % (syzygy_adj.split('-')[0]) return '%s %s %s' % (win_flags, draw_flags, syzygy_flags) @staticmethod def book_settings(config, cutechess_idx): # Can handle EPD and PGN Books, which must be specified book_name = config.workload['test']['book']['name'] book_suffix = book_name.split('.')[-1] # Start position is determined partially by cutechess index pairs = config.workload['distribution']['games-per-cutechess'] // 2 start = config.workload['test']['book_index'] + cutechess_idx * pairs return '-openings file=Books/%s format=%s order=random start=%d -srand %d' % ( book_name, book_suffix, start, config.workload['test']['book_seed']) @staticmethod def engine_settings(config, command, branch, scale_factor, cutechess_idx): # Extract configuration from the Workload options = config.workload['test'][branch]['options'] network = config.workload['test'][branch]['network'] private = config.workload['test'][branch]['private'] engine = config.workload['test'][branch]['engine'] syzygy = config.workload['test']['syzygy_wdl'] # Human-readable name, and scale the time control name = command.replace('.exe', '') control = scale_time_control(config.workload, scale_factor, branch) # Private engines, when using Networks, must set them via UCI if private and network and network != 'None': options += ' EvalFile=%s' % (os.path.join('../Networks', network)) name += '-%s' % (network) # Set the SyzygyPath if we have them, and are allowed to use them if syzygy != 'DISABLED' and config.syzygy_max: options += ' SyzygyPath=%s' % (config.syzygy_path.replace('\\', '\\\\')) # Set a SyzygyProbeLimit if we may only use up-to N-Man if syzygy != 'DISABLED' and syzygy != 'OPTIONAL': options += ' SyzygyProbeLimit=%s' % (syzygy.split('-')[0]) # Add any of the custom SPSA settings if config.workload['test']['type'] == 'SPSA': for param, data in config.workload['spsa'].items(): options += ' %s=%s' % (param, str(data[branch][cutechess_idx])) # Join options together in the Cutechess format options = ' option.'.join([''] + re.findall(r'"[^"]*"|\S+', options)) return '-engine dir=Engines/ cmd=./%s proto=uci %s%s name=%s-%s' % (command, control, options, engine, branch) @staticmethod def pgnout_settings(config, timestamp, cutechess_idx): return '-pgnout %s' % (Cutechess.pgn_name(config, timestamp, cutechess_idx)) @staticmethod def update_results(results, line): # Given any game #, find the other in the pair def game_to_pair(g): return (g, g+1) if g % 2 else (g-1, g) # Find the Pentanomial index given a game pair def pair_to_penta(r1, r2): lookup = { '0-1' : 0, '1/2-1/2' : 1, '1-0' : 2 } return lookup[r1] + 2 - lookup[r2] # Find the Trinomial indices, from our POV, for a give game pair def pair_to_trinomial(r1, r2): lookup = { '0-1' : 0, '1/2-1/2' : 1, '1-0' : 2 } return lookup[r1], 2 - lookup[r2] # Extract the game # and result str from a Cutechess line def parse_finished_game(line): tokens = line.split() return int(tokens[2]), tokens[6] # Parse for errors resulting in adjudication reason = line.split(':')[1] results['crashes' ] += 'disconnect' in reason or 'stalls' in reason results['timelosses'] += 'on time' in reason results['illegals' ] += 'illegal' in reason # Parse Game # and result, and save game, result = parse_finished_game(line) results['games'][game] = result # Check to see if the Pair has finished first, second = game_to_pair(game) if first not in results['games'] or second not in results['games']: return # Get the indices for the Pentanomial, and the two for Trinomial p = pair_to_penta(results['games'][first], results['games'][second]) t1, t2 = pair_to_trinomial(results['games'][first], results['games'][second]) # Update everything results['trinomial' ][t1] += 1 results['trinomial' ][t2] += 1 results['pentanomial'][p ] += 1 # Clean up results['games'] del results['games'][first] del results['games'][second] @staticmethod def kill_everything(dev_process, base_process): if IS_LINUX: subprocess.run(['pkill', '-f', 'cutechess-ob']) subprocess.run(['pkill', '-f', dev_process]) subprocess.run(['pkill', '-f', base_process]) if IS_WINDOWS: subprocess.run(['taskkill', '/f', '/im', 'cutechess-ob.exe']) subprocess.run(['taskkill', '/f', '/im', dev_process]) subprocess.run(['taskkill', '/f', '/im', base_process]) @staticmethod def pgn_name(config, timestamp, cutechess_idx): test_id = int(config.workload['test']['id']) result_id = int(config.workload['result']['id']) # Format: --