utils.py 10 KB

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