



import inspect
import unittest

from transformers import DPTConfig
from transformers.file_utils import is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
				import torch
				from torch import nn

				from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel
				from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
				from PIL import Image

				from transformers import DPTImageProcessor

class 						UpperCAmelCase__     :




			'''simple docstring'''






			def __init__(  self				:					List[Any]			,			a_				:					List[Any]			,			a_				:					List[Any]=2			,			a_				:					List[Any]=32			,			a_				:					Dict=16			,			a_				:					Optional[int]=3			,			a_				:					str=True			,			a_				:					Any=True			,			a_				:					Optional[Any]=32			,			a_				:					Tuple=4			,			a_				:					Union[str, Any]=[0, 1, 2, 3]			,			a_				:					Optional[Any]=4			,			a_				:					Tuple=37			,			a_				:					Dict="gelu"			,			a_				:					Tuple=0.1			,			a_				:					List[Any]=0.1			,			a_				:					Optional[int]=0.0_2			,			a_				:					Dict=3			,			a_				:					int=False			,			a_				:					Optional[Any]=None			,			):
					'''simple docstring'''





					__UpperCAmelCase       :	Union[str, Any]						=      parent
					__UpperCAmelCase       :	Dict						=      batch_size
					__UpperCAmelCase       :	List[Any]						=      image_size
					__UpperCAmelCase       :	Tuple						=      patch_size
					__UpperCAmelCase       :	Union[str, Any]						=      num_channels
					__UpperCAmelCase       :	int						=      is_training
					__UpperCAmelCase       :	Any						=      use_labels
					__UpperCAmelCase       :	Optional[Any]						=      hidden_size
					__UpperCAmelCase       :	Union[str, Any]						=      num_hidden_layers
					__UpperCAmelCase       :	List[str]						=      backbone_out_indices
					__UpperCAmelCase       :	Optional[int]						=      num_attention_heads
					__UpperCAmelCase       :	Union[str, Any]						=      intermediate_size
					__UpperCAmelCase       :	Union[str, Any]						=      hidden_act
					__UpperCAmelCase       :	Tuple						=      hidden_dropout_prob
					__UpperCAmelCase       :	Optional[int]						=      attention_probs_dropout_prob
					__UpperCAmelCase       :	Optional[int]						=      initializer_range
					__UpperCAmelCase       :	List[Any]						=      num_labels
					__UpperCAmelCase       :	Union[str, Any]						=      scope
					__UpperCAmelCase       :	Any						=      is_hybrid
					# sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token)
					__UpperCAmelCase       :	Dict						=      (image_size // patch_size) ** 2
					__UpperCAmelCase       :	Optional[int]						=      num_patches + 1




			def 					snake_case__	(  self				:					Optional[int]					):
					'''simple docstring'''





					__UpperCAmelCase       :	Any						=      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

					__UpperCAmelCase       :	Optional[Any]						=      None
					if self.use_labels:
							__UpperCAmelCase       :	List[str]						=      ids_tensor([self.batch_size, self.image_size, self.image_size]			,			self.num_labels					)

					__UpperCAmelCase       :	Optional[Any]						=      self.get_config()

					return config, pixel_values, labels




			def 					snake_case__	(  self				:					Optional[int]					):
					'''simple docstring'''





					return DPTConfig(
					    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			,			backbone_out_indices=self.backbone_out_indices			,			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=_lowercase			,			initializer_range=self.initializer_range			,			is_hybrid=self.is_hybrid			,			)




			def 					snake_case__	(  self				:					List[Any]			,			a_				:					Union[str, Any]			,			a_				:					Optional[int]			,			a_				:					int					):
					'''simple docstring'''





					__UpperCAmelCase       :	Union[str, Any]						=      DPTModel(config=_lowercase					)
					model.to(_lowercase					)
					model.eval()
					__UpperCAmelCase       :	List[str]						=      model(_lowercase					)
					self.parent.assertEqual(result.last_hidden_state.shape			,			(self.batch_size, self.seq_length, self.hidden_size)					)




			def 					snake_case__	(  self				:					str			,			a_				:					Union[str, Any]			,			a_				:					Dict			,			a_				:					List[Any]					):
					'''simple docstring'''





					__UpperCAmelCase       :	Optional[Any]						=      self.num_labels
					__UpperCAmelCase       :	Optional[Any]						=      DPTForDepthEstimation(_lowercase					)
					model.to(_lowercase					)
					model.eval()
					__UpperCAmelCase       :	Tuple						=      model(_lowercase					)
					self.parent.assertEqual(result.predicted_depth.shape			,			(self.batch_size, self.image_size, self.image_size)					)




			def 					snake_case__	(  self				:					str			,			a_				:					Tuple			,			a_				:					List[str]			,			a_				:					List[str]					):
					'''simple docstring'''





					__UpperCAmelCase       :	Dict						=      self.num_labels
					__UpperCAmelCase       :	Any						=      DPTForSemanticSegmentation(_lowercase					)
					model.to(_lowercase					)
					model.eval()
					__UpperCAmelCase       :	Any						=      model(_lowercase			,			labels=_lowercase					)
					self.parent.assertEqual(
					    result.logits.shape			,			(self.batch_size, self.num_labels, self.image_size, self.image_size)					)




			def 					snake_case__	(  self				:					int					):
					'''simple docstring'''





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

@require_torch
class 						UpperCAmelCase__     (     _snake_case		,_snake_case		,unittest.TestCase  ):




			'''simple docstring'''






			UpperCamelCase     		=			(DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
			UpperCamelCase     		=			(
			    {
			        "depth-estimation": DPTForDepthEstimation,
			        "feature-extraction": DPTModel,
			        "image-segmentation": DPTForSemanticSegmentation,
			    }
			    if is_torch_available()
			    else {}
			)

			UpperCamelCase     		=			False
			UpperCamelCase     		=			False
			UpperCamelCase     		=			False




			def 					snake_case__	(  self				:					Optional[int]					):
					'''simple docstring'''





					__UpperCAmelCase       :	Dict						=      DPTModelTester(self					)
					__UpperCAmelCase       :	Dict						=      ConfigTester(self			,			config_class=_lowercase			,			has_text_modality=_lowercase			,			hidden_size=37					)




			def 					snake_case__	(  self				:					List[Any]					):
					'''simple docstring'''





					self.config_tester.run_common_tests()




			@unittest.skip(reason='''DPT does not use inputs_embeds'''					)
			def 					snake_case__	(  self				:					Tuple					):
					'''simple docstring'''





					pass




			def 					snake_case__	(  self				:					int					):
					'''simple docstring'''





					__UpperCAmelCase				,   __UpperCAmelCase       :	Dict						=      self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
							__UpperCAmelCase       :	List[str]						=      model_class(_lowercase					)
							self.assertIsInstance(model.get_input_embeddings()			,			(nn.Module)					)
							__UpperCAmelCase       :	Dict						=      model.get_output_embeddings()
							self.assertTrue(x is None or isinstance(_lowercase			,			nn.Linear					)					)




			def 					snake_case__	(  self				:					List[str]					):
					'''simple docstring'''





					__UpperCAmelCase				,   __UpperCAmelCase       :	Tuple						=      self.model_tester.prepare_config_and_inputs_for_common()

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

							__UpperCAmelCase       :	List[str]						=      ['''pixel_values''']
							self.assertListEqual(arg_names[:1]			,			_lowercase					)




			def 					snake_case__	(  self				:					Dict					):
					'''simple docstring'''





					__UpperCAmelCase       :	str						=      self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*_lowercase					)




			def 					snake_case__	(  self				:					str					):
					'''simple docstring'''





					__UpperCAmelCase       :	Dict						=      self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_depth_estimation(*_lowercase					)




			def 					snake_case__	(  self				:					Optional[Any]					):
					'''simple docstring'''





					__UpperCAmelCase       :	Optional[Any]						=      self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_semantic_segmentation(*_lowercase					)




			def 					snake_case__	(  self				:					Any					):
					'''simple docstring'''





					for model_class in self.all_model_classes:
							if model_class.__name__ == "DPTForDepthEstimation":
									continue

							__UpperCAmelCase				,   __UpperCAmelCase       :	Any						=      self.model_tester.prepare_config_and_inputs_for_common()
							__UpperCAmelCase       :	Union[str, Any]						=      True

							if model_class in get_values(_lowercase					):
									continue

							__UpperCAmelCase       :	List[str]						=      model_class(_lowercase					)
							model.to(_lowercase					)
							model.train()
							__UpperCAmelCase       :	Any						=      self._prepare_for_class(_lowercase			,			_lowercase			,			return_labels=_lowercase					)
							__UpperCAmelCase       :	Dict						=      model(**_lowercase					).loss
							loss.backward()




			def 					snake_case__	(  self				:					Tuple					):
					'''simple docstring'''





					for model_class in self.all_model_classes:
							if model_class.__name__ == "DPTForDepthEstimation":
									continue

							__UpperCAmelCase				,   __UpperCAmelCase       :	str						=      self.model_tester.prepare_config_and_inputs_for_common()
							__UpperCAmelCase       :	List[Any]						=      False
							__UpperCAmelCase       :	Union[str, Any]						=      True

							if model_class in get_values(_lowercase					) or not model_class.supports_gradient_checkpointing:
									continue
							__UpperCAmelCase       :	str						=      model_class(_lowercase					)
							model.to(_lowercase					)
							model.gradient_checkpointing_enable()
							model.train()
							__UpperCAmelCase       :	Tuple						=      self._prepare_for_class(_lowercase			,			_lowercase			,			return_labels=_lowercase					)
							__UpperCAmelCase       :	Optional[int]						=      model(**_lowercase					).loss
							loss.backward()




			def 					snake_case__	(  self				:					List[str]					):
					'''simple docstring'''





					__UpperCAmelCase				,   __UpperCAmelCase       :	List[str]						=      self.model_tester.prepare_config_and_inputs_for_common()

					__UpperCAmelCase       :	Optional[Any]						=      _config_zero_init(_lowercase					)
					for model_class in self.all_model_classes:
							__UpperCAmelCase       :	Optional[Any]						=      model_class(config=_lowercase					)
							# Skip the check for the backbone
							__UpperCAmelCase       :	Optional[Any]						=      []
							for name, module in model.named_modules():
									if module.__class__.__name__ == "DPTViTHybridEmbeddings":
											__UpperCAmelCase       :	str						=      [F'{name}.{key}' for key in module.state_dict().keys()]
											break

							for name, param in model.named_parameters():
									if param.requires_grad:
											if name in backbone_params:
													continue
											self.assertIn(
											    ((param.data.mean() * 1e9).round() / 1e9).item()			,			[0.0, 1.0]			,			msg=F'Parameter {name} of model {model_class} seems not properly initialized'			,			)




			@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''					)
			def 					snake_case__	(  self				:					Union[str, Any]					):
					'''simple docstring'''





					pass




			@slow
			def 					snake_case__	(  self				:					Dict					):
					'''simple docstring'''





					for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							__UpperCAmelCase       :	Dict						=      DPTModel.from_pretrained(_lowercase					)
							self.assertIsNotNone(_lowercase					)

