diff --git a/Client/Client.py b/Client/Client.py index 323768b..d6b4042 100644 --- a/Client/Client.py +++ b/Client/Client.py @@ -37,59 +37,455 @@ import zipfile from subprocess import PIPE, Popen, call, STDOUT from itertools import combinations_with_replacement +from concurrent.futures import ThreadPoolExecutor -# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # -# # -# Configuration for the Client. To disable deleting old files, use the # -# value None. If Syzygy Tablebases are not present, set to None. # -# # -# Each engine allows a custom set of arguments. All engines will compile # -# without any custom options. However you have the ability to add args # -# in order to get better builds, like PGO or PEXT/BMI2. # -# # -# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +## Basic configuration of the Client. These timeouts can be changed at will -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 -CLIENT_VERSION = '9' # 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 +CLIENT_VERSION = '10' # Client version to send to the Server -SYZYGY_WDL_PATH = None # Pathway to WDL Syzygy Tables -FLEET_MODE = False # Exit when there are no workloads +IS_WINDOWS = platform.system() == 'Windows' # Don't touch this +IS_LINUX = platform.system() != 'Windows' # Don't touch this -ERRORS = { - 'cutechess' : 'Unable to fetch Cutechess location and download it!', - 'configure' : 'Unable to fetch and determine acceptable workloads!', - 'request' : 'Unable to reach server for workload request!', -} +class Configuration(object): -# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # -# # -# Setting up the Client. Build the OpenBench file structure, check for # -# Syzygy Tables for both WDL (Adjudication, and Gameplay). Download a # -# static Cutechess binary, and determine what engines we are able to # -# compile by asking the server for compiler and CPU Flag requirements # -# # -# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + ## 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 -# Differentiate Windows and Linux systems -IS_WINDOWS = platform.system() == 'Windows' -IS_LINUX = platform.system() != 'Windows' + def __init__(self): + + # 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.parse_arguments() # 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 parse_arguments(self): + + # We can use ENV variables for the Username and Passwords + req_user = required=('OPENBENCH_USERNAME' not in os.environ) + req_pass = required=('OPENBENCH_PASSWORD' not in os.environ) + help_user = 'Username. May also be passed as OPENBENCH_USERNAME environment variable' + help_pass = 'Password. May also be passed as OPENBENCH_PASSWORD environment variable' + + # Create and parse all arguments into a raw format + p = argparse.ArgumentParser() + p.add_argument('-U', '--username' , help=help_user , required=req_user ) + p.add_argument('-P', '--password' , help=help_pass , required=req_pass ) + p.add_argument('-S', '--server' , help='Webserver Address' , required=True ) + p.add_argument('-T', '--threads' , help='Total Threads' , required=True ) + p.add_argument('-N', '--nsockets' , help='Number of Sockets' , required=True ) + p.add_argument('-I', '--identity' , help='Machine pseudonym' , required=False ) + p.add_argument( '--syzygy' , help='Syzygy WDL' , required=False ) + p.add_argument( '--fleet' , help='Fleet Mode' , action='store_true') + p.add_argument( '--proxy' , help='Github Proxy' , action='store_true') + args = p.parse_args() + + # Extract all of the options + self.username = args.username if args.username else os.environ['OPENBENCH_USERNAME'] + self.password = args.password if args.password else os.environ['OPENBENCH_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.proxy = args.proxy if args.proxy else False + + 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.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', 'SSE4_1', 'SSE4_2', 'SSE4A', 'AVX', 'AVX2', 'FMA'] + desired += ['AVX512_VNNI', '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] + + def choose_best_artifact(self, options): + + # Step 1. Filter down to our operating system only + options = [x for x in options if x.split('-')[1] == self.os_name.lower()] + + # Pick betwen various Vector instruction sets that might apply + has_ssse3 = all(x in self.cpu_flags for x in ['SSSE3']) + has_sse4 = has_ssse3 and all(x in self.cpu_flags for x in ['SSE4_1', 'SSE4_2']) + has_avx = has_sse4 and all(x in self.cpu_flags for x in ['AVX']) + has_avx2 = has_avx and all(x in self.cpu_flags for x in ['AVX2', 'FMA']) + has_avx512 = has_avx2 and all(x in self.cpu_flags for x in ['AVX512BW', 'AVX512DQ', 'AVX512F']) + has_vnni = has_avx512 and all(x in self.cpu_flags for x in ['AVX512_VNNI']) + + # Filtering system, where we remove everything but the strongest that is available + selection = [ + (has_vnni , 'vnni' ), (has_avx512, 'avx512'), (has_avx2 , 'avx2' ), + (has_avx , 'avx' ), (has_sse4 , 'sse4' ), (has_ssse3 , 'ssse3' ), + ] + + # Step 2. Filter everything but the best Vector instruction set that was available + for boolean, identifier in selection: + if boolean and identifier in [x.split('-')[2] for x in options]: + options = [x for x in options if x.split('-')[2] == identifier] + break + + # Identify any Ryzen or AMD chip, excluding the 7B12 + ryzen = 'AMD' in self.cpu_name.upper() + ryzen = 'RYZEN' in self.cpu_name.upper() or ryzen + ryzen = ryzen and '7B12' not in self.cpu_name.upper() + + # Pick between POPCNT and BMI2/PEXT + has_popcnt = 'POPCNT' in self.cpu_flags + has_bmi2 = 'BMI2' in self.cpu_flags and not ryzen + + # Filtering system, where we remove everything but the strongest that is available + selection = [ (has_bmi2, 'pext'), (has_popcnt, 'popcnt') ] + + # Step 3. Filter everything but the best bitop instruction set that was available + for boolean, identifier in selection: + if boolean and identifier in [x.split('-')[3] for x in options]: + options = [x for x in options if x.split('-')[3] == identifier] + break + + return options[0] + +class ServerReporter(object): + + ## 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): + payload['machine_id'] = config.machine_id + payload['secret'] = config.secret_token + target = url_join(config.server, endpoint) + return requests.post(target, data=payload, timeout=TIMEOUT_HTTP) + + @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' : compiler_output, + } + + return ServerReporter.report(config, 'clientSubmitError', payload) + + @staticmethod + def report_engine_error(config, cutechess_str, pgn): + + white, black = cutechess_str.split('(')[1].split(')')[0].split(' vs ') + + error = cutechess_str.split('{')[1].rstrip().rstrip('}') + error = error.replace('White', '-'.join(white.split('-')[1:]).rstrip()) + error = error.replace('Black', '-'.join(black.split('-')[1:]).rstrip()) + + payload = { + 'test_id' : config.workload['test']['id'], + 'error' : error, + 'logs' : pgn, + } + + return ServerReporter.report(config, 'clientSubmitError', payload) + + @staticmethod + def report_bad_bench(config, branch, bench): + + payload = { + 'test_id' : config.workload['test']['id'], + 'engine' : config.workload['test'][branch]['name'], + 'correct' : config.workload['test'][branch]['bench'], + 'wrong' : bench, + } + + return ServerReporter.report(config, 'clientWrongBench', payload) + + @staticmethod + def report_results(config, stats): + + wins, losses, draws, crashes, timelosses = stats + + payload = { + 'test_id' : config.workload['test']['id'], + 'result_id' : config.workload['result']['id'], + 'wins' : wins, + 'losses' : losses, + 'draws' : draws, + 'crashes' : crashes, + 'timeloss' : timelosses, + } + + return ServerReporter.report(config, 'clientSubmitResults', payload) + +class Cutechess(object): + + ## 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, socket): + + # Book seed, with an offset between concurrent Cutechesses + seed = time.time() + socket + + # 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 -srand %d -variant %s' % (seed, variant) + + @staticmethod + def concurrency_settings(config): + + # Extract # of Threads for the dev engine + dev_options = config.workload['test']['dev' ]['options'] + dev_threads = int(extract_option(dev_options, 'Threads')) + + # Extract # of Threads for the base engine + base_options = config.workload['test']['base']['options'] + base_threads = int(extract_option(base_options, 'Threads')) + + # Number of concurrency games that this socket can play + concurrency = config.threads / config.sockets + concurrency = concurrency // max(dev_threads, base_threads) + + # Play at least a single game-pair per concurrency + games = int(concurrency * config.workload['test']['workload_size']) + games = max(concurrency * 2, games - (games % (2 * concurrency))) + + return '-concurrency %d -games %d' % (concurrency, games) + + @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): + + # Can handle EPD and PGN Books, which must be specified + book_name = config.workload['test']['book']['name'] + book_suffix = book_name.split('.')[-1] + return '-openings file=Books/%s format=%s order=random plies=16' % (book_name, book_suffix) + + @staticmethod + def engine_settings(config, command, branch, nps): + + # Extract configuration from the Workload + options = config.workload['test'][branch]['options'] + network = config.workload['test'][branch]['network'] + private = config.workload['test'][branch]['private'] + syzygy = config.workload['test']['syzygy_wdl'] + + # Human-readable name, and scale the time control + name = command.removesuffix('.exe') + control = scale_time_control(config.workload, nps, 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]) + + # 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' % (command, control, options, name) + + @staticmethod + def pgnout_settings(config, dev_cmd, base_cmd, socket): + + # Extract Network names + dev_network = config.workload['test']['dev' ]['network'] + base_network = config.workload['test']['base']['network'] + + # Extract private status + dev_private = config.workload['test']['dev' ]['private'] + base_private = config.workload['test']['base']['private'] + + # Append Network name for private engines + dev_name = dev_cmd.removesuffix('.exe') + if dev_private and dev_network and dev_network != 'None': + dev_name += '-%s' % (dev_network) + + # Append Network name for private engines + base_name = base_cmd.removesuffix('.exe') + if base_private and base_network and base_network != 'None': + base_name += '-%s' % (base_network) + + # Tack the socket number onto the end to distinguish the PGNs + return '-pgnout PGNs/%s_vs_%s.%d' % (dev_name, base_name, socket) -SYSTEM_COMPILERS = {} -SYSTEM_GIT_TOKENS = {} -SYSTEM_CPU_FLAGS = [] -SYSTEM_CPU_NAME = '' -SYSTEM_OS_NAME = platform.system() -SYSTEM_OS_VER = platform.release() -SYSTEM_PYTHON_VER = platform.python_version() -SYSTEM_MAC_ADDRESS = hex(uuid.getnode()).upper()[2:] -SYSTEM_LOGICAL_CORES = psutil.cpu_count(logical=True) -SYSTEM_PHYSICAL_CORES = psutil.cpu_count(logical=False) -SYSTEM_RAM_TOTAL_MB = psutil.virtual_memory().total // (1024 ** 2) -SYSTEM_MACHINE_NAME = 'None' -SYSTEM_MACHINE_ID = 'None' -SYSTEM_SECRET_TOKEN = 'None' def get_version(program): @@ -108,124 +504,12 @@ def get_version(program): def locate_utility(util, force_exit=True, report_error=True): - try: - return get_version(util) + try: return get_version(util) except Exception: + if report_error: print('[Error] Unable to locate %s' % (util)) + if force_exit: sys.exit() - if report_error: - print('[Error] Unable to locate %s' % (util)) - - if force_exit: - sys.exit() - - return False - - -def scan_for_compilers(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 'artifacts' in build_info: 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)) - SYSTEM_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 SYSTEM_COMPILERS: - print('%-16s | Missing %s' % (engine, data[engine]['compilers'])) - -def scan_for_private_tokens(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 'artifacts' in build_info: 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: SYSTEM_GIT_TOKENS[engine] = True - -def scan_for_cpu_flags(data): - - print('\nScanning for CPU Flags...') - - # Get all flags, and for sanity uppercase them - info = cpuinfo.get_cpu_info() - actual = [x.upper() for x in info['flags']] - - # Set the CPU name which has to be done via global - global SYSTEM_CPU_NAME, SYSTEM_CPU_FLAGS - SYSTEM_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', 'SSE4_1', 'SSE4_2', 'SSE4A', 'AVX', 'AVX2', 'FMA'] - desired += ['AVX512_VNNI', 'AVX512BW', 'AVX512CD', '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) - SYSTEM_CPU_FLAGS = [x for x in desired if x in actual] - - # Report the results of our search, including any "missing flags - print ('Found |', ' '.join(SYSTEM_CPU_FLAGS)) - print ('Missing |', ' '.join([x for x in desired if x not in actual])) - -def scan_for_machine_id(): - - # If we don't have one, the server will give us one, and then include it - # in future HTTP responses. We simply need to save the a .txt file, later - - global SYSTEM_MACHINE_ID - - if os.path.isfile('machine.txt'): - with open('machine.txt') as fin: - SYSTEM_MACHINE_ID = fin.readlines()[0] - - if SYSTEM_MACHINE_ID == 'None': - print('[NOTE] This machine is currently unregistered') - - -def init_client(arguments): - - # Verify that we have make installed - print('\nScanning For Basic Utilities...') - 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) - - # Verify all WDL tables are present when told they are - validate_syzygy_exists() def cleanup_client(): @@ -247,28 +531,7 @@ def cleanup_client(): if file_age(os.path.join('Networks', file)) > SECONDS_PER_MONTH: os.remove(os.path.join('Networks', file)) -def validate_syzygy_exists(): - - global SYZYGY_WDL_PATH - - print('\nScanning for Syzygy Configuration...') - - for filename in tablebase_names(): - - # Build the paths when the configuration enables Syzygy - if SYZYGY_WDL_PATH: - wdlpath = os.path.join(SYZYGY_WDL_PATH, filename + '.rtbw') - - # Reset the configuration if the file is missing - if SYZYGY_WDL_PATH and not os.path.isfile(wdlpath): - SYZYGY_WDL_PATH = None - - # Report final results, which may conflict with the original configuration - if SYZYGY_WDL_PATH: - print('Verified Syzygy WDL (%s)' % (SYZYGY_WDL_PATH)) - else: print('Syzygy WDL Not Found') - -def tablebase_names(K=6): +def validate_syzygy_exists(config, K): letters = ['', 'Q', 'R', 'B', 'N', 'P'] @@ -285,7 +548,37 @@ def tablebase_names(K=6): lhs, rhs = name.replace('K', '9').split('v') return int(lhs) >= int(rhs) and name != 'KvK' - return list(filter(valid_filename, set(candidates))) + # See if file exists in (any of) the paths + def has_filename(paths, name): + for path in paths: + if os.path.isfile(os.path.join(path, name + '.rtbw')): + return True + return False + + # Split paths, using ":" on Unix, and ";" on Windows + paths = config.syzygy_path.split(':' if IS_LINUX else ';') + + # Check to see if each Syzygy File exists as desired + for filename in list(filter(valid_filename, set(candidates))): + if not has_filename(paths, filename): + return False + + return True + +def try_forever(func, args, message): + + while True: + try: + return func(*args) + + except Exception as exception: + print ('\n\n' + message) + print ('[Note] Sleeping for %d seconds' % (TIMEOUT_ERROR)) + print ('[Note] Traceback:') + traceback.print_exc() + print () + + time.sleep(TIMEOUT_ERROR) def url_join(*args): @@ -293,19 +586,6 @@ def url_join(*args): # Join a set of URL paths while maintaining the correct format return '/'.join([f.lstrip('/').rstrip('/') for f in args]) + '/' -def try_until_success(mesg): - def _try_until_success(funct): - def __try_until_success(*args): - while True: - try: return funct(*args) - except Exception: - print('[Error]', mesg); - if FLEET_MODE: sys.exit() - time.sleep(TIMEOUT_ERROR) - traceback.print_exc() - return __try_until_success - return _try_until_success - def download_file(source, outname, post_data=None, headers=None): arguments = { 'stream' : True, 'timeout' : TIMEOUT_ERROR, 'headers' : headers } @@ -324,13 +604,25 @@ def unzip_delete_file(source, outdir): os.remove(source) -def make_command(arguments, engine, src_path, network_path): +def extract_option(options, option): - command = 'make %s=%s EXE=%s -j%d' % ( - ['CC', 'CXX']['++' in SYSTEM_COMPILERS[engine][0]], SYSTEM_COMPILERS[engine][0], engine, arguments.threads) + match = re.search('(?<={0}=")[^"]*'.format(option), options) + if match: return match.group() + + match = re.search('(?<={0}=\')[^\']*'.format(option), options) + if match: return match.group() + + match = re.search('(?<={0}=)[^ ]*'.format(option), options) + if match: return match.group() + +def make_command(config, engine, src_path, network_path): + + compiler = config.compilers[engine][0] + comp_flag = ['CC', 'CXX']['++' in compiler] + command = 'make %s=%s EXE=%s -j%d' % (comp_flag, compiler, engine, config.threads) if network_path != None: - path = os.path.relpath(os.path.abspath(network_path), src_path) + path = os.path.relpath(os.path.abspath(network_path), src_path) command += ' EVALFILE=%s' % (path.replace('\\', '/')) return command.split() @@ -447,17 +739,11 @@ def find_pgn_error(reason, command): ii = ii - 1 return data[ii] + pgn -# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # -# # -# All functions used to make requests to the OpenBench server. Workload # -# requests require Username and Password authentication. Communication # -# with the server is required to succeed except for result uploads which # -# may be batched and held onto in the event of outages. # -# # -# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # -@try_until_success(mesg=ERRORS['cutechess']) -def server_download_cutechess(arguments): +## Functions interacting with the OpenBench server that establish the initial +## connection and then make simple requests to retrieve Workloads as json objects + +def server_download_cutechess(config): print('\nFetching Cutechess Binary...') @@ -465,10 +751,10 @@ def server_download_cutechess(arguments): # Fetch the source location if we are missing the binary source = requests.get( - url_join(arguments.server, 'clientGetFiles'), + url_join(config.server, 'clientGetFiles'), timeout=TIMEOUT_HTTP).json()['location'] - if arguments.proxy: source = 'https://ghproxy.com/' + source + if config.proxy: source = 'https://ghproxy.com/' + source # Windows workers simply need a static compile (64-bit) download_file(url_join(source, 'cutechess-windows.exe').rstrip('/'), 'cutechess-ob.exe') @@ -481,10 +767,10 @@ def server_download_cutechess(arguments): # Fetch the source location if we are missing the binary source = requests.get( - url_join(arguments.server, 'clientGetFiles'), + url_join(config.server, 'clientGetFiles'), timeout=TIMEOUT_HTTP).json()['location'] - if arguments.proxy: source = 'https://ghproxy.com/' + source + if config.proxy: source = 'https://ghproxy.com/' + source # Linux workers need a static compile (64-bit) with execute permissions download_file(url_join(source, 'cutechess-linux').rstrip('/'), 'cutechess-ob') @@ -494,82 +780,75 @@ def server_download_cutechess(arguments): if not locate_utility('./cutechess-ob', False): raise Exception -@try_until_success(mesg=ERRORS['configure']) -def server_configure_worker(arguments): - - global SYSTEM_MACHINE_ID, SYSTEM_SECRET_TOKEN +def server_configure_worker(config): # Server tells us how to build or obtain binaries - target = url_join(arguments.server, 'clientGetBuildInfo') + target = url_join(config.server, 'clientGetBuildInfo') data = requests.get(target, timeout=TIMEOUT_HTTP).json() - scan_for_compilers(data) # Public engines - scan_for_private_tokens(data) # Private engines - scan_for_cpu_flags(data) # For executing binaries - scan_for_machine_id() # None, or the content of machine.txt + config.scan_for_compilers(data) # Public engine build tools + config.scan_for_private_tokens(data) # Private engine access tokens + config.scan_for_cpu_flags(data) # For executing binaries + config.scan_for_machine_id() # None, or the content of machine.txt system_info = { - 'compilers' : SYSTEM_COMPILERS, # Key: Engine, Value: (Compiler, Version) - 'tokens' : SYSTEM_GIT_TOKENS, # Key: Engine, Value: True, for tokens we have - 'cpu_flags' : SYSTEM_CPU_FLAGS, # List of CPU flags found in the Client or Server - 'cpu_name' : SYSTEM_CPU_NAME, # Raw CPU name as per py-cpuinfo - 'os_name' : SYSTEM_OS_NAME, # Should be Windows, Linux, or Darwin - 'os_ver' : SYSTEM_OS_VER, # Release version of the OS - 'python_ver' : SYSTEM_PYTHON_VER, # Python version running the Client - 'mac_address' : SYSTEM_MAC_ADDRESS, # Used to softly verify the Machine IDs - 'logical_cores' : SYSTEM_LOGICAL_CORES, # Logical cores, to differentiate hyperthreads - 'physical_cores' : SYSTEM_PHYSICAL_CORES, # Physical cores, to differentiate hyperthreads - 'ram_total_mb' : SYSTEM_RAM_TOTAL_MB, # Total RAM on the system, to avoid over assigning - 'machine_id' : SYSTEM_MACHINE_ID, # Assigned value, or None. Will be replaced if wrong - 'machine_name' : SYSTEM_MACHINE_NAME, # Optional pseudonym for the machine, otherwise None - 'concurrency' : arguments.threads, # Threads to use to play games - 'ncutechesses' : arguments.ncutechess, # Cutechess copies, usually equal to Socket count + 'compilers' : config.compilers, # Key: Engine, Value: (Compiler, Version) + 'tokens' : config.git_tokens, # Key: Engine, Value: True, for tokens we have + 'cpu_flags' : config.cpu_flags, # List of CPU flags found in the Client or Server + 'cpu_name' : config.cpu_name, # Raw CPU name as per py-cpuinfo + 'os_name' : config.os_name, # Should be Windows, Linux, or Darwin + 'os_ver' : config.os_ver, # Release version of the OS + 'python_ver' : config.python_ver, # Python version running the Client + 'mac_address' : config.mac_address, # Used to softly verify the Machine IDs + 'logical_cores' : config.logical_cores, # Logical cores, to differentiate hyperthreads + 'physical_cores' : config.physical_cores, # Physical cores, to differentiate hyperthreads + 'ram_total_mb' : config.ram_total_mb, # Total RAM on the system, to avoid over assigning + 'machine_id' : config.machine_id, # Assigned value, or None. Will be replaced if wrong + 'machine_name' : config.identity, # Optional pseudonym for the machine, otherwise None + 'concurrency' : config.threads, # Threads to use to play games + 'sockets' : config.sockets, # Cutechess copies, usually equal to Socket count + 'syzygy_max' : config.syzygy_max, # Whether or not the machine has Syzygy support 'client_ver' : CLIENT_VERSION, # Version of the Client, which the server may reject - 'syzygy_wdl' : bool(SYZYGY_WDL_PATH), # Whether or not the machine has Syzygy support } payload = { - 'username' : arguments.username, - 'password' : arguments.password, + 'username' : config.username, + 'password' : config.password, 'system_info' : json.dumps(system_info), } # Send all of this to the server, and get a Machine Id + Secret Token - target = url_join(arguments.server, 'clientWorkerInfo') + target = url_join(config.server, 'clientWorkerInfo') response = requests.post(target, data=payload, timeout=TIMEOUT_HTTP).json() # Delete the machine.txt if we have saved an invalid machine number - if 'error' in response and response['error'].lower() == "bad machine id": + if response.get('error', '').lower() == "bad machine id": + config.machine_id = 'None' os.remove('machine.txt') # The 'error' header is included if there was an issue if 'error' in response: - print('[Error] %s\n' % (response['error'])) - sys.exit() + raise Exception('[Error] %s' % (response['error'])) # Save the machine id, to avoid re-registering every time with open('machine.txt', 'w') as fout: fout.write(str(response['machine_id'])) - # Save it within the code as well for future requests - SYSTEM_MACHINE_ID = str(response['machine_id']) + # Store machine_id, and the secret for this session + config.machine_id = response['machine_id'] + config.secret_token = response['secret'] - # Save the secret token, to send with all future requests - SYSTEM_SECRET_TOKEN = response['secret'] - -@try_until_success(mesg=ERRORS['request']) -def server_request_workload(arguments): +def server_request_workload(config): print('\nRequesting Workload from Server...') - payload = { 'machine_id' : SYSTEM_MACHINE_ID, 'secret' : SYSTEM_SECRET_TOKEN } - target = url_join(arguments.server, 'clientGetWorkload') + payload = { 'machine_id' : config.machine_id, 'secret' : config.secret_token } + target = url_join(config.server, 'clientGetWorkload') response = requests.post(target, data=payload, timeout=TIMEOUT_HTTP).json() # The 'error' header is included if there was an issue if 'error' in response: - print('[Error] %s\n' % (response['error'])) - sys.exit() + raise Exception('[Error] %s' % (response['error'])) # Log the start of a new Workload if 'workload' in response: @@ -579,202 +858,95 @@ def server_request_workload(arguments): base_name = response['workload']['test']['base']['name' ] print('Workload [%s] %s vs [%s] %s\n' % (dev_engine, dev_name, base_engine, base_name)) - return None if 'workload' not in response else response['workload'] + config.workload = response.get('workload', None) -def server_report_nps(arguments, workload, dev_nps, base_nps): - payload = { - 'machine_id' : SYSTEM_MACHINE_ID, - 'secret' : SYSTEM_SECRET_TOKEN, - 'nps' : (dev_nps + base_nps) // 2 - } +def complete_workload(config): - target = url_join(arguments.server, 'clientSubmitNPS') - response = requests.post(target, data=payload, timeout=TIMEOUT_ERROR) + # Download the opening book, throws an exception on corruption + download_opening_book(config) -def server_report_missing_artifact(arguments, workload, branch, artifact_name, artifact_json): + # Download each NNUE file, throws an exception on corruption + dev_network = download_network_weights(config, 'dev' ) + base_network = download_network_weights(config, 'base') - payload = { - 'machine_id' : SYSTEM_MACHINE_ID, - 'secret' : SYSTEM_SECRET_TOKEN, - 'test_id' : workload['test']['id'], - 'error' : 'Artifact %s missing' % (artifact_name), - 'logs' : json.dumps(artifact_json, indent=2), - } + # Build or download each engine, or exit if an error occured + dev_name = download_engine(config, 'dev' , dev_network ) + base_name = download_engine(config, 'base', base_network) + if not dev_name or not base_name: return - target = url_join(arguments.server, 'clientSubmitError') - requests.post(target, data=payload, timeout=TIMEOUT_HTTP) + # Run the benchmarks and compute the scaling NPS value + dev_nps = run_benchmarks(config, 'dev' , dev_name , dev_network ) + base_nps = run_benchmarks(config, 'base', base_name, base_network) + avg_nps = (dev_nps + base_nps) // 2 -def server_report_build_fail(arguments, workload, branch, compiler_output): + # Report NPS to server, or exit if an error occured + if not dev_nps or not base_nps: return + ServerReporter.report_nps(config, dev_nps, base_nps) - name = workload['test'][branch]['name'] - if workload['test']['dev']['engine'] != workload['test']['base']['engine']: - name = '[%s] %s' % (workload['test'][branch]['engine'], name) + # Launch and manage all of the Cutechess workers + with ThreadPoolExecutor(max_workers=config.sockets) as executor: - payload = { - 'machine_id' : SYSTEM_MACHINE_ID, - 'secret' : SYSTEM_SECRET_TOKEN, - 'test_id' : workload['test']['id'], - 'error' : '%s build failed' % (name), - 'logs' : compiler_output, - } + tasks = [] # Create each of the Cutechess workers + for x in range(config.sockets): + cmd = build_cutechess_command(config, dev_name, base_name, avg_nps, x) + tasks.append(executor.submit(run_and_parse_cutechess, config, cmd, x)) - target = url_join(arguments.server, 'clientSubmitError') - requests.post(target, data=payload, timeout=TIMEOUT_HTTP) + # Await the completion of all Cutechess workers + try: + for task in tasks: + task.result() -def server_report_engine_error(arguments, workload, cutechess_str, pgn): + # Kill everything during an Keyboard Interrupt + except KeyboardInterrupt: + for task in tasks: task.cancel() + raise KeyboardInterrupt - pairing = cutechess_str.split('(')[1].split(')')[0] - white, black = pairing.split(' vs ') - - error = cutechess_str.split('{')[1].rstrip().rstrip('}') - error = error.replace('White', '-'.join(white.split('-')[1:]).rstrip()) - error = error.replace('Black', '-'.join(black.split('-')[1:]).rstrip()) - - payload = { - 'machine_id' : SYSTEM_MACHINE_ID, - 'secret' : SYSTEM_SECRET_TOKEN, - 'test_id' : workload['test']['id'], - 'error' : error, - 'logs' : pgn, - } - - target = url_join(arguments.server, 'clientSubmitError') - requests.post(target, data=payload, timeout=TIMEOUT_HTTP) - -def server_report_bad_bench(arguments, workload, branch, bench): - - payload = { - 'machine_id' : SYSTEM_MACHINE_ID, - 'secret' : SYSTEM_SECRET_TOKEN, - 'test_id' : workload['test']['id'], - 'engine' : workload['test'][branch]['name'], - 'correct' : workload['test'][branch]['bench'], - 'wrong' : bench, - } - - target = url_join(arguments.server, 'clientWrongBench') - requests.post(target, data=payload, timeout=TIMEOUT_HTTP) - -def server_report_results(arguments, workload, stats): - - wins, losses, draws, crashes, timelosses = stats - - payload = { - 'machine_id' : SYSTEM_MACHINE_ID, - 'secret' : SYSTEM_SECRET_TOKEN, - 'test_id' : workload['test']['id'], - 'result_id' : workload['result']['id'], - 'wins' : wins, - 'losses' : losses, - 'draws' : draws, - 'crashes' : crashes, - 'timeloss' : timelosses, - } - - target = url_join(arguments.server, 'clientSubmitResults') - return requests.post(target, data=payload, timeout=TIMEOUT_HTTP).json() - -# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # -# # -# # -# # -# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # - -def complete_workload(arguments, workload): - - dev_network = download_network_weights(arguments, workload, 'dev' ) - base_network = download_network_weights(arguments, workload, 'base') - - dev_name = download_engine(arguments, workload, 'dev' , dev_network ) - base_name = download_engine(arguments, workload, 'base', base_network) - if dev_name == None or base_name == None: return - - dev_bench, dev_nps = run_benchmarks(arguments, workload, 'dev' , dev_name , dev_network ) - base_bench, base_nps = run_benchmarks(arguments, workload, 'base', base_name, base_network) - average_nps = (dev_nps + base_nps) // 2 - - dev_status = verify_benchmarks(arguments, workload, 'dev' , dev_bench ) - base_status = verify_benchmarks(arguments, workload, 'base', base_bench) - - if not dev_status or not base_status: return - server_report_nps(arguments, workload, dev_nps, base_nps) - download_opening_book(arguments, workload) - - # Construct each individual Cutechess argument, which differs by PGN output - cutechess_args = [ - build_cutechess_command(arguments, workload, dev_name, base_name, average_nps, ii) - for ii in range(int(arguments.ncutechess)) - ] - - # Create a process for the each copy of run_and_parse_cutechess() - processes = [ - multiprocessing.Process( - target=run_and_parse_cutechess, - args=(arguments, workload, *cutechess_args[ii], ii)) - for ii in range(int(arguments.ncutechess)) - ] - - try: - # Launch and wait for each cutechess copy - for process in processes: process.start() - for process in processes: process.join() - - except KeyboardInterrupt: - # Kill everything and pass the error back up - for process in processes: process.kill() - raise KeyboardInterrupt - -def download_opening_book(arguments, workload): +def download_opening_book(config): # Log our attempts to download and verify the book - book_sha256 = workload['test']['book']['sha' ] - book_source = workload['test']['book']['source'] - book_name = workload['test']['book']['name' ] + book_sha256 = config.workload['test']['book']['sha' ] + book_source = config.workload['test']['book']['source'] + book_name = config.workload['test']['book']['name' ] book_path = os.path.join('Books', book_name) - print('\nFetching Opening Book [%s]' % (book_name)) + print('Fetching Opening Book [%s]' % (book_name)) # Download file if we do not already have it if not os.path.isfile(book_path): - if arguments.proxy: book_source = 'https://ghproxy.com/' + book_source + if config.proxy: book_source = 'https://ghproxy.com/' + book_source download_file(book_source, book_name + '.zip') unzip_delete_file(book_name + '.zip', 'Books/') # Verify SHAs match with the server with open(book_path) as fin: content = fin.read().encode('utf-8') - sha256 = hashlib.sha256(content).hexdigest() + sha256 = hashlib.sha256(content).hexdigest() if book_sha256 != sha256: os.remove(book_path) # Log SHAs on every workload print('Correct SHA256 %s' % (book_sha256.upper())) - print('Download SHA256 %s' % ( sha256.upper())) + print('Download SHA256 %s\n' % ( sha256.upper())) # We have to have the correct SHA to continue if book_sha256 != sha256: raise Exception('Invalid SHA for %s' % (book_name)) -def download_network_weights(arguments, workload, branch): +def download_network_weights(config, branch): # Some tests may not use Neural Networks - network_name = workload['test'][branch]['network'] + network_name = config.workload['test'][branch]['network'] if not network_name or network_name == 'None': return None # Log that we are obtaining a Neural Network pattern = 'Fetching Neural Network [ %s, %-4s ]' print(pattern % (network_name, branch.upper())) - # Neural Network requests require authorization - payload = { - 'username' : arguments.username, - 'password' : arguments.password, - } - # Fetch the Netural Network if we do not already have it network_path = os.path.join('Networks', network_name) if not os.path.isfile(network_path): - api = url_join(arguments.server, 'clientGetNetwork') - download_file(url_join(api, network_name), network_path, payload) + target = url_join(config.server, 'clientGetNetwork') + payload = { 'username' : config.username, 'password' : config.password } + download_file(url_join(target, network_name), network_path, payload) # Verify the download and delete partial or corrupted ones with open(network_path, 'rb') as network: @@ -788,14 +960,13 @@ def download_network_weights(arguments, workload, branch): return network_path -def download_engine(arguments, workload, branch, network): +def download_engine(arguments, branch, network): - engine = workload['test'][branch]['engine'] - branch_name = workload['test'][branch]['name'] - commit_sha = workload['test'][branch]['sha'] - source = workload['test'][branch]['source'] - build_path = workload['test'][branch]['build']['path'] - private = 'artifacts' in workload['test'][branch]['build'] + engine = config.workload['test'][branch]['engine'] + branch_name = config.workload['test'][branch]['name'] + commit_sha = config.workload['test'][branch]['sha'] + source = config.workload['test'][branch]['source'] + private = config.workload['test'][branch]['private'] # Naming as Engine-CommitSha[:8]-NetworkSha[:8] final_name = '%s-%s' % (engine, commit_sha.upper()[:8]) @@ -812,38 +983,33 @@ def download_engine(arguments, workload, branch, network): print ('\nFetching Artifacts for %s' % branch_name) with open('credentials.%s' % (engine.replace(' ', '').lower())) as fin: auth_headers = { 'Authorization' : 'token %s' % fin.readlines()[0].rstrip() } + + # Pick from available artifacts the name of the best one artifacts = requests.get(url=source, headers=auth_headers).json()['artifacts'] - - # For sanity, just avoid using PEXT/BMI2 on AMD Chips - ryzen = 'AMD' in SYSTEM_CPU_NAME.upper() - ryzen = 'RYZEN' in SYSTEM_CPU_NAME.upper() or ryzen - - # Construct the artifact string for the desired binary - os_string = ['windows', 'linux' ][IS_LINUX] - avx_string = ['avx2' , 'avx512']['AVX512_VNNI' in str(SYSTEM_CPU_FLAGS)] - bit_string = ['popcnt' , 'pext' ]['BMI2' in str(SYSTEM_CPU_FLAGS) and not ryzen] - desired = '%s-%s-%s' % (os_string, avx_string, bit_string) + options = [artifact['name'] for artifact in artifacts] + best = config.choose_best_artifact(options) # Search for our artifact in the list provided artifact_id = None for artifact in artifacts: - if artifact['name'] == '%s-%s' % (commit_sha, desired): + if artifact['name'] == best: artifact_id = artifact['id'] # Artifact was missing, workload cannot be completed if artifact_id == None: - server_report_missing_artifact(arguments, workload, branch, desired, artifacts) + ServerReporter.report_missing_artifact(config, branch, best, artifacts) return None # Download the binary that matches our desired artifact - print ('Downloading [%s] %s' % (branch_name, desired)) + print ('Downloading [%s] %s' % (branch_name, best)) base = source.split('/runs/')[0] url = url_join(base, 'artifacts', str(artifact_id), 'zip').rstrip('/') download_file(url, 'artifact.zip', None, auth_headers) - # Unzip the binary, and determine where to move the binary + # Unzip the binary, and place it into a known output name unzip_delete_file('artifact.zip', 'tmp/') output_name = os.path.join('tmp', engine.replace(' ', '').lower()) + os.rename(os.path.join('tmp', os.listdir('tmp/')[0]), output_name) # Binaries don't have execute permissions by default if IS_LINUX: @@ -858,12 +1024,13 @@ def download_engine(arguments, workload, branch, network): # Parse out paths to find the makefile location tokens = source.split('/') unzip_name = '%s-%s' % (tokens[-3], tokens[-1].rstrip('.zip')) + build_path = config.workload['test'][branch]['build']['path'] src_path = os.path.join('tmp', unzip_name, *build_path.split('/')) # Build the engine and drop it into src_path print('\nBuilding [%s]' % (final_path)) output_name = os.path.join(src_path, engine) - command = make_command(arguments, engine, src_path, network) + command = make_command(config, engine, src_path, network) process = Popen(command, cwd=src_path, stdout=PIPE, stderr=STDOUT) cxx_output = process.communicate()[0].decode('utf-8') print (cxx_output) @@ -882,109 +1049,53 @@ def download_engine(arguments, workload, branch, network): # Manual builds should have exited by now if not private: - server_report_build_fail(arguments, workload, branch, cxx_output) + ServerReporter.report_build_fail(config, branch, cxx_output) return None -def run_benchmarks(arguments, workload, branch, engine, network): +def run_benchmarks(config, branch, engine, network): - cores = arguments.threads queue = multiprocessing.Queue() - name = workload['test'][branch]['name'] - private = 'artifacts' in workload['test'][branch]['build'] - print('\nRunning %dx Benchmarks for %s' % (cores, name)) + name = config.workload['test'][branch]['name'] + private = config.workload['test'][branch]['private'] + print('\nRunning %dx Benchmarks for %s' % (config.threads, name)) - for ii in range(cores): + # Execute a benchmark on each of the Threads + for ii in range(config.threads): args = [os.path.join('Engines', engine), queue] if private and network: args.append(network) multiprocessing.Process(target=run_bench, args=args).start() - bench, nps = list(zip(*[queue.get() for ii in range(cores)])) - if len(set(bench)) > 1: return (0, 0) # Flag an error + # Collect all bench and nps values, and set bench to 0 if any vary + bench, nps = list(zip(*[queue.get() for ii in range(config.threads)])) + bench = [0, bench[0]][len(set(bench)) == 1] + nps = sum(nps) // config.threads - print('Bench for %s is %d' % (name, bench[0])) - print('Speed for %s is %d' % (name, sum(nps) // cores)) - return bench[0], sum(nps) // cores + # Output everything, including 0 for an error + print('Bench for %s is %d' % (name, bench)) + print('Speed for %s is %d' % (name, nps)) -def verify_benchmarks(arguments, workload, branch, bench): - if bench != int(workload['test'][branch]['bench']): - server_report_bad_bench(arguments, workload, branch, bench) - return bench == int(workload['test'][branch]['bench']) + # Flag the test to abort if we have a bench mismatch + if error := (bench != int(config.workload['test'][branch]['bench'])): + ServerReporter.report_bad_bench(config, branch, bench) -def build_cutechess_command(arguments, workload, dev_cmd, base_cmd, nps, cutechess_idx): + # Set NPS to 0 if we had any errors + return 0 if not bench or error else nps - dev_options = workload['test']['dev' ]['options'] - base_options = workload['test']['base']['options'] +def build_cutechess_command(config, dev_cmd, base_cmd, nps, socket): - dev_threads = int(re.search('(?<=Threads=)\d*', dev_options ).group()) - base_threads = int(re.search('(?<=Threads=)\d*', base_options).group()) + flags = ' ' + Cutechess.basic_settings(config, socket) + flags += ' ' + Cutechess.concurrency_settings(config) + flags += ' ' + Cutechess.adjudication_settings(config) + flags += ' ' + Cutechess.engine_settings(config, dev_cmd, 'dev', nps) + flags += ' ' + Cutechess.engine_settings(config, base_cmd, 'base', nps) + flags += ' ' + Cutechess.book_settings(config) + flags += ' ' + Cutechess.pgnout_settings(config, dev_cmd, base_cmd, socket) - dev_network = workload['test']['dev' ]['network'] # Could be empty strings - base_network = workload['test']['base']['network'] # Could be empty strings + return ['cutechess-ob.exe', './cutechess-ob'][IS_LINUX] + flags - dev_time = scale_time_control(workload, nps, 'dev') - base_time = scale_time_control(workload, nps, 'base') +def run_and_parse_cutechess(config, command, socket): - dev_name = dev_cmd.rstrip('.exe') # Used to name the PGN file and Headers - base_name = base_cmd.rstrip('.exe') # Used to name the PGN file and Headers - - # Possibly add SyzygyPath to dev and base options - if SYZYGY_WDL_PATH and workload['test']['syzygy_wdl'] != 'DISABLED': - path = SYZYGY_WDL_PATH.replace('\\', '\\\\') - dev_options += ' SyzygyPath=%s' % (path) - base_options += ' SyzygyPath=%s' % (path) - - # Private engines may need extra options to set their NNUE files - if 'artifacts' in workload['test']['dev']['build'] and dev_network and dev_network != 'None': - dev_options += ' EvalFile=%s' % (os.path.join('../Networks', dev_network)) - dev_name += '-%s' % (dev_network) - - # Private engines may need extra options to set their NNUE files - if 'artifacts' in workload['test']['base']['build'] and base_network and base_network != 'None': - base_options += ' EvalFile=%s' % (os.path.join('../Networks', base_network)) - base_name += '-%s' % (base_network) - - # Join all of the options into a single string - dev_options = ' option.'.join([''] + dev_options.split()) - base_options = ' option.'.join([''] + base_options.split()) - - win_adj = ['', '-resign ' + workload['test']['win_adj' ]][workload['test']['win_adj' ] != 'None'] - draw_adj = ['', '-draw ' + workload['test']['draw_adj']][workload['test']['draw_adj'] != 'None'] - - book_name = workload['test']['book']['name'] - variant = ['standard', 'fischerandom']['FRC' in book_name.upper()] - - flags = '-repeat -recover %s %s ' - flags += '-srand %d -variant %s -concurrency %d -games %d ' - flags += '-engine dir=Engines/ cmd=./%s proto=uci %s%s name=%s ' - flags += '-engine dir=Engines/ cmd=./%s proto=uci %s%s name=%s ' - flags += '-openings file=Books/%s format=%s order=random plies=16 ' - flags += '-pgnout PGNs/%s_vs_%s.%d ' - - if SYZYGY_WDL_PATH and workload['test']['syzygy_adj'] != 'DISABLED': - flags += '-tb %s' % (SYZYGY_WDL_PATH.replace('\\', '\\\\')) - - concurrency = arguments.threads / arguments.ncutechess - concurrency = concurrency // max(dev_threads, base_threads) - - games = int(concurrency * workload['test']['workload_size']) - games = max(8, concurrency * 2, games - (games % (2 * concurrency))) - - args = ( - win_adj, draw_adj, - int(time.time() + cutechess_idx), variant, concurrency, games, - dev_cmd, dev_time, dev_options, dev_name, - base_cmd, base_time, base_options, base_name, - book_name, book_name.split('.')[-1], - dev_name, base_name, cutechess_idx, - ) - - if IS_LINUX: - return concurrency, './cutechess-ob ' + flags % (args) - return concurrency, 'cutechess-ob.exe ' + flags % (args) - -def run_and_parse_cutechess(arguments, workload, concurrency, command, cutechess_idx): - - print('\n[#%d] Launching Cutechess...\n%s\n' % (cutechess_idx, command)) + print('\n[#%d] Launching Cutechess...\n%s\n' % (socket, command)) cutechess = Popen(command.split(), stdout=PIPE) crashes = timelosses = 0 @@ -995,7 +1106,7 @@ def run_and_parse_cutechess(arguments, workload, concurrency, command, cutechess # Read each line of output until the pipe closes line = cutechess.stdout.readline().strip().decode('ascii') - if line != '': print('[#%d] %s' % (cutechess_idx, line)) + if line != '': print('[#%d] %s' % (socket, line)) else: cutechess.wait(); return # Real updates contain a colon @@ -1011,7 +1122,7 @@ def run_and_parse_cutechess(arguments, workload, concurrency, command, cutechess for error in errors: if error in score_reason: pgn = find_pgn_error(score_reason, command) - server_report_engine_error(arguments, workload, line, pgn) + ServerReporter.report_engine_error(config, line, pgn) # All remaining processing is for score updates only if not line.startswith('Score of'): @@ -1019,14 +1130,14 @@ def run_and_parse_cutechess(arguments, workload, concurrency, command, cutechess # Only report scores after every eight games score = list(map(int, score_reason.split()[0:5:2])) - if ((sum(score) - sum(sent)) % workload['test']['report_rate'] != 0): + if ((sum(score) - sum(sent)) % config.workload['test']['report_rate'] != 0): continue try: # Report new results to the server wld = [score[ii] - sent[ii] for ii in range(3)] stats = wld + [crashes, timelosses] - status = server_report_results(arguments, workload, stats) + status = ServerReporter.report_results(config, stats).json() # Reset the reporting since this report was a success crashes = timelosses = 0 @@ -1049,65 +1160,30 @@ def run_and_parse_cutechess(arguments, workload, concurrency, command, cutechess if __name__ == '__main__': - req_user = required=('OPENBENCH_USERNAME' not in os.environ) - req_pass = required=('OPENBENCH_PASSWORD' not in os.environ) - help_user = 'Username. May also be passed as OPENBENCH_USERNAME environment variable' - help_pass = 'Password. May also be passed as OPENBENCH_PASSWORD environment variable' + config = Configuration() # System info, Cmdline arguments, and Workload - p = argparse.ArgumentParser() + cutechess_error = '[Note] Unable to fetch Cutechess location and download it!' + setup_error = '[Note] Unable to establish initial connection with the Server!' + connection_error = '[Note] Unable to reach the server to request a workload!' - # Required arguments - p.add_argument('-U', '--username' , help=help_user , required=req_user) - p.add_argument('-P', '--password' , help=help_pass , required=req_pass) - p.add_argument('-S', '--server' , help='Webserver Address' , required=True) - p.add_argument('-T', '--threads' , help='Total Threads' , required=True) - p.add_argument('-N', '--ncutechess' , help='Cutechess Copies' , required=True) - p.add_argument('-I', '--identity' , help='Machine pseudonym' , required=False) - - # Optional arguments - p.add_argument('--syzygy', help='Syzygy WDL' , required=False) - p.add_argument('--fleet' , help='Fleet Mode' , action='store_true') - p.add_argument('--proxy' , help='Github Proxy', action='store_true') - - arguments = p.parse_args() - - arguments.threads = int(arguments.threads) - arguments.ncutechess = int(arguments.ncutechess) - - # Make sure the thread distibution between Cutechess copies is correct - assert (arguments.threads >= 1) - assert (arguments.ncutechess >= 1) - assert (arguments.threads >= arguments.ncutechess) - assert (arguments.threads % arguments.ncutechess == 0) - - if arguments.username is None: - arguments.username = os.environ['OPENBENCH_USERNAME'] - - if arguments.password is None: - arguments.password = os.environ['OPENBENCH_PASSWORD'] - - if arguments.identity: - SYSTEM_MACHINE_NAME = arguments.identity - - if arguments.syzygy is not None: - SYZYGY_WDL_PATH = arguments.syzygy - - if arguments.fleet: - FLEET_MODE = True - - init_client(arguments) - server_download_cutechess(arguments) - server_configure_worker(arguments) + try_forever(server_download_cutechess, [config], cutechess_error) + try_forever(server_configure_worker, [config], setup_error ) while True: try: # Cleanup on each workload request cleanup_client() - # Fleet workers exit when there are no workloads - if workload := server_request_workload(arguments): - complete_workload(arguments, workload) - elif FLEET_MODE: break + # Keep asking for a workload until we get a response + try_forever(server_request_workload, [config], connection_error) + + # Complete the workload if there was work to be done + if config.workload: complete_workload(config) + + # Otherwise --fleet workers will exit when there is no work + elif config.fleet: break + + # In either case, wait before requesting again else: time.sleep(TIMEOUT_WORKLOAD) # Check for exit signal via openbench.exit @@ -1115,4 +1191,5 @@ if __name__ == '__main__': print('Exited via openbench.exit') break - except Exception: traceback.print_exc() + except Exception: + traceback.print_exc() diff --git a/Engines/4ku.json b/Engines/4ku.json index d94a45a..b6422da 100644 --- a/Engines/4ku.json +++ b/Engines/4ku.json @@ -12,7 +12,8 @@ "build" : { "path" : "", "compilers" : ["g++"], - "cpuflags" : ["POPCNT"] + "cpuflags" : ["POPCNT"], + "systems" : ["Windows", "Linux"] }, "testmodes" : { diff --git a/Engines/Berserk.json b/Engines/Berserk.json index 6e45759..8374b7b 100644 --- a/Engines/Berserk.json +++ b/Engines/Berserk.json @@ -12,7 +12,8 @@ "build" : { "path" : "src", "compilers" : ["gcc"], - "cpuflags" : ["AVX2", "FMA", "POPCNT"] + "cpuflags" : ["AVX2", "FMA", "POPCNT"], + "systems" : ["Windows", "Linux"] }, "testmodes" : { diff --git a/Engines/Bit-Genie.json b/Engines/Bit-Genie.json index 7240ba5..37ca48f 100644 --- a/Engines/Bit-Genie.json +++ b/Engines/Bit-Genie.json @@ -12,7 +12,8 @@ "build" : { "path" : "src", "compilers" : ["g++"], - "cpuflags" : ["POPCNT"] + "cpuflags" : ["POPCNT"], + "systems" : ["Windows", "Linux"] }, "testmodes" : { diff --git a/Engines/BlackMarlin.json b/Engines/BlackMarlin.json index 711df8d..ea63a2a 100644 --- a/Engines/BlackMarlin.json +++ b/Engines/BlackMarlin.json @@ -12,7 +12,8 @@ "build" : { "path" : "", "compilers" : ["cargo>=1.57.0"], - "cpuflags" : [ "AVX2", "FMA", "POPCNT"] + "cpuflags" : ["AVX2", "FMA", "POPCNT"], + "systems" : ["Windows", "Linux"] }, "testmodes" : { diff --git a/Engines/Demolito.json b/Engines/Demolito.json index 7dcced5..004dd07 100644 --- a/Engines/Demolito.json +++ b/Engines/Demolito.json @@ -12,7 +12,8 @@ "build" : { "path" : "src", "compilers" : ["clang", "gcc"], - "cpuflags" : ["POPCNT"] + "cpuflags" : ["POPCNT"], + "systems" : ["Windows", "Linux"] }, "testmodes" : { diff --git a/Engines/Drofa.json b/Engines/Drofa.json index 6e1d3bf..e498a24 100644 --- a/Engines/Drofa.json +++ b/Engines/Drofa.json @@ -12,7 +12,8 @@ "build" : { "path" : "", "compilers" : ["g++"], - "cpuflags" : ["POPCNT"] + "cpuflags" : ["POPCNT"], + "systems" : ["Windows", "Linux"] }, "testmodes" : { diff --git a/Engines/Ethereal.json b/Engines/Ethereal.json index 0e6212c..a476e04 100644 --- a/Engines/Ethereal.json +++ b/Engines/Ethereal.json @@ -12,7 +12,8 @@ "build" : { "path" : "src", "compilers" : ["clang", "gcc"], - "cpuflags" : ["AVX2", "FMA", "POPCNT"] + "cpuflags" : ["AVX2", "FMA", "POPCNT"], + "systems" : ["Windows", "Linux"] }, "testmodes" : { diff --git a/Engines/FabChess.json b/Engines/FabChess.json index fcb17e1..5085900 100644 --- a/Engines/FabChess.json +++ b/Engines/FabChess.json @@ -12,7 +12,8 @@ "build" : { "path" : "", "compilers" : ["cargo>=1.41.0"], - "cpuflags" : ["POPCNT"] + "cpuflags" : ["POPCNT"], + "systems" : ["Windows", "Linux"] }, "testmodes" : { diff --git a/Engines/Halogen.json b/Engines/Halogen.json index 2213eb1..fde3bde 100644 --- a/Engines/Halogen.json +++ b/Engines/Halogen.json @@ -12,7 +12,8 @@ "build" : { "path" : "src", "compilers" : ["g++"], - "cpuflags" : ["POPCNT"] + "cpuflags" : ["POPCNT"], + "systems" : ["Windows", "Linux"] }, "testmodes" : { diff --git a/Engines/Igel.json b/Engines/Igel.json index f1d9c13..eafce02 100644 --- a/Engines/Igel.json +++ b/Engines/Igel.json @@ -12,7 +12,8 @@ "build" : { "path" : "src", "compilers" : ["g++"], - "cpuflags" : ["POPCNT"] + "cpuflags" : ["POPCNT"], + "systems" : ["Windows", "Linux"] }, "testmodes" : { diff --git a/Engines/Koivisto.json b/Engines/Koivisto.json index 9e0d532..6facae3 100644 --- a/Engines/Koivisto.json +++ b/Engines/Koivisto.json @@ -12,7 +12,8 @@ "build" : { "path" : "src_files", "compilers" : ["g++"], - "cpuflags" : ["AVX2", "FMA", "POPCNT"] + "cpuflags" : ["AVX2", "FMA", "POPCNT"], + "systems" : ["Windows", "Linux"] }, "testmodes" : { diff --git a/Engines/Laser.json b/Engines/Laser.json index 099c3e0..ddac236 100644 --- a/Engines/Laser.json +++ b/Engines/Laser.json @@ -12,7 +12,8 @@ "build" : { "path" : "src", "compilers" : ["g++"], - "cpuflags" : ["POPCNT"] + "cpuflags" : ["POPCNT"], + "systems" : ["Windows", "Linux"] }, "testmodes" : { diff --git a/Engines/RubiChess.json b/Engines/RubiChess.json index 873acb5..5c476c3 100644 --- a/Engines/RubiChess.json +++ b/Engines/RubiChess.json @@ -12,7 +12,8 @@ "build" : { "path" : "src", "compilers" : ["g++"], - "cpuflags" : ["POPCNT"] + "cpuflags" : ["POPCNT"], + "systems" : ["Windows", "Linux"] }, "testmodes" : { diff --git a/Engines/Seer.json b/Engines/Seer.json index 773362d..cdc70fb 100644 --- a/Engines/Seer.json +++ b/Engines/Seer.json @@ -12,7 +12,8 @@ "build" : { "path" : "build", "compilers" : ["g++>=9.0.0"], - "cpuflags" : ["AVX2", "FMA", "POPCNT"] + "cpuflags" : ["AVX2", "FMA", "POPCNT"], + "systems" : ["Windows", "Linux"] }, "testmodes" : { diff --git a/Engines/Stash.json b/Engines/Stash.json index 83b8699..abcef6b 100644 --- a/Engines/Stash.json +++ b/Engines/Stash.json @@ -12,7 +12,8 @@ "build" : { "path" : "src", "compilers" : ["gcc", "clang"], - "cpuflags" : ["POPCNT"] + "cpuflags" : ["POPCNT"], + "systems" : ["Windows", "Linux"] }, "testmodes" : { diff --git a/Engines/Weiss.json b/Engines/Weiss.json index 45ee574..601adc1 100644 --- a/Engines/Weiss.json +++ b/Engines/Weiss.json @@ -12,7 +12,8 @@ "build" : { "path" : "src", "compilers" : ["gcc"], - "cpuflags" : ["POPCNT"] + "cpuflags" : ["POPCNT"], + "systems" : ["Windows", "Linux"] }, "testmodes" : { diff --git a/Engines/Winter.json b/Engines/Winter.json index 7df2c7e..adaf76a 100644 --- a/Engines/Winter.json +++ b/Engines/Winter.json @@ -12,7 +12,8 @@ "build" : { "path" : "", "compilers" : ["clang++", "g++"], - "cpuflags" : ["POPCNT"] + "cpuflags" : ["POPCNT"], + "systems" : ["Windows", "Linux"] }, "testmodes" : { diff --git a/Engines/Zahak.json b/Engines/Zahak.json index 8199d26..44fc5ca 100644 --- a/Engines/Zahak.json +++ b/Engines/Zahak.json @@ -12,7 +12,8 @@ "build" : { "path" : "", "compilers" : ["go"], - "cpuflags" : ["AVX", "POPCNT"] + "cpuflags" : ["AVX", "POPCNT"], + "systems" : ["Windows", "Linux"] }, "testmodes" : { diff --git a/OpenBench/config.py b/OpenBench/config.py index 1d3a63e..45fe611 100644 --- a/OpenBench/config.py +++ b/OpenBench/config.py @@ -18,12 +18,16 @@ # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # -import json, os.path +import json, os.path, sys from OpenSite.settings import PROJECT_PATH def load_json_config(*path): - with open(os.path.join(PROJECT_PATH, *path)) as fin: - return json.load(fin) + try: + with open(os.path.join(PROJECT_PATH, *path)) as fin: + return json.load(fin) + except: + print ('Error reading ', path) + sys.exit() def load_folder_of_configs(*path): return { @@ -38,11 +42,11 @@ REQUIRE_MANUAL_REGISTRATION = False # Disable the public facing registration pag OPENBENCH_CONFIG = { # Server Client version control - 'client_version' : '9', + 'client_version' : '10', # Generic Error Messages useful to those setting up their own instance 'error' : { - 'disabled' : 'Account has not been enabled. Contact andrew@grantnet.us', + 'disabled' : 'Account has not been enabled. Contact an Administrator', 'fakeuser' : 'This is not a real OpenBench User. Create an OpenBench account', 'requires_login' : 'All pages require a user login to access', 'manual_registration' : 'Registration can only be done via an Administrator', diff --git a/OpenBench/management/commands/runserver.py b/OpenBench/management/commands/runserver.py index 4f2f003..0979e8b 100644 --- a/OpenBench/management/commands/runserver.py +++ b/OpenBench/management/commands/runserver.py @@ -1,29 +1,46 @@ import django.apps -import threading, time +import requests, sys, threading, time import OpenBench.utils from django.core.management.commands.runserver import Command as BaseRunserverCommand class ArtifactWatcher(threading.Thread): + def check_for_artifacts(self, data): + + # Success, if we had all artifacts. Otherwise consider re-running the Workflow + retval, has_all = OpenBench.utils.fetch_artifact_url(*data, return_data=True) + if has_all: return retval, True + + # Otherwise, we may have returned the Jobs + Artifacts + jobs, artifacts = retval + + # Catch expired artifacts, or a Github API bug and run the Workflow + if all(job['conclusion'] == 'success' for job in jobs): + run_id = jobs[0]['run_id'] + url = OpenBench.utils.path_join(data[0], 'actions', 'runs', str(run_id), 'rerun') + requests.post(url=url, headers=data[2]).json() + + # We did not have all artifacts needed, return the original source + return data[0], False + def update_test(self, test): - dev_has_all = test.dev.source.endswith('artifacts') - base_has_all = test.base.source.endswith('artifacts') - - dev_headers = OpenBench.utils.read_git_credentials(test.dev_engine) - base_headers = OpenBench.utils.read_git_credentials(test.base_engine) - - if dev_headers and not dev_has_all: - test.dev.source, dev_has_all = OpenBench.utils.fetch_artifact_url( - test.dev.source, test.dev_engine, dev_headers, test.dev.sha) + # Check for Artifacts for Dev, and re-run if needed + if not (dev_has_all := test.dev.source.endswith('artifacts')): + dev_headers = OpenBench.utils.read_git_credentials(test.dev_engine) + data = [test.dev.source, test.dev_engine, dev_headers, test.dev.sha] + test.dev.source, dev_has_all = self.check_for_artifacts(data) test.dev.save() - if base_headers and not base_has_all: - test.base.source, base_has_all = OpenBench.utils.fetch_artifact_url( - test.base.source, test.base_engine, base_headers, test.base.sha) + # Check for Artifacts for Base, and re-run if needed + if not (base_has_all := test.base.source.endswith('artifacts')): + base_headers = OpenBench.utils.read_git_credentials(test.base_engine) + data = [test.base.source, test.base_engine, base_headers, test.base.sha] + test.base.source, base_has_all = self.check_for_artifacts(data) test.base.save() + # If both finished, flag the test as no longer awaiting if dev_has_all and base_has_all: test.awaiting = False test.save() @@ -31,8 +48,12 @@ class ArtifactWatcher(threading.Thread): def run(self): while True: for test in OpenBench.utils.get_awaiting_tests(): - self.update_test(test) - time.sleep(10) + try: self.update_test(test) + except: + import traceback, sys + traceback.print_exc() + sys.stdout.flush() + time.sleep(15) class Command(BaseRunserverCommand): diff --git a/OpenBench/models.py b/OpenBench/models.py index 9667459..0f1204e 100644 --- a/OpenBench/models.py +++ b/OpenBench/models.py @@ -49,12 +49,14 @@ class Profile(Model): class Machine(Model): - user = ForeignKey(User, PROTECT, related_name='owner') - mnps = FloatField(default=0.00) - updated = DateTimeField(auto_now=True) - secret = CharField(max_length=64, default='None') - info = JSONField() - workload = IntegerField(default=0) + user = ForeignKey(User, PROTECT, related_name='owner') + mnps = FloatField(default=0.00) + dev_mnps = FloatField(default=0.00) + base_mnps = FloatField(default=0.00) + updated = DateTimeField(auto_now=True) + secret = CharField(max_length=64, default='None') + info = JSONField() + workload = IntegerField(default=0) def __str__(self): return '[%d] %s' % (self.id, self.user.username) diff --git a/OpenBench/utils.py b/OpenBench/utils.py index e1f4528..e5f0cb8 100644 --- a/OpenBench/utils.py +++ b/OpenBench/utils.py @@ -119,36 +119,6 @@ def getMachineStatus(username=None): "{0} Threads / ".format(sum([f.info['concurrency'] for f in machines])) + \ "{0} MNPS ".format(round(sum([f.info['concurrency'] * f.mnps for f in machines]), 2)) -def get_test_context(test): - - # Select the Test, and all Result objects attached - results = Result.objects.filter(test=test).order_by('machine_id') - data = { 'test' : test, 'results': {} } - - for result in results: - - # Insert the Result into the results - if result.machine.id not in data['results'].keys(): - data['results'][result.machine.id] = { - 'games' : 0, 'wins' : 0, 'losses' : 0, - 'draws' : 0, 'timeloss' : 0, 'crashes' : 0, - } - - # Always use the latest Time stamp, by virtue of sorting Results - data['results'][result.machine.id]['machine_id'] = result.machine.id - data['results'][result.machine.id]['username' ] = result.machine.user.username - data['results'][result.machine.id]['updated' ] = result.updated - - # Sum up all results from a given machine into a single value - data['results'][result.machine.id]['games' ] += result.games - data['results'][result.machine.id]['wins' ] += result.wins - data['results'][result.machine.id]['losses' ] += result.losses - data['results'][result.machine.id]['draws' ] += result.draws - data['results'][result.machine.id]['timeloss' ] += result.timeloss - data['results'][result.machine.id]['crashes' ] += result.crashes - - return data - def getPaging(content, page, url, pagelen=25): start = max(0, pagelen * (page - 1)) @@ -269,6 +239,10 @@ def collect_github_info(request, errors, field): # Actual branches have to go one layer deeper elif not bysha: data = data['commit'] + # Check that all the data we need going forward is present + assert 'message' in data['commit'] and 'sha' in data + assert private or 'sha' in data['commit']['tree'] + except: # Unable to find for whatever reason errors.append('%s could not be found' % (branch)) return (None, None) @@ -279,7 +253,7 @@ def collect_github_info(request, errors, field): return (None, None) # Public Engines: Construct the .zip download and return everything - if not OPENBENCH_CONFIG['engines'][engine]['private']: + if not private: treeurl = data['commit']['tree']['sha'] + '.zip' source = path_join(request.POST['%s_repo' % (field)], 'archive', treeurl) return (source, branch, data['sha'], bench), True @@ -292,7 +266,7 @@ def collect_github_info(request, errors, field): url, has_all = fetch_artifact_url(base, engine, headers, data['sha']) return (url, branch, data['sha'], bench), has_all -def fetch_artifact_url(base, engine, headers, sha): +def fetch_artifact_url(base, engine, headers, sha, return_data=False): try: # Fetch the run id for the openbench workflow for this comment @@ -300,17 +274,26 @@ def fetch_artifact_url(base, engine, headers, sha): url += '?head_sha=%s' % (sha) run_id = requests.get(url=url, headers=headers).json()['workflow_runs'][0]['id'] - # Construct the final URL that will be used to look at artifacts + # Fetch information about individual job results + url = path_join(base, 'actions', 'runs', str(run_id), 'jobs') + jobs = requests.get(url=url, headers=headers).json()['jobs'] + + # Fetch information about individual artifact url = path_join(base, 'actions', 'runs', str(run_id), 'artifacts') artifacts = requests.get(url=url, headers=headers).json()['artifacts'] - # Verify that all of the artifacts exist and are not expired - available = [ f['name'] for f in artifacts if f['expired'] == False ] - required = OPENBENCH_CONFIG['engines'][engine]['build']['artifacts'] - has_all = all(['%s-%s' % (sha, name) in available for name in required]) + # All jobs finished, with an associated, non-expired Artifact + error = any(job['conclusion'] != 'success' for job in jobs) + error = error or any(artifact['expired'] for artifact in artifacts) + error = error or len(jobs) != len(artifacts) - # Return the URL iff we found them; otherwise base - return (url if has_all else base, has_all) + # Toss back the data if we care about it + if error and return_data: + return ((jobs, artifacts), False) + + # Only set the url if we have everything we need + assert not error + return (url, True) except Exception as error: # If anything goes wrong, retry later with the same base URL @@ -353,8 +336,9 @@ def verify_test_creation(request): except: errors.append('Invalid Draw Adjudication Setting. Try "None"?') def verify_github_repo(field): - try: assert request.POST[field].startswith('https://github.com/') - except: errors.append('Sources must be found on https://github.com/') + pattern = r'^https:\/\/github\.com\/[A-Za-z0-9-]+\/[A-Za-z0-9_.-]+\/?$' + try: assert re.match(pattern, request.POST[field]) + except: errors.append('Sources must be found on https://github.com//') def verify_network(field, fieldName): try: @@ -390,8 +374,9 @@ def verify_test_creation(request): except: errors.append('Fixed Games Tests must last at least one game') def verify_syzygy_field(field, field_name): - try: assert request.POST[field] in ['OPTIONAL', 'REQUIRED', 'DISABLED'] - except: errors.append('{0} must be OPTIONAL, REQUIRED, or DISABLED'.format(field_name)) + candidates = ['OPTIONAL', 'DISABLED', '3-MAN', '4-MAN', '5-MAN', '6-MAN'] + try: assert request.POST[field] in candidates + except: errors.append('%s must be in %s' % (field_name, ', '.join(candidates))) verifications = [ @@ -532,9 +517,11 @@ def get_workload(machine): if not (tests := get_valid_workloads(machine)): return {} - # Select from valid workloads and create a Result object - test = select_workload(machine, tests) - result = Result(test=test, machine=machine) + # Select from valid workloads the most needing test + test = select_workload(machine, tests) + + try: result = Result.objects.get(test=test, machine=machine) + except: result = Result(test=test, machine=machine) # Update the Machine's status and save everything machine.workload = test.id; machine.save(); result.save() @@ -555,33 +542,33 @@ def get_valid_workloads(machine): tests = tests.exclude(base_engine=engine) # Skip tests with unmet Syzygy requirments - if not machine.info['syzygy_wdl']: - tests = tests.exclude(syzygy_adj='REQUIRED') - tests = tests.exclude(syzygy_wdl='REQUIRED') + for K in range(machine.info['syzygy_max'] + 1, 10): + tests = tests.exclude(syzygy_adj='%d-MAN' % (K)) + tests = tests.exclude(syzygy_wdl='%d-MAN' % (K)) # Skip tests that would waste available Threads or exceed them threads = machine.info['concurrency'] - ncutechess = machine.info['ncutechesses'] + sockets = machine.info['sockets'] hyperthreads = machine.info['physical_cores'] < threads options = [x for x in tests if - test_maps_onto_thread_count(x, threads, ncutechess, hyperthreads)] + test_maps_onto_thread_count(x, threads, sockets, hyperthreads)] # Finally refine for tests of the highest priority if not options: return [] highest_prio = max(options, key=lambda x: x.priority).priority return [test for test in options if test.priority == highest_prio] -def test_maps_onto_thread_count(test, threads, ncutechess, hyperthreads): +def test_maps_onto_thread_count(test, threads, sockets, hyperthreads): dev_threads = int(extract_option(test.dev_options, 'Threads')) base_threads = int(extract_option(test.base_options, 'Threads')) # Each individual cutechess copy must have access to sufficient Threads - if max(dev_threads, base_threads) > (threads / ncutechess): + if max(dev_threads, base_threads) > (threads / sockets): return False # Intentional Thread Imbalance, or real cores, or evenly distributed - return dev_threads != base_threads or not hyperthreads or (threads / ncutechess) % dev_threads == 0 + return dev_threads != base_threads or not hyperthreads or (threads / sockets) % dev_threads == 0 def select_workload(machine, tests, variance=0.25): @@ -638,6 +625,7 @@ def workload_to_dictionary(test, result): 'time_control' : test.dev_time_control, 'nps' : OPENBENCH_CONFIG['engines'][test.dev_engine]['nps'], 'build' : OPENBENCH_CONFIG['engines'][test.dev_engine]['build'], + 'private' : OPENBENCH_CONFIG['engines'][test.dev_engine]['private'], }, 'base' : { @@ -652,6 +640,7 @@ def workload_to_dictionary(test, result): 'time_control' : test.base_time_control, 'nps' : OPENBENCH_CONFIG['engines'][test.base_engine]['nps'], 'build' : OPENBENCH_CONFIG['engines'][test.base_engine]['build'], + 'private' : OPENBENCH_CONFIG['engines'][test.base_engine]['private'], }, }, } diff --git a/OpenBench/views.py b/OpenBench/views.py index b10e62f..6c65292 100644 --- a/OpenBench/views.py +++ b/OpenBench/views.py @@ -18,7 +18,7 @@ # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # -import os, hashlib, datetime, json, secrets, re +import os, hashlib, datetime, json, secrets, sys, re import django.http import django.shortcuts @@ -365,7 +365,8 @@ def test(request, id, action=None): return django.http.HttpResponseRedirect('/index/') if action not in ['APPROVE', 'RESTART', 'STOP', 'DELETE', 'MODIFY']: - return render(request, 'test.html', OpenBench.utils.get_test_context(test)) + data = { 'test' : test, 'results': Result.objects.filter(test=test) } + return render(request, 'test.html', data) if not request.user.is_authenticated: return redirect(request, '/login/', error='Only users may interact with tests') @@ -590,6 +591,7 @@ def client_get_build_info(request): data = {} for engine, config in OPENBENCH_CONFIG['engines'].items(): data[engine] = config['build'] + data[engine]['private'] = config['private'] return JsonResponse(data) @csrf_exempt @@ -628,6 +630,10 @@ def client_worker_info(request): if not data['private'] and engine not in machine.info['compilers'].keys(): continue + # Must match the Operating Systems supported by the engine + if machine.info['os_name'] not in data['build']['systems']: + continue + # All requirements are met, and this Machine can play with the given engine machine.info['supported'].append(engine) @@ -696,8 +702,11 @@ def client_submit_nps(request): machine, response = client_verify_worker(request) if response != None: return response - # Update the NPS counter for the GUI views - machine.mnps = float(request.POST['nps']) / 1e6; machine.save() + # Update the NPS counters for the GUI views + machine.mnps = float(request.POST['nps' ]) / 1e6; + machine.dev_mnps = float(request.POST['dev_nps' ]) / 1e6; + machine.base_mnps = float(request.POST['base_nps']) / 1e6; + machine.save() # Pass back an empty JSON response return JsonResponse({}) diff --git a/Templates/OpenBench/create_test.html b/Templates/OpenBench/create_test.html index 890acb0..65c82c3 100644 --- a/Templates/OpenBench/create_test.html +++ b/Templates/OpenBench/create_test.html @@ -132,9 +132,12 @@
@@ -150,9 +153,12 @@
diff --git a/Templates/OpenBench/machine.html b/Templates/OpenBench/machine.html index e8c1583..9fafe34 100644 --- a/Templates/OpenBench/machine.html +++ b/Templates/OpenBench/machine.html @@ -25,7 +25,7 @@ Logical Cores{{machine.info.logical_cores}} Physical Cores{{machine.info.physical_cores}} Total RAM (MB){{machine.info.ram_total_mb}} - Syzygy WDL-6{{machine.info.syzygy_wdl}} + Syzygy WDL{{machine.info.syzygy_max}}-Man
diff --git a/Templates/OpenBench/test.html b/Templates/OpenBench/test.html index 215f16b..2f803b2 100644 --- a/Templates/OpenBench/test.html +++ b/Templates/OpenBench/test.html @@ -64,6 +64,7 @@ Base Engine{{test.base_engine}} Base Source{{test.base_repo}} Base Sha{{test.base.sha}} + Base Branch{{test.base.name|prettyName}} Base Bench{{test.base.bench}} {% if test.base_network %} @@ -172,10 +173,10 @@ Crash - {% for id, result in results.items %} + {% for result in results %} - {{result.machine_id}} - {{result.username|capfirst}} + {{result.machine.id}} + {{result.machine.user.username|capfirst}} {{result.updated|date:'U'}} {{result.games}} {{result.wins}}