






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				:





	"""simple docstring"""






	def __init__(							self ,					UpperCAmelCase ,					UpperCAmelCase=13 ,					UpperCAmelCase=32 ,					UpperCAmelCase=1 ,					UpperCAmelCase=3 ,					UpperCAmelCase=16 ,					UpperCAmelCase=[1, 2, 1] ,					UpperCAmelCase=[2, 2, 4] ,					UpperCAmelCase=2 ,					UpperCAmelCase=2.0 ,					UpperCAmelCase=True ,					UpperCAmelCase=0.0 ,					UpperCAmelCase=0.0 ,					UpperCAmelCase=0.1 ,					UpperCAmelCase="gelu" ,					UpperCAmelCase=False ,					UpperCAmelCase=True ,					UpperCAmelCase=0.02 ,					UpperCAmelCase=1e-5 ,					UpperCAmelCase=True ,					UpperCAmelCase=None ,					UpperCAmelCase=False ,					UpperCAmelCase=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(UpperCAmelCase					)
							_UpperCAmelCase             =    embed_dim
							_UpperCAmelCase             =    (image_size // patch_size) ** 2

	def  UpperCamelCase					(							self					):
							"""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  UpperCamelCase					(							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  UpperCamelCase					(							self ,					UpperCAmelCase ,					UpperCAmelCase ,					UpperCAmelCase					):
							"""simple docstring"""







							_UpperCAmelCase             =    SwinaSRModel(config=UpperCAmelCase					)
							model.to(UpperCAmelCase					)
							model.eval()
							_UpperCAmelCase             =    model(UpperCAmelCase					)

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

	def  UpperCamelCase					(							self ,					UpperCAmelCase ,					UpperCAmelCase ,					UpperCAmelCase					):
							"""simple docstring"""







							_UpperCAmelCase             =    SwinaSRForImageSuperResolution(UpperCAmelCase					)
							model.to(UpperCAmelCase					)
							model.eval()
							_UpperCAmelCase             =    model(UpperCAmelCase					)

							_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  UpperCamelCase					(							self					):
							"""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 __lowerCamelCase				(   snake_case__  , snake_case__  , unittest.TestCase):





	"""simple docstring"""






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

	UpperCamelCase__			=   False
	UpperCamelCase__			=   False
	UpperCamelCase__			=   False
	UpperCamelCase__			=   False
	UpperCamelCase__			=   False

	def  UpperCamelCase					(							self					):
							"""simple docstring"""







							_UpperCAmelCase             =    SwinaSRModelTester(self					)
							_UpperCAmelCase             =    ConfigTester(self ,					config_class=UpperCAmelCase ,					embed_dim=37					)

	def  UpperCamelCase					(							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  UpperCamelCase					(							self					):
							"""simple docstring"""







							_UpperCAmelCase             =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*UpperCAmelCase					)

	def  UpperCamelCase					(							self					):
							"""simple docstring"""







							_UpperCAmelCase             =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_super_resolution(*UpperCAmelCase					)

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







							pass

	@unittest.skip(reason='Swin2SR does not use inputs_embeds'					)
	def  UpperCamelCase					(							self					):
							"""simple docstring"""







							pass

	@unittest.skip(reason='Swin2SR does not support training yet'					)
	def  UpperCamelCase					(							self					):
							"""simple docstring"""







							pass

	@unittest.skip(reason='Swin2SR does not support training yet'					)
	def  UpperCamelCase					(							self					):
							"""simple docstring"""







							pass

	def  UpperCamelCase					(							self					):
							"""simple docstring"""







							_UpperCAmelCase      ,				_UpperCAmelCase             =    self.model_tester.prepare_config_and_inputs_for_common()

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

	def  UpperCamelCase					(							self					):
							"""simple docstring"""







							_UpperCAmelCase      ,				_UpperCAmelCase             =    self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
													_UpperCAmelCase             =    model_class(UpperCAmelCase					)
													_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] ,					UpperCAmelCase					)

	@slow
	def  UpperCamelCase					(							self					):
							"""simple docstring"""







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

	def  UpperCamelCase					(							self					):
							"""simple docstring"""







							_UpperCAmelCase      ,				_UpperCAmelCase             =    self.model_tester.prepare_config_and_inputs_for_common()

							_UpperCAmelCase             =    _config_zero_init(UpperCAmelCase					)
							for model_class in self.all_model_classes:
													_UpperCAmelCase             =    model_class(config=UpperCAmelCase					)
													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  UpperCamelCase					(							self					):
							"""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(UpperCAmelCase					)
													model.to(UpperCAmelCase					)
													model.eval()
													with torch.no_grad():
																			_UpperCAmelCase             =    model(**self._prepare_for_class(UpperCAmelCase ,					UpperCAmelCase					)					)
													_UpperCAmelCase             =    outputs.attentions
													_UpperCAmelCase             =    len(self.model_tester.depths					)
													self.assertEqual(len(UpperCAmelCase					) ,					UpperCAmelCase					)

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

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

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

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

													_UpperCAmelCase             =    outputs.attentions

													self.assertEqual(len(UpperCAmelCase					) ,					UpperCAmelCase					)

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





	"""simple docstring"""






	def  UpperCamelCase					(							self					):
							"""simple docstring"""







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

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

							# forward pass
							with torch.no_grad():
													_UpperCAmelCase             =    model(**UpperCAmelCase					)

							# verify the logits
							_UpperCAmelCase             =    torch.Size([1, 3, 976, 1296]					)
							self.assertEqual(outputs.reconstruction.shape ,					UpperCAmelCase					)
							_UpperCAmelCase             =    torch.tensor(
							    [[0.54_58, 0.55_46, 0.56_38], [0.55_26, 0.55_65, 0.56_51], [0.53_96, 0.54_26, 0.56_21]]					).to(UpperCAmelCase					)
							self.assertTrue(torch.allclose(outputs.reconstruction[0, 0, :3, :3] ,					UpperCAmelCase ,					atol=1e-4					)					)








from typing import Any





class __lowerCamelCase				:





	"""simple docstring"""






	def __init__(							self					):
							"""simple docstring"""







							_UpperCAmelCase             =    []
							_UpperCAmelCase             =    0

	def __str__(							self					):
							"""simple docstring"""







							_UpperCAmelCase             =    '<' + str(self.stack					)[1:-1] + '>'
							return printed

	def  UpperCamelCase					(							self ,					UpperCAmelCase					):
							"""simple docstring"""







							self.stack.append(UpperCAmelCase					)
							_UpperCAmelCase             =    self.length + 1

	def  UpperCamelCase					(							self					):
							"""simple docstring"""







							self.rotate(1					)
							_UpperCAmelCase             =    self.stack[self.length - 1]
							_UpperCAmelCase             =    self.stack[:-1]
							self.rotate(self.length - 1					)
							_UpperCAmelCase             =    self.length - 1
							return dequeued

	def  UpperCamelCase					(							self ,					UpperCAmelCase					):
							"""simple docstring"""







							for _ in range(UpperCAmelCase					):
													_UpperCAmelCase             =    self.stack[0]
													_UpperCAmelCase             =    self.stack[1:]
													self.put(UpperCAmelCase					)
													_UpperCAmelCase             =    self.length - 1

	def  UpperCamelCase					(							self					):
							"""simple docstring"""







							_UpperCAmelCase             =    self.get()
							self.put(UpperCAmelCase					)
							self.rotate(self.length - 1					)
							return front

	def  UpperCamelCase					(							self					):
							"""simple docstring"""







							return self.length
