
import copy
import inspect
import unittest

import numpy as np
from huggingface_hub import hf_hub_download

from transformers import TimesformerConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
      import torch
      from torch import nn

      from transformers import (
          MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING,
          TimesformerForVideoClassification,
          TimesformerModel,
      )
      from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
      from transformers import VideoMAEImageProcessor



class 		UpperCamelCase__  :
   def __init__(self			: Dict ,    snake_case_			: Tuple ,    snake_case_			: int=1_3 ,    snake_case_			: List[Any]=1_0 ,    snake_case_			: List[str]=3 ,    snake_case_			: List[Any]=2 ,    snake_case_			: Optional[int]=2 ,    snake_case_			: Any=True ,    snake_case_			: Any=True ,    snake_case_			: Union[str, Any]=3_2 ,    snake_case_			: str=5 ,    snake_case_			: List[str]=4 ,    snake_case_			: str=3_7 ,    snake_case_			: List[str]="gelu" ,    snake_case_			: Tuple=0.1 ,    snake_case_			: str=0.1 ,    snake_case_			: Tuple=1_0 ,    snake_case_			: Dict=0.02 ,    snake_case_			: Tuple="divided_space_time" ,    snake_case_			: Union[str, Any]=None ,    ):
    __a			:  int		    =  parent
    __a			:  str		    =  batch_size
    __a			:  int		    =  image_size
    __a			:  List[Any]		    =  num_channels
    __a			:  List[Any]		    =  patch_size
    __a			:  List[Any]		    =  num_frames
    __a			:  Optional[int]		    =  is_training
    __a			:  List[str]		    =  use_labels
    __a			:  List[Any]		    =  hidden_size
    __a			:  Any		    =  num_hidden_layers
    __a			:  Tuple		    =  num_attention_heads
    __a			:  int		    =  intermediate_size
    __a			:  Optional[int]		    =  hidden_act
    __a			:  Optional[Any]		    =  hidden_dropout_prob
    __a			:  Union[str, Any]		    =  attention_probs_dropout_prob
    __a			:  Any		    =  attention_type
    __a			:  Any		    =  initializer_range
    __a			:  List[str]		    =  scope
    __a			:  Tuple		    =  num_labels

    # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token
    __a			:  Any		    =  (image_size // patch_size) ** 2
    __a			:  List[str]		    =  (num_frames) * self.num_patches_per_frame + 1
   def 				lowerCAmelCase      (self			: Dict       ):
    __a			:  Tuple		    =  floats_tensor(
        [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size]       )

    __a			:  Optional[Any]		    =  None
    if self.use_labels:
     __a			:  int		    =  ids_tensor([self.batch_size] ,    self.num_labels       )

    __a			:  Optional[Any]		    =  self.get_config()

    return config, pixel_values, labels
   def 				lowerCAmelCase      (self			: Optional[int]       ):
    __a			:  Union[str, Any]		    =  TimesformerConfig(
        image_size=self.image_size ,    patch_size=self.patch_size ,    num_channels=self.num_channels ,    num_frames=self.num_frames ,    hidden_size=self.hidden_size ,    num_hidden_layers=self.num_hidden_layers ,    num_attention_heads=self.num_attention_heads ,    intermediate_size=self.intermediate_size ,    hidden_act=self.hidden_act ,    hidden_dropout_prob=self.hidden_dropout_prob ,    attention_probs_dropout_prob=self.attention_probs_dropout_prob ,    initializer_range=self.initializer_range ,    attention_type=self.attention_type ,    )
    __a			:  Union[str, Any]		    =  self.num_labels
    return config
   def 				lowerCAmelCase      (self			: Any ,    snake_case_			: Dict ,    snake_case_			: Union[str, Any] ,    snake_case_			: Any       ):
    __a			:  Any		    =  TimesformerModel(config=snake_case_       )
    model.to(snake_case_       )
    model.eval()
    __a			:  Tuple		    =  model(snake_case_       )
    self.parent.assertEqual(result.last_hidden_state.shape ,    (self.batch_size, self.seq_length, self.hidden_size)       )
   def 				lowerCAmelCase      (self			: int ,    snake_case_			: List[Any] ,    snake_case_			: Union[str, Any] ,    snake_case_			: List[Any]       ):
    __a			:  Union[str, Any]		    =  TimesformerForVideoClassification(snake_case_       )
    model.to(snake_case_       )
    model.eval()

    __a			:  str		    =  model(snake_case_       )

    # verify the logits shape
    __a			:  Union[str, Any]		    =  torch.Size((self.batch_size, self.num_labels)       )
    self.parent.assertEqual(result.logits.shape ,    snake_case_       )







   def 				lowerCAmelCase      (self			: Optional[int]       ):
    __a			:  int		    =  self.prepare_config_and_inputs()
    __a    ,	__a    ,	__a			:  int		    =  config_and_inputs
    __a			:  Optional[int]		    =  {'''pixel_values''': pixel_values}
    return config, inputs_dict





@require_torch
class 		UpperCamelCase__  (	__lowercase   ,__lowercase   ,unittest.TestCase   ):
   _SCREAMING_SNAKE_CASE				:							Dict     	=				(TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else ()
   _SCREAMING_SNAKE_CASE				:							Any     	=				(
       {"feature-extraction": TimesformerModel, "video-classification": TimesformerForVideoClassification}
       if is_torch_available()
       else {}
   )

   _SCREAMING_SNAKE_CASE				:							Optional[Any]     	=				False
   _SCREAMING_SNAKE_CASE				:							int     	=				False
   _SCREAMING_SNAKE_CASE				:							Dict     	=				False
   _SCREAMING_SNAKE_CASE				:							str     	=				False
   def 				lowerCAmelCase      (self			: int       ):
    __a			:  List[str]		    =  TimesformerModelTester(self       )
    __a			:  Optional[Any]		    =  ConfigTester(
        self ,    config_class=snake_case_ ,    has_text_modality=snake_case_ ,    hidden_size=3_7       )
   def 				lowerCAmelCase      (self			: Tuple ,    snake_case_			: Optional[int] ,    snake_case_			: str ,    snake_case_			: Optional[int]=False       ):
    __a			:  Union[str, Any]		    =  copy.deepcopy(snake_case_       )

    if return_labels:
     if model_class in get_values(snake_case_       ):
      __a			:  Optional[Any]		    =  torch.zeros(
          self.model_tester.batch_size ,    dtype=torch.long ,    device=snake_case_       )

    return inputs_dict
   def 				lowerCAmelCase      (self			: Any       ):
    self.config_tester.run_common_tests()
   @unittest.skip(reason='''TimeSformer does not use inputs_embeds'''       )
   def 				lowerCAmelCase      (self			: Union[str, Any]       ):
    pass
   def 				lowerCAmelCase      (self			: Union[str, Any]       ):
    __a    ,	__a			:  int		    =  self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
     __a			:  List[Any]		    =  model_class(snake_case_       )
     self.assertIsInstance(model.get_input_embeddings() ,    (nn.Module)       )
     __a			:  Any		    =  model.get_output_embeddings()
     self.assertTrue(x is None or isinstance(snake_case_ ,    nn.Linear       )       )
   def 				lowerCAmelCase      (self			: int       ):
    __a    ,	__a			:  int		    =  self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
     __a			:  List[Any]		    =  model_class(snake_case_       )
     __a			:  Optional[int]		    =  inspect.signature(model.forward       )
     # signature.parameters is an OrderedDict => so arg_names order is deterministic
     __a			:  int		    =  [*signature.parameters.keys()]

     __a			:  int		    =  ['''pixel_values''']
     self.assertListEqual(arg_names[:1] ,    snake_case_       )
   def 				lowerCAmelCase      (self			: List[str]       ):
    __a			:  Union[str, Any]		    =  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*snake_case_       )
   def 				lowerCAmelCase      (self			: Dict       ):
    __a			:  List[str]		    =  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_video_classification(*snake_case_       )
   @slow
   def 				lowerCAmelCase      (self			: List[str]       ):
    for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     __a			:  List[Any]		    =  TimesformerModel.from_pretrained(snake_case_       )
     self.assertIsNotNone(snake_case_       )
   def 				lowerCAmelCase      (self			: Optional[Any]       ):
    if not self.has_attentions:
     pass

    else:
     __a    ,	__a			:  List[str]		    =  self.model_tester.prepare_config_and_inputs_for_common()
     __a			:  int		    =  True

     for model_class in self.all_model_classes:
      __a			:  List[str]		    =  self.model_tester.seq_length
      __a			:  Dict		    =  self.model_tester.num_frames

      __a			:  Any		    =  True
      __a			:  int		    =  False
      __a			:  Tuple		    =  True
      __a			:  Optional[int]		    =  model_class(snake_case_       )
      model.to(snake_case_       )
      model.eval()
      with torch.no_grad():
       __a			:  Optional[Any]		    =  model(**self._prepare_for_class(snake_case_ ,    snake_case_       )       )
      __a			:  Union[str, Any]		    =  outputs.attentions
      self.assertEqual(len(snake_case_       ) ,    self.model_tester.num_hidden_layers       )

      # check that output_attentions also work using config
      del inputs_dict["output_attentions"]
      __a			:  Any		    =  True
      __a			:  Optional[Any]		    =  model_class(snake_case_       )
      model.to(snake_case_       )
      model.eval()
      with torch.no_grad():
       __a			:  int		    =  model(**self._prepare_for_class(snake_case_ ,    snake_case_       )       )
      __a			:  Any		    =  outputs.attentions
      self.assertEqual(len(snake_case_       ) ,    self.model_tester.num_hidden_layers       )

      # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1)
      self.assertListEqual(
          list(attentions[0].shape[-3:]       ) ,    [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] ,    )
      __a			:  Union[str, Any]		    =  len(snake_case_       )

      # Check attention is always last and order is fine
      __a			:  Dict		    =  True
      __a			:  List[Any]		    =  True
      __a			:  Any		    =  model_class(snake_case_       )
      model.to(snake_case_       )
      model.eval()
      with torch.no_grad():
       __a			:  Any		    =  model(**self._prepare_for_class(snake_case_ ,    snake_case_       )       )

      self.assertEqual(out_len + 1 ,    len(snake_case_       )       )

      __a			:  List[Any]		    =  outputs.attentions

      self.assertEqual(len(snake_case_       ) ,    self.model_tester.num_hidden_layers       )

      # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1)
      self.assertListEqual(
          list(self_attentions[0].shape[-3:]       ) ,    [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] ,    )







   def 				lowerCAmelCase      (self			: Union[str, Any]       ):
    def check_hidden_states_output(snake_case_			: int ,    snake_case_			: Tuple ,    snake_case_			: int       ):
     __a			:  int		    =  model_class(snake_case_       )
     model.to(snake_case_       )
     model.eval()

     with torch.no_grad():
      __a			:  Optional[int]		    =  model(**self._prepare_for_class(snake_case_ ,    snake_case_       )       )

     __a			:  List[str]		    =  outputs.hidden_states
     __a			:  Any		    =  self.model_tester.num_hidden_layers + 1
     self.assertEqual(len(snake_case_       ) ,    snake_case_       )

     __a			:  Dict		    =  self.model_tester.seq_length

     self.assertListEqual(
         list(hidden_states[0].shape[-2:]       ) ,    [seq_length, self.model_tester.hidden_size] ,    )

    __a    ,	__a			:  List[Any]		    =  self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
     __a			:  Optional[int]		    =  True
     check_hidden_states_output(snake_case_ ,    snake_case_ ,    snake_case_       )

     # check that output_hidden_states also work using config
     del inputs_dict["output_hidden_states"]
     __a			:  List[Any]		    =  True

     check_hidden_states_output(snake_case_ ,    snake_case_ ,    snake_case_       )





def        __UpperCamelCase					(    ):
 __a			:  Optional[int]		    =  hf_hub_download(
     repo_id='''hf-internal-testing/spaghetti-video'''  ,       filename='''eating_spaghetti.npy'''  ,       repo_type='''dataset'''  )
 __a			:  int		    =  np.load(lowerCAmelCase__  )
 return list(lowerCAmelCase__  )



@require_torch
@require_vision
class 		UpperCamelCase__  (	unittest.TestCase   ):
   @cached_property
   def 				lowerCAmelCase      (self			: Tuple       ):
    # logits were tested with a different mean and std, so we use the same here
    return (
        VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] ,    image_std=[0.5, 0.5, 0.5]       )
        if is_vision_available()
        else None
    )







   @slow
   def 				lowerCAmelCase      (self			: str       ):
    __a			:  Optional[Any]		    =  TimesformerForVideoClassification.from_pretrained('''facebook/timesformer-base-finetuned-k400'''       ).to(
        snake_case_       )

    __a			:  int		    =  self.default_image_processor
    __a			:  Dict		    =  prepare_video()
    __a			:  int		    =  image_processor(video[:8] ,    return_tensors='''pt'''       ).to(snake_case_       )

    # forward pass
    with torch.no_grad():
     __a			:  List[Any]		    =  model(**snake_case_       )

    # verify the logits
    __a			:  List[Any]		    =  torch.Size((1, 4_0_0)       )
    self.assertEqual(outputs.logits.shape ,    snake_case_       )

    __a			:  str		    =  torch.tensor([-0.3016, -0.7713, -0.4205]       ).to(snake_case_       )

    self.assertTrue(torch.allclose(outputs.logits[0, :3] ,    snake_case_ ,    atol=1E-4       )       )


