



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  :    str					,						A  :    List[Any]					,						A  :    int=13					,						A  :    List[str]=32					,						A  :    Dict=1					,						A  :    Tuple=3					,						A  :    Tuple=16					,						A  :    Union[str, Any]=[1, 2, 1]					,						A  :    Dict=[2, 2, 4]					,						A  :    Any=2					,						A  :    List[Any]=2.0					,						A  :    Union[str, Any]=True					,						A  :    Dict=0.0					,						A  :    Tuple=0.0					,						A  :    str=0.1					,						A  :    Any="gelu"					,						A  :    Optional[Any]=False					,						A  :    Dict=True					,						A  :    str=0.0_2					,						A  :    str=1E-5					,						A  :    int=True					,						A  :    Optional[int]=None					,						A  :    List[str]=False					,						A  :    Any=2					,						)  ->       List[Any]:



						"""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(A)
						_UpperCAmelCase									=  embed_dim
						_UpperCAmelCase									=  (image_size // patch_size) ** 2



			def        _lowerCamelCase			(		self  :    str)  ->       int:



						"""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        _lowerCamelCase			(		self  :    str)  ->       List[str]:



						"""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  :    str					,						A  :    int					,						A  :    str					,						A  :    int)  ->       List[Any]:



						"""simple docstring"""






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

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



			def        _lowerCamelCase			(		self  :    Any					,						A  :    Tuple					,						A  :    Dict					,						A  :    Optional[Any])  ->       Optional[int]:



						"""simple docstring"""






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

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



						"""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       (     A							,		A							,		unittest.TestCase		):
			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        _lowerCamelCase			(		self  :    Any)  ->       List[Any]:



						"""simple docstring"""






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



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



						"""simple docstring"""






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



			def        _lowerCamelCase			(		self  :    Optional[int])  ->       str:



						"""simple docstring"""






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



			@unittest.skip(reason='Got `CUDA error: misaligned address` with PyTorch 2.0.0.')
			def        _lowerCamelCase			(		self  :    List[str])  ->       Optional[Any]:



						"""simple docstring"""






						pass



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



						"""simple docstring"""






						pass



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



						"""simple docstring"""






						pass



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



						"""simple docstring"""






						pass



			def        _lowerCamelCase			(		self  :    List[Any])  ->       Dict:



						"""simple docstring"""






						_UpperCAmelCase			,	_UpperCAmelCase									=  self.model_tester.prepare_config_and_inputs_for_common()

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



			def        _lowerCamelCase			(		self  :    Any)  ->       Tuple:



						"""simple docstring"""






						_UpperCAmelCase			,	_UpperCAmelCase									=  self.model_tester.prepare_config_and_inputs_for_common()

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



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



						"""simple docstring"""






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



			def        _lowerCamelCase			(		self  :    Tuple)  ->       Optional[int]:



						"""simple docstring"""






						_UpperCAmelCase			,	_UpperCAmelCase									=  self.model_tester.prepare_config_and_inputs_for_common()

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



						"""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(A)
									model.to(A)
									model.eval()
									with torch.no_grad():
												_UpperCAmelCase									=  model(**self._prepare_for_class(A					,						A))
									_UpperCAmelCase									=  outputs.attentions
									_UpperCAmelCase									=  len(self.model_tester.depths)
									self.assertEqual(len(A)					,						A)

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

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

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

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

									_UpperCAmelCase									=  outputs.attentions

									self.assertEqual(len(A)					,						A)

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



						"""simple docstring"""






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

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

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

						# verify the logits
						_UpperCAmelCase									=  torch.Size([1, 3, 9_76, 12_96])
						self.assertEqual(outputs.reconstruction.shape					,						A)
						_UpperCAmelCase									=  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(A)
						self.assertTrue(torch.allclose(outputs.reconstruction[0, 0, :3, :3]					,						A					,						atol=1E-4))





import sys

sys.set_int_max_str_digits(0)  # type: ignore





def 				A      (	_UpperCAmelCase							:  int       )							->					bool:







			'''simple docstring'''
			_UpperCAmelCase									=  [0] * 11
			_UpperCAmelCase									=  [0] * 11

			# mark last 9 numbers
			for _ in range(9       ):
						_UpperCAmelCase									=  1
						_UpperCAmelCase									=  number // 10
			# flag
			_UpperCAmelCase									=  True

			# check last 9 numbers for pandigitality

			for x in range(9       ):
						if not check_last[x + 1]:
									_UpperCAmelCase									=  False
			if not f:
						return f

			# mark first 9 numbers
			_UpperCAmelCase									=  int(str(_UpperCAmelCase       )[:9]       )

			for _ in range(9       ):
						_UpperCAmelCase									=  1
						_UpperCAmelCase									=  number // 10

			# check first 9 numbers for pandigitality

			for x in range(9       ):
						if not check_front[x + 1]:
									_UpperCAmelCase									=  False
			return f





def 				A      (	_UpperCAmelCase							:  int       )							->					bool:







			'''simple docstring'''
			_UpperCAmelCase									=  [0] * 11

			# mark last 9 numbers
			for _ in range(9       ):
						_UpperCAmelCase									=  1
						_UpperCAmelCase									=  number // 10
			# flag
			_UpperCAmelCase									=  True

			# check last 9 numbers for pandigitality

			for x in range(9       ):
						if not check_last[x + 1]:
									_UpperCAmelCase									=  False
			return f





def 				A      (	)							->					int:







			'''simple docstring'''
			_UpperCAmelCase									=  1
			_UpperCAmelCase									=  1
			_UpperCAmelCase									=  2
			# temporary Fibonacci numbers

			_UpperCAmelCase									=  1
			_UpperCAmelCase									=  1
			_UpperCAmelCase									=  2
			# temporary Fibonacci numbers mod 1e9

			# mod m=1e9, done for fast optimisation
			_UpperCAmelCase									=  [0] * 1_000_000
			_UpperCAmelCase									=  1_000_000_000

			for x in range(1_000_000       ):
						_UpperCAmelCase									=  (aa + ba) % m
						_UpperCAmelCase									=  ba % m
						_UpperCAmelCase									=  ca % m
						if checka(_UpperCAmelCase       ):
									_UpperCAmelCase									=  1

			for x in range(1_000_000       ):
						_UpperCAmelCase									=  a + b
						_UpperCAmelCase									=  b
						_UpperCAmelCase									=  c
						# perform check only if in tocheck
						if tocheck[x + 3] and check(_UpperCAmelCase       ):
									return x + 3  # first 2 already done
			return -1


if __name__ == "__main__":
							print(f"""{solution() = }""")