def 			a		( ):







		'''simple docstring'''





		__UpperCAmelCase       :	Union[str, Any]						=      Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''		)
		return image

@require_torch
@require_vision
@slow
class 						UpperCAmelCase__     (     unittest.TestCase  ):




			'''simple docstring'''






			def 					snake_case__	(  self				:					List[str]					):
					'''simple docstring'''





					__UpperCAmelCase       :	int						=      DPTImageProcessor.from_pretrained('''Intel/dpt-large'''					)
					__UpperCAmelCase       :	Dict						=      DPTForDepthEstimation.from_pretrained('''Intel/dpt-large'''					).to(_lowercase					)

					__UpperCAmelCase       :	Any						=      prepare_img()
					__UpperCAmelCase       :	Optional[Any]						=      image_processor(images=_lowercase			,			return_tensors='''pt'''					).to(_lowercase					)

					# forward pass
					with torch.no_grad():
							__UpperCAmelCase       :	List[str]						=      model(**_lowercase					)
							__UpperCAmelCase       :	Optional[Any]						=      outputs.predicted_depth

					# verify the predicted depth
					__UpperCAmelCase       :	int						=      torch.Size((1, 3_84, 3_84)					)
					self.assertEqual(predicted_depth.shape			,			_lowercase					)

					__UpperCAmelCase       :	int						=      torch.tensor(
					    [[6.3_1_9_9, 6.3_6_2_9, 6.4_1_4_8], [6.3_8_5_0, 6.3_6_1_5, 6.4_1_6_6], [6.3_5_1_9, 6.3_1_7_6, 6.3_5_7_5]]					).to(_lowercase					)

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




			def 					snake_case__	(  self				:					Tuple					):
					'''simple docstring'''





					__UpperCAmelCase       :	List[Any]						=      DPTImageProcessor.from_pretrained('''Intel/dpt-large-ade'''					)
					__UpperCAmelCase       :	List[str]						=      DPTForSemanticSegmentation.from_pretrained('''Intel/dpt-large-ade'''					).to(_lowercase					)

					__UpperCAmelCase       :	Optional[Any]						=      prepare_img()
					__UpperCAmelCase       :	Dict						=      image_processor(images=_lowercase			,			return_tensors='''pt'''					).to(_lowercase					)

					# forward pass
					with torch.no_grad():
							__UpperCAmelCase       :	str						=      model(**_lowercase					)

					# verify the logits
					__UpperCAmelCase       :	Optional[int]						=      torch.Size((1, 1_50, 4_80, 4_80)					)
					self.assertEqual(outputs.logits.shape			,			_lowercase					)

					__UpperCAmelCase       :	Dict						=      torch.tensor(
					    [[4.0_4_8_0, 4.2_4_2_0, 4.4_3_6_0], [4.3_1_2_4, 4.5_6_9_3, 4.8_2_6_1], [4.5_7_6_8, 4.8_9_6_5, 5.2_1_6_3]]					).to(_lowercase					)

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




			def 					snake_case__	(  self				:					List[str]					):
					'''simple docstring'''





					__UpperCAmelCase       :	List[Any]						=      DPTImageProcessor.from_pretrained('''Intel/dpt-large-ade'''					)
					__UpperCAmelCase       :	str						=      DPTForSemanticSegmentation.from_pretrained('''Intel/dpt-large-ade'''					).to(_lowercase					)

					__UpperCAmelCase       :	int						=      prepare_img()
					__UpperCAmelCase       :	List[Any]						=      image_processor(images=_lowercase			,			return_tensors='''pt'''					).to(_lowercase					)

					# forward pass
					with torch.no_grad():
							__UpperCAmelCase       :	Any						=      model(**_lowercase					)

					__UpperCAmelCase       :	List[Any]						=      outputs.logits.detach().cpu()

					__UpperCAmelCase       :	List[str]						=      image_processor.post_process_semantic_segmentation(outputs=_lowercase			,			target_sizes=[(5_00, 3_00)]					)
					__UpperCAmelCase       :	List[Any]						=      torch.Size((5_00, 3_00)					)
					self.assertEqual(segmentation[0].shape			,			_lowercase					)

					__UpperCAmelCase       :	Union[str, Any]						=      image_processor.post_process_semantic_segmentation(outputs=_lowercase					)
					__UpperCAmelCase       :	Union[str, Any]						=      torch.Size((4_80, 4_80)					)
					self.assertEqual(segmentation[0].shape			,			_lowercase					)










