





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


	"""simple docstring"""





	def __init__(					self   ,     UpperCAmelCase__   ,     UpperCAmelCase__=1_3   ,     UpperCAmelCase__=3_2   ,     UpperCAmelCase__=1   ,     UpperCAmelCase__=3   ,     UpperCAmelCase__=1_6   ,     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.0_2   ,     UpperCAmelCase__=1e-5   ,     UpperCAmelCase__=True   ,     UpperCAmelCase__=None   ,     UpperCAmelCase__=False   ,     UpperCAmelCase__=2   ,     )       ->				str:
					_A :				List[Any]				=  parent
					_A :				str				=  batch_size
					_A :				Any				=  image_size
					_A :				str				=  patch_size
					_A :				Dict				=  num_channels
					_A :				Optional[Any]				=  embed_dim
					_A :				str				=  depths
					_A :				str				=  num_heads
					_A :				Union[str, Any]				=  window_size
					_A :				Any				=  mlp_ratio
					_A :				List[str]				=  qkv_bias
					_A :				str				=  hidden_dropout_prob
					_A :				Optional[Any]				=  attention_probs_dropout_prob
					_A :				Union[str, Any]				=  drop_path_rate
					_A :				List[Any]				=  hidden_act
					_A :				Dict				=  use_absolute_embeddings
					_A :				Any				=  patch_norm
					_A :				Tuple				=  layer_norm_eps
					_A :				int				=  initializer_range
					_A :				List[Any]				=  is_training
					_A :				Union[str, Any]				=  scope
					_A :				Dict				=  use_labels
					_A :				Dict				=  upscale

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




	def 				_lowerCamelCase				(					self			)       ->				Dict:
					_A :				List[str]				=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

					_A :				List[Any]				=  None
					if self.use_labels:
									_A :				Optional[Any]				=  ids_tensor([self.batch_size]   ,     self.type_sequence_label_size			)

					_A :				Dict				=  self.get_config()

					return config, pixel_values, labels




	def 				_lowerCamelCase				(					self			)       ->				str:
					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   ,     UpperCAmelCase__   ,     UpperCAmelCase__   ,     UpperCAmelCase__			)       ->				List[str]:
					_A :				Tuple				=  SwinaSRModel(config=__UpperCamelCase			)
					model.to(__UpperCamelCase			)
					model.eval()
					_A :				Any				=  model(__UpperCamelCase			)

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




	def 				_lowerCamelCase				(					self   ,     UpperCAmelCase__   ,     UpperCAmelCase__   ,     UpperCAmelCase__			)       ->				Union[str, Any]:
					_A :				int				=  SwinaSRForImageSuperResolution(__UpperCamelCase			)
					model.to(__UpperCamelCase			)
					model.eval()
					_A :				Dict				=  model(__UpperCamelCase			)

					_A :				List[str]				=  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[Any]:
					_A :				List[Any]				=  self.prepare_config_and_inputs()
					_A	,       _A	,       _A :				Any				=  config_and_inputs
					_A :				Union[str, Any]				=  {'''pixel_values''': pixel_values}
					return config, inputs_dict



