p1atdev commited on
Commit
a467fd4
1 Parent(s): 0bf12b4

Upload 2 files

Browse files
Files changed (2) hide show
  1. loss_fn.py +201 -0
  2. modeling_siglip.py +83 -0
loss_fn.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # https://github.com/Alibaba-MIIL/ASL/blob/main/src/loss_functions/losses.py
2
+
3
+ # MIT License
4
+
5
+ # Copyright (c) 2020 Alibaba-MIIL
6
+
7
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ # of this software and associated documentation files (the "Software"), to deal
9
+ # in the Software without restriction, including without limitation the rights
10
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ # copies of the Software, and to permit persons to whom the Software is
12
+ # furnished to do so, subject to the following conditions:
13
+
14
+ # The above copyright notice and this permission notice shall be included in all
15
+ # copies or substantial portions of the Software.
16
+
17
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ # SOFTWARE.
24
+
25
+
26
+ import torch
27
+ import torch.nn as nn
28
+
29
+
30
+ class AsymmetricLoss(nn.Module):
31
+ def __init__(
32
+ self,
33
+ gamma_neg=4,
34
+ gamma_pos=1,
35
+ clip=0.05,
36
+ eps=1e-8,
37
+ disable_torch_grad_focal_loss=True,
38
+ ):
39
+ super(AsymmetricLoss, self).__init__()
40
+
41
+ self.gamma_neg = gamma_neg
42
+ self.gamma_pos = gamma_pos
43
+ self.clip = clip
44
+ self.disable_torch_grad_focal_loss = disable_torch_grad_focal_loss
45
+ self.eps = eps
46
+
47
+ def forward(self, x, y):
48
+ """ "
49
+ Parameters
50
+ ----------
51
+ x: input logits
52
+ y: targets (multi-label binarized vector)
53
+ """
54
+
55
+ # Calculating Probabilities
56
+ x_sigmoid = torch.sigmoid(x)
57
+ xs_pos = x_sigmoid
58
+ xs_neg = 1 - x_sigmoid
59
+
60
+ # Asymmetric Clipping
61
+ if self.clip is not None and self.clip > 0:
62
+ xs_neg = (xs_neg + self.clip).clamp(max=1)
63
+
64
+ # Basic CE calculation
65
+ los_pos = y * torch.log(xs_pos.clamp(min=self.eps))
66
+ los_neg = (1 - y) * torch.log(xs_neg.clamp(min=self.eps))
67
+ loss = los_pos + los_neg
68
+
69
+ # Asymmetric Focusing
70
+ if self.gamma_neg > 0 or self.gamma_pos > 0:
71
+ if self.disable_torch_grad_focal_loss:
72
+ torch.set_grad_enabled(False)
73
+ pt0 = xs_pos * y
74
+ pt1 = xs_neg * (1 - y) # pt = p if t > 0 else 1-p
75
+ pt = pt0 + pt1
76
+ one_sided_gamma = self.gamma_pos * y + self.gamma_neg * (1 - y)
77
+ one_sided_w = torch.pow(1 - pt, one_sided_gamma)
78
+ if self.disable_torch_grad_focal_loss:
79
+ torch.set_grad_enabled(True)
80
+ loss *= one_sided_w
81
+
82
+ return -loss.sum()
83
+
84
+
85
+ class AsymmetricLossOptimized(nn.Module):
86
+ """Notice - optimized version, minimizes memory allocation and gpu uploading,
87
+ favors inplace operations"""
88
+
89
+ def __init__(
90
+ self,
91
+ gamma_neg=4,
92
+ gamma_pos=1,
93
+ clip=0.05,
94
+ eps=1e-8,
95
+ disable_torch_grad_focal_loss=False,
96
+ ):
97
+ super(AsymmetricLossOptimized, self).__init__()
98
+
99
+ self.gamma_neg = gamma_neg
100
+ self.gamma_pos = gamma_pos
101
+ self.clip = clip
102
+ self.disable_torch_grad_focal_loss = disable_torch_grad_focal_loss
103
+ self.eps = eps
104
+
105
+ # prevent memory allocation and gpu uploading every iteration, and encourages inplace operations
106
+ self.targets = self.anti_targets = self.xs_pos = self.xs_neg = (
107
+ self.asymmetric_w
108
+ ) = self.loss = None
109
+
110
+ def forward(self, x, y):
111
+ """ "
112
+ Parameters
113
+ ----------
114
+ x: input logits
115
+ y: targets (multi-label binarized vector)
116
+ """
117
+
118
+ self.targets = y
119
+ self.anti_targets = 1 - y
120
+
121
+ # Calculating Probabilities
122
+ self.xs_pos = torch.sigmoid(x)
123
+ self.xs_neg = 1.0 - self.xs_pos
124
+
125
+ # Asymmetric Clipping
126
+ if self.clip is not None and self.clip > 0:
127
+ self.xs_neg.add_(self.clip).clamp_(max=1)
128
+
129
+ # Basic CE calculation
130
+ self.loss = self.targets * torch.log(self.xs_pos.clamp(min=self.eps))
131
+ self.loss.add_(self.anti_targets * torch.log(self.xs_neg.clamp(min=self.eps)))
132
+
133
+ # Asymmetric Focusing
134
+ if self.gamma_neg > 0 or self.gamma_pos > 0:
135
+ if self.disable_torch_grad_focal_loss:
136
+ torch.set_grad_enabled(False)
137
+ self.xs_pos = self.xs_pos * self.targets
138
+ self.xs_neg = self.xs_neg * self.anti_targets
139
+ self.asymmetric_w = torch.pow(
140
+ 1 - self.xs_pos - self.xs_neg,
141
+ self.gamma_pos * self.targets + self.gamma_neg * self.anti_targets,
142
+ )
143
+ if self.disable_torch_grad_focal_loss:
144
+ torch.set_grad_enabled(True)
145
+ self.loss *= self.asymmetric_w
146
+
147
+ return -self.loss.sum()
148
+
149
+
150
+ class ASLSingleLabel(nn.Module):
151
+ """
152
+ This loss is intended for single-label classification problems
153
+ """
154
+
155
+ def __init__(self, gamma_pos=0, gamma_neg=4, eps: float = 0.1, reduction="mean"):
156
+ super(ASLSingleLabel, self).__init__()
157
+
158
+ self.eps = eps
159
+ self.logsoftmax = nn.LogSoftmax(dim=-1)
160
+ self.targets_classes = []
161
+ self.gamma_pos = gamma_pos
162
+ self.gamma_neg = gamma_neg
163
+ self.reduction = reduction
164
+
165
+ def forward(self, inputs, target):
166
+ """
167
+ "input" dimensions: - (batch_size,number_classes)
168
+ "target" dimensions: - (batch_size)
169
+ """
170
+ num_classes = inputs.size()[-1]
171
+ log_preds = self.logsoftmax(inputs)
172
+ self.targets_classes = torch.zeros_like(inputs).scatter_(
173
+ 1, target.long().unsqueeze(1), 1
174
+ )
175
+
176
+ # ASL weights
177
+ targets = self.targets_classes
178
+ anti_targets = 1 - targets
179
+ xs_pos = torch.exp(log_preds)
180
+ xs_neg = 1 - xs_pos
181
+ xs_pos = xs_pos * targets
182
+ xs_neg = xs_neg * anti_targets
183
+ asymmetric_w = torch.pow(
184
+ 1 - xs_pos - xs_neg,
185
+ self.gamma_pos * targets + self.gamma_neg * anti_targets,
186
+ )
187
+ log_preds = log_preds * asymmetric_w
188
+
189
+ if self.eps > 0: # label smoothing
190
+ self.targets_classes = self.targets_classes.mul(1 - self.eps).add(
191
+ self.eps / num_classes
192
+ )
193
+
194
+ # loss calculation
195
+ loss = -self.targets_classes.mul(log_preds)
196
+
197
+ loss = loss.sum(dim=-1)
198
+ if self.reduction == "mean":
199
+ loss = loss.mean()
200
+
201
+ return loss
modeling_siglip.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
6
+
7
+ from transformers import SiglipVisionModel, SiglipPreTrainedModel, SiglipVisionConfig
8
+ from transformers.utils import ModelOutput
9
+
10
+ from loss_fn import AsymmetricLossOptimized
11
+
12
+
13
+ @dataclass
14
+ class SiglipForImageClassifierOutput(ModelOutput):
15
+ loss: torch.FloatTensor | None = None
16
+ logits: torch.FloatTensor | None = None
17
+ pooler_output: torch.FloatTensor | None = None
18
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
19
+ attentions: tuple[torch.FloatTensor, ...] | None = None
20
+
21
+
22
+ class SiglipForImageClassification(SiglipPreTrainedModel):
23
+ config_class = SiglipVisionConfig
24
+ main_input_name = "pixel_values"
25
+
26
+ def __init__(
27
+ self,
28
+ config,
29
+ ):
30
+ super().__init__(config)
31
+
32
+ self.num_labels = config.num_labels
33
+ self.siglip = SiglipVisionModel(config)
34
+
35
+ # Classifier head
36
+ self.classifier = (
37
+ nn.Linear(config.hidden_size, config.num_labels)
38
+ if config.num_labels > 0
39
+ else nn.Identity()
40
+ )
41
+
42
+ # Initialize weights and apply final processing
43
+ self.post_init()
44
+
45
+ def forward(
46
+ self, pixel_values: torch.FloatTensor, labels: torch.LongTensor | None = None
47
+ ):
48
+ outputs = self.siglip(pixel_values)
49
+ pooler_output = outputs.pooler_output
50
+ logits = self.classifier(pooler_output)
51
+
52
+ loss = None
53
+ if labels is not None:
54
+ if self.config.problem_type is None:
55
+ if self.num_labels == 1:
56
+ self.config.problem_type = "regression"
57
+ elif self.num_labels > 1 and (
58
+ labels.dtype == torch.long or labels.dtype == torch.int
59
+ ):
60
+ self.config.problem_type = "single_label_classification"
61
+ else:
62
+ self.config.problem_type = "multi_label_classification"
63
+
64
+ if self.config.problem_type == "regression":
65
+ loss_fct = MSELoss()
66
+ if self.num_labels == 1:
67
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
68
+ else:
69
+ loss = loss_fct(logits, labels)
70
+ elif self.config.problem_type == "single_label_classification":
71
+ loss_fct = CrossEntropyLoss()
72
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
73
+ elif self.config.problem_type == "multi_label_classification":
74
+ loss_fct = AsymmetricLossOptimized()
75
+ loss = loss_fct(logits, labels)
76
+
77
+ return SiglipForImageClassifierOutput(
78
+ loss=loss,
79
+ logits=logits,
80
+ pooler_output=outputs.pooler_output,
81
+ hidden_states=outputs.hidden_states,
82
+ attentions=outputs.attentions,
83
+ )