






"""simple docstring"""


import inspect
import unittest

from transformers import SwinaSRConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
   import torch
   from torch import nn

   from transformers import SwinaSRForImageSuperResolution, SwinaSRModel
   from transformers.models.swinasr.modeling_swinasr import SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
   from PIL import Image

   from transformers import SwinaSRImageProcessor






class __a :



  def __init__(self	:		List[str]					,      lowercase_	:		List[Any]					,      lowercase_	:		Dict=13					,      lowercase_	:		List[Any]=32					,      lowercase_	:		Tuple=1					,      lowercase_	:		List[str]=3					,      lowercase_	:		Optional[Any]=16					,      lowercase_	:		Tuple=[1, 2, 1]					,      lowercase_	:		str=[2, 2, 4]					,      lowercase_	:		Dict=2					,      lowercase_	:		List[Any]=2.0					,      lowercase_	:		Optional[Any]=True					,      lowercase_	:		Dict=0.0					,      lowercase_	:		Union[str, Any]=0.0					,      lowercase_	:		Any=0.1					,      lowercase_	:		str="gelu"					,      lowercase_	:		Dict=False					,      lowercase_	:		Optional[int]=True					,      lowercase_	:		str=0.02					,      lowercase_	:		List[str]=1E-5					,      lowercase_	:		Union[str, Any]=True					,      lowercase_	:		List[str]=None					,      lowercase_	:		Optional[int]=False					,      lowercase_	:		Optional[int]=2					,      )		->				List[str]:
   __A						:							Dict      =						parent
   __A						:							Optional[Any]      =						batch_size
   __A						:							Any      =						image_size
   __A						:							Union[str, Any]      =						patch_size
   __A						:							Any      =						num_channels
   __A						:							Union[str, Any]      =						embed_dim
   __A						:							Any      =						depths
   __A						:							int      =						num_heads
   __A						:							List[str]      =						window_size
   __A						:							str      =						mlp_ratio
   __A						:							Tuple      =						qkv_bias
   __A						:							List[Any]      =						hidden_dropout_prob
   __A						:							List[str]      =						attention_probs_dropout_prob
   __A						:							str      =						drop_path_rate
   __A						:							List[str]      =						hidden_act
   __A						:							int      =						use_absolute_embeddings
   __A						:							Any      =						patch_norm
   __A						:							Dict      =						layer_norm_eps
   __A						:							int      =						initializer_range
   __A						:							Union[str, Any]      =						is_training
   __A						:							str      =						scope
   __A						:							Optional[int]      =						use_labels
   __A						:							Union[str, Any]      =						upscale

   # here we set some attributes to make tests pass
   __A						:							Dict      =						len(SCREAMING_SNAKE_CASE_ )
   __A						:							str      =						embed_dim
   __A						:							List[Any]      =						(image_size // patch_size) ** 2



  def     A_					(self	:		Optional[int] )		->				Any:
   __A						:							List[Any]      =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

   __A						:							Any      =						None
   if self.use_labels:
    __A						:							Union[str, Any]      =						ids_tensor([self.batch_size]					,      self.type_sequence_label_size )

   __A						:							List[Any]      =						self.get_config()

   return config, pixel_values, labels



  def     A_					(self	:		Optional[int] )		->				int:
   return SwinaSRConfig(
       image_size=self.image_size					,      patch_size=self.patch_size					,      num_channels=self.num_channels					,      embed_dim=self.embed_dim					,      depths=self.depths					,      num_heads=self.num_heads					,      window_size=self.window_size					,      mlp_ratio=self.mlp_ratio					,      qkv_bias=self.qkv_bias					,      hidden_dropout_prob=self.hidden_dropout_prob					,      attention_probs_dropout_prob=self.attention_probs_dropout_prob					,      drop_path_rate=self.drop_path_rate					,      hidden_act=self.hidden_act					,      use_absolute_embeddings=self.use_absolute_embeddings					,      path_norm=self.patch_norm					,      layer_norm_eps=self.layer_norm_eps					,      initializer_range=self.initializer_range					,      upscale=self.upscale					,      )



  def     A_					(self	:		Union[str, Any]					,      lowercase_	:		Optional[Any]					,      lowercase_	:		Optional[int]					,      lowercase_	:		Dict )		->				Optional[int]:
   __A						:							Optional[int]      =						SwinaSRModel(config=SCREAMING_SNAKE_CASE_ )
   model.to(SCREAMING_SNAKE_CASE_ )
   model.eval()
   __A						:							Dict      =						model(SCREAMING_SNAKE_CASE_ )

   self.parent.assertEqual(
       result.last_hidden_state.shape					,      (self.batch_size, self.embed_dim, self.image_size, self.image_size) )



  def     A_					(self	:		str					,      lowercase_	:		Tuple					,      lowercase_	:		str					,      lowercase_	:		List[str] )		->				Dict:
   __A						:							List[str]      =						SwinaSRForImageSuperResolution(SCREAMING_SNAKE_CASE_ )
   model.to(SCREAMING_SNAKE_CASE_ )
   model.eval()
   __A						:							List[Any]      =						model(SCREAMING_SNAKE_CASE_ )

   __A						:							Any      =						self.image_size * self.upscale
   self.parent.assertEqual(
       result.reconstruction.shape					,      (self.batch_size, self.num_channels, expected_image_size, expected_image_size) )



  def     A_					(self	:		int )		->				Optional[Any]:
   __A						:							int      =						self.prepare_config_and_inputs()
   __A     ,       __A     ,       __A						:							Any      =						config_and_inputs
   __A						:							List[Any]      =						{'pixel_values': pixel_values}
   return config, inputs_dict






@require_torch
class __a ( SCREAMING_SNAKE_CASE_			,SCREAMING_SNAKE_CASE_			,unittest.TestCase					):
  __lowercase     :     Union[str, Any]       						=       (SwinaSRModel, SwinaSRForImageSuperResolution) if is_torch_available() else ()
  __lowercase     :     Union[str, Any]       						=       {'feature-extraction': SwinaSRModel} if is_torch_available() else {}

  __lowercase     :     int       						=       False
  __lowercase     :     List[str]       						=       False
  __lowercase     :     str       						=       False
  __lowercase     :     Any       						=       False
  __lowercase     :     List[str]       						=       False



  def     A_					(self	:		Dict )		->				Optional[int]:
   __A						:							Union[str, Any]      =						SwinaSRModelTester(self )
   __A						:							Dict      =						ConfigTester(self					,      config_class=SCREAMING_SNAKE_CASE_					,      embed_dim=37 )



  def     A_					(self	:		List[Any] )		->				List[Any]:
   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] )		->				Optional[int]:
   __A						:							Dict      =						self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ )



  def     A_					(self	:		Dict )		->				Optional[Any]:
   __A						:							Dict      =						self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_image_super_resolution(*SCREAMING_SNAKE_CASE_ )



  @unittest.skip(reason='Got `CUDA error: misaligned address` with PyTorch 2.0.0.' )
  def     A_					(self	:		Tuple )		->				Tuple:
   pass



  @unittest.skip(reason='Swin2SR does not use inputs_embeds' )
  def     A_					(self	:		int )		->				Optional[int]:
   pass



  @unittest.skip(reason='Swin2SR does not support training yet' )
  def     A_					(self	:		Optional[Any] )		->				Dict:
   pass



  @unittest.skip(reason='Swin2SR does not support training yet' )
  def     A_					(self	:		Union[str, Any] )		->				Union[str, Any]:
   pass



  def     A_					(self	:		Optional[Any] )		->				Dict:
   __A     ,       __A						:							str      =						self.model_tester.prepare_config_and_inputs_for_common()

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



  def     A_					(self	:		Optional[int] )		->				str:
   __A     ,       __A						:							Union[str, Any]      =						self.model_tester.prepare_config_and_inputs_for_common()

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

    __A						:							List[Any]      =						['pixel_values']
    self.assertListEqual(arg_names[:1]					,      SCREAMING_SNAKE_CASE_ )



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






   for model_name in SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
    __A						:							Optional[Any]      =						SwinaSRModel.from_pretrained(SCREAMING_SNAKE_CASE_ )
    self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )



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

   __A						:							Optional[Any]      =						_config_zero_init(SCREAMING_SNAKE_CASE_ )
   for model_class in self.all_model_classes:
    __A						:							List[Any]      =						model_class(config=SCREAMING_SNAKE_CASE_ )
    for name, param in model.named_parameters():
     if "logit_scale" in name:
      continue
     if param.requires_grad:
      self.assertIn(
          ((param.data.mean() * 1E9).round() / 1E9).item()					,      [0.0, 1.0]					,      msg=f"Parameter {name} of model {model_class} seems not properly initialized"					,      )



  def     A_					(self	:		Any )		->				str:
   __A     ,       __A						:							Optional[int]      =						self.model_tester.prepare_config_and_inputs_for_common()
   __A						:							List[str]      =						True

   for model_class in self.all_model_classes:
    __A						:							Optional[Any]      =						True
    __A						:							Any      =						False
    __A						:							Dict      =						True
    __A						:							int      =						model_class(SCREAMING_SNAKE_CASE_ )
    model.to(SCREAMING_SNAKE_CASE_ )
    model.eval()
    with torch.no_grad():
     __A						:							Any      =						model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_ ) )
    __A						:							Union[str, Any]      =						outputs.attentions
    __A						:							Union[str, Any]      =						len(self.model_tester.depths )
    self.assertEqual(len(SCREAMING_SNAKE_CASE_ )					,      SCREAMING_SNAKE_CASE_ )

    # check that output_attentions also work using config
    del inputs_dict["output_attentions"]
    __A						:							int      =						True
    __A						:							List[Any]      =						config.window_size**2
    __A						:							List[Any]      =						model_class(SCREAMING_SNAKE_CASE_ )
    model.to(SCREAMING_SNAKE_CASE_ )
    model.eval()
    with torch.no_grad():
     __A						:							Tuple      =						model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_ ) )
    __A						:							Tuple      =						outputs.attentions
    self.assertEqual(len(SCREAMING_SNAKE_CASE_ )					,      SCREAMING_SNAKE_CASE_ )

    self.assertListEqual(
        list(attentions[0].shape[-3:] )					,      [self.model_tester.num_heads[0], window_size_squared, window_size_squared]					,      )
    __A						:							Any      =						len(SCREAMING_SNAKE_CASE_ )

    # Check attention is always last and order is fine
    __A						:							str      =						True
    __A						:							List[str]      =						True
    __A						:							Union[str, Any]      =						model_class(SCREAMING_SNAKE_CASE_ )
    model.to(SCREAMING_SNAKE_CASE_ )
    model.eval()
    with torch.no_grad():
     __A						:							int      =						model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_ ) )

    self.assertEqual(out_len + 1					,      len(SCREAMING_SNAKE_CASE_ ) )

    __A						:							int      =						outputs.attentions

    self.assertEqual(len(SCREAMING_SNAKE_CASE_ )					,      SCREAMING_SNAKE_CASE_ )

    self.assertListEqual(
        list(self_attentions[0].shape[-3:] )					,      [self.model_tester.num_heads[0], window_size_squared, window_size_squared]					,      )






