New Networks API + Cross-Engine Fixes + Script fixes

This commit is contained in:
Andrew Grant authored and GitHub committed 2023-07-15 04:20:32 -04:00
commit 2b28f9b498
14 files changed
+474 -404

No files matched your search

+32 -26
View File
@@ -44,7 +44,7 @@ from concurrent.futures import ThreadPoolExecutor
TIMEOUT_HTTP = 30 # Timeout in seconds for HTTP requests TIMEOUT_HTTP = 30 # Timeout in seconds for HTTP requests
TIMEOUT_ERROR = 10 # Timeout in seconds when any errors are thrown TIMEOUT_ERROR = 10 # Timeout in seconds when any errors are thrown
TIMEOUT_WORKLOAD = 30 # Timeout in seconds between workload requests TIMEOUT_WORKLOAD = 30 # Timeout in seconds between workload requests
CLIENT_VERSION = '10' # Client version to send to the Server CLIENT_VERSION = '11' # Client version to send to the Server
IS_WINDOWS = platform.system() == 'Windows' # Don't touch this IS_WINDOWS = platform.system() == 'Windows' # Don't touch this
IS_LINUX = platform.system() != 'Windows' # Don't touch this IS_LINUX = platform.system() != 'Windows' # Don't touch this
@@ -433,7 +433,7 @@ class Cutechess(object):
return '-openings file=Books/%s format=%s order=random plies=16' % (book_name, book_suffix) return '-openings file=Books/%s format=%s order=random plies=16' % (book_name, book_suffix)
@staticmethod @staticmethod
def engine_settings(config, command, branch, nps): def engine_settings(config, command, branch, scale_factor):
# Extract configuration from the Workload # Extract configuration from the Workload
options = config.workload['test'][branch]['options'] options = config.workload['test'][branch]['options']
@@ -443,7 +443,7 @@ class Cutechess(object):
# Human-readable name, and scale the time control # Human-readable name, and scale the time control
name = command.removesuffix('.exe') name = command.removesuffix('.exe')
control = scale_time_control(config.workload, nps, branch) control = scale_time_control(config.workload, scale_factor, branch)
# Private engines, when using Networks, must set them via UCI # Private engines, when using Networks, must set them via UCI
if private and network and network != 'None': if private and network and network != 'None':
@@ -665,7 +665,7 @@ def run_bench(engine, outqueue, private_net=None):
outqueue.put(parse_bench_output(stdout)) outqueue.put(parse_bench_output(stdout))
except Exception: outqueue.put((0, 0)) except Exception: outqueue.put((0, 0))
def scale_time_control(workload, nps, branch): def scale_time_control(workload, scale_factor, branch):
# Extract everything from the workload dictionary # Extract everything from the workload dictionary
reference_nps = workload['test'][branch]['nps'] reference_nps = workload['test'][branch]['nps']
@@ -687,7 +687,7 @@ def scale_time_control(workload, nps, branch):
# Scale the time based on this machine's NPS. Add a time Margin to avoid time losses. # Scale the time based on this machine's NPS. Add a time Margin to avoid time losses.
if results: if results:
mode, value = results.group('mode', 'value') mode, value = results.group('mode', 'value')
return 'st=%.2f timemargin=100' % ((float(value) * reference_nps) / (1000 * nps)) return 'st=%.2f timemargin=100' % ((float(value) * scale_factor / 1000))
# Searching for "X/Y+Z" time controls # Searching for "X/Y+Z" time controls
pattern = '(?P<moves>(\d+/)?)(?P<base>\d*(\.\d+)?)(?P<inc>\+(\d+\.)?\d+)?' pattern = '(?P<moves>(\d+/)?)(?P<base>\d*(\.\d+)?)(?P<inc>\+(\d+\.)?\d+)?'
@@ -699,8 +699,8 @@ def scale_time_control(workload, nps, branch):
inc = 0.0 if inc is None else inc.lstrip('+') inc = 0.0 if inc is None else inc.lstrip('+')
# Scale the time based on this machine's NPS # Scale the time based on this machine's NPS
base = float(base) * reference_nps / nps base = float(base) * scale_factor
inc = float(inc ) * reference_nps / nps inc = float(inc ) * scale_factor
# Format the time control for cutechess # Format the time control for cutechess
if moves is None: return 'tc=%.2f+%.2f' % (base, inc) if moves is None: return 'tc=%.2f+%.2f' % (base, inc)
@@ -883,12 +883,22 @@ def complete_workload(config):
if not dev_nps or not base_nps: return if not dev_nps or not base_nps: return
ServerReporter.report_nps(config, dev_nps, base_nps) ServerReporter.report_nps(config, dev_nps, base_nps)
# Scale the engines together, using their NPS relative to expected
dev_factor = config.workload['test']['dev' ]['nps'] / dev_nps
base_factor = config.workload['test']['base']['nps'] / base_nps
avg_factor = (dev_factor + base_factor) / 2
print () # Record this information
print ('Scale Factor Dev : %.4f' % (dev_factor ))
print ('Scale Factor Base : %.4f' % (base_factor))
print ('Scale Factor Avg : %.4f' % (avg_factor ))
# Launch and manage all of the Cutechess workers # Launch and manage all of the Cutechess workers
with ThreadPoolExecutor(max_workers=config.sockets) as executor: with ThreadPoolExecutor(max_workers=config.sockets) as executor:
tasks = [] # Create each of the Cutechess workers tasks = [] # Create each of the Cutechess workers
for x in range(config.sockets): for x in range(config.sockets):
cmd = build_cutechess_command(config, dev_name, base_name, dev_nps, base_nps, x) cmd = build_cutechess_command(config, dev_name, base_name, avg_factor, x)
tasks.append(executor.submit(run_and_parse_cutechess, config, cmd, x)) tasks.append(executor.submit(run_and_parse_cutechess, config, cmd, x))
# Await the completion of all Cutechess workers # Await the completion of all Cutechess workers
@@ -933,29 +943,30 @@ def download_opening_book(config):
def download_network_weights(config, branch): def download_network_weights(config, branch):
# Some tests may not use Neural Networks # Some tests may not use Neural Networks
network_name = config.workload['test'][branch]['network'] engine_name = config.workload['test'][branch]['engine']
if not network_name or network_name == 'None': return None network_sha = config.workload['test'][branch]['network']
if not network_sha or network_sha == 'None': return None
# Log that we are obtaining a Neural Network # Log that we are obtaining a Neural Network
pattern = 'Fetching Neural Network [ %s, %-4s ]' pattern = 'Fetching Neural Network [ %s, %-4s ]'
print(pattern % (network_name, branch.upper())) print(pattern % (network_sha, branch.upper()))
# Fetch the Netural Network if we do not already have it # Fetch the Netural Network if we do not already have it
network_path = os.path.join('Networks', network_name) network_path = os.path.join('Networks', network_sha)
if not os.path.isfile(network_path): if not os.path.isfile(network_path):
target = url_join(config.server, 'clientGetNetwork') target = url_join(config.server, 'clientGetNetwork')
payload = { 'username' : config.username, 'password' : config.password } payload = { 'username' : config.username, 'password' : config.password }
download_file(url_join(target, network_name), network_path, payload) download_file(url_join(target, engine_name, network_sha), network_path, payload)
# Verify the download and delete partial or corrupted ones # Verify the download and delete partial or corrupted ones
with open(network_path, 'rb') as network: with open(network_path, 'rb') as network:
sha256 = hashlib.sha256(network.read()).hexdigest() sha256 = hashlib.sha256(network.read()).hexdigest()
sha256 = sha256[:8].upper() sha256 = sha256[:8].upper()
if network_name != sha256: os.remove(network_path) if network_sha != sha256: os.remove(network_path)
# We have to have the correct Neural Network to continue # We have to have the correct Neural Network to continue
if network_name != sha256: if network_sha != sha256:
raise Exception('Invalid SHA for %s' % (network_name)) raise Exception('Invalid SHA for %s' % (network_sha))
return network_path return network_path
@@ -1051,6 +1062,7 @@ def download_engine(arguments, branch, network):
ServerReporter.report_build_fail(config, branch, cxx_output) ServerReporter.report_build_fail(config, branch, cxx_output)
return None return None
def run_benchmarks(config, branch, engine, network): def run_benchmarks(config, branch, engine, network):
queue = multiprocessing.Queue() queue = multiprocessing.Queue()
@@ -1080,20 +1092,13 @@ def run_benchmarks(config, branch, engine, network):
# Set NPS to 0 if we had any errors # Set NPS to 0 if we had any errors
return 0 if not bench or error else nps return 0 if not bench or error else nps
def build_cutechess_command(config, dev_cmd, base_cmd, dev_nps, base_nps, socket): def build_cutechess_command(config, dev_cmd, base_cmd, scale_factor, socket):
dev_engine = config.workload['test']['dev' ]['engine']
base_engine = config.workload['test']['base']['engine']
# Average the time control scalings for self-play only
if dev_engine == base_engine:
dev_nps = base_nps = (dev_nps + base_nps) / 2
flags = ' ' + Cutechess.basic_settings(config, socket) flags = ' ' + Cutechess.basic_settings(config, socket)
flags += ' ' + Cutechess.concurrency_settings(config) flags += ' ' + Cutechess.concurrency_settings(config)
flags += ' ' + Cutechess.adjudication_settings(config) flags += ' ' + Cutechess.adjudication_settings(config)
flags += ' ' + Cutechess.engine_settings(config, dev_cmd, 'dev', dev_nps) flags += ' ' + Cutechess.engine_settings(config, dev_cmd, 'dev', scale_factor)
flags += ' ' + Cutechess.engine_settings(config, base_cmd, 'base', base_nps) flags += ' ' + Cutechess.engine_settings(config, base_cmd, 'base', scale_factor)
flags += ' ' + Cutechess.book_settings(config) flags += ' ' + Cutechess.book_settings(config)
flags += ' ' + Cutechess.pgnout_settings(config, dev_cmd, base_cmd, socket) flags += ' ' + Cutechess.pgnout_settings(config, dev_cmd, base_cmd, socket)
@@ -1199,3 +1204,4 @@ if __name__ == '__main__':
except Exception: except Exception:
traceback.print_exc() traceback.print_exc()
time.sleep(TIMEOUT_ERROR)
+1 -1
View File
@@ -42,7 +42,7 @@ REQUIRE_MANUAL_REGISTRATION = False # Disable the public facing registration pag
OPENBENCH_CONFIG = { OPENBENCH_CONFIG = {
# Server Client version control # Server Client version control
'client_version' : '10', 'client_version' : '11',
# Generic Error Messages useful to those setting up their own instance # Generic Error Messages useful to those setting up their own instance
'error' : { 'error' : {
+36
View File
@@ -0,0 +1,36 @@
var Networks = JSON.parse(document.getElementById('json-networks').textContent);
var Network_Sorting;
function swap_networks(index1, index2) {
var temp = Networks[index1];
Networks[index1] = Networks[index2];
Networks[index2] = temp;
var table = document.getElementById("network-table");
var temp_row = table.rows[index1+1].innerHTML
table.rows[index1+1].innerHTML = table.rows[index2+1].innerHTML;
table.rows[index2+1].innerHTML = temp_row;
}
function invert_networks() {
for (let i = 0; Networks.length > i * 2; i++)
swap_networks(i, Networks.length-i-1);
}
function sort_networks(field) {
console.log(field);
if (Network_Sorting == field)
return invert_networks();
for (let i = 0; i != Networks.length; i++)
for (let j = i + 1; j != Networks.length; j++)
if (Networks[j][field] > Networks[i][field])
swap_networks(i, j);
Network_Sorting = field;
};
+6
View File
@@ -137,6 +137,12 @@ body, html, main{
word-wrap: break-word; word-wrap: break-word;
} }
/* Things which enable a Cursor Pointer event */
#content .cursor {
cursor: pointer;
}
/* Table Headers in General */ /* Table Headers in General */
#content .table-header th:first-child { #content .table-header th:first-child {
+5 -4
View File
@@ -56,8 +56,10 @@ urlpatterns = [
# Links for viewing and managing Networks # Links for viewing and managing Networks
django.urls.path(r'networks/', OpenBench.views.networks), django.urls.path(r'networks/', OpenBench.views.networks),
django.urls.path(r'networks/<str:target>/', OpenBench.views.networks), django.urls.path(r'networks/<str:engine>/', OpenBench.views.networks),
django.urls.path(r'networks/<str:target>/<str:sha256>/', OpenBench.views.networks), django.urls.path(r'networks/<str:engine>/<str:action>/', OpenBench.views.networks),
django.urls.path(r'networks/<str:engine>/<str:action>/<str:name>/', OpenBench.views.networks),
django.urls.path(r'newNetwork/', OpenBench.views.network_form),
# Links for interacting with OpenBench via scripting # Links for interacting with OpenBench via scripting
django.urls.path(r'scripts/', OpenBench.views.scripts), django.urls.path(r'scripts/', OpenBench.views.scripts),
@@ -67,8 +69,7 @@ urlpatterns = [
django.urls.path(r'clientGetBuildInfo/', OpenBench.views.client_get_build_info), django.urls.path(r'clientGetBuildInfo/', OpenBench.views.client_get_build_info),
django.urls.path(r'clientWorkerInfo/', OpenBench.views.client_worker_info), django.urls.path(r'clientWorkerInfo/', OpenBench.views.client_worker_info),
django.urls.path(r'clientGetWorkload/', OpenBench.views.client_get_workload), django.urls.path(r'clientGetWorkload/', OpenBench.views.client_get_workload),
django.urls.path(r'clientGetNetwork/<str:identifier>/', OpenBench.views.client_get_network), django.urls.path(r'clientGetNetwork/<str:engine>/<str:name>/', OpenBench.views.client_get_network),
django.urls.path(r'clientGetNetwork/<str:identifier>/<str:engine>/', OpenBench.views.client_get_network),
django.urls.path(r'clientWrongBench/', OpenBench.views.client_wrong_bench), django.urls.path(r'clientWrongBench/', OpenBench.views.client_wrong_bench),
django.urls.path(r'clientSubmitNPS/', OpenBench.views.client_submit_nps), django.urls.path(r'clientSubmitNPS/', OpenBench.views.client_submit_nps),
django.urls.path(r'clientSubmitError/', OpenBench.views.client_submit_error), django.urls.path(r'clientSubmitError/', OpenBench.views.client_submit_error),
+123 -24
View File
@@ -18,18 +18,29 @@
# # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
import math, re, requests, random, datetime, os, json import datetime
import hashlib
import json
import math
import os
import random
import re
import requests
import OpenBench.models, OpenBench.stats
import django.utils.timezone
from django.utils import timezone
from django.db.models import F
from django.contrib.auth import authenticate from django.contrib.auth import authenticate
from django.core.files.base import ContentFile
from django.core.files.storage import FileSystemStorage
from django.db.models import F
from django.http import FileResponse
from django.utils import timezone
from wsgiref.util import FileWrapper
from OpenBench.config import * from OpenSite.settings import MEDIA_ROOT
from OpenBench.models import Engine, Profile, Machine, Result, Test, Network
from OpenBench.config import OPENBENCH_CONFIG
from OpenBench.models import *
from OpenBench.stats import SPRT
from OpenBench.views import redirect
def path_join(*args): def path_join(*args):
@@ -78,25 +89,25 @@ def parse_time_control(time_control):
def get_pending_tests(): def get_pending_tests():
t = OpenBench.models.Test.objects.filter(approved=False) t = Test.objects.filter(approved=False)
t = t.exclude(finished=True) t = t.exclude(finished=True)
t = t.exclude(deleted=True) t = t.exclude(deleted=True)
return t.order_by('-creation') return t.order_by('-creation')
def get_active_tests(): def get_active_tests():
t = OpenBench.models.Test.objects.filter(approved=True) t = Test.objects.filter(approved=True)
t = t.exclude(awaiting=True) t = t.exclude(awaiting=True)
t = t.exclude(finished=True) t = t.exclude(finished=True)
t = t.exclude(deleted=True) t = t.exclude(deleted=True)
return t.order_by('-priority', '-currentllr') return t.order_by('-priority', '-currentllr')
def get_completed_tests(): def get_completed_tests():
t = OpenBench.models.Test.objects.filter(finished=True) t = Test.objects.filter(finished=True)
t = t.exclude(deleted=True) t = t.exclude(deleted=True)
return t.order_by('-updated') return t.order_by('-updated')
def get_awaiting_tests(): def get_awaiting_tests():
t = OpenBench.models.Test.objects.filter(awaiting=True) t = Test.objects.filter(awaiting=True)
t = t.exclude(finished=True) t = t.exclude(finished=True)
t = t.exclude(deleted=True) t = t.exclude(deleted=True)
return t.order_by('-creation') return t.order_by('-creation')
@@ -104,7 +115,7 @@ def get_awaiting_tests():
def getRecentMachines(minutes=5): def getRecentMachines(minutes=5):
target = datetime.datetime.utcnow() target = datetime.datetime.utcnow()
target = target.replace(tzinfo=django.utils.timezone.utc) target = target.replace(tzinfo=timezone.utc)
target = target - datetime.timedelta(minutes=minutes) target = target - datetime.timedelta(minutes=minutes)
return Machine.objects.filter(updated__gte=target) return Machine.objects.filter(updated__gte=target)
@@ -313,7 +324,7 @@ def verify_test_creation(request):
except: errors.append('"{0}" needs to be at least 1 for {1}'.format(option, field_name)) except: errors.append('"{0}" needs to be at least 1 for {1}'.format(option, field_name))
def verify_configuration(field, field_name, parent): def verify_configuration(field, field_name, parent):
try: assert request.POST[field] in OpenBench.config.OPENBENCH_CONFIG[parent].keys() try: assert request.POST[field] in OPENBENCH_CONFIG[parent].keys()
except: errors.append('{0} was not found in the configuration'.format(field_name)) except: errors.append('{0} was not found in the configuration'.format(field_name))
def verify_time_control(field, field_name): def verify_time_control(field, field_name):
@@ -337,11 +348,11 @@ def verify_test_creation(request):
try: assert re.match(pattern, request.POST[field]) try: assert re.match(pattern, request.POST[field])
except: errors.append('Sources must be found on https://github.com/<User>/<Repo>') except: errors.append('Sources must be found on https://github.com/<User>/<Repo>')
def verify_network(field, fieldName): def verify_network(field, field_name, engine_field):
try: try:
if request.POST[field] == '': return if request.POST[field] == '': return
Network.objects.get(sha256=request.POST[field]) Network.objects.get(engine=request.POST[engine_field], sha256=request.POST[field])
except: errors.append('Unknown Network Provided for {0}'.format(fieldName)) except: errors.append('Unknown Network Provided for {0}'.format(field_name))
def verify_test_mode(field): def verify_test_mode(field):
try: assert request.POST[field] in ['SPRT', 'GAMES'] try: assert request.POST[field] in ['SPRT', 'GAMES']
@@ -380,7 +391,7 @@ def verify_test_creation(request):
# Verify everything about the Dev Engine # Verify everything about the Dev Engine
(verify_configuration, 'dev_engine', 'Dev Engine', 'engines'), (verify_configuration, 'dev_engine', 'Dev Engine', 'engines'),
(verify_github_repo , 'dev_repo'), (verify_github_repo , 'dev_repo'),
(verify_network , 'dev_network', 'Dev Network'), (verify_network , 'dev_network', 'Dev Network', 'dev_engine'),
(verify_options , 'dev_options', 'Threads', 'Dev Options'), (verify_options , 'dev_options', 'Threads', 'Dev Options'),
(verify_options , 'dev_options', 'Hash', 'Dev Options'), (verify_options , 'dev_options', 'Hash', 'Dev Options'),
(verify_time_control , 'dev_time_control', 'Dev Time Control'), (verify_time_control , 'dev_time_control', 'Dev Time Control'),
@@ -388,7 +399,7 @@ def verify_test_creation(request):
# Verify everything about the Base Engine # Verify everything about the Base Engine
(verify_configuration, 'base_engine', 'Base Engine', 'engines'), (verify_configuration, 'base_engine', 'Base Engine', 'engines'),
(verify_github_repo , 'base_repo'), (verify_github_repo , 'base_repo'),
(verify_network , 'base_network', 'Base Network'), (verify_network , 'base_network', 'Base Network', 'base_engine'),
(verify_options , 'base_options', 'Threads', 'Base Options'), (verify_options , 'base_options', 'Threads', 'Base Options'),
(verify_options , 'base_options', 'Hash', 'Base Options'), (verify_options , 'base_options', 'Hash', 'Base Options'),
(verify_time_control , 'base_time_control', 'Base Time Control'), (verify_time_control , 'base_time_control', 'Base Time Control'),
@@ -474,10 +485,10 @@ def create_new_test(request):
test.max_games = int(request.POST['test_max_games']) test.max_games = int(request.POST['test_max_games'])
if test.dev_network: if test.dev_network:
test.dev_netname = Network.objects.get(sha256=test.dev_network ).name test.dev_netname = Network.objects.get(engine=test.dev_engine, sha256=test.dev_network).name
if test.base_network: if test.base_network:
test.base_netname = Network.objects.get(sha256=test.base_network).name test.base_netname = Network.objects.get(engine=test.base_engine, sha256=test.base_network).name
test.save() test.save()
@@ -525,6 +536,94 @@ def get_workload(machine):
return { 'workload' : workload_to_dictionary(test, result) } return { 'workload' : workload_to_dictionary(test, result) }
# Purely Helper functions for Networks views
def network_disambiguate(engine, identifier):
candidates = Network.objects.filter(engine=engine)
# Identifier actually refers to the Network name
if (network := candidates.filter(name=identifier).first()):
return network
# Identifier actually refers to the Network SHA
if (network := candidates.filter(sha256=identifier).first()):
return network
# No Network exists with engine this Name or Sha
return None
def network_upload(request, engine, name):
# Extract and process the Network file to produce a SHA
netfile = request.FILES['netfile']
sha256 = hashlib.sha256(netfile.file.read()).hexdigest()[:8].upper()
# Rejecct Networks with strange characters
if not re.match(r'^[a-zA-Z0-9_.-]+$', name):
return redirect(request, '/networks/', error='Valid characters are [a-zA-Z0-9_.-]')
# Don't allow duplicate uploads for the same engine
if Network.objects.filter(engine=engine, sha256=sha256):
return redirect(request, '/networks/', error='Network with that hash already exists for that engine')
# Don't allow duplicate uploads for the same engine
if Network.objects.filter(engine=engine, name=name):
return redirect(request, '/networks/', error='Network with that name already exists for that engine')
# Filter out anyone who has used an unknown engine
if engine not in OPENBENCH_CONFIG['engines'].keys():
return redirect(request, '/networks/', error='No Engine found with matching name')
# Save the file locally into /Media/ if we don't already have this file
if not Network.objects.filter(sha256=sha256):
FileSystemStorage().save('%s' % (sha256), netfile)
# Create the Network object mapping to the saved local file
Network.objects.create(
sha256=sha256, name=name,
engine=engine, author=request.user.username)
# Redirect to Engine specific view, to add clarity
return redirect(request, '/networks/%s/' % (engine), status='Uploaded %s for %s' % (name, engine))
def network_default(request, engine, network):
# Update default to False for all Networks, except this one
Network.objects.filter(engine=engine).update(default=False)
network.default = True; network.save()
# Report this, and refer to the Engine specific view
status = 'Set %s as default for %s' % (network.name, network.engine)
return redirect(request, '/networks/%s/' % (network.engine), status=status)
def network_delete(request, engine, network):
# Save information before deleting the Network Model
status = 'Deleted %s for %s' % (network.name, network.engine)
sha256 = network.sha256; network.delete()
# Only delete the actual file if no other engines use it
if not Network.objects.filter(sha256=sha256):
FileSystemStorage().delete(sha256)
# Report this, and refer to the Engine specific view
return redirect(request, '/networks/%s/' % (engine), status=status)
def network_download(request, engine, network):
# Craft the download HTML response
netfile = os.path.join(MEDIA_ROOT, network.sha256)
fwrapper = FileWrapper(open(netfile, 'rb'), 8192)
response = FileResponse(fwrapper, content_type='application/octet-stream')
# Set all headers and return response
response['Expires'] = (datetime.datetime.utcnow() + datetime.timedelta(days=7)).ctime()
response['Content-Length'] = os.path.getsize(netfile)
response['Content-Disposition'] = 'attachment; filename=' + network.sha256
return response
# Purely Helper functions for get_workload() # Purely Helper functions for get_workload()
def get_valid_workloads(machine): def get_valid_workloads(machine):
@@ -587,7 +686,7 @@ def select_workload(machine, tests, variance=0.25):
# therefore we may have this machine repeat its existing workload again # 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()]) 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: if min(ratios) / ideal_ratio > 1 - variance:
return OpenBench.models.Test.objects.get(id=machine.workload) return Test.objects.get(id=machine.workload)
# Fallback to simply doing the least attention given test # Fallback to simply doing the least attention given test
return tests[random.choice(lowest_idxs)] return tests[random.choice(lowest_idxs)]
@@ -673,7 +772,7 @@ def update_test(request, machine):
# Compute a new LLR for the updated results # Compute a new LLR for the updated results
WLD = (swins, slosses, sdraws) WLD = (swins, slosses, sdraws)
sprt = OpenBench.stats.SPRT(*WLD, test.elolower, test.eloupper) sprt = SPRT(*WLD, test.elolower, test.eloupper)
# Check for H0 or H1 being accepted # Check for H0 or H1 being accepted
passed = sprt > test.upperllr passed = sprt > test.upperllr
+46 -95
View File
@@ -33,9 +33,8 @@ from OpenBench.models import *
from django.contrib.auth.models import User from django.contrib.auth.models import User
from OpenSite.settings import MEDIA_ROOT from OpenSite.settings import MEDIA_ROOT
from wsgiref.util import FileWrapper
from django.db.models import F from django.db.models import F
from django.http import HttpResponse, FileResponse, JsonResponse from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt from django.views.decorators.csrf import csrf_exempt
from django.core.files.storage import FileSystemStorage from django.core.files.storage import FileSystemStorage
from django.core.files.base import ContentFile from django.core.files.base import ContentFile
@@ -438,103 +437,55 @@ def create_test(request):
# NETWORK MANAGEMENT VIEWS # # NETWORK MANAGEMENT VIEWS #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def networks(request, target=None, sha256=None, client=False): def networks(request, engine=None, action=None, name=None, client=False):
# *** GET Requests: # Without an identifier and a valid action, all we can do is view the list
# [1] Fetch a view of all the Networks on the framework (/networks/) if not name or action.upper() not in ['UPLOAD', 'DEFAULT', 'DELETE', 'DOWNLOAD']:
# [2] Fetch a view of all Networks for a given engine (/networks/<engine>/)
# [3] Download the contents of a Network if allowed (/networks/download/<sha256>/)
#
# *** POST Requests:
# [1] Upload a Network to the framework (/networks/upload/)
# [2] Set as default a Network on the framework (/networks/default/<sha256>/)
# [3] Delete a Network from the framework (/networks/delete/<sha256>/)
#
# *** Rights:
# Any user may look at the list of Networks, for all or some engines
# Only authenticated and approved Users may interact in the remaining ways
if not target or target.upper() not in ['UPLOAD', 'DEFAULT', 'DELETE', 'DOWNLOAD']:
networks = Network.objects.all() networks = Network.objects.all()
if target: networks = networks.filter(engine=target) if engine and engine in OPENBENCH_CONFIG['engines'].keys():
return render(request, 'networks.html', { 'networks' : networks.order_by('-id') }) networks = networks.filter(engine=engine)
return render(request, 'networks.html', { 'networks' : list(networks.order_by('-id').values()) })
# Require logins. Clients will be artifically logged in
if not request.user.is_authenticated: if not request.user.is_authenticated:
return django.http.HttpResponseRedirect('/login/') return django.http.HttpResponseRedirect('/login/')
# Require approver credentials, unless downloading as a client
if not client and not Profile.objects.get(user=request.user).approver: if not client and not Profile.objects.get(user=request.user).approver:
return django.http.HttpResponseRedirect('/index/') return django.http.HttpResponseRedirect('/index/')
if target.upper() == 'UPLOAD': # Split out Uploads, since there is no logic to disambiguate the name
if action.upper() == 'UPLOAD':
return OpenBench.utils.network_upload(request, engine, name)
# Push off all the actual effort to OpenBench.utils for all actions
actions = {
'DEFAULT' : OpenBench.utils.network_default,
'DELETE' : OpenBench.utils.network_delete,
'DOWNLOAD' : OpenBench.utils.network_download,
}
# Update the Network, if we can find one for the given name/sha256
if (network := OpenBench.utils.network_disambiguate(engine, name)):
return actions[action.upper()](request, engine, network)
# Otherwise we could not find the Network, and cannot do anything
return redirect(request, '/networks/', error='No network found with matching Sha')
def network_form(request):
# Require logins. Clients will be artifically logged in
if not request.user.is_authenticated:
return django.http.HttpResponseRedirect('/login/')
# Require approver credentials, unless downloading as a client
if not Profile.objects.get(user=request.user).approver:
return django.http.HttpResponseRedirect('/index/')
# Get requests should not be reaching this point
if request.method == 'GET': if request.method == 'GET':
return render(request, 'uploadnet.html', {}) return render(request, 'uploadnet.html', {})
name = request.POST['name']
engine = request.POST['engine']
netfile = request.FILES['netfile']
sha256 = hashlib.sha256(netfile.file.read()).hexdigest()[:8].upper()
if not re.match(r'^[a-zA-Z0-9_.-]+$', name):
return redirect(request, '/uploadnet/', error='Valid characters are [a-zA-Z0-9_.-]')
if Network.objects.filter(sha256=sha256):
return redirect(request, '/uploadnet/', error='Network with that hash already exists')
if Network.objects.filter(engine=engine, name=name):
return redirect(request, '/uploadnet/', error='Network with that name already exists for that engine')
if engine not in OPENBENCH_CONFIG['engines'].keys():
return redirect(request, '/uploadnet/', error='No Engine found with matching name')
FileSystemStorage().save(sha256, netfile)
Network.objects.create(
sha256=sha256, name=name,
engine=engine, author=request.user.username)
return redirect(request, '/networks/', status='Uploaded %s for %s' % (engine, name))
if target.upper() == 'DEFAULT':
if not Network.objects.filter(sha256=sha256):
return redirect(request, '/networks/', error='No network found with matching Sha')
network = Network.objects.get(sha256=sha256)
Network.objects.filter(engine=network.engine).update(default=False)
network.default = True; network.save()
status = 'Set %s as default for %s' % (network.name, network.engine)
return redirect(request, '/networks/', status=status)
if target.upper() == 'DELETE':
if not Network.objects.filter(sha256=sha256):
return redirect(request, '/networks/', error='No network found with matching Sha')
network = Network.objects.get(sha256=sha256)
status = 'Deleted %s for %s' % (network.name, network.engine)
network.delete()
FileSystemStorage().delete(sha256)
return redirect(request, '/networks/', status=status)
if target.upper() == 'DOWNLOAD':
if not Network.objects.filter(sha256=sha256):
return redirect(request, '/networks/', error='No network found with matching Sha')
netfile = os.path.join(MEDIA_ROOT, sha256)
fwrapper = FileWrapper(open(netfile, 'rb'), 8192)
response = FileResponse(fwrapper, content_type='application/octet-stream')
response['Expires'] = (datetime.datetime.utcnow() + datetime.timedelta(days=7)).ctime()
response['Content-Length'] = os.path.getsize(netfile)
response['Content-Disposition'] = 'attachment; filename=' + sha256
return response
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# OPENBENCH SCRIPTING # # OPENBENCH SCRIPTING #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
@@ -544,8 +495,13 @@ def scripts(request):
login(request) # All requests are attached to a User login(request) # All requests are attached to a User
if request.POST['action'] == 'UPLOAD': if request.POST['action'] == 'UPLOAD_NETWORK':
return networks(request, target='UPLOAD') engine = request.POST['engine']
name = request.POST['name']
import sys
sys.stdout.write(engine + ' ' + name + '\n')
sys.stdout.flush()
return networks(request, engine, 'upload', name)
if request.POST['action'] == 'CREATE_TEST': if request.POST['action'] == 'CREATE_TEST':
return newTest(request) return newTest(request)
@@ -654,19 +610,14 @@ def client_get_workload(request):
return JsonResponse(OpenBench.utils.get_workload(machine)) return JsonResponse(OpenBench.utils.get_workload(machine))
@csrf_exempt @csrf_exempt
def client_get_network(request, identifier, engine=None): def client_get_network(request, engine, name):
# Verify the User's credentials # Verify the User's credentials
try: django.contrib.auth.login(request, authenticate(request, True)) try: django.contrib.auth.login(request, authenticate(request, True))
except UnableToAuthenticate: return HttpResponse('Bad Credentials') except UnableToAuthenticate: return HttpResponse('Bad Credentials')
# Return the requested Neural Network, after resolving the Network name
if engine is not None:
try: identifier = Network.objects.get(name=identifier, engine=engine).sha256
except: return HttpResponse('Unable to find associated Network')
# Return the requested Neural Network file for the Client # Return the requested Neural Network file for the Client
return networks(request, target='DOWNLOAD', sha256=identifier, client=True) return networks(request, engine, 'DOWNLOAD', name, client=True)
@csrf_exempt @csrf_exempt
def client_wrong_bench(request): def client_wrong_bench(request):
-139
View File
@@ -1,139 +0,0 @@
import argparse
import hashlib
import multiprocessing
import os
import re
import requests
import subprocess
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
from bench_engine import run_benchmark
from OpenBench.config import OPENBENCH_CONFIG
USE_OLD_BINARIES = True
OPENBENCH_USERNAME = None
OPENBENCH_PASSWORD = None
OPENBENCH_SERVER = 'http://chess.grantnet.us'
BENCHMARK_THREADS = None
BENCHMARK_SETS = None
def download_network(engine, sha256):
if not os.path.isdir('Networks'):
os.mkdir('Networks')
if not os.path.isfile('Networks/%s' % (sha256)):
print ('Downloading %s for %s...' % (sha256, engine))
target = '%s/clientGetNetwork/%s/' % (OPENBENCH_SERVER, sha256)
payload = { 'username' : OPENBENCH_USERNAME, 'password' : OPENBENCH_PASSWORD }
request = requests.post(data=payload, url=target)
with open('Networks/%s' % (sha256), 'wb') as fout:
for chunk in request.iter_content(chunk_size=1024):
if chunk: fout.write(chunk)
fout.flush()
with open('Networks/%s' % (sha256), 'rb') as network:
assert sha256 == hashlib.sha256(network.read()).hexdigest()[:8].upper()
def download_default_networks():
target = '%s/networks/' % (OPENBENCH_SERVER)
information = requests.get(url=target)
pattern = r'class="fas fa-star">.*?<a href="/networks/(?P<eng>.*?)/".*?<a href="/networks/download/(?P<sha>.{8})'
default_networks = list(re.findall(pattern, information.text))
for engine, network in default_networks:
download_network(engine, network)
return { engine : network for engine, network in default_networks }
def update_repositories():
if not os.path.isdir('Repositories'):
os.mkdir('Repositories')
for engine, config in OPENBENCH_CONFIG['engines'].items():
if not os.path.isdir('Repositories/' + config['source'].split('/')[-1]):
os.system('cd Repositories && git clone %s && cd ../' % (config['source']))
if not USE_OLD_BINARIES:
os.system('cd Repositories/%s && git pull && cd ../../' % config['source'].split('/')[-1])
def build_engine(engine, config, defaults):
git_path = 'Repositories/' + config['source'].split('/')[-1]
base_path = os.path.dirname(os.path.realpath(__file__))
build_path = os.path.join(base_path, git_path, config['build']['path'])
command = 'make -j EXE=%s' % (engine)
if engine in defaults:
command += ' EVALFILE=%s' % (os.path.join(base_path, 'Networks', defaults[engine]).replace('\\', '/'))
print ('=' * 120)
print ('Attempting to build %s...' % (engine))
subprocess.Popen(command.split(), cwd=build_path).wait()
if os.path.isfile(os.path.join(build_path, engine)):
os.rename(os.path.join(build_path, engine), os.path.join('Binaries', engine))
print ('Succesfully built %s' % (engine))
if os.path.isfile(os.path.join(build_path, engine + '.exe')):
os.rename(os.path.join(build_path, engine + '.exe'), os.path.join('Binaries', engine))
print ('Succesfully built %s' % (engine))
print ('=' * 120)
print ()
def build_all_engines():
update_repositories()
defaults = download_default_networks()
if not os.path.isdir('Binaries'):
os.mkdir('Binaries')
for engine, config in OPENBENCH_CONFIG['engines'].items():
if USE_OLD_BINARIES and os.path.isfile('Binaries/' + engine):
continue
build_engine(engine, config, defaults)
def bench_built_engines():
for engine in sorted(os.listdir('Binaries')):
nps = run_benchmark('./Binaries/%s' % (engine), BENCHMARK_THREADS, BENCHMARK_SETS)
print ('%-15s | %d' % (engine, nps))
if __name__ == '__main__':
req_user = required=('OPENBENCH_USERNAME' not in os.environ)
req_pass = required=('OPENBENCH_PASSWORD' not in os.environ)
help_user = 'Username. May also be passed as OPENBENCH_USERNAME environment variable'
help_pass = 'Password. May also be passed as OPENBENCH_PASSWORD environment variable'
p = argparse.ArgumentParser()
p.add_argument('-U', '--username', help=help_user, required=req_user)
p.add_argument('-P', '--password', help=help_pass, required=req_pass)
p.add_argument('-T', '--threads' , help='Concurrent Benchmarks', required=True)
p.add_argument('-S', '--sets' , help='Benchmark Sample Count', required=True)
p.add_argument('-R', '--rebuild' , help='Rebuild Binaries', action='store_true')
arguments = p.parse_args()
USE_OLD_BINARIES = not arguments.rebuild
OPENBENCH_USERNAME = arguments.username
OPENBENCH_PASSWORD = arguments.password
BENCHMARK_THREADS = int(arguments.threads)
BENCHMARK_SETS = int(arguments.sets)
if arguments.username is None: OPENBENCH_USERNAME = os.environ['OPENBENCH_USERNAME']
if arguments.password is None: OPENBENCH_PASSWORD = os.environ['OPENBENCH_PASSWORD']
build_all_engines()
bench_built_engines()
+41 -12
View File
@@ -1,3 +1,25 @@
#!/bin/python3
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# OpenBench is a chess engine testing framework by Andrew Grant. #
# <https://github.com/AndyGrant/OpenBench> <andrew@grantnet.us> #
# #
# OpenBench is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# OpenBench is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
import argparse import argparse
import multiprocessing import multiprocessing
import re import re
@@ -27,52 +49,59 @@ def parse_stream_output(stream):
# Parse out the integer portion from our matches # Parse out the integer portion from our matches
nps = int(re.search(r'\d+', nps ).group()) if nps else None nps = int(re.search(r'\d+', nps ).group()) if nps else None
bench = int(re.search(r'\d+', bench).group()) if bench else None bench = int(re.search(r'\d+', bench).group()) if bench else None
return (bench, nps) return (bench, nps)
def single_core_bench(engine, outqueue): def single_core_bench(engine, network, outqueue):
# Basic command for Public engines
cmd = ['./' + engine, 'bench']
# Adjust to handle setting Networks in Private engines
if network:
option = 'setoption name EvalFile value %s' % (network)
cmd = ['./%s' % (engine), option, 'bench', 'quit']
# Launch the bench and wait for results # Launch the bench and wait for results
stdout, stderr = subprocess.Popen( stdout, stderr = subprocess.Popen(
'./{0} bench'.format(engine).split(), cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate() ).communicate()
outqueue.put(parse_stream_output(stdout)) outqueue.put(parse_stream_output(stdout))
def multi_core_bench(engine, threads): def multi_core_bench(engine, network, threads):
outqueue = multiprocessing.Queue() outqueue = multiprocessing.Queue()
processes = [ processes = [
multiprocessing.Process( multiprocessing.Process(
target=single_core_bench, target=single_core_bench,
args=(engine, outqueue) args=(engine, network, outqueue)
) for ii in range(threads) ) for ii in range(threads)
] ]
for process in processes: process.start() for process in processes: process.start()
return [outqueue.get() for ii in range(threads)] return [outqueue.get() for ii in range(threads)]
def run_benchmark(engine, threads, sets): def run_benchmark(engine, network, threads, sets):
benches, speeds = [], [] benches, speeds = [], []
for ii in range(sets): for ii in range(sets):
for bench, speed in multi_core_bench(engine, threads): for bench, speed in multi_core_bench(engine, network, threads):
benches.append(bench); speeds.append(speed) benches.append(bench); speeds.append(speed)
if len(set(benches)) != 1: if len(set(benches)) != 1:
print("Error: Non-Deterministic Results!") print("Error: Non-Deterministic Results!")
sys.exit() return (0, 0)
return int(sum(speeds) / len(speeds)) return int(sum(speeds) / len(speeds)), benches[0]
if __name__ == '__main__': if __name__ == '__main__':
p = argparse.ArgumentParser() p = argparse.ArgumentParser()
p.add_argument('-E', '--engine' , help='Binary Name', required=True) p.add_argument('-E', '--engine' , help='Binary Name', required=True)
p.add_argument('-N', '--network' , help='Networks for Private Engines', required=False)
p.add_argument('-T', '--threads' , help='Concurrent Benchmarks', required=True) p.add_argument('-T', '--threads' , help='Concurrent Benchmarks', required=True)
p.add_argument('-S', '--sets' , help='Benchmark Sample Count', required=True) p.add_argument('-S', '--sets' , help='Benchmark Sample Count', required=True)
args = p.parse_args() args = p.parse_args()
print (run_benchmark(args.engine, int(args.threads), int(args.sets))) print (run_benchmark(args.engine, args.network, int(args.threads), int(args.sets)))
+46 -21
View File
@@ -1,46 +1,71 @@
#!/usr/bin/python3 #!/bin/python3
import argparse, hashlib, os, requests # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# OpenBench is a chess engine testing framework by Andrew Grant. #
# <https://github.com/AndyGrant/OpenBench> <andrew@grantnet.us> #
# #
# OpenBench is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# OpenBench is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
OPENBENCH_SERVER = 'http://chess.grantnet.us' import argparse
import hashlib
import os
import requests
def download_network(username, password, sha256): def url_join(*args):
# Join a set of URL paths while maintaining the correct format
return '/'.join([f.lstrip('/').rstrip('/') for f in args]) + '/'
print ('Downloading %s...' % (sha256)) def download_network(username, password, server, engine, name):
# Check if we already have the Network file by looking at SHA256 print ('Downloading %s for %s...' % (name, engine))
if os.path.isfile(sha256):
with open(sha256, 'rb') as network:
if sha256 == hashlib.sha256(network.read()).hexdigest()[:8].upper():
return
target = '%s/clientGetNetwork/%s/' % (OPENBENCH_SERVER, sha256) target = url_join(server, 'clientGetNetwork', engine, name)
payload = { 'username' : username, 'password' : password } payload = { 'username' : username, 'password' : password }
request = requests.post(data=payload, url=target) request = requests.post(data=payload, url=target)
with open(sha256, 'wb') as fout: with open(name, 'wb') as fout:
for chunk in request.iter_content(chunk_size=1024): for chunk in request.iter_content(chunk_size=1024):
if chunk: fout.write(chunk) if chunk: fout.write(chunk)
fout.flush() fout.flush()
with open(sha256, 'rb') as network:
if sha256 != hashlib.sha256(network.read()).hexdigest()[:8].upper():
print ('Failed to Download...')
if __name__ == '__main__': if __name__ == '__main__':
# We can use ENV variables for Username, Password, and Server
req_user = required=('OPENBENCH_USERNAME' not in os.environ) req_user = required=('OPENBENCH_USERNAME' not in os.environ)
req_pass = required=('OPENBENCH_PASSWORD' not in os.environ) req_pass = required=('OPENBENCH_PASSWORD' not in os.environ)
req_server = required=('OPENBENCH_SERVER' not in os.environ)
# For clarity, seperate out this help text
help_user = 'Username. May also be passed as OPENBENCH_USERNAME environment variable' help_user = 'Username. May also be passed as OPENBENCH_USERNAME environment variable'
help_pass = 'Password. May also be passed as OPENBENCH_PASSWORD environment variable' help_pass = 'Password. May also be passed as OPENBENCH_PASSWORD environment variable'
help_server = ' Server. May also be passed as OPENBENCH_SERVER environment variable'
# Parse all arguments, all of which must exist in some form
p = argparse.ArgumentParser() p = argparse.ArgumentParser()
p.add_argument('-U', '--username', help=help_user , required=req_user ) p.add_argument('-U', '--username', help=help_user , required=req_user )
p.add_argument('-P', '--password', help=help_pass , required=req_pass ) p.add_argument('-P', '--password', help=help_pass , required=req_pass )
p.add_argument('-N', '--network', help='Network SHA256', required=True) p.add_argument('-S', '--server' , help=help_server , required=req_server)
arguments = p.parse_args() p.add_argument('-E', '--engine' , help='Engine' , required=True )
p.add_argument('-N', '--network' , help='Name or Sha', required=True )
args = p.parse_args()
if arguments.username is None: arguments.username = os.environ['OPENBENCH_USERNAME'] # Fallback on ENV variables for Username, Password, and Server
if arguments.password is None: arguments.password = os.environ['OPENBENCH_PASSWORD'] args.username = args.username if args.username else os.environ['OPENBENCH_USERNAME']
args.password = args.password if args.password else os.environ['OPENBENCH_PASSWORD']
args.server = args.server if args.server else os.environ['OPENBENCH_SERVER' ]
download_network(arguments.username, arguments.password, arguments.network) download_network(args.username, args.password, args.server, args.engine, args.network)
+80 -10
View File
@@ -1,17 +1,87 @@
#!/bin/python3
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# OpenBench is a chess engine testing framework by Andrew Grant. #
# <https://github.com/AndyGrant/OpenBench> <andrew@grantnet.us> #
# #
# OpenBench is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# OpenBench is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
import argparse
import os
import re
import requests import requests
URL = 'http://chess.grantnet.us/scripts/' def url_join(*args):
FILENAME = '' # Join a set of URL paths while maintaining the correct format
return '/'.join([f.lstrip('/').rstrip('/') for f in args]) + '/'
def upload_network():
# We can use ENV variables for Username, Password, and Server
req_user = required=('OPENBENCH_USERNAME' not in os.environ)
req_pass = required=('OPENBENCH_PASSWORD' not in os.environ)
req_server = required=('OPENBENCH_SERVER' not in os.environ)
# For clarity, seperate out this help text
help_user = 'Username. May also be passed as OPENBENCH_USERNAME environment variable'
help_pass = 'Password. May also be passed as OPENBENCH_PASSWORD environment variable'
help_server = ' Server. May also be passed as OPENBENCH_SERVER environment variable'
# Parse all arguments, all of which must exist in some form
p = argparse.ArgumentParser()
p.add_argument('-U', '--username', help=help_user , required=req_user )
p.add_argument('-P', '--password', help=help_pass , required=req_pass )
p.add_argument('-S', '--server' , help=help_server , required=req_server)
p.add_argument('-E', '--engine' , help='Engine' , required=True )
p.add_argument('-N', '--name' , help='Network Name', required=True )
p.add_argument('-F', '--file' , help='File Name' , required=True )
args = p.parse_args()
# Fallback on ENV variables for Username, Password, and Server
args.username = args.username if args.username else os.environ['OPENBENCH_USERNAME']
args.password = args.password if args.password else os.environ['OPENBENCH_PASSWORD']
args.server = args.server if args.server else os.environ['OPENBENCH_SERVER' ]
# All scripts connect through this API point, with an action in the POST data
url = url_join(args.server, 'scripts')
# POST payload must contain an action value
data = { data = {
'engine' : '', 'username' : args.username,
'name' : '', 'password' : args.password,
'username' : '', 'engine' : args.engine,
'password' : '', 'name' : args.name,
'action' : 'UPLOAD', 'action' : 'UPLOAD_NETWORK',
} }
with open(FILENAME, 'rb') as file: # Upload the file and report the status code
r = requests.post(URL, data=data, files={'netfile' : file}) with open(args.file, 'rb') as network:
r = requests.post(url, data=data, files={ 'netfile' : network })
print ('Code : %s' % (r.status_code))
print(r.text) # Report any error messages
pattern = r'<div class="error-message">\s*<pre>(.*?)</pre>\s*</div>'
if matches := re.findall(pattern, r.text, re.DOTALL):
print ('Error : %s' % (matches[0].strip()))
# Report any status messages
pattern = r'<div class="status-message">\s*<pre>(.*?)</pre>\s*</div>'
if matches := re.findall(pattern, r.text, re.DOTALL):
print ('Status: %s' % (matches[0].strip()))
if __name__ == '__main__':
upload_network()
+1 -1
View File
@@ -70,7 +70,7 @@
<ul> <ul>
<li class="header">Actions</li> <li class="header">Actions</li>
<li><a href="/newTest"><i class="fa-solid fa-plus fa-fw"></i> Create Test</a></li> <li><a href="/newTest"><i class="fa-solid fa-plus fa-fw"></i> Create Test</a></li>
<li><a href="/networks/upload"><i class="fa-solid fa-upload fa-fw"></i> Upload Net</a></li> <li><a href="/newNetwork"><i class="fa-solid fa-upload fa-fw"></i> Upload Net</a></li>
</ul> </ul>
<hr> <hr>
+27 -61
View File
@@ -1,59 +1,22 @@
{% extends "OpenBench/base.html" %} {% extends "OpenBench/base.html" %}
{% block style %} {% load static %}
{% endblock %}
{% block scripts %} {% block scripts %}
{{ networks|json_script:"json-networks" }}
<script src="{% static 'networks.js' %}"></script>
<script> <script>
document.addEventListener(
var Networks = [ 'DOMContentLoaded', function () {
{% for network in networks %} sort_networks("name");
{ sort_networks("engine");
'default' : "{{network.default}}", sort_networks("default");
'engine' : "{{network.engine}}", }, false
'author' : "{{network.author|capfirst}}", );
'name' : "{{network.name}}", </script>
'hash' : "{{network.sha256}}",
},
{% endfor %}
];
var Network_Sorting;
function swap_networks(index1, index2) {
var temp = Networks[index1];
Networks[index1] = Networks[index2];
Networks[index2] = temp;
var table = document.getElementById("network-table");
var temp_row = table.rows[index1+1].innerHTML
table.rows[index1+1].innerHTML = table.rows[index2+1].innerHTML;
table.rows[index2+1].innerHTML = temp_row;
}
function invert_networks() {
for (let i = 0; Networks.length > i * 2; i++)
swap_networks(i, Networks.length-i-1);
}
function sort_networks(field) {
if (Network_Sorting == field)
return invert_networks();
for (let i = 0; i != Networks.length; i++)
for (let j = i + 1; j != Networks.length; j++)
if (Networks[j][field] > Networks[i][field])
swap_networks(i, j);
Network_Sorting = field;
};
document.addEventListener('DOMContentLoaded', function () { sort_networks("default"); }, false);
</scrpipt>
{% endblock %} {% endblock %}
@@ -62,31 +25,34 @@
<table id="network-table" class="hoverable"> <table id="network-table" class="hoverable">
<tr class="table-header"> <tr class="table-header">
<th onclick=sort_networks("default")></th> <th class="cursor" onclick="sort_networks('default')"></th>
<th onclick=sort_networks("engine")>Engine</th> <th class="cursor" onclick="sort_networks('engine')">Engine</th>
<th onclick=sort_networks("author")>Uploader</th> <th class="cursor" onclick="sort_networks('author')">Author</th>
<th onclick=sort_networks("name")>Name</th> <th class="cursor" onclick="sort_networks('name')">Name</th>
<th onclick=sort_networks("hash")>Hash</th> <th class="cursor" onclick="sort_networks('sha256')")>Hash</th>
<th></th> <th></th>
</tr> </tr>
{% for network in networks %} {% for network in networks %}
<tr> <tr>
{% if network.default %} {% if network.default %}
<td><i class="fas fa-star" aria-hidden="true"></i></td> <td><i class="fas fa-star" aria-hidden="true"></i></td>
{% else %} {% else %}
<td><a class="unstarred" href="/networks/default/{{network.sha256}}"> <td><a class="unstarred" href="/networks/{{network.engine}}/default/{{network.sha256}}">
<i class="far fa-star" aria-hidden="true"></i></a></td> <i class="far fa-star" aria-hidden="true"></i></a></td>
{% endif %} {% endif %}
<td><a href="/networks/{{network.engine}}/">{{network.engine}}</a></td> <td><a href="/networks/{{network.engine}}/">{{network.engine}}</a></td>
<td><a href="/user/{{network.author}}">{{network.author|capfirst}}</a></td> <td>{{network.author|capfirst}}</td>
<td><a href="/networks/download/{{network.sha256}}">{{network.name}}</a></td> <td><a href="/networks/{{network.engine}}/download/{{network.sha256}}">{{network.name}}</a></td>
<td>{{network.sha256}}</td> <td>{{network.sha256}}</td>
<td><a class="redlink" onclick="return confirm('YOU ARE DELETING THIS NETWORK FILE FOREVER')" href="/networks/delete/{{network.sha256}}"> <td>
<i class="fas fa-minus-circle"></i></a></td> <a class="redlink"
onclick="return confirm('YOU ARE DELETING THIS NETWORK FILE FOREVER')"
href="/networks/{{network.engine}}/delete/{{network.sha256}}">
<i class="fas fa-minus-circle"></i></a>
</td>
</tr> </tr>
{% endfor %} {% endfor %}
+30 -10
View File
@@ -1,21 +1,47 @@
{% extends "OpenBench/base.html" %} {% extends "OpenBench/base.html" %}
{% block scripts %}
<script>
document.addEventListener(
'DOMContentLoaded', function () {
var form = document.getElementById("network-form");
form.addEventListener("submit", function(event) {
event.preventDefault(); // Stop event from hitting the wrong URL
// Adjust the Form endpoint based on Network Name and Engine
var network_name = encodeURIComponent(document.getElementById("network-name").value);
var engine_name = encodeURIComponent(document.getElementById("network-engine").value);
// OpenBench Endpoint: networks/engine/upload/name/
form.action = '/networks/' + engine_name + '/upload/' + network_name + '/'
form.submit()
});
}, false
);
</script>
{% endblock %}
{% block content %} {% block content %}
<form method="post" enctype="multipart/form-data"> <form method="post" enctype="multipart/form-data" id="network-form">
{% csrf_token %} {% csrf_token %}
<div class="form"> <div class="form">
<div class="col"> <div class="col">
<div class="row"> <div class="row">
<label>Name</label><input name="name"> <label>Name</label><input id="network-name" name="name">
</div> </div>
<div class="row"> <div class="row">
<label>Weights</label><input name="netfile" type="file"> <label>Weights</label><input name="netfile" type="file">
</div> </div>
<div class="row"> <div class="row">
<label>Engine</label> <label>Engine</label>
<select id="engine" name="engine"> <select id="network-engine" name="engine">
{% for engine in config.engines %} {% for engine in config.engines %}
{% if engine == profile.engine %} {% if engine == profile.engine %}
<option selected value="{{ engine }}">{{ engine }}</option> <option selected value="{{ engine }}">{{ engine }}</option>
@@ -25,15 +51,9 @@
{% endfor %} {% endfor %}
</select> </select>
</div> </div>
<input type="submit" class="anchorbutton btn-blue w-100" value="Upload"> <input type="submit" class="anchorbutton btn-blue w-100" value="Upload">
</div> </div>
</div> </div>
<form> <form>
{% endblock %} {% endblock %}