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.

test_trainer_gpu.py 11 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. # Copyright (c) Alibaba, Inc. and its affiliates.
  2. import glob
  3. import os
  4. import shutil
  5. import tempfile
  6. import unittest
  7. import json
  8. import numpy as np
  9. import torch
  10. from torch import nn
  11. from torch.optim import SGD
  12. from torch.optim.lr_scheduler import StepLR
  13. from torch.utils.data import IterableDataset
  14. from modelscope.metainfo import Metrics, Trainers
  15. from modelscope.metrics.builder import MetricKeys
  16. from modelscope.models.base import Model
  17. from modelscope.trainers import EpochBasedTrainer, build_trainer
  18. from modelscope.utils.constant import LogKeys, ModeKeys, ModelFile, Tasks
  19. from modelscope.utils.test_utils import (DistributedTestCase,
  20. create_dummy_test_dataset, test_level)
  21. class DummyIterableDataset(IterableDataset):
  22. def __iter__(self):
  23. feat = np.random.random(size=(5, )).astype(np.float32)
  24. labels = np.random.randint(0, 4, (1, ))
  25. iterations = [{'feat': feat, 'labels': labels}] * 500
  26. return iter(iterations)
  27. dummy_dataset_small = create_dummy_test_dataset(
  28. np.random.random(size=(5, )), np.random.randint(0, 4, (1, )), 20)
  29. dummy_dataset_big = create_dummy_test_dataset(
  30. np.random.random(size=(5, )), np.random.randint(0, 4, (1, )), 40)
  31. class DummyModel(nn.Module, Model):
  32. def __init__(self):
  33. super().__init__()
  34. self.linear = nn.Linear(5, 4)
  35. self.bn = nn.BatchNorm1d(4)
  36. def forward(self, feat, labels):
  37. x = self.linear(feat)
  38. x = self.bn(x)
  39. loss = torch.sum(x)
  40. return dict(logits=x, loss=loss)
  41. class DummyModelForwardInputs(DummyModel):
  42. def forward(self, inputs):
  43. feat, labels = inputs['feat'], inputs['labels']
  44. return super().forward(feat, labels)
  45. def train_func(work_dir,
  46. dist=False,
  47. iterable_dataset=False,
  48. forward_inputs=False,
  49. **kwargs):
  50. json_cfg = {
  51. 'task': Tasks.image_classification,
  52. 'train': {
  53. 'work_dir': work_dir,
  54. 'dataloader': {
  55. 'batch_size_per_gpu': 2,
  56. 'workers_per_gpu': 1
  57. },
  58. 'hooks': [{
  59. 'type': 'EvaluationHook',
  60. 'interval': 1
  61. }]
  62. },
  63. 'evaluation': {
  64. 'dataloader': {
  65. 'batch_size_per_gpu': 1,
  66. 'workers_per_gpu': 1,
  67. 'shuffle': False
  68. },
  69. 'metrics': [Metrics.seq_cls_metric]
  70. }
  71. }
  72. config_path = os.path.join(work_dir, ModelFile.CONFIGURATION)
  73. with open(config_path, 'w') as f:
  74. json.dump(json_cfg, f)
  75. if forward_inputs:
  76. model = DummyModelForwardInputs()
  77. else:
  78. model = DummyModel()
  79. optimmizer = SGD(model.parameters(), lr=0.01)
  80. lr_scheduler = StepLR(optimmizer, 2)
  81. trainer_name = Trainers.default
  82. if iterable_dataset:
  83. train_dataset = DummyIterableDataset()
  84. eval_dataset = DummyIterableDataset()
  85. else:
  86. train_dataset = dummy_dataset_big
  87. eval_dataset = dummy_dataset_small
  88. _kwargs = dict(
  89. cfg_file=config_path,
  90. model=model,
  91. data_collator=None,
  92. train_dataset=train_dataset,
  93. eval_dataset=eval_dataset,
  94. optimizers=(optimmizer, lr_scheduler),
  95. max_epochs=3,
  96. device='gpu',
  97. launcher='pytorch' if dist else None,
  98. **kwargs)
  99. trainer = build_trainer(trainer_name, _kwargs)
  100. trainer.train()
  101. @unittest.skipIf(not torch.cuda.is_available(), 'cuda unittest')
  102. class TrainerTestSingleGpu(unittest.TestCase):
  103. def setUp(self):
  104. print(('Testing %s.%s' % (type(self).__name__, self._testMethodName)))
  105. self.tmp_dir = tempfile.TemporaryDirectory().name
  106. if not os.path.exists(self.tmp_dir):
  107. os.makedirs(self.tmp_dir)
  108. def tearDown(self):
  109. super().tearDown()
  110. shutil.rmtree(self.tmp_dir)
  111. @unittest.skipUnless(test_level() >= 0, 'skip test in current test level')
  112. def test_single_gpu(self):
  113. train_func(self.tmp_dir)
  114. results_files = os.listdir(self.tmp_dir)
  115. json_files = glob.glob(os.path.join(self.tmp_dir, '*.log.json'))
  116. self.assertEqual(len(json_files), 1)
  117. with open(json_files[0], 'r', encoding='utf-8') as f:
  118. lines = [i.strip() for i in f.readlines()]
  119. self.assertDictContainsSubset(
  120. {
  121. LogKeys.MODE: ModeKeys.TRAIN,
  122. LogKeys.EPOCH: 1,
  123. LogKeys.ITER: 10,
  124. LogKeys.LR: 0.01
  125. }, json.loads(lines[0]))
  126. self.assertDictContainsSubset(
  127. {
  128. LogKeys.MODE: ModeKeys.TRAIN,
  129. LogKeys.EPOCH: 1,
  130. LogKeys.ITER: 20,
  131. LogKeys.LR: 0.01
  132. }, json.loads(lines[1]))
  133. self.assertDictContainsSubset(
  134. {
  135. LogKeys.MODE: ModeKeys.EVAL,
  136. LogKeys.EPOCH: 1,
  137. LogKeys.ITER: 20
  138. }, json.loads(lines[2]))
  139. self.assertDictContainsSubset(
  140. {
  141. LogKeys.MODE: ModeKeys.TRAIN,
  142. LogKeys.EPOCH: 2,
  143. LogKeys.ITER: 10,
  144. LogKeys.LR: 0.01
  145. }, json.loads(lines[3]))
  146. self.assertDictContainsSubset(
  147. {
  148. LogKeys.MODE: ModeKeys.TRAIN,
  149. LogKeys.EPOCH: 2,
  150. LogKeys.ITER: 20,
  151. LogKeys.LR: 0.01
  152. }, json.loads(lines[4]))
  153. self.assertDictContainsSubset(
  154. {
  155. LogKeys.MODE: ModeKeys.EVAL,
  156. LogKeys.EPOCH: 2,
  157. LogKeys.ITER: 20
  158. }, json.loads(lines[5]))
  159. self.assertDictContainsSubset(
  160. {
  161. LogKeys.MODE: ModeKeys.TRAIN,
  162. LogKeys.EPOCH: 3,
  163. LogKeys.ITER: 10,
  164. LogKeys.LR: 0.001
  165. }, json.loads(lines[6]))
  166. self.assertDictContainsSubset(
  167. {
  168. LogKeys.MODE: ModeKeys.TRAIN,
  169. LogKeys.EPOCH: 3,
  170. LogKeys.ITER: 20,
  171. LogKeys.LR: 0.001
  172. }, json.loads(lines[7]))
  173. self.assertDictContainsSubset(
  174. {
  175. LogKeys.MODE: ModeKeys.EVAL,
  176. LogKeys.EPOCH: 3,
  177. LogKeys.ITER: 20
  178. }, json.loads(lines[8]))
  179. self.assertIn(f'{LogKeys.EPOCH}_1.pth', results_files)
  180. self.assertIn(f'{LogKeys.EPOCH}_2.pth', results_files)
  181. self.assertIn(f'{LogKeys.EPOCH}_3.pth', results_files)
  182. for i in [0, 1, 3, 4, 6, 7]:
  183. self.assertIn(LogKeys.DATA_LOAD_TIME, lines[i])
  184. self.assertIn(LogKeys.ITER_TIME, lines[i])
  185. for i in [2, 5, 8]:
  186. self.assertIn(MetricKeys.ACCURACY, lines[i])
  187. @unittest.skipIf(not torch.cuda.is_available()
  188. or torch.cuda.device_count() <= 1, 'distributed unittest')
  189. class TrainerTestMultiGpus(DistributedTestCase):
  190. def setUp(self):
  191. print(('Testing %s.%s' % (type(self).__name__, self._testMethodName)))
  192. self.tmp_dir = tempfile.TemporaryDirectory().name
  193. if not os.path.exists(self.tmp_dir):
  194. os.makedirs(self.tmp_dir)
  195. def tearDown(self):
  196. super().tearDown()
  197. shutil.rmtree(self.tmp_dir)
  198. @unittest.skipUnless(test_level() >= 1, 'skip test in current test level')
  199. def test_multi_gpus(self):
  200. self.start(train_func, num_gpus=2, work_dir=self.tmp_dir, dist=True)
  201. results_files = os.listdir(self.tmp_dir)
  202. json_files = glob.glob(os.path.join(self.tmp_dir, '*.log.json'))
  203. self.assertEqual(len(json_files), 1)
  204. with open(json_files[0], 'r', encoding='utf-8') as f:
  205. lines = [i.strip() for i in f.readlines()]
  206. self.assertDictContainsSubset(
  207. {
  208. LogKeys.MODE: ModeKeys.TRAIN,
  209. LogKeys.EPOCH: 1,
  210. LogKeys.ITER: 10,
  211. LogKeys.LR: 0.01
  212. }, json.loads(lines[0]))
  213. self.assertDictContainsSubset(
  214. {
  215. LogKeys.MODE: ModeKeys.EVAL,
  216. LogKeys.EPOCH: 1,
  217. LogKeys.ITER: 10
  218. }, json.loads(lines[1]))
  219. self.assertDictContainsSubset(
  220. {
  221. LogKeys.MODE: ModeKeys.TRAIN,
  222. LogKeys.EPOCH: 2,
  223. LogKeys.ITER: 10,
  224. LogKeys.LR: 0.01
  225. }, json.loads(lines[2]))
  226. self.assertDictContainsSubset(
  227. {
  228. LogKeys.MODE: ModeKeys.EVAL,
  229. LogKeys.EPOCH: 2,
  230. LogKeys.ITER: 10
  231. }, json.loads(lines[3]))
  232. self.assertDictContainsSubset(
  233. {
  234. LogKeys.MODE: ModeKeys.TRAIN,
  235. LogKeys.EPOCH: 3,
  236. LogKeys.ITER: 10,
  237. LogKeys.LR: 0.001
  238. }, json.loads(lines[4]))
  239. self.assertDictContainsSubset(
  240. {
  241. LogKeys.MODE: ModeKeys.EVAL,
  242. LogKeys.EPOCH: 3,
  243. LogKeys.ITER: 10
  244. }, json.loads(lines[5]))
  245. self.assertIn(f'{LogKeys.EPOCH}_1.pth', results_files)
  246. self.assertIn(f'{LogKeys.EPOCH}_2.pth', results_files)
  247. self.assertIn(f'{LogKeys.EPOCH}_3.pth', results_files)
  248. for i in [0, 2, 4]:
  249. self.assertIn(LogKeys.DATA_LOAD_TIME, lines[i])
  250. self.assertIn(LogKeys.ITER_TIME, lines[i])
  251. for i in [1, 3, 5]:
  252. self.assertIn(MetricKeys.ACCURACY, lines[i])
  253. @unittest.skipUnless(test_level() >= 1, 'skip test in current test level')
  254. def test_multi_gpus_forward_inputs(self):
  255. self.start(
  256. train_func,
  257. num_gpus=2,
  258. work_dir=self.tmp_dir,
  259. dist=True,
  260. forward_inputs=True)
  261. results_files = os.listdir(self.tmp_dir)
  262. json_files = glob.glob(os.path.join(self.tmp_dir, '*.log.json'))
  263. self.assertEqual(len(json_files), 1)
  264. self.assertIn(f'{LogKeys.EPOCH}_1.pth', results_files)
  265. self.assertIn(f'{LogKeys.EPOCH}_2.pth', results_files)
  266. self.assertIn(f'{LogKeys.EPOCH}_3.pth', results_files)
  267. # TODO: support iters_per_epoch for dist mode
  268. @unittest.skipIf(True, 'need to adapt to DistributedSampler')
  269. def test_multi_gpus_with_iters_per_epoch(self):
  270. self.start(
  271. train_func,
  272. num_gpus=2,
  273. work_dir=self.tmp_dir,
  274. dist=True,
  275. iterable_dataset=True,
  276. train_iters_per_epoch=20,
  277. val_iters_per_epoch=10,
  278. )
  279. results_files = os.listdir(self.tmp_dir)
  280. json_files = glob.glob(os.path.join(self.tmp_dir, '*.log.json'))
  281. self.assertEqual(len(json_files), 1)
  282. with open(json_files[0], 'r', encoding='utf-8') as f:
  283. lines = [i.strip() for i in f.readlines()]
  284. print(results_files, lines)
  285. if __name__ == '__main__':
  286. unittest.main()