


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[str]       ,    _a					: Union[str, Any]       ,    _a					: Optional[int]=1_3       ,    _a					: List[Any]=3_2       ,    _a					: Tuple=1       ,    _a					: int=3       ,    _a					: Union[str, Any]=1_6       ,    _a					: Any=[1, 2, 1]       ,    _a					: Any=[2, 2, 4]       ,    _a					: str=2       ,    _a					: Any=2.0       ,    _a					: List[Any]=True       ,    _a					: Optional[Any]=0.0       ,    _a					: List[Any]=0.0       ,    _a					: Union[str, Any]=0.1       ,    _a					: int="gelu"       ,    _a					: List[Any]=False       ,    _a					: Optional[Any]=True       ,    _a					: Union[str, Any]=0.0_2       ,    _a					: int=1E-5       ,    _a					: Tuple=True       ,    _a					: Optional[int]=None       ,    _a					: Any=False       ,    _a					: Tuple=2       ,    )    ->			Dict:
      UpperCAmelCase						:				Optional[int]		  =			parent
      UpperCAmelCase						:				Any		  =			batch_size
      UpperCAmelCase						:				Optional[Any]		  =			image_size
      UpperCAmelCase						:				Any		  =			patch_size
      UpperCAmelCase						:				int		  =			num_channels
      UpperCAmelCase						:				List[Any]		  =			embed_dim
      UpperCAmelCase						:				List[str]		  =			depths
      UpperCAmelCase						:				List[Any]		  =			num_heads
      UpperCAmelCase						:				Union[str, Any]		  =			window_size
      UpperCAmelCase						:				int		  =			mlp_ratio
      UpperCAmelCase						:				Optional[int]		  =			qkv_bias
      UpperCAmelCase						:				Optional[int]		  =			hidden_dropout_prob
      UpperCAmelCase						:				Optional[Any]		  =			attention_probs_dropout_prob
      UpperCAmelCase						:				Dict		  =			drop_path_rate
      UpperCAmelCase						:				Tuple		  =			hidden_act
      UpperCAmelCase						:				Optional[int]		  =			use_absolute_embeddings
      UpperCAmelCase						:				Optional[Any]		  =			patch_norm
      UpperCAmelCase						:				List[Any]		  =			layer_norm_eps
      UpperCAmelCase						:				Any		  =			initializer_range
      UpperCAmelCase						:				Union[str, Any]		  =			is_training
      UpperCAmelCase						:				List[Any]		  =			scope
      UpperCAmelCase						:				Union[str, Any]		  =			use_labels
      UpperCAmelCase						:				Dict		  =			upscale

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

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

      UpperCAmelCase						:				Optional[Any]		  =			self.get_config()

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

      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					: List[Any]				)    ->			int:
      UpperCAmelCase						:				Optional[Any]		  =			self.prepare_config_and_inputs()
      UpperCAmelCase						:				List[str]		  =			config_and_inputs
      UpperCAmelCase						:				Any		  =			{"pixel_values": pixel_values}
      return config, inputs_dict




