Ë
    T^(hx9  ã                   ó|  — d Z ddlmZ ddlmZmZmZ ddlZddlZddlm	Z	 ddl
mZ ddlmZmZmZmZmZ dd	lmZ d
dlmZ  ej,                  e«      ZdZe G d„ de«      «       Z G d„ de«      ZdZdZdd„Z G d„ de	j>                  «      Z  G d„ de	j>                  «      Z! ede«       G d„ de«      «       Z"ddgZ#y)zPyTorch VitPose model.é    )Ú	dataclass)ÚOptionalÚTupleÚUnionN)Únné   )ÚPreTrainedModel)ÚModelOutputÚadd_start_docstringsÚ%add_start_docstrings_to_model_forwardÚloggingÚreplace_return_docstrings)Úload_backboneé   )ÚVitPoseConfigr   c                   óÆ   — e Zd ZU dZdZeej                     ed<   dZ	eej                     ed<   dZ
eeej                  df      ed<   dZeeej                  df      ed<   y)ÚVitPoseEstimatorOutputaQ  
    Class for outputs of pose estimation models.

    Args:
        loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
            Loss is not supported at this moment. See https://github.com/ViTAE-Transformer/ViTPose/tree/main/mmpose/models/losses for further detail.
        heatmaps (`torch.FloatTensor` of shape `(batch_size, num_keypoints, height, width)`):
            Heatmaps as predicted by the model.
        hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
            one for the output of each stage) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states
            (also called feature maps) of the model at the output of each stage.
        attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, patch_size,
            sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.
    NÚlossÚheatmaps.Úhidden_statesÚ