from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available


lowercase__          ={
    'configuration_data2vec_audio': ['DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Data2VecAudioConfig'],
    'configuration_data2vec_text': [
        'DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP',
        'Data2VecTextConfig',
        'Data2VecTextOnnxConfig',
    ],
    'configuration_data2vec_vision': [
        'DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP',
        'Data2VecVisionConfig',
        'Data2VecVisionOnnxConfig',
    ],
}

try:
      if not is_torch_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      lowercase__          =[
          'DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST',
          'Data2VecAudioForAudioFrameClassification',
          'Data2VecAudioForCTC',
          'Data2VecAudioForSequenceClassification',
          'Data2VecAudioForXVector',
          'Data2VecAudioModel',
          'Data2VecAudioPreTrainedModel',
      ]
      lowercase__          =[
          'DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST',
          'Data2VecTextForCausalLM',
          'Data2VecTextForMaskedLM',
          'Data2VecTextForMultipleChoice',
          'Data2VecTextForQuestionAnswering',
          'Data2VecTextForSequenceClassification',
          'Data2VecTextForTokenClassification',
          'Data2VecTextModel',
          'Data2VecTextPreTrainedModel',
      ]
      lowercase__          =[
          'DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST',
          'Data2VecVisionForImageClassification',
          'Data2VecVisionForMaskedImageModeling',
          'Data2VecVisionForSemanticSegmentation',
          'Data2VecVisionModel',
          'Data2VecVisionPreTrainedModel',
      ]

