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):