Modernize running benchmarks and reporting errors

This commit is contained in:
andrew authored and Andrew Grant committed 2024-02-02 05:35:19 -05:00
1 parent 8f250c2c3f
commit c268b47e4d
7 files changed
+175 -170

No files matched your search

+117
View File
@@ -0,0 +1,117 @@
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# 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/>. #
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# The sole purpose of this module is to invoke run_benchmark().
#
# - binary : Path to, and including, the Binary File
# - network : Path to Network File, or None
# - private : True or False; Private NNUE engines require special care
# - threads : Number of concurrent benches to run
# - sets : Number of times to repeat this experiment
# - expected : None, or an expected value, which if not matched raises Exceptions
#
# run_benchmark() may raise utils.OpenBenchBadBenchException.
# An associated error message, including the binary name, is included
import multiprocessing
import os
import re
import subprocess
import sys
from utils import OpenBenchBadBenchException
def parse_stream_output(stream):
nps = bench = None # Search through output Stream
for line in stream.decode('ascii').strip().split('\n')[::-1]:
# Convert non alpha-numerics to spaces
line = re.sub(r'[^a-zA-Z0-9 ]+', ' ', line)
# Multiple methods, including Ethereal and Stockfish
nps_pattern = r'(\d+\s+nps)|(nps\s+\d+)|(nodes second\s+\d+)'
bench_pattern = r'(\d+\s+nodes)|(nodes\s+\d+)|(nodes searched\s+\d+)'
# Search for and set only once the NPS value
if (re_nps := re.search(nps_pattern, line, re.IGNORECASE)):
nps = nps if nps else re_nps.group()
# Search for and set only once the Bench value
if (re_bench := re.search(bench_pattern, line, re.IGNORECASE)):
bench = bench if bench else re_bench.group()
# 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(binary, network, private, outqueue):
# Basic command for Public engines
cmd = ['./%s' % (binary), 'bench']
# Adjust to handle setting Networks in Private engines
if network and private:
option = 'setoption name EvalFile value %s' % (network)
cmd = ['./%s' % (binary), option, 'bench', 'quit']
try: # Launch the bench and wait for results
stdout, stderr = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
).communicate()
outqueue.put(parse_stream_output(stdout))
except: # Signal an error with (None, None)
outqueue.put((None, None))
def multi_core_bench(binary, network, private, threads):
outqueue = multiprocessing.Queue()
processes = [
multiprocessing.Process(
target=single_core_bench,
args=(binary, network, private, outqueue)
) for ii in range(threads)
]
for process in processes: process.start()
return [outqueue.get() for ii in range(threads)]
def run_benchmark(binary, network, private, threads, sets, expected=None):
engine = os.path.basename(binary)
benches, speeds = [], []
for ii in range(sets):
for bench, speed in multi_core_bench(binary, network, private, threads):
benches.append(bench); speeds.append(speed)
if len(set(benches)) != 1:
raise OpenBenchBadBenchException('[%s] Non-Deterministic Benches' % (engine))
if None in benches or None in speeds:
raise OpenBenchBadBenchException('[%s] Failed to Execute Benchmark' % (engine))
if expected and expected != benches[0]:
raise OpenBenchBadBenchException('[%s] Wrong Bench: %d' % (engine, benches[0]))
return int(sum(speeds) / len(speeds)), benches[0]
+12 -2
View File
@@ -29,6 +29,12 @@ import tempfile
import zipfile
class OpenBenchBuildFailedException(Exception):
def __init__(self, message, logs):
self.message = message
self.logs = logs
super().__init__(self.message)
class OpenBenchBadBenchException(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)
@@ -247,8 +253,11 @@ def download_network(server, username, password, engine, net_name, net_sha, net_
if chunk: fout.write(chunk)
fout.flush()
else:
print ('Found %s (%s) for %s' % (net_name, net_sha, engine))
# Check for the first 8 characters of the sha256
print ('Verifying %s (%s) for %s' % (net_name, net_sha, engine))
print ('Verifying %s (%s) for %s\n' % (net_name, net_sha, engine))
with open(net_path, 'rb') as network:
sha256 = hashlib.sha256(network.read()).hexdigest()[:8].upper()
@@ -298,7 +307,8 @@ def download_public_engine(engine, net_path, branch, source, make_path, out_path
return os.path.basename(check_for_engine_binary(out_path))
# Someone should catch this, and possibly report it to the OpenBench server
raise OpenBenchBuildFailedException(comp_output)
message = 'Error during compilation. The logs have been sent to the server'
raise OpenBenchBuildFailedException(message, comp_output)
def download_private_engine(engine, branch, source, out_path, cpu_name, cpu_flags):
+22 -82
View File
@@ -40,6 +40,10 @@ from subprocess import PIPE, Popen, call, STDOUT
from itertools import combinations_with_replacement
from concurrent.futures import ThreadPoolExecutor
## Local imports
import bench
from client import BadVersionException
from client import url_join
from client import try_forever
@@ -284,16 +288,14 @@ class ServerReporter:
return ServerReporter.report(config, 'clientSubmitError', payload)
@staticmethod
def report_bad_bench(config, branch, bench):
def report_bad_bench(config, error):
payload = {
'test_id' : config.workload['test']['id'],
'engine' : config.workload['test'][branch]['name'],
'correct' : config.workload['test'][branch]['bench'],
'wrong' : bench,
'error' : error,
}
return ServerReporter.report(config, 'clientWrongBench', payload)
return ServerReporter.report(config, 'clientBenchError', payload)
@staticmethod
def report_results(config, batches):
@@ -770,46 +772,6 @@ def validate_syzygy_exists(config, K):
return True
def parse_bench_output(stream):
nps = bench = None # Search through output Stream
for line in stream.decode('ascii').strip().split('\n')[::-1]:
# Convert non alpha-numerics to spaces
line = re.sub(r'[^a-zA-Z0-9 ]+', ' ', line)
# Multiple methods, including Ethereal and Stockfish
nps_pattern = r'(\d+\s+nps)|(nps\s+\d+)|(nodes second\s+\d+)'
bench_pattern = r'(\d+\s+nodes)|(nodes\s+\d+)|(nodes searched\s+\d+)'
# Search for and set only once the NPS value
re_nps = re.search(nps_pattern, line, re.IGNORECASE)
if re_nps:
nps = nps if nps else re_nps.group()
# Search for and set only once the Bench value
re_bench = re.search(bench_pattern, line, re.IGNORECASE)
if re_bench:
bench = bench if bench else re_bench.group()
# 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 run_bench(engine, outqueue, private_net=None):
try:
# We may need to set an EvalFile via the UCI Options
if not private_net: cmd = ['./' + engine, 'bench']
else: cmd = ['./' + engine, 'setoption name EvalFile value %s' % (private_net), 'bench', 'quit']
# Launch the engine and parse output for statistics
stdout, stderr = Popen(cmd, stdout=PIPE, stderr=STDOUT).communicate()
outqueue.put(parse_bench_output(stdout))
except Exception: outqueue.put((0, 0))
def scale_time_control(workload, scale_factor, branch):
# Extract everything from the workload dictionary
@@ -984,14 +946,10 @@ def complete_workload(config):
# 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
# 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)
# 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)
# Scale the engines together, using their NPS relative to expected
@@ -1103,47 +1061,29 @@ def download_engine(config, branch, net_path):
engine, net_path, branch_name, source, make_path, out_path, compiler)
except OpenBenchBuildFailedException as error:
ServerReporter.report_build_fail(config, branch, error.message)
ServerReporter.report_build_fail(config, branch, error.logs)
raise
def run_benchmarks(config, branch, engine, network):
queue = multiprocessing.Queue()
name = config.workload['test'][branch]['name']
private = config.workload['test'][branch]['private']
print('\nRunning %dx Benchmarks for %s' % (config.threads, name))
name = config.workload['test'][branch]['name']
private = config.workload['test'][branch]['private']
expected = int(config.workload['test'][branch]['bench'])
binary = os.path.join('Engines', engine)
args = [os.path.join('Engines', engine), queue]
if private and network:
args.append(network)
try:
print('\nRunning %dx Benchmarks for %s' % (config.threads, name))
speed, nodes = bench.run_benchmark(
binary, network, private, config.threads, 1, expected)
# Run the benchmark on all threads we are using
workers = [
multiprocessing.Process(target=run_bench, args=args)
for ii in range(config.threads)
]
except OpenBenchBadBenchException as error:
ServerReporter.report_bad_bench(config, error.message)
raise
# Start and wait for each worker to finish
for worker in workers: worker.start()
for worker in workers: worker.join()
# 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
# Output everything, including 0 for an error
print('Bench for %s is %d' % (name, bench))
print('Speed for %s is %d' % (name, nps))
# Flag the test to abort if we have a bench mismatch
error = (bench != int(config.workload['test'][branch]['bench']))
if error:
ServerReporter.report_bad_bench(config, branch, bench)
# Set NPS to 0 if we had any errors
return 0 if not bench or error else nps
print('Bench for %s is %d' % (name, nodes))
print('Speed for %s is %d' % (name, speed))
return speed
def build_cutechess_command(config, dev_cmd, base_cmd, scale_factor, timestamp, cutechess_idx):
+1 -1
View File
@@ -74,7 +74,7 @@ urlpatterns = [
django.urls.path(r'clientWorkerInfo/', OpenBench.views.client_worker_info),
django.urls.path(r'clientGetWorkload/', OpenBench.views.client_get_workload),
django.urls.path(r'clientGetNetwork/<str:engine>/<str:name>/', OpenBench.views.client_get_network),
django.urls.path(r'clientWrongBench/', OpenBench.views.client_wrong_bench),
django.urls.path(r'clientBenchError/', OpenBench.views.client_bench_error),
django.urls.path(r'clientSubmitNPS/', OpenBench.views.client_submit_nps),
django.urls.path(r'clientSubmitError/', OpenBench.views.client_submit_error),
django.urls.path(r'clientSubmitResults/', OpenBench.views.client_submit_results),
+4 -10
View File
@@ -681,22 +681,16 @@ def client_get_workload(request, machine):
@csrf_exempt
@verify_worker
def client_wrong_bench(request, machine):
def client_bench_error(request, machine):
# Find and stop the test with the bad bench
if int(request.POST['wrong']) != 0:
test = Test.objects.get(id=int(request.POST['test_id']))
test.finished = True; test.save()
# Collect information on the Error
wrong = int(request.POST['wrong'])
correct = int(request.POST['correct'])
name = request.POST['engine']
test = Test.objects.get(id=int(request.POST['test_id']))
test.finished = True; test.save()
# Log the error into the Events table
LogEvent.objects.create(
author = machine.user.username,
summary = 'Got %d Expected %d for %s' % (wrong, correct, name),
summary = request.POST['error'],
log_file = '',
machine_id = int(request.POST['machine_id']),
test_id = int(request.POST['test_id']))
+7 -2
View File
@@ -32,6 +32,7 @@ PARENT = os.path.join(os.path.dirname(__file__), os.path.pardir)
sys.path.append(os.path.abspath(PARENT))
from Client.utils import *
from Client.bench import run_benchmark
from bench_engine import run_benchmark
def get_default_network(args, network):
@@ -141,6 +142,10 @@ if __name__ == '__main__':
if not configs[engine]['private']:
get_public_engine(engine, configs[engine])
# Pretty Formatting
max_length = max(len(engine) for engine in engines)
print_format = '%-' + str(max_length) + 's %8d nps %10d nodes in %6.3f seconds'
for engine in engines:
# Builds may have failed in previous steps, which we can ignore
@@ -152,5 +157,5 @@ if __name__ == '__main__':
private_net = configs[engine]['private'] and configs[engine].get('network')
net_path = os.path.join('Networks', configs[engine]['network']['sha']) if private_net else None
nps, nodes = run_benchmark(bin_path, net_path, args.threads, args.sets)
print ('%s %d nps %d nodes in %.3f seconds' % (engine, nps, nodes, nodes / max(1e-6, nps)))
nps, nodes = run_benchmark(bin_path, net_path, private_net, args.threads, args.sets)
print (print_format % (engine, nps, nodes, nodes / max(1e-6, nps)))
+12 -73
View File
@@ -21,87 +21,26 @@
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
import argparse
import multiprocessing
import re
import subprocess
import os
import sys
def parse_stream_output(stream):
# Needed to include from ../Client/*.py
PARENT = os.path.join(os.path.dirname(__file__), os.path.pardir)
sys.path.append(os.path.abspath(PARENT))
nps = bench = None # Search through output Stream
for line in stream.decode('ascii').strip().split('\n')[::-1]:
# Convert non alpha-numerics to spaces
line = re.sub(r'[^a-zA-Z0-9 ]+', ' ', line)
# Multiple methods, including Ethereal and Stockfish
nps_pattern = r'(\d+\s+nps)|(nps\s+\d+)|(nodes second\s+\d+)'
bench_pattern = r'(\d+\s+nodes)|(nodes\s+\d+)|(nodes searched\s+\d+)'
# Search for and set only once the NPS value
if (re_nps := re.search(nps_pattern, line, re.IGNORECASE)):
nps = nps if nps else re_nps.group()
# Search for and set only once the Bench value
if (re_bench := re.search(bench_pattern, line, re.IGNORECASE)):
bench = bench if bench else re_bench.group()
# 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, 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(
cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
).communicate()
outqueue.put(parse_stream_output(stdout))
def multi_core_bench(engine, network, threads):
outqueue = multiprocessing.Queue()
processes = [
multiprocessing.Process(
target=single_core_bench,
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, network, threads, sets):
benches, speeds = [], []
for ii in range(sets):
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!")
return (0, 0)
return int(sum(speeds) / len(speeds)), benches[0]
from Client.bench import run_benchmark
if __name__ == '__main__':
p = argparse.ArgumentParser()
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)
p.add_argument('-T', '--threads' , help='Concurrent Benchmarks', required=True, type=int)
p.add_argument('-S', '--sets' , help='Benchmark Sample Count', required=True, type=int)
args = p.parse_args()
print (run_benchmark(args.engine, args.network, int(args.threads), int(args.sets)))
private = args.network != None
speed, bench = run_benchmark(args.engine, args.network, private, args.threads, args.sets)
print('Bench for %s is %d' % (args.engine, bench))
print('Speed for %s is %d' % (args.engine, speed))