



'''simple docstring'''






import copy
import fnmatch
import json
import os
import pickle as pkl
import shutil
import sys
import tarfile
import tempfile
from collections import OrderedDict
from contextlib import contextmanager
from functools import partial
from hashlib import shaaaa
from io import BytesIO
from pathlib import Path
from urllib.parse import urlparse
from zipfile import ZipFile, is_zipfile

import cva
import numpy as np
import requests
import wget
from filelock import FileLock
from PIL import Image
from tqdm.auto import tqdm
from yaml import Loader, dump, load


try:
     import torch

     lowerCAmelCase:					Optional[int]						       =						True
except ImportError:
     lowerCAmelCase:					int						       =						False


try:
     from torch.hub import _get_torch_home

     lowerCAmelCase:					List[Any]						       =						_get_torch_home()
except ImportError:
     lowerCAmelCase:					Optional[int]						       =						os.path.expanduser(
         os.getenv('TORCH_HOME', os.path.join(os.getenv('XDG_CACHE_HOME', '~/.cache'), 'torch'))
     )

lowerCAmelCase:					List[str]						       =						os.path.join(torch_cache_home, 'transformers')

lowerCAmelCase:					List[str]						       =						"""https://cdn.huggingface.co"""
lowerCAmelCase:					int						       =						"""https://s3.amazonaws.com/models.huggingface.co/bert"""
lowerCAmelCase:					int						       =						"""/""".join(str(Path(__file__).resolve()).split('/')[:-1])
lowerCAmelCase:					List[Any]						       =						os.path.join(PATH, 'config.yaml')
lowerCAmelCase:					List[str]						       =						os.path.join(PATH, 'attributes.txt')
lowerCAmelCase:					Optional[Any]						       =						os.path.join(PATH, 'objects.txt')
lowerCAmelCase:					Tuple						       =						os.getenv('PYTORCH_PRETRAINED_BERT_CACHE', default_cache_path)
lowerCAmelCase:					int						       =						os.getenv('PYTORCH_TRANSFORMERS_CACHE', PYTORCH_PRETRAINED_BERT_CACHE)
lowerCAmelCase:					Optional[Any]						       =						os.getenv('TRANSFORMERS_CACHE', PYTORCH_TRANSFORMERS_CACHE)
lowerCAmelCase:					Tuple						       =						"""pytorch_model.bin"""
lowerCAmelCase:					int						       =						"""config.yaml"""
def       lowerCamelCase__       (						_A=OBJECTS ,			_A=ATTRIBUTES				):
  a						:					Dict        =     []
  with open(A__				) as f:
    for object in f.readlines():
      vg_classes.append(object.split(','				)[0].lower().strip()				)

  a						:					Optional[int]        =     []
  with open(A__				) as f:
    for object in f.readlines():
      vg_attrs.append(object.split(','				)[0].lower().strip()				)
  return vg_classes, vg_attrs
def       lowerCamelCase__       (						_A				):
  a						:					Optional[Any]        =     OrderedDict()
  with open(A__ ,			'rb'				) as f:
    a						:					List[str]        =     pkl.load(A__				)['model']
  for k in copy.deepcopy(list(ckp.keys()				)				):
    a						:					Tuple        =     ckp.pop(A__				)
    if isinstance(A__ ,			np.ndarray				):
      a						:					str        =     torch.tensor(A__				)
    else:
      assert isinstance(A__ ,			torch.tensor				), type(A__				)
    a						:					Optional[int]        =     v
  return r

