test_utils.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. #!/usr/bin/env python
  2. # Copyright (c) Alibaba, Inc. and its affiliates.
  3. import copy
  4. import os
  5. import pickle
  6. import shutil
  7. import socket
  8. import subprocess
  9. import sys
  10. import tarfile
  11. import tempfile
  12. import unittest
  13. from collections import OrderedDict
  14. from collections.abc import Mapping
  15. from os.path import expanduser
  16. import numpy as np
  17. import requests
  18. from modelscope.hub.constants import DEFAULT_CREDENTIALS_PATH
  19. from modelscope.utils.import_utils import is_tf_available, is_torch_available
  20. TEST_LEVEL = 2
  21. TEST_LEVEL_STR = 'TEST_LEVEL'
  22. # for user citest and sdkdev
  23. TEST_ACCESS_TOKEN1 = os.environ.get('TEST_ACCESS_TOKEN_CITEST', None)
  24. TEST_ACCESS_TOKEN2 = os.environ.get('TEST_ACCESS_TOKEN_SDKDEV', None)
  25. TEST_MODEL_CHINESE_NAME = '内部测试模型'
  26. TEST_MODEL_ORG = os.environ.get('TEST_MODEL_ORG', 'citest')
  27. if not hasattr(np, 'NaN'):
  28. np.NaN = np.nan
  29. def delete_credential():
  30. path_credential = expanduser(DEFAULT_CREDENTIALS_PATH)
  31. shutil.rmtree(path_credential, ignore_errors=True)
  32. def test_level():
  33. global TEST_LEVEL
  34. if TEST_LEVEL_STR in os.environ:
  35. TEST_LEVEL = int(os.environ[TEST_LEVEL_STR])
  36. return TEST_LEVEL
  37. def require_tf(test_case):
  38. if not is_tf_available():
  39. test_case = unittest.skip('test requires TensorFlow')(test_case)
  40. return test_case
  41. def require_torch(test_case):
  42. if not is_torch_available():
  43. test_case = unittest.skip('test requires PyTorch')(test_case)
  44. return test_case
  45. def set_test_level(level: int):
  46. global TEST_LEVEL
  47. TEST_LEVEL = level
  48. class DummyTorchDataset:
  49. def __init__(self, feat, label, num) -> None:
  50. self.feat = feat
  51. self.label = label
  52. self.num = num
  53. def __getitem__(self, index):
  54. import torch
  55. return {
  56. 'feat': torch.Tensor(self.feat),
  57. 'labels': torch.Tensor(self.label)
  58. }
  59. def __len__(self):
  60. return self.num
  61. def create_dummy_test_dataset(feat, label, num):
  62. return DummyTorchDataset(feat, label, num)
  63. def download_and_untar(fpath, furl, dst) -> str:
  64. if not os.path.exists(fpath):
  65. r = requests.get(furl)
  66. with open(fpath, 'wb') as f:
  67. f.write(r.content)
  68. file_name = os.path.basename(fpath)
  69. root_dir = os.path.dirname(fpath)
  70. target_dir_name = os.path.splitext(os.path.splitext(file_name)[0])[0]
  71. target_dir_path = os.path.join(root_dir, target_dir_name)
  72. # untar the file
  73. t = tarfile.open(fpath)
  74. t.extractall(path=dst)
  75. return target_dir_path
  76. def get_case_model_info():
  77. status_code, result = subprocess.getstatusoutput(
  78. 'grep -rn "damo/" tests/ | grep -v "*.pyc" | grep -v "Binary file" | grep -v run.py '
  79. )
  80. lines = result.split('\n')
  81. test_cases = OrderedDict()
  82. model_cases = OrderedDict()
  83. for line in lines:
  84. # "tests/msdatasets/test_ms_dataset.py:92: model_id = 'damo/bert-base-sst2'"
  85. line = line.strip()
  86. elements = line.split(':')
  87. test_file = elements[0]
  88. model_pos = line.find('damo')
  89. if model_pos == -1 or (model_pos - 1) > len(line):
  90. continue
  91. left_quote = line[model_pos - 1]
  92. rquote_idx = line.rfind(left_quote)
  93. model_name = line[model_pos:rquote_idx]
  94. if test_file not in test_cases:
  95. test_cases[test_file] = set()
  96. model_info = test_cases[test_file]
  97. model_info.add(model_name)
  98. if model_name not in model_cases:
  99. model_cases[model_name] = set()
  100. case_info = model_cases[model_name]
  101. case_info.add(
  102. test_file.replace('tests/', '').replace('.py',
  103. '').replace('/', '.'))
  104. return model_cases
  105. def compare_arguments_nested(print_content,
  106. arg1,
  107. arg2,
  108. rtol=1.e-3,
  109. atol=1.e-8,
  110. ignore_unknown_type=True):
  111. type1 = type(arg1)
  112. type2 = type(arg2)
  113. if type1.__name__ != type2.__name__:
  114. if print_content is not None:
  115. print(
  116. f'{print_content}, type not equal:{type1.__name__} and {type2.__name__}'
  117. )
  118. return False
  119. if arg1 is None:
  120. return True
  121. elif isinstance(arg1, (int, str, bool, np.bool_, np.integer, np.str_)):
  122. if arg1 != arg2:
  123. if print_content is not None:
  124. print(f'{print_content}, arg1:{arg1}, arg2:{arg2}')
  125. return False
  126. return True
  127. elif isinstance(arg1, (float, np.floating)):
  128. if not np.isclose(arg1, arg2, rtol=rtol, atol=atol, equal_nan=True):
  129. if print_content is not None:
  130. print(f'{print_content}, arg1:{arg1}, arg2:{arg2}')
  131. return False
  132. return True
  133. elif isinstance(arg1, (tuple, list)):
  134. if len(arg1) != len(arg2):
  135. if print_content is not None:
  136. print(
  137. f'{print_content}, length is not equal:{len(arg1)}, {len(arg2)}'
  138. )
  139. return False
  140. if not all([
  141. compare_arguments_nested(
  142. None, sub_arg1, sub_arg2, rtol=rtol, atol=atol)
  143. for sub_arg1, sub_arg2 in zip(arg1, arg2)
  144. ]):
  145. if print_content is not None:
  146. print(f'{print_content}')
  147. return False
  148. return True
  149. elif isinstance(arg1, Mapping):
  150. keys1 = arg1.keys()
  151. keys2 = arg2.keys()
  152. if len(keys1) != len(keys2):
  153. if print_content is not None:
  154. print(
  155. f'{print_content}, key length is not equal:{len(keys1)}, {len(keys2)}'
  156. )
  157. return False
  158. if len(set(keys1) - set(keys2)) > 0:
  159. if print_content is not None:
  160. print(f'{print_content}, key diff:{set(keys1) - set(keys2)}')
  161. return False
  162. if not all([
  163. compare_arguments_nested(
  164. None, arg1[key], arg2[key], rtol=rtol, atol=atol)
  165. for key in keys1
  166. ]):
  167. if print_content is not None:
  168. print(f'{print_content}')
  169. return False
  170. return True
  171. elif isinstance(arg1, np.ndarray):
  172. arg1 = np.where(np.equal(arg1, None), np.NaN, arg1).astype(dtype=float)
  173. arg2 = np.where(np.equal(arg2, None), np.NaN, arg2).astype(dtype=float)
  174. if not all(
  175. np.isclose(arg1, arg2, rtol=rtol, atol=atol,
  176. equal_nan=True).flatten()):
  177. if print_content is not None:
  178. print(f'{print_content}')
  179. return False
  180. return True
  181. else:
  182. if ignore_unknown_type:
  183. return True
  184. else:
  185. raise ValueError(f'type not supported: {type1}')
  186. _DIST_SCRIPT_TEMPLATE = """
  187. import ast
  188. import argparse
  189. import pickle
  190. import torch
  191. from torch import distributed as dist
  192. from modelscope.utils.torch_utils import get_dist_info
  193. import {}
  194. parser = argparse.ArgumentParser()
  195. parser.add_argument('--save_all_ranks', type=ast.literal_eval, help='save all ranks results')
  196. parser.add_argument('--save_file', type=str, help='save file')
  197. parser.add_argument('--local_rank', type=int, default=0)
  198. args = parser.parse_args()
  199. def main():
  200. results = {}.{}({}) # module.func(params)
  201. if args.save_all_ranks:
  202. save_file = args.save_file + str(dist.get_rank())
  203. with open(save_file, 'wb') as f:
  204. pickle.dump(results, f)
  205. else:
  206. rank, _ = get_dist_info()
  207. if rank == 0:
  208. with open(args.save_file, 'wb') as f:
  209. pickle.dump(results, f)
  210. if __name__ == '__main__':
  211. main()
  212. """
  213. class DistributedTestCase(unittest.TestCase):
  214. """Distributed TestCase for test function with distributed mode.
  215. Examples:
  216. >>> import torch
  217. >>> from torch import distributed as dist
  218. >>> from modelscope.utils.torch_utils import init_dist
  219. >>> def _test_func(*args, **kwargs):
  220. >>> init_dist(launcher='pytorch')
  221. >>> rank = dist.get_rank()
  222. >>> if rank == 0:
  223. >>> value = torch.tensor(1.0).cuda()
  224. >>> else:
  225. >>> value = torch.tensor(2.0).cuda()
  226. >>> dist.all_reduce(value)
  227. >>> return value.cpu().numpy()
  228. >>> class DistTest(DistributedTestCase):
  229. >>> def test_function_dist(self):
  230. >>> args = () # args should be python builtin type
  231. >>> kwargs = {} # kwargs should be python builtin type
  232. >>> self.start(
  233. >>> _test_func,
  234. >>> num_gpus=2,
  235. >>> assert_callback=lambda x: self.assertEqual(x, 3.0),
  236. >>> *args,
  237. >>> **kwargs,
  238. >>> )
  239. """
  240. def _start(self,
  241. dist_start_cmd,
  242. func,
  243. num_gpus,
  244. assert_callback=None,
  245. save_all_ranks=False,
  246. *args,
  247. **kwargs):
  248. script_path = func.__code__.co_filename
  249. script_dir, script_name = os.path.split(script_path)
  250. script_name = os.path.splitext(script_name)[0]
  251. func_name = func.__qualname__
  252. func_params = []
  253. for arg in args:
  254. if isinstance(arg, str):
  255. arg = ('\'{}\''.format(arg))
  256. func_params.append(str(arg))
  257. for k, v in kwargs.items():
  258. if isinstance(v, str):
  259. v = ('\'{}\''.format(v))
  260. func_params.append('{}={}'.format(k, v))
  261. func_params = ','.join(func_params).strip(',')
  262. tmp_run_file = tempfile.NamedTemporaryFile(suffix='.py').name
  263. tmp_res_file = tempfile.NamedTemporaryFile(suffix='.pkl').name
  264. with open(tmp_run_file, 'w') as f:
  265. print('save temporary run file to : {}'.format(tmp_run_file))
  266. print('save results to : {}'.format(tmp_res_file))
  267. run_file_content = _DIST_SCRIPT_TEMPLATE.format(
  268. script_name, script_name, func_name, func_params)
  269. f.write(run_file_content)
  270. tmp_res_files = []
  271. if save_all_ranks:
  272. for i in range(num_gpus):
  273. tmp_res_files.append(tmp_res_file + str(i))
  274. else:
  275. tmp_res_files = [tmp_res_file]
  276. self.addCleanup(self.clean_tmp, [tmp_run_file] + tmp_res_files)
  277. tmp_env = copy.deepcopy(os.environ)
  278. tmp_env['PYTHONPATH'] = ':'.join(
  279. (tmp_env.get('PYTHONPATH', ''), script_dir)).lstrip(':')
  280. # avoid distributed test hang
  281. tmp_env['NCCL_P2P_DISABLE'] = '1'
  282. script_params = '--save_all_ranks=%s --save_file=%s' % (save_all_ranks,
  283. tmp_res_file)
  284. script_cmd = '%s %s %s' % (dist_start_cmd, tmp_run_file, script_params)
  285. print('script command: %s' % script_cmd)
  286. res = subprocess.call(script_cmd, shell=True, env=tmp_env)
  287. script_res = []
  288. for res_file in tmp_res_files:
  289. with open(res_file, 'rb') as f:
  290. script_res.append(pickle.load(f))
  291. if not save_all_ranks:
  292. script_res = script_res[0]
  293. if assert_callback:
  294. assert_callback(script_res)
  295. self.assertEqual(
  296. res,
  297. 0,
  298. msg='The test function ``{}`` in ``{}`` run failed!'.format(
  299. func_name, script_name))
  300. return script_res
  301. def start(self,
  302. func,
  303. num_gpus,
  304. assert_callback=None,
  305. save_all_ranks=False,
  306. *args,
  307. **kwargs):
  308. from .torch_utils import _find_free_port
  309. ip = socket.gethostbyname(socket.gethostname())
  310. if 'dist_start_cmd' in kwargs:
  311. dist_start_cmd = kwargs.pop('dist_start_cmd')
  312. else:
  313. dist_start_cmd = '%s -m torch.distributed.launch --nproc_per_node=%d ' \
  314. '--master_addr=\'%s\' --master_port=%s' % (sys.executable, num_gpus, ip, _find_free_port())
  315. return self._start(
  316. dist_start_cmd=dist_start_cmd,
  317. func=func,
  318. num_gpus=num_gpus,
  319. assert_callback=assert_callback,
  320. save_all_ranks=save_all_ranks,
  321. *args,
  322. **kwargs)
  323. def clean_tmp(self, tmp_file_list):
  324. for file in tmp_file_list:
  325. if os.path.exists(file):
  326. if os.path.isdir(file):
  327. shutil.rmtree(file)
  328. else:
  329. os.remove(file)