Ë
    ÜÓ^j0-  ã                   ó¢  — d Z ddlmZ ddl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 dd
lmZ ddlmZmZmZmZ ddlmZ ddlmZ  ej2                  e«      Z ed¬«      e G d„ de«      «       «       Ze G d„ de«      «       Zdd„Z G d„ dej>                  «      Z  G d„ dej>                  «      Z! ed¬«       G d„ de«      «       Z"ddgZ#y)zPyTorch VitPose model.é    )Ú	dataclassN)Únné   )Úinitialization)Úload_backbone)ÚBackboneOutput)ÚPreTrainedModel)ÚUnpack)ÚModelOutputÚTransformersKwargsÚauto_docstringÚlogging)Úcan_return_tupleé   )ÚVitPoseConfigz6
    Class for outputs of pose estimation models.
    )Úcustom_introc                   óÆ   — 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
ej                  df   dz  ed<   dZe
ej                  df   dz  ed<   y)ÚVitPoseEstimatorOutputaH  
    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.
    NÚlossÚheatmaps.Úhidden_statesÚ
attentions)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   ÚtorchÚFloatTensorÚ__annotations__r   r   Útupler   © ó    úw/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/vitpose/modeling_vitpose.pyr   r   $   sq   … ñ	ð &*€Dˆ%×
Ñ
˜dÑ
"Ó)Ø)-€Hˆe×Ñ $Ñ&Ó-Ø:>€M�5˜×*Ñ*¨CÐ/Ñ0°4Ñ7Ó>Ø7;€J��e×'Ñ'¨Ð,Ñ-°Ñ4Ô;r"   r   c                   ó°   ‡ — e Zd ZU eed<   dZdZdZdZ e	j                  «       dej                  ej                  z  ej                  z  fˆ fd„«       Zˆ xZS )ÚVitPosePreTrainedModelÚconfigÚvitÚpixel_values)ÚimageTÚmodulec                 ó>  •— t         ‰| �  |«       t        |t        j                  t        j
                  f«      rct        j                  |j                  d| j                  j                  ¬«       |j                  � t        j                  |j                  «       yyy)zInitialize the weightsg        )ÚmeanÚstdN)ÚsuperÚ_init_weightsÚ
isinstancer   ÚLinearÚConv2dÚinitÚtrunc_normal_Úweightr&   Úinitializer_rangeÚbiasÚzeros_)Úselfr*   Ú	__class__s     €r#   r/   z$VitPosePreTrainedModel._init_weightsD   sm   ø€ ô 	‰Ñ˜fÔ%Ü�fœrŸy™y¬"¯)©)Ð4Ô5Ü×Ñ˜vŸ}™}°3¸D¿K¹K×<YÑ<YÕZØ�{‰{Ð&Ü—‘˜FŸK™KÕ(ð 'ð 6r"   )r   r   r   r   r   Úbase_model_prefixÚmain_input_nameÚinput_modalitiesÚsupports_gradient_checkpointingr   Úno_gradr   r1   r2   Ú	LayerNormr/   Ú__classcell__©r:   s   @r#   r%   r%   <   sW   ø… àÓØÐØ$€OØ!ÐØ&*Ð#à€U‡]�]ƒ_ð) B§I¡I°·	±	Ñ$9¸B¿L¹LÑ$Hô )ó ô)r"   r%   c                 óä  — |dvrt        d«      ‚| j                  dk7  rt        d«      ‚| j                  \  }}}}d}|dk(  r+d}| j                  «       } | 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   rE   r   N.éÿÿÿÿ)Ú
ValueErrorÚndimÚshapeÚcloneÚreshapeÚunbindÚflip)Úoutput_flippedÚ
flip_pairsÚtarget_typeÚ
batch_sizeÚnum_keypointsÚheightÚwidthÚchannelsÚoutput_flipped_backÚleft_indicesÚright_indicess              r#   Ú	flip_backrZ   N   sA  € ð" Ð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Ðð #-×"3Ñ"3°BÓ"7Ñ€L�-Ø0>ºqÀ-ÐQTÐ?TÑ0UÐš˜<¨Ð,Ñ-Ø1?ÂÀ<ÐQTÐ@TÑ1UÐš˜=¨#Ð-Ñ.Ø-×5Ñ5°zÀ=ÐRXÐZ_Ð6`ÓaÐà-×2Ñ2°2Ó6ÐØÐr"   c                   ó€   ‡ — e Zd ZdZdefˆ fd„Zd	dej                  dej                  dz  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)r.   Ú__init__r   ÚReLUÚ
activationÚUpsampler_   Ú
upsamplingr2   Úbackbone_configÚhidden_sizeÚ
num_labelsÚconv©r9   r&   r:   s     €r#   rf   zVitPoseSimpleDecoder.__init__~   se   ø€ Ü‰ÑÔäŸ'™'›)ˆŒÜŸ+™+°6×3FÑ3FÈZÐglÔmˆŒÜ—I‘IØ×"Ñ"×.Ñ.°×0AÑ0AÈqÐYZÐdeô
ˆ�	r"   NÚhidden_staterP   Úreturnc                 óˆ   — | j                  |«      }| j                  |«      }| j                  |«      }|�t        ||«      }|S ©N)rh   rj   rn   rZ   ©r9   rp   rP   r   s       r#   ÚforwardzVitPoseSimpleDecoder.forward‡   sC   € à—‘ |Ó4ˆØ—‘ |Ó4ˆØ—9‘9˜\Ó*ˆàÐ!Ü  ¨:Ó6ˆHàˆr"   rs   ©
r   r   r   r   r   rf   r   ÚTensorru   rA   rB   s   @r#   r\   r\   x   sB   ø„ ñð

