
    ix                     V   d Z ddlZddlmZ ddlmZ ddl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 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 ddlm Z m!Z! ddl"m#Z#m$Z$ ddl%m&Z&  ejN                  e(      Z)e ed       G d de                    Z*e ed       G d de                    Z+d Z, G d dejZ                        Z. G d dejZ                        Z/	 	 dCdejZ                  d e
j`                  d!e
j`                  d"e
j`                  d#e
j`                  dz  d$e1dz  d%e1d&ee   fd'Z2 G d( d)ejZ                        Z3 G d* d+ejZ                        Z4 G d, d-ejZ                        Z5 G d. d/ejZ                        Z6 G d0 d1ejZ                        Z7 G d2 d3e      Z8 G d4 d5ejZ                        Z9e G d6 d7e             Z:e G d8 d9e:             Z; G d: d;ejZ                        Z< ed<       G d= d>e:             Z= ed?       G d@ dAe:             Z>g dBZ?y)Dz,PyTorch VideoMAE (masked autoencoder) model.    N)Callable)deepcopy)	dataclass)nn)MSELoss   )ACT2FN)GradientCheckpointingLayer)BaseModelOutputImageClassifierOutput)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)ModelOutputTransformersKwargsauto_docstringlogging)IMAGENET_DEFAULT_MEANIMAGENET_DEFAULT_STD)can_return_tuplecheck_model_inputs   )VideoMAEConfigz[
    Class for VideoMAEDecoder's outputs, with potential hidden states and attentions.
    )custom_introc                       e Zd ZU dZdZej                  dz  ed<   dZe	ej                     dz  ed<   dZ
e	ej                     dz  ed<   y)VideoMAEDecoderOutputz
    logits (`torch.FloatTensor` of shape `(batch_size, patch_size ** 2 * num_channels)`):
        Pixel reconstruction logits.
    Nlogitshidden_states
attentions)__name__
__module____qualname____doc__r   torchFloatTensor__annotations__r   tupler        x/home/obispo/Crisostomo_bridge/mision_env/lib/python3.12/site-packages/transformers/models/videomae/modeling_videomae.pyr   r   (   sR    
 (,FE$+59M5**+d2926Je''(4/6r)   r   zb
    Class for VideoMAEForPreTraining's outputs, with potential hidden states and attentions.
    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
ej                     dz  ed<   dZe
ej                     dz  ed<   y)VideoMAEForPreTrainingOutputz
    loss (`torch.FloatTensor` of shape `(1,)`):
        Pixel reconstruction loss.
    logits (`torch.FloatTensor` of shape `(batch_size, patch_size ** 2 * num_channels)`):
        Pixel reconstruction logits.
    Nlossr   r   r   )r    r!   r"   r#   r-   r$   r%   r&   r   r   r'   r   r(   r)   r*   r,   r,   9   sg     &*D%

d
")'+FE$+59M5**+d2926Je''(4/6r)   r,   c                 h   fd}t        j                  t        |       D cg c]
  } ||       c}      }t        j                  |dddddf         |dddddf<   t        j                  |dddddf         |dddddf<   t        j                  |      j                  d      S c c}w )z Sinusoid position encoding tablec           
          t              D cg c]$  }| t        j                  dd|dz  z  z        z  & c}S c c}w )Ni'     )rangenppower)positionhid_jd_hids     r*   get_position_angle_vecz;get_sinusoid_encoding_table.<locals>.get_position_angle_vecS   s;    RWX]R^_288E1
+;e+CDD___s   );Nr   r0   r   )r2   arrayr1   sincosr$   r%   	unsqueeze)
n_positionr6   r7   pos_isinusoid_tables    `   r*   get_sinusoid_encoding_tabler?   O   s    ` XX%PZJ[\5e<\]N ff^Aqt!tG%<=N1add7 ff^Aqt!tG%<=N1add7^,66q99	 ]s   B/c                   (     e Zd ZdZ fdZd Z xZS )VideoMAEEmbeddingsz7
    Construct the patch and position embeddings.

    c                     t         |           t        |      | _        | j                  j                  | _        t        | j                  |j                        | _        || _        y N)	super__init__VideoMAEPatchEmbeddingspatch_embeddingsnum_patchesr?   hidden_sizeposition_embeddingsconfigselfrK   	__class__s     r*   rE   zVideoMAEEmbeddings.__init__c   sR     7 ?00<<#>t?O?OQWQcQc#d r)   c                    | j                  |      }|| j                  j                         j                  |      j	                  |j
                  d      z   }|)|j                  \  }}}||    }|j                  |d|      }|S )NTdevicecopy)rG   rJ   detachtype_astorQ   shapereshape)rM   pixel_valuesbool_masked_pos
