



'''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       snake_case__		:
 def __init__(					self		:				List[Any]	,			__a		:				List[Any]	,			__a		:				Tuple=13	,			__a		:				Optional[Any]=32	,			__a		:				Tuple=1	,			__a		:				Tuple=3	,			__a		:				str=16	,			__a		:				List[str]=[1, 2, 1]	,			__a		:				Optional[int]=[2, 2, 4]	,			__a		:				List[Any]=2	,			__a		:				int=2.0	,			__a		:				List[Any]=True	,			__a		:				Optional[Any]=0.0	,			__a		:				Dict=0.0	,			__a		:				Any=0.1	,			__a		:				Optional[Any]="gelu"	,			__a		:				List[Any]=False	,			__a		:				Dict=True	,			__a		:				List[str]=0.0_2	,			__a		:				Union[str, Any]=1e-5	,			__a		:				Any=True	,			__a		:				str=None	,			__a		:				int=False	,			__a		:				List[Any]=2	,			)	->					int:







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

       # here we set some attributes to make tests pass
       __snake_case      :					Union[str, Any]						=  len(lowerCAmelCase__   )
       __snake_case      :					Union[str, Any]						=  embed_dim
       __snake_case      :					str						=  (image_size // patch_size) ** 2
 def A_					(					self		:				Optional[Any]   )	->					Optional[Any]:







       '''simple docstring'''
       __snake_case      :					Tuple						=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

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

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

       return config, pixel_values, labels
 def A_					(					self		:				List[Any]   )	->					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		:				Any	,			__a		:				str	,			__a		:				Tuple	,			__a		:				str   )	->					List[str]:







       '''simple docstring'''
       __snake_case      :					Dict						=  SwinaSRModel(config=lowerCAmelCase__   )
       model.to(lowerCAmelCase__   )
       model.eval()
       __snake_case      :					str						=  model(lowerCAmelCase__   )

       self.parent.assertEqual(
           result.last_hidden_state.shape	,			(self.batch_size, self.embed_dim, self.image_size, self.image_size)   )
 def A_					(					self		:				str	,			__a		:				Union[str, Any]	,			__a		:				str	,			__a		:				Optional[Any]   )	->					Optional[int]:







       '''simple docstring'''
       __snake_case      :					Union[str, Any]						=  SwinaSRForImageSuperResolution(lowerCAmelCase__   )
       model.to(lowerCAmelCase__   )
       model.eval()
       __snake_case      :					int						=  model(lowerCAmelCase__   )

       __snake_case      :					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 A_					(					self		:				Dict   )	->					List[Any]:







       '''simple docstring'''
       __snake_case      :					List[str]						=  self.prepare_config_and_inputs()
       __snake_case      :					Dict						=  config_and_inputs
       __snake_case      :					Optional[int]						=  {'''pixel_values''': pixel_values}
       return config, inputs_dict



@require_torch
class       snake_case__		(  _lowerCAmelCase   ,			_lowerCAmelCase   ,			unittest.TestCase							):
 A__							=      (SwinaSRModel, SwinaSRForImageSuperResolution) if is_torch_available() else ()
 A__							=      {'''feature-extraction''': SwinaSRModel} if is_torch_available() else {}

 A__							=      False
 A__							=      False
 A__							=      False
 A__							=      False
 A__							=      False
 def A_					(					self		:				Tuple   )	->					Optional[int]:







       '''simple docstring'''
       __snake_case      :					int						=  SwinaSRModelTester(self   )
       __snake_case      :					Dict						=  ConfigTester(self	,			config_class=lowerCAmelCase__	,			embed_dim=37   )
 def A_					(					self		:				Any   )	->					Optional[Any]:







       '''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		:				List[str]   )	->					Dict:







       '''simple docstring'''
       __snake_case      :					int						=  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*lowerCAmelCase__   )
 def A_					(					self		:				List[Any]   )	->					Union[str, Any]:







       '''simple docstring'''
       __snake_case      :					str						=  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 A_					(					self		:				Optional[int]   )	->					int:







       '''simple docstring'''
       pass
 @unittest.skip(reason='Swin2SR does not use inputs_embeds'   )
 def A_					(					self		:				Optional[Any]   )	->					Dict:







       '''simple docstring'''
       pass
 @unittest.skip(reason='Swin2SR does not support training yet'   )
 def A_					(					self		:				int   )	->					List[Any]:







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







       '''simple docstring'''
       pass
 def A_					(					self		:				Optional[int]   )	->					Optional[Any]:







       '''simple docstring'''
       __snake_case      :					str						=  self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
             __snake_case      :					int						=  model_class(lowerCAmelCase__   )
             self.assertIsInstance(model.get_input_embeddings()	,			(nn.Module)   )
             __snake_case      :					Dict						=  model.get_output_embeddings()
             self.assertTrue(x is None or isinstance(lowerCAmelCase__	,			nn.Linear   )   )
 def A_					(					self		:				int   )	->					str:







       '''simple docstring'''
       __snake_case      :					List[Any]						=  self.model_tester.prepare_config_and_inputs_for_common()

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

             __snake_case      :					Any						=  ['''pixel_values''']
             self.assertListEqual(arg_names[:1]	,			lowerCAmelCase__   )
 @slow
 def A_					(					self		:				Dict   )	->					Union[str, Any]:







       '''simple docstring'''



       for model_name in SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             __snake_case      :					Optional[Any]						=  SwinaSRModel.from_pretrained(lowerCAmelCase__   )
             self.assertIsNotNone(lowerCAmelCase__   )
 def A_					(					self		:				List[Any]   )	->					List[str]:







       '''simple docstring'''
       __snake_case      :					str						=  self.model_tester.prepare_config_and_inputs_for_common()

       __snake_case      :					Union[str, Any]						=  _config_zero_init(lowerCAmelCase__   )
       for model_class in self.all_model_classes:
             __snake_case      :					List[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 A_					(					self		:				Union[str, Any]   )	->					int:







       '''simple docstring'''
       __snake_case      :					Optional[int]						=  self.model_tester.prepare_config_and_inputs_for_common()
       __snake_case      :					Optional[Any]						=  True

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

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

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

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

             __snake_case      :					List[str]						=  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       snake_case__		(  unittest.TestCase							):
 def A_					(					self		:				Optional[Any]   )	->					Optional[Any]:







       '''simple docstring'''
       __snake_case      :					Tuple						=  SwinaSRImageProcessor()
       __snake_case      :					Optional[Any]						=  SwinaSRForImageSuperResolution.from_pretrained('caidas/swin2SR-classical-sr-x2-64'   ).to(lowerCAmelCase__   )

       __snake_case      :					Tuple						=  Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'   )
       __snake_case      :					Tuple						=  processor(images=lowerCAmelCase__	,			return_tensors='pt'   ).to(lowerCAmelCase__   )

       # forward pass
       with torch.no_grad():
             __snake_case      :					Optional[Any]						=  model(**lowerCAmelCase__   )

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










"""simple docstring"""




from functools import lru_cache





@lru_cache
def        a_				(							_lowercase   ):
						if not isinstance(_lowercase       ,						_lowercase   ):
												raise TypeError('''k must be an integer.'''   )
						if k < 0:
												raise ValueError('''k integer must be greater or equal to zero.'''   )
						if k == 0:
												return 0
						elif k == 1:
												return 1
						else:
												return fibonacci(k - 1   ) + fibonacci(k - 2   )





def        a_				(							_lowercase       ,						_lowercase   ):
						_UpperCamelCase			:					Any     =    len(_lowercase   )
						# Find m such that F_m >= n where F_i is the i_th fibonacci number.
						_UpperCamelCase			:					Optional[int]     =    0
						while True:
												if fibonacci(_lowercase   ) >= len_list:
																		_UpperCamelCase			:					List[Any]     =    i
																		break
												i += 1
						_UpperCamelCase			:					Tuple     =    0
						while fibb_k > 0:
												_UpperCamelCase			:					Union[str, Any]     =    min(
												    offset + fibonacci(fibb_k - 1   )       ,						len_list - 1   )  # Prevent out of range
												_UpperCamelCase			:					Any     =    arr[index_k]
												if item_k_1 == val:
																		return index_k
												elif val < item_k_1:
																		fibb_k -= 1
												elif val > item_k_1:
																		offset += fibonacci(fibb_k - 1   )
																		fibb_k -= 2
						else:
												return -1


if __name__ == "__main__":
						import doctest

						doctest.testmod()



