Implement support for DATAGEN Workloads through the genfens interface (#200)

This commit is contained in:
Andrew Grant authored and GitHub committed 2024-03-12 21:22:07 -04:00
1 parent 45302fa347
commit 2fcb7329ce
57 files changed
+1096 -131

No files matched your search

+1 -5
View File
@@ -5,8 +5,4 @@ rm -rf PGNS/
rm -rf Networks/
rm -rf __pycache__/
rm machine.txt
rm requirements.txt
rm worker.py
rm cutechess-ob
rm cutechess-ob.exe
rm machine.txt
+133
View File
@@ -0,0 +1,133 @@
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# 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 create_genfens_opening_book().
#
# This will execute engines with commands like the following:
# ./engine "genfens N seed S book <None|Books/book.epd> <?exta>" "quit"
#
# This work is split over many engines. If a workload requires 1024 openings,
# and there are 16 threads, then each thread will generate 128 openings. The
# openings are saved to Books/openbench.genfens.epd
#
# create_genfens_opening_book() may raise utils.OpenBenchFailedGenfensException.
# This occurs when longer than 15 seconds has elapsed since getting an opening.
# This should only occur if one or more of the engine processes has stalled.
import math
import os
import queue
import subprocess
import time
import multiprocessing
from utils import kill_process_by_name
from utils import OpenBenchFailedGenfensException
def create_genfens_opening_book(config, binary_name, network):
# Format: ./engine "genfens N seed S book <None|book.epd>" "quit"
N = genfens_required_openings_each(config)
seed = config.workload['test']['book_index']
args = genfens_command_args(config, binary_name, network)
print ('\nGenerating %d Openings using %d Threads...' % (N * config.threads, config.threads))
start_time = time.time()
# Execute all the helpers, who will dump results into the Queue
output = multiprocessing.Queue()
for f in range(config.threads):
command = genfens_command_builder(*args, seed)
multiprocessing.Process(target=genfens_single_threaded, args=(command, output)).start()
seed += N # Step the seed ahead to vary it over the Threads
# Parse the Queue and save the content into Books/openbench.genfens.epd
with open(os.path.join('Books', 'openbench.genfens.epd'), 'w') as fout:
try:
for iteration in range(N * config.threads):
fout.write(output.get(timeout=15) + '\n')
genfens_progress_bar(iteration+1, N * config.threads)
except queue.Empty:
kill_process_by_name(binary_name)
raise OpenBenchFailedGenfensException('[%s] Stalled during genfens' % (binary_name))
print('\nFinished Building Opening Book in %.3f seconds' % (time.time() - start_time))
def genfens_required_openings_each(config):
cutechess_cnt = config.workload['distribution']['cutechess-count']
games_per = config.workload['distribution']['games-per-cutechess']
repeat = config.workload['test']['play_reverses']
total_games = cutechess_cnt * games_per // (1 + repeat)
return math.ceil(total_games / config.threads)
def genfens_command_args(config, binary_name, network):
binary = os.path.join('Engines', binary_name)
private = config.workload['test']['dev']['private']
N = genfens_required_openings_each(config)
book = genfens_book_input_name(config)
extra_args = config.workload['test']['genfens_args']
return (binary, network, private, N, book, extra_args)
def genfens_book_input_name(config):
book_name = config.workload['test']['book']['name']
book_none = book_name.upper() == 'NONE'
return 'None' if book_none else os.path.join('Books', book_name)
def genfens_command_builder(binary, network, private, N, book, extra_args, seed):
command = ['./%s' % (binary)]
if network and private:
command += ['setoption name EvalFile value %s' % (network)]
command += ['genfens %d seed %d book %s %s' % (N, seed, book, extra_args), 'quit']
return command
def genfens_single_threaded(command, queue):
try:
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in iter(process.stdout.readline, b''):
if line.decode('utf-8').startswith('info string genfens '):
queue.put(line.decode('utf-8').split('genfens ')[1].rstrip())
process.wait()
except:
raise
def genfens_progress_bar(curr, total):
prev_progress = int(50 * (curr - 1) / total)
curr_progress = int(50 * (curr - 0) / total)
if curr_progress != prev_progress:
bar_text = '=' * curr_progress + ' ' * (50 - curr_progress)
print ('\r[%s] %d/%d' % (bar_text, curr, total), end='', flush=True)
+21
View File
@@ -28,6 +28,9 @@ import subprocess
import tempfile
import zipfile
IS_WINDOWS = platform.system() == 'Windows' # Don't touch this
IS_LINUX = platform.system() != 'Windows' # Don't touch this
class OpenBenchBuildFailedException(Exception):
def __init__(self, message, logs):
self.message = message
@@ -65,6 +68,20 @@ class OpenBenchBadServerResponseException(Exception):
self.message = ''
super().__init__(self.message)
class OpenBenchFailedGenfensException(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)
def kill_process_by_name(process_name):
if IS_LINUX:
subprocess.run(['pkill', '-f', process_name])
if IS_WINDOWS:
subprocess.run(['taskkill', '/f', '/im', process_name])
def url_join(*args, trailing_slash=True):
@@ -200,6 +217,10 @@ def download_opening_book(book_sha, book_source, book_name):
book_path = os.path.join('Books', book_name)
# Datagen workloads might not include a book
if book_name.upper() == 'NONE':
return
# Book might already have been downloaded
if not os.path.exists(book_path):
+49 -24
View File
@@ -50,6 +50,7 @@ from client import try_forever
from utils import *
from pgn_util import compress_list_of_pgns
from genfens import create_genfens_opening_book
## Basic configuration of the Client. These timeouts can be changed at will
@@ -277,7 +278,7 @@ class ServerReporter:
return ServerReporter.report(config, 'clientSubmitError', payload)
@staticmethod
def report_engine_error(config, error, pgn):
def report_engine_error(config, error, pgn=None):
payload = {
'test_id' : config.workload['test']['id'],
@@ -379,8 +380,12 @@ class Cutechess:
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)
# Only include -repeat if not skipping the reverses in DATAGEN
is_datagen = config.workload['test']['type'] == 'DATAGEN'
no_reverse = is_datagen and not config.workload['test']['play_reverses']
# Always include -recover and -variant
return ['-repeat', ''][no_reverse] + ' -recover -variant %s' % (variant)
@staticmethod
def concurrency_settings(config):
@@ -417,6 +422,15 @@ class Cutechess:
@staticmethod
def book_settings(config, cutechess_idx):
# DATAGEN creates their own book
if config.workload['test']['type'] == 'DATAGEN':
# -repeat might not be applied, so handle the book offsets
no_reverse = not config.workload['test']['play_reverses']
pairs = config.workload['distribution']['games-per-cutechess'] // 2
start = 1 + (cutechess_idx * pairs * (1 + no_reverse))
return '-openings file=Books/openbench.genfens.epd format=epd order=sequential start=%d' % (start)
# Can handle EPD and PGN Books, which must be specified
book_name = config.workload['test']['book']['name']
book_suffix = book_name.split('.')[-1]
@@ -522,14 +536,13 @@ class Cutechess:
def kill_everything(dev_process, base_process):
if IS_LINUX:
subprocess.run(['pkill', '-f', 'cutechess-ob'])
subprocess.run(['pkill', '-f', dev_process])
subprocess.run(['pkill', '-f', base_process])
kill_process_by_name('cutechess-ob')
if IS_WINDOWS:
subprocess.run(['taskkill', '/f', '/im', 'cutechess-ob.exe'])
subprocess.run(['taskkill', '/f', '/im', dev_process])
subprocess.run(['taskkill', '/f', '/im', base_process])
kill_process_by_name('cutechess-ob.exe')
kill_process_by_name(dev_process)
kill_process_by_name(base_process)
@staticmethod
def pgn_name(config, timestamp, cutechess_idx):
@@ -940,16 +953,20 @@ def complete_workload(config):
)
# Download each NNUE file, throws an exception on corruption
dev_network = download_network_weights(config, 'dev' )
base_network = download_network_weights(config, 'base')
dev_network = safe_download_network_weights(config, 'dev' )
base_network = safe_download_network_weights(config, 'base')
# 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)
dev_name = safe_download_engine(config, 'dev' , dev_network )
base_name = safe_download_engine(config, 'base', base_network)
# Datagen creates a book on-the-fly
if config.workload['test']['type'] == 'DATAGEN':
safe_create_genfens_opening_book(config, dev_name, dev_network)
# 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)
dev_nps = safe_run_benchmarks(config, 'dev' , dev_name , dev_network )
base_nps = safe_run_benchmarks(config, 'base', base_name, base_network)
ServerReporter.report_nps(config, dev_nps, base_nps)
# Scale the engines together, using their NPS relative to expected
@@ -962,11 +979,6 @@ def complete_workload(config):
print ('Scale Factor Base : %.4f' % (base_factor))
print ('Scale Factor Avg : %.4f' % (avg_factor ))
# Scale using the base factor only, in the event of a cross-engine test
dev_engine = config.workload['test']['dev' ]['engine']
base_engine = config.workload['test']['base']['engine']
scale_factor = base_factor if dev_engine != base_engine else avg_factor
# Server knows how many copies of Cutechess we should run
cutechess_cnt = config.workload['distribution']['cutechess-count']
concurrency_per = config.workload['distribution']['concurrency-per']
@@ -975,7 +987,12 @@ def complete_workload(config):
print () # Record this information
print ('%d cutechess copies' % (cutechess_cnt))
print ('%d concurrent games per copy' % (concurrency_per))
print ('%d total games per cutechess copy' % (games_per))
print ('%d total games per cutechess copy\n' % (games_per))
# Scale using the base factor only, in the event of a cross-engine test
dev_engine = config.workload['test']['dev' ]['engine']
base_engine = config.workload['test']['base']['engine']
scale_factor = base_factor if dev_engine != base_engine else avg_factor
# Launch and manage all of the Cutechess workers
with ThreadPoolExecutor(max_workers=cutechess_cnt) as executor:
@@ -1009,7 +1026,7 @@ def complete_workload(config):
pgn_files = [Cutechess.pgn_name(config, timestamp, x) for x in range(cutechess_cnt)]
ServerReporter.report_pgn(config, compress_list_of_pgns(pgn_files, scale_factor, compact))
def download_network_weights(config, branch):
def safe_download_network_weights(config, branch):
# Wraps utils.py:download_network()
# May raise OpenBenchCorruptedNetworkException
@@ -1028,7 +1045,7 @@ def download_network_weights(config, branch):
return net_path
def download_engine(config, branch, net_path):
def safe_download_engine(config, branch, net_path):
# Wraps utils.py:download_public_engine() and utils.py:download_private_engine()
@@ -1070,8 +1087,15 @@ def download_engine(config, branch, net_path):
ServerReporter.report_build_fail(config, branch, error.logs)
raise
def safe_create_genfens_opening_book(config, dev_name, dev_network):
def run_benchmarks(config, branch, engine, network):
try: create_genfens_opening_book(config, dev_name, dev_network)
except OpenBenchFailedGenfensException as error:
ServerReporter.report_engine_error(config, error.message)
raise
def safe_run_benchmarks(config, branch, engine, network):
name = config.workload['test'][branch]['name']
private = config.workload['test'][branch]['private']
@@ -1091,6 +1115,7 @@ def run_benchmarks(config, branch, engine, network):
print('Speed for %s is %d' % (name, speed))
return speed
def build_cutechess_command(config, dev_cmd, base_cmd, scale_factor, timestamp, cutechess_idx):
flags = ' ' + Cutechess.basic_settings(config)