Ë
    ÜÓ^jIõ  ã                   óú  — d Z ddlmZ ddlmZ ddlmZ ddlZddlmZm	Z	 ddl
mZ dd	lmZ dd
lmZ ddlmZ ddlmZmZ ddlmZmZ ddlmZ ddlmZmZmZmZm Z m!Z! ddl"m#Z#m$Z$ ddl%m&Z& ddl'm(Z(m)Z)m*Z*  e«       rddl+m,Z,  e jZ                  e.«      Z/dej                  dej                  fd„Z0dej                  dej                  fd„Z1ee G d„ de«      «       «       Z2dedefd„Z3dedefd„Z4d „ Z5d!„ Z6 ed"¬#«      e G d$„ d%e«      «       «       Z7 ed&¬#«      e G d'„ d(e«      «       «       Z8 G d)„ d*e	jr                  «      Z: G d+„ d,e	jr                  «      Z;	 	 dQd-e	jr                  d.ej                  d/ej                  d0ej                  d1ej                  dz  d2e<dz  d3e<d4ee   fd5„Z= G d6„ d7e	jr                  «      Z> G d8„ d9e	jr                  «      Z? G d:„ d;e«      Z@e G d<„ d=e«      «       ZA G d>„ d?e	jr                  «      ZB G d@„ dAeA«      ZC G dB„ dCeA«      ZD G dD„ dEeA«      ZE G dF„ dGeA«      ZFe G dH„ dIeA«      «       ZG G dJ„ dKe	jr                  «      ZH G dL„ dMe	jr                  «      ZI G dN„ dOeA«      ZJg dP¢ZKy)RzPyTorch OWL-ViT model.é    )ÚCallable)Ú	dataclass)ÚAnyN)ÚTensorÚnné   )Úinitialization)ÚACT2FN)Úcreate_causal_mask)ÚGradientCheckpointingLayer)ÚBaseModelOutputÚBaseModelOutputWithPooling)ÚALL_ATTENTION_FUNCTIONSÚPreTrainedModel)ÚUnpack)ÚModelOutputÚTransformersKwargsÚauto_docstringÚis_vision_availableÚloggingÚ	torch_int)Úcan_return_tupleÚmerge_with_config_defaults)Úcapture_outputsé   )ÚOwlViTConfigÚOwlViTTextConfigÚOwlViTVisionConfig)Úcenter_to_corners_formatÚlogitsÚreturnc                 ó’   — t         j                  j                  | t        j                  t        | «      | j                  ¬«      «      S )N©Údevice)r   Ú
functionalÚcross_entropyÚtorchÚarangeÚlenr$   )r    s    úu/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/owlvit/modeling_owlvit.pyÚcontrastive_lossr+   6   s/   € Ü�=‰=×&Ñ& v¬u¯|©|¼CÀ»KÐPV×P]ÑP]Ô/^Ó_Ð_ó    Ú
similarityc                 óR   — t        | «      }t        | j                  «      }||z   dz  S )Ng       @)r+   ÚT)r-   Úcaption_lossÚ
image_losss      r*   Úimage_text_contrastive_lossr2   ;   s*   € Ü# JÓ/€LÜ! *§,¡,Ó/€JØ˜:Ñ%¨Ñ,Ð,r,   c                   ó  — e Zd ZU dZdZej                  dz  ed<   dZej                  dz  ed<   dZ	ej                  dz  ed<   dZ
ej                  dz  ed<   dZej                  dz  ed<   dZeed<   dZeed	<   d
ee   fd„Zy)ÚOwlViTOutputa×  
    loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
        Contrastive loss for image-text similarity.
    logits_per_image (`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
        The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
        similarity scores.
    logits_per_text (`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
        The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
        similarity scores.
    text_embeds (`torch.FloatTensor` of shape `(batch_size * num_max_text_queries, output_dim`):
        The text embeddings obtained by applying the projection layer to the pooled output of [`OwlViTTextModel`].
    image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
        The image embeddings obtained by applying the projection layer to the pooled output of
        [`OwlViTVisionModel`].
    text_model_output (tuple[`BaseModelOutputWithPooling`]):
        The output of the [`OwlViTTextModel`].
    vision_model_output (`BaseModelOutputWithPooling`):
        The output of the [`OwlViTVisionModel`].
    NÚlossÚlogits_per_imageÚlogits_per_textÚtext_embedsÚimage_embedsÚtext_model_outputÚvision_model_outputr!   c                 óH   ‡ — t        ˆ fd„‰ j                  «       D «       «      S )Nc              3   ód   •K  — | ]'  }|d vr‰|   nt        ‰|«      j                  «       –— Œ) y­w©)r:   r;   N©ÚgetattrÚto_tuple©Ú.0ÚkÚselfs     €r*   ú	<genexpr>z(OwlViTOutput.to_tuple.<locals>.<genexpr>a   ó=   øè ø€ ò 
àð Ð LÑLˆD�ŠGÔRYÐZ^Ð`aÓRb×RkÑRkÓRmÓmñ
ùó   ƒ-0©ÚtupleÚkeys©rE   s   `r*   rA   zOwlViTOutput.to_tuple`   ó#   ø€ Üó 
à—Y‘Y“[ô
ó 
ð 	
r,   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r5   r'   ÚFloatTensorÚ__annotations__r6   r7   r8   r9   r:   r   r;   rJ   r   rA   © r,   r*   r4   r4   A   s›   … ñð( &*€Dˆ%×
Ñ
˜dÑ
"Ó)Ø15Ð�e×'Ñ'¨$Ñ.Ó5Ø04€O�U×&Ñ&¨Ñ-Ó4Ø,0€K�×"Ñ" TÑ)Ó0Ø-1€L�%×#Ñ# dÑ*Ó1Ø48ÐÐ1Ó8Ø6:ÐÐ3Ó:ð
˜% ™*ô 
r,   r4   Útc                 ó  — | j                  «       r>| j                  t        j                  t        j                  fv r| S | j                  «       S | j                  t        j                  t        j                  fv r| S | j                  «       S ©N)	Úis_floating_pointÚdtyper'   Úfloat32Úfloat64ÚfloatÚint32Úint64Úint)rU   s    r*   Ú_upcastr`   h   s`   € à×ÑÔØ—G‘G¤§¡¬u¯}©}Ð=Ñ=ˆqÐLÀ1Ç7Á7Ã9ÐLà—G‘G¤§¡¬U¯[©[Ð9Ñ9ˆqÐF¸q¿u¹u»wÐFr,   Úboxesc                 óf   — t        | «      } | dd…df   | dd…df   z
  | dd…df   | dd…df   z
  z  S )a´  
    Computes the area of a set of bounding boxes, which are specified by its (x1, y1, x2, y2) coordinates.

    Args:
        boxes (`torch.FloatTensor` of shape `(number_of_boxes, 4)`):
            Boxes for which the area will be computed. They are expected to be in (x1, y1, x2, y2) format with `0 <= x1
            < x2` and `0 <= y1 < y2`.

    Returns:
        `torch.FloatTensor`: a tensor containing the area for each box.
    Né   r   r   r   )r`   )ra   s    r*   Úbox_areard   q   sB   € ô �E‹N€EØ’!�Q�$‰K˜%¢ 1 ™+Ñ%¨%²°1°©+¸ºaÀ¸d¹Ñ*CÑDÐDr,   c                 ó^  — t        | «      }t        |«      }t        j                  | d d …d d d…f   |d d …d d…f   «      }t        j                  | d d …d dd …f   |d d …dd …f   «      }||z
  j	                  d¬«      }|d d …d d …df   |d d …d d …df   z  }|d d …d f   |z   |z
  }||z  }	|	|fS )Nrc   r   ©Úminr   )rd   r'   Úmaxrg   Úclamp)
Úboxes1Úboxes2Úarea1Úarea2Úleft_topÚright_bottomÚwidth_heightÚinterÚunionÚious
             r*   Úbox_iourt   ‚   sÊ   € Ü�VÓ€EÜ�VÓ€Eä�y‰y˜¢ 4¨¨!¨ Ñ,¨f²Q¸¸¸°U©mÓ<€HÜ—9‘9˜V¢A t¨Q©R KÑ0°&º¸A¹B¸±-Ó@€Là  8Ñ+×2Ñ2°qÐ2Ó9€LØššA˜q˜Ñ! L²²A°q°Ñ$9Ñ9€Eà’!�T�'‰N˜UÑ" UÑ*€Eà
�%‰-€CØ�ˆ:Ðr,   c                 ó  — | dd…dd…f   | dd…dd…f   k\  j                  «       st        d| › �«      ‚|dd…dd…f   |dd…dd…f   k\  j                  «       st        d|› �«      ‚t        | |«      \  }}t        j                  | dd…ddd…f   |dd…dd…f   «      }t        j
                  | dd…ddd…f   |dd…dd…f   «      }||z
  j                  d¬«      }|dd…dd…df   |dd…dd…df   z  }|||z
  |z  z
  S )zâ
    Generalized IoU from https://giou.stanford.edu/. The boxes should be in [x0, y0, x1, y1] (corner) format.

    Returns:
        `torch.FloatTensor`: a [N, M] pairwise matrix, where N = len(boxes1) and M = len(boxes2)
    Nrc   z<boxes1 must be in [x0, y0, x1, y1] (corner) format, but got z<boxes2 must be in [x0, y0, x1, y1] (corner) format, but got r   rf   r   )ÚallÚ
ValueErrorrt   r'   rg   rh   ri   )rj   rk   rs   rr   Útop_leftÚbottom_rightrp   Úareas           r*   Úgeneralized_box_iour{   “   s*  € ð ’1�a‘b�5‰M˜V¢A r¨ r E™]Ñ*×/Ñ/Ô1ÜÐWÐX^ÐW_Ð`ÓaÐaØ’1�a‘b�5‰M˜V¢A r¨ r E™]Ñ*×/Ñ/Ô1ÜÐWÐX^ÐW_Ð`ÓaÐaÜ˜ Ó(�J€Cˆä�y‰y˜¢ 4¨¨!¨ Ñ,¨f²Q¸¸¸°U©mÓ<€HÜ—9‘9˜V¢A t¨Q©R KÑ0°&º¸A¹B¸±-Ó@€Là  8Ñ+×2Ñ2°qÐ2Ó9€LØšš1˜a˜Ñ  <²²1°a°Ñ#8Ñ8€Dà�$˜‘, $Ñ&Ñ&Ð&r,   z6
    Output type of [`OwlViTForObjectDetection`].
    )Úcustom_introc                   óD  — e Zd ZU dZdZej                  dz  ed<   dZe	dz  ed<   dZ
