



'''simple docstring'''



from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import DeiTConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
		import tensorflow as tf

		from transformers import (
		    TFDeiTForImageClassification,
		    TFDeiTForImageClassificationWithTeacher,
		    TFDeiTForMaskedImageModeling,
		    TFDeiTModel,
		)
		from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import DeiTImageProcessor





class _UpperCamelCase		:





				'''simple docstring'''





				def __init__(				self	:	int	,							_lowerCAmelCase	:	int	,							_lowerCAmelCase	:	Tuple=1_3	,							_lowerCAmelCase	:	Dict=3_0	,							_lowerCAmelCase	:	List[str]=2	,							_lowerCAmelCase	:	Dict=3	,							_lowerCAmelCase	:	Optional[Any]=True	,							_lowerCAmelCase	:	Tuple=True	,							_lowerCAmelCase	:	Union[str, Any]=3_2	,							_lowerCAmelCase	:	List[str]=2	,							_lowerCAmelCase	:	Tuple=4	,							_lowerCAmelCase	:	List[Any]=3_7	,							_lowerCAmelCase	:	Tuple="gelu"	,							_lowerCAmelCase	:	int=0.1	,							_lowerCAmelCase	:	Tuple=0.1	,							_lowerCAmelCase	:	Any=1_0	,							_lowerCAmelCase	:	str=0.02	,							_lowerCAmelCase	:	Dict=3	,							_lowerCAmelCase	:	List[str]=None	,							_lowerCAmelCase	:	Optional[int]=2	,							):







											'''simple docstring'''

											__lowercase													=parent
											__lowercase													=batch_size
											__lowercase													=image_size
											__lowercase													=patch_size
											__lowercase													=num_channels
											__lowercase													=is_training
											__lowercase													=use_labels
											__lowercase													=hidden_size
											__lowercase													=num_hidden_layers
											__lowercase													=num_attention_heads
											__lowercase													=intermediate_size
											__lowercase													=hidden_act
											__lowercase													=hidden_dropout_prob
											__lowercase													=attention_probs_dropout_prob
											__lowercase													=type_sequence_label_size
											__lowercase													=initializer_range
											__lowercase													=scope
											__lowercase													=encoder_stride

											# in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens)
											__lowercase													=(image_size // patch_size) ** 2
											__lowercase													=num_patches + 2

				def 					__lowerCamelCase  (				self	:	int):







											'''simple docstring'''

											__lowercase													=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

											__lowercase													=None
											if self.use_labels:
																		__lowercase													=ids_tensor([self.batch_size]	,							self.type_sequence_label_size)

											__lowercase													=self.get_config()

											return config, pixel_values, labels

				def 					__lowerCamelCase  (				self	:	List[Any]):







											'''simple docstring'''

											return DeiTConfig(
											    image_size=self.image_size	,							patch_size=self.patch_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	,							is_decoder=_lowerCamelCase	,							initializer_range=self.initializer_range	,							encoder_stride=self.encoder_stride	,							)

				def 					__lowerCamelCase  (				self	:	str	,							_lowerCAmelCase	:	int	,							_lowerCAmelCase	:	List[str]	,							_lowerCAmelCase	:	Union[str, Any]):







											'''simple docstring'''

											__lowercase													=TFDeiTModel(config=_lowerCamelCase)
											__lowercase													=model(_lowerCamelCase)
											self.parent.assertEqual(result.last_hidden_state.shape	,							(self.batch_size, self.seq_length, self.hidden_size))

				def 					__lowerCamelCase  (				self	:	int	,							_lowerCAmelCase	:	List[Any]	,							_lowerCAmelCase	:	List[str]	,							_lowerCAmelCase	:	str):







											'''simple docstring'''

											__lowercase													=TFDeiTForMaskedImageModeling(config=_lowerCamelCase)
											__lowercase													=model(_lowerCamelCase)
											self.parent.assertEqual(
											    result.reconstruction.shape	,							(self.batch_size, self.num_channels, self.image_size, self.image_size))

											# test greyscale images
											__lowercase													=1
											__lowercase													=TFDeiTForMaskedImageModeling(_lowerCamelCase)

											__lowercase													=floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
											__lowercase													=model(_lowerCamelCase)
											self.parent.assertEqual(result.reconstruction.shape	,							(self.batch_size, 1, self.image_size, self.image_size))

				def 					__lowerCamelCase  (				self	:	Dict	,							_lowerCAmelCase	:	Any	,							_lowerCAmelCase	:	Tuple	,							_lowerCAmelCase	:	Optional[int]):







											'''simple docstring'''

											__lowercase													=self.type_sequence_label_size
											__lowercase													=TFDeiTForImageClassification(_lowerCamelCase)
											__lowercase													=model(_lowerCamelCase	,							labels=_lowerCamelCase)
											self.parent.assertEqual(result.logits.shape	,							(self.batch_size, self.type_sequence_label_size))

											# test greyscale images
											__lowercase													=1
											__lowercase													=TFDeiTForImageClassification(_lowerCamelCase)

											__lowercase													=floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
											__lowercase													=model(_lowerCamelCase	,							labels=_lowerCamelCase)
											self.parent.assertEqual(result.logits.shape	,							(self.batch_size, self.type_sequence_label_size))

				def 					__lowerCamelCase  (				self	:	Union[str, Any]):







											'''simple docstring'''

											__lowercase													=self.prepare_config_and_inputs()
											__lowercase													=config_and_inputs
											__lowercase													={'''pixel_values''': pixel_values}
											return config, inputs_dict





@require_tf
class _UpperCamelCase		(  _snake_case   ,							_snake_case   ,							unittest.TestCase		):





				'''simple docstring'''





				lowerCAmelCase__            =     (
				    (
				        TFDeiTModel,
				        TFDeiTForImageClassification,
				        TFDeiTForImageClassificationWithTeacher,
				        TFDeiTForMaskedImageModeling,
				    )
				    if is_tf_available()
				    else ()
				)
				lowerCAmelCase__            =     (
				    {
				        """feature-extraction""": TFDeiTModel,
				        """image-classification""": (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher),
				    }
				    if is_tf_available()
				    else {}
				)

				lowerCAmelCase__            =     False
				lowerCAmelCase__            =     False
				lowerCAmelCase__            =     False
				lowerCAmelCase__            =     False

				def 					__lowerCamelCase  (				self	:	Optional[Any]):







											'''simple docstring'''

											__lowercase													=TFDeiTModelTester(self)
											__lowercase													=ConfigTester(self	,							config_class=_lowerCamelCase	,							has_text_modality=_lowerCamelCase	,							hidden_size=3_7)

				def 					__lowerCamelCase  (				self	:	Optional[int]):







											'''simple docstring'''

											self.config_tester.run_common_tests()

				@unittest.skip(reason='DeiT does not use inputs_embeds')
				def 					__lowerCamelCase  (				self	:	Tuple):







											'''simple docstring'''

											pass

				def 					__lowerCamelCase  (				self	:	Any):







											'''simple docstring'''

											__lowercase													=self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																		__lowercase													=model_class(_lowerCamelCase)
																		self.assertIsInstance(model.get_input_embeddings()	,							(tf.keras.layers.Layer))
																		__lowercase													=model.get_output_embeddings()
																		self.assertTrue(x is None or isinstance(_lowerCamelCase	,							tf.keras.layers.Dense))

				def 					__lowerCamelCase  (				self	:	str):







											'''simple docstring'''

											__lowercase													=self.model_tester.prepare_config_and_inputs_for_common()

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

																		__lowercase													=['''pixel_values''']
																		self.assertListEqual(arg_names[:1]	,							_lowerCamelCase)

				def 					__lowerCamelCase  (				self	:	List[Any]):







											'''simple docstring'''

											__lowercase													=self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*_lowerCamelCase)

				def 					__lowerCamelCase  (				self	:	List[str]):







											'''simple docstring'''

											__lowercase													=self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_masked_image_modeling(*_lowerCamelCase)

				def 					__lowerCamelCase  (				self	:	int):







											'''simple docstring'''

											__lowercase													=self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_image_classification(*_lowerCamelCase)

				def 					__lowerCamelCase  (				self	:	Tuple	,							_lowerCAmelCase	:	Union[str, Any]	,							_lowerCAmelCase	:	List[str]	,							_lowerCAmelCase	:	List[Any]=False):







											'''simple docstring'''

											__lowercase													=super()._prepare_for_class(_lowerCamelCase	,							_lowerCamelCase	,							return_labels=_lowerCamelCase)

											if return_labels:
																		if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call).parameters:
																									del inputs_dict["labels"]

											return inputs_dict

				@slow
				def 					__lowerCamelCase  (				self	:	Any):







											'''simple docstring'''

											for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																		__lowercase													=TFDeiTModel.from_pretrained(_lowerCamelCase)
																		self.assertIsNotNone(_lowerCamelCase)



