"""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      _lowercase						:

				def __init__(       self    :      List[Any]    ,      _lowercase    :      List[str]    ,      _lowercase    :      Optional[Any]=1_3    ,      _lowercase    :      Tuple=3_2    ,      _lowercase    :      List[str]=1    ,      _lowercase    :      Any=3    ,      _lowercase    :      str=1_6    ,      _lowercase    :      Any=[1, 2, 1]    ,      _lowercase    :      Dict=[2, 2, 4]    ,      _lowercase    :      str=2    ,      _lowercase    :      Optional[Any]=2.0    ,      _lowercase    :      Optional[int]=True    ,      _lowercase    :      Optional[Any]=0.0    ,      _lowercase    :      Dict=0.0    ,      _lowercase    :      List[str]=0.1    ,      _lowercase    :      Optional[Any]="gelu"    ,      _lowercase    :      Optional[int]=False    ,      _lowercase    :      int=True    ,      _lowercase    :      Optional[Any]=0.02    ,      _lowercase    :      int=1e-5    ,      _lowercase    :      List[str]=True    ,      _lowercase    :      int=None    ,      _lowercase    :      List[Any]=False    ,      _lowercase    :      Dict=2    ,      ):


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

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

				def     A	(       self    :      str       ):


										'''simple docstring'''
										UpperCAmelCase__   		=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

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

										UpperCAmelCase__   		=						self.get_config()

										return config, pixel_values, labels

				def     A	(       self    :      Optional[Any]       ):


										'''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     A	(       self    :      Union[str, Any]    ,      _lowercase    :      Any    ,      _lowercase    :      Any    ,      _lowercase    :      Optional[Any]       ):


										'''simple docstring'''
										UpperCAmelCase__   		=						SwinaSRModel(config=_lowercase       )
										model.to(_lowercase       )
										model.eval()
										UpperCAmelCase__   		=						model(_lowercase       )

										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    :      List[Any]    ,      _lowercase    :      Optional[Any]       ):


										'''simple docstring'''
										UpperCAmelCase__   		=						SwinaSRForImageSuperResolution(_lowercase       )
										model.to(_lowercase       )
										model.eval()
										UpperCAmelCase__   		=						model(_lowercase       )

										UpperCAmelCase__   		=						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    :      Any       ):


										'''simple docstring'''
										UpperCAmelCase__   		=						self.prepare_config_and_inputs()
										UpperCAmelCase__		, UpperCAmelCase__		, UpperCAmelCase__   		=						config_and_inputs
										UpperCAmelCase__   		=						{"""pixel_values""": pixel_values}
										return config, inputs_dict


@require_torch
class      _lowercase						(				__lowerCamelCase , __lowerCamelCase , unittest.TestCase					):
				lowerCamelCase__									=    (SwinaSRModel, SwinaSRForImageSuperResolution) if is_torch_available() else ()
				lowerCamelCase__									=    {'feature-extraction': SwinaSRModel} if is_torch_available() else {}

				lowerCamelCase__									=    False
				lowerCamelCase__									=    False
				lowerCamelCase__									=    False
				lowerCamelCase__									=    False
				lowerCamelCase__									=    False

				def     A	(       self    :      str       ):


										'''simple docstring'''
										UpperCAmelCase__   		=						SwinaSRModelTester(self       )
										UpperCAmelCase__   		=						ConfigTester(self    ,      config_class=_lowercase    ,      embed_dim=3_7       )

				def     A	(       self    :      Dict       ):


										'''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     A	(       self    :      Any       ):


										'''simple docstring'''
										UpperCAmelCase__   		=						self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*_lowercase       )

				def     A	(       self    :      List[Any]       ):


										'''simple docstring'''
										UpperCAmelCase__   		=						self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_super_resolution(*_lowercase       )

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


										'''simple docstring'''
										pass

				@unittest.skip(reason="""Swin2SR does not use inputs_embeds"""       )
				def     A	(       self    :      int       ):


										'''simple docstring'''
										pass

				@unittest.skip(reason="""Swin2SR does not support training yet"""       )
				def     A	(       self    :      Dict       ):


										'''simple docstring'''
										pass

				@unittest.skip(reason="""Swin2SR does not support training yet"""       )
				def     A	(       self    :      Dict       ):


										'''simple docstring'''
										pass

				def     A	(       self    :      List[Any]       ):


										'''simple docstring'''
										UpperCAmelCase__		, UpperCAmelCase__   		=						self.model_tester.prepare_config_and_inputs_for_common()

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

				def     A	(       self    :      int       ):


										'''simple docstring'''
										UpperCAmelCase__		, UpperCAmelCase__   		=						self.model_tester.prepare_config_and_inputs_for_common()

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

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

				@slow
				def     A	(       self    :      Any       ):


										'''simple docstring'''
										for model_name in SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																UpperCAmelCase__   		=						SwinaSRModel.from_pretrained(_lowercase       )
																self.assertIsNotNone(_lowercase       )

				def     A	(       self    :      List[str]       ):


										'''simple docstring'''
										UpperCAmelCase__		, UpperCAmelCase__   		=						self.model_tester.prepare_config_and_inputs_for_common()

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


										'''simple docstring'''
										UpperCAmelCase__		, UpperCAmelCase__   		=						self.model_tester.prepare_config_and_inputs_for_common()
										UpperCAmelCase__   		=						True

										for model_class in self.all_model_classes:
																UpperCAmelCase__   		=						True
																UpperCAmelCase__   		=						False
																UpperCAmelCase__   		=						True
																UpperCAmelCase__   		=						model_class(_lowercase       )
																model.to(_lowercase       )
																model.eval()
																with torch.no_grad():
																						UpperCAmelCase__   		=						model(**self._prepare_for_class(_lowercase    ,      _lowercase       )       )
																UpperCAmelCase__   		=						outputs.attentions
																UpperCAmelCase__   		=						len(self.model_tester.depths       )
																self.assertEqual(len(_lowercase       )    ,      _lowercase       )

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

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

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

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

																UpperCAmelCase__   		=						outputs.attentions

																self.assertEqual(len(_lowercase       )    ,      _lowercase       )

																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      _lowercase						(				unittest.TestCase					):

				def     A	(       self    :      List[str]       ):


										'''simple docstring'''
										UpperCAmelCase__   		=						SwinaSRImageProcessor()
										UpperCAmelCase__   		=						SwinaSRForImageSuperResolution.from_pretrained("""caidas/swin2SR-classical-sr-x2-64"""       ).to(_lowercase       )

										UpperCAmelCase__   		=						Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""       )
										UpperCAmelCase__   		=						processor(images=_lowercase    ,      return_tensors="""pt"""       ).to(_lowercase       )

										# forward pass
										with torch.no_grad():
																UpperCAmelCase__   		=						model(**_lowercase       )

										# verify the logits
										UpperCAmelCase__   		=						torch.Size([1, 3, 9_7_6, 1_2_9_6]       )
										self.assertEqual(outputs.reconstruction.shape    ,      _lowercase       )
										UpperCAmelCase__   		=						torch.tensor(
										    [[0.5458, 0.5546, 0.5638], [0.5526, 0.5565, 0.5651], [0.5396, 0.5426, 0.5621]]       ).to(_lowercase       )
										self.assertTrue(torch.allclose(outputs.reconstruction[0, 0, :3, :3]    ,      _lowercase    ,      atol=1e-4       )       )


"""simple docstring"""







import safs


class      _lowercase						(				safs.SaFileSystem					):
				pass