@require_torch
class  lowerCamelCase__				(						snake_case_  ,							snake_case_  ,							unittest.TestCase						):


	"""simple docstring"""





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

	__magic_name__							   =		False
	__magic_name__							   =		False
	__magic_name__							   =		False
	__magic_name__							   =		False
	__magic_name__							   =		False




	def 				_lowerCamelCase				(					self			)       ->				List[str]:
					_A :				int				=  SwinaSRModelTester(self			)
					_A :				str				=  ConfigTester(self   ,     config_class=__UpperCamelCase   ,     embed_dim=3_7			)




	def 				_lowerCamelCase				(					self			)       ->				Tuple:
					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]:
					_A :				Tuple				=  self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*__UpperCamelCase			)




	def 				_lowerCamelCase				(					self			)       ->				Optional[Any]:
					_A :				str				=  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 				_lowerCamelCase				(					self			)       ->				Union[str, Any]:
					pass




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




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




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




	def 				_lowerCamelCase				(					self			)       ->				int:
					_A	,       _A :				Any				=  self.model_tester.prepare_config_and_inputs_for_common()

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




	def 				_lowerCamelCase				(					self			)       ->				Optional[Any]:
					_A	,       _A :				Optional[Any]				=  self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
									_A :				str				=  model_class(__UpperCamelCase			)
									_A :				Union[str, Any]				=  inspect.signature(model.forward			)
									# signature.parameters is an OrderedDict => so arg_names order is deterministic
									_A :				List[Any]				=  [*signature.parameters.keys()]

									_A :				List[str]				=  ['''pixel_values''']
									self.assertListEqual(arg_names[:1]   ,     __UpperCamelCase			)




	@slow
	def 				_lowerCamelCase				(					self			)       ->				Tuple:





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




	def 				_lowerCamelCase				(					self			)       ->				Optional[Any]:
					_A	,       _A :				Any				=  self.model_tester.prepare_config_and_inputs_for_common()

					_A :				Optional[Any]				=  _config_zero_init(__UpperCamelCase			)
					for model_class in self.all_model_classes:
									_A :				str				=  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 				_lowerCamelCase				(					self			)       ->				str:
					_A	,       _A :				List[str]				=  self.model_tester.prepare_config_and_inputs_for_common()
					_A :				List[Any]				=  True

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

									# check that output_attentions also work using config
									del inputs_dict["output_attentions"]
									_A :				Dict				=  True
									_A :				List[str]				=  config.window_size**2
									_A :				List[Any]				=  model_class(__UpperCamelCase			)
									model.to(__UpperCamelCase			)
									model.eval()
									with torch.no_grad():
													_A :				str				=  model(**self._prepare_for_class(__UpperCamelCase   ,     __UpperCamelCase			)			)
									_A :				int				=  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]   ,     )
									_A :				List[Any]				=  len(__UpperCamelCase			)

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

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

									_A :				str				=  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 				_lowerCamelCase				(					self			)       ->				List[str]:
					_A :				Dict				=  SwinaSRImageProcessor()
					_A :				int				=  SwinaSRForImageSuperResolution.from_pretrained('''caidas/swin2SR-classical-sr-x2-64'''			).to(__UpperCamelCase			)

					_A :				List[str]				=  Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''			)
					_A :				Dict				=  processor(images=__UpperCamelCase   ,     return_tensors='''pt'''			).to(__UpperCamelCase			)

					# forward pass
					with torch.no_grad():
									_A :				Optional[int]				=  model(**__UpperCamelCase			)

					# verify the logits
					_A :				Any				=  torch.Size([1, 3, 9_7_6, 1_2_9_6]			)
					self.assertEqual(outputs.reconstruction.shape   ,     __UpperCamelCase			)
					_A :				Tuple				=  torch.tensor(
					    [[0.5_4_5_8, 0.5_5_4_6, 0.5_6_3_8], [0.5_5_2_6, 0.5_5_6_5, 0.5_6_5_1], [0.5_3_9_6, 0.5_4_2_6, 0.5_6_2_1]]			).to(__UpperCamelCase			)
					self.assertTrue(torch.allclose(outputs.reconstruction[0, 0, :3, :3]   ,     __UpperCamelCase   ,     atol=1e-4			)			)



from __future__ import annotations

from collections.abc import Iterator
from typing import Any

class 					__UpperCamelCase					:







	def __init__( self:			Optional[Any]	,			__UpperCamelCase:			Any   ):

						'''simple docstring'''





						__magic_name__				=     data
						__magic_name__				=     None







	def __str__( self:			Optional[int]   ):

						'''simple docstring'''





						return F'{self.data}'




class 					__UpperCamelCase					:







	def __init__( self:			List[Any]   ):

						'''simple docstring'''





						__magic_name__				=     None
						__magic_name__				=     None







	def __iter__( self:			str   ):

						'''simple docstring'''





						__magic_name__				=     self.front
						while node:
											yield node.data
											__magic_name__				=     node.next







	def __len__( self:			Any   ):

						'''simple docstring'''





						return len(tuple(iter(self   )   )   )







	def __str__( self:			List[str]   ):

						'''simple docstring'''





						return " <- ".join(str(__UpperCamelCase   ) for item in self   )







	def 						_SCREAMING_SNAKE_CASE				( self:			Any   ):

						'''simple docstring'''





						return len(self   ) == 0







	def 						_SCREAMING_SNAKE_CASE				( self:			Any	,			__UpperCamelCase:			Any   ):

						'''simple docstring'''





						__magic_name__				=     Node(__UpperCamelCase   )
						if self.is_empty():
											__magic_name__				=     __magic_name__				=     node
						else:
											assert isinstance(self.rear	,			__UpperCamelCase   )
											__magic_name__				=     node
											__magic_name__				=     node







	def 						_SCREAMING_SNAKE_CASE				( self:			Any   ):

						'''simple docstring'''





						if self.is_empty():
											raise IndexError('dequeue from empty queue'   )
						assert isinstance(self.front	,			__UpperCamelCase   )
						__magic_name__				=     self.front
						__magic_name__				=     self.front.next
						if self.front is None:
											__magic_name__				=     None
						return node.data







	def 						_SCREAMING_SNAKE_CASE				( self:			Tuple   ):

						'''simple docstring'''





						__magic_name__				=     __magic_name__				=     None


if __name__ == "__main__":
						from doctest import testmod

						testmod()