@require_vision
@require_torch
@slow
class __a ( unittest.TestCase					):



  def     A_					(self	:		int )		->				int:
   __A						:							Any      =						SwinaSRImageProcessor()
   __A						:							List[Any]      =						SwinaSRForImageSuperResolution.from_pretrained('caidas/swin2SR-classical-sr-x2-64' ).to(SCREAMING_SNAKE_CASE_ )

   __A						:							Union[str, Any]      =						Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
   __A						:							Optional[int]      =						processor(images=SCREAMING_SNAKE_CASE_					,      return_tensors='pt' ).to(SCREAMING_SNAKE_CASE_ )

   # forward pass
   with torch.no_grad():
    __A						:							List[Any]      =						model(**SCREAMING_SNAKE_CASE_ )

   # verify the logits
   __A						:							Dict      =						torch.Size([1, 3, 976, 1_296] )
   self.assertEqual(outputs.reconstruction.shape					,      SCREAMING_SNAKE_CASE_ )
   __A						:							Optional[Any]      =						torch.tensor(
       [[0.5458, 0.5546, 0.5638], [0.5526, 0.5565, 0.5651], [0.5396, 0.5426, 0.5621]] ).to(SCREAMING_SNAKE_CASE_ )
   self.assertTrue(torch.allclose(outputs.reconstruction[0, 0, :3, :3]					,      SCREAMING_SNAKE_CASE_					,      atol=1E-4 ) )







