Ë
    ÜÓ^j=  ã                   óö  — 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mZmZ dd	lmZ dd
l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mZmZmZm Z m!Z! ddl"m#Z#  ejH                  e%«      Z& G d„ dejN                  «      Z( G d„ de«      Z) G d„ de«      Z* G d„ de«      Z+ G d„ de«      Z, G d„ de «      Z-e G d„ de!«      «       Z.e G d„ d e«      «       Z/ ed!¬"«       G d#„ d$e.«      «       Z0g d%¢Z1y)&zHPyTorch ViViT model - modular file inheriting transformer core from ViT.é    )ÚIterableN)Únné   )Úinitialization)Úcreate_bidirectional_mask)ÚBaseModelOutputÚBaseModelOutputWithPoolingÚImageClassifierOutput)ÚUnpack)ÚTransformersKwargsÚauto_docstringÚlogging)Úcan_return_tupleÚmerge_with_config_defaults)Úcapture_outputsé   )ÚPreTrainedModelÚViTAttentionÚViTEmbeddingsÚViTLayerÚViTMLPÚViTModelÚ	ViTPoolerÚViTPreTrainedModelé   )ÚVivitConfigc                   ó`   ‡ — e Zd ZdZdefˆ fd„Zdej                  dej                  fd„Zˆ xZ	S )ÚVivitTubeletEmbeddingsay  
    This class turns `pixel_values` of shape `(batch_size, num_frames, num_channels, height, width)` into the initial
    `hidden_states` (tubelet embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
    Transformer encoder.

    The seq_length equals (num_frames // tubelet_size[0]) * (height // tubelet_size[1]) * (width // tubelet_size[2]).
    Úconfigc                 óN  •— t         ‰| �  «        |j                  }|j                  }t	        |t
        «      r|n||f}|j                  |d   z  |d   |d   z  z  |d   |d   z  z  | _        || _        t        j                  |j                  |j                  ||¬«      | _        y )Nr   r   r   )Úkernel_sizeÚstride)ÚsuperÚ__init__Útubelet_sizeÚ
image_sizeÚ
isinstancer   Ú
num_framesÚnum_patchesr   ÚConv3dÚnum_channelsÚhidden_sizeÚ
projection)Úselfr   r%   r&   Ú	__class__s       €úr/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/vivit/modular_vivit.pyr$   zVivitTubeletEmbeddings.__init__5   s¯   ø€ Ü‰ÑÔØ×*Ñ*ˆØ×&Ñ&ˆ
Ü#-¨j¼(Ô#C‘ZÈ*ÐV`ÐIaˆ
ð ×Ñ ,¨q¡/Ñ1Ø˜!‰} ¨Q¡Ñ/ñ1à˜!‰} ¨Q¡Ñ/ñ1ð 	Ôð
 %ˆŒÜŸ)™)Ø×Ñ ×!3Ñ!3ÀÐVbô
