




'''simple docstring'''





import os
from shutil import copyfile
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


if TYPE_CHECKING:
  from transformers.pipelines.conversational import Conversation

a		:	str       =      logging.get_logger(__name__)

a		:	int       =      {'''vocab_file''': '''tokenizer.model'''}

a		:	Optional[Any]       =      {
    '''vocab_file''': {
        '''hf-internal-testing/llama-tokenizer''': '''https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer.model''',
    },
    '''tokenizer_file''': {
        '''hf-internal-testing/llama-tokenizer''': '''https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer_config.json''',
    },
}
a		:	Optional[int]       =      {
    '''hf-internal-testing/llama-tokenizer''': 2_0_4_8,
}
a		:	Optional[Any]       =      '''▁'''

a      ,				a		:	Optional[Any]       =      '''[INST]''', '''[/INST]'''
a      ,				a		:	Optional[Any]       =      '''<<SYS>>\n''', '''\n<</SYS>>\n\n'''

# fmt: off
a		:	int       =      '''You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your\
answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\
that your responses are socially unbiased and positive in nature.

If a question does not make any sense, or is not factually coherent, explain why instead of answering something not\
correct. If you don\'t know the answer to a question, please don\'t share false information.'''




class      UpperCamelCase       (	snake_case__       ):
  a     :Dict          =					VOCAB_FILES_NAMES
  a     :Any          =					PRETRAINED_VOCAB_FILES_MAP
  a     :Optional[int]          =					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  a     :Optional[Any]          =					['input_ids', 'attention_mask']



  def __init__(			self		,     __lowerCAmelCase		,     __lowerCAmelCase="<unk>"		,     __lowerCAmelCase="<s>"		,     __lowerCAmelCase="</s>"		,     __lowerCAmelCase=None		,     __lowerCAmelCase = None		,     __lowerCAmelCase=True		,     __lowerCAmelCase=False		,     __lowerCAmelCase=False		,     __lowerCAmelCase=True		,     **__lowerCAmelCase		,     ):







      '''simple docstring'''


      _a				:							Dict							       =      {} if sp_model_kwargs is None else sp_model_kwargs
      _a				:							Any							       =      AddedToken(__lowerCAmelCase		,     lstrip=__lowerCAmelCase		,     rstrip=__lowerCAmelCase ) if isinstance(__lowerCAmelCase		,     __lowerCAmelCase ) else bos_token
      _a				:							Optional[Any]							       =      AddedToken(__lowerCAmelCase		,     lstrip=__lowerCAmelCase		,     rstrip=__lowerCAmelCase ) if isinstance(__lowerCAmelCase		,     __lowerCAmelCase ) else eos_token
      _a				:							Dict							       =      AddedToken(__lowerCAmelCase		,     lstrip=__lowerCAmelCase		,     rstrip=__lowerCAmelCase ) if isinstance(__lowerCAmelCase		,     __lowerCAmelCase ) else unk_token
      _a				:							Union[str, Any]							       =      AddedToken(__lowerCAmelCase		,     lstrip=__lowerCAmelCase		,     rstrip=__lowerCAmelCase ) if isinstance(__lowerCAmelCase		,     __lowerCAmelCase ) else pad_token
      super().__init__(
          bos_token=__lowerCAmelCase		,     eos_token=__lowerCAmelCase		,     unk_token=__lowerCAmelCase		,     pad_token=__lowerCAmelCase		,     add_bos_token=__lowerCAmelCase		,     add_eos_token=__lowerCAmelCase		,     sp_model_kwargs=self.sp_model_kwargs		,     clean_up_tokenization_spaces=__lowerCAmelCase		,     legacy=__lowerCAmelCase		,     **__lowerCAmelCase		,     )
      if legacy:
          logger.warning_once(
              f'''You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to'''
              """ read the related pull request available at https://github.com/huggingface/transformers/pull/24565""" )
      _a				:							Optional[Any]							       =      legacy
      _a				:							Dict							       =      vocab_file
      _a				:							Optional[Any]							       =      add_bos_token
      _a				:							int							       =      add_eos_token
      _a				:							Optional[int]							       =      spm.SentencePieceProcessor(**self.sp_model_kwargs )
      self.sp_model.Load(__lowerCAmelCase )



  def __getstate__(			self ):







      '''simple docstring'''


      _a				:							Any							       =      self.__dict__.copy()
      _a				:							Tuple							       =      None
      _a				:							Any							       =      self.sp_model.serialized_model_proto()
      return state



  def __setstate__(			self		,     __lowerCAmelCase ):







      '''simple docstring'''


      _a				:							List[str]							       =      d
      _a				:							int							       =      spm.SentencePieceProcessor(**self.sp_model_kwargs )
      self.sp_model.LoadFromSerializedProto(self.sp_model_proto )



  @property
  def     a_							(			self ):







      '''simple docstring'''


      return self.sp_model.get_piece_size()



  def     a_							(			self ):







      '''simple docstring'''


      _a				:							Tuple							       =      {self.convert_ids_to_tokens(__lowerCAmelCase ): i for i in range(self.vocab_size )}
      vocab.update(self.added_tokens_encoder )
      return vocab



  def     a_							(			self		,     __lowerCAmelCase		,     **__lowerCAmelCase ):







      '''simple docstring'''


      if not self.legacy:
          _a				:							Optional[Any]							       =      SPIECE_UNDERLINE + text.replace(__lowerCAmelCase		,     """ """ )
      return super().tokenize(__lowerCAmelCase		,     **__lowerCAmelCase )



  def     a_							(			self		,     __lowerCAmelCase ):







      '''simple docstring'''


      if not self.legacy:
          _a				:							str							       =      text.startswith(__lowerCAmelCase )
          if is_first:
              _a				:							Optional[Any]							       =      text[1:]

      _a				:							List[Any]							       =      self.sp_model.encode(__lowerCAmelCase		,     out_type=__lowerCAmelCase )

      if not self.legacy and not is_first and not text.startswith(""" """ ) and tokens[0].startswith(__lowerCAmelCase ):
          _a				:							Union[str, Any]							       =      ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:]
      return tokens



  def     a_							(			self		,     __lowerCAmelCase ):







      '''simple docstring'''


      return self.sp_model.piece_to_id(__lowerCAmelCase )



  def     a_							(			self		,     __lowerCAmelCase ):







      '''simple docstring'''


      _a				:							Any							       =      self.sp_model.IdToPiece(__lowerCAmelCase )
      return token



  def     a_							(			self		,     __lowerCAmelCase ):







      '''simple docstring'''


      _a				:							List[str]							       =      []
      _a				:							Any							       =      """"""
      _a				:							str							       =      False
      for i, token in enumerate(__lowerCAmelCase ):
          # make sure that special tokens are not decoded using sentencepiece model
          if token in self.all_special_tokens:
              if not prev_is_special and i != 0:
                  out_string += " "
              out_string += self.sp_model.decode(__lowerCAmelCase ) + token
              _a				:							List[str]							       =      True
              _a				:							str							       =      []
          else:
              current_sub_tokens.append(__lowerCAmelCase )
              _a				:							Union[str, Any]							       =      False
      out_string += self.sp_model.decode(__lowerCAmelCase )
      return out_string



  def     a_							(			self		,     __lowerCAmelCase		,     __lowerCAmelCase = None ):







      '''simple docstring'''


      if not os.path.isdir(__lowerCAmelCase ):
          logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' )
          return
      _a				:							Optional[int]							       =      os.path.join(
          __lowerCAmelCase		,     (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] )

      if os.path.abspath(self.vocab_file ) != os.path.abspath(__lowerCAmelCase ) and os.path.isfile(self.vocab_file ):
          copyfile(self.vocab_file		,     __lowerCAmelCase )
      elif not os.path.isfile(self.vocab_file ):
          with open(__lowerCAmelCase		,     """wb""" ) as fi:
              _a				:							Dict							       =      self.sp_model.serialized_model_proto()
              fi.write(__lowerCAmelCase )

      return (out_vocab_file,)



  def     a_							(			self		,     __lowerCAmelCase		,     __lowerCAmelCase=None ):







      '''simple docstring'''


      _a				:							List[Any]							       =      [self.bos_token_id] if self.add_bos_token else []
      _a				:							int							       =      [self.eos_token_id] if self.add_eos_token else []

      _a				:							Tuple							       =      bos_token_id + token_ids_a + eos_token_id

      if token_ids_a is not None:
          _a				:							Optional[int]							       =      output + bos_token_id + token_ids_a + eos_token_id

      return output



  def     a_							(			self		,     __lowerCAmelCase		,     __lowerCAmelCase = None		,     __lowerCAmelCase = False ):







      '''simple docstring'''


      if already_has_special_tokens:
          return super().get_special_tokens_mask(
              token_ids_a=__lowerCAmelCase		,     token_ids_a=__lowerCAmelCase		,     already_has_special_tokens=__lowerCAmelCase )

      _a				:							Any							       =      [1] if self.add_bos_token else []
      _a				:							Dict							       =      [1] if self.add_eos_token else []

      if token_ids_a is None:
          return bos_token_id + ([0] * len(__lowerCAmelCase )) + eos_token_id
      return (
          bos_token_id
          + ([0] * len(__lowerCAmelCase ))
          + eos_token_id
          + bos_token_id
          + ([0] * len(__lowerCAmelCase ))
          + eos_token_id
      )



  def     a_							(			self		,     __lowerCAmelCase		,     __lowerCAmelCase = None ):







      '''simple docstring'''


      _a				:							Any							       =      [self.bos_token_id] if self.add_bos_token else []
      _a				:							Optional[Any]							       =      [self.eos_token_id] if self.add_eos_token else []

      _a				:							Optional[Any]							       =      [0] * len(bos_token_id + token_ids_a + eos_token_id )

      if token_ids_a is not None:
          output += [1] * len(bos_token_id + token_ids_a + eos_token_id )

      return output



  def     a_							(			self		,     __lowerCAmelCase ):







      '''simple docstring'''


      _a				:							Union[str, Any]							       =      list(conversation.iter_texts() )
      if not all([is_user for is_user, msg in dialogue[::2]] ) or not all(
          [not is_user for is_user, msg in dialogue[1::2]] ):
          raise ValueError(
              """The model only supports 'user' and 'assistant' roles, starting with user and alternating (u/a/u/a/u...)""" )

      _a				:							List[int]							       =      []
      if len(conversation.past_user_inputs ) > 0:
          if not conversation.past_user_inputs[0].startswith(__lowerCAmelCase ) or E_SYS not in conversation.past_user_inputs[0]:
              _a				:							Optional[int]							       =      (
                  B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + conversation.past_user_inputs[0]
              )
      elif not dialogue[0][1].startswith(__lowerCAmelCase ) or E_SYS not in dialogue[0][1]:
          _a				:							str							       =      (dialogue[0][0], B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + dialogue[0][1])

      dialog_tokens += sum(
          [
              [self.bos_token_id]
              + self.encode(
                  f'''{B_INST} {(prompt[1]).strip()} {E_INST} {(answer[1]).strip()} '''		,     add_special_tokens=__lowerCAmelCase )
              + [self.eos_token_id]
              for prompt, answer in zip(dialogue[::2]		,     dialogue[1::2] )
          ]		,     []		,     )
      if not (dialogue[-1][0]):
          raise ValueError(f'''Last message must be from user, got {dialogue[-1]['role']}''' )
      dialog_tokens += [self.bos_token_id] + self.encode(
          f'''{B_INST} {(dialogue[-1][1]).strip()} {E_INST}'''		,     add_special_tokens=__lowerCAmelCase )
      return dialog_tokens








