utils.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. import unittest
  2. import sys
  3. import os
  4. import sys
  5. import time
  6. import json
  7. import urllib
  8. import urllib2
  9. import subprocess
  10. import signal
  11. import random
  12. import operator
  13. sys.path.append("interface/HUTN")
  14. sys.path.append("scripts")
  15. from hutn_compiler.compiler import main as do_compile
  16. from check_objects import to_recompile
  17. USERNAME = "test_task"
  18. PARALLEL_PUSH = True
  19. BOOTSTRAP_FOLDER_NAME = "bootstrap"
  20. CURRENT_FOLDER_NAME = "performance"
  21. PORTS = set()
  22. OPTIMIZATION_LEVEL_LEGACY_INTERPRETER = "legacy-interpreter"
  23. OPTIMIZATION_LEVEL_INTERPRETER = "interpreter"
  24. OPTIMIZATION_LEVEL_BASELINE_JIT = "baseline-jit"
  25. OPTIMIZATION_LEVEL_BASELINE_JIT_NO_THUNKS = "baseline-jit,no-thunks"
  26. OPTIMIZATION_LEVEL_FAST_JIT = "fast-jit"
  27. ALL_OPTIMIZATION_LEVELS = [
  28. OPTIMIZATION_LEVEL_LEGACY_INTERPRETER,
  29. OPTIMIZATION_LEVEL_INTERPRETER,
  30. OPTIMIZATION_LEVEL_BASELINE_JIT,
  31. OPTIMIZATION_LEVEL_BASELINE_JIT_NO_THUNKS,
  32. OPTIMIZATION_LEVEL_FAST_JIT
  33. ]
  34. class ModelverseTerminated(Exception):
  35. """An exception that tells the task that the Modelverse has terminated."""
  36. pass
  37. def get_code_folder_name():
  38. """Gets the name of the code folder."""
  39. return '%s/code' % CURRENT_FOLDER_NAME
  40. def get_free_port():
  41. """Gets a unique new port."""
  42. while 1:
  43. port = random.randint(10000, 20000)
  44. # Check if this port is in the set of ports.
  45. if port not in PORTS:
  46. # We have found a unique port. Add it to the set and return.
  47. PORTS.add(port)
  48. return port
  49. def execute(scriptname, parameters=None, wait=False):
  50. """Runs a script."""
  51. if os.name not in ["nt", "posix"]:
  52. # Stop now, as we would have no clue on how to kill its subtree
  53. raise Exception("Unknown OS version: " + str(os.name))
  54. command = [sys.executable, "scripts/%s.py" % scriptname] + (
  55. [] if parameters is None else parameters)
  56. if wait:
  57. return subprocess.call(command, shell=False)
  58. else:
  59. return subprocess.Popen(command, shell=False)
  60. def kill(process):
  61. """Kills the given process."""
  62. if os.name == "nt":
  63. subprocess.call(["taskkill", "/F", "/T", "/PID", "%i" % process.pid])
  64. elif os.name == "posix":
  65. subprocess.call(["pkill", "-P", "%i" % process.pid])
  66. def set_input_data(address, data):
  67. """Sets the Modelverse program's input data."""
  68. if data is not None:
  69. urllib2.urlopen(
  70. urllib2.Request(
  71. address,
  72. urllib.urlencode(
  73. {"op": "set_input", "data": json.dumps(data), "taskname": USERNAME})),
  74. timeout=10).read()
  75. else:
  76. return []
  77. def compile_file(address, mod_filename, filename, mode, proc):
  78. """Compiles the given file."""
  79. # Load in the file required
  80. try:
  81. timeout_val = 240
  82. taskname = str(random.random())
  83. while 1:
  84. proc2 = execute(
  85. "compile", [address, mod_filename, taskname, filename, mode], wait=False)
  86. if proc.returncode is not None:
  87. # Modelverse has already terminated, which isn't a good sign!
  88. raise Exception("Modelverse died!")
  89. while proc2.returncode is None:
  90. time.sleep(0.01)
  91. proc2.poll()
  92. timeout_val -= 0.01
  93. if timeout_val < 0:
  94. kill(proc2)
  95. print("Compilation timeout expired!")
  96. return False
  97. if proc2.returncode != 2:
  98. break
  99. # Make sure everything stopped correctly
  100. assert proc2.returncode == 0
  101. if proc2.returncode != 0:
  102. return False
  103. except:
  104. raise
  105. finally:
  106. try:
  107. kill(proc2)
  108. except UnboundLocalError:
  109. pass
  110. def run_file(files, parameters, mode, handle_output, optimization_level=None):
  111. """Compiles the given sequence of files, feeds them the given input in the given mode,
  112. and handles their output."""
  113. # Resolve file
  114. import os.path
  115. time.sleep(0.01)
  116. port = get_free_port()
  117. address = "http://127.0.0.1:%i" % port
  118. try:
  119. # Run Modelverse server
  120. modelverse_args = [str(port)]
  121. if optimization_level is not None:
  122. modelverse_args.append('--kernel=%s' % optimization_level)
  123. proc = execute("run_local_modelverse", modelverse_args, wait=False)
  124. threads = []
  125. mod_files = []
  126. for filename in files:
  127. if os.path.isfile("%s/%s" % (get_code_folder_name(), filename)):
  128. mod_filename = "%s/%s" % (get_code_folder_name(), filename)
  129. elif os.path.isfile("%s/%s" % (BOOTSTRAP_FOLDER_NAME, filename)):
  130. mod_filename = "%s/%s" % (BOOTSTRAP_FOLDER_NAME, filename)
  131. else:
  132. raise Exception("File not found: %s" % filename)
  133. mod_files.append(mod_filename)
  134. to_compile = to_recompile(address, mod_files)
  135. for mod_filename in to_compile:
  136. if PARALLEL_PUSH:
  137. import threading
  138. threads.append(
  139. threading.Thread(
  140. target=compile_file,
  141. args=[address, mod_filename, mod_filename, mode, proc]))
  142. threads[-1].start()
  143. else:
  144. compile_file(address, mod_filename, mod_filename, mode, proc)
  145. if PARALLEL_PUSH:
  146. for t in threads:
  147. t.join()
  148. if mode[-1] == "O":
  149. # Fire up the linker
  150. val = execute("link_and_load", [address, USERNAME] + mod_files, wait=True)
  151. if val != 0:
  152. raise Exception("Linking error")
  153. # Send the request ...
  154. set_input_data(address, parameters)
  155. # ... and wait for replies
  156. while 1:
  157. val = urllib2.urlopen(
  158. urllib2.Request(
  159. address,
  160. urllib.urlencode({"op": "get_output", "taskname": USERNAME})),
  161. timeout=240).read()
  162. val = json.loads(val)
  163. if proc.returncode is not None:
  164. # Modelverse has terminated. This may or may not be what we want.
  165. raise ModelverseTerminated()
  166. if not handle_output(val):
  167. return
  168. # All passed!
  169. return
  170. except:
  171. raise
  172. finally:
  173. try:
  174. kill(proc)
  175. except UnboundLocalError:
  176. pass
  177. def run_file_to_completion(files, parameters, mode):
  178. """Compiles the given sequence of files, feeds them the given input in the given mode,
  179. and then collects and returns output."""
  180. results = []
  181. def handle_output(output):
  182. """Appends the given output to the list of results."""
  183. results.append(output)
  184. return True
  185. try:
  186. run_file(files, parameters, mode, handle_output)
  187. except ModelverseTerminated:
  188. return results
  189. def run_file_fixed_output_count(files, parameters, mode, output_count, optimization_level=None):
  190. """Compiles the given sequence of files, feeds them the given input in the given mode,
  191. and then collects and returns a fixed number of outputs."""
  192. results = []
  193. def handle_output(output):
  194. """Appends the given output to the list of results."""
  195. if len(results) < output_count:
  196. results.append(output)
  197. return True
  198. else:
  199. return False
  200. run_file(files, parameters, mode, handle_output, optimization_level)
  201. return results
  202. def run_file_single_output(files, parameters, mode, optimization_level=None):
  203. """Compiles the given sequence of files, feeds them the given input in the given mode,
  204. and then collects and returns a single output."""
  205. return run_file_fixed_output_count(files, parameters, mode, 1, optimization_level)[0]
  206. def run_perf_test(files, parameters, optimization_level, n_iterations=1):
  207. """Compiles the given sequence of files, feeds them the given input in the given mode,
  208. and then collects their output. This process is repeated n_iterations times. The
  209. return value is the average of all outputs."""
  210. result = 0.0
  211. for _ in xrange(n_iterations):
  212. result += float(
  213. run_file_single_output(
  214. files, parameters + [0], 'CO',
  215. optimization_level)) / float(n_iterations)
  216. return result
  217. def format_output(output):
  218. """Formats the output of `run_file_to_completion` as a string."""
  219. return '\n'.join(output)
  220. def define_perf_test(target_class, test_function, optimization_level):
  221. """Defines a performance test in the given class. The performance test calls the given function
  222. at the given optimization level."""
  223. setattr(
  224. target_class,
  225. 'test_%s' % optimization_level.replace('-', '_').lower(),
  226. lambda self: test_function(self, optimization_level))
  227. def define_perf_tests(target_class, test_function):
  228. """Defines performance tests in the given class. Each test calls the given function."""
  229. for optimization_level in ALL_OPTIMIZATION_LEVELS:
  230. define_perf_test(target_class, test_function, optimization_level)
  231. DEFAULT_PERF_FILE_NAME = 'perf_data.txt'
  232. def write_perf_to_file(test_name, optimization_level, result, file_name=DEFAULT_PERF_FILE_NAME):
  233. """Writes performance data to a file."""
  234. with open(file_name, "a") as perf_file:
  235. perf_file.write('%s:%s:%f\n' % (test_name, optimization_level, result))
  236. def parse_perf_data(file_name):
  237. """Parses the performance data in the given file."""
  238. results = {}
  239. with open(file_name, 'r') as perf_file:
  240. for line in perf_file.readlines():
  241. test_name, optimization_level, result = line.strip().split(':')
  242. if optimization_level not in results:
  243. results[optimization_level] = []
  244. results[optimization_level].append((test_name, result))
  245. return sorted(results.items(), key=operator.itemgetter(1))