






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					:



      """simple docstring"""


      def __init__(   self      :    List[Any]	,   __lowercase      :    int	,   __lowercase      :    int=13	,   __lowercase      :    Union[str, Any]=32	,   __lowercase      :    Optional[int]=1	,   __lowercase      :    Any=3	,   __lowercase      :    str=16	,   __lowercase      :    Union[str, Any]=[1, 2, 1]	,   __lowercase      :    Dict=[2, 2, 4]	,   __lowercase      :    Any=2	,   __lowercase      :    str=2.0	,   __lowercase      :    List[str]=True	,   __lowercase      :    List[Any]=0.0	,   __lowercase      :    Dict=0.0	,   __lowercase      :    Optional[Any]=0.1	,   __lowercase      :    Optional[Any]="gelu"	,   __lowercase      :    List[str]=False	,   __lowercase      :    Tuple=True	,   __lowercase      :    List[str]=0.02	,   __lowercase      :    Optional[int]=1e-5	,   __lowercase      :    List[str]=True	,   __lowercase      :    str=None	,   __lowercase      :    Dict=False	,   __lowercase      :    Optional[int]=2	,   )							->   Dict:
        __UpperCAmelCase							:			Union[str, Any]     =						parent
        __UpperCAmelCase							:			str     =						batch_size
        __UpperCAmelCase							:			List[Any]     =						image_size
        __UpperCAmelCase							:			Any     =						patch_size
        __UpperCAmelCase							:			List[str]     =						num_channels
        __UpperCAmelCase							:			List[str]     =						embed_dim
        __UpperCAmelCase							:			Optional[Any]     =						depths
        __UpperCAmelCase							:			List[str]     =						num_heads
        __UpperCAmelCase							:			List[Any]     =						window_size
        __UpperCAmelCase							:			int     =						mlp_ratio
        __UpperCAmelCase							:			Any     =						qkv_bias
        __UpperCAmelCase							:			Optional[Any]     =						hidden_dropout_prob
        __UpperCAmelCase							:			str     =						attention_probs_dropout_prob
        __UpperCAmelCase							:			List[str]     =						drop_path_rate
        __UpperCAmelCase							:			Optional[int]     =						hidden_act
        __UpperCAmelCase							:			List[str]     =						use_absolute_embeddings
        __UpperCAmelCase							:			List[str]     =						patch_norm
        __UpperCAmelCase							:			int     =						layer_norm_eps
        __UpperCAmelCase							:			Optional[Any]     =						initializer_range
        __UpperCAmelCase							:			Optional[int]     =						is_training
        __UpperCAmelCase							:			Dict     =						scope
        __UpperCAmelCase							:			List[Any]     =						use_labels
        __UpperCAmelCase							:			str     =						upscale

        # here we set some attributes to make tests pass
        __UpperCAmelCase							:			List[Any]     =						len(__lowercase      )
        __UpperCAmelCase							:			str     =						embed_dim
        __UpperCAmelCase							:			List[str]     =						(image_size // patch_size) ** 2
      def 			UpperCAmelCase   (   self      :    List[str]      )							->   str:
        __UpperCAmelCase							:			Dict     =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

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

        __UpperCAmelCase							:			Union[str, Any]     =						self.get_config()

        return config, pixel_values, labels
      def 			UpperCAmelCase   (   self      :    Optional[int]      )							->   int:
        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      :    Optional[Any]	,   __lowercase      :    List[str]	,   __lowercase      :    Optional[Any]	,   __lowercase      :    str      )							->   Any:
        __UpperCAmelCase							:			Dict     =						SwinaSRModel(config=__lowercase      )
        model.to(__lowercase      )
        model.eval()
        __UpperCAmelCase							:			Any     =						model(__lowercase      )

        self.parent.assertEqual(
            result.last_hidden_state.shape	,   (self.batch_size, self.embed_dim, self.image_size, self.image_size)      )
      def 			UpperCAmelCase   (   self      :    List[str]	,   __lowercase      :    str	,   __lowercase      :    List[Any]	,   __lowercase      :    List[Any]      )							->   List[str]:
        __UpperCAmelCase							:			List[Any]     =						SwinaSRForImageSuperResolution(__lowercase      )
        model.to(__lowercase      )
        model.eval()
        __UpperCAmelCase							:			List[str]     =						model(__lowercase      )

        __UpperCAmelCase							:			str     =						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      :    Union[str, Any]      )							->   Tuple:
        __UpperCAmelCase							:			Dict     =						self.prepare_config_and_inputs()
        __UpperCAmelCase   ,				__UpperCAmelCase   ,				__UpperCAmelCase							:			Any     =						config_and_inputs
        __UpperCAmelCase							:			Tuple     =						{"""pixel_values""": pixel_values}
        return config, inputs_dict


