






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	:





				"""simple docstring"""







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




									"""simple docstring"""

									__UpperCamelCase :   Dict									=parent
									__UpperCamelCase :   Optional[Any]									=batch_size
									__UpperCamelCase :   Union[str, Any]									=image_size
									__UpperCamelCase :   Tuple									=patch_size
									__UpperCamelCase :   int									=num_channels
									__UpperCamelCase :   Any									=embed_dim
									__UpperCamelCase :   int									=depths
									__UpperCamelCase :   Union[str, Any]									=num_heads
									__UpperCamelCase :   str									=window_size
									__UpperCamelCase :   List[Any]									=mlp_ratio
									__UpperCamelCase :   Dict									=qkv_bias
									__UpperCamelCase :   int									=hidden_dropout_prob
									__UpperCamelCase :   List[str]									=attention_probs_dropout_prob
									__UpperCamelCase :   Dict									=drop_path_rate
									__UpperCamelCase :   Dict									=hidden_act
									__UpperCamelCase :   Dict									=use_absolute_embeddings
									__UpperCamelCase :   Optional[Any]									=patch_norm
									__UpperCamelCase :   Optional[int]									=layer_norm_eps
									__UpperCamelCase :   Dict									=initializer_range
									__UpperCamelCase :   Optional[Any]									=is_training
									__UpperCamelCase :   Tuple									=scope
									__UpperCamelCase :   Any									=use_labels
									__UpperCamelCase :   Optional[int]									=upscale

									# here we set some attributes to make tests pass
									__UpperCamelCase :   Optional[int]									=len(lowerCamelCase__       )
									__UpperCamelCase :   Optional[Any]									=embed_dim
									__UpperCamelCase :   List[str]									=(image_size // patch_size) ** 2


				def  __lowercase				(					self       ):




									"""simple docstring"""

									__UpperCamelCase :   int									=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

									__UpperCamelCase :   int									=None
									if self.use_labels:
														__UpperCamelCase :   Tuple									=ids_tensor([self.batch_size]				,    self.type_sequence_label_size       )

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

									return config, pixel_values, labels


				def  __lowercase				(					self       ):




									"""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  __lowercase				(					self				,    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__       ):




									"""simple docstring"""

									__UpperCamelCase :   Optional[int]									=SwinaSRModel(config=lowerCamelCase__       )
									model.to(lowerCamelCase__       )
									model.eval()
									__UpperCamelCase :   Dict									=model(lowerCamelCase__       )

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


				def  __lowercase				(					self				,    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__       ):




									"""simple docstring"""

									__UpperCamelCase :   List[Any]									=SwinaSRForImageSuperResolution(lowerCamelCase__       )
									model.to(lowerCamelCase__       )
									model.eval()
									__UpperCamelCase :   List[Any]									=model(lowerCamelCase__       )

									__UpperCamelCase :   Union[str, 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  __lowercase				(					self       ):




									"""simple docstring"""

									__UpperCamelCase :   Optional[Any]									=self.prepare_config_and_inputs()
									__UpperCamelCase						,							__UpperCamelCase						,							__UpperCamelCase :   Dict									=config_and_inputs
									__UpperCamelCase :   Dict									={'pixel_values': pixel_values}
									return config, inputs_dict




@require_torch
class 							__A	(     a ,	a ,	unittest.TestCase					):





				"""simple docstring"""







				UpperCamelCase__					: int     					=(SwinaSRModel, SwinaSRForImageSuperResolution) if is_torch_available() else ()
				UpperCamelCase__					: Tuple     					={"""feature-extraction""": SwinaSRModel} if is_torch_available() else {}

				UpperCamelCase__					: Optional[Any]     					=False
				UpperCamelCase__					: Optional[Any]     					=False
				UpperCamelCase__					: List[str]     					=False
				UpperCamelCase__					: Optional[Any]     					=False
				UpperCamelCase__					: Union[str, Any]     					=False


				def  __lowercase				(					self       ):




									"""simple docstring"""

									__UpperCamelCase :   Tuple									=SwinaSRModelTester(self       )
									__UpperCamelCase :   Tuple									=ConfigTester(self				,    config_class=lowerCamelCase__				,    embed_dim=37       )


				def  __lowercase				(					self       ):




									"""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  __lowercase				(					self       ):




									"""simple docstring"""

									__UpperCamelCase :   str									=self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*lowerCamelCase__       )


				def  __lowercase				(					self       ):




									"""simple docstring"""

									__UpperCamelCase :   Optional[int]									=self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_super_resolution(*lowerCamelCase__       )


				@unittest.skip(reason='Got `CUDA error: misaligned address` with PyTorch 2.0.0.'       )
				def  __lowercase				(					self       ):




									"""simple docstring"""

									pass


				@unittest.skip(reason='Swin2SR does not use inputs_embeds'       )
				def  __lowercase				(					self       ):




									"""simple docstring"""

									pass


				@unittest.skip(reason='Swin2SR does not support training yet'       )
				def  __lowercase				(					self       ):




									"""simple docstring"""

									pass


				@unittest.skip(reason='Swin2SR does not support training yet'       )
				def  __lowercase				(					self       ):




									"""simple docstring"""

									pass


				def  __lowercase				(					self       ):




									"""simple docstring"""

									__UpperCamelCase						,							__UpperCamelCase :   List[str]									=self.model_tester.prepare_config_and_inputs_for_common()

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


				def  __lowercase				(					self       ):




									"""simple docstring"""

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

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

														__UpperCamelCase :   Tuple									=['pixel_values']
														self.assertListEqual(arg_names[:1]				,    lowerCamelCase__       )


				@slow
				def  __lowercase				(					self       ):




									"""simple docstring"""

									for model_name in SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
														__UpperCamelCase :   Dict									=SwinaSRModel.from_pretrained(lowerCamelCase__       )
														self.assertIsNotNone(lowerCamelCase__       )


				def  __lowercase				(					self       ):




									"""simple docstring"""

									__UpperCamelCase						,							__UpperCamelCase :   Optional[int]									=self.model_tester.prepare_config_and_inputs_for_common()

									__UpperCamelCase :   Optional[int]									=_config_zero_init(lowerCamelCase__       )
									for model_class in self.all_model_classes:
														__UpperCamelCase :   Optional[Any]									=model_class(config=lowerCamelCase__       )
														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  __lowercase				(					self       ):




									"""simple docstring"""

									__UpperCamelCase						,							__UpperCamelCase :   int									=self.model_tester.prepare_config_and_inputs_for_common()
									__UpperCamelCase :   Any									=True

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

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

														self.assertListEqual(
														    list(attentions[0].shape[-3:]       )				,    [self.model_tester.num_heads[0], window_size_squared, window_size_squared]				,    )
														__UpperCamelCase :   Tuple									=len(lowerCamelCase__       )

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

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

														__UpperCamelCase :   int									=outputs.attentions

														self.assertEqual(len(lowerCamelCase__       )				,    lowerCamelCase__       )

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





				"""simple docstring"""







				def  __lowercase				(					self       ):




									"""simple docstring"""

									__UpperCamelCase :   Optional[int]									=SwinaSRImageProcessor()
									__UpperCamelCase :   Optional[int]									=SwinaSRForImageSuperResolution.from_pretrained('caidas/swin2SR-classical-sr-x2-64'       ).to(lowerCamelCase__       )

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

									# forward pass
									with torch.no_grad():
														__UpperCamelCase :   int									=model(**lowerCamelCase__       )

									# verify the logits
									__UpperCamelCase :   Union[str, Any]									=torch.Size([1, 3, 976, 1296]       )
									self.assertEqual(outputs.reconstruction.shape				,    lowerCamelCase__       )
									__UpperCamelCase :   str									=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(lowerCamelCase__       )
									self.assertTrue(torch.allclose(outputs.reconstruction[0, 0, :3, :3]				,    lowerCamelCase__				,    atol=1E-4       )       )









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


A_			:List[str]	    =		get_logger(__name__)






def 				A	(			a_   )	->		Tuple:
					if version.parse(a_   ) < version.parse(a_   ):
										if "dev" in min_version:
															__UpperCamelCase :   List[str]									=(
															    'This example requires a source install from HuggingFace diffusers (see '
															    '`https://huggingface.co/docs/diffusers/installation#install-from-source`),'
															)
										else:
															__UpperCamelCase :   Tuple									=F'This example requires a minimum version of {min_version},'
										error_message += F' but the version found is {__version__}.\n'
										raise ImportError(a_   )

