






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







   def __init__(self       , __a       , __a=1_3       , __a=3_2       , __a=1       , __a=3       , __a=1_6       , __a=[1, 2, 1]       , __a=[2, 2, 4]       , __a=2       , __a=2.0       , __a=True       , __a=0.0       , __a=0.0       , __a=0.1       , __a="gelu"       , __a=False       , __a=True       , __a=0.02       , __a=1E-5       , __a=True       , __a=None       , __a=False       , __a=2       , )      ->   str:
      """simple docstring"""






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

      # here we set some attributes to make tests pass
      __snake_case					:   Any  				=			len(__a)
      __snake_case					:   int  				=			embed_dim
      __snake_case					:   List[str]  				=			(image_size // patch_size) ** 2







   def      SCREAMING_SNAKE_CASE__       (self)      ->   List[Any]:
      """simple docstring"""






      __snake_case					:   List[Any]  				=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

      __snake_case					:   Tuple  				=			self.get_config()

      return config, pixel_values, labels







   def      SCREAMING_SNAKE_CASE__       (self)      ->   List[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      SCREAMING_SNAKE_CASE__       (self       , __a       , __a       , __a)      ->   Tuple:
      """simple docstring"""






      __snake_case					:   Optional[Any]  				=			SwinaSRModel(config=__a)
      model.to(__a)
      model.eval()
      __snake_case					:   Any  				=			model(__a)

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







   def      SCREAMING_SNAKE_CASE__       (self       , __a       , __a       , __a)      ->   Optional[int]:
      """simple docstring"""






      __snake_case					:   Union[str, Any]  				=			SwinaSRForImageSuperResolution(__a)
      model.to(__a)
      model.eval()
      __snake_case					:   Optional[Any]  				=			model(__a)

      __snake_case					:   int  				=			self.image_size * self.upscale
      self.parent.assertEqual(
          result.reconstruction.shape       , (self.batch_size, self.num_channels, expected_image_size, expected_image_size))







   def      SCREAMING_SNAKE_CASE__       (self)      ->   Dict:
      """simple docstring"""






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




@require_torch
class a_     (     UpperCamelCase_		,   UpperCamelCase_		,   unittest.TestCase				):
   _snake_case	   =				(SwinaSRModel, SwinaSRForImageSuperResolution) if is_torch_available() else ()
   _snake_case	   =				{"""feature-extraction""": SwinaSRModel} if is_torch_available() else {}

   _snake_case	   =				False
   _snake_case	   =				False
   _snake_case	   =				False
   _snake_case	   =				False
   _snake_case	   =				False







   def      SCREAMING_SNAKE_CASE__       (self)      ->   str:
      """simple docstring"""






      __snake_case					:   Tuple  				=			SwinaSRModelTester(self)
      __snake_case					:   int  				=			ConfigTester(self       , config_class=__a       , embed_dim=3_7)







   def      SCREAMING_SNAKE_CASE__       (self)      ->   List[str]:
      """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      SCREAMING_SNAKE_CASE__       (self)      ->   Any:
      """simple docstring"""






      __snake_case					:   Tuple  				=			self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*__a)







   def      SCREAMING_SNAKE_CASE__       (self)      ->   int:
      """simple docstring"""






      __snake_case					:   List[str]  				=			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      SCREAMING_SNAKE_CASE__       (self)      ->   Dict:
      """simple docstring"""






      pass







   @unittest.skip(reason='Swin2SR does not use inputs_embeds')
   def      SCREAMING_SNAKE_CASE__       (self)      ->   Union[str, Any]:
      """simple docstring"""






      pass







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






      pass







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






      pass







   def      SCREAMING_SNAKE_CASE__       (self)      ->   Optional[Any]:
      """simple docstring"""






      __snake_case				,__snake_case					:   Dict  				=			self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
         __snake_case					:   Optional[int]  				=			model_class(__a)
         self.assertIsInstance(model.get_input_embeddings()       , (nn.Module))
         __snake_case					:   Union[str, Any]  				=			model.get_output_embeddings()
         self.assertTrue(x is None or isinstance(__a       , nn.Linear))







   def      SCREAMING_SNAKE_CASE__       (self)      ->   int:
      """simple docstring"""






      __snake_case				,__snake_case					:   Optional[Any]  				=			self.model_tester.prepare_config_and_inputs_for_common()

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

         __snake_case					:   Any  				=			['pixel_values']
         self.assertListEqual(arg_names[:1]       , __a)







   @slow
   def      SCREAMING_SNAKE_CASE__       (self)      ->   Optional[int]:
      """simple docstring"""






      for model_name in SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         __snake_case					:   Optional[Any]  				=			SwinaSRModel.from_pretrained(__a)
         self.assertIsNotNone(__a)







   def      SCREAMING_SNAKE_CASE__       (self)      ->   Tuple:
      """simple docstring"""






      __snake_case				,__snake_case					:   Dict  				=			self.model_tester.prepare_config_and_inputs_for_common()

      __snake_case					:   Union[str, Any]  				=			_config_zero_init(__a)
      for model_class in self.all_model_classes:
         __snake_case					:   Any  				=			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      SCREAMING_SNAKE_CASE__       (self)      ->   Tuple:
      """simple docstring"""






      __snake_case				,__snake_case					:   int  				=			self.model_tester.prepare_config_and_inputs_for_common()
      __snake_case					:   str  				=			True

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

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

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

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

         __snake_case					:   Dict  				=			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 a_     (     unittest.TestCase				):







   def      SCREAMING_SNAKE_CASE__       (self)      ->   List[str]:
      """simple docstring"""






      __snake_case					:   Optional[int]  				=			SwinaSRImageProcessor()
      __snake_case					:   int  				=			SwinaSRForImageSuperResolution.from_pretrained('caidas/swin2SR-classical-sr-x2-64').to(__a)

      __snake_case					:   Optional[Any]  				=			Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png')
      __snake_case					:   List[str]  				=			processor(images=__a       , return_tensors='pt').to(__a)

      # forward pass
      with torch.no_grad():
         __snake_case					:   Union[str, Any]  				=			model(**__a)

      # verify the logits
      __snake_case					:   Dict  				=			torch.Size([1, 3, 9_7_6, 1_2_9_6])
      self.assertEqual(outputs.reconstruction.shape       , __a)
      __snake_case					:   int  				=			torch.tensor(
          [[0.5_458, 0.5_546, 0.5_638], [0.5_526, 0.5_565, 0.5_651], [0.5_396, 0.5_426, 0.5_621]]).to(__a)
      self.assertTrue(torch.allclose(outputs.reconstruction[0, 0, :3, :3]       , __a       , atol=1E-4))







'''simple docstring'''






def 							_SCREAMING_SNAKE_CASE	(					)     ->			int:







   """simple docstring"""

   for a in range(3_00	):
      for b in range(a + 1	,		4_00	):
         for c in range(b + 1	,		5_00	):
            if (a + b + c) == 10_00 and (a**2) + (b**2) == (c**2):
               return a * b * c

   return -1




def 							_SCREAMING_SNAKE_CASE	(					)     ->			int:







   """simple docstring"""

   for a in range(3_00	):
      for b in range(4_00	):
         __snake_case					:   Optional[Any]  				=			10_00 - a - b
         if a < b < c and (a**2) + (b**2) == (c**2):
            return a * b * c

   return -1




def 							_SCREAMING_SNAKE_CASE	(					)     ->			None:







   """simple docstring"""
   import timeit

   print(
       timeit.timeit('solution()'	,		setup='from __main__ import solution'	,		number=10_00	)	)
   print(
       timeit.timeit(
           'solution_fast()'	,		setup='from __main__ import solution_fast'	,		number=10_00	)	)


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