-
-
Notifications
You must be signed in to change notification settings - Fork 309
/
Copy pathutils.py
391 lines (305 loc) · 11.4 KB
/
utils.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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
import os
import subprocess
import urllib.request
import numpy as np
from dezero import as_variable
from dezero import Variable
from dezero import cuda
# =============================================================================
# Visualize for computational graph
# =============================================================================
def _dot_var(v, verbose=False):
dot_var = '{} [label="{}", color=orange, style=filled]\n'
name = '' if v.name is None else v.name
if verbose and v.data is not None:
if v.name is not None:
name += ': '
name += str(v.shape) + ' ' + str(v.dtype)
return dot_var.format(id(v), name)
def _dot_func(f):
# for function
dot_func = '{} [label="{}", color=lightblue, style=filled, shape=box]\n'
ret = dot_func.format(id(f), f.__class__.__name__)
# for edge
dot_edge = '{} -> {}\n'
for x in f.inputs:
ret += dot_edge.format(id(x), id(f))
for y in f.outputs: # y is weakref
ret += dot_edge.format(id(f), id(y()))
return ret
def get_dot_graph(output, verbose=True):
"""Generates a graphviz DOT text of a computational graph.
Build a graph of functions and variables backward-reachable from the
output. To visualize a graphviz DOT text, you need the dot binary from the
graphviz package (www.graphviz.org).
Args:
output (dezero.Variable): Output variable from which the graph is
constructed.
verbose (bool): If True the dot graph contains additional information
such as shapes and dtypes.
Returns:
str: A graphviz DOT text consisting of nodes and edges that are
backward-reachable from the output
"""
txt = ''
funcs = []
seen_set = set()
def add_func(f):
if f not in seen_set:
funcs.append(f)
# funcs.sort(key=lambda x: x.generation)
seen_set.add(f)
add_func(output.creator)
txt += _dot_var(output, verbose)
while funcs:
func = funcs.pop()
txt += _dot_func(func)
for x in func.inputs:
txt += _dot_var(x, verbose)
if x.creator is not None:
add_func(x.creator)
return 'digraph g {\n' + txt + '}'
def plot_dot_graph(output, verbose=True, to_file='graph.png'):
dot_graph = get_dot_graph(output, verbose)
tmp_dir = os.path.join(os.path.expanduser('~'), '.dezero')
if not os.path.exists(tmp_dir):
os.mkdir(tmp_dir)
graph_path = os.path.join(tmp_dir, 'tmp_graph.dot')
with open(graph_path, 'w') as f:
f.write(dot_graph)
extension = os.path.splitext(to_file)[1][1:] # Extension(e.g. png, pdf)
cmd = 'dot {} -T {} -o {}'.format(graph_path, extension, to_file)
subprocess.run(cmd, shell=True)
# Return the image as a Jupyter Image object, to be displayed in-line.
try:
from IPython import display
return display.Image(filename=to_file)
except:
pass
# =============================================================================
# Utility functions for numpy (numpy magic)
# =============================================================================
def sum_to(x, shape):
"""Sum elements along axes to output an array of a given shape.
Args:
x (ndarray): Input array.
shape:
Returns:
ndarray: Output array of the shape.
"""
ndim = len(shape)
lead = x.ndim - ndim
lead_axis = tuple(range(lead))
axis = tuple([i + lead for i, sx in enumerate(shape) if sx == 1])
y = x.sum(lead_axis + axis, keepdims=True)
if lead > 0:
y = y.squeeze(lead_axis)
return y
def reshape_sum_backward(gy, x_shape, axis, keepdims):
"""Reshape gradient appropriately for dezero.functions.sum's backward.
Args:
gy (dezero.Variable): Gradient variable from the output by backprop.
x_shape (tuple): Shape used at sum function's forward.
axis (None or int or tuple of ints): Axis used at sum function's
forward.
keepdims (bool): Keepdims used at sum function's forward.
Returns:
dezero.Variable: Gradient variable which is reshaped appropriately
"""
ndim = len(x_shape)
tupled_axis = axis
if axis is None:
tupled_axis = None
elif not isinstance(axis, tuple):
tupled_axis = (axis,)
if not (ndim == 0 or tupled_axis is None or keepdims):
actual_axis = [a if a >= 0 else a + ndim for a in tupled_axis]
shape = list(gy.shape)
for a in sorted(actual_axis):
shape.insert(a, 1)
else:
shape = gy.shape
gy = gy.reshape(shape) # reshape
return gy
def logsumexp(x, axis=1):
xp = cuda.get_array_module(x)
m = x.max(axis=axis, keepdims=True)
y = x - m
xp.exp(y, out=y)
s = y.sum(axis=axis, keepdims=True)
xp.log(s, out=s)
m += s
return m
def max_backward_shape(x, axis):
if axis is None:
axis = range(x.ndim)
elif isinstance(axis, int):
axis = (axis,)
else:
axis = axis
shape = [s if ax not in axis else 1 for ax, s in enumerate(x.shape)]
return shape
# =============================================================================
# Gradient check
# =============================================================================
def gradient_check(f, x, *args, rtol=1e-4, atol=1e-5, **kwargs):
"""Test backward procedure of a given function.
This automatically checks the backward-process of a given function. For
checking the correctness, this function compares gradients by
backprop and ones by numerical derivation. If the result is within a
tolerance this function return True, otherwise False.
Args:
f (callable): A function which gets `Variable`s and returns `Variable`s.
x (`ndarray` or `dezero.Variable`): A traget `Variable` for computing
the gradient.
*args: If `f` needs variables except `x`, you can specify with this
argument.
rtol (float): The relative tolerance parameter.
atol (float): The absolute tolerance parameter.
**kwargs: If `f` needs keyword variables, you can specify with this
argument.
Returns:
bool: Return True if the result is within a tolerance, otherwise False.
"""
x = as_variable(x)
x.data = x.data.astype(np.float64)
num_grad = numerical_grad(f, x, *args, **kwargs)
y = f(x, *args, **kwargs)
y.backward()
bp_grad = x.grad.data
assert bp_grad.shape == num_grad.shape
res = array_allclose(num_grad, bp_grad, atol=atol, rtol=rtol)
if not res:
print('')
print('========== FAILED (Gradient Check) ==========')
print('Numerical Grad')
print(' shape: {}'.format(num_grad.shape))
val = str(num_grad.flatten()[:10])
print(' values: {} ...'.format(val[1:-1]))
print('Backprop Grad')
print(' shape: {}'.format(bp_grad.shape))
val = str(bp_grad.flatten()[:10])
print(' values: {} ...'.format(val[1:-1]))
return res
def numerical_grad(f, x, *args, **kwargs):
"""Computes numerical gradient by finite differences.
Args:
f (callable): A function which gets `Variable`s and returns `Variable`s.
x (`ndarray` or `dezero.Variable`): A target `Variable` for computing
the gradient.
*args: If `f` needs variables except `x`, you can specify with this
argument.
**kwargs: If `f` needs keyword variables, you can specify with this
argument.
Returns:
`ndarray`: Gradient.
"""
eps = 1e-4
x = x.data if isinstance(x, Variable) else x
xp = cuda.get_array_module(x)
if xp is not np:
np_x = cuda.as_numpy(x)
else:
np_x = x
grad = xp.zeros_like(x)
it = np.nditer(np_x, flags=['multi_index'], op_flags=['readwrite'])
while not it.finished:
idx = it.multi_index
tmp_val = x[idx].copy()
x[idx] = tmp_val + eps
y1 = f(x, *args, **kwargs) # f(x+h)
if isinstance(y1, Variable):
y1 = y1.data
y1 = y1.copy()
x[idx] = tmp_val - eps
y2 = f(x, *args, **kwargs) # f(x-h)
if isinstance(y2, Variable):
y2 = y2.data
y2 = y2.copy()
diff = (y1 - y2).sum()
grad[idx] = diff / (2 * eps)
x[idx] = tmp_val
it.iternext()
return grad
def array_equal(a, b):
"""True if two arrays have the same shape and elements, False otherwise.
Args:
a, b (numpy.ndarray or cupy.ndarray or dezero.Variable): input arrays
to compare
Returns:
bool: True if the two arrays are equal.
"""
a = a.data if isinstance(a, Variable) else a
b = b.data if isinstance(b, Variable) else b
a, b = cuda.as_numpy(a), cuda.as_numpy(b)
return np.array_equal(a, b)
def array_allclose(a, b, rtol=1e-4, atol=1e-5):
"""Returns True if two arrays(or variables) are element-wise equal within a
tolerance.
Args:
a, b (numpy.ndarray or cupy.ndarray or dezero.Variable): input arrays
to compare
rtol (float): The relative tolerance parameter.
atol (float): The absolute tolerance parameter.
Returns:
bool: True if the two arrays are equal within the given tolerance,
False otherwise.
"""
a = a.data if isinstance(a, Variable) else a
b = b.data if isinstance(b, Variable) else b
a, b = cuda.as_numpy(a), cuda.as_numpy(b)
return np.allclose(a, b, atol=atol, rtol=rtol)
# =============================================================================
# download function
# =============================================================================
def show_progress(block_num, block_size, total_size):
bar_template = "\r[{}] {:.2f}%"
downloaded = block_num * block_size
p = downloaded / total_size * 100
i = int(downloaded / total_size * 30)
if p >= 100.0: p = 100.0
if i >= 30: i = 30
bar = "#" * i + "." * (30 - i)
print(bar_template.format(bar, p), end='')
cache_dir = os.path.join(os.path.expanduser('~'), '.dezero')
def get_file(url, file_name=None):
"""Download a file from the `url` if it is not in the cache.
The file at the `url` is downloaded to the `~/.dezero`.
Args:
url (str): URL of the file.
file_name (str): Name of the file. It `None` is specified the original
file name is used.
Returns:
str: Absolute path to the saved file.
"""
if file_name is None:
file_name = url[url.rfind('/') + 1:]
file_path = os.path.join(cache_dir, file_name)
if not os.path.exists(cache_dir):
os.mkdir(cache_dir)
if os.path.exists(file_path):
return file_path
print("Downloading: " + file_name)
try:
urllib.request.urlretrieve(url, file_path, show_progress)
except (Exception, KeyboardInterrupt) as e:
if os.path.exists(file_path):
os.remove(file_path)
raise
print(" Done")
return file_path
# =============================================================================
# others
# =============================================================================
def get_deconv_outsize(size, k, s, p):
return s * (size - 1) + k - 2 * p
def get_conv_outsize(input_size, kernel_size, stride, pad):
return (input_size + pad * 2 - kernel_size) // stride + 1
def pair(x):
if isinstance(x, int):
return (x, x)
elif isinstance(x, tuple):
assert len(x) == 2
return x
else:
raise ValueError