python_op_test.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. from caffe2.python import core, workspace
  2. from caffe2.python.core import CreatePythonOperator
  3. import caffe2.python.hypothesis_test_util as hu
  4. from hypothesis import given, settings
  5. import hypothesis.strategies as st
  6. import numpy as np
  7. class CustomError(Exception):
  8. pass
  9. def SubFunctionThatThrowsCustomError():
  10. raise CustomError("This is an intentional exception.")
  11. def MainOpFunctionThatThrowsCustomError(inputs, _):
  12. return SubFunctionThatThrowsCustomError()
  13. def MainOpFunctionThatThrowsCustomErrorInBuilder(inputs, _):
  14. raise CustomError("This is an intentional exception in builder.")
  15. def op_builder(name, index, extra):
  16. iterations = [0]
  17. assert name == 'name'
  18. assert index == 5
  19. assert extra - 4.2 < 0.0001
  20. def my_op(inputs, outputs):
  21. assert inputs[0].data[0] == iterations[0]
  22. assert name == 'name'
  23. assert index == 5
  24. assert extra - 4.2 < 0.0001
  25. iterations[0] += 1
  26. return my_op
  27. class PythonOpTest(hu.HypothesisTestCase):
  28. @given(x=hu.tensor())
  29. def test_feed(self, x):
  30. def f(inputs, _):
  31. self.assertEqual(x.shape, inputs[0].shape)
  32. self.assertEqual(type(inputs[0].shape), tuple)
  33. self.assertEqual(type(inputs[0].data), np.ndarray)
  34. np.testing.assert_almost_equal(x, inputs[0].data)
  35. op = CreatePythonOperator(f, ["x"], [])
  36. workspace.FeedBlob("x", x)
  37. workspace.RunOperatorOnce(op)
  38. def test_exception(self):
  39. op = CreatePythonOperator(MainOpFunctionThatThrowsCustomError, [], [])
  40. with self.assertRaisesRegex(CustomError, "This is an intentional exception."):
  41. workspace.RunOperatorOnce(op)
  42. def test_exception_builder(self):
  43. op = CreatePythonOperator(MainOpFunctionThatThrowsCustomErrorInBuilder, [], [])
  44. with self.assertRaisesRegex(CustomError, "This is an intentional exception in builder."):
  45. workspace.RunOperatorOnce(op)
  46. @given(x=hu.tensor())
  47. def test_feed_with_helper_function(self, x):
  48. def f(inputs, _):
  49. self.assertEqual(x.shape, inputs[0].shape)
  50. self.assertEqual(type(inputs[0].shape), tuple)
  51. self.assertEqual(type(inputs[0].data), np.ndarray)
  52. np.testing.assert_almost_equal(x, inputs[0].data)
  53. net = core.Net("test")
  54. net.Python(f)(["x"], [])
  55. workspace.FeedBlob("x", x)
  56. workspace.RunNetOnce(net)
  57. def test_builder_tuple(self):
  58. net = core.Net("builder_template")
  59. iter_blob = 'iter'
  60. net.Python((op_builder, ['name', 5], {'extra': 4.2}))([iter_blob], [])
  61. net.Python((op_builder, ['name', 5], {'extra': 4.2}))([iter_blob], [])
  62. for repeat in range(2):
  63. # check that the builder will be called exactly once for each
  64. # PythonOp constructor. Cloning the net will also trigger a call
  65. # to the builder when the net is created.
  66. cloned_net = net.Clone('builder_%d' % repeat)
  67. workspace.FeedBlob(iter_blob, np.array([0]))
  68. # Builder gets called once per python op in the line below
  69. workspace.CreateNet(cloned_net)
  70. for i in range(10):
  71. workspace.FeedBlob(iter_blob, np.array([i]))
  72. workspace.RunNet(cloned_net)
  73. @given(x=hu.tensor())
  74. def test_feed_with_gc(self, x):
  75. def f(inputs, _):
  76. self.assertEqual(x.shape, inputs[0].shape)
  77. np.testing.assert_almost_equal(x, inputs[0].data)
  78. op = CreatePythonOperator(f, ["x"], [])
  79. workspace.FeedBlob("x", x)
  80. workspace.RunOperatorOnce(op)
  81. del f
  82. workspace.FeedBlob("x", x)
  83. workspace.RunOperatorOnce(op)
  84. @given(x=hu.tensor())
  85. def test_reshape(self, x):
  86. def f(inputs, outputs):
  87. outputs[0].reshape(inputs[0].shape)
  88. self.assertEqual(x.shape, inputs[0].shape)
  89. self.assertEqual(x.shape, outputs[0].shape)
  90. outputs[0].data[...] = inputs[0].data
  91. op = CreatePythonOperator(f, ["x"], ["y"])
  92. workspace.FeedBlob("x", x)
  93. workspace.RunOperatorOnce(op)
  94. y = workspace.FetchBlob("y")
  95. np.testing.assert_almost_equal(x, y)
  96. @given(x=hu.tensor())
  97. def test_workspace_manipulation(self, x):
  98. """
  99. Verify that python op can manipulate workspace directly
  100. """
  101. def f(inputs, outputs, ws):
  102. fetched = ws.blobs['internal'].fetch()
  103. np.testing.assert_almost_equal(fetched, x)
  104. ws = workspace.C.Workspace()
  105. net = core.Net("test")
  106. net.GivenTensorFill([], ['internal'], values=x, shape=x.shape)
  107. net.Python(f, pass_workspace=True)([], [])
  108. ws.run(net)
  109. @given(x=hu.tensor())
  110. def test_caught_exception_doesnt_terminate(self, x):
  111. def f(inputs, outputs):
  112. try:
  113. raise Exception("Exception in handler")
  114. except Exception:
  115. pass
  116. op = CreatePythonOperator(f, ["x"], ["y"])
  117. workspace.FeedBlob("x", x)
  118. workspace.RunOperatorOnce(op)
  119. @given(x=hu.tensor(),
  120. n=st.integers(min_value=1, max_value=20),
  121. w=st.integers(min_value=1, max_value=20))
  122. @settings(deadline=1000)
  123. def test_multithreaded_evaluation(self, x, n, w):
  124. def f(inputs, outputs):
  125. outputs[0].reshape(inputs[0].shape)
  126. outputs[0].data[...] = inputs[0].data
  127. ops = [CreatePythonOperator(f, ["x"], [str(i)]) for i in range(n)]
  128. net = core.Net("net")
  129. net.Proto().op.extend(ops)
  130. net.Proto().type = "dag"
  131. net.Proto().num_workers = w
  132. iters = 100
  133. plan = core.Plan("plan")
  134. plan.AddStep(core.ExecutionStep("test-step", net, iters))
  135. workspace.FeedBlob("x", x)
  136. workspace.RunPlan(plan.Proto().SerializeToString())
  137. for i in range(n):
  138. y = workspace.FetchBlob(str(i))
  139. np.testing.assert_almost_equal(x, y)
  140. @given(x=hu.tensor(), in_place=st.booleans(), **hu.gcs)
  141. @settings(deadline=10000)
  142. def test_gradient(self, x, in_place, gc, dc):
  143. def f(inputs, outputs):
  144. outputs[0].reshape(inputs[0].shape)
  145. outputs[0].data[...] = inputs[0].data * 2
  146. def grad_f(inputs, outputs):
  147. # Ordering is [inputs, outputs, grad_outputs]
  148. grad_output = inputs[2]
  149. grad_input = outputs[0]
  150. grad_input.reshape(grad_output.shape)
  151. grad_input.data[...] = grad_output.data * 2
  152. op = CreatePythonOperator(
  153. f, ["x"], ["x" if in_place else "y"], grad_f=grad_f)
  154. self.assertGradientChecks(gc, op, [x], 0, [0])
  155. self.assertDeviceChecks(dc, op, [x], [0])
  156. @given(inputs=hu.tensors(n=2), **hu.gcs)
  157. @settings(deadline=10000)
  158. def test_gradient_multiple(self, inputs, gc, dc):
  159. (x1, x2) = inputs
  160. def f(inputs, outputs):
  161. for idx in [0, 1]:
  162. self.assertEqual(type(inputs[idx].shape), tuple)
  163. outputs[idx].reshape(inputs[idx].shape)
  164. outputs[idx].data[...] = inputs[idx].data * 2
  165. def grad_f(inputs, outputs):
  166. # Ordering is [inputs, outputs, grad_outputs]
  167. self.assertEqual(len(inputs), 6)
  168. self.assertEqual(len(outputs), 2)
  169. for (grad_output_idx, grad_input_idx) in [(4, 0), (5, 1)]:
  170. grad_output = inputs[grad_output_idx]
  171. grad_input = outputs[grad_input_idx]
  172. grad_input.reshape(grad_output.shape)
  173. grad_input.data[...] = grad_output.data * 2
  174. op = CreatePythonOperator(f, ["x1", "x2"], ["y1", "y2"], grad_f=grad_f)
  175. for idx in [0, 1]:
  176. self.assertGradientChecks(gc, op, [x1, x2], idx, [0, 1])
  177. self.assertDeviceChecks(dc, op, [x1, x2], [0, 1])
  178. @given(inputs=hu.tensors(n=3), **hu.gcs)
  179. @settings(deadline=10000)
  180. def test_gradient_multiple_with_indices(self, inputs, gc, dc):
  181. (x1, x2, x3) = inputs
  182. def f(inputs, outputs):
  183. for idx in [0, 1, 2]:
  184. self.assertEqual(type(inputs[idx].shape), tuple)
  185. outputs[idx].reshape(inputs[idx].shape)
  186. outputs[idx].data[...] = inputs[idx].data * 2
  187. def grad_f(inputs, outputs):
  188. # Ordering is [inputs, outputs, grad_outputs]
  189. self.assertEqual(len(inputs), 8)
  190. self.assertEqual(len(outputs), 1)
  191. for (grad_output_idx, grad_input_idx) in [(6, 0)]:
  192. grad_output = inputs[grad_output_idx]
  193. grad_input = outputs[grad_input_idx]
  194. grad_input.reshape(grad_output.shape)
  195. grad_input.data[...] = grad_output.data * 2
  196. op = CreatePythonOperator(
  197. f, ["x1", "x2", "x3"], ["y1", "y2", "y3"],
  198. grad_f=grad_f,
  199. grad_output_indices=[0, 2], # Receive grad outputs for y1 and y3
  200. grad_input_indices=[0] # Produce grad inputs for x1
  201. )
  202. self.assertGradientChecks(gc, op, [x1, x2, x3], 0, [0, 2])
  203. self.assertDeviceChecks(dc, op, [x1, x2, x3], [0, 1, 2])