o
    ei3e                     @   s  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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 ddlmZmZ ddlmZ ddlm Z  e!e"Z#G dd dej$Z%G dd dej$Z&		d9dej$dej'dej'dej'dej'dB de(dB de(dee fddZ)G d d! d!ej$Z*G d"d# d#ej$Z+G d$d% d%ej$Z,G d&d' d'ej$Z-G d(d) d)ej$Z.G d*d+ d+eZ/G d,d- d-ej$Z0G d.d/ d/ej$Z1eG d0d1 d1eZ2eG d2d3 d3e2Z3ed4d5G d6d7 d7e2Z4g d8Z5dS ):zPyTorch ViViT model.    )CallableN)nn   )initialization)ACT2FN)GradientCheckpointingLayer)BaseModelOutputBaseModelOutputWithPoolingImageClassifierOutput)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)TransformersKwargsauto_docstringlogging	torch_int)can_return_tuplemerge_with_config_defaults)capture_outputs   )VivitConfigc                       sB   e Zd ZdZdef fddZddejdedejfd	d
Z	  Z
S )VivitTubeletEmbeddingsa  
    Construct Vivit Tubelet embeddings.

    This module turns a batch of videos of shape (batch_size, num_frames, num_channels, height, width) into a tensor of
    shape (batch_size, seq_len, hidden_size) to be consumed by a Transformer encoder.

    The seq_len (the number of patches) equals (number of frames // tubelet_size[0]) * (height // tubelet_size[1]) *
    (width // tubelet_size[2]).
    configc                    s|   t    |j| _|j| _|j| _| j| jd  | j| jd   | j| jd   | _|j| _t	j
|j|j|j|jd| _d S )N   r   r   )kernel_sizestride)super__init__
num_frames
image_sizetubelet_size
patch_sizenum_patcheshidden_size	embed_dimr   Conv3dnum_channels
projectionselfr   	__class__ f/home/ubuntu/transcripts/venv/lib/python3.10/site-packages/transformers/models/vivit/modeling_vivit.pyr   /   s   
zVivitTubeletEmbeddings.__init__Fpixel_valuesinterpolate_pos_encodingreturnc           	   
   C   s   |j \}}}}}|s+|| jks|| jkr+td| d| d| jd  d| jd  d	|ddddd	}| |}|ddd}|S )
