



"""simple docstring"""






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 	__SCREAMING_SNAKE_CASE     :


					'''simple docstring'''





					def __init__(	self							:  int,  lowerCamelCase							:  Union[str, Any],  lowerCamelCase							:  str=13,  lowerCamelCase							:  Optional[Any]=3,  lowerCamelCase							:  List[str]=True,  lowerCamelCase							:  str=True,  lowerCamelCase							:  Optional[int]=0.1,  lowerCamelCase							:  Union[str, Any]=0.1,  lowerCamelCase							:  Optional[Any]=224,  lowerCamelCase							:  str=1000,  lowerCamelCase							:  Optional[Any]=[3, 3, 6, 4],  lowerCamelCase							:  int=[48, 56, 112, 220],  )-> Any:
								lowerCamelCase__		:		int		     =parent
								lowerCamelCase__		:		Union[str, Any]		     =batch_size
								lowerCamelCase__		:		Optional[Any]		     =num_channels
								lowerCamelCase__		:		List[Any]		     =is_training
								lowerCamelCase__		:		Optional[Any]		     =use_labels
								lowerCamelCase__		:		List[Any]		     =hidden_dropout_prob
								lowerCamelCase__		:		Optional[int]		     =attention_probs_dropout_prob
								lowerCamelCase__		:		Dict		     =num_labels
								lowerCamelCase__		:		Union[str, Any]		     =image_size
								lowerCamelCase__		:		Optional[int]		     =layer_depths
								lowerCamelCase__		:		int		     =embed_dims



					def 		snake_case	(	self							:  Tuple					)-> Union[str, Any]:
								lowerCamelCase__		:		Union[str, Any]		     =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

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

								lowerCamelCase__		:		List[str]		     =self.get_config()

								return config, pixel_values, labels



					def 		snake_case	(	self							:  Optional[Any]					)-> Any:
								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=lowerCamelCase,  layer_scale_init_value=1E-5,  )



					def 		snake_case	(	self							:  str,  lowerCamelCase							:  Optional[Any],  lowerCamelCase							:  str,  lowerCamelCase							:  Any					)-> Dict:
								lowerCamelCase__		:		Dict		     =SwiftFormerModel(config=lowerCamelCase					)
								model.to(lowerCamelCase					)
								model.eval()
								lowerCamelCase__		:		List[Any]		     =model(lowerCamelCase					)
								self.parent.assertEqual(result.last_hidden_state.shape,  (self.batch_size, self.embed_dims[-1], 7, 7)					)



					def 		snake_case	(	self							:  List[str],  lowerCamelCase							:  Optional[int],  lowerCamelCase							:  List[str],  lowerCamelCase							:  List[Any]					)-> Any:
								lowerCamelCase__		:		str		     =self.num_labels
								lowerCamelCase__		:		List[str]		     =SwiftFormerForImageClassification(lowerCamelCase					)
								model.to(lowerCamelCase					)
								model.eval()
								lowerCamelCase__		:		List[str]		     =model(lowerCamelCase,  labels=lowerCamelCase					)
								self.parent.assertEqual(result.logits.shape,  (self.batch_size, self.num_labels)					)

								lowerCamelCase__		:		Tuple		     =SwiftFormerForImageClassification(lowerCamelCase					)
								model.to(lowerCamelCase					)
								model.eval()

								lowerCamelCase__		:		List[Any]		     =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)
								lowerCamelCase__		:		List[Any]		     =model(lowerCamelCase					)
								self.parent.assertEqual(result.logits.shape,  (self.batch_size, self.num_labels)					)




					def 		snake_case	(	self							:  Any					)-> Optional[int]:
								((lowerCamelCase__)     ,       (lowerCamelCase__)     ,       (lowerCamelCase__))		:		Optional[Any]		     =self.prepare_config_and_inputs()
								lowerCamelCase__		:		Tuple		     ={'''pixel_values''': pixel_values}
								return config, inputs_dict





@require_torch
class 	__SCREAMING_SNAKE_CASE     (				lowerCAmelCase_		,       lowerCAmelCase_		,       unittest.TestCase       ):


					'''simple docstring'''





					_a             =							(SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else ()
					_a             =							(
					    {'feature-extraction': SwiftFormerModel, 'image-classification': SwiftFormerForImageClassification}
					    if is_torch_available()
					    else {}
					)

					_a             =							False
					_a             =							False
					_a             =							False
					_a             =							False
					_a             =							False



					def 		snake_case	(	self							:  Dict					)-> Dict:
								lowerCamelCase__		:		List[Any]		     =SwiftFormerModelTester(self					)
								lowerCamelCase__		:		Optional[Any]		     =ConfigTester(
								    self,  config_class=lowerCamelCase,  has_text_modality=lowerCamelCase,  hidden_size=37,  num_attention_heads=12,  num_hidden_layers=12,  )



					def 		snake_case	(	self							:  Dict					)-> Any:
								self.config_tester.run_common_tests()



					@unittest.skip(reason='''SwiftFormer does not use inputs_embeds'''					)
					def 		snake_case	(	self							:  int					)-> Union[str, Any]:
								pass



					def 		snake_case	(	self							:  int					)-> Union[str, Any]:
								lowerCamelCase__     ,       lowerCamelCase__		:		Tuple		     =self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
											lowerCamelCase__		:		Any		     =model_class(lowerCamelCase					)
											lowerCamelCase__		:		List[str]		     =model.get_output_embeddings()
											self.assertTrue(x is None or isinstance(lowerCamelCase,  nn.Linear					)					)



					def 		snake_case	(	self							:  Tuple					)-> int:
								lowerCamelCase__     ,       lowerCamelCase__		:		Any		     =self.model_tester.prepare_config_and_inputs_for_common()

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

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



					def 		snake_case	(	self							:  Optional[int]					)-> Tuple:
								lowerCamelCase__		:		Union[str, Any]		     =self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*lowerCamelCase					)



					def 		snake_case	(	self							:  int					)-> Union[str, Any]:
								lowerCamelCase__		:		List[str]		     =self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*lowerCamelCase					)



					@slow
					def 		snake_case	(	self							:  Optional[Any]					)-> Optional[Any]:
								for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											lowerCamelCase__		:		str		     =SwiftFormerModel.from_pretrained(lowerCamelCase					)
											self.assertIsNotNone(lowerCamelCase					)



					@unittest.skip(reason='''SwiftFormer does not output attentions'''					)
					def 		snake_case	(	self							:  Union[str, Any]					)-> List[Any]:
								pass



					def 		snake_case	(	self							:  Tuple					)-> List[Any]:
								def check_hidden_states_output(lowerCamelCase							:  Optional[Any],  lowerCamelCase							:  List[str],  lowerCamelCase							:  List[Any]					):
											lowerCamelCase__		:		str		     =model_class(lowerCamelCase					)
											model.to(lowerCamelCase					)
											model.eval()

											with torch.no_grad():
														lowerCamelCase__		:		List[Any]		     =model(**self._prepare_for_class(lowerCamelCase,  lowerCamelCase					)					)

											lowerCamelCase__		:		Optional[int]		     =outputs.hidden_states

											lowerCamelCase__		:		Tuple		     =8
											self.assertEqual(len(lowerCamelCase					),  lowerCamelCase					)  # 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(lowerCamelCase					)					):
														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),
														        ]					),  )

								lowerCamelCase__     ,       lowerCamelCase__		:		Optional[Any]		     =self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
											lowerCamelCase__		:		str		     =True
											check_hidden_states_output(lowerCamelCase,  lowerCamelCase,  lowerCamelCase					)

											# check that output_hidden_states also work using config
											del inputs_dict["output_hidden_states"]
											lowerCamelCase__		:		List[str]		     =True

											check_hidden_states_output(lowerCamelCase,  lowerCamelCase,  lowerCamelCase					)



					def 		snake_case	(	self							:  int					)-> List[str]:
								def _config_zero_init(lowerCamelCase							:  Optional[Any]					):
											lowerCamelCase__		:		List[Any]		     =copy.deepcopy(lowerCamelCase					)
											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(lowerCamelCase,  lowerCamelCase,  1E-10					)
														if isinstance(getattr(lowerCamelCase,  lowerCamelCase,  lowerCamelCase					),  lowerCamelCase					):
																	lowerCamelCase__		:		str		     =_config_zero_init(getattr(lowerCamelCase,  lowerCamelCase					)					)
																	setattr(lowerCamelCase,  lowerCamelCase,  lowerCamelCase					)
											return configs_no_init

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

								lowerCamelCase__		:		Any		     =_config_zero_init(lowerCamelCase					)
								for model_class in self.all_model_classes:
											lowerCamelCase__		:		List[Any]		     =model_class(config=lowerCamelCase					)
											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 		snake_case	(	self							:  Dict					)-> Union[str, Any]:
								pass






def 					snake_case__       (		):
			"""simple docstring"""
			lowerCamelCase__		:		Optional[Any]		     =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''     )
			return image

@require_torch
@require_vision
class 	__SCREAMING_SNAKE_CASE     (				unittest.TestCase       ):


					'''simple docstring'''





					@cached_property
					def 		snake_case	(	self							:  List[Any]					)-> str:
								return ViTImageProcessor.from_pretrained('''MBZUAI/swiftformer-xs'''					) if is_vision_available() else None




					@slow
					def 		snake_case	(	self							:  int					)-> Dict:
								lowerCamelCase__		:		str		     =SwiftFormerForImageClassification.from_pretrained('''MBZUAI/swiftformer-xs'''					).to(lowerCamelCase					)

								lowerCamelCase__		:		Any		     =self.default_image_processor
								lowerCamelCase__		:		Tuple		     =prepare_img()
								lowerCamelCase__		:		Tuple		     =image_processor(images=lowerCamelCase,  return_tensors='''pt'''					).to(lowerCamelCase					)

								# forward pass
								with torch.no_grad():
											lowerCamelCase__		:		Tuple		     =model(**lowerCamelCase					)

								# verify the logits
								lowerCamelCase__		:		Tuple		     =torch.Size((1, 1000)					)
								self.assertEqual(outputs.logits.shape,  lowerCamelCase					)

								lowerCamelCase__		:		Dict		     =torch.tensor([[-2.1703E00, 2.1107E00, -2.0811E00]]					).to(lowerCamelCase					)
								self.assertTrue(torch.allclose(outputs.logits[0, :3],  lowerCamelCase,  atol=1E-4					)					)









"""simple docstring"""






def 					snake_case__       (		__lowerCamelCase    :   int							,		__lowerCamelCase    :   int     ):
			"""simple docstring"""
			return int((input_a, input_a).count(0     ) != 0     )






def 					snake_case__       (		):
			"""simple docstring"""
			assert nand_gate(0							,		0     ) == 1
			assert nand_gate(0							,		1     ) == 1
			assert nand_gate(1							,		0     ) == 1
			assert nand_gate(1							,		1     ) == 0


if __name__ == "__main__":
		print(nand_gate(0, 0))
		print(nand_gate(0, 1))
		print(nand_gate(1, 0))
		print(nand_gate(1, 1))




