code: 
  
  
  """simple docstring"""
  
  
  
  
  import json
  import os
  import re
  import unicodedata
  from typing import Optional, Tuple
  
  from ...tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace
  from ...utils import logging
  
  
  __magic_name__	:   str          =							logging.get_logger(__name__)
  
  __magic_name__	:   Optional[Any]          =							{
      'vocab_file': 'vocab.json',
      'merges_file': 'merges.txt',
  }
  
  __magic_name__	:   str          =							{
      'vocab_file': {'openai-gpt': 'https://huggingface.co/openai-gpt/resolve/main/vocab.json'},
      'merges_file': {'openai-gpt': 'https://huggingface.co/openai-gpt/resolve/main/merges.txt'},
  }
  
  __magic_name__	:   Optional[int]          =							{
      'openai-gpt': 5_1_2,
  }
  
  
  
  
  
  def 			a_   (  lowercase__   :Any    ):
  			__lowerCamelCase     :   str        =			text.strip()
  			if not text:
  						return []
  			__lowerCamelCase     :   List[str]        =			text.split()
  			return tokens
  
  
  
  
  class  __snake_case      (lowerCamelCase     ):
  
  
  
  
  							def __init__(    self:						List[str]    ,       A_:						List[str]=True    ,       A_:						List[Any]=None    ,       A_:						Any=True    ,       A_:						Any=None    ,       A_:						str=True    ,       ):
  										if never_split is None:
  													__lowerCamelCase     :   Optional[Any]        =			[]
  										__lowerCamelCase     :   Union[str, Any]        =			do_lower_case
  										__lowerCamelCase     :   str        =			set(A_      )
  										__lowerCamelCase     :   Dict        =			tokenize_chinese_chars
  										__lowerCamelCase     :   Any        =			strip_accents
  										__lowerCamelCase     :   List[str]        =			do_split_on_punc
  
  
  
  
  							def      __a      (    self:						Union[str, Any]    ,       A_:						Union[str, Any]    ,       A_:						int=None      ):
  										__lowerCamelCase     :   Optional[Any]        =			self.never_split.union(set(A_      )      ) if never_split else self.never_split
  										__lowerCamelCase     :   Optional[int]        =			self._clean_text(A_      )
  
  										# This was added on November 1st, 2018 for the multilingual and Chinese
  										# models. This is also applied to the English models now, but it doesn't
  										# matter since the English models were not trained on any Chinese data
  										# and generally don't have any Chinese data in them (there are Chinese
  										# characters in the vocabulary because Wikipedia does have some Chinese
  										# words in the English Wikipedia.).
  										if self.tokenize_chinese_chars:
  													__lowerCamelCase     :   int        =			self._tokenize_chinese_chars(A_      )
  										# prevents treating the same character with different unicode codepoints as different characters
  										__lowerCamelCase     :   List[Any]        =			unicodedata.normalize("""NFC"""    ,       A_      )
  										__lowerCamelCase     :   List[str]        =			whitespace_tokenize(A_      )
  										__lowerCamelCase     :   Union[str, Any]        =			[]
  										for token in orig_tokens:
  													if token not in never_split:
  																if self.do_lower_case:
  																			__lowerCamelCase     :   Optional[Any]        =			token.lower()
  																			if self.strip_accents is not False:
  																						__lowerCamelCase     :   Union[str, Any]        =			self._run_strip_accents(A_      )
  																elif self.strip_accents:
  																			__lowerCamelCase     :   str        =			self._run_strip_accents(A_      )
  													split_tokens.extend(self._run_split_on_punc(A_    ,       A_      )      )
  
  										__lowerCamelCase     :   Tuple        =			whitespace_tokenize(""" """.join(A_      )      )
  										return output_tokens
  
  
  
  
  							def      __a      (    self:						Optional[int]    ,       A_:						Union[str, Any]      ):
  										__lowerCamelCase     :   Any        =			unicodedata.normalize("""NFD"""    ,       A_      )
  										__lowerCamelCase     :   List[Any]        =			[]
  										for char in text:
  													__lowerCamelCase     :   Optional[Any]        =			unicodedata.category(A_      )
  													if cat == "Mn":
  																continue
  													output.append(A_      )
  										return "".join(A_      )
  
  
  
  
  							def      __a      (    self:						Dict    ,       A_:						int    ,       A_:						Union[str, Any]=None      ):
  										if not self.do_split_on_punc or (never_split is not None and text in never_split):
  													return [text]
  										__lowerCamelCase     :   int        =			list(A_      )
  										__lowerCamelCase     :   Optional[int]        =			0
  										__lowerCamelCase     :   str        =			True
  										__lowerCamelCase     :   Any        =			[]
  										while i < len(A_      ):
  													__lowerCamelCase     :   Union[str, Any]        =			chars[i]
  													if _is_punctuation(A_      ):
  																output.append([char]      )
  																__lowerCamelCase     :   Dict        =			True
  													else:
  																if start_new_word:
  																			output.append([]      )
  																__lowerCamelCase     :   Tuple        =			False
  																output[-1].append(A_      )
  													i += 1
  
  										return ["".join(A_      ) for x in output]
  
  
  
  
  							def      __a      (    self:						List[str]    ,       A_:						Optional[int]      ):
  										__lowerCamelCase     :   int        =			[]
  										for char in text:
  													__lowerCamelCase     :   Dict        =			ord(A_      )
  													if self._is_chinese_char(A_      ):
  																output.append(""" """      )
  																output.append(A_      )
  																output.append(""" """      )
  													else:
  																output.append(A_      )
  										return "".join(A_      )
  
  
  
  
  							def      __a      (    self:						List[Any]    ,       A_:						Optional[int]      ):
  										# This defines a "chinese character" as anything in the CJK Unicode block:
  										#   https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
  										#
  										# Note that the CJK Unicode block is NOT all Japanese and Korean characters,
  										# despite its name. The modern Korean Hangul alphabet is a different block,
  										# as is Japanese Hiragana and Katakana. Those alphabets are used to write
  										# space-separated words, so they are not treated specially and handled
  										# like the all of the other languages.
  										if (
  										    (cp >= 0X4E00 and cp <= 0X9FFF)
  										    or (cp >= 0X3400 and cp <= 0X4DBF)  #
  										    or (cp >= 0X2_0000 and cp <= 0X2_A6DF)  #
  										    or (cp >= 0X2_A700 and cp <= 0X2_B73F)  #
  										    or (cp >= 0X2_B740 and cp <= 0X2_B81F)  #
  										    or (cp >= 0X2_B820 and cp <= 0X2_CEAF)  #
  										    or (cp >= 0XF900 and cp <= 0XFAFF)
  										    or (cp >= 0X2_F800 and cp <= 0X2_FA1F)  #
  										):  #
  													return True
  
  										return False
  
  
  
  
  							def      __a      (    self:						Optional[Any]    ,       A_:						Tuple      ):
  										__lowerCamelCase     :   List[Any]        =			[]
  										for char in text:
  													__lowerCamelCase     :   Optional[int]        =			ord(A_      )
  													if cp == 0 or cp == 0XFFFD or _is_control(A_      ):
  																continue
  													if _is_whitespace(A_      ):
  																output.append(""" """      )
  													else:
  																output.append(A_      )
  										return "".join(A_      )
  
  
  
  
  
  def 			a_   (  lowercase__   :List[str]    ):
  			__lowerCamelCase     :   List[Any]        =			set()
  			__lowerCamelCase     :   Optional[int]        =			word[0]
  			for char in word[1:]:
  						pairs.add((prev_char, char)    )
  						__lowerCamelCase     :   Union[str, Any]        =			char
  			return pairs
  
  
  
  
  
  def 			a_   (  lowercase__   :Optional[Any]    ):
  			__lowerCamelCase     :   str        =			text.replace("""—""", """-"""    )
  			__lowerCamelCase     :   List[Any]        =			text.replace("""–""", """-"""    )
  			__lowerCamelCase     :   Tuple        =			text.replace("""―""", """-"""    )
  			__lowerCamelCase     :   Union[str, Any]        =			text.replace("""…""", """..."""    )
  			__lowerCamelCase     :   Union[str, Any]        =			text.replace("""´""", """'"""    )
  			__lowerCamelCase     :   Dict        =			re.sub(r"""(-+|~+|!+|\"+|;+|\?+|\++|,+|\)+|\(+|\\+|\/+|\*+|\[+|\]+|}+|{+|\|+|_+)""", r""" \1 """, lowercase__    )
  			__lowerCamelCase     :   Optional[Any]        =			re.sub(r"""\s*\n\s*""", """ \n """, lowercase__    )
  			__lowerCamelCase     :   Any        =			re.sub(r"""[^\S\n]+""", """ """, lowercase__    )
  			return text.strip()
  
  
  
  
  class  __snake_case      (lowerCamelCase     ):
  							__a				   =					VOCAB_FILES_NAMES
  							__a				   =					PRETRAINED_VOCAB_FILES_MAP
  							__a				   =					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  							__a				   =					['''input_ids''', '''attention_mask''']
  
  
  
  
  							def __init__(    self:						Union[str, Any]    ,       A_:						int    ,       A_:						Dict    ,       A_:						Dict="<unk>"    ,       **A_:						Union[str, Any]      ):
  										super().__init__(unk_token=A_    ,       **A_      )
  
  										try:
  													import ftfy
  													from spacy.lang.en import English
  
  													__lowerCamelCase     :   Optional[int]        =			English()
  													__lowerCamelCase     :   Union[str, Any]        =			_nlp.tokenizer
  													__lowerCamelCase     :   str        =			ftfy.fix_text
  										except ImportError:
  													logger.warning("""ftfy or spacy is not installed using BERT BasicTokenizer instead of SpaCy & ftfy."""      )
  													__lowerCamelCase     :   int        =			BasicTokenizer(do_lower_case=A_      )
  													__lowerCamelCase     :   Union[str, Any]        =			None
  
  										with open(A_    ,       encoding="""utf-8"""      ) as vocab_handle:
  													__lowerCamelCase     :   str        =			json.load(A_      )
  										__lowerCamelCase     :   int        =			{v: k for k, v in self.encoder.items()}
  										with open(A_    ,       encoding="""utf-8"""      ) as merges_handle:
  													__lowerCamelCase     :   Union[str, Any]        =			merges_handle.read().split("""\n"""      )[1:-1]
  										__lowerCamelCase     :   List[Any]        =			[tuple(merge.split()      ) for merge in merges]
  										__lowerCamelCase     :   int        =			dict(zip(A_    ,       range(len(A_      )      )      )      )
  										__lowerCamelCase     :   Union[str, Any]        =			{}
  
  
  
  
  							@property
  							def      __a      (    self:						List[str]      ):
  										return True
  
  
  
  
  							@property
  							def      __a      (    self:						Optional[Any]      ):
  										return len(self.encoder      )
  
  
  
  
  							def      __a      (    self:						Optional[int]      ):
  										return dict(self.encoder    ,       **self.added_tokens_encoder      )
  
  
  
  
  							def      __a      (    self:						Union[str, Any]    ,       A_:						Tuple      ):
  										__lowerCamelCase     :   List[str]        =			tuple(token[:-1]      ) + (token[-1] + """</w>""",)
  										if token in self.cache:
  													return self.cache[token]
  										__lowerCamelCase     :   Dict        =			get_pairs(A_      )
  
  										if not pairs:
  													return token + "</w>"
  
  										while True:
  													__lowerCamelCase     :   List[Any]        =			min(A_    ,       key=lambda A_      : self.bpe_ranks.get(A_    ,       float("""inf"""      )      )      )
  													if bigram not in self.bpe_ranks:
  																break
  													__lowerCamelCase    ,__lowerCamelCase     :   List[Any]        =			bigram
  													__lowerCamelCase     :   int        =			[]
  													__lowerCamelCase     :   List[Any]        =			0
  													while i < len(A_      ):
  																try:
  																			__lowerCamelCase     :   List[str]        =			word.index(A_    ,       A_      )
  																except ValueError:
  																			new_word.extend(word[i:]      )
  																			break
  																else:
  																			new_word.extend(word[i:j]      )
  																			__lowerCamelCase     :   Optional[Any]        =			j
  
  																if word[i] == first and i < len(A_      ) - 1 and word[i + 1] == second:
  																			new_word.append(first + second      )
  																			i += 2
  																else:
  																			new_word.append(word[i]      )
  																			i += 1
  													__lowerCamelCase     :   Any        =			tuple(A_      )
  													__lowerCamelCase     :   Dict        =			new_word
  													if len(A_      ) == 1:
  																break
  													else:
  																__lowerCamelCase     :   int        =			get_pairs(A_      )
  										__lowerCamelCase     :   str        =			""" """.join(A_      )
  										if word == "\n  </w>":
  													__lowerCamelCase     :   Dict        =			"""\n</w>"""
  										__lowerCamelCase     :   Tuple        =			word
  										return word
  
  
  
  
  							def      __a      (    self:						Any    ,       A_:						Any      ):
  										__lowerCamelCase     :   List[Any]        =			[]
  										if self.fix_text is None:
  													# Using BERT's BasicTokenizer
  													__lowerCamelCase     :   Any        =			self.nlp.tokenize(A_      )
  													for token in text:
  																split_tokens.extend(list(self.bpe(A_      ).split(""" """      )      )      )
  										else:
  													# Using SpaCy & ftfy (original tokenization process of OpenAI GPT)
  													__lowerCamelCase     :   Optional[Any]        =			self.nlp(text_standardize(self.fix_text(A_      )      )      )
  													for token in text:
  																split_tokens.extend(list(self.bpe(token.text.lower()      ).split(""" """      )      )      )
  										return split_tokens
  
  
  
  
  							def      __a      (    self:						List[Any]    ,       A_:						List[str]      ):
  										return self.encoder.get(A_    ,       self.encoder.get(self.unk_token      )      )
  
  
  
  
  							def      __a      (    self:						Dict    ,       A_:						Union[str, Any]      ):
  										return self.decoder.get(A_    ,       self.unk_token      )
  
  
  
  
  							def      __a      (    self:						List[Any]    ,       A_:						Any      ):
  										__lowerCamelCase     :   Dict        =			"""""".join(A_      ).replace("""</w>"""    ,       """ """      ).strip()
  										return out_string
  
  
  
  
  							def      __a      (    self:						Union[str, Any]    ,       A_:						str    ,       A_:						Optional[str] = None      ):
  										if not os.path.isdir(A_      ):
  													logger.error(f'Vocabulary path ({save_directory}) should be a directory'      )
  													return
  										__lowerCamelCase     :   Tuple        =			os.path.join(
  										    A_    ,       (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]      )
  										__lowerCamelCase     :   List[Any]        =			os.path.join(
  										    A_    ,       (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""merges_file"""]      )
  
  										with open(A_    ,       """w"""    ,       encoding="""utf-8"""      ) as f:
  													f.write(json.dumps(self.encoder    ,       indent=2    ,       sort_keys=A_    ,       ensure_ascii=A_      ) + """\n"""      )
  
  										__lowerCamelCase     :   Optional[Any]        =			0
  										with open(A_    ,       """w"""    ,       encoding="""utf-8"""      ) as writer:
  													writer.write("""#version: 0.2\n"""      )
  													for bpe_tokens, token_index in sorted(self.bpe_ranks.items()    ,       key=lambda A_      : kv[1]      ):
  																if index != token_index:
  																			logger.warning(
  																			    f'Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.'
  																			    """ Please check that the tokenizer is not corrupted!"""      )
  																			__lowerCamelCase     :   Optional[Any]        =			token_index
  																writer.write(""" """.join(A_      ) + """\n"""      )
  																index += 1
  
  										return vocab_file, merge_file
  
  
  
  
  
style_context: 
  
  
  """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:						str    ,       A_:						str    ,       A_:						int=13    ,       A_:						Any=32    ,       A_:						int=1    ,       A_:						Dict=3    ,       A_:						Union[str, Any]=16    ,       A_:						List[str]=[1, 2, 1]    ,       A_:						Dict=[2, 2, 4]    ,       A_:						List[Any]=2    ,       A_:						List[Any]=2.0    ,       A_:						str=True    ,       A_:						Dict=0.0    ,       A_:						Optional[Any]=0.0    ,       A_:						Tuple=0.1    ,       A_:						str="gelu"    ,       A_:						Optional[Any]=False    ,       A_:						Dict=True    ,       A_:						Tuple=0.02    ,       A_:						List[Any]=1E-5    ,       A_:						Dict=True    ,       A_:						Any=None    ,       A_:						Optional[Any]=False    ,       A_:						Optional[int]=2    ,       ):
  										__lowerCamelCase        =			parent
  										__lowerCamelCase        =			batch_size
  										__lowerCamelCase        =			image_size
  										__lowerCamelCase        =			patch_size
  										__lowerCamelCase        =			num_channels
  										__lowerCamelCase        =			embed_dim
  										__lowerCamelCase        =			depths
  										__lowerCamelCase        =			num_heads
  										__lowerCamelCase        =			window_size
  										__lowerCamelCase        =			mlp_ratio
  										__lowerCamelCase        =			qkv_bias
  										__lowerCamelCase        =			hidden_dropout_prob
  										__lowerCamelCase        =			attention_probs_dropout_prob
  										__lowerCamelCase        =			drop_path_rate
  										__lowerCamelCase        =			hidden_act
  										__lowerCamelCase        =			use_absolute_embeddings
  										__lowerCamelCase        =			patch_norm
  										__lowerCamelCase        =			layer_norm_eps
  										__lowerCamelCase        =			initializer_range
  										__lowerCamelCase        =			is_training
  										__lowerCamelCase        =			scope
  										__lowerCamelCase        =			use_labels
  										__lowerCamelCase        =			upscale
  
  										# here we set some attributes to make tests pass
  										__lowerCamelCase        =			len(A_      )
  										__lowerCamelCase        =			embed_dim
  										__lowerCamelCase        =			(image_size // patch_size) ** 2
  
  
  
  
  							def      __a      (    self:						Tuple      ):
  										__lowerCamelCase        =			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )
  
  										__lowerCamelCase        =			None
  										if self.use_labels:
  													__lowerCamelCase        =			ids_tensor([self.batch_size]    ,       self.type_sequence_label_size      )
  
  										__lowerCamelCase        =			self.get_config()
  
  										return config, pixel_values, labels
  
  
  
  
  							def      __a      (    self:						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      __a      (    self:						str    ,       A_:						str    ,       A_:						Optional[int]    ,       A_:						List[str]      ):
  										__lowerCamelCase        =			SwinaSRModel(config=A_      )
  										model.to(A_      )
  										model.eval()
  										__lowerCamelCase        =			model(A_      )
  
  										self.parent.assertEqual(
  										    result.last_hidden_state.shape    ,       (self.batch_size, self.embed_dim, self.image_size, self.image_size)      )
  
  
  
  
  							def      __a      (    self:						Any    ,       A_:						Tuple    ,       A_:						Any    ,       A_:						Dict      ):
  										__lowerCamelCase        =			SwinaSRForImageSuperResolution(A_      )
  										model.to(A_      )
  										model.eval()
  										__lowerCamelCase        =			model(A_      )
  
  										__lowerCamelCase        =			self.image_size * self.upscale
  										self.parent.assertEqual(
  										    result.reconstruction.shape    ,       (self.batch_size, self.num_channels, expected_image_size, expected_image_size)      )
  
  
  
  
  							def      __a      (    self:						Tuple      ):
  										__lowerCamelCase        =			self.prepare_config_and_inputs()
  										__lowerCamelCase    ,__lowerCamelCase    ,__lowerCamelCase        =			config_and_inputs
  										__lowerCamelCase        =			{"""pixel_values""": pixel_values}
  										return config, inputs_dict
  
  
  
  
  @require_torch
  class  __snake_case      (lowerCamelCase ,		lowerCamelCase ,		unittest.TestCase     ):
  							__a				   =					(SwinaSRModel, SwinaSRForImageSuperResolution) if is_torch_available() else ()
  							__a				   =					{'''feature-extraction''': SwinaSRModel} if is_torch_available() else {}
  
  							__a				   =					False
  							__a				   =					False
  							__a				   =					False
  							__a				   =					False
  							__a				   =					False
  
  
  
  
  							def      __a      (    self:						List[str]      ):
  										__lowerCamelCase        =			SwinaSRModelTester(self      )
  										__lowerCamelCase        =			ConfigTester(self    ,       config_class=A_    ,       embed_dim=37      )
  
  
  
  
  							def      __a      (    self:						Optional[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      __a      (    self:						Tuple      ):
  										__lowerCamelCase        =			self.model_tester.prepare_config_and_inputs()
  										self.model_tester.create_and_check_model(*A_      )
  
  
  
  
  							def      __a      (    self:						Any      ):
  										__lowerCamelCase        =			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      __a      (    self:						Union[str, Any]      ):
  										pass
  
  
  
  
  							@unittest.skip(reason="""Swin2SR does not use inputs_embeds"""      )
  							def      __a      (    self:						str      ):
  										pass
  
  
  
  
  							@unittest.skip(reason="""Swin2SR does not support training yet"""      )
  							def      __a      (    self:						int      ):
  										pass
  
  
  
  
  							@unittest.skip(reason="""Swin2SR does not support training yet"""      )
  							def      __a      (    self:						Optional[int]      ):
  										pass
  
  
  
  
  							def      __a      (    self:						List[Any]      ):
  										__lowerCamelCase    ,__lowerCamelCase        =			self.model_tester.prepare_config_and_inputs_for_common()
  
  										for model_class in self.all_model_classes:
  													__lowerCamelCase        =			model_class(A_      )
  													self.assertIsInstance(model.get_input_embeddings()    ,       (nn.Module)      )
  													__lowerCamelCase        =			model.get_output_embeddings()
  													self.assertTrue(x is None or isinstance(A_    ,       nn.Linear      )      )
  
  
  
  
  							def      __a      (    self:						Optional[Any]      ):
  										__lowerCamelCase    ,__lowerCamelCase        =			self.model_tester.prepare_config_and_inputs_for_common()
  
  										for model_class in self.all_model_classes:
  													__lowerCamelCase        =			model_class(A_      )
  													__lowerCamelCase        =			inspect.signature(model.forward      )
  													# signature.parameters is an OrderedDict => so arg_names order is deterministic
  													__lowerCamelCase        =			[*signature.parameters.keys()]
  
  													__lowerCamelCase        =			["""pixel_values"""]
  													self.assertListEqual(arg_names[:1]    ,       A_      )
  
  
  
  
  							@slow
  							def      __a      (    self:						List[Any]      ):
  										for model_name in SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
  													__lowerCamelCase        =			SwinaSRModel.from_pretrained(A_      )
  													self.assertIsNotNone(A_      )
  
  
  
  
  							def      __a      (    self:						Optional[int]      ):
  										__lowerCamelCase    ,__lowerCamelCase        =			self.model_tester.prepare_config_and_inputs_for_common()
  
  										__lowerCamelCase        =			_config_zero_init(A_      )
  										for model_class in self.all_model_classes:
  													__lowerCamelCase        =			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      __a      (    self:						Any      ):
  										__lowerCamelCase    ,__lowerCamelCase        =			self.model_tester.prepare_config_and_inputs_for_common()
  										__lowerCamelCase        =			True
  
  										for model_class in self.all_model_classes:
  													__lowerCamelCase        =			True
  													__lowerCamelCase        =			False
  													__lowerCamelCase        =			True
  													__lowerCamelCase        =			model_class(A_      )
  													model.to(A_      )
  													model.eval()
  													with torch.no_grad():
  																__lowerCamelCase        =			model(**self._prepare_for_class(A_    ,       A_      )      )
  													__lowerCamelCase        =			outputs.attentions
  													__lowerCamelCase        =			len(self.model_tester.depths      )
  													self.assertEqual(len(A_      )    ,       A_      )
  
  													# check that output_attentions also work using config
  													del inputs_dict["output_attentions"]
  													__lowerCamelCase        =			True
  													__lowerCamelCase        =			config.window_size**2
  													__lowerCamelCase        =			model_class(A_      )
  													model.to(A_      )
  													model.eval()
  													with torch.no_grad():
  																__lowerCamelCase        =			model(**self._prepare_for_class(A_    ,       A_      )      )
  													__lowerCamelCase        =			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]    ,       )
  													__lowerCamelCase        =			len(A_      )
  
  													# Check attention is always last and order is fine
  													__lowerCamelCase        =			True
  													__lowerCamelCase        =			True
  													__lowerCamelCase        =			model_class(A_      )
  													model.to(A_      )
  													model.eval()
  													with torch.no_grad():
  																__lowerCamelCase        =			model(**self._prepare_for_class(A_    ,       A_      )      )
  
  													self.assertEqual(out_len + 1    ,       len(A_      )      )
  
  													__lowerCamelCase        =			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      __a      (    self:						List[Any]      ):
  										__lowerCamelCase        =			SwinaSRImageProcessor()
  										__lowerCamelCase        =			SwinaSRForImageSuperResolution.from_pretrained("""caidas/swin2SR-classical-sr-x2-64"""      ).to(A_      )
  
  										__lowerCamelCase        =			Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""      )
  										__lowerCamelCase        =			processor(images=A_    ,       return_tensors="""pt"""      ).to(A_      )
  
  										# forward pass
  										with torch.no_grad():
  													__lowerCamelCase        =			model(**A_      )
  
  										# verify the logits
  										__lowerCamelCase        =			torch.Size([1, 3, 9_76, 12_96]      )
  										self.assertEqual(outputs.reconstruction.shape    ,       A_      )
  										__lowerCamelCase        =			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(A_      )
  										self.assertTrue(torch.allclose(outputs.reconstruction[0, 0, :3, :3]    ,       A_    ,       atol=1E-4      )      )
  
  
  
  
  