
    qix                     b   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& ddl'm(Z(  ejR                  e*      Z+e ed       G d de                    Z,e ed       G d de                    Z-d Z. G d dej^                        Z0 G d dej^                        Z1	 	 dDd ej^                  d!e
jd                  d"e
jd                  d#e
jd                  d$e
jd                  dz  d%e3dz  d&e3d'ee   fd(Z4 G d) d*ej^                        Z5 G d+ d,ej^                        Z6 G d- d.ej^                        Z7 G d/ d0ej^                        Z8 G d1 d2ej^                        Z9 G d3 d4e      Z: G d5 d6ej^                        Z;e G d7 d8e             Z<e G d9 d:e<             Z= G d; d<ej^                        Z> ed=       G d> d?e<             Z? ed@       G dA dBe<             Z@g dCZAy)Ez,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merge_with_config_defaults)capture_outputs   )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         `/opt/pipecat/venv/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-   :   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_vecT   s;    RWX]R^_288E1
+;e+CDD___s   );Nr   r1   r   )r3   arrayr2   sincosr%   r&   	unsqueeze)
n_positionr7   r8   pos_isinusoid_tables    `   r+   get_sinusoid_encoding_tabler@   P   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selfrL   	__class__s     r+   rF   zVideoMAEEmbeddings.__init__d   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)rH   rK   detachtype_astorR   shapereshape)rN   pixel_valuesbool_masked_pos
embeddings
batch_size_num_channelss          r+   forwardzVideoMAEEmbeddings.forwardm   s    **<8
  $":":"A"A"C"K"KJ"W"Z"Z$$4 #[ #
 


 &*4*:*:'J<#_$45J#++JLIJr*   r!   r"   r#   r$   rF   r`   __classcell__rO   s   @r+   rB   rB   ^   s    
r*   rB   c                   (     e Zd ZdZ fdZd Z xZS )rG   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)rE   rF   
image_size
patch_sizer_   rJ   
num_framestubelet_size
isinstancecollectionsabcIterableintrI   r   Conv3d
projection)
rN   rL   rj   rk   r_   rJ   rl   rm   rI   rO   s
            r+   rF   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).r1   r      )rX   r_   
ValueErrorrj   permutert   flatten	transpose)rN   rZ   r]   rl   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*   ra   rc   s   @r+   rG   rG      s    
6r*   rG   modulequerykeyvalueattention_maskscalingdropoutkwargsc                    ||j                  d      dz  }t        j                  ||j                  dd            |z  }|||z   }t        j
                  j                  |d      }t        j
                  j                  ||| j                        }t        j                  ||      }	|	j                  dd      j                         }	|	|fS )NrT         r1   r   dim)ptrainingr   )
sizer%   matmulr{   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!#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 )VideoMAESelfAttentionrL   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)rE   rF   rJ   num_attention_headshasattrrx   rL   rr   attention_head_sizeall_head_sizeattention_probs_dropout_probdropout_probr   	is_causalr   Linearr   r   r   qkv_bias	Parameterr%   zerosq_biasv_biasrM   s     r+   rF   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   rT   r   r1           )r   r   r   )rX   r   r%   
zeros_liker   r   r   linearr   r   r   r   viewr   r   r{   r   get_interfacerL   _attn_implementationr   r   r   r   r   r   r   rY   )rN   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*   rD   )
r!   r"   r#   r   rF   r%   Tensorr(   r`   rb   rc   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.
    rL   c                     t         |           t        j                  |j                  |j                        | _        t        j                  |j                        | _        y rD   )	rE   rF   r   r   rJ   denseDropouthidden_dropout_probr   rM   s     r+   rF   zVideoMAESelfOutput.__init__  sB    YYv1163E3EF
zz&"<"<=r*   r   input_tensorr   c                 J    | j                  |      }| j                  |      }|S rD   r   r   rN   r   r   s      r+   r`   zVideoMAESelfOutput.forward  s$    

=1]3r*   
r!   r"   r#   r$   r   rF   r%   r   r`   rb   rc   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 )VideoMAEAttentionrL   c                 b    t         |           t        |      | _        t	        |      | _        y rD   )rE   rF   r   	attentionr   outputrM   s     r+   rF   zVideoMAEAttention.__init__!  s&    .v6(0r*   r   r   c                 R    | j                  |      \  }}| j                  ||      }|S rD   )r   r   )rN   r   self_attn_outputr^   r   s        r+   r`   zVideoMAEAttention.forward&  s,    "nn];!-}=r*   	r!   r"   r#   r   rF   r%   r   r`   rb   rc   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 )VideoMAEIntermediaterL   c                    t         |           t        j                  |j                  |j
                        | _        t        |j                  t              rt        |j                     | _        y |j                  | _        y rD   )rE   rF   r   r   rJ   intermediate_sizer   rn   
hidden_actstrr	   intermediate_act_fnrM   s     r+   rF   zVideoMAEIntermediate.__init__.  s]    YYv1163K3KL
f''-'-f.?.?'@D$'-'8'8D$r*   r   r   c                 J    | j                  |      }| j                  |      }|S rD   )r   r   )rN   r   s     r+   r`   zVideoMAEIntermediate.forward6  s&    

=100?r*   r   rc   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 )VideoMAEOutputrL   c                     t         |           t        j                  |j                  |j
                        | _        t        j                  |j                        | _	        y rD   )
