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 9.9 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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
  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. def train_func(work_dir, dist=False, iterable_dataset=False, **kwargs):
  42. json_cfg = {
  43. 'train': {
  44. 'work_dir': work_dir,
  45. 'dataloader': {
  46. 'batch_size_per_gpu': 2,
  47. 'workers_per_gpu': 1
  48. },
  49. 'hooks': [{
  50. 'type': 'EvaluationHook',
  51. 'interval': 1
  52. }]
  53. },
  54. 'evaluation': {
  55. 'dataloader': {
  56. 'batch_size_per_gpu': 1,
  57. 'workers_per_gpu': 1,
  58. 'shuffle': False
  59. },
  60. 'metrics': [Metrics.seq_cls_metric]
  61. }
  62. }
  63. config_path = os.path.join(work_dir, ModelFile.CONFIGURATION)
  64. with open(config_path, 'w') as f:
  65. json.dump(json_cfg, f)
  66. model = DummyModel()
  67. optimmizer = SGD(model.parameters(), lr=0.01)
  68. lr_scheduler = StepLR(optimmizer, 2)
  69. trainer_name = Trainers.default
  70. if iterable_dataset:
  71. train_dataset = DummyIterableDataset()
  72. eval_dataset = DummyIterableDataset()
  73. else:
  74. train_dataset = dummy_dataset_big
  75. eval_dataset = dummy_dataset_small
  76. _kwargs = dict(
  77. cfg_file=config_path,
  78. model=model,
  79. data_collator=None,
  80. train_dataset=train_dataset,
  81. eval_dataset=eval_dataset,
  82. optimizers=(optimmizer, lr_scheduler),
  83. max_epochs=3,
  84. device='gpu',
  85. launcher='pytorch' if dist else None,
  86. **kwargs)
  87. trainer = build_trainer(trainer_name, _kwargs)
  88. trainer.train()
  89. @unittest.skipIf(not torch.cuda.is_available(), 'cuda unittest')
  90. class TrainerTestSingleGpu(unittest.TestCase):
  91. def setUp(self):
  92. print(('Testing %s.%s' % (type(self).__name__, self._testMethodName)))
  93. self.tmp_dir = tempfile.TemporaryDirectory().name
  94. if not os.path.exists(self.tmp_dir):
  95. os.makedirs(self.tmp_dir)
  96. def tearDown(self):
  97. super().tearDown()
  98. shutil.rmtree(self.tmp_dir)
  99. @unittest.skipUnless(test_level() >= 1, 'skip test in current test level')
  100. def test_single_gpu(self):
  101. train_func(self.tmp_dir)
  102. results_files = os.listdir(self.tmp_dir)
  103. json_files = glob.glob(os.path.join(self.tmp_dir, '*.log.json'))
  104. self.assertEqual(len(json_files), 1)
  105. with open(json_files[0], 'r') as f:
  106. lines = [i.strip() for i in f.readlines()]
  107. self.assertDictContainsSubset(
  108. {
  109. LogKeys.MODE: ModeKeys.TRAIN,
  110. LogKeys.EPOCH: 1,
  111. LogKeys.ITER: 10,
  112. LogKeys.LR: 0.01
  113. }, json.loads(lines[0]))
  114. self.assertDictContainsSubset(
  115. {
  116. LogKeys.MODE: ModeKeys.TRAIN,
  117. LogKeys.EPOCH: 1,
  118. LogKeys.ITER: 20,
  119. LogKeys.LR: 0.01
  120. }, json.loads(lines[1]))
  121. self.assertDictContainsSubset(
  122. {
  123. LogKeys.MODE: ModeKeys.EVAL,
  124. LogKeys.EPOCH: 1,
  125. LogKeys.ITER: 20
  126. }, json.loads(lines[2]))
  127. self.assertDictContainsSubset(
  128. {
  129. LogKeys.MODE: ModeKeys.TRAIN,
  130. LogKeys.EPOCH: 2,
  131. LogKeys.ITER: 10,
  132. LogKeys.LR: 0.01
  133. }, json.loads(lines[3]))
  134. self.assertDictContainsSubset(
  135. {
  136. LogKeys.MODE: ModeKeys.TRAIN,
  137. LogKeys.EPOCH: 2,
  138. LogKeys.ITER: 20,
  139. LogKeys.LR: 0.01
  140. }, json.loads(lines[4]))
  141. self.assertDictContainsSubset(
  142. {
  143. LogKeys.MODE: ModeKeys.EVAL,
  144. LogKeys.EPOCH: 2,
  145. LogKeys.ITER: 20
  146. }, json.loads(lines[5]))
  147. self.assertDictContainsSubset(
  148. {
  149. LogKeys.MODE: ModeKeys.TRAIN,
  150. LogKeys.EPOCH: 3,
  151. LogKeys.ITER: 10,
  152. LogKeys.LR: 0.001
  153. }, json.loads(lines[6]))
  154. self.assertDictContainsSubset(
  155. {
  156. LogKeys.MODE: ModeKeys.TRAIN,
  157. LogKeys.EPOCH: 3,
  158. LogKeys.ITER: 20,
  159. LogKeys.LR: 0.001
  160. }, json.loads(lines[7]))
  161. self.assertDictContainsSubset(
  162. {
  163. LogKeys.MODE: ModeKeys.EVAL,
  164. LogKeys.EPOCH: 3,
  165. LogKeys.ITER: 20
  166. }, json.loads(lines[8]))
  167. self.assertIn(f'{LogKeys.EPOCH}_1.pth', results_files)
  168. self.assertIn(f'{LogKeys.EPOCH}_2.pth', results_files)
  169. self.assertIn(f'{LogKeys.EPOCH}_3.pth', results_files)
  170. for i in [0, 1, 3, 4, 6, 7]:
  171. self.assertIn(LogKeys.DATA_LOAD_TIME, lines[i])
  172. self.assertIn(LogKeys.ITER_TIME, lines[i])
  173. for i in [2, 5, 8]:
  174. self.assertIn(MetricKeys.ACCURACY, lines[i])
  175. @unittest.skipIf(not torch.cuda.is_available()
  176. or torch.cuda.device_count() <= 1, 'distributed unittest')
  177. class TrainerTestMultiGpus(DistributedTestCase):
  178. def setUp(self):
  179. print(('Testing %s.%s' % (type(self).__name__, self._testMethodName)))
  180. self.tmp_dir = tempfile.TemporaryDirectory().name
  181. if not os.path.exists(self.tmp_dir):
  182. os.makedirs(self.tmp_dir)
  183. def tearDown(self):
  184. super().tearDown()
  185. shutil.rmtree(self.tmp_dir)
  186. @unittest.skipUnless(test_level() >= 1, 'skip test in current test level')
  187. def test_multi_gpus(self):
  188. self.start(train_func, num_gpus=2, work_dir=self.tmp_dir, dist=True)
  189. results_files = os.listdir(self.tmp_dir)
  190. json_files = glob.glob(os.path.join(self.tmp_dir, '*.log.json'))
  191. self.assertEqual(len(json_files), 1)
  192. with open(json_files[0], 'r') as f:
  193. lines = [i.strip() for i in f.readlines()]
  194. self.assertDictContainsSubset(
  195. {
  196. LogKeys.MODE: ModeKeys.TRAIN,
  197. LogKeys.EPOCH: 1,
  198. LogKeys.ITER: 10,
  199. LogKeys.LR: 0.01
  200. }, json.loads(lines[0]))
  201. self.assertDictContainsSubset(
  202. {
  203. LogKeys.MODE: ModeKeys.EVAL,
  204. LogKeys.EPOCH: 1,
  205. LogKeys.ITER: 10
  206. }, json.loads(lines[1]))
  207. self.assertDictContainsSubset(
  208. {
  209. LogKeys.MODE: ModeKeys.TRAIN,
  210. LogKeys.EPOCH: 2,
  211. LogKeys.ITER: 10,
  212. LogKeys.LR: 0.01
  213. }, json.loads(lines[2]))
  214. self.assertDictContainsSubset(
  215. {
  216. LogKeys.MODE: ModeKeys.EVAL,
  217. LogKeys.EPOCH: 2,
  218. LogKeys.ITER: 10
  219. }, json.loads(lines[3]))
  220. self.assertDictContainsSubset(
  221. {
  222. LogKeys.MODE: ModeKeys.TRAIN,
  223. LogKeys.EPOCH: 3,
  224. LogKeys.ITER: 10,
  225. LogKeys.LR: 0.001
  226. }, json.loads(lines[4]))
  227. self.assertDictContainsSubset(
  228. {
  229. LogKeys.MODE: ModeKeys.EVAL,
  230. LogKeys.EPOCH: 3,
  231. LogKeys.ITER: 10
  232. }, json.loads(lines[5]))
  233. self.assertIn(f'{LogKeys.EPOCH}_1.pth', results_files)
  234. self.assertIn(f'{LogKeys.EPOCH}_2.pth', results_files)
  235. self.assertIn(f'{LogKeys.EPOCH}_3.pth', results_files)
  236. for i in [0, 2, 4]:
  237. self.assertIn(LogKeys.DATA_LOAD_TIME, lines[i])
  238. self.assertIn(LogKeys.ITER_TIME, lines[i])
  239. for i in [1, 3, 5]:
  240. self.assertIn(MetricKeys.ACCURACY, lines[i])
  241. # TODO: support iters_per_epoch for dist mode
  242. @unittest.skipIf(True, 'need to adapt to DistributedSampler')
  243. def test_multi_gpus_with_iters_per_epoch(self):
  244. self.start(
  245. train_func,
  246. num_gpus=2,
  247. work_dir=self.tmp_dir,
  248. dist=True,
  249. iterable_dataset=True,
  250. train_iters_per_epoch=20,
  251. val_iters_per_epoch=10,
  252. )
  253. results_files = os.listdir(self.tmp_dir)
  254. json_files = glob.glob(os.path.join(self.tmp_dir, '*.log.json'))
  255. self.assertEqual(len(json_files), 1)
  256. with open(json_files[0], 'r') as f:
  257. lines = [i.strip() for i in f.readlines()]
  258. print(results_files, lines)
  259. if __name__ == '__main__':
  260. unittest.main()