import numpy as np
import qiskit







def 							A     (						__UpperCAmelCase				,   __UpperCAmelCase      )			->			qiskit.QuantumCircuit:



						'''simple docstring'''






						UpperCAmelCase_					=	qiskit.QuantumCircuit(num_qubits + 1      )

						# First, let's deal with the case in which oracle is balanced
						if case == "balanced":
												# First generate a random number that tells us which CNOTs to
												# wrap in X-gates:
												UpperCAmelCase_					=	np.random.randint(1				,   2**num_qubits      )
												# Next, format 'b' as a binary string of length 'n', padded with zeros:
												UpperCAmelCase_					=	format(__UpperCAmelCase				,   f"0{num_qubits}b"      )
												# Next, we place the first X-gates. Each digit in our binary string
												# corresponds to a qubit, if the digit is 0, we do nothing, if it's 1
												# we apply an X-gate to that qubit:
												for index, bit in enumerate(__UpperCAmelCase      ):
																		if bit == "1":
																								oracle_qc.x(__UpperCAmelCase      )
        # Do the controlled-NOT gates for each qubit, using the output qubit
        # as the target:
												for index in range(__UpperCAmelCase      ):
																		oracle_qc.cx(__UpperCAmelCase				,   __UpperCAmelCase      )
												# Next, place the final X-gates
												for index, bit in enumerate(__UpperCAmelCase      ):
																		if bit == "1":
																								oracle_qc.x(__UpperCAmelCase      )

    # Case in which oracle is constant
						if case == "constant":
												# First decide what the fixed output of the oracle will be
												# (either always 0 or always 1)
												UpperCAmelCase_					=	np.random.randint(2      )
												if output == 1:
																		oracle_qc.x(__UpperCAmelCase      )

						UpperCAmelCase_					=	oracle_qc.to_gate()
						UpperCAmelCase_					=	'''Oracle'''  # To show when we display the circuit
						return oracle_gate







