




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      ,     SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE=13      ,     SCREAMING_SNAKE_CASE=10      ,     SCREAMING_SNAKE_CASE=3      ,     SCREAMING_SNAKE_CASE=2      ,     SCREAMING_SNAKE_CASE=2      ,     SCREAMING_SNAKE_CASE=True      ,     SCREAMING_SNAKE_CASE=True      ,     SCREAMING_SNAKE_CASE=32      ,     SCREAMING_SNAKE_CASE=5      ,     SCREAMING_SNAKE_CASE=4      ,     SCREAMING_SNAKE_CASE=37      ,     SCREAMING_SNAKE_CASE="gelu"      ,     SCREAMING_SNAKE_CASE=0.1      ,     SCREAMING_SNAKE_CASE=0.1      ,     SCREAMING_SNAKE_CASE=10      ,     SCREAMING_SNAKE_CASE=0.0_2      ,     SCREAMING_SNAKE_CASE="divided_space_time"      ,     SCREAMING_SNAKE_CASE=None      ,     )  ->					Union[str, Any]:




				"""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 						A_(							self      )  ->					Tuple:




				"""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 						A_(							self      )  ->					str:




				"""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 						A_(							self      ,     SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      )  ->					str:




				"""simple docstring"""



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





	def 						A_(							self      ,     SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      )  ->					int:




				"""simple docstring"""



				SCREAMING_SNAKE_CASE_								=						TimesformerForVideoClassification(SCREAMING_SNAKE_CASE      )
				model.to(SCREAMING_SNAKE_CASE      )
				model.eval()

				SCREAMING_SNAKE_CASE_								=						model(SCREAMING_SNAKE_CASE      )

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





	def 						A_(							self      )  ->					Dict:




				"""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       a_       (     SCREAMING_SNAKE_CASE__  ,    SCREAMING_SNAKE_CASE__  ,    unittest.TestCase     ):
	A    							= (TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else ()
	A    							= (
	    {'''feature-extraction''': TimesformerModel, '''video-classification''': TimesformerForVideoClassification}
	    if is_torch_available()
	    else {}
	)

	A    							= False
	A    							= False
	A    							= False
	A    							= False





	def 						A_(							self      )  ->					Any:




				"""simple docstring"""



				SCREAMING_SNAKE_CASE_								=						TimesformerModelTester(self      )
				SCREAMING_SNAKE_CASE_								=						ConfigTester(
				    self      ,     config_class=SCREAMING_SNAKE_CASE      ,     has_text_modality=SCREAMING_SNAKE_CASE      ,     hidden_size=37      )





	def 						A_(							self      ,     SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE=False      )  ->					List[Any]:




				"""simple docstring"""



				SCREAMING_SNAKE_CASE_								=						copy.deepcopy(SCREAMING_SNAKE_CASE      )

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

				return inputs_dict





	def 						A_(							self      )  ->					int:




				"""simple docstring"""



				self.config_tester.run_common_tests()





	@unittest.skip(reason='TimeSformer does not use inputs_embeds'      )
	def 						A_(							self      )  ->					Optional[int]:




				"""simple docstring"""



				pass





	def 						A_(							self      )  ->					List[str]:




				"""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(SCREAMING_SNAKE_CASE      )
							self.assertIsInstance(model.get_input_embeddings()      ,     (nn.Module)      )
							SCREAMING_SNAKE_CASE_								=						model.get_output_embeddings()
							self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE      ,     nn.Linear      )      )





	def 						A_(							self      )  ->					Any:




				"""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(SCREAMING_SNAKE_CASE      )
							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]      ,     SCREAMING_SNAKE_CASE      )





	def 						A_(							self      )  ->					Dict:




				"""simple docstring"""



				SCREAMING_SNAKE_CASE_								=						self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE      )





	def 						A_(							self      )  ->					Optional[int]:




				"""simple docstring"""



				SCREAMING_SNAKE_CASE_								=						self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_video_classification(*SCREAMING_SNAKE_CASE      )





	@slow
	def 						A_(							self      )  ->					Dict:




				"""simple docstring"""



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





	def 						A_(							self      )  ->					Any:




				"""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(SCREAMING_SNAKE_CASE      )
										model.to(SCREAMING_SNAKE_CASE      )
										model.eval()
										with torch.no_grad():
													SCREAMING_SNAKE_CASE_								=						model(**self._prepare_for_class(SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      )      )
										SCREAMING_SNAKE_CASE_								=						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"]
										SCREAMING_SNAKE_CASE_								=						True
										SCREAMING_SNAKE_CASE_								=						model_class(SCREAMING_SNAKE_CASE      )
										model.to(SCREAMING_SNAKE_CASE      )
										model.eval()
										with torch.no_grad():
													SCREAMING_SNAKE_CASE_								=						model(**self._prepare_for_class(SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      )      )
										SCREAMING_SNAKE_CASE_								=						outputs.attentions
										self.assertEqual(len(SCREAMING_SNAKE_CASE      )      ,     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(SCREAMING_SNAKE_CASE      )

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

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

										SCREAMING_SNAKE_CASE_								=						outputs.attentions

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




				"""simple docstring"""



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

							with torch.no_grad():
										SCREAMING_SNAKE_CASE_								=						model(**self._prepare_for_class(SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      )      )

							SCREAMING_SNAKE_CASE_								=						outputs.hidden_states
							SCREAMING_SNAKE_CASE_								=						self.model_tester.num_hidden_layers + 1
							self.assertEqual(len(SCREAMING_SNAKE_CASE      )      ,     SCREAMING_SNAKE_CASE      )

							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(SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      )

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

							check_hidden_states_output(SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      )




def lowercase    (  )			->							List[Any]:


			'''simple docstring'''







			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(SCREAMING_SNAKE_CASE )
			return list(SCREAMING_SNAKE_CASE )



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





	@cached_property
	def 						A_(							self      )  ->					Dict:




				"""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 						A_(							self      )  ->					Any:




				"""simple docstring"""



				SCREAMING_SNAKE_CASE_								=						TimesformerForVideoClassification.from_pretrained('facebook/timesformer-base-finetuned-k400'      ).to(
				    SCREAMING_SNAKE_CASE      )

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

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

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

				SCREAMING_SNAKE_CASE_								=						torch.tensor([-0.3_0_1_6, -0.7_7_1_3, -0.4_2_0_5]      ).to(SCREAMING_SNAKE_CASE      )

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