ej                  dz  ed<   dZej                  dz  ed<   dZej                  dz  ed<   dZej                  dz  ed<   dZej                  dz  ed	<   dZeed
<   dZeed<   dee   fd„Zy)ÚOwlViTObjectDetectionOutputaá  
    loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` are provided)):
        Total loss as a linear combination of a negative log-likelihood (cross-entropy) for class prediction and a
        bounding box loss. The latter is defined as a linear combination of the L1 loss and the generalized
        scale-invariant IoU loss.
    loss_dict (`Dict`, *optional*):
        A dictionary containing the individual losses. Useful for logging.
    logits (`torch.FloatTensor` of shape `(batch_size, num_patches, num_queries)`):
        Classification logits (including no-object) for all queries.
    pred_boxes (`torch.FloatTensor` of shape `(batch_size, num_patches, 4)`):
        Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). These
        values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding
        possible padding). You can use [`~OwlViTImageProcessor.post_process_object_detection`] to retrieve the
        unnormalized bounding boxes.
    text_embeds (`torch.FloatTensor` of shape `(batch_size, num_max_text_queries, output_dim`):
        The text embeddings obtained by applying the projection layer to the pooled output of [`OwlViTTextModel`].
    image_embeds (`torch.FloatTensor` of shape `(batch_size, patch_size, patch_size, output_dim`):
        Pooled output of [`OwlViTVisionModel`]. OWL-ViT represents images as a set of image patches and computes
        image embeddings for each patch.
    class_embeds (`torch.FloatTensor` of shape `(batch_size, num_patches, hidden_size)`):
        Class embeddings of all image patches. OWL-ViT represents images as a set of image patches where the total
        number of patches is (image_size / patch_size)**2.
    text_model_output (tuple[`BaseModelOutputWithPooling`]):
        The output of the [`OwlViTTextModel`].
    vision_model_output (`BaseModelOutputWithPooling`):
        The output of the [`OwlViTVisionModel`].
    Nr5   Ú	loss_dictr    Ú
pred_boxesr8   r9   Úclass_embedsr:   r;   r!   c                 óH   ‡ — t        ˆ fd„‰ j                  «       D «       «      S )Nc              3   ód   •K  — | ]'  }|d vr‰|   nt        ‰|«      j                  «       –— Œ) y­wr>   r?   rB   s     €r*   rF   z7OwlViTObjectDetectionOutput.to_tuple.<locals>.<genexpr>Ù   rG   rH   rI   rL   s   `r*   rA   z$OwlViTObjectDetectionOutput.to_tupleØ   rM   r,   )rN   rO   rP   rQ   r5   r'   rR   rS   r   Údictr    r€   r8   r9   r�   r:   r   r;   rJ   r   rA   rT   r,   r*   r~   r~   «   s½   … ñð8 &*€Dˆ%×
Ñ
˜dÑ
"Ó)Ø!€Iˆt�d‰{Ó!Ø'+€FˆE×Ñ Ñ$Ó+Ø+/€J�×!Ñ! DÑ(Ó/Ø,0€K�×"Ñ" TÑ)Ó0Ø-1€L�%×#Ñ# dÑ*Ó1Ø-1€L�%×#Ñ# dÑ*Ó1Ø48ÐÐ1Ó8Ø6:ÐÐ3Ó:ð
˜% ™*ô 
r,   r~   zM
    Output type of [`OwlViTForObjectDetection.image_guided_detection`].
    c                   ó0  — e Zd ZU dZdZej                  dz  ed<   dZej                  dz  ed<   dZ	ej                  dz  ed<   dZ
ej                  dz  ed<   dZej                  dz  ed<   dZej                  dz  ed<   dZeed	<   dZeed
<   dee   fd„Zy)Ú&OwlViTImageGuidedObjectDetectionOutputa  
    logits (`torch.FloatTensor` of shape `(batch_size, num_patches, num_queries)`):
        Classification logits (including no-object) for all queries.
    image_embeds (`torch.FloatTensor` of shape `(batch_size, patch_size, patch_size, output_dim`):
        Pooled output of [`OwlViTVisionModel`]. OWL-ViT represents images as a set of image patches and computes
        image embeddings for each patch.
    query_image_embeds (`torch.FloatTensor` of shape `(batch_size, patch_size, patch_size, output_dim`):
        Pooled output of [`OwlViTVisionModel`]. OWL-ViT represents images as a set of image patches and computes
        image embeddings for each patch.
    target_pred_boxes (`torch.FloatTensor` of shape `(batch_size, num_patches, 4)`):
        Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). These
        values are normalized in [0, 1], relative to the size of each individual target image in the batch
        (disregarding possible padding). You can use [`~OwlViTImageProcessor.post_process_object_detection`] to
        retrieve the unnormalized bounding boxes.
    query_pred_boxes (`torch.FloatTensor` of shape `(batch_size, num_patches, 4)`):
        Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). These
        values are normalized in [0, 1], relative to the size of each individual query image in the batch
        (disregarding possible padding). You can use [`~OwlViTImageProcessor.post_process_object_detection`] to
        retrieve the unnormalized bounding boxes.
    class_embeds (`torch.FloatTensor` of shape `(batch_size, num_patches, hidden_size)`):
        Class embeddings of all image patches. OWL-ViT represents images as a set of image patches where the total
        number of patches is (image_size / patch_size)**2.
    text_model_output (tuple[`BaseModelOutputWithPooling`]):
        The output of the [`OwlViTTextModel`].
    vision_model_output (`BaseModelOutputWithPooling`):
        The output of the [`OwlViTVisionModel`].
    Nr    r9   Úquery_image_embedsÚtarget_pred_boxesÚquery_pred_boxesr�   r:   r;   r!   c                 óH   ‡ — t        ˆ fd„‰ j                  «       D «       «      S )Nc              3   ód   •K  — | ]'  }|d vr‰|   nt        ‰|«      j                  «       –— Œ) y­wr>   r?   rB   s     €r*   rF   zBOwlViTImageGuidedObjectDetectionOutput.to_tuple.<locals>.<genexpr>  rG   rH   rI   rL   s   `r*   rA   z/OwlViTImageGuidedObjectDetectionOutput.to_tuple  rM   r,   )rN   rO   rP   rQ   r    r'   rR   rS   r9   r‡   rˆ   r‰   r�   r:   r   r;   rJ   r   rA   rT   r,   r*   r†   r†   ß   s²   … ñð8 (,€FˆE×Ñ Ñ$Ó+Ø-1€L�%×#Ñ# dÑ*Ó1Ø37Ð˜×)Ñ)¨DÑ0Ó7Ø26Ð�u×(Ñ(¨4Ñ/Ó6Ø15Ð�e×'Ñ'¨$Ñ.Ó5Ø-1€L�%×#Ñ# dÑ*Ó1Ø48ÐÐ1Ó8Ø6:ÐÐ3Ó:ð
˜% ™*ô 
r,   r†   c                   ó¢   ‡ — e Zd Zdefˆ fd„Zdej                  dededej                  fd„Zddej                  d	e
dej                  fd
„Zˆ xZS )ÚOwlViTVisionEmbeddingsÚconfigc                 ó¸  •— t         ‰| �  «        |j                  | _        || _        |j                  | _        t        j                  t        j                  |j                  «      «      | _
        t        j                  |j                  | j
                  |j                  |j                  d¬«      | _        |j                  |j                  z  dz  | _        | j                  dz   | _        t        j"                  | j                   | j
                  «      | _        | j'                  dt        j(                  | j                   «      j+                  d«      d¬«       y )NF)Úin_channelsÚout_channelsÚkernel_sizeÚstrideÚbiasrc   r   Úposition_ids©r   éÿÿÿÿ©Ú
persistent)ÚsuperÚ__init__Ú
patch_sizerŽ   Úhidden_sizeÚ	embed_dimr   Ú	Parameterr'   ÚrandnÚclass_embeddingÚConv2dÚnum_channelsÚpatch_embeddingÚ
image_sizeÚnum_patchesÚnum_positionsÚ	EmbeddingÚposition_embeddingÚregister_bufferr(   Úexpand©rE   rŽ   Ú	__class__s     €r*   r›   zOwlViTVisionEmbeddings.__init__  s  ø€ Ü‰ÑÔØ ×+Ñ+ˆŒØˆŒØ×+Ñ+ˆŒÜ!Ÿ|™|¬E¯K©K¸×8JÑ8JÓ,KÓLˆÔä!Ÿy™yØ×+Ñ+ØŸ™Ø×)Ñ)Ø×$Ñ$Øô 
ˆÔð #×-Ñ-°×1BÑ1BÑBÀqÑHˆÔØ!×-Ñ-°Ñ1ˆÔÜ"$§,¡,¨t×/AÑ/AÀ4Ç>Á>Ó"RˆÔØ×Ñ˜^¬U¯\©\¸$×:LÑ:LÓ-M×-TÑ-TÐU\Ó-]ÐjoÐÕpr,   Ú
embeddingsÚheightÚwidthr!   c                 óÒ  — |j                   d   dz
  }| j                  j                  j                  d«      }|j                   d   dz
  }t        j
                  j                  «       s%||k(  r ||k(  r| j                  | j                  «      S |dd…dd…f   }|dd…dd…f   }|j                   d   }	|| j                  z  }
|| j                  z  }t        |dz  «      }|j                  d|||	«      }|j                  dddd«      }t        j                  j                  ||
|fdd	¬
«      }|j                  dddd«      j                  dd|	«      }t	        j                   ||fd¬«      S )a   
        This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
        images. This method is also adapted to support torch.jit tracing.

        Adapted from:
        - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
        - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
        r   r   Nr—   g      à?r   rc   ÚbicubicF)ÚsizeÚmodeÚalign_corners©Údim)Úshaper©   ÚweightÚ	unsqueezer'   ÚjitÚ
is_tracingr•   rœ   r   ÚreshapeÚpermuter   r%   ÚinterpolateÚviewÚcat)rE   r®   r¯   r°   r¦   r©   r§   Úclass_pos_embedÚpatch_pos_embedr·   Ú
new_heightÚ	new_widthÚsqrt_num_positionss                r*   Úinterpolate_pos_encodingz/OwlViTVisionEmbeddings.interpolate_pos_encoding(  sv  € ð !×&Ñ& qÑ)¨AÑ-ˆØ!×4Ñ4×;Ñ;×EÑEÀaÓHÐØ*×0Ñ0°Ñ3°aÑ7ˆô �y‰y×#Ñ#Ô%¨+¸Ò*FÈ6ÐUZÊ?Ø×*Ñ*¨4×+<Ñ+<Ó=Ð=à,ªQ°°°¨UÑ3ˆØ,ªQ°±¨UÑ3ˆà×Ñ˜rÑ"ˆà˜tŸ™Ñ.ˆ
Ø˜TŸ_™_Ñ,ˆ	ä& }°cÑ'9Ó:ÐØ)×1Ñ1°!Ð5GÐI[Ð]`ÓaˆØ)×1Ñ1°!°Q¸¸1Ó=ˆÜŸ-™-×3Ñ3ØØ˜iÐ(ØØð	 4ó 
ˆð *×1Ñ1°!°Q¸¸1Ó=×BÑBÀ1ÀbÈ#ÓNˆÜ�y‰y˜/¨?Ð;ÀÔCÐCr,   Úpixel_valuesrÇ   c                 óh  — |j                   \  }}}}| j                  |«      }|j                  d«      j                  dd«      }| j                  j                  |dd«      }t        j                  ||gd¬«      }	|r|	| j                  |	||«      z   }	|	S |	| j                  | j                  «      z   }	|	S )Nrc   r   r—   r¶   )r¸   r¤   ÚflattenÚ	transposer¡   r«   r'   rÁ   rÇ   r©   r•   )
rE   rÈ   rÇ   Ú
batch_sizeÚ_r¯   r°   Úpatch_embedsr�   r®   s
             r*   ÚforwardzOwlViTVisionEmbeddings.forwardN  s»   € Ø'3×'9Ñ'9Ñ$ˆ