NzImage image size (*z) doesn't match model (r   r   z).r   r      )shaper   
ValueErrorpermuter'   flatten	transpose)	r)   r.   r/   
batch_sizer   r&   heightwidthxr,   r,   r-   forward?   s   (
zVivitTubeletEmbeddings.forwardF)__name__
__module____qualname____doc__r   r   torchTensorboolr<   __classcell__r,   r,   r*   r-   r   $   s    
$r   c                       s`   e Zd ZdZdef fddZdejdededejfd	d
Z	ddejde
dejfddZ  ZS )VivitEmbeddingsz
    Vivit Embeddings.

    Creates embeddings from a video using VivitTubeletEmbeddings, adds CLS token and positional embeddings.
    r   c                    st   t    ttdd|j| _t|| _	ttd| j	j
d |j| _t|j| _|jdd  | _|| _d S )Nr   )r   r   r   	ParameterrB   zerosr#   	cls_tokenr   patch_embeddingsr"   position_embeddingsDropouthidden_dropout_probdropoutr    r!   r   r(   r*   r,   r-   r   W   s   


zVivitEmbeddings.__init__
embeddingsr9   r:   r0   c                 C   s   |j d d }| jj d d }tj s||kr||kr| jS | jddddf }| jddddf }|j d }|| jd  }	|| jd  }
t|d }|d|||}|dddd}t	j
j||	|
fdd	d
}|dddddd|}tj||fd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   Nr   g      ?r   r   bicubicF)sizemodealign_cornersdim)r3   rK   rB   jit
is_tracingr!   r   reshaper5   r   
functionalinterpolateviewcat)r)   rO   r9   r:   r"   num_positionsclass_pos_embedpatch_pos_embedrV   
new_height	new_widthsqrt_num_positionsr,   r,   r-   r/   e   s(   

z(VivitEmbeddings.interpolate_pos_encodingFr.   r/   c           
      C   sr   |j \}}}}}| j||d}| j|ddg}	tj|	|fdd}|r-|| ||| }n|| j }| |}|S )Nr/   r   rU   )	r3   rJ   rI   tilerB   r]   r/   rK   rN   )
r)   r.   r/   r8   r   r&   r9   r:   rO   
cls_tokensr,   r,   r-   r<      s   

zVivitEmbeddings.forwardr=   )r>   r?   r@   rA   r   r   rB   rC   intr/   rD   r<   rE   r,   r,   r*   r-   rF   P   s
    $(rF           modulequerykeyvalueattention_maskscalingrN   kwargsc           
      K   s   |d u r| dd }t||dd| }|d ur|| }tjj|dd}tjj||| jd}t||}	|	dd	 }	|	|fS )NrP         r   r   rU   )ptrainingr   )
rR   rB   matmulr7   r   rZ   softmaxrN   rr   
contiguous)
ri   rj   rk   rl   rm   rn   rN   ro   attn_weightsattn_outputr,   r,   r-   eager_attention_forward   s   
rx   c                       sB   e Zd Zdef fddZdejdeejejf fddZ  Z	S )VivitSelfAttentionr   c                    s   t    |j|j dkrt|dstd|j d|j d|| _|j| _t|j|j | _| j| j | _	|j
| _| jd | _d| _tj|j| j	|jd| _tj|j| j	|jd| _tj|j| j	|jd| _d S )	Nr   embedding_sizezThe hidden size z4 is not a multiple of the number of attention heads .rp   F)bias)r   r   r#   num_attention_headshasattrr4   r   rg   attention_head_sizeall_head_sizeattention_probs_dropout_probdropout_probrn   	is_causalr   Linearqkv_biasrj   rk   rl   r(   r*   r,   r-   r      s"   

zVivitSelfAttention.__init__hidden_statesr0   c              
   C   s   |j d }|d| j| jf}| |j| dd}| |j| dd}| |j| dd}t	| j
jt}|| |||d | j| j| jsHdn| jd\}}	| d d | jf }
||
}||	fS )Nr   rP   r   r   rh   )r   rn   rN   )r3   r}   r   rk   r\   r7   rl   rj   r   get_interfacer   _attn_implementationrx   r   rn   rr   r   rR   r   rY   )r)   r   r8   	new_shape	key_layervalue_layerquery_layerattention_interfacecontext_layerattention_probsnew_context_layer_shaper,   r,   r-   r<      s*   


zVivitSelfAttention.forward)
r>   r?   r@   r   r   rB   rC   tupler<   rE   r,   r,   r*   r-   ry      s    (ry   c                       sB   e Zd ZdZdef fddZdejdejdejfdd	Z  Z	S )
VivitSelfOutputz
    The residual connection is defined in VivitLayer instead of here (as is the case with other models), due to the
    layernorm applied before each block.
    r   c                    s.   t    t|j|j| _t|j| _d S N)	r   r   r   r   r#   denserL   rM   rN   r(   r*   r,   r-   r         
zVivitSelfOutput.__init__r   input_tensorr0   c                 C   s   |  |}| |}|S r   r   rN   r)   r   r   r,   r,   r-   r<      s   

zVivitSelfOutput.forward
r>   r?   r@   rA   r   r   rB   rC   r<   rE   r,   r,   r*   r-   r      s    $r   c                       8   e Zd Zdef fddZdejdejfddZ  ZS )VivitAttentionr   c                    s"   t    t|| _t|| _d S r   )r   r   ry   	attentionr   outputr(   r*   r,   r-   r     s   

zVivitAttention.__init__r   r0   c                 C   s   |  |\}}| ||}|S r   )r   r   )r)   r   self_attn_output_r   r,   r,   r-   r<     s   zVivitAttention.forward	r>   r?   r@   r   r   rB   rC   r<   rE   r,   r,   r*   r-   r         r   c                       r   )VivitIntermediater   c                    sR   t    t|j|j| _t|j| _	t
|jtr#t|j | _d S |j| _d S r   )r   r   r   r   r#   intermediate_sizer   rL   rM   rN   
isinstance
hidden_actstrr   intermediate_act_fnr(   r*   r,   r-   r     s   
zVivitIntermediate.__init__r   r0   c                 C   s"   |  |}| |}| |}|S r   )r   r   rN   )r)   r   r,   r,   r-   r<     s   


zVivitIntermediate.forwardr   r,   r,   r*   r-   r     s    	r   c                       s>   e Zd Zdef fddZdejdejdejfddZ  ZS )	VivitOutputr   c                    s.   t    t|j|j| _t|j| _	d S r   )
r   r   r   r   r   r#   r   rL   rM   rN   r(   r*   r,   r-   r   !  r   zVivitOutput.__init__r   r   r0   c                 C   s    |  |}| |}|| }|S r   r   r   r,   r,   r-   r<   &  s   

zVivitOutput.forwardr   r,   r,   r*   r-   r      s    $r   c                       s<   e Zd ZdZdef fddZdejdejfddZ  Z	S )	
VivitLayerzNThis corresponds to the EncoderBlock class in the scenic/vivit implementation.r   c                    sb   t    |j| _d| _t|| _t|| _t|| _	t
j|j|jd| _t
j|j|jd| _d S )Nr   eps)r   r   chunk_size_feed_forwardseq_len_dimr   r   r   intermediater   r   r   	LayerNormr#   layer_norm_epslayernorm_beforelayernorm_afterr(   r*   r,   r-   r   0  s   



zVivitLayer.__init__r   r0   c                 C   s@   |  |}| |}|| }| |}| |}| ||}|S r   )r   r   r   r   r   )r)   r   hidden_states_normattention_outputlayer_outputr,   r,   r-   r<   :  s   



zVivitLayer.forwardr   r,   r,   r*   r-   r   -  s    
r   c                       s6   e Zd Zdef fddZdejdefddZ  Z	S )VivitEncoderr   c                    s:   t     | _t fddt jD | _d| _d S )Nc                    s   g | ]}t  qS r,   )r   ).0r   r   r,   r-   
<listcomp>O  s    z)VivitEncoder.__init__.<locals>.<listcomp>F)	r   r   r   r   
ModuleListrangenum_hidden_layerslayergradient_checkpointingr(   r*   r   r-   r   L  s   
 
zVivitEncoder.__init__r   r0   c                 C   s&   t | jD ]\}}||}qt|dS )N)last_hidden_state)	enumerater   r   )r)   r   ilayer_moduler,   r,   r-   r<   R  s   

zVivitEncoder.forward)
r>   r?   r@   r   r   rB   rC   r   r<   rE   r,   r,   r*   r-   r   K  s    r   c                       r   )VivitPoolerr   c                    s*   t    t|j|j| _t | _d S r   )r   r   r   r   r#   r   Tanh
activationr(   r*   r,   r-   r   Z  s   
zVivitPooler.__init__r   r0   c                 C   s(   |d d df }|  |}| |}|S )Nr   )r   r   )r)   r   first_token_tensorpooled_outputr,   r,   r-   r<   _  s   

zVivitPooler.forwardr   r,   r,   r*   r-   r   Y  r   r   c                       s^   e Zd ZU eed< dZdZdZdZdgZ	dZ
dZdZdZeedZe  fdd	Z  ZS )
VivitPreTrainedModelr   vivitr.   videoTr   )r   
attentionsc                    s6   t  | t|trt|j t|j dS dS )zInitialize the weightsN)r   _init_weightsr   rF   initzeros_rI   rK   )r)   ri   r*   r,   r-   r   y  s
   
z"VivitPreTrainedModel._init_weights)r>   r?   r@   r   __annotations__base_model_prefixmain_input_nameinput_modalitiessupports_gradient_checkpointing_no_split_modules_supports_sdpa_supports_flash_attn_supports_flex_attn_supports_attention_backendr   ry   _can_record_outputsrB   no_gradr   rE   r,   r,   r*   r-   r   h  s    
 r   c                       sl   e Zd Zddedef fddZdd Zeedd	e		
	dde
jd
B dedee defddZ  ZS )
VivitModelTr   add_pooling_layerc                    sX   t  | || _t|| _t|| _tj|j	|j
d| _|r#t|nd| _|   dS )zv
        add_pooling_layer (bool, *optional*, defaults to `True`):
            Whether to add a pooling layer
        r   N)r   r   r   rF   rO   r   encoderr   r   r#   r   	layernormr   pooler	post_init)r)   r   r   r*   r,   r-   r     s   

zVivitModel.__init__c                 C   s   | j jS r   )rO   rJ   )r)   r,   r,   r-   get_input_embeddings  s   zVivitModel.get_input_embeddingsF)tie_last_hidden_statesNr.   r/   ro   r0   c                 K   s\   |du rt d| j||d}| |}|j}| |}| jdur&| |nd}t||d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]
        ```Nz You have to specify pixel_valuesrd   )r   pooler_output)r4   rO   r   r   r   r   r	   )r)   r.   r/   ro   embedding_outputencoder_outputssequence_outputr   r,   r,   r-   r<     s   T

