


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




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

             # here we set some attributes to make tests pass
             _lowerCamelCase :	Optional[Any]						=len(__SCREAMING_SNAKE_CASE				)
             _lowerCamelCase :	int						=embed_dim
             _lowerCamelCase :	Union[str, Any]						=(image_size // patch_size) ** 2






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




             _lowerCamelCase :	List[str]						=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

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

             _lowerCamelCase :	int						=self.get_config()

             return config, pixel_values, labels






      def  lowerCamelCase (      self		:  Optional[Any]				)      ->		int:
             """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    ,     lowercase_		:  List[Any]    ,     lowercase_		:  int    ,     lowercase_		:  str				)      ->		Optional[int]:
             """simple docstring"""




             _lowerCamelCase :	Optional[Any]						=SwinaSRModel(config=__SCREAMING_SNAKE_CASE				)
             model.to(__SCREAMING_SNAKE_CASE				)
             model.eval()
             _lowerCamelCase :	Optional[Any]						=model(__SCREAMING_SNAKE_CASE				)

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






      def  lowerCamelCase (      self		:  List[Any]    ,     lowercase_		:  str    ,     lowercase_		:  Optional[Any]    ,     lowercase_		:  Union[str, Any]				)      ->		Tuple:
             """simple docstring"""




             _lowerCamelCase :	int						=SwinaSRForImageSuperResolution(__SCREAMING_SNAKE_CASE				)
             model.to(__SCREAMING_SNAKE_CASE				)
             model.eval()
             _lowerCamelCase :	Tuple						=model(__SCREAMING_SNAKE_CASE				)

             _lowerCamelCase :	Optional[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  lowerCamelCase (      self		:  Optional[int]				)      ->		Tuple:
             """simple docstring"""




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




@require_torch
class A						(     lowerCAmelCase_					,							lowerCAmelCase_					,							unittest.TestCase  ):
      UpperCamelCase__							:						List[Any]   =(SwinaSRModel, SwinaSRForImageSuperResolution) if is_torch_available() else ()
      UpperCamelCase__							:						Optional[Any]   ={"""feature-extraction""": SwinaSRModel} if is_torch_available() else {}

      UpperCamelCase__							:						str   =False
      UpperCamelCase__							:						Dict   =False
      UpperCamelCase__							:						Any   =False
      UpperCamelCase__							:						Tuple   =False
      UpperCamelCase__							:						Optional[int]   =False






      def  lowerCamelCase (      self		:  int				)      ->		Union[str, Any]:
             """simple docstring"""




             _lowerCamelCase :	str						=SwinaSRModelTester(self				)
             _lowerCamelCase :	List[Any]						=ConfigTester(self    ,     config_class=__SCREAMING_SNAKE_CASE    ,     embed_dim=37				)






      def  lowerCamelCase (      self		:  Any				)      ->		Union[str, 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  lowerCamelCase (      self		:  Dict				)      ->		Union[str, Any]:
             """simple docstring"""




             _lowerCamelCase :	Any						=self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE				)






      def  lowerCamelCase (      self		:  List[str]				)      ->		Optional[Any]:
             """simple docstring"""




             _lowerCamelCase :	int						=self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_image_super_resolution(*__SCREAMING_SNAKE_CASE				)






      @unittest.skip(reason='Got `CUDA error: misaligned address` with PyTorch 2.0.0.'				)
      def  lowerCamelCase (      self		:  List[Any]				)      ->		List[Any]:
             """simple docstring"""




             pass






      @unittest.skip(reason='Swin2SR does not use inputs_embeds'				)
      def  lowerCamelCase (      self		:  Tuple				)      ->		List[Any]:
             """simple docstring"""




             pass






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




             pass






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




             pass






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




             _lowerCamelCase			,  _lowerCamelCase :	Tuple						=self.model_tester.prepare_config_and_inputs_for_common()

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






      def  lowerCamelCase (      self		:  Tuple				)      ->		Union[str, Any]:
             """simple docstring"""




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

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

                    _lowerCamelCase :	Union[str, Any]						=['pixel_values']
                    self.assertListEqual(arg_names[:1]    ,     __SCREAMING_SNAKE_CASE				)






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




             for model_name in SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                    _lowerCamelCase :	List[str]						=SwinaSRModel.from_pretrained(__SCREAMING_SNAKE_CASE				)
                    self.assertIsNotNone(__SCREAMING_SNAKE_CASE				)






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




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

             _lowerCamelCase :	List[str]						=_config_zero_init(__SCREAMING_SNAKE_CASE				)
             for model_class in self.all_model_classes:
                    _lowerCamelCase :	Dict						=model_class(config=__SCREAMING_SNAKE_CASE				)
                    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		:  Dict				)      ->		List[str]:
             """simple docstring"""




             _lowerCamelCase			,  _lowerCamelCase :	Tuple						=self.model_tester.prepare_config_and_inputs_for_common()
             _lowerCamelCase :	int						=True

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

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

                    self.assertListEqual(
                        list(attentions[0].shape[-3:]				)    ,     [self.model_tester.num_heads[0], window_size_squared, window_size_squared]    ,     )
                    _lowerCamelCase :	List[str]						=len(__SCREAMING_SNAKE_CASE				)

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

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

                    _lowerCamelCase :	List[Any]						=outputs.attentions

                    self.assertEqual(len(__SCREAMING_SNAKE_CASE				)    ,     __SCREAMING_SNAKE_CASE				)

                    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  lowerCamelCase (      self		:  Optional[Any]				)      ->		int:
             """simple docstring"""




             _lowerCamelCase :	int						=SwinaSRImageProcessor()
             _lowerCamelCase :	int						=SwinaSRForImageSuperResolution.from_pretrained('caidas/swin2SR-classical-sr-x2-64'				).to(__SCREAMING_SNAKE_CASE				)

             _lowerCamelCase :	str						=Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'				)
             _lowerCamelCase :	str						=processor(images=__SCREAMING_SNAKE_CASE    ,     return_tensors='pt'				).to(__SCREAMING_SNAKE_CASE				)

             # forward pass
             with torch.no_grad():
                    _lowerCamelCase :	Tuple						=model(**__SCREAMING_SNAKE_CASE				)

             # verify the logits
             _lowerCamelCase :	List[Any]						=torch.Size([1, 3, 976, 1296]				)
             self.assertEqual(outputs.reconstruction.shape    ,     __SCREAMING_SNAKE_CASE				)
             _lowerCamelCase :	Tuple						=torch.tensor(
                 [[0.5458, 0.5546, 0.5638], [0.5526, 0.5565, 0.5651], [0.5396, 0.5426, 0.5621]]				).to(__SCREAMING_SNAKE_CASE				)
             self.assertTrue(torch.allclose(outputs.reconstruction[0, 0, :3, :3]    ,     __SCREAMING_SNAKE_CASE    ,     atol=1E-4				)				)






from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


lowerCamelCase		      = {
    'configuration_deberta_v2': ['DEBERTA_V2_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DebertaV2Config', 'DebertaV2OnnxConfig'],
    'tokenization_deberta_v2': ['DebertaV2Tokenizer'],
}

try:
 if not is_tokenizers_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 lowerCamelCase		      = ['DebertaV2TokenizerFast']

try:
 if not is_tf_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 lowerCamelCase		      = [
     'TF_DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST',
     'TFDebertaV2ForMaskedLM',
     'TFDebertaV2ForQuestionAnswering',
     'TFDebertaV2ForSequenceClassification',
     'TFDebertaV2ForTokenClassification',
     'TFDebertaV2Model',
     'TFDebertaV2PreTrainedModel',
 ]

try:
 if not is_torch_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 lowerCamelCase		      = [
     'DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST',
     'DebertaV2ForMaskedLM',
     'DebertaV2ForMultipleChoice',
     'DebertaV2ForQuestionAnswering',
     'DebertaV2ForSequenceClassification',
     'DebertaV2ForTokenClassification',
     'DebertaV2Model',
     'DebertaV2PreTrainedModel',
 ]


if TYPE_CHECKING:
 from .configuration_deberta_va import (
     DEBERTA_V2_PRETRAINED_CONFIG_ARCHIVE_MAP,
     DebertaVaConfig,
     DebertaVaOnnxConfig,
 )
 from .tokenization_deberta_va import DebertaVaTokenizer

 try:
  if not is_tokenizers_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .tokenization_deberta_va_fast import DebertaVaTokenizerFast

 try:
  if not is_tf_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_tf_deberta_va import (
      TF_DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST,
      TFDebertaVaForMaskedLM,
      TFDebertaVaForQuestionAnswering,
      TFDebertaVaForSequenceClassification,
      TFDebertaVaForTokenClassification,
      TFDebertaVaModel,
      TFDebertaVaPreTrainedModel,
  )

 try:
  if not is_torch_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_deberta_va import (
      DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST,
      DebertaVaForMaskedLM,
      DebertaVaForMultipleChoice,
      DebertaVaForQuestionAnswering,
      DebertaVaForSequenceClassification,
      DebertaVaForTokenClassification,
      DebertaVaModel,
      DebertaVaPreTrainedModel,
  )

else:
 import sys

 lowerCamelCase		      = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)


