





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 					__snake_case	:


    '''simple docstring'''







    def __init__(       self   ,				A_   ,				A_=13   ,				A_=10   ,				A_=3   ,				A_=2   ,				A_=2   ,				A_=True   ,				A_=True   ,				A_=32   ,				A_=5   ,				A_=4   ,				A_=37   ,				A_="gelu"   ,				A_=0.1   ,				A_=0.1   ,				A_=10   ,				A_=0.02   ,				A_="divided_space_time"   ,				A_=None   ,				):





        '''simple docstring'''

        SCREAMING_SNAKE_CASE__											=			parent
        SCREAMING_SNAKE_CASE__											=			batch_size
        SCREAMING_SNAKE_CASE__											=			image_size
        SCREAMING_SNAKE_CASE__											=			num_channels
        SCREAMING_SNAKE_CASE__											=			patch_size
        SCREAMING_SNAKE_CASE__											=			num_frames
        SCREAMING_SNAKE_CASE__											=			is_training
        SCREAMING_SNAKE_CASE__											=			use_labels
        SCREAMING_SNAKE_CASE__											=			hidden_size
        SCREAMING_SNAKE_CASE__											=			num_hidden_layers
        SCREAMING_SNAKE_CASE__											=			num_attention_heads
        SCREAMING_SNAKE_CASE__											=			intermediate_size
        SCREAMING_SNAKE_CASE__											=			hidden_act
        SCREAMING_SNAKE_CASE__											=			hidden_dropout_prob
        SCREAMING_SNAKE_CASE__											=			attention_probs_dropout_prob
        SCREAMING_SNAKE_CASE__											=			attention_type
        SCREAMING_SNAKE_CASE__											=			initializer_range
        SCREAMING_SNAKE_CASE__											=			scope
        SCREAMING_SNAKE_CASE__											=			num_labels

        # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token
        SCREAMING_SNAKE_CASE__											=			(image_size // patch_size) ** 2
        SCREAMING_SNAKE_CASE__											=			(num_frames) * self.num_patches_per_frame + 1



    def  lowercase_					(       self     ):





        '''simple docstring'''

        SCREAMING_SNAKE_CASE__											=			floats_tensor(
            [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size]     )

        SCREAMING_SNAKE_CASE__											=			None
        if self.use_labels:
            SCREAMING_SNAKE_CASE__											=			ids_tensor([self.batch_size]   ,				self.num_labels     )

        SCREAMING_SNAKE_CASE__											=			self.get_config()

        return config, pixel_values, labels



    def  lowercase_					(       self     ):





        '''simple docstring'''

        SCREAMING_SNAKE_CASE__											=			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   ,				)
        SCREAMING_SNAKE_CASE__											=			self.num_labels
        return config



    def  lowercase_					(       self   ,				A_   ,				A_   ,				A_     ):





        '''simple docstring'''

        SCREAMING_SNAKE_CASE__											=			TimesformerModel(config=A_     )
        model.to(A_     )
        model.eval()
        SCREAMING_SNAKE_CASE__											=			model(A_     )
        self.parent.assertEqual(result.last_hidden_state.shape   ,				(self.batch_size, self.seq_length, self.hidden_size)     )



    def  lowercase_					(       self   ,				A_   ,				A_   ,				A_     ):





        '''simple docstring'''

        SCREAMING_SNAKE_CASE__											=			TimesformerForVideoClassification(A_     )
        model.to(A_     )
        model.eval()

        SCREAMING_SNAKE_CASE__											=			model(A_     )

        # verify the logits shape
        SCREAMING_SNAKE_CASE__											=			torch.Size((self.batch_size, self.num_labels)     )
        self.parent.assertEqual(result.logits.shape   ,				A_     )




    def  lowercase_					(       self     ):





        '''simple docstring'''

        SCREAMING_SNAKE_CASE__											=			self.prepare_config_and_inputs()
        SCREAMING_SNAKE_CASE__				,		SCREAMING_SNAKE_CASE__				,		SCREAMING_SNAKE_CASE__											=			config_and_inputs
        SCREAMING_SNAKE_CASE__											=			{'''pixel_values''': pixel_values}
        return config, inputs_dict





