-
Notifications
You must be signed in to change notification settings - Fork 34
/
unittest_util.py
311 lines (246 loc) · 10.1 KB
/
unittest_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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
# Copyright 2021 The FastEstimator Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
from collections import ChainMap
from typing import Any, Dict
import cv2
import numpy as np
import tensorflow as tf
import torch
from PIL import Image
from plotly.graph_objects import Figure
import fastestimator as fe
from fastestimator.dataset.numpy_dataset import NumpyDataset
from fastestimator.op.tensorop.model import ModelOp
from fastestimator.summary import System
from fastestimator.trace import Trace
from fastestimator.util.data import Data
def is_equal(obj1: Any, obj2: Any, assert_type: bool = True, assert_dtype: bool = False) -> bool:
"""Check whether input objects are equal. The object type can be nested iterable (list, tuple, set, dict) and
with elements such as int, float, np.ndarray, tf.Tensor, tf.Varaible, torch.Tensor
Args:
obj1: Input object 1
obj2: Input object 2
assert_type: Whether to assert the same data type
assert_dtype: Whether to assert the same dtype in case of nd.array, tf.Tensor, torch.Tensor
Returns:
Boolean of whether those two object are equal
"""
if assert_type and type(obj1) != type(obj2):
return False
if type(obj1) in [list, set, tuple]:
if len(obj1) != len(obj2):
return False
for iter1, iter2 in zip(obj1, obj2):
if not is_equal(iter1, iter2):
return False
return True
elif type(obj1) == dict:
if len(obj1) != len(obj2):
return False
if obj1.keys() != obj2.keys():
return False
for value1, value2 in zip(obj1.values(), obj2.values()):
if not is_equal(value1, value2):
return False
return True
elif type(obj1) == np.ndarray:
if assert_dtype and obj1.dtype != obj2.dtype:
return False
return np.array_equal(obj1, obj2)
elif tf.is_tensor(obj1):
if assert_dtype and obj1.dtype != obj2.dtype:
return False
obj1 = obj1.numpy()
obj2 = obj2.numpy()
return np.array_equal(obj1, obj2)
elif isinstance(obj1, torch.Tensor):
if assert_dtype and obj1.dtype != obj2.dtype:
return False
return torch.equal(obj1, obj2)
else:
return obj1 == obj2
def one_layer_tf_model() -> tf.keras.Model:
"""Tensorflow Model with one dense layer without activation function.
* Model input shape: (3,)
* Model output: (1,)
* dense layer weight: [1.0, 2.0, 3.0]
How to feed_forward this model
```python
model = one_layer_tf_model()
x = tf.constant([[1.0, 1.0, 1.0], [1.0, -1.0, -0.5]])
b = fe.backend.feed_forward(model, x) # [[6.0], [-2.5]]
```
Returns:
tf.keras.Model: The model
"""
inp = tf.keras.layers.Input([3])
x = tf.keras.layers.Dense(units=1, use_bias=False)(inp)
model = tf.keras.models.Model(inputs=inp, outputs=x)
model.layers[1].set_weights([np.array([[1.0], [2.0], [3.0]])])
return model
def multi_layer_tf_model() -> tf.keras.Model:
inp = tf.keras.layers.Input([4])
x = tf.keras.layers.Dense(units=2, use_bias=False, name='fc1')(inp)
x = tf.keras.layers.Dense(units=1, use_bias=False, name='fc2')(x)
model = tf.keras.models.Model(inputs=inp, outputs=x)
model.layers[1].set_weights([np.array([[1.0, 2.0], [2.0, 3.0], [3.0, 4.0], [4.0, 6.0]])])
model.layers[2].set_weights([np.array([[1.0], [2.0]])])
return model
class OneLayerTorchModel(torch.nn.Module):
"""Torch Model with one dense layer without activation function.
* Model input shape: (3,)
* Model output: (1,)
* dense layer weight: [1.0, 2.0, 3.0]
How to feed_forward this model
```python
model = OneLayerTorchModel()
x = torch.tensor([[1.0, 1.0, 1.0], [1.0, -1.0, -0.5]])
b = fe.backend.feed_forward(model, x) # [[6.0], [-2.5]]
```
"""
def __init__(self) -> None:
super().__init__()
self.fc1 = torch.nn.Linear(3, 1, bias=False)
self.fc1.weight.data = torch.tensor([[1, 2, 3]], dtype=torch.float32)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.fc1(x)
return x
class MultiLayerTorchModel(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.fc1 = torch.nn.Linear(4, 2, bias=False)
self.fc1.weight.data = torch.tensor([[1, 2, 3, 4], [2, 3, 4, 6]], dtype=torch.float32)
self.fc2 = torch.nn.Linear(2, 1, bias=False)
self.fc2.weight.data = torch.tensor([[1, 2]], dtype=torch.float32)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.fc1(x)
x = self.fc2(x)
return x
class MockBetaDistribution:
def __init__(self, framework='tf'):
self.framework = framework
def sample(self):
if self.framework == 'tf':
return tf.constant(0.5)
elif self.framework == 'torch':
return torch.Tensor([0.5])
else:
raise ValueError("Unrecognized framework {}".format(self.framework))
class MockUniformDistribution:
def __init__(self, framework='tf'):
self.framework = framework
def sample(self):
if self.framework == 'tf':
return tf.constant(0.25)
elif self.framework == 'torch':
return torch.Tensor([0.25])
else:
raise ValueError("Unrecognized framework {}".format(self.framework))
def sample_system_object():
x_train = np.random.rand(3, 28, 28, 3)
y_train = np.random.randint(10, size=(3, ))
x_eval = np.random.rand(2, 28, 28, 3)
y_eval = np.random.randint(10, size=(2, ))
train_data = NumpyDataset({'x': x_train, 'y': y_train})
eval_data = NumpyDataset({'x': x_eval, 'y': y_eval})
test_data = eval_data.split(0.5)
model = fe.build(model_fn=fe.architecture.tensorflow.LeNet, optimizer_fn='adam', model_name='tf')
pipeline = fe.Pipeline(train_data=train_data, eval_data=eval_data, test_data=test_data, batch_size=1)
network = fe.Network(ops=[ModelOp(model=model, inputs="x_out", outputs="y_pred")])
system = System(network=network, pipeline=pipeline, traces=[], total_epochs=10, mode='train')
return system
def sample_system_object_torch():
x_train = np.random.rand(3, 28, 28, 3)
y_train = np.random.randint(10, size=(3, ))
x_eval = np.random.rand(2, 28, 28, 3)
y_eval = np.random.randint(10, size=(2, ))
train_data = NumpyDataset({'x': x_train, 'y': y_train})
eval_data = NumpyDataset({'x': x_eval, 'y': y_eval})
test_data = eval_data.split(0.5)
model = fe.build(model_fn=fe.architecture.pytorch.LeNet, optimizer_fn='adam', model_name='torch')
pipeline = fe.Pipeline(train_data=train_data, eval_data=eval_data, test_data=test_data, batch_size=1)
network = fe.Network(ops=[ModelOp(model=model, inputs="x_out", outputs="y_pred")])
system = System(network=network, pipeline=pipeline, traces=[], total_epochs=10, mode='train')
return system
def check_img_similar(img1: np.ndarray, img2: np.ndarray, ptol: int = 3, ntol: float = 0.01) -> bool:
"""Check whether img1 and img2 array are similar based on pixel to pixel comparision
Args:
img1: Image 1
img2: Image 2
ptol: Pixel value tolerance
ntol: Number of pixel difference tolerace rate
Returns:
Boolean of whether the images are similar
"""
if img1.shape == img2.shape:
diff = np.abs(img1.astype(np.float32) - img2.astype(np.float32))
n_pixel_diff = diff[diff > ptol].size
if n_pixel_diff < img1.size * ntol:
return True
else:
return False
return False
def img_to_rgb_array(path: str) -> np.ndarray:
"""Read png file to numpy array (RGB)
Args:
path: Image path
Returns:
Image numpy array
"""
return np.asarray(Image.open(path).convert('RGB'))
def fig_to_rgb_array(fig: Figure) -> np.ndarray:
"""Convert image in plt.Figure to numpy array
Args:
fig: Input figure object
Returns:
Image array
"""
p = fig.to_image(format='png')
decoded = cv2.imdecode(np.frombuffer(p, np.uint8), cv2.IMREAD_COLOR)
decoded = cv2.cvtColor(decoded, cv2.COLOR_BGR2RGB)
return decoded
class TraceRun:
"""Class to simulate the trace calling protocol.
This serve for testing purpose without using estimator class.
Args:
trace: Target trace to run.
batch: Batch data from pipepline.
prediction: Batch data from network.
"""
def __init__(self, trace: Trace, batch: Dict[str, Any], prediction: Dict[str, Any]):
self.trace = trace
self.batch = batch
self.prediction = prediction
self.data_on_begin = None
self.data_on_end = None
self.data_on_epoch_begin = None
self.data_on_epoch_end = None
self.data_on_batch_begin = None
self.data_on_batch_end = None
def run_trace(self) -> None:
system = sample_system_object()
self.trace.system = system
self.data_on_begin = Data()
self.trace.on_begin(self.data_on_begin)
self.data_on_epoch_begin = Data()
self.trace.on_epoch_begin(self.data_on_epoch_begin)
self.data_on_batch_begin = Data(self.batch)
self.trace.on_batch_begin(self.data_on_batch_begin)
self.data_on_batch_end = Data(ChainMap(self.prediction, self.batch))
self.trace.on_batch_end(self.data_on_batch_end)
self.data_on_epoch_end = Data()
self.trace.on_epoch_end(self.data_on_epoch_end)
self.data_on_end = Data()
self.trace.on_end(self.data_on_end)