class 							a__:
    lowercase__ =    {}







    def __init__(      self :  List[Any]						,			__snake_case :  str						,			__snake_case :  List[Any] = "root"						,			__snake_case :  Dict=0	):
      a						:					List[str]        =     name
      a						:					Optional[Any]        =     level
      a						:					Tuple        =     {}
      for k, v in dictionary.items():
        if v is None:
          raise ValueError()
        a						:					Dict        =     copy.deepcopy(__snake_case	)
        a						:					Any        =     copy.deepcopy(__snake_case	)
        if isinstance(__snake_case						,			__snake_case	):
          a						:					Tuple        =     Config(__snake_case						,			name=__snake_case						,			level=level + 1	)
        a						:					Dict        =     v
        setattr(self						,			__snake_case						,			__snake_case	)

      a						:					List[Any]        =     d







    def __repr__(      self :  Optional[int]	):
      return str(list((self._pointer.keys())	)	)







    def __setattr__(      self :  Union[str, Any]						,			__snake_case :  List[str]						,			__snake_case :  int	):
      a						:					str        =     val
      a						:					Tuple        =     val
      a						:					int        =     key.split('.'	)
      a						:					Tuple        =     len(__snake_case	) - 1
      a						:					int        =     self._pointer
      if len(__snake_case	) > 1:
        for i, l in enumerate(__snake_case	):
          if hasattr(self						,			__snake_case	) and isinstance(getattr(self						,			__snake_case	)						,			__snake_case	):
            setattr(getattr(self						,			__snake_case	)						,			'.'.join(levels[i:]	)						,			__snake_case	)
          if l == last_level:
            a						:					List[str]        =     val
          else:
            a						:					Tuple        =     pointer[l]







    def 			lowercase_       (      self :  Union[str, Any]	):
      return self._pointer







    def 			lowercase_       (      self :  Optional[int]						,			__snake_case :  Any						,			__snake_case :  str	):

      with open(F"""{file_name}"""						,			'w'	) as stream:
        dump(__snake_case						,			__snake_case	)







    def 			lowercase_       (      self :  str						,			__snake_case :  Any						,			__snake_case :  Dict	):

      with open(F"""{file_name}"""						,			'w'	) as stream:
        json.dump(__snake_case						,			__snake_case	)







    @staticmethod
    def 			lowercase_       (      __snake_case :  str	):

      with open(__snake_case	) as stream:
        a						:					Tuple        =     load(__snake_case						,			Loader=__snake_case	)
      return data







    def __str__(      self :  List[str]	):
      a						:					Optional[int]        =     '    '
      if self._name != "root":
        a						:					Any        =     F"""{t * (self._level-1)}{self._name}:\n"""
      else:
        a						:					Dict        =     ''
      a						:					Tuple        =     self._level
      for i, (k, v) in enumerate(self._pointer.items()	):
        if isinstance(__snake_case						,			__snake_case	):
          r += F"""{t * (self._level)}{v}\n"""
          self._level += 1
        else:
          r += F"""{t * (self._level)}{k}: {v} ({type(__snake_case	).__name__})\n"""
        a						:					Tuple        =     level
      return r[:-1]







    @classmethod
    def 			lowercase_       (      cls :  Dict						,			__snake_case :  Dict						,			**__snake_case :  Optional[int]	):
      a						:					Optional[Any]        =     cls.get_config_dict(__snake_case						,			**__snake_case	)
      return cls(__snake_case	)







    @classmethod
    def 			lowercase_       (      cls :  Dict						,			__snake_case :  Any						,			**__snake_case :  List[str]	):
      a						:					Union[str, Any]        =     kwargs.pop('cache_dir'						,			__snake_case	)
      a						:					Tuple        =     kwargs.pop('force_download'						,			__snake_case	)
      a						:					str        =     kwargs.pop('resume_download'						,			__snake_case	)
      a						:					Tuple        =     kwargs.pop('proxies'						,			__snake_case	)
      a						:					List[str]        =     kwargs.pop('local_files_only'						,			__snake_case	)

      if os.path.isdir(__snake_case	):
        a						:					int        =     os.path.join(__snake_case						,			__snake_case	)
      elif os.path.isfile(__snake_case	) or is_remote_url(__snake_case	):
        a						:					Union[str, Any]        =     pretrained_model_name_or_path
      else:
        a						:					Tuple        =     hf_bucket_url(__snake_case						,			filename=__snake_case						,			use_cdn=__snake_case	)

      try:
        # Load from URL or cache if already cached
        a						:					Optional[Any]        =     cached_path(
            __snake_case						,			cache_dir=__snake_case						,			force_download=__snake_case						,			proxies=__snake_case						,			resume_download=__snake_case						,			local_files_only=__snake_case						,			)
        # Load config dict
        if resolved_config_file is None:
          raise EnvironmentError

        a						:					Optional[int]        =     Config.load_yaml(__snake_case	)

      except EnvironmentError:
        a						:					List[str]        =     'Can\'t load config for'
        raise EnvironmentError(__snake_case	)

      if resolved_config_file == config_file:
        print('loading configuration file from path'	)
      else:
        print('loading configuration file cache'	)

      return Config.load_yaml(__snake_case	), kwargs