zVivitModel.forward)T)NF)r>   r?   r@   r   rD   r   r   r   r   r   rB   FloatTensorr   r   r	   r<   rE   r,   r,   r*   r-   r     s"    r   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                       s`   e Zd Zdef fddZee			ddejdB dej	dB de
d	ee d
ef
ddZ  ZS )VivitForVideoClassificationr   c                    sR   t  | |j| _t|dd| _|jdkrt|j|jnt | _	| 
  d S )NF)r   r   )r   r   
num_labelsr   r   r   r   r#   Identity
classifierr   r(   r*   r,   r-   r     s
   $z$VivitForVideoClassification.__init__NFr.   labelsr/   ro   r0   c           	      K   sp   | j |fd|i|}|j}| |dddddf }d}|dur.| j||| jfi |}t|||j|jd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
        ```r/   Nr   )losslogitsr   r   )r   r   r   loss_functionr   r
   r   r   )	r)   r.   r   r/   ro   outputsr   r   r   r,   r,   r-   r<     s$   \z#VivitForVideoClassification.forward)NNF)r>   r?   r@   r   r   r   r   rB   r   
LongTensorrD   r   r   r
   r<   rE   r,   r,   r*   r-   r     s$    r   )r   r   r   )Nrh   )6rA   collections.abcr   rB   r    r   r   activationsr   modeling_layersr   modeling_outputsr   r	   r
   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   utils.genericr   r   utils.output_capturingr   configuration_vivitr   
get_loggerr>   loggerModuler   rF   rC   floatrx   ry   r   r   r   r   r   r   r   r   r   r   __all__r,   r,   r,   r-   <module>   sj   
,V
3u{