





'''simple docstring'''




from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices


lowercase__       : Union[str, Any]         =       logging.get_logger(__name__)

lowercase__       : Dict         =       {
    '''microsoft/swin-tiny-patch4-window7-224''': (
        '''https://huggingface.co/microsoft/swin-tiny-patch4-window7-224/resolve/main/config.json'''
    ),
    # See all Swin models at https://huggingface.co/models?filter=swin
}


class 					SCREAMING_SNAKE_CASE       (a__   ,						a__				):
     lowerCAmelCase						     =			'''swin'''

     lowerCAmelCase						     =			{
         '''num_attention_heads''': '''num_heads''',
         '''num_hidden_layers''': '''num_layers''',
     }


     def __init__(		self		,      _UpperCAmelCase=224		,      _UpperCAmelCase=4		,      _UpperCAmelCase=3		,      _UpperCAmelCase=96		,      _UpperCAmelCase=[2, 2, 6, 2]		,      _UpperCAmelCase=[3, 6, 12, 24]		,      _UpperCAmelCase=7		,      _UpperCAmelCase=4.0		,      _UpperCAmelCase=True		,      _UpperCAmelCase=0.0		,      _UpperCAmelCase=0.0		,      _UpperCAmelCase=0.1		,      _UpperCAmelCase="gelu"		,      _UpperCAmelCase=False		,      _UpperCAmelCase=0.02		,      _UpperCAmelCase=1e-5		,      _UpperCAmelCase=32		,      _UpperCAmelCase=None		,      _UpperCAmelCase=None		,      **_UpperCAmelCase		,      ):

          '''simple docstring'''






          super().__init__(**_UpperCAmelCase)

          __A		:					str						=			image_size
          __A		:					Dict						=			patch_size
          __A		:					Union[str, Any]						=			num_channels
          __A		:					str						=			embed_dim
          __A		:					List[str]						=			depths
          __A		:					List[Any]						=			len(_UpperCAmelCase)
          __A		:					Optional[int]						=			num_heads
          __A		:					Tuple						=			window_size
          __A		:					Union[str, Any]						=			mlp_ratio
          __A		:					List[str]						=			qkv_bias
          __A		:					Dict						=			hidden_dropout_prob
          __A		:					Dict						=			attention_probs_dropout_prob
          __A		:					Any						=			drop_path_rate
          __A		:					List[str]						=			hidden_act
          __A		:					str						=			use_absolute_embeddings
          __A		:					Union[str, Any]						=			layer_norm_eps
          __A		:					str						=			initializer_range
          __A		:					int						=			encoder_stride
          # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel
          # this indicates the channel dimension after the last stage of the model
          __A		:					Dict						=			int(embed_dim * 2 ** (len(_UpperCAmelCase) - 1))
          __A		:					Any						=			['stem'] + [F'stage{idx}' for idx in range(1		,      len(_UpperCAmelCase) + 1)]
          __A					,__A		:					str						=			get_aligned_output_features_output_indices(
              out_features=_UpperCAmelCase		,      out_indices=_UpperCAmelCase		,      stage_names=self.stage_names)




class 					SCREAMING_SNAKE_CASE       (a__				):
     lowerCAmelCase						     =			version.parse('''1.11'''				)


     @property
     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          return OrderedDict(
              [
                  ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}),
              ])


     @property
     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          return 1e-4






'''simple docstring'''




import json
import os
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from requests.exceptions import HTTPError

from transformers.utils import (
    CONFIG_NAME,
    FLAX_WEIGHTS_NAME,
    TF2_WEIGHTS_NAME,
    TRANSFORMERS_CACHE,
    WEIGHTS_NAME,
    cached_file,
    get_file_from_repo,
    has_file,
)


lowercase__       : Any         =       '''hf-internal-testing/tiny-random-bert'''
lowercase__       : Optional[Any]         =       os.path.join(TRANSFORMERS_CACHE, '''models--hf-internal-testing--tiny-random-bert''')
lowercase__       : List[Any]         =       '''9b8c223d42b2188cb49d29af482996f9d0f3e5a6'''