def       lowerCamelCase__       (						_A				):
  a						:					str        =     torch.load('dump.pt' ,			map_location=in_tensor.device				)
  a						:					Optional[Any]        =     in_tensor.numpy()
  a						:					List[Any]        =     out_tensor.numpy()[0]
  print(na.shape ,			na[0, 0, :5]				)
  print(na.shape ,			na[0, 0, :5]				)
  assert np.allclose(A__ ,			A__ ,			rtol=0.01 ,			atol=0.1				), (
      f"""{sum([1 for x in np.isclose(A__ ,			A__ ,			rtol=0.01 ,			atol=0.1				).flatten() if x is False]				)/len(na.flatten()				)*100:.4f} %"""
      " element-wise mismatch"
  )
  raise Exception('tensors are all good'				)

  # Hugging face functions below
def       lowerCamelCase__       (						_A				):
  a						:					Dict        =     urlparse(A__				)
  return parsed.scheme in ("http", "https")
def       lowerCamelCase__       (						_A ,			_A ,			_A=True				):
  a						:					int        =     CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
  a						:					Any        =     '/' not in model_id
  if legacy_format:
    return f"""{endpoint}/{model_id}-{filename}"""
  else:
    return f"""{endpoint}/{model_id}/{filename}"""
def       lowerCamelCase__       (						_A ,			_A ,			_A=None ,			_A=0 ,			_A=None ,			):
  a						:					int        =     'python/{}'.format(sys.version.split()[0]				)
  if _torch_available:
    ua += "; torch/{}".format(torch.__version__				)
  if isinstance(A__ ,			A__				):
    ua += "; " + "; ".join('{}/{}'.format(A__ ,			A__				) for k, v in user_agent.items()				)
  elif isinstance(A__ ,			A__				):
    ua += "; " + user_agent
  a						:					Dict        =     {'user-agent': ua}
  if resume_size > 0:
    a						:					Optional[Any]        =     'bytes=%d-' % (resume_size,)
  a						:					Any        =     requests.get(A__ ,			stream=A__ ,			proxies=A__ ,			headers=A__				)
  if response.status_code == 416:  # Range not satisfiable
    return
  a						:					List[Any]        =     response.headers.get('Content-Length'				)
  a						:					Optional[Any]        =     resume_size + int(A__				) if content_length is not None else None
  a						:					Any        =     tqdm(
      unit='B' ,			unit_scale=A__ ,			total=A__ ,			initial=A__ ,			desc='Downloading' ,			)
  for chunk in response.iter_content(chunk_size=1024				):
    if chunk:  # filter out keep-alive new chunks
      progress.update(len(A__				)				)
      temp_file.write(A__				)
  progress.close()