def 	_A							( ):



							"""simple docstring"""



							__lowercase													=Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'       )
							return image





@require_tf
@require_vision
class _UpperCamelCase		(  unittest.TestCase		):





				'''simple docstring'''





				@cached_property
				def 					__lowerCamelCase  (				self	:	List[Any]):







											'''simple docstring'''

											return (
											    DeiTImageProcessor.from_pretrained('facebook/deit-base-distilled-patch16-224')
											    if is_vision_available()
											    else None
											)

				@slow
				def 					__lowerCamelCase  (				self	:	List[Any]):







											'''simple docstring'''

											__lowercase													=TFDeiTForImageClassificationWithTeacher.from_pretrained('facebook/deit-base-distilled-patch16-224')

											__lowercase													=self.default_image_processor
											__lowercase													=prepare_img()
											__lowercase													=image_processor(images=_lowerCamelCase	,							return_tensors='tf')

											# forward pass
											__lowercase													=model(**_lowerCamelCase)

											# verify the logits
											__lowercase													=tf.TensorShape((1, 1_0_0_0))
											self.assertEqual(outputs.logits.shape	,							_lowerCamelCase)

											__lowercase													=tf.constant([-1.0266, 0.1912, -1.2861])

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







import qiskit
def 							__lowerCamelCase		(					UpperCAmelCase_		:						int					,    UpperCAmelCase_		:						int		):




      """simple docstring"""





      a		:Tuple									=			qiskit.Aer.get_backend('''aer_simulator'''		)

      # Create a Quantum Circuit acting on the q register
      a		:str									=			qiskit.QuantumCircuit(UpperCAmelCase_					,    UpperCAmelCase_		)

      # Apply X (NOT) Gate to Qubits 0 & 1
      circuit.x(0		)
      circuit.x(1		)

      # Map the quantum measurement to the classical bits
      circuit.measure([0, 1]					,    [0, 1]		)

      # Execute the circuit on the qasm simulator
      a		:Optional[Any]									=			qiskit.execute(UpperCAmelCase_					,    UpperCAmelCase_					,    shots=1000		)

      # Return the histogram data of the results of the experiment.
      return job.result().get_counts(UpperCAmelCase_		)


if __name__ == "__main__":
     snake_case							:       Any										=	single_qubit_measure(2, 2)
     print(F"""Total count for various states are: {counts}""")