attentions)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   ÚtorchÚFloatTensorÚ__annotations__r   r   r   r   © ó    új/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/models/vitpose/modeling_vitpose.pyr   r   *   sq   … ñð( )-€Dˆ(�5×$Ñ$Ñ
%Ó,Ø,0€Hˆh�u×(Ñ(Ñ)Ó0Ø=A€M�8˜E %×"3Ñ"3°SÐ"8Ñ9Ñ:ÓAØ:>€J�˜˜u×0Ñ0°#Ð5Ñ6Ñ7Ô>r    r   c                   óx   — e Zd ZdZeZdZdZdZde	e
j                  e
j                  e
j                  f   ddfd„Zy)	ÚVitPosePreTrainedModelz†
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    ÚvitÚpixel_valuesTÚmoduleÚreturnNc                 ó¶  — t        |t        j                  t        j                  f«      rËt        j                  j                  |j                  j                  j                  t        j                  «      d| j                  j                  ¬«      j                  |j                  j                  «      |j                  _        |j                  �%|j                  j                  j                  «        yyt        |t        j                   «      rJ|j                  j                  j                  «        |j                  j                  j#                  d«       yy)zInitialize the weightsg        )ÚmeanÚstdNg      ð?)Ú
isinstancer   ÚLinearÚConv2dÚinitÚtrunc_normal_ÚweightÚdataÚtor   Úfloat32ÚconfigÚinitializer_rangeÚdtypeÚbiasÚzero_Ú	LayerNormÚfill_)Úselfr&   s     r!   Ú_init_weightsz$VitPosePreTrainedModel._init_weightsQ   sä   € ä�fœrŸy™y¬"¯)©)Ð4Ô5ô "$§¡×!6Ñ!6Ø—‘×"Ñ"×%Ñ%¤e§m¡mÓ4¸3ÀDÇKÁK×DaÑDað "7ó "ç‰b�—‘×$Ñ$Ó%ð �M‰MÔð �{‰{Ð&Ø—‘× Ñ ×&Ñ&Õ(ð 'ä˜¤§¡Ô-Ø�K‰K×Ñ×"Ñ"Ô$Ø�M‰M×Ñ×$Ñ$ SÕ)ð .r    )r   r   r   r   r   Úconfig_classÚbase_model_prefixÚmain_input_nameÚsupports_gradient_checkpointingr   r   r,   r-   r9   r<   r   r    r!   r#   r#   F   sK   „ ñð
 !€LØÐØ$€OØ&*Ð#ð* E¨"¯)©)°R·Y±YÀÇÁÐ*LÑ$Mð *ÐRVô *r    r#   aI  
    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
    as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
    behavior.

    Parameters:
        config ([`VitPoseConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
a4  
    Args:
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`VitPoseImageProcessor`]. See
            [`VitPoseImageProcessor.__call__`] for details.

        dataset_index (`torch.Tensor` of shape `(batch_size,)`):
            Index to use in the Mixture-of-Experts (MoE) blocks of the backbone.

            This corresponds to the dataset index used during training, e.g. For the single dataset index 0 refers to the corresponding dataset. For the multiple datasets index 0 refers to dataset A (e.g. MPII) and index 1 refers to dataset B (e.g. CrowdPose).

        flip_pairs (`torch.tensor`, *optional*):
            Whether to mirror pairs of keypoints (for example, left ear -- right ear).

        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
c                 óÌ  — |dvrt        d«      ‚| j                  dk7  rt        d«      ‚| j                  \  }}}}d}|dk(  rd}| dd…ddd…d	f    | dd…ddd…d	f<   | j                  |d
|||«      } | j	                  «       }|j                  «       D ])  \  }	}
| dd…|
d	f   |dd…|	d	f<   | dd…|	d	f   |dd…|
d	f<   Œ+ |j                  ||||f«      }|j                  d
«      }|S )aÃ  Flip the flipped heatmaps back to the original form.

    Args:
        output_flipped (`torch.tensor` of shape `(batch_size, num_keypoints, height, width)`):
            The output heatmaps obtained from the flipped images.
        flip_pairs (`torch.Tensor` of shape `(num_keypoints, 2)`):
            Pairs of keypoints which are mirrored (for example, left ear -- right ear).
        target_type (`str`, *optional*, defaults to `"gaussian-heatmap"`):
            Target type to use. Can be gaussian-heatmap or combined-target.
            gaussian-heatmap: Classification target with gaussian distribution.
            combined-target: The combination of classification target (response map) and regression target (offset map).
            Paper ref: Huang et al. The Devil is in the Details: Delving into Unbiased Data Processing for Human Pose Estimation (CVPR 2020).

    Returns:
        torch.Tensor: heatmaps that flipped back to the original image
    )úgaussian-heatmapúcombined-targetz9target_type should be gaussian-heatmap or combined-targeté   zCoutput_flipped should be [batch_size, num_keypoints, height, width]r   rC   r   N.éÿÿÿÿ)Ú
ValueErrorÚndimÚshapeÚreshapeÚcloneÚtolistÚflip)Úoutput_flippedÚ
flip_pairsÚtarget_typeÚ
batch_sizeÚnum_keypointsÚheightÚwidthÚchannelsÚoutput_flipped_backÚleftÚrights              r!   Ú	flip_backrX   „   s8  € ð" ÐAÑAÜÐTÓUÐUà×Ñ˜aÒÜÐ^Ó_Ð_Ø/=×/CÑ/CÑ,€J�˜v uØ€HØÐ'Ò'ØˆØ(6²q¸!¸$¸Q¸$À°|Ñ(DÐ'Dˆ’q˜!˜$˜Q˜$ �|Ñ$Ø#×+Ñ+¨J¸¸HÀfÈeÓT€NØ(×.Ñ.Ó0Ðð "×(Ñ(Ó*ò J‰ˆˆeØ,:º1¸eÀS¸=Ñ,IÐšA˜t S˜LÑ)Ø-;ºA¸tÀS¸LÑ-IÐšA˜u c˜MÒ*ðJð .×5Ñ5°zÀ=ÐRXÐZ_Ð6`ÓaÐà-×2Ñ2°2Ó6ÐØÐr    c                   ó|   ‡ — e Zd ZdZdˆ fd„Zddej                  deej                     dej                  fd„Zˆ xZ	S )	ÚVitPoseSimpleDecoderz�
    Simple decoding head consisting of a ReLU activation, 4x upsampling and a 3x3 convolution, turning the
    feature maps into heatmaps.
    r'   c                 ó  •— t         ‰| �  «        t        j                  «       | _        t        j
                  |j                  dd¬«      | _        t        j                  |j                  j                  |j                  ddd¬«      | _        y )NÚbilinearF)Úscale_factorÚmodeÚalign_cornersr   r   ©Úkernel_sizeÚstrideÚpadding)ÚsuperÚ__init__r   ÚReLUÚ
activationÚUpsampler]   Ú
upsamplingr-   Úbackbone_configÚhidden_sizeÚ
num_labelsÚconv©r;   r4   Ú	__class__s     €r!   re   zVitPoseSimpleDecoder.__init__²   se   ø€ Ü‰ÑÔäŸ'™'›)ˆŒÜŸ+™+°6×3FÑ3FÈZÐglÔmˆŒÜ—I‘IØ×"Ñ"×.Ñ.°×0AÑ0AÈqÐYZÐdeô
ˆ�	r    Úhidden_staterN   c                 óˆ   — | j                  |«      }| j                  |«      }| j                  |«      }|�t        ||«      }|S ©N)rg   ri   rm   rX   ©r;   rp   rN   r   s       r!   ÚforwardzVitPoseSimpleDecoder.forward»   sC   € à—‘ |Ó4ˆØ—‘ |Ó4ˆØ—9‘9˜\Ó*ˆàÐ!Ü  ¨:Ó6ˆHàˆr    )r'   Nrr   )
r   r   r   r   re   r   ÚTensorr   rt   Ú__classcell__©ro   s   @r!   rZ   rZ   ¬   s;   ø„ ñõ

