Update download_network.py script, and bench_engine.py script

This commit is contained in:
andrew committed 2023-07-14 22:50:30 -04:00
1 parent 353e9e6f3c
commit 5d6ae6a06b
4 files changed
+104 -185

No files matched your search

-139
View File
@@ -1,139 +0,0 @@
import argparse
import hashlib
import multiprocessing
import os
import re
import requests
import subprocess
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
from bench_engine import run_benchmark
from OpenBench.config import OPENBENCH_CONFIG
USE_OLD_BINARIES = True
OPENBENCH_USERNAME = None
OPENBENCH_PASSWORD = None
OPENBENCH_SERVER = 'http://chess.grantnet.us'
BENCHMARK_THREADS = None
BENCHMARK_SETS = None
def download_network(engine, sha256):
if not os.path.isdir('Networks'):
os.mkdir('Networks')
if not os.path.isfile('Networks/%s' % (sha256)):
print ('Downloading %s for %s...' % (sha256, engine))
target = '%s/clientGetNetwork/%s/' % (OPENBENCH_SERVER, sha256)
payload = { 'username' : OPENBENCH_USERNAME, 'password' : OPENBENCH_PASSWORD }
request = requests.post(data=payload, url=target)
with open('Networks/%s' % (sha256), 'wb') as fout:
for chunk in request.iter_content(chunk_size=1024):
if chunk: fout.write(chunk)
fout.flush()
with open('Networks/%s' % (sha256), 'rb') as network:
assert sha256 == hashlib.sha256(network.read()).hexdigest()[:8].upper()
def download_default_networks():
target = '%s/networks/' % (OPENBENCH_SERVER)
information = requests.get(url=target)
pattern = r'class="fas fa-star">.*?<a href="/networks/(?P<eng>.*?)/".*?<a href="/networks/download/(?P<sha>.{8})'
default_networks = list(re.findall(pattern, information.text))
for engine, network in default_networks:
download_network(engine, network)
return { engine : network for engine, network in default_networks }
def update_repositories():
if not os.path.isdir('Repositories'):
os.mkdir('Repositories')
for engine, config in OPENBENCH_CONFIG['engines'].items():
if not os.path.isdir('Repositories/' + config['source'].split('/')[-1]):
os.system('cd Repositories && git clone %s && cd ../' % (config['source']))
if not USE_OLD_BINARIES:
os.system('cd Repositories/%s && git pull && cd ../../' % config['source'].split('/')[-1])
def build_engine(engine, config, defaults):
git_path = 'Repositories/' + config['source'].split('/')[-1]
base_path = os.path.dirname(os.path.realpath(__file__))
build_path = os.path.join(base_path, git_path, config['build']['path'])
command = 'make -j EXE=%s' % (engine)
if engine in defaults:
command += ' EVALFILE=%s' % (os.path.join(base_path, 'Networks', defaults[engine]).replace('\\', '/'))
print ('=' * 120)
print ('Attempting to build %s...' % (engine))
subprocess.Popen(command.split(), cwd=build_path).wait()
if os.path.isfile(os.path.join(build_path, engine)):
os.rename(os.path.join(build_path, engine), os.path.join('Binaries', engine))
print ('Succesfully built %s' % (engine))
if os.path.isfile(os.path.join(build_path, engine + '.exe')):
os.rename(os.path.join(build_path, engine + '.exe'), os.path.join('Binaries', engine))
print ('Succesfully built %s' % (engine))
print ('=' * 120)
print ()
def build_all_engines():
update_repositories()
defaults = download_default_networks()
if not os.path.isdir('Binaries'):
os.mkdir('Binaries')
for engine, config in OPENBENCH_CONFIG['engines'].items():
if USE_OLD_BINARIES and os.path.isfile('Binaries/' + engine):
continue
build_engine(engine, config, defaults)
def bench_built_engines():
for engine in sorted(os.listdir('Binaries')):
nps = run_benchmark('./Binaries/%s' % (engine), BENCHMARK_THREADS, BENCHMARK_SETS)
print ('%-15s | %d' % (engine, nps))
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'
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('-T', '--threads' , help='Concurrent Benchmarks', required=True)
p.add_argument('-S', '--sets' , help='Benchmark Sample Count', required=True)
p.add_argument('-R', '--rebuild' , help='Rebuild Binaries', action='store_true')
arguments = p.parse_args()
USE_OLD_BINARIES = not arguments.rebuild
OPENBENCH_USERNAME = arguments.username
OPENBENCH_PASSWORD = arguments.password
BENCHMARK_THREADS = int(arguments.threads)
BENCHMARK_SETS = int(arguments.sets)
if arguments.username is None: OPENBENCH_USERNAME = os.environ['OPENBENCH_USERNAME']
if arguments.password is None: OPENBENCH_PASSWORD = os.environ['OPENBENCH_PASSWORD']
build_all_engines()
bench_built_engines()
+44 -15
View File
@@ -1,3 +1,25 @@
#!/bin/python3
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# OpenBench is a chess engine testing framework by Andrew Grant. #
# <https://github.com/AndyGrant/OpenBench> <andrew@grantnet.us> #
# #
# OpenBench is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# OpenBench is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
import argparse
import multiprocessing
import re
@@ -27,52 +49,59 @@ def parse_stream_output(stream):
# Parse out the integer portion from our matches
nps = int(re.search(r'\d+', nps ).group()) if nps else None
bench = int(re.search(r'\d+', bench).group()) if bench else None
return (bench, nps)
def single_core_bench(engine, outqueue):
def single_core_bench(engine, network, outqueue):
# Basic command for Public engines
cmd = ['./' + engine, 'bench']
# Adjust to handle setting Networks in Private engines
if network:
option = 'setoption name EvalFile value %s' % (network)
cmd = ['./%s' % (engine), option, 'bench', 'quit']
# Launch the bench and wait for results
stdout, stderr = subprocess.Popen(
'./{0} bench'.format(engine).split(),
stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
).communicate()
outqueue.put(parse_stream_output(stdout))
def multi_core_bench(engine, threads):
def multi_core_bench(engine, network, threads):
outqueue = multiprocessing.Queue()
processes = [
multiprocessing.Process(
target=single_core_bench,
args=(engine, outqueue)
args=(engine, network, outqueue)
) for ii in range(threads)
]
for process in processes: process.start()
return [outqueue.get() for ii in range(threads)]
def run_benchmark(engine, threads, sets):
def run_benchmark(engine, network, threads, sets):
benches, speeds = [], []
for ii in range(sets):
for bench, speed in multi_core_bench(engine, threads):
for bench, speed in multi_core_bench(engine, network, threads):
benches.append(bench); speeds.append(speed)
if len(set(benches)) != 1:
print("Error: Non-Deterministic Results!")
sys.exit()
return (0, 0)
return int(sum(speeds) / len(speeds))
return int(sum(speeds) / len(speeds)), benches[0]
if __name__ == '__main__':
p = argparse.ArgumentParser()
p.add_argument('-E', '--engine' , help='Binary Name', required=True)
p.add_argument('-T', '--threads' , help='Concurrent Benchmarks', required=True)
p.add_argument('-S', '--sets' , help='Benchmark Sample Count', required=True)
p.add_argument('-E', '--engine' , help='Binary Name', required=True)
p.add_argument('-N', '--network' , help='Networks for Private Engines', required=False)
p.add_argument('-T', '--threads' , help='Concurrent Benchmarks', required=True)
p.add_argument('-S', '--sets' , help='Benchmark Sample Count', required=True)
args = p.parse_args()
print (run_benchmark(args.engine, int(args.threads), int(args.sets)))
print (run_benchmark(args.engine, args.network, int(args.threads), int(args.sets)))
+52 -27
View File
@@ -1,46 +1,71 @@
#!/usr/bin/python3
#!/bin/python3
import argparse, hashlib, os, requests
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# OpenBench is a chess engine testing framework by Andrew Grant. #
# <https://github.com/AndyGrant/OpenBench> <andrew@grantnet.us> #
# #
# OpenBench is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# OpenBench is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
OPENBENCH_SERVER = 'http://chess.grantnet.us'
import argparse
import hashlib
import os
import requests
def download_network(username, password, sha256):
def url_join(*args):
# Join a set of URL paths while maintaining the correct format
return '/'.join([f.lstrip('/').rstrip('/') for f in args]) + '/'
print ('Downloading %s...' % (sha256))
def download_network(username, password, server, engine, name):
# Check if we already have the Network file by looking at SHA256
if os.path.isfile(sha256):
with open(sha256, 'rb') as network:
if sha256 == hashlib.sha256(network.read()).hexdigest()[:8].upper():
return
print ('Downloading %s for %s...' % (name, engine))
target = '%s/clientGetNetwork/%s/' % (OPENBENCH_SERVER, sha256)
target = url_join(server, 'clientGetNetwork', engine, name)
payload = { 'username' : username, 'password' : password }
request = requests.post(data=payload, url=target)
with open(sha256, 'wb') as fout:
with open(name, 'wb') as fout:
for chunk in request.iter_content(chunk_size=1024):
if chunk: fout.write(chunk)
fout.flush()
with open(sha256, 'rb') as network:
if sha256 != hashlib.sha256(network.read()).hexdigest()[:8].upper():
print ('Failed to Download...')
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'
# We can use ENV variables for Username, Password, and Server
req_user = required=('OPENBENCH_USERNAME' not in os.environ)
req_pass = required=('OPENBENCH_PASSWORD' not in os.environ)
req_server = required=('OPENBENCH_SERVER' not in os.environ)
# For clarity, seperate out this help text
help_user = 'Username. May also be passed as OPENBENCH_USERNAME environment variable'
help_pass = 'Password. May also be passed as OPENBENCH_PASSWORD environment variable'
help_server = ' Server. May also be passed as OPENBENCH_SERVER environment variable'
# Parse all arguments, all of which must exist in some form
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('-N', '--network', help='Network SHA256', required=True)
arguments = p.parse_args()
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=help_server , required=req_server)
p.add_argument('-E', '--engine' , help='Engine' , required=True )
p.add_argument('-N', '--network' , help='Name or Sha', required=True )
args = p.parse_args()
if arguments.username is None: arguments.username = os.environ['OPENBENCH_USERNAME']
if arguments.password is None: arguments.password = os.environ['OPENBENCH_PASSWORD']
# Fallback on ENV variables for Username, Password, and Server
args.username = args.username if args.username else os.environ['OPENBENCH_USERNAME']
args.password = args.password if args.password else os.environ['OPENBENCH_PASSWORD']
args.server = args.server if args.server else os.environ['OPENBENCH_SERVER' ]
download_network(arguments.username, arguments.password, arguments.network)
download_network(args.username, args.password, args.server, args.engine, args.network)
+8 -4
View File
@@ -1,3 +1,5 @@
#!/bin/python3
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# OpenBench is a chess engine testing framework by Andrew Grant. #
@@ -23,9 +25,11 @@ import os
import re
import requests
from urllib.parse import urljoin
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 upload_file():
def upload_network():
# We can use ENV variables for Username, Password, and Server
req_user = required=('OPENBENCH_USERNAME' not in os.environ)
@@ -53,7 +57,7 @@ def upload_file():
args.server = args.server if args.server else os.environ['OPENBENCH_SERVER' ]
# All scripts connect through this API point, with an action in the POST data
url = urljoin(args.server, 'scripts/')
url = url_join(args.server, 'scripts')
# POST payload must contain an action value
data = {
@@ -80,4 +84,4 @@ def upload_file():
print ('Status: %s' % (matches[0].strip()))
if __name__ == '__main__':
upload_file()
upload_network()