@require_torch
class 					a					(				lowercase__							, lowercase__							, unittest.TestCase     ):



      """simple docstring"""


      a						:				Any							 =			(SwinaSRModel, SwinaSRForImageSuperResolution) if is_torch_available() else ()
      a						:				Optional[Any]							 =			{'feature-extraction': SwinaSRModel} if is_torch_available() else {}

      a						:				int							 =			False
      a						:				List[str]							 =			False
      a						:				str							 =			False
      a						:				int							 =			False
      a						:				List[str]							 =			False
      def 			UpperCAmelCase   (   self      :    Tuple      )							->   int:
        __UpperCAmelCase							:			Optional[int]     =						SwinaSRModelTester(self      )
        __UpperCAmelCase							:			Optional[int]     =						ConfigTester(self	,   config_class=__lowercase	,   embed_dim=37      )
      def 			UpperCAmelCase   (   self      :    List[str]      )							->   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      :    Any      )							->   Optional[Any]:
        __UpperCAmelCase							:			str     =						self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__lowercase      )
      def 			UpperCAmelCase   (   self      :    Tuple      )							->   Any:
        __UpperCAmelCase							:			Optional[int]     =						self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_super_resolution(*__lowercase      )
      @unittest.skip(reason="""Got `CUDA error: misaligned address` with PyTorch 2.0.0."""      )
      def 			UpperCAmelCase   (   self      :    Union[str, Any]      )							->   Optional[int]:
        pass
      @unittest.skip(reason="""Swin2SR does not use inputs_embeds"""      )
      def 			UpperCAmelCase   (   self      :    Union[str, Any]      )							->   List[str]:
        pass
      @unittest.skip(reason="""Swin2SR does not support training yet"""      )
      def 			UpperCAmelCase   (   self      :    Any      )							->   List[str]:
        pass
      @unittest.skip(reason="""Swin2SR does not support training yet"""      )
      def 			UpperCAmelCase   (   self      :    Optional[int]      )							->   Any:
        pass
      def 			UpperCAmelCase   (   self      :    str      )							->   int:
        __UpperCAmelCase   ,				__UpperCAmelCase							:			List[Any]     =						self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
          __UpperCAmelCase							:			str     =						model_class(__lowercase      )
          self.assertIsInstance(model.get_input_embeddings()	,   (nn.Module)      )
          __UpperCAmelCase							:			Optional[Any]     =						model.get_output_embeddings()
          self.assertTrue(x is None or isinstance(__lowercase	,   nn.Linear      )      )
      def 			UpperCAmelCase   (   self      :    str      )							->   Optional[Any]:
        __UpperCAmelCase   ,				__UpperCAmelCase							:			int     =						self.model_tester.prepare_config_and_inputs_for_common()

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

          __UpperCAmelCase							:			int     =						["""pixel_values"""]
          self.assertListEqual(arg_names[:1]	,   __lowercase      )
      @slow
      def 			UpperCAmelCase   (   self      :    int      )							->   str:
        for model_name in SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          __UpperCAmelCase							:			int     =						SwinaSRModel.from_pretrained(__lowercase      )
          self.assertIsNotNone(__lowercase      )
      def 			UpperCAmelCase   (   self      :    int      )							->   int:
        __UpperCAmelCase   ,				__UpperCAmelCase							:			Union[str, Any]     =						self.model_tester.prepare_config_and_inputs_for_common()

        __UpperCAmelCase							:			str     =						_config_zero_init(__lowercase      )
        for model_class in self.all_model_classes:
          __UpperCAmelCase							:			List[Any]     =						model_class(config=__lowercase      )
          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      :    Union[str, Any]      )							->   Optional[Any]:
        __UpperCAmelCase   ,				__UpperCAmelCase							:			List[str]     =						self.model_tester.prepare_config_and_inputs_for_common()
        __UpperCAmelCase							:			Tuple     =						True

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

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

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

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

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

          __UpperCAmelCase							:			Dict     =						outputs.attentions

          self.assertEqual(len(__lowercase      )	,   __lowercase      )

          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     ):



      """simple docstring"""


      def 			UpperCAmelCase   (   self      :    str      )							->   Optional[Any]:
        __UpperCAmelCase							:			List[Any]     =						SwinaSRImageProcessor()
        __UpperCAmelCase							:			List[Any]     =						SwinaSRForImageSuperResolution.from_pretrained("""caidas/swin2SR-classical-sr-x2-64"""      ).to(__lowercase      )

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

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

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










from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


a	: Union[str, Any]      =				{
    "configuration_mobilenet_v1": [
        "MOBILENET_V1_PRETRAINED_CONFIG_ARCHIVE_MAP",
        "MobileNetV1Config",
        "MobileNetV1OnnxConfig",
    ],
}

try:
       if not is_vision_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       a	: int      =				["MobileNetV1FeatureExtractor"]
       a	: int      =				["MobileNetV1ImageProcessor"]

try:
       if not is_torch_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       a	: int      =				[
           "MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST",
           "MobileNetV1ForImageClassification",
           "MobileNetV1Model",
           "MobileNetV1PreTrainedModel",
           "load_tf_weights_in_mobilenet_v1",
       ]


if TYPE_CHECKING:
       from .configuration_mobilenet_va import (
           MOBILENET_V1_PRETRAINED_CONFIG_ARCHIVE_MAP,
           MobileNetVaConfig,
           MobileNetVaOnnxConfig,
       )

       try:
              if not is_vision_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .feature_extraction_mobilenet_va import MobileNetVaFeatureExtractor
              from .image_processing_mobilenet_va import MobileNetVaImageProcessor

       try:
              if not is_torch_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_mobilenet_va import (
                  MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST,
                  MobileNetVaForImageClassification,
                  MobileNetVaModel,
                  MobileNetVaPreTrainedModel,
                  load_tf_weights_in_mobilenet_va,
              )


else:
       import sys

       a	: str      =				_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)


