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
+1782 -1545

No files matched your search

+2
View File
@@ -10,4 +10,6 @@ Scripts/Binaries/*
Scripts/Networks/* Scripts/Networks/*
Scripts/Repositories/* Scripts/Repositories/*
Engines/*.json
Media/* Media/*
+42 -51
View File
@@ -44,10 +44,10 @@ from concurrent.futures import ThreadPoolExecutor
## Basic configuration of the Client. These timeouts can be changed at will ## Basic configuration of the Client. These timeouts can be changed at will
CLIENT_VERSION = 14 # Client version to send to the Server
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 = '13' # Client version to send to the Server
REPORT_INTERVAL = 30 # Seconds between reports to the Server REPORT_INTERVAL = 30 # Seconds between reports to the Server
IS_WINDOWS = platform.system() == 'Windows' # Don't touch this IS_WINDOWS = platform.system() == 'Windows' # Don't touch this
@@ -367,10 +367,22 @@ class ServerReporter:
payload['timelosses'] += batch['timelosses'] payload['timelosses'] += batch['timelosses']
payload['illegals' ] += batch['illegals' ] payload['illegals' ] += batch['illegals' ]
if config.workload['test']['type'] == 'SPSA':
# Pairs can be added one at a time, or in bulk
result = batch['trinomial'][2] - batch['trinomial'][0]
# For each param compute the update step for the Server
for name, param in config.workload['spsa'].items():
delta = param['r'] * param['c'] * result * param['flip'][batch['cutechess_idx']]
payload['spsa_%s' % (name)] = payload.get('spsa_%s' % (name), 0.0) + delta
# Collapse into a JSON friendly format for Django # Collapse into a JSON friendly format for Django
payload['trinomial' ] = ' '.join(map(str, payload['trinomial' ])) payload['trinomial' ] = ' '.join(map(str, payload['trinomial' ]))
payload['pentanomial'] = ' '.join(map(str, payload['pentanomial'])) payload['pentanomial'] = ' '.join(map(str, payload['pentanomial']))
print (payload)
return ServerReporter.report(config, 'clientSubmitResults', payload) return ServerReporter.report(config, 'clientSubmitResults', payload)
class Cutechess: class Cutechess:
@@ -393,23 +405,11 @@ class Cutechess:
@staticmethod @staticmethod
def concurrency_settings(config): def concurrency_settings(config):
# Extract # of Threads for the dev engine # Already computed for us by the Server
dev_options = config.workload['test']['dev' ]['options'] return '-concurrency %d -games %d' % (
dev_threads = int(extract_option(dev_options, 'Threads')) config.workload['distribution']['concurrency-per'],
config.workload['distribution']['games-per-cutechess'],
# Extract # of Threads for the base engine )
base_options = config.workload['test']['base']['options']
base_threads = int(extract_option(base_options, 'Threads'))
# Number of concurrency games that this socket can play
concurrency = config.threads / config.sockets
concurrency = concurrency // max(dev_threads, base_threads)
# Play at least a single game-pair per concurrency
games = int(concurrency * config.workload['test']['workload_size'])
games = max(concurrency * 2, games - (games % (2 * concurrency)))
return '-concurrency %d -games %d' % (concurrency, games)
@staticmethod @staticmethod
def adjudication_settings(config): def adjudication_settings(config):
@@ -443,7 +443,7 @@ class Cutechess:
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, scale_factor): def engine_settings(config, command, branch, scale_factor, cutechess_idx):
# Extract configuration from the Workload # Extract configuration from the Workload
options = config.workload['test'][branch]['options'] options = config.workload['test'][branch]['options']
@@ -468,6 +468,11 @@ class Cutechess:
if syzygy != 'DISABLED' and syzygy != 'OPTIONAL': if syzygy != 'DISABLED' and syzygy != 'OPTIONAL':
options += ' SyzygyProbeLimit=%s' % (syzygy.split('-')[0]) options += ' SyzygyProbeLimit=%s' % (syzygy.split('-')[0])
# Add any of the custom SPSA settings
if config.workload['test']['type'] == 'SPSA':
for param, data in config.workload['spsa'].items():
options += ' %s=%s' % (param, str(data[branch][cutechess_idx]))
# Join options together in the Cutechess format # Join options together in the Cutechess format
options = ' option.'.join([''] + re.findall(r'"[^"]*"|\S+', options)) options = ' option.'.join([''] + re.findall(r'"[^"]*"|\S+', options))
return '-engine dir=Engines/ cmd=./%s proto=uci %s%s name=%s-%s' % (command, control, options, name, branch) return '-engine dir=Engines/ cmd=./%s proto=uci %s%s name=%s-%s' % (command, control, options, name, branch)
@@ -639,10 +644,6 @@ class ResultsReporter(object):
try: try:
# Send all of the queued Results at once # Send all of the queued Results at once
response = ServerReporter.report_results(self.config, self.pending).json() response = ServerReporter.report_results(self.config, self.pending).json()
# Log, and then clear pending queue
for result in self.pending:
print (result)
self.pending = [] self.pending = []
# If the test ended, kill all tasks # If the test ended, kill all tasks
@@ -656,9 +657,9 @@ class ResultsReporter(object):
traceback.print_exc() traceback.print_exc()
print ('[Note] Failed to upload results to server...') print ('[Note] Failed to upload results to server...')
def send_errors(self, seed): def send_errors(self, seed, cutechess_cnt):
for x in range(self.config.sockets): for x in range(cutechess_cnt):
# Reuse logic that was given to Cutechess to decide the PGN name # Reuse logic that was given to Cutechess to decide the PGN name
fname = Cutechess.pgnout_settings(self.config, seed + x).split()[1] fname = Cutechess.pgnout_settings(self.config, seed + x).split()[1]
@@ -787,17 +788,6 @@ def unzip_delete_file(source, outdir):
os.remove(source) os.remove(source)
def extract_option(options, option):
match = re.search('(?<={0}=")[^"]*'.format(option), options)
if match: return match.group()
match = re.search('(?<={0}=\')[^\']*'.format(option), options)
if match: return match.group()
match = re.search('(?<={0}=)[^ ]*'.format(option), options)
if match: return match.group()
def make_command(config, engine, src_path, network_path): def make_command(config, engine, src_path, network_path):
compiler = config.compilers[engine][0] compiler = config.compilers[engine][0]
@@ -1066,23 +1056,26 @@ def complete_workload(config):
base_engine = config.workload['test']['base']['engine'] base_engine = config.workload['test']['base']['engine']
scale_factor = base_factor if dev_engine != base_engine else avg_factor scale_factor = base_factor if dev_engine != base_engine else avg_factor
# Server knows how many copies of Cutechess we should run
cutechess_cnt = config.workload['distribution']['cutechess-count']
# 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=cutechess_cnt) as executor:
seed = time.time() seed = time.time()
results = multiprocessing.Queue() results = multiprocessing.Queue()
abort_flag = threading.Event() abort_flag = threading.Event()
tasks = [] # Create each of the Cutechess workers tasks = [] # Create each of the Cutechess workers
for x in range(config.sockets): for x in range(cutechess_cnt):
cmd = build_cutechess_command(config, dev_name, base_name, scale_factor, seed + x) cmd = build_cutechess_command(config, dev_name, base_name, scale_factor, seed + x, x)
tasks.append(executor.submit(run_and_parse_cutechess, config, cmd, x, results, abort_flag)) tasks.append(executor.submit(run_and_parse_cutechess, config, cmd, x, results, abort_flag))
# Process the Queue until we exit, finish, or are told to stop by the server # Process the Queue until we exit, finish, or are told to stop by the server
try: try:
rr = ResultsReporter(config, tasks, results, abort_flag) rr = ResultsReporter(config, tasks, results, abort_flag)
rr.process_until_finished() rr.process_until_finished()
rr.send_errors(seed) rr.send_errors(seed, cutechess_cnt)
Cutechess.kill_everything(dev_name, base_name) Cutechess.kill_everything(dev_name, base_name)
# Kill everything during an Exception, but print it # Kill everything during an Exception, but print it
@@ -1281,21 +1274,21 @@ 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, scale_factor, seed): def build_cutechess_command(config, dev_cmd, base_cmd, scale_factor, seed, cutechess_idx):
flags = ' ' + Cutechess.basic_settings(config, seed) flags = ' ' + Cutechess.basic_settings(config, seed)
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', scale_factor) flags += ' ' + Cutechess.engine_settings(config, dev_cmd, 'dev', scale_factor, cutechess_idx)
flags += ' ' + Cutechess.engine_settings(config, base_cmd, 'base', scale_factor) flags += ' ' + Cutechess.engine_settings(config, base_cmd, 'base', scale_factor, cutechess_idx)
flags += ' ' + Cutechess.book_settings(config) flags += ' ' + Cutechess.book_settings(config)
flags += ' ' + Cutechess.pgnout_settings(config, seed) flags += ' ' + Cutechess.pgnout_settings(config, seed)
return ['cutechess-ob.exe', './cutechess-ob'][IS_LINUX] + flags return ['cutechess-ob.exe', './cutechess-ob'][IS_LINUX] + flags
def run_and_parse_cutechess(config, command, socket, results_queue, abort_flag): def run_and_parse_cutechess(config, command, cutechess_idx, results_queue, abort_flag):
print('\n[#%d] Launching Cutechess...\n%s\n' % (socket, command)) print('\n[#%d] Launching Cutechess...\n%s\n' % (cutechess_idx, command))
cutechess = Popen(command.split(), stdout=PIPE) cutechess = Popen(command.split(), stdout=PIPE)
results = { results = {
@@ -1316,16 +1309,13 @@ def run_and_parse_cutechess(config, command, socket, results_queue, abort_flag):
break break
if 'Started game' not in line and 'Score of' not in line: if 'Started game' not in line and 'Score of' not in line:
print('[#%d] %s' % (socket, line)) print('[#%d] %s' % (cutechess_idx, line))
if 'Finished game' in line: if 'Finished game' in line:
Cutechess.update_results(results, line) Cutechess.update_results(results, line)
# Report results at the end, or once hitting the report_rate # Add to the results queue every time we have a game-pair finished
report = 'Elo difference' in line if any(results['pentanomial']):
report = report or sum(results['pentanomial']) == config.workload['test']['report_rate']
if report:
# Place the results into the Queue, and be sure to copy the lists # Place the results into the Queue, and be sure to copy the lists
results_queue.put({ results_queue.put({
@@ -1334,6 +1324,7 @@ def run_and_parse_cutechess(config, command, socket, results_queue, abort_flag):
'crashes' : results['crashes'], 'crashes' : results['crashes'],
'timelosses' : results['timelosses'], 'timelosses' : results['timelosses'],
'illegals' : results['illegals'], 'illegals' : results['illegals'],
'cutechess_idx' : cutechess_idx,
}) })
# Clear out all the results, so we can start collecting a new set # Clear out all the results, so we can start collecting a new set
-49
View File
@@ -1,49 +0,0 @@
{
"private" : false,
"nps" : 1254000,
"base" : "master",
"source" : "https://github.com/kz04px/4ku",
"bounds" : "[0.00, 5.00]",
"book" : "Pohl.pgn",
"win_adj" : "movecount=3 score=400",
"draw_adj" : "movenumber=40 movecount=8 score=10",
"build" : {
"path" : "",
"compilers" : ["g++"],
"cpuflags" : ["POPCNT"],
"systems" : ["Windows", "Linux"]
},
"testmodes" : {
"STC" : {
"options" : "Threads=1 Hash=8",
"timecontrol" : "8.0+0.08",
"report_rate" : 16,
"workload_size" : 32
},
"LTC" : {
"options" : "Threads=1 Hash=64",
"timecontrol" : "40.0+0.4",
"report_rate" : 4,
"workload_size" : 8
},
"SMP STC" : {
"options" : "Threads=8 Hash=64",
"timecontrol" : "5.0+0.05",
"report_rate" : 1,
"workload_size" : 64
},
"SMP LTC" : {
"options" : "Threads=8 Hash=256",
"timecontrol" : "20.0+0.2",
"report_rate" : 1,
"workload_size" : 16
}
}
}
-49
View File
@@ -1,49 +0,0 @@
{
"private" : false,
"nps" : 1145000,
"base" : "main",
"source" : "https://github.com/jhonnold/berserk",
"bounds" : "[0.00, 3.00]",
"book" : "Pohl.epd",
"win_adj" : "movecount=3 score=400",
"draw_adj" : "movenumber=40 movecount=8 score=10",
"build" : {
"path" : "src",
"compilers" : ["gcc"],
"cpuflags" : ["AVX2", "FMA", "POPCNT"],
"systems" : ["Windows", "Linux"]
},
"testmodes" : {
"STC" : {
"options" : "Threads=1 Hash=8",
"timecontrol" : "8.0+0.08",
"report_rate" : 16,
"workload_size" : 32
},
"LTC" : {
"options" : "Threads=1 Hash=64",
"timecontrol" : "40.0+0.4",
"report_rate" : 4,
"workload_size" : 8
},
"SMP STC" : {
"options" : "Threads=8 Hash=64",
"timecontrol" : "4.0+0.04",
"report_rate" : 1,
"workload_size" : 64
},
"SMP LTC" : {
"options" : "Threads=8 Hash=256",
"timecontrol" : "16.0+0.16",
"report_rate" : 1,
"workload_size" : 16
}
}
}
-49
View File
@@ -1,49 +0,0 @@
{
"private" : false,
"nps" : 2096000,
"base" : "master",
"source" : "https://github.com/Aryan1508/Bit-Genie",
"bounds" : "[0.00, 5.00]",
"book" : "Pohl.epd",
"win_adj" : "movecount=3 score=400",
"draw_adj" : "movenumber=40 movecount=8 score=10",
"build" : {
"path" : "src",
"compilers" : ["g++"],
"cpuflags" : ["POPCNT"],
"systems" : ["Windows", "Linux"]
},
"testmodes" : {
"STC" : {
"options" : "Threads=1 Hash=8",
"timecontrol" : "8.0+0.08",
"report_rate" : 16,
"workload_size" : 32
},
"LTC" : {
"options" : "Threads=1 Hash=64",
"timecontrol" : "40.0+0.4",
"report_rate" : 4,
"workload_size" : 8
},
"SMP STC" : {
"options" : "Threads=8 Hash=64",
"timecontrol" : "5.0+0.05",
"report_rate" : 1,
"workload_size" : 64
},
"SMP LTC" : {
"options" : "Threads=8 Hash=256",
"timecontrol" : "20.0+0.2",
"report_rate" : 1,
"workload_size" : 16
}
}
}
-49
View File
@@ -1,49 +0,0 @@
{
"private" : false,
"nps" : 1106000,
"base" : "main",
"source" : "https://github.com/dsekercioglu/blackmarlin",
"bounds" : "[0.00, 5.00]",
"book" : "Pohl.epd",
"win_adj" : "movecount=3 score=400",
"draw_adj" : "movenumber=40 movecount=8 score=10",
"build" : {
"path" : "",
"compilers" : ["cargo>=1.57.0"],
"cpuflags" : ["AVX2", "FMA", "POPCNT"],
"systems" : ["Windows", "Linux"]
},
"testmodes" : {
"STC" : {
"options" : "Threads=1 Hash=8",
"timecontrol" : "8.0+0.08",
"report_rate" : 16,
"workload_size" : 32
},
"LTC" : {
"options" : "Threads=1 Hash=64",
"timecontrol" : "40.0+0.4",
"report_rate" : 4,
"workload_size" : 8
},
"SMP STC" : {
"options" : "Threads=8 Hash=64",
"timecontrol" : "5.0+0.05",
"report_rate" : 1,
"workload_size" : 64
},
"SMP LTC" : {
"options" : "Threads=8 Hash=256",
"timecontrol" : "20.0+0.2",
"report_rate" : 1,
"workload_size" : 16
}
}
}
-49
View File
@@ -1,49 +0,0 @@
{
"private" : false,
"nps" : 1395000,
"base" : "master",
"source" : "https://github.com/lucasart/Demolito",
"bounds" : "[0.00, 5.00]",
"book" : "Pohl.epd",
"win_adj" : "movecount=3 score=400",
"draw_adj" : "movenumber=40 movecount=8 score=10",
"build" : {
"path" : "src",
"compilers" : ["clang", "gcc"],
"cpuflags" : ["POPCNT"],
"systems" : ["Windows", "Linux"]
},
"testmodes" : {
"STC" : {
"options" : "Threads=1 Hash=8",
"timecontrol" : "8.0+0.08",
"report_rate" : 16,
"workload_size" : 32
},
"LTC" : {
"options" : "Threads=1 Hash=32",
"timecontrol" : "32.0+0.32",
"report_rate" : 4,
"workload_size" : 8
},
"SMP STC" : {
"options" : "Threads=8 Hash=32",
"timecontrol" : "4.0+0.04",
"report_rate" : 1,
"workload_size" : 64
},
"SMP LTC" : {
"options" : "Threads=8 Hash=128",
"timecontrol" : "16.0+0.16",
"report_rate" : 1,
"workload_size" : 16
}
}
}
-49
View File
@@ -1,49 +0,0 @@
{
"private" : false,
"nps" : 1163000,
"base" : "master",
"source" : "https://github.com/justNo4b/Drofa",
"bounds" : "[0.00, 5.00]",
"book" : "4moves_noob.epd",
"win_adj" : "movecount=3 score=400",
"draw_adj" : "movenumber=40 movecount=8 score=10",
"build" : {
"path" : "",
"compilers" : ["g++"],
"cpuflags" : ["POPCNT"],
"systems" : ["Windows", "Linux"]
},
"testmodes" : {
"STC" : {
"options" : "Threads=1 Hash=8",
"timecontrol" : "8.0+0.08",
"report_rate" : 16,
"workload_size" : 32
},
"LTC" : {
"options" : "Threads=1 Hash=64",
"timecontrol" : "40.0+0.4",
"report_rate" : 4,
"workload_size" : 8
},
"SMP STC" : {
"options" : "Threads=8 Hash=64",
"timecontrol" : "5.0+0.05",
"report_rate" : 1,
"workload_size" : 64
},
"SMP LTC" : {
"options" : "Threads=8 Hash=256",
"timecontrol" : "20.0+0.2",
"report_rate" : 1,
"workload_size" : 16
}
}
}
-49
View File
@@ -1,49 +0,0 @@
{
"private" : false,
"nps" : 1012000,
"base" : "master",
"source" : "https://github.com/fabianvdW/FabChess",
"bounds" : "[0.00, 5.00]",
"book" : "Pohl.epd",
"win_adj" : "movecount=3 score=400",
"draw_adj" : "movenumber=40 movecount=8 score=10",
"build" : {
"path" : "",
"compilers" : ["cargo>=1.41.0"],
"cpuflags" : ["POPCNT"],
"systems" : ["Windows", "Linux"]
},
"testmodes" : {
"STC" : {
"options" : "Threads=1 Hash=8",
"timecontrol" : "8.0+0.08",
"report_rate" : 16,
"workload_size" : 32
},
"LTC" : {
"options" : "Threads=1 Hash=64",
"timecontrol" : "40.0+0.4",
"report_rate" : 4,
"workload_size" : 8
},
"SMP STC" : {
"options" : "Threads=8 Hash=64",
"timecontrol" : "5.0+0.05",
"report_rate" : 1,
"workload_size" : 64
},
"SMP LTC" : {
"options" : "Threads=8 Hash=256",
"timecontrol" : "20.0+0.2",
"report_rate" : 1,
"workload_size" : 16
}
}
}
-49
View File
@@ -1,49 +0,0 @@
{
"private" : false,
"nps" : 1881000,
"base" : "master",
"source" : "https://github.com/KierenP/Halogen",
"bounds" : "[0.00, 5.00]",
"book" : "Pohl.epd",
"win_adj" : "movecount=3 score=400",
"draw_adj" : "movenumber=40 movecount=8 score=10",
"build" : {
"path" : "src",
"compilers" : ["g++"],
"cpuflags" : ["POPCNT"],
"systems" : ["Windows", "Linux"]
},
"testmodes" : {
"STC" : {
"options" : "Threads=1 Hash=8",
"timecontrol" : "8.0+0.08",
"report_rate" : 16,
"workload_size" : 32
},
"LTC" : {
"options" : "Threads=1 Hash=64",
"timecontrol" : "40.0+0.4",
"report_rate" : 4,
"workload_size" : 8
},
"SMP STC" : {
"options" : "Threads=8 Hash=64",
"timecontrol" : "5.0+0.05",
"report_rate" : 1,
"workload_size" : 64
},
"SMP LTC" : {
"options" : "Threads=8 Hash=256",
"timecontrol" : "20.0+0.2",
"report_rate" : 1,
"workload_size" : 16
}
}
}
-49
View File
@@ -1,49 +0,0 @@
{
"private" : false,
"nps" : 470000,
"base" : "master",
"source" : "https://github.com/vshcherbyna/igel",
"bounds" : "[0.00, 3.00]",
"book" : "Pohl.epd",
"win_adj" : "movecount=3 score=400",
"draw_adj" : "movenumber=40 movecount=8 score=10",
"build" : {
"path" : "src",
"compilers" : ["g++"],
"cpuflags" : ["POPCNT"],
"systems" : ["Windows", "Linux"]
},
"testmodes" : {
"STC" : {
"options" : "Threads=1 Hash=8",
"timecontrol" : "10.0+0.1",
"report_rate" : 16,
"workload_size" : 32
},
"LTC" : {
"options" : "Threads=1 Hash=64",
"timecontrol" : "60.0+0.6",
"report_rate" : 4,
"workload_size" : 8
},
"SMP STC" : {
"options" : "Threads=8 Hash=64",
"timecontrol" : "5.0+0.05",
"report_rate" : 1,
"workload_size" : 64
},
"SMP LTC" : {
"options" : "Threads=8 Hash=256",
"timecontrol" : "20.0+0.2",
"report_rate" : 1,
"workload_size" : 16
}
}
}
-49
View File
@@ -1,49 +0,0 @@
{
"private" : false,
"nps" : 1346000,
"base" : "master",
"source" : "https://github.com/Luecx/Koivisto",
"bounds" : "[0.00, 2.50]",
"book" : "Pohl.epd",
"win_adj" : "movecount=3 score=400",
"draw_adj" : "movenumber=40 movecount=8 score=10",
"build" : {
"path" : "src_files",
"compilers" : ["g++"],
"cpuflags" : ["AVX2", "FMA", "POPCNT"],
"systems" : ["Windows", "Linux"]
},
"testmodes" : {
"STC" : {
"options" : "Threads=1 Hash=8",
"timecontrol" : "8.0+0.08",
"report_rate" : 16,
"workload_size" : 32
},
"LTC" : {
"options" : "Threads=1 Hash=64",
"timecontrol" : "40.0+0.4",
"report_rate" : 4,
"workload_size" : 8
},
"SMP STC" : {
"options" : "Threads=8 Hash=64",
"timecontrol" : "5.0+0.05",
"report_rate" : 1,
"workload_size" : 64
},
"SMP LTC" : {
"options" : "Threads=8 Hash=256",
"timecontrol" : "20.0+0.2",
"report_rate" : 1,
"workload_size" : 16
}
}
}
-49
View File
@@ -1,49 +0,0 @@
{
"private" : false,
"nps" : 941000,
"base" : "master",
"source" : "https://github.com/jeffreyan11/uci-chess-engine",
"bounds" : "[0.00, 5.00]",
"book" : "Pohl.epd",
"win_adj" : "movecount=3 score=400",
"draw_adj" : "movenumber=40 movecount=8 score=10",
"build" : {
"path" : "src",
"compilers" : ["g++"],
"cpuflags" : ["POPCNT"],
"systems" : ["Windows", "Linux"]
},
"testmodes" : {
"STC" : {
"options" : "Threads=1 Hash=8",
"timecontrol" : "8.0+0.08",
"report_rate" : 16,
"workload_size" : 32
},
"LTC" : {
"options" : "Threads=1 Hash=64",
"timecontrol" : "40.0+0.4",
"report_rate" : 4,
"workload_size" : 8
},
"SMP STC" : {
"options" : "Threads=8 Hash=64",
"timecontrol" : "5.0+0.05",
"report_rate" : 1,
"workload_size" : 64
},
"SMP LTC" : {
"options" : "Threads=8 Hash=256",
"timecontrol" : "20.0+0.2",
"report_rate" : 1,
"workload_size" : 16
}
}
}
-49
View File
@@ -1,49 +0,0 @@
{
"private" : false,
"nps" : 937000,
"base" : "master",
"source" : "https://github.com/Matthies/RubiChess",
"bounds" : "[0.00, 5.00]",
"book" : "Pohl.epd",
"win_adj" : "movecount=3 score=400",
"draw_adj" : "movenumber=40 movecount=8 score=10",
"build" : {
"path" : "src",
"compilers" : ["g++"],
"cpuflags" : ["POPCNT"],
"systems" : ["Windows", "Linux"]
},
"testmodes" : {
"STC" : {
"options" : "Threads=1 Hash=8",
"timecontrol" : "10.0+0.1",
"report_rate" : 16,
"workload_size" : 32
},
"LTC" : {
"options" : "Threads=1 Hash=64",
"timecontrol" : "60.0+0.6",
"report_rate" : 4,
"workload_size" : 8
},
"SMP STC" : {
"options" : "Threads=8 Hash=64",
"timecontrol" : "5.0+0.05",
"report_rate" : 1,
"workload_size" : 64
},
"SMP LTC" : {
"options" : "Threads=8 Hash=256",
"timecontrol" : "20.0+0.2",
"report_rate" : 1,
"workload_size" : 16
}
}
}
-49
View File
@@ -1,49 +0,0 @@
{
"private" : false,
"nps" : 736000,
"base" : "main",
"source" : "https://github.com/connormcmonigle/seer-nnue",
"bounds" : "[0.00, 5.00]",
"book" : "Pohl.epd",
"win_adj" : "movecount=3 score=400",
"draw_adj" : "movenumber=40 movecount=8 score=10",
"build" : {
"path" : "build",
"compilers" : ["g++>=9.0.0"],
"cpuflags" : ["AVX2", "FMA", "POPCNT"],
"systems" : ["Windows", "Linux"]
},
"testmodes" : {
"STC" : {
"options" : "Threads=1 Hash=32",
"timecontrol" : "8.0+0.08",
"report_rate" : 16,
"workload_size" : 32
},
"LTC" : {
"options" : "Threads=1 Hash=64",
"timecontrol" : "40.0+0.4",
"report_rate" : 4,
"workload_size" : 8
},
"SMP STC" : {
"options" : "Threads=8 Hash=64",
"timecontrol" : "5.0+0.05",
"report_rate" : 1,
"workload_size" : 64
},
"SMP LTC" : {
"options" : "Threads=8 Hash=256",
"timecontrol" : "20.0+0.2",
"report_rate" : 1,
"workload_size" : 16
}
}
}
-49
View File
@@ -1,49 +0,0 @@
{
"private" : false,
"nps" : 1689000,
"base" : "master",
"source" : "https://github.com/mhouppin/stash-bot",
"bounds" : "[0.00, 5.00]",
"book" : "4moves_noob.epd",
"win_adj" : "movecount=3 score=400",
"draw_adj" : "movenumber=40 movecount=8 score=10",
"build" : {
"path" : "src",
"compilers" : ["gcc", "clang"],
"cpuflags" : ["POPCNT"],
"systems" : ["Windows", "Linux"]
},
"testmodes" : {
"STC" : {
"options" : "Threads=1 Hash=16",
"timecontrol" : "8.0+0.08",
"report_rate" : 16,
"workload_size" : 32
},
"LTC" : {
"options" : "Threads=1 Hash=64",
"timecontrol" : "40.0+0.4",
"report_rate" : 4,
"workload_size" : 8
},
"SMP STC" : {
"options" : "Threads=8 Hash=64",
"timecontrol" : "5.0+0.05",
"report_rate" : 1,
"workload_size" : 64
},
"SMP LTC" : {
"options" : "Threads=8 Hash=256",
"timecontrol" : "20.0+0.2",
"report_rate" : 1,
"workload_size" : 16
}
}
}
-101
View File
@@ -1,101 +0,0 @@
{
"private" : false,
"nps" : 995000,
"base" : "ob_16",
"source" : "https://github.com/AndyGrant/Stockfish",
"bounds" : "[0.00, 2.00]",
"book" : "Pohl.epd",
"win_adj" : "movecount=5 score=600",
"draw_adj" : "movenumber=32 movecount=6 score=15",
"build" : {
"path" : "src",
"compilers" : ["g++"],
"cpuflags" : ["AVX2", "FMA", "POPCNT"],
"systems" : ["Windows", "Linux"]
},
"testmodes" : {
"STC" : {
"options" : "Threads=1 Hash=16 MoveOverhead=100",
"timecontrol" : "10.0+0.10",
"report_rate" : 16,
"workload_size" : 32
},
"LTC" : {
"options" : "Threads=1 Hash=64 MoveOverhead=100",
"timecontrol" : "60.0+0.6",
"report_rate" : 4,
"workload_size" : 8,
"bounds" : "[0.50, 2.50]"
},
"SMP STC" : {
"options" : "Threads=7 Hash=64 MoveOverhead=100",
"timecontrol" : "10.0+0.1",
"report_rate" : 4,
"workload_size" : 64
},
"SMP LTC" : {
"options" : "Threads=14 Hash=256 MoveOverhead=100",
"timecontrol" : "30.0+0.3",
"report_rate" : 4,
"workload_size" : 16,
"bounds" : "[0.50, 2.50]"
},
"STC Simplification" : {
"options" : "Threads=1 Hash=16 MoveOverhead=100",
"timecontrol" : "10.0+0.10",
"report_rate" : 16,
"workload_size" : 32,
"bounds" : "[-1.75, 0.25]"
},
"LTC Simplification" : {
"options" : "Threads=1 Hash=64 MoveOverhead=100",
"timecontrol" : "60.0+0.6",
"report_rate" : 4,
"workload_size" : 8,
"bounds" : "[-1.75, 0.25]"
},
"STC Regression" : {
"options" : "Threads=1 Hash=16 MoveOverhead=100",
"timecontrol" : "10.0+0.10",
"report_rate" : 16,
"workload_size" : 32,
"book" : "8moves_v3.epd",
"games" : 40000
},
"LTC Regression" : {
"options" : "Threads=1 Hash=64 MoveOverhead=100",
"timecontrol" : "60.0+0.6",
"report_rate" : 4,
"workload_size" : 8,
"book" : "8moves_v3.epd",
"games" : 40000
},
"STC Fixed Games" : {
"options" : "Threads=1 Hash=16 MoveOverhead=100",
"timecontrol" : "10.0+0.10",
"report_rate" : 16,
"workload_size" : 32,
"games" : 40000
},
"LTC Fixed Games" : {
"options" : "Threads=1 Hash=64 MoveOverhead=100",
"timecontrol" : "60.0+0.6",
"report_rate" : 4,
"workload_size" : 8,
"games" : 40000
}
}
}
-49
View File
@@ -1,49 +0,0 @@
{
"private" : false,
"nps" : 1758000,
"base" : "master",
"source" : "https://github.com/TerjeKir/weiss",
"bounds" : "[0.00, 3.00]",
"book" : "Pohl.epd",
"win_adj" : "movecount=3 score=400",
"draw_adj" : "movenumber=40 movecount=8 score=10",
"build" : {
"path" : "src",
"compilers" : ["gcc"],
"cpuflags" : ["POPCNT"],
"systems" : ["Windows", "Linux"]
},
"testmodes" : {
"STC" : {
"options" : "Threads=1 Hash=32",
"timecontrol" : "8.0+0.08",
"report_rate" : 16,
"workload_size" : 32
},
"LTC" : {
"options" : "Threads=1 Hash=128",
"timecontrol" : "40.0+0.4",
"report_rate" : 4,
"workload_size" : 8
},
"SMP STC" : {
"options" : "Threads=8 Hash=128",
"timecontrol" : "5.0+0.05",
"report_rate" : 1,
"workload_size" : 64
},
"SMP LTC" : {
"options" : "Threads=8 Hash=512",
"timecontrol" : "20.0+0.2",
"report_rate" : 1,
"workload_size" : 16
}
}
}
-49
View File
@@ -1,49 +0,0 @@
{
"private" : false,
"nps" : 661000,
"base" : "master",
"source" : "https://github.com/rosenthj/Winter",
"bounds" : "[0.00, 5.00]",
"book" : "Pohl.epd",
"win_adj" : "movecount=3 score=400",
"draw_adj" : "movenumber=40 movecount=8 score=10",
"build" : {
"path" : "",
"compilers" : ["clang++", "g++"],
"cpuflags" : ["POPCNT"],
"systems" : ["Windows", "Linux"]
},
"testmodes" : {
"STC" : {
"options" : "Threads=1 Hash=8",
"timecontrol" : "8.0+0.08",
"report_rate" : 16,
"workload_size" : 32
},
"LTC" : {
"options" : "Threads=1 Hash=64",
"timecontrol" : "40.0+0.4",
"report_rate" : 4,
"workload_size" : 8
},
"SMP STC" : {
"options" : "Threads=8 Hash=64",
"timecontrol" : "5.0+0.05",
"report_rate" : 1,
"workload_size" : 64
},
"SMP LTC" : {
"options" : "Threads=8 Hash=256",
"timecontrol" : "20.0+0.2",
"report_rate" : 1,
"workload_size" : 16
}
}
}
-49
View File
@@ -1,49 +0,0 @@
{
"private" : false,
"nps" : 946000,
"base" : "master",
"source" : "https://github.com/amanjpro/zahak",
"bounds" : "[0.00, 5.00]",
"book" : "Pohl.epd",
"win_adj" : "movecount=3 score=400",
"draw_adj" : "movenumber=40 movecount=8 score=10",
"build" : {
"path" : "",
"compilers" : ["go"],
"cpuflags" : ["AVX", "POPCNT"],
"systems" : ["Windows", "Linux"]
},
"testmodes" : {
"STC" : {
"options" : "Threads=1 Hash=8",
"timecontrol" : "8.0+0.08",
"report_rate" : 16,
"workload_size" : 32
},
"LTC" : {
"options" : "Threads=1 Hash=64",
"timecontrol" : "40.0+0.4",
"report_rate" : 4,
"workload_size" : 8
},
"SMP STC" : {
"options" : "Threads=8 Hash=64",
"timecontrol" : "5.0+0.05",
"report_rate" : 1,
"workload_size" : 64
},
"SMP LTC" : {
"options" : "Threads=8 Hash=256",
"timecontrol" : "20.0+0.2",
"report_rate" : 1,
"workload_size" : 16
}
}
}
+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' : '13', 'client_version' : 14,
# Generic Error Messages useful to those setting up their own instance # Generic Error Messages useful to those setting up their own instance
'error' : { 'error' : {
+3 -1
View File
@@ -112,7 +112,8 @@ class Test(Model):
base_time_control = CharField(max_length=32) base_time_control = CharField(max_length=32)
# Changable Test Parameters # Changable Test Parameters
report_rate = IntegerField(default=8) worker_limit = IntegerField(default=0)
thread_limit = IntegerField(default=0)
workload_size = IntegerField(default=32) workload_size = IntegerField(default=32)
priority = IntegerField(default=0) priority = IntegerField(default=0)
throughput = IntegerField(default=0) throughput = IntegerField(default=0)
@@ -133,6 +134,7 @@ class Test(Model):
currentllr = FloatField(default=0.0) # SPRT currentllr = FloatField(default=0.0) # SPRT
upperllr = FloatField(default=0.0) # SPRT upperllr = FloatField(default=0.0) # SPRT
max_games = IntegerField(default=0) # GAMES max_games = IntegerField(default=0) # GAMES
spsa = JSONField(default=dict, blank=True, null=True) # SPSA
# Collection of all individual Result() objects # Collection of all individual Result() objects
games = IntegerField(default=0) # Overall 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 engine = selection.options[selection.selectedIndex].value;
const mode = extract_mode_config(mode_str, 'dev'); 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('workload_size').value = mode['workload_size'] || 32;
document.getElementById('book_name' ).value = mode['book'] || config.engines[engine].book; 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) color: var(--color-font2)
} }
#content .row input, #content .row select { #content .row input, #content .row select, #content .row textarea {
flex-grow: 1; flex-grow: 1;
min-width: 0; min-width: 0;
border: 1px solid var(--color3); border: 1px solid var(--color3);
@@ -70,7 +70,7 @@
padding: 2px 2px; padding: 2px 2px;
} }
#content .row input:focus, #content .row select:focus { #content .row input:focus, #content .row select:focus, #content .row textarea {
outline: none; outline: none;
border-color: var(--color3); border-color: var(--color3);
box-shadow: 0 0 0 3px rgba(77, 144, 254, 0.25); box-shadow: 0 0 0 3px rgba(77, 144, 254, 0.25);
+49 -5
View File
@@ -21,7 +21,6 @@
import re, django import re, django
import OpenBench.config, OpenBench.utils, OpenBench.stats, OpenBench.models import OpenBench.config, OpenBench.utils, OpenBench.stats, OpenBench.models
def oneDigitPrecision(value): def oneDigitPrecision(value):
try: try:
value = round(value, 1) value = round(value, 1)
@@ -58,17 +57,23 @@ def gitDiffLink(test):
def shortStatBlock(test): def shortStatBlock(test):
tri_line = 'Games: %d W: %d L: %d D: %d' % (test.games, test.wins, test.losses, test.draws) if test.test_mode == 'SPSA':
penta_line = 'Pntml(0-2): %d, %d, %d, %d, %d' % (test.LL, test.LD, test.DD, test.DW, test.WW) 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]' % ( top_line = 'LLR: %0.2f (%0.2f, %0.2f) [%0.2f, %0.2f]' % (
test.currentllr, test.lowerllr, test.upperllr, test.elolower, test.eloupper) 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]) 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) 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: if test.use_penta:
return '\n'.join([top_line, tri_line, penta_line]) return '\n'.join([top_line, tri_line, penta_line])
@@ -79,6 +84,8 @@ def shortStatBlock(test):
def longStatBlock(test): def longStatBlock(test):
assert test.test_mode != 'SPSA'
threads = int(OpenBench.utils.extract_option(test.dev_options, 'Threads')) threads = int(OpenBench.utils.extract_option(test.dev_options, 'Threads'))
hashmb = int(OpenBench.utils.extract_option(test.dev_options, 'Hash')) hashmb = int(OpenBench.utils.extract_option(test.dev_options, 'Hash'))
timecontrol = test.dev_time_control + ['s', '']['=' in test.dev_time_control] 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'] return machine.info['machine_name']
except: return 'None' except: return 'None'
register = django.template.Library() register = django.template.Library()
register.filter('oneDigitPrecision', oneDigitPrecision) register.filter('oneDigitPrecision', oneDigitPrecision)
register.filter('twoDigitPrecision', twoDigitPrecision) register.filter('twoDigitPrecision', twoDigitPrecision)
@@ -217,3 +225,39 @@ register.filter('cpuflagsBlock', cpuflagsBlock)
register.filter('compilerBlock', compilerBlock) register.filter('compilerBlock', compilerBlock)
register.filter('removePrefix', removePrefix) register.filter('removePrefix', removePrefix)
register.filter('machine_name', machine_name) 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/', OpenBench.views.machines),
django.urls.path(r'machines/<int:machineid>/', 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'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'test/<int:id>/<str:action>', OpenBench.views.test),
django.urls.path(r'newTest/', OpenBench.views.create_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 # 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:engine>/', 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.models import *
from OpenBench.stats import TrinomialSPRT, PentanomialSPRT from OpenBench.stats import TrinomialSPRT, PentanomialSPRT
import OpenBench.views import OpenBench.views
@@ -122,6 +123,13 @@ class TimeControl(object):
return float(time_str.split('+')[0]) 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): def path_join(*args):
return "/".join([f.lstrip("/").rstrip("/") for f in args]).rstrip('/') return "/".join([f.lstrip("/").rstrip("/") for f in args]).rstrip('/')
@@ -137,6 +145,8 @@ def extract_option(options, option):
if match: return match.group() if match: return match.group()
def get_pending_tests(): def get_pending_tests():
t = Test.objects.filter(approved=False) t = Test.objects.filter(approved=False)
t = t.exclude(finished=True) t = t.exclude(finished=True)
@@ -209,13 +219,6 @@ def getPaging(content, page, url, pagelen=25):
return start, end, context 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): def branch_is_out_of_date(test):
@@ -240,336 +243,6 @@ def branch_is_out_of_date(test):
traceback.print_exc() traceback.print_exc()
return False 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): def get_machine(machineid, user, info):
@@ -592,22 +265,6 @@ def get_machine(machineid, user, info):
return machine 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 # Purely Helper functions for Networks views
@@ -697,124 +354,6 @@ def network_download(request, engine, network):
return response 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): def update_test(request, machine):
# Extract error information # 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.failed = test.games >= test.max_games and test.wins < test.losses
test.finished = test.passed or test.failed 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() test.save()
# Update Result object; No risk from concurrent access # 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.config
import OpenBench.utils 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.config import OPENBENCH_CONFIG
from OpenBench.models import * from OpenBench.models import *
@@ -437,70 +442,45 @@ def machines(request, machineid=None):
def test(request, id, action=None): def test(request, id, action=None):
if not (test := Test.objects.filter(id=id).first()): # Request is to modify or interact with the Test
return django.http.HttpResponseRedirect('/index/') if action != None:
return modify_workload(request, id, action)
if action not in ['APPROVE', 'RESTART', 'STOP', 'DELETE', 'RESTORE', 'MODIFY']: # Verify that the Test id exists
if not (test := Test.objects.filter(id=id).first()):
return redirect(request, '/index/', error='No such Test exists')
# 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')
# Package everything up and display the test
data = { 'test' : test, 'results': Result.objects.filter(test=test) } data = { 'test' : test, 'results': Result.objects.filter(test=test) }
return render(request, 'test.html', data) return render(request, 'test.html', data)
if not request.user.is_authenticated: def tune(request, id, action=None):
return redirect(request, '/login/', error='Only users may interact with tests')
profile = Profile.objects.get(user=request.user) # Request is to modify or interact with the Tune
if not profile.approver and test.author != request.user.username: if action != None:
return redirect(request, '/index/', error='You cannot interact with another user\'s test') return modify_workload(request, id, action)
if action == 'APPROVE': # Verify that the Tune id exists
if test.author == request.user.username and not user.is_superuser: if not (tune := Test.objects.filter(id=id).first()):
return redirect(request, '/index/', error='You cannot approve your own test') return redirect(request, '/index/', error='No such Tune exists')
if action == 'APPROVE': test.approved = True; test.save() # Verify that it is indeed a Tune and not a Test
if action == 'RESTART': test.finished = False; test.save() if tune.test_mode == 'SPRT' or tune.test_mode == 'FIXED':
if action == 'STOP' : test.finished = True; test.save() return redirect(request, '/index/', error='You are trying to view a Test not Tune')
if action == 'DELETE' : test.deleted = True; test.save()
if action == 'RESTORE': test.deleted = False; test.save()
if action == 'MODIFY': # Package everything up and display the Tune
test.priority = int(request.POST['priority']) data = { 'test' : tune, 'results': Result.objects.filter(test=tune) }
test.throughput = max(1, int(request.POST['throughput'])) return render(request, 'tune.html', data)
test.report_rate = max(1, int(request.POST['report_rate']))
test.workload_size = max(1, int(request.POST['workload_size']))
test.save()
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/')
def create_test(request): def create_test(request):
return create_workload(request, 'TEST')
if not request.user.is_authenticated: def create_tune(request):
return redirect(request, '/login/', error='Only enabled users can create tests') return create_workload(request, 'TUNE')
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)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# NETWORK MANAGEMENT VIEWS # # NETWORK MANAGEMENT VIEWS #
@@ -588,7 +568,7 @@ def client_verify_worker(request):
# Ensure the Client is using the same version as the Server # Ensure the Client is using the same version as the Server
if machine.info['client_ver'] != OPENBENCH_CONFIG['client_version']: if machine.info['client_ver'] != OPENBENCH_CONFIG['client_version']:
expected_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 # Use the secret token as our soft verification
if machine.secret != request.POST['secret']: if machine.secret != request.POST['secret']:
@@ -673,7 +653,7 @@ def client_get_workload(request):
if response != None: return response if response != None: return response
# Contains keys 'workload', otherwise none # Contains keys 'workload', otherwise none
return JsonResponse(OpenBench.utils.get_workload(machine)) return JsonResponse(get_workload(machine))
@csrf_exempt @csrf_exempt
def client_get_network(request, engine, name): def client_get_network(request, engine, name):
+8 -6
View File
@@ -24,7 +24,9 @@ import threading
import time import time
import traceback 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): class ArtifactWatcher(threading.Thread):
@@ -40,15 +42,15 @@ class ArtifactWatcher(threading.Thread):
base_has = test.base.source.endswith('.zip') or base_has base_has = test.base.source.endswith('.zip') or base_has
if not dev_has: # Check for new Artifacts for Dev 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] 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() test.dev.save()
if not base_has: # Check for new Artifacts for Base 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] 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() test.base.save()
# If both finished, flag the test as no longer awaiting # If both finished, flag the test as no longer awaiting
@@ -58,7 +60,7 @@ class ArtifactWatcher(threading.Thread):
def run(self): def run(self):
while True: while True:
for test in OpenBench.utils.get_awaiting_tests(): for test in get_awaiting_tests():
try: self.update_test(test) try: self.update_test(test)
except: except:
traceback.print_exc() 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)
@@ -2,7 +2,12 @@
<td><a href="/user/{{test.author}}">{{test.author|capfirst|slice:":6"}}</a></td> <td><a href="/user/{{test.author}}">{{test.author|capfirst|slice:":6"}}</a></td>
<td>{{test.dev_engine}}</td> <td>{{test.dev_engine}}</td>
<td> <td>
{% if test.test_mode != "SPSA" %}
<a href="/test/{{test.id}}">{{test|prettyDevName}}</a> <a href="/test/{{test.id}}">{{test|prettyDevName}}</a>
{% else %}
<a href="/tune/{{test.id}}">{{test|prettyDevName}}</a>
{% endif %}
{% if test.error %} <span style="color: red">*</span> {% endif %} {% if test.error %} <span style="color: red">*</span> {% endif %}
{% if test|testIsFRC %} <span style="color: green">*</span> {% endif %} {% if test|testIsFRC %} <span style="color: green">*</span> {% endif %}
</td> </td>
+1
View File
@@ -86,6 +86,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="/newTune"><i class="fa-solid fa-plus fa-fw"></i> Create Tune</a></li>
<li><a href="/newNetwork"><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>
+9 -9
View File
@@ -129,7 +129,15 @@
<div class="row"> <div class="row">
<label> Throughput </label> <input value="1000" id="throughput" , name="throughput"> <label> Throughput </label> <input value="1000" id="throughput" , name="throughput">
</div> </div>
<div class="row">
<label> Worker Limit</label> <input value="None" id="worker_limit" name="worker_limit">
</div>
<div class="row">
<label> Thread Limit </label> <input value="None" id="thread_limit" name="thread_limit">
</div>
<div class="row">
<label> Workload Size </label> <input id="workload_size" name="workload_size">
</div>
<div class="row"> <div class="row">
<label> Syzygy WDL </label> <select name="syzygy_wdl"> <label> Syzygy WDL </label> <select name="syzygy_wdl">
<option selected value="DISABLED"> Disabled </option> <option selected value="DISABLED"> Disabled </option>
@@ -142,14 +150,6 @@
</select> </select>
</div> </div>
<h3> Workload Settings </h3>
<div class="row">
<label> Report Rate </label> <input id="report_rate" name="report_rate">
</div>
<div class="row">
<label> Workload Size </label> <input id="workload_size" name="workload_size">
</div>
<h3> Adjudication Settings </h3> <h3> Adjudication Settings </h3>
<div class="row"> <div class="row">
<label> Syzygy ADJ. </label> <label> Syzygy ADJ. </label>
+159
View File
@@ -0,0 +1,159 @@
{% extends "OpenBench/base.html" %}
{% load static %}
{% block scripts %}
{{ config|json_script:"json-config" }}
{{ networks|json_script:"json-networks" }}
{{ profile.repos|json_script:"json-repos" }}
<script src="{% static 'create_tune.js' %}"></script>
<script>
document.addEventListener(
'DOMContentLoaded', function () {
set_engine('{{ profile.engine }}');
enforce_default_text('repo', 'https://github.com/');
}, false
);
</script>
{% endblock %}
{% block content %}
<form method="POST" action="/newTune/">
{% csrf_token %}
<div class="form w-100">
<div class="col">
<h3> Engine </h3>
<div class="row">
<label> Engine </label>
<select id="engine" name="dev_engine" onchange="set_engine(value);">
{% for engine in config.engines %}
<option value="{{ engine }}">{{ engine }}</option>
{% endfor %}
</select>
</div>
<div class="row">
<label> Source </label> <input id="repo" name="dev_repo">
</div>
<h3> Engine Settings </h3>
<div class="row">
<label> Branch </label> <input id="branch" name="dev_branch" autofocus>
</div>
<div class="row">
<label> Bench </label> <input value="Autofill" name="dev_bench">
</div>
<div class="row">
<label> Network </label> <select id="network" name="dev_network"></select>
</div>
<div class="row">
<label> Options </label> <input id="options" name="dev_options">
</div>
<div class="row">
<label> Time </label> <input id="time_control" name="dev_time_control">
</div>
<h3> SPSA Input </h3>
<div class="row">
<textarea style="margin-left:24px" id="spsa_inputs" name="spsa_inputs" rows=17></textarea>
</div>
</div>
<div class="col">
<h3> SPSA Settings </h3>
<div class="row">
<label> Opening Book </label> <select id="book_name" name="book_name">
{% for name, data in config.books.items %}
<option value="{{ name }}">{{ name }}</option>
{% endfor %}
</select>
</div>
<div class="row">
<label> Alpha </label> <input value="0.602" id="spsa_alpha" name="spsa_alpha">
</div>
<div class="row">
<label> Gamma </label> <input value="0.101" id="spsa_gamma" name="spsa_gamma">
</div>
<div class="row">
<label> A-Ratio </label> <input value="0.1" id="spsa_A_ratio" name="spsa_A_ratio">
</div>
<div class="row">
<label> Iterations </label> <input value="200000" id="spsa_iterations" name="spsa_iterations">
</div>
<div class="row">
<label> Pairs-Per </label> <input value="1" id="spsa_pairs_per" name="spsa_pairs_per">
</div>
<h3> General Settings </h3>
<div class="row">
<label> Priority </label> <input value="1" name="priority">
</div>
<div class="row">
<label> Throughput </label> <input value="1000" id="throughput" , name="throughput">
</div>
<div class="row">
<label> Worker Limit</label> <input value="5" id="worker_limit" name="worker_limit">
</div>
<div class="row">
<label> Thread Limit </label> <input value="None" id="thread_limit" name="thread_limit">
</div>
<div class="row">
<label> Syzygy WDL </label> <select name="syzygy_wdl">
<option selected value="DISABLED"> Disabled </option>
<option value="OPTIONAL"> Optional </option>
<option value="7-MAN"> 7-Man </option>
<option value="6-MAN"> 6-Man </option>
<option value="5-MAN"> 5-Man </option>
<option value="4-MAN"> 4-Man </option>
<option value="3-MAN"> 3-Man </option>
</select>
</div>
<h3> Adjudication Settings </h3>
<div class="row">
<label> Syzygy ADJ. </label>
<select name="syzygy_adj">
<option value="DISABLED"> Disabled </option>
<option selected value="OPTIONAL"> Optional </option>
<option value="7-MAN"> 7-Man </option>
<option value="6-MAN"> 6-Man </option>
<option value="5-MAN"> 5-Man </option>
<option value="4-MAN"> 4-Man </option>
<option value="3-MAN"> 3-Man </option>
</select>
</div>
<div class="row">
<label> Win ADJ. </label> <input id="win_adj" name="win_adj">
</div>
<div class="row">
<label> Draw ADJ. </label> <input id="draw_adj" name="draw_adj">
</div>
</div>
</div>
<input type="submit" class="anchorbutton btn-start mt-3 mw-84" name="submit" value="Create SPSA Tune">
</form>
<div class="form">
<div class="col-full">
<div id="test-mode-buttons">
<!-- Generated based on the selected Engine -->
</div>
</div>
</div>
{% endblock %}
+10 -7
View File
@@ -151,7 +151,10 @@
<label>Throughput</label><input value="{{test.throughput}}" name="throughput"> <label>Throughput</label><input value="{{test.throughput}}" name="throughput">
</div> </div>
<div class="row"> <div class="row">
<label>Report Rate</label><input value="{{test.report_rate}}" name="report_rate"> <label>Worker Limit</label><input value="{{test.worker_limit|default:'None'}}" name="worker_limit">
</div>
<div class="row">
<label>Thread Limit</label><input value="{{test.thread_limit|default:'None'}}" name="thread_limit">
</div> </div>
<div class="row"> <div class="row">
<label>Workload Size</label><input value="{{test.workload_size}}" name="workload_size"> <label>Workload Size</label><input value="{{test.workload_size}}" name="workload_size">
@@ -173,12 +176,12 @@
<th>#</th> <th>#</th>
<th>User</th> <th>User</th>
<th>Updated</th> <th>Updated</th>
<th style="width: 60px">Games</th> <th style="width: 45px">Games</th>
<th style="width: 60px">Won</th> <th style="width: 45px">Won</th>
<th style="width: 60px">Lost</th> <th style="width: 45px">Lost</th>
<th style="width: 60px">Drawn</th> <th style="width: 45px">Drawn</th>
<th style="width: 60px">Time</th> <th style="width: 45px">Time</th>
<th style="width: 60px">Crash</th> <th style="width: 45px">Crash</th>
</tr> </tr>
{% for result in results %} {% for result in results %}
+218
View File
@@ -0,0 +1,218 @@
{% extends "OpenBench/base.html" %}
{% load mytags %}
{% block style %}
{% endblock %}
{% block scripts %}
<script>
function copy_statblock() {
var text = document.getElementById("long-statblock").innerHTML;
text = text.replace(/<br>/g, "\n");
text += "\n" + window.location.href;
// navigator.clipboard.writeText(text); // Optimal solution
// Suboptimal, HTTP solution
var area = document.createElement("textarea");
area.value = text;
document.body.append(area);
area.focus();
area.select();
try {
document.execCommand("copy");
document.body.removeChild(area);
}
catch (err) {
document.body.removeChild(area);
console.error("Unable to copy to Clipboard");
}
}
</script>
{% endblock %}
{% block content %}
<div id="config" style="display: block; overflow-x: auto;">
<table class="test-config left-align wrappable" style="table-layout: auto; width: 100%;">
<tr><td class="td-label">Author</td><td>{{test.author|capfirst}}</td></tr>
<tr><td class="td-label">Creation</td><td class="timestamp">{{test.creation|date:'U'}}</td></tr>
<tr><td class="td-label">Engine</td><td>{{test.dev_engine}}</td></tr>
<tr><td class="td-label">Source</td><td><a href="{{test.dev_repo}}">{{test.dev_repo}}</a></td></tr>
<tr><td class="td-label">Sha</td><td>{{test.dev.sha}}</td></tr>
<tr><td class="td-label">Branch</td><td>{{test.dev.name|prettyName}}</td></tr>
<tr><td class="td-label">Bench</td><td>{{test.dev.bench}}</td></tr>
{% if test.dev_network %}
<tr>
<td class="td-label">Network</td>
<td><a href="{{test.devnetwork|resolveNetworkURL}}">{{test.dev_netname}}</td>
</tr>
{% endif %}
<tr><td class="td-label">Options</td><td>{{test.dev_options}}</td></tr>
<tr><td class="td-label">Time</td><td>{{test.dev_time_control}}</td></tr>
<tr><td class="td-label">Opening Book</td><td><a href="{{config.framework}}raw/master/Books/{{test.bookname}}.zip">{{test.book_name}}</a></td></tr>
<tr><td class="td-label">Syzygy WDL</td><td>{{test.syzygy_wdl}}</td></tr>
<tr><td class="td-label">Syzygy ADJ.</td><td>{{test.syzygy_adj}}</td></tr>
<tr><td class="td-label">Win ADJ.</td><td>{{test.win_adj}}</td></tr>
<tr><td class="td-label">Draw ADJ.</td><td>{{test.draw_adj}}</td></tr>
<tr><td class="td-label">Alpha</td><td>{{test.spsa.Alpha}}</td></tr>
<tr><td class="td-label">Gamma</td><td>{{test.spsa.Gamma}}</td></tr>
<tr><td class="td-label">A-Ratio</td><td>{{test.spsa.A}}</td></tr>
</table>
</div>
<div id="actions" class="ml-3">
<!-- Dev vs Base [Git Diff Link] -->
<h4><a href="{{test|gitDiffLink}}">
{{test.dev.name|prettyName}} vs {{test.base.name|prettyName}}
</a></h4>
<!-- Approve Button: For Admins, or Cross-approvers -->
{% if not test.approved and profile.approver and profile.user.username != test.author %}
<a class="w-25 mr-2 anchorbutton btn-blue" href="/tune/{{test.id}}/APPROVE">Approve</a>
{% elif not test.approved and request.user.is_superuser %}
<a class="w-25 mr-2 anchorbutton btn-blue" href="/tune/{{test.id}}/APPROVE">Approve</a>
{% else %}
<a class="w-25 mr-2 anchorbutton btn-disabled">Approve</a>
{% endif %}
<!-- Restart Button: For Approvers or Test Authors of finished tests -->
{% if test.finished and profile.approver %}
<a class="w-25 mr-2 anchorbutton btn-yellow" href="/tune/{{test.id}}/RESTART">Restart</a>
{% elif test.finished and profile.user.username == test.author %}
<a class="w-25 mr-2 anchorbutton btn-yellow" href="/tune/{{test.id}}/RESTART">Restart</a>
{% elif test.finished %}
<a class="w-25 mr-2 anchorbutton btn-disabled">Restart</a>
{% endif %}
<!-- Stop Button: For Approvers or Test Authors of active tests -->
{% if not test.finished and profile.approver %}
<a class="w-25 mr-2 anchorbutton btn-yellow" href="/tune/{{test.id}}/STOP">Stop</a>
{% elif not test.finished and profile.user.username == test.author %}
<a class="w-25 mr-2 anchorbutton btn-yellow" href="/tune/{{test.id}}/STOP">Stop</a>
{% elif not test.finished %}
<a class="w-25 mr-2 anchorbutton btn-disabled">Stop</a>
{% endif %}
<!-- Delete/Restore Button: For Approvers or Test Authors -->
{% if profile.approver or profile.user.username == test.author %}
{% if test.deleted %}
<a class="w-25 mr-2 anchorbutton btn-preset" href="/tune/{{test.id}}/RESTORE">Restore</a>
{% else %}
<a class="w-25 mr-2 anchorbutton btn-red" href="/tune/{{test.id}}/DELETE">Delete</a>
{% endif %}
{% else %}
{% if test.deleted %}
<a class="w-25 mr-2 anchorbutton btn-disabled">Restore</a>
{% else %}
<a class="w-25 mr-2 anchorbutton btn-disabled">Delete</a>
{% endif %}
{% endif %}
<!-- Copy Button: Copy the current results statblock -->
<a class="copy-button" onclick="copy_statblock()">
<i class="fa-regular fa-clone copy-button"></i>
</a>
<!-- Elo, (SPRT/LRR if SPRT, otherwise CONF), Games -->
<!-- For SPSA, # of Params, Iterations, and Games -->
<pre class="long-statblock" id="long-statblock">{{test|shortStatBlock|linebreaksbr}}</pre>
<!-- Forum to modify the Priority or Throughput -->
<form method="POST" action="/tune/{{test.id}}/MODIFY">
{% csrf_token %}
<div class="form">
<div class="col-full">
<div class="row">
<label>Priority</label>
<input value="{{test.priority}}" name="priority">
</div>
<div class="row">
<label>Throughput</label>
<input value="{{test.throughput}}" name="throughput">
</div>
<div class="row">
<label>Worker Limit</label>
<input value="{{test.worker_limit|default:'None'}}" name="worker_limit">
</div>
<div class="row">
<label>Thread Limit</label>
<input value="{{test.thread_limit|default:'None'}}" name="thread_limit">
</div>
<!-- Edit Button: For Approvers or Test Authors -->
{% if profile.approver or profile.user.username == test.author %}
<input class="anchorbutton btn-blue w-100" type="submit" name="submit" value="Modify">
{% else %}
<input class="anchorbutton btn-disabled w-100" type="submit" name="submit" value="Modify">
{% endif %}
</div>
</div>
</form>
</div>
<div id="parameters" class="w-100 mt-3" style="float:left;">
<table class="stripes wrappable">
<tr class="table-header">
<th> Name </th>
<th> Start </th>
<th> Curr </th>
<th> Min </th>
<th> Max </th>
<th> C </th>
<th> C_end </th>
<th> R </th>
<th> R_end </th>
</tr>
{% for row in test|spsa_param_digest %}
<tr>
{% for element in row %}
<td> {{ element }} </td>
{% endfor %}
<tr>
{% endfor %}
</table>
</div>
<div id="results" class="w-100 mt-3" style="float:left;">
<table class="stripes wrappable">
<tr class="table-header">
<th>#</th>
<th>User</th>
<th>Updated</th>
<th style="width: 45px">Games</th>
<th style="width: 45px">Won</th>
<th style="width: 45px">Lost</th>
<th style="width: 45px">Drawn</th>
<th style="width: 45px">Time</th>
<th style="width: 45px">Crash</th>
</tr>
{% for result in results %}
<tr>
<td><a href="/machines/{{result.machine.id}}">{{result.machine.id}}</a></td>
<td>{{result.machine.user.username|capfirst}}</td>
<td class="timestamp">{{result.updated|date:'U'}}</td>
<td class="numeric">{{result.games}}</td>
<td class="numeric">{{result.wins}}</td>
<td class="numeric">{{result.losses}}</td>
<td class="numeric">{{result.draws}}</td>
<td class="numeric">{{result.timeloss}}</td>
<td class="numeric">{{result.crashes}}</td>
</tr>
{% endfor %}
</table>
</div>
{% endblock %}