More client work .. reports wrong benches.
Just need report NPS after running benches Just need report Results after games
This commit is contained in:
1 parent
009424b616
commit
dcce521447
6 files changed
+234
-212
No files matched your search
+201
-201
@@ -3,402 +3,402 @@ import shutil, subprocess, requests, zipfile, os, math, json
|
|||||||
|
|
||||||
# Argument Parsing ... <Server> <Threads> <?Compiler> <?UsePGO>
|
# Argument Parsing ... <Server> <Threads> <?Compiler> <?UsePGO>
|
||||||
parser = argparse.ArgumentParser()
|
parser = argparse.ArgumentParser()
|
||||||
parser.add_argument("-U", "--username", help="Username", required=True)
|
parser.add_argument('-U', '--username', help='Username', required=True)
|
||||||
parser.add_argument("-P", "--password", help="Password", required=True)
|
parser.add_argument('-P', '--password', help='Password', required=True)
|
||||||
parser.add_argument("-E", "--server", help="Server Address", required=True)
|
parser.add_argument('-E', '--server', help='Server Address', required=True)
|
||||||
parser.add_argument("-T", "--threads", help="# of Threads", required=True)
|
parser.add_argument('-T', '--threads', help='# of Threads', required=True)
|
||||||
parser.add_argument("-C", "--compiler", help="Compiler Name", required=True)
|
parser.add_argument('-C', '--compiler', help='Compiler Name', required=True)
|
||||||
parser.add_argument("-O", "--profile", help="Use PGO Builds", required=False, default=False)
|
parser.add_argument('-O', '--profile', help='Use PGO Builds', required=False, default=False)
|
||||||
arguments = parser.parse_args()
|
arguments = parser.parse_args()
|
||||||
|
|
||||||
# Client Parameters
|
# Client Parameters
|
||||||
USERNAME = arguments.username
|
USERNAME = arguments.username
|
||||||
PASSWORD = arguments.password
|
PASSWORD = arguments.password
|
||||||
SERVER = arguments.server
|
SERVER = arguments.server
|
||||||
THREADS = arguments.threads
|
THREADS = int(arguments.threads)
|
||||||
COMPILER = arguments.compiler
|
COMPILER = arguments.compiler
|
||||||
PROFILE = arguments.profile
|
PROFILE = arguments.profile
|
||||||
|
|
||||||
# Windows treated seperatly from Linux
|
# Windows treated seperatly from Linux
|
||||||
IS_WINDOWS = platform.system() == "Windows"
|
IS_WINDOWS = platform.system() == 'Windows'
|
||||||
|
|
||||||
# Server wants to identify different machines
|
# Server wants to identify different machines
|
||||||
OS_NAME = platform.system() + " " + platform.release()
|
OS_NAME = platform.system() + ' ' + platform.release()
|
||||||
|
|
||||||
# Server tracks machines by IDs, which are saved
|
# Server tracks machines by IDs, which are saved
|
||||||
# locally once assigned. Regesitering a machine is
|
# locally once assigned. Regesitering a machine is
|
||||||
# not a problem, but creates junk in the database
|
# not a problem, but creates junk in the database
|
||||||
try:
|
try:
|
||||||
with open("machine.txt") as fin:
|
with open('machine.txt') as fin:
|
||||||
MACHINE_ID = int(fin.readlines()[0])
|
MACHINE_ID = int(fin.readlines()[0])
|
||||||
except:
|
except:
|
||||||
MACHINE_ID = None
|
MACHINE_ID = None
|
||||||
print("<Warning> Machine unregistered, will register with Server")
|
print('<Warning> Machine unregistered, will register with Server')
|
||||||
|
|
||||||
# Run from any location ...
|
# Run from any location ...
|
||||||
os.chdir(os.path.dirname(os.path.abspath(__file__)))
|
os.chdir(os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
|
||||||
def killProcess(process):
|
def killProcess(process):
|
||||||
if IS_WINDOWS:
|
if not IS_WINDOWS : os.system('pkill -TERM -P {0}'.format(process.pid))
|
||||||
subprocess.call(['taskkill', '/F', '/T', '/PID', str(process.pid)])
|
else : subprocess.call(['taskkill', '/F', '/T', '/PID', str(process.pid)])
|
||||||
else:
|
|
||||||
os.system("pkill -TERM -P {0}".format(process.pid))
|
|
||||||
|
|
||||||
def getNameAsExe(program):
|
def getNameAsExe(program):
|
||||||
if IS_WINDOWS: return program + ".exe"
|
if IS_WINDOWS: return program + '.exe'
|
||||||
return program
|
return program
|
||||||
|
|
||||||
def getFile(source, savedname):
|
def getFile(source, outname):
|
||||||
|
|
||||||
# Read a file from the given source and save it locally
|
# Read a file from the given source and save it locally
|
||||||
request = requests.get(url=source, stream=True)
|
request = requests.get(url=source, stream=True)
|
||||||
with open(savedname, "wb") as fout:
|
with open(outname, 'wb') as fout:
|
||||||
for chunk in request.iter_content(chunk_size=1024):
|
for chunk in request.iter_content(chunk_size=1024):
|
||||||
if chunk: fout.write(chunk)
|
if chunk: fout.write(chunk)
|
||||||
fout.flush()
|
fout.flush()
|
||||||
|
|
||||||
def getCoreFiles(server):
|
def getCoreFiles():
|
||||||
|
|
||||||
# Ask the server where the core files are saved
|
# Ask the server where the core files are saved
|
||||||
request = requests.get(server + "/getFiles/")
|
request = requests.get(SERVER + '/getFiles/')
|
||||||
location = request.content.decode("utf-8")
|
location = request.content.decode('utf-8')
|
||||||
|
|
||||||
# Download the proper cutechess program, and a dll if needed
|
# Download the proper cutechess program, and a dll if needed
|
||||||
if IS_WINDOWS:
|
if IS_WINDOWS:
|
||||||
if not os.path.isfile("cutechess.exe"):
|
if not os.path.isfile('cutechess.exe'):
|
||||||
getFile(location + "cutechess-windows.exe", "cutechess.exe")
|
getFile(location + 'cutechess-windows.exe', 'cutechess.exe')
|
||||||
if not os.path.isfile("Qt5Core.dll"):
|
if not os.path.isfile('Qt5Core.dll'):
|
||||||
getFile(location +"cutechess-qt5core.dll", "Qt5Core.dll")
|
getFile(location +'cutechess-qt5core.dll', 'Qt5Core.dll')
|
||||||
else:
|
else:
|
||||||
if not os.path.isfile("cutechess"):
|
if not os.path.isfile('cutechess'):
|
||||||
getFile(location + "cutechess-linux", "cutechess")
|
getFile(location + 'cutechess-linux', 'cutechess')
|
||||||
os.system("chmod 777 cutechess")
|
os.system('chmod 777 cutechess')
|
||||||
|
|
||||||
def getEngine(data):
|
def getEngine(data):
|
||||||
|
|
||||||
isCandidate = "sha" in data
|
name = data['sha']
|
||||||
|
source = data['source']
|
||||||
if isCandidate:
|
|
||||||
name = data["sha"]
|
|
||||||
source = data["source"]
|
|
||||||
exe = getNameAsExe(name)
|
|
||||||
unzipname = source.split("/")[-3] + "-" + source.split("/")[-1].replace(".zip", "")
|
|
||||||
|
|
||||||
else:
|
|
||||||
name = unzipname = data["name"]
|
|
||||||
source = data["source"] + name + ".zip"
|
|
||||||
exe = getNameAsExe(name)
|
exe = getNameAsExe(name)
|
||||||
|
unzipname = source.split('/')[-3] + '-' + source.split('/')[-1].replace('.zip', '')
|
||||||
|
|
||||||
# Don't redownload an engine we already have
|
# Don't redownload an engine we already have
|
||||||
if os.path.isfile("Engines/" + exe):
|
if os.path.isfile('Engines/' + exe):
|
||||||
return
|
return
|
||||||
|
|
||||||
# Log the fact that we are downloading a new engine
|
# Log the fact that we are downloading a new engine
|
||||||
print("\nEngine :", data["name"])
|
print('\nEngine :', data['name'])
|
||||||
print( "Commit :", data["sha"])
|
print( 'Commit :', data['sha'])
|
||||||
print( "Source :", source)
|
print( 'Source :', source)
|
||||||
|
|
||||||
# Extract and delete the zip file
|
# Extract and delete the zip file
|
||||||
getFile(source, name + ".zip")
|
getFile(source, name + '.zip')
|
||||||
with zipfile.ZipFile(name + ".zip") as data:
|
with zipfile.ZipFile(name + '.zip') as data:
|
||||||
data.extractall("tmp")
|
data.extractall('tmp')
|
||||||
os.remove(name + ".zip")
|
os.remove(name + '.zip')
|
||||||
|
|
||||||
# Build Engine using provided gcc and PGO flags
|
# Build Engine using provided gcc and PGO flags
|
||||||
buildEngine(exe, unzipname)
|
buildEngine(exe, unzipname)
|
||||||
|
|
||||||
# Create the Engines directory if it does not exist
|
# Create the Engines directory if it does not exist
|
||||||
if not os.path.isdir("Engines"):
|
if not os.path.isdir('Engines'):
|
||||||
os.mkdir("Engines")
|
os.mkdir('Engines')
|
||||||
|
|
||||||
# Move the compiled engine
|
# Move the compiled engine
|
||||||
if os.path.isfile("tmp/{0}/src/{1}".format(unzipname, exe)):
|
if os.path.isfile('tmp/{0}/src/{1}'.format(unzipname, exe)):
|
||||||
os.rename("tmp/{0}/src/{1}".format(unzipname, exe), "Engines/{0}".format(exe))
|
os.rename('tmp/{0}/src/{1}'.format(unzipname, exe), 'Engines/{0}'.format(exe))
|
||||||
|
|
||||||
elif os.path.isfile("tmp/{0}/src/{1}".format(unzipname, name)):
|
elif os.path.isfile('tmp/{0}/src/{1}'.format(unzipname, name)):
|
||||||
os.rename("tmp/{0}/src/{1}".format(unzipname, name), "Engines/{0}".format(exe))
|
os.rename('tmp/{0}/src/{1}'.format(unzipname, name), 'Engines/{0}'.format(exe))
|
||||||
|
|
||||||
# Cleanup the unzipped zip file
|
# Cleanup the unzipped zip file
|
||||||
shutil.rmtree("tmp")
|
shutil.rmtree('tmp')
|
||||||
|
|
||||||
def buildEngine(exe, unzipname):
|
def buildEngine(exe, unzipname):
|
||||||
|
|
||||||
# Build a standard non-PGO binary
|
# Build a standard non-PGO binary
|
||||||
if not USE_PROFILE:
|
if not PROFILE:
|
||||||
subprocess.Popen(
|
subprocess.Popen(
|
||||||
['make', 'CC={0}'.format(GCC_VERSION), 'EXE={0}'.format(exe)],
|
['make', 'CC={0}'.format(COMPILER), 'EXE={0}'.format(exe)],
|
||||||
cwd="tmp/{0}/src/".format(unzipname)).wait()
|
cwd='tmp/{0}/src/'.format(unzipname)).wait()
|
||||||
return
|
return
|
||||||
|
|
||||||
# Build a profiled binary
|
# Build a profiled binary
|
||||||
subprocess.Popen(
|
subprocess.Popen(
|
||||||
['make', 'CC={0} -fprofile-generate'.format(GCC_VERSION), 'EXE={0}'.format(exe)],
|
['make', 'CC={0} -fprofile-generate'.format(COMPILER), 'EXE={0}'.format(exe)],
|
||||||
cwd="tmp/{0}/src/".format(unzipname)).wait()
|
cwd='tmp/{0}/src/'.format(unzipname)).wait()
|
||||||
|
|
||||||
# Run a bench to generate profiler data
|
# Run a bench to generate profiler data
|
||||||
subprocess.Popen(
|
subprocess.Popen(
|
||||||
["tmp/{0}/src/{1}".format(unzipname, exe), "bench"],
|
['tmp/{0}/src/{1}'.format(unzipname, exe), 'bench'],
|
||||||
stdin=subprocess.PIPE,
|
stdin=subprocess.PIPE,
|
||||||
universal_newlines=True
|
universal_newlines=True
|
||||||
).wait()
|
).wait()
|
||||||
|
|
||||||
# Build the final binary using the PGO data
|
# Build the final binary using the PGO data
|
||||||
subprocess.Popen(
|
subprocess.Popen(
|
||||||
['make', 'CC={0} -fprofile-use'.format(GCC_VERSION), 'EXE={0}'.format(exe)],
|
['make', 'CC={0} -fprofile-use'.format(COMPILER), 'EXE={0}'.format(exe)],
|
||||||
cwd="tmp/{0}/src".format(unzipname)).wait()
|
cwd='tmp/{0}/src'.format(unzipname)).wait()
|
||||||
|
|
||||||
def getCutechessCommand(cores, data, scalefactor):
|
def getCutechessCommand(data, scalefactor):
|
||||||
|
|
||||||
if IS_WINDOWS: exe = "cutechess.exe"
|
if IS_WINDOWS: exe = 'cutechess.exe'
|
||||||
else: exe = "./cutechess"
|
else: exe = './cutechess'
|
||||||
|
|
||||||
timecontrol = data["enginetest"]["timecontrol"]
|
timecontrol = data['test']['timecontrol']
|
||||||
|
|
||||||
# Parse X / Y + Z time controls
|
# Parse X / Y + Z time controls
|
||||||
if "/" in timecontrol and "+" in timecontrol:
|
if '/' in timecontrol and '+' in timecontrol:
|
||||||
moves = timecontrol.split("/")[0]
|
moves = timecontrol.split('/')[0]
|
||||||
start, inc = map(float, timecontrol.split("/")[1].split("+"))
|
start, inc = map(float, timecontrol.split('/')[1].split('+'))
|
||||||
start = round(start * scalefactor, 2)
|
start = round(start * scalefactor, 2)
|
||||||
inc = round(inc * scalefactor, 2)
|
inc = round(inc * scalefactor, 2)
|
||||||
tc = moves + "/" + str(start) + "+" + str(inc)
|
tc = moves + '/' + str(start) + '+' + str(inc)
|
||||||
|
|
||||||
# Parse X / Y time controls
|
# Parse X / Y time controls
|
||||||
elif "/" in timecontrol:
|
elif '/' in timecontrol:
|
||||||
|
moves = timecontrol.split('/')[0]
|
||||||
moves = timecontrol.split("/")[0]
|
start = float(timecontrol.split('/')[1])
|
||||||
start = float(timecontrol.split("/")[1])
|
|
||||||
start = round(start * scalefactor, 2)
|
start = round(start * scalefactor, 2)
|
||||||
tc = moves + "/" + str(start)
|
tc = moves + '/' + str(start)
|
||||||
|
|
||||||
# Parse X + Z time controls
|
# Parse X + Z time controls
|
||||||
else:
|
else:
|
||||||
start, inc = map(float, timecontrol.split("+"))
|
start, inc = map(float, timecontrol.split('+'))
|
||||||
start = round(start * scalefactor, 2)
|
start = round(start * scalefactor, 2)
|
||||||
inc = round(inc * scalefactor, 2)
|
inc = round(inc * scalefactor, 2)
|
||||||
tc = str(start) + "+" + str(inc)
|
tc = str(start) + '+' + str(inc)
|
||||||
|
|
||||||
print ("ORIGINAL :", timecontrol)
|
# Find Threads for the Dev Engine
|
||||||
print ("SCALED :", tc)
|
tokens = data['test']['dev']['options'].split(' ')
|
||||||
print ("")
|
devthreads = tokens[0].split('=')[1]
|
||||||
|
|
||||||
|
# Find Threads for the Base Engine
|
||||||
|
tokens = data['test']['base']['options'].split(' ')
|
||||||
|
basethreads = tokens[0].split('=')[1]
|
||||||
|
|
||||||
|
# Finally, output the time control for the user
|
||||||
|
print ('ORIGINAL :\n', data['test']['timecontrol']),
|
||||||
|
print ('SCALED :\n', timecontrol)
|
||||||
|
|
||||||
generalFlags = (
|
generalFlags = (
|
||||||
"-repeat"
|
'-repeat'
|
||||||
" -srand " + str(int(time.time())) +
|
' -srand ' + str(int(time.time())) +
|
||||||
" -resign movecount=3 score=400"
|
' -resign movecount=3 score=400'
|
||||||
" -draw movenumber=40 movecount=8 score=10"
|
' -draw movenumber=40 movecount=8 score=10'
|
||||||
" -concurrency " + str(floor(cores / data["enginetest"]["threads"])) +
|
' -concurrency ' + str(floor(THREADS / max(devthreads, basethreads))) +
|
||||||
" -games 1000"
|
' -games 1000'
|
||||||
" -recover"
|
' -recover'
|
||||||
" -wait 10"
|
' -wait 10'
|
||||||
)
|
)
|
||||||
|
|
||||||
candidateflags = (
|
devflags = (
|
||||||
"-engine"
|
'-engine'
|
||||||
" cmd=Engines/" + getNameAsExe(data["enginetest"]["test"]["sha"]) +
|
' cmd=Engines/' + getNameAsExe(data['test']['dev']['sha']) +
|
||||||
" proto=uci" +
|
' proto=' + data['test']['dev']['protocol'] +
|
||||||
" tc=" + tc +
|
' tc=' + timecontrol + devoptions
|
||||||
" option.Hash=" + str(data["enginetest"]["hashsize"]) +
|
|
||||||
" option.Threads=" + str(data["enginetest"]["threads"])
|
|
||||||
)
|
)
|
||||||
|
|
||||||
opponentflags = (
|
baseflags = (
|
||||||
"-engine"
|
'-engine'
|
||||||
" cmd=Engines/" + getNameAsExe(data["enginetest"]["base"]["sha"]) +
|
' cmd=Engines/' + getNameAsExe(data['test']['base']['sha']) +
|
||||||
" proto=uci" +
|
' proto=' + data['test']['base']['protocol'] +
|
||||||
" tc=" + tc +
|
' tc=' + timecontrol + baseoptions
|
||||||
" option.Hash=" + str(data["enginetest"]["hashsize"]) +
|
|
||||||
" option.Threads=" + str(data["enginetest"]["threads"])
|
|
||||||
)
|
)
|
||||||
|
|
||||||
bookflags = (
|
bookflags = (
|
||||||
"-openings"
|
'-openings'
|
||||||
" file=book.pgn"
|
' file=' + data['test']['bookname'] +
|
||||||
" format=pgn"
|
' format=pgn'
|
||||||
" order=random"
|
' order=random'
|
||||||
" plies=16"
|
' plies=16'
|
||||||
)
|
)
|
||||||
|
|
||||||
return " ".join([exe, generalFlags, candidateflags, opponentflags, bookflags])
|
return ' '.join([exe, generalFlags, devflags, baseflags, bookflags])
|
||||||
|
|
||||||
def singleCoreBench(name, outqueue):
|
def singleCoreBench(name, outqueue):
|
||||||
|
|
||||||
# Format file path because of Windows ....
|
# Format file path because of Windows ....
|
||||||
dir = os.path.join("Engines", getNameAsExe(name))
|
dir = os.path.join('Engines', getNameAsExe(name))
|
||||||
|
|
||||||
# Last two lines should hold node count and NPS
|
# Last two lines should hold node count and NPS
|
||||||
data = os.popen("{0} bench 13 |tail -2".format(dir)).read()
|
data = os.popen('{0} bench 13 |tail -2'.format(dir)).read()
|
||||||
data = data.strip().split("\n")
|
data = data.strip().split('\n')
|
||||||
|
|
||||||
# Parse and dump results into queue
|
# Parse and dump results into queue
|
||||||
bench = int(data[0].split(":")[1])
|
bench = int(data[0].split(':')[1])
|
||||||
nps = int(data[1].split(":")[1])
|
nps = int(data[1].split(':')[1])
|
||||||
outqueue.put((bench, nps))
|
outqueue.put((bench, nps))
|
||||||
|
|
||||||
def getBenchSignature(engine, cores):
|
def getBenchSignature(engine):
|
||||||
|
|
||||||
print ("Running Benchmark for {0} on {1} cores".format(engine["name"], cores))
|
print ('Running Benchmark for {0} on {1} cores'.format(engine['name'], THREADS))
|
||||||
|
|
||||||
# Allow each process to send back completition times
|
# Allow each process to send back completition times
|
||||||
outqueue = multiprocessing.Queue()
|
outqueue = multiprocessing.Queue()
|
||||||
|
|
||||||
# Launch and wait for completion of one process for each core
|
# Launch and wait for completion of one process for each core
|
||||||
processes = []
|
processes = []
|
||||||
for f in range(cores):
|
for f in range(THREADS):
|
||||||
processes.append(
|
processes.append(
|
||||||
multiprocessing.Process(
|
multiprocessing.Process(
|
||||||
target=singleCoreBench,
|
target=singleCoreBench,
|
||||||
args=(engine["sha"], outqueue,)))
|
args=(engine['sha'], outqueue,)))
|
||||||
for p in processes: p.start()
|
for p in processes: p.start()
|
||||||
for p in processes: p.join()
|
for p in processes: p.join()
|
||||||
|
|
||||||
data = [outqueue.get() for f in range(cores)]
|
# Parse data and compute average speed
|
||||||
|
data = [outqueue.get() for f in range(THREADS)]
|
||||||
bench = [f[0] for f in data]
|
bench = [f[0] for f in data]
|
||||||
nps = [f[1] for f in data]
|
nps = [f[1] for f in data]
|
||||||
avg = sum(nps) / len(nps)
|
avg = sum(nps) / len(nps)
|
||||||
|
|
||||||
|
# All benches should be the same
|
||||||
if (len(set(bench)) > 1):
|
if (len(set(bench)) > 1):
|
||||||
return (0, 0)
|
return (0, 0)
|
||||||
|
|
||||||
print ("Bench for {0} is {1}".format(engine["name"], bench[0]))
|
# Log and return computed bench and speed
|
||||||
print ("NPS for {0} is {1}\n".format(engine["name"], int(avg)))
|
print ('Bench for {0} is {1}'.format(engine['name'], bench[0]))
|
||||||
|
print ('NPS for {0} is {1}\n'.format(engine['name'], int(avg)))
|
||||||
return (bench[0], avg)
|
return (bench[0], avg)
|
||||||
|
|
||||||
def completeWorkload(server, cores, data):
|
def reportWrongBench(data, engine):
|
||||||
|
|
||||||
# Download both engines in the matchup and the root engine
|
# Server wants verification for reporting
|
||||||
getEngine(data["enginetest"]["test"])
|
postdata = {
|
||||||
getEngine(data["enginetest"]["base"])
|
'username' : USERNAME,
|
||||||
print ("")
|
'password' : PASSWORD,
|
||||||
|
'engineid' : engine['id'],
|
||||||
|
'testid' : data['test']['id']}
|
||||||
|
requests.post('{0}/wrongBench/'.format(SERVER), data=postdata)
|
||||||
|
|
||||||
# Verify the bench of the test engine
|
def reportResults(data, wins, losses, draws, crashes, timeloss):
|
||||||
testbench, testnps = getBenchSignature(data["enginetest"]["test"], cores)
|
pass
|
||||||
if testbench != int(data["enginetest"]["test"]["bench"]):
|
|
||||||
print (testbench, int(data["enginetest"]["test"]["bench"]))
|
def completeWorkload(data):
|
||||||
enginetestid = int(data["enginetest"]["id"])
|
|
||||||
requests.get(server + "/wrongbench/{0}/".format(enginetestid))
|
# Download engines and opening book
|
||||||
|
getEngine(data['test']['dev'])
|
||||||
|
getEngine(data['test']['base'])
|
||||||
|
getFile(data['test']['booksource'], data['test']['bookname'])
|
||||||
|
|
||||||
|
# Verify the bench of the dev engine
|
||||||
|
devbench, devnps = getBenchSignature(data['test']['dev'])
|
||||||
|
if devbench != int(data['test']['dev']['bench']):
|
||||||
|
print ('<ERROR> Invalid Bench. Got {0} Expected {1}'.format(
|
||||||
|
devbench, int(data['test']['dev']['bench'])))
|
||||||
|
reportWrongBench(data, data['test']['dev'])
|
||||||
return
|
return
|
||||||
|
|
||||||
# Verify the bench of the base engine
|
# Verify the bench of the base engine
|
||||||
basebench, basenps = getBenchSignature(data["enginetest"]["base"], cores)
|
basebench, basenps = getBenchSignature(data['test']['dev'])
|
||||||
if basebench != int(data["enginetest"]["base"]["bench"]):
|
if basebench != int(data['test']['dev']['bench']):
|
||||||
print (basebench, int(data["enginetest"]["base"]["bench"]))
|
print ('<ERROR> Invalid Bench. Got {0} Expected {1}'.format(
|
||||||
enginetestid = int(data["enginetest"]["id"])
|
basebench, int(data['test']['dev']['bench'])))
|
||||||
requests.get(server + "/wrongbench/{0}/".format(enginetestid))
|
reportWrongBench(data, data['test']['baes'])
|
||||||
return
|
return
|
||||||
|
|
||||||
scalefactor = 2650000 / ((testnps + basenps) / 2)
|
# Compute and report CPU scaling factor
|
||||||
print ("FACTOR : {0}".format(round(1 / scalefactor, 2)))
|
avgnps = (devnps + basenps) / 2.0
|
||||||
|
scalefactor = 2650000 / avgnps
|
||||||
|
print ('FACTOR : {0}'.format(round(1 / scalefactor, 2)))
|
||||||
|
|
||||||
command = getCutechessCommand(cores, data, scalefactor)
|
# Compute and report cutechess-cli string
|
||||||
|
command = getCutechessCommand(data, scalefactor)
|
||||||
print(command)
|
print(command)
|
||||||
|
|
||||||
|
# Spawn cutechess process
|
||||||
process = subprocess.Popen(
|
process = subprocess.Popen(
|
||||||
command,
|
command,
|
||||||
shell=not IS_WINDOWS,
|
shell=not IS_WINDOWS,
|
||||||
stdout=subprocess.PIPE
|
stdout=subprocess.PIPE
|
||||||
)
|
)
|
||||||
|
|
||||||
# Cutechess uses W / L / D
|
# Tracking results of each game
|
||||||
score = [0, 0, 0]
|
crashes = timeloss = 0
|
||||||
sent = [0, 0, 0]
|
sent = [0, 0, 0]; score = [0, 0, 0]
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
|
|
||||||
# Grab the next line of cutechess output
|
# Grab the next line of cutechess output
|
||||||
line = process.stdout.readline().strip().decode("ascii")
|
line = process.stdout.readline().strip().decode('ascii')
|
||||||
|
if line != '': print(line)
|
||||||
# Skip over empty lines
|
|
||||||
if line != "":
|
|
||||||
print(line)
|
|
||||||
|
|
||||||
# Update the current score line
|
# Update the current score line
|
||||||
if line.startswith("Score of"):
|
if line.startswith('Score of'):
|
||||||
chunks = line.split(":")
|
chunks = line.split(':')
|
||||||
chunks = chunks[1].split()
|
chunks = chunks[1].split()
|
||||||
score = list(map(int, chunks[0:5:2]))
|
score = list(map(int, chunks[0:5:2]))
|
||||||
|
|
||||||
# Search for the end of the cutechess process
|
# Search for the end of the cutechess process
|
||||||
if line.startswith("Finished match") or "Elo difference" in line:
|
if line.startswith('Finished match') or 'Elo difference' in line:
|
||||||
killProcess(process)
|
killProcess(process)
|
||||||
break
|
break
|
||||||
|
|
||||||
# Send results in sets of 25
|
# Batch result updates
|
||||||
if (sum(score) - sum(sent)) % 25 == 0 and sum(score) - sum(sent) > 0:
|
if (sum(score) - sum(sent)) % 25 == 0 and score != sent:
|
||||||
try:
|
wins = score[0] - sent[0]
|
||||||
r = requests.post(url=server+"/submitResults/", data={
|
losses = score[0] - sent[0]
|
||||||
"enginetestid" : data["enginetest"]["id"],
|
draws = score[0] - sent[0]
|
||||||
"wins" : score[0] - sent[0],
|
reportResults(data, wins, losses, draws, crashes, timeloss)
|
||||||
"draws" : score[2] - sent[2],
|
crashes = timeloss = 0
|
||||||
"losses" : score[1] - sent[1],
|
|
||||||
})
|
|
||||||
sent = score[::]
|
|
||||||
|
|
||||||
if r.text == "Stop":
|
# One final result send before we exit just in case
|
||||||
killProcess(process)
|
wins = score[0] - sent[0]
|
||||||
break
|
losses = score[0] - sent[0]
|
||||||
except: pass
|
draws = score[0] - sent[0]
|
||||||
|
reportResults(data, wins, losses, draws, crashes, timeloss)
|
||||||
|
|
||||||
# Send any leftover results before exiting
|
if __name__ == '__main__':
|
||||||
while True:
|
|
||||||
try:
|
|
||||||
requests.post(url=server+"/submitResults/", data={
|
|
||||||
"enginetestid" : data["enginetest"]["id"],
|
|
||||||
"wins" : score[0] - sent[0],
|
|
||||||
"draws" : score[2] - sent[2],
|
|
||||||
"losses" : score[1] - sent[1],
|
|
||||||
})
|
|
||||||
return
|
|
||||||
except: pass
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
|
|
||||||
# Download cutechess and any .dlls needed
|
# Download cutechess and any .dlls needed
|
||||||
getCoreFiles(SERVER)
|
getCoreFiles()
|
||||||
|
|
||||||
# Each Workload request will send this data
|
# Each Workload request will send this data
|
||||||
data = {
|
postdata = {
|
||||||
"username" : USERNAME,
|
'username' : USERNAME,
|
||||||
"password" : PASSWORD,
|
'password' : PASSWORD,
|
||||||
"threads" : THREADS,
|
'threads' : THREADS,
|
||||||
"osname" : OS_NAME,
|
'osname' : OS_NAME,
|
||||||
"machineid" : str(MACHINE_ID),
|
'machineid' : str(MACHINE_ID),
|
||||||
}
|
}
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
|
|
||||||
# Request the information for the next workload
|
# Request the information for the next workload
|
||||||
request = requests.post("{0}/getWorkload/".format(SERVER), data=data)
|
request = requests.post('{0}/getWorkload/'.format(SERVER), data=postdata)
|
||||||
|
|
||||||
# Response is a dictionary of information, "None", or an erro
|
# Response is a dictionary of information, 'None', or an erro
|
||||||
response = request.content.decode("utf-8")
|
data = request.content.decode('utf-8')
|
||||||
|
|
||||||
# Server has nothing to run, ask again later
|
# Server has nothing to run, ask again later
|
||||||
if response == "None":
|
if data == 'None':
|
||||||
print("<Warning> Server has no workloads for us")
|
print ('<Warning> Server has no workloads for us')
|
||||||
time.sleep(60)
|
time.sleep(60)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# Server was unable to authenticate us
|
# Server was unable to authenticate us
|
||||||
if response == "Bad Credentials":
|
if data == 'Bad Credentials':
|
||||||
print("<Error> Invalid Login Credentials")
|
print ('<ERROR> Invalid Login Credentials')
|
||||||
sys.exit()
|
sys.exit()
|
||||||
|
|
||||||
# Server might reject our Machine ID
|
# Server might reject our Machine ID
|
||||||
if response == "Bad Machine":
|
if data == 'Bad Machine':
|
||||||
print("<Error> Bad Machine. Delete machine.txt")
|
print ('<ERROR> Bad Machine. Delete machine.txt')
|
||||||
sys.exit()
|
sys.exit()
|
||||||
|
|
||||||
# Convert response into a data dictionary
|
# Convert response into a data dictionary
|
||||||
response = ast.literal_eval(response)
|
data = ast.literal_eval(data)
|
||||||
|
|
||||||
# Update and save our assigned machine ID
|
# Update and save our assigned machine ID
|
||||||
data["machineid"] = response["machine"]["id"]
|
postdata['machineid'] = data['machine']['id']
|
||||||
with open("machine.txt", "w") as fout:
|
with open('machine.txt', 'w') as fout:
|
||||||
fout.write(str(data["machineid"]))
|
fout.write(str(postdata['machineid']))
|
||||||
|
|
||||||
# Update machine id in case ours was bad
|
# Update machine id in case ours was bad
|
||||||
data["machineid"] = response["machine"]["id"]
|
postdata['machineid'] = data['machine']['id']
|
||||||
|
|
||||||
print (response)
|
# Try to complete the workload, rest for a few
|
||||||
|
# seconds in the event of an error, giving the
|
||||||
sys.exit(0)
|
# server time to correct the mistake ...
|
||||||
|
try: completeWorkload(data)
|
||||||
|
except Exception as error:
|
||||||
|
print ('<WARNING> {0}'.format(error))
|
||||||
|
time.sleep(15)
|
||||||
@@ -8,4 +8,3 @@ rm -rf *.fen
|
|||||||
rm -rf *.epd
|
rm -rf *.epd
|
||||||
rm -rf *.dll
|
rm -rf *.dll
|
||||||
rm -rf cutechess*
|
rm -rf cutechess*
|
||||||
rm -rf machine.txt
|
|
||||||
+1
-1
@@ -27,6 +27,6 @@ urlpatterns = [
|
|||||||
|
|
||||||
path(r'getFiles/', OpenBench.views.getFiles),
|
path(r'getFiles/', OpenBench.views.getFiles),
|
||||||
path(r'getWorkload/', OpenBench.views.getWorkload),
|
path(r'getWorkload/', OpenBench.views.getWorkload),
|
||||||
|
path(r'wrongBench/', OpenBench.views.wrongBench),
|
||||||
path(r'submitResults/', OpenBench.views.submitResults),
|
path(r'submitResults/', OpenBench.views.submitResults),
|
||||||
path(r'invalidBench/', OpenBench.views.invalidBench),
|
|
||||||
]
|
]
|
||||||
+3
-1
@@ -69,7 +69,7 @@ def newTest(request):
|
|||||||
def getEngine(name, source, protocol, sha, bench):
|
def getEngine(name, source, protocol, sha, bench):
|
||||||
|
|
||||||
# Engine may already exist, which is okay
|
# Engine may already exist, which is okay
|
||||||
try: return Engine.objects.get(sha=sha)
|
try: return Engine.objects.get(name=name, source=source, protocol=protocol, sha=sha, bench=bench)
|
||||||
except: pass
|
except: pass
|
||||||
|
|
||||||
# Build new Engine
|
# Build new Engine
|
||||||
@@ -169,6 +169,7 @@ def workloadDictionary(machine, result, test):
|
|||||||
'booksource' : FRAMEWORK_REPO_URL + '/raw/master/Books/',
|
'booksource' : FRAMEWORK_REPO_URL + '/raw/master/Books/',
|
||||||
'timecontrol' : test.timecontrol,
|
'timecontrol' : test.timecontrol,
|
||||||
'dev' : {
|
'dev' : {
|
||||||
|
'id' : test.dev.id,
|
||||||
'name' : test.dev.name,
|
'name' : test.dev.name,
|
||||||
'source' : test.dev.source,
|
'source' : test.dev.source,
|
||||||
'protocol' : test.dev.protocol,
|
'protocol' : test.dev.protocol,
|
||||||
@@ -177,6 +178,7 @@ def workloadDictionary(machine, result, test):
|
|||||||
'options' : test.devoptions,
|
'options' : test.devoptions,
|
||||||
},
|
},
|
||||||
'base' : {
|
'base' : {
|
||||||
|
'id' : test.base.id,
|
||||||
'name' : test.base.name,
|
'name' : test.base.name,
|
||||||
'source' : test.base.source,
|
'source' : test.base.source,
|
||||||
'protocol' : test.base.protocol,
|
'protocol' : test.base.protocol,
|
||||||
|
|||||||
+29
-8
@@ -324,7 +324,7 @@ def deleteTest(request, id):
|
|||||||
|
|
||||||
# Delete the provided test
|
# Delete the provided test
|
||||||
test = Test.objects.get(id=id)
|
test = Test.objects.get(id=id)
|
||||||
test.delete = True
|
test.deleted = True
|
||||||
test.save()
|
test.save()
|
||||||
|
|
||||||
# Log the test deltion
|
# Log the test deltion
|
||||||
@@ -343,7 +343,7 @@ def deleteTest(request, id):
|
|||||||
def getFiles(request):
|
def getFiles(request):
|
||||||
|
|
||||||
# Core Files should be sitting in framework's repo
|
# Core Files should be sitting in framework's repo
|
||||||
source = FRAMEWORK_REPO_URL + '/raw/master/CoreFiles/'
|
source = FRAMEWORK_REPO_URL + 'raw/master/CoreFiles/'
|
||||||
return HttpResponse(source)
|
return HttpResponse(source)
|
||||||
|
|
||||||
@csrf_exempt
|
@csrf_exempt
|
||||||
@@ -374,13 +374,34 @@ def getWorkload(request):
|
|||||||
# Send ID's and test information as a string dictionary
|
# Send ID's and test information as a string dictionary
|
||||||
return HttpResponse(str(OpenBench.utils.workloadDictionary(machine, result, test)))
|
return HttpResponse(str(OpenBench.utils.workloadDictionary(machine, result, test)))
|
||||||
|
|
||||||
|
@csrf_exempt
|
||||||
|
def wrongBench(request):
|
||||||
|
|
||||||
|
# Attempt to login in user
|
||||||
|
try: loginUser(request, authenticate(
|
||||||
|
username=request.POST['username'],
|
||||||
|
password=request.POST['password']))
|
||||||
|
except: return HttpResponse('Bad Credentials')
|
||||||
|
|
||||||
|
# Find the engine with the bad bench
|
||||||
|
engineid = int(request.POST['engineid'])
|
||||||
|
engine = Engine.objects.get(id=engineid)
|
||||||
|
|
||||||
|
# Find and stop the test with the bad bench
|
||||||
|
testid = int(request.POST['testid'])
|
||||||
|
test = Test.objects.get(id=testid)
|
||||||
|
test.finished = True
|
||||||
|
test.save()
|
||||||
|
|
||||||
|
# Log the bad bench so we know why the test was stopped
|
||||||
|
LogEvent.objects.create(
|
||||||
|
data='Invalid bench for {0} with {1}'.format(str(test), str(engine)),
|
||||||
|
author=request.POST['username']
|
||||||
|
)
|
||||||
|
|
||||||
|
return HttpResponse('None')
|
||||||
|
|
||||||
@csrf_exempt
|
@csrf_exempt
|
||||||
def submitResults(request):
|
def submitResults(request):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@csrf_exempt
|
|
||||||
def invalidBench(request):
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
BIN
Binary file not shown.
Reference in new issue
Block a user