embeddings
batch_size_num_channelss          r*   forwardzVideoMAEEmbeddings.forwardl   s    **<8
  $":":"A"A"C"K"KJ"W"Z"Z$$4 #[ #
 


 &*4*:*:'J<#_$45J#++JLIJr)   r    r!   r"   r#   rE   r_   __classcell__rN   s   @r*   rA   rA   ]   s    
r)   rA   c                   (     e Zd ZdZ fdZd Z xZS )rF   aw  
    Video to Patch Embedding. 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) * (height // patch_size) * (width //
    patch_size).

    c           	         t         	|           |j                  }|j                  }|j                  }|j
                  }|j                  }|j                  }t        |t        j                  j                        r|n||f}t        |t        j                  j                        r|n||f}|| _        || _        t        |      | _        |d   |d   z  |d   |d   z  z  || j                  z  z  }|| _        || _        t        j                  ||| j                  |d   |d   f| j                  |d   |d   f      | _        y )Nr   r   )in_channelsout_channelskernel_sizestride)rD   rE   
image_size
patch_sizer^   rI   
num_framestubelet_size
isinstancecollectionsabcIterableintrH   r   Conv3d
projection)
rM   rK   ri   rj   r^   rI   rk   rl   rH   rN   s
            r*   rE   z VideoMAEPatchEmbeddings.__init__   s>   &&
&&
**((&&
**#-j+//:R:R#SZZdfpYq
#-j+//:R:R#SZZdfpYq
$$-]jm+
1A0NOS]aeararSrs 	 )&))$$**JqM:a=I%%z!}jmD	
r)   c                    |j                   \  }}}}}|| j                  k7  rt        d      || j                  d   k7  s|| j                  d   k7  r2t        d| d| d| j                  d    d| j                  d    d	      |j	                  dddd	d
      }| j                  |      j                  d      j                  dd      }|S )NzeMake sure that the channel dimension of the pixel values match with the one set in the configuration.r   r   zInput image size (*z) doesn't match model (z).r0   r      )rW   r^   