rE   rF   r   r   r   rJ   r   r   r   r   rM   s     r+   rF   zVideoMAEOutput.__init__>  sB    YYv779K9KL
zz&"<"<=r*   r   r   r   c                 T    | j                  |      }| j                  |      }||z   }|S rD   r   r   s      r+   r`   zVideoMAEOutput.forwardC  s.    

=1]3%4r*   r   rc   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.rL   c                 r   t         |           |j                  | _        d| _        t	        |      | _        t        |      | _        t        |      | _	        t        j                  |j                  |j                        | _        t        j                  |j                  |j                        | _        y )Nr   eps)rE   rF   chunk_size_feed_forwardseq_len_dimr   r   r   intermediater   r   r   	LayerNormrJ   layer_norm_epslayernorm_beforelayernorm_afterrM   s     r+   rF   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 rD   )r   r   r   r   r   )rN   r   hidden_states_normattention_outputlayer_outputs        r+   r`   zVideoMAELayer.forwardX  si    !22=A>>*<= )=8 ++M:((6 {{<?r*   r   rc   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 )VideoMAEEncoderrL   c                     t         |           || _        t        j                  t        |j                        D cg c]  }t        |       c}      | _        d| _	        y c c}w )NF)
rE   rF   rL   r   
ModuleListr2   num_hidden_layersr   layergradient_checkpointing)rN   rL   r^   rO   s      r+   rF   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   )rN   r   ilayer_modules       r+   r`   zVideoMAEEncoder.forwardq  s5    (4 	8OA|(7M	8 ??r*   )
r!   r"   r#   r   rF   r%   r   r   r`   rb   rc   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	)
VideoMAEPreTrainedModelrL   videomaerZ   videoTrB   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 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   )rE   rF   rL   rB   r\   r   encoderuse_mean_pooling	layernormr   r   rJ   r   	post_initrM   s     r+   rF   zVideoMAEModel.__init__  si     ,V4&v.""!DN\\&*<*<&BWBWXDN 	r*   c                 .    | j                   j                  S rD   )r\   rH   )rN   s    r+   get_input_embeddingsz"VideoMAEModel.get_input_embeddings  s    ///r*   F)tie_last_hidden_statesNrZ   r[   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   )rN   rZ   r[   r   embedding_outputencoder_outputssequence_outputs          r+   r`   zVideoMAEModel.forward  sS    T  ??<I+/<<8H+I);;>>%"nn_=OAAr*   rD   )r!   r"   r#   rF   r  r   r   r   r%   r&   
BoolTensorr   r   r   r`   rb   rc   s   @r+   r  r    s~    0  E2 48.B''.B ))D0.B +,	.B
 
.B  3  .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 )VideoMAEDecoderrL   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 )Nr1   r   F)rE   rF   r_   rm   rk   r   decoder_hidden_sizerJ   decoder_num_hidden_layersr   decoder_num_attention_headsr   decoder_intermediate_sizer   r   r   r2   r   decoder_layersr   normr   Identityheadr   rL   )rN   rL   decoder_num_labelsdecoder_configr^   rO   s        r+   rF   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   )rN   r   r'  r   r   s        r+   r`   zVideoMAEDecoder.forward  sb     // 	8L(7M	8 &a*:):);&;< 		-0=)$F33r*   )
r!   r"   r#   r   rF   r%   r   rr   r`   rb   rc   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   )rE   rF   rL   r  r   r   r   rJ   r  encoder_to_decoderr   r%   r   
mask_tokenr@   r\   rI   rK   r  decoderr  rM   s     r+   rF   zVideoMAEForPreTraining.__init__  s     %f-"$))F,>,>@Z@Zaf"g,,u{{1a9S9S'TU#>MM$$00&2L2L$
  'v. 	r*   rZ   r[   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
        ```r[   Nz!One must provided a boolean mask rT   TrQ   r   r   r   )rR   dtyper   rw      r1         r   )r   keepdim)r   unbiasedr4  gư>zQCan't unnormalize non-RGB images. Consider setting config.norm_pix_loss to False.r.   r   r   r    )%r   r   r,  rX   rx   rK   expandrV   rU   rW   rR   rY   r%   catr-  r.  r   no_gradrL   r_   r0  	as_tensorr   r   rm   rk   norm_pix_lossr   ry   r   meanvarsqrtr   r-   r   r    )rN   rZ   r[   r   outputsr  r]   r^   r_   expanded_position_embeddingspos_emb_visiblepos_emb_maskx_fulldecoder_outputsr   r.   framesrR   r0  r<  stdtimer|   r}   rm   rk   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#   rF   r   r   r%   r&   r  r   r   r-   r`   rb   rc   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   )rE   rF   
num_labelsr  r   r  r   r   rJ   fc_normr   r#  
classifierr  rM   s     r+   rF   z'VideoMAEForVideoClassification.__init__  s      ++%f- <B;R;Rr||F$6$67X\NTN_N_bcNc"))F$6$68I8IJikititiv 	r*   NrZ   rJ  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   r6  )
r   r   rP  r<  rQ  loss_functionrL   r   r   r    )	rN   rZ   rJ  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#   rF   r   r   r%   r   r   r   r   r`   rb   rc   s   @r+   rM  rM    sj      -1&*;
llT);
 t#;
 +,	;

 
;
  ;
r*   rM  )r*  r  r   rM  )Nr   )Br$   collections.abcro   r   rS   r   dataclassesr   numpyr3   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   utils.output_capturingr   configuration_videomaer   
get_loggerr!   loggerr   r-   r@   ModulerB   rG   r   floatr   r   r   r   r   r   r   r   r   r  r  r*  rM  __all__r)   r*   r+   <module>rg     so   3  $  !     ! 9 F F & M M J I 5 2 
		H	% 
7K 7 7 
7; 7 7 : B2bii 2x !%II%<<% 
% <<	%
 LL4'% T\% % '(%89.BII 9.z $			 	299  
RYY 
. >@bii @ o  " DB+ DB DBN"4bii "4J 
`
4 `

`
F K
%< K
K
\ sr*   