

"""simple docstring"""




import warnings

from ...configuration_utils import PretrainedConfig
from ...utils import logging


_lowercase   :	List[str]												=						logging.get_logger(__name__)

_lowercase   :	str												=						{
    'xlnet-base-cased': 'https://huggingface.co/xlnet-base-cased/resolve/main/config.json',
    'xlnet-large-cased': 'https://huggingface.co/xlnet-large-cased/resolve/main/config.json',
}
class      _UpperCAmelCase   (							_lowerCAmelCase       ):
	a__		: str					=					"xlnet"
	a__		: str					=					["mems"]
	a__		: List[Any]					=					{
	    "n_token": "vocab_size",  # Backward compatibility
	    "hidden_size": "d_model",
	    "num_attention_heads": "n_head",
	    "num_hidden_layers": "n_layer",
	}



	def __init__(  self     :       Tuple			,    _lowercase     :       Union[str, Any]=3_20_00			,    _lowercase     :       Dict=10_24			,    _lowercase     :       List[str]=24			,    _lowercase     :       int=16			,    _lowercase     :       Any=40_96			,    _lowercase     :       Tuple="gelu"			,    _lowercase     :       Union[str, Any]=True			,    _lowercase     :       Optional[Any]="bi"			,    _lowercase     :       Dict=0.02			,    _lowercase     :       int=1E-12			,    _lowercase     :       Tuple=0.1			,    _lowercase     :       Any=5_12			,    _lowercase     :       Any=None			,    _lowercase     :       List[str]=True			,    _lowercase     :       List[Any]=False			,    _lowercase     :       Optional[int]=False			,    _lowercase     :       List[str]=-1			,    _lowercase     :       Dict=False			,    _lowercase     :       str="last"			,    _lowercase     :       str=True			,    _lowercase     :       Dict="tanh"			,    _lowercase     :       str=0.1			,    _lowercase     :       int=5			,    _lowercase     :       Union[str, Any]=5			,    _lowercase     :       List[str]=5			,    _lowercase     :       Union[str, Any]=1			,    _lowercase     :       int=2			,    **_lowercase     :       Dict			,    ):
		__UpperCAmelCase      		= vocab_size
		__UpperCAmelCase      		= d_model
		__UpperCAmelCase      		= n_layer
		__UpperCAmelCase      		= n_head
		if d_model % n_head != 0:
			raise ValueError(F'''\'d_model % n_head\' ({d_model % n_head}) should be equal to 0'''						)
		if "d_head" in kwargs:
			if kwargs["d_head"] != d_model // n_head:
				raise ValueError(
				    F'''`d_head` ({kwargs["d_head"]}) should be equal to `d_model // n_head` ({d_model // n_head})'''						)
		__UpperCAmelCase      		= d_model // n_head
		__UpperCAmelCase      		= ff_activation
		__UpperCAmelCase      		= d_inner
		__UpperCAmelCase      		= untie_r
		__UpperCAmelCase      		= attn_type

		__UpperCAmelCase      		= initializer_range
		__UpperCAmelCase      		= layer_norm_eps

		__UpperCAmelCase      		= dropout
		__UpperCAmelCase      		= mem_len
		__UpperCAmelCase      		= reuse_len
		__UpperCAmelCase      		= bi_data
		__UpperCAmelCase      		= clamp_len
		__UpperCAmelCase      		= same_length

		__UpperCAmelCase      		= summary_type
		__UpperCAmelCase      		= summary_use_proj
		__UpperCAmelCase      		= summary_activation
		__UpperCAmelCase      		= summary_last_dropout
		__UpperCAmelCase      		= start_n_top
		__UpperCAmelCase      		= end_n_top

		__UpperCAmelCase      		= bos_token_id
		__UpperCAmelCase      		= pad_token_id
		__UpperCAmelCase      		= eos_token_id

		if "use_cache" in kwargs:
			warnings.warn(
			    '''The `use_cache` argument is deprecated and will be removed in a future version, use `use_mems_eval`'''
			    ''' instead.'''			,    _lowercase			,    )
			__UpperCAmelCase      		= kwargs['''use_cache''']

		__UpperCAmelCase      		= use_mems_eval
		__UpperCAmelCase      		= use_mems_train
		super().__init__(pad_token_id=_lowercase			,    bos_token_id=_lowercase			,    eos_token_id=_lowercase			,    **_lowercase						)



	@property
	def        a  (  self     :       Optional[int]						):
		logger.info(F'''The model {self.model_type} is one of the few models that has no sequence length limit.'''						)
		return -1



	@max_position_embeddings.setter
	def        a  (  self     :       Tuple			,    _lowercase     :       Dict						):
		# Message copied from Transformer-XL documentation
		raise NotImplementedError(
		    F'''The model {self.model_type} is one of the few models that has no sequence length limit.'''						)




"""simple docstring"""


import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError

from transformers import AutoImageProcessor, ViTImageProcessor
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test


sys.path.append(str(Path(__file__).parent.parent / 'utils'))

from test_module.custom_image_processing import CustomImageProcessor  # noqa E402


__snake_case    					=					get_tests_dir('fixtures')