ˆ�ó    Úpixel_valuesÚreturnc                 ó†   — |j                  dd«      }| j                  |«      j                  d«      j                  dd«      S )Nr   r   )Ú	transposer-   Úflatten)r.   r2   s     r0   ÚforwardzVivitTubeletEmbeddings.forwardE   s;   € à#×-Ñ-¨a°Ó3ˆØ�‰˜|Ó,×4Ñ4°QÓ7×AÑAÀ!ÀQÓGÐGr1   )
Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r$   ÚtorchÚTensorr7   Ú__classcell__©r/   s   @r0   r   r   ,   s2   ø„ ñð
˜{õ 
ð H E§L¡Lð H°U·\±\÷ Hr1   r   c                   óª   ‡ — e Zd ZdZdefˆ fd„Zdej                  dededej                  fˆ fd„Z	dd	ej                  d
e
dej                  fd„Zˆ xZS )ÚVivitEmbeddingszY
    Construct the CLS token, position and tubelet patch embeddings for video input.
    r   c                 ó„  •— t         ‰| �  «        t        j                  t	        j
                  dd|j                  «      «      | _        t        |«      | _	        | j                  j                  }t        j                  t	        j
                  d|dz   |j                  «      «      | _        |j                  dd  | _        | `y )Nr   )r#   r$   r   Ú	Parameterr<   Úzerosr,   Ú	cls_tokenr   Úpatch_embeddingsr)   Úposition_embeddingsr%   Ú
patch_sizeÚ
mask_token)r.   r   r)   r/   s      €r0   r$   zVivitEmbeddings.__init__P   s‘   ø€ Ü‰ÑÔäŸ™¤e§k¡k°!°Q¸×8JÑ8JÓ&KÓLˆŒÜ 6°vÓ >ˆÔØ×+Ñ+×7Ñ7ˆÜ#%§<¡<´·±¸A¸{ÈQ¹ÐPV×PbÑPbÓ0cÓ#dˆÔ à ×-Ñ-¨a¨bÐ1ˆŒØ‰Or1   Ú
embeddingsÚheightÚwidthr3   c                 óp   •— t         ‰| �  |||«       || j                  d   z  }|| j                  d   z  }y )Nr   r   )r#   Úinterpolate_pos_encodingrH   )r.   rJ   rK   rL   Ú
new_heightÚ	new_widthr/   s         €r0   rN   z(VivitEmbeddings.interpolate_pos_encoding[   s:   ø€ Ü‰Ñ(¨°V¸UÔCà˜tŸ™¨qÑ1Ñ1ˆ
Ø˜TŸ_™_¨QÑ/Ñ/‰	r1   r2   rN   c                 óÖ  — |j                   \  }}}}}| j                  |«      }| j                  j                  |dd«      }	t	        j
                  |	|fd¬«      }|r|| j                  |||«      z   }ne|| j                  d   k7  s|| j                  d   k7  r2t        d|› d|› d| j                  d   › d| j                  d   › d�	«      ‚|| j                  z   }| j                  |«      }|S )	Néÿÿÿÿr   )Údimr   zInput image size (Ú*z) doesn't match model (z).)ÚshaperF   rE   Úexpandr<   ÚcatrN   r&   Ú
ValueErrorrG   Údropout)
r.   r2   rN   Ú
batch_sizer(   r+   rK   rL   rJ   Ú
cls_tokenss
             r0   r7   zVivitEmbeddings.forwarda   s  € Ø>J×>PÑ>PÑ;ˆ
�J ¨f°eØ×*Ñ*¨<Ó8ˆ
ð —^‘^×*Ñ*¨:°r¸2Ó>ˆ
Ü—Y‘Y 
¨JÐ7¸QÔ?ˆ
á#Ø# d×&CÑ&CÀJÐPVÐX]Ó&^Ñ^‰Jà˜Ÿ™¨Ñ+Ò+¨u¸¿¹ÈÑ8JÒ/JÜ Ø(¨¨°°%°ð 9ØŸ™¨Ñ+Ð,¨A¨d¯o©o¸aÑ.@Ð-AÀðEóð ð $ d×&>Ñ&>Ñ>ˆJà—\‘\ *Ó-ˆ
àÐr1   )F)r8   r9   r:   r;   r   r$   r<   r=   ÚintrN   Úboolr7   r>   r?   s   @r0   rA   rA   K   sf   ø„ ñð	˜{õ 	ð0°5·<±<ð 0Èð 0ÐUXð 0Ð]b×]iÑ]iõ 0ñ E§L¡Lð ÈDð Ð]b×]iÑ]i÷ r1   rA   c                   ó   — e Zd Zy)ÚVivitAttentionN©r8   r9   r:   © r1   r0   r_   r_   x   ó   „ Ør1   r_   c                   ó   — e Zd Zy)ÚVivitMLPNr`   ra   r1   r0   rd   rd   |   rb   r1   rd   c                   ó   — e Zd Zy)Ú
VivitLayerNr`   ra   r1   r0   rf   rf   €   rb   r1   rf   c                   ó   — e Zd Zy)ÚVivitPoolerNr`   ra   r1   r0   rh   rh   „   rb   r1   rh   c                   óV   — e Zd ZU eed<   dZdZddgZ ej                  «       d„ «       Z
y)ÚVivitPreTrainedModelr   Úvivit)ÚvideorA   rf   c                 óÎ   — t        j                  | |«       t        |t        «      r?t	        j
                  |j                  «       t	        j
                  |j                  «       yy)zInitialize the weightsN)r   Ú_init_weightsr'   rA   ÚinitÚzeros_rE   rG   )r.   Úmodules     r0   rn   z"VivitPreTrainedModel._init_weights�   sG   € ô 	×%Ñ% d¨FÔ3Ü�fœoÔ.Ü�K‰K˜×(Ñ(Ô)Ü�K‰K˜×2Ñ2Õ3ð /r1   N)r8   r9   r:   r   Ú__annotations__Úbase_model_prefixÚinput_modalitiesÚ_no_split_modulesr<   Úno_gradrn   ra   r1   r0   rj   rj   ˆ   s9   … àÓØÐØ!ÐØ*¨LÐ9Ðà€U‡]�]ƒ_ñ4ó ñ4r1   rj   c                   ó´   ‡ — e Zd Zddedefˆ fd„Ze ed¬«      e	 	 	 dde	j                  dz  ded	e	j                  dz  d
