bbexx commited on
Commit
e1927f5
1 Parent(s): 999ed39
Files changed (1) hide show
  1. vitamin.py +34 -1
vitamin.py CHANGED
@@ -31,7 +31,7 @@ from torch.utils.checkpoint import checkpoint
31
  from timm.models.layers import create_attn, get_norm_layer, get_norm_act_layer, create_conv2d, make_divisible, trunc_normal_tf_
32
 
33
 
34
- from timm.layers import to_2tuple, DropPath, Format, trunc_normal_
35
  from timm.layers.norm_act import _create_act
36
  from timm.models._registry import register_model
37
  from timm.models._manipulate import named_apply, checkpoint_seq
@@ -335,6 +335,39 @@ class HybridEmbed(nn.Module):
335
  x = x.flatten(2).transpose(1, 2)
336
  return x
337
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
338
  class ViTamin(nn.Module):
339
  """ hack timm VisionTransformer
340
  """
 
31
  from timm.models.layers import create_attn, get_norm_layer, get_norm_act_layer, create_conv2d, make_divisible, trunc_normal_tf_
32
 
33
 
34
+ from timm.layers import to_2tuple, DropPath, Format # , trunc_normal_
35
  from timm.layers.norm_act import _create_act
36
  from timm.models._registry import register_model
37
  from timm.models._manipulate import named_apply, checkpoint_seq
 
335
  x = x.flatten(2).transpose(1, 2)
336
  return x
337
 
338
+ def _trunc_normal_(tensor, mean, std, a, b):
339
+ # rewrite timm trunc normal
340
+ def norm_cdf(x):
341
+ # Computes standard normal cumulative distribution function
342
+ return (1. + math.erf(x / math.sqrt(2.))) / 2.
343
+
344
+ if (mean < a - 2 * std) or (mean > b + 2 * std):
345
+ warnings.warn("mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
346
+ "The distribution of values may be incorrect.",
347
+ stacklevel=2)
348
+
349
+ l = norm_cdf((a - mean) / std)
350
+ u = norm_cdf((b - mean) / std)
351
+
352
+ # Uniformly fill tensor with values from [l, u], then translate to
353
+ # [2l-1, 2u-1].
354
+ tensor.uniform_(2 * l - 1, 2 * u - 1)
355
+
356
+ # Use inverse cdf transform for normal distribution to get truncated standard normal
357
+ # tensor.erfinv_() # NOTE: deleted as "erfinv_cuda" not implemented for 'BFloat16'
358
+
359
+ # Transform to proper mean, std
360
+ tensor.mul_(std * math.sqrt(2.))
361
+ tensor.add_(mean)
362
+
363
+ # Clamp to ensure it's in the proper range
364
+ tensor.clamp_(min=a, max=b)
365
+ return tensor
366
+
367
+ def trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.):
368
+ with torch.no_grad():
369
+ return _trunc_normal_(tensor, mean, std, a, b)
370
+
371
  class ViTamin(nn.Module):
372
  """ hack timm VisionTransformer
373
  """