



import inspect
import unittest

from transformers import ResNetConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from transformers.utils import cached_property, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


if is_flax_available():
							import jax
							import jax.numpy as jnp

							from transformers.models.resnet.modeling_flax_resnet import FlaxResNetForImageClassification, FlaxResNetModel

if is_vision_available():
							from PIL import Image

							from transformers import AutoImageProcessor







class 				a_    (						unittest.TestCase							):

						def __init__(       self      :List[str]  ,		_lowercase      :List[str]  ,		_lowercase      :Optional[int]=3  ,		_lowercase      :Any=32  ,		_lowercase      :Union[str, Any]=3  ,		_lowercase      :Any=10  ,		_lowercase      :Optional[Any]=[10, 20, 30, 40]  ,		_lowercase      :Dict=[1, 1, 2, 1]  ,		_lowercase      :Optional[Any]=True  ,		_lowercase      :Optional[int]=True  ,		_lowercase      :Optional[Any]="relu"  ,		_lowercase      :Dict=3  ,		_lowercase      :Union[str, Any]=None  ,		)						->   Union[str, Any]:
												UpperCAmelCase_					=	parent
												UpperCAmelCase_					=	batch_size
												UpperCAmelCase_					=	image_size
												UpperCAmelCase_					=	num_channels
												UpperCAmelCase_					=	embeddings_size
												UpperCAmelCase_					=	hidden_sizes
												UpperCAmelCase_					=	depths
												UpperCAmelCase_					=	is_training
												UpperCAmelCase_					=	use_labels
												UpperCAmelCase_					=	hidden_act
												UpperCAmelCase_					=	num_labels
												UpperCAmelCase_					=	scope
												UpperCAmelCase_					=	len(_lowercase)

						def       __a			(       self      :Tuple)						->   Optional[int]:
												UpperCAmelCase_					=	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

												UpperCAmelCase_					=	self.get_config()

												return config, pixel_values

						def       __a			(       self      :List[Any])						->   List[Any]:
												return ResNetConfig(
												    num_channels=self.num_channels  ,		embeddings_size=self.embeddings_size  ,		hidden_sizes=self.hidden_sizes  ,		depths=self.depths  ,		hidden_act=self.hidden_act  ,		num_labels=self.num_labels  ,		image_size=self.image_size  ,		)

						def       __a			(       self      :Optional[int]  ,		_lowercase      :Optional[Any]  ,		_lowercase      :str)						->   Optional[int]:
												UpperCAmelCase_					=	FlaxResNetModel(config=_lowercase)
												UpperCAmelCase_					=	model(_lowercase)

												# Output shape (b, c, h, w)
												self.parent.assertEqual(
												    result.last_hidden_state.shape  ,		(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)  ,		)

						def       __a			(       self      :Dict  ,		_lowercase      :int  ,		_lowercase      :List[Any])						->   Union[str, Any]:
												UpperCAmelCase_					=	self.num_labels
												UpperCAmelCase_					=	FlaxResNetForImageClassification(config=_lowercase)
												UpperCAmelCase_					=	model(_lowercase)
												self.parent.assertEqual(result.logits.shape  ,		(self.batch_size, self.num_labels))




						def       __a			(       self      :int)						->   int:
												UpperCAmelCase_					=	self.prepare_config_and_inputs()
												UpperCAmelCase_				, UpperCAmelCase_					=	config_and_inputs
												UpperCAmelCase_					=	{'''pixel_values''': pixel_values}
												return config, inputs_dict







