

import re
import time
from typing import Optional

import IPython.display as disp

from ..trainer_callback import TrainerCallback
from ..trainer_utils import IntervalStrategy, has_length





def 	__a     (      A__			:  str       ):
    SCREAMING_SNAKE_CASE										=   int(A__       )
    SCREAMING_SNAKE_CASE							,	SCREAMING_SNAKE_CASE							,	SCREAMING_SNAKE_CASE										=   t // 3600, (t // 60) % 60, t % 60
    return F"{h}:{m:02d}:{s:02d}" if h != 0 else F"{m:02d}:{s:02d}"





def 	__a     (      A__			:  Dict			,  A__			:  Union[str, Any]			,  A__			:  Dict			,  A__			:  Tuple			,  A__			:  Union[str, Any]=300       ):
    # docstyle-ignore
    return F"\n    <div>\n      {prefix}\n      <progress value='{value}' max='{total}' style='width:{width}px; height:20px; vertical-align: middle;'></progress>\n      {label}\n    </div>\n    "





def 	__a     (      A__			:  str       ):
    SCREAMING_SNAKE_CASE										=   "<table border=\"1\" class=\"dataframe\">\n"
    html_code += """  <thead>\n <tr style="text-align: left;">\n"""
    for i in items[0]:
        html_code += F"      <th>{i}</th>\n"
    html_code += "    </tr>\n  </thead>\n  <tbody>\n"
    for line in items[1:]:
        html_code += "    <tr>\n"
        for elt in line:
            SCREAMING_SNAKE_CASE										=   F"{elt:.6f}" if isinstance(A__			,  A__       ) else str(A__       )
            html_code += F"      <td>{elt}</td>\n"
        html_code += "    </tr>\n"
    html_code += "  </tbody>\n</table><p>"
    return html_code





