modeling_owlv2.py 76 KB

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