





import json
import os
import shutil
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 AutoConfig, BertConfig, GPTaConfig
from transformers.configuration_utils import PretrainedConfig
from transformers.testing_utils import TOKEN, USER, is_staging_test


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

from test_module.custom_configuration import CustomConfig  # noqa E402


__A									=				{
    "return_dict": False,
    "output_hidden_states": True,
    "output_attentions": True,
    "torchscript": True,
    "torch_dtype": "float16",
    "use_bfloat16": True,
    "tf_legacy_loss": True,
    "pruned_heads": {"a": 1},
    "tie_word_embeddings": False,
    "is_decoder": True,
    "cross_attention_hidden_size": 128,
    "add_cross_attention": True,
    "tie_encoder_decoder": True,
    "max_length": 50,
    "min_length": 3,
    "do_sample": True,
    "early_stopping": True,
    "num_beams": 3,
    "num_beam_groups": 3,
    "diversity_penalty": 0.5,
    "temperature": 2.0,
    "top_k": 10,
    "top_p": 0.7,
    "typical_p": 0.2,
    "repetition_penalty": 0.8,
    "length_penalty": 0.8,
    "no_repeat_ngram_size": 5,
    "encoder_no_repeat_ngram_size": 5,
    "bad_words_ids": [1, 2, 3],
    "num_return_sequences": 3,
    "chunk_size_feed_forward": 5,
    "output_scores": True,
    "return_dict_in_generate": True,
    "forced_bos_token_id": 2,
    "forced_eos_token_id": 3,
    "remove_invalid_values": True,
    "architectures": ["BertModel"],
    "finetuning_task": "translation",
    "id2label": {0: "label"},
    "label2id": {"label": "0"},
    "tokenizer_class": "BertTokenizerFast",
    "prefix": "prefix",
    "bos_token_id": 6,
    "pad_token_id": 7,
    "eos_token_id": 8,
    "sep_token_id": 9,
    "decoder_start_token_id": 10,
    "exponential_decay_length_penalty": (5, 1.0_1),
    "suppress_tokens": [0, 1],
    "begin_suppress_tokens": 2,
    "task_specific_params": {"translation": "some_params"},
    "problem_type": "regression",
}