ValueErrorri   permuters   flatten	transpose)rM   rY   r\   rk   r^   heightwidthr[   s           r*   r_   zVideoMAEPatchEmbeddings.forward   s    >J>P>P;
Jfe4,,,w  T__Q''5DOOA4F+F$VHAeW4KDOO\]L^K__`aeapapqras`ttvw  $++Aq!Q:__\2::1=GG1M
r)   r`   rb   s   @r*   rF   rF   ~   s    
6r)   rF   modulequerykeyvalueattention_maskscalingdropoutkwargsc                    ||j                  d      dz  }t        j                  ||j                  dd            |z  }|#|d d d d d d d |j                  d   f   }||z   }t
        j                  j                  |d      }t
        j                  j                  ||| j                        }t        j                  ||      }	|	j                  dd      j                         }	|	|fS )	NrS         r0   r   dim)ptrainingr   )sizer$   matmulrz   rW   r   
functional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EL!'1a399R=(@A#n4==((2(>L==((6??([L,,|U3K''1-88:K$$r)   c                        e Zd Zdeddf fdZddej                  dz  deej                  ej                  f   fdZ xZ	S )VideoMAESelfAttentionrK   returnNc                    t         |           |j                  |j                  z  dk7  r2t	        |d      s&t        d|j                   d|j                   d      || _        |j                  | _        t        |j                  |j                  z        | _        | j                  | j                  z  | _	        |j                  | _        | j                  dz  | _        d| _        t        j                  |j                  | j                  d      | _        t        j                  |j                  | j                  d      | _        t        j                  |j                  | j                  d      | _        |j&                  rot        j(                  t+        j,                  | j                              | _        t        j(                  t+        j,                  | j                              | _        y d | _        d | _        y )	Nr   embedding_sizezThe hidden size z4 is not a multiple of the number of attention heads .r   Fbias)rD   rE   rI   num_attention_headshasattrrw   rK   rq   attention_head_sizeall_head_sizeattention_probs_dropout_probdropout_probr   	is_causalr   Linearr~   r   r   qkv_bias	Parameterr$   zerosq_biasv_biasrL   s     r*   rE   zVideoMAESelfAttention.__init__   s    : ::a?PVXhHi"6#5#5"6 7334A7  #)#=#= #&v'9'9F<V<V'V#W !558P8PP"??//5YYv1143E3EER
99V//1C1C%PYYv1143E3EER
??,,u{{43E3E'FGDK,,u{{43E3E'FGDKDKDKr)   r   c           
         |j                   \  }}}| j                  !t        j                  | j                  d      nd }t
        j                  j                  || j                  j                  |      }t
        j                  j                  || j                  j                  | j                        }t
        j                  j                  || j                  j                  | j                        }|j                  |d| j                  | j                        j                  dd      }	|j                  |d| j                  | j                        j                  dd      }
|j                  |d| j                  | j                        j                  dd      }t!        j"                  | j$                  j&                  t(              } || ||	|
d | j*                  | j,                  | j.                  sdn| j0                        \  }}|j3                         d d	 | j4                  fz   }|j7                  |      }||fS )
NF)requires_grad)inputweightr   rS   r   r0           )r   r   r   r   )rW   r   r$   
zeros_liker   r   r   linearr   r   r   r~   viewr   r   rz   r   get_interfacerK   _attn_implementationr   r   r   r   r   r   r   rX   )rM   r   r\   
seq_lengthr]   k_biaskeysvaluesqueries	key_layervalue_layerquery_layerattention_interfacecontext_layerattention_probsnew_context_layer_shapes                   r*   r_   zVideoMAESelfAttention.forward   s   $1$7$7!
JGK{{G^!!$++UCdh}}##-V\#]%%M$**BSBSZ^ZeZe%f--&&]4::CTCT[_[f[f&gIIj"d.F.FH`H`akklmopq	kk*b$2J2JDLdLdeoopqstull:r43K3KTMeMefppqrtuv(?(M(MKK,,.E)
 *=nnLL#}}C$2C2C	*
& #0"4"4"6s";t?Q?Q>S"S%--.EFo--r)   rC   )
r    r!   r"   r   rE   r$   Tensorr'   r_   ra   rb   s   @r*   r   r      sG    ~ $ 4.U\\D%8 .E%,,X]XdXdJdDe .r)   r   c                   x     e Zd ZdZdef fdZdej                  dej                  dej                  fdZ xZ	S )VideoMAESelfOutputz
    The residual connection is defined in VideoMAELayer instead of here (as is the case with other models), due to the
    layernorm applied before each block.
    rK   c                     t         |           t        j                  |j                  |j                        | _        t        j                  |j                        | _        y rC   )	rD   rE   r   r   rI   denseDropouthidden_dropout_probr   rL   s     r*   rE   zVideoMAESelfOutput.__init__  sB    YYv1163E3EF
zz&"<"<=r)   r   input_tensorr   c                 J    | j                  |      }| j                  |      }|S rC   r   r   rM   r   r   s      r*   r_   zVideoMAESelfOutput.forward  s$    

=1]3r)   
r    r!   r"   r#   r   rE   r$   r   r_   ra   rb   s   @r*   r   r     s=    
>~ >
U\\  RWR^R^ r)   r   c                   \     e Zd Zdef fdZdej                  dej                  fdZ xZS )VideoMAEAttentionrK   c                 b    t         |           t        |      | _        t	        |      | _        y rC   )rD   rE   r   	attentionr   outputrL   s     r*   rE   zVideoMAEAttention.__init__!  s&    .v6(0r)   r   r   c                 R    | j                  |      \  }}| j                  ||      }|S rC   )r   r   )rM   r   self_attn_outputr]   r   s        r*   r_   zVideoMAEAttention.forward&  s,    "nn];!-}=r)   	r    r!   r"   r   rE   r$   r   r_   ra   rb   s   @r*   r   r      s*    1~ 1
U\\ ell r)   r   c                   \     e Zd Zdef fdZdej                  dej                  fdZ xZS )VideoMAEIntermediaterK   c                    t         |           t        j                  |j                  |j
                        | _        t        |j                  t              rt        |j                     | _        y |j                  | _        y rC   )rD   rE   r   r   rI   intermediate_sizer   rm   
hidden_actstrr	   intermediate_act_fnrL   s     r*   rE   zVideoMAEIntermediate.__init__.  s]    YYv1163K3KL
f''-'-f.?.?'@D$'-'8'8D$r)   r   r   c                 J    | j                  |      }| j                  |      }|S rC   )r   r   )rM   r   s     r*   r_   zVideoMAEIntermediate.forward6  s&    

=100?r)   r   rb   s   @r*   r   r   -  s*    9~ 9U\\ ell r)   r   c                   t     e Zd Zdef fdZdej                  dej                  dej                  fdZ xZS )VideoMAEOutputrK   c                     t         |           t        j                  |j                  |j
                        | _        t        j                  |j                        | _	        y rC   )
rD   rE   r   r   r   rI   r   r   r   r   rL   s     r*   rE   zVideoMAEOutput.__init__>  sB    YYv779K9KL
zz&"<"<=r)   r   r   r   c                 T    | j                  |      }| j                  |      }||z   }|S rC   r   r   s      r*   r_   zVideoMAEOutput.forwardC  s.    

=1]3%4r)   r   rb   s   @r*   r   r   =  s8    >~ >
U\\  RWR^R^ r)   r   c                   `     e Zd ZdZdef fdZdej                  dej                  fdZ xZ	S )VideoMAELayerz?This corresponds to the Block class in the timm implementation.rK   c                 r   t         |           |j                  | _        d| _        t	        |      | _        t        |      | _        t        |      | _	        t        j                  |j                  |j                        | _        t        j                  |j                  |j                        | _        y )Nr   eps)rD   rE   chunk_size_feed_forwardseq_len_dimr   r   r   intermediater   r   r   	LayerNormrI   layer_norm_epslayernorm_beforelayernorm_afterrL   s     r*   rE   zVideoMAELayer.__init__N  s    '-'E'E$*6208$V, "V-?-?VEZEZ [!||F,>,>FDYDYZr)   r   r   c                     | j                  |      }| j                  |      }||z   }| j                  |      }| j                  |      }| j	                  ||      }|S rC   )r   r   r   r   r   )rM   r   hidden_states_normattention_outputlayer_outputs        r*   r_   zVideoMAELayer.forwardX  si    !22=A>>*<= )=8 ++M:((6 {{<?r)   r   rb   s   @r*   r   r   K  s/    I[~ [U\\ ell r)   r   c                   H     e Zd Zdef fdZdej                  defdZ xZ	S )VideoMAEEncoderrK   c                     t         |           || _        t        j                  t        |j                        D cg c]  }t        |       c}      | _        d| _	        y c c}w )NF)
rD   rE   rK   r   
ModuleListr1   num_hidden_layersr   layergradient_checkpointing)rM   rK   r]   rN   s      r*   rE   zVideoMAEEncoder.__init__k  sN    ]]5IaIaCb#caM&$9#cd
&+# $ds   A#r   r   c                 d    t        | j                        D ]  \  }} ||      } t        |      S )Nlast_hidden_state)	enumerater   r   )rM   r   ilayer_modules       r*   r_   zVideoMAEEncoder.forwardq  s5    (4 	8OA|(7M	8 ??r)   )
r    r!   r"   r   rE   r$   r   r   r_   ra   rb   s   @r*   r   r   j  s)    ,~ ,@U\\ @o @r)   r   c                   J    e Zd ZU eed<   dZdZdZdZddgZ	dZ
dZdZdZeedZy	)
VideoMAEPreTrainedModelrK   videomaerY   videoTrA   r   )r   r   N)r    r!   r"   r   r&   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   r   _can_record_outputsr(   r)   r*   r   r   x  sO    "$O&*#-?N"&&+r)   r   c                        e Zd Z fdZd Z ed      e	 ddej                  dej                  dz  de
e   d	efd
              Z xZS )VideoMAEModelc                    t         |   |       || _        t        |      | _        t        |      | _        |j                  rd | _        n0t        j                  |j                  |j                        | _        | j                          y )Nr   )rD   rE   rK   rA   r[   r   encoderuse_mean_pooling	layernormr   r   rI   r   	post_initrL   s     r*   rE   zVideoMAEModel.__init__  si     ,V4&v.""!DN\\&*<*<&BWBWXDN 	r)   c                 .    | j                   j                  S rC   )r[   rG   )rM   s    r*   get_input_embeddingsz"VideoMAEModel.get_input_embeddings  s    ///r)   F)tie_last_hidden_statesNrY   rZ   r   r   c                     | j                  ||      }| j                  |      }|j                  }| j                  | j                  |      }t	        |      S )aB  
        bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Boolean masked positions. Indicates which patches are masked (1) and which aren't (0). Each video in the
            batch must have the same number of masked patches. If `None`, then all patches are considered. Sequence
            length is `(num_frames // tubelet_size) * (image_size // patch_size) ** 2`.

        Examples:

        ```python
        >>> import torch
        >>> from transformers import VideoMAEVideoProcessor, VideoMAEModel
        >>> from huggingface_hub import hf_hub_download

        >>> # replace this with your own video file
        >>> video_path = hf_hub_download(
        ...     repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
        ... )

        >>> video_processor = VideoMAEVideoProcessor.from_pretrained("MCG-NJU/videomae-base")
        >>> model = VideoMAEModel.from_pretrained("MCG-NJU/videomae-base")

        >>> # prepare video for the model
        >>> inputs = video_processor(video_path, return_tensors="pt")

        >>> # forward pass
        >>> with torch.no_grad():
        ...     outputs = model(**inputs)

        >>> last_hidden_states = outputs.last_hidden_state
        >>> list(last_hidden_states.shape)
        [1, 1568, 768]
        ```r   )r[   r  r   r  r   )rM   rY   rZ   r   embedding_outputencoder_outputssequence_outputs          r*   r_   zVideoMAEModel.forward  sS    R  ??<I+/<<8H+I);;>>%"nn_=OAAr)   rC   )r    r!   r"   rE   r  r   r   r$   r%   