�A�v˜uØ×+Ñ+¨LÓ9ˆØ#×+Ñ+¨AÓ.×8Ñ8¸¸AÓ>ˆØ×+Ñ+×2Ñ2°:¸qÀ"ÓEˆÜ—Y‘Y ¨lÐ;ÀÔCˆ
Ù#Ø# d×&CÑ&CÀJÐPVÐX]Ó&^Ñ^ˆJð Ðð $ d×&=Ñ&=¸d×>OÑ>OÓ&PÑPˆJØÐr,   ©F)rN   rO   rP   r   r›   r'   r   r_   rÇ   rR   ÚboolrÏ   Ú__classcell__©r­   s   @r*   r�   r�     sm   ø„ ðqÐ1õ qð*$D°5·<±<ð $DÈð $DÐUXð $DÐ]b×]iÑ]ió $DñL
 E×$5Ñ$5ð 
ÐQUð 
Ðbg×bnÑbn÷ 
r,   r�   c            	       ó¦   ‡ — e Zd Zdefˆ fd„Z	 	 	 d	dej                  dz  dej                  dz  dej                  dz  dej                  fd„Z	ˆ xZ
S )
ÚOwlViTTextEmbeddingsrŽ   c                 ó^  •— t         ‰| �  «        t        j                  |j                  |j
                  «      | _        t        j                  |j                  |j
                  «      | _        | j                  dt        j                  |j                  «      j                  d«      d¬«       y )Nr•   r–   Fr˜   )rš   r›   r   r¨   Ú
vocab_sizer�   Útoken_embeddingÚmax_position_embeddingsr©   rª   r'   r(   r«   r¬   s     €r*   r›   zOwlViTTextEmbeddings.__init__\  s„   ø€ Ü‰ÑÔÜ!Ÿ|™|¨F×,=Ñ,=¸v×?QÑ?QÓRˆÔÜ"$§,¡,¨v×/MÑ/MÈv×OaÑOaÓ"bˆÔð 	×ÑØœEŸL™L¨×)GÑ)GÓH×OÑOÐPWÓXÐejð 	õ 	
r,   NÚ	input_idsr•   Úinputs_embedsr!   c                 óÆ   — |�|j                   d   n|j                   d   }|€| j                  d d …d |…f   }|€| j                  |«      }| j                  |«      }||z   }|S )Nr—   éþÿÿÿ)r¸   r•   rØ   r©   )rE   rÚ   r•   rÛ   Ú
seq_lengthÚposition_embeddingsr®   s          r*   rÏ   zOwlViTTextEmbeddings.forwardf  s{   € ð -6Ð,A�Y—_‘_ RÒ(À}×GZÑGZÐ[]ÑG^ˆ
àÐØ×,Ñ,ªQ°°°¨^Ñ<ˆLàÐ Ø ×0Ñ0°Ó;ˆMà"×5Ñ5°lÓCÐØ"Ð%8Ñ8ˆ
àÐr,   ©NNN)rN   rO   rP   r   r›   r'   Ú
LongTensorrR   r   rÏ   rÒ   rÓ   s   @r*   rÕ   rÕ   [  sk   ø„ ð
Ð/õ 
ð .2Ø04Ø26ñ	à×#Ñ# dÑ*ðð ×&Ñ&¨Ñ-ðð ×(Ñ(¨4Ñ/ð	ð
 
�‰÷r,   rÕ   ÚmoduleÚqueryÚkeyÚvalueÚattention_maskÚscalingÚdropoutÚkwargsc                 óœ  — |€|j                  d«      dz  }t        j                  ||j                  dd«      «      |z  }|�||z   }t        j
                  j                  |d¬«      }t        j
                  j                  ||| j                  ¬«      }t        j                  ||«      }	|	j                  dd«      j                  «       }	|	|fS )Nr—   ç      à¿rc   r   r¶   )ÚpÚtrainingr   )
r³   r'   ÚmatmulrË   r   r%   Úsoftmaxrè   rí   Ú
contiguous)
râ   rã   rä   rå   ræ   rç   rè   ré   Úattn_weightsÚattn_outputs
             r*   Úeager_attention_forwardró   {  s»   € ð €Ø—*‘*˜R“. DÑ(ˆô —<‘<  s§}¡}°Q¸Ó':Ó;¸gÑE€LàÐ!Ø# nÑ4ˆä—=‘=×(Ñ(¨¸2Ð(Ó>€LÜ—=‘=×(Ñ(¨¸È6Ï?É?Ð(Ó[€Lä—,‘,˜|¨UÓ3€KØ×'Ñ'¨¨1Ó-×8Ñ8Ó:€Kà˜Ð$Ð$r,   c                   óª   ‡ — e Zd ZdZˆ fd„Z	 d	dej                  dej                  dz  dee   de	ej                  ej                  dz  f   fd„Z
ˆ xZS )
ÚOwlViTAttentionz=Multi-headed attention from 'Attention Is All You Need' paperc                 ó  •— t         ‰| �  «        || _        |j                  | _        |j
                  | _        | j                  | j                  z  | _        | j                  | j                  z  | j                  k7  r&t        d| j                  › d| j                  › d�«      ‚| j                  dz  | _	        |j                  | _        d| _        t        j                  | j                  | j                  «      | _        t        j                  | j                  | j                  «      | _        t        j                  | j                  | j                  «      | _        t        j                  | j                  | j                  «      | _        y )Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).rë   F)rš   r›   rŽ   r�   rž   Únum_attention_headsÚ	num_headsÚhead_dimrw   ÚscaleÚattention_dropoutrè   Ú	is_causalr   ÚLinearÚk_projÚv_projÚq_projÚout_projr¬   s     €r*   r›   zOwlViTAttention.__init__š  s  ø€ Ü‰ÑÔØˆŒØ×+Ñ+ˆŒØ×3Ñ3ˆŒØŸ™¨$¯.©.Ñ8ˆŒØ�=‰=˜4Ÿ>™>Ñ)¨T¯^©^Ò;ÜØMÈdÏnÉnÐM]ð ^Ø—N‘NÐ# 2ð'óð ð —]‘] DÑ(ˆŒ
Ø×/Ñ/ˆŒØˆŒä—i‘i §¡°·±Ó?ˆŒÜ—i‘i §¡°·±Ó?ˆŒÜ—i‘i §¡°·±Ó?ˆŒÜŸ	™	 $§.¡.°$·.±.ÓAˆ�r,   NÚhidden_statesræ   ré   r!   c                 óŽ  — |j                   d d }g |¢d‘| j                  ‘­} | j                  |«      j                  |Ž j	                  dd«      } | j                  |«      j                  |Ž j	                  dd«      } | j                  |«      j                  |Ž j	                  dd«      }t        j                  | j                  j                  t        «      }	 |	| ||||f| j                  | j                  sdn| j                  dœ|¤Ž\  }
} |
j                  g |¢d‘­Ž j!                  «       }
| j#                  |
«      }
|
|fS )Nr—   r   rc   ç        )rç   rè   )r¸   rù   r   rÀ   rË   rþ   rÿ   r   Úget_interfacerŽ   Ú_attn_implementationró   rú   rí   rè   r½   rð   r  )rE   r  ræ   ré   Úinput_shapeÚhidden_shapeÚquery_statesÚ
key_statesÚvalue_statesÚattention_interfacerò   rñ   s               r*   rÏ   zOwlViTAttention.forward®  sQ  € ð $×)Ñ)¨#¨2Ð.ˆØ8˜Ð8 bÐ8¨$¯-©-Ñ8ˆà6�t—{‘{ =Ó1×6Ñ6¸ÐE×OÑOÐPQÐSTÓUˆØ4�T—[‘[ Ó/×4Ñ4°lÐC×MÑMÈaÐQRÓSˆ
Ø6�t—{‘{ =Ó1×6Ñ6¸ÐE×OÑOÐPQÐSTÓUˆä(?×(MÑ(MØ�K‰K×,Ñ,Ô.Eó)
Ðñ %8ØØØØØð	%
ð —J‘JØ#Ÿ}š}‘C°$·,±,ñ	%
ð ñ	%
Ñ!ˆ�\ð *�k×)Ñ)Ð;¨;Ð;¸Ò;×FÑFÓHˆØ—m‘m KÓ0ˆà˜LÐ(Ð(r,   rW   )rN   rO   rP   rQ   r›   r'   r   r   r   rJ   rÏ   rÒ   rÓ   s   @r*   rõ   rõ   —  sf   ø„ ÙGôBð. /3ñ)à—|‘|ð)ð Ÿ™ tÑ+ð)ð Ð+Ñ,ð	)ð
 
ˆu�|‰|˜UŸ\™\¨DÑ0Ð0Ñ	1÷)r,   rõ   c                   óV   ‡ — e Zd Zˆ fd„Zdej
                  dej
                  fd„Zˆ xZS )Ú	OwlViTMLPc                 ó  •— t         ‰| �  «        || _        t        |j                     | _        t        j                  |j                  |j                  «      | _
        t        j                  |j                  |j                  «      | _        y rW   )rš   r›   rŽ   r
   Ú
hidden_actÚactivation_fnr   rý   r�   Úintermediate_sizeÚfc1Úfc2r¬   s     €r*   r›   zOwlViTMLP.__init__Ò  sd   ø€ Ü‰ÑÔØˆŒÜ# F×$5Ñ$5Ñ6ˆÔÜ—9‘9˜V×/Ñ/°×1IÑ1IÓJˆŒÜ—9‘9˜V×5Ñ5°v×7IÑ7IÓJˆ�r,   r  r!   c                 ól   — | j                  |«      }| j                  |«      }| j                  |«      }|S rW   )r  r  r  )rE   r  s     r*   rÏ   zOwlViTMLP.forwardÙ  s4   € ØŸ™ Ó/ˆØ×*Ñ*¨=Ó9ˆØŸ™ Ó/ˆØÐr,   )rN   rO   rP   r›   r'   r   rÏ   rÒ   rÓ   s   @r*   r  r  Ñ  s$   ø„ ôKð U§\¡\ð °e·l±l÷ r,   r  c                   ó„   ‡ — e Zd Zdeez  fˆ fd„Zdej                  dej                  dee	   dej                  fd„Zˆ xZS )ÚOwlViTEncoderLayerrŽ   c                 óD  •— t         ‰| �  «        |j                  | _        t	        |«      | _        t        j                  | j                  |j                  ¬«      | _	        t        |«      | _        t        j                  | j                  |j                  ¬«      | _        y ©N©Úeps)rš   r›   r�   rž   rõ   Ú	self_attnr   Ú	LayerNormÚlayer_norm_epsÚlayer_norm1r  ÚmlpÚlayer_norm2r¬   s     €r*   r›   zOwlViTEncoderLayer.__init__â  sm   ø€ Ü‰ÑÔØ×+Ñ+ˆŒÜ(¨Ó0ˆŒÜŸ<™<¨¯©¸F×<QÑ<QÔRˆÔÜ˜VÓ$ˆŒÜŸ<™<¨¯©¸F×<QÑ<QÔRˆÕr,   r  ræ   ré   r!   c                 ó¸   — |}| j                  |«      } | j                  d||dœ|¤Ž\  }}||z   }|}| j                  |«      }| j                  |«      }||z   }|S )N)r  ræ   rT   )r  r  r!  r   )rE   r  ræ   ré   ÚresidualrÍ   s         r*   rÏ   zOwlViTEncoderLayer.forwardê  s‚   € ð !ˆà×(Ñ(¨Ó7ˆØ)˜4Ÿ>™>ð 
Ø'Ø)ñ
ð ñ
Ñˆ�qð
 ! =Ñ0ˆà ˆØ×(Ñ(¨Ó7ˆØŸ™ Ó/ˆØ  =Ñ0ˆàÐr,   )rN   rO   rP   r   r   r›   r'   r   r   r   rR   rÏ   rÒ   rÓ   s   @r*   r  r  á  sW   ø„ ðSÐ1Ð4DÑDõ Sðà—|‘|ðð Ÿ™ðð Ð+Ñ,ð	ð
 
×	Ñ	÷r,   r  c                   ó˜   ‡ — e Zd ZU eed<   dZdZdZdZdZ	dZ
dZdgZeedœZ ej"                  «       dej&                  fˆ fd„«       Zˆ xZS )	ÚOwlViTPreTrainedModelrŽ   Úowlvit)ÚimageÚtextTr  )r  Ú
attentionsrâ   c                 ó¼	  •— t         ‰| �  |«       | j                  j                  }t	        |t
        «      r¸t        j                  |j                  j                  d|dz  ¬«       t        j                  |j                  j                  d|dz  ¬«       t        j                  |j                  t        j                  |j                  j                  d   «      j!                  d«      «       y	t	        |t"        «      �rt        j                  |j$                  d|j&                  dz  |z  ¬«       t        j                  |j(                  j                  |j                  j*                  |z  ¬«       t        j                  |j                  j                  |j                  j*                  |z  ¬«       t        j                  |j                  t        j                  |j                  j                  d   «      j!                  d«      «       y	t	        |t,        «      rî|j&                  dz  d|j                  j.                  z  dz  z  |z  }|j&                  dz  |z  }t        j                  |j0                  j                  |¬«       t        j                  |j2                  j                  |¬«       t        j                  |j4                  j                  |¬«       t        j                  |j6                  j                  |¬«       y	t	        |t8        «      r¯|j                  j:                  dz  d|j                  j.                  z  dz  z  |z  }d|j                  j:                  z  dz  |z  }t        j                  |j<                  j                  |¬«       t        j                  |j>                  j                  |¬«       y	t	        |t@        «      r«t        j                  |jB                  j                  |jD                  dz  |z  ¬«       t        j                  |jF                  j                  |jH                  dz  |z  ¬«       t        jJ                  |jL                  | j                  jN                  «       y	t	        |tP        «      rEt        j                  |jR                  |jU                  |jV                  |jX                  «      «       y	y	)