@require_torch
class    A_   ( a_      ,						a_      ,						unittest.TestCase     ):







 """simple docstring"""





 _UpperCamelCase				: Tuple      =					(SwinaSRModel, SwinaSRForImageSuperResolution) if is_torch_available() else ()
 _UpperCamelCase				: Any      =					{'''feature-extraction''': SwinaSRModel} if is_torch_available() else {}

 _UpperCamelCase				: Union[str, Any]      =					False
 _UpperCamelCase				: Any      =					False
 _UpperCamelCase				: str      =					False
 _UpperCamelCase				: Any      =					False
 _UpperCamelCase				: Union[str, Any]      =					False
 def   _UpperCamelCase    (			self					: Tuple				)    ->			Dict:
      UpperCAmelCase						:				Dict		  =			SwinaSRModelTester(self				)
      UpperCAmelCase						:				Any		  =			ConfigTester(self       ,    config_class=_a       ,    embed_dim=3_7				)
 def   _UpperCamelCase    (			self					: Optional[Any]				)    ->			Union[str, Any]:
      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					: List[Any]				)    ->			Tuple:
      UpperCAmelCase						:				Union[str, Any]		  =			self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*_a				)
 def   _UpperCamelCase    (			self					: List[Any]				)    ->			Optional[Any]:
      UpperCAmelCase						:				List[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   _UpperCamelCase    (			self					: Union[str, Any]				)    ->			List[str]:
      pass
 @unittest.skip(reason="Swin2SR does not use inputs_embeds"				)
 def   _UpperCamelCase    (			self					: Dict				)    ->			List[Any]:
      pass
 @unittest.skip(reason="Swin2SR does not support training yet"				)
 def   _UpperCamelCase    (			self					: Any				)    ->			Optional[Any]:
      pass
 @unittest.skip(reason="Swin2SR does not support training yet"				)
 def   _UpperCamelCase    (			self					: Tuple				)    ->			Optional[Any]:
      pass
 def   _UpperCamelCase    (			self					: Dict				)    ->			Dict:
      UpperCAmelCase						:				Optional[Any]		  =			self.model_tester.prepare_config_and_inputs_for_common()

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

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

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

      UpperCAmelCase						:				str		  =			_config_zero_init(_a				)
      for model_class in self.all_model_classes:
           UpperCAmelCase						:				Optional[int]		  =			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   _UpperCamelCase    (			self					: Optional[int]				)    ->			Optional[int]:
      UpperCAmelCase						:				Tuple		  =			self.model_tester.prepare_config_and_inputs_for_common()
      UpperCAmelCase						:				Tuple		  =			True

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

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

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

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

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







 """simple docstring"""





 def   _UpperCamelCase    (			self					: str				)    ->			Optional[Any]:
      UpperCAmelCase						:				Union[str, Any]		  =			SwinaSRImageProcessor()
      UpperCAmelCase						:				Union[str, Any]		  =			SwinaSRForImageSuperResolution.from_pretrained("caidas/swin2SR-classical-sr-x2-64"				).to(_a				)

      UpperCAmelCase						:				int		  =			Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"				)
      UpperCAmelCase						:				Optional[int]		  =			processor(images=_a       ,    return_tensors="pt"				).to(_a				)

      # forward pass
      with torch.no_grad():
           UpperCAmelCase						:				Any		  =			model(**_a				)

      # verify the logits
      UpperCAmelCase						:				Any		  =			torch.Size([1, 3, 9_7_6, 1_2_9_6]				)
      self.assertEqual(outputs.reconstruction.shape       ,    _a				)
      UpperCAmelCase						:				List[str]		  =			torch.tensor(
          [[0.5_4_5_8, 0.5_5_4_6, 0.5_6_3_8], [0.5_5_2_6, 0.5_5_6_5, 0.5_6_5_1], [0.5_3_9_6, 0.5_4_2_6, 0.5_6_2_1]]				).to(_a				)
      self.assertTrue(torch.allclose(outputs.reconstruction[0, 0, :3, :3]       ,    _a       ,    atol=1E-4				)				)







from __future__ import annotations

from collections.abc import Callable
from typing import Generic, TypeVar

_snake_case   = TypeVar("T")
_snake_case   = TypeVar("U")




class    A_   ( Generic[T, U]     ):







 """simple docstring"""





 def __init__(			self					: List[Any]       ,    _a					: T | None       ,    _a					: U | None				)    ->			Dict:
      UpperCAmelCase						:				str		  =			key
      UpperCAmelCase						:				Dict		  =			val
      UpperCAmelCase						:				int		  =			0
      UpperCAmelCase						:				DoubleLinkedListNode[T, U] | None		  =			None
      UpperCAmelCase						:				DoubleLinkedListNode[T, U] | None		  =			None

 def __repr__(			self					: List[str]				)    ->			str:
      return "Node: key: {}, val: {}, freq: {}, has next: {}, has prev: {}".format(
          self.key       ,    self.val       ,    self.freq       ,    self.next is not None       ,    self.prev is not None				)




class    A_   ( Generic[T, U]     ):







 """simple docstring"""





 def __init__(			self					: Any				)    ->			None:
      UpperCAmelCase						:				DoubleLinkedListNode[T, U]		  =			DoubleLinkedListNode(_a       ,    _a				)
      UpperCAmelCase						:				DoubleLinkedListNode[T, U]		  =			DoubleLinkedListNode(_a       ,    _a				)
      UpperCAmelCase  , UpperCAmelCase						:				Optional[int]		  =			self.rear, self.head
 def __repr__(			self					: int				)    ->			str:
      UpperCAmelCase						:				Union[str, Any]		  =			["DoubleLinkedList"]
      UpperCAmelCase						:				int		  =			self.head
      while node.next is not None:
           rep.append(str(_a				)				)
           UpperCAmelCase						:				Union[str, Any]		  =			node.next
      rep.append(str(self.rear				)				)
      return ",\n    ".join(_a				)
 def   _UpperCamelCase    (			self					: List[Any]       ,    _a					: DoubleLinkedListNode[T, U]				)    ->			None:
      UpperCAmelCase						:				str		  =			self.rear.prev

      # All nodes other than self.head are guaranteed to have non-None previous
      assert previous is not None

      UpperCAmelCase						:				Any		  =			node
      UpperCAmelCase						:				Optional[int]		  =			previous
      UpperCAmelCase						:				Optional[int]		  =			node
      UpperCAmelCase						:				Union[str, Any]		  =			self.rear
      node.freq += 1
      self._position_node(_a				)
 def   _UpperCamelCase    (			self					: Any       ,    _a					: DoubleLinkedListNode[T, U]				)    ->			None:

      while node.prev is not None and node.prev.freq > node.freq:
           # swap node with previous node
           UpperCAmelCase						:				List[str]		  =			node.prev

           UpperCAmelCase						:				Any		  =			previous_node.prev
           UpperCAmelCase						:				int		  =			node.prev
           UpperCAmelCase						:				Tuple		  =			previous_node
           UpperCAmelCase						:				Optional[int]		  =			node

 def   _UpperCamelCase    (			self					: str       ,    _a					: DoubleLinkedListNode[T, U]				)    ->			DoubleLinkedListNode[T, U] | None:

      if node.prev is None or node.next is None:
           return None

      UpperCAmelCase						:				Dict		  =			node.next
      UpperCAmelCase						:				Optional[Any]		  =			node.prev
      UpperCAmelCase						:				List[Any]		  =			None
      UpperCAmelCase						:				int		  =			None
      return node




class    A_   ( Generic[T, U]     ):







 """simple docstring"""





 _UpperCamelCase				: dict[Callable[[T], U], LFUCache[T, U]]      =					{}
 def __init__(			self					: List[Any]       ,    _a					: int				)    ->			int:
      UpperCAmelCase						:				DoubleLinkedList[T, U]		  =			DoubleLinkedList()
      UpperCAmelCase						:				Any		  =			capacity
      UpperCAmelCase						:				Union[str, Any]		  =			0
      UpperCAmelCase						:				Any		  =			0
      UpperCAmelCase						:				Dict		  =			0
      UpperCAmelCase						:				dict[T, DoubleLinkedListNode[T, U]]		  =			{}
 def __repr__(			self					: Union[str, Any]				)    ->			str:
      return (
          f'CacheInfo(hits={self.hits}, misses={self.miss}, '
          f'capacity={self.capacity}, current_size={self.num_keys})'
      )
 def __contains__(			self					: Optional[int]       ,    _a					: T				)    ->			bool:
      return key in self.cache
 def   _UpperCamelCase    (			self					: Optional[int]       ,    _a					: T				)    ->			U | None:

      if key in self.cache:
           self.hits += 1
           UpperCAmelCase						:				DoubleLinkedListNode[T, U]		  =			self.cache[key]
           UpperCAmelCase						:				Optional[int]		  =			self.list.remove(self.cache[key]				)
           assert node == value_node

           # node is guaranteed not None because it is in self.cache
           assert node is not None
           self.list.add(_a				)
           return node.val
      self.miss += 1
      return None
 def   _UpperCamelCase    (			self					: str       ,    _a					: T       ,    _a					: U				)    ->			None:

      if key not in self.cache:
           if self.num_keys >= self.capacity:
                # delete first node when over capacity
                UpperCAmelCase						:				Any		  =			self.list.head.next

                # guaranteed to have a non-None first node when num_keys > 0
                # explain to type checker via assertions
                assert first_node is not None
                assert first_node.key is not None
                assert self.list.remove(_a				) is not None
                # first_node guaranteed to be in list

                del self.cache[first_node.key]
                self.num_keys -= 1
           UpperCAmelCase						:				Optional[Any]		  =			DoubleLinkedListNode(_a       ,    _a				)
           self.list.add(self.cache[key]				)
           self.num_keys += 1

      else:
           UpperCAmelCase						:				Any		  =			self.list.remove(self.cache[key]				)
           assert node is not None  # node guaranteed to be in list
           UpperCAmelCase						:				str		  =			value
           self.list.add(_a				)

 @classmethod
 def   _UpperCamelCase    (			cls					: type[LFUCache[T, U]]       ,    _a					: int = 1_2_8				)    ->			Callable[[Callable[[T], U]], Callable[..., U]]:

      def cache_decorator_inner(_a					: Callable[[T], U]				) -> Callable[..., U]:
           def cache_decorator_wrapper(*_a					: T				) -> U:
                if func not in cls.decorator_function_to_instance_map:
                     UpperCAmelCase						:				List[Any]		  =			LFUCache(_a				)

                UpperCAmelCase						:				List[Any]		  =			cls.decorator_function_to_instance_map[func].get(args[0]				)
                if result is None:
                     UpperCAmelCase						:				List[Any]		  =			func(*_a				)
                     cls.decorator_function_to_instance_map[func].put(args[0]       ,    _a				)
                return result

           def cache_info() -> LFUCache[T, U]:
                return cls.decorator_function_to_instance_map[func]

           setattr(_a       ,    "cache_info"       ,    _a				)  # noqa: B010

           return cache_decorator_wrapper

      return cache_decorator_inner


if __name__ == "__main__":
      import doctest

      doctest.testmod()



