


import copy
import inspect
import unittest

from transformers import PretrainedConfig, SwiftFormerConfig
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 SwiftFormerForImageClassification, SwiftFormerModel
		from transformers.models.swiftformer.modeling_swiftformer import SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import ViTImageProcessor

class 						__a :
		def __init__(     self     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE=13     ,       _SCREAMING_SNAKE_CASE=3     ,       _SCREAMING_SNAKE_CASE=True     ,       _SCREAMING_SNAKE_CASE=True     ,       _SCREAMING_SNAKE_CASE=0.1     ,       _SCREAMING_SNAKE_CASE=0.1     ,       _SCREAMING_SNAKE_CASE=224     ,       _SCREAMING_SNAKE_CASE=1000     ,       _SCREAMING_SNAKE_CASE=[3, 3, 6, 4]     ,       _SCREAMING_SNAKE_CASE=[48, 56, 112, 220]     ,       )					->			Union[str, Any]:




									"""simple docstring"""





									_UpperCAmelCase											=     parent
									_UpperCAmelCase											=     batch_size
									_UpperCAmelCase											=     num_channels
									_UpperCAmelCase											=     is_training
									_UpperCAmelCase											=     use_labels
									_UpperCAmelCase											=     hidden_dropout_prob
									_UpperCAmelCase											=     attention_probs_dropout_prob
									_UpperCAmelCase											=     num_labels
									_UpperCAmelCase											=     image_size
									_UpperCAmelCase											=     layer_depths
									_UpperCAmelCase											=     embed_dims
		def       UpperCAmelCase__							(     self		)					->			Dict:




									"""simple docstring"""





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

									_UpperCAmelCase											=     None
									if self.use_labels:
																_UpperCAmelCase											=     ids_tensor([self.batch_size]     ,       self.num_labels		)

									_UpperCAmelCase											=     self.get_config()

									return config, pixel_values, labels
		def       UpperCAmelCase__							(     self		)					->			List[str]:




									"""simple docstring"""





									return SwiftFormerConfig(
									    depths=self.layer_depths     ,       embed_dims=self.embed_dims     ,       mlp_ratio=4     ,       downsamples=[True, True, True, True]     ,       hidden_act='gelu'     ,       num_labels=self.num_labels     ,       down_patch_size=3     ,       down_stride=2     ,       down_pad=1     ,       drop_rate=0.0     ,       drop_path_rate=0.0     ,       use_layer_scale=_SCREAMING_SNAKE_CASE     ,       layer_scale_init_value=1e-5     ,       )
		def       UpperCAmelCase__							(     self     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		)					->			Optional[int]:




									"""simple docstring"""





									_UpperCAmelCase											=     SwiftFormerModel(config=_SCREAMING_SNAKE_CASE		)
									model.to(_SCREAMING_SNAKE_CASE		)
									model.eval()
									_UpperCAmelCase											=     model(_SCREAMING_SNAKE_CASE		)
									self.parent.assertEqual(result.last_hidden_state.shape     ,       (self.batch_size, self.embed_dims[-1], 7, 7)		)
		def       UpperCAmelCase__							(     self     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		)					->			List[str]:




									"""simple docstring"""





									_UpperCAmelCase											=     self.num_labels
									_UpperCAmelCase											=     SwiftFormerForImageClassification(_SCREAMING_SNAKE_CASE		)
									model.to(_SCREAMING_SNAKE_CASE		)
									model.eval()
									_UpperCAmelCase											=     model(_SCREAMING_SNAKE_CASE     ,       labels=_SCREAMING_SNAKE_CASE		)
									self.parent.assertEqual(result.logits.shape     ,       (self.batch_size, self.num_labels)		)

									_UpperCAmelCase											=     SwiftFormerForImageClassification(_SCREAMING_SNAKE_CASE		)
									model.to(_SCREAMING_SNAKE_CASE		)
									model.eval()

									_UpperCAmelCase											=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)
									_UpperCAmelCase											=     model(_SCREAMING_SNAKE_CASE		)
									self.parent.assertEqual(result.logits.shape     ,       (self.batch_size, self.num_labels)		)






		def       UpperCAmelCase__							(     self		)					->			Tuple:




									"""simple docstring"""





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



