yanze commited on
Commit
972091b
1 Parent(s): e7d2488

Update eva_clip/transformer.py

Browse files
Files changed (1) hide show
  1. eva_clip/transformer.py +60 -5
eva_clip/transformer.py CHANGED
@@ -2,17 +2,13 @@ import os
2
  import logging
3
  from collections import OrderedDict
4
  import math
 
5
  from typing import Callable, Optional, Sequence
6
  import numpy as np
7
  import torch
8
  from torch import nn
9
  from torch.nn import functional as F
10
 
11
- try:
12
- from timm.models.layers import trunc_normal_
13
- except:
14
- from timm.layers import trunc_normal_
15
-
16
  from .rope import VisionRotaryEmbedding, VisionRotaryEmbeddingFast
17
  from .utils import to_2tuple
18
 
@@ -33,6 +29,65 @@ except ImportError:
33
  xops = None
34
  print("Please 'pip install xformers'")
35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  class LayerNormFp32(nn.LayerNorm):
37
  """Subclass torch's LayerNorm to handle fp16 (by casting to float32 and back)."""
38
  def __init__(self, *args, **kwargs):
 
2
  import logging
3
  from collections import OrderedDict
4
  import math
5
+ import warnings
6
  from typing import Callable, Optional, Sequence
7
  import numpy as np
8
  import torch
9
  from torch import nn
10
  from torch.nn import functional as F
11
 
 
 
 
 
 
12
  from .rope import VisionRotaryEmbedding, VisionRotaryEmbeddingFast
13
  from .utils import to_2tuple
14
 
 
29
  xops = None
30
  print("Please 'pip install xformers'")
31
 
32
+
33
+ def _no_grad_trunc_normal_(tensor, mean, std, a, b):
34
+ # Cut & paste from PyTorch official master until it's in a few official releases - RW
35
+ # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
36
+ def norm_cdf(x):
37
+ # Computes standard normal cumulative distribution function
38
+ return (1. + math.erf(x / math.sqrt(2.))) / 2.
39
+
40
+ if (mean < a - 2 * std) or (mean > b + 2 * std):
41
+ warnings.warn("mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
42
+ "The distribution of values may be incorrect.",
43
+ stacklevel=2)
44
+
45
+ with torch.no_grad():
46
+ # Values are generated by using a truncated uniform distribution and
47
+ # then using the inverse CDF for the normal distribution.
48
+ # Get upper and lower cdf values
49
+ l = norm_cdf((a - mean) / std)
50
+ u = norm_cdf((b - mean) / std)
51
+
52
+ # Uniformly fill tensor with values from [l, u], then translate to
53
+ # [2l-1, 2u-1].
54
+ tensor.uniform_(2 * l - 1, 2 * u - 1)
55
+
56
+ # Use inverse cdf transform for normal distribution to get truncated
57
+ # standard normal
58
+ tensor.erfinv_()
59
+
60
+ # Transform to proper mean, std
61
+ tensor.mul_(std * math.sqrt(2.))
62
+ tensor.add_(mean)
63
+
64
+ # Clamp to ensure it's in the proper range
65
+ tensor.clamp_(min=a, max=b)
66
+ return tensor
67
+
68
+
69
+ def trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.):
70
+ # type: (Tensor, float, float, float, float) -> Tensor
71
+ r"""Fills the input Tensor with values drawn from a truncated
72
+ normal distribution. The values are effectively drawn from the
73
+ normal distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)`
74
+ with values outside :math:`[a, b]` redrawn until they are within
75
+ the bounds. The method used for generating the random values works
76
+ best when :math:`a \leq \text{mean} \leq b`.
77
+ Args:
78
+ tensor: an n-dimensional `torch.Tensor`
79
+ mean: the mean of the normal distribution
80
+ std: the standard deviation of the normal distribution
81
+ a: the minimum cutoff value
82
+ b: the maximum cutoff value
83
+ Examples:
84
+ >>> w = torch.empty(3, 5)
85
+ >>> nn.init.trunc_normal_(w)
86
+ """
87
+ return _no_grad_trunc_normal_(tensor, mean, std, a, b)
88
+
89
+
90
+
91
  class LayerNormFp32(nn.LayerNorm):
92
  """Subclass torch's LayerNorm to handle fp16 (by casting to float32 and back)."""
93
  def __init__(self, *args, **kwargs):