ñ	 E§L¡Lð 	¸hÀuÇ|Á|Ñ>Tð 	Ð`e×`lÑ`l÷ 	r    rZ   c                   óh   ‡ — e Zd ZdZdefˆ fd„Zddej                  deej                     fd„Z	ˆ xZ
S )ÚVitPoseClassicDecoderzš
    Classic decoding head consisting of a 2 deconvolutional blocks, followed by a 1x1 convolution layer,
    turning the feature maps into heatmaps.
    r4   c                 óè  •— t         ‰| �  «        t        j                  |j                  j
                  ddddd¬«      | _        t        j                  d«      | _        t        j                  «       | _
        t        j                  dddddd¬«      | _        t        j                  d«      | _        t        j                  «       | _        t        j                  d|j                  ddd¬«      | _        y )	Né   rD   é   r   F)ra   rb   rc   r7   r   r`   )rd   re   r   ÚConvTranspose2drj   rk   Údeconv1ÚBatchNorm2dÚ
batchnorm1rf   Úrelu1Údeconv2Ú
batchnorm2Úrelu2r-   rl   rm   rn   s     €r!   re   zVitPoseClassicDecoder.__init__Í   s´   ø€ Ü‰ÑÔä×)Ñ)Ø×"Ñ"×.Ñ.°ÀÈ1ÐVWÐ^cô
ˆŒô Ÿ.™.¨Ó-ˆŒÜ—W‘W“YˆŒ
ä×)Ñ)¨#¨sÀÈ!ÐUVÐ]bÔcˆŒÜŸ.™.¨Ó-ˆŒÜ—W‘W“YˆŒ
ä—I‘I˜c 6×#4Ñ#4À!ÈAÐWXÔYˆ�	r    rp   rN   c                 ó  — | j                  |«      }| j                  |«      }| j                  |«      }| j                  |«      }| j	                  |«      }| j                  |«      }| j                  |«      }|�t        ||«      }|S rr   )r~   r€   r�   r‚   rƒ   r„   rm   rX   rs   s       r!   rt   zVitPoseClassicDecoder.forwardÜ   s{   € Ø—|‘| LÓ1ˆØ—‘ |Ó4ˆØ—z‘z ,Ó/ˆà—|‘| LÓ1ˆØ—‘ |Ó4ˆØ—z‘z ,Ó/ˆà—9‘9˜\Ó*ˆàÐ!Ü  ¨:Ó6ˆHàˆr    rr   )r   r   r   r   r   re   r   ru   r   rt   rv   rw   s   @r!   ry   ry   Ç   s6   ø„ ñð
Z˜}õ Zñ E§L¡Lð ¸hÀuÇ|Á|Ñ>T÷ r    ry   z5The VitPose model with a pose estimation head on top.c                   ó  ‡ — e Zd Zdeddfˆ fd„Z ee«       eee	¬«      	 	 	 	 	 	 dde
j                  dee
j                     dee
j                     d	ee
j                     d
ee   dee   dee   deeef   fd„«       «       Zˆ xZS )ÚVitPoseForPoseEstimationr4   r'   Nc                 ó´  •— t         ‰| �  |«       t        |«      | _        t	        | j                  j
                  d«      st        d«      ‚t	        | j                  j
                  d«      st        d«      ‚t	        | j                  j
                  d«      st        d«      ‚|j                  rt        |«      n
t        |«      | _
        | j                  «        y )Nrk   z0The backbone should have a hidden_size attributeÚ
image_sizez0The backbone should have an image_size attributeÚ
patch_sizez/The backbone should have a patch_size attribute)rd   re   r   ÚbackboneÚhasattrr4   rF   Úuse_simple_decoderrZ   ry   ÚheadÚ	post_initrn   s     €r!   re   z!VitPoseForPoseEstimation.__init__ò   s¨   ø€ Ü‰Ñ˜Ô ä% fÓ-ˆŒô �t—}‘}×+Ñ+¨]Ô;ÜÐOÓPÐPÜ�t—}‘}×+Ñ+¨\Ô:ÜÐOÓPÐPÜ�t—}‘}×+Ñ+¨\Ô:ÜÐNÓOÐOà4:×4MÒ4MÔ(¨Ô0ÔShÐioÓSpˆŒ	ð 	�‰Õr    )Úoutput_typer=   r%   Údataset_indexrN   ÚlabelsÚoutput_attentionsÚoutput_hidden_statesÚreturn_dictc                 ó|  — |�|n| j                   j                  }|�|n| j                   j                  }|�|n| j                   j                  }d}|�t	        d«      ‚| j
                  j                  |||||¬«      }	|r|	j                  d   n|	d   d   }