@is_staging_test
class    _SCREAMING_SNAKE_CASE						(	unittest.TestCase    ):







 '''simple docstring'''

 @classmethod
 def 							SCREAMING_SNAKE_CASE_					(cls				:   Optional[Any])       ->str:



   '''simple docstring'''



   lowerCamelCase__:      Tuple			  =TOKEN
   HfFolder.save_token(UpperCAmelCase_)

 @classmethod
 def 							SCREAMING_SNAKE_CASE_					(cls				:   List[str])       ->str:



   '''simple docstring'''



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

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

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

 def 							SCREAMING_SNAKE_CASE_					(self				:   List[str])       ->Union[str, Any]:



   '''simple docstring'''



   lowerCamelCase__:      List[Any]			  =BertConfig(
       vocab_size=99       , hidden_size=32       , num_hidden_layers=5       , num_attention_heads=4       , intermediate_size=37)
   config.push_to_hub("test-config"       , use_auth_token=self._token)

   lowerCamelCase__:      Dict			  =BertConfig.from_pretrained(F"""{USER}/test-config""")
   for k, v in config.to_dict().items():
     if k != "transformers_version":
       self.assertEqual(UpperCAmelCase_       , getattr(UpperCAmelCase_       , UpperCAmelCase_))

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

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

   lowerCamelCase__:      Optional[int]			  =BertConfig.from_pretrained(F"""{USER}/test-config""")
   for k, v in config.to_dict().items():
     if k != "transformers_version":
       self.assertEqual(UpperCAmelCase_       , getattr(UpperCAmelCase_       , UpperCAmelCase_))

 def 							SCREAMING_SNAKE_CASE_					(self				:   Any)       ->Tuple:



   '''simple docstring'''



   lowerCamelCase__:      Optional[int]			  =BertConfig(
       vocab_size=99       , hidden_size=32       , num_hidden_layers=5       , num_attention_heads=4       , intermediate_size=37)
   config.push_to_hub("valid_org/test-config-org"       , use_auth_token=self._token)

   lowerCamelCase__:      Optional[int]			  =BertConfig.from_pretrained("valid_org/test-config-org")
   for k, v in config.to_dict().items():
     if k != "transformers_version":
       self.assertEqual(UpperCAmelCase_       , getattr(UpperCAmelCase_       , UpperCAmelCase_))

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

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

   lowerCamelCase__:      List[str]			  =BertConfig.from_pretrained("valid_org/test-config-org")
   for k, v in config.to_dict().items():
     if k != "transformers_version":
       self.assertEqual(UpperCAmelCase_       , getattr(UpperCAmelCase_       , UpperCAmelCase_))







 def 							SCREAMING_SNAKE_CASE_					(self				:   Optional[Any])       ->Optional[int]:



   '''simple docstring'''



   CustomConfig.register_for_auto_class()
   lowerCamelCase__:      Optional[Any]			  =CustomConfig(attribute=42)

   config.push_to_hub("test-dynamic-config"       , use_auth_token=self._token)

   # This has added the proper auto_map field to the config
   self.assertDictEqual(config.auto_map       , {"AutoConfig": "custom_configuration.CustomConfig"})

   lowerCamelCase__:      List[str]			  =AutoConfig.from_pretrained(F"""{USER}/test-dynamic-config"""       , trust_remote_code=UpperCAmelCase_)
   # Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module
   self.assertEqual(new_config.__class__.__name__       , "CustomConfig")
   self.assertEqual(new_config.attribute       , 42)