class 			_SCREAMING_SNAKE_CASE :







   '''simple docstring'''




   lowerCamelCase__				=      5
   lowerCamelCase__				=      0.2





   def __init__(       self					:			Optional[int]     , __lowerCamelCase					:			int     , __lowerCamelCase					:			Optional[str] = None     , __lowerCamelCase					:			bool = True     , __lowerCamelCase					:			Optional["NotebookTrainingTracker"] = None     , __lowerCamelCase					:			int = 300     , ):
       SCREAMING_SNAKE_CASE										=   total
       SCREAMING_SNAKE_CASE										=   "" if prefix is None else prefix
       SCREAMING_SNAKE_CASE										=   leave
       SCREAMING_SNAKE_CASE										=   parent
       SCREAMING_SNAKE_CASE										=   width
       SCREAMING_SNAKE_CASE										=   None
       SCREAMING_SNAKE_CASE										=   None
       SCREAMING_SNAKE_CASE										=   None





   def      _snake_case		(       self					:			Union[str, Any]     , __lowerCamelCase					:			int     , __lowerCamelCase					:			bool = False     , __lowerCamelCase					:			str = None			):
       SCREAMING_SNAKE_CASE										=   value
       if comment is not None:
           SCREAMING_SNAKE_CASE										=   comment
       if self.last_value is None:
           SCREAMING_SNAKE_CASE										=   SCREAMING_SNAKE_CASE										=   time.time()
           SCREAMING_SNAKE_CASE										=   SCREAMING_SNAKE_CASE										=   value
           SCREAMING_SNAKE_CASE										=   SCREAMING_SNAKE_CASE										=   None
           SCREAMING_SNAKE_CASE										=   self.warmup
           SCREAMING_SNAKE_CASE										=   1
           self.update_bar(__lowerCamelCase			)
       elif value <= self.last_value and not force_update:
           return
       elif force_update or self.first_calls > 0 or value >= min(self.last_value + self.wait_for     , self.total			):
           if self.first_calls > 0:
               self.first_calls -= 1
           SCREAMING_SNAKE_CASE										=   time.time()
           SCREAMING_SNAKE_CASE										=   current_time - self.start_time
           # We could have value = self.start_value if the update is called twixe with the same start value.
           if value > self.start_value:
               SCREAMING_SNAKE_CASE										=   self.elapsed_time / (value - self.start_value)
           else:
               SCREAMING_SNAKE_CASE										=   None
           if value >= self.total:
               SCREAMING_SNAKE_CASE										=   self.total
               SCREAMING_SNAKE_CASE										=   None
               if not self.leave:
                   self.close()
           elif self.average_time_per_item is not None:
               SCREAMING_SNAKE_CASE										=   self.average_time_per_item * (self.total - value)
           self.update_bar(__lowerCamelCase			)
           SCREAMING_SNAKE_CASE										=   value
           SCREAMING_SNAKE_CASE										=   current_time
           if self.average_time_per_item is None:
               SCREAMING_SNAKE_CASE										=   1
           else:
               SCREAMING_SNAKE_CASE										=   max(int(self.update_every / self.average_time_per_item			)     , 1			)





   def      _snake_case		(       self					:			str     , __lowerCamelCase					:			List[Any]     , __lowerCamelCase					:			List[Any]=None			):
       SCREAMING_SNAKE_CASE										=   " " * (len(str(self.total			)			) - len(str(__lowerCamelCase			)			)) + str(__lowerCamelCase			)
       if self.elapsed_time is None:
           SCREAMING_SNAKE_CASE										=   f"[{spaced_value}/{self.total} : < :"
       elif self.predicted_remaining is None:
           SCREAMING_SNAKE_CASE										=   f"[{spaced_value}/{self.total} {format_time(self.elapsed_time			)}"
       else:
           SCREAMING_SNAKE_CASE										=   (
               f"[{spaced_value}/{self.total} {format_time(self.elapsed_time			)} <"
               f" {format_time(self.predicted_remaining			)}"
           )
           self.label += f", {1/self.average_time_per_item:.2f} it/s"
       self.label += "]" if self.comment is None or len(self.comment			) == 0 else f", {self.comment}]"
       self.display()





   def      _snake_case		(       self					:			Optional[Any]			):
       SCREAMING_SNAKE_CASE										=   html_progress_bar(self.value     , self.total     , self.prefix     , self.label     , self.width			)
       if self.parent is not None:
           # If this is a child bar, the parent will take care of the display.
           self.parent.display()
           return
       if self.output is None:
           SCREAMING_SNAKE_CASE										=   disp.display(disp.HTML(self.html_code			)     , display_id=__lowerCamelCase			)
       else:
           self.output.update(disp.HTML(self.html_code			)			)





   def      _snake_case		(       self					:			Union[str, Any]			):
       if self.parent is None and self.output is not None:
           self.output.update(disp.HTML(""			)			)





class 			_SCREAMING_SNAKE_CASE (   __snake_case		):







   '''simple docstring'''




   def __init__(       self					:			int     , __lowerCamelCase					:			Optional[int]     , __lowerCamelCase					:			List[str]=None			):
       super().__init__(__lowerCamelCase			)
       SCREAMING_SNAKE_CASE										=   None if column_names is None else [column_names]
       SCREAMING_SNAKE_CASE										=   None





   def      _snake_case		(       self					:			Any			):
       SCREAMING_SNAKE_CASE										=   html_progress_bar(self.value     , self.total     , self.prefix     , self.label     , self.width			)
       if self.inner_table is not None:
           self.html_code += text_to_html_table(self.inner_table			)
       if self.child_bar is not None:
           self.html_code += self.child_bar.html_code
       if self.output is None:
           SCREAMING_SNAKE_CASE										=   disp.display(disp.HTML(self.html_code			)     , display_id=__lowerCamelCase			)
       else:
           self.output.update(disp.HTML(self.html_code			)			)





   def      _snake_case		(       self					:			Optional[Any]     , __lowerCamelCase					:			Optional[Any]			):
       if self.inner_table is None:
           SCREAMING_SNAKE_CASE										=   [list(values.keys()			), list(values.values()			)]
       else:
           SCREAMING_SNAKE_CASE										=   self.inner_table[0]
           if len(self.inner_table			) == 1:
               # We give a chance to update the column names at the first iteration
               for key in values.keys():
                   if key not in columns:
                       columns.append(__lowerCamelCase			)
               SCREAMING_SNAKE_CASE										=   columns
           self.inner_table.append([values[c] for c in columns]			)





   def      _snake_case		(       self					:			Dict     , __lowerCamelCase					:			Any     , __lowerCamelCase					:			List[str]=None     , __lowerCamelCase					:			str=300			):
       SCREAMING_SNAKE_CASE										=   NotebookProgressBar(__lowerCamelCase     , prefix=__lowerCamelCase     , parent=self     , width=__lowerCamelCase			)
       return self.child_bar





   def      _snake_case		(       self					:			Tuple			):
       SCREAMING_SNAKE_CASE										=   None
       self.display()





