Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

__init__.py 16 KB

You have to be logged in to leave a comment. Sign In
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
  1. import numpy as np
  2. from core.leras import nn
  3. tf = nn.tf
  4. from tensorflow.python.ops import array_ops, random_ops, math_ops, sparse_ops, gradients
  5. from tensorflow.python.framework import sparse_tensor
  6. def tf_get_value(tensor):
  7. return nn.tf_sess.run (tensor)
  8. nn.tf_get_value = tf_get_value
  9. def batch_set_value(tuples):
  10. if len(tuples) != 0:
  11. with nn.tf.device('/CPU:0'):
  12. assign_ops = []
  13. feed_dict = {}
  14. for x, value in tuples:
  15. if isinstance(value, nn.tf.Operation) or \
  16. isinstance(value, nn.tf.Variable):
  17. assign_ops.append(value)
  18. else:
  19. value = np.asarray(value, dtype=x.dtype.as_numpy_dtype)
  20. assign_placeholder = nn.tf.placeholder( x.dtype.base_dtype, shape=[None]*value.ndim )
  21. assign_op = nn.tf.assign (x, assign_placeholder )
  22. assign_ops.append(assign_op)
  23. feed_dict[assign_placeholder] = value
  24. nn.tf_sess.run(assign_ops, feed_dict=feed_dict)
  25. nn.batch_set_value = batch_set_value
  26. def init_weights(weights):
  27. ops = []
  28. ca_tuples_w = []
  29. ca_tuples = []
  30. for w in weights:
  31. initializer = w.initializer
  32. for input in initializer.inputs:
  33. if "_cai_" in input.name:
  34. ca_tuples_w.append (w)
  35. ca_tuples.append ( (w.shape.as_list(), w.dtype.as_numpy_dtype) )
  36. break
  37. else:
  38. ops.append (initializer)
  39. if len(ops) != 0:
  40. nn.tf_sess.run (ops)
  41. if len(ca_tuples) != 0:
  42. nn.batch_set_value( [*zip(ca_tuples_w, nn.initializers.ca.generate_batch (ca_tuples))] )
  43. nn.init_weights = init_weights
  44. def tf_gradients ( loss, vars ):
  45. grads = gradients.gradients(loss, vars, colocate_gradients_with_ops=True )
  46. gv = [*zip(grads,vars)]
  47. for g,v in gv:
  48. if g is None:
  49. raise Exception(f"Variable {v.name} is declared as trainable, but no tensors flow through it.")
  50. return gv
  51. nn.gradients = tf_gradients
  52. def average_gv_list(grad_var_list, tf_device_string=None):
  53. if len(grad_var_list) == 1:
  54. return grad_var_list[0]
  55. e = tf.device(tf_device_string) if tf_device_string is not None else None
  56. if e is not None: e.__enter__()
  57. result = []
  58. for i, (gv) in enumerate(grad_var_list):
  59. for j,(g,v) in enumerate(gv):
  60. g = tf.expand_dims(g, 0)
  61. if i == 0:
  62. result += [ [[g], v] ]
  63. else:
  64. result[j][0] += [g]
  65. for i,(gs,v) in enumerate(result):
  66. result[i] = ( tf.reduce_mean( tf.concat (gs, 0), 0 ), v )
  67. if e is not None: e.__exit__(None,None,None)
  68. return result
  69. nn.average_gv_list = average_gv_list
  70. def average_tensor_list(tensors_list, tf_device_string=None):
  71. if len(tensors_list) == 1:
  72. return tensors_list[0]
  73. e = tf.device(tf_device_string) if tf_device_string is not None else None
  74. if e is not None: e.__enter__()
  75. result = tf.reduce_mean(tf.concat ([tf.expand_dims(t, 0) for t in tensors_list], 0), 0)
  76. if e is not None: e.__exit__(None,None,None)
  77. return result
  78. nn.average_tensor_list = average_tensor_list
  79. def concat (tensors_list, axis):
  80. """
  81. Better version.
  82. """
  83. if len(tensors_list) == 1:
  84. return tensors_list[0]
  85. return tf.concat(tensors_list, axis)
  86. nn.concat = concat
  87. def gelu(x):
  88. cdf = 0.5 * (1.0 + tf.nn.tanh((np.sqrt(2 / np.pi) * (x + 0.044715 * tf.pow(x, 3)))))
  89. return x * cdf
  90. nn.gelu = gelu
  91. def upsample2d(x, size=2):
  92. if nn.data_format == "NCHW":
  93. x = tf.transpose(x, (0,2,3,1))
  94. x = tf.image.resize_nearest_neighbor(x, (x.shape[1]*size, x.shape[2]*size) )
  95. x = tf.transpose(x, (0,3,1,2))
  96. # b,c,h,w = x.shape.as_list()
  97. # x = tf.reshape (x, (-1,c,h,1,w,1) )
  98. # x = tf.tile(x, (1,1,1,size,1,size) )
  99. # x = tf.reshape (x, (-1,c,h*size,w*size) )
  100. return x
  101. else:
  102. return tf.image.resize_nearest_neighbor(x, (x.shape[1]*size, x.shape[2]*size) )
  103. nn.upsample2d = upsample2d
  104. def resize2d_bilinear(x, size=2):
  105. h = x.shape[nn.conv2d_spatial_axes[0]].value
  106. w = x.shape[nn.conv2d_spatial_axes[1]].value
  107. if nn.data_format == "NCHW":
  108. x = tf.transpose(x, (0,2,3,1))
  109. if size > 0:
  110. new_size = (h*size,w*size)
  111. else:
  112. new_size = (h//-size,w//-size)
  113. x = tf.image.resize(x, new_size, method=tf.image.ResizeMethod.BILINEAR)
  114. if nn.data_format == "NCHW":
  115. x = tf.transpose(x, (0,3,1,2))
  116. return x
  117. nn.resize2d_bilinear = resize2d_bilinear
  118. def resize2d_nearest(x, size=2):
  119. if size in [-1,0,1]:
  120. return x
  121. if size > 0:
  122. raise Exception("")
  123. else:
  124. if nn.data_format == "NCHW":
  125. x = x[:,:,::-size,::-size]
  126. else:
  127. x = x[:,::-size,::-size,:]
  128. return x
  129. h = x.shape[nn.conv2d_spatial_axes[0]].value
  130. w = x.shape[nn.conv2d_spatial_axes[1]].value
  131. if nn.data_format == "NCHW":
  132. x = tf.transpose(x, (0,2,3,1))
  133. if size > 0:
  134. new_size = (h*size,w*size)
  135. else:
  136. new_size = (h//-size,w//-size)
  137. x = tf.image.resize(x, new_size, method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)
  138. if nn.data_format == "NCHW":
  139. x = tf.transpose(x, (0,3,1,2))
  140. return x
  141. nn.resize2d_nearest = resize2d_nearest
  142. def flatten(x):
  143. if nn.data_format == "NHWC":
  144. # match NCHW version in order to switch data_format without problems
  145. x = tf.transpose(x, (0,3,1,2) )
  146. return tf.reshape (x, (-1, np.prod(x.shape[1:])) )
  147. nn.flatten = flatten
  148. def max_pool(x, kernel_size=2, strides=2):
  149. if nn.data_format == "NHWC":
  150. return tf.nn.max_pool(x, [1,kernel_size,kernel_size,1], [1,strides,strides,1], 'SAME', data_format=nn.data_format)
  151. else:
  152. return tf.nn.max_pool(x, [1,1,kernel_size,kernel_size], [1,1,strides,strides], 'SAME', data_format=nn.data_format)
  153. nn.max_pool = max_pool
  154. def reshape_4D(x, w,h,c):
  155. if nn.data_format == "NHWC":
  156. # match NCHW version in order to switch data_format without problems
  157. x = tf.reshape (x, (-1,c,h,w))
  158. x = tf.transpose(x, (0,2,3,1) )
  159. return x
  160. else:
  161. return tf.reshape (x, (-1,c,h,w))
  162. nn.reshape_4D = reshape_4D
  163. def random_binomial(shape, p=0.0, dtype=None, seed=None):
  164. if dtype is None:
  165. dtype=tf.float32
  166. if seed is None:
  167. seed = np.random.randint(10e6)
  168. return array_ops.where(
  169. random_ops.random_uniform(shape, dtype=tf.float16, seed=seed) < p,
  170. array_ops.ones(shape, dtype=dtype), array_ops.zeros(shape, dtype=dtype))
  171. nn.random_binomial = random_binomial
  172. def gaussian_blur(input, radius=2.0):
  173. def gaussian(x, mu, sigma):
  174. return np.exp(-(float(x) - float(mu)) ** 2 / (2 * sigma ** 2))
  175. def make_kernel(sigma):
  176. kernel_size = max(3, int(2 * 2 * sigma))
  177. if kernel_size % 2 == 0:
  178. kernel_size += 1
  179. mean = np.floor(0.5 * kernel_size)
  180. kernel_1d = np.array([gaussian(x, mean, sigma) for x in range(kernel_size)])
  181. np_kernel = np.outer(kernel_1d, kernel_1d).astype(np.float32)
  182. kernel = np_kernel / np.sum(np_kernel)
  183. return kernel, kernel_size
  184. gauss_kernel, kernel_size = make_kernel(radius)
  185. padding = kernel_size//2
  186. if padding != 0:
  187. if nn.data_format == "NHWC":
  188. padding = [ [0,0], [padding,padding], [padding,padding], [0,0] ]
  189. else:
  190. padding = [ [0,0], [0,0], [padding,padding], [padding,padding] ]
  191. else:
  192. padding = None
  193. gauss_kernel = gauss_kernel[:,:,None,None]
  194. x = input
  195. k = tf.tile (gauss_kernel, (1,1,x.shape[nn.conv2d_ch_axis],1) )
  196. x = tf.pad(x, padding )
  197. x = tf.nn.depthwise_conv2d(x, k, strides=[1,1,1,1], padding='VALID', data_format=nn.data_format)
  198. return x
  199. nn.gaussian_blur = gaussian_blur
  200. def style_loss(target, style, gaussian_blur_radius=0.0, loss_weight=1.0, step_size=1):
  201. def sd(content, style, loss_weight):
  202. content_nc = content.shape[ nn.conv2d_ch_axis ]
  203. style_nc = style.shape[nn.conv2d_ch_axis]
  204. if content_nc != style_nc:
  205. raise Exception("style_loss() content_nc != style_nc")
  206. c_mean, c_var = tf.nn.moments(content, axes=nn.conv2d_spatial_axes, keep_dims=True)
  207. s_mean, s_var = tf.nn.moments(style, axes=nn.conv2d_spatial_axes, keep_dims=True)
  208. c_std, s_std = tf.sqrt(c_var + 1e-5), tf.sqrt(s_var + 1e-5)
  209. mean_loss = tf.reduce_sum(tf.square(c_mean-s_mean), axis=[1,2,3])
  210. std_loss = tf.reduce_sum(tf.square(c_std-s_std), axis=[1,2,3])
  211. return (mean_loss + std_loss) * ( loss_weight / content_nc.value )
  212. if gaussian_blur_radius > 0.0:
  213. target = gaussian_blur(target, gaussian_blur_radius)
  214. style = gaussian_blur(style, gaussian_blur_radius)
  215. return sd( target, style, loss_weight=loss_weight )
  216. nn.style_loss = style_loss
  217. def dssim(img1,img2, max_val, filter_size=11, filter_sigma=1.5, k1=0.01, k2=0.03):
  218. if img1.dtype != img2.dtype:
  219. raise ValueError("img1.dtype != img2.dtype")
  220. not_float32 = img1.dtype != tf.float32
  221. if not_float32:
  222. img_dtype = img1.dtype
  223. img1 = tf.cast(img1, tf.float32)
  224. img2 = tf.cast(img2, tf.float32)
  225. filter_size = max(1, filter_size)
  226. kernel = np.arange(0, filter_size, dtype=np.float32)
  227. kernel -= (filter_size - 1 ) / 2.0
  228. kernel = kernel**2
  229. kernel *= ( -0.5 / (filter_sigma**2) )
  230. kernel = np.reshape (kernel, (1,-1)) + np.reshape(kernel, (-1,1) )
  231. kernel = tf.constant ( np.reshape (kernel, (1,-1)), dtype=tf.float32 )
  232. kernel = tf.nn.softmax(kernel)
  233. kernel = tf.reshape (kernel, (filter_size, filter_size, 1, 1))
  234. kernel = tf.tile (kernel, (1,1, img1.shape[ nn.conv2d_ch_axis ] ,1))
  235. def reducer(x):
  236. return tf.nn.depthwise_conv2d(x, kernel, strides=[1,1,1,1], padding='VALID', data_format=nn.data_format)
  237. c1 = (k1 * max_val) ** 2
  238. c2 = (k2 * max_val) ** 2
  239. mean0 = reducer(img1)
  240. mean1 = reducer(img2)
  241. num0 = mean0 * mean1 * 2.0
  242. den0 = tf.square(mean0) + tf.square(mean1)
  243. luminance = (num0 + c1) / (den0 + c1)
  244. num1 = reducer(img1 * img2) * 2.0
  245. den1 = reducer(tf.square(img1) + tf.square(img2))
  246. c2 *= 1.0 #compensation factor
  247. cs = (num1 - num0 + c2) / (den1 - den0 + c2)
  248. ssim_val = tf.reduce_mean(luminance * cs, axis=nn.conv2d_spatial_axes )
  249. dssim = (1.0 - ssim_val ) / 2.0
  250. if not_float32:
  251. dssim = tf.cast(dssim, img_dtype)
  252. return dssim
  253. nn.dssim = dssim
  254. def space_to_depth(x, size):
  255. if nn.data_format == "NHWC":
  256. # match NCHW version in order to switch data_format without problems
  257. b,h,w,c = x.shape.as_list()
  258. oh, ow = h // size, w // size
  259. x = tf.reshape(x, (-1, size, oh, size, ow, c))
  260. x = tf.transpose(x, (0, 2, 4, 1, 3, 5))
  261. x = tf.reshape(x, (-1, oh, ow, size* size* c ))
  262. return x
  263. else:
  264. return tf.space_to_depth(x, size, data_format=nn.data_format)
  265. nn.space_to_depth = space_to_depth
  266. def depth_to_space(x, size):
  267. if nn.data_format == "NHWC":
  268. # match NCHW version in order to switch data_format without problems
  269. b,h,w,c = x.shape.as_list()
  270. oh, ow = h * size, w * size
  271. oc = c // (size * size)
  272. x = tf.reshape(x, (-1, h, w, size, size, oc, ) )
  273. x = tf.transpose(x, (0, 1, 3, 2, 4, 5))
  274. x = tf.reshape(x, (-1, oh, ow, oc, ))
  275. return x
  276. else:
  277. cfg = nn.getCurrentDeviceConfig()
  278. if not cfg.cpu_only:
  279. return tf.depth_to_space(x, size, data_format=nn.data_format)
  280. b,c,h,w = x.shape.as_list()
  281. oh, ow = h * size, w * size
  282. oc = c // (size * size)
  283. x = tf.reshape(x, (-1, size, size, oc, h, w, ) )
  284. x = tf.transpose(x, (0, 3, 4, 1, 5, 2))
  285. x = tf.reshape(x, (-1, oc, oh, ow))
  286. return x
  287. nn.depth_to_space = depth_to_space
  288. def rgb_to_lab(srgb):
  289. srgb_pixels = tf.reshape(srgb, [-1, 3])
  290. linear_mask = tf.cast(srgb_pixels <= 0.04045, dtype=tf.float32)
  291. exponential_mask = tf.cast(srgb_pixels > 0.04045, dtype=tf.float32)
  292. rgb_pixels = (srgb_pixels / 12.92 * linear_mask) + (((srgb_pixels + 0.055) / 1.055) ** 2.4) * exponential_mask
  293. rgb_to_xyz = tf.constant([
  294. # X Y Z
  295. [0.412453, 0.212671, 0.019334], # R
  296. [0.357580, 0.715160, 0.119193], # G
  297. [0.180423, 0.072169, 0.950227], # B
  298. ])
  299. xyz_pixels = tf.matmul(rgb_pixels, rgb_to_xyz)
  300. xyz_normalized_pixels = tf.multiply(xyz_pixels, [1/0.950456, 1.0, 1/1.088754])
  301. epsilon = 6/29
  302. linear_mask = tf.cast(xyz_normalized_pixels <= (epsilon**3), dtype=tf.float32)
  303. exponential_mask = tf.cast(xyz_normalized_pixels > (epsilon**3), dtype=tf.float32)
  304. fxfyfz_pixels = (xyz_normalized_pixels / (3 * epsilon**2) + 4/29) * linear_mask + (xyz_normalized_pixels ** (1/3)) * exponential_mask
  305. fxfyfz_to_lab = tf.constant([
  306. # l a b
  307. [ 0.0, 500.0, 0.0], # fx
  308. [116.0, -500.0, 200.0], # fy
  309. [ 0.0, 0.0, -200.0], # fz
  310. ])
  311. lab_pixels = tf.matmul(fxfyfz_pixels, fxfyfz_to_lab) + tf.constant([-16.0, 0.0, 0.0])
  312. return tf.reshape(lab_pixels, tf.shape(srgb))
  313. nn.rgb_to_lab = rgb_to_lab
  314. def total_variation_mse(images):
  315. """
  316. Same as generic total_variation, but MSE diff instead of MAE
  317. """
  318. pixel_dif1 = images[:, 1:, :, :] - images[:, :-1, :, :]
  319. pixel_dif2 = images[:, :, 1:, :] - images[:, :, :-1, :]
  320. tot_var = ( tf.reduce_sum(tf.square(pixel_dif1), axis=[1,2,3]) +
  321. tf.reduce_sum(tf.square(pixel_dif2), axis=[1,2,3]) )
  322. return tot_var
  323. nn.total_variation_mse = total_variation_mse
  324. def pixel_norm(x, axes):
  325. return x * tf.rsqrt(tf.reduce_mean(tf.square(x), axis=axes, keepdims=True) + 1e-06)
  326. nn.pixel_norm = pixel_norm
  327. """
  328. def tf_suppress_lower_mean(t, eps=0.00001):
  329. if t.shape.ndims != 1:
  330. raise ValueError("tf_suppress_lower_mean: t rank must be 1")
  331. t_mean_eps = tf.reduce_mean(t) - eps
  332. q = tf.clip_by_value(t, t_mean_eps, tf.reduce_max(t) )
  333. q = tf.clip_by_value(q-t_mean_eps, 0, eps)
  334. q = q * (t/eps)
  335. return q
  336. """
  337. def _get_pixel_value(img, x, y):
  338. shape = tf.shape(x)
  339. batch_size = shape[0]
  340. height = shape[1]
  341. width = shape[2]
  342. batch_idx = tf.range(0, batch_size)
  343. batch_idx = tf.reshape(batch_idx, (batch_size, 1, 1))
  344. b = tf.tile(batch_idx, (1, height, width))
  345. indices = tf.stack([b, y, x], 3)
  346. return tf.gather_nd(img, indices)
  347. def bilinear_sampler(img, x, y):
  348. H = tf.shape(img)[1]
  349. W = tf.shape(img)[2]
  350. H_MAX = tf.cast(H - 1, tf.int32)
  351. W_MAX = tf.cast(W - 1, tf.int32)
  352. # grab 4 nearest corner points for each (x_i, y_i)
  353. x0 = tf.cast(tf.floor(x), tf.int32)
  354. x1 = x0 + 1
  355. y0 = tf.cast(tf.floor(y), tf.int32)
  356. y1 = y0 + 1
  357. # clip to range [0, H-1/W-1] to not violate img boundaries
  358. x0 = tf.clip_by_value(x0, 0, W_MAX)
  359. x1 = tf.clip_by_value(x1, 0, W_MAX)
  360. y0 = tf.clip_by_value(y0, 0, H_MAX)
  361. y1 = tf.clip_by_value(y1, 0, H_MAX)
  362. # get pixel value at corner coords
  363. Ia = _get_pixel_value(img, x0, y0)
  364. Ib = _get_pixel_value(img, x0, y1)
  365. Ic = _get_pixel_value(img, x1, y0)
  366. Id = _get_pixel_value(img, x1, y1)
  367. # recast as float for delta calculation
  368. x0 = tf.cast(x0, tf.float32)
  369. x1 = tf.cast(x1, tf.float32)
  370. y0 = tf.cast(y0, tf.float32)
  371. y1 = tf.cast(y1, tf.float32)
  372. # calculate deltas
  373. wa = (x1-x) * (y1-y)
  374. wb = (x1-x) * (y-y0)
  375. wc = (x-x0) * (y1-y)
  376. wd = (x-x0) * (y-y0)
  377. # add dimension for addition
  378. wa = tf.expand_dims(wa, axis=3)
  379. wb = tf.expand_dims(wb, axis=3)
  380. wc = tf.expand_dims(wc, axis=3)
  381. wd = tf.expand_dims(wd, axis=3)
  382. # compute output
  383. out = tf.add_n([wa*Ia, wb*Ib, wc*Ic, wd*Id])
  384. return out
  385. nn.bilinear_sampler = bilinear_sampler
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...