Overhaul Client Reporting mechanism (#153)

Collects results as game-pairs, instead of as individual results. This removes some noise and bias that may have existed prior.

The master thread now handles all reporting to the OpenBench server. Help threads, ( one for each --nsockets or -N ), will place their results in a multiprocessing.Queue().

We will report report_rate-pairs at a time. However we will only report up to once every 30 seconds. This means we might batch report many many games at a time. This acts as a natural remedy to if someone were to have created an insanely short time control, or low nodes test. This will cause fixed-game tests to go over the cap. IE, a 40,000 game test is very likely to receive a small number of games above 40,000. Fixing these seems non-trivial, and also not important.

The Client also sends Pentanomial information to the server now. This information is not acted upon.

This involved a complete rewrite of how data (trinomial) information is extracted from Cutechess. It is predicated upon the assertion that cutechess pairs are sequential. IE, pair one will be game 1/2. Pair two will be games 3/4. Etc. This is the fundemental assertion that is in Fishtest, although very confusing to extract from observation.

Resolves an issue where the worker threads, spawned to run benchmarks, were not being killed, as .start() was not followed by a .join().

Makes more cleanly aborting threads, by explicitly murdering them with an abort_flag from threading.Event(). This speeds up killing workers that have multi-sockets. It also helps further protect us against Cutechess being left open.

Performs atomic transactions with the database for tests. This is critical for dealing with future SPSA efforts. Updates to Profile, individual Result, and Machine, are left as is. This is because Model.objects.filter().update() is atomic, and the contents of Results are hit by only 1-thread at a time, and Profile/Machine's updates do not matter.

Resolves #144 and then some.
This commit is contained in:
Andrew Grant authored and GitHub committed 2023-08-16 08:02:56 -04:00
1 parent 3b4103baf7
commit d32761c53c
3 files changed
+256 -108

No files matched your search

+206 -63
View File
@@ -26,10 +26,12 @@ import multiprocessing
import os import os
import platform import platform
import psutil import psutil
import queue
import re import re
import requests import requests
import shutil import shutil
import sys import sys
import threading
import time import time
import traceback import traceback
import uuid import uuid
@@ -44,7 +46,7 @@ from concurrent.futures import ThreadPoolExecutor
TIMEOUT_HTTP = 30 # Timeout in seconds for HTTP requests TIMEOUT_HTTP = 30 # Timeout in seconds for HTTP requests
TIMEOUT_ERROR = 10 # Timeout in seconds when any errors are thrown TIMEOUT_ERROR = 10 # Timeout in seconds when any errors are thrown
TIMEOUT_WORKLOAD = 30 # Timeout in seconds between workload requests TIMEOUT_WORKLOAD = 30 # Timeout in seconds between workload requests
CLIENT_VERSION = '11' # Client version to send to the Server CLIENT_VERSION = '12' # Client version to send to the Server
IS_WINDOWS = platform.system() == 'Windows' # Don't touch this IS_WINDOWS = platform.system() == 'Windows' # Don't touch this
IS_LINUX = platform.system() != 'Windows' # Don't touch this IS_LINUX = platform.system() != 'Windows' # Don't touch this
@@ -344,20 +346,34 @@ class ServerReporter(object):
return ServerReporter.report(config, 'clientWrongBench', payload) return ServerReporter.report(config, 'clientWrongBench', payload)
@staticmethod @staticmethod
def report_results(config, stats): def report_results(config, batches):
wins, losses, draws, crashes, timelosses = stats
payload = { payload = {
'test_id' : config.workload['test']['id'], 'test_id' : config.workload['test']['id'],
'result_id' : config.workload['result']['id'], 'result_id' : config.workload['result']['id'],
'wins' : wins,
'losses' : losses, 'trinomial' : [0, 0, 0], # LDW
'draws' : draws, 'pentanomial' : [0, 0, 0, 0, 0], # LL DL DD DW WW
'crashes' : crashes,
'timeloss' : timelosses, 'crashes' : 0, # " disconnect" or "connection stalls"
'timelosses' : 0, # " loses on time "
'illegals' : 0, # " illegal move "
} }
for batch in batches:
payload['trinomial' ] = [x+y for x,y in zip(payload['trinomial' ], batch['trinomial' ])]
payload['pentanomial'] = [x+y for x,y in zip(payload['pentanomial'], batch['pentanomial'])]
payload['crashes' ] += batch['crashes' ]
payload['timelosses'] += batch['timelosses']
payload['illegals' ] += batch['illegals' ]
# Collapse into a JSON friendly format for Django
payload['trinomial' ] = ' '.join(map(str, payload['trinomial' ]))
payload['pentanomial'] = ' '.join(map(str, payload['pentanomial']))
return ServerReporter.report(config, 'clientSubmitResults', payload) return ServerReporter.report(config, 'clientSubmitResults', payload)
class Cutechess(object): class Cutechess(object):
@@ -486,6 +502,123 @@ class Cutechess(object):
# Tack the socket number onto the end to distinguish the PGNs # Tack the socket number onto the end to distinguish the PGNs
return '-pgnout PGNs/%s_vs_%s.%d' % (dev_name, base_name, socket) return '-pgnout PGNs/%s_vs_%s.%d' % (dev_name, base_name, socket)
@staticmethod
def update_results(results, line):
# Given any game #, find the other in the pair
def game_to_pair(g):
return (g, g+1) if g % 2 else (g-1, g)
# Find the Pentanomial index given a game pair
def pair_to_penta(r1, r2):
lookup = { '0-1' : 0, '1/2-1/2' : 1, '1-0' : 2 }
return lookup[r1] + 2 - lookup[r2]
# Find the Trinomial indices, from our POV, for a give game pair
def pair_to_trinomial(r1, r2):
lookup = { '0-1' : 0, '1/2-1/2' : 1, '1-0' : 2 }
return lookup[r1], 2 - lookup[r2]
# Extract the game # and result str from a Cutechess line
def parse_finished_game(line):
tokens = line.split()
return int(tokens[2]), tokens[6]
# Parse for errors resulting in adjudication
reason = line.split(':')[1]
results['crashes' ] += 'disconnect' in reason or 'stalls' in reason
results['timelosses'] += 'on time' in reason
results['illegals' ] += 'illegal' in reason
# Parse Game # and result, and save
game, result = parse_finished_game(line)
results['games'][game] = result
# Check to see if the Pair has finished
first, second = game_to_pair(game)
if first not in results['games'] or second not in results['games']:
return
# Get the indices for the Pentanomial, and the two for Trinomial
p = pair_to_penta(results['games'][first], results['games'][second])
t1, t2 = pair_to_trinomial(results['games'][first], results['games'][second])
# Update everything
results['trinomial' ][t1] += 1
results['trinomial' ][t2] += 1
results['pentanomial'][p ] += 1
# Clean up results['games']
del results['games'][first]
del results['games'][second]
class ResultsReporter(object):
def __init__(self, config, tasks, results_queue, abort_flag):
self.config = config
self.tasks = tasks
self.results_queue = results_queue
self.abort_flag = abort_flag
def process_until_finished(self):
self.last_report = 0
self.pending = []
# Collect results until all Tasks are done
while any(not task.done() for task in self.tasks):
if (result := self.get_next_result()):
self.pending.append(result)
# Send results every 30 seconds, until all Tasks are done
if self.send_results(report_interval=30):
return
# Kill everything if openbench.exit is created
if os.path.isfile('openbench.exit'):
return self.abort_flag.set()
# Exhaust the Results Queue completely since Tasks are done
while (result := self.get_next_result()):
self.pending.append(result)
# Send any remaining results immediately
self.send_results(report_interval=0)
def get_next_result(self):
try: return self.results_queue.get(timeout=5)
except queue.Empty: return None
def send_results(self, report_interval):
# Nothing to send, or we are sending too frequently
if not self.pending or self.last_report + report_interval > time.time():
return False
# Most recent time we sent a report is now
self.last_report = time.time()
try:
# Send all of the queued Results at once
response = ServerReporter.report_results(self.config, self.pending)
# Log, and then clear pending queue
for result in self.pending:
print (result)
self.pending = []
# If the test ended, kill all tasks
if 'stop' in response.json():
self.abort_flag.set()
# Signal an exit if the test ended
return 'stop' in response.json()
except Exception:
traceback.print_exc()
print ('[Note] Failed to upload results to server...')
def get_version(program): def get_version(program):
@@ -896,20 +1029,29 @@ def complete_workload(config):
# Launch and manage all of the Cutechess workers # Launch and manage all of the Cutechess workers
with ThreadPoolExecutor(max_workers=config.sockets) as executor: with ThreadPoolExecutor(max_workers=config.sockets) as executor:
results = multiprocessing.Queue()
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(config.sockets):
cmd = build_cutechess_command(config, dev_name, base_name, avg_factor, x) cmd = build_cutechess_command(config, dev_name, base_name, avg_factor, x)
tasks.append(executor.submit(run_and_parse_cutechess, config, cmd, x)) tasks.append(executor.submit(run_and_parse_cutechess, config, cmd, x, results, abort_flag))
# Await the completion of all Cutechess workers # Process the Queue until we exit, finish, or are told to stop by the server
try: try:
for task in tasks: rr = ResultsReporter(config, tasks, results, abort_flag)
task.result() rr.process_until_finished()
# Kill everything during an Keyboard Interrupt # Kill everything during an Exception, but print it
except Exception:
traceback.print_exc()
abort_flag.set()
raise
# Kill everything during a Keyboard Interrupt
except KeyboardInterrupt: except KeyboardInterrupt:
for task in tasks: task.cancel() abort_flag.set()
raise KeyboardInterrupt raise
def download_opening_book(config): def download_opening_book(config):
@@ -1070,11 +1212,19 @@ def run_benchmarks(config, branch, engine, network):
private = config.workload['test'][branch]['private'] private = config.workload['test'][branch]['private']
print('\nRunning %dx Benchmarks for %s' % (config.threads, name)) print('\nRunning %dx Benchmarks for %s' % (config.threads, name))
# Execute a benchmark on each of the Threads
for ii in range(config.threads):
args = [os.path.join('Engines', engine), queue] args = [os.path.join('Engines', engine), queue]
if private and network: args.append(network) if private and network:
multiprocessing.Process(target=run_bench, args=args).start() args.append(network)
# Run the benchmark on all threads we are using
workers = [
multiprocessing.Process(target=run_bench, args=args)
for ii in range(config.threads)
]
# Start and wait for each worker to finish
for worker in workers: worker.start()
for worker in workers: worker.join()
# Collect all bench and nps values, and set bench to 0 if any vary # Collect all bench and nps values, and set bench to 0 if any vary
bench, nps = list(zip(*[queue.get() for ii in range(config.threads)])) bench, nps = list(zip(*[queue.get() for ii in range(config.threads)]))
@@ -1104,64 +1254,57 @@ def build_cutechess_command(config, dev_cmd, base_cmd, scale_factor, socket):
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): def run_and_parse_cutechess(config, command, socket, results_queue, abort_flag):
print('\n[#%d] Launching Cutechess...\n%s\n' % (socket, command)) print('\n[#%d] Launching Cutechess...\n%s\n' % (socket, command))
cutechess = Popen(command.split(), stdout=PIPE) cutechess = Popen(command.split(), stdout=PIPE)
crashes = timelosses = 0 results = {
score = [0, 0, 0]; sent = [0, 0, 0] # WLD
errors = ['on time', 'disconnects', 'connection stalls', 'illegal']
while True: 'trinomial' : [0, 0, 0], # LDW
'pentanomial' : [0, 0, 0, 0, 0], # LL DL DD DW WW
'games' : {}, # game_id : result_str
# Read each line of output until the pipe closes 'crashes' : 0, # " disconnect" or "connection stalls"
line = cutechess.stdout.readline().strip().decode('ascii') 'timelosses' : 0, # " loses on time "
if line != '': print('[#%d] %s' % (socket, line)) 'illegals' : 0, # " illegal move "
else: cutechess.wait(); return }
# Real updates contain a colon # Read each line of output until the pipe closes and we get "" back
if ':' not in line: continue while (line := cutechess.stdout.readline().strip().decode('ascii')):
# Parse for crashes and timelosses if abort_flag.is_set():
score_reason = line.split(':')[1] return kill_cutechess(cutechess)
timelosses += 'on time' in score_reason
crashes += 'disconnects' in score_reason
crashes += 'connection stalls' in score_reason
# Forcefully report any engine failures to the server if 'Started game' not in line and 'Score of' not in line:
for error in errors: print('[#%d] %s' % (socket, line))
if error in score_reason:
# pgn = find_pgn_error(score_reason, command)
ServerReporter.report_engine_error(config, line, "")
# All remaining processing is for score updates only if 'Finished game' in line:
if not line.startswith('Score of'): Cutechess.update_results(results, line)
continue
# Only report scores after every eight games # Report results at the end, or once hitting the report_rate
score = list(map(int, score_reason.split()[0:5:2])) report = 'Elo difference' in line
if ((sum(score) - sum(sent)) % config.workload['test']['report_rate'] != 0): report = report or sum(results['pentanomial']) == config.workload['test']['report_rate']
continue
try: if report:
# Report new results to the server
wld = [score[ii] - sent[ii] for ii in range(3)]
stats = wld + [crashes, timelosses]
status = ServerReporter.report_results(config, stats).json()
# Reset the reporting since this report was a success # Place the results into the Queue, and be sure to copy the lists
crashes = timelosses = 0 results_queue.put({
sent = score[::] 'trinomial' : list(results['trinomial']),
'pentanomial' : list(results['pentanomial']),
'crashes' : results['crashes'],
'timelosses' : results['timelosses'],
'illegals' : results['illegals'],
})
except: # Clear out all the results, so we can start collecting a new set
# Failed to connect, but we can delay the reports until later results['trinomial' ] = [0, 0, 0]
print('[NOTE] Unable To Reach Server'); results['pentanomial'] = [0, 0, 0, 0, 0]
results['crashes' ] = 0
results['timelosses' ] = 0
results['illegals' ] = 0
# Check for openbench.exit, or server instructing us to exit cutechess.wait() # Gracefully exit
if os.path.isfile('openbench.exit') or 'stop' in status:
kill_cutechess(cutechess)
return
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # #
+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' : '11', 'client_version' : '12',
# Generic Error Messages useful to those setting up their own instance # Generic Error Messages useful to those setting up their own instance
'error' : { 'error' : {
+49 -44
View File
@@ -30,6 +30,7 @@ import requests
from django.contrib.auth import authenticate from django.contrib.auth import authenticate
from django.core.files.base import ContentFile from django.core.files.base import ContentFile
from django.core.files.storage import FileSystemStorage from django.core.files.storage import FileSystemStorage
from django.db import transaction
from django.db.models import F from django.db.models import F
from django.http import FileResponse from django.http import FileResponse
from django.utils import timezone from django.utils import timezone
@@ -816,71 +817,75 @@ def workload_to_dictionary(test, result):
def update_test(request, machine): def update_test(request, machine):
# New results from the Worker # Extract error information
wins = int(request.POST['wins' ])
losses = int(request.POST['losses' ])
draws = int(request.POST['draws' ])
crashes = int(request.POST['crashes' ]) crashes = int(request.POST['crashes' ])
timeloss = int(request.POST['timeloss']) timelosses = int(request.POST['timelosses'])
games = wins + losses + draws illegals = int(request.POST['illegals' ])
has_error = crashes or timelosses or illegals
# Worker knows where to save the results # Extract Database information
machineid = int(request.POST['machine_id']) machine_id = int(request.POST['machine_id'])
resultid = int(request.POST['result_id' ]) result_id = int(request.POST['result_id' ])
testid = int(request.POST['test_id' ]) test_id = int(request.POST['test_id' ])
# Prevent updating a finished test # Trinomial Implementation
test = Test.objects.get(id=testid) losses, draws, wins = map(int, request.POST['trinomial'].split())
games = losses + draws + wins
# Pentanomial Implementation
# ll, dl, dd, dw, ww = map(int, request.POST['pentanomial'].split())
# games = ll + dl + dd + dw + ww
with transaction.atomic():
test = Test.objects.get(id=test_id)
if test.finished or test.deleted: if test.finished or test.deleted:
return { 'stop' : True } return { 'stop' : True }
# Tally up the updated WLD stats test.losses += losses
swins = test.wins + wins test.draws += draws
slosses = test.losses + losses test.wins += wins
sdraws = test.draws + draws test.games += games
sgames = swins + slosses + sdraws
test.error = test.error or has_error
if test.test_mode == 'SPRT': if test.test_mode == 'SPRT':
# Compute a new LLR for the updated results # Compute a new LLR for the updated results
WLD = (swins, slosses, sdraws) WLD = (test.wins, test.losses, test.draws)
sprt = SPRT(*WLD, test.elolower, test.eloupper) test.sprt = SPRT(*WLD, test.elolower, test.eloupper)
# Check for H0 or H1 being accepted # Check for H0 or H1 being accepted
passed = sprt > test.upperllr test.passed = sprt > test.upperllr
failed = sprt < test.lowerllr test.failed = sprt < test.lowerllr
finished = passed or failed test.finished = passed or failed
if test.test_mode == 'GAMES': elif test.test_mode == 'GAMES':
# Finish test once we've played the proper amount of games # Finish test once we've played the proper amount of games
passed = sgames >= test.max_games and swins >= slosses test.passed = test.games >= test.max_games and test.wins >= test.losses
failed = sgames >= test.max_games and swins < slosses test.failed = test.games >= test.max_games and test.wins < test.losses
finished = passed or failed test.finished = test.passed or test.failed
sprt = 0.0 # Hack to "update" the currentllr
# Update total games played by the Player test.save()
Profile.objects.filter(user=machine.user).update(games=F('games') + games)
Profile.objects.get(user=machine.user).save()
# Update the datetime in the Machine # Update Result object; No risk from concurrent access
machine.save() Result.objects.filter(id=result_id).update(
# Update individual Result entry for the Player
Result.objects.filter(id=resultid).update(
games = F('games') + games, wins = F('wins' ) + wins, games = F('games') + games, wins = F('wins' ) + wins,
losses = F('losses') + losses, draws = F('draws' ) + draws, losses = F('losses') + losses, draws = F('draws' ) + draws,
crashes = F('crashes') + crashes, timeloss = F('timeloss') + timeloss, crashes = F('crashes') + crashes, timeloss = F('timeloss') + timelosses,
updated=timezone.now()
) )
# Update the overall test with the new data # Update Profile object; No risk from concurrent access
Test.objects.filter(id=testid).update( Profile.objects.filter(user=Machine.objects.get(id=machine_id).user).update(
games = F('games' ) + games, wins = F('wins' ) + wins, games=F('games') + games,
losses = F('losses') + losses, draws = F('draws') + draws, updated=timezone.now()
currentllr=sprt, passed=passed, failed=failed, finished=finished,
) )
# Force a refresh of the updated field when finished # Update Machine object; No risk from concurrent access
if finished: Test.objects.get(id=testid).save() Machine.objects.filter(id=machine_id).update(
updated=timezone.now()
)
return [{}, {'stop' : True}][finished] return [{}, { 'stop' : True }][test.finished]