class 			_SCREAMING_SNAKE_CASE (   __snake_case		):







   '''simple docstring'''




   def __init__(       self					:			Dict			):
       SCREAMING_SNAKE_CASE										=   None
       SCREAMING_SNAKE_CASE										=   None
       SCREAMING_SNAKE_CASE										=   False





   def      _snake_case		(       self					:			Optional[int]     , __lowerCamelCase					:			Optional[Any]     , __lowerCamelCase					:			str     , __lowerCamelCase					:			str     , **__lowerCamelCase					:			Tuple			):
       SCREAMING_SNAKE_CASE										=   "Epoch" if args.evaluation_strategy == IntervalStrategy.EPOCH else "Step"
       SCREAMING_SNAKE_CASE										=   0
       SCREAMING_SNAKE_CASE										=   0
       SCREAMING_SNAKE_CASE										=   [self.first_column] + ["Training Loss"]
       if args.evaluation_strategy != IntervalStrategy.NO:
           column_names.append("Validation Loss"			)
       SCREAMING_SNAKE_CASE										=   NotebookTrainingTracker(state.max_steps     , __lowerCamelCase			)





   def      _snake_case		(       self					:			Dict     , __lowerCamelCase					:			Optional[Any]     , __lowerCamelCase					:			Dict     , __lowerCamelCase					:			Tuple     , **__lowerCamelCase					:			List[str]			):
       SCREAMING_SNAKE_CASE										=   int(state.epoch			) if int(state.epoch			) == state.epoch else f"{state.epoch:.2f}"
       self.training_tracker.update(
           state.global_step + 1     , comment=f"Epoch {epoch}/{state.num_train_epochs}"     , force_update=self._force_next_update     , )
       SCREAMING_SNAKE_CASE										=   False





   def      _snake_case		(       self					:			Dict     , __lowerCamelCase					:			int     , __lowerCamelCase					:			List[str]     , __lowerCamelCase					:			int     , __lowerCamelCase					:			Any=None     , **__lowerCamelCase					:			int			):
       if not has_length(__lowerCamelCase			):
           return
       if self.prediction_bar is None:
           if self.training_tracker is not None:
               SCREAMING_SNAKE_CASE										=   self.training_tracker.add_child(len(__lowerCamelCase			)			)
           else:
               SCREAMING_SNAKE_CASE										=   NotebookProgressBar(len(__lowerCamelCase			)			)
           self.prediction_bar.update(1			)
       else:
           self.prediction_bar.update(self.prediction_bar.value + 1			)





   def      _snake_case		(       self					:			Union[str, Any]     , __lowerCamelCase					:			Optional[int]     , __lowerCamelCase					:			Union[str, Any]     , __lowerCamelCase					:			List[str]     , **__lowerCamelCase					:			List[Any]			):
       if self.prediction_bar is not None:
           self.prediction_bar.close()
       SCREAMING_SNAKE_CASE										=   None





   def      _snake_case		(       self					:			Optional[Any]     , __lowerCamelCase					:			str     , __lowerCamelCase					:			int     , __lowerCamelCase					:			Tuple     , __lowerCamelCase					:			Dict=None     , **__lowerCamelCase					:			Dict			):
       # Only for when there is no evaluation
       if args.evaluation_strategy == IntervalStrategy.NO and "loss" in logs:
           SCREAMING_SNAKE_CASE										=   {"Training Loss": logs["loss"]}
           # First column is necessarily Step sine we're not in epoch eval strategy
           SCREAMING_SNAKE_CASE										=   state.global_step
           self.training_tracker.write_line(__lowerCamelCase			)





   def      _snake_case		(       self					:			str     , __lowerCamelCase					:			str     , __lowerCamelCase					:			List[Any]     , __lowerCamelCase					:			Any     , __lowerCamelCase					:			Optional[int]=None     , **__lowerCamelCase					:			int			):
       if self.training_tracker is not None:
           SCREAMING_SNAKE_CASE										=   {"Training Loss": "No log", "Validation Loss": "No log"}
           for log in reversed(state.log_history			):
               if "loss" in log:
                   SCREAMING_SNAKE_CASE										=   log["loss"]
                   break

           if self.first_column == "Epoch":
               SCREAMING_SNAKE_CASE										=   int(state.epoch			)
           else:
               SCREAMING_SNAKE_CASE										=   state.global_step
           SCREAMING_SNAKE_CASE										=   "eval"
           for k in metrics:
               if k.endswith("_loss"			):
                   SCREAMING_SNAKE_CASE										=   re.sub(r"\_loss$"     , ""     , __lowerCamelCase			)
           SCREAMING_SNAKE_CASE										=   metrics.pop("total_flos"     , __lowerCamelCase			)
           SCREAMING_SNAKE_CASE										=   metrics.pop("epoch"     , __lowerCamelCase			)
           SCREAMING_SNAKE_CASE										=   metrics.pop(f"{metric_key_prefix}_runtime"     , __lowerCamelCase			)
           SCREAMING_SNAKE_CASE										=   metrics.pop(f"{metric_key_prefix}_samples_per_second"     , __lowerCamelCase			)
           SCREAMING_SNAKE_CASE										=   metrics.pop(f"{metric_key_prefix}_steps_per_second"     , __lowerCamelCase			)
           SCREAMING_SNAKE_CASE										=   metrics.pop(f"{metric_key_prefix}_jit_compilation_time"     , __lowerCamelCase			)
           for k, v in metrics.items():
               if k == f"{metric_key_prefix}_loss":
                   SCREAMING_SNAKE_CASE										=   v
               else:
                   SCREAMING_SNAKE_CASE										=   k.split("_"			)
                   SCREAMING_SNAKE_CASE										=   " ".join([part.capitalize() for part in splits[1:]]			)
                   SCREAMING_SNAKE_CASE										=   v
           self.training_tracker.write_line(__lowerCamelCase			)
           self.training_tracker.remove_child()
           SCREAMING_SNAKE_CASE										=   None
           # Evaluation takes a long time so we should force the next update.
           SCREAMING_SNAKE_CASE										=   True





   def      _snake_case		(       self					:			Union[str, Any]     , __lowerCamelCase					:			Dict     , __lowerCamelCase					:			Dict     , __lowerCamelCase					:			Dict     , **__lowerCamelCase					:			Any			):
       self.training_tracker.update(
           state.global_step     , comment=f"Epoch {int(state.epoch			)}/{state.num_train_epochs}"     , force_update=__lowerCamelCase			)
       SCREAMING_SNAKE_CASE										=   None

