test_model.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import paddle
  15. import numpy as np
  16. from testing_utils import CommonTest
  17. class _TestModelNamespace:
  18. class TestModel(CommonTest):
  19. MODEL_CLASS = None
  20. DEFAULT_HW = (256, 256)
  21. DEFAULT_BATCH_SIZE = 2
  22. def setUp(self):
  23. self.set_specs()
  24. self.set_inputs()
  25. self.set_targets()
  26. self.set_models()
  27. def test_forward(self):
  28. for i, (
  29. input, model, target
  30. ) in enumerate(zip(self.inputs, self.models, self.targets)):
  31. with self.subTest(i=i):
  32. output = model(input)
  33. self.check_output(output, target)
  34. def check_output(self, output, target):
  35. pass
  36. def set_specs(self):
  37. self.specs = []
  38. def set_models(self):
  39. self.models = (self.build_model(spec) for spec in self.specs)
  40. def set_inputs(self):
  41. self.inputs = []
  42. def set_targets(self):
  43. self.targets = []
  44. def build_model(self, spec):
  45. if '_phase' in spec:
  46. phase = spec.pop('_phase')
  47. else:
  48. phase = 'train'
  49. if '_stop_grad' in spec:
  50. stop_grad = spec.pop('_stop_grad')
  51. else:
  52. stop_grad = False
  53. model = self.MODEL_CLASS(**spec)
  54. if phase == 'train':
  55. model.train()
  56. elif phase == 'eval':
  57. model.eval()
  58. if stop_grad:
  59. for p in model.parameters():
  60. p.stop_gradient = True
  61. return model
  62. def get_shape(self, c, b=None, h=None, w=None):
  63. if h is None or w is None:
  64. h, w = self.DEFAULT_HW
  65. if b is None:
  66. b = self.DEFAULT_BATCH_SIZE
  67. return (b, c, h, w)
  68. def get_zeros_array(self, c, b=None, h=None, w=None):
  69. shape = self.get_shape(c, b, h, w)
  70. return np.zeros(shape)
  71. def get_randn_tensor(self, c, b=None, h=None, w=None):
  72. shape = self.get_shape(c, b, h, w)
  73. return paddle.randn(shape)
  74. TestModel = _TestModelNamespace.TestModel