

'''simple docstring'''
import inspect
import unittest

from transformers import ViTMSNConfig
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 ViTMSNForImageClassification, ViTMSNModel
    from transformers.models.vit_msn.modeling_vit_msn import VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
    from PIL import Image

    from transformers import ViTImageProcessor


class        a__  :






   """simple docstring"""




   def __init__(			self      ,    _UpperCamelCase      ,    _UpperCamelCase=13      ,    _UpperCamelCase=30      ,    _UpperCamelCase=2      ,    _UpperCamelCase=3      ,    _UpperCamelCase=True      ,    _UpperCamelCase=True      ,    _UpperCamelCase=32      ,    _UpperCamelCase=5      ,    _UpperCamelCase=4      ,    _UpperCamelCase=37      ,    _UpperCamelCase="gelu"      ,    _UpperCamelCase=0.1      ,    _UpperCamelCase=0.1      ,    _UpperCamelCase=10      ,    _UpperCamelCase=0.0_2      ,    _UpperCamelCase=None      ,    ):





      """simple docstring"""





      _lowercase      :				str      					=       parent
      _lowercase      :				Any      					=       batch_size
      _lowercase      :				int      					=       image_size
      _lowercase      :				Optional[Any]      					=       patch_size
      _lowercase      :				Optional[int]      					=       num_channels
      _lowercase      :				List[Any]      					=       is_training
      _lowercase      :				str      					=       use_labels
      _lowercase      :				Any      					=       hidden_size
      _lowercase      :				List[str]      					=       num_hidden_layers
      _lowercase      :				List[Any]      					=       num_attention_heads
      _lowercase      :				str      					=       intermediate_size
      _lowercase      :				Optional[int]      					=       hidden_act
      _lowercase      :				Any      					=       hidden_dropout_prob
      _lowercase      :				List[Any]      					=       attention_probs_dropout_prob
      _lowercase      :				List[str]      					=       type_sequence_label_size
      _lowercase      :				Optional[Any]      					=       initializer_range
      _lowercase      :				Optional[int]      					=       scope

      # in ViT MSN, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
      _lowercase      :				int      					=       (image_size // patch_size) ** 2
      _lowercase      :				List[Any]      					=       num_patches + 1


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase      :				Tuple      					=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

      _lowercase      :				Dict      					=       None
      if self.use_labels:
         _lowercase      :				List[Any]      					=       ids_tensor([self.batch_size]      ,    self.type_sequence_label_size  )

      _lowercase      :				int      					=       self.get_config()

      return config, pixel_values, labels


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      return ViTMSNConfig(
          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      ,    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      ,    initializer_range=self.initializer_range      ,    )


   def 						_lowerCamelCase       (			self      ,    _UpperCamelCase      ,    _UpperCamelCase      ,    _UpperCamelCase  ):





      """simple docstring"""





      _lowercase      :				Optional[Any]      					=       ViTMSNModel(config=_a  )
      model.to(_a  )
      model.eval()
      _lowercase      :				str      					=       model(_a  )
      self.parent.assertEqual(result.last_hidden_state.shape      ,    (self.batch_size, self.seq_length, self.hidden_size)  )


   def 						_lowerCamelCase       (			self      ,    _UpperCamelCase      ,    _UpperCamelCase      ,    _UpperCamelCase  ):





      """simple docstring"""





      _lowercase      :				Optional[int]      					=       self.type_sequence_label_size
      _lowercase      :				List[Any]      					=       ViTMSNForImageClassification(_a  )
      model.to(_a  )
      model.eval()
      _lowercase      :				Tuple      					=       model(_a      ,    labels=_a  )
      print("Pixel and labels shape: {pixel_values.shape}, {labels.shape}"  )
      print("Labels: {labels}"  )
      self.parent.assertEqual(result.logits.shape      ,    (self.batch_size, self.type_sequence_label_size)  )

      # test greyscale images
      _lowercase      :				Optional[int]      					=       1
      _lowercase      :				List[str]      					=       ViTMSNForImageClassification(_a  )
      model.to(_a  )
      model.eval()

      _lowercase      :				Tuple      					=       floats_tensor([self.batch_size, 1, self.image_size, self.image_size]  )
      _lowercase      :				Optional[int]      					=       model(_a  )
      self.parent.assertEqual(result.logits.shape      ,    (self.batch_size, self.type_sequence_label_size)  )






   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





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




@require_torch
class        a__  (							UpperCamelCase_  ,				UpperCamelCase_  ,				unittest.TestCase  ):






   """simple docstring"""




   _SCREAMING_SNAKE_CASE   :					Any     	=							(ViTMSNModel, ViTMSNForImageClassification) if is_torch_available() else ()
   _SCREAMING_SNAKE_CASE   :					List[Any]     	=							(
       {"""feature-extraction""": ViTMSNModel, """image-classification""": ViTMSNForImageClassification}
       if is_torch_available()
       else {}
   )

   _SCREAMING_SNAKE_CASE   :					Dict     	=							False
   _SCREAMING_SNAKE_CASE   :					Dict     	=							False
   _SCREAMING_SNAKE_CASE   :					Optional[Any]     	=							False
   _SCREAMING_SNAKE_CASE   :					str     	=							False


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase      :				Optional[Any]      					=       ViTMSNModelTester(self  )
      _lowercase      :				Union[str, Any]      					=       ConfigTester(self      ,    config_class=_a      ,    has_text_modality=_a      ,    hidden_size=37  )


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      self.config_tester.run_common_tests()


   @unittest.skip(reason="ViTMSN does not use inputs_embeds"  )
   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      pass


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase      :				Any      					=       self.model_tester.prepare_config_and_inputs_for_common()

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


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase      :				int      					=       self.model_tester.prepare_config_and_inputs_for_common()

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

         _lowercase      :				str      					=       ["""pixel_values"""]
         self.assertListEqual(arg_names[:1]      ,    _a  )


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





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


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase      :				List[Any]      					=       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*_a  )






   @slow
   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      for model_name in VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         _lowercase      :				Dict      					=       ViTMSNModel.from_pretrained(_a  )
         self.assertIsNotNone(_a  )







