Caffe2 - Python API
A deep learning, cross platform ML framework
test_util.py
1 ## @package test_util
2 # Module caffe2.python.test_util
3 from __future__ import absolute_import
4 from __future__ import division
5 from __future__ import print_function
6 from __future__ import unicode_literals
7 import numpy as np
8 from caffe2.python import core, workspace
9 
10 import unittest
11 import os
12 
13 def rand_array(*dims):
14  # np.random.rand() returns float instead of 0-dim array, that's why need to
15  # do some tricks
16  return np.array(np.random.rand(*dims) - 0.5).astype(np.float32)
17 
18 
19 def randBlob(name, type, *dims, **kwargs):
20  offset = kwargs['offset'] if 'offset' in kwargs else 0.0
21  workspace.FeedBlob(name, np.random.rand(*dims).astype(type) + offset)
22 
23 
24 def randBlobFloat32(name, *dims, **kwargs):
25  randBlob(name, np.float32, *dims, **kwargs)
26 
27 
28 def randBlobsFloat32(names, *dims, **kwargs):
29  for name in names:
30  randBlobFloat32(name, *dims, **kwargs)
31 
32 
33 def numOps(net):
34  return len(net.Proto().op)
35 
36 
37 def str_compare(a, b, encoding="utf8"):
38  if isinstance(a, bytes):
39  a = a.decode(encoding)
40  if isinstance(b, bytes):
41  b = b.decode(encoding)
42  return a == b
43 
44 
45 def get_default_test_flags():
46  return [
47  'caffe2',
48  '--caffe2_log_level=0',
49  '--caffe2_cpu_allocator_do_zero_fill=0',
50  '--caffe2_cpu_allocator_do_junk_fill=1',
51  ]
52 
53 
54 class TestCase(unittest.TestCase):
55  @classmethod
56  def setUpClass(cls):
57  workspace.GlobalInit(get_default_test_flags())
58  # clear the default engines settings to separate out its
59  # affect from the ops tests
60  core.SetEnginePref({}, {})
61 
62  def setUp(self):
63  self.ws = workspace.C.Workspace()
64  workspace.ResetWorkspace()
65 
66  def tearDown(self):
67  workspace.ResetWorkspace()