




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 						SCREAMING_SNAKE_CASE__		:
     def __init__(	self  :		Tuple					,	__lowerCamelCase  :		List[str]					,	__lowerCamelCase  :		Optional[Any]=2					,	__lowerCamelCase  :		List[Any]=True					,	__lowerCamelCase  :		Optional[Any]=True					,	__lowerCamelCase  :		int=10					,	__lowerCamelCase  :		str=10					,	__lowerCamelCase  :		List[Any]=8					,	__lowerCamelCase  :		Dict=[2, 4, 4]					,	__lowerCamelCase  :		Optional[int]=3					,	__lowerCamelCase  :		Optional[int]=7_68					,	__lowerCamelCase  :		Optional[Any]=5					,	__lowerCamelCase  :		Any=4					,	__lowerCamelCase  :		List[str]=37					,	__lowerCamelCase  :		Optional[int]="gelu_fast"					,	__lowerCamelCase  :		Tuple=0.0					,	__lowerCamelCase  :		Tuple=0.0					,	__lowerCamelCase  :		str=0.02					,	__lowerCamelCase  :		Union[str, Any]=1e-06					,	__lowerCamelCase  :		Tuple=True					,	__lowerCamelCase  :		Optional[int]=None					,	):



       """simple docstring"""
       lowerCAmelCase__								=			parent
       lowerCAmelCase__								=			batch_size
       lowerCAmelCase__								=			is_training
       lowerCAmelCase__								=			use_labels
       lowerCAmelCase__								=			num_labels
       lowerCAmelCase__								=			image_size
       lowerCAmelCase__								=			num_frames
       lowerCAmelCase__								=			tubelet_size
       lowerCAmelCase__								=			num_channels
       lowerCAmelCase__								=			hidden_size
       lowerCAmelCase__								=			num_hidden_layers
       lowerCAmelCase__								=			num_attention_heads
       lowerCAmelCase__								=			intermediate_size
       lowerCAmelCase__								=			hidden_act
       lowerCAmelCase__								=			hidden_dropout_prob
       lowerCAmelCase__								=			attention_probs_dropout_prob
       lowerCAmelCase__								=			initializer_range
       lowerCAmelCase__								=			layer_norm_eps
       lowerCAmelCase__								=			qkv_bias
       lowerCAmelCase__								=			scope

       lowerCAmelCase__								=			(
           (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 					A__			(	self  :		str	):



       """simple docstring"""
       lowerCAmelCase__								=			floats_tensor(
           [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size]	)

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

       lowerCAmelCase__								=			self.get_config()

       return config, pixel_values, labels
     def 					A__			(	self  :		Any	):



       """simple docstring"""
       lowerCAmelCase__								=			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					,	)
       lowerCAmelCase__								=			self.num_labels
       return config
     def 					A__			(	self  :		List[Any]					,	__lowerCamelCase  :		Tuple					,	__lowerCamelCase  :		Tuple					,	__lowerCamelCase  :		Dict	):



       """simple docstring"""
       lowerCAmelCase__								=			VivitModel(config=__lowerCamelCase	)
       model.to(__lowerCamelCase	)
       model.eval()
       lowerCAmelCase__								=			model(__lowerCamelCase	)
       self.parent.assertEqual(result.last_hidden_state.shape					,	(self.batch_size, self.seq_length, self.hidden_size)	)
     def 					A__			(	self  :		Optional[Any]					,	__lowerCamelCase  :		Optional[Any]					,	__lowerCamelCase  :		Optional[Any]					,	__lowerCamelCase  :		Dict	):



       """simple docstring"""
       lowerCAmelCase__								=			VivitForVideoClassification(__lowerCamelCase	)
       model.to(__lowerCamelCase	)
       model.eval()

       lowerCAmelCase__								=			model(__lowerCamelCase	)

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



     def 					A__			(	self  :		Optional[Any]	):



       """simple docstring"""
       lowerCAmelCase__								=			self.prepare_config_and_inputs()
       lowerCAmelCase__							,			lowerCAmelCase__							,			lowerCAmelCase__								=			config_and_inputs
       lowerCAmelCase__								=			{'''pixel_values''': pixel_values}
       return config, inputs_dict





@require_torch
class 						SCREAMING_SNAKE_CASE__		(_a						,				unittest.TestCase ):
     lowercase_   :			Optional[Any]   =   (VivitModel, VivitForVideoClassification) if is_torch_available() else ()

     lowercase_   :			List[str]   =   False
     lowercase_   :			Optional[int]   =   False
     lowercase_   :			int   =   False
     lowercase_   :			Union[str, Any]   =   False
     def 					A__			(	self  :		str	):



       """simple docstring"""
       lowerCAmelCase__								=			VivitModelTester(self	)
       lowerCAmelCase__								=			ConfigTester(self					,	config_class=__lowerCamelCase					,	has_text_modality=__lowerCamelCase					,	hidden_size=37	)
     def 					A__			(	self  :		Union[str, Any]					,	__lowerCamelCase  :		List[str]					,	__lowerCamelCase  :		Union[str, Any]					,	__lowerCamelCase  :		str=False	):



       """simple docstring"""
       lowerCAmelCase__								=			copy.deepcopy(__lowerCamelCase	)

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

       return inputs_dict
     def 					A__			(	self  :		str	):



       """simple docstring"""
       self.config_tester.run_common_tests()
     @unittest.skip(reason='''Vivit does not use inputs_embeds'''	)
     def 					A__			(	self  :		str	):



       """simple docstring"""
       pass
     def 					A__			(	self  :		int	):



       """simple docstring"""
       lowerCAmelCase__							,			lowerCAmelCase__								=			self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
         lowerCAmelCase__								=			model_class(__lowerCamelCase	)
         self.assertIsInstance(model.get_input_embeddings()					,	(nn.Module)	)
         lowerCAmelCase__								=			model.get_output_embeddings()
         self.assertTrue(x is None or isinstance(__lowerCamelCase					,	nn.Linear	)	)
     def 					A__			(	self  :		Union[str, Any]	):



       """simple docstring"""
       lowerCAmelCase__							,			lowerCAmelCase__								=			self.model_tester.prepare_config_and_inputs_for_common()

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

         lowerCAmelCase__								=			['''pixel_values''', '''head_mask''']
         self.assertListEqual(arg_names[:2]					,	__lowerCamelCase	)
     def 					A__			(	self  :		str	):



       """simple docstring"""
       lowerCAmelCase__								=			self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*__lowerCamelCase	)
     def 					A__			(	self  :		Union[str, Any]	):



       """simple docstring"""
       lowerCAmelCase__								=			self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_video_classification(*__lowerCamelCase	)
     @slow
     def 					A__			(	self  :		Union[str, Any]	):



       """simple docstring"""
       for model_name in VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         lowerCAmelCase__								=			VivitModel.from_pretrained(__lowerCamelCase	)
         self.assertIsNotNone(__lowerCamelCase	)
     def 					A__			(	self  :		str	):



       """simple docstring"""
       lowerCAmelCase__							,			lowerCAmelCase__								=			self.model_tester.prepare_config_and_inputs_for_common()
       lowerCAmelCase__								=			True

       for model_class in self.all_model_classes:
         lowerCAmelCase__								=			self.model_tester.seq_length

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

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

         self.assertListEqual(
             list(attentions[0].shape[-3:]	)					,	[self.model_tester.num_attention_heads, seq_len, seq_len]					,	)
         lowerCAmelCase__								=			len(__lowerCamelCase	)

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

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

         lowerCAmelCase__								=			outputs.attentions

         self.assertEqual(len(__lowerCamelCase	)					,	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 					A__			(	self  :		Tuple	):



       """simple docstring"""
       def check_hidden_states_output(__lowerCamelCase  :		List[str]					,	__lowerCamelCase  :		Union[str, Any]					,	__lowerCamelCase  :		Dict	):
         lowerCAmelCase__								=			model_class(__lowerCamelCase	)
         model.to(__lowerCamelCase	)
         model.eval()

         with torch.no_grad():
           lowerCAmelCase__								=			model(**self._prepare_for_class(__lowerCamelCase					,	__lowerCamelCase	)	)

         lowerCAmelCase__								=			outputs.hidden_states
         lowerCAmelCase__								=			self.model_tester.num_hidden_layers + 1
         self.assertEqual(len(__lowerCamelCase	)					,	__lowerCamelCase	)

         lowerCAmelCase__								=			self.model_tester.seq_length

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

       lowerCAmelCase__							,			lowerCAmelCase__								=			self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
         lowerCAmelCase__								=			True
         check_hidden_states_output(__lowerCamelCase					,	__lowerCamelCase					,	__lowerCamelCase	)

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

         check_hidden_states_output(__lowerCamelCase					,	__lowerCamelCase					,	__lowerCamelCase	)



     @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''	)
     def 					A__			(	self  :		List[Any]	):



       """simple docstring"""
       pass