zInitialize the weightsr  g{®Gáz”?)ÚmeanÚstdr—   r–   rë   )r,  rc   N)-rš   Ú_init_weightsrŽ   Úinitializer_factorÚ
isinstancerÕ   ÚinitÚnormal_rØ   r¹   r©   Úcopy_r•   r'   r(   r¸   r«   r�   r¡   rž   r¤   Úinitializer_rangerõ   Únum_hidden_layersr   rþ   rÿ   r  r  r�   r  r  ÚOwlViTModelÚtext_projectionÚtext_embed_dimÚvisual_projectionÚvision_embed_dimÚ	constant_Úlogit_scaleÚlogit_scale_init_valueÚOwlViTForObjectDetectionÚbox_biasÚcompute_box_biasÚnum_patches_heightÚnum_patches_width)rE   râ   ÚfactorÚin_proj_stdÚout_proj_stdÚfc_stdr­   s         €r*   r-  z#OwlViTPreTrainedModel._init_weights  si  ø€ ô 	‰Ñ˜fÔ%Ø—‘×/Ñ/ˆÜ�fÔ2Ô3Ü�L‰L˜×/Ñ/×6Ñ6¸SÀfÈtÁmÕTÜ�L‰L˜×2Ñ2×9Ñ9ÀÈÐRVÉÕWÜ�J‰J�v×*Ñ*¬E¯L©L¸×9LÑ9L×9RÑ9RÐSUÑ9VÓ,W×,^Ñ,^Ð_fÓ,gÕhÜ˜Ô 6Õ7Ü�L‰L˜×/Ñ/°c¸v×?OÑ?OÐQUÑ?UÐX^Ñ?^Õ_Ü�L‰L˜×/Ñ/×6Ñ6¸F¿M¹M×<[Ñ<[Ð^dÑ<dÕeÜ�L‰L˜×2Ñ2×9Ñ9¸v¿}¹}×?^Ñ?^ÐagÑ?gÕhÜ�J‰J�v×*Ñ*¬E¯L©L¸×9LÑ9L×9RÑ9RÐSUÑ9VÓ,W×,^Ñ,^Ð_fÓ,gÕhÜ˜¤Ô0Ø!×+Ñ+¨TÑ1°q¸6¿=¹=×;ZÑ;ZÑ7ZÐ_cÑ6cÑdÐgmÑmˆKØ"×,Ñ,¨dÑ2°fÑ<ˆLÜ�L‰L˜Ÿ™×-Ñ-°;Õ?Ü�L‰L˜Ÿ™×-Ñ-°;Õ?Ü�L‰L˜Ÿ™×-Ñ-°;Õ?Ü�L‰L˜Ÿ™×/Ñ/°\ÖBÜ˜¤	Ô*Ø!Ÿ=™=×4Ñ4°dÑ:ÀÀFÇMÁM×DcÑDcÑ@cÐhlÑ?lÑmÐpvÑvˆKØ˜&Ÿ-™-×3Ñ3Ñ3¸Ñ<¸vÑEˆFÜ�L‰L˜Ÿ™×*Ñ*°Õ7Ü�L‰L˜Ÿ™×*Ñ*°Ö<Ü˜¤Ô,Ü�L‰LØ×&Ñ&×-Ñ-Ø×)Ñ)¨4Ñ/°&Ñ8õô �L‰LØ×(Ñ(×/Ñ/Ø×+Ñ+¨TÑ1°FÑ:õô �N‰N˜6×-Ñ-¨t¯{©{×/QÑ/QÕRÜ˜Ô 8Ô9Ü�J‰J�v—‘¨×(?Ñ(?À×@YÑ@YÐ[a×[sÑ[sÓ(tÕuð :r,   )rN   rO   rP   r   rS   Úbase_model_prefixÚinput_modalitiesÚsupports_gradient_checkpointingÚ_supports_sdpaÚ_supports_flash_attnÚ_supports_flex_attnÚ_supports_attention_backendÚ_no_split_modulesr  rõ   Ú_can_record_outputsr'   Úno_gradr   ÚModuler-  rÒ   rÓ   s   @r*   r%  r%    ss   ø… àÓØ ÐØ(ÐØ&*Ð#Ø€NØÐØÐØ"&ÐØ-Ð.Ðà+Ø%ñÐð
 €U‡]�]ƒ_ð$v B§I¡Iô $vó ô$vr,   r%  c                   ó`   ‡ — e Zd ZdZdefˆ fd„Z	 d	dej                  dz  dee	   de
fd„Zˆ xZS )
ÚOwlViTEncoderz±
    Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
    [`OwlViTEncoderLayer`].

    Args:
        config: OwlViTConfig
    rŽ   c                 óÐ   •— t         ‰| �  «        || _        t        j                  t        |j                  «      D �cg c]  }t        |«      ‘Œ c}«      | _        d| _	        y c c}w ©NF)
rš   r›   rŽ   r   Ú
ModuleListÚranger4  r  ÚlayersÚgradient_checkpointing)rE   rŽ   rÍ   r­   s      €r*   r›   zOwlViTEncoder.__init__D  sO   ø€ Ü‰ÑÔØˆŒÜ—m‘mÌÈv×OgÑOgÓIhÖ$iÀAÔ%7¸Õ%?Ò$iÓjˆŒØ&+ˆÕ#ùò %js   ½A#Nræ   ré   r!   c                 óT   — |}| j                   D ]  } |||fi |¤Ž}Œ t        |¬«      S )N)Úlast_hidden_state)rW  r   )rE   rÛ   ræ   ré   r  Úencoder_layers         r*   rÏ   zOwlViTEncoder.forwardJ  sH   € ð &ˆØ!Ÿ[™[ò 	ˆMÙ)ØØñð ñ‰Mð	ô Ø+ô
ð 	
r,   rW   )rN   rO   rP   rQ   r   r›   r'   r   r   r   r   rÏ   rÒ   rÓ   s   @r*   rR  rR  ;  sK   ø„ ñð,˜|õ ,ð /3ñ
ð Ÿ™ tÑ+ð
ð Ð+Ñ,ð	
ð
 
÷
r,   rR  c                   óÎ   ‡ — e Zd Zdefˆ fd„Ze ed¬«      e	 	 	 ddej                  dz  dej                  dz  dej                  dz  d	e
e   d
eez  f
d„«       «       «       Zˆ xZS )ÚOwlViTTextTransformerrŽ   c                 óè   •— t         ‰| �  |«       |j                  }t        |«      | _        t        |«      | _        t        j                  ||j                  ¬«      | _
        | j                  «        y r  )rš   r›   r�   rÕ   r®   rR  Úencoderr   r  r  Úfinal_layer_normÚ	post_init)rE   rŽ   rž   r­   s      €r*   r›   zOwlViTTextTransformer.__init__^  sX   ø€ Ü‰Ñ˜Ô à×&Ñ&ˆ	Ü.¨vÓ6ˆŒÜ$ VÓ,ˆŒÜ "§¡¨Y¸F×<QÑ<QÔ RˆÔð 	�‰Õr,   F©Útie_last_hidden_statesNrÚ   ræ   r•   ré   r!   c                 ó:  — |j                  «       }|j                  d|d   «      }| j                  ||¬«      }t        | j                  ||d¬«      }|j                  dd«        | j                  d||ddœ|¤Ž}|j                  }| j                  |«      }|t        j                  |j                  d   |j                  ¬	«      |j                  t        j                  «      j                  d¬
«      j                  |j                  «      f   }	t!        ||	¬«      S )a|  
        input_ids (`torch.LongTensor` of shape `(batch_size * num_max_text_queries, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See
            [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input
            IDs?](../glossary#input-ids)
        r—   )rÚ   r•   N)rŽ   rÛ   ræ   Úpast_key_valuesrü   T)rÛ   ræ   rü   r   r#   r¶   ©rZ  Úpooler_outputrT   )r³   rÀ   r®   r   rŽ   Úpopr_  rZ  r`  r'   r(   r¸   r$   Útor_   Úargmaxr   )
rE   rÚ   ræ   r•   ré   r  r  Úencoder_outputsrZ  Úpooled_outputs
             r*   rÏ   zOwlViTTextTransformer.forwardi  s   € ð   —n‘nÓ&ˆØ—N‘N 2 {°2¡Ó7ˆ	ØŸ™°)È,˜ÓWˆä+Ø—;‘;Ø'Ø)Ø ô	
ˆð 	�
‰
�; Ô%Ø+7¨4¯<©<ð ,
Ø'Ø)Øñ,
ð ñ	,
ˆð ,×=Ñ=ÐØ ×1Ñ1Ð2CÓDÐð *Ü�L‰LÐ*×0Ñ0°Ñ3Ð<M×<TÑ<TÔUØ�L‰LœŸ™Ó#×*Ñ*¨rÐ*Ó2×5Ñ5Ð6G×6NÑ6NÓOðQñ
ˆô
 *Ø/Ø'ô
ð 	
r,   rà   )rN   rO   rP   r   r›   r   r   r   r'   r   r   r   rJ   r   rÏ   rÒ   rÓ   s   @r*   r]  r]  ]  s›   ø„ ð	Ð/õ 	ð  Ù¨EÔ2Øð *.Ø.2Ø,0ñ	-
à—<‘< $Ñ&ð-
ð Ÿ™ tÑ+ð-
ð —l‘l TÑ)ð	-
ð
 Ð+Ñ,ð-