BoolTensorr   r   r   r_   ra   rb   s   @r*   r  r    sv    0 u5 48.B''.B ))D0.B +,	.B
 
.B  6.Br)   r  c                   H     e Zd Zdef fdZdej                  defdZ xZ	S )VideoMAEDecoderrK   c                    t         |           |j                  |j                  z  |j                  dz  z  }t        |      }|j                  |_        |j                  |_	        |j                  |_        |j                  |_        t        j                  t!        |j                        D cg c]  }t#        |       c}      | _        t        j&                  |j                        | _        |dkD  r t        j*                  |j                  |      nt        j,                         | _        d| _        || _        y c c}w )Nr0   r   F)rD   rE   r^   rl   rj   r   decoder_hidden_sizerI   decoder_num_hidden_layersr   decoder_num_attention_headsr   decoder_intermediate_sizer   r   r   r1   r   decoder_layersr   normr   Identityheadr   rK   )rM   rK   decoder_num_labelsdecoder_configr]   rN   s        r*   rE   zVideoMAEDecoder.__init__  s   #0063F3FFIZIZ\]I]]!&)%+%?%?"+1+K+K(-3-O-O*+1+K+K( mm49&:Z:Z4[\q]>*\
 LL!;!;<	I[^_I_BIIf002DEegepeper 		 ',#$ ]s   .D=r   return_token_numc                     | j                   D ]
  } ||      } |d d | d f   }| j                  |      }| j                  |      }t        |      S )N)r   )r   r!  r#  r   )rM   r   r&  r   r   s        r*   r_   zVideoMAEDecoder.forward  sb     // 	8L(7M	8 &a*:):);&;< 		-0=)$F33r)   )