def 		a_       (   ):
  lowerCAmelCase__								=			hf_hub_download(
      repo_id='''hf-internal-testing/spaghetti-video'''      ,   filename='''eating_spaghetti_32_frames.npy'''      ,   repo_type='''dataset'''							)
  lowerCAmelCase__								=			np.load(__lowerCAmelCase							)
  return list(__lowerCAmelCase							)





@require_torch
@require_vision
class 						SCREAMING_SNAKE_CASE__		(unittest.TestCase ):
     @cached_property
     def 					A__			(	self  :		Tuple	):



       """simple docstring"""
       return VivitImageProcessor() if is_vision_available() else None



     @slow
     def 					A__			(	self  :		Any	):



       """simple docstring"""
       lowerCAmelCase__								=			VivitForVideoClassification.from_pretrained('''google/vivit-b-16x2-kinetics400'''	).to(__lowerCamelCase	)

       lowerCAmelCase__								=			self.default_image_processor
       lowerCAmelCase__								=			prepare_video()
       lowerCAmelCase__								=			image_processor(__lowerCamelCase					,	return_tensors='''pt'''	).to(__lowerCamelCase	)

       # forward pass
       with torch.no_grad():
         lowerCAmelCase__								=			model(**__lowerCamelCase	)

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

       # taken from original model
       lowerCAmelCase__								=			torch.tensor([-1.0543, 2.0764, -0.2104, 0.4439, -0.9658]	).to(__lowerCamelCase	)

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