ee   def
d„«       «       «       Zˆ xZS )Ú
VivitModelr   Úadd_pooling_layerc                 óD   •— t         ‰| �  |«       t        |«      | _        y)zv
        add_pooling_layer (bool, *optional*, defaults to `True`):
            Whether to add a pooling layer
        N)r#   r$   rA   rJ   )r.   r   ry   r/   s      €r0   r$   zVivitModel.__init__š   s   ø€ ô
 	‰Ñ˜Ô Ü)¨&Ó1ˆ�r1   F)Útie_last_hidden_statesNr2   rN   Úattention_maskÚkwargsr3   c                 ó  — | j                  ||¬«      }t        | j                  ||¬«      }|}| j                  D ]  } |||fi |¤Ž}Œ | j	                  |«      }| j
                  �| j                  |«      nd}	t        ||	¬«      S )a  
        Examples:

        ```python
        >>> import av
        >>> import numpy as np

        >>> from transformers import VivitImageProcessor, VivitModel
        >>> from huggingface_hub import hf_hub_download

        >>> np.random.seed(0)


        >>> def read_video_pyav(container, indices):
        ...     '''
        ...     Decode the video with PyAV decoder.
        ...     Args:
        ...         container (`av.container.input.InputContainer`): PyAV container.
        ...         indices (`list[int]`): List of frame indices to decode.
        ...     Returns:
        ...         result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
        ...     '''
        ...     frames = []
        ...     container.seek(0)
        ...     start_index = indices[0]
        ...     end_index = indices[-1]
        ...     for i, frame in enumerate(container.decode(video=0)):
        ...         if i > end_index:
        ...             break
        ...         if i >= start_index and i in indices:
        ...             frames.append(frame)
        ...     return np.stack([x.to_ndarray(format="rgb24") for x in frames])


        >>> def sample_frame_indices(clip_len, frame_sample_rate, seg_len):
        ...     '''
        ...     Sample a given number of frame indices from the video.
        ...     Args:
        ...         clip_len (`int`): Total number of frames to sample.
        ...         frame_sample_rate (`int`): Sample every n-th frame.
        ...         seg_len (`int`): Maximum allowed index of sample's last frame.
        ...     Returns:
        ...         indices (`list[int]`): List of sampled frame indices
        ...     '''
        ...     converted_len = int(clip_len * frame_sample_rate)
        ...     end_idx = np.random.randint(converted_len, seg_len)
        ...     start_idx = end_idx - converted_len
        ...     indices = np.linspace(start_idx, end_idx, num=clip_len)
        ...     indices = np.clip(indices, start_idx, end_idx - 1).astype(np.int64)
        ...     return indices


        >>> # video clip consists of 300 frames (10 seconds at 30 FPS)
        >>> file_path = hf_hub_download(
        ...     repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
        ... )
        >>> container = av.open(file_path)

        >>> # sample 32 frames
        >>> indices = sample_frame_indices(clip_len=32, frame_sample_rate=1, seg_len=container.streams.video[0].frames)
        >>> video = read_video_pyav(container=container, indices=indices)

        >>> image_processor = VivitImageProcessor.from_pretrained("google/vivit-b-16x2-kinetics400")
        >>> model = VivitModel.from_pretrained("google/vivit-b-16x2-kinetics400")

        >>> # prepare video for the model
        >>> inputs = image_processor(list(video), return_tensors="pt")

        >>> # forward pass
        >>> outputs = model(**inputs)
        >>> last_hidden_states = outputs.last_hidden_state
        >>> list(last_hidden_states.shape)
        [1, 3137, 768]
        ```)rN   )r   Úinputs_embedsr|   N)Úlast_hidden_stateÚpooler_output)rJ   r   r   ÚlayersÚ	layernormÚpoolerr	   )