ð 
Ð+Ñ	+ò-
ó ó 3ó  ô-
r,   r]  c                   óÂ   ‡ — e Zd ZU eed<   dZdefˆ fd„Zdej                  fd„Z	d„ Z
e	 	 ddej                  dz  d	ej                  dz  d
ee   deez  fd„«       Zˆ xZS )ÚOwlViTTextModelrŽ   )r(  c                 ód   •— t         ‰| �  |«       t        |«      | _        | j	                  «        y rW   )rš   r›   r]  Ú
text_modelra  r¬   s     €r*   r›   zOwlViTTextModel.__init__   s&   ø€ Ü‰Ñ˜Ô Ü/°Ó7ˆŒà�‰Õr,   r!   c                 óB   — | j                   j                  j                  S rW   ©rp  r®   rØ   rL   s    r*   Úget_input_embeddingsz$OwlViTTextModel.get_input_embeddings¦  s   € Ø�‰×)Ñ)×9Ñ9Ð9r,   c                 ó:   — || j                   j                  _        y rW   rr  )rE   rå   s     r*   Úset_input_embeddingsz$OwlViTTextModel.set_input_embeddings©  s   € Ø5:ˆ�‰×"Ñ"Õ2r,   NrÚ   ræ   ré   c                 ó,   —  | j                   d||dœ|¤ŽS )aÛ  
        input_ids (`torch.LongTensor` of shape `(batch_size * num_max_text_queries, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See
            [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input
            IDs?](../glossary#input-ids)

        Examples:
        ```python
        >>> from transformers import AutoProcessor, OwlViTTextModel

        >>> model = OwlViTTextModel.from_pretrained("google/owlvit-base-patch32")
        >>> processor = AutoProcessor.from_pretrained("google/owlvit-base-patch32")
        >>> inputs = processor(
        ...     text=[["a photo of a cat", "a photo of a dog"], ["photo of a astranaut"]], return_tensors="pt"
        ... )
        >>> outputs = model(**inputs)
        >>> last_hidden_state = outputs.last_hidden_state
        >>> pooled_output = outputs.pooler_output  # pooled (EOS token) states
        ```©rÚ   ræ   rT   )rp  )rE   rÚ   ræ   ré   s       r*   rÏ   zOwlViTTextModel.forward¬  s,   € ð6 ˆt�‰ð 
ØØ)ñ
ð ñ
ð 	
r,   ©NN)rN   rO   rP   r   rS   rG  r›   r   rP  rs  ru  r   r'   r   r   r   rJ   r   rÏ   rÒ   rÓ   s   @r*   rn  rn  œ  s‘   ø… ØÓØ ÐðÐ/õ ð: b§i¡ió :ò;ð ð *.Ø.2ñ
à—<‘< $Ñ&ð
ð Ÿ™ tÑ+ð
ð Ð+Ñ,ð	
ð
 
Ð+Ñ	+ò
ó ô
r,   rn  c                   ó’   ‡ — e Zd Zdefˆ fd„Ze ed¬«      e	 ddej                  de
dz  dee   d	eez  fd
„«       «       «       Zˆ xZS )ÚOwlViTVisionTransformerrŽ   c                 óD  •— t         ‰| �  |«       t        |«      | _        t	        j
                  |j                  |j                  ¬«      | _        t        |«      | _
        t	        j
                  |j                  |j                  ¬«      | _        | j                  «        y r  )rš   r›   r�   r®   r   r  r�   r  Úpre_layernormrR  r_  Úpost_layernormra  r¬   s     €r*   r›   z OwlViTVisionTransformer.__init__Ï  sr   ø€ Ü‰Ñ˜Ô ä0°Ó8ˆŒÜŸ\™\¨&×*<Ñ*<À&×BWÑBWÔXˆÔÜ$ VÓ,ˆŒÜ Ÿl™l¨6×+=Ñ+=À6×CXÑCXÔYˆÔð 	�‰Õr,   Frb  rÈ   rÇ   Nré   r!   c                 óT  — | j                   j                  j                  j                  }|j	                  |«      }| j                  ||¬«      }| j                  |«      } | j                  dd|i|¤Ž}|j                  }|d d …dd d …f   }| j                  |«      }t        ||¬«      S )N)rÇ   rÛ   r   rf  rT   )
r®   r¤   r¹   rY   ri  r|  r_  rZ  r}  r   )	rE   rÈ   rÇ   ré   Úexpected_input_dtyper  rk  rZ  rl  s	            r*   rÏ   zOwlViTVisionTransformer.forwardÚ  s³   € ð  $Ÿ™×>Ñ>×EÑE×KÑKÐØ#—‘Ð';Ó<ˆàŸ™¨ÐOg˜ÓhˆØ×*Ñ*¨=Ó9ˆà+7¨4¯<©<ñ ,
Ø'ð,
àñ,
ˆð
 ,×=Ñ=ÐØ)ª!¨Q²¨'Ñ2ˆØ×+Ñ+¨MÓ:ˆä)Ø/Ø'ô
ð 	
r,   rÐ   )rN   rO   rP   r   r›   r   r   r   r'   rR   rÑ   r   r   rJ   r   rÏ   rÒ   rÓ   s   @r*   rz  rz  Î  sz   ø„ ð	Ð1õ 	ð  Ù¨EÔ2Øð 16ñ
à×'Ñ'ð
ð #'¨¡+ð
ð Ð+Ñ,ð	
ð
 
Ð+Ñ	+ò
ó ó 3ó  ô
r,   rz  c            
       ó    ‡ — e Zd ZU eed<   dZdZdefˆ fd„Zdej                  fd„Z
e	 	 ddej                  dz  ded	ee   defd
„«       Zˆ xZS )ÚOwlViTVisionModelrŽ   rÈ   )r'  c                 ód   •— t         ‰| �  |«       t        |«      | _        | j	                  «        y rW   )rš   r›   rz  Úvision_modelra  r¬   s     €r*   r›   zOwlViTVisionModel.__init__þ  s'   ø€ Ü‰Ñ˜Ô Ü3°FÓ;ˆÔà�‰Õr,   r!   c                 óB   — | j                   j                  j                  S rW   )rƒ  r®   r¤   rL   s    r*   rs  z&OwlViTVisionModel.get_input_embeddings  s   € Ø× Ñ ×+Ñ+×;Ñ;Ð;r,   NrÇ   ré   c                 ó,   —  | j                   d||dœ|¤ŽS )a'  
        Examples:
        ```python
        >>> from PIL import Image
        >>> import httpx
        >>> from io import BytesIO
        >>> from transformers import AutoProcessor, OwlViTVisionModel

        >>> model = OwlViTVisionModel.from_pretrained("google/owlvit-base-patch32")
        >>> processor = AutoProcessor.from_pretrained("google/owlvit-base-patch32")
        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> with httpx.stream("GET", url) as response:
        ...     image = Image.open(BytesIO(response.read()))

        >>> inputs = processor(images=image, return_tensors="pt")

        >>> outputs = model(**inputs)
        >>> last_hidden_state = outputs.last_hidden_state
        >>> pooled_output = outputs.pooler_output  # pooled CLS states
        ```©rÈ   rÇ   rT   )rƒ  )rE   rÈ   rÇ   ré   s       r*   rÏ   zOwlViTVisionModel.forward  s.   € ð8 !ˆt× Ñ ð 
Ø%Ø%=ñ
ð ñ
ð 	
r,   rT  )rN   rO   rP   r   rS   Úmain_input_namerG  r›   r   rP  rs  r   r'   rR   rÑ   r   r   r   rÏ   rÒ   rÓ   s   @r*   r�  r�  ù  s„   ø… ØÓØ$€OØ!ÐðÐ1õ ð< b§i¡ió <ð ð 26Ø).ñ
à×'Ñ'¨$Ñ.ð
ð #'ð
ð Ð+Ñ,ð	
ð
 
$ò
ó ô
r,   r�  c                   óš  ‡ — e Zd ZU eed<   defˆ fd„Zee	 ddej                  dej                  dz  de
e   deez  fd„«       «       Zee	 dd	ej                  d
ede
e   deez  fd„«       «       Zee	 	 	 	 	 	 ddej"                  dz  d	ej$                  dz  dej                  dz  dedz  d
ededz  de
e   deez  fd„«       «       Zˆ xZS )r5  rŽ   c                 óL  •— t         ‰| �  |«       |j                  }|j                  }|j                  | _        |j
                  | _        |j
                  | _        t        |«      | _	        t        |«      | _        t        j                  | j                  | j                  d¬«      | _        t        j                  | j                  | j                  d¬«      | _        t        j                   t#        j$                  |j&                  «      «      | _        | j+                  «        y )NF)r”   )rš   r›   Útext_configÚvision_configÚprojection_dimr�   r7  r9  r]  rp  rz  rƒ  r   rý   r8  r6  rŸ   r'   Útensorr<  r;  ra  )rE   rŽ   rŠ  r‹  r­   s       €r*   r›   zOwlViTModel.__init__.  sÙ   ø€ Ü‰Ñ˜Ô à×(Ñ(ˆØ×,Ñ,ˆà$×3Ñ3ˆÔØ)×5Ñ5ˆÔØ -× 9Ñ 9ˆÔä/°Ó<ˆŒÜ3°MÓBˆÔä!#§¡¨4×+@Ñ+@À$×BUÑBUÐ\aÔ!bˆÔÜ!Ÿy™y¨×)<Ñ)<¸d×>QÑ>QÐX]Ô^ˆÔÜŸ<™<¬¯©°V×5RÑ5RÓ(SÓTˆÔð 	�‰Õr,   NrÚ   ræ   ré   r!   c                 ót   —  | j                   d||dœ|¤Ž}|j                  }| j                  |«      |_        |S )a¨  
        input_ids (`torch.LongTensor` of shape `(batch_size * num_max_text_queries, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See
            [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input
            IDs?](../glossary#input-ids)

        Examples:
        ```python
        >>> import torch
        >>> from transformers import AutoProcessor, OwlViTModel

        >>> model = OwlViTModel.from_pretrained("google/owlvit-base-patch32")
        >>> processor = AutoProcessor.from_pretrained("google/owlvit-base-patch32")
        >>> inputs = processor(
        ...     text=[["a photo of a cat", "a photo of a dog"], ["photo of a astranaut"]], return_tensors="pt"
        ... )
        >>> with torch.inference_mode():
        ...     text_features = model.get_text_features(**inputs)
        ```rw  rT   )rp  rg  r6  )rE   rÚ   ræ   ré   Útext_outputsrl  s         r*   Úget_text_featureszOwlViTModel.get_text_featuresB  sP   € ð6 4C°4·?±?ð 4
ØØ)ñ4
ð ñ4
ˆð
 %×2Ñ2ˆØ%)×%9Ñ%9¸-Ó%HˆÔ"àÐr,   rÈ   rÇ   c                 óp   —  | j                   d||dœ|¤Ž}| j                  |j                  «      |_        |S )aˆ  
        Examples:
        ```python
        >>> import torch
        >>> from transformers.image_utils import load_image
        >>> from transformers import AutoProcessor, OwlViTModel

        >>> model = OwlViTModel.from_pretrained("google/owlvit-base-patch32")
        >>> processor = AutoProcessor.from_pretrained("google/owlvit-base-patch32")

        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> image = load_image(url)

        >>> inputs = processor(images=image, return_tensors="pt")
        >>> with torch.inference_mode():
        ...     image_features = model.get_image_features(**inputs)
        ```r†  rT   )rƒ  r8  rg  )rE   rÈ   rÇ   ré   Úvision_outputss        r*   Úget_image_featureszOwlViTModel.get_image_featuresg  sM   € ð2 6G°T×5FÑ5Fð 6