class 				_SCREAMING_SNAKE_CASE				(							unittest.TestCase  ):
   """simple docstring"""



   def 					UpperCAmelCase__(						self						)      ->							str:
    # A mock response for an HTTP head request to emulate server down
    lowercase__       :       List[str]				=						mock.Mock()
    lowercase__       :       Dict				=						500
    lowercase__       :       Any				=						{}
    lowercase__       :       int				=						HTTPError
    lowercase__       :       Optional[int]				=						{}

    # Download this model to make sure it's in the cache.
    lowercase__       :       Dict				=						ViTImageProcessor.from_pretrained("""hf-internal-testing/tiny-random-vit"""						)
    # Under the mock environment we get a 500 error when trying to reach the model.
    with mock.patch("""requests.Session.request""" ,     return_value=lowerCamelCase__						) as mock_head:
     lowercase__       :       Dict				=						ViTImageProcessor.from_pretrained("""hf-internal-testing/tiny-random-vit"""						)
     # This check we did call the fake head request
     mock_head.assert_called()


   def 					UpperCAmelCase__(						self						)      ->							Dict:
    # This test is for deprecated behavior and can be removed in v5
    lowercase__       :       Dict				=						ViTImageProcessor.from_pretrained(
        """https://huggingface.co/hf-internal-testing/tiny-random-vit/resolve/main/preprocessor_config.json"""						)







   def 					UpperCAmelCase__(						self						)      ->							Tuple:
    with self.assertRaises(lowerCamelCase__						):
     # config is in subfolder, the following should not work without specifying the subfolder
     lowercase__       :       List[str]				=						AutoImageProcessor.from_pretrained("""hf-internal-testing/stable-diffusion-all-variants"""						)

    lowercase__       :       Any				=						AutoImageProcessor.from_pretrained(
        """hf-internal-testing/stable-diffusion-all-variants""" ,     subfolder="""feature_extractor"""						)

    self.assertIsNotNone(lowerCamelCase__						)

@is_staging_test
class 				_SCREAMING_SNAKE_CASE				(							unittest.TestCase  ):
   """simple docstring"""



   @classmethod
   def 					UpperCAmelCase__(						cls						)      ->							int:
    lowercase__       :       str				=						TOKEN
    HfFolder.save_token(lowerCamelCase__						)


   @classmethod
   def 					UpperCAmelCase__(						cls						)      ->							List[str]:
    try:
     delete_repo(token=cls._token ,     repo_id="""test-image-processor"""						)
    except HTTPError:
     pass

    try:
     delete_repo(token=cls._token ,     repo_id="""valid_org/test-image-processor-org"""						)
    except HTTPError:
     pass

    try:
     delete_repo(token=cls._token ,     repo_id="""test-dynamic-image-processor"""						)
    except HTTPError:
     pass


   def 					UpperCAmelCase__(						self						)      ->							int:
    lowercase__       :       List[str]				=						ViTImageProcessor.from_pretrained(lowerCamelCase__						)
    image_processor.push_to_hub("""test-image-processor""" ,     use_auth_token=self._token						)

    lowercase__       :       str				=						ViTImageProcessor.from_pretrained(F'''{USER}/test-image-processor'''						)
    for k, v in image_processor.__dict__.items():
     self.assertEqual(lowerCamelCase__ ,     getattr(lowerCamelCase__ ,     lowerCamelCase__						)						)

    # Reset repo
    delete_repo(token=self._token ,     repo_id="""test-image-processor"""						)

    # Push to hub via save_pretrained
    with tempfile.TemporaryDirectory() as tmp_dir:
     image_processor.save_pretrained(
         lowerCamelCase__ ,     repo_id="""test-image-processor""" ,     push_to_hub=lowerCamelCase__ ,     use_auth_token=self._token						)

    lowercase__       :       Union[str, Any]				=						ViTImageProcessor.from_pretrained(F'''{USER}/test-image-processor'''						)
    for k, v in image_processor.__dict__.items():
     self.assertEqual(lowerCamelCase__ ,     getattr(lowerCamelCase__ ,     lowerCamelCase__						)						)


   def 					UpperCAmelCase__(						self						)      ->							Optional[int]:
    lowercase__       :       Tuple				=						ViTImageProcessor.from_pretrained(lowerCamelCase__						)
    image_processor.push_to_hub("""valid_org/test-image-processor""" ,     use_auth_token=self._token						)

    lowercase__       :       Any				=						ViTImageProcessor.from_pretrained("""valid_org/test-image-processor"""						)
    for k, v in image_processor.__dict__.items():
     self.assertEqual(lowerCamelCase__ ,     getattr(lowerCamelCase__ ,     lowerCamelCase__						)						)

    # Reset repo
    delete_repo(token=self._token ,     repo_id="""valid_org/test-image-processor"""						)

    # Push to hub via save_pretrained
    with tempfile.TemporaryDirectory() as tmp_dir:
     image_processor.save_pretrained(
         lowerCamelCase__ ,     repo_id="""valid_org/test-image-processor-org""" ,     push_to_hub=lowerCamelCase__ ,     use_auth_token=self._token						)

    lowercase__       :       List[Any]				=						ViTImageProcessor.from_pretrained("""valid_org/test-image-processor-org"""						)
    for k, v in image_processor.__dict__.items():
     self.assertEqual(lowerCamelCase__ ,     getattr(lowerCamelCase__ ,     lowerCamelCase__						)						)







   def 					UpperCAmelCase__(						self						)      ->							Dict:
    CustomImageProcessor.register_for_auto_class()
    lowercase__       :       List[str]				=						CustomImageProcessor.from_pretrained(lowerCamelCase__						)

    image_processor.push_to_hub("""test-dynamic-image-processor""" ,     use_auth_token=self._token						)

    # This has added the proper auto_map field to the config
    self.assertDictEqual(
        image_processor.auto_map ,     {"""AutoImageProcessor""": """custom_image_processing.CustomImageProcessor"""} ,     )

    lowercase__       :       Dict				=						AutoImageProcessor.from_pretrained(
        F'''{USER}/test-dynamic-image-processor''' ,     trust_remote_code=lowerCamelCase__						)
    # Can't make an isinstance check because the new_image_processor is from the CustomImageProcessor class of a dynamic module
    self.assertEqual(new_image_processor.__class__.__name__ ,     """CustomImageProcessor"""						)