import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
				import torch

if is_vision_available():
				from PIL import Image

				from transformers import DeiTImageProcessor






class 							SCREAMING_SNAKE_CASE__     (				unittest.TestCase     ):

							"""simple docstring"""






							def __init__(	self  ,						SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_=7  ,						SCREAMING_SNAKE_CASE_=3  ,						SCREAMING_SNAKE_CASE_=18  ,						SCREAMING_SNAKE_CASE_=30  ,						SCREAMING_SNAKE_CASE_=400  ,						SCREAMING_SNAKE_CASE_=True  ,						SCREAMING_SNAKE_CASE_=None  ,						SCREAMING_SNAKE_CASE_=True  ,						SCREAMING_SNAKE_CASE_=None  ,						SCREAMING_SNAKE_CASE_=True  ,						SCREAMING_SNAKE_CASE_=[0.5, 0.5, 0.5]  ,						SCREAMING_SNAKE_CASE_=[0.5, 0.5, 0.5]  ,						)-> List[str]:





													'''simple docstring'''






													__UpperCamelCase  	=      size if size is not None else {'''height''': 20, '''width''': 20}
													__UpperCamelCase  	=      crop_size if crop_size is not None else {'''height''': 18, '''width''': 18}

													__UpperCamelCase  	=      parent
													__UpperCamelCase  	=      batch_size
													__UpperCamelCase  	=      num_channels
													__UpperCamelCase  	=      image_size
													__UpperCamelCase  	=      min_resolution
													__UpperCamelCase  	=      max_resolution
													__UpperCamelCase  	=      do_resize
													__UpperCamelCase  	=      size
													__UpperCamelCase  	=      do_center_crop
													__UpperCamelCase  	=      crop_size
													__UpperCamelCase  	=      do_normalize
													__UpperCamelCase  	=      image_mean
													__UpperCamelCase  	=      image_std



							def      A__		(	self      )-> int:





													'''simple docstring'''






													return {
													    "do_resize": self.do_resize,
													    "size": self.size,
													    "do_center_crop": self.do_center_crop,
													    "crop_size": self.crop_size,
													    "do_normalize": self.do_normalize,
													    "image_mean": self.image_mean,
													    "image_std": self.image_std,
													}