def       lowerCamelCase__       (						_A ,			_A=None ,			_A=False ,			_A=None ,			_A=10 ,			_A=False ,			_A=None ,			_A=False ,			):
  if cache_dir is None:
    a						:					str        =     TRANSFORMERS_CACHE
  if isinstance(A__ ,			A__				):
    a						:					Dict        =     str(A__				)

  os.makedirs(A__ ,			exist_ok=A__				)

  a						:					Union[str, Any]        =     None
  if not local_files_only:
    try:
      a						:					Union[str, Any]        =     requests.head(A__ ,			allow_redirects=A__ ,			proxies=A__ ,			timeout=A__				)
      if response.status_code == 200:
        a						:					Union[str, Any]        =     response.headers.get('ETag'				)
    except (EnvironmentError, requests.exceptions.Timeout):
      # etag is already None
      pass

  a						:					Optional[Any]        =     url_to_filename(A__ ,			A__				)

  # get cache path to put the file
  a						:					str        =     os.path.join(A__ ,			A__				)

  # etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible.
  # try to get the last downloaded one
  if etag is None:
    if os.path.exists(A__				):
      return cache_path
    else:
      a						:					List[Any]        =     [
          file
          for file in fnmatch.filter(os.listdir(A__				) ,			filename + '.*'				)
          if not file.endswith('.json'				) and not file.endswith('.lock'				)
      ]
      if len(A__				) > 0:
        return os.path.join(A__ ,			matching_files[-1]				)
      else:
        # If files cannot be found and local_files_only=True,
        # the models might've been found if local_files_only=False
        # Notify the user about that
        if local_files_only:
          raise ValueError(
              'Cannot find the requested files in the cached path and outgoing traffic has been'
              ' disabled. To enable model look-ups and downloads online, set \'local_files_only\''
              ' to False.'				)
        return None

    # From now on, etag is not None.
  if os.path.exists(A__				) and not force_download:
    return cache_path

  # Prevent parallel downloads of the same file with a lock.
  a						:					str        =     cache_path + '.lock'
  with FileLock(A__				):
    # If the download just completed while the lock was activated.
    if os.path.exists(A__				) and not force_download:
      # Even if returning early like here, the lock will be released.
      return cache_path

    if resume_download:
      a						:					Any        =     cache_path + '.incomplete'

      @contextmanager
      def _resumable_file_manager():
        with open(A__ ,			'a+b'				) as f:
          yield f

      a						:					Optional[Any]        =     _resumable_file_manager
      if os.path.exists(A__				):
        a						:					str        =     os.stat(A__				).st_size
      else:
        a						:					str        =     0
    else:
      a						:					List[Any]        =     partial(tempfile.NamedTemporaryFile ,			dir=A__ ,			delete=A__				)
      a						:					Optional[Any]        =     0

    # Download to temporary file, then copy to cache dir once finished.
    # Otherwise you get corrupt cache entries if the download gets interrupted.
    with temp_file_manager() as temp_file:
      print(
          '%s not found in cache or force_download set to True, downloading to %s' ,			A__ ,			temp_file.name ,			)

      http_get(
          A__ ,			A__ ,			proxies=A__ ,			resume_size=A__ ,			user_agent=A__ ,			)

    os.replace(temp_file.name ,			A__				)

    a						:					Dict        =     {'url': url, 'etag': etag}
    a						:					str        =     cache_path + '.json'
    with open(A__ ,			'w'				) as meta_file:
      json.dump(A__ ,			A__				)

  return cache_path
def       lowerCamelCase__       (						_A ,			_A=None				):
  a						:					int        =     url.encode('utf-8'				)
  a						:					str        =     shaaaa(A__				)
  a						:					Union[str, Any]        =     url_hash.hexdigest()

  if etag:
    a						:					Optional[Any]        =     etag.encode('utf-8'				)
    a						:					Tuple        =     shaaaa(A__				)
    filename += "." + etag_hash.hexdigest()

  if url.endswith('.h5'				):
    filename += ".h5"

  return filename