˜}õ 
ñ	 E§L¡Lð 	¸e¿l¹lÈTÑ>Qð 	Ð]b×]iÑ]i÷ 	r"   r\   c                   óh   ‡ — e Zd ZdZdefˆ fd„Zddej                  dej                  dz  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.
    r&   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é   rF   é   r   F)rc   rd   re   r7   r   rb   )r.   rf   r   ÚConvTranspose2drk   rl   Údeconv1ÚBatchNorm2dÚ
batchnorm1rg   Úrelu1Údeconv2Ú
batchnorm2Úrelu2r2   rm   rn   ro   s     €r#   rf   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"   Nrp   rP   c                 ó  — | j                  |«      }| j                  |«      }| j                  |«      }| j                  |«      }| j	                  |«      }| j                  |«      }| j                  |«      }|�t        ||«      }|S rs   )r~   r€   r�   r‚   rƒ   r„   rn   rZ   rt   s       r#   ru   zVitPoseClassicDecoder.forward¨   s{   € Ø—|‘| LÓ1ˆØ—‘ |Ó4ˆØ—z‘z ,Ó/ˆà—|‘| LÓ1ˆØ—‘ |Ó4ˆØ—z‘z ,Ó/ˆà—9‘9˜\Ó*ˆàÐ!Ü  ¨:Ó6ˆHàˆr"   rs   rv   rB   s   @r#   ry   ry   “   s6   ø„ ñð
Z˜}õ Zñ E§L¡Lð ¸e¿l¹lÈTÑ>Q÷ r"   ry   z?
    The VitPose model with a pose estimation head on top.
    c                   óÈ   ‡ — e Zd Zdefˆ fd„Zee	 	 	 ddej                  dej                  dz  dej                  dz  dej                  dz  de	e
   d	efd
„«       «       Zˆ xZS )ÚVitPoseForPoseEstimationr&   c                 ó´  •— 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 )Nrl   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)r.   rf   r   ÚbackboneÚhasattrr&   rH   Úuse_simple_decoderr\   ry   ÚheadÚ	post_initro   s     €r#   rf   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"   Nr(   Údataset_indexrP   ÚlabelsÚkwargsrq   c                 óŒ  — d}|�t        d«      ‚ | j                  j                  |fd|i|¤Ž}|j                  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                  ||¬«      }t        |||j                  |j                  ¬	«      S )
a´  
        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).

        Examples:

        ```python
        >>> from transformers import AutoImageProcessor, VitPoseForPoseEstimation
        >>> import torch
        >>> from PIL import Image
        >>> import httpx
        >>> from io import BytesIO

        >>> 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"
        >>> with httpx.stream("GET", url) as response:
        ...     image = Image.open(BytesIO(response.read()))
        >>> 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 supportedr�   rG   r   r   r|   )rP   )r   r   r   r   )ÚNotImplementedErrorr‹   Úforward_with_filtered_kwargsÚfeature_mapsrJ   r&   rk   r‰   rŠ   ÚpermuterL   Ú
contiguousrŽ   r   r   r   )r9   r(   r�   rP   r‘   r’   r   ÚoutputsÚsequence_outputrR   Úpatch_heightÚpatch_widthr   s                r#   ru   z VitPoseForPoseEstimation.forwardÑ   s>  € ðR ˆØÐÜ%Ð&EÓFÐFà"L $§-¡-×"LÑ"LØñ#
à'ð#
ð ñ#
ˆð "×.Ñ.¨rÑ2ˆØ$×*Ñ*¨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ˆØ)×1Ñ1°!°Q¸Ó:ˆØ)×1Ñ1°*¸bÀ,ÐP[Ó\×gÑgÓiˆà—9‘9˜_¸�9ÓDˆä%ØØØ!×/Ñ/Ø×)Ñ)ô	
ð 	
r"   )NNN)r   r   r   r   rf   r   r   r   rw   r
   r   r   ru   rA   rB   s   @r#   r‡   r‡   ¹   s�   ø„ ð˜}õ ð$ Øð .2Ø*.Ø&*ñ@
à—l‘lð@
ð —|‘| dÑ*ð@
ð —L‘L 4Ñ'ð	@
ð
 —‘˜tÑ#ð@
ð Ð+Ñ,ð@
ð 
 ò@
ó ó ô@
r"   r‡   )rD   )$r   Údataclassesr   r   r   Ú r   r3   Úbackbone_utilsr   Úmodeling_outputsr   Úmodeling_utilsr	   Úprocessing_utilsr
   Úutilsr   r   r   r   Úutils.genericr   Úconfiguration_vitposer   Ú
get_loggerr   Úloggerr   r%   rZ   ÚModuler\   ry   r‡   Ú__all__r!   r"   r#   ú<module>rª      sê   ðñ å !ã Ý å &Ý +Ý .Ý -Ý &ß MÓ MÝ -Ý 0ð 
ˆ×	Ñ	˜HÓ	%€ñ
 ðôð
 ô<˜[ó <ó óð<ð$ ô)˜_ó )ó ð)ó"'ôT˜2Ÿ9™9ô ô6#˜BŸI™Iô #ñL ðôô
U
Ð5ó U
óð
U
ðp $Ð%?Ð
@�r"   