




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


       def __init__(      self			,     __SCREAMING_SNAKE_CASE			,     __SCREAMING_SNAKE_CASE=13			,     __SCREAMING_SNAKE_CASE=32			,     __SCREAMING_SNAKE_CASE=1			,     __SCREAMING_SNAKE_CASE=3			,     __SCREAMING_SNAKE_CASE=16			,     __SCREAMING_SNAKE_CASE=[1, 2, 1]			,     __SCREAMING_SNAKE_CASE=[2, 2, 4]			,     __SCREAMING_SNAKE_CASE=2			,     __SCREAMING_SNAKE_CASE=2.0			,     __SCREAMING_SNAKE_CASE=True			,     __SCREAMING_SNAKE_CASE=0.0			,     __SCREAMING_SNAKE_CASE=0.0			,     __SCREAMING_SNAKE_CASE=0.1			,     __SCREAMING_SNAKE_CASE="gelu"			,     __SCREAMING_SNAKE_CASE=False			,     __SCREAMING_SNAKE_CASE=True			,     __SCREAMING_SNAKE_CASE=0.02			,     __SCREAMING_SNAKE_CASE=1E-5			,     __SCREAMING_SNAKE_CASE=True			,     __SCREAMING_SNAKE_CASE=None			,     __SCREAMING_SNAKE_CASE=False			,     __SCREAMING_SNAKE_CASE=2			,     )					->     Any:



            '''simple docstring'''




            __snake_case			    =     parent
            __snake_case			    =     batch_size
            __snake_case			    =     image_size
            __snake_case			    =     patch_size
            __snake_case			    =     num_channels
            __snake_case			    =     embed_dim
            __snake_case			    =     depths
            __snake_case			    =     num_heads
            __snake_case			    =     window_size
            __snake_case			    =     mlp_ratio
            __snake_case			    =     qkv_bias
            __snake_case			    =     hidden_dropout_prob
            __snake_case			    =     attention_probs_dropout_prob
            __snake_case			    =     drop_path_rate
            __snake_case			    =     hidden_act
            __snake_case			    =     use_absolute_embeddings
            __snake_case			    =     patch_norm
            __snake_case			    =     layer_norm_eps
            __snake_case			    =     initializer_range
            __snake_case			    =     is_training
            __snake_case			    =     scope
            __snake_case			    =     use_labels
            __snake_case			    =     upscale

            # here we set some attributes to make tests pass
            __snake_case			    =     len(__SCREAMING_SNAKE_CASE     )
            __snake_case			    =     embed_dim
            __snake_case			    =     (image_size // patch_size) ** 2


       def 					lowerCAmelCase					(      self     )					->     Dict:



            '''simple docstring'''




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

            __snake_case			    =     None
            if self.use_labels:
                 __snake_case			    =     ids_tensor([self.batch_size]			,     self.type_sequence_label_size     )

            __snake_case			    =     self.get_config()

            return config, pixel_values, labels


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



            '''simple docstring'''




            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 					lowerCAmelCase					(      self			,     __SCREAMING_SNAKE_CASE			,     __SCREAMING_SNAKE_CASE			,     __SCREAMING_SNAKE_CASE     )					->     Any:



            '''simple docstring'''




            __snake_case			    =     SwinaSRModel(config=__SCREAMING_SNAKE_CASE     )
            model.to(__SCREAMING_SNAKE_CASE     )
            model.eval()
            __snake_case			    =     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 					lowerCAmelCase					(      self			,     __SCREAMING_SNAKE_CASE			,     __SCREAMING_SNAKE_CASE			,     __SCREAMING_SNAKE_CASE     )					->     Any:



            '''simple docstring'''




            __snake_case			    =     SwinaSRForImageSuperResolution(__SCREAMING_SNAKE_CASE     )
            model.to(__SCREAMING_SNAKE_CASE     )
            model.eval()
            __snake_case			    =     model(__SCREAMING_SNAKE_CASE     )

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




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



            '''simple docstring'''




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





@require_torch
class 			lowerCAmelCase      (       __lowerCAmelCase ,      __lowerCAmelCase ,      unittest.TestCase):
       __lowercase     :					Any       				=	(SwinaSRModel, SwinaSRForImageSuperResolution) if is_torch_available() else ()
       __lowercase     :					Dict       				=	{'''feature-extraction''': SwinaSRModel} if is_torch_available() else {}

       __lowercase     :					int       				=	False
       __lowercase     :					Any       				=	False
       __lowercase     :					Union[str, Any]       				=	False
       __lowercase     :					Dict       				=	False
       __lowercase     :					int       				=	False


       def 					lowerCAmelCase					(      self     )					->     str:



            '''simple docstring'''




            __snake_case			    =     SwinaSRModelTester(self     )
            __snake_case			    =     ConfigTester(self			,     config_class=__SCREAMING_SNAKE_CASE			,     embed_dim=37     )


       def 					lowerCAmelCase					(      self     )					->     Tuple:



            '''simple docstring'''




            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 					lowerCAmelCase					(      self     )					->     Optional[int]:



            '''simple docstring'''




            __snake_case			    =     self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE     )


       def 					lowerCAmelCase					(      self     )					->     str:



            '''simple docstring'''




            __snake_case			    =     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 					lowerCAmelCase					(      self     )					->     Optional[int]:



            '''simple docstring'''




            pass


       @unittest.skip(reason='''Swin2SR does not use inputs_embeds'''     )
       def 					lowerCAmelCase					(      self     )					->     Dict:



            '''simple docstring'''




            pass


       @unittest.skip(reason='''Swin2SR does not support training yet'''     )
       def 					lowerCAmelCase					(      self     )					->     Tuple:



            '''simple docstring'''




            pass


       @unittest.skip(reason='''Swin2SR does not support training yet'''     )
       def 					lowerCAmelCase					(      self     )					->     str:



            '''simple docstring'''




            pass


       def 					lowerCAmelCase					(      self     )					->     Tuple:



            '''simple docstring'''




            __snake_case    ,			__snake_case			    =     self.model_tester.prepare_config_and_inputs_for_common()

            for model_class in self.all_model_classes:
                 __snake_case			    =     model_class(__SCREAMING_SNAKE_CASE     )
                 self.assertIsInstance(model.get_input_embeddings()			,     (nn.Module)     )
                 __snake_case			    =     model.get_output_embeddings()
                 self.assertTrue(x is None or isinstance(__SCREAMING_SNAKE_CASE			,     nn.Linear     )     )


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



            '''simple docstring'''




            __snake_case    ,			__snake_case			    =     self.model_tester.prepare_config_and_inputs_for_common()

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

                 __snake_case			    =     ['''pixel_values''']
                 self.assertListEqual(arg_names[:1]			,     __SCREAMING_SNAKE_CASE     )


       @slow
       def 					lowerCAmelCase					(      self     )					->     Union[str, Any]:



            '''simple docstring'''




            for model_name in SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 __snake_case			    =     SwinaSRModel.from_pretrained(__SCREAMING_SNAKE_CASE     )
                 self.assertIsNotNone(__SCREAMING_SNAKE_CASE     )


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



            '''simple docstring'''




            __snake_case    ,			__snake_case			    =     self.model_tester.prepare_config_and_inputs_for_common()

            __snake_case			    =     _config_zero_init(__SCREAMING_SNAKE_CASE     )
            for model_class in self.all_model_classes:
                 __snake_case			    =     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 					lowerCAmelCase					(      self     )					->     Dict:



            '''simple docstring'''




            __snake_case    ,			__snake_case			    =     self.model_tester.prepare_config_and_inputs_for_common()
            __snake_case			    =     True

            for model_class in self.all_model_classes:
                 __snake_case			    =     True
                 __snake_case			    =     False
                 __snake_case			    =     True
                 __snake_case			    =     model_class(__SCREAMING_SNAKE_CASE     )
                 model.to(__SCREAMING_SNAKE_CASE     )
                 model.eval()
                 with torch.no_grad():
                      __snake_case			    =     model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE			,     __SCREAMING_SNAKE_CASE     )     )
                 __snake_case			    =     outputs.attentions
                 __snake_case			    =     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"]
                 __snake_case			    =     True
                 __snake_case			    =     config.window_size**2
                 __snake_case			    =     model_class(__SCREAMING_SNAKE_CASE     )
                 model.to(__SCREAMING_SNAKE_CASE     )
                 model.eval()
                 with torch.no_grad():
                      __snake_case			    =     model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE			,     __SCREAMING_SNAKE_CASE     )     )
                 __snake_case			    =     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]			,     )
                 __snake_case			    =     len(__SCREAMING_SNAKE_CASE     )

                 # Check attention is always last and order is fine
                 __snake_case			    =     True
                 __snake_case			    =     True
                 __snake_case			    =     model_class(__SCREAMING_SNAKE_CASE     )
                 model.to(__SCREAMING_SNAKE_CASE     )
                 model.eval()
                 with torch.no_grad():
                      __snake_case			    =     model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE			,     __SCREAMING_SNAKE_CASE     )     )

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

                 __snake_case			    =     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 			lowerCAmelCase      (       unittest.TestCase):


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



            '''simple docstring'''




            __snake_case			    =     SwinaSRImageProcessor()
            __snake_case			    =     SwinaSRForImageSuperResolution.from_pretrained('''caidas/swin2SR-classical-sr-x2-64'''     ).to(__SCREAMING_SNAKE_CASE     )

            __snake_case			    =     Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''     )
            __snake_case			    =     processor(images=__SCREAMING_SNAKE_CASE			,     return_tensors='''pt'''     ).to(__SCREAMING_SNAKE_CASE     )

            # forward pass
            with torch.no_grad():
                 __snake_case			    =     model(**__SCREAMING_SNAKE_CASE     )

            # verify the logits
            __snake_case			    =     torch.Size([1, 3, 976, 1296]     )
            self.assertEqual(outputs.reconstruction.shape			,     __SCREAMING_SNAKE_CASE     )
            __snake_case			    =     torch.tensor(
                [[0.5_458, 0.5_546, 0.5_638], [0.5_526, 0.5_565, 0.5_651], [0.5_396, 0.5_426, 0.5_621]]     ).to(__SCREAMING_SNAKE_CASE     )
            self.assertTrue(torch.allclose(outputs.reconstruction[0, 0, :3, :3]			,     __SCREAMING_SNAKE_CASE			,     atol=1E-4     )     )