def       lowerCamelCase__       (						_A ,			_A=None ,			_A=False ,			_A=None ,			_A=False ,			_A=None ,			_A=False ,			_A=False ,			_A=False ,			):
  if cache_dir is None:
    a						:					Tuple        =     TRANSFORMERS_CACHE
  if isinstance(A__ ,			A__				):
    a						:					Optional[Any]        =     str(A__				)
  if isinstance(A__ ,			A__				):
    a						:					Optional[int]        =     str(A__				)

  if is_remote_url(A__				):
    # URL, so get it from the cache (downloading if necessary)
    a						:					Any        =     get_from_cache(
        A__ ,			cache_dir=A__ ,			force_download=A__ ,			proxies=A__ ,			resume_download=A__ ,			user_agent=A__ ,			local_files_only=A__ ,			)
  elif os.path.exists(A__				):
    # File, and it exists.
    a						:					Tuple        =     url_or_filename
  elif urlparse(A__				).scheme == "":
    # File, but it doesn't exist.
    raise EnvironmentError('file {} not found'.format(A__				)				)
  else:
    # Something unknown
    raise ValueError('unable to parse {} as a URL or as a local path'.format(A__				)				)

  if extract_compressed_file:
    if not is_zipfile(A__				) and not tarfile.is_tarfile(A__				):
      return output_path

    # Path where we extract compressed archives
    # We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/"
    a						:					List[Any]        =     os.path.split(A__				)
    a						:					Dict        =     output_file.replace('.' ,			'-'				) + '-extracted'
    a						:					Union[str, Any]        =     os.path.join(A__ ,			A__				)

    if os.path.isdir(A__				) and os.listdir(A__				) and not force_extract:
      return output_path_extracted

    # Prevent parallel extractions
    a						:					List[Any]        =     output_path + '.lock'
    with FileLock(A__				):
      shutil.rmtree(A__ ,			ignore_errors=A__				)
      os.makedirs(A__				)
      if is_zipfile(A__				):
        with ZipFile(A__ ,			'r'				) as zip_file:
          zip_file.extractall(A__				)
          zip_file.close()
      elif tarfile.is_tarfile(A__				):
        a						:					List[Any]        =     tarfile.open(A__				)
        tar_file.extractall(A__				)
        tar_file.close()
      else:
        raise EnvironmentError('Archive format of {} could not be identified'.format(A__				)				)

    return output_path_extracted

  return output_path
def       lowerCamelCase__       (						_A ,			_A=","				):
  assert isinstance(A__ ,			A__				)
  if os.path.isfile(A__				):
    with open(A__				) as f:
      a						:					List[Any]        =     eval(f.read()				)
  else:
    a						:					Optional[Any]        =     requests.get(A__				)
    try:
      a						:					str        =     requests.json()
    except Exception:
      a						:					str        =     req.content.decode()
      assert data is not None, "could not connect"
      try:
        a						:					Tuple        =     eval(A__				)
      except Exception:
        a						:					List[Any]        =     data.split('\n'				)
    req.close()
  return data
def       lowerCamelCase__       (						_A				):
  a						:					str        =     requests.get(A__				)
  a						:					str        =     np.array(Image.open(BytesIO(response.content				)				)				)
  return img
def       lowerCamelCase__       (						_A				):
  a						:					List[str]        =     url.split('/'				)[-1]
  if fn not in os.listdir(os.getcwd()				):
    wget.download(A__				)
  with open(A__ ,			'rb'				) as stream:
    a						:					Tuple        =     pkl.load(A__				)
  a						:					Optional[Any]        =     weights.pop('model'				)
  a						:					int        =     {}
  for k, v in model.items():
    a						:					List[str]        =     torch.from_numpy(A__				)
    if "running_var" in k:
      a						:					str        =     torch.tensor([0]				)
      a						:					List[Any]        =     k.replace('running_var' ,			'num_batches_tracked'				)
      a						:					int        =     zero
  return new
def       lowerCamelCase__       (						):
  print(f"""{os.path.abspath(os.path.join(A__ ,			os.pardir				)				)}/demo.ipynb"""				)
def       lowerCamelCase__       (						_A ,			_A="RGB"				):
  assert isinstance(A__ ,			A__				)
  if os.path.isfile(A__				):
    a						:					Any        =     cva.imread(A__				)
  else:
    a						:					Dict        =     get_image_from_url(A__				)
    assert img is not None, f"""could not connect to: {im}"""
  a						:					Dict        =     cva.cvtColor(A__ ,			cva.COLOR_BGR2RGB				)
  if input_format == "RGB":
    a						:					Optional[int]        =     img[:, :, ::-1]
  return img

def       lowerCamelCase__       (						_A ,			_A=1				):
  return (images[i : i + batch] for i in range(0 ,			len(A__				) ,			A__				))