def  _A		(     )      ->     Union[str, Any]:
   _lowercase      :				Tuple      					=       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"					)
   return image


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






   """simple docstring"""




   @cached_property
   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      return ViTImageProcessor.from_pretrained("facebook/vit-msn-small"  ) if is_vision_available() else None






   @slow
   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      torch.manual_seed(2  )
      _lowercase      :				int      					=       ViTMSNForImageClassification.from_pretrained("facebook/vit-msn-small"  ).to(_a  )

      _lowercase      :				Dict      					=       self.default_image_processor
      _lowercase      :				str      					=       prepare_img()
      _lowercase      :				int      					=       image_processor(images=_a      ,    return_tensors="pt"  ).to(_a  )

      # forward pass
      with torch.no_grad():
         _lowercase      :				Union[str, Any]      					=       model(**_a  )

      # verify the logits
      _lowercase      :				Dict      					=       torch.Size((1, 1000)  )
      self.assertEqual(outputs.logits.shape      ,    _a  )

      _lowercase      :				List[str]      					=       torch.tensor([-0.0_8_0_3, -0.4_4_5_4, -0.2_3_7_5]  ).to(_a  )

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









'''simple docstring'''
import random
import unittest

import torch

from diffusers import IFImgaImgSuperResolutionPipeline
from diffusers.utils import floats_tensor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import skip_mps, torch_device

from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin


@skip_mps
class        a__  (							lowerCamelCase_  ,				lowerCamelCase_  ,				unittest.TestCase  ):
   _SCREAMING_SNAKE_CASE   :					List[str]     	=							IFImgaImgSuperResolutionPipeline
   _SCREAMING_SNAKE_CASE   :					int     	=							TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'width', 'height'}
   _SCREAMING_SNAKE_CASE   :					List[str]     	=							TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'original_image'}  )
   _SCREAMING_SNAKE_CASE   :					Optional[int]     	=							PipelineTesterMixin.required_optional_params - {'latents'}


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      return self._get_superresolution_dummy_components()


   def 						_lowerCamelCase       (			self      ,    _UpperCamelCase      ,    _UpperCamelCase=0  ):





      """simple docstring"""





      if str(_UpperCamelCase  ).startswith("mps"  ):
         _lowercase      :				Tuple      					=       torch.manual_seed(_UpperCamelCase  )
      else:
         _lowercase      :				int      					=       torch.Generator(device=_UpperCamelCase  ).manual_seed(_UpperCamelCase  )

      _lowercase      :				List[Any]      					=       floats_tensor((1, 3, 32, 32)      ,    rng=random.Random(_UpperCamelCase  )  ).to(_UpperCamelCase  )
      _lowercase      :				Optional[int]      					=       floats_tensor((1, 3, 16, 16)      ,    rng=random.Random(_UpperCamelCase  )  ).to(_UpperCamelCase  )

      _lowercase      :				List[str]      					=       {
          "prompt": "A painting of a squirrel eating a burger",
          "image": image,
          "original_image": original_image,
          "generator": generator,
          "num_inference_steps": 2,
          "output_type": "numpy",
      }

      return inputs


   @unittest.skipIf(
       torch_device != "cuda" or not is_xformers_available()      ,    reason="XFormers attention is only available with CUDA and `xformers` installed"      ,    )
   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3  )


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      self._test_save_load_optional_components()


   @unittest.skipIf(torch_device != "cuda"      ,    reason="float16 requires CUDA"  )
   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      super().test_save_load_floataa(expected_max_diff=1E-1  )


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      self._test_attention_slicing_forward_pass(expected_max_diff=1E-2  )


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      self._test_save_load_local()






   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      self._test_inference_batch_single_identical(
          expected_max_diff=1E-2      ,    )