r    r!   r"   r   rE   r$   r   rq   r_   ra   rb   s   @r*   r  r    s&    %~ %,4U\\ 4S 4r)   r  zb
    The VideoMAE Model transformer with the decoder on top for self-supervised pre-training.
    c            
       x     e Zd Z fdZeedej                  dej                  de	e
   defd              Z xZS )VideoMAEForPreTrainingc                    t         |   |       || _        t        |      | _        t        j                  |j                  |j                  d      | _	        t        j                  t        j                  dd|j                              | _        t        | j                  j                  j                   |j                        | _        t%        |      | _        | j)                          y )NFr   r   )rD   rE   rK   r  r   r   r   rI   r  encoder_to_decoderr   r$   r   
mask_tokenr?   r[   rH   rJ   r  decoderr  rL   s     r*   rE   zVideoMAEForPreTraining.__init__  s     %f-"$))F,>,>@Z@Zaf"g,,u{{1a9S9S'TU#>MM$$00&2L2L$
  'v. 	r)   rY   rZ   r   r   c                 *    | j                   |fd|i|}|j                  }| j                  |      }|j                  \  }}}|t	        d      | j
                  j                  |dd      j                  |      }	|	j                         j                  |j                  d      }	|	|    j                  |d|      }
|	|   j                  |d|      }t        j                  ||
z   | j                  |z   gd      }| j                  ||j                  d         }|j                   }d}t        j"                         5  | j$                  j&                  d	k7  r|}n|j                  }|j(                  }t        j*                  t,              j                  ||
      ddddddf   }t        j*                  t.              j                  ||
      ddddddf   }||z  |z   }|j                  \  }}}}}| j$                  j0                  | j$                  j2                  }}| j$                  j4                  r|j7                  |||z  ||||z  |||z  |      }|j9                  dddddddd	      j;                         }|j7                  |||z  |z  |z  |z  |z  ||z  |z  |      }||j=                  dd      z
  |j?                  ddd      jA                         dz   z  }|j7                  |||z  |z  |z  |z  |z  ||z  |z  |z        }n| j$                  j&                  d	k7  rt	        d      |j7                  |||z  ||||z  |||z  |      }|j9                  dddddddd	      j;                         }|j7                  |||z  |z  |z  |z  |z  ||z  |z  |z        }|j                  \  }}}||   j                  |d|      }ddd       tC               } ||      }tE        |||jF                  |jH                        S # 1 sw Y   ?xY w)a  
        bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, sequence_length)`):
            Boolean masked positions. Indicates which patches are masked (1) and which aren't (0). Each video in the
            batch must have the same number of masked patches. Sequence length is `(num_frames // tubelet_size) *
            (image_size // patch_size) ** 2`.

        Examples:
        ```python
        >>> from transformers import AutoImageProcessor, VideoMAEForPreTraining
        >>> import numpy as np
        >>> import torch

        >>> num_frames = 16
        >>> video = list(np.random.randint(0, 256, (num_frames, 3, 224, 224)))

        >>> image_processor = AutoImageProcessor.from_pretrained("MCG-NJU/videomae-base")
        >>> model = VideoMAEForPreTraining.from_pretrained("MCG-NJU/videomae-base")

        >>> pixel_values = image_processor(video, return_tensors="pt").pixel_values

        >>> num_patches_per_frame = (model.config.image_size // model.config.patch_size) ** 2
        >>> seq_length = (num_frames // model.config.tubelet_size) * num_patches_per_frame
        >>> bool_masked_pos = torch.randint(0, 2, (1, seq_length)).bool()

        >>> outputs = model(pixel_values, bool_masked_pos=bool_masked_pos)
        >>> loss = outputs.loss
        ```rZ   Nz!One must provided a boolean mask rS   TrP   r   r   r   )rQ   dtyper   rv      r0         r   )r   keepdim)r   unbiasedr3  gư>zQCan't unnormalize non-RGB images. Consider setting config.norm_pix_loss to False.r-   r   r   r   )%r   r   r+  rW   rw   rJ   expandrU   rT   rV   rQ   rX   r$   catr,  r-  r   no_gradrK   r^   r/  	as_tensorr   r   rl   rj   norm_pix_lossr   rx   r   meanvarsqrtr   r,   r   r   )rM   rY   rZ   r   outputsr  r\   r]   r^   expanded_position_embeddingspos_emb_visiblepos_emb_maskx_fulldecoder_outputsr   r-   framesrQ   r/  r;  stdtimer{   r|   rl   rj   frames_normvideos_patchlabelsloss_fcts                                 r*   r_   zVideoMAEForPreTraining.forward  s   F $14==#i#ibh#i!3311/B '6&;&;#