Ø%Ø%=ñ6
ð ñ6
ˆð
 (,×'=Ñ'=¸n×>ZÑ>ZÓ'[ˆÔ$àÐr,   Úreturn_lossÚreturn_base_image_embedsc           	      ó|  —  | j                   d	||dœ|¤Ž} | j                  d	||dœ|¤Ž}	|	j                  }
| j                  |
«      }
|j                  }| j	                  |«      }|t
        j                  j                  |ddd¬«      z  }|
t
        j                  j                  |
ddd¬«      z  }| j                  j                  «       j                  |j                  «      }t        j                  ||j                  «       «      |z  }|j                  «       }d}|rt        |«      }|}
t        ||||
||	|¬«      S )
aw  
        return_loss (`bool`, *optional*):
            Whether or not to return the contrastive loss.
        return_base_image_embeds (`bool`, *optional*):
            Whether or not to return the base image embeddings.

        Examples:
        ```python
        >>> from PIL import Image
        >>> import httpx
        >>> from io import BytesIO
        >>> from transformers import AutoProcessor, OwlViTModel

        >>> model = OwlViTModel.from_pretrained("google/owlvit-base-patch32")
        >>> processor = AutoProcessor.from_pretrained("google/owlvit-base-patch32")
        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> with httpx.stream("GET", url) as response:
        ...     image = Image.open(BytesIO(response.read()))
        >>> inputs = processor(text=[["a photo of a cat", "a photo of a dog"]], images=image, return_tensors="pt")
        >>> outputs = model(**inputs)
        >>> logits_per_image = outputs.logits_per_image  # this is the image-text similarity score
        >>> probs = logits_per_image.softmax(dim=1)  # we can take the softmax to get the label probabilities
        ```r†  rw  rc   r—   T)Úordr·   ÚkeepdimN)r5   r6   r7   r8   r9   r:   r;   rT   )rƒ  rp  rg  r6  r8  r'   ÚlinalgÚnormr;  Úexpri  r$   rî   rU   r2   r4   )rE   rÚ   rÈ   ræ   r”  rÇ   r•  ré   r’  r�  r8   r9   Útext_embeds_normr;  r7   r6   r5   s                    r*   rÏ   zOwlViTModel.forward‰  sd  € ðF 6G°T×5FÑ5Fð 6
Ø%Ø%=ñ6
ð ñ6
ˆð 4C°4·?±?ð 4
ØØ)ñ4
ð ñ4
ˆð #×0Ñ0ˆØ×*Ñ*¨;Ó7ˆØ%×3Ñ3ˆØ×-Ñ-¨lÓ;ˆð $¤e§l¡l×&7Ñ&7¸È!ÐQSÐ]aÐ&7Ó&bÑbˆØ&¬¯©×):Ñ):¸;ÈAÐSUÐ_cÐ):Ó)dÑdÐð ×&Ñ&×*Ñ*Ó,×/Ñ/°×0CÑ0CÓDˆäŸ,™,Ð'7¸¿¹Ó9IÓJÈ[ÑXˆØ*×,Ñ,Ó.ÐàˆÙÜ.¨Ó?ˆDà&ˆäØØ-Ø+Ø#Ø%Ø*Ø .ô
ð 	
r,   rW   rÐ   )NNNNFN)rN   rO   rP   r   rS   r›   r   r   r'   r   r   r   rJ   r   r�  rÑ   r“  rá   rR   r4   rÏ   rÒ   rÓ   s   @r*   r5  r5  *  sˆ  ø… àÓð˜|õ ð( Øð /3ñ!à—<‘<ð!ð Ÿ™ tÑ+ð!ð Ð+Ñ,ð	!ð
 
Ð+Ñ	+ò!ó ó ð!ðF Øð */ñà—l‘lðð #'ðð Ð+Ñ,ð	ð
 
Ð+Ñ	+òó ó ðð@ Øð .2Ø15Ø.2Ø#'Ø).Ø04ñK
à×#Ñ# dÑ*ðK
ð ×'Ñ'¨$Ñ.ðK
ð Ÿ™ tÑ+ð	K
ð
 ˜D‘[ðK
ð #'ðK
ð #'¨¡+ðK
ð Ð+Ñ,ðK
ð 
�Ñ	òK
ó ó ôK
r,   r5  c                   ób   ‡ — e Zd Zddedefˆ fd„Zdej                  dej                  fd„Z	ˆ xZ
S )ÚOwlViTBoxPredictionHeadrŽ   Úout_dimc                 ó"  •— t         ‰| �  «        |j                  j                  }t	        j
                  ||«      | _        t	        j
                  ||«      | _        t	        j                  «       | _	        t	        j
                  ||«      | _
        y rW   )rš   r›   r‹  r�   r   rý   Údense0Údense1ÚGELUÚgeluÚdense2)rE   rŽ   rŸ  r°   r­   s       €r*   r›   z OwlViTBoxPredictionHead.__init__Ú  sb   ø€ Ü‰ÑÔà×$Ñ$×0Ñ0ˆÜ—i‘i  uÓ-ˆŒÜ—i‘i  uÓ-ˆŒÜ—G‘G“IˆŒ	Ü—i‘i  wÓ/ˆ�r,   Úimage_featuresr!   c                 ó°   — | j                  |«      }| j                  |«      }| j                  |«      }| j                  |«      }| j                  |«      }|S rW   )r¡  r¤  r¢  r¥  )rE   r¦  Úoutputs      r*   rÏ   zOwlViTBoxPredictionHead.forwardã  sM   € Ø—‘˜^Ó,ˆØ—‘˜6Ó"ˆØ—‘˜VÓ$ˆØ—‘˜6Ó"ˆØ—‘˜VÓ$ˆØˆr,   )é   )rN   rO   rP   r   r_   r›   r'   r   rR   rÏ   rÒ   rÓ   s   @r*   rž  rž  Ù  s3   ø„ ñ0˜|ð 0°cõ 0ð e§l¡lð °u×7HÑ7H÷ r,   rž  c            	       óž   ‡ — e Zd Zdefˆ fd„Zdej                  dej                  dz  dej                  dz  deej                     fd„Z	ˆ xZ
S )	ÚOwlViTClassPredictionHeadrŽ   c                 ó”  •— t         ‰| �  «        |j                  j                  }|j                  j                  | _        t        j                  | j
                  |«      | _        t        j                  | j
                  d«      | _	        t        j                  | j
                  d«      | _
        t        j                  «       | _        y )Nr   )rš   r›   rŠ  r�   r‹  Ú	query_dimr   rý   r¡  Úlogit_shiftr;  ÚELUÚelu)rE   rŽ   rŸ  r­   s      €r*   r›   z"OwlViTClassPredictionHead.__init__í  sƒ   ø€ Ü‰ÑÔà×$Ñ$×0Ñ0ˆØ×-Ñ-×9Ñ9ˆŒä—i‘i §¡°Ó8ˆŒÜŸ9™9 T§^¡^°QÓ7ˆÔÜŸ9™9 T§^¡^°QÓ7ˆÔÜ—6‘6“8ˆ�r,   r9   Úquery_embedsNÚ
query_maskr!   c                 ó0  — | j                  |«      }|€S|j                  }|j                  d d \  }}t        j                  ||| j
                  f«      j                  |«      }||fS |t        j                  j                  |dd¬«      dz   z  }|t        j                  j                  |dd¬«      dz   z  }t        j                  d||«      }| j                  |«      }	| j                  |«      }
| j                  |
«      dz   }
||	z   |
z  }|�†|j                  dkD  rt        j                  |d¬	«      }t        j                  |d
k(  t        j                   |j"                  «      j$                  |«      }|j                  t        j&                  «      }||fS )Nrc   r—   T)r·   r˜  g�íµ ÷Æ°>z...pd,...qd->...pqr   rÝ   r¶   r   )r¡  r$   r¸   r'   Úzerosr­  ri  r™  rš  Úeinsumr®  r;  r°  Úndimrº   ÚwhereÚfinforY   rg   rZ   )rE   r9   r±  r²  Úimage_class_embedsr$   rÌ   r¦   Úpred_logitsr®  r;  s              r*   rÏ   z!OwlViTClassPredictionHead.forwardø  s…  € ð "Ÿ[™[¨Ó6ÐØÐØ'×.Ñ.ˆFØ&8×&>Ñ&>¸rÀÐ&BÑ#ˆJ˜ÜŸ+™+ z°;ÀÇÁÐ&OÓP×SÑSÐTZÓ[ˆKØÐ!3Ð4Ð4ð 0´5·<±<×3DÑ3DÐEWÐ]_ÐimÐ3DÓ3nÐquÑ3uÑvÐØ#¤u§|¡|×'8Ñ'8¸È2ÐW[Ð'8Ó'\Ð_cÑ'cÑdˆô —l‘lÐ#7Ð9KÈ\ÓZˆð ×&Ñ& |Ó4ˆØ×&Ñ& |Ó4ˆØ—h‘h˜{Ó+¨aÑ/ˆØ" [Ñ0°KÑ?ˆàÐ!Ø�‰ Ò"Ü"Ÿ_™_¨Z¸RÔ@�
äŸ+™+ j°A¡o´u·{±{À;×CTÑCTÓ7U×7YÑ7YÐ[fÓgˆKØ%Ÿ.™.¬¯©Ó7ˆKàÐ/Ð0Ð0r,   )rN   rO   rP   r   r›   r'   rR   r   rJ   rÏ   rÒ   rÓ   s   @r*   r«  r«  ì  s_   ø„ ð	˜|õ 	ð!1à×'Ñ'ð!1ð ×'Ñ'¨$Ñ.ð!1ð —L‘L 4Ñ'ð	!1ð
 
ˆu× Ñ Ñ	!÷!1r,   r«  c                   óv  ‡ — e Zd ZU eed<   defˆ fd„Zedededej                  fd„«       Z
dededej                  fd„Z	 ddej                  d	ej                  d
edej                  fd„Z	 	 ddej                  dej                  dz  dej                  dz  deej                     fd„Z	 ddej                  dej                  dej                  d
edee   deej                     fd„Z	 ddej                  d
edee   deej                     fd„Z	 ddej                  dej                  d
edej                  fd„Zee	 	 ddej                  dej                  dz  d
edee   def
d„«       «       Zee	 	 ddej                  dej                  dej                  dz  d
edee   defd„«       «       Zˆ xZS )r=  rŽ   c                 óô  •— t         ‰| �  |«       t        |«      | _        t	        |«      | _        t        |«      | _        t        j                  |j                  j                  |j                  j                  ¬«      | _        t        j                  «       | _        || _        | j                   j                  j"                  | j                   j                  j$                  z  | _        | j                   j                  j"                  | j                   j                  j$                  z  | _        | j+                  d| j-                  | j&                  | j(                  «      d¬«       | j/                  «        y )Nr  r>  Fr˜   )rš   r›   r5  r&  r«  Ú
class_headrž  Úbox_headr   r  r‹  r�   r  Ú
layer_normÚSigmoidÚsigmoidrŽ   r¥   rœ   r@  rA  rª   r?  ra  r¬   s     €r*   r›   z!OwlViTForObjectDetection.__init__  s  ø€ Ü‰Ñ˜Ô ä! &Ó)ˆŒÜ3°FÓ;ˆŒÜ/°Ó7ˆŒäŸ,™, v×';Ñ';×'GÑ'GÈV×MaÑMa×MpÑMpÔqˆŒÜ—z‘z“|ˆŒØˆŒØ"&§+¡+×";Ñ";×"FÑ"FÈ$Ï+É+×JcÑJc×JnÑJnÑ"nˆÔØ!%§¡×!:Ñ!:×!EÑ!EÈÏÉ×IbÑIb×ImÑImÑ!mˆÔØ×ÑØ˜×-Ñ-¨d×.EÑ.EÀt×G]ÑG]Ó^Ðkpð 	ô 	
ð 	�‰Õr,   r@  rA  r!   c                 ój  — t        j                  d|dz   t         j                  ¬«      }t        j                  d| dz   t         j                  ¬«      }t        j                  ||d¬«      \  }}t        j                  ||fd¬«      }|dxx   |z  cc<   |dxx   | z  cc<   |j                  dd	«      }|S )
Nr   )rY   Úxy)Úindexingr—   r¶   ©.r   ©.r   rc   )r'   r(   rZ   ÚmeshgridÚstackrÀ   )r@  rA  Úx_coordinatesÚy_coordinatesÚxxÚyyÚbox_coordinatess          r*   Ú!normalize_grid_corner_coordinatesz:OwlViTForObjectDetection.normalize_grid_corner_coordinates1  s¤   € ô Ÿ™ QÐ(9¸AÑ(=ÄUÇ]Á]ÔSˆÜŸ™ QÐ(:¸QÑ(>ÄeÇmÁmÔTˆÜ—‘ ¨}ÀtÔL‰ˆˆBô  Ÿ+™+ r¨2 h°BÔ7ˆØ˜ÓÐ#4Ñ4ÓØ˜ÓÐ#5Ñ5Óð *×.Ñ.¨r°1Ó5ˆàÐr,   c                 ó²  — | j                  ||«      }t        j                  |dd«      }t        j                  |dz   «      t        j                  | dz   «      z
  }t        j
                  |d«      }|dxx   |z  cc<   |dxx   |z  cc<   t        j                  |dz   «      t        j                  | dz   «      z
  }t        j                  ||gd¬«      }|S )Nr  g      ð?g-Cëâ6?rÅ  rÆ  r—   r¶   )rÎ  r'   ÚclipÚlogÚlog1pÚ	full_likerÁ   )rE   r@  rA  rÍ  Úbox_coord_biasÚbox_sizeÚbox_size_biasr>  s           r*   r?  z)OwlViTForObjectDetection.compute_box_biasB  sË   € à×@Ñ@ÐASÐUfÓgˆÜŸ*™* _°c¸3Ó?ˆô Ÿ™ ?°TÑ#9Ó:¼U¿[¹[È/ÐIYÐ\`ÑI`Ó=aÑaˆô —?‘? >°3Ó7ˆØ�ÓÐ-Ñ-ÓØ�ÓÐ.Ñ.ÓÜŸ	™	 (¨T¡/Ó2´U·[±[À(ÀÈTÑAQÓ5RÑRˆô —9‘9˜n¨mÐ<À"ÔEˆØˆr,   Úimage_featsÚfeature_maprÇ   c                 óî   — | j                  |«      }|r$|j                  \  }}}}| j                  ||«      }n| j                  }|j	                  |j
                  «      }||z  }| j                  |«      }|S )a  
        Args:
            image_feats:
                Features extracted from the image, returned by the `image_text_embedder` method.
            feature_map:
                A spatial re-arrangement of image_features, also returned by the `image_text_embedder` method.
            interpolate_pos_encoding:
                Whether to interpolate the pre-trained position encodings.
        Returns:
            pred_boxes:
                List of predicted boxes (cxcywh normalized to 0, 1) nested within a dictionary.
        )r¾  r¸   r?  r>  ri  r$   rÁ  )	rE   r×  rØ  rÇ   r€   rÍ   r@  rA  r>  s	            r*   Úbox_predictorz&OwlViTForObjectDetection.box_predictorT  s|   € ð& —]‘] ;Ó/ˆ