def 							A     (						__UpperCAmelCase				,   __UpperCAmelCase      )			->			qiskit.QuantumCircuit:



						'''simple docstring'''






						UpperCAmelCase_					=	qiskit.QuantumCircuit(num_qubits + 1				,   __UpperCAmelCase      )
						# Set up the output qubit:
						dj_circuit.x(__UpperCAmelCase      )
						dj_circuit.h(__UpperCAmelCase      )
						# And set up the input register:
						for qubit in range(__UpperCAmelCase      ):
												dj_circuit.h(__UpperCAmelCase      )
						# Let's append the oracle gate to our circuit:
						dj_circuit.append(__UpperCAmelCase				,   range(num_qubits + 1      )      )
						# Finally, perform the H-gates again and measure:
						for qubit in range(__UpperCAmelCase      ):
												dj_circuit.h(__UpperCAmelCase      )

						for i in range(__UpperCAmelCase      ):
												dj_circuit.measure(__UpperCAmelCase				,   __UpperCAmelCase      )

						return dj_circuit







def 							A     (						__UpperCAmelCase				,   __UpperCAmelCase      )			->			qiskit.result.counts.Counts:



						'''simple docstring'''






						UpperCAmelCase_					=	qiskit.Aer.get_backend('''aer_simulator'''      )

						UpperCAmelCase_					=	dj_oracle(__UpperCAmelCase				,   __UpperCAmelCase      )
						UpperCAmelCase_					=	dj_algorithm(__UpperCAmelCase				,   __UpperCAmelCase      )

						# Execute the circuit on the simulator
						UpperCAmelCase_					=	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__":
							print(f"Deutsch Jozsa - Constant Oracle: {deutsch_jozsa('constant', 3)}")
							print(f"Deutsch Jozsa - Balanced Oracle: {deutsch_jozsa('balanced', 3)}")