class    _SCREAMING_SNAKE_CASE						(	unittest.TestCase    ):







 '''simple docstring'''

 def 							SCREAMING_SNAKE_CASE_					(self				:   List[Any])       ->Dict:



   '''simple docstring'''



   lowerCamelCase__:      Tuple			  =GPTaConfig()

   # attempt to modify each of int/float/bool/str config records and verify they were updated
   lowerCamelCase__:      Tuple			  =c.n_embd + 1  # int
   lowerCamelCase__:      Optional[int]			  =c.resid_pdrop + 1.0  # float
   lowerCamelCase__:      Dict			  =not c.scale_attn_weights  # bool
   lowerCamelCase__:      Any			  =c.summary_type + "foo"  # str
   c.update_from_string(
       F"""n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}""")
   self.assertEqual(UpperCAmelCase_       , c.n_embd       , "mismatch for key: n_embd")
   self.assertEqual(UpperCAmelCase_       , c.resid_pdrop       , "mismatch for key: resid_pdrop")
   self.assertEqual(UpperCAmelCase_       , c.scale_attn_weights       , "mismatch for key: scale_attn_weights")
   self.assertEqual(UpperCAmelCase_       , c.summary_type       , "mismatch for key: summary_type")

 def 							SCREAMING_SNAKE_CASE_					(self				:   List[Any])       ->Union[str, Any]:



   '''simple docstring'''



   lowerCamelCase__:      Union[str, Any]			  =PretrainedConfig()
   lowerCamelCase__:      str			  =[key for key in base_config.__dict__ if key not in config_common_kwargs]
   # If this part of the test fails, you have arguments to addin config_common_kwargs above.
   self.assertListEqual(
       UpperCAmelCase_       , ["is_encoder_decoder", "_name_or_path", "_commit_hash", "transformers_version"])
   lowerCamelCase__:      int			  =[key for key, value in config_common_kwargs.items() if value == getattr(UpperCAmelCase_       , UpperCAmelCase_)]
   if len(UpperCAmelCase_) > 0:
     raise ValueError(
         "The following keys are set with the default values in"
         " `test_configuration_common.config_common_kwargs` pick another value for them:"
         F""" {", ".join(UpperCAmelCase_)}.""")

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



   '''simple docstring'''



   with self.assertRaises(UpperCAmelCase_):
     # config is in subfolder, the following should not work without specifying the subfolder
     lowerCamelCase__:      Tuple			  =BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder")

   lowerCamelCase__:      Union[str, Any]			  =BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder"       , subfolder="bert")

   self.assertIsNotNone(UpperCAmelCase_)

 def 							SCREAMING_SNAKE_CASE_					(self				:   List[str])       ->Union[str, Any]:



   '''simple docstring'''



   lowerCamelCase__:      Tuple			  =mock.Mock()
   lowerCamelCase__:      Tuple			  =500
   lowerCamelCase__:      Union[str, Any]			  ={}
   lowerCamelCase__:      str			  =HTTPError
   lowerCamelCase__:      Tuple			  ={}

   # Download this model to make sure it's in the cache.
   lowerCamelCase__:      str			  =BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert")

   # Under the mock environment we get a 500 error when trying to reach the model.
   with mock.patch("requests.Session.request"       , return_value=UpperCAmelCase_) as mock_head:
     lowerCamelCase__:      List[str]			  =BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert")
     # This check we did call the fake head request
     mock_head.assert_called()

 def 							SCREAMING_SNAKE_CASE_					(self				:   List[Any])       ->Union[str, Any]:



   '''simple docstring'''



   lowerCamelCase__:      Optional[Any]			  =BertConfig.from_pretrained(
       "https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/config.json")

 def 							SCREAMING_SNAKE_CASE_					(self				:   Tuple)       ->int:



   '''simple docstring'''



   lowerCamelCase__:      Union[str, Any]			  =AutoConfig.from_pretrained("bert-base-cased")
   lowerCamelCase__:      Any			  =["config.4.0.0.json"]

   with tempfile.TemporaryDirectory() as tmp_dir:
     configuration.save_pretrained(UpperCAmelCase_)
     lowerCamelCase__:      List[Any]			  =2
     json.dump(configuration.to_dict()       , open(os.path.join(UpperCAmelCase_       , "config.4.0.0.json")       , "w"))

     # This should pick the new configuration file as the version of Transformers is > 4.0.0
     lowerCamelCase__:      Optional[Any]			  =AutoConfig.from_pretrained(UpperCAmelCase_)
     self.assertEqual(new_configuration.hidden_size       , 2)

     # Will need to be adjusted if we reach v42 and this test is still here.
     # Should pick the old configuration file as the version of Transformers is < 4.42.0
     lowerCamelCase__:      Any			  =["config.42.0.0.json"]
     lowerCamelCase__:      List[Any]			  =768
     configuration.save_pretrained(UpperCAmelCase_)
     shutil.move(os.path.join(UpperCAmelCase_       , "config.4.0.0.json")       , os.path.join(UpperCAmelCase_       , "config.42.0.0.json"))
     lowerCamelCase__:      Optional[int]			  =AutoConfig.from_pretrained(UpperCAmelCase_)
     self.assertEqual(new_configuration.hidden_size       , 768)







 def 							SCREAMING_SNAKE_CASE_					(self				:   Dict)       ->Optional[Any]:



   '''simple docstring'''



   lowerCamelCase__:      List[str]			  ="hf-internal-testing/test-two-configs"

   import transformers as new_transformers

   lowerCamelCase__:      Dict			  ="v4.0.0"
   lowerCamelCase__  ,					lowerCamelCase__:      Optional[int]			  =new_transformers.models.auto.AutoConfig.from_pretrained(
       UpperCAmelCase_       , return_unused_kwargs=UpperCAmelCase_)
   self.assertEqual(new_configuration.hidden_size       , 2)
   # This checks `_configuration_file` ia not kept in the kwargs by mistake.
   self.assertDictEqual(UpperCAmelCase_       , {})

   # Testing an older version by monkey-patching the version in the module it's used.
   import transformers as old_transformers

   lowerCamelCase__:      str			  ="v3.0.0"
   lowerCamelCase__:      Tuple			  =old_transformers.models.auto.AutoConfig.from_pretrained(UpperCAmelCase_)
   self.assertEqual(old_configuration.hidden_size       , 768)