ñ $Ø:E×:KÑ:KÑ7ˆAÐ!Ð#4°aØ×,Ñ,Ð-?ÐARÓS‰Hà—}‘}ˆHà—;‘;˜{×1Ñ1Ó2ˆØ�hÑˆ
Ø—\‘\ *Ó-ˆ
ØÐr,   Nr±  r²  c                 ó6   — | j                  |||«      \  }}||fS )a8  
        Args:
            image_feats:
                Features extracted from the `image_text_embedder`.
            query_embeds:
                Text query embeddings.
            query_mask:
                Must be provided with query_embeddings. A mask indicating which query embeddings are valid.
        )r½  )rE   r×  r±  r²  rº  r¹  s         r*   Úclass_predictorz(OwlViTForObjectDetection.class_predictoru  s)   € ð -1¯O©O¸KÈÐWaÓ,bÑ)ˆÐ(àÐ/Ð0Ð0r,   rÚ   rÈ   ræ   ré   c                 ó   —  | j                   d||||dœ|¤Ž}|rX|j                  \  }}}}	|| j                  j                  j                  z  }
|	| j                  j                  j                  z  }n| j
                  }
| j                  }|j                  d   }| j                   j                  j                  |«      }t        j                  |d d …d d…d d …f   |d d …d d…f   j                  «      }|d d …dd …d d …f   |z  }| j                  |«      }|j                  d   |
||j                  d   f}|j                  |«      }|d   }|||fS )N)rÈ   rÚ   ræ   rÇ   r   r   r—   éüÿÿÿrT   )r&  r¸   rŽ   r‹  rœ   r@  rA  r;   rƒ  r}  r'   Úbroadcast_tor¿  r½   )rE   rÚ   rÈ   ræ   rÇ   ré   ÚoutputsrÍ   r¯   r°   r@  rA  rZ  r9   Úclass_token_outÚnew_sizer8   s                    r*   Úimage_text_embedderz,OwlViTForObjectDetection.image_text_embedderˆ  sy  € ð �$—+‘+ð 
Ø%ØØ)Ø%=ñ	
ð
 ñ
ˆñ $Ø".×"4Ñ"4ÑˆAˆq�&˜%Ø!'¨4¯;©;×+DÑ+D×+OÑ+OÑ!OÐØ %¨¯©×)BÑ)B×)MÑ)MÑ MÑà!%×!8Ñ!8ÐØ $× 6Ñ 6Ðð $×7Ñ7¸Ñ:ÐØ—{‘{×/Ñ/×>Ñ>Ð?PÓQˆô  ×,Ñ,¨\º!¸R¸a¸RÂ¸(Ñ-CÀ\ÒRSÐUXÐVXÐUXÐRXÑEY×E_ÑE_Ó`ˆð $¢A q¡rª1 HÑ-°Ñ?ˆØ—‘ |Ó4ˆð ×Ñ˜qÑ!ØØØ×Ñ˜rÑ"ð	
ˆð $×+Ñ+¨HÓ5ˆØ˜b‘kˆà˜\¨7Ð3Ð3r,   c                 ó�  —  | j                   j                  d||dœ|¤Ž}|rX|j                  \  }}}}|| j                  j                  j
                  z  }|| j                  j                  j
                  z  }	n| j                  }| j                  }	|d   }
| j                   j                  j                  |
«      }t        j                  |d d …d d…d d …f   |d d …d d…f   j                  «      }|d d …dd …d d …f   |z  }| j                  |«      }|j                  d   ||	|j                  d   f}|j                  |«      }||fS )Nr†  r   r   r—   rT   )r&  rƒ  r¸   rŽ   r‹  rœ   r@  rA  r}  r'   rß  r¿  r½   )rE   rÈ   rÇ   ré   r’  rÍ   r¯   r°   r@  rA  rZ  r9   rá  râ  s                 r*   Úimage_embedderz'OwlViTForObjectDetection.image_embedder·  sg  € ð 6N°T·[±[×5MÑ5Mð 6
Ø%Ð@Xñ6
Ø\bñ6
ˆñ $Ø".×"4Ñ"4ÑˆAˆq�&˜%Ø!'¨4¯;©;×+DÑ+D×+OÑ+OÑ!OÐØ %¨¯©×)BÑ)B×)MÑ)MÑ MÑà!%×!8Ñ!8ÐØ $× 6Ñ 6Ðð +¨1Ñ-ÐØ—{‘{×/Ñ/×>Ñ>Ð?PÓQˆô  ×,Ñ,¨\º!¸R¸a¸RÂ¸(Ñ-CÀ\ÒRSÐUXÐVXÐUXÐRXÑEY×E_ÑE_Ó`ˆð $¢A q¡rª1 HÑ-°Ñ?ˆØ—‘ |Ó4ˆð ×Ñ˜qÑ!ØØØ×Ñ˜rÑ"ð	
ˆð $×+Ñ+¨HÓ5ˆà˜nÐ-Ð-r,   Úquery_image_featuresÚquery_feature_mapc                 ój  — | j                  |«      \  }}| j                  |||«      }t        |«      }g }g }	|j                  }
t	        |j
                  d   «      D �]  }t        j                  g d¢g|
¬«      }||   }t        ||«      \  }}t        j                  |d   dk(  «      rt        ||«      }t        j                  |«      dz  }|d   |k\  j                  «       }|j                  «       sŒ˜||   |j                  d«         }t        j                  ||   d¬«      }t        j                   d||«      }|t        j"                  |«         }|j%                  ||   |   «       |	j%                  |«       �Œ" |r+t        j&                  |«      }t        j&                  |	«      }nd	\  }}|||fS )
Nr   )r   r   r   r   r#   r  gš™™™™™é?r   )Úaxiszd,id->irx  )rÜ  rÚ  r   r$   rV  r¸   r'   r�  rt   rv   r{   rh   ÚnonzeroÚnumelÚsqueezer+  rµ  ÚargminÚappendrÈ  )rE   ræ  rç  rÇ   rÍ   r�   r€   Úpred_boxes_as_cornersÚbest_class_embedsÚbest_box_indicesÚpred_boxes_deviceÚiÚeach_query_boxÚeach_query_pred_boxesÚiousÚiou_thresholdÚselected_indsÚselected_embeddingsÚmean_embedsÚmean_simÚbest_box_indr±  Úbox_indicess                          r*   Úembed_image_queryz*OwlViTForObjectDetection.embed_image_queryà  s±  € ð ×.Ñ.Ð/CÓD‰ˆˆ<Ø×'Ñ'Ð(<Ð>OÐQiÓjˆ
Ü 8¸Ó DÐð ÐØÐØ1×8Ñ8ÐäÐ+×1Ñ1°!Ñ4Ó5ó 	6ˆAÜ"Ÿ\™\ª<¨.ÐARÔSˆNØ$9¸!Ñ$<Ð!Ü˜nÐ.CÓD‰GˆD�!ô �y‰y˜˜a™ C™Ô(Ü*¨>Ð;PÓQ�ô "ŸI™I d›O¨cÑ1ˆMà! !™W¨Ñ5×>Ñ>Ó@ˆMØ×"Ñ"Õ$Ø&2°1¡o°m×6KÑ6KÈAÓ6NÑ&OÐ#Ü#Ÿj™j¨°a©¸qÔA�Ü Ÿ<™<¨	°;Ð@SÓT�Ø,¬U¯\©\¸(Ó-CÑD�Ø!×(Ñ(¨°a©¸Ñ)FÔGØ ×'Ñ'¨Ö5ð'	6ñ* Ü Ÿ;™;Ð'8Ó9ˆLÜŸ+™+Ð&6Ó7‰Kà(2Ñ%ˆL˜+à˜[¨*Ð4Ð4r,   Úquery_pixel_valuesc           
      ó¸  — | j                  ||¬«      d   } | j                   d||dœ|¤Ž\  }}|j                  \  }}	}
}t        j                  |||	|
z  |f«      }|j                  \  }}	}
}t        j                  |||	|
z  |f«      }| j	                  |||«      \  }}}| j                  ||¬«      \  }}| j                  |||«      }t        ||||||d|¬«      S )a’  
        query_pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values of query image(s) to be detected. Pass in one query image per target image.

        Examples:
        ```python
        >>> import httpx
        >>> from io import BytesIO
        >>> from PIL import Image
        >>> import torch
        >>> from transformers import AutoProcessor, OwlViTForObjectDetection

        >>> processor = AutoProcessor.from_pretrained("google/owlvit-base-patch16")
        >>> model = OwlViTForObjectDetection.from_pretrained("google/owlvit-base-patch16")
        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> with httpx.stream("GET", url) as response:
        ...     image = Image.open(BytesIO(response.read()))
        >>> query_url = "http://images.cocodataset.org/val2017/000000001675.jpg"
        >>> with httpx.stream("GET", query_url) as response:
        ...     query_image = Image.open(BytesIO(response.read()))
        >>> inputs = processor(images=image, query_images=query_image, return_tensors="pt")
        >>> with torch.no_grad():
        ...     outputs = model.image_guided_detection(**inputs)
        >>> # Target image sizes (height, width) to rescale box predictions [batch_size, 2]
        >>> target_sizes = torch.Tensor([image.size[::-1]])
        >>> # Convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
        >>> results = processor.post_process_image_guided_detection(
        ...     outputs=outputs, threshold=0.6, nms_threshold=0.3, target_sizes=target_sizes
        ... )
        >>> i = 0  # Retrieve predictions for the first image
        >>> boxes, scores = results[i]["boxes"], results[i]["scores"]
        >>> for box, score in zip(boxes, scores):
        ...     box = [round(i, 2) for i in box.tolist()]
        ...     print(f"Detected similar object with confidence {round(score.item(), 3)} at location {box}")
        Detected similar object with confidence 0.856 at location [10.94, 50.4, 315.8, 471.39]
        Detected similar object with confidence 1.0 at location [334.84, 25.33, 636.16, 374.71]
        ```r†  r   )r×  r±  N)r9   r‡   rˆ   r‰   r    r�   r:   r;   rT   )rå  r¸   r'   r½   rþ  rÜ  rÚ  r†   )rE   rÈ   rÿ  rÇ   ré   rç  rØ  r’  rÌ   r@  rA  Ú