@require_torch
@require_vision
class 							SCREAMING_SNAKE_CASE__     (				SCREAMING_SNAKE_CASE_ ,		unittest.TestCase     ):

							"""simple docstring"""






							_snake_case  		=	DeiTImageProcessor if is_vision_available() else None
							_snake_case  		=	True



							def      A__		(	self      )-> int:





													'''simple docstring'''






													__UpperCamelCase  	=      DeiTImageProcessingTester(self      )



							@property
							def      A__		(	self      )-> Any:





													'''simple docstring'''






													return self.image_processor_tester.prepare_image_processor_dict()



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





													'''simple docstring'''






													__UpperCamelCase  	=      self.image_processing_class(**self.image_processor_dict      )
													self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_  ,						'''do_resize'''      )      )
													self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_  ,						'''size'''      )      )
													self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_  ,						'''do_center_crop'''      )      )
													self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_  ,						'''center_crop'''      )      )
													self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_  ,						'''do_normalize'''      )      )
													self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_  ,						'''image_mean'''      )      )
													self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_  ,						'''image_std'''      )      )



							def      A__		(	self      )-> int:





													'''simple docstring'''






													__UpperCamelCase  	=      self.image_processing_class.from_dict(self.image_processor_dict      )
													self.assertEqual(image_processor.size  ,						{'''height''': 20, '''width''': 20}      )
													self.assertEqual(image_processor.crop_size  ,						{'''height''': 18, '''width''': 18}      )

													__UpperCamelCase  	=      self.image_processing_class.from_dict(self.image_processor_dict  ,						size=42  ,						crop_size=84      )
													self.assertEqual(image_processor.size  ,						{'''height''': 42, '''width''': 42}      )
													self.assertEqual(image_processor.crop_size  ,						{'''height''': 84, '''width''': 84}      )



							def      A__		(	self      )-> Union[str, Any]:





													'''simple docstring'''






													pass



							def      A__		(	self      )-> str:





													'''simple docstring'''






													__UpperCamelCase  	=      self.image_processing_class(**self.image_processor_dict      )
													# create random PIL images
													__UpperCamelCase  	=      prepare_image_inputs(self.image_processor_tester  ,						equal_resolution=SCREAMING_SNAKE_CASE_      )
													for image in image_inputs:
																			self.assertIsInstance(SCREAMING_SNAKE_CASE_  ,						Image.Image      )

													# Test not batched input
													__UpperCamelCase  	=      image_processing(image_inputs[0]  ,						return_tensors='''pt'''      ).pixel_values
													self.assertEqual(
													    encoded_images.shape  ,						(
													        1,
													        self.image_processor_tester.num_channels,
													        self.image_processor_tester.crop_size['''height'''],
													        self.image_processor_tester.crop_size['''width'''],
													    )  ,						)

													# Test batched
													__UpperCamelCase  	=      image_processing(SCREAMING_SNAKE_CASE_  ,						return_tensors='''pt'''      ).pixel_values
													self.assertEqual(
													    encoded_images.shape  ,						(
													        self.image_processor_tester.batch_size,
													        self.image_processor_tester.num_channels,
													        self.image_processor_tester.crop_size['''height'''],
													        self.image_processor_tester.crop_size['''width'''],
													    )  ,						)



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





													'''simple docstring'''






													__UpperCamelCase  	=      self.image_processing_class(**self.image_processor_dict      )
													# create random numpy tensors
													__UpperCamelCase  	=      prepare_image_inputs(self.image_processor_tester  ,						equal_resolution=SCREAMING_SNAKE_CASE_  ,						numpify=SCREAMING_SNAKE_CASE_      )
													for image in image_inputs:
																			self.assertIsInstance(SCREAMING_SNAKE_CASE_  ,						np.ndarray      )

													# Test not batched input
													__UpperCamelCase  	=      image_processing(image_inputs[0]  ,						return_tensors='''pt'''      ).pixel_values
													self.assertEqual(
													    encoded_images.shape  ,						(
													        1,
													        self.image_processor_tester.num_channels,
													        self.image_processor_tester.crop_size['''height'''],
													        self.image_processor_tester.crop_size['''width'''],
													    )  ,						)

													# Test batched
													__UpperCamelCase  	=      image_processing(SCREAMING_SNAKE_CASE_  ,						return_tensors='''pt'''      ).pixel_values
													self.assertEqual(
													    encoded_images.shape  ,						(
													        self.image_processor_tester.batch_size,
													        self.image_processor_tester.num_channels,
													        self.image_processor_tester.crop_size['''height'''],
													        self.image_processor_tester.crop_size['''width'''],
													    )  ,						)



							def      A__		(	self      )-> str:





													'''simple docstring'''






													__UpperCamelCase  	=      self.image_processing_class(**self.image_processor_dict      )
													# create random PyTorch tensors
													__UpperCamelCase  	=      prepare_image_inputs(self.image_processor_tester  ,						equal_resolution=SCREAMING_SNAKE_CASE_  ,						torchify=SCREAMING_SNAKE_CASE_      )
													for image in image_inputs:
																			self.assertIsInstance(SCREAMING_SNAKE_CASE_  ,						torch.Tensor      )

													# Test not batched input
													__UpperCamelCase  	=      image_processing(image_inputs[0]  ,						return_tensors='''pt'''      ).pixel_values
													self.assertEqual(
													    encoded_images.shape  ,						(
													        1,
													        self.image_processor_tester.num_channels,
													        self.image_processor_tester.crop_size['''height'''],
													        self.image_processor_tester.crop_size['''width'''],
													    )  ,						)

													# Test batched
													__UpperCamelCase  	=      image_processing(SCREAMING_SNAKE_CASE_  ,						return_tensors='''pt'''      ).pixel_values
													self.assertEqual(
													    encoded_images.shape  ,						(
													        self.image_processor_tester.batch_size,
													        self.image_processor_tester.num_channels,
													        self.image_processor_tester.crop_size['''height'''],
													        self.image_processor_tester.crop_size['''width'''],
													    )  ,						)




