'''simple docstring'''





import copy
import inspect
import unittest

import numpy as np
from huggingface_hub import hf_hub_download

from transformers import VivitConfig
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


if is_torch_available():
     import torch
     from torch import nn

     from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VivitForVideoClassification, VivitModel
     from transformers.models.vivit.modeling_vivit import VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
     from transformers import VivitImageProcessor







class 			__snake_case   :
 def __init__(  self		,   snake_case__		,   snake_case__=2		,   snake_case__=True		,   snake_case__=True		,   snake_case__=10		,   snake_case__=10		,   snake_case__=8		,   snake_case__=[2, 4, 4]		,   snake_case__=3		,   snake_case__=768		,   snake_case__=5		,   snake_case__=4		,   snake_case__=37		,   snake_case__="gelu_fast"		,   snake_case__=0.0		,   snake_case__=0.0		,   snake_case__=0.02		,   snake_case__=1e-06		,   snake_case__=True		,   snake_case__=None		,   )	->							Optional[int]:
       '''simple docstring'''





       UpperCAmelCase    : int      =parent
       UpperCAmelCase    : int      =batch_size
       UpperCAmelCase    : Any      =is_training
       UpperCAmelCase    : Tuple      =use_labels
       UpperCAmelCase    : List[str]      =num_labels
       UpperCAmelCase    : Optional[int]      =image_size
       UpperCAmelCase    : Optional[int]      =num_frames
       UpperCAmelCase    : Any      =tubelet_size
       UpperCAmelCase    : List[Any]      =num_channels
       UpperCAmelCase    : Dict      =hidden_size
       UpperCAmelCase    : Dict      =num_hidden_layers
       UpperCAmelCase    : Union[str, Any]      =num_attention_heads
       UpperCAmelCase    : Optional[int]      =intermediate_size
       UpperCAmelCase    : Optional[Any]      =hidden_act
       UpperCAmelCase    : List[str]      =hidden_dropout_prob
       UpperCAmelCase    : Union[str, Any]      =attention_probs_dropout_prob
       UpperCAmelCase    : Dict      =initializer_range
       UpperCAmelCase    : Tuple      =layer_norm_eps
       UpperCAmelCase    : Dict      =qkv_bias
       UpperCAmelCase    : Optional[int]      =scope

       UpperCAmelCase    : int      =(
           (self.image_size // self.tubelet_size[2])
           * (self.image_size // self.tubelet_size[1])
           * (self.num_frames // self.tubelet_size[0])
       ) + 1  # CLS token
 def 	UpperCAmelCase__       (  self						)	->							Dict:
       '''simple docstring'''





       UpperCAmelCase    : str      =floats_tensor(
           [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size]						)

       UpperCAmelCase    : Tuple      =None
       if self.use_labels:
             UpperCAmelCase    : List[str]      =ids_tensor([self.batch_size]		,   self.num_labels						)

       UpperCAmelCase    : str      =self.get_config()

       return config, pixel_values, labels
 def 	UpperCAmelCase__       (  self						)	->							Tuple:
       '''simple docstring'''





       UpperCAmelCase    : Optional[Any]      =VivitConfig(
           num_frames=self.num_frames		,   image_size=self.image_size		,   tubelet_size=self.tubelet_size		,   num_channels=self.num_channels		,   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		,   layer_norm_eps=self.layer_norm_eps		,   qkv_bias=self.qkv_bias		,   )
       UpperCAmelCase    : str      =self.num_labels
       return config
 def 	UpperCAmelCase__       (  self		,   snake_case__		,   snake_case__		,   snake_case__						)	->							Optional[int]:
       '''simple docstring'''





       UpperCAmelCase    : Optional[Any]      =VivitModel(config=snake_case__						)
       model.to(snake_case__						)
       model.eval()
       UpperCAmelCase    : Dict      =model(snake_case__						)
       self.parent.assertEqual(result.last_hidden_state.shape		,   (self.batch_size, self.seq_length, self.hidden_size)						)
 def 	UpperCAmelCase__       (  self		,   snake_case__		,   snake_case__		,   snake_case__						)	->							Optional[int]:
       '''simple docstring'''





       UpperCAmelCase    : Dict      =VivitForVideoClassification(snake_case__						)
       model.to(snake_case__						)
       model.eval()

       UpperCAmelCase    : Optional[Any]      =model(snake_case__						)

       # verify the logits shape
       UpperCAmelCase    : List[str]      =torch.Size((self.batch_size, self.num_labels)						)
       self.parent.assertEqual(result.logits.shape		,   snake_case__						)






 def 	UpperCAmelCase__       (  self						)	->							Tuple:
       '''simple docstring'''





       UpperCAmelCase    : Any      =self.prepare_config_and_inputs()
       UpperCAmelCase  ,						UpperCAmelCase  ,						UpperCAmelCase    : str      =config_and_inputs
       UpperCAmelCase    : Optional[Any]      ={'''pixel_values''': pixel_values}
       return config, inputs_dict







@require_torch
class 			__snake_case   (     lowercase_					,   unittest.TestCase   ):
 __lowerCamelCase    :   List[str]     =      (VivitModel, VivitForVideoClassification) if is_torch_available() else ()

 __lowerCamelCase    :   Tuple     =      False
 __lowerCamelCase    :   Optional[Any]     =      False
 __lowerCamelCase    :   str     =      False
 __lowerCamelCase    :   Any     =      False
 def 	UpperCAmelCase__       (  self						)	->							Optional[Any]:
       '''simple docstring'''





       UpperCAmelCase    : Tuple      =VivitModelTester(self						)
       UpperCAmelCase    : Any      =ConfigTester(self		,   config_class=snake_case__		,   has_text_modality=snake_case__		,   hidden_size=37						)
 def 	UpperCAmelCase__       (  self		,   snake_case__		,   snake_case__		,   snake_case__=False						)	->							Any:
       '''simple docstring'''





       UpperCAmelCase    : int      =copy.deepcopy(snake_case__						)

       if return_labels:
             if model_class in get_values(snake_case__						):
                   UpperCAmelCase    : List[str]      =torch.zeros(
                       self.model_tester.batch_size		,   dtype=torch.long		,   device=snake_case__						)

       return inputs_dict
 def 	UpperCAmelCase__       (  self						)	->							Optional[Any]:
       '''simple docstring'''





       self.config_tester.run_common_tests()
 @unittest.skip(reason='''Vivit does not use inputs_embeds'''						)
 def 	UpperCAmelCase__       (  self						)	->							Optional[Any]:
       '''simple docstring'''





       pass
 def 	UpperCAmelCase__       (  self						)	->							str:
       '''simple docstring'''





       UpperCAmelCase  ,						UpperCAmelCase    : int      =self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
             UpperCAmelCase    : List[Any]      =model_class(snake_case__						)
             self.assertIsInstance(model.get_input_embeddings()		,   (nn.Module)						)
             UpperCAmelCase    : List[Any]      =model.get_output_embeddings()
             self.assertTrue(x is None or isinstance(snake_case__		,   nn.Linear						)						)
 def 	UpperCAmelCase__       (  self						)	->							List[str]:
       '''simple docstring'''





       UpperCAmelCase  ,						UpperCAmelCase    : Dict      =self.model_tester.prepare_config_and_inputs_for_common()

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

             UpperCAmelCase    : Union[str, Any]      =['''pixel_values''', '''head_mask''']
             self.assertListEqual(arg_names[:2]		,   snake_case__						)
 def 	UpperCAmelCase__       (  self						)	->							Union[str, Any]:
       '''simple docstring'''





       UpperCAmelCase    : int      =self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*snake_case__						)
 def 	UpperCAmelCase__       (  self						)	->							Tuple:
       '''simple docstring'''





       UpperCAmelCase    : Any      =self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_video_classification(*snake_case__						)
 @slow
 def 	UpperCAmelCase__       (  self						)	->							Dict:
       '''simple docstring'''





       for model_name in VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             UpperCAmelCase    : Dict      =VivitModel.from_pretrained(snake_case__						)
             self.assertIsNotNone(snake_case__						)
 def 	UpperCAmelCase__       (  self						)	->							Union[str, Any]:
       '''simple docstring'''





       UpperCAmelCase  ,						UpperCAmelCase    : str      =self.model_tester.prepare_config_and_inputs_for_common()
       UpperCAmelCase    : List[Any]      =True

       for model_class in self.all_model_classes:
             UpperCAmelCase    : int      =self.model_tester.seq_length

             UpperCAmelCase    : int      =True
             UpperCAmelCase    : Any      =False
             UpperCAmelCase    : Union[str, Any]      =True
             UpperCAmelCase    : Union[str, Any]      =model_class(snake_case__						)
             model.to(snake_case__						)
             model.eval()
             with torch.no_grad():
                   UpperCAmelCase    : List[str]      =model(**self._prepare_for_class(snake_case__		,   snake_case__						)						)
             UpperCAmelCase    : List[str]      =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"]
             UpperCAmelCase    : Any      =True
             UpperCAmelCase    : Optional[int]      =model_class(snake_case__						)
             model.to(snake_case__						)
             model.eval()
             with torch.no_grad():
                   UpperCAmelCase    : Union[str, Any]      =model(**self._prepare_for_class(snake_case__		,   snake_case__						)						)
             UpperCAmelCase    : Optional[int]      =outputs.attentions
             self.assertEqual(len(snake_case__						)		,   self.model_tester.num_hidden_layers						)

             self.assertListEqual(
                 list(attentions[0].shape[-3:]						)		,   [self.model_tester.num_attention_heads, seq_len, seq_len]		,   )
             UpperCAmelCase    : List[Any]      =len(snake_case__						)

             # Check attention is always last and order is fine
             UpperCAmelCase    : int      =True
             UpperCAmelCase    : Any      =True
             UpperCAmelCase    : int      =model_class(snake_case__						)
             model.to(snake_case__						)
             model.eval()
             with torch.no_grad():
                   UpperCAmelCase    : str      =model(**self._prepare_for_class(snake_case__		,   snake_case__						)						)

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

             UpperCAmelCase    : Optional[int]      =outputs.attentions

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

             self.assertListEqual(
                 list(self_attentions[0].shape[-3:]						)		,   [self.model_tester.num_attention_heads, seq_len, seq_len]		,   )
 def 	UpperCAmelCase__       (  self						)	->							Optional[Any]:
       '''simple docstring'''





       def check_hidden_states_output(snake_case__		,   snake_case__		,   snake_case__						):
             UpperCAmelCase    : Tuple      =model_class(snake_case__						)
             model.to(snake_case__						)
             model.eval()

             with torch.no_grad():
                   UpperCAmelCase    : Union[str, Any]      =model(**self._prepare_for_class(snake_case__		,   snake_case__						)						)

             UpperCAmelCase    : List[str]      =outputs.hidden_states
             UpperCAmelCase    : Tuple      =self.model_tester.num_hidden_layers + 1
             self.assertEqual(len(snake_case__						)		,   snake_case__						)

             UpperCAmelCase    : Optional[int]      =self.model_tester.seq_length

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

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

       for model_class in self.all_model_classes:
             UpperCAmelCase    : Any      =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"]
             UpperCAmelCase    : Any      =True

             check_hidden_states_output(snake_case__		,   snake_case__		,   snake_case__						)






 @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''						)
 def 	UpperCAmelCase__       (  self						)	->							Tuple:
       '''simple docstring'''





       pass





def   lowerCAmelCase_ (				)->  List[Any]:






      '''simple docstring'''





      UpperCAmelCase    : str      =hf_hub_download(
          repo_id='''hf-internal-testing/spaghetti-video'''		,					filename='''eating_spaghetti_32_frames.npy'''		,					repo_type='''dataset'''						)
      UpperCAmelCase    : Optional[int]      =np.load(__lowerCAmelCase						)
      return list(__lowerCAmelCase						)







@require_torch
@require_vision
class 			__snake_case   (     unittest.TestCase   ):
 @cached_property
 def 	UpperCAmelCase__       (  self						)	->							int:
       '''simple docstring'''





       return VivitImageProcessor() if is_vision_available() else None






 @slow
 def 	UpperCAmelCase__       (  self						)	->							Union[str, Any]:
       '''simple docstring'''





       UpperCAmelCase    : str      =VivitForVideoClassification.from_pretrained('''google/vivit-b-16x2-kinetics400'''						).to(snake_case__						)

       UpperCAmelCase    : Dict      =self.default_image_processor
       UpperCAmelCase    : int      =prepare_video()
       UpperCAmelCase    : str      =image_processor(snake_case__		,   return_tensors='''pt'''						).to(snake_case__						)

       # forward pass
       with torch.no_grad():
             UpperCAmelCase    : Any      =model(**snake_case__						)

       # verify the logits
       UpperCAmelCase    : Union[str, Any]      =torch.Size((1, 400)						)
       self.assertEqual(outputs.logits.shape		,   snake_case__						)

       # taken from original model
       UpperCAmelCase    : List[Any]      =torch.tensor([-1.0543, 2.0764, -0.2104, 0.4439, -0.9658]						).to(snake_case__						)

       self.assertTrue(torch.allclose(outputs.logits[0, :5]		,   snake_case__		,   atol=1e-4						)						)

import json
import os
import tempfile
import unittest

from transformers.modelcard import ModelCard







class 			__snake_case   (     unittest.TestCase   ):
 def 	UpperCAmelCase__       (  self						)	->							Optional[Any]:
       '''simple docstring'''





       UpperCAmelCase    : List[str]      ={
           '''model_details''': {
               '''Organization''': '''testing''',
               '''Model date''': '''today''',
               '''Model version''': '''v2.1, Developed by Test Corp in 2019.''',
               '''Architecture''': '''Convolutional Neural Network.''',
           },
           '''metrics''': '''BLEU and ROUGE-1''',
           '''evaluation_data''': {
               '''Datasets''': {'''BLEU''': '''My-great-dataset-v1''', '''ROUGE-1''': '''My-short-dataset-v2.1'''},
               '''Preprocessing''': '''See details on https://arxiv.org/pdf/1810.03993.pdf''',
           },
           '''training_data''': {
               '''Dataset''': '''English Wikipedia dump dated 2018-12-01''',
               '''Preprocessing''': (
                   '''Using SentencePiece vocabulary of size 52k tokens. See details on'''
                   ''' https://arxiv.org/pdf/1810.03993.pdf'''
               ),
           },
           '''quantitative_analyses''': {'''BLEU''': 55.1, '''ROUGE-1''': 76},
       }
 def 	UpperCAmelCase__       (  self						)	->							Dict:
       '''simple docstring'''





       UpperCAmelCase    : Optional[Any]      =ModelCard.from_dict(self.inputs_dict						)
       self.assertTrue(hasattr(snake_case__		,   '''model_details'''						)						)
       self.assertTrue(hasattr(snake_case__		,   '''intended_use'''						)						)
       self.assertTrue(hasattr(snake_case__		,   '''factors'''						)						)
       self.assertTrue(hasattr(snake_case__		,   '''metrics'''						)						)
       self.assertTrue(hasattr(snake_case__		,   '''evaluation_data'''						)						)
       self.assertTrue(hasattr(snake_case__		,   '''training_data'''						)						)
       self.assertTrue(hasattr(snake_case__		,   '''quantitative_analyses'''						)						)
       self.assertTrue(hasattr(snake_case__		,   '''ethical_considerations'''						)						)
       self.assertTrue(hasattr(snake_case__		,   '''caveats_and_recommendations'''						)						)
 def 	UpperCAmelCase__       (  self						)	->							Tuple:
       '''simple docstring'''





       UpperCAmelCase    : Optional[Any]      =ModelCard.from_dict(self.inputs_dict						)
       UpperCAmelCase    : int      =json.loads(modelcard.to_json_string()						)
       for key, value in self.inputs_dict.items():
             self.assertEqual(obj[key]		,   snake_case__						)
 def 	UpperCAmelCase__       (  self						)	->							Tuple:
       '''simple docstring'''





       UpperCAmelCase    : List[str]      =ModelCard.from_dict(self.inputs_dict						)

       with tempfile.TemporaryDirectory() as tmpdirname:
             UpperCAmelCase    : Optional[Any]      =os.path.join(snake_case__		,   '''modelcard.json'''						)
             model_card_first.to_json_file(snake_case__						)
             UpperCAmelCase    : Tuple      =ModelCard.from_json_file(snake_case__						)

       self.assertEqual(model_card_second.to_dict()		,   model_card_first.to_dict()						)






 def 	UpperCAmelCase__       (  self						)	->							str:
       '''simple docstring'''





       UpperCAmelCase    : Optional[int]      =ModelCard.from_dict(self.inputs_dict						)

       with tempfile.TemporaryDirectory() as tmpdirname:
             model_card_first.save_pretrained(snake_case__						)
             UpperCAmelCase    : Dict      =ModelCard.from_pretrained(snake_case__						)

       self.assertEqual(model_card_second.to_dict()		,   model_card_first.to_dict()						)