|
j                  d   }| j                   j                  j                  d   | j                   j                  j                  d   z  }| j                   j                  j                  d   | j                   j                  j                  d   z  }|
j                  ddd«      j                  |d||«      j                  «       }
| j                  |
|¬«      }|s|r
|f|	dd z   }n	|f|	dd z   }|�|f|z   S |S t!        |||	j"                  |	j$                  ¬	«      S )
aT  
        Returns:

        Examples:

        ```python
        >>> from transformers import AutoImageProcessor, VitPoseForPoseEstimation
        >>> import torch
        >>> from PIL import Image
        >>> import requests

        >>> processor = AutoImageProcessor.from_pretrained("usyd-community/vitpose-base-simple")
        >>> model = VitPoseForPoseEstimation.from_pretrained("usyd-community/vitpose-base-simple")

        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> image = Image.open(requests.get(url, stream=True).raw)
        >>> boxes = [[[412.8, 157.61, 53.05, 138.01], [384.43, 172.21, 15.12, 35.74]]]
        >>> inputs = processor(image, boxes=boxes, return_tensors="pt")

        >>> with torch.no_grad():
        ...     outputs = model(**inputs)
        >>> heatmaps = outputs.heatmaps
        ```NzTraining is not yet supported)r‘   r”   r“   r•   rE   r   r   r|   )rN   )r   r   r   r   )r4   Úuse_return_dictr”   r“   ÚNotImplementedErrorr‹   Úforward_with_filtered_kwargsÚfeature_mapsrH   rj   r‰   rŠ   ÚpermuterI   Ú
contiguousrŽ   r   r   r   )r;   r%   r‘   rN   r’   r“   r”   r•   r   ÚoutputsÚsequence_outputrP   Úpatch_heightÚpatch_widthr   Úoutputs                   r!   rt   z VitPoseForPoseEstimation.forward  sØ  € ðH &1Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆà$8Ð$DÑ È$Ï+É+×JjÑJjð 	ð 2CÐ1NÑ-ÐTX×T_ÑT_×TqÑTqÐàˆØÐÜ%Ð&EÓFÐFà—-‘-×<Ñ<ØØ'Ø!5Ø/Ø#ð =ó 
ˆñ 7B˜'×.Ñ.¨rÒ2ÀwÈqÁzÐRTÁ~ˆØ$×*Ñ*¨1Ñ-ˆ
Ø—{‘{×2Ñ2×=Ñ=¸aÑ@ÀDÇKÁK×D_ÑD_×DjÑDjÐklÑDmÑmˆØ—k‘k×1Ñ1×<Ñ<¸QÑ?À4Ç;Á;×C^ÑC^×CiÑCiÐjkÑClÑlˆà×#Ñ# A q¨!Ó,×4Ñ4°ZÀÀ\ÐS^Ó_×jÑjÓlð 	ð —9‘9˜_¸�9ÓDˆáÙ#Ø"˜ w¨q¨r {Ñ2‘à"˜ w¨q¨r {Ñ2�Ø)-Ð)9�T�G˜fÑ$ÐE¸vÐEä%ØØØ!×/Ñ/Ø×)Ñ)ô	
ð 	
r    )NNNNNN)r   r   r   r   re   r   ÚVITPOSE_INPUTS_DOCSTRINGr   r   Ú_CONFIG_FOR_DOCr   ru   r   Úboolr   Útuplert   rv   rw   s   @r!   r‡   r‡   í   så   ø„ ð
˜}ð °õ ñ$ +Ð+CÓDÙÐ+AÐP_Ô`ð 15Ø-1Ø)-Ø,0Ø/3Ø&*ñK
à—l‘lðK
ð   §¡Ñ-ðK
ð ˜UŸ\™\Ñ*ð	K
ð
 ˜Ÿ™Ñ&ðK
ð $ D™>ðK
ð ' t™nðK
ð ˜d‘^ðK
ð 
ˆuÐ,Ð,Ñ	-òK
ó aó EôK
r    r‡   )rB   )$r   Údataclassesr   Útypingr   r   r   r   Útorch.utils.checkpointr   Úmodeling_utilsr	   Úutilsr
   r   r   r   r   Úutils.backbone_utilsr   Úconfiguration_vitposer   Ú
get_loggerr   Úloggerr£   r   r#   ÚVITPOSE_START_DOCSTRINGr¢   rX   ÚModulerZ   ry   r‡   Ú__all__r   r    r!   ú<module>r²      sâ   ðñ å !ß )Ñ )ã Û Ý å -÷õ õ 2Ý 0ð 
ˆ×	Ñ	˜HÓ	%€ð "€ð ô?˜[ó ?ó ð?ô6*˜_ô *ð4	Ð ðÐ ó2%ôP˜2Ÿ9™9ô ô6#˜BŸI™Iô #ñL Ø;Øóô`
Ð5ó `
ó	ð`
ðF $Ð%?Ð
@�r    