class 					SCREAMING_SNAKE_CASE       (unittest.TestCase				):


     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          __A		:					List[Any]						=			cached_file(_UpperCAmelCase		,      _UpperCAmelCase)
          # Should have downloaded the file in here
          self.assertTrue(os.path.isdir(_UpperCAmelCase))
          # Cache should contain at least those three subfolders:
          for subfolder in ["blobs", "refs", "snapshots"]:
               self.assertTrue(os.path.isdir(os.path.join(_UpperCAmelCase		,      _UpperCAmelCase)))
          with open(os.path.join(_UpperCAmelCase		,      'refs'		,      'main')) as f:
               __A		:					Any						=			f.read()
          self.assertEqual(_UpperCAmelCase		,      os.path.join(_UpperCAmelCase		,      'snapshots'		,      _UpperCAmelCase		,      _UpperCAmelCase))
          self.assertTrue(os.path.isfile(_UpperCAmelCase))

          # File is cached at the same place the second time.
          __A		:					Tuple						=			cached_file(_UpperCAmelCase		,      _UpperCAmelCase)
          self.assertEqual(_UpperCAmelCase		,      _UpperCAmelCase)

          # Using a specific revision to test the full commit hash.
          __A		:					List[Any]						=			cached_file(_UpperCAmelCase		,      _UpperCAmelCase		,      revision='9b8c223')
          self.assertEqual(_UpperCAmelCase		,      os.path.join(_UpperCAmelCase		,      'snapshots'		,      _UpperCAmelCase		,      _UpperCAmelCase))


     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          with self.assertRaisesRegex(_UpperCAmelCase		,      'is not a valid model identifier'):
               __A		:					Dict						=			cached_file('tiny-random-bert'		,      _UpperCAmelCase)

          with self.assertRaisesRegex(_UpperCAmelCase		,      'is not a valid git identifier'):
               __A		:					Optional[int]						=			cached_file(_UpperCAmelCase		,      _UpperCAmelCase		,      revision='aaaa')

          with self.assertRaisesRegex(_UpperCAmelCase		,      'does not appear to have a file named'):
               __A		:					int						=			cached_file(_UpperCAmelCase		,      'conf')


     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          with self.assertRaisesRegex(_UpperCAmelCase		,      'does not appear to have a file named'):
               __A		:					Any						=			cached_file(_UpperCAmelCase		,      'conf')

          with open(os.path.join(_UpperCAmelCase		,      'refs'		,      'main')) as f:
               __A		:					Dict						=			f.read()
          self.assertTrue(os.path.isfile(os.path.join(_UpperCAmelCase		,      '.no_exist'		,      _UpperCAmelCase		,      'conf')))

          __A		:					List[Any]						=			cached_file(_UpperCAmelCase		,      'conf'		,      _raise_exceptions_for_missing_entries=_UpperCAmelCase)
          self.assertIsNone(_UpperCAmelCase)

          __A		:					str						=			cached_file(_UpperCAmelCase		,      'conf'		,      local_files_only=_UpperCAmelCase		,      _raise_exceptions_for_missing_entries=_UpperCAmelCase)
          self.assertIsNone(_UpperCAmelCase)

          __A		:					List[str]						=			mock.Mock()
          __A		:					Dict						=			500
          __A		:					List[str]						=			{}
          __A		:					List[Any]						=			HTTPError
          __A		:					Optional[Any]						=			{}

          # Under the mock environment we get a 500 error when trying to reach the tokenizer.
          with mock.patch('requests.Session.request'		,      return_value=_UpperCAmelCase) as mock_head:
               __A		:					Dict						=			cached_file(_UpperCAmelCase		,      'conf'		,      _raise_exceptions_for_connection_errors=_UpperCAmelCase)
               self.assertIsNone(_UpperCAmelCase)
               # This check we did call the fake head request
               mock_head.assert_called()


     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          self.assertTrue(has_file('hf-internal-testing/tiny-bert-pt-only'		,      _UpperCAmelCase))
          self.assertFalse(has_file('hf-internal-testing/tiny-bert-pt-only'		,      _UpperCAmelCase))
          self.assertFalse(has_file('hf-internal-testing/tiny-bert-pt-only'		,      _UpperCAmelCase))


     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          self.assertIsNone(get_file_from_repo('bert-base-cased'		,      'ahah.txt'))

          # The function raises if the repository does not exist.
          with self.assertRaisesRegex(_UpperCAmelCase		,      'is not a valid model identifier'):
               get_file_from_repo('bert-base-case'		,      _UpperCAmelCase)

          # The function raises if the revision does not exist.
          with self.assertRaisesRegex(_UpperCAmelCase		,      'is not a valid git identifier'):
               get_file_from_repo('bert-base-cased'		,      _UpperCAmelCase		,      revision='ahaha')

          __A		:					List[str]						=			get_file_from_repo('bert-base-cased'		,      _UpperCAmelCase)
          # The name is the cached name which is not very easy to test, so instead we load the content.
          __A		:					List[str]						=			json.loads(open(_UpperCAmelCase		,      'r').read())
          self.assertEqual(config['hidden_size']		,      768)


     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          with tempfile.TemporaryDirectory() as tmp_dir:
               __A		:					Tuple						=			Path(_UpperCAmelCase) / 'a.txt'
               filename.touch()
               self.assertEqual(get_file_from_repo(_UpperCAmelCase		,      'a.txt')		,      str(_UpperCAmelCase))

               self.assertIsNone(get_file_from_repo(_UpperCAmelCase		,      'b.txt'))