




from typing import Callable, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


__a  :		int			=    logging.get_logger(__name__)

__a  :		Optional[int]			=    {
    'microsoft/prophetnet-large-uncased': (
        'https://huggingface.co/microsoft/prophetnet-large-uncased/resolve/main/config.json'
    ),
}







class       UpperCAmelCase(     snake_case_     ):



	"""simple docstring"""






	a	:					str         =     """prophetnet"""
	a	:					Tuple         =     ["""past_key_values"""]
	a	:					int         =     {
	    """num_attention_heads""": """num_encoder_attention_heads""",
	}

	def __init__(     self       ,      lowerCamelCase = 0.1       ,      lowerCamelCase = "gelu"       ,      lowerCamelCase = 30522       ,      lowerCamelCase = 1024       ,      lowerCamelCase = 4096       ,      lowerCamelCase = 12       ,      lowerCamelCase = 16       ,      lowerCamelCase = 4096       ,      lowerCamelCase = 12       ,      lowerCamelCase = 16       ,      lowerCamelCase = 0.1       ,      lowerCamelCase = 0.1       ,      lowerCamelCase = 512       ,      lowerCamelCase = 0.02       ,      lowerCamelCase = True       ,      lowerCamelCase = True       ,      lowerCamelCase = 0       ,      lowerCamelCase = 2       ,      lowerCamelCase = 32       ,      lowerCamelCase = 128       ,      lowerCamelCase = False       ,      lowerCamelCase = 0.0       ,      lowerCamelCase = True       ,      lowerCamelCase = 0       ,      lowerCamelCase = 1       ,      lowerCamelCase = 2       ,      **lowerCamelCase       ,      )					->			Tuple:





								"""simple docstring"""


								lowercase__  :       Optional[Any]   					=							vocab_size
								lowercase__  :       Union[str, Any]   					=							hidden_size
								lowercase__  :       Optional[Any]   					=							encoder_ffn_dim
								lowercase__  :       Dict   					=							num_encoder_layers
								lowercase__  :       Tuple   					=							num_encoder_attention_heads
								lowercase__  :       Tuple   					=							decoder_ffn_dim
								lowercase__  :       Dict   					=							num_decoder_layers
								lowercase__  :       Optional[Any]   					=							num_decoder_attention_heads
								lowercase__  :       Tuple   					=							max_position_embeddings
								lowercase__  :       int   					=							init_std  # Normal(0, this parameter)
								lowercase__  :       Optional[Any]   					=							activation_function

								# parameters for prophetnet
								lowercase__  :       List[Any]   					=							ngram
								lowercase__  :       List[str]   					=							num_buckets
								lowercase__  :       Optional[Any]   					=							relative_max_distance
								lowercase__  :       Optional[int]   					=							disable_ngram_loss
								lowercase__  :       Optional[Any]   					=							eps

								# 3 Types of Dropout
								lowercase__  :       Dict   					=							attention_dropout
								lowercase__  :       Tuple   					=							activation_dropout
								lowercase__  :       Dict   					=							dropout

								lowercase__  :       Tuple   					=							use_cache

								super().__init__(
								    pad_token_id=lowerCamelCase       ,      bos_token_id=lowerCamelCase       ,      eos_token_id=lowerCamelCase       ,      is_encoder_decoder=lowerCamelCase       ,      add_cross_attention=lowerCamelCase       ,      decoder_start_token_id=lowerCamelCase       ,      **lowerCamelCase       ,      )

	@property
	def     __a	(     self				)					->			Optional[Any]:





								"""simple docstring"""


								return self.num_encoder_layers + self.num_decoder_layers







	@num_hidden_layers.setter
	def     __a	(     self       ,      lowerCamelCase				)					->			List[Any]:





								"""simple docstring"""


								raise NotImplementedError(
								    "This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and"
								    " `num_decoder_layers`."				)







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


      '''simple docstring'''




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

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





    def 				lowerCamelCase__      (							self	:					str			):


      '''simple docstring'''




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

      a     :			List[str]				=   None
      if self.use_labels:
        a     :			Tuple				=   ids_tensor([self.batch_size]				,		self.type_sequence_label_size			)

      a     :			Any				=   self.get_config()

      return config, pixel_values, labels





    def 				lowerCamelCase__      (							self	:					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	:					Union[str, Any]				,		A	:					Dict				,		A	:					Union[str, Any]				,		A	:					List[str]			):


      '''simple docstring'''




      a     :			List[Any]				=   SwinaSRModel(config=A			)
      model.to(A			)
      model.eval()
      a     :			Optional[int]				=   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	:					List[str]				,		A	:					Tuple				,		A	:					str				,		A	:					Tuple			):


      '''simple docstring'''




      a     :			Optional[Any]				=   SwinaSRForImageSuperResolution(A			)
      model.to(A			)
      model.eval()
      a     :			List[str]				=   model(A			)

      a     :			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 				lowerCamelCase__      (							self	:					Union[str, Any]			):


      '''simple docstring'''




      a     :			Tuple				=   self.prepare_config_and_inputs()
      a,     a,     a     :			Union[str, Any]				=   config_and_inputs
      a     :			List[str]				=   {'pixel_values': pixel_values}
      return config, inputs_dict