if is_tf_available():
      lowercase__          =[
          'TFData2VecVisionForImageClassification',
          'TFData2VecVisionForSemanticSegmentation',
          'TFData2VecVisionModel',
          'TFData2VecVisionPreTrainedModel',
      ]

if TYPE_CHECKING:
      from .configuration_dataavec_audio import DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecAudioConfig
      from .configuration_dataavec_text import (
          DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP,
          DataaVecTextConfig,
          DataaVecTextOnnxConfig,
      )
      from .configuration_dataavec_vision import (
          DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP,
          DataaVecVisionConfig,
          DataaVecVisionOnnxConfig,
      )

      try:
            if not is_torch_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_dataavec_audio import (
                DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST,
                DataaVecAudioForAudioFrameClassification,
                DataaVecAudioForCTC,
                DataaVecAudioForSequenceClassification,
                DataaVecAudioForXVector,
                DataaVecAudioModel,
                DataaVecAudioPreTrainedModel,
            )
            from .modeling_dataavec_text import (
                DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST,
                DataaVecTextForCausalLM,
                DataaVecTextForMaskedLM,
                DataaVecTextForMultipleChoice,
                DataaVecTextForQuestionAnswering,
                DataaVecTextForSequenceClassification,
                DataaVecTextForTokenClassification,
                DataaVecTextModel,
                DataaVecTextPreTrainedModel,
            )
            from .modeling_dataavec_vision import (
                DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST,
                DataaVecVisionForImageClassification,
                DataaVecVisionForMaskedImageModeling,
                DataaVecVisionForSemanticSegmentation,
                DataaVecVisionModel,
                DataaVecVisionPreTrainedModel,
            )
      if is_tf_available():
            from .modeling_tf_dataavec_vision import (
                TFDataaVecVisionForImageClassification,
                TFDataaVecVisionForSemanticSegmentation,
                TFDataaVecVisionModel,
                TFDataaVecVisionPreTrainedModel,
            )

else:
      import sys

      lowercase__          =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