A| "@AA'+'?'?'F'FzSUWY'Z'b'bco'p$'C'J'J'L'O'OWcWjWjqu'O'v$67GHPPQ[]_amn3ODLLZY[]ij Oo=tQ]?]^def 26flFXFXYZF[1\ '']]_ H	Y{{''1,% &,,$**'<=@@V[@\]acgijlprv]vwoo&:;>>fTY>Z[_aeghjnpt[tu%+d2<BLL9JlFE'+{{'?'?AWAW*L{{((L(  j(Z'	  1aAq!Q?JJLL(61Z?%G:U :-
: 	  &D(IIJJ2dJCHHJTQ  +//L(61Z?%G:U :-
:\I  ;;++q0$k   L(  j(Z'	  1aAq!Q?JJL%{{L(61Z?%G:U :-
:\I  +7*<*<'J<!/2:::r<XFQH	YT 9'+!//))	
 	
[H	Y H	Ys   >JP		P)r    r!   r"   rE   r   r   r$   r%   r  r   r   r,   r_   ra   rb   s   @r*   r)  r)    sb    " L
''L
 ))L
 +,	L

 
&L
  L
r)   r)  z
    VideoMAE Model transformer with a video classification head on top (a linear layer on top of the average pooled hidden
    states of all tokens) e.g. for ImageNet.
    c                        e Zd Z fdZee	 	 ddej                  dz  dej                  dz  dee	   de