@require_torch
class 					__snake_case	(  __SCREAMING_SNAKE_CASE			,     __SCREAMING_SNAKE_CASE			,     unittest.TestCase    ):


    '''simple docstring'''







    lowerCamelCase__    :		List[Any]				=	(TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else ()
    lowerCamelCase__    :		Optional[int]				=	(
        {"""feature-extraction""": TimesformerModel, """video-classification""": TimesformerForVideoClassification}
        if is_torch_available()
        else {}
    )

    lowerCamelCase__    :		List[str]				=	False
    lowerCamelCase__    :		Any				=	False
    lowerCamelCase__    :		Union[str, Any]				=	False
    lowerCamelCase__    :		Dict				=	False



    def  lowercase_					(       self     ):





        '''simple docstring'''

        SCREAMING_SNAKE_CASE__											=			TimesformerModelTester(self     )
        SCREAMING_SNAKE_CASE__											=			ConfigTester(
            self   ,				config_class=A_   ,				has_text_modality=A_   ,				hidden_size=37     )



    def  lowercase_					(       self   ,				A_   ,				A_   ,				A_=False     ):





        '''simple docstring'''

        SCREAMING_SNAKE_CASE__											=			copy.deepcopy(A_     )

        if return_labels:
            if model_class in get_values(A_     ):
                SCREAMING_SNAKE_CASE__											=			torch.zeros(
                    self.model_tester.batch_size   ,				dtype=torch.long   ,				device=A_     )

        return inputs_dict



    def  lowercase_					(       self     ):





        '''simple docstring'''

        self.config_tester.run_common_tests()



    @unittest.skip(reason='''TimeSformer does not use inputs_embeds'''     )
    def  lowercase_					(       self     ):





        '''simple docstring'''

        pass



    def  lowercase_					(       self     ):





        '''simple docstring'''

        SCREAMING_SNAKE_CASE__				,		SCREAMING_SNAKE_CASE__											=			self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
            SCREAMING_SNAKE_CASE__											=			model_class(A_     )
            self.assertIsInstance(model.get_input_embeddings()   ,				(nn.Module)     )
            SCREAMING_SNAKE_CASE__											=			model.get_output_embeddings()
            self.assertTrue(x is None or isinstance(A_   ,				nn.Linear     )     )



    def  lowercase_					(       self     ):





        '''simple docstring'''

        SCREAMING_SNAKE_CASE__				,		SCREAMING_SNAKE_CASE__											=			self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
            SCREAMING_SNAKE_CASE__											=			model_class(A_     )
            SCREAMING_SNAKE_CASE__											=			inspect.signature(model.forward     )
            # signature.parameters is an OrderedDict => so arg_names order is deterministic
            SCREAMING_SNAKE_CASE__											=			[*signature.parameters.keys()]

            SCREAMING_SNAKE_CASE__											=			['''pixel_values''']
            self.assertListEqual(arg_names[:1]   ,				A_     )



    def  lowercase_					(       self     ):





        '''simple docstring'''

        SCREAMING_SNAKE_CASE__											=			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*A_     )



    def  lowercase_					(       self     ):





        '''simple docstring'''

        SCREAMING_SNAKE_CASE__											=			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_video_classification(*A_     )



    @slow
    def  lowercase_					(       self     ):





        '''simple docstring'''

        for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            SCREAMING_SNAKE_CASE__											=			TimesformerModel.from_pretrained(A_     )
            self.assertIsNotNone(A_     )



    def  lowercase_					(       self     ):





        '''simple docstring'''

        if not self.has_attentions:
            pass

        else:
            SCREAMING_SNAKE_CASE__				,		SCREAMING_SNAKE_CASE__											=			self.model_tester.prepare_config_and_inputs_for_common()
            SCREAMING_SNAKE_CASE__											=			True

            for model_class in self.all_model_classes:
                SCREAMING_SNAKE_CASE__											=			self.model_tester.seq_length
                SCREAMING_SNAKE_CASE__											=			self.model_tester.num_frames

                SCREAMING_SNAKE_CASE__											=			True
                SCREAMING_SNAKE_CASE__											=			False
                SCREAMING_SNAKE_CASE__											=			True
                SCREAMING_SNAKE_CASE__											=			model_class(A_     )
                model.to(A_     )
                model.eval()
                with torch.no_grad():
                    SCREAMING_SNAKE_CASE__											=			model(**self._prepare_for_class(A_   ,				A_     )     )
                SCREAMING_SNAKE_CASE__											=			outputs.attentions
                self.assertEqual(len(A_     )   ,				self.model_tester.num_hidden_layers     )

                # check that output_attentions also work using config
                del inputs_dict["output_attentions"]
                SCREAMING_SNAKE_CASE__											=			True
                SCREAMING_SNAKE_CASE__											=			model_class(A_     )
                model.to(A_     )
                model.eval()
                with torch.no_grad():
                    SCREAMING_SNAKE_CASE__											=			model(**self._prepare_for_class(A_   ,				A_     )     )
                SCREAMING_SNAKE_CASE__											=			outputs.attentions
                self.assertEqual(len(A_     )   ,				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]   ,				)
                SCREAMING_SNAKE_CASE__											=			len(A_     )

                # Check attention is always last and order is fine
                SCREAMING_SNAKE_CASE__											=			True
                SCREAMING_SNAKE_CASE__											=			True
                SCREAMING_SNAKE_CASE__											=			model_class(A_     )
                model.to(A_     )
                model.eval()
                with torch.no_grad():
                    SCREAMING_SNAKE_CASE__											=			model(**self._prepare_for_class(A_   ,				A_     )     )

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

                SCREAMING_SNAKE_CASE__											=			outputs.attentions

                self.assertEqual(len(A_     )   ,				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  lowercase_					(       self     ):





        '''simple docstring'''

        def check_hidden_states_output(A_   ,				A_   ,				A_     ):
            SCREAMING_SNAKE_CASE__											=			model_class(A_     )
            model.to(A_     )
            model.eval()

            with torch.no_grad():
                SCREAMING_SNAKE_CASE__											=			model(**self._prepare_for_class(A_   ,				A_     )     )

            SCREAMING_SNAKE_CASE__											=			outputs.hidden_states
            SCREAMING_SNAKE_CASE__											=			self.model_tester.num_hidden_layers + 1
            self.assertEqual(len(A_     )   ,				A_     )

            SCREAMING_SNAKE_CASE__											=			self.model_tester.seq_length

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

        SCREAMING_SNAKE_CASE__				,		SCREAMING_SNAKE_CASE__											=			self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
            SCREAMING_SNAKE_CASE__											=			True
            check_hidden_states_output(A_   ,				A_   ,				A_     )

            # check that output_hidden_states also work using config
            del inputs_dict["output_hidden_states"]
            SCREAMING_SNAKE_CASE__											=			True

            check_hidden_states_output(A_   ,				A_   ,				A_     )





def 							__snake_case							(    )				->						Optional[Any]:
    SCREAMING_SNAKE_CASE__											=			hf_hub_download(
        repo_id='''hf-internal-testing/spaghetti-video''' ,							filename='''eating_spaghetti.npy''' ,							repo_type='''dataset'''	)
    SCREAMING_SNAKE_CASE__											=			np.load(lowerCAmelCase_	)
    return list(lowerCAmelCase_	)



@require_torch
@require_vision
class 					__snake_case	(  unittest.TestCase    ):


    '''simple docstring'''







    @cached_property
    def  lowercase_					(       self     ):





        '''simple docstring'''

        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  lowercase_					(       self     ):





        '''simple docstring'''

        SCREAMING_SNAKE_CASE__											=			TimesformerForVideoClassification.from_pretrained('''facebook/timesformer-base-finetuned-k400'''     ).to(
            A_     )

        SCREAMING_SNAKE_CASE__											=			self.default_image_processor
        SCREAMING_SNAKE_CASE__											=			prepare_video()
        SCREAMING_SNAKE_CASE__											=			image_processor(video[:8]   ,				return_tensors='''pt'''     ).to(A_     )

        # forward pass
        with torch.no_grad():
            SCREAMING_SNAKE_CASE__											=			model(**A_     )

        # verify the logits
        SCREAMING_SNAKE_CASE__											=			torch.Size((1, 4_00)     )
        self.assertEqual(outputs.logits.shape   ,				A_     )

        SCREAMING_SNAKE_CASE__											=			torch.tensor([-0.3016, -0.7713, -0.4205]     ).to(A_     )

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




from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


__snake_case   							=						logging.get_logger(__name__)

__snake_case   							=						{
    '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/config.json''',
    '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/config.json''',
    '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/config.json''',
    '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/config.json''',
    '''bert-base-multilingual-uncased''': '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/config.json''',
    '''bert-base-multilingual-cased''': '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/config.json''',
    '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/config.json''',
    '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/config.json''',
    '''bert-large-uncased-whole-word-masking''': (
        '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/config.json'''
    ),
    '''bert-large-cased-whole-word-masking''': (
        '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/config.json'''
    ),
    '''bert-large-uncased-whole-word-masking-finetuned-squad''': (
        '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/config.json'''
    ),
    '''bert-large-cased-whole-word-masking-finetuned-squad''': (
        '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/config.json'''
    ),
    '''bert-base-cased-finetuned-mrpc''': '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/config.json''',
    '''bert-base-german-dbmdz-cased''': '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/config.json''',
    '''bert-base-german-dbmdz-uncased''': '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/config.json''',
    '''cl-tohoku/bert-base-japanese''': '''https://huggingface.co/cl-tohoku/bert-base-japanese/resolve/main/config.json''',
    '''cl-tohoku/bert-base-japanese-whole-word-masking''': (
        '''https://huggingface.co/cl-tohoku/bert-base-japanese-whole-word-masking/resolve/main/config.json'''
    ),
    '''cl-tohoku/bert-base-japanese-char''': (
        '''https://huggingface.co/cl-tohoku/bert-base-japanese-char/resolve/main/config.json'''
    ),
    '''cl-tohoku/bert-base-japanese-char-whole-word-masking''': (
        '''https://huggingface.co/cl-tohoku/bert-base-japanese-char-whole-word-masking/resolve/main/config.json'''
    ),
    '''TurkuNLP/bert-base-finnish-cased-v1''': (
        '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/config.json'''
    ),
    '''TurkuNLP/bert-base-finnish-uncased-v1''': (
        '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/config.json'''
    ),
    '''wietsedv/bert-base-dutch-cased''': '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/config.json''',
    # See all BERT models at https://huggingface.co/models?filter=bert
}



class 	__lowerCamelCase			(_a						):
       _lowercase											=     """bert"""







       def __init__(			self: Any,A_: Dict=3_0522,A_: Optional[Any]=768,A_: Union[str, Any]=12,A_: List[Any]=12,A_: Optional[int]=3072,A_: Union[str, Any]="gelu",A_: List[str]=0.1,A_: Dict=0.1,A_: Optional[int]=512,A_: Optional[Any]=2,A_: Union[str, Any]=0.0_2,A_: List[Any]=1E-12,A_: Optional[int]=0,A_: List[Any]="absolute",A_: str=True,A_: Union[str, Any]=None,**A_: int,):






            '''simple docstring'''




            super().__init__(pad_token_id=A_,**A_					)

            __UpperCamelCase =			vocab_size
            __UpperCamelCase =			hidden_size
            __UpperCamelCase =			num_hidden_layers
            __UpperCamelCase =			num_attention_heads
            __UpperCamelCase =			hidden_act
            __UpperCamelCase =			intermediate_size
            __UpperCamelCase =			hidden_dropout_prob
            __UpperCamelCase =			attention_probs_dropout_prob
            __UpperCamelCase =			max_position_embeddings
            __UpperCamelCase =			type_vocab_size
            __UpperCamelCase =			initializer_range
            __UpperCamelCase =			layer_norm_eps
            __UpperCamelCase =			position_embedding_type
            __UpperCamelCase =			use_cache
            __UpperCamelCase =			classifier_dropout



class 	__lowerCamelCase			(_a						):







       @property
       def 		snake_case_	(			self: Optional[int]					):






            '''simple docstring'''




            if self.task == "multiple-choice":
                 __UpperCamelCase =			{0: 'batch', 1: 'choice', 2: 'sequence'}
            else:
                 __UpperCamelCase =			{0: 'batch', 1: 'sequence'}
            return OrderedDict(
                [
                    ('input_ids', dynamic_axis),
                    ('attention_mask', dynamic_axis),
                    ('token_type_ids', dynamic_axis),
                ]					)