r.   r2   rN   r|   r}   Úembedding_outputÚhidden_statesÚlayerÚsequence_outputÚpooled_outputs
             r0   r7   zVivitModel.forward¢   s“   € ðj  Ÿ?™?¨<ÐRj˜?ÓkÐÜ2Ø—;‘;Ø*Ø)ô
ˆð
 )ˆØ—[‘[ò 	KˆEÙ! -°ÑJÀ6ÑJ‰Mð	KàŸ.™.¨Ó7ˆØ8<¿¹Ð8O˜Ÿ™ OÔ4ÐUYˆä)¸OÐ[hÔiÐir1   )T)NFN)r8   r9   r:   r   r]   r$   r   r   r   r<   ÚFloatTensorr=   r   r   r	   r7   r>   r?   s   @r0   rx   rx   ˜   s¢   ø„ ñ2˜{ð 2¸tõ 2ð  Ù¨EÔ2Øð 26Ø).Ø.2ñ	^jà×'Ñ'¨$Ñ.ð^jð #'ð^jð Ÿ™ tÑ+ð	^jð
 Ð+Ñ,ð^jð 
$ò^jó ó 3ó  ô^jr1   rx   aý  
        ViViT Transformer model with a video classification head on top (a linear layer on top of the final hidden state of the
    [CLS] token) e.g. for Kinetics-400.

        <Tip>

            Note that it's possible to fine-tune ViT on higher resolution images than the ones it has been trained on, by
            setting `interpolate_pos_encoding` to `True` in the forward of the model. This will interpolate the pre-trained
            position embeddings to the higher resolution.

        </Tip>
    )Úcustom_introc                   ó–   ‡ — e Zd Zdefˆ fd„Zee	 	 	 d
dej                  dz  dej                  dz  de
dee   def
d	„«       «       Zˆ xZS )ÚVivitForVideoClassificationr   c                 ó.  •— t         ‰| �  |«       |j                  | _        t        |d¬«      | _        |j                  dkD  r*t        j                  |j                  |j                  «      nt        j                  «       | _	        | j                  «        y )NF)ry   r   )r#   r$   Ú
num_labelsrx   rk   r   ÚLinearr,   ÚIdentityÚ
classifierÚ	post_init)r.   r   r/   s     €r0   r$   z$VivitForVideoClassification.__init__  ss   ø€ Ü‰Ñ˜Ô à ×+Ñ+ˆŒÜ ¸%Ô@ˆŒ
ð OU×N_ÑN_ÐbcÒNcœ"Ÿ)™) F×$6Ñ$6¸×8IÑ8IÔJÔik×itÑitÓivˆŒð 	�‰Õr1   Nr2   ÚlabelsrN   r}   r3   c                 ó  —  | j                   |fd|i|¤Ž}|j                  }| j                  |dd…ddd…f   «      }d}|� | j                  ||| j                  fi |¤Ž}t        |||j                  |j                  ¬«      S )a  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).

        Examples:

        ```python
        >>> import av
        >>> import numpy as np
        >>> import torch

        >>> from transformers import VivitImageProcessor, VivitForVideoClassification
        >>> from huggingface_hub import hf_hub_download

        >>> np.random.seed(0)


        >>> def read_video_pyav(container, indices):
        ...     '''
        ...     Decode the video with PyAV decoder.
        ...     Args:
        ...         container (`av.container.input.InputContainer`): PyAV container.
        ...         indices (`list[int]`): List of frame indices to decode.
        ...     Returns:
        ...         result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
        ...     '''
        ...     frames = []
        ...     container.seek(0)
        ...     start_index = indices[0]
        ...     end_index = indices[-1]
        ...     for i, frame in enumerate(container.decode(video=0)):
        ...         if i > end_index:
        ...             break
        ...         if i >= start_index and i in indices:
        ...             frames.append(frame)
        ...     return np.stack([x.to_ndarray(format="rgb24") for x in frames])


        >>> def sample_frame_indices(clip_len, frame_sample_rate, seg_len):
        ...     '''
        ...     Sample a given number of frame indices from the video.
        ...     Args:
        ...         clip_len (`int`): Total number of frames to sample.
        ...         frame_sample_rate (`int`): Sample every n-th frame.
        ...         seg_len (`int`): Maximum allowed index of sample's last frame.
        ...     Returns:
        ...         indices (`list[int]`): List of sampled frame indices
        ...     '''
        ...     converted_len = int(clip_len * frame_sample_rate)
        ...     end_idx = np.random.randint(converted_len, seg_len)
        ...     start_idx = end_idx - converted_len
        ...     indices = np.linspace(start_idx, end_idx, num=clip_len)
        ...     indices = np.clip(indices, start_idx, end_idx - 1).astype(np.int64)
        ...     return indices


        >>> # video clip consists of 300 frames (10 seconds at 30 FPS)
        >>> file_path = hf_hub_download(
        ...     repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
        ... )
        >>> container = av.open(file_path)

        >>> # sample 32 frames
        >>> indices = sample_frame_indices(clip_len=32, frame_sample_rate=4, seg_len=container.streams.video[0].frames)
        >>> video = read_video_pyav(container=container, indices=indices)

        >>> image_processor = VivitImageProcessor.from_pretrained("google/vivit-b-16x2-kinetics400")
        >>> model = VivitForVideoClassification.from_pretrained("google/vivit-b-16x2-kinetics400")

        >>> inputs = image_processor(list(video), return_tensors="pt")

        >>> with torch.no_grad():
        ...     outputs = model(**inputs)
        ...     logits = outputs.logits

        >>> # model predicts one of the 400 Kinetics-400 classes
        >>> predicted_label = logits.argmax(-1).item()
        >>> print(model.config.id2label[predicted_label])
        LABEL_116
        ```rN   Nr   )ÚlossÚlogitsr†   Ú