fd              Z xZS )	VideoMAEForVideoClassificationc                    t         |   |       |j                  | _        t        |      | _        |j
                  rt        j                  |j                        nd | _	        |j                  dkD  r*t        j                  |j                  |j                        nt        j                         | _        | j                          y )Nr   )rD   rE   
num_labelsr  r   r  r   r   rI   fc_normr   r"  
classifierr  rL   s     r*   rE   z'VideoMAEForVideoClassification.__init__  s      ++%f- <B;R;Rr||F$6$67X\NTN_N_bcNc"))F$6$68I8IJikititiv 	r)   NrY   rI  r   r   c                 ^    | j                   |fi |}|j                  }| j                  #|j                  d      }| j                  |      }n	|dddf   }| j	                  |      }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 torch
        >>> from transformers import VideoMAEVideoProcessor, VideoMAEForVideoClassification
        >>> from huggingface_hub import hf_hub_download

        >>> # replace this with your own video file
        >>> video_path = hf_hub_download(
        ...     repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
        ... )

        >>> video_processor = VideoMAEVideoProcessor.from_pretrained("MCG-NJU/videomae-base-finetuned-kinetics")
        >>> model = VideoMAEForVideoClassification.from_pretrained("MCG-NJU/videomae-base-finetuned-kinetics")

        >>> inputs = video_processor(video_path, 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])
        eating spaghetti
        ```Nr   r   r5  )
r   r   rO  r;  rP  loss_functionrK   r   r   r   )	rM   rY   rI  r   r>  r  r   r   r-   s	            r*   r_   z&VideoMAEForVideoClassification.forward  s    R $14==#H#H!33<<#$))!,F\\&)F$QT*F(%4%%ffdkkLVLD$!//))	
 	
r)   )NN)r    r!   r"   rE   r   r   r$   r   r   r   r   r_   ra   rb   s   @r*   rL  rL    sj      -1&*;
llT);
 t#;
 +,	;

 
;
  ;
r)   rL  )r)  r  r   rL  )Nr   )@r#   collections.abcrn   r   rR   r   dataclassesr   numpyr2   r$   r   torch.nnr   activationsr	   modeling_layersr
   modeling_outputsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   utils.constantsr   r   utils.genericr   r   configuration_videomaer   
get_loggerr    loggerr   r,   r?   ModulerA   rF   r   floatr   r   r   r   r   r   r   r   r   r  r  r)  rL  __all__r(   r)   r*   <module>re     sl   3  $  !     ! 9 F F & M M J A 2 
		H	% 
7K 7 7 
7; 7 7 : B2bii 2x !%II%<<% 
% <<	%
 LL4'% T\% % '(%:9.BII 9.z $			 	299  
RYY 
. >@bii @ o  " CB+ CB CBL"4bii "4J 
`
4 `

`
F K
%< K
K
\ sr)   