



'''simple docstring'''





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  snake_case__						:
 def __init__(   self						:							int      ,     __a						:							Any      ,     __a						:							Tuple=13      ,     __a						:							Any=10      ,     __a						:							Union[str, Any]=3      ,     __a						:							Optional[Any]=2      ,     __a						:							Tuple=2      ,     __a						:							Any=True      ,     __a						:							List[str]=True      ,     __a						:							Dict=32      ,     __a						:							Union[str, Any]=5      ,     __a						:							Optional[int]=4      ,     __a						:							Dict=37      ,     __a						:							int="gelu"      ,     __a						:							str=0.1      ,     __a						:							str=0.1      ,     __a						:							List[Any]=10      ,     __a						:							Dict=0.0_2      ,     __a						:							Union[str, Any]="divided_space_time"      ,     __a						:							str=None      ,     )      ->   int:







       '''simple docstring'''
       __snake_case :   Dict													=    parent
       __snake_case :   int													=    batch_size
       __snake_case :   Dict													=    image_size
       __snake_case :   List[Any]													=    num_channels
       __snake_case :   str													=    patch_size
       __snake_case :   Any													=    num_frames
       __snake_case :   Optional[Any]													=    is_training
       __snake_case :   int													=    use_labels
       __snake_case :   Optional[int]													=    hidden_size
       __snake_case :   str													=    num_hidden_layers
       __snake_case :   str													=    num_attention_heads
       __snake_case :   str													=    intermediate_size
       __snake_case :   List[Any]													=    hidden_act
       __snake_case :   List[str]													=    hidden_dropout_prob
       __snake_case :   Dict													=    attention_probs_dropout_prob
       __snake_case :   Optional[Any]													=    attention_type
       __snake_case :   str													=    initializer_range
       __snake_case :   Dict													=    scope
       __snake_case :   List[str]													=    num_labels

       # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token
       __snake_case :   str													=    (image_size // patch_size) ** 2
       __snake_case :   str													=    (num_frames) * self.num_patches_per_frame + 1
 def A_   (   self						:							Tuple  )      ->   Union[str, Any]:







       '''simple docstring'''
       __snake_case :   Optional[Any]													=    floats_tensor(
           [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size]  )

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

       __snake_case :   Dict													=    self.get_config()

       return config, pixel_values, labels
 def A_   (   self						:							Union[str, Any]  )      ->   Tuple:







       '''simple docstring'''
       __snake_case :   Tuple													=    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      ,     )
       __snake_case :   Optional[int]													=    self.num_labels
       return config
 def A_   (   self						:							Tuple      ,     __a						:							Any      ,     __a						:							Any      ,     __a						:							List[str]  )      ->   Dict:







       '''simple docstring'''
       __snake_case :   Optional[Any]													=    TimesformerModel(config=__a  )
       model.to(__a  )
       model.eval()
       __snake_case :   List[Any]													=    model(__a  )
       self.parent.assertEqual(result.last_hidden_state.shape      ,     (self.batch_size, self.seq_length, self.hidden_size)  )
 def A_   (   self						:							Optional[Any]      ,     __a						:							List[str]      ,     __a						:							str      ,     __a						:							List[str]  )      ->   Union[str, Any]:







       '''simple docstring'''
       __snake_case :   int													=    TimesformerForVideoClassification(__a  )
       model.to(__a  )
       model.eval()

       __snake_case :   Dict													=    model(__a  )

       # verify the logits shape
       __snake_case :   Optional[int]													=    torch.Size((self.batch_size, self.num_labels)  )
       self.parent.assertEqual(result.logits.shape      ,     __a  )





 def A_   (   self						:							Any  )      ->   Tuple:







       '''simple docstring'''
       __snake_case :   Any													=    self.prepare_config_and_inputs()
       __snake_case							,     __snake_case							,     __snake_case :   Any													=    config_and_inputs
       __snake_case :   Optional[int]													=    {'pixel_values': pixel_values}
       return config, inputs_dict



