modeling_owlvit.py 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642
  1. # coding=utf-8
  2. # Copyright 2022 Google AI and The HuggingFace Team. All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """PyTorch OWL-ViT model."""
  16. from dataclasses import dataclass
  17. from functools import lru_cache
  18. from typing import Any, Optional, Union
  19. import torch
  20. from torch import Tensor, nn
  21. from ...activations import ACT2FN
  22. from ...modeling_attn_mask_utils import _create_4d_causal_attention_mask, _prepare_4d_attention_mask
  23. from ...modeling_layers import GradientCheckpointingLayer
  24. from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling
  25. from ...modeling_utils import PreTrainedModel
  26. from ...utils import (
  27. ModelOutput,
  28. auto_docstring,
  29. filter_out_non_signature_kwargs,
  30. is_vision_available,
  31. logging,
  32. torch_int,
  33. )
  34. from .configuration_owlvit import OwlViTConfig, OwlViTTextConfig, OwlViTVisionConfig
  35. if is_vision_available():
  36. from transformers.image_transforms import center_to_corners_format
  37. logger = logging.get_logger(__name__)
  38. # See all OwlViT models at https://huggingface.co/models?filter=owlvit
  39. # Copied from transformers.models.clip.modeling_clip.contrastive_loss with clip->owlvit
  40. def contrastive_loss(logits: torch.Tensor) -> torch.Tensor:
  41. return nn.functional.cross_entropy(logits, torch.arange(len(logits), device=logits.device))
  42. # Copied from transformers.models.clip.modeling_clip.clip_loss with clip->owlvit
  43. def owlvit_loss(similarity: torch.Tensor) -> torch.Tensor:
  44. caption_loss = contrastive_loss(similarity)
  45. image_loss = contrastive_loss(similarity.t())
  46. return (caption_loss + image_loss) / 2.0
  47. @dataclass
  48. @auto_docstring
  49. class OwlViTOutput(ModelOutput):
  50. r"""
  51. loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
  52. Contrastive loss for image-text similarity.
  53. logits_per_image (`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
  54. The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
  55. similarity scores.
  56. logits_per_text (`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
  57. The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
  58. similarity scores.
  59. text_embeds (`torch.FloatTensor` of shape `(batch_size * num_max_text_queries, output_dim`):
  60. The text embeddings obtained by applying the projection layer to the pooled output of [`OwlViTTextModel`].
  61. image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
  62. The image embeddings obtained by applying the projection layer to the pooled output of
  63. [`OwlViTVisionModel`].
  64. text_model_output (tuple[`BaseModelOutputWithPooling`]):
  65. The output of the [`OwlViTTextModel`].
  66. vision_model_output (`BaseModelOutputWithPooling`):
  67. The output of the [`OwlViTVisionModel`].
  68. """
  69. loss: Optional[torch.FloatTensor] = None
  70. logits_per_image: Optional[torch.FloatTensor] = None
  71. logits_per_text: Optional[torch.FloatTensor] = None
  72. text_embeds: Optional[torch.FloatTensor] = None
  73. image_embeds: Optional[torch.FloatTensor] = None
  74. text_model_output: BaseModelOutputWithPooling = None
  75. vision_model_output: BaseModelOutputWithPooling = None
  76. def to_tuple(self) -> tuple[Any]:
  77. return tuple(
  78. self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
  79. for k in self.keys()
  80. )
  81. # Copied from transformers.loss.loss_for_object_detection._upcast
  82. def _upcast(t: Tensor) -> Tensor:
  83. # Protects from numerical overflows in multiplications by upcasting to the equivalent higher type
  84. if t.is_floating_point():
  85. return t if t.dtype in (torch.float32, torch.float64) else t.float()
  86. else:
  87. return t if t.dtype in (torch.int32, torch.int64) else t.int()
  88. # Copied from transformers.loss.loss_for_object_detection.box_area
  89. def box_area(boxes: Tensor) -> Tensor:
  90. """
  91. Computes the area of a set of bounding boxes, which are specified by its (x1, y1, x2, y2) coordinates.
  92. Args:
  93. boxes (`torch.FloatTensor` of shape `(number_of_boxes, 4)`):
  94. Boxes for which the area will be computed. They are expected to be in (x1, y1, x2, y2) format with `0 <= x1
  95. < x2` and `0 <= y1 < y2`.
  96. Returns:
  97. `torch.FloatTensor`: a tensor containing the area for each box.
  98. """
  99. boxes = _upcast(boxes)
  100. return (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])
  101. # Copied from transformers.loss.loss_for_object_detection.box_iou
  102. def box_iou(boxes1, boxes2):
  103. area1 = box_area(boxes1)
  104. area2 = box_area(boxes2)
  105. left_top = torch.max(boxes1[:, None, :2], boxes2[:, :2]) # [N,M,2]
  106. right_bottom = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) # [N,M,2]
  107. width_height = (right_bottom - left_top).clamp(min=0) # [N,M,2]
  108. inter = width_height[:, :, 0] * width_height[:, :, 1] # [N,M]
  109. union = area1[:, None] + area2 - inter
  110. iou = inter / union
  111. return iou, union
  112. # Copied from transformers.loss.loss_for_object_detection.generalized_box_iou
  113. def generalized_box_iou(boxes1, boxes2):
  114. """
  115. Generalized IoU from https://giou.stanford.edu/. The boxes should be in [x0, y0, x1, y1] (corner) format.
  116. Returns:
  117. `torch.FloatTensor`: a [N, M] pairwise matrix, where N = len(boxes1) and M = len(boxes2)
  118. """
  119. # degenerate boxes gives inf / nan results
  120. # so do an early check
  121. if not (boxes1[:, 2:] >= boxes1[:, :2]).all():
  122. raise ValueError(f"boxes1 must be in [x0, y0, x1, y1] (corner) format, but got {boxes1}")
  123. if not (boxes2[:, 2:] >= boxes2[:, :2]).all():
  124. raise ValueError(f"boxes2 must be in [x0, y0, x1, y1] (corner) format, but got {boxes2}")
  125. iou, union = box_iou(boxes1, boxes2)
  126. top_left = torch.min(boxes1[:, None, :2], boxes2[:, :2])
  127. bottom_right = torch.max(boxes1[:, None, 2:], boxes2[:, 2:])
  128. width_height = (bottom_right - top_left).clamp(min=0) # [N,M,2]
  129. area = width_height[:, :, 0] * width_height[:, :, 1]
  130. return iou - (area - union) / area
  131. @dataclass
  132. @auto_docstring(
  133. custom_intro="""
  134. Output type of [`OwlViTForObjectDetection`].
  135. """
  136. )
  137. class OwlViTObjectDetectionOutput(ModelOutput):
  138. r"""
  139. loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` are provided)):
  140. Total loss as a linear combination of a negative log-likehood (cross-entropy) for class prediction and a
  141. bounding box loss. The latter is defined as a linear combination of the L1 loss and the generalized
  142. scale-invariant IoU loss.
  143. loss_dict (`Dict`, *optional*):
  144. A dictionary containing the individual losses. Useful for logging.
  145. logits (`torch.FloatTensor` of shape `(batch_size, num_patches, num_queries)`):
  146. Classification logits (including no-object) for all queries.
  147. pred_boxes (`torch.FloatTensor` of shape `(batch_size, num_patches, 4)`):
  148. Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). These
  149. values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding
  150. possible padding). You can use [`~OwlViTImageProcessor.post_process_object_detection`] to retrieve the
  151. unnormalized bounding boxes.
  152. text_embeds (`torch.FloatTensor` of shape `(batch_size, num_max_text_queries, output_dim`):
  153. The text embeddings obtained by applying the projection layer to the pooled output of [`OwlViTTextModel`].
  154. image_embeds (`torch.FloatTensor` of shape `(batch_size, patch_size, patch_size, output_dim`):
  155. Pooled output of [`OwlViTVisionModel`]. OWL-ViT represents images as a set of image patches and computes
  156. image embeddings for each patch.
  157. class_embeds (`torch.FloatTensor` of shape `(batch_size, num_patches, hidden_size)`):
  158. Class embeddings of all image patches. OWL-ViT represents images as a set of image patches where the total
  159. number of patches is (image_size / patch_size)**2.
  160. text_model_output (tuple[`BaseModelOutputWithPooling`]):
  161. The output of the [`OwlViTTextModel`].
  162. vision_model_output (`BaseModelOutputWithPooling`):
  163. The output of the [`OwlViTVisionModel`].
  164. """
  165. loss: Optional[torch.FloatTensor] = None
  166. loss_dict: Optional[dict] = None
  167. logits: Optional[torch.FloatTensor] = None
  168. pred_boxes: Optional[torch.FloatTensor] = None
  169. text_embeds: Optional[torch.FloatTensor] = None
  170. image_embeds: Optional[torch.FloatTensor] = None
  171. class_embeds: Optional[torch.FloatTensor] = None
  172. text_model_output: BaseModelOutputWithPooling = None
  173. vision_model_output: BaseModelOutputWithPooling = None
  174. def to_tuple(self) -> tuple[Any]:
  175. return tuple(
  176. self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
  177. for k in self.keys()
  178. )
  179. @dataclass
  180. @auto_docstring(
  181. custom_intro="""
  182. Output type of [`OwlViTForObjectDetection.image_guided_detection`].
  183. """
  184. )
  185. class OwlViTImageGuidedObjectDetectionOutput(ModelOutput):
  186. r"""
  187. logits (`torch.FloatTensor` of shape `(batch_size, num_patches, num_queries)`):
  188. Classification logits (including no-object) for all queries.
  189. image_embeds (`torch.FloatTensor` of shape `(batch_size, patch_size, patch_size, output_dim`):
  190. Pooled output of [`OwlViTVisionModel`]. OWL-ViT represents images as a set of image patches and computes
  191. image embeddings for each patch.
  192. query_image_embeds (`torch.FloatTensor` of shape `(batch_size, patch_size, patch_size, output_dim`):
  193. Pooled output of [`OwlViTVisionModel`]. OWL-ViT represents images as a set of image patches and computes
  194. image embeddings for each patch.
  195. target_pred_boxes (`torch.FloatTensor` of shape `(batch_size, num_patches, 4)`):
  196. Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). These
  197. values are normalized in [0, 1], relative to the size of each individual target image in the batch
  198. (disregarding possible padding). You can use [`~OwlViTImageProcessor.post_process_object_detection`] to
  199. retrieve the unnormalized bounding boxes.
  200. query_pred_boxes (`torch.FloatTensor` of shape `(batch_size, num_patches, 4)`):
  201. Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). These
  202. values are normalized in [0, 1], relative to the size of each individual query image in the batch
  203. (disregarding possible padding). You can use [`~OwlViTImageProcessor.post_process_object_detection`] to
  204. retrieve the unnormalized bounding boxes.
  205. class_embeds (`torch.FloatTensor` of shape `(batch_size, num_patches, hidden_size)`):
  206. Class embeddings of all image patches. OWL-ViT represents images as a set of image patches where the total
  207. number of patches is (image_size / patch_size)**2.
  208. text_model_output (tuple[`BaseModelOutputWithPooling`]):
  209. The output of the [`OwlViTTextModel`].
  210. vision_model_output (`BaseModelOutputWithPooling`):
  211. The output of the [`OwlViTVisionModel`].
  212. """
  213. logits: Optional[torch.FloatTensor] = None
  214. image_embeds: Optional[torch.FloatTensor] = None
  215. query_image_embeds: Optional[torch.FloatTensor] = None
  216. target_pred_boxes: Optional[torch.FloatTensor] = None
  217. query_pred_boxes: Optional[torch.FloatTensor] = None
  218. class_embeds: Optional[torch.FloatTensor] = None
  219. text_model_output: BaseModelOutputWithPooling = None
  220. vision_model_output: BaseModelOutputWithPooling = None
  221. def to_tuple(self) -> tuple[Any]:
  222. return tuple(
  223. self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
  224. for k in self.keys()
  225. )
  226. class OwlViTVisionEmbeddings(nn.Module):
  227. def __init__(self, config: OwlViTVisionConfig):
  228. super().__init__()
  229. self.patch_size = config.patch_size
  230. self.config = config
  231. self.embed_dim = config.hidden_size
  232. self.class_embedding = nn.Parameter(torch.randn(config.hidden_size))
  233. self.patch_embedding = nn.Conv2d(
  234. in_channels=config.num_channels,
  235. out_channels=self.embed_dim,
  236. kernel_size=config.patch_size,
  237. stride=config.patch_size,
  238. bias=False,
  239. )
  240. self.num_patches = (config.image_size // config.patch_size) ** 2
  241. self.num_positions = self.num_patches + 1
  242. self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
  243. self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)), persistent=False)
  244. # Copied from transformers.models.clip.modeling_clip.CLIPVisionEmbeddings.interpolate_pos_encoding
  245. def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
  246. """
  247. This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
  248. images. This method is also adapted to support torch.jit tracing.
  249. Adapted from:
  250. - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
  251. - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
  252. """
  253. num_patches = embeddings.shape[1] - 1
  254. position_embedding = self.position_embedding.weight.unsqueeze(0)
  255. num_positions = position_embedding.shape[1] - 1
  256. # always interpolate when tracing to ensure the exported model works for dynamic input shapes
  257. if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
  258. return self.position_embedding(self.position_ids)
  259. class_pos_embed = position_embedding[:, :1]
  260. patch_pos_embed = position_embedding[:, 1:]
  261. dim = embeddings.shape[-1]
  262. new_height = height // self.patch_size
  263. new_width = width // self.patch_size
  264. sqrt_num_positions = torch_int(num_positions**0.5)
  265. patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
  266. patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
  267. patch_pos_embed = nn.functional.interpolate(
  268. patch_pos_embed,
  269. size=(new_height, new_width),
  270. mode="bicubic",
  271. align_corners=False,
  272. )
  273. patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
  274. return torch.cat((class_pos_embed, patch_pos_embed), dim=1)
  275. def forward(self, pixel_values: torch.FloatTensor, interpolate_pos_encoding: bool = False) -> torch.Tensor:
  276. batch_size, _, height, width = pixel_values.shape
  277. patch_embeds = self.patch_embedding(pixel_values) # shape = [batch_size, num_channels, height, width]
  278. patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
  279. class_embeds = self.class_embedding.expand(batch_size, 1, -1)
  280. embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
  281. if interpolate_pos_encoding:
  282. embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
  283. else:
  284. embeddings = embeddings + self.position_embedding(self.position_ids)
  285. return embeddings
  286. class OwlViTTextEmbeddings(nn.Module):
  287. def __init__(self, config: OwlViTTextConfig):
  288. super().__init__()
  289. self.token_embedding = nn.Embedding(config.vocab_size, config.hidden_size)
  290. self.position_embedding = nn.Embedding(config.max_position_embeddings, config.hidden_size)
  291. # position_ids (1, len position emb) is contiguous in memory and exported when serialized
  292. self.register_buffer(
  293. "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
  294. )
  295. def forward(
  296. self,
  297. input_ids: Optional[torch.LongTensor] = None,
  298. position_ids: Optional[torch.LongTensor] = None,
  299. inputs_embeds: Optional[torch.FloatTensor] = None,
  300. ) -> torch.Tensor:
  301. seq_length = input_ids.shape[-1] if input_ids is not None else inputs_embeds.shape[-2]
  302. if position_ids is None:
  303. position_ids = self.position_ids[:, :seq_length]
  304. if inputs_embeds is None:
  305. inputs_embeds = self.token_embedding(input_ids)
  306. position_embeddings = self.position_embedding(position_ids)
  307. embeddings = inputs_embeds + position_embeddings
  308. return embeddings
  309. class OwlViTAttention(nn.Module):
  310. """Multi-headed attention from 'Attention Is All You Need' paper"""
  311. def __init__(self, config):
  312. super().__init__()
  313. self.config = config
  314. self.embed_dim = config.hidden_size
  315. self.num_heads = config.num_attention_heads
  316. self.head_dim = self.embed_dim // self.num_heads
  317. if self.head_dim * self.num_heads != self.embed_dim:
  318. raise ValueError(
  319. f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
  320. f" {self.num_heads})."
  321. )
  322. self.scale = self.head_dim**-0.5
  323. self.dropout = config.attention_dropout
  324. self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
  325. self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
  326. self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
  327. self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
  328. def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
  329. return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
  330. def forward(
  331. self,
  332. hidden_states: torch.Tensor,
  333. attention_mask: Optional[torch.Tensor] = None,
  334. causal_attention_mask: Optional[torch.Tensor] = None,
  335. output_attentions: Optional[bool] = False,
  336. ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
  337. """Input shape: Batch x Time x Channel"""
  338. bsz, tgt_len, embed_dim = hidden_states.size()
  339. # get query proj
  340. query_states = self.q_proj(hidden_states) * self.scale
  341. key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
  342. value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
  343. proj_shape = (bsz * self.num_heads, -1, self.head_dim)
  344. query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
  345. key_states = key_states.view(*proj_shape)
  346. value_states = value_states.view(*proj_shape)
  347. src_len = key_states.size(1)
  348. attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
  349. if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
  350. raise ValueError(
  351. f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
  352. f" {attn_weights.size()}"
  353. )
  354. # apply the causal_attention_mask first
  355. if causal_attention_mask is not None:
  356. if causal_attention_mask.size() != (bsz, 1, tgt_len, src_len):
  357. raise ValueError(
  358. f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is"
  359. f" {causal_attention_mask.size()}"
  360. )
  361. attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + causal_attention_mask
  362. attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
  363. if attention_mask is not None:
  364. if attention_mask.size() != (bsz, 1, tgt_len, src_len):
  365. raise ValueError(
  366. f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
  367. )
  368. attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
  369. attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
  370. attn_weights = nn.functional.softmax(attn_weights, dim=-1)
  371. if output_attentions:
  372. # this operation is a bit awkward, but it's required to
  373. # make sure that attn_weights keeps its gradient.
  374. # In order to do so, attn_weights have to reshaped
  375. # twice and have to be reused in the following
  376. attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
  377. attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
  378. else:
  379. attn_weights_reshaped = None
  380. attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
  381. # For int8 compatibility, sometimes the `attn_probs` are in `fp32`
  382. attn_probs = attn_probs.to(value_states.dtype)
  383. attn_output = torch.bmm(attn_probs, value_states)
  384. if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
  385. raise ValueError(
  386. f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
  387. f" {attn_output.size()}"
  388. )
  389. attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
  390. attn_output = attn_output.transpose(1, 2)
  391. attn_output = attn_output.reshape(bsz, tgt_len, embed_dim)
  392. attn_output = self.out_proj(attn_output)
  393. return attn_output, attn_weights_reshaped
  394. # Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->OwlViT
  395. class OwlViTMLP(nn.Module):
  396. def __init__(self, config):
  397. super().__init__()
  398. self.config = config
  399. self.activation_fn = ACT2FN[config.hidden_act]
  400. self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
  401. self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
  402. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  403. hidden_states = self.fc1(hidden_states)
  404. hidden_states = self.activation_fn(hidden_states)
  405. hidden_states = self.fc2(hidden_states)
  406. return hidden_states
  407. # Copied from transformers.models.altclip.modeling_altclip.AltCLIPEncoderLayer with AltCLIP->OwlViT
  408. class OwlViTEncoderLayer(GradientCheckpointingLayer):
  409. def __init__(self, config: OwlViTConfig):
  410. super().__init__()
  411. self.embed_dim = config.hidden_size
  412. self.self_attn = OwlViTAttention(config)
  413. self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
  414. self.mlp = OwlViTMLP(config)
  415. self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
  416. def forward(
  417. self,
  418. hidden_states: torch.Tensor,
  419. attention_mask: torch.Tensor,
  420. causal_attention_mask: torch.Tensor,
  421. output_attentions: Optional[bool] = False,
  422. ) -> tuple[torch.FloatTensor]:
  423. """
  424. Args:
  425. hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
  426. attention_mask (`torch.FloatTensor`): attention mask of size
  427. `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
  428. `(config.encoder_attention_heads,)`.
  429. output_attentions (`bool`, *optional*):
  430. Whether or not to return the attentions tensors of all attention layers. See `attentions` under
  431. returned tensors for more detail.
  432. """
  433. residual = hidden_states
  434. hidden_states = self.layer_norm1(hidden_states)
  435. hidden_states, attn_weights = self.self_attn(
  436. hidden_states=hidden_states,
  437. attention_mask=attention_mask,
  438. causal_attention_mask=causal_attention_mask,
  439. output_attentions=output_attentions,
  440. )
  441. hidden_states = residual + hidden_states
  442. residual = hidden_states
  443. hidden_states = self.layer_norm2(hidden_states)
  444. hidden_states = self.mlp(hidden_states)
  445. hidden_states = residual + hidden_states
  446. outputs = (hidden_states,)
  447. if output_attentions:
  448. outputs += (attn_weights,)
  449. return outputs
  450. @auto_docstring
  451. class OwlViTPreTrainedModel(PreTrainedModel):
  452. config: OwlViTConfig
  453. base_model_prefix = "owlvit"
  454. supports_gradient_checkpointing = True
  455. _no_split_modules = ["OwlViTEncoderLayer"]
  456. def _init_weights(self, module: nn.Module):
  457. """Initialize the weights"""
  458. factor = self.config.initializer_factor
  459. if isinstance(module, OwlViTTextEmbeddings):
  460. module.token_embedding.weight.data.normal_(mean=0.0, std=factor * 0.02)
  461. module.position_embedding.weight.data.normal_(mean=0.0, std=factor * 0.02)
  462. elif isinstance(module, OwlViTVisionEmbeddings):
  463. nn.init.normal_(module.class_embedding, mean=0.0, std=module.embed_dim**-0.5 * factor)
  464. nn.init.normal_(module.patch_embedding.weight, std=module.config.initializer_range * factor)
  465. nn.init.normal_(module.position_embedding.weight, std=module.config.initializer_range * factor)
  466. elif isinstance(module, OwlViTAttention):
  467. in_proj_std = (module.embed_dim**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
  468. out_proj_std = (module.embed_dim**-0.5) * factor
  469. nn.init.normal_(module.q_proj.weight, std=in_proj_std)
  470. nn.init.normal_(module.k_proj.weight, std=in_proj_std)
  471. nn.init.normal_(module.v_proj.weight, std=in_proj_std)
  472. nn.init.normal_(module.out_proj.weight, std=out_proj_std)
  473. elif isinstance(module, OwlViTMLP):
  474. in_proj_std = (module.config.hidden_size**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
  475. fc_std = (2 * module.config.hidden_size) ** -0.5 * factor
  476. nn.init.normal_(module.fc1.weight, std=fc_std)
  477. nn.init.normal_(module.fc2.weight, std=in_proj_std)
  478. elif isinstance(module, OwlViTModel):
  479. nn.init.normal_(
  480. module.text_projection.weight,
  481. std=module.text_embed_dim**-0.5 * factor,
  482. )
  483. nn.init.normal_(
  484. module.visual_projection.weight,
  485. std=module.vision_embed_dim**-0.5 * factor,
  486. )
  487. module.logit_scale.data.fill_(self.config.logit_scale_init_value)
  488. if isinstance(module, nn.LayerNorm):
  489. module.bias.data.zero_()
  490. module.weight.data.fill_(1.0)
  491. if isinstance(module, nn.Linear):
  492. module.weight.data.normal_(mean=0.0, std=factor)
  493. if module.bias is not None:
  494. module.bias.data.zero_()
  495. class OwlViTEncoder(nn.Module):
  496. """
  497. Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
  498. [`OwlViTEncoderLayer`].
  499. Args:
  500. config: OwlViTConfig
  501. """
  502. def __init__(self, config: OwlViTConfig):
  503. super().__init__()
  504. self.layers = nn.ModuleList([OwlViTEncoderLayer(config) for _ in range(config.num_hidden_layers)])
  505. self.gradient_checkpointing = False
  506. def forward(
  507. self,
  508. inputs_embeds,
  509. attention_mask: Optional[torch.Tensor] = None,
  510. causal_attention_mask: Optional[torch.Tensor] = None,
  511. output_attentions: Optional[bool] = None,
  512. output_hidden_states: Optional[bool] = None,
  513. return_dict: Optional[bool] = None,
  514. ) -> Union[tuple, BaseModelOutput]:
  515. r"""
  516. Args:
  517. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`).
  518. attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
  519. Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
  520. - 1 for tokens that are **not masked**,
  521. - 0 for tokens that are **masked**.
  522. [What are attention masks?](../glossary#attention-mask)
  523. causal_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
  524. Causal mask for the text model. Mask values selected in `[0, 1]`:
  525. - 1 for tokens that are **not masked**,
  526. - 0 for tokens that are **masked**.
  527. [What are attention masks?](../glossary#attention-mask)
  528. output_attentions (`bool`, *optional*):
  529. Whether or not to return the attentions tensors of all attention layers. See `attentions` under
  530. returned tensors for more detail.
  531. output_hidden_states (`bool`, *optional*):
  532. Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
  533. for more detail.
  534. return_dict (`bool`, *optional*):
  535. Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
  536. """
  537. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  538. output_hidden_states = (
  539. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  540. )
  541. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  542. encoder_states = () if output_hidden_states else None
  543. all_attentions = () if output_attentions else None
  544. hidden_states = inputs_embeds
  545. for encoder_layer in self.layers:
  546. if output_hidden_states:
  547. encoder_states = encoder_states + (hidden_states,)
  548. layer_outputs = encoder_layer(
  549. hidden_states,
  550. attention_mask,
  551. causal_attention_mask,
  552. output_attentions=output_attentions,
  553. )
  554. hidden_states = layer_outputs[0]
  555. if output_attentions:
  556. all_attentions = all_attentions + (layer_outputs[1],)
  557. if output_hidden_states:
  558. encoder_states = encoder_states + (hidden_states,)
  559. if not return_dict:
  560. return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
  561. return BaseModelOutput(
  562. last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
  563. )
  564. class OwlViTTextTransformer(nn.Module):
  565. def __init__(self, config: OwlViTTextConfig):
  566. super().__init__()
  567. self.config = config
  568. embed_dim = config.hidden_size
  569. self.embeddings = OwlViTTextEmbeddings(config)
  570. self.encoder = OwlViTEncoder(config)
  571. self.final_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
  572. @auto_docstring
  573. def forward(
  574. self,
  575. input_ids: torch.Tensor,
  576. attention_mask: Optional[torch.Tensor] = None,
  577. position_ids: Optional[torch.Tensor] = None,
  578. output_attentions: Optional[bool] = None,
  579. output_hidden_states: Optional[bool] = None,
  580. return_dict: Optional[bool] = None,
  581. ) -> Union[tuple, BaseModelOutputWithPooling]:
  582. r"""
  583. input_ids (`torch.LongTensor` of shape `(batch_size * num_max_text_queries, sequence_length)`):
  584. Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See
  585. [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input
  586. IDs?](../glossary#input-ids)
  587. """
  588. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  589. output_hidden_states = (
  590. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  591. )
  592. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  593. input_shape = input_ids.size()
  594. input_ids = input_ids.view(-1, input_shape[-1])
  595. hidden_states = self.embeddings(input_ids=input_ids, position_ids=position_ids)
  596. # num_samples, seq_len = input_shape where num_samples = batch_size * num_max_text_queries
  597. # OWLVIT's text model uses causal mask, prepare it here.
  598. # https://github.com/openai/CLIP/blob/cfcffb90e69f37bf2ff1e988237a0fbe41f33c04/clip/model.py#L324
  599. causal_attention_mask = _create_4d_causal_attention_mask(
  600. input_shape, hidden_states.dtype, device=hidden_states.device
  601. )
  602. # expand attention_mask
  603. if attention_mask is not None:
  604. # [num_samples, seq_len] -> [num_samples, 1, tgt_seq_len, src_seq_len]
  605. attention_mask = _prepare_4d_attention_mask(attention_mask, hidden_states.dtype)
  606. encoder_outputs = self.encoder(
  607. inputs_embeds=hidden_states,
  608. attention_mask=attention_mask,
  609. causal_attention_mask=causal_attention_mask,
  610. output_attentions=output_attentions,
  611. output_hidden_states=output_hidden_states,
  612. return_dict=return_dict,
  613. )
  614. last_hidden_state = encoder_outputs[0]
  615. last_hidden_state = self.final_layer_norm(last_hidden_state)
  616. # take features from the end of tokens embedding (end of token is the highest number in each sequence)
  617. # casting to torch.int for onnx compatibility: argmax doesn't support int64 inputs with opset 14
  618. pooled_output = last_hidden_state[
  619. torch.arange(last_hidden_state.shape[0], device=last_hidden_state.device),
  620. input_ids.to(torch.int).argmax(dim=-1).to(last_hidden_state.device),
  621. ]
  622. if not return_dict:
  623. return (last_hidden_state, pooled_output) + encoder_outputs[1:]
  624. return BaseModelOutputWithPooling(
  625. last_hidden_state=last_hidden_state,
  626. pooler_output=pooled_output,
  627. hidden_states=encoder_outputs.hidden_states,
  628. attentions=encoder_outputs.attentions,
  629. )
  630. class OwlViTTextModel(OwlViTPreTrainedModel):
  631. config: OwlViTTextConfig
  632. def __init__(self, config: OwlViTTextConfig):
  633. super().__init__(config)
  634. self.text_model = OwlViTTextTransformer(config)
  635. # Initialize weights and apply final processing
  636. self.post_init()
  637. def get_input_embeddings(self) -> nn.Module:
  638. return self.text_model.embeddings.token_embedding
  639. def set_input_embeddings(self, value):
  640. self.text_model.embeddings.token_embedding = value
  641. @auto_docstring
  642. def forward(
  643. self,
  644. input_ids: torch.Tensor,
  645. attention_mask: Optional[torch.Tensor] = None,
  646. output_attentions: Optional[bool] = None,
  647. output_hidden_states: Optional[bool] = None,
  648. return_dict: Optional[bool] = None,
  649. ) -> Union[tuple, BaseModelOutputWithPooling]:
  650. r"""
  651. input_ids (`torch.LongTensor` of shape `(batch_size * num_max_text_queries, sequence_length)`):
  652. Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See
  653. [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input
  654. IDs?](../glossary#input-ids)
  655. Examples:
  656. ```python
  657. >>> from transformers import AutoProcessor, OwlViTTextModel
  658. >>> model = OwlViTTextModel.from_pretrained("google/owlvit-base-patch32")
  659. >>> processor = AutoProcessor.from_pretrained("google/owlvit-base-patch32")
  660. >>> inputs = processor(
  661. ... text=[["a photo of a cat", "a photo of a dog"], ["photo of a astranaut"]], return_tensors="pt"
  662. ... )
  663. >>> outputs = model(**inputs)
  664. >>> last_hidden_state = outputs.last_hidden_state
  665. >>> pooled_output = outputs.pooler_output # pooled (EOS token) states
  666. ```"""
  667. # Get embeddings for all text queries in all batch samples
  668. return self.text_model(
  669. input_ids=input_ids,
  670. attention_mask=attention_mask,
  671. output_attentions=output_attentions,
  672. output_hidden_states=output_hidden_states,
  673. return_dict=return_dict,
  674. )
  675. class OwlViTVisionTransformer(nn.Module):
  676. def __init__(self, config: OwlViTVisionConfig):
  677. super().__init__()
  678. self.config = config
  679. self.embeddings = OwlViTVisionEmbeddings(config)
  680. self.pre_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  681. self.encoder = OwlViTEncoder(config)
  682. self.post_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  683. @auto_docstring
  684. def forward(
  685. self,
  686. pixel_values: torch.FloatTensor,
  687. output_attentions: Optional[bool] = None,
  688. output_hidden_states: Optional[bool] = None,
  689. interpolate_pos_encoding: Optional[bool] = False,
  690. return_dict: Optional[bool] = None,
  691. ) -> Union[tuple, BaseModelOutputWithPooling]:
  692. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  693. output_hidden_states = (
  694. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  695. )
  696. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  697. # Cast the input to the expected `dtype`
  698. expected_input_dtype = self.embeddings.patch_embedding.weight.dtype
  699. pixel_values = pixel_values.to(expected_input_dtype)
  700. hidden_states = self.embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)
  701. hidden_states = self.pre_layernorm(hidden_states)
  702. encoder_outputs = self.encoder(
  703. inputs_embeds=hidden_states,
  704. output_attentions=output_attentions,
  705. output_hidden_states=output_hidden_states,
  706. return_dict=return_dict,
  707. )
  708. last_hidden_state = encoder_outputs[0]
  709. pooled_output = last_hidden_state[:, 0, :]
  710. pooled_output = self.post_layernorm(pooled_output)
  711. if not return_dict:
  712. return (last_hidden_state, pooled_output) + encoder_outputs[1:]
  713. return BaseModelOutputWithPooling(
  714. last_hidden_state=last_hidden_state,
  715. pooler_output=pooled_output,
  716. hidden_states=encoder_outputs.hidden_states,
  717. attentions=encoder_outputs.attentions,
  718. )
  719. class OwlViTVisionModel(OwlViTPreTrainedModel):
  720. config: OwlViTVisionConfig
  721. main_input_name = "pixel_values"
  722. def __init__(self, config: OwlViTVisionConfig):
  723. super().__init__(config)
  724. self.vision_model = OwlViTVisionTransformer(config)
  725. # Initialize weights and apply final processing
  726. self.post_init()
  727. def get_input_embeddings(self) -> nn.Module:
  728. return self.vision_model.embeddings.patch_embedding
  729. @auto_docstring
  730. def forward(
  731. self,
  732. pixel_values: Optional[torch.FloatTensor] = None,
  733. output_attentions: Optional[bool] = None,
  734. output_hidden_states: Optional[bool] = None,
  735. interpolate_pos_encoding: bool = False,
  736. return_dict: Optional[bool] = None,
  737. ) -> Union[tuple, BaseModelOutputWithPooling]:
  738. r"""
  739. Examples:
  740. ```python
  741. >>> from PIL import Image
  742. >>> import requests
  743. >>> from transformers import AutoProcessor, OwlViTVisionModel
  744. >>> model = OwlViTVisionModel.from_pretrained("google/owlvit-base-patch32")
  745. >>> processor = AutoProcessor.from_pretrained("google/owlvit-base-patch32")
  746. >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
  747. >>> image = Image.open(requests.get(url, stream=True).raw)
  748. >>> inputs = processor(images=image, return_tensors="pt")
  749. >>> outputs = model(**inputs)
  750. >>> last_hidden_state = outputs.last_hidden_state
  751. >>> pooled_output = outputs.pooler_output # pooled CLS states
  752. ```"""
  753. return self.vision_model(
  754. pixel_values=pixel_values,
  755. output_attentions=output_attentions,
  756. output_hidden_states=output_hidden_states,
  757. interpolate_pos_encoding=interpolate_pos_encoding,
  758. return_dict=return_dict,
  759. )
  760. @auto_docstring
  761. class OwlViTModel(OwlViTPreTrainedModel):
  762. config: OwlViTConfig
  763. def __init__(self, config: OwlViTConfig):
  764. super().__init__(config)
  765. if not isinstance(config.text_config, OwlViTTextConfig):
  766. raise TypeError(
  767. "config.text_config is expected to be of type OwlViTTextConfig but is of type"
  768. f" {type(config.text_config)}."
  769. )
  770. if not isinstance(config.vision_config, OwlViTVisionConfig):
  771. raise TypeError(
  772. "config.vision_config is expected to be of type OwlViTVisionConfig but is of type"
  773. f" {type(config.vision_config)}."
  774. )
  775. text_config = config.text_config
  776. vision_config = config.vision_config
  777. self.projection_dim = config.projection_dim
  778. self.text_embed_dim = text_config.hidden_size
  779. self.vision_embed_dim = vision_config.hidden_size
  780. self.text_model = OwlViTTextTransformer(text_config)
  781. self.vision_model = OwlViTVisionTransformer(vision_config)
  782. self.visual_projection = nn.Linear(self.vision_embed_dim, self.projection_dim, bias=False)
  783. self.text_projection = nn.Linear(self.text_embed_dim, self.projection_dim, bias=False)
  784. self.logit_scale = nn.Parameter(torch.tensor(config.logit_scale_init_value))
  785. # Initialize weights and apply final processing
  786. self.post_init()
  787. @filter_out_non_signature_kwargs()
  788. @auto_docstring
  789. def get_text_features(
  790. self,
  791. input_ids: torch.Tensor,
  792. attention_mask: Optional[torch.Tensor] = None,
  793. ) -> torch.FloatTensor:
  794. r"""
  795. input_ids (`torch.LongTensor` of shape `(batch_size * num_max_text_queries, sequence_length)`):
  796. Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See
  797. [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input
  798. IDs?](../glossary#input-ids)
  799. Returns:
  800. text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
  801. applying the projection layer to the pooled output of [`OwlViTTextModel`].
  802. Examples:
  803. ```python
  804. >>> import torch
  805. >>> from transformers import AutoProcessor, OwlViTModel
  806. >>> model = OwlViTModel.from_pretrained("google/owlvit-base-patch32")
  807. >>> processor = AutoProcessor.from_pretrained("google/owlvit-base-patch32")
  808. >>> inputs = processor(
  809. ... text=[["a photo of a cat", "a photo of a dog"], ["photo of a astranaut"]], return_tensors="pt"
  810. ... )
  811. >>> with torch.inference_mode():
  812. ... text_features = model.get_text_features(**inputs)
  813. ```"""
  814. # Get embeddings for all text queries in all batch samples
  815. text_outputs: BaseModelOutputWithPooling = self.text_model(input_ids=input_ids, attention_mask=attention_mask)
  816. text_features = self.text_projection(text_outputs.pooler_output)
  817. return text_features
  818. @filter_out_non_signature_kwargs()
  819. @auto_docstring
  820. def get_image_features(
  821. self,
  822. pixel_values: torch.Tensor,
  823. interpolate_pos_encoding: bool = False,
  824. ) -> torch.FloatTensor:
  825. r"""
  826. Returns:
  827. image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by
  828. applying the projection layer to the pooled output of [`OwlViTVisionModel`].
  829. Examples:
  830. ```python
  831. >>> import torch
  832. >>> from transformers.image_utils import load_image
  833. >>> from transformers import AutoProcessor, OwlViTModel
  834. >>> model = OwlViTModel.from_pretrained("google/owlvit-base-patch32")
  835. >>> processor = AutoProcessor.from_pretrained("google/owlvit-base-patch32")
  836. >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
  837. >>> image = load_image(url)
  838. >>> inputs = processor(images=image, return_tensors="pt")
  839. >>> with torch.inference_mode():
  840. ... image_features = model.get_image_features(**inputs)
  841. ```"""
  842. vision_outputs: BaseModelOutputWithPooling = self.vision_model(
  843. pixel_values=pixel_values,
  844. interpolate_pos_encoding=interpolate_pos_encoding,
  845. )
  846. image_features = self.visual_projection(vision_outputs.pooler_output)
  847. return image_features
  848. @auto_docstring
  849. def forward(
  850. self,
  851. input_ids: Optional[torch.LongTensor] = None,
  852. pixel_values: Optional[torch.FloatTensor] = None,
  853. attention_mask: Optional[torch.Tensor] = None,
  854. return_loss: Optional[bool] = None,
  855. output_attentions: Optional[bool] = None,
  856. output_hidden_states: Optional[bool] = None,
  857. interpolate_pos_encoding: bool = False,
  858. return_base_image_embeds: Optional[bool] = None,
  859. return_dict: Optional[bool] = None,
  860. ) -> Union[tuple, OwlViTOutput]:
  861. r"""
  862. return_loss (`bool`, *optional*):
  863. Whether or not to return the contrastive loss.
  864. return_base_image_embeds (`bool`, *optional*):
  865. Whether or not to return the base image embeddings.
  866. Examples:
  867. ```python
  868. >>> from PIL import Image
  869. >>> import requests
  870. >>> from transformers import AutoProcessor, OwlViTModel
  871. >>> model = OwlViTModel.from_pretrained("google/owlvit-base-patch32")
  872. >>> processor = AutoProcessor.from_pretrained("google/owlvit-base-patch32")
  873. >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
  874. >>> image = Image.open(requests.get(url, stream=True).raw)
  875. >>> inputs = processor(text=[["a photo of a cat", "a photo of a dog"]], images=image, return_tensors="pt")
  876. >>> outputs = model(**inputs)
  877. >>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score
  878. >>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities
  879. ```"""
  880. # Use OWL-ViT model's config for some fields (if specified) instead of those of vision & text components.
  881. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  882. output_hidden_states = (
  883. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  884. )
  885. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  886. vision_outputs = self.vision_model(
  887. pixel_values=pixel_values,
  888. output_attentions=output_attentions,
  889. output_hidden_states=output_hidden_states,
  890. interpolate_pos_encoding=interpolate_pos_encoding,
  891. return_dict=return_dict,
  892. )
  893. # Get embeddings for all text queries in all batch samples
  894. text_outputs = self.text_model(
  895. input_ids=input_ids,
  896. attention_mask=attention_mask,
  897. output_attentions=output_attentions,
  898. output_hidden_states=output_hidden_states,
  899. return_dict=return_dict,
  900. )
  901. text_embeds = text_outputs[1]
  902. text_embeds = self.text_projection(text_embeds)
  903. image_embeds = vision_outputs[1]
  904. image_embeds = self.visual_projection(image_embeds)
  905. # normalized features
  906. image_embeds = image_embeds / torch.linalg.norm(image_embeds, ord=2, dim=-1, keepdim=True)
  907. text_embeds_norm = text_embeds / torch.linalg.norm(text_embeds, ord=2, dim=-1, keepdim=True)
  908. # cosine similarity as logits and set it on the correct device
  909. logit_scale = self.logit_scale.exp().to(image_embeds.device)
  910. logits_per_text = torch.matmul(text_embeds_norm, image_embeds.t()) * logit_scale
  911. logits_per_image = logits_per_text.t()
  912. loss = None
  913. if return_loss:
  914. loss = owlvit_loss(logits_per_text)
  915. text_embeds = text_embeds_norm
  916. if not return_dict:
  917. output = (logits_per_image, logits_per_text, text_embeds, image_embeds, text_outputs, vision_outputs)
  918. return ((loss,) + output) if loss is not None else output
  919. return OwlViTOutput(
  920. loss=loss,
  921. logits_per_image=logits_per_image,
  922. logits_per_text=logits_per_text,
  923. text_embeds=text_embeds,
  924. image_embeds=image_embeds,
  925. text_model_output=text_outputs,
  926. vision_model_output=vision_outputs,
  927. )
  928. class OwlViTBoxPredictionHead(nn.Module):
  929. def __init__(self, config: OwlViTConfig, out_dim: int = 4):
  930. super().__init__()
  931. width = config.vision_config.hidden_size
  932. self.dense0 = nn.Linear(width, width)
  933. self.dense1 = nn.Linear(width, width)
  934. self.gelu = nn.GELU()
  935. self.dense2 = nn.Linear(width, out_dim)
  936. def forward(self, image_features: torch.Tensor) -> torch.FloatTensor:
  937. output = self.dense0(image_features)
  938. output = self.gelu(output)
  939. output = self.dense1(output)
  940. output = self.gelu(output)
  941. output = self.dense2(output)
  942. return output
  943. class OwlViTClassPredictionHead(nn.Module):
  944. def __init__(self, config: OwlViTConfig):
  945. super().__init__()
  946. out_dim = config.text_config.hidden_size
  947. self.query_dim = config.vision_config.hidden_size
  948. self.dense0 = nn.Linear(self.query_dim, out_dim)
  949. self.logit_shift = nn.Linear(self.query_dim, 1)
  950. self.logit_scale = nn.Linear(self.query_dim, 1)
  951. self.elu = nn.ELU()
  952. def forward(
  953. self,
  954. image_embeds: torch.FloatTensor,
  955. query_embeds: Optional[torch.FloatTensor],
  956. query_mask: Optional[torch.Tensor],
  957. ) -> tuple[torch.FloatTensor]:
  958. image_class_embeds = self.dense0(image_embeds)
  959. if query_embeds is None:
  960. device = image_class_embeds.device
  961. batch_size, num_patches = image_class_embeds.shape[:2]
  962. pred_logits = torch.zeros((batch_size, num_patches, self.query_dim)).to(device)
  963. return (pred_logits, image_class_embeds)
  964. # Normalize image and text features
  965. image_class_embeds = image_class_embeds / (torch.linalg.norm(image_class_embeds, dim=-1, keepdim=True) + 1e-6)
  966. query_embeds = query_embeds / (torch.linalg.norm(query_embeds, dim=-1, keepdim=True) + 1e-6)
  967. # Get class predictions
  968. pred_logits = torch.einsum("...pd,...qd->...pq", image_class_embeds, query_embeds)
  969. # Apply a learnable shift and scale to logits
  970. logit_shift = self.logit_shift(image_embeds)
  971. logit_scale = self.logit_scale(image_embeds)
  972. logit_scale = self.elu(logit_scale) + 1
  973. pred_logits = (pred_logits + logit_shift) * logit_scale
  974. if query_mask is not None:
  975. if query_mask.ndim > 1:
  976. query_mask = torch.unsqueeze(query_mask, dim=-2)
  977. pred_logits = torch.where(query_mask == 0, torch.finfo(pred_logits.dtype).min, pred_logits)
  978. pred_logits = pred_logits.to(torch.float32)
  979. return (pred_logits, image_class_embeds)
  980. class OwlViTForObjectDetection(OwlViTPreTrainedModel):
  981. config: OwlViTConfig
  982. def __init__(self, config: OwlViTConfig):
  983. super().__init__(config)
  984. self.owlvit = OwlViTModel(config)
  985. self.class_head = OwlViTClassPredictionHead(config)
  986. self.box_head = OwlViTBoxPredictionHead(config)
  987. self.layer_norm = nn.LayerNorm(config.vision_config.hidden_size, eps=config.vision_config.layer_norm_eps)
  988. self.sigmoid = nn.Sigmoid()
  989. self.config = config
  990. self.num_patches_height = self.config.vision_config.image_size // self.config.vision_config.patch_size
  991. self.num_patches_width = self.config.vision_config.image_size // self.config.vision_config.patch_size
  992. self.box_bias = self.compute_box_bias(self.num_patches_height, self.num_patches_width)
  993. @staticmethod
  994. def normalize_grid_corner_coordinates(num_patches_height: int, num_patches_width: int) -> torch.Tensor:
  995. # Create grid coordinates using torch
  996. x_coordinates = torch.arange(1, num_patches_width + 1, dtype=torch.float32)
  997. y_coordinates = torch.arange(1, num_patches_height + 1, dtype=torch.float32)
  998. xx, yy = torch.meshgrid(x_coordinates, y_coordinates, indexing="xy")
  999. # Stack the coordinates and divide by their respective patch counts
  1000. box_coordinates = torch.stack((xx, yy), dim=-1)
  1001. box_coordinates[..., 0] /= num_patches_width
  1002. box_coordinates[..., 1] /= num_patches_height
  1003. # Flatten (h, w, 2) -> (h*w, 2)
  1004. box_coordinates = box_coordinates.view(-1, 2)
  1005. return box_coordinates
  1006. @lru_cache(maxsize=2)
  1007. def compute_box_bias(
  1008. self, num_patches_height: int, num_patches_width: int, feature_map: Optional[torch.FloatTensor] = None
  1009. ) -> torch.Tensor:
  1010. if feature_map is not None:
  1011. raise ValueError("feature_map has been deprecated as an input. Please pass in num_patches instead")
  1012. # The box center is biased to its position on the feature grid
  1013. box_coordinates = self.normalize_grid_corner_coordinates(num_patches_height, num_patches_width)
  1014. box_coordinates = torch.clip(box_coordinates, 0.0, 1.0)
  1015. # Unnormalize xy
  1016. box_coord_bias = torch.log(box_coordinates + 1e-4) - torch.log1p(-box_coordinates + 1e-4)
  1017. # The box size is biased to the patch size
  1018. box_size = torch.full_like(box_coord_bias, 1.0)
  1019. box_size[..., 0] /= num_patches_width
  1020. box_size[..., 1] /= num_patches_height
  1021. box_size_bias = torch.log(box_size + 1e-4) - torch.log1p(-box_size + 1e-4)
  1022. # Compute box bias
  1023. box_bias = torch.cat([box_coord_bias, box_size_bias], dim=-1)
  1024. return box_bias
  1025. def box_predictor(
  1026. self,
  1027. image_feats: torch.FloatTensor,
  1028. feature_map: torch.FloatTensor,
  1029. interpolate_pos_encoding: bool = False,
  1030. ) -> torch.FloatTensor:
  1031. """
  1032. Args:
  1033. image_feats:
  1034. Features extracted from the image, returned by the `image_text_embedder` method.
  1035. feature_map:
  1036. A spatial re-arrangement of image_features, also returned by the `image_text_embedder` method.
  1037. interpolate_pos_encoding:
  1038. Whether to interpolate the pre-trained position encodings.
  1039. Returns:
  1040. pred_boxes:
  1041. List of predicted boxes (cxcywh normalized to 0, 1) nested within a dictionary.
  1042. """
  1043. # Bounding box detection head [batch_size, num_boxes, 4].
  1044. pred_boxes = self.box_head(image_feats)
  1045. # Compute the location of each token on the grid and use it to compute a bias for the bbox prediction
  1046. if interpolate_pos_encoding:
  1047. _, num_patches_height, num_patches_width, _ = feature_map.shape
  1048. box_bias = self.compute_box_bias(num_patches_height, num_patches_width)
  1049. else:
  1050. box_bias = self.box_bias
  1051. box_bias = box_bias.to(feature_map.device)
  1052. pred_boxes += box_bias
  1053. pred_boxes = self.sigmoid(pred_boxes)
  1054. return pred_boxes
  1055. def class_predictor(
  1056. self,
  1057. image_feats: torch.FloatTensor,
  1058. query_embeds: Optional[torch.FloatTensor] = None,
  1059. query_mask: Optional[torch.Tensor] = None,
  1060. ) -> tuple[torch.FloatTensor]:
  1061. """
  1062. Args:
  1063. image_feats:
  1064. Features extracted from the `image_text_embedder`.
  1065. query_embeds:
  1066. Text query embeddings.
  1067. query_mask:
  1068. Must be provided with query_embeddings. A mask indicating which query embeddings are valid.
  1069. """
  1070. (pred_logits, image_class_embeds) = self.class_head(image_feats, query_embeds, query_mask)
  1071. return (pred_logits, image_class_embeds)
  1072. def image_text_embedder(
  1073. self,
  1074. input_ids: torch.Tensor,
  1075. pixel_values: torch.FloatTensor,
  1076. attention_mask: torch.Tensor,
  1077. output_attentions: Optional[bool] = None,
  1078. output_hidden_states: Optional[bool] = None,
  1079. interpolate_pos_encoding: bool = False,
  1080. ) -> tuple[torch.FloatTensor]:
  1081. # Encode text and image
  1082. outputs = self.owlvit(
  1083. pixel_values=pixel_values,
  1084. input_ids=input_ids,
  1085. attention_mask=attention_mask,
  1086. output_attentions=output_attentions,
  1087. output_hidden_states=output_hidden_states,
  1088. interpolate_pos_encoding=interpolate_pos_encoding,
  1089. return_dict=True,
  1090. )
  1091. if interpolate_pos_encoding:
  1092. _, _, height, width = pixel_values.shape
  1093. num_patches_height = height // self.config.vision_config.patch_size
  1094. num_patches_width = width // self.config.vision_config.patch_size
  1095. else:
  1096. num_patches_height = self.num_patches_height
  1097. num_patches_width = self.num_patches_width
  1098. # Get image embeddings
  1099. last_hidden_state = outputs.vision_model_output[0]
  1100. image_embeds = self.owlvit.vision_model.post_layernorm(last_hidden_state)
  1101. # Resize class token
  1102. class_token_out = torch.broadcast_to(image_embeds[:, :1, :], image_embeds[:, :-1].shape)
  1103. # Merge image embedding with class tokens
  1104. image_embeds = image_embeds[:, 1:, :] * class_token_out
  1105. image_embeds = self.layer_norm(image_embeds)
  1106. # Resize to [batch_size, num_patches_height, num_patches_width, hidden_size]
  1107. new_size = (
  1108. image_embeds.shape[0],
  1109. num_patches_height,
  1110. num_patches_width,
  1111. image_embeds.shape[-1],
  1112. )
  1113. image_embeds = image_embeds.reshape(new_size)
  1114. text_embeds = outputs[-4]
  1115. return (text_embeds, image_embeds, outputs)
  1116. def image_embedder(
  1117. self,
  1118. pixel_values: torch.FloatTensor,
  1119. output_attentions: Optional[bool] = None,
  1120. output_hidden_states: Optional[bool] = None,
  1121. interpolate_pos_encoding: bool = False,
  1122. ) -> tuple[torch.FloatTensor]:
  1123. # Get OwlViTModel vision embeddings (same as CLIP)
  1124. vision_outputs = self.owlvit.vision_model(
  1125. pixel_values=pixel_values, interpolate_pos_encoding=interpolate_pos_encoding, return_dict=True
  1126. )
  1127. if interpolate_pos_encoding:
  1128. _, _, height, width = pixel_values.shape
  1129. num_patches_height = height // self.config.vision_config.patch_size
  1130. num_patches_width = width // self.config.vision_config.patch_size
  1131. else:
  1132. num_patches_height = self.num_patches_height
  1133. num_patches_width = self.num_patches_width
  1134. # Apply post_layernorm to last_hidden_state, return non-projected output
  1135. last_hidden_state = vision_outputs[0]
  1136. image_embeds = self.owlvit.vision_model.post_layernorm(last_hidden_state)
  1137. # Resize class token
  1138. class_token_out = torch.broadcast_to(image_embeds[:, :1, :], image_embeds[:, :-1].shape)
  1139. # Merge image embedding with class tokens
  1140. image_embeds = image_embeds[:, 1:, :] * class_token_out
  1141. image_embeds = self.layer_norm(image_embeds)
  1142. # Resize to [batch_size, num_patches_height, num_patches_width, hidden_size]
  1143. new_size = (
  1144. image_embeds.shape[0],
  1145. num_patches_height,
  1146. num_patches_width,
  1147. image_embeds.shape[-1],
  1148. )
  1149. image_embeds = image_embeds.reshape(new_size)
  1150. return (image_embeds, vision_outputs)
  1151. def embed_image_query(
  1152. self,
  1153. query_image_features: torch.FloatTensor,
  1154. query_feature_map: torch.FloatTensor,
  1155. interpolate_pos_encoding: bool = False,
  1156. ) -> torch.FloatTensor:
  1157. _, class_embeds = self.class_predictor(query_image_features)
  1158. pred_boxes = self.box_predictor(query_image_features, query_feature_map, interpolate_pos_encoding)
  1159. pred_boxes_as_corners = center_to_corners_format(pred_boxes)
  1160. # Loop over query images
  1161. best_class_embeds = []
  1162. best_box_indices = []
  1163. pred_boxes_device = pred_boxes_as_corners.device
  1164. for i in range(query_image_features.shape[0]):
  1165. each_query_box = torch.tensor([[0, 0, 1, 1]], device=pred_boxes_device)
  1166. each_query_pred_boxes = pred_boxes_as_corners[i]
  1167. ious, _ = box_iou(each_query_box, each_query_pred_boxes)
  1168. # If there are no overlapping boxes, fall back to generalized IoU
  1169. if torch.all(ious[0] == 0.0):
  1170. ious = generalized_box_iou(each_query_box, each_query_pred_boxes)
  1171. # Use an adaptive threshold to include all boxes within 80% of the best IoU
  1172. iou_threshold = torch.max(ious) * 0.8
  1173. selected_inds = (ious[0] >= iou_threshold).nonzero()
  1174. if selected_inds.numel():
  1175. selected_embeddings = class_embeds[i][selected_inds.squeeze(1)]
  1176. mean_embeds = torch.mean(class_embeds[i], axis=0)
  1177. mean_sim = torch.einsum("d,id->i", mean_embeds, selected_embeddings)
  1178. best_box_ind = selected_inds[torch.argmin(mean_sim)]
  1179. best_class_embeds.append(class_embeds[i][best_box_ind])
  1180. best_box_indices.append(best_box_ind)
  1181. if best_class_embeds:
  1182. query_embeds = torch.stack(best_class_embeds)
  1183. box_indices = torch.stack(best_box_indices)
  1184. else:
  1185. query_embeds, box_indices = None, None
  1186. return query_embeds, box_indices, pred_boxes
  1187. @auto_docstring
  1188. def image_guided_detection(
  1189. self,
  1190. pixel_values: torch.FloatTensor,
  1191. query_pixel_values: Optional[torch.FloatTensor] = None,
  1192. output_attentions: Optional[bool] = None,
  1193. output_hidden_states: Optional[bool] = None,
  1194. interpolate_pos_encoding: bool = False,
  1195. return_dict: Optional[bool] = None,
  1196. ) -> OwlViTImageGuidedObjectDetectionOutput:
  1197. r"""
  1198. query_pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
  1199. Pixel values of query image(s) to be detected. Pass in one query image per target image.
  1200. Examples:
  1201. ```python
  1202. >>> import requests
  1203. >>> from PIL import Image
  1204. >>> import torch
  1205. >>> from transformers import AutoProcessor, OwlViTForObjectDetection
  1206. >>> processor = AutoProcessor.from_pretrained("google/owlvit-base-patch16")
  1207. >>> model = OwlViTForObjectDetection.from_pretrained("google/owlvit-base-patch16")
  1208. >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
  1209. >>> image = Image.open(requests.get(url, stream=True).raw)
  1210. >>> query_url = "http://images.cocodataset.org/val2017/000000001675.jpg"
  1211. >>> query_image = Image.open(requests.get(query_url, stream=True).raw)
  1212. >>> inputs = processor(images=image, query_images=query_image, return_tensors="pt")
  1213. >>> with torch.no_grad():
  1214. ... outputs = model.image_guided_detection(**inputs)
  1215. >>> # Target image sizes (height, width) to rescale box predictions [batch_size, 2]
  1216. >>> target_sizes = torch.Tensor([image.size[::-1]])
  1217. >>> # Convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
  1218. >>> results = processor.post_process_image_guided_detection(
  1219. ... outputs=outputs, threshold=0.6, nms_threshold=0.3, target_sizes=target_sizes
  1220. ... )
  1221. >>> i = 0 # Retrieve predictions for the first image
  1222. >>> boxes, scores = results[i]["boxes"], results[i]["scores"]
  1223. >>> for box, score in zip(boxes, scores):
  1224. ... box = [round(i, 2) for i in box.tolist()]
  1225. ... print(f"Detected similar object with confidence {round(score.item(), 3)} at location {box}")
  1226. Detected similar object with confidence 0.856 at location [10.94, 50.4, 315.8, 471.39]
  1227. Detected similar object with confidence 1.0 at location [334.84, 25.33, 636.16, 374.71]
  1228. ```"""
  1229. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  1230. output_hidden_states = (
  1231. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  1232. )
  1233. return_dict = return_dict if return_dict is not None else self.config.return_dict
  1234. # Compute feature maps for the input and query images
  1235. query_feature_map = self.image_embedder(
  1236. pixel_values=query_pixel_values, interpolate_pos_encoding=interpolate_pos_encoding
  1237. )[0]
  1238. feature_map, vision_outputs = self.image_embedder(
  1239. pixel_values=pixel_values,
  1240. output_attentions=output_attentions,
  1241. output_hidden_states=output_hidden_states,
  1242. interpolate_pos_encoding=interpolate_pos_encoding,
  1243. )
  1244. batch_size, num_patches_height, num_patches_width, hidden_dim = feature_map.shape
  1245. image_feats = torch.reshape(feature_map, (batch_size, num_patches_height * num_patches_width, hidden_dim))
  1246. batch_size, num_patches_height, num_patches_width, hidden_dim = query_feature_map.shape
  1247. query_image_feats = torch.reshape(
  1248. query_feature_map, (batch_size, num_patches_height * num_patches_width, hidden_dim)
  1249. )
  1250. # Get top class embedding and best box index for each query image in batch
  1251. query_embeds, best_box_indices, query_pred_boxes = self.embed_image_query(
  1252. query_image_feats, query_feature_map, interpolate_pos_encoding
  1253. )
  1254. # Predict object classes [batch_size, num_patches, num_queries+1]
  1255. (pred_logits, class_embeds) = self.class_predictor(image_feats=image_feats, query_embeds=query_embeds)
  1256. # Predict object boxes
  1257. target_pred_boxes = self.box_predictor(image_feats, feature_map, interpolate_pos_encoding)
  1258. if not return_dict:
  1259. output = (
  1260. feature_map,
  1261. query_feature_map,
  1262. target_pred_boxes,
  1263. query_pred_boxes,
  1264. pred_logits,
  1265. class_embeds,
  1266. vision_outputs.to_tuple(),
  1267. )
  1268. output = tuple(x for x in output if x is not None)
  1269. return output
  1270. return OwlViTImageGuidedObjectDetectionOutput(
  1271. image_embeds=feature_map,
  1272. query_image_embeds=query_feature_map,
  1273. target_pred_boxes=target_pred_boxes,
  1274. query_pred_boxes=query_pred_boxes,
  1275. logits=pred_logits,
  1276. class_embeds=class_embeds,
  1277. text_model_output=None,
  1278. vision_model_output=vision_outputs,
  1279. )
  1280. @auto_docstring
  1281. def forward(
  1282. self,
  1283. input_ids: torch.Tensor,
  1284. pixel_values: torch.FloatTensor,
  1285. attention_mask: Optional[torch.Tensor] = None,
  1286. output_attentions: Optional[bool] = None,
  1287. output_hidden_states: Optional[bool] = None,
  1288. interpolate_pos_encoding: bool = False,
  1289. return_dict: Optional[bool] = None,
  1290. ) -> OwlViTObjectDetectionOutput:
  1291. r"""
  1292. input_ids (`torch.LongTensor` of shape `(batch_size * num_max_text_queries, sequence_length)`, *optional*):
  1293. Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See
  1294. [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input
  1295. IDs?](../glossary#input-ids).
  1296. output_hidden_states (`bool`, *optional*):
  1297. Whether or not to return the last hidden state. See `text_model_last_hidden_state` and
  1298. `vision_model_last_hidden_state` under returned tensors for more detail.
  1299. Examples:
  1300. ```python
  1301. >>> import requests
  1302. >>> from PIL import Image
  1303. >>> import torch
  1304. >>> from transformers import OwlViTProcessor, OwlViTForObjectDetection
  1305. >>> processor = OwlViTProcessor.from_pretrained("google/owlvit-base-patch32")
  1306. >>> model = OwlViTForObjectDetection.from_pretrained("google/owlvit-base-patch32")
  1307. >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
  1308. >>> image = Image.open(requests.get(url, stream=True).raw)
  1309. >>> text_labels = [["a photo of a cat", "a photo of a dog"]]
  1310. >>> inputs = processor(text=text_labels, images=image, return_tensors="pt")
  1311. >>> outputs = model(**inputs)
  1312. >>> # Target image sizes (height, width) to rescale box predictions [batch_size, 2]
  1313. >>> target_sizes = torch.tensor([(image.height, image.width)])
  1314. >>> # Convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
  1315. >>> results = processor.post_process_grounded_object_detection(
  1316. ... outputs=outputs, target_sizes=target_sizes, threshold=0.1, text_labels=text_labels
  1317. ... )
  1318. >>> # Retrieve predictions for the first image for the corresponding text queries
  1319. >>> result = results[0]
  1320. >>> boxes, scores, text_labels = result["boxes"], result["scores"], result["text_labels"]
  1321. >>> for box, score, text_label in zip(boxes, scores, text_labels):
  1322. ... box = [round(i, 2) for i in box.tolist()]
  1323. ... print(f"Detected {text_label} with confidence {round(score.item(), 3)} at location {box}")
  1324. Detected a photo of a cat with confidence 0.707 at location [324.97, 20.44, 640.58, 373.29]
  1325. Detected a photo of a cat with confidence 0.717 at location [1.46, 55.26, 315.55, 472.17]
  1326. ```"""
  1327. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  1328. output_hidden_states = (
  1329. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  1330. )
  1331. return_dict = return_dict if return_dict is not None else self.config.return_dict
  1332. # Embed images and text queries
  1333. query_embeds, feature_map, outputs = self.image_text_embedder(
  1334. input_ids=input_ids,
  1335. pixel_values=pixel_values,
  1336. attention_mask=attention_mask,
  1337. output_attentions=output_attentions,
  1338. output_hidden_states=output_hidden_states,
  1339. interpolate_pos_encoding=interpolate_pos_encoding,
  1340. )
  1341. # Text and vision model outputs
  1342. text_outputs = outputs.text_model_output
  1343. vision_outputs = outputs.vision_model_output
  1344. batch_size, num_patches_height, num_patches_width, hidden_dim = feature_map.shape
  1345. image_feats = torch.reshape(feature_map, (batch_size, num_patches_height * num_patches_width, hidden_dim))
  1346. # Reshape from [batch_size * max_text_queries, hidden_dim] -> [batch_size, max_text_queries, hidden_dim]
  1347. max_text_queries = input_ids.shape[0] // batch_size
  1348. query_embeds = query_embeds.reshape(batch_size, max_text_queries, query_embeds.shape[-1])
  1349. # If first token is 0, then this is a padded query [batch_size, num_queries].
  1350. input_ids = input_ids.reshape(batch_size, max_text_queries, input_ids.shape[-1])
  1351. query_mask = input_ids[..., 0] > 0
  1352. # Predict object classes [batch_size, num_patches, num_queries+1]
  1353. (pred_logits, class_embeds) = self.class_predictor(image_feats, query_embeds, query_mask)
  1354. # Predict object boxes
  1355. pred_boxes = self.box_predictor(image_feats, feature_map, interpolate_pos_encoding)
  1356. if not return_dict:
  1357. output = (
  1358. pred_logits,
  1359. pred_boxes,
  1360. query_embeds,
  1361. feature_map,
  1362. class_embeds,
  1363. text_outputs.to_tuple(),
  1364. vision_outputs.to_tuple(),
  1365. )
  1366. output = tuple(x for x in output if x is not None)
  1367. return output
  1368. return OwlViTObjectDetectionOutput(
  1369. image_embeds=feature_map,
  1370. text_embeds=query_embeds,
  1371. pred_boxes=pred_boxes,
  1372. logits=pred_logits,
  1373. class_embeds=class_embeds,
  1374. text_model_output=text_outputs,
  1375. vision_model_output=vision_outputs,
  1376. )
  1377. __all__ = ["OwlViTModel", "OwlViTPreTrainedModel", "OwlViTTextModel", "OwlViTVisionModel", "OwlViTForObjectDetection"]