__magic_name__     :     dict[str, float]  							=					{
    "kilogram": 1,
    "gram": pow(10, 3),
    "milligram": pow(10, 6),
    "metric-ton": pow(10, -3),
    "long-ton": 0.0009842073,
    "short-ton": 0.0011023122,
    "pound": 2.2046244202,
    "stone": 0.1574731728,
    "ounce": 35.273990723,
    "carrat": 50_00,
    "atomic-mass-unit": 6.022_136_652E26,
}

__magic_name__     :     dict[str, float]  							=					{
    "kilogram": 1,
    "gram": pow(10, -3),
    "milligram": pow(10, -6),
    "metric-ton": pow(10, 3),
    "long-ton": 1016.04608,
    "short-ton": 907.184,
    "pound": 0.453592,
    "stone": 6.35029,
    "ounce": 0.0283495,
    "carrat": 0.0002,
    "atomic-mass-unit": 1.660_540_199E-27,
}
def 		a_       (   __lowerCAmelCase      ,   __lowerCAmelCase      ,   __lowerCAmelCase							):
  if to_type not in KILOGRAM_CHART or from_type not in WEIGHT_TYPE_CHART:
    lowerCAmelCase__								=			(
        F"""Invalid 'from_type' or 'to_type' value: {from_type!r}, {to_type!r}\n"""
        F"""Supported values are: {', '.join(__lowerCAmelCase							)}"""
    )
    raise ValueError(__lowerCAmelCase							)
  return value * KILOGRAM_CHART[to_type] * WEIGHT_TYPE_CHART[from_type]


if __name__ == "__main__":
      import doctest

      doctest.testmod()