import functools
import operator

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


__A									=				logging.get_logger(__name__)

__A									=				{
    "microsoft/unispeech-large-1500h-cv": (
        "https://huggingface.co/microsoft/unispeech-large-1500h-cv/resolve/main/config.json"
    ),
    # See all UniSpeech models at https://huggingface.co/models?filter=unispeech
}



class    _SCREAMING_SNAKE_CASE						(	__SCREAMING_SNAKE_CASE    ):







 '''simple docstring'''
 lowercase_		=			"unispeech"

 def __init__(self				:   Any       , UpperCAmelCase_				:   Any=32       , UpperCAmelCase_				:   List[str]=768       , UpperCAmelCase_				:   Any=12       , UpperCAmelCase_				:   Union[str, Any]=12       , UpperCAmelCase_				:   Optional[Any]=3_072       , UpperCAmelCase_				:   List[Any]="gelu"       , UpperCAmelCase_				:   int=0.1       , UpperCAmelCase_				:   Optional[int]=0.1       , UpperCAmelCase_				:   int=0.1       , UpperCAmelCase_				:   Any=0.0       , UpperCAmelCase_				:   str=0.0       , UpperCAmelCase_				:   Dict=0.1       , UpperCAmelCase_				:   Optional[int]=0.1       , UpperCAmelCase_				:   Optional[Any]=0.02       , UpperCAmelCase_				:   Union[str, Any]=1E-5       , UpperCAmelCase_				:   str="group"       , UpperCAmelCase_				:   List[Any]="gelu"       , UpperCAmelCase_				:   Tuple=(512, 512, 512, 512, 512, 512, 512)       , UpperCAmelCase_				:   str=(5, 2, 2, 2, 2, 2, 2)       , UpperCAmelCase_				:   Any=(10, 3, 3, 3, 3, 2, 2)       , UpperCAmelCase_				:   Optional[Any]=False       , UpperCAmelCase_				:   str=128       , UpperCAmelCase_				:   int=16       , UpperCAmelCase_				:   Dict=False       , UpperCAmelCase_				:   Optional[int]=True       , UpperCAmelCase_				:   Dict=0.05       , UpperCAmelCase_				:   Optional[int]=10       , UpperCAmelCase_				:   Tuple=2       , UpperCAmelCase_				:   Union[str, Any]=0.0       , UpperCAmelCase_				:   int=10       , UpperCAmelCase_				:   List[Any]=0       , UpperCAmelCase_				:   Optional[Any]=320       , UpperCAmelCase_				:   int=2       , UpperCAmelCase_				:   Union[str, Any]=0.1       , UpperCAmelCase_				:   str=100       , UpperCAmelCase_				:   Any=256       , UpperCAmelCase_				:   int=256       , UpperCAmelCase_				:   Optional[Any]=0.1       , UpperCAmelCase_				:   str="mean"       , UpperCAmelCase_				:   Union[str, Any]=False       , UpperCAmelCase_				:   List[str]=False       , UpperCAmelCase_				:   List[Any]=256       , UpperCAmelCase_				:   Optional[int]=80       , UpperCAmelCase_				:   Optional[int]=0       , UpperCAmelCase_				:   Optional[Any]=1       , UpperCAmelCase_				:   Union[str, Any]=2       , UpperCAmelCase_				:   Dict=0.5       , **UpperCAmelCase_				:   Optional[int]       , )       ->str:



   '''simple docstring'''



   super().__init__(**UpperCAmelCase_       , pad_token_id=UpperCAmelCase_       , bos_token_id=UpperCAmelCase_       , eos_token_id=UpperCAmelCase_)
   lowerCamelCase__:      Union[str, Any]			  =hidden_size
   lowerCamelCase__:      List[str]			  =feat_extract_norm
   lowerCamelCase__:      Dict			  =feat_extract_activation
   lowerCamelCase__:      Optional[Any]			  =list(UpperCAmelCase_)
   lowerCamelCase__:      Any			  =list(UpperCAmelCase_)
   lowerCamelCase__:      Union[str, Any]			  =list(UpperCAmelCase_)
   lowerCamelCase__:      Dict			  =conv_bias
   lowerCamelCase__:      Optional[Any]			  =num_conv_pos_embeddings
   lowerCamelCase__:      Dict			  =num_conv_pos_embedding_groups
   lowerCamelCase__:      int			  =len(self.conv_dim)
   lowerCamelCase__:      Union[str, Any]			  =num_hidden_layers
   lowerCamelCase__:      Union[str, Any]			  =intermediate_size
   lowerCamelCase__:      Dict			  =hidden_act
   lowerCamelCase__:      List[Any]			  =num_attention_heads
   lowerCamelCase__:      Dict			  =hidden_dropout
   lowerCamelCase__:      Optional[Any]			  =attention_dropout
   lowerCamelCase__:      Optional[Any]			  =activation_dropout
   lowerCamelCase__:      Tuple			  =feat_proj_dropout
   lowerCamelCase__:      int			  =final_dropout
   lowerCamelCase__:      Optional[Any]			  =layerdrop
   lowerCamelCase__:      Dict			  =layer_norm_eps
   lowerCamelCase__:      Optional[Any]			  =initializer_range
   lowerCamelCase__:      int			  =num_ctc_classes
   lowerCamelCase__:      Tuple			  =vocab_size
   lowerCamelCase__:      Dict			  =do_stable_layer_norm
   lowerCamelCase__:      List[Any]			  =use_weighted_layer_sum
   lowerCamelCase__:      Dict			  =classifier_proj_size

   if (
       (len(self.conv_stride) != self.num_feat_extract_layers)
       or (len(self.conv_kernel) != self.num_feat_extract_layers)
       or (len(self.conv_dim) != self.num_feat_extract_layers)
   ):
     raise ValueError(
         "Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="
         " `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="
         F""" {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,"""
         F""" `len(config.conv_kernel) = {len(self.conv_kernel)}`.""")

   # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
   lowerCamelCase__:      int			  =apply_spec_augment
   lowerCamelCase__:      List[str]			  =mask_time_prob
   lowerCamelCase__:      Union[str, Any]			  =mask_time_length
   lowerCamelCase__:      List[Any]			  =mask_time_min_masks
   lowerCamelCase__:      Any			  =mask_feature_prob
   lowerCamelCase__:      Optional[Any]			  =mask_feature_length
   lowerCamelCase__:      List[str]			  =mask_feature_min_masks

   # parameters for pretraining with codevector quantized representations
   lowerCamelCase__:      Optional[Any]			  =num_codevectors_per_group
   lowerCamelCase__:      str			  =num_codevector_groups
   lowerCamelCase__:      Tuple			  =contrastive_logits_temperature
   lowerCamelCase__:      int			  =feat_quantizer_dropout
   lowerCamelCase__:      Any			  =num_negatives
   lowerCamelCase__:      List[str]			  =codevector_dim
   lowerCamelCase__:      Union[str, Any]			  =proj_codevector_dim
   lowerCamelCase__:      Any			  =diversity_loss_weight

   # ctc loss
   lowerCamelCase__:      Any			  =ctc_loss_reduction
   lowerCamelCase__:      Dict			  =ctc_zero_infinity

   # pretraining loss
   lowerCamelCase__:      Dict			  =replace_prob







 @property
 def 							SCREAMING_SNAKE_CASE_					(self				:   List[Any])       ->Optional[Any]:



   '''simple docstring'''



   return functools.reduce(operator.mul       , self.conv_stride       , 1)

