diff --git a/.gitignore b/.gitignore index 09f477f..5569687 100644 --- a/.gitignore +++ b/.gitignore @@ -10,4 +10,8 @@ Scripts/Binaries/* Scripts/Networks/* Scripts/Repositories/* -Media/* \ No newline at end of file +Media/* + +!Client/*.py +!Client/cutechess-ob +!Client/cutechess-ob.exe diff --git a/Client/Client.py b/Client/Client.py index 0ffde53..06f0c79 100644 --- a/Client/Client.py +++ b/Client/Client.py @@ -19,1405 +19,75 @@ # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # import argparse -import cpuinfo -import hashlib -import json -import multiprocessing import os -import platform -import psutil -import queue -import re import requests -import shutil -import subprocess -import sys -import threading -import time -import traceback -import uuid +import tempfile import zipfile -from subprocess import PIPE, Popen, call, STDOUT -from itertools import combinations_with_replacement -from concurrent.futures import ThreadPoolExecutor - -## Basic configuration of the Client. These timeouts can be changed at will - -CLIENT_VERSION = 18 # 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): - - # 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.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] - - 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 ['SSE41', 'SSE42']) - 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 ['AVX512VNNI']) - - # 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: - - ## 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' : 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, 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, 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) - -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'] - 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' % (command, control, options, branch) - - @staticmethod - def pgnout_settings(config, timestamp, cutechess_idx): - - test_id = int(config.workload['test']['id']) - result_id = int(config.workload['result']['id']) - - # Format: --