@require_flax
class 				a_    (						_snake_case   ,					unittest.TestCase							):
						UpperCamelCase__ :		Any										=(FlaxResNetModel, FlaxResNetForImageClassification) if is_flax_available() else ()

						UpperCamelCase__ :		int										=False
						UpperCamelCase__ :		str										=False
						UpperCamelCase__ :		Union[str, Any]										=False

						def       __a			(       self      :Optional[int])						->   None:
												UpperCAmelCase_					=	FlaxResNetModelTester(self)
												UpperCAmelCase_					=	ConfigTester(self  ,		config_class=_lowercase  ,		has_text_modality=_lowercase)

						def       __a			(       self      :int)						->   Any:
												self.create_and_test_config_common_properties()
												self.config_tester.create_and_test_config_to_json_string()
												self.config_tester.create_and_test_config_to_json_file()
												self.config_tester.create_and_test_config_from_and_save_pretrained()
												self.config_tester.create_and_test_config_with_num_labels()
												self.config_tester.check_config_can_be_init_without_params()
												self.config_tester.check_config_arguments_init()

						def       __a			(       self      :Optional[Any])						->   Tuple:
												return

						def       __a			(       self      :Any)						->   Any:
												UpperCAmelCase_					=	self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*_lowercase)

						def       __a			(       self      :Optional[int])						->   List[Any]:
												UpperCAmelCase_					=	self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_image_classification(*_lowercase)

						@unittest.skip(reason='''ResNet does not use inputs_embeds''')
						def       __a			(       self      :str)						->   int:
												pass

						@unittest.skip(reason='''ResNet does not support input and output embeddings''')
						def       __a			(       self      :Union[str, Any])						->   Optional[Any]:
												pass

						def       __a			(       self      :int)						->   Optional[Any]:
												UpperCAmelCase_				, UpperCAmelCase_					=	self.model_tester.prepare_config_and_inputs_for_common()

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

																		UpperCAmelCase_					=	['''pixel_values''']
																		self.assertListEqual(arg_names[:1]  ,		_lowercase)

						def       __a			(       self      :Union[str, Any])						->   Tuple:
												def check_hidden_states_output(_lowercase      :Tuple  ,		_lowercase      :Optional[Any]  ,		_lowercase      :Tuple):
																		UpperCAmelCase_					=	model_class(_lowercase)

																		UpperCAmelCase_					=	model(**self._prepare_for_class(_lowercase  ,		_lowercase))

																		UpperCAmelCase_					=	outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

																		UpperCAmelCase_					=	self.model_tester.num_stages
																		self.assertEqual(len(_lowercase)  ,		expected_num_stages + 1)

						@unittest.skip(reason='''ResNet does not use feedforward chunking''')
						def       __a			(       self      :Any)						->   Dict:
												pass




						def       __a			(       self      :List[Any])						->   Union[str, Any]:
												UpperCAmelCase_				, UpperCAmelCase_					=	self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes:
																		with self.subTest(model_class.__name__):
																								UpperCAmelCase_					=	self._prepare_for_class(_lowercase  ,		_lowercase)
																								UpperCAmelCase_					=	model_class(_lowercase)

																								@jax.jit
																								def model_jitted(_lowercase      :Union[str, Any]  ,		**_lowercase      :Dict):
																														return model(pixel_values=_lowercase  ,		**_lowercase)

																								with self.subTest('''JIT Enabled'''):
																														UpperCAmelCase_					=	model_jitted(**_lowercase).to_tuple()

																								with self.subTest('''JIT Disabled'''):
																														with jax.disable_jit():
																																				UpperCAmelCase_					=	model_jitted(**_lowercase).to_tuple()

																								self.assertEqual(len(_lowercase)  ,		len(_lowercase))
																								for jitted_output, output in zip(_lowercase  ,		_lowercase):
																														self.assertEqual(jitted_output.shape  ,		output.shape)







def 							A     (						)			->			List[Any]:



						'''simple docstring'''






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







@require_flax
class 				a_    (						unittest.TestCase							):

						@cached_property
						def       __a			(       self      :List[str])						->   Tuple:
												return AutoImageProcessor.from_pretrained('''microsoft/resnet-50''') if is_vision_available() else None




						@slow
						def       __a			(       self      :Dict)						->   List[str]:
												UpperCAmelCase_					=	FlaxResNetForImageClassification.from_pretrained('''microsoft/resnet-50''')

												UpperCAmelCase_					=	self.default_image_processor
												UpperCAmelCase_					=	prepare_img()
												UpperCAmelCase_					=	image_processor(images=_lowercase  ,		return_tensors='''np''')

												UpperCAmelCase_					=	model(**_lowercase)

												# verify the logits
												UpperCAmelCase_					=	(1, 1000)
												self.assertEqual(outputs.logits.shape  ,		_lowercase)

												UpperCAmelCase_					=	jnp.array([-11.1_069, -9.7_877, -8.3_777])

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










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)}")





