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

#578 Feature/sg 516 support head replacement for local pretrained weights unknown dataset

Merged
Ghost merged 1 commits into Deci-AI:master from deci-ai:feature/SG-516_support_head_replacement_for_local_pretrained_weights_unknown_dataset
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
  1. """ RandAugment
  2. RandAugment is a variant of AutoAugment which randomly selects transformations
  3. from AutoAugment to be applied on an image.
  4. RandomAugmentation Implementation adapted from:
  5. https://github.com/rwightman/pytorch-image-models/blob/master/timm/data/auto_augment.py
  6. Papers:
  7. RandAugment: Practical automated data augmentation... - https://arxiv.org/abs/1909.13719
  8. """
  9. import random
  10. import re
  11. from typing import List
  12. from PIL import Image, ImageOps, ImageEnhance
  13. import numpy as np
  14. _FILL = (128, 128, 128)
  15. # to unify the calls of the different augmentations in terms of params, all augmentations are set to work with a single
  16. # magnitude params, normalized according to _MAX_MAGNITUDE
  17. _MAX_MAGNITUDE = 10.
  18. _HPARAMS_DEFAULT = dict(
  19. translate_const=250,
  20. img_mean=_FILL,
  21. )
  22. # Define the interpolation types
  23. _RANDOM_INTERPOLATION = Image.BILINEAR
  24. def _interpolation(kwargs):
  25. """
  26. Performs Bi-Linear interpolation
  27. """
  28. interpolation = kwargs.pop('resample', Image.BILINEAR)
  29. if isinstance(interpolation, (list, tuple)):
  30. return random.choice(interpolation)
  31. else:
  32. return interpolation
  33. def shear_x(img, factor, **kwargs):
  34. return img.transform(img.size, Image.AFFINE, (1, factor, 0, 0, 1, 0), **kwargs)
  35. def shear_y(img, factor, **kwargs):
  36. return img.transform(img.size, Image.AFFINE, (1, 0, 0, factor, 1, 0), **kwargs)
  37. def translate_x_rel(img, pct, **kwargs):
  38. pixels = pct * img.size[0]
  39. return img.transform(img.size, Image.AFFINE, (1, 0, pixels, 0, 1, 0), **kwargs)
  40. def translate_y_rel(img, pct, **kwargs):
  41. pixels = pct * img.size[1]
  42. return img.transform(img.size, Image.AFFINE, (1, 0, 0, 0, 1, pixels), **kwargs)
  43. def translate_x_abs(img, pixels, **kwargs):
  44. return img.transform(img.size, Image.AFFINE, (1, 0, pixels, 0, 1, 0), **kwargs)
  45. def translate_y_abs(img, pixels, **kwargs):
  46. return img.transform(img.size, Image.AFFINE, (1, 0, 0, 0, 1, pixels), **kwargs)
  47. def rotate(img, degrees, **kwargs):
  48. return img.rotate(degrees, **kwargs)
  49. def auto_contrast(img, **__):
  50. return ImageOps.autocontrast(img)
  51. def invert(img, **__):
  52. return ImageOps.invert(img)
  53. def equalize(img, **__):
  54. return ImageOps.equalize(img)
  55. def solarize(img, thresh, **__):
  56. return ImageOps.solarize(img, thresh)
  57. def solarize_add(img, add, thresh=128, **__):
  58. lut = []
  59. for i in range(256):
  60. if i < thresh:
  61. lut.append(min(255, i + add))
  62. else:
  63. lut.append(i)
  64. if img.mode in ("L", "RGB"):
  65. if img.mode == "RGB" and len(lut) == 256:
  66. lut = lut + lut + lut
  67. return img.point(lut)
  68. else:
  69. return img
  70. def posterize(img, bits_to_keep, **__):
  71. if bits_to_keep >= 8:
  72. return img
  73. return ImageOps.posterize(img, bits_to_keep)
  74. def contrast(img, factor, **__):
  75. return ImageEnhance.Contrast(img).enhance(factor)
  76. def color(img, factor, **__):
  77. return ImageEnhance.Color(img).enhance(factor)
  78. def brightness(img, factor, **__):
  79. return ImageEnhance.Brightness(img).enhance(factor)
  80. def sharpness(img, factor, **__):
  81. return ImageEnhance.Sharpness(img).enhance(factor)
  82. def _randomly_negate(v):
  83. """With 50% prob, negate the value"""
  84. return -v if random.random() > 0.5 else v
  85. def _rotate_level_to_arg(level, _hparams):
  86. # range [-30, 30]
  87. level = (level / _MAX_MAGNITUDE) * 30.
  88. level = _randomly_negate(level)
  89. return level,
  90. def _enhance_level_to_arg(level, _hparams):
  91. # range [0.1, 1.9]
  92. return (level / _MAX_MAGNITUDE) * 1.8 + 0.1,
  93. def _enhance_increasing_level_to_arg(level, _hparams):
  94. # range [0.1, 1.9]
  95. level = (level / _MAX_MAGNITUDE) * .9
  96. level = 1.0 + _randomly_negate(level)
  97. return level,
  98. def _shear_level_to_arg(level, _hparams):
  99. # range [-0.3, 0.3]
  100. level = (level / _MAX_MAGNITUDE) * 0.3
  101. level = _randomly_negate(level)
  102. return level,
  103. def _translate_abs_level_to_arg(level, hparams):
  104. translate_const = hparams['translate_const']
  105. level = (level / _MAX_MAGNITUDE) * float(translate_const)
  106. level = _randomly_negate(level)
  107. return level,
  108. def _translate_rel_level_to_arg(level, hparams):
  109. # default range [-0.45, 0.45]
  110. translate_pct = hparams.get('translate_pct', 0.45)
  111. level = (level / _MAX_MAGNITUDE) * translate_pct
  112. level = _randomly_negate(level)
  113. return level,
  114. def _posterize_level_to_arg(level, _hparams):
  115. # As per Tensorflow TPU EfficientNet impl
  116. # range [0, 4], 'keep 0 up to 4 MSB of original image'
  117. # intensity/severity of augmentation decreases with level
  118. return int((level / _MAX_MAGNITUDE) * 4),
  119. def _posterize_increasing_level_to_arg(level, hparams):
  120. # As per Tensorflow models research and UDA impl
  121. # range [4, 0], 'keep 4 down to 0 MSB of original image',
  122. # intensity/severity of augmentation increases with level
  123. return 4 - _posterize_level_to_arg(level, hparams)[0],
  124. def _posterize_original_level_to_arg(level, _hparams):
  125. # As per original AutoAugment paper description
  126. # range [4, 8], 'keep 4 up to 8 MSB of image'
  127. # intensity/severity of augmentation decreases with level
  128. return int((level / _MAX_MAGNITUDE) * 4) + 4,
  129. def _solarize_level_to_arg(level, _hparams):
  130. # range [0, 256]
  131. # intensity/severity of augmentation decreases with level
  132. return int((level / _MAX_MAGNITUDE) * 256),
  133. def _solarize_increasing_level_to_arg(level, _hparams):
  134. # range [0, 256]
  135. # intensity/severity of augmentation increases with level
  136. return 256 - _solarize_level_to_arg(level, _hparams)[0],
  137. def _solarize_add_level_to_arg(level, _hparams):
  138. # range [0, 110]
  139. return int((level / _MAX_MAGNITUDE) * 110),
  140. LEVEL_TO_ARG = {
  141. 'AutoContrast': None,
  142. 'Equalize': None,
  143. 'Invert': None,
  144. 'Rotate': _rotate_level_to_arg,
  145. # There are several variations of the posterize level scaling in various Tensorflow/Google repositories/papers
  146. 'Posterize': _posterize_level_to_arg,
  147. 'PosterizeIncreasing': _posterize_increasing_level_to_arg,
  148. 'PosterizeOriginal': _posterize_original_level_to_arg,
  149. 'Solarize': _solarize_level_to_arg,
  150. 'SolarizeIncreasing': _solarize_increasing_level_to_arg,
  151. 'SolarizeAdd': _solarize_add_level_to_arg,
  152. 'Color': _enhance_level_to_arg,
  153. 'ColorIncreasing': _enhance_increasing_level_to_arg,
  154. 'Contrast': _enhance_level_to_arg,
  155. 'ContrastIncreasing': _enhance_increasing_level_to_arg,
  156. 'Brightness': _enhance_level_to_arg,
  157. 'BrightnessIncreasing': _enhance_increasing_level_to_arg,
  158. 'Sharpness': _enhance_level_to_arg,
  159. 'SharpnessIncreasing': _enhance_increasing_level_to_arg,
  160. 'ShearX': _shear_level_to_arg,
  161. 'ShearY': _shear_level_to_arg,
  162. 'TranslateX': _translate_abs_level_to_arg,
  163. 'TranslateY': _translate_abs_level_to_arg,
  164. 'TranslateXRel': _translate_rel_level_to_arg,
  165. 'TranslateYRel': _translate_rel_level_to_arg,
  166. }
  167. NAME_TO_OP = {
  168. 'AutoContrast': auto_contrast,
  169. 'Equalize': equalize,
  170. 'Invert': invert,
  171. 'Rotate': rotate,
  172. 'Posterize': posterize,
  173. 'PosterizeIncreasing': posterize,
  174. 'PosterizeOriginal': posterize,
  175. 'Solarize': solarize,
  176. 'SolarizeIncreasing': solarize,
  177. 'SolarizeAdd': solarize_add,
  178. 'Color': color,
  179. 'ColorIncreasing': color,
  180. 'Contrast': contrast,
  181. 'ContrastIncreasing': contrast,
  182. 'Brightness': brightness,
  183. 'BrightnessIncreasing': brightness,
  184. 'Sharpness': sharpness,
  185. 'SharpnessIncreasing': sharpness,
  186. 'ShearX': shear_x,
  187. 'ShearY': shear_y,
  188. 'TranslateX': translate_x_abs,
  189. 'TranslateY': translate_y_abs,
  190. 'TranslateXRel': translate_x_rel,
  191. 'TranslateYRel': translate_y_rel,
  192. }
  193. class AugmentOp:
  194. """
  195. single auto augment operations
  196. """
  197. def __init__(self, name, prob=0.5, magnitude=10, hparams=None):
  198. hparams = hparams or _HPARAMS_DEFAULT
  199. self.aug_fn = NAME_TO_OP[name]
  200. self.level_fn = LEVEL_TO_ARG[name]
  201. self.prob = prob
  202. self.magnitude = magnitude
  203. self.hparams = hparams.copy()
  204. self.kwargs = dict(
  205. fillcolor=hparams['img_mean'] if 'img_mean' in hparams else _FILL,
  206. resample=hparams['interpolation'] if 'interpolation' in hparams else _RANDOM_INTERPOLATION,
  207. )
  208. # If magnitude_std is > 0, introduce some randomness
  209. self.magnitude_std = self.hparams.get('magnitude_std', 0)
  210. def __call__(self, img):
  211. if self.prob < 1.0 and random.random() > self.prob:
  212. return img
  213. magnitude = self.magnitude
  214. if self.magnitude_std:
  215. if self.magnitude_std == float('inf'):
  216. magnitude = random.uniform(0, magnitude)
  217. elif self.magnitude_std > 0:
  218. magnitude = random.gauss(magnitude, self.magnitude_std)
  219. magnitude = min(_MAX_MAGNITUDE, max(0, magnitude)) # clip to valid range
  220. level_args = self.level_fn(magnitude, self.hparams) if self.level_fn is not None else tuple()
  221. return self.aug_fn(img, *level_args, **self.kwargs)
  222. _RAND_TRANSFORMS = [
  223. 'AutoContrast',
  224. 'Equalize',
  225. 'Invert',
  226. 'Rotate',
  227. 'Posterize',
  228. 'Solarize',
  229. 'SolarizeAdd',
  230. 'Color',
  231. 'Contrast',
  232. 'Brightness',
  233. 'Sharpness',
  234. 'ShearX',
  235. 'ShearY',
  236. 'TranslateXRel',
  237. 'TranslateYRel',
  238. # 'Cutout' # NOTE I've implement this as random erasing separately
  239. ]
  240. _RAND_INCREASING_TRANSFORMS = [
  241. 'AutoContrast',
  242. 'Equalize',
  243. 'Invert',
  244. 'Rotate',
  245. 'PosterizeIncreasing',
  246. 'SolarizeIncreasing',
  247. 'SolarizeAdd',
  248. 'ColorIncreasing',
  249. 'ContrastIncreasing',
  250. 'BrightnessIncreasing',
  251. 'SharpnessIncreasing',
  252. 'ShearX',
  253. 'ShearY',
  254. 'TranslateXRel',
  255. 'TranslateYRel',
  256. # 'Cutout' # NOTE I've implement this as random erasing separately
  257. ]
  258. # These experimental weights are based loosely on the relative improvements mentioned in paper.
  259. # They may not result in increased performance, but could likely be tuned to so.
  260. _RAND_CHOICE_WEIGHTS_0 = {
  261. 'Rotate': 0.3,
  262. 'ShearX': 0.2,
  263. 'ShearY': 0.2,
  264. 'TranslateXRel': 0.1,
  265. 'TranslateYRel': 0.1,
  266. 'Color': .025,
  267. 'Sharpness': 0.025,
  268. 'AutoContrast': 0.025,
  269. 'Solarize': .005,
  270. 'SolarizeAdd': .005,
  271. 'Contrast': .005,
  272. 'Brightness': .005,
  273. 'Equalize': .005,
  274. 'Posterize': 0,
  275. 'Invert': 0,
  276. }
  277. def _select_rand_weights(weight_idx=0, transforms=None):
  278. transforms = transforms or _RAND_TRANSFORMS
  279. assert weight_idx == 0 # only one set of weights currently
  280. rand_weights = _RAND_CHOICE_WEIGHTS_0
  281. probs = [rand_weights[k] for k in transforms]
  282. probs /= np.sum(probs)
  283. return probs
  284. def rand_augment_ops(magnitude=10, hparams=None, transforms=None):
  285. hparams = hparams or _HPARAMS_DEFAULT
  286. transforms = transforms or _RAND_TRANSFORMS
  287. return [AugmentOp(
  288. name, prob=0.5, magnitude=magnitude, hparams=hparams) for name in transforms]
  289. class RandAugment:
  290. """
  291. Random auto augment class, will select auto augment transforms according to probability weights for each op
  292. """
  293. def __init__(self, ops, num_layers=2, choice_weights=None):
  294. self.ops = ops
  295. self.num_layers = num_layers
  296. self.choice_weights = choice_weights
  297. def __call__(self, img):
  298. # no replacement when using weighted choice
  299. ops = np.random.choice(
  300. self.ops, self.num_layers, replace=self.choice_weights is None, p=self.choice_weights)
  301. for op in ops:
  302. img = op(img)
  303. return img
  304. def rand_augment_transform(config_str, crop_size: int, img_mean: List[float]):
  305. """
  306. Create a RandAugment transform
  307. :param config_str: String defining configuration of random augmentation. Consists of multiple sections separated by
  308. dashes ('-'). The first section defines the specific variant of rand augment (currently only 'rand'). The remaining
  309. sections, not order sepecific determine
  310. 'm' - integer magnitude of rand augment
  311. 'n' - integer num layers (number of transform ops selected per image)
  312. 'w' - integer probabiliy weight index (index of a set of weights to influence choice of op)
  313. 'mstd' - float std deviation of magnitude noise applied
  314. 'inc' - integer (bool), use augmentations that increase in severity with magnitude (default: 0)
  315. Ex 'rand-m9-n3-mstd0.5' results in RandAugment with magnitude 9, num_layers 3, magnitude_std 0.5
  316. 'rand-mstd1-w0' results in magnitude_std 1.0, weights 0, default magnitude of 10 and num_layers 2
  317. :param crop_size: The size of crop image
  318. :param img_mean: Average per channel
  319. :return: A PyTorch compatible Transform
  320. """
  321. hparams = dict(translate_const=int(crop_size * 0.45),
  322. img_mean=tuple([min(255, round(255 * channel_mean)) for channel_mean in img_mean]))
  323. magnitude = _MAX_MAGNITUDE # default to _MAX_MAGNITUDE for magnitude (currently 10)
  324. num_layers = 2 # default to 2 ops per image
  325. weight_idx = None # default to no probability weights for op choice
  326. transforms = _RAND_TRANSFORMS
  327. config = config_str.split('-')
  328. for c in config:
  329. cs = re.split(r'(\d.*)', c)
  330. if len(cs) < 2:
  331. continue
  332. key, val = cs[:2]
  333. if key == 'mstd':
  334. # noise param injected via hparams for now
  335. hparams.setdefault('magnitude_std', float(val))
  336. elif key == 'inc':
  337. if bool(val):
  338. transforms = _RAND_INCREASING_TRANSFORMS
  339. elif key == 'm':
  340. magnitude = int(val)
  341. elif key == 'n':
  342. num_layers = int(val)
  343. elif key == 'w':
  344. weight_idx = int(val)
  345. else:
  346. assert False, 'Unknown RandAugment config section'
  347. ra_ops = rand_augment_ops(magnitude=magnitude, hparams=hparams, transforms=transforms)
  348. choice_weights = None if weight_idx is None else _select_rand_weights(weight_idx)
  349. return RandAugment(ra_ops, num_layers, choice_weights=choice_weights)
Discard
Tip!

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