





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






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

										"""simple docstring"""




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

										# in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token
										__SCREAMING_SNAKE_CASE:				str           =   (image_size // patch_size) ** 2
										__SCREAMING_SNAKE_CASE:				Optional[Any]           =   (num_frames) * self.num_patches_per_frame + 1






				def 			snake_case_    (  self					):

										"""simple docstring"""




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

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

										__SCREAMING_SNAKE_CASE:				List[Any]           =   self.get_config()

										return config, pixel_values, labels






				def 			snake_case_    (  self					):

										"""simple docstring"""




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






				def 			snake_case_    (  self			, _lowerCAmelCase			, _lowerCAmelCase			, _lowerCAmelCase					):

										"""simple docstring"""




										__SCREAMING_SNAKE_CASE:				List[str]           =   TimesformerModel(config=_lowerCAmelCase					)
										model.to(_lowerCAmelCase					)
										model.eval()
										__SCREAMING_SNAKE_CASE:				List[str]           =   model(_lowerCAmelCase					)
										self.parent.assertEqual(result.last_hidden_state.shape			, (self.batch_size, self.seq_length, self.hidden_size)					)






				def 			snake_case_    (  self			, _lowerCAmelCase			, _lowerCAmelCase			, _lowerCAmelCase					):

										"""simple docstring"""




										__SCREAMING_SNAKE_CASE:				List[str]           =   TimesformerForVideoClassification(_lowerCAmelCase					)
										model.to(_lowerCAmelCase					)
										model.eval()

										__SCREAMING_SNAKE_CASE:				List[str]           =   model(_lowerCAmelCase					)

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






				def 			snake_case_    (  self					):

										"""simple docstring"""




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





@require_torch
class 				a			(      __lowercase   ,__lowercase   ,unittest.TestCase			):
				SCREAMING_SNAKE_CASE__     :   Tuple		      =     (TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else ()
				SCREAMING_SNAKE_CASE__     :   Tuple		      =     (
				    {'''feature-extraction''': TimesformerModel, '''video-classification''': TimesformerForVideoClassification}
				    if is_torch_available()
				    else {}
				)

				SCREAMING_SNAKE_CASE__     :   Tuple		      =     False
				SCREAMING_SNAKE_CASE__     :   Union[str, Any]		      =     False
				SCREAMING_SNAKE_CASE__     :   List[str]		      =     False
				SCREAMING_SNAKE_CASE__     :   Optional[Any]		      =     False






				def 			snake_case_    (  self					):

										"""simple docstring"""




										__SCREAMING_SNAKE_CASE:				Optional[Any]           =   TimesformerModelTester(self					)
										__SCREAMING_SNAKE_CASE:				Any           =   ConfigTester(
										    self			, config_class=_lowerCAmelCase			, has_text_modality=_lowerCAmelCase			, hidden_size=37					)






				def 			snake_case_    (  self			, _lowerCAmelCase			, _lowerCAmelCase			, _lowerCAmelCase=False					):

										"""simple docstring"""




										__SCREAMING_SNAKE_CASE:				Optional[Any]           =   copy.deepcopy(_lowerCAmelCase					)

										if return_labels:
																if model_class in get_values(_lowerCAmelCase					):
																						__SCREAMING_SNAKE_CASE:				int           =   torch.zeros(
																						    self.model_tester.batch_size			, dtype=torch.long			, device=_lowerCAmelCase					)

										return inputs_dict






				def 			snake_case_    (  self					):

										"""simple docstring"""




										self.config_tester.run_common_tests()






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

										"""simple docstring"""




										pass






				def 			snake_case_    (  self					):

										"""simple docstring"""




										__SCREAMING_SNAKE_CASE       ,__SCREAMING_SNAKE_CASE:				Optional[Any]           =   self.model_tester.prepare_config_and_inputs_for_common()

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






				def 			snake_case_    (  self					):

										"""simple docstring"""




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

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

																__SCREAMING_SNAKE_CASE:				Any           =   ['''pixel_values''']
																self.assertListEqual(arg_names[:1]			, _lowerCAmelCase					)






				def 			snake_case_    (  self					):

										"""simple docstring"""




										__SCREAMING_SNAKE_CASE:				int           =   self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*_lowerCAmelCase					)






				def 			snake_case_    (  self					):

										"""simple docstring"""




										__SCREAMING_SNAKE_CASE:				Optional[Any]           =   self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_video_classification(*_lowerCAmelCase					)






				@slow
				def 			snake_case_    (  self					):

										"""simple docstring"""




										for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																__SCREAMING_SNAKE_CASE:				Dict           =   TimesformerModel.from_pretrained(_lowerCAmelCase					)
																self.assertIsNotNone(_lowerCAmelCase					)






				def 			snake_case_    (  self					):

										"""simple docstring"""




										if not self.has_attentions:
																pass

										else:
																__SCREAMING_SNAKE_CASE       ,__SCREAMING_SNAKE_CASE:				List[Any]           =   self.model_tester.prepare_config_and_inputs_for_common()
																__SCREAMING_SNAKE_CASE:				Optional[int]           =   True

																for model_class in self.all_model_classes:
																						__SCREAMING_SNAKE_CASE:				int           =   self.model_tester.seq_length
																						__SCREAMING_SNAKE_CASE:				List[str]           =   self.model_tester.num_frames

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

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

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

																						__SCREAMING_SNAKE_CASE:				Dict           =   outputs.attentions

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

										"""simple docstring"""




										def check_hidden_states_output(_lowerCAmelCase			, _lowerCAmelCase			, _lowerCAmelCase					):
																__SCREAMING_SNAKE_CASE:				Dict           =   model_class(_lowerCAmelCase					)
																model.to(_lowerCAmelCase					)
																model.eval()

																with torch.no_grad():
																						__SCREAMING_SNAKE_CASE:				str           =   model(**self._prepare_for_class(_lowerCAmelCase			, _lowerCAmelCase					)					)

																__SCREAMING_SNAKE_CASE:				Any           =   outputs.hidden_states
																__SCREAMING_SNAKE_CASE:				Union[str, Any]           =   self.model_tester.num_hidden_layers + 1
																self.assertEqual(len(_lowerCAmelCase					)			, _lowerCAmelCase					)

																__SCREAMING_SNAKE_CASE:				List[str]           =   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:				Tuple           =   self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
																__SCREAMING_SNAKE_CASE:				Any           =   True
																check_hidden_states_output(_lowerCAmelCase			, _lowerCAmelCase			, _lowerCAmelCase					)

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

																check_hidden_states_output(_lowerCAmelCase			, _lowerCAmelCase			, _lowerCAmelCase					)






def 		lowerCAmelCase  (	)      ->    Dict:

						"""simple docstring"""





						__SCREAMING_SNAKE_CASE:				int           =   hf_hub_download(
						    repo_id='''hf-internal-testing/spaghetti-video'''       ,			filename='''eating_spaghetti.npy'''       ,			repo_type='''dataset'''					)
						__SCREAMING_SNAKE_CASE:				Union[str, Any]           =   np.load(UpperCamelCase__					)
						return list(UpperCamelCase__					)





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






				@cached_property
				def 			snake_case_    (  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 			snake_case_    (  self					):

										"""simple docstring"""




										__SCREAMING_SNAKE_CASE:				List[Any]           =   TimesformerForVideoClassification.from_pretrained('''facebook/timesformer-base-finetuned-k400'''					).to(
										    _lowerCAmelCase					)

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

										# forward pass
										with torch.no_grad():
																__SCREAMING_SNAKE_CASE:				str           =   model(**_lowerCAmelCase					)

										# verify the logits
										__SCREAMING_SNAKE_CASE:				List[Any]           =   torch.Size((1, 400)					)
										self.assertEqual(outputs.logits.shape			, _lowerCAmelCase					)

										__SCREAMING_SNAKE_CASE:				int           =   torch.tensor([-0.3016, -0.7713, -0.4205]					).to(_lowerCAmelCase					)

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










def 		lowerCAmelCase  (	UpperCamelCase__   :   list       ,			UpperCamelCase__   :   list       ,			UpperCamelCase__   :   int					)      ->    list:

						"""simple docstring"""





						__SCREAMING_SNAKE_CASE:				Tuple           =   len(UpperCamelCase__					)
						__SCREAMING_SNAKE_CASE:				Optional[int]           =   [[0] * n for i in range(UpperCamelCase__					)]
						for i in range(UpperCamelCase__					):
												__SCREAMING_SNAKE_CASE:				str           =   y_points[i]

						for i in range(2       ,			UpperCamelCase__					):
												for j in range(UpperCamelCase__       ,			UpperCamelCase__					):
																		__SCREAMING_SNAKE_CASE:				Optional[int]           =   (
																		    (xa - x_points[j - i + 1]) * q[j][i - 1]
																		    - (xa - x_points[j]) * q[j - 1][i - 1]
																		) / (x_points[j] - x_points[j - i + 1])

						return [q[n - 1][n - 1], q]


if __name__ == "__main__":
							import doctest

							doctest.testmod()