import inspect
import unittest

from transformers import ViTMSNConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
    import torch
    from torch import nn

    from transformers import ViTMSNForImageClassification, ViTMSNModel
    from transformers.models.vit_msn.modeling_vit_msn import VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
    from PIL import Image

    from transformers import ViTImageProcessor





class  A__    :




   """simple docstring"""



   def __init__(					self					,  lowercase					,  lowercase=13					,  lowercase=30					,  lowercase=2					,  lowercase=3					,  lowercase=True					,  lowercase=True					,  lowercase=32					,  lowercase=5					,  lowercase=4					,  lowercase=37					,  lowercase="gelu"					,  lowercase=0.1					,  lowercase=0.1					,  lowercase=10					,  lowercase=0.02					,  lowercase=None					,  )			->						Union[str, Any]:







          '''simple docstring'''

          a__						:	Optional[int] =				parent
          a__						:	List[str] =				batch_size
          a__						:	List[str] =				image_size
          a__						:	Dict =				patch_size
          a__						:	Optional[Any] =				num_channels
          a__						:	List[Any] =				is_training
          a__						:	str =				use_labels
          a__						:	Dict =				hidden_size
          a__						:	Tuple =				num_hidden_layers
          a__						:	Tuple =				num_attention_heads
          a__						:	Union[str, Any] =				intermediate_size
          a__						:	List[str] =				hidden_act
          a__						:	List[str] =				hidden_dropout_prob
          a__						:	Any =				attention_probs_dropout_prob
          a__						:	Dict =				type_sequence_label_size
          a__						:	Tuple =				initializer_range
          a__						:	Optional[int] =				scope

          # in ViT MSN, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
          a__						:	List[str] =				(image_size // patch_size) ** 2
          a__						:	Any =				num_patches + 1

   def 							__lowercase		(					self)			->						int:







          '''simple docstring'''

          a__						:	Tuple =				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

          a__						:	Tuple =				None
          if self.use_labels:
                 a__						:	List[Any] =				ids_tensor([self.batch_size]					,  self.type_sequence_label_size)

          a__						:	List[str] =				self.get_config()

          return config, pixel_values, labels

   def 							__lowercase		(					self)			->						Optional[int]:







          '''simple docstring'''

          return ViTMSNConfig(
              image_size=self.image_size					,  patch_size=self.patch_size					,  num_channels=self.num_channels					,  hidden_size=self.hidden_size					,  num_hidden_layers=self.num_hidden_layers					,  num_attention_heads=self.num_attention_heads					,  intermediate_size=self.intermediate_size					,  hidden_act=self.hidden_act					,  hidden_dropout_prob=self.hidden_dropout_prob					,  attention_probs_dropout_prob=self.attention_probs_dropout_prob					,  initializer_range=self.initializer_range					,  )

   def 							__lowercase		(					self					,  lowercase					,  lowercase					,  lowercase)			->						List[str]:







          '''simple docstring'''

          a__						:	int =				ViTMSNModel(config=lowercase)
          model.to(lowercase)
          model.eval()
          a__						:	int =				model(lowercase)
          self.parent.assertEqual(result.last_hidden_state.shape					,  (self.batch_size, self.seq_length, self.hidden_size))

   def 							__lowercase		(					self					,  lowercase					,  lowercase					,  lowercase)			->						Tuple:







          '''simple docstring'''

          a__						:	Optional[Any] =				self.type_sequence_label_size
          a__						:	List[str] =				ViTMSNForImageClassification(lowercase)
          model.to(lowercase)
          model.eval()
          a__						:	int =				model(lowercase					,  labels=lowercase)
          print('Pixel and labels shape: {pixel_values.shape}, {labels.shape}')
          print('Labels: {labels}')
          self.parent.assertEqual(result.logits.shape					,  (self.batch_size, self.type_sequence_label_size))

          # test greyscale images
          a__						:	List[str] =				1
          a__						:	Optional[int] =				ViTMSNForImageClassification(lowercase)
          model.to(lowercase)
          model.eval()

          a__						:	Dict =				floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
          a__						:	Dict =				model(lowercase)
          self.parent.assertEqual(result.logits.shape					,  (self.batch_size, self.type_sequence_label_size))

   def 							__lowercase		(					self)			->						Tuple:







          '''simple docstring'''

          a__						:	List[Any] =				self.prepare_config_and_inputs()
          a__ ,							a__ ,							a__						:	Optional[Any] =				config_and_inputs
          a__						:	Dict =				{'pixel_values': pixel_values}
          return config, inputs_dict





@require_torch
class  A__    (							__UpperCAmelCase ,  __UpperCAmelCase ,  unittest.TestCase	):




   """simple docstring"""



   __A   :				Any         =  (ViTMSNModel, ViTMSNForImageClassification) if is_torch_available() else ()
   __A   :				Tuple         =  (
       {'''feature-extraction''': ViTMSNModel, '''image-classification''': ViTMSNForImageClassification}
       if is_torch_available()
       else {}
   )

   __A   :				List[str]         =  False
   __A   :				Optional[Any]         =  False
   __A   :				Union[str, Any]         =  False
   __A   :				Any         =  False

   def 							__lowercase		(					self)			->						List[str]:







          '''simple docstring'''

          a__						:	Optional[int] =				ViTMSNModelTester(self)
          a__						:	Union[str, Any] =				ConfigTester(self					,  config_class=lowercase					,  has_text_modality=lowercase					,  hidden_size=37)

   def 							__lowercase		(					self)			->						List[Any]:







          '''simple docstring'''

          self.config_tester.run_common_tests()

   @unittest.skip(reason='ViTMSN does not use inputs_embeds')
   def 							__lowercase		(					self)			->						Any:







          '''simple docstring'''

          pass

   def 							__lowercase		(					self)			->						Tuple:







          '''simple docstring'''

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

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

   def 							__lowercase		(					self)			->						Tuple:







          '''simple docstring'''

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

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

                 a__						:	Optional[Any] =				['pixel_values']
                 self.assertListEqual(arg_names[:1]					,  lowercase)

   def 							__lowercase		(					self)			->						str:







          '''simple docstring'''

          a__						:	List[str] =				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*lowercase)

   def 							__lowercase		(					self)			->						str:







          '''simple docstring'''

          a__						:	Any =				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*lowercase)

   @slow
   def 							__lowercase		(					self)			->						Union[str, Any]:







          '''simple docstring'''

          for model_name in VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 a__						:	Tuple =				ViTMSNModel.from_pretrained(lowercase)
                 self.assertIsNotNone(lowercase)