hidden_dimr×  Úquery_image_featsr±  rñ  r‰   rº  r�   rˆ   s                       r*   Úimage_guided_detectionz/OwlViTForObjectDetection.image_guided_detection  sH  € ð^ !×/Ñ/Ø+ÐF^ð 0ó 
à
ñÐð ': d×&9Ñ&9ð '
Ø%Ø%=ñ'
ð ñ'
Ñ#ˆ�^ð IT×HYÑHYÑEˆ
Ð&Ð(9¸:Ü—m‘m K°*Ð>PÐSdÑ>dÐfpÐ1qÓrˆàHY×H_ÑH_ÑEˆ
Ð&Ð(9¸:Ü!ŸM™MØ 
Ð,>ÐARÑ,RÐT^Ð_ó
Ðð <@×;QÑ;QØÐ0Ð2Jó<
Ñ8ˆÐ&Ð(8ð
 '+×&:Ñ&:À{ÐamÐ&:Ó&nÑ#ˆ�lð !×.Ñ.¨{¸KÐIaÓbÐä5Ø$Ø0Ø/Ø-ØØ%Ø"Ø .ô	
ð 		
r,   c           	      óì  —  | j                   d||||dœ|¤Ž\  }}}|j                  }	|j                  }
|j                  \  }}}}t	        j
                  ||||z  |f«      }|j                  d   |z  }|j                  |||j                  d   «      }|j                  |||j                  d   «      }|d   dkD  }| j                  |||«      \  }}| j                  |||«      }t        ||||||	|
¬«      S )a	  
        input_ids (`torch.LongTensor` of shape `(batch_size * num_max_text_queries, sequence_length)`, *optional*):
            Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See
            [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input
            IDs?](../glossary#input-ids).

        Examples:
        ```python
        >>> import httpx
        >>> from io import BytesIO
        >>> from PIL import Image
        >>> import torch

        >>> from transformers import OwlViTProcessor, OwlViTForObjectDetection

        >>> processor = OwlViTProcessor.from_pretrained("google/owlvit-base-patch32")
        >>> model = OwlViTForObjectDetection.from_pretrained("google/owlvit-base-patch32")

        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> with httpx.stream("GET", url) as response:
        ...     image = Image.open(BytesIO(response.read()))
        >>> text_labels = [["a photo of a cat", "a photo of a dog"]]
        >>> inputs = processor(text=text_labels, images=image, return_tensors="pt")
        >>> outputs = model(**inputs)

        >>> # Target image sizes (height, width) to rescale box predictions [batch_size, 2]
        >>> target_sizes = torch.tensor([(image.height, image.width)])
        >>> # Convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
        >>> results = processor.post_process_grounded_object_detection(
        ...     outputs=outputs, target_sizes=target_sizes, threshold=0.1, text_labels=text_labels
        ... )
        >>> # Retrieve predictions for the first image for the corresponding text queries
        >>> result = results[0]
        >>> boxes, scores, text_labels = result["boxes"], result["scores"], result["text_labels"]
        >>> for box, score, text_label in zip(boxes, scores, text_labels):
        ...     box = [round(i, 2) for i in box.tolist()]
        ...     print(f"Detected {text_label} with confidence {round(score.item(), 3)} at location {box}")
        Detected a photo of a cat with confidence 0.707 at location [324.97, 20.44, 640.58, 373.29]
        Detected a photo of a cat with confidence 0.717 at location [1.46, 55.26, 315.55, 472.17]
        ```)rÚ   rÈ   ræ   rÇ   r   r—   rÅ  )r9   r8   r€   r    r�   r:   r;   rT   )	rã  r:   r;   r¸   r'   r½   rÜ  rÚ  r~   )rE   rÚ   rÈ   ræ   rÇ   ré   r±  rØ  rà  r�  r’  rÌ   r@  rA  r  r×  Úmax_text_queriesr²  rº  r�   r€   s                        r*   rÏ   z OwlViTForObjectDetection.forwarda  sC  € ðf .F¨T×-EÑ-Eð .
ØØ%Ø)Ø%=ñ	.
ð
 ñ.
Ñ*ˆ�k 7ð ×0Ñ0ˆØ ×4Ñ4ˆàHS×HYÑHYÑEˆ
Ð&Ð(9¸:Ü—m‘m K°*Ð>PÐSdÑ>dÐfpÐ1qÓrˆð %Ÿ?™?¨1Ñ-°Ñ;ÐØ#×+Ñ+¨JÐ8HÈ,×J\ÑJ\Ð]_ÑJ`Óaˆð ×%Ñ% jÐ2BÀIÇOÁOÐTVÑDWÓXˆ	Ø˜vÑ&¨Ñ*ˆ
ð '+×&:Ñ&:¸;ÈÐV`Ó&aÑ#ˆ�lð ×'Ñ'¨°[ÐBZÓ[ˆ
ä*Ø$Ø$Ø!ØØ%Ø*Ø .ô
ð 	
r,   rÐ   rx  rT  )rN   rO   rP   r   rS   r›   Ústaticmethodr_   r'   r   rÎ  r?  rR   rÑ   rÚ  rJ   rÜ  r   r   rã  rå  rþ  r   r   r†   r  r~   rÏ   rÒ   rÓ   s   @r*   r=  r=    sã  ø… ØÓð˜|õ ð$ ð¸cð ÐVYð Ð^c×^jÑ^jò ó ðð °3ð È3ð ÐSX×S_ÑS_ó ð, */ñ	à×&Ñ&ðð ×&Ñ&ðð #'ð	ð
 
×	Ñ	óðH 26Ø*.ñ	1à×&Ñ&ð1ð ×'Ñ'¨$Ñ.ð1ð —L‘L 4Ñ'ð	1ð
 
ˆu× Ñ Ñ	!ó1ð0 */ñ-4à—<‘<ð-4ð ×'Ñ'ð-4ð Ÿ™ð	-4ð
 #'ð-4ð Ð+Ñ,ð-4ð 
ˆu× Ñ Ñ	!ó-4ðd */ñ'.à×'Ñ'ð'.ð #'ð'.ð Ð+Ñ,ð	'.ð
 
ˆu× Ñ Ñ	!ó'.ðZ */ñ	*5à#×/Ñ/ð*5ð !×,Ñ,ð*5ð #'ð	*5ð
 
×	Ñ	ó*5ðX Øð 8<Ø).ñ	Q
à×'Ñ'ðQ
ð "×-Ñ-°Ñ4ðQ
ð #'ð	Q
ð
 Ð+Ñ,ðQ
ð 
0òQ
ó ó ðQ
ðf Øð
 /3Ø).ñV
à—<‘<ðV
ð ×'Ñ'ðV
ð Ÿ™ tÑ+ð	V
ð
 #'ðV
ð Ð+Ñ,ðV
ð 
%òV
ó ó ôV
r,   r=  )r5  r%  rn  r�  r=  )Nr  )LrQ   Úcollections.abcr   Údataclassesr   Útypingr   r'   r   r   Ú r	   r0  Úactivationsr
   Úmasking_utilsr   Úmodeling_layersr   Úmodeling_outputsr   r   Úmodeling_utilsr   r   Úprocessing_utilsr   Úutilsr   r   r   r   r   r   Úutils.genericr   r   Úutils.output_capturingr   Úconfiguration_owlvitr   r   r   Útransformers.image_transformsr   Ú
get_loggerrN   Úloggerr+   r2   r4   r`   rd   rt   r{   r~   r†   rP  r�   rÕ   r\   ró   rõ   r  r  r%  rR  r]  rn  rz  r�  r5  rž  r«  r=  Ú__all__rT   r,   r*   ú<module>r     sé  ðñ å $Ý !Ý ã ß å &Ý !Ý /Ý 9ß Kß FÝ &÷÷ ÷ JÝ 5ß TÑ Tñ ÔÝFð 
ˆ×	Ñ	˜HÓ	%€ð`˜UŸ\™\ð `¨e¯l©ló `ð
-¨E¯L©Lð -¸U¿\¹\ó -ð Ø
ô!
�;ó !
ó ó ð!
ðJGˆvð G˜&ó GðE�Fð E˜vó Eò"ò"'ñ0 ðôð
 ô+
 +ó +
ó óð+
ñ\ ðôð
 ô*
¨[ó *
ó óð*
ôZF˜RŸY™Yô FôR˜2Ÿ9™9ô ðL !Øñ%Ø�I‰Ið%à�<‰<ð%ð 
�‰ð%ð �<‰<ð	%ð
 —L‘L 4Ñ'ð%ð �T‰\ð%ð ð%ð Ð'Ñ(ó%ô86)�b—i‘iô 6)ôt�—	‘	ô ô Ð3ô ðB ô4v˜Oó 4vó ð4vôp
�B—I‘Iô 
ôD<
Ð1ô <
ô~/
Ð+ô /
ôd(
Ð3ô (
ôV.
Ð-ô .
ðb ôk
Ð'ó k
ó ðk
ô\˜bŸi™iô ô&-1 §	¡	ô -1ô`]
Ð4ô ]
ò@ w�r,   