Implement SPSA for OpenBench (#169)

* Support Worker and Thread Limits
* Drop report_rate from the Client
* Creation page
* WIP for SPSA; Lots of code shuffling to clean it up
* Able to create a Tune in the interface
* Start to work on a display page for Tunes
* Move all workload utilities to their own dir
* Ignore config files going forward
* Able to produce an SPSA test from the Server
* Round integers with probabilities that make sense
* Client side working
* Report as results come in, don't wait
* Fix workload size comment
* Cleanup and fix Tune modifications
* Adustment to random value in tuning
* Delete engine configs
This commit is contained in:
Andrew Grant authored and GitHub committed 2023-09-19 14:44:52 -04:00
1 parent bc26be7a4c
commit ee267381fc
40 files changed
+1799 -1562

No files matched your search

+1 -1
View File
@@ -42,7 +42,7 @@ REQUIRE_MANUAL_REGISTRATION = False # Disable the public facing registration pag
OPENBENCH_CONFIG = {
# Server Client version control
'client_version' : '13',
'client_version' : 14,
# Generic Error Messages useful to those setting up their own instance
'error' : {
+3 -1
View File
@@ -112,7 +112,8 @@ class Test(Model):
base_time_control = CharField(max_length=32)
# Changable Test Parameters
report_rate = IntegerField(default=8)
worker_limit = IntegerField(default=0)
thread_limit = IntegerField(default=0)
workload_size = IntegerField(default=32)
priority = IntegerField(default=0)
throughput = IntegerField(default=0)
@@ -133,6 +134,7 @@ class Test(Model):
currentllr = FloatField(default=0.0) # SPRT
upperllr = FloatField(default=0.0) # SPRT
max_games = IntegerField(default=0) # GAMES
spsa = JSONField(default=dict, blank=True, null=True) # SPSA
# Collection of all individual Result() objects
games = IntegerField(default=0) # Overall
-1
View File
@@ -144,7 +144,6 @@ function set_test_mode(mode_str) {
const engine = selection.options[selection.selectedIndex].value;
const mode = extract_mode_config(mode_str, 'dev');
document.getElementById('report_rate' ).value = mode['report_rate'] || 8;
document.getElementById('workload_size').value = mode['workload_size'] || 32;
document.getElementById('book_name' ).value = mode['book'] || config.engines[engine].book;
+146
View File
@@ -0,0 +1,146 @@
var config = JSON.parse(document.getElementById('json-config' ).textContent);
var networks = JSON.parse(document.getElementById('json-networks').textContent);
var repos = JSON.parse(document.getElementById('json-repos' ).textContent);
function create_network_options(field_id, engine) {
var has_default = false;
var network_options = document.getElementById(field_id);
// Delete all existing Networks
while (network_options.length)
network_options.remove(0);
// Add each Network that matches the given engine
for (const network of networks) {
if (network.engine !== engine)
continue;
var opt = document.createElement('option');
opt.text = network.name;
opt.value = network.sha256;
opt.selected = network.default;
network_options.add(opt)
has_default = has_default || network.default;
}
{ // Add a None option and set it to default if there was not one yet
var opt = document.createElement('option');
opt.text = 'None';
opt.value = '';
opt.selected = !has_default;
network_options.add(opt);
}
}
function create_testmode_buttons(engine) {
// Clear out all of the existing buttons
var button_div = document.getElementById('test-mode-buttons');
while (button_div.hasChildNodes())
button_div.removeChild(button_div.lastChild);
var index = 0;
for (let mode in config.engines[engine].tunemodes) {
// Create a new button for the test mode
var btn = document.createElement('button')
btn.innerHTML = mode;
btn.onclick = function() { set_test_mode(mode); };
// Apply all of our CSS bootstrapping
btn.classList.add('anchorbutton');
btn.classList.add('btn-preset');
btn.classList.add('mt-2');
btn.classList.add('w-100');
// Put the button in a div, so we can handle padding
var div = document.createElement('div')
div.appendChild(btn)
div.classList.add('col-half');
// Left pad everything but the first
if ((index % 4) != 0)
div.classList.add('pl-1');
// Right pad everything but the last
if ((index % 4) != 3)
div.classList.add('pr-1');
button_div.append(div);
index++;
}
}
function extract_mode_config(mode_str) {
// Find test mode configuration for the engine
var selection = document.getElementById('engine');
var engine = selection.options[selection.selectedIndex].value;
return config.engines[engine].tunemodes[mode_str];
}
function set_engine_options(mode_str) {
// Extract UCI options for both the engine
var options = extract_mode_config(mode_str)['options'];
document.getElementById('options').value = options;
}
function set_test_mode(mode_str) {
const selection = document.getElementById('engine');
const engine = selection.options[selection.selectedIndex].value;
const mode = extract_mode_config(mode_str);
document.getElementById('book_name' ).value = mode['book'] || config.engines[engine].book;
document.getElementById('time_control' ).value = mode['timecontrol'] || '10.0+0.1';
set_engine_options(mode_str);
}
/* External */
function set_engine(engine) {
// Always update the Engine and Repository to the defaults
document.getElementById('engine').value = engine;
document.getElementById('repo' ).value = repos[engine] || config.engines[engine].source
// Create dropdown of all Networks associated with the engine
create_network_options('network', engine);
// Set default UCI options as if we were running an STC when changing
set_engine_options('STC');
// Engine decides the Adjudication and Book settings
document.getElementById('book_name' ).value = config.engines[engine].book;
document.getElementById('win_adj' ).value = config.engines[engine].win_adj;
document.getElementById('draw_adj' ).value = config.engines[engine].draw_adj;
set_test_mode('STC');
create_testmode_buttons(engine)
}
function enforce_default_text(id, text) {
window.addEventListener('DOMContentLoaded', function() {
var field = document.getElementById(id);
field.addEventListener('input', function() {
if (field.value.startsWith(text) || field.value === text)
return;
if (field.value.endsWith('/'))
field.value = text + field.value.substr(text.length).replace(/\/+$/, '');
else
field.value = text + field.value.substr(text.length);
});
});
}
+2 -2
View File
@@ -55,7 +55,7 @@
color: var(--color-font2)
}
#content .row input, #content .row select {
#content .row input, #content .row select, #content .row textarea {
flex-grow: 1;
min-width: 0;
border: 1px solid var(--color3);
@@ -70,7 +70,7 @@
padding: 2px 2px;
}
#content .row input:focus, #content .row select:focus {
#content .row input:focus, #content .row select:focus, #content .row textarea {
outline: none;
border-color: var(--color3);
box-shadow: 0 0 0 3px rgba(77, 144, 254, 0.25);
+49 -5
View File
@@ -21,7 +21,6 @@
import re, django
import OpenBench.config, OpenBench.utils, OpenBench.stats, OpenBench.models
def oneDigitPrecision(value):
try:
value = round(value, 1)
@@ -58,17 +57,23 @@ def gitDiffLink(test):
def shortStatBlock(test):
tri_line = 'Games: %d W: %d L: %d D: %d' % (test.games, test.wins, test.losses, test.draws)
penta_line = 'Pntml(0-2): %d, %d, %d, %d, %d' % (test.LL, test.LD, test.DD, test.DW, test.WW)
if test.test_mode == 'SPSA':
return '\n'.join([
'Tuning %d Parameters' % (len(test.spsa['parameters'].keys())),
'%d/%d Iterations' % (test.games / (2 * test.spsa['pairs_per']), test.spsa['iterations']),
'%d/%d Games Played' % (test.games, 2 * test.spsa['iterations'] * test.spsa['pairs_per'])])
if test.test_mode == "SPRT":
if test.test_mode == 'SPRT':
top_line = 'LLR: %0.2f (%0.2f, %0.2f) [%0.2f, %0.2f]' % (
test.currentllr, test.lowerllr, test.upperllr, test.elolower, test.eloupper)
if test.test_mode == "GAMES":
if test.test_mode == 'GAMES':
lower, elo, upper = OpenBench.stats.ELO([test.losses, test.draws, test.wins])
top_line = 'Elo: %0.2f +- %0.2f (95%%) [N=%d]' % (elo, max(upper - elo, elo - lower), test.max_games)
tri_line = 'Games: %d W: %d L: %d D: %d' % (test.games, test.wins, test.losses, test.draws)
penta_line = 'Pntml(0-2): %d, %d, %d, %d, %d' % (test.LL, test.LD, test.DD, test.DW, test.WW)
if test.use_penta:
return '\n'.join([top_line, tri_line, penta_line])
@@ -79,6 +84,8 @@ def shortStatBlock(test):
def longStatBlock(test):
assert test.test_mode != 'SPSA'
threads = int(OpenBench.utils.extract_option(test.dev_options, 'Threads'))
hashmb = int(OpenBench.utils.extract_option(test.dev_options, 'Hash'))
timecontrol = test.dev_time_control + ['s', '']['=' in test.dev_time_control]
@@ -198,6 +205,7 @@ def machine_name(machine_id):
return machine.info['machine_name']
except: return 'None'
register = django.template.Library()
register.filter('oneDigitPrecision', oneDigitPrecision)
register.filter('twoDigitPrecision', twoDigitPrecision)
@@ -217,3 +225,39 @@ register.filter('cpuflagsBlock', cpuflagsBlock)
register.filter('compilerBlock', compilerBlock)
register.filter('removePrefix', removePrefix)
register.filter('machine_name', machine_name)
def spsa_param_digest(test):
digest = []
# C and R are compressed as we progress iterations
iteration = 10000 + (test.games / (test.spsa['pairs_per'] * 2))
c_compression = iteration ** test.spsa['Gamma']
r_compression = (test.spsa['A'] + iteration) ** test.spsa['Alpha']
for name, param in test.spsa['parameters'].items():
# C and R if we got a workload right now
c = param['c'] / c_compression
r = param['a'] / r_compression / c ** 2
digest.append([
name,
'%.4f' % (param['start']),
'%.4f' % (param['value']),
'%.4f' % (param['min' ]),
'%.4f' % (param['max' ]),
'%.4f' % (c),
'%.4f' % (param['c_end']),
'%.4f' % (r),
'%.4f' % (param['r_end']),
])
return digest
register.filter('spsa_param_digest', spsa_param_digest)
+6 -2
View File
@@ -48,12 +48,16 @@ urlpatterns = [
django.urls.path(r'machines/', OpenBench.views.machines),
django.urls.path(r'machines/<int:machineid>/', OpenBench.views.machines),
# Links for viewing and managing tests (maintain Legacy)
# Links for viewing and managing tests
django.urls.path(r'test/<int:id>/', OpenBench.views.test),
django.urls.path(r'viewTest/<int:id>/', OpenBench.views.test),
django.urls.path(r'test/<int:id>/<str:action>', OpenBench.views.test),
django.urls.path(r'newTest/', OpenBench.views.create_test),
# Links for viewing and managing tunes
django.urls.path(r'tune/<int:id>/', OpenBench.views.tune),
django.urls.path(r'tune/<int:id>/<str:action>', OpenBench.views.tune),
django.urls.path(r'newTune/', OpenBench.views.create_tune),
# Links for viewing and managing Networks
django.urls.path(r'networks/', OpenBench.views.networks),
django.urls.path(r'networks/<str:engine>/', OpenBench.views.networks),
+19 -471
View File
@@ -42,6 +42,7 @@ from OpenBench.config import OPENBENCH_CONFIG
from OpenBench.models import *
from OpenBench.stats import TrinomialSPRT, PentanomialSPRT
import OpenBench.views
@@ -122,6 +123,13 @@ class TimeControl(object):
return float(time_str.split('+')[0])
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() }
def path_join(*args):
return "/".join([f.lstrip("/").rstrip("/") for f in args]).rstrip('/')
@@ -137,6 +145,8 @@ def extract_option(options, option):
if match: return match.group()
def get_pending_tests():
t = Test.objects.filter(approved=False)
t = t.exclude(finished=True)
@@ -209,13 +219,6 @@ def getPaging(content, page, url, pagelen=25):
return start, end, context
def getEngine(source, name, sha, bench):
engine = Engine.objects.filter(name=name, source=source, sha=sha, bench=bench)
if engine.first() != None: return engine.first()
return Engine.objects.create(name=name, source=source, sha=sha, bench=bench)
def branch_is_out_of_date(test):
@@ -240,336 +243,6 @@ def branch_is_out_of_date(test):
traceback.print_exc()
return False
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() }
def requests_illegal_fork(request, field):
# Strip trailing '/'s for sanity
engine = OPENBENCH_CONFIG['engines'][request.POST['%s_engine' % (field)]]
eng_src = engine['source'].rstrip('/')
tar_src = request.POST['%s_repo' % (field)].rstrip('/')
# Illegal if sources do not match for Private engines
return engine['private'] and eng_src != tar_src
def determine_bench(request, field, message):
# Use the provided bench if possible
try: return int(request.POST['{0}_bench'.format(field)])
except: pass
# Fallback to try to parse the Bench from the commit
try:
benches = re.findall('(?:BENCH|NODES)[ :=]+([0-9,]+)', message, re.IGNORECASE)
return int(benches[-1].replace(',', ''))
except: return None
def collect_github_info(request, errors, field):
# Get branch name / commit sha / tag, and the API path for it
branch = request.POST['{0}_branch'.format(field)]
bysha = bool(re.search('[0-9a-fA-F]{40}', branch))
# All API requests will share this common path. Some engines are private.
base = request.POST['%s_repo' % (field)].replace('github.com', 'api.github.com/repos')
engine = request.POST['%s_engine' % (field)]
private = OPENBENCH_CONFIG['engines'][engine]['private']
headers = {}
## Step 1: Verify the target of the API requests
## [A] We will not attempt to reach any site other than api.github.com
## [B] Private engines may only use their main repo for sources of tests
## [C] Determine which, if any, credentials we want to pass along
# Private engines must have a token stored in credentials.enginename
if private and not (headers := read_git_credentials(engine)):
errors.append('Server does not have access tokens for this engine')
return (None, None)
# Do not allow private engines to use forked repos ( We don't have a token! )
if requests_illegal_fork(request, field):
errors.append('Forked Repositories are not allowed for Private engines')
return (None, None)
# Avoid leaking our credentials to other websites
if not base.startswith('https://api.github.com/'):
errors.append('OpenBench may only reach Github\'s API')
return (None, None)
## Step 2: Connect to the Github API for the given Branch or Commit SHA.
## [A] We will attempt to parse the most recent commit message for a
## bench, unless one was supplied.
## [B] We will translate any branch name into a commit SHA for later use,
## so we may compare branches and generate diff URLs
## [C] If the engine is public, we will construct the URL to download the
## source code from Github into a .zip file.
## [D] If the engine is private, we will carry onto Step 3.
try: # Fetch data from the Github API
# Lookup branch or commit sha, but will fail for tags
url = path_join(base, 'commits' if bysha else 'branches', branch)
data = requests.get(url, headers=headers).json()
# Check to see if the branch name was actually a tag name
if not bysha and 'commit' not in data:
url = path_join(base, 'commits', branch)
data = requests.get(url, headers=headers).json()
# Actual branches have to go one layer deeper
elif not bysha: data = data['commit']
# Check that all the data we need going forward is present
assert 'message' in data['commit'] and 'sha' in data
assert private or 'sha' in data['commit']['tree']
except: # Unable to find for whatever reason
import traceback
traceback.print_exc()
errors.append('%s could not be found' % (branch))
return (None, None)
# Extract the bench from the web form, or from the commit message
if not (bench := determine_bench(request, field, data['commit']['message'])):
errors.append('Unable to parse a Bench for %s' % (branch))
return (None, None)
# Public Engines: Construct the .zip download and return everything
if not private:
treeurl = data['commit']['tree']['sha'] + '.zip'
source = path_join(request.POST['%s_repo' % (field)], 'archive', treeurl)
return (source, branch, data['sha'], bench), True
## Step 3: Construct the URL for the API request to list all Artifacts
## [A] OpenBench artifacts are always run via a file named openbench.yml
## [B] These should contain combinations for windows/linux, avx2/avx512, popcnt/pext
## [C] If those artifacts are not found, we flag the test as awaiting, and try later.
url, has_all = fetch_artifact_url(base, engine, headers, data['sha'])
return (url, branch, data['sha'], bench), has_all
def fetch_artifact_url(base, engine, headers, sha):
try:
# Fetch the run id for the openbench workflow for this comment
url = path_join(base, 'actions', 'workflows', 'openbench.yml', 'runs')
url += '?head_sha=%s' % (sha)
run_id = requests.get(url=url, headers=headers).json()['workflow_runs'][0]['id']
# Fetch information about individual job results
url = path_join(base, 'actions', 'runs', str(run_id), 'jobs')
jobs = requests.get(url=url, headers=headers).json()['jobs']
# Fetch information about individual artifact
url = path_join(base, 'actions', 'runs', str(run_id), 'artifacts')
artifacts = requests.get(url=url, headers=headers).json()['artifacts']
# All jobs finished, with at least one non-expired Artifact
assert not any(job['conclusion'] != 'success' for job in jobs)
assert not any(artifact['expired'] for artifact in artifacts)
assert len(artifacts) >= len(jobs)
# Only set the url if we have everything we need
return (url, True)
except Exception as error:
# If anything goes wrong, retry later with the same base URL
return (base, False)
def verify_test_creation(request):
errors = []
def verify_integer(field, field_name):
try: int(request.POST[field])
except: errors.append('"{0}" is not an Integer'.format(field_name))
def verify_greater_than(field, field_name, value):
try: assert int(request.POST[field]) > value
except: errors.append('"{0}" is not greater than {1}'.format(field_name, value))
def verify_options(field, option, field_name):
try: assert int(extract_option(request.POST[field], option)) >= 1
except: errors.append('"{0}" needs to be at least 1 for {1}'.format(option, field_name))
def verify_configuration(field, field_name, parent):
try: assert request.POST[field] in OPENBENCH_CONFIG[parent].keys()
except: errors.append('{0} was not found in the configuration'.format(field_name))
def verify_time_control(field, field_name):
try: TimeControl.parse(request.POST[field])
except: errors.append('{0} is not parsable'.format(field_name))
def verify_win_adj(field):
try:
if (content := request.POST[field]) == 'None': return
assert re.match('movecount=[0-9]+ score=[0-9]+', content)
except: errors.append('Invalid Win Adjudication Setting. Try "None"?')
def verify_draw_adj(field):
try:
if (content := request.POST[field]) == 'None': return
assert re.match('movenumber=[0-9]+ movecount=[0-9]+ score=[0-9]+', content)
except: errors.append('Invalid Draw Adjudication Setting. Try "None"?')
def verify_github_repo(field):
pattern = r'^https:\/\/github\.com\/[A-Za-z0-9-]+\/[A-Za-z0-9_.-]+\/?$'
try: assert re.match(pattern, request.POST[field])
except: errors.append('Sources must be found on https://github.com/<User>/<Repo>')
def verify_network(field, field_name, engine_field):
try:
if request.POST[field] == '': return
Network.objects.get(engine=request.POST[engine_field], sha256=request.POST[field])
except: errors.append('Unknown Network Provided for {0}'.format(field_name))
def verify_test_mode(field):
try: assert request.POST[field] in ['SPRT', 'GAMES']
except: errors.append('Unknown Test Mode')
def verify_sprt_bounds(field):
try:
if request.POST['test_mode'] != 'SPRT': return
pattern = r'^\[(-?\d+(?:\.\d+)?), (-?\d+(?:\.\d+)?)\]$'
match = re.match(pattern, request.POST['test_bounds'])
assert float(match.group(1)) < float(match.group(2))
except: errors.append('SPRT Bounds must be formatted as [float1, float2]')
def verify_sprt_conf(field):
try:
if request.POST['test_mode'] != 'SPRT': return
pattern = r'^\[(-?\d+(?:\.\d+)?), (-?\d+(?:\.\d+)?)\]$'
match = re.match(pattern, request.POST['test_confidence'])
assert 0.00 < float(match.group(1)) < 1.00
assert 0.00 < float(match.group(2)) < 1.00
except: errors.append('Confidence Bounds must be formatted as [float1, float2], within (0.00, 1.00)')
def verify_max_games(field):
try:
if request.POST['test_mode'] != 'GAMES': return
assert int(request.POST['test_max_games']) > 0
except: errors.append('Fixed Games Tests must last at least one game')
def verify_syzygy_field(field, field_name):
candidates = ['OPTIONAL', 'DISABLED', '3-MAN', '4-MAN', '5-MAN', '6-MAN', '7-MAN']
try: assert request.POST[field] in candidates
except: errors.append('%s must be in %s' % (field_name, ', '.join(candidates)))
verifications = [
# Verify everything about the Dev Engine
(verify_configuration, 'dev_engine', 'Dev Engine', 'engines'),
(verify_github_repo , 'dev_repo'),
(verify_network , 'dev_network', 'Dev Network', 'dev_engine'),
(verify_options , 'dev_options', 'Threads', 'Dev Options'),
(verify_options , 'dev_options', 'Hash', 'Dev Options'),
(verify_time_control , 'dev_time_control', 'Dev Time Control'),
# Verify everything about the Base Engine
(verify_configuration, 'base_engine', 'Base Engine', 'engines'),
(verify_github_repo , 'base_repo'),
(verify_network , 'base_network', 'Base Network', 'base_engine'),
(verify_options , 'base_options', 'Threads', 'Base Options'),
(verify_options , 'base_options', 'Hash', 'Base Options'),
(verify_time_control , 'base_time_control', 'Base Time Control'),
# Verify everything about the Test Settings
(verify_configuration, 'book_name', 'Book', 'books'),
(verify_test_mode , 'test_mode'),
(verify_sprt_bounds , 'test_bounds'),
(verify_sprt_conf , 'test_confidence'),
(verify_max_games , 'test_max_games'),
# Verify everything about the General Settings
(verify_integer , 'priority', 'Priority'),
(verify_greater_than , 'throughput', 'Throughput', 0),
(verify_syzygy_field , 'syzygy_wdl', 'Syzygy WDL'),
# Verify everything about the Workload Settings
(verify_greater_than , 'report_rate', 'Report Rate', 0),
(verify_greater_than , 'workload_size', 'Workload Size', 0),
# Verify everything about the Adjudicaton Settings
(verify_syzygy_field , 'syzygy_adj', 'Syzygy Adjudication'),
(verify_win_adj , 'win_adj'),
(verify_draw_adj , 'draw_adj'),
]
for verification in verifications:
verification[0](*verification[1:])
return errors
def create_new_test(request):
# Verify all of the fields in the request
if (errors := verify_test_creation(request)):
return None, errors
# Collect Github meta information (Shas, Sources, Benches)
devinfo, dev_has_all = collect_github_info(request, errors, 'dev')
baseinfo, base_has_all = collect_github_info(request, errors, 'base')
if errors != []: return None, errors
test = Test()
test.author = request.user.username
test.book_name = request.POST['book_name']
test.dev = getEngine(*devinfo)
test.dev_repo = request.POST['dev_repo']
test.dev_engine = request.POST['dev_engine']
test.dev_options = request.POST['dev_options']
test.dev_network = request.POST['dev_network']
test.dev_time_control = TimeControl.parse(request.POST['dev_time_control'])
test.base = getEngine(*baseinfo)
test.base_repo = request.POST['base_repo']
test.base_engine = request.POST['base_engine']
test.base_options = request.POST['base_options']
test.base_network = request.POST['base_network']
test.base_time_control = TimeControl.parse(request.POST['base_time_control'])
test.report_rate = int(request.POST['report_rate'])
test.workload_size = int(request.POST['workload_size'])
test.priority = int(request.POST['priority'])
test.throughput = int(request.POST['throughput'])
test.syzygy_wdl = request.POST['syzygy_wdl']
test.syzygy_adj = request.POST['syzygy_adj']
test.win_adj = request.POST['win_adj']
test.draw_adj = request.POST['draw_adj']
test.test_mode = request.POST['test_mode']
test.awaiting = not (dev_has_all and base_has_all)
if test.test_mode == 'SPRT':
test.elolower = float(request.POST['test_bounds'].split(',')[0].lstrip('['))
test.eloupper = float(request.POST['test_bounds'].split(',')[1].rstrip(']'))
test.alpha = float(request.POST['test_confidence'].split(',')[1].rstrip(']'))
test.beta = float(request.POST['test_confidence'].split(',')[0].lstrip('['))
test.lowerllr = math.log(test.beta / (1.0 - test.alpha))
test.upperllr = math.log((1.0 - test.beta) / test.alpha)
if test.test_mode == 'GAMES':
test.max_games = int(request.POST['test_max_games'])
if test.dev_network:
test.dev_netname = Network.objects.get(engine=test.dev_engine, sha256=test.dev_network).name
if test.base_network:
test.base_netname = Network.objects.get(engine=test.base_engine, sha256=test.base_network).name
test.save()
profile = Profile.objects.get(user=request.user)
profile.tests += 1
profile.save()
return test, None
def get_machine(machineid, user, info):
@@ -592,22 +265,6 @@ def get_machine(machineid, user, info):
return machine
def get_workload(machine):
# Check to make sure we have a potential workload
if not (tests := get_valid_workloads(machine)):
return {}
# Select from valid workloads the most needing test
test = select_workload(machine, tests)
try: result = Result.objects.get(test=test, machine=machine)
except: result = Result(test=test, machine=machine)
# Update the Machine's status and save everything
machine.workload = test.id; machine.save(); result.save()
return { 'workload' : workload_to_dictionary(test, result) }
# Purely Helper functions for Networks views
@@ -697,124 +354,6 @@ def network_download(request, engine, network):
return response
# Purely Helper functions for get_workload()
def get_valid_workloads(machine):
# Skip anything that is not running
tests = get_active_tests()
# Skip engines that the Machine cannot handle
for engine in OPENBENCH_CONFIG['engines'].keys():
if engine not in machine.info['supported']:
tests = tests.exclude(dev_engine=engine)
tests = tests.exclude(base_engine=engine)
# Skip tests with unmet Syzygy requirments
for K in range(machine.info['syzygy_max'] + 1, 10):
tests = tests.exclude(syzygy_adj='%d-MAN' % (K))
tests = tests.exclude(syzygy_wdl='%d-MAN' % (K))
# Skip tests that would waste available Threads or exceed them
threads = machine.info['concurrency']
sockets = machine.info['sockets']
hyperthreads = machine.info['physical_cores'] < threads
options = [x for x in tests if
test_maps_onto_thread_count(x, threads, sockets, hyperthreads)]
# Finally refine for tests of the highest priority
if not options: return []
highest_prio = max(options, key=lambda x: x.priority).priority
return [test for test in options if test.priority == highest_prio]
def test_maps_onto_thread_count(test, threads, sockets, hyperthreads):
dev_threads = int(extract_option(test.dev_options, 'Threads'))
base_threads = int(extract_option(test.base_options, 'Threads'))
# Each individual cutechess copy must have access to sufficient Threads
if max(dev_threads, base_threads) > (threads / sockets):
return False
# Refuse to run thread-odds when dipping into hyperthreads
return dev_threads == base_threads or not hyperthreads
def select_workload(machine, tests, variance=0.25):
# Determine how many threads are assigned to each workload
table = { test.id : { 'cores' : 0, 'throughput' : test.throughput } for test in tests }
for m in getRecentMachines():
if m.workload in table and m != machine:
table[m.workload]['cores'] += m.info['concurrency']
# Find the tests most deserving of resources currently
ratios = [table[x]['cores'] / table[x]['throughput'] for x in table]
lowest_idxs = [i for i, r in enumerate(ratios) if r == min(ratios)]
# Machine is out of date; or there is an unassigned test
if machine.workload not in table or min(ratios) == 0:
return tests[random.choice(lowest_idxs)]
# No test has less than (1-variance)% of its deserved resources, and
# therefore we may have this machine repeat its existing workload again
ideal_ratio = sum([x['cores'] for x in table.values()]) / sum([x['throughput'] for x in table.values()])
if min(ratios) / ideal_ratio > 1 - variance:
return Test.objects.get(id=machine.workload)
# Fallback to simply doing the least attention given test
return tests[random.choice(lowest_idxs)]
def workload_to_dictionary(test, result):
return {
'result' : {
'id' : result.id
},
'test' : {
'id' : test.id,
'syzygy_wdl' : test.syzygy_wdl,
'syzygy_adj' : test.syzygy_adj,
'win_adj' : test.win_adj,
'draw_adj' : test.draw_adj,
'report_rate' : test.report_rate,
'workload_size' : test.workload_size,
'book' : OPENBENCH_CONFIG['books'][test.book_name],
'dev' : {
'id' : test.dev.id,
'name' : test.dev.name,
'source' : test.dev.source,
'sha' : test.dev.sha,
'bench' : test.dev.bench,
'engine' : test.dev_engine,
'options' : test.dev_options,
'network' : test.dev_network,
'time_control' : test.dev_time_control,
'nps' : OPENBENCH_CONFIG['engines'][test.dev_engine]['nps'],
'build' : OPENBENCH_CONFIG['engines'][test.dev_engine]['build'],
'private' : OPENBENCH_CONFIG['engines'][test.dev_engine]['private'],
},
'base' : {
'id' : test.base.id,
'name' : test.base.name,
'source' : test.base.source,
'sha' : test.base.sha,
'bench' : test.base.bench,
'engine' : test.base_engine,
'options' : test.base_options,
'network' : test.base_network,
'time_control' : test.base_time_control,
'nps' : OPENBENCH_CONFIG['engines'][test.base_engine]['nps'],
'build' : OPENBENCH_CONFIG['engines'][test.base_engine]['build'],
'private' : OPENBENCH_CONFIG['engines'][test.base_engine]['private'],
},
},
}
def update_test(request, machine):
# Extract error information
@@ -877,6 +416,15 @@ def update_test(request, machine):
test.failed = test.games >= test.max_games and test.wins < test.losses
test.finished = test.passed or test.failed
elif test.test_mode == 'SPSA':
# Update each parameter, as determined by the Worker
for name, param in test.spsa['parameters'].items():
x = param['value'] + float(request.POST['spsa_%s' % (name)])
param['value'] = max(param['min'], min(param['max'], x))
test.finished = test.games / test.spsa['pairs_per'] > test.spsa['iterations']
test.save()
# Update Result object; No risk from concurrent access
+35 -55
View File
@@ -27,6 +27,11 @@ import django.contrib.auth
import OpenBench.config
import OpenBench.utils
from OpenBench.workloads.get_workload import get_workload
from OpenBench.workloads.create_workload import create_workload
from OpenBench.workloads.verify_workload import verify_workload
from OpenBench.workloads.modify_workload import modify_workload
from OpenBench.config import OPENBENCH_CONFIG
from OpenBench.models import *
@@ -437,70 +442,45 @@ def machines(request, machineid=None):
def test(request, id, action=None):
# Request is to modify or interact with the Test
if action != None:
return modify_workload(request, id, action)
# Verify that the Test id exists
if not (test := Test.objects.filter(id=id).first()):
return django.http.HttpResponseRedirect('/index/')
return redirect(request, '/index/', error='No such Test exists')
if action not in ['APPROVE', 'RESTART', 'STOP', 'DELETE', 'RESTORE', 'MODIFY']:
data = { 'test' : test, 'results': Result.objects.filter(test=test) }
return render(request, 'test.html', data)
# Verify that it is indeed a Test and not a Tune
if test.test_mode != 'SPRT' and test.test_mode != 'FIXED':
return redirect(request, '/index/', error='You are trying to view a Tune not Test')
if not request.user.is_authenticated:
return redirect(request, '/login/', error='Only users may interact with tests')
# Package everything up and display the test
data = { 'test' : test, 'results': Result.objects.filter(test=test) }
return render(request, 'test.html', data)
profile = Profile.objects.get(user=request.user)
if not profile.approver and test.author != request.user.username:
return redirect(request, '/index/', error='You cannot interact with another user\'s test')
def tune(request, id, action=None):
if action == 'APPROVE':
if test.author == request.user.username and not user.is_superuser:
return redirect(request, '/index/', error='You cannot approve your own test')
# Request is to modify or interact with the Tune
if action != None:
return modify_workload(request, id, action)
if action == 'APPROVE': test.approved = True; test.save()
if action == 'RESTART': test.finished = False; test.save()
if action == 'STOP' : test.finished = True; test.save()
if action == 'DELETE' : test.deleted = True; test.save()
if action == 'RESTORE': test.deleted = False; test.save()
# Verify that the Tune id exists
if not (tune := Test.objects.filter(id=id).first()):
return redirect(request, '/index/', error='No such Tune exists')
if action == 'MODIFY':
test.priority = int(request.POST['priority'])
test.throughput = max(1, int(request.POST['throughput']))
test.report_rate = max(1, int(request.POST['report_rate']))
test.workload_size = max(1, int(request.POST['workload_size']))
test.save()
# Verify that it is indeed a Tune and not a Test
if tune.test_mode == 'SPRT' or tune.test_mode == 'FIXED':
return redirect(request, '/index/', error='You are trying to view a Test not Tune')
action += " P=%d TP=%d RR=%d WS=%d" % (test.priority, test.throughput, test.report_rate, test.workload_size)
LogEvent.objects.create(author=request.user.username, summary=action, log_file='', test_id=test.id)
return django.http.HttpResponseRedirect('/index/')
# Package everything up and display the Tune
data = { 'test' : tune, 'results': Result.objects.filter(test=tune) }
return render(request, 'tune.html', data)
def create_test(request):
return create_workload(request, 'TEST')
if not request.user.is_authenticated:
return redirect(request, '/login/', error='Only enabled users can create tests')
if not Profile.objects.get(user=request.user).enabled:
return redirect(request, '/login/', error='Only enabled users can create tests')
if request.method == 'GET':
data = { 'networks' : list(Network.objects.all().values()) }
return render(request, 'create_test.html', data)
test, errors = OpenBench.utils.create_new_test(request)
if errors != [] and errors != None:
return redirect(request, '/newTest/', error='\n'.join(errors))
if warning := OpenBench.utils.branch_is_out_of_date(test):
warning = 'Consider Rebasing: Dev (%s) appears behind Base (%s)' % (test.dev.name, test.base.name)
username = request.user.username
profile = Profile.objects.get(user=request.user)
summary = 'CREATE P=%d TP=%d' % (test.priority, test.throughput)
LogEvent.objects.create(author=username, summary=summary, log_file='', test_id=test.id)
if not OpenBench.config.USE_CROSS_APPROVAL and profile.approver:
test.approved = True; test.save()
return redirect(request, '/index/', warning=warning)
def create_tune(request):
return create_workload(request, 'TUNE')
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# NETWORK MANAGEMENT VIEWS #
@@ -588,7 +568,7 @@ def client_verify_worker(request):
# Ensure the Client is using the same version as the Server
if machine.info['client_ver'] != OPENBENCH_CONFIG['client_version']:
expected_ver = OPENBENCH_CONFIG['client_version']
return machine, JsonResponse({ 'error' : 'Bad Client Version: Expected %s' % (expected_ver)})
return machine, JsonResponse({ 'error' : 'Bad Client Version: Expected %d' % (expected_ver)})
# Use the secret token as our soft verification
if machine.secret != request.POST['secret']:
@@ -673,7 +653,7 @@ def client_get_workload(request):
if response != None: return response
# Contains keys 'workload', otherwise none
return JsonResponse(OpenBench.utils.get_workload(machine))
return JsonResponse(get_workload(machine))
@csrf_exempt
def client_get_network(request, engine, name):
+8 -6
View File
@@ -24,7 +24,9 @@ import threading
import time
import traceback
import OpenBench.utils
from OpenBench.utils import get_awaiting_tests
from OpenBench.utils import read_git_credentials
from OpenBench.workloads.verify_workload import fetch_artifact_url
class ArtifactWatcher(threading.Thread):
@@ -40,15 +42,15 @@ class ArtifactWatcher(threading.Thread):
base_has = test.base.source.endswith('.zip') or base_has
if not dev_has: # Check for new Artifacts for Dev
dev_headers = OpenBench.utils.read_git_credentials(test.dev_engine)
dev_headers = read_git_credentials(test.dev_engine)
data = [test.dev.source, test.dev_engine, dev_headers, test.dev.sha]
test.dev.source, dev_has = OpenBench.utils.fetch_artifact_url(*data)
test.dev.source, dev_has = fetch_artifact_url(*data)
test.dev.save()
if not base_has: # Check for new Artifacts for Base
base_headers = OpenBench.utils.read_git_credentials(test.base_engine)
base_headers = read_git_credentials(test.base_engine)
data = [test.base.source, test.base_engine, base_headers, test.base.sha]
test.base.source, base_has = OpenBench.utils.fetch_artifact_url(*data)
test.base.source, base_has = fetch_artifact_url(*data)
test.base.save()
# If both finished, flag the test as no longer awaiting
@@ -58,7 +60,7 @@ class ArtifactWatcher(threading.Thread):
def run(self):
while True:
for test in OpenBench.utils.get_awaiting_tests():
for test in get_awaiting_tests():
try: self.update_test(test)
except:
traceback.print_exc()
+237
View File
@@ -0,0 +1,237 @@
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# OpenBench is a chess engine testing framework authored 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/>. #
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Module serves a singular purpose, to invoke:
# >>> create_workload(request, type)
#
# A Workload can be a "TEST", which is an SPRT, or FIXED type.
# A Workload can be a "TUNE", which is an SPSA tuning session
#
# This module will either create the workload and return the user to the index,
# which will display their newly created test. Or it will return them to index,
# with a list of errors that need to be fixed. A warning may also be displayed,
# if the Base branch appears ahead of the Dev branch.
import math
import OpenBench.utils
import OpenBench.views
from OpenBench.models import *
from OpenBench.workloads.verify_workload import verify_workload
def create_workload(request, workload_type):
assert workload_type in [ 'TEST', 'TUNE' ]
if not request.user.is_authenticated:
return OpenBench.views.redirect(request, '/login/', error='Only enabled users can create tests')
if not Profile.objects.get(user=request.user).enabled:
return OpenBench.views.redirect(request, '/login/', error='Only enabled users can create tests')
if request.method == 'GET':
data = { 'networks' : list(Network.objects.all().values()) }
template = 'create_test.html' if workload_type == 'TEST' else 'create_tune.html'
return OpenBench.views.render(request, template, data)
if workload_type == 'TEST':
workload, errors = create_new_test(request)
if workload_type == 'TUNE':
workload, errors = create_new_tune(request)
if errors != [] and errors != None:
url = '/newTest/' if workload_type == 'TEST' else '/newTune/'
return OpenBench.views.redirect(request, url, error='\n'.join(errors))
if warning := OpenBench.utils.branch_is_out_of_date(workload):
warning = 'Consider Rebasing: Dev (%s) appears behind Base (%s)' % (workload.dev.name, workload.base.name)
username = request.user.username
profile = Profile.objects.get(user=request.user)
summary = 'CREATE P=%d TP=%d' % (workload.priority, workload.throughput)
LogEvent.objects.create(author=username, summary=summary, log_file='', test_id=workload.id)
if not OpenBench.config.USE_CROSS_APPROVAL and profile.approver:
workload.approved = True; workload.save()
return OpenBench.views.redirect(request, '/index/', warning=warning)
def create_new_test(request):
# Collects erros, and collects all data from the Github API
errors, engine_info = verify_workload(request, 'TEST')
dev_info, dev_has_all = engine_info[0]
base_ingo, base_has_all = engine_info[1]
if errors:
return None, errors
test = Test()
test.author = request.user.username
test.book_name = request.POST['book_name']
test.dev = get_engine(*dev_info)
test.dev_repo = request.POST['dev_repo']
test.dev_engine = request.POST['dev_engine']
test.dev_options = request.POST['dev_options']
test.dev_network = request.POST['dev_network']
test.dev_time_control = OpenBench.utils.TimeControl.parse(request.POST['dev_time_control'])
test.base = get_engine(*base_ingo)
test.base_repo = request.POST['base_repo']
test.base_engine = request.POST['base_engine']
test.base_options = request.POST['base_options']
test.base_network = request.POST['base_network']
test.base_time_control = OpenBench.utils.TimeControl.parse(request.POST['base_time_control'])
test.worker_limit = 0 if request.POST['worker_limit'] == 'None' else int(request.POST['worker_limit'])
test.thread_limit = 0 if request.POST['thread_limit'] == 'None' else int(request.POST['thread_limit'])
test.workload_size = int(request.POST['workload_size'])
test.priority = int(request.POST['priority'])
test.throughput = int(request.POST['throughput'])
test.syzygy_wdl = request.POST['syzygy_wdl']
test.syzygy_adj = request.POST['syzygy_adj']
test.win_adj = request.POST['win_adj']
test.draw_adj = request.POST['draw_adj']
test.test_mode = request.POST['test_mode']
test.awaiting = not (dev_has_all and base_has_all)
if test.test_mode == 'SPRT':
test.elolower = float(request.POST['test_bounds'].split(',')[0].lstrip('['))
test.eloupper = float(request.POST['test_bounds'].split(',')[1].rstrip(']'))
test.alpha = float(request.POST['test_confidence'].split(',')[1].rstrip(']'))
test.beta = float(request.POST['test_confidence'].split(',')[0].lstrip('['))
test.lowerllr = math.log(test.beta / (1.0 - test.alpha))
test.upperllr = math.log((1.0 - test.beta) / test.alpha)
if test.test_mode == 'GAMES':
test.max_games = int(request.POST['test_max_games'])
if test.dev_network:
test.dev_netname = Network.objects.get(engine=test.dev_engine, sha256=test.dev_network).name
if test.base_network:
test.base_netname = Network.objects.get(engine=test.base_engine, sha256=test.base_network).name
test.save()
profile = Profile.objects.get(user=request.user)
profile.tests += 1
profile.save()
return test, None
def create_new_tune(request):
# Collects erros, and collects all data from the Github API
errors, engine_info = verify_workload(request, 'TUNE')
dev_info, dev_has_all = engine_info
if errors:
return None, errors
test = Test()
test.author = request.user.username
test.book_name = request.POST['book_name']
test.dev = test.base = get_engine(*dev_info)
test.dev_repo = test.base_repo = request.POST['dev_repo']
test.dev_engine = test.base_engine = request.POST['dev_engine']
test.dev_options = test.base_options = request.POST['dev_options']
test.dev_network = test.base_network = request.POST['dev_network']
test.dev_time_control = test.base_time_control = OpenBench.utils.TimeControl.parse(request.POST['dev_time_control'])
test.worker_limit = 0 if request.POST['worker_limit'] == 'None' else int(request.POST['worker_limit'])
test.thread_limit = 0 if request.POST['thread_limit'] == 'None' else int(request.POST['thread_limit'])
test.workload_size = int(request.POST['spsa_pairs_per'])
test.priority = int(request.POST['priority'])
test.throughput = int(request.POST['throughput'])
test.syzygy_wdl = request.POST['syzygy_wdl']
test.syzygy_adj = request.POST['syzygy_adj']
test.win_adj = request.POST['win_adj']
test.draw_adj = request.POST['draw_adj']
test.test_mode = 'SPSA'
test.spsa = extract_spas_params(request)
test.awaiting = not dev_has_all
if test.dev_network:
name = Network.objects.get(engine=test.dev_engine, sha256=test.dev_network).name
test.dev_netname = test.base_netname = name
test.save()
profile = Profile.objects.get(user=request.user)
profile.tests += 1
profile.save()
return test, None
def extract_spas_params(request):
spsa = {} # SPSA Hyperparams
spsa['Alpha' ] = float(request.POST['spsa_alpha'])
spsa['Gamma' ] = float(request.POST['spsa_gamma'])
spsa['A_ratio'] = float(request.POST['spsa_A_ratio'])
# Tuning durations
spsa['iterations'] = int(request.POST['spsa_iterations'])
spsa['pairs_per' ] = int(request.POST['spsa_pairs_per'])
spsa['A' ] = spsa['A_ratio'] * spsa['iterations']
# Each individual tuning parameter
spsa['parameters'] = {}
for line in request.POST['spsa_inputs'].split('\n'):
# Comma-seperated values, already verified in verify_workload()
name, data_type, value, minimum, maximum, c_end, r_end = line.split(',')
param = {} # Raw extraction
param['float'] = data_type.strip() == 'float'
param['start'] = float(value)
param['value'] = float(value)
param['min' ] = float(minimum)
param['max' ] = float(maximum)
param['c_end'] = float(c_end)
param['r_end'] = float(r_end)
# Verbatim Fishtest logic for computing these
param['c'] = param['c_end'] * spsa['iterations'] ** spsa['Gamma']
param['a_end'] = param['r_end'] * param['c_end'] ** 2
param['a'] = param['a_end'] * (spsa['A'] + spsa['iterations']) ** spsa['Alpha']
spsa['parameters'][name] = param
return spsa
def get_engine(source, name, sha, bench):
engine = Engine.objects.filter(name=name, source=source, sha=sha, bench=bench)
if engine.first() != None:
return engine.first()
return Engine.objects.create(name=name, source=source, sha=sha, bench=bench)
+316
View File
@@ -0,0 +1,316 @@
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# OpenBench is a chess engine testing framework authored 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/>. #
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Module serves a singular purpose, to invoke:
# >>> get_workload(Machine)
#
# Selects a Test, from the active tests, with the following procedure...
# 1. Remove all tests with Engines not supported by the Worker
# 2. Remove all tests with unmet Syzygy requirements
# 3. Remove all tests with thread-odds, if the Worker is hyperthreading
# 4. Remove all tests where our machine will exceed the Worker Limit
# 5. Remove all tests where our machine will exceed the Thread Limit
# 6. Remove all tests that don't have the highest priority in the test list
#
# At this point, we select from these candidate tests using the following:
# 1. Randomly select from any tests that have 0 workers
# 2. Repeat the same test ( if it exists ), if distribution is still "Fair"
# 3. Select the test with the most "Unfair" distribution of workers
#
# Our response includes three critical values:
#
# 1. cutechess-count The # of Sockets on the worker for SPRT/FIXED tests
# The # of max possible concurrent games for SPRT tests
# 2. concurrency-per The # of concurrent games to run per Cutechess copy.
# Function of the machine, and each engine's options
# 3. games-per-cutechess # of total games to run per Cutechess copy
# This is the 2 x workload_size x concurrency-per
import math
import random
import re
import sys
import OpenBench.utils
from OpenBench.config import OPENBENCH_CONFIG
from OpenBench.models import Result, Test
def get_workload(machine):
# Select a workload from the possible ones, if we can
if not (test := select_workload(machine)):
return {}
# Fetch or create the Result object for the test
try: result = Result.objects.get(test=test, machine=machine)
except: result = Result(test=test, machine=machine)
# Update the Machine's status and save everything
machine.workload = test.id; machine.save(); result.save()
return { 'workload' : workload_to_dictionary(test, result, machine) }
def select_workload(machine):
# Find valid workloads, given the current distribution of workers
active, distribution = worker_distribution(machine)
if not (tests := filter_valid_workloads(active, machine, distribution)):
return {}
# Find the tests most deserving of resources currently
ratios = [distribution[x.id]['threads'] / x.throughput for x in tests]
lowest_indices = [i for i, r in enumerate(ratios) if r == min(ratios)]
# Machine is out of date; or there is an unassigned test
if machine.workload not in distribution or min(ratios) == 0:
return tests[random.choice(lowest_indices)]
# Determine the "fair" ratio given the total threads and total throughput of tests
total_threads = sum([distribution[x.id]['threads'] for x in tests])
total_throughput = sum([x.throughput for x in tests])
fair_ratio = total_threads / total_throughput
# Repeat the same test if the distribution is still fair
if min(ratios) / fair_ratio > 0.75:
return Test.objects.get(id=machine.workload)
# Fallback to simply doing the least attention given test
return tests[random.choice(lowest_indices)]
def worker_distribution(machine):
# For each test ( which some worker claims to be running ), return
# a dict with the # of workers and # of threads actively on the test
tests = OpenBench.utils.get_active_tests()
distribution = {
test.id : { 'workers' : 0, 'threads' : 0 } for test in tests
}
# Don't count ourselves; and don't include non-active tests
for x in OpenBench.utils.getRecentMachines():
if machine != x and x.workload in distribution:
distribution[x.workload]['workers'] += 1
distribution[x.workload]['threads'] += x.info['concurrency']
return tests, distribution
def filter_valid_workloads(tests, machine, distribution):
# Skip engines that the Machine cannot handle
for engine in OPENBENCH_CONFIG['engines'].keys():
if engine not in machine.info['supported']:
tests = tests.exclude(dev_engine=engine)
tests = tests.exclude(base_engine=engine)
# Skip tests with unmet Syzygy requirements
for K in range(machine.info['syzygy_max'] + 1, 10):
tests = tests.exclude(syzygy_adj='%d-MAN' % (K))
tests = tests.exclude(syzygy_wdl='%d-MAN' % (K))
# Skip tests that would waste available Threads or exceed them
threads = machine.info['concurrency']
sockets = machine.info['sockets']
hyperthreads = machine.info['physical_cores'] < threads
options = [x for x in tests if valid_assignment(machine, x, distribution)]
# Finally refine for tests of the highest priority
if not options: return []
highest_prio = max(options, key=lambda x: x.priority).priority
return [test for test in options if test.priority == highest_prio]
def valid_assignment(machine, test, distribution):
# Extract thread requirements from the test itself
dev_threads = int(OpenBench.utils.extract_option(test.dev_options, 'Threads'))
base_threads = int(OpenBench.utils.extract_option(test.base_options, 'Threads'))
# Extract the information from our machine
threads = machine.info['concurrency']
sockets = machine.info['sockets']
hyperthreads = machine.info['physical_cores'] < threads
# SPSA plays a pair at a time, not a game at a time
is_spsa = test.test_mode == 'SPSA'
is_sprt = test.test_mode != 'SPSA'
# Refuse if there are not enough threads-per-socket for the test
if (1 + is_spsa) * max(dev_threads, base_threads) > (threads / sockets):
return False
# Refuse thread odds if we are using hyperthreads
if dev_threads != base_threads and hyperthreads:
return False
# Refuse to assign more workers than the test will allow
current_workers = distribution[test.id]['workers'] if test.id in distribution else 0
if test.worker_limit and current_workers >= test.worker_limit:
return False
# Refuse to assign more threads than the test will allow
current_threads = distribution[test.id]['threads'] if test.id in distribution else 0
if test.thread_limit and current_threads + threads > test.thread_limit:
return False
# All Criteria have been met
return True
def workload_to_dictionary(test, result, machine):
workload = {}
workload['result'] = {
'id' : result.id,
}
workload['test'] = {
'id' : test.id,
'type' : test.test_mode,
'syzygy_wdl' : test.syzygy_wdl,
'syzygy_adj' : test.syzygy_adj,
'win_adj' : test.win_adj,
'draw_adj' : test.draw_adj,
'workload_size' : test.workload_size,
'book' : OPENBENCH_CONFIG['books'][test.book_name],
}
workload['test']['dev'] = {
'id' : test.dev.id,
'name' : test.dev.name,
'source' : test.dev.source,
'sha' : test.dev.sha,
'bench' : test.dev.bench,
'engine' : test.dev_engine,
'options' : test.dev_options,
'network' : test.dev_network,
'time_control' : test.dev_time_control,
'nps' : OPENBENCH_CONFIG['engines'][test.dev_engine]['nps'],
'build' : OPENBENCH_CONFIG['engines'][test.dev_engine]['build'],
'private' : OPENBENCH_CONFIG['engines'][test.dev_engine]['private'],
}
workload['test']['base'] = {
'id' : test.base.id,
'name' : test.base.name,
'source' : test.base.source,
'sha' : test.base.sha,
'bench' : test.base.bench,
'engine' : test.base_engine,
'options' : test.base_options,
'network' : test.base_network,
'time_control' : test.base_time_control,
'nps' : OPENBENCH_CONFIG['engines'][test.base_engine]['nps'],
'build' : OPENBENCH_CONFIG['engines'][test.base_engine]['build'],
'private' : OPENBENCH_CONFIG['engines'][test.base_engine]['private'],
}
workload['distribution'] = game_distribution(test, machine)
workload['spsa'] = spsa_to_dictionary(test, workload['distribution']['cutechess-count'])
return workload
def spsa_to_dictionary(test, permutations):
if test.test_mode != 'SPSA':
return None
# C & R are scaled over the course of the iterations
iteration = 1 + (test.games / (test.spsa['pairs_per'] * 2))
c_compression = iteration ** test.spsa['Gamma']
r_compression = (test.spsa['A'] + iteration) ** test.spsa['Alpha']
spsa = {}
for name, param in test.spsa['parameters'].items():
spsa[name] = {
'dev' : [], # One for each Permutation the Worker will run
'base' : [], # One for each Permutation the Worker will run
'flip' : [], # One for each Permutation the Worker will run
}
# C & R are constants for a particular assignment, for all Permutations
spsa[name]['c'] = param['c'] / c_compression
spsa[name]['r'] = param['a'] / r_compression / spsa[name]['c'] ** 2
for f in range(permutations):
# Adjust current best by +- C
flip = 1 if random.getrandbits(1) else -1
dev = param['value'] + flip * spsa[name]['c']
base = param['value'] - flip * spsa[name]['c']
# Probabilistic rounding for Integer types
if not param['float']:
r = random.uniform(0, 1)
dev = math.floor(dev + r)
base = math.floor(base + r)
# Clip within [Min, Max]
dev = max(param['min'], min(param['max'], dev ))
base = max(param['min'], min(param['max'], base))
# Round integer values down
if not param['float']:
dev = int(dev )
base = int(base)
# Append each permutation
spsa[name]['dev' ].append(dev)
spsa[name]['base'].append(base)
spsa[name]['flip'].append(flip)
return spsa
def extract_option(options, option):
if (match := re.search('(?<=%s=")[^"]*' % (option), options)):
return match.group()
if (match := re.search('(?<=%s=\')[^\']*' % (option), options)):
return match.group()
if (match := re.search('(?<=%s=)[^ ]*' % (option), options)):
return match.group()
def game_distribution(test, machine):
# Every Option contains Threads= for both engines
dev_threads = int(extract_option(test.dev_options, 'Threads'))
base_threads = int(extract_option(test.base_options, 'Threads'))
# "concurrency" is the total number of connected Threads
worker_threads = machine.info['concurrency']
worker_sockets = machine.info['sockets']
# Concurrency per cutechess, if splitting by sockets
concurrency = (worker_threads // worker_sockets) // max(dev_threads, base_threads)
# Number of params being evaluated at a single time
spsa_count = (worker_threads // max(dev_threads, base_threads)) // 2
is_spsa = test.test_mode == 'SPSA'
return {
'cutechess-count' : spsa_count if is_spsa else worker_sockets,
'concurrency-per' : 2 if is_spsa else concurrency,
'games-per-cutechess' : 2 * test.workload_size * (1 if is_spsa else concurrency),
}
+111
View File
@@ -0,0 +1,111 @@
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# OpenBench is a chess engine testing framework authored 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/>. #
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Module serves a singular purpose, to invoke:
# >>> modify_workload(request, id, action)
#
# Given a request, a workload id, and an action, attempt to modify the workload as
# requested. This will return the user to the index, or a login page, with some
# indication as to success, or a reason for failure.
import OpenBench.views
from OpenBench.models import *
def modify_workload(request, id, action=None):
actions = {
'APPROVE' : approve_workload, 'RESTART' : restart_workload,
'STOP' : stop_workload, 'DELETE' : delete_workload,
'RESTORE' : restore_workload, 'MODIFY' : tweak_workload,
}
# Make sure the requested Action is a known one
if action not in actions.keys():
return OpenBench.views.redirect(request, '/index/', error='Unknown Workload action')
# Make sure that the Test or Tune exists
if not (workload := Test.objects.filter(id=id).first()):
return OpenBench.views.redirect(request, '/index/', error='No such Workload exists')
# Must be logged in to interact with Tests and Tunes
if not request.user.is_authenticated:
return OpenBench.views.redirect(request, '/login/', error='Only users may modify Workloads')
# Must be an approver, or interacting with their own Test or Tune
profile = Profile.objects.get(user=request.user)
if not profile.approver and workload.author != request.user.username:
return OpenBench.views.redirect(request, '/index/', error='You cannot interact with another user\'s Workload')
# Make the change; Record the change; Save the change
message = actions[action](request, profile, workload)
LogEvent.objects.create(author=request.user.username, summary=action, log_file='', test_id=id)
workload.save()
# Send back to the index, notifying them of the success
return OpenBench.views.redirect(request, '/index/', status=message)
def approve_workload(request, profile, workload):
workload.approved = True;
return 'Workload was Approved!'
def restart_workload(request, profile, workload):
workload.finished = False;
return 'Workload was Restarted!'
def stop_workload(request, profile, workload):
workload.finished = True;
return 'Workload was Stopped!'
def delete_workload(request, profile, workload):
workload.deleted = True
return 'Workload was Deleted!'
def restore_workload(request, profile, workload):
workload.deleted = False
return 'Workload was Restored!'
def tweak_workload(request, profile, workload):
try: # Priority can be any integer value
workload.priority = int(request.POST['priority'])
except: pass
try: # Throughput must be at least 1
workload.throughput = max(1, int(request.POST['throughput']))
except: pass
try: # Must be at least 0. Convert "None" to 0
x = request.POST['worker_limit']
workload.worker_limit = 0 if x == 'None' else max(0, int(x))
except: pass
try: # Must be at least 0. Convert "None" to 0
x = request.POST['thread_limit']
workload.thread_limit = 0 if x == 'None' else max(0, int(x))
except: pass
try: # Must be at least one. Cannot be changed for Tuning workloads
if workload.test_mode != 'SPSA':
workload.workload_size = max(1, int(request.POST['workload_size']))
except: pass
return 'Workload was Modified!'
+403
View File
@@ -0,0 +1,403 @@
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# OpenBench is a chess engine testing framework authored 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/>. #
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Module serves a singular purpose, to invoke:
# >>> verify_workload(request, type)
#
# Given a request, and a workload_type [TEST, TUNE], verify all of the form
# inputs, collect all of the information from Github, verify all of the data
# from Github, and return a tuple of (errors, engines)
#
# For Verifying and Collection information on a Test:
# >>> errors, engine_info = verify_workload(request, 'TEST')
# >>> dev_info, base_info = engine_info
#
# For Verifying and Collection information on a Tune:
# >>> errors, engine_info = verify_workload(request, 'TUNE')
import os
import re
import requests
import traceback
import OpenBench.config
import OpenBench.utils
from OpenBench.models import *
def verify_workload(request, workload_type):
assert workload_type in [ 'TEST', 'TUNE' ]
errors = []
if workload_type == 'TEST':
verify_test_creation(errors, request)
dev = collect_github_info(errors, request, 'dev')
base = collect_github_info(errors, request, 'base')
return errors, (dev, base)
if workload_type == 'TUNE':
verify_tune_creation(errors, request)
engine = collect_github_info(errors, request, 'dev')
return errors, engine
def verify_test_creation(errors, request):
verifications = [
# Verify everything about the Dev Engine
(verify_configuration , 'dev_engine', 'Dev Engine', 'engines'),
(verify_github_repo , 'dev_repo'),
(verify_network , 'dev_network', 'Dev Network', 'dev_engine'),
(verify_options , 'dev_options', 'Threads', 'Dev Options'),
(verify_options , 'dev_options', 'Hash', 'Dev Options'),
(verify_time_control , 'dev_time_control', 'Dev Time Control'),
# Verify everything about the Base Engine
(verify_configuration , 'base_engine', 'Base Engine', 'engines'),
(verify_github_repo , 'base_repo'),
(verify_network , 'base_network', 'Base Network', 'base_engine'),
(verify_options , 'base_options', 'Threads', 'Base Options'),
(verify_options , 'base_options', 'Hash', 'Base Options'),
(verify_time_control , 'base_time_control', 'Base Time Control'),
# Verify everything about the Test Settings
(verify_configuration , 'book_name', 'Book', 'books'),
(verify_test_mode , 'test_mode'),
(verify_sprt_bounds , 'test_bounds'),
(verify_sprt_conf , 'test_confidence'),
(verify_max_games , 'test_max_games'),
# Verify everything about the General Settings
(verify_integer , 'priority', 'Priority'),
(verify_greater_than , 'throughput', 'Throughput', 0),
(verify_syzygy_field , 'syzygy_wdl', 'Syzygy WDL'),
# Verify everything about the Workload Settings
(verify_integer_or_none, 'worker_limit', 'Worker Limit'),
(verify_integer_or_none, 'thread_limit', 'Thread Limit'),
(verify_integer , 'workload_size', 'Workload Size'),
(verify_greater_than , 'workload_size', 'Workload Size', 0),
# Verify everything about the Adjudicaton Settings
(verify_syzygy_field , 'syzygy_adj', 'Syzygy Adjudication'),
(verify_win_adj , 'win_adj'),
(verify_draw_adj , 'draw_adj'),
]
for verification in verifications:
verification[0](errors, request, *verification[1:])
def verify_tune_creation(errors, request):
verifications = [
# Verify everything about the Engine
(verify_configuration , 'dev_engine', 'Engine', 'engines'),
(verify_github_repo , 'dev_repo'),
(verify_network , 'dev_network', 'Network', 'dev_engine'),
(verify_options , 'dev_options', 'Threads', 'Options'),
(verify_options , 'dev_options', 'Hash', 'Options'),
(verify_time_control , 'dev_time_control', 'Time Control'),
# Verify everything about the Test Settings
(verify_configuration , 'book_name', 'Book', 'books'),
# Verify everything about the General Settings
(verify_integer , 'priority', 'Priority'),
(verify_greater_than , 'throughput', 'Throughput', 0),
(verify_syzygy_field , 'syzygy_wdl', 'Syzygy WDL'),
# Verify everything about the Workload Settings
(verify_integer_or_none, 'worker_limit', 'Worker Limit'),
(verify_integer_or_none, 'thread_limit', 'Thread Limit'),
# Verify everything about the Adjudicaton Settings
(verify_syzygy_field , 'syzygy_adj', 'Syzygy Adjudication'),
(verify_win_adj , 'win_adj'),
(verify_draw_adj , 'draw_adj'),
# Verify everything about the SPSA Settings
(verify_float , 'spsa_alpha', 'SPSA A-Ratio'),
(verify_float , 'spsa_alpha', 'SPSA Alpha'),
(verify_float , 'spsa_gamma', 'SPSA Gamma'),
(verify_integer , 'spsa_iterations', 'SPSA Iterations'),
(verify_integer , 'spsa_pairs_per', 'SPSA Pairs-Per'),
(verify_greater_than , 'spsa_alpha', 'SPSA A-Ratio', 0.00),
(verify_greater_than , 'spsa_alpha', 'SPSA Alpha', 0.00),
(verify_greater_than , 'spsa_gamma', 'SPSA Gamma', 0.00),
(verify_greater_than , 'spsa_iterations', 'SPSA Iterations', 0),
(verify_greater_than , 'spsa_pairs_per', 'SPSA Pairs-Per', 0),
# Verify the SPSA raw inputs for each parameter
(verify_spsa_inputs , 'spsa_inputs'),
]
for verification in verifications:
verification[0](errors, request, *verification[1:])
def verify_integer(errors, request, field, field_name):
try: int(request.POST[field])
except: errors.append('"{0}" is not an Integer'.format(field_name))
def verify_integer_or_none(errors, request, field, field_name):
try: True if request.POST[field] == 'None' else int(request.POST[field])
except: errors.append('"{0}" is neither an Integer nor "None"'.format(field_name))
def verify_float(errors, request, field, field_name):
try: float(request.POST[field])
except: errors.append('"{0}" is not a Float'.format(field_name))
def verify_greater_than(errors, request, field, field_name, value):
try: assert float(request.POST[field]) > value
except: errors.append('"{0}" is not greater than {1}'.format(field_name, value))
def verify_options(errors, request, field, option, field_name):
try: assert int(OpenBench.utils.extract_option(request.POST[field], option)) >= 1
except: errors.append('"{0}" needs to be at least 1 for {1}'.format(option, field_name))
def verify_configuration(errors, request, field, field_name, parent):
try: assert request.POST[field] in OpenBench.config.OPENBENCH_CONFIG[parent].keys()
except: errors.append('{0} was not found in the configuration'.format(field_name))
def verify_time_control(errors, request, field, field_name):
try: OpenBench.utils.TimeControl.parse(request.POST[field])
except: errors.append('{0} is not parsable'.format(field_name))
def verify_win_adj(errors, request, field):
try:
if (content := request.POST[field]) == 'None': return
assert re.match('movecount=[0-9]+ score=[0-9]+', content)
except: errors.append('Invalid Win Adjudication Setting. Try "None"?')
def verify_draw_adj(errors, request, field):
try:
if (content := request.POST[field]) == 'None': return
assert re.match('movenumber=[0-9]+ movecount=[0-9]+ score=[0-9]+', content)
except: errors.append('Invalid Draw Adjudication Setting. Try "None"?')
def verify_github_repo(errors, request, field):
pattern = r'^https:\/\/github\.com\/[A-Za-z0-9-]+\/[A-Za-z0-9_.-]+\/?$'
try: assert re.match(pattern, request.POST[field])
except: errors.append('Sources must be found on https://github.com/<User>/<Repo>')
def verify_network(errors, request, field, field_name, engine_field):
try:
if request.POST[field] == '': return
Network.objects.get(engine=request.POST[engine_field], sha256=request.POST[field])
except: errors.append('Unknown Network Provided for {0}'.format(field_name))
def verify_test_mode(errors, request, field):
try: assert request.POST[field] in ['SPRT', 'GAMES']
except: errors.append('Unknown Test Mode')
def verify_sprt_bounds(errors, request, field):
try:
if request.POST['test_mode'] != 'SPRT': return
pattern = r'^\[(-?\d+(?:\.\d+)?), (-?\d+(?:\.\d+)?)\]$'
match = re.match(pattern, request.POST['test_bounds'])
assert float(match.group(1)) < float(match.group(2))
except: errors.append('SPRT Bounds must be formatted as [float1, float2]')
def verify_sprt_conf(errors, request, field):
try:
if request.POST['test_mode'] != 'SPRT': return
pattern = r'^\[(-?\d+(?:\.\d+)?), (-?\d+(?:\.\d+)?)\]$'
match = re.match(pattern, request.POST['test_confidence'])
assert 0.00 < float(match.group(1)) < 1.00
assert 0.00 < float(match.group(2)) < 1.00
except: errors.append('Confidence Bounds must be formatted as [float1, float2], within (0.00, 1.00)')
def verify_max_games(errors, request, field):
try:
if request.POST['test_mode'] != 'GAMES': return
assert int(request.POST['test_max_games']) > 0
except: errors.append('Fixed Games Tests must last at least one game')
def verify_syzygy_field(errors, request, field, field_name):
candidates = ['OPTIONAL', 'DISABLED', '3-MAN', '4-MAN', '5-MAN', '6-MAN', '7-MAN']
try: assert request.POST[field] in candidates
except: errors.append('%s must be in %s' % (field_name, ', '.join(candidates)))
def verify_spsa_inputs(errors, request, field):
try:
if not (lines := request.POST[field].split('\n')):
errors.append('No Parameters Provided')
for line in lines:
name, data_type, value, minimum, maximum, c, r = line.split(',')
if data_type.strip() not in [ 'int', 'float' ]:
errors.append('Datatype must be int for float, for %s' % (name))
if float(minimum) >= float(maximum):
errors.append('Max does not exceed Min, for %s' % (name))
if not (float(minimum) <= float(value) <= float(maximum)):
errors.append('Value must be within [Min, Max], for %s' % (name))
if float(c) <= 0.00:
errors.append('C must be > 0.00, for %s' % (name))
if float(r) <= 0.00:
errors.append('C must be > 0.00, for %s' % (name))
except:
traceback.print_exc()
errors.append('Malformed SPSA Input')
def collect_github_info(errors, request, field):
# Get branch name / commit sha / tag, and the API path for it
branch = request.POST['{0}_branch'.format(field)]
bysha = bool(re.search('[0-9a-fA-F]{40}', branch))
# All API requests will share this common path. Some engines are private.
base = request.POST['%s_repo' % (field)].replace('github.com', 'api.github.com/repos')
engine = request.POST['%s_engine' % (field)]
private = OpenBench.config.OPENBENCH_CONFIG['engines'][engine]['private']
headers = {}
## Step 1: Verify the target of the API requests
## [A] We will not attempt to reach any site other than api.github.com
## [B] Private engines may only use their main repo for sources of tests
## [C] Determine which, if any, credentials we want to pass along
# Private engines must have a token stored in credentials.enginename
if private and not (headers := OpenBench.utils.read_git_credentials(engine)):
errors.append('Server does not have access tokens for this engine')
return (None, None)
# Do not allow private engines to use forked repos ( We don't have a token! )
if requests_illegal_fork(request, field):
errors.append('Forked Repositories are not allowed for Private engines')
return (None, None)
# Avoid leaking our credentials to other websites
if not base.startswith('https://api.github.com/'):
errors.append('OpenBench may only reach Github\'s API')
return (None, None)
## Step 2: Connect to the Github API for the given Branch or Commit SHA.
## [A] We will attempt to parse the most recent commit message for a
## bench, unless one was supplied.
## [B] We will translate any branch name into a commit SHA for later use,
## so we may compare branches and generate diff URLs
## [C] If the engine is public, we will construct the URL to download the
## source code from Github into a .zip file.
## [D] If the engine is private, we will carry onto Step 3.
try: # Fetch data from the Github API
# Lookup branch or commit sha, but will fail for tags
url = OpenBench.utils.path_join(base, 'commits' if bysha else 'branches', branch)
data = requests.get(url, headers=headers).json()
# Check to see if the branch name was actually a tag name
if not bysha and 'commit' not in data:
url = OpenBench.utils.path_join(base, 'commits', branch)
data = requests.get(url, headers=headers).json()
# Actual branches have to go one layer deeper
elif not bysha: data = data['commit']
# Check that all the data we need going forward is present
assert 'message' in data['commit'] and 'sha' in data
assert private or 'sha' in data['commit']['tree']
except: # Unable to find for whatever reason
traceback.print_exc()
errors.append('%s could not be found' % (branch or 'Branch'))
return (None, None)
# Extract the bench from the web form, or from the commit message
if not (bench := determine_bench(request, field, data['commit']['message'])):
errors.append('Unable to parse a Bench for %s' % (branch))
return (None, None)
# Public Engines: Construct the .zip download and return everything
if not private:
treeurl = data['commit']['tree']['sha'] + '.zip'
source = OpenBench.utils.path_join(request.POST['%s_repo' % (field)], 'archive', treeurl)
return (source, branch, data['sha'], bench), True
## Step 3: Construct the URL for the API request to list all Artifacts
## [A] OpenBench artifacts are always run via a file named openbench.yml
## [B] These should contain combinations for windows/linux, avx2/avx512, popcnt/pext
## [C] If those artifacts are not found, we flag the test as awaiting, and try later.
url, has_all = fetch_artifact_url(base, engine, headers, data['sha'])
return (url, branch, data['sha'], bench), has_all
def requests_illegal_fork(request, field):
# Strip trailing '/'s for sanity
engine = OpenBench.config.OPENBENCH_CONFIG['engines'][request.POST['%s_engine' % (field)]]
eng_src = engine['source'].rstrip('/')
tar_src = request.POST['%s_repo' % (field)].rstrip('/')
# Illegal if sources do not match for Private engines
return engine['private'] and eng_src != tar_src
def determine_bench(request, field, message):
# Use the provided bench if possible
try: return int(request.POST['{0}_bench'.format(field)])
except: pass
# Fallback to try to parse the Bench from the commit
try:
benches = re.findall('(?:BENCH|NODES)[ :=]+([0-9,]+)', message, re.IGNORECASE)
return int(benches[-1].replace(',', ''))
except: return None
def fetch_artifact_url(base, engine, headers, sha):
try:
# Fetch the run id for the openbench workflow for this comment
url = OpenBench.utils.path_join(base, 'actions', 'workflows', 'openbench.yml', 'runs')
url += '?head_sha=%s' % (sha)
run_id = requests.get(url=url, headers=headers).json()['workflow_runs'][0]['id']
# Fetch information about individual job results
url = OpenBench.utils.path_join(base, 'actions', 'runs', str(run_id), 'jobs')
jobs = requests.get(url=url, headers=headers).json()['jobs']
# Fetch information about individual artifact
url = OpenBench.utils.path_join(base, 'actions', 'runs', str(run_id), 'artifacts')
artifacts = requests.get(url=url, headers=headers).json()['artifacts']
# All jobs finished, with at least one non-expired Artifact
assert not any(job['conclusion'] != 'success' for job in jobs)
assert not any(artifact['expired'] for artifact in artifacts)
assert len(artifacts) >= len(jobs)
# Only set the url if we have everything we need
return (url, True)
except Exception as error:
# If anything goes wrong, retry later with the same base URL
return (base, False)