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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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 modelscope.metrics.builder import MetricKeys
  14. from modelscope.trainers import build_trainer
  15. from modelscope.utils.constant import LogKeys, ModeKeys, ModelFile
  16. from modelscope.utils.test_utils import (DistributedTestCase,
  17. create_dummy_test_dataset, test_level)
  18. dummy_dataset_small = create_dummy_test_dataset(
  19. np.random.random(size=(5, )), np.random.randint(0, 4, (1, )), 20)
  20. dummy_dataset_big = create_dummy_test_dataset(
  21. np.random.random(size=(5, )), np.random.randint(0, 4, (1, )), 40)
  22. class DummyModel(nn.Module):
  23. def __init__(self):
  24. super().__init__()
  25. self.linear = nn.Linear(5, 4)
  26. self.bn = nn.BatchNorm1d(4)
  27. def forward(self, feat, labels):
  28. x = self.linear(feat)
  29. x = self.bn(x)
  30. loss = torch.sum(x)
  31. return dict(logits=x, loss=loss)
  32. def train_func(work_dir, dist=False):
  33. json_cfg = {
  34. 'train': {
  35. 'work_dir': work_dir,
  36. 'dataloader': {
  37. 'batch_size_per_gpu': 2,
  38. 'workers_per_gpu': 1
  39. },
  40. 'hooks': [{
  41. 'type': 'EvaluationHook',
  42. 'interval': 1
  43. }]
  44. },
  45. 'evaluation': {
  46. 'dataloader': {
  47. 'batch_size_per_gpu': 1,
  48. 'workers_per_gpu': 1,
  49. 'shuffle': False
  50. },
  51. 'metrics': ['seq_cls_metric']
  52. }
  53. }
  54. config_path = os.path.join(work_dir, ModelFile.CONFIGURATION)
  55. with open(config_path, 'w') as f:
  56. json.dump(json_cfg, f)
  57. model = DummyModel()
  58. optimmizer = SGD(model.parameters(), lr=0.01)
  59. lr_scheduler = StepLR(optimmizer, 2)
  60. trainer_name = 'EpochBasedTrainer'
  61. kwargs = dict(
  62. cfg_file=config_path,
  63. model=model,
  64. data_collator=None,
  65. train_dataset=dummy_dataset_big,
  66. eval_dataset=dummy_dataset_small,
  67. optimizers=(optimmizer, lr_scheduler),
  68. max_epochs=3,
  69. device='gpu',
  70. launcher='pytorch' if dist else None)
  71. trainer = build_trainer(trainer_name, kwargs)
  72. trainer.train()
  73. @unittest.skipIf(not torch.cuda.is_available(), 'cuda unittest')
  74. class TrainerTestSingleGpu(unittest.TestCase):
  75. def setUp(self):
  76. print(('Testing %s.%s' % (type(self).__name__, self._testMethodName)))
  77. self.tmp_dir = tempfile.TemporaryDirectory().name
  78. if not os.path.exists(self.tmp_dir):
  79. os.makedirs(self.tmp_dir)
  80. def tearDown(self):
  81. super().tearDown()
  82. shutil.rmtree(self.tmp_dir)
  83. @unittest.skipUnless(test_level() >= 1, 'skip test in current test level')
  84. def test_single_gpu(self):
  85. train_func(self.tmp_dir)
  86. results_files = os.listdir(self.tmp_dir)
  87. json_files = glob.glob(os.path.join(self.tmp_dir, '*.log.json'))
  88. self.assertEqual(len(json_files), 1)
  89. with open(json_files[0], 'r') as f:
  90. lines = [i.strip() for i in f.readlines()]
  91. self.assertDictContainsSubset(
  92. {
  93. LogKeys.MODE: ModeKeys.TRAIN,
  94. LogKeys.EPOCH: 1,
  95. LogKeys.ITER: 10,
  96. LogKeys.LR: 0.01
  97. }, json.loads(lines[0]))
  98. self.assertDictContainsSubset(
  99. {
  100. LogKeys.MODE: ModeKeys.TRAIN,
  101. LogKeys.EPOCH: 1,
  102. LogKeys.ITER: 20,
  103. LogKeys.LR: 0.01
  104. }, json.loads(lines[1]))
  105. self.assertDictContainsSubset(
  106. {
  107. LogKeys.MODE: ModeKeys.EVAL,
  108. LogKeys.EPOCH: 1,
  109. LogKeys.ITER: 20
  110. }, json.loads(lines[2]))
  111. self.assertDictContainsSubset(
  112. {
  113. LogKeys.MODE: ModeKeys.TRAIN,
  114. LogKeys.EPOCH: 2,
  115. LogKeys.ITER: 10,
  116. LogKeys.LR: 0.01
  117. }, json.loads(lines[3]))
  118. self.assertDictContainsSubset(
  119. {
  120. LogKeys.MODE: ModeKeys.TRAIN,
  121. LogKeys.EPOCH: 2,
  122. LogKeys.ITER: 20,
  123. LogKeys.LR: 0.01
  124. }, json.loads(lines[4]))
  125. self.assertDictContainsSubset(
  126. {
  127. LogKeys.MODE: ModeKeys.EVAL,
  128. LogKeys.EPOCH: 2,
  129. LogKeys.ITER: 20
  130. }, json.loads(lines[5]))
  131. self.assertDictContainsSubset(
  132. {
  133. LogKeys.MODE: ModeKeys.TRAIN,
  134. LogKeys.EPOCH: 3,
  135. LogKeys.ITER: 10,
  136. LogKeys.LR: 0.001
  137. }, json.loads(lines[6]))
  138. self.assertDictContainsSubset(
  139. {
  140. LogKeys.MODE: ModeKeys.TRAIN,
  141. LogKeys.EPOCH: 3,
  142. LogKeys.ITER: 20,
  143. LogKeys.LR: 0.001
  144. }, json.loads(lines[7]))
  145. self.assertDictContainsSubset(
  146. {
  147. LogKeys.MODE: ModeKeys.EVAL,
  148. LogKeys.EPOCH: 3,
  149. LogKeys.ITER: 20
  150. }, json.loads(lines[8]))
  151. self.assertIn(f'{LogKeys.EPOCH}_1.pth', results_files)
  152. self.assertIn(f'{LogKeys.EPOCH}_2.pth', results_files)
  153. self.assertIn(f'{LogKeys.EPOCH}_3.pth', results_files)
  154. for i in [0, 1, 3, 4, 6, 7]:
  155. self.assertIn(LogKeys.DATA_LOAD_TIME, lines[i])
  156. self.assertIn(LogKeys.ITER_TIME, lines[i])
  157. for i in [2, 5, 8]:
  158. self.assertIn(MetricKeys.ACCURACY, lines[i])
  159. @unittest.skipIf(not torch.cuda.is_available()
  160. or torch.cuda.device_count() <= 1, 'distributed unittest')
  161. class TrainerTestMultiGpus(DistributedTestCase):
  162. def setUp(self):
  163. print(('Testing %s.%s' % (type(self).__name__, self._testMethodName)))
  164. self.tmp_dir = tempfile.TemporaryDirectory().name
  165. if not os.path.exists(self.tmp_dir):
  166. os.makedirs(self.tmp_dir)
  167. def tearDown(self):
  168. super().tearDown()
  169. shutil.rmtree(self.tmp_dir)
  170. @unittest.skipUnless(test_level() >= 1, 'skip test in current test level')
  171. def test_multi_gpus(self):
  172. self.start(train_func, num_gpus=2, work_dir=self.tmp_dir, dist=True)
  173. results_files = os.listdir(self.tmp_dir)
  174. json_files = glob.glob(os.path.join(self.tmp_dir, '*.log.json'))
  175. self.assertEqual(len(json_files), 1)
  176. with open(json_files[0], 'r') as f:
  177. lines = [i.strip() for i in f.readlines()]
  178. self.assertDictContainsSubset(
  179. {
  180. LogKeys.MODE: ModeKeys.TRAIN,
  181. LogKeys.EPOCH: 1,
  182. LogKeys.ITER: 10,
  183. LogKeys.LR: 0.01
  184. }, json.loads(lines[0]))
  185. self.assertDictContainsSubset(
  186. {
  187. LogKeys.MODE: ModeKeys.EVAL,
  188. LogKeys.EPOCH: 1,
  189. LogKeys.ITER: 10
  190. }, json.loads(lines[1]))
  191. self.assertDictContainsSubset(
  192. {
  193. LogKeys.MODE: ModeKeys.TRAIN,
  194. LogKeys.EPOCH: 2,
  195. LogKeys.ITER: 10,
  196. LogKeys.LR: 0.01
  197. }, json.loads(lines[2]))
  198. self.assertDictContainsSubset(
  199. {
  200. LogKeys.MODE: ModeKeys.EVAL,
  201. LogKeys.EPOCH: 2,
  202. LogKeys.ITER: 10
  203. }, json.loads(lines[3]))
  204. self.assertDictContainsSubset(
  205. {
  206. LogKeys.MODE: ModeKeys.TRAIN,
  207. LogKeys.EPOCH: 3,
  208. LogKeys.ITER: 10,
  209. LogKeys.LR: 0.001
  210. }, json.loads(lines[4]))
  211. self.assertDictContainsSubset(
  212. {
  213. LogKeys.MODE: ModeKeys.EVAL,
  214. LogKeys.EPOCH: 3,
  215. LogKeys.ITER: 10
  216. }, json.loads(lines[5]))
  217. self.assertIn(f'{LogKeys.EPOCH}_1.pth', results_files)
  218. self.assertIn(f'{LogKeys.EPOCH}_2.pth', results_files)
  219. self.assertIn(f'{LogKeys.EPOCH}_3.pth', results_files)
  220. for i in [0, 2, 4]:
  221. self.assertIn(LogKeys.DATA_LOAD_TIME, lines[i])
  222. self.assertIn(LogKeys.ITER_TIME, lines[i])
  223. for i in [1, 3, 5]:
  224. self.assertIn(MetricKeys.ACCURACY, lines[i])
  225. if __name__ == '__main__':
  226. unittest.main()