




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


			def __init__(       self			,	SCREAMING_SNAKE_CASE			,	SCREAMING_SNAKE_CASE=2			,	SCREAMING_SNAKE_CASE=True			,	SCREAMING_SNAKE_CASE=True			,	SCREAMING_SNAKE_CASE=10			,	SCREAMING_SNAKE_CASE=10			,	SCREAMING_SNAKE_CASE=8			,	SCREAMING_SNAKE_CASE=[2, 4, 4]			,	SCREAMING_SNAKE_CASE=3			,	SCREAMING_SNAKE_CASE=768			,	SCREAMING_SNAKE_CASE=5			,	SCREAMING_SNAKE_CASE=4			,	SCREAMING_SNAKE_CASE=37			,	SCREAMING_SNAKE_CASE="gelu_fast"			,	SCREAMING_SNAKE_CASE=0.0			,	SCREAMING_SNAKE_CASE=0.0			,	SCREAMING_SNAKE_CASE=0.02			,	SCREAMING_SNAKE_CASE=1E-06			,	SCREAMING_SNAKE_CASE=True			,	SCREAMING_SNAKE_CASE=None			,	):



					"""simple docstring"""







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

					snake_case						:  str        =			(
					    (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 							lowerCamelCase_			(       self							):



					"""simple docstring"""







					snake_case						:  Tuple        =			floats_tensor(
					    [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size]							)

					snake_case						:  str        =			None
					if self.use_labels:
							snake_case						:  Union[str, Any]        =			ids_tensor([self.batch_size]			,	self.num_labels							)

					snake_case						:  str        =			self.get_config()

					return config, pixel_values, labels


			def 							lowerCamelCase_			(       self							):



					"""simple docstring"""







					snake_case						:  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			,	)
					snake_case						:  Optional[Any]        =			self.num_labels
					return config


			def 							lowerCamelCase_			(       self			,	SCREAMING_SNAKE_CASE			,	SCREAMING_SNAKE_CASE			,	SCREAMING_SNAKE_CASE							):



					"""simple docstring"""







					snake_case						:  Any        =			VivitModel(config=SCREAMING_SNAKE_CASE							)
					model.to(SCREAMING_SNAKE_CASE							)
					model.eval()
					snake_case						:  List[Any]        =			model(SCREAMING_SNAKE_CASE							)
					self.parent.assertEqual(result.last_hidden_state.shape			,	(self.batch_size, self.seq_length, self.hidden_size)							)


			def 							lowerCamelCase_			(       self			,	SCREAMING_SNAKE_CASE			,	SCREAMING_SNAKE_CASE			,	SCREAMING_SNAKE_CASE							):



					"""simple docstring"""







					snake_case						:  List[str]        =			VivitForVideoClassification(SCREAMING_SNAKE_CASE							)
					model.to(SCREAMING_SNAKE_CASE							)
					model.eval()

					snake_case						:  Optional[int]        =			model(SCREAMING_SNAKE_CASE							)

					# verify the logits shape
					snake_case						:  List[Any]        =			torch.Size((self.batch_size, self.num_labels)							)
					self.parent.assertEqual(result.logits.shape			,	SCREAMING_SNAKE_CASE							)



			def 							lowerCamelCase_			(       self							):



					"""simple docstring"""







					snake_case						:  Dict        =			self.prepare_config_and_inputs()
					snake_case						:  int        =			config_and_inputs
					snake_case						:  Tuple        =			{"pixel_values": pixel_values}
					return config, inputs_dict







@require_torch
class      lowerCamelCase__      (					lowerCamelCase_			,					unittest.TestCase     ):
			a__	: List[str]        =       (VivitModel, VivitForVideoClassification) if is_torch_available() else ()

			a__	: Any        =       False
			a__	: Any        =       False
			a__	: Optional[int]        =       False
			a__	: Optional[int]        =       False


			def 							lowerCamelCase_			(       self							):



					"""simple docstring"""







					snake_case						:  Union[str, Any]        =			VivitModelTester(self							)
					snake_case						:  Tuple        =			ConfigTester(self			,	config_class=SCREAMING_SNAKE_CASE			,	has_text_modality=SCREAMING_SNAKE_CASE			,	hidden_size=37							)


			def 							lowerCamelCase_			(       self			,	SCREAMING_SNAKE_CASE			,	SCREAMING_SNAKE_CASE			,	SCREAMING_SNAKE_CASE=False							):



					"""simple docstring"""







					snake_case						:  int        =			copy.deepcopy(SCREAMING_SNAKE_CASE							)

					if return_labels:
							if model_class in get_values(SCREAMING_SNAKE_CASE							):
									snake_case						:  str        =			torch.zeros(
									    self.model_tester.batch_size			,	dtype=torch.long			,	device=SCREAMING_SNAKE_CASE							)

					return inputs_dict


			def 							lowerCamelCase_			(       self							):



					"""simple docstring"""







					self.config_tester.run_common_tests()


			@unittest.skip(reason="Vivit does not use inputs_embeds"							)
			def 							lowerCamelCase_			(       self							):



					"""simple docstring"""







					pass


			def 							lowerCamelCase_			(       self							):



					"""simple docstring"""







					snake_case						:  Tuple        =			self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
							snake_case						:  Optional[int]        =			model_class(SCREAMING_SNAKE_CASE							)
							self.assertIsInstance(model.get_input_embeddings()			,	(nn.Module)							)
							snake_case						:  Optional[int]        =			model.get_output_embeddings()
							self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE			,	nn.Linear							)							)


			def 							lowerCamelCase_			(       self							):



					"""simple docstring"""







					snake_case						:  Any        =			self.model_tester.prepare_config_and_inputs_for_common()

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

							snake_case						:  Optional[int]        =			["pixel_values", "head_mask"]
							self.assertListEqual(arg_names[:2]			,	SCREAMING_SNAKE_CASE							)


			def 							lowerCamelCase_			(       self							):



					"""simple docstring"""







					snake_case						:  Optional[int]        =			self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE							)


			def 							lowerCamelCase_			(       self							):



					"""simple docstring"""







					snake_case						:  int        =			self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_video_classification(*SCREAMING_SNAKE_CASE							)


			@slow
			def 							lowerCamelCase_			(       self							):



					"""simple docstring"""







					for model_name in VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							snake_case						:  List[Any]        =			VivitModel.from_pretrained(SCREAMING_SNAKE_CASE							)
							self.assertIsNotNone(SCREAMING_SNAKE_CASE							)


			def 							lowerCamelCase_			(       self							):



					"""simple docstring"""







					snake_case						:  Tuple        =			self.model_tester.prepare_config_and_inputs_for_common()
					snake_case						:  str        =			True

					for model_class in self.all_model_classes:
							snake_case						:  Tuple        =			self.model_tester.seq_length

							snake_case						:  Tuple        =			True
							snake_case						:  Tuple        =			False
							snake_case						:  str        =			True
							snake_case						:  str        =			model_class(SCREAMING_SNAKE_CASE							)
							model.to(SCREAMING_SNAKE_CASE							)
							model.eval()
							with torch.no_grad():
									snake_case						:  Tuple        =			model(**self._prepare_for_class(SCREAMING_SNAKE_CASE			,	SCREAMING_SNAKE_CASE							)							)
							snake_case						:  List[Any]        =			outputs.attentions
							self.assertEqual(len(SCREAMING_SNAKE_CASE							)			,	self.model_tester.num_hidden_layers							)

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

							# Check attention is always last and order is fine
							snake_case						:  Any        =			True
							snake_case						:  Tuple        =			True
							snake_case						:  Optional[int]        =			model_class(SCREAMING_SNAKE_CASE							)
							model.to(SCREAMING_SNAKE_CASE							)
							model.eval()
							with torch.no_grad():
									snake_case						:  Union[str, Any]        =			model(**self._prepare_for_class(SCREAMING_SNAKE_CASE			,	SCREAMING_SNAKE_CASE							)							)

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

							snake_case						:  List[Any]        =			outputs.attentions

							self.assertEqual(len(SCREAMING_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 							lowerCamelCase_			(       self							):



					"""simple docstring"""







					def check_hidden_states_output(SCREAMING_SNAKE_CASE			,	SCREAMING_SNAKE_CASE			,	SCREAMING_SNAKE_CASE							):
							snake_case						:  Dict        =			model_class(SCREAMING_SNAKE_CASE							)
							model.to(SCREAMING_SNAKE_CASE							)
							model.eval()

							with torch.no_grad():
									snake_case						:  List[Any]        =			model(**self._prepare_for_class(SCREAMING_SNAKE_CASE			,	SCREAMING_SNAKE_CASE							)							)

							snake_case						:  List[Any]        =			outputs.hidden_states
							snake_case						:  Any        =			self.model_tester.num_hidden_layers + 1
							self.assertEqual(len(SCREAMING_SNAKE_CASE							)			,	SCREAMING_SNAKE_CASE							)

							snake_case						:  str        =			self.model_tester.seq_length

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

					snake_case						:  Any        =			self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
							snake_case						:  Optional[Any]        =			True
							check_hidden_states_output(SCREAMING_SNAKE_CASE			,	SCREAMING_SNAKE_CASE			,	SCREAMING_SNAKE_CASE							)

							# check that output_hidden_states also work using config
							del inputs_dict["output_hidden_states"]
							snake_case						:  Union[str, Any]        =			True

							check_hidden_states_output(SCREAMING_SNAKE_CASE			,	SCREAMING_SNAKE_CASE			,	SCREAMING_SNAKE_CASE							)



			@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."							)
			def 							lowerCamelCase_			(       self							):



					"""simple docstring"""







					pass







def 					UpperCamelCase__       (						):
		snake_case						:  Any        =			hf_hub_download(
		    repo_id="hf-internal-testing/spaghetti-video"    ,       filename="eating_spaghetti_32_frames.npy"    ,       repo_type="dataset"				)
		snake_case						:  List[Any]        =			np.load(lowercase__				)
		return list(lowercase__				)
@require_torch
@require_vision
class      lowerCamelCase__      (					unittest.TestCase     ):


			@cached_property
			def 							lowerCamelCase_			(       self							):



					"""simple docstring"""







					return VivitImageProcessor() if is_vision_available() else None



			@slow
			def 							lowerCamelCase_			(       self							):



					"""simple docstring"""







					snake_case						:  Optional[int]        =			VivitForVideoClassification.from_pretrained("google/vivit-b-16x2-kinetics400"							).to(SCREAMING_SNAKE_CASE							)

					snake_case						:  Optional[int]        =			self.default_image_processor
					snake_case						:  List[str]        =			prepare_video()
					snake_case						:  List[Any]        =			image_processor(SCREAMING_SNAKE_CASE			,	return_tensors="pt"							).to(SCREAMING_SNAKE_CASE							)

					# forward pass
					with torch.no_grad():
							snake_case						:  str        =			model(**SCREAMING_SNAKE_CASE							)

					# verify the logits
					snake_case						:  str        =			torch.Size((1, 400)							)
					self.assertEqual(outputs.logits.shape			,	SCREAMING_SNAKE_CASE							)

					# taken from original model
					snake_case						:  Optional[Any]        =			torch.tensor([-1.05_43, 2.07_64, -0.21_04, 0.44_39, -0.96_58]							).to(SCREAMING_SNAKE_CASE							)

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







"""simple docstring"""

def 					UpperCamelCase__       (						lowercase__					:       int				):
		if not isinstance(lowercase__    ,       lowercase__				):
				raise ValueError("double_factorial() only accepts integral values"				)
		if n < 0:
				raise ValueError("double_factorial() not defined for negative values"				)
		return 1 if n <= 1 else n * double_factorial(n - 2				)


if __name__ == "__main__":
							import doctest

							doctest.testmod()

