You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

run.py 16 kB

[to #9061073] feat: merge tts to master Link: https://code.alibaba-inc.com/Ali-MaaS/MaaS-lib/codereview/9061073 Link: https://code.alibaba-inc.com/Ali-MaaS/MaaS-lib/codereview/9061073 * [to #41669377] docs and tools refinement and release 1. add build_doc linter script 2. add sphinx-docs support 3. add development doc and api doc 4. change version to 0.1.0 for the first internal release version Link: https://code.aone.alibaba-inc.com/Ali-MaaS/MaaS-lib/codereview/8775307 * [to #41669377] add pipeline tutorial and fix bugs 1. add pipleine tutorial 2. fix bugs when using pipeline with certain model and preprocessor Link: https://code.alibaba-inc.com/Ali-MaaS/MaaS-lib/codereview/8814301 * refine doc * refine doc * merge remote release/0.1 and fix conflict * Merge branch 'release/0.1' into 'nls/tts' Release/0.1 See merge request !1700968 * [Add] add tts preprocessor without requirements. finish requirements build later * [Add] add requirements and frd submodule * [Fix] remove models submodule * [Add] add am module * [Update] update am and vocoder * [Update] remove submodule * [Update] add models * [Fix] fix init error * [Fix] fix bugs with tts pipeline * merge master * [Update] merge from master * remove frd subdmoule and using wheel from oss * change scripts * [Fix] fix bugs in am and vocoder * [Merge] merge from master * Merge branch 'master' into nls/tts * [Fix] fix bugs * [Fix] fix pep8 * Merge branch 'master' into nls/tts * [Update] remove hparams and import configuration from kwargs * Merge branch 'master' into nls/tts * upgrade tf113 to tf115 * Merge branch 'nls/tts' of gitlab.alibaba-inc.com:Ali-MaaS/MaaS-lib into nls/tts * add multiple versions of ttsfrd * merge master * [Fix] fix cr comments * Merge branch 'master' into nls/tts * [Fix] fix cr comments 0617 * Merge branch 'master' into nls/tts * [Fix] remove comment out codes * [Merge] merge from master * [Fix] fix crash for incompatible tf and pytorch version, and frd using zip file resource * Merge branch 'master' into nls/tts * [Add] add cuda support
3 years ago
[to #9061073] feat: merge tts to master Link: https://code.alibaba-inc.com/Ali-MaaS/MaaS-lib/codereview/9061073 Link: https://code.alibaba-inc.com/Ali-MaaS/MaaS-lib/codereview/9061073 * [to #41669377] docs and tools refinement and release 1. add build_doc linter script 2. add sphinx-docs support 3. add development doc and api doc 4. change version to 0.1.0 for the first internal release version Link: https://code.aone.alibaba-inc.com/Ali-MaaS/MaaS-lib/codereview/8775307 * [to #41669377] add pipeline tutorial and fix bugs 1. add pipleine tutorial 2. fix bugs when using pipeline with certain model and preprocessor Link: https://code.alibaba-inc.com/Ali-MaaS/MaaS-lib/codereview/8814301 * refine doc * refine doc * merge remote release/0.1 and fix conflict * Merge branch 'release/0.1' into 'nls/tts' Release/0.1 See merge request !1700968 * [Add] add tts preprocessor without requirements. finish requirements build later * [Add] add requirements and frd submodule * [Fix] remove models submodule * [Add] add am module * [Update] update am and vocoder * [Update] remove submodule * [Update] add models * [Fix] fix init error * [Fix] fix bugs with tts pipeline * merge master * [Update] merge from master * remove frd subdmoule and using wheel from oss * change scripts * [Fix] fix bugs in am and vocoder * [Merge] merge from master * Merge branch 'master' into nls/tts * [Fix] fix bugs * [Fix] fix pep8 * Merge branch 'master' into nls/tts * [Update] remove hparams and import configuration from kwargs * Merge branch 'master' into nls/tts * upgrade tf113 to tf115 * Merge branch 'nls/tts' of gitlab.alibaba-inc.com:Ali-MaaS/MaaS-lib into nls/tts * add multiple versions of ttsfrd * merge master * [Fix] fix cr comments * Merge branch 'master' into nls/tts * [Fix] fix cr comments 0617 * Merge branch 'master' into nls/tts * [Fix] remove comment out codes * [Merge] merge from master * [Fix] fix crash for incompatible tf and pytorch version, and frd using zip file resource * Merge branch 'master' into nls/tts * [Add] add cuda support
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. #!/usr/bin/env python
  2. # Copyright (c) Alibaba, Inc. and its affiliates.
  3. import argparse
  4. import datetime
  5. import multiprocessing
  6. import os
  7. import subprocess
  8. import sys
  9. import tempfile
  10. import unittest
  11. from fnmatch import fnmatch
  12. from multiprocessing.managers import BaseManager
  13. from pathlib import Path
  14. from turtle import shape
  15. from unittest import TestResult, TextTestResult
  16. import pandas
  17. # NOTICE: Tensorflow 1.15 seems not so compatible with pytorch.
  18. # A segmentation fault may be raise by pytorch cpp library
  19. # if 'import tensorflow' in front of 'import torch'.
  20. # Puting a 'import torch' here can bypass this incompatibility.
  21. import torch
  22. import yaml
  23. from modelscope.utils.logger import get_logger
  24. from modelscope.utils.model_tag import ModelTag, commit_model_ut_result
  25. from modelscope.utils.test_utils import (get_case_model_info, set_test_level,
  26. test_level)
  27. logger = get_logger()
  28. def test_cases_result_to_df(result_list):
  29. table_header = [
  30. 'Name', 'Result', 'Info', 'Start time', 'Stop time',
  31. 'Time cost(seconds)'
  32. ]
  33. df = pandas.DataFrame(
  34. result_list, columns=table_header).sort_values(
  35. by=['Start time'], ascending=True)
  36. return df
  37. def statistics_test_result(df):
  38. total_cases = df.shape[0]
  39. # yapf: disable
  40. success_cases = df.loc[df['Result'] == 'Success'].shape[0]
  41. error_cases = df.loc[df['Result'] == 'Error'].shape[0]
  42. failures_cases = df.loc[df['Result'] == 'Failures'].shape[0]
  43. expected_failure_cases = df.loc[df['Result'] == 'ExpectedFailures'].shape[0]
  44. unexpected_success_cases = df.loc[df['Result'] == 'UnexpectedSuccesses'].shape[0]
  45. skipped_cases = df.loc[df['Result'] == 'Skipped'].shape[0]
  46. # yapf: enable
  47. if failures_cases > 0 or \
  48. error_cases > 0 or \
  49. unexpected_success_cases > 0:
  50. final_result = 'FAILED'
  51. else:
  52. final_result = 'SUCCESS'
  53. result_msg = '%s (Runs=%s,success=%s,failures=%s,errors=%s,\
  54. skipped=%s,expected failures=%s,unexpected successes=%s)' % (
  55. final_result, total_cases, success_cases, failures_cases, error_cases,
  56. skipped_cases, expected_failure_cases, unexpected_success_cases)
  57. model_cases = get_case_model_info()
  58. for model_name, case_info in model_cases.items():
  59. cases = df.loc[df['Name'].str.contains('|'.join(list(case_info)))]
  60. results = cases['Result']
  61. result = None
  62. if any(results == 'Error') or any(results == 'Failures') or any(
  63. results == 'UnexpectedSuccesses'):
  64. result = ModelTag.MODEL_FAIL
  65. elif any(results == 'Success'):
  66. result = ModelTag.MODEL_PASS
  67. elif all(results == 'Skipped'):
  68. result = ModelTag.MODEL_SKIP
  69. else:
  70. print(f'invalid results for {model_name} \n{result}')
  71. if result is not None:
  72. commit_model_ut_result(model_name, result)
  73. print('Testing result summary.')
  74. print(result_msg)
  75. if final_result == 'FAILED':
  76. sys.exit(1)
  77. def gather_test_suites_in_files(test_dir, case_file_list, list_tests):
  78. test_suite = unittest.TestSuite()
  79. for case in case_file_list:
  80. test_case = unittest.defaultTestLoader.discover(
  81. start_dir=test_dir, pattern=case)
  82. test_suite.addTest(test_case)
  83. if hasattr(test_case, '__iter__'):
  84. for subcase in test_case:
  85. if list_tests:
  86. print(subcase)
  87. else:
  88. if list_tests:
  89. print(test_case)
  90. return test_suite
  91. def gather_test_suites_files(test_dir, pattern):
  92. case_file_list = []
  93. for dirpath, dirnames, filenames in os.walk(test_dir):
  94. for file in filenames:
  95. if fnmatch(file, pattern):
  96. case_file_list.append(file)
  97. return case_file_list
  98. def collect_test_results(case_results):
  99. result_list = [
  100. ] # each item is Case, Result, Start time, Stop time, Time cost
  101. for case_result in case_results.successes:
  102. result_list.append(
  103. (case_result.test_full_name, 'Success', '', case_result.start_time,
  104. case_result.stop_time, case_result.time_cost))
  105. for case_result in case_results.errors:
  106. result_list.append(
  107. (case_result[0].test_full_name, 'Error', case_result[1],
  108. case_result[0].start_time, case_result[0].stop_time,
  109. case_result[0].time_cost))
  110. for case_result in case_results.skipped:
  111. result_list.append(
  112. (case_result[0].test_full_name, 'Skipped', case_result[1],
  113. case_result[0].start_time, case_result[0].stop_time,
  114. case_result[0].time_cost))
  115. for case_result in case_results.expectedFailures:
  116. result_list.append(
  117. (case_result[0].test_full_name, 'ExpectedFailures', case_result[1],
  118. case_result[0].start_time, case_result[0].stop_time,
  119. case_result[0].time_cost))
  120. for case_result in case_results.failures:
  121. result_list.append(
  122. (case_result[0].test_full_name, 'Failures', case_result[1],
  123. case_result[0].start_time, case_result[0].stop_time,
  124. case_result[0].time_cost))
  125. for case_result in case_results.unexpectedSuccesses:
  126. result_list.append((case_result.test_full_name, 'UnexpectedSuccesses',
  127. '', case_result.start_time, case_result.stop_time,
  128. case_result.time_cost))
  129. return result_list
  130. def run_command_with_popen(cmd):
  131. with subprocess.Popen(
  132. cmd,
  133. stdout=subprocess.PIPE,
  134. stderr=subprocess.STDOUT,
  135. bufsize=1,
  136. encoding='utf8') as sub_process:
  137. for line in iter(sub_process.stdout.readline, ''):
  138. sys.stdout.write(line)
  139. def save_test_result(df, args):
  140. if args.result_dir is not None:
  141. file_name = str(int(datetime.datetime.now().timestamp() * 1000))
  142. os.umask(0)
  143. Path(args.result_dir).mkdir(mode=0o777, parents=True, exist_ok=True)
  144. Path(os.path.join(args.result_dir, file_name)).touch(
  145. mode=0o666, exist_ok=True)
  146. df.to_pickle(os.path.join(args.result_dir, file_name))
  147. def run_command(cmd):
  148. logger.info('Running command: %s' % ' '.join(cmd))
  149. response = subprocess.run(
  150. cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  151. try:
  152. response.check_returncode()
  153. logger.info(response.stdout.decode('utf8'))
  154. except subprocess.CalledProcessError as error:
  155. logger.error(
  156. 'stdout: %s, stderr: %s' %
  157. (response.stdout.decode('utf8'), error.stderr.decode('utf8')))
  158. def install_packages(pkgs):
  159. cmd = [sys.executable, '-m', 'pip', 'install']
  160. for pkg in pkgs:
  161. cmd.append(pkg)
  162. run_command(cmd)
  163. def install_requirements(requirements):
  164. for req in requirements:
  165. cmd = [
  166. sys.executable, '-m', 'pip', 'install', '-r',
  167. 'requirements/%s' % req, '-f',
  168. 'https://modelscope.oss-cn-beijing.aliyuncs.com/releases/repo.html'
  169. ]
  170. run_command(cmd)
  171. def run_case_in_env(env_name, env, test_suite_env_map, isolated_cases,
  172. result_dir):
  173. # install requirements and deps # run_config['envs'][env]
  174. if 'requirements' in env:
  175. install_requirements(env['requirements'])
  176. if 'dependencies' in env:
  177. install_packages(env['dependencies'])
  178. for test_suite_file in isolated_cases: # run case in subprocess
  179. if test_suite_file in test_suite_env_map and test_suite_env_map[
  180. test_suite_file] == env_name:
  181. cmd = [
  182. 'python',
  183. 'tests/run.py',
  184. '--pattern',
  185. test_suite_file,
  186. '--result_dir',
  187. result_dir,
  188. ]
  189. run_command_with_popen(cmd)
  190. else:
  191. pass # case not in run list.
  192. # run remain cases in a process.
  193. remain_suite_files = []
  194. for k, v in test_suite_env_map.items():
  195. if k not in isolated_cases and v == env_name:
  196. remain_suite_files.append(k)
  197. if len(remain_suite_files) == 0:
  198. return
  199. cmd = ['python', 'tests/run.py', '--result_dir', result_dir, '--suites']
  200. for suite in remain_suite_files:
  201. cmd.append(suite)
  202. run_command_with_popen(cmd)
  203. def run_in_subprocess(args):
  204. # only case args.isolated_cases run in subporcess, all other run in a subprocess
  205. test_suite_files = gather_test_suites_files(
  206. os.path.abspath(args.test_dir), args.pattern)
  207. run_config = None
  208. isolated_cases = []
  209. test_suite_env_map = {}
  210. # put all the case in default env.
  211. for test_suite_file in test_suite_files:
  212. test_suite_env_map[test_suite_file] = 'default'
  213. if args.run_config is not None and Path(args.run_config).exists():
  214. with open(args.run_config) as f:
  215. run_config = yaml.load(f, Loader=yaml.FullLoader)
  216. if 'isolated' in run_config:
  217. isolated_cases = run_config['isolated']
  218. if 'envs' in run_config:
  219. for env in run_config['envs']:
  220. if env != 'default':
  221. for test_suite in run_config['envs'][env]['tests']:
  222. if test_suite in test_suite_env_map:
  223. test_suite_env_map[test_suite] = env
  224. if args.subprocess: # run all case in subprocess
  225. isolated_cases = test_suite_files
  226. with tempfile.TemporaryDirectory() as temp_result_dir:
  227. for env in set(test_suite_env_map.values()):
  228. run_case_in_env(env, run_config['envs'][env], test_suite_env_map,
  229. isolated_cases, temp_result_dir)
  230. result_dfs = []
  231. result_path = Path(temp_result_dir)
  232. for result in result_path.iterdir():
  233. if Path.is_file(result):
  234. df = pandas.read_pickle(result)
  235. result_dfs.append(df)
  236. result_pd = pandas.concat(
  237. result_dfs) # merge result of every test suite.
  238. print_table_result(result_pd)
  239. print_abnormal_case_info(result_pd)
  240. statistics_test_result(result_pd)
  241. def get_object_full_name(obj):
  242. klass = obj.__class__
  243. module = klass.__module__
  244. if module == 'builtins':
  245. return klass.__qualname__
  246. return module + '.' + klass.__qualname__
  247. class TimeCostTextTestResult(TextTestResult):
  248. """Record test case time used!"""
  249. def __init__(self, stream, descriptions, verbosity):
  250. self.successes = []
  251. return super(TimeCostTextTestResult,
  252. self).__init__(stream, descriptions, verbosity)
  253. def startTest(self, test):
  254. test.start_time = datetime.datetime.now()
  255. test.test_full_name = get_object_full_name(
  256. test) + '.' + test._testMethodName
  257. self.stream.writeln('Test case: %s start at: %s' %
  258. (test.test_full_name, test.start_time))
  259. return super(TimeCostTextTestResult, self).startTest(test)
  260. def stopTest(self, test):
  261. TextTestResult.stopTest(self, test)
  262. test.stop_time = datetime.datetime.now()
  263. test.time_cost = (test.stop_time - test.start_time).total_seconds()
  264. self.stream.writeln(
  265. 'Test case: %s stop at: %s, cost time: %s(seconds)' %
  266. (test.test_full_name, test.stop_time, test.time_cost))
  267. super(TimeCostTextTestResult, self).stopTest(test)
  268. def addSuccess(self, test):
  269. self.successes.append(test)
  270. super(TextTestResult, self).addSuccess(test)
  271. class TimeCostTextTestRunner(unittest.runner.TextTestRunner):
  272. resultclass = TimeCostTextTestResult
  273. def run(self, test):
  274. return super(TimeCostTextTestRunner, self).run(test)
  275. def _makeResult(self):
  276. result = super(TimeCostTextTestRunner, self)._makeResult()
  277. return result
  278. def gather_test_cases(test_dir, pattern, list_tests):
  279. case_list = []
  280. for dirpath, dirnames, filenames in os.walk(test_dir):
  281. for file in filenames:
  282. if fnmatch(file, pattern):
  283. case_list.append(file)
  284. test_suite = unittest.TestSuite()
  285. for case in case_list:
  286. test_case = unittest.defaultTestLoader.discover(
  287. start_dir=test_dir, pattern=case)
  288. test_suite.addTest(test_case)
  289. if hasattr(test_case, '__iter__'):
  290. for subcase in test_case:
  291. if list_tests:
  292. print(subcase)
  293. else:
  294. if list_tests:
  295. print(test_case)
  296. return test_suite
  297. def print_abnormal_case_info(df):
  298. df = df.loc[(df['Result'] == 'Error') | (df['Result'] == 'Failures')]
  299. for _, row in df.iterrows():
  300. print('Case %s run result: %s, msg:\n%s' %
  301. (row['Name'], row['Result'], row['Info']))
  302. def print_table_result(df):
  303. df = df.loc[df['Result'] != 'Skipped']
  304. df = df.drop('Info', axis=1)
  305. formatters = {
  306. 'Name': '{{:<{}s}}'.format(df['Name'].str.len().max()).format,
  307. 'Result': '{{:<{}s}}'.format(df['Result'].str.len().max()).format,
  308. }
  309. with pandas.option_context('display.max_rows', None, 'display.max_columns',
  310. None, 'display.width', None):
  311. print(df.to_string(justify='left', formatters=formatters, index=False))
  312. def main(args):
  313. runner = TimeCostTextTestRunner()
  314. if args.suites is not None and len(args.suites) > 0:
  315. logger.info('Running: %s' % ' '.join(args.suites))
  316. test_suite = gather_test_suites_in_files(args.test_dir, args.suites,
  317. args.list_tests)
  318. else:
  319. test_suite = gather_test_cases(
  320. os.path.abspath(args.test_dir), args.pattern, args.list_tests)
  321. if not args.list_tests:
  322. result = runner.run(test_suite)
  323. result = collect_test_results(result)
  324. df = test_cases_result_to_df(result)
  325. if args.result_dir is not None:
  326. save_test_result(df, args)
  327. else:
  328. print_table_result(df)
  329. print_abnormal_case_info(df)
  330. statistics_test_result(df)
  331. if __name__ == '__main__':
  332. parser = argparse.ArgumentParser('test runner')
  333. parser.add_argument(
  334. '--list_tests', action='store_true', help='list all tests')
  335. parser.add_argument(
  336. '--pattern', default='test_*.py', help='test file pattern')
  337. parser.add_argument(
  338. '--test_dir', default='tests', help='directory to be tested')
  339. parser.add_argument(
  340. '--level', default=0, type=int, help='2 -- all, 1 -- p1, 0 -- p0')
  341. parser.add_argument(
  342. '--disable_profile', action='store_true', help='disable profiling')
  343. parser.add_argument(
  344. '--run_config',
  345. default=None,
  346. help='specified case run config file(yaml file)')
  347. parser.add_argument(
  348. '--subprocess',
  349. action='store_true',
  350. help='run all test suite in subprocess')
  351. parser.add_argument(
  352. '--result_dir',
  353. default=None,
  354. help='Save result to directory, internal use only')
  355. parser.add_argument(
  356. '--suites',
  357. nargs='*',
  358. help='Run specified test suites(test suite files list split by space)')
  359. args = parser.parse_args()
  360. set_test_level(args.level)
  361. os.environ['REGRESSION_BASELINE'] = '1'
  362. logger.info(f'TEST LEVEL: {test_level()}')
  363. if not args.disable_profile:
  364. from utils import profiler
  365. logger.info('enable profile ...')
  366. profiler.enable()
  367. if args.run_config is not None or args.subprocess:
  368. run_in_subprocess(args)
  369. else:
  370. main(args)