attentions)rk   r€   r’   Úloss_functionr   r
   r†   r˜   )	r.   r2   r”   rN   r}   Úoutputsrˆ   r—   r–   s	            r0   r7   z#VivitForVideoClassification.forward!  s�   € ðx $. 4§:¡:Øñ$
Ø3Kð$
ØOUñ$
ˆð "×3Ñ3ˆØ—‘ ²°A²q°Ñ!9Ó:ˆàˆØÐØ%�4×%Ñ% f¨f°d·k±kÑLÀVÑLˆDä$ØØØ!×/Ñ/Ø×)Ñ)ô	
ð 	
r1   )NNF)r8   r9   r:   r   r$   r   r   r<   rŠ   Ú
LongTensorr]   r   r   r
   r7   r>   r?   s   @r0   r�   r�     s‰   ø„ ð
˜{õ 
ð Øð 26Ø*.Ø).ñ	i
à×'Ñ'¨$Ñ.ði
ð × Ñ  4Ñ'ði
ð #'ð	i
ð
 Ð+Ñ,ði
ð 
òi
ó ó ôi
r1   r�   )rx   rj   r�   )2r;   Úcollections.abcr   r<   r   Ú r   ro   Úmasking_utilsr   Úmodeling_outputsr   r	   r
   Úprocessing_utilsr   Úutilsr   r   r   Úutils.genericr   r   Úutils.output_capturingr   Úvit.modeling_vitr   r   r   r   r   r   r   r   Úconfiguration_vivitr   Ú
get_loggerr8   ÚloggerÚModuler   rA   r_   rd   rf   rh   rj   rx   r�   Ú__all__ra   r1   r0   ú<module>rª      s  ðñ Oå $ã Ý å &Ý 6ß bÑ bÝ &ß @Ñ @ß IÝ 5÷	÷ 	ó 	õ -ð 
ˆ×	Ñ	˜HÓ	%€ôH˜RŸY™Yô Hô>*�mô *ôZ	�\ô 	ô	ˆvô 	ô	�ô 	ô	�)ô 	ð ô4Ð-ó 4ó ð4ð ôjj�ó jjó ðjjñZ ðôôx
Ð"6ó x
óðx
òv P�r1   