@require_torch
class  snake_case__						(    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						:							Union[str, Any]  )      ->   Tuple:







       '''simple docstring'''
       __snake_case :   Tuple													=    TimesformerModelTester(self  )
       __snake_case :   str													=    ConfigTester(
           self      ,     config_class=__a      ,     has_text_modality=__a      ,     hidden_size=37  )
 def A_   (   self						:							str      ,     __a						:							Any      ,     __a						:							Any      ,     __a						:							Union[str, Any]=False  )      ->   Any:







       '''simple docstring'''
       __snake_case :   Any													=    copy.deepcopy(__a  )

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

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







       '''simple docstring'''
       self.config_tester.run_common_tests()
 @unittest.skip(reason='TimeSformer does not use inputs_embeds'  )
 def A_   (   self						:							Any  )      ->   str:







       '''simple docstring'''
       pass
 def A_   (   self						:							Dict  )      ->   Optional[int]:







       '''simple docstring'''
       __snake_case							,     __snake_case :   Any													=    self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
             __snake_case :   Tuple													=    model_class(__a  )
             self.assertIsInstance(model.get_input_embeddings()      ,     (nn.Module)  )
             __snake_case :   Tuple													=    model.get_output_embeddings()
             self.assertTrue(x is None or isinstance(__a      ,     nn.Linear  )  )
 def A_   (   self						:							str  )      ->   List[str]:







       '''simple docstring'''
       __snake_case							,     __snake_case :   Optional[Any]													=    self.model_tester.prepare_config_and_inputs_for_common()

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

             __snake_case :   str													=    ['pixel_values']
             self.assertListEqual(arg_names[:1]      ,     __a  )
 def A_   (   self						:							List[str]  )      ->   Tuple:







       '''simple docstring'''
       __snake_case :   Optional[Any]													=    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*__a  )
 def A_   (   self						:							Tuple  )      ->   int:







       '''simple docstring'''
       __snake_case :   int													=    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_video_classification(*__a  )
 @slow
 def A_   (   self						:							List[Any]  )      ->   Tuple:







       '''simple docstring'''
       for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             __snake_case :   Any													=    TimesformerModel.from_pretrained(__a  )
             self.assertIsNotNone(__a  )
 def A_   (   self						:							Dict  )      ->   Optional[int]:







       '''simple docstring'''
       if not self.has_attentions:
             pass

       else:
             __snake_case							,     __snake_case :   Optional[Any]													=    self.model_tester.prepare_config_and_inputs_for_common()
             __snake_case :   Union[str, Any]													=    True

             for model_class in self.all_model_classes:
                   __snake_case :   int													=    self.model_tester.seq_length
                   __snake_case :   Optional[int]													=    self.model_tester.num_frames

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

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

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

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

                   __snake_case :   List[str]													=    outputs.attentions

                   self.assertEqual(len(__a  )      ,     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						:							List[Any]  )      ->   str:







       '''simple docstring'''
       def check_hidden_states_output(__a						:							Union[str, Any]      ,     __a						:							Optional[Any]      ,     __a						:							List[Any]  ):
             __snake_case :   List[Any]													=    model_class(__a  )
             model.to(__a  )
             model.eval()

             with torch.no_grad():
                   __snake_case :   Optional[int]													=    model(**self._prepare_for_class(__a      ,     __a  )  )

             __snake_case :   Dict													=    outputs.hidden_states
             __snake_case :   Optional[int]													=    self.model_tester.num_hidden_layers + 1
             self.assertEqual(len(__a  )      ,     __a  )

             __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							,     __snake_case :   Optional[Any]													=    self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
             __snake_case :   Tuple													=    True
             check_hidden_states_output(__a      ,     __a      ,     __a  )

             # 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(__a      ,     __a      ,     __a  )





def   a_   (		)    ->  Tuple:
      __snake_case :   Any													=    hf_hub_download(
          repo_id='hf-internal-testing/spaghetti-video' ,filename='eating_spaghetti.npy' ,repo_type='dataset'				)
      __snake_case :   str													=    np.load(_UpperCAmelCase				)
      return list(_UpperCAmelCase				)





@require_torch
@require_vision
class  snake_case__						(    unittest.TestCase				):
 @cached_property
 def A_   (   self						:							str  )      ->   Dict:







       '''simple docstring'''
       # logits were tested with a different mean and std, so we use the same here
       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						:							int  )      ->   Dict:







       '''simple docstring'''
       __snake_case :   int													=    TimesformerForVideoClassification.from_pretrained('facebook/timesformer-base-finetuned-k400'  ).to(
           __a  )

       __snake_case :   List[str]													=    self.default_image_processor
       __snake_case :   Any													=    prepare_video()
       __snake_case :   Union[str, Any]													=    image_processor(video[:8]      ,     return_tensors='pt'  ).to(__a  )

       # forward pass
       with torch.no_grad():
             __snake_case :   List[str]													=    model(**__a  )

       # verify the logits
       __snake_case :   Tuple													=    torch.Size((1, 400)  )
       self.assertEqual(outputs.logits.shape      ,     __a  )

       __snake_case :   str													=    torch.tensor([-0.3_0_1_6, -0.7_7_1_3, -0.4_2_0_5]  ).to(__a  )

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








'''simple docstring'''





import qiskit





def   a_   (		_UpperCAmelCase    :      int = 2				)    ->  qiskit.result.counts.Counts:
      __snake_case :   Union[str, Any]													=    qubits

      # Using Aer's simulator
      __snake_case :   List[Any]													=    qiskit.Aer.get_backend('aer_simulator'				)

      # Creating a Quantum Circuit acting on the q register
      __snake_case :   Dict													=    qiskit.QuantumCircuit(_UpperCAmelCase ,_UpperCAmelCase				)

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

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

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

      # 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
      __snake_case :   Optional[Any]													=    qiskit.execute(_UpperCAmelCase ,_UpperCAmelCase ,shots=10_00				)

      return job.result().get_counts(_UpperCAmelCase				)


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