@require_torch
class 						__a (							UpperCAmelCase       , UpperCAmelCase       , unittest.TestCase     ):
		_a      :    int           =      (SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else ()
		_a      :    List[str]           =      (
		    {'feature-extraction': SwiftFormerModel, 'image-classification': SwiftFormerForImageClassification}
		    if is_torch_available()
		    else {}
		)

		_a      :    str           =      False
		_a      :    Union[str, Any]           =      False
		_a      :    Optional[Any]           =      False
		_a      :    Dict           =      False
		_a      :    int           =      False
		def       UpperCAmelCase__							(     self		)					->			List[Any]:




									"""simple docstring"""





									_UpperCAmelCase											=     SwiftFormerModelTester(self		)
									_UpperCAmelCase											=     ConfigTester(
									    self     ,       config_class=_SCREAMING_SNAKE_CASE     ,       has_text_modality=_SCREAMING_SNAKE_CASE     ,       hidden_size=37     ,       num_attention_heads=12     ,       num_hidden_layers=12     ,       )
		def       UpperCAmelCase__							(     self		)					->			int:




									"""simple docstring"""





									self.config_tester.run_common_tests()
		@unittest.skip(reason='SwiftFormer does not use inputs_embeds'		)
		def       UpperCAmelCase__							(     self		)					->			Any:




									"""simple docstring"""





									pass
		def       UpperCAmelCase__							(     self		)					->			Dict:




									"""simple docstring"""





									_UpperCAmelCase						,			_UpperCAmelCase											=     self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
																_UpperCAmelCase											=     model_class(_SCREAMING_SNAKE_CASE		)
																_UpperCAmelCase											=     model.get_output_embeddings()
																self.assertTrue(x is None or isinstance(_SCREAMING_SNAKE_CASE     ,       nn.Linear		)		)
		def       UpperCAmelCase__							(     self		)					->			Tuple:




									"""simple docstring"""





									_UpperCAmelCase						,			_UpperCAmelCase											=     self.model_tester.prepare_config_and_inputs_for_common()

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

																_UpperCAmelCase											=     ['pixel_values']
																self.assertListEqual(arg_names[:1]     ,       _SCREAMING_SNAKE_CASE		)
		def       UpperCAmelCase__							(     self		)					->			Optional[Any]:




									"""simple docstring"""





									_UpperCAmelCase											=     self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE		)
		def       UpperCAmelCase__							(     self		)					->			str:




									"""simple docstring"""





									_UpperCAmelCase											=     self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE		)
		@slow
		def       UpperCAmelCase__							(     self		)					->			int:




									"""simple docstring"""





									for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																_UpperCAmelCase											=     SwiftFormerModel.from_pretrained(_SCREAMING_SNAKE_CASE		)
																self.assertIsNotNone(_SCREAMING_SNAKE_CASE		)
		@unittest.skip(reason='SwiftFormer does not output attentions'		)
		def       UpperCAmelCase__							(     self		)					->			Optional[int]:




									"""simple docstring"""





									pass
		def       UpperCAmelCase__							(     self		)					->			Optional[int]:




									"""simple docstring"""





									def check_hidden_states_output(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		):
																_UpperCAmelCase											=     model_class(_SCREAMING_SNAKE_CASE		)
																model.to(_SCREAMING_SNAKE_CASE		)
																model.eval()

																with torch.no_grad():
																							_UpperCAmelCase											=     model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		)		)

																_UpperCAmelCase											=     outputs.hidden_states

																_UpperCAmelCase											=     8
																self.assertEqual(len(_SCREAMING_SNAKE_CASE		)     ,       _SCREAMING_SNAKE_CASE		)  # TODO

																# SwiftFormer's feature maps are of shape (batch_size, embed_dims, height, width)
																# with the width and height being successively divided by 2, after every 2 blocks
																for i in range(len(_SCREAMING_SNAKE_CASE		)		):
																							self.assertEqual(
																							    hidden_states[i].shape     ,       torch.Size(
																							        [
																							            self.model_tester.batch_size,
																							            self.model_tester.embed_dims[i // 2],
																							            (self.model_tester.image_size // 4) // 2 ** (i // 2),
																							            (self.model_tester.image_size // 4) // 2 ** (i // 2),
																							        ]		)     ,       )

									_UpperCAmelCase						,			_UpperCAmelCase											=     self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
																_UpperCAmelCase											=     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"]
																_UpperCAmelCase											=     True

																check_hidden_states_output(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		)
		def       UpperCAmelCase__							(     self		)					->			Optional[int]:




									"""simple docstring"""





									def _config_zero_init(_SCREAMING_SNAKE_CASE		):
																_UpperCAmelCase											=     copy.deepcopy(_SCREAMING_SNAKE_CASE		)
																for key in configs_no_init.__dict__.keys():
																							if "_range" in key or "_std" in key or "initializer_factor" in key or "layer_scale" in key:
																														setattr(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       1e-1_0		)
																							if isinstance(getattr(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		)     ,       _SCREAMING_SNAKE_CASE		):
																														_UpperCAmelCase											=     _config_zero_init(getattr(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		)		)
																														setattr(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		)
																return configs_no_init

									_UpperCAmelCase						,			_UpperCAmelCase											=     self.model_tester.prepare_config_and_inputs_for_common()

									_UpperCAmelCase											=     _config_zero_init(_SCREAMING_SNAKE_CASE		)
									for model_class in self.all_model_classes:
																_UpperCAmelCase											=     model_class(config=_SCREAMING_SNAKE_CASE		)
																for name, param in model.named_parameters():
																							if param.requires_grad:
																														self.assertIn(
																														    ((param.data.mean() * 1e9) / 1e9).round().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       UpperCAmelCase__							(     self		)					->			int:




									"""simple docstring"""





									pass



def 			lowerCAmelCase__					(     )    ->						int:


							'''simple docstring'''





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







@require_torch
@require_vision
class 						__a (							unittest.TestCase     ):
		@cached_property
		def       UpperCAmelCase__							(     self		)					->			List[Any]:




									"""simple docstring"""





									return ViTImageProcessor.from_pretrained('MBZUAI/swiftformer-xs'		) if is_vision_available() else None






		@slow
		def       UpperCAmelCase__							(     self		)					->			Dict:




									"""simple docstring"""





									_UpperCAmelCase											=     SwiftFormerForImageClassification.from_pretrained('MBZUAI/swiftformer-xs'		).to(_SCREAMING_SNAKE_CASE		)

									_UpperCAmelCase											=     self.default_image_processor
									_UpperCAmelCase											=     prepare_img()
									_UpperCAmelCase											=     image_processor(images=_SCREAMING_SNAKE_CASE     ,       return_tensors='pt'		).to(_SCREAMING_SNAKE_CASE		)

									# forward pass
									with torch.no_grad():
																_UpperCAmelCase											=     model(**_SCREAMING_SNAKE_CASE		)

									# verify the logits
									_UpperCAmelCase											=     torch.Size((1, 1000)		)
									self.assertEqual(outputs.logits.shape     ,       _SCREAMING_SNAKE_CASE		)

									_UpperCAmelCase											=     torch.tensor([[-2.1_7_0_3e0_0, 2.1_1_0_7e0_0, -2.0_8_1_1e0_0]]		).to(_SCREAMING_SNAKE_CASE		)
									self.assertTrue(torch.allclose(outputs.logits[0, :3]     ,       _SCREAMING_SNAKE_CASE     ,       atol=1e-4		)		)




import math

import qiskit

def 			lowerCAmelCase__					(     a__:						int = 1     ,    a__:						int = 1     ,    a__:						int = 1			)    ->						qiskit.result.counts.Counts:


							'''simple docstring'''





							if (
							    isinstance(a__     ,    a__			)
							    or isinstance(a__     ,    a__			)
							    or isinstance(a__     ,    a__			)
							):
														raise TypeError('inputs must be integers.'			)

							if (input_a < 0) or (input_a < 0) or (carry_in < 0):
														raise ValueError('inputs must be positive.'			)

							if (
							    (math.floor(a__			) != input_a)
							    or (math.floor(a__			) != input_a)
							    or (math.floor(a__			) != carry_in)
							):
														raise ValueError('inputs must be exact integers.'			)

							if (input_a > 2) or (input_a > 2) or (carry_in > 2):
														raise ValueError('inputs must be less or equal to 2.'			)

							# build registers
							_UpperCAmelCase											=     qiskit.QuantumRegister(4     ,    'qr'			)
							_UpperCAmelCase											=     qiskit.ClassicalRegister(2     ,    'cr'			)
							# list the entries
							_UpperCAmelCase											=     [input_a, input_a, carry_in]

							_UpperCAmelCase											=     qiskit.QuantumCircuit(a__     ,    a__			)

							for i in range(0     ,    3			):
														if entry[i] == 2:
																					quantum_circuit.h(a__			)  # for hadamard entries
														elif entry[i] == 1:
																					quantum_circuit.x(a__			)  # for 1 entries
														elif entry[i] == 0:
																					quantum_circuit.i(a__			)  # for 0 entries

    # build the circuit
							quantum_circuit.ccx(0     ,    1     ,    3			)  # ccx = toffoli gate
							quantum_circuit.cx(0     ,    1			)
							quantum_circuit.ccx(1     ,    2     ,    3			)
							quantum_circuit.cx(1     ,    2			)
							quantum_circuit.cx(0     ,    1			)

							quantum_circuit.measure([2, 3]     ,    a__			)  # measure the last two qbits

							_UpperCAmelCase											=     qiskit.Aer.get_backend('aer_simulator'			)
							_UpperCAmelCase											=     qiskit.execute(a__     ,    a__     ,    shots=1_0_0_0			)

							return job.result().get_counts(a__			)


if __name__ == "__main__":
		print(f'''Total sum count for state is: {quantum_full_adder(1, 1, 1)}''')