@require_torch
class 						snake_case  (  UpperCAmelCase   , UpperCAmelCase   , unittest.TestCase       ):
    __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	:					Optional[int]			):


      '''simple docstring'''




      a     :			List[str]				=   SwinaSRModelTester(self			)
      a     :			int				=   ConfigTester(self				,		config_class=A				,		embed_dim=3_7			)





    def 				lowerCamelCase__      (							self	:					Optional[int]			):


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


      '''simple docstring'''




      a     :			str				=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*A			)





    def 				lowerCamelCase__      (							self	:					Tuple			):


      '''simple docstring'''




      a     :			Any				=   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	:					str			):


      '''simple docstring'''




      pass





    @unittest.skip(reason='Swin2SR does not use inputs_embeds'			)
    def 				lowerCamelCase__      (							self	:					Tuple			):


      '''simple docstring'''




      pass





    @unittest.skip(reason='Swin2SR does not support training yet'			)
    def 				lowerCamelCase__      (							self	:					Optional[int]			):


      '''simple docstring'''




      pass





    @unittest.skip(reason='Swin2SR does not support training yet'			)
    def 				lowerCamelCase__      (							self	:					int			):


      '''simple docstring'''




      pass





    def 				lowerCamelCase__      (							self	:					int			):


      '''simple docstring'''




      a,     a     :			Optional[int]				=   self.model_tester.prepare_config_and_inputs_for_common()

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





    def 				lowerCamelCase__      (							self	:					Optional[int]			):


      '''simple docstring'''




      a,     a     :			int				=   self.model_tester.prepare_config_and_inputs_for_common()

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

        a     :			Tuple				=   ['pixel_values']
        self.assertListEqual(arg_names[:1]				,		A			)





    @slow
    def 				lowerCamelCase__      (							self	:					List[str]			):


      '''simple docstring'''




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





    def 				lowerCamelCase__      (							self	:					Dict			):


      '''simple docstring'''




      a,     a     :			str				=   self.model_tester.prepare_config_and_inputs_for_common()

      a     :			int				=   _config_zero_init(A			)
      for model_class in self.all_model_classes:
        a     :			List[str]				=   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	:					List[str]			):


      '''simple docstring'''




      a,     a     :			Union[str, Any]				=   self.model_tester.prepare_config_and_inputs_for_common()
      a     :			List[str]				=   True

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

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

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

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

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





    def 				lowerCamelCase__      (							self	:					Optional[int]			):


      '''simple docstring'''




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

      a     :			str				=   Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'			)
      a     :			Union[str, Any]				=   processor(images=A				,		return_tensors='pt'			).to(A			)

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

      # verify the logits
      a     :			Optional[int]				=   torch.Size([1, 3, 9_7_6, 1_2_9_6]			)
      self.assertEqual(outputs.reconstruction.shape				,		A			)
      a     :			Tuple				=   torch.tensor(
          [[0.54_58, 0.55_46, 0.56_38], [0.55_26, 0.55_65, 0.56_51], [0.53_96, 0.54_26, 0.56_21]]			).to(A			)
      self.assertTrue(torch.allclose(outputs.reconstruction[0, 0, :3, :3]				,		A				,		atol=1E-4			)			)




