test_base.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. # Copyright (c) 2020 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. from __future__ import print_function
  15. import unittest
  16. import contextlib
  17. import numpy as np
  18. import paddle
  19. import paddle.fluid as fluid
  20. from paddle.fluid.framework import Program
  21. from paddle.fluid import core
  22. class LayerTest(unittest.TestCase):
  23. @classmethod
  24. def setUpClass(cls):
  25. cls.seed = 111
  26. @classmethod
  27. def tearDownClass(cls):
  28. pass
  29. def _get_place(self, force_to_use_cpu=False):
  30. # this option for ops that only have cpu kernel
  31. if force_to_use_cpu:
  32. return core.CPUPlace()
  33. else:
  34. if core.is_compiled_with_cuda():
  35. return core.CUDAPlace(0)
  36. return core.CPUPlace()
  37. @contextlib.contextmanager
  38. def static_graph(self):
  39. paddle.enable_static()
  40. scope = fluid.core.Scope()
  41. program = Program()
  42. with fluid.scope_guard(scope):
  43. with fluid.program_guard(program):
  44. paddle.seed(self.seed)
  45. paddle.framework.random._manual_program_seed(self.seed)
  46. yield
  47. def get_static_graph_result(self,
  48. feed,
  49. fetch_list,
  50. with_lod=False,
  51. force_to_use_cpu=False):
  52. exe = fluid.Executor(self._get_place(force_to_use_cpu))
  53. exe.run(fluid.default_startup_program())
  54. return exe.run(fluid.default_main_program(),
  55. feed=feed,
  56. fetch_list=fetch_list,
  57. return_numpy=(not with_lod))
  58. @contextlib.contextmanager
  59. def dynamic_graph(self, force_to_use_cpu=False):
  60. paddle.disable_static()
  61. with fluid.dygraph.guard(
  62. self._get_place(force_to_use_cpu=force_to_use_cpu)):
  63. paddle.seed(self.seed)
  64. paddle.framework.random._manual_program_seed(self.seed)
  65. yield