def A_	(		)  ->		Dict:
       a__						:	List[str] =				Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'				)
       return image





@require_torch
@require_vision
class  A__    (							unittest.TestCase	):




   """simple docstring"""



   @cached_property
   def 							__lowercase		(					self)			->						List[Any]:







          '''simple docstring'''

          return ViTImageProcessor.from_pretrained('facebook/vit-msn-small') if is_vision_available() else None

   @slow
   def 							__lowercase		(					self)			->						List[Any]:







          '''simple docstring'''

          torch.manual_seed(2)
          a__						:	List[str] =				ViTMSNForImageClassification.from_pretrained('facebook/vit-msn-small').to(lowercase)

          a__						:	Any =				self.default_image_processor
          a__						:	List[Any] =				prepare_img()
          a__						:	Optional[Any] =				image_processor(images=lowercase					,  return_tensors='pt').to(lowercase)

          # forward pass
          with torch.no_grad():
                 a__						:	Tuple =				model(**lowercase)

          # verify the logits
          a__						:	Union[str, Any] =				torch.Size((1, 1000))
          self.assertEqual(outputs.logits.shape					,  lowercase)

          a__						:	Any =				torch.tensor([-0.08_03, -0.44_54, -0.23_75]).to(lowercase)

          self.assertTrue(torch.allclose(outputs.logits[0, :3]					,  lowercase					,  atol=1e-4))