'''simple docstring'''



import os

from packaging import version

from .. import __version__
from .accelerate_utils import apply_forward_hook
from .constants import (
    CONFIG_NAME,
    DEPRECATED_REVISION_ARGS,
    DIFFUSERS_CACHE,
    DIFFUSERS_DYNAMIC_MODULE_NAME,
    FLAX_WEIGHTS_NAME,
    HF_MODULES_CACHE,
    HUGGINGFACE_CO_RESOLVE_ENDPOINT,
    ONNX_EXTERNAL_WEIGHTS_NAME,
    ONNX_WEIGHTS_NAME,
    SAFETENSORS_WEIGHTS_NAME,
    TEXT_ENCODER_ATTN_MODULE,
    WEIGHTS_NAME,
)
from .deprecation_utils import deprecate
from .doc_utils import replace_example_docstring
from .dynamic_modules_utils import get_class_from_dynamic_module
from .hub_utils import (
    HF_HUB_OFFLINE,
    _add_variant,
    _get_model_file,
    extract_commit_hash,
    http_user_agent,
)
from .import_utils import (
    BACKENDS_MAPPING,
    ENV_VARS_TRUE_AND_AUTO_VALUES,
    ENV_VARS_TRUE_VALUES,
    USE_JAX,
    USE_TF,
    USE_TORCH,
    DummyObject,
    OptionalDependencyNotAvailable,
    is_accelerate_available,
    is_accelerate_version,
    is_bsa_available,
    is_flax_available,
    is_ftfy_available,
    is_inflect_available,
    is_invisible_watermark_available,
    is_k_diffusion_available,
    is_k_diffusion_version,
    is_librosa_available,
    is_note_seq_available,
    is_omegaconf_available,
    is_onnx_available,
    is_safetensors_available,
    is_scipy_available,
    is_tensorboard_available,
    is_tf_available,
    is_torch_available,
    is_torch_version,
    is_torchsde_available,
    is_transformers_available,
    is_transformers_version,
    is_unidecode_available,
    is_wandb_available,
    is_xformers_available,
    requires_backends,
)
from .logging import get_logger
from .outputs import BaseOutput
from .pil_utils import PIL_INTERPOLATION, numpy_to_pil, pt_to_pil
from .torch_utils import is_compiled_module, randn_tensor


if is_torch_available():
     from .testing_utils import (
         floats_tensor,
         load_hf_numpy,
         load_image,
         load_numpy,
         load_pt,
         nightly,
         parse_flag_from_env,
         print_tensor_test,
         require_torch_a,
         require_torch_gpu,
         skip_mps,
         slow,
         torch_all_close,
         torch_device,
     )
     from .torch_utils import maybe_allow_in_graph

from .testing_utils import export_to_gif, export_to_video


UpperCAmelCase_				:     int     			=						get_logger(__name__)







def 	_UpperCamelCase       (_lowerCamelCase							:   Union[str, Any]		)->      Tuple:




     '''simple docstring'''





     if version.parse(_lowerCamelCase		) < version.parse(_lowerCamelCase		):
          if "dev" in min_version:
               __snake_case			    =     (
                   '''This example requires a source install from HuggingFace diffusers (see '''
                   '''`https://huggingface.co/docs/diffusers/installation#install-from-source`),'''
               )
          else:
               __snake_case			    =     f'''This example requires a minimum version of {min_version},'''
          error_message += f''' but the version found is {__version__}.\n'''
          raise ImportError(_lowerCamelCase		)






