Views
No views yet
1from transformers.models.clip.modeling_clip import CLIPPreTrainedModel, CLIPConfig, CLIPVisionTransformer
2from transformers.modeling_outputs import (
3 BaseModelOutput,
4 BaseModelOutputWithPooling,
5 ImageClassifierOutput,
6 MaskedImageModelingOutput,
7)
8from typing import Dict, List, Optional, Set, Tuple, Union
9import torch
10from torch import nn
11from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
12
13
14class CLIPViTForImageClassification(CLIPPreTrainedModel):
15 def __init__(self, config: CLIPConfig) -> None:
16 super().__init__(config)
17
18 self.num_labels = config.num_labels
19 vision_config = config.vision_config
20 self.vision_model = CLIPVisionTransformer(vision_config)
21
22 # Classifier head
23
24 self.classifier = nn.Linear(vision_config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
25
26 # Initialize weights and apply final processing
27 self.post_init()
28
29 def forward(
30 self,
31 pixel_values: Optional[torch.Tensor] = None,
32 #head_mask: Optional[torch.Tensor] = None,
33 labels: Optional[torch.Tensor] = None,
34 output_attentions: Optional[bool] = None,
35 output_hidden_states: Optional[bool] = None,
36 #interpolate_pos_encoding: Optional[bool] = None,
37 return_dict: Optional[bool] = None,
38 ) -> Union[tuple, ImageClassifierOutput]:
39 r"""
40 labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
41 Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
42 config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
43 `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
44 """
45 return_dict = return_dict if return_dict is not None else self.config.use_return_dict
46
47 outputs = self.vision_model(
48 pixel_values,
49 #head_mask=head_mask,
50 output_attentions=output_attentions,
51 output_hidden_states=output_hidden_states,
52 #interpolate_pos_encoding=interpolate_pos_encoding,
53 return_dict=return_dict,
54 )
55
56 sequence_output = outputs[0]
57
58 logits = self.classifier(sequence_output[:, 0, :])
59
60 loss = None
61 if labels is not None:
62 # move labels to correct device to enable model parallelism
63 labels = labels.to(logits.device)
64 if self.config.problem_type is None:
65 if self.num_labels == 1:
66 self.config.problem_type = "regression"
67 elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
68 self.config.problem_type = "single_label_classification"
69 else:
70 self.config.problem_type = "multi_label_classification"
71
72 if self.config.problem_type == "regression":
73 loss_fct = MSELoss()
74 if self.num_labels == 1:
75 loss = loss_fct(logits.squeeze(), labels.squeeze())
76 else:
77 loss = loss_fct(logits, labels)
78 elif self.config.problem_type == "single_label_classification":
79 loss_fct = CrossEntropyLoss()
80 loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
81 elif self.config.problem_type == "multi_label_classification":
82 loss_fct = BCEWithLogitsLoss()
83 loss = loss_fct(logits, labels)
84
85 if not return_dict:
86 output = (logits,) + outputs[1:]
87 return ((loss,) + output) if loss is not None else output
88
89 return ImageClassifierOutput(
90 loss=loss,
91 logits=logits,
92 hidden_states=outputs.hidden_states,
93 attentions=outputs.attentions,
94 )