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_base_torch.py 1.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # Copyright (c) Alibaba, Inc. and its affiliates.
  2. import unittest
  3. import numpy as np
  4. import torch
  5. import torch.nn as nn
  6. import torch.nn.functional as F
  7. from modelscope.models.base_torch import TorchModel
  8. class TorchBaseTest(unittest.TestCase):
  9. def test_custom_model(self):
  10. class MyTorchModel(TorchModel):
  11. def __init__(self):
  12. super().__init__()
  13. self.conv1 = nn.Conv2d(1, 20, 5)
  14. self.conv2 = nn.Conv2d(20, 20, 5)
  15. def forward(self, x):
  16. x = F.relu(self.conv1(x))
  17. return F.relu(self.conv2(x))
  18. model = MyTorchModel()
  19. model.train()
  20. model.eval()
  21. out = model.forward(torch.rand(1, 1, 10, 10))
  22. self.assertEqual((1, 20, 2, 2), out.shape)
  23. def test_custom_model_with_postprocess(self):
  24. add_bias = 200
  25. class MyTorchModel(TorchModel):
  26. def __init__(self):
  27. super().__init__()
  28. self.conv1 = nn.Conv2d(1, 20, 5)
  29. self.conv2 = nn.Conv2d(20, 20, 5)
  30. def forward(self, x):
  31. x = F.relu(self.conv1(x))
  32. return F.relu(self.conv2(x))
  33. def postprocess(self, x):
  34. return x + add_bias
  35. model = MyTorchModel()
  36. model.train()
  37. model.eval()
  38. out = model(torch.rand(1, 1, 10, 10))
  39. self.assertEqual((1, 20, 2, 2), out.shape)
  40. self.assertTrue(np.all(out.detach().numpy() > (add_bias - 10)))
  41. if __name__ == '__main__':
  42. unittest.main()