'''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      UpperCamelCase       :



  def __init__(			self		,     __lowerCAmelCase		,     __lowerCAmelCase=13		,     __lowerCAmelCase=32		,     __lowerCAmelCase=1		,     __lowerCAmelCase=3		,     __lowerCAmelCase=16		,     __lowerCAmelCase=[1, 2, 1]		,     __lowerCAmelCase=[2, 2, 4]		,     __lowerCAmelCase=2		,     __lowerCAmelCase=2.0		,     __lowerCAmelCase=True		,     __lowerCAmelCase=0.0		,     __lowerCAmelCase=0.0		,     __lowerCAmelCase=0.1		,     __lowerCAmelCase="gelu"		,     __lowerCAmelCase=False		,     __lowerCAmelCase=True		,     __lowerCAmelCase=0.02		,     __lowerCAmelCase=1e-5		,     __lowerCAmelCase=True		,     __lowerCAmelCase=None		,     __lowerCAmelCase=False		,     __lowerCAmelCase=2		,     ):







      '''simple docstring'''


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

      # here we set some attributes to make tests pass
      _a				:							List[str]							       =      len(__lowerCAmelCase )
      _a				:							str							       =      embed_dim
      _a				:							Optional[int]							       =      (image_size // patch_size) ** 2



  def     a_							(			self ):







      '''simple docstring'''


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

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

      _a				:							str							       =      self.get_config()

      return config, pixel_values, labels



  def     a_							(			self ):







      '''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     a_							(			self		,     __lowerCAmelCase		,     __lowerCAmelCase		,     __lowerCAmelCase ):







      '''simple docstring'''


      _a				:							Union[str, Any]							       =      SwinaSRModel(config=__lowerCAmelCase )
      model.to(__lowerCAmelCase )
      model.eval()
      _a				:							List[str]							       =      model(__lowerCAmelCase )

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



  def     a_							(			self		,     __lowerCAmelCase		,     __lowerCAmelCase		,     __lowerCAmelCase ):







      '''simple docstring'''


      _a				:							Dict							       =      SwinaSRForImageSuperResolution(__lowerCAmelCase )
      model.to(__lowerCAmelCase )
      model.eval()
      _a				:							Tuple							       =      model(__lowerCAmelCase )

      _a				:							Dict							       =      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 ):







      '''simple docstring'''


      _a				:							List[Any]							       =      self.prepare_config_and_inputs()
      _a       , _a       , _a				:							int							       =      config_and_inputs
      _a				:							Optional[int]							       =      {"""pixel_values""": pixel_values}
      return config, inputs_dict






@require_torch
class      UpperCamelCase       (	snake_case__      ,		snake_case__      ,		unittest.TestCase       ):
  a     :Dict          =					(SwinaSRModel, SwinaSRForImageSuperResolution) if is_torch_available() else ()
  a     :List[str]          =					{'feature-extraction': SwinaSRModel} if is_torch_available() else {}

  a     :List[Any]          =					False
  a     :Tuple          =					False
  a     :Any          =					False
  a     :Union[str, Any]          =					False
  a     :Union[str, Any]          =					False



  def     a_							(			self ):







      '''simple docstring'''


      _a				:							Optional[Any]							       =      SwinaSRModelTester(self )
      _a				:							Optional[int]							       =      ConfigTester(self		,     config_class=__lowerCAmelCase		,     embed_dim=37 )



  def     a_							(			self ):







      '''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     a_							(			self ):







      '''simple docstring'''


      _a				:							int							       =      self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*__lowerCAmelCase )



  def     a_							(			self ):







      '''simple docstring'''


      _a				:							Tuple							       =      self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_super_resolution(*__lowerCAmelCase )



  @unittest.skip(reason="""Got `CUDA error: misaligned address` with PyTorch 2.0.0.""" )
  def     a_							(			self ):







      '''simple docstring'''


      pass



  @unittest.skip(reason="""Swin2SR does not use inputs_embeds""" )
  def     a_							(			self ):







      '''simple docstring'''


      pass



  @unittest.skip(reason="""Swin2SR does not support training yet""" )
  def     a_							(			self ):







      '''simple docstring'''


      pass



  @unittest.skip(reason="""Swin2SR does not support training yet""" )
  def     a_							(			self ):







      '''simple docstring'''


      pass



  def     a_							(			self ):







      '''simple docstring'''


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

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



  def     a_							(			self ):







      '''simple docstring'''


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

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

          _a				:							List[Any]							       =      ["""pixel_values"""]
          self.assertListEqual(arg_names[:1]		,     __lowerCAmelCase )



  @slow
  def     a_							(			self ):







      '''simple docstring'''


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



  def     a_							(			self ):







      '''simple docstring'''


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

      _a				:							Union[str, Any]							       =      _config_zero_init(__lowerCAmelCase )
      for model_class in self.all_model_classes:
          _a				:							Any							       =      model_class(config=__lowerCAmelCase )
          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 ):







      '''simple docstring'''


      _a       , _a				:							Dict							       =      self.model_tester.prepare_config_and_inputs_for_common()
      _a				:							List[str]							       =      True

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

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

          self.assertListEqual(
              list(attentions[0].shape[-3:] )		,     [self.model_tester.num_heads[0], window_size_squared, window_size_squared]		,     )
          _a				:							Dict							       =      len(__lowerCAmelCase )

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

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

          _a				:							List[str]							       =      outputs.attentions

          self.assertEqual(len(__lowerCAmelCase )		,     __lowerCAmelCase )

          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      UpperCamelCase       (	unittest.TestCase       ):



  def     a_							(			self ):







      '''simple docstring'''


      _a				:							int							       =      SwinaSRImageProcessor()
      _a				:							Optional[Any]							       =      SwinaSRForImageSuperResolution.from_pretrained("""caidas/swin2SR-classical-sr-x2-64""" ).to(__lowerCAmelCase )

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

      # forward pass
      with torch.no_grad():
          _a				:							str							       =      model(**__lowerCAmelCase )

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