import qiskit

def lowercase    (  SCREAMING_SNAKE_CASE = 2 )			->							qiskit.result.counts.Counts:


			'''simple docstring'''







			SCREAMING_SNAKE_CASE_								=						qubits

			# Using Aer's simulator
			SCREAMING_SNAKE_CASE_								=						qiskit.Aer.get_backend('aer_simulator' )

			# Creating a Quantum Circuit acting on the q register
			SCREAMING_SNAKE_CASE_								=						qiskit.QuantumCircuit(SCREAMING_SNAKE_CASE       ,    SCREAMING_SNAKE_CASE )

			# Adding a H gate on qubit 0 (now q0 in superposition)
			circuit.h(0 )

			for i in range(1       ,    SCREAMING_SNAKE_CASE ):
						# Adding CX (CNOT) gate
						circuit.cx(i - 1       ,    SCREAMING_SNAKE_CASE )

			# Mapping the quantum measurement to the classical bits
			circuit.measure(list(range(SCREAMING_SNAKE_CASE ) )       ,    list(range(SCREAMING_SNAKE_CASE ) ) )

			# Now measuring any one qubit would affect other qubits to collapse
			# their super position and have same state as the measured one.

			# Executing the circuit on the simulator
			SCREAMING_SNAKE_CASE_								=						qiskit.execute(SCREAMING_SNAKE_CASE       ,    SCREAMING_SNAKE_CASE       ,    shots=10_00 )

			return job.result().get_counts(SCREAMING_SNAKE_CASE )


if __name__ == "__main__":
				print(f"""Total count for various states are: {quantum_entanglement(3)}""")
