diff --git a/Client/utils.py b/Client/utils.py index d0cdf54..7851989 100644 --- a/Client/utils.py +++ b/Client/utils.py @@ -18,9 +18,11 @@ # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +import shutil import argparse import hashlib import os +import platform import requests import subprocess import tempfile @@ -31,11 +33,26 @@ class OpenBenchBuildFailedException(Exception): self.message = message super().__init__(self.message) +class OpenBenchCorruptedNetworkException(Exception): + def __init__(self, message): + self.message = message + super().__init__(self.message) -def url_join(*args): +class OpenBenchMissingAPICredentialsException(Exception): + def __init__(self, message): + self.message = message + super().__init__(self.message) + +class OpenBenchMissingArtifactExceptionException(Exception): + def __init__(self, message): + self.message = message + super().__init__(self.message) + + +def url_join(*args, trailing_slash=True): # Join a set of URL paths while maintaining the correct format - return '/'.join([f.lstrip('/').rstrip('/') for f in args]) + '/' + return '/'.join([f.lstrip('/').rstrip('/') for f in args]) + ['', '/'][trailing_slash] def credentialed_cmdline_args(parser=None): @@ -76,20 +93,34 @@ def credentialed_request(server, username, password, endpoint): return requests.post(data=payload, url=target) +def read_git_credentials(engine): + fname = 'credentials.%s' % (engine.replace(' ', '').lower()) + if os.path.exists(fname): + with open(fname) as fin: + return { 'Authorization' : 'token %s' % fin.readlines()[0].rstrip() } + raise OpenBenchMissingAPICredentialsException('%s not found' % fname) -def makefile_command(net_path, make_path, out_path, compiler, threads): - # Build with EXE= to contol the output location - command = ['make', 'EXE=%s' % (out_path)] +def check_for_engine_binary(out_path): + + # Check for already having the binary ( Linux ) + if os.path.isfile(out_path): + return out_path + + # Check for already having the binary ( Windows ) + if os.path.isfile('%s.exe' % (out_path)): + return '%s.exe' % (out_path) + +def makefile_command(net_path, make_path, out_path, compiler): + + # Build with -j, and EXE= to contol the output location + command = ['make', '-j', 'EXE=%s' % (out_path)] # Build with CC/CXX= when using a custom compiler if compiler: comp_flag = ['CC', 'CXX']['++' in compiler] command += ['%s=%s' % (comp_flag, compiler)] - # Build with -jN, or just -j if threads is not explicit - command += ['-j' if not threads else '-j%d' % (threads)] - # Build with EVALFILE= to embed NNUE files if net_path: rel_net_path = os.path.relpath(os.path.abspath(net_path), make_path) @@ -97,15 +128,59 @@ def makefile_command(net_path, make_path, out_path, compiler, threads): return command +def select_best_artifact(options, cpu_name, cpu_flags): + + # Step 1. Filter down to our operating system only + artifacts = [x for x in options.keys() if x.split('-')[1] == platform.system().lower()] + + # Pick betwen various Vector instruction sets that might apply + has_ssse3 = all(x in cpu_flags for x in ['SSSE3']) + has_sse4 = has_ssse3 and all(x in cpu_flags for x in ['SSE41', 'SSE42']) + has_avx = has_sse4 and all(x in cpu_flags for x in ['AVX']) + has_avx2 = has_avx and all(x in cpu_flags for x in ['AVX2', 'FMA']) + has_avx512 = has_avx2 and all(x in cpu_flags for x in ['AVX512BW', 'AVX512DQ', 'AVX512F']) + has_vnni = has_avx512 and all(x in 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 artifacts]: + artifacts = [x for x in artifacts if x.split('-')[2] == identifier] + break + + # Identify any Ryzen or AMD chip, excluding the 7B12 + ryzen = 'AMD' in cpu_name.upper() + ryzen = 'RYZEN' in cpu_name.upper() or ryzen + ryzen = ryzen and '7B12' not in cpu_name.upper() + + # Pick between POPCNT and BMI2/PEXT + has_popcnt = 'POPCNT' in cpu_flags + has_bmi2 = 'BMI2' in 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 artifacts]: + artifacts = [x for x in artifacts if x.split('-')[3] == identifier] + break + + return options[artifacts[0]] + def download_network(server, username, password, engine, net_name, net_sha, net_path): - print ('Fetching %s (%s) for %s' % (net_name, net_sha, engine)) - # Avoid redownloading Network files if not os.path.isfile(net_path): # Format the API request, including credentials + print ('Fetching %s (%s) for %s' % (net_name, net_sha, engine)) endpoint = '/api/networks/%s/%s' % (engine, net_sha) request = credentialed_request(server, username, password, endpoint) @@ -116,23 +191,20 @@ def download_network(server, username, password, engine, net_name, net_sha, net_ fout.flush() # Check for the first 8 characters of the sha256 + print ('Verifying %s (%s) for %s' % (net_name, net_sha, engine)) with open(net_path, 'rb') as network: sha256 = hashlib.sha256(network.read()).hexdigest()[:8].upper() # Verify the download and delete partial or corrupted ones if net_sha != sha256: os.remove(net_path) - raise Exception('Invalid SHA for %s' % (network_sha)) + raise OpenBenchCorruptedNetworkException('Invalid SHA for %s' % (network_sha)) -def download_public_engine(engine, net_path, branch, source, make_path, out_path, compiler=None, threads=None): +def download_public_engine(engine, net_path, branch, source, make_path, out_path, compiler=None): - # Check for already having the binary ( Linux ) - if os.path.isfile(out_path): - return out_path - - # Check for already having the binary ( Windows ) - if os.path.isfile('%s.exe' % (out_path)): - return '%s.exe' % (out_path) + # Check to see if we already have the binary + if check_for_engine_binary(out_path): + return check_for_engine_binary(out_path) # Work with temp files and directories until finished building with tempfile.TemporaryDirectory() as temp_dir: @@ -157,22 +229,53 @@ def download_public_engine(engine, net_path, branch, source, make_path, out_path # Prepare the MAKEFILE command make_path = os.path.join(src_path, make_path) rel_out_path = os.path.relpath(os.path.abspath(out_path), make_path) - make_cmd = makefile_command(net_path, make_path, rel_out_path, compiler, threads) + make_cmd = makefile_command(net_path, make_path, rel_out_path, compiler) # Build the engine, which will produce a binary to the original out_path process = subprocess.Popen(make_cmd, cwd=make_path, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) comp_output = process.communicate()[0].decode('utf-8') - # Indicate where the true binary name ( Linux ) - if os.path.isfile(out_path): - return out_path - - # Indicate where the true binary name ( Windows ) - if os.path.isfile('%s.exe' % (out_path)): - return '%s.exe' % (out_path) + # Check to see if we already have the binary + if check_for_engine_binary(out_path): + return check_for_engine_binary(out_path) # Someone should catch this, and possibly report it to the OpenBench server raise OpenBenchBuildFailedException(comp_output) +def download_private_engine(engine, branch, source, out_path, cpu_name, cpu_flags, compiler=None): + # Check to see if we already have the binary + if check_for_engine_binary(out_path): + return check_for_engine_binary(out_path) + # Pick the best artifact to match this machine + headers = read_git_credentials(engine) + artifacts = requests.get(url=source, headers=headers).json()['artifacts'] + options = { artifact['name'] : artifact for artifact in artifacts } + best = select_best_artifact(options, cpu_name, cpu_flags) + + # Work with temp files and directories until finished extracting + with tempfile.TemporaryDirectory() as temp_dir: + + print('Fetching [%s-%s]' % (engine, branch)) + + # Download the zip file from Github + zip_path = os.path.join(temp_dir, '%s-%s' % (engine, branch)) + with open(zip_path, 'wb') as zip_file: + zip_file.write(requests.get(best['archive_download_url'], headers=headers).content) + + # Unzip the engine to a directory called + unzip_path = os.path.join(temp_dir, engine) + with zipfile.ZipFile(zip_path, 'r') as zip_file: + zip_file.extractall(unzip_path) + + # Rename the sole binary + unzip_root = os.path.join(unzip_path, os.listdir(unzip_path)[0]) + shutil.move(unzip_root, out_path) + + # Check to see if we already have the binary + if check_for_engine_binary(out_path): + return check_for_engine_binary(out_path) + + # Someone should catch this, and possibly report it to the OpenBench server + raise OpenBenchMissingArtifactExceptionException('Failed to fetch %s' % (best['name'])) diff --git a/Scripts/bench_all.py b/Scripts/bench_all.py index 002ed51..7bb90a5 100644 --- a/Scripts/bench_all.py +++ b/Scripts/bench_all.py @@ -21,6 +21,7 @@ # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # import argparse +import cpuinfo import os import requests import sys @@ -32,8 +33,11 @@ sys.path.append(os.path.abspath(PARENT)) from Client.utils import url_join from Client.utils import credentialed_cmdline_args from Client.utils import credentialed_request +from Client.utils import read_git_credentials from Client.utils import download_network from Client.utils import download_public_engine +from Client.utils import download_private_engine + def get_default_network_if_any(args, networks): @@ -49,6 +53,37 @@ def get_default_network_if_any(args, networks): return net_path +def get_public_engine(engine, config, net_path): + + make_path = config['build']['path'] + branch = config['test_presets']['default']['base_branch'] + out_path = os.path.join('Engines', engine) + target = url_join(config['source'], 'archive', '%s.zip' % (branch)) + + download_public_engine(engine, net_paths[engine], branch, target, make_path, out_path) + +def get_private_engine(engine, config): + + out_path = os.path.join('Engines', engine) + branch = config['test_presets']['default']['base_branch'] + + # Format an API request to get the most recent openbench.yml workflow on the primary branch + api_repo = config['source'].replace('github.com', 'api.github.com/repos') + target = url_join(api_repo, 'actions/workflows/openbench.yml/runs', trailing_slash=False) + target += '?branch=%s' % (branch) + + # Use the run_id for the primary branch's openbench.yml workflow to locate the artifacts + headers = read_git_credentials(engine) + run_id = requests.get(url=target, headers=headers).json()['workflow_runs'][0]['id'] + source = url_join(api_repo, 'actions/runs/%d/artifacts' % (run_id), trailing_slash=False) + + # Selecting an artifact requires knowledge of the CPU + cpu_info = cpuinfo.get_cpu_info() + cpu_name = cpu_info.get('brand_raw', cpu_info.get('brand', 'Unknown')) + cpu_flags = [x.replace('_', '').replace('.', '').upper() for x in cpu_info.get('flags', [])] + + download_private_engine(engine, branch, source, out_path, cpu_name, cpu_flags, None) + if __name__ == '__main__': # Use bench_all.py's path as the base pathway @@ -63,24 +98,27 @@ if __name__ == '__main__': args = credentialed_cmdline_args() request = credentialed_request(args.server, args.username, args.password, 'api/config') + configs = {} # Get the configuration file for all the engines for engine in request.json()['engines']: - - if engine == 'Torch': - continue - - # Get the configuration file for the engine endpoint = 'api/config/%s' % (engine) request = credentialed_request(args.server, args.username, args.password, endpoint) - config = request.json() + configs[engine] = request.json() - # Get the list of all Networks for the engine + net_paths = {} # Get all the Network files for the engines + for engine, config in configs.items(): endpoint = 'api/networks/%s' % (engine) request = credentialed_request(args.server, args.username, args.password, endpoint) - net_path = get_default_network_if_any(args, request.json()) + net_paths[engine] = get_default_network_if_any(args, request.json()) + + # Download, build, and move the Private engines to Engines/ + for engine, config in configs.items(): + if config['private']: + get_private_engine(engine, config) + + # Download and move the Public engines to Engines/ + for engine, config in configs.items(): + if not config['private']: + get_public_engine(engine, config, net_paths[engine]) + + - # Download, build, and move the engine to Engines/ - make_path = config['build']['path'] - branch = config['test_presets']['default']['base_branch'] - out_path = os.path.join('Engines', engine) - target = url_join(config['source'], 'archive', '%s.zip' % (branch)) - download_public_engine(engine, net_path, branch, target, make_path, out_path)