forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_util.py
90 lines (64 loc) · 2.35 KB
/
test_util.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
## @package test_util
# Module caffe2.python.test_util
import numpy as np
from caffe2.python import core, workspace
import os
import pathlib
import shutil
import tempfile
import unittest
from typing import Any, Callable, Tuple, Type
from types import TracebackType
def rand_array(*dims):
# np.random.rand() returns float instead of 0-dim array, that's why need to
# do some tricks
return np.array(np.random.rand(*dims) - 0.5).astype(np.float32)
def randBlob(name, type, *dims, **kwargs):
offset = kwargs['offset'] if 'offset' in kwargs else 0.0
workspace.FeedBlob(name, np.random.rand(*dims).astype(type) + offset)
def randBlobFloat32(name, *dims, **kwargs):
randBlob(name, np.float32, *dims, **kwargs)
def randBlobsFloat32(names, *dims, **kwargs):
for name in names:
randBlobFloat32(name, *dims, **kwargs)
def numOps(net):
return len(net.Proto().op)
def str_compare(a, b, encoding="utf8"):
if isinstance(a, bytes):
a = a.decode(encoding)
if isinstance(b, bytes):
b = b.decode(encoding)
return a == b
def get_default_test_flags():
return [
'caffe2',
'--caffe2_log_level=0',
'--caffe2_cpu_allocator_do_zero_fill=0',
'--caffe2_cpu_allocator_do_junk_fill=1',
]
class TestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
workspace.GlobalInit(get_default_test_flags())
# clear the default engines settings to separate out its
# affect from the ops tests
core.SetEnginePref({}, {})
def setUp(self):
self.ws = workspace.C.Workspace()
workspace.ResetWorkspace()
def tearDown(self):
workspace.ResetWorkspace()
def make_tempdir(self) -> pathlib.Path:
tmp_folder = pathlib.Path(tempfile.mkdtemp(prefix="caffe2_test."))
self.addCleanup(self._remove_tempdir, tmp_folder)
return tmp_folder
def _remove_tempdir(self, path: pathlib.Path) -> None:
def _onerror(
fn: Callable[..., Any],
path: str,
exc_info: Tuple[Type[BaseException], BaseException, TracebackType],
) -> None:
# Ignore FileNotFoundError, but re-raise anything else
if not isinstance(exc_info[1], FileNotFoundError):
raise exc_info[1].with_traceback(exc_info[2])
shutil.rmtree(str(path), onerror=_onerror)