
"""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       ,							__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       ,							)   ->List[Any]:
      a_						   =     parent
      a_						   =     batch_size
      a_						   =     image_size
      a_						   =     patch_size
      a_						   =     num_channels
      a_						   =     embed_dim
      a_						   =     depths
      a_						   =     num_heads
      a_						   =     window_size
      a_						   =     mlp_ratio
      a_						   =     qkv_bias
      a_						   =     hidden_dropout_prob
      a_						   =     attention_probs_dropout_prob
      a_						   =     drop_path_rate
      a_						   =     hidden_act
      a_						   =     use_absolute_embeddings
      a_						   =     patch_norm
      a_						   =     layer_norm_eps
      a_						   =     initializer_range
      a_						   =     is_training
      a_						   =     scope
      a_						   =     use_labels
      a_						   =     upscale

      # here we set some attributes to make tests pass
      a_						   =     len(__UpperCAmelCase)
      a_						   =     embed_dim
      a_						   =     (image_size // patch_size) ** 2







   def    UpperCAmelCase__	( self)   ->List[Any]:
      a_						   =     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

      a_						   =     None
      if self.use_labels:
         a_						   =     ids_tensor([self.batch_size]       ,							self.type_sequence_label_size)

      a_						   =     self.get_config()

      return config, pixel_values, labels







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

      a_						   =     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)   ->str:
      a_						   =     self.prepare_config_and_inputs()
      a_   ,			a_   ,			a_						   =     config_and_inputs
      a_						   =     {"pixel_values": pixel_values}
      return config, inputs_dict






@require_torch
class 							snake_case       (     SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_							,       unittest.TestCase		):
   a_					:		Union[str, Any]     					=     (SwinaSRModel, SwinaSRForImageSuperResolution) if is_torch_available() else ()
   a_					:		Union[str, Any]     					=     {"""feature-extraction""": SwinaSRModel} if is_torch_available() else {}

   a_					:		Any     					=     False
   a_					:		Union[str, Any]     					=     False
   a_					:		Union[str, Any]     					=     False
   a_					:		int     					=     False
   a_					:		str     					=     False







   def    UpperCAmelCase__	( self)   ->List[Any]:
      a_						   =     SwinaSRModelTester(self)
      a_						   =     ConfigTester(self       ,							config_class=__UpperCAmelCase       ,							embed_dim=37)







   def    UpperCAmelCase__	( self)   ->List[str]:
      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)   ->str:
      a_						   =     self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*__UpperCAmelCase)







   def    UpperCAmelCase__	( self)   ->List[str]:
      a_						   =     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)   ->List[Any]:
      pass







   @unittest.skip(reason="Swin2SR does not use inputs_embeds")
   def    UpperCAmelCase__	( self)   ->List[Any]:
      pass







   @unittest.skip(reason="Swin2SR does not support training yet")
   def    UpperCAmelCase__	( self)   ->Tuple:
      pass







   @unittest.skip(reason="Swin2SR does not support training yet")
   def    UpperCAmelCase__	( self)   ->Dict:
      pass







   def    UpperCAmelCase__	( self)   ->Union[str, Any]:
      a_   ,			a_						   =     self.model_tester.prepare_config_and_inputs_for_common()

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







   def    UpperCAmelCase__	( self)   ->List[str]:
      a_   ,			a_						   =     self.model_tester.prepare_config_and_inputs_for_common()

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

         a_						   =     ["pixel_values"]
         self.assertListEqual(arg_names[:1]       ,							__UpperCAmelCase)







   @slow
   def    UpperCAmelCase__	( self)   ->Dict:
      for model_name in SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         a_						   =     SwinaSRModel.from_pretrained(__UpperCAmelCase)
         self.assertIsNotNone(__UpperCAmelCase)







   def    UpperCAmelCase__	( self)   ->int:
      a_   ,			a_						   =     self.model_tester.prepare_config_and_inputs_for_common()

      a_						   =     _config_zero_init(__UpperCAmelCase)
      for model_class in self.all_model_classes:
         a_						   =     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)   ->Dict:
      a_   ,			a_						   =     self.model_tester.prepare_config_and_inputs_for_common()
      a_						   =     True

      for model_class in self.all_model_classes:
         a_						   =     True
         a_						   =     False
         a_						   =     True
         a_						   =     model_class(__UpperCAmelCase)
         model.to(__UpperCAmelCase)
         model.eval()
         with torch.no_grad():
            a_						   =     model(**self._prepare_for_class(__UpperCAmelCase       ,							__UpperCAmelCase))
         a_						   =     outputs.attentions
         a_						   =     len(self.model_tester.depths)
         self.assertEqual(len(__UpperCAmelCase)       ,							__UpperCAmelCase)

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

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

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

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







   def    UpperCAmelCase__	( self)   ->Any:
      a_						   =     SwinaSRImageProcessor()
      a_						   =     SwinaSRForImageSuperResolution.from_pretrained("caidas/swin2SR-classical-sr-x2-64").to(__UpperCAmelCase)

      a_						   =     Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
      a_						   =     processor(images=__UpperCAmelCase       ,							return_tensors="pt").to(__UpperCAmelCase)

      # forward pass
      with torch.no_grad():
         a_						   =     model(**__UpperCAmelCase)

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

"""simple docstring"""






def    UpperCamelCase						(					UpperCAmelCase ,   UpperCAmelCase = 1_000     )						->str:

   """simple docstring"""



   if (not isinstance(UpperCAmelCase ,   UpperCAmelCase     )) or (digit_position <= 0):
      raise ValueError("Digit position must be a positive integer"     )
   elif (not isinstance(UpperCAmelCase ,   UpperCAmelCase     )) or (precision < 0):
      raise ValueError("Precision must be a nonnegative integer"     )

   # compute an approximation of (16 ** (n - 1)) * pi whose fractional part is mostly
   # accurate
   a_						   =     (
       4 * _subsum(UpperCAmelCase ,   1 ,   UpperCAmelCase     )
       - 2 * _subsum(UpperCAmelCase ,   4 ,   UpperCAmelCase     )
       - _subsum(UpperCAmelCase ,   5 ,   UpperCAmelCase     )
       - _subsum(UpperCAmelCase ,   6 ,   UpperCAmelCase     )
   )

   # return the first hex digit of the fractional part of the result
   return hex(int((sum_result % 1) * 16     )     )[2:]
def    UpperCamelCase						(					UpperCAmelCase ,   UpperCAmelCase ,   UpperCAmelCase     )						->float:

   """simple docstring"""



   a_						   =     0.0
   for sum_index in range(digit_pos_to_extract + precision     ):
      a_						   =     8 * sum_index + denominator_addend
      if sum_index < digit_pos_to_extract:
         # if the exponential term is an integer and we mod it by the denominator
         # before dividing, only the integer part of the sum will change;
         # the fractional part will not
         a_						   =     pow(
             16 ,   digit_pos_to_extract - 1 - sum_index ,   UpperCAmelCase     )
      else:
         a_						   =     pow(16 ,   digit_pos_to_extract - 1 - sum_index     )
      total += exponential_term / denominator
   return total


if __name__ == "__main__":
      import doctest

      doctest.testmod()