



'''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 	UpperCAmelCase	:


	'''simple docstring'''




	def __init__(   self							,  lowerCAmelCase_							,  lowerCAmelCase_=1_3							,  lowerCAmelCase_=3							,  lowerCAmelCase_=True							,  lowerCAmelCase_=True							,  lowerCAmelCase_=0.1							,  lowerCAmelCase_=0.1							,  lowerCAmelCase_=2_2_4							,  lowerCAmelCase_=1_0_0_0							,  lowerCAmelCase_=[3, 3, 6, 4]							,  lowerCAmelCase_=[4_8, 5_6, 1_1_2, 2_2_0]							,  ) ->      Any:



						"""simple docstring"""







						a_       		=parent
						a_       		=batch_size
						a_       		=num_channels
						a_       		=is_training
						a_       		=use_labels
						a_       		=hidden_dropout_prob
						a_       		=attention_probs_dropout_prob
						a_       		=num_labels
						a_       		=image_size
						a_       		=layer_depths
						a_       		=embed_dims




	def       lowercase_  (   self) ->      Optional[int]:



						"""simple docstring"""







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

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

						a_       		=self.get_config()

						return config, pixel_values, labels




	def       lowercase_  (   self) ->      Dict:



						"""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=lowerCAmelCase_							,  layer_scale_init_value=1e-5							,  )




	def       lowercase_  (   self							,  lowerCAmelCase_							,  lowerCAmelCase_							,  lowerCAmelCase_) ->      Tuple:



						"""simple docstring"""







						a_       		=SwiftFormerModel(config=lowerCAmelCase_)
						model.to(lowerCAmelCase_)
						model.eval()
						a_       		=model(lowerCAmelCase_)
						self.parent.assertEqual(result.last_hidden_state.shape							,  (self.batch_size, self.embed_dims[-1], 7, 7))




	def       lowercase_  (   self							,  lowerCAmelCase_							,  lowerCAmelCase_							,  lowerCAmelCase_) ->      Any:



						"""simple docstring"""







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

						a_       		=SwiftFormerForImageClassification(lowerCAmelCase_)
						model.to(lowerCAmelCase_)
						model.eval()

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




	def       lowercase_  (   self) ->      str:



						"""simple docstring"""







						((a_)		,						(a_)		,						(a_))       		=self.prepare_config_and_inputs()
						a_       		={"pixel_values": pixel_values}
						return config, inputs_dict







@require_torch
class 	UpperCAmelCase	(		__a					,	__a					,	unittest.TestCase):


	'''simple docstring'''




	__magic_name__					: Any  =      (SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else ()
	__magic_name__					: List[Any]  =      (
	    {"feature-extraction": SwiftFormerModel, "image-classification": SwiftFormerForImageClassification}
	    if is_torch_available()
	    else {}
	)

	__magic_name__					: Union[str, Any]  =      False
	__magic_name__					: List[Any]  =      False
	__magic_name__					: int  =      False
	__magic_name__					: List[str]  =      False
	__magic_name__					: List[Any]  =      False




	def       lowercase_  (   self) ->      int:



						"""simple docstring"""







						a_       		=SwiftFormerModelTester(self)
						a_       		=ConfigTester(
						    self							,  config_class=lowerCAmelCase_							,  has_text_modality=lowerCAmelCase_							,  hidden_size=3_7							,  num_attention_heads=1_2							,  num_hidden_layers=1_2							,  )




	def       lowercase_  (   self) ->      List[str]:



						"""simple docstring"""







						self.config_tester.run_common_tests()




	@unittest.skip(reason="SwiftFormer does not use inputs_embeds")
	def       lowercase_  (   self) ->      Optional[Any]:



						"""simple docstring"""







						pass




	def       lowercase_  (   self) ->      Dict:



						"""simple docstring"""







						a_		,						a_       		=self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
											a_       		=model_class(lowerCAmelCase_)
											a_       		=model.get_output_embeddings()
											self.assertTrue(x is None or isinstance(lowerCAmelCase_							,  nn.Linear))




	def       lowercase_  (   self) ->      Tuple:



						"""simple docstring"""







						a_		,						a_       		=self.model_tester.prepare_config_and_inputs_for_common()

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

											a_       		=["pixel_values"]
											self.assertListEqual(arg_names[:1]							,  lowerCAmelCase_)




	def       lowercase_  (   self) ->      Any:



						"""simple docstring"""







						a_       		=self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*lowerCAmelCase_)




	def       lowercase_  (   self) ->      Optional[Any]:



						"""simple docstring"""







						a_       		=self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase_)




	@slow
	def       lowercase_  (   self) ->      List[str]:



						"""simple docstring"""







						for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											a_       		=SwiftFormerModel.from_pretrained(lowerCAmelCase_)
											self.assertIsNotNone(lowerCAmelCase_)




	@unittest.skip(reason="SwiftFormer does not output attentions")
	def       lowercase_  (   self) ->      Any:



						"""simple docstring"""







						pass




	def       lowercase_  (   self) ->      str:



						"""simple docstring"""







						def check_hidden_states_output(lowerCAmelCase_							,  lowerCAmelCase_							,  lowerCAmelCase_):
											a_       		=model_class(lowerCAmelCase_)
											model.to(lowerCAmelCase_)
											model.eval()

											with torch.no_grad():
																a_       		=model(**self._prepare_for_class(lowerCAmelCase_							,  lowerCAmelCase_))

											a_       		=outputs.hidden_states

											a_       		=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),
																        ])							,  )

						a_		,						a_       		=self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
											a_       		=True
											check_hidden_states_output(lowerCAmelCase_							,  lowerCAmelCase_							,  lowerCAmelCase_)

											# check that output_hidden_states also work using config
											del inputs_dict["output_hidden_states"]
											a_       		=True

											check_hidden_states_output(lowerCAmelCase_							,  lowerCAmelCase_							,  lowerCAmelCase_)




	def       lowercase_  (   self) ->      str:



						"""simple docstring"""







						def _config_zero_init(lowerCAmelCase_):
											a_       		=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_):
																					a_       		=_config_zero_init(getattr(lowerCAmelCase_							,  lowerCAmelCase_))
																					setattr(lowerCAmelCase_							,  lowerCAmelCase_							,  lowerCAmelCase_)
											return configs_no_init

						a_		,						a_       		=self.model_tester.prepare_config_and_inputs_for_common()

						a_       		=_config_zero_init(lowerCAmelCase_)
						for model_class in self.all_model_classes:
											a_       		=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       lowercase_  (   self) ->      Optional[int]:



						"""simple docstring"""







						pass






def  UpperCAmelCase_       (		):


					'''simple docstring'''







					a_       		=Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"       )
					return image







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


	'''simple docstring'''




	@cached_property
	def       lowercase_  (   self) ->      Union[str, Any]:



						"""simple docstring"""







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




	@slow
	def       lowercase_  (   self) ->      str:



						"""simple docstring"""







						a_       		=SwiftFormerForImageClassification.from_pretrained("MBZUAI/swiftformer-xs").to(lowerCAmelCase_)

						a_       		=self.default_image_processor
						a_       		=prepare_img()
						a_       		=image_processor(images=lowerCAmelCase_							,  return_tensors="pt").to(lowerCAmelCase_)

						# forward pass
						with torch.no_grad():
											a_       		=model(**lowerCAmelCase_)

						# verify the logits
						a_       		=torch.Size((1, 1_0_0_0))
						self.assertEqual(outputs.logits.shape							,  lowerCAmelCase_)

						a_       		=torch.tensor([[-2.1703e00, 2.1107e00, -2.0811e00]]).to(lowerCAmelCase_)
						self.assertTrue(torch.allclose(outputs.logits[0, :3]							,  lowerCAmelCase_							,  atol=1e-4))







'''simple docstring'''


from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_tf_available,
    is_torch_available,
)


lowercase							       =			{
    '''configuration_vision_encoder_decoder''': ['''VisionEncoderDecoderConfig''', '''VisionEncoderDecoderOnnxConfig''']
}

try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  lowercase							       =			['''VisionEncoderDecoderModel''']

try:
  if not is_tf_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  lowercase							       =			['''TFVisionEncoderDecoderModel''']

try:
  if not is_flax_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  lowercase							       =			['''FlaxVisionEncoderDecoderModel''']

if TYPE_CHECKING:
  from .configuration_vision_encoder_decoder import VisionEncoderDecoderConfig, VisionEncoderDecoderOnnxConfig

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_vision_encoder_decoder import VisionEncoderDecoderModel

  try:
    if not is_tf_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_tf_vision_encoder_decoder import TFVisionEncoderDecoderModel

  try:
    if not is_flax_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_flax_vision_encoder_decoder import FlaxVisionEncoderDecoderModel

else:
  import sys

  lowercase							       =			_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)