"""simple docstring"""


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


SCREAMING_SNAKE_CASE			  =  {
    """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.01),
    """suppress_tokens""": [0, 1],
    """begin_suppress_tokens""": 2,
    """task_specific_params""": {"""translation""": """some_params"""},
    """problem_type""": """regression""",
}



@is_staging_test
class 	__a	(   unittest.TestCase						):






       @classmethod
       def 						_SCREAMING_SNAKE_CASE							(	cls			:				Union[str, Any]      )->	List[Any]:







              """simple docstring"""
              UpperCamelCase       			=		TOKEN
              HfFolder.save_token(UpperCAmelCase_      )






       @classmethod
       def 						_SCREAMING_SNAKE_CASE							(	cls			:				str      )->	Dict:







              """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[Any]      )->	int:







              """simple docstring"""
              UpperCamelCase       			=		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      )

              UpperCamelCase       			=		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      )

              UpperCamelCase       			=		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			:				Tuple      )->	List[str]:







              """simple docstring"""
              UpperCamelCase       			=		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      )

              UpperCamelCase       			=		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      )

              UpperCamelCase       			=		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			:				int      )->	Union[str, Any]:







              """simple docstring"""
              CustomConfig.register_for_auto_class()
              UpperCamelCase       			=		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"}      )

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






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Any      )->	Any:







              """simple docstring"""
              UpperCamelCase       			=		GPTaConfig()

              # attempt to modify each of int/float/bool/str config records and verify they were updated
              UpperCamelCase       			=		c.n_embd + 1  # int
              UpperCamelCase       			=		c.resid_pdrop + 1.0  # float
              UpperCamelCase       			=		not c.scale_attn_weights  # bool
              UpperCamelCase       			=		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			:				Any      )->	List[str]:







              """simple docstring"""
              UpperCamelCase       			=		PretrainedConfig()
              UpperCamelCase       			=		[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"]      )
              UpperCamelCase       			=		[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			:				Optional[int]      )->	Optional[Any]:







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

              UpperCamelCase       			=		BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder"							,   subfolder="bert"      )

              self.assertIsNotNone(UpperCAmelCase_      )






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Any      )->	Any:







              """simple docstring"""
              # A mock response for an HTTP head request to emulate server down
              UpperCamelCase       			=		mock.Mock()
              UpperCamelCase       			=		500
              UpperCamelCase       			=		{}
              UpperCamelCase       			=		HTTPError
              UpperCamelCase       			=		{}

              # Download this model to make sure it's in the cache.
              UpperCamelCase       			=		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:
                     UpperCamelCase       			=		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			:				Tuple      )->	int:







              """simple docstring"""
              # This test is for deprecated behavior and can be removed in v5
              UpperCamelCase       			=		BertConfig.from_pretrained(
                  "https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/config.json"      )






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Union[str, Any]      )->	Optional[int]:







              """simple docstring"""
              UpperCamelCase       			=		AutoConfig.from_pretrained("bert-base-cased"      )
              UpperCamelCase       			=		["config.4.0.0.json"]

              with tempfile.TemporaryDirectory() as tmp_dir:
                     configuration.save_pretrained(UpperCAmelCase_      )
                     UpperCamelCase       			=		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
                     UpperCamelCase       			=		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
                     UpperCamelCase       			=		["config.42.0.0.json"]
                     UpperCamelCase       			=		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"      )      )
                     UpperCamelCase       			=		AutoConfig.from_pretrained(UpperCAmelCase_      )
                     self.assertEqual(new_configuration.hidden_size							,   768      )






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







              """simple docstring"""
              # This repo has two configuration files, one for v4.0.0 and above with a different hidden size.
              UpperCamelCase       			=		"hf-internal-testing/test-two-configs"

              import transformers as new_transformers

              UpperCamelCase       			=		"v4.0.0"
              UpperCamelCase			,							UpperCamelCase       			=		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

              UpperCamelCase       			=		"v3.0.0"
              UpperCamelCase       			=		old_transformers.models.auto.AutoConfig.from_pretrained(UpperCAmelCase_      )
              self.assertEqual(old_configuration.hidden_size							,   768      )





