





"""simple docstring"""
import importlib.metadata
import warnings
from copy import deepcopy

from packaging import version

from ..utils import logging
from .import_utils import is_accelerate_available, is_bitsandbytes_available


if is_bitsandbytes_available():
  import bitsandbytes as bnb
  import torch
  import torch.nn as nn

  from ..pytorch_utils import ConvaD

if is_accelerate_available():
  from accelerate import init_empty_weights
  from accelerate.utils import find_tied_parameters

lowerCamelCase_								=		logging.get_logger(__name__)



def      __lowerCamelCase   (							a_     :		Union[str, Any] ,   a_     :		Optional[Any] ,   a_     :		str ,   a_     :		Dict=None ,   a_     :		Tuple=None							)			->      int:
      # Recurse if needed
      if "." in tensor_name:
            __SCREAMING_SNAKE_CASE   :Any						=  tensor_name.split('''.'''							)
            for split in splits[:-1]:
                  __SCREAMING_SNAKE_CASE   :str						=  getattr(a_ ,   a_							)
                  if new_module is None:
                        raise ValueError(f'''{module} has no attribute {split}.'''							)
                  __SCREAMING_SNAKE_CASE   :int						=  new_module
            __SCREAMING_SNAKE_CASE   :Tuple						=  splits[-1]

      if tensor_name not in module._parameters and tensor_name not in module._buffers:
            raise ValueError(f'''{module} does not have a parameter or a buffer named {tensor_name}.'''							)
      __SCREAMING_SNAKE_CASE   :List[str]						=  tensor_name in module._buffers
      __SCREAMING_SNAKE_CASE   :Dict						=  getattr(a_ ,   a_							)

      if old_value.device == torch.device('''meta'''							) and device not in ["meta", torch.device('''meta'''							)] and value is None:
            raise ValueError(f'''{tensor_name} is on the meta device, we need a `value` to put in on {device}.'''							)

      __SCREAMING_SNAKE_CASE   :int						=  False
      __SCREAMING_SNAKE_CASE   :Any						=  False
      if is_buffer or not is_bitsandbytes_available():
            __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  False
            __SCREAMING_SNAKE_CASE   :Optional[int]						=  False
      else:
            __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  hasattr(bnb.nn ,   '''Params4bit'''							) and isinstance(module._parameters[tensor_name] ,   bnb.nn.Paramsabit							)
            __SCREAMING_SNAKE_CASE   :List[str]						=  isinstance(module._parameters[tensor_name] ,   bnb.nn.IntaParams							)

      if is_abit or is_abit:
            __SCREAMING_SNAKE_CASE   :str						=  module._parameters[tensor_name]
            if param.device.type != "cuda":
                  if value is None:
                        __SCREAMING_SNAKE_CASE   :str						=  old_value.to(a_							)
                  elif isinstance(a_ ,   torch.Tensor							):
                        __SCREAMING_SNAKE_CASE   :Dict						=  value.to('''cpu'''							)
                        if value.dtype == torch.inta:
                              __SCREAMING_SNAKE_CASE   :Tuple						=  version.parse(importlib.metadata.version('''bitsandbytes'''							)							) > version.parse(
                                  '''0.37.2'''							)
                              if not is_abit_serializable:
                                    raise ValueError(
                                        '''Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. '''
                                        '''Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.'''							)
                  else:
                        __SCREAMING_SNAKE_CASE   :str						=  torch.tensor(a_ ,   device='''cpu'''							)

                  # Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization.
                  # Since weights are saved in the correct "orientation", we skip transposing when loading.
                  if issubclass(module.source_cls ,   a_							) and fpaa_statistics is None:
                        __SCREAMING_SNAKE_CASE   :int						=  new_value.T

                  __SCREAMING_SNAKE_CASE   :Tuple						=  old_value.__dict__
                  if is_abit:
                        __SCREAMING_SNAKE_CASE   :str						=  bnb.nn.IntaParams(a_ ,   requires_grad=a_ ,   **a_							).to(a_							)
                  elif is_abit:
                        __SCREAMING_SNAKE_CASE   :List[Any]						=  bnb.nn.Paramsabit(a_ ,   requires_grad=a_ ,   **a_							).to(a_							)

                  __SCREAMING_SNAKE_CASE   :List[str]						=  new_value
                  if fpaa_statistics is not None:
                        setattr(module.weight ,   '''SCB''' ,   fpaa_statistics.to(a_							)							)

      else:
            if value is None:
                  __SCREAMING_SNAKE_CASE   :Optional[Any]						=  old_value.to(a_							)
            elif isinstance(a_ ,   torch.Tensor							):
                  __SCREAMING_SNAKE_CASE   :Tuple						=  value.to(a_							)
            else:
                  __SCREAMING_SNAKE_CASE   :Tuple						=  torch.tensor(a_ ,   device=a_							)

            if is_buffer:
                  __SCREAMING_SNAKE_CASE   :Optional[Any]						=  new_value
            else:
                  __SCREAMING_SNAKE_CASE   :List[Any]						=  nn.Parameter(a_ ,   requires_grad=old_value.requires_grad							)
                  __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  new_value



def      __lowerCamelCase   (							a_     :		Tuple ,   a_     :		Dict=None ,   a_     :		int=None ,   a_     :		List[str]=None ,   a_     :		int=False							)			->      Tuple:
      for name, module in model.named_children():
            if current_key_name is None:
                  __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  []
            current_key_name.append(a_							)

            if (isinstance(a_ ,   nn.Linear							) or isinstance(a_ ,   a_							)) and name not in modules_to_not_convert:
                  # Check if the current key is not in the `modules_to_not_convert`
                  if not any(key in '''.'''.join(a_							) for key in modules_to_not_convert							):
                        with init_empty_weights():
                              if isinstance(a_ ,   a_							):
                                    __SCREAMING_SNAKE_CASE				,__SCREAMING_SNAKE_CASE   :List[str]						=  module.weight.shape
                              else:
                                    __SCREAMING_SNAKE_CASE   :List[str]						=  module.in_features
                                    __SCREAMING_SNAKE_CASE   :str						=  module.out_features

                              if quantization_config.quantization_method() == "llm_int8":
                                    __SCREAMING_SNAKE_CASE   :Any						=  bnb.nn.LinearabitLt(
                                        a_ ,   a_ ,   module.bias is not None ,   has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight ,   threshold=quantization_config.llm_inta_threshold ,   )
                                    __SCREAMING_SNAKE_CASE   :Tuple						=  True
                              else:
                                    if (
                                        quantization_config.llm_inta_skip_modules is not None
                                        and name in quantization_config.llm_inta_skip_modules
                                    ):
                                          pass
                                    else:
                                          __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  bnb.nn.Linearabit(
                                              a_ ,   a_ ,   module.bias is not None ,   quantization_config.bnb_abit_compute_dtype ,   compress_statistics=quantization_config.bnb_abit_use_double_quant ,   quant_type=quantization_config.bnb_abit_quant_type ,   )
                                          __SCREAMING_SNAKE_CASE   :Optional[int]						=  True
                    # Store the module class in case we need to transpose the weight later
                              __SCREAMING_SNAKE_CASE   :str						=  type(a_							)
                              # Force requires grad to False to avoid unexpected errors
                              model._modules[name].requires_grad_(a_							)
            if len(list(module.children()							)							) > 0:
                  __SCREAMING_SNAKE_CASE				,__SCREAMING_SNAKE_CASE   :int						=  _replace_with_bnb_linear(
                      a_ ,   a_ ,   a_ ,   a_ ,   has_been_replaced=a_ ,   )
            # Remove the last key for recursion
            current_key_name.pop(-1							)
      return model, has_been_replaced



def      __lowerCamelCase   (							a_     :		Any ,   a_     :		List[Any]=None ,   a_     :		int=None ,   a_     :		Any=None							)			->      Tuple:
      __SCREAMING_SNAKE_CASE   :Tuple						=  ['''lm_head'''] if modules_to_not_convert is None else modules_to_not_convert
      __SCREAMING_SNAKE_CASE				,__SCREAMING_SNAKE_CASE   :str						=  _replace_with_bnb_linear(
          a_ ,   a_ ,   a_ ,   a_							)

      if not has_been_replaced:
            logger.warning(
                '''You are loading your model in 8bit or 4bit but no linear modules were found in your model.'''
                ''' Please double check your model architecture, or submit an issue on github if you think this is'''
                ''' a bug.'''							)

      return model



def      __lowerCamelCase   (							*a_     :		List[Any] ,   **a_     :		Any							)			->      Any:
      warnings.warn(
          '''`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead''' ,   a_ ,   )
      return replace_with_bnb_linear(*a_ ,   **a_							)



def      __lowerCamelCase   (							*a_     :		int ,   **a_     :		Tuple							)			->      List[Any]:
      warnings.warn(
          '''`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead''' ,   a_ ,   )
      return set_module_quantized_tensor_to_device(*a_ ,   **a_							)







def      __lowerCamelCase   (							a_     :		Any							)			->      Union[str, Any]:
      __SCREAMING_SNAKE_CASE   :int						=  deepcopy(a_							)  # this has 0 cost since it is done inside `init_empty_weights` context manager`
      tied_model.tie_weights()

      __SCREAMING_SNAKE_CASE   :List[str]						=  find_tied_parameters(a_							)
      # For compatibility with Accelerate < 0.18
      if isinstance(a_ ,   a_							):
            __SCREAMING_SNAKE_CASE   :Optional[Any]						=  sum(list(tied_params.values()							) ,   []							) + list(tied_params.keys()							)
      else:
            __SCREAMING_SNAKE_CASE   :str						=  sum(a_ ,   []							)
      __SCREAMING_SNAKE_CASE   :List[str]						=  len(a_							) > 0

      # Check if it is a base model
      __SCREAMING_SNAKE_CASE   :str						=  not hasattr(a_ ,   model.base_model_prefix							)

      # Ignore this for base models (BertModel, GPT2Model, etc.)
      if (not has_tied_params) and is_base_model:
            return []

      # otherwise they have an attached head
      __SCREAMING_SNAKE_CASE   :int						=  list(model.named_children()							)
      __SCREAMING_SNAKE_CASE   :Optional[Any]						=  [list_modules[-1][0]]

      # add last module together with tied weights
      __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  set(a_							) - set(a_							)
      __SCREAMING_SNAKE_CASE   :Optional[int]						=  list(set(a_							)							) + list(a_							)

      # remove ".weight" from the keys
      __SCREAMING_SNAKE_CASE   :Optional[int]						=  ['''.weight''', '''.bias''']
      __SCREAMING_SNAKE_CASE   :str						=  []
      for name in list_untouched:
            for name_to_remove in names_to_remove:
                  if name_to_remove in name:
                        __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  name.replace(a_ ,   ''''''							)
            filtered_module_names.append(a_							)

      return filtered_module_names






"""simple docstring"""
from __future__ import annotations

import copy
import tempfile
import unittest

from transformers import CONFIG_MAPPING, AutoConfig, BertConfig, GPTaConfig, TaConfig, TapasConfig, is_tf_available
from transformers.testing_utils import (
    DUMMY_UNKNOWN_IDENTIFIER,
    SMALL_MODEL_IDENTIFIER,
    RequestCounter,
    require_tensorflow_probability,
    require_tf,
    slow,
)

from ..bert.test_modeling_bert import BertModelTester


if is_tf_available():
  from transformers import (
      TFAutoModel,
      TFAutoModelForCausalLM,
      TFAutoModelForMaskedLM,
      TFAutoModelForPreTraining,
      TFAutoModelForQuestionAnswering,
      TFAutoModelForSeqaSeqLM,
      TFAutoModelForSequenceClassification,
      TFAutoModelForTableQuestionAnswering,
      TFAutoModelForTokenClassification,
      TFAutoModelWithLMHead,
      TFBertForMaskedLM,
      TFBertForPreTraining,
      TFBertForQuestionAnswering,
      TFBertForSequenceClassification,
      TFBertModel,
      TFFunnelBaseModel,
      TFFunnelModel,
      TFGPTaLMHeadModel,
      TFRobertaForMaskedLM,
      TFTaForConditionalGeneration,
      TFTapasForQuestionAnswering,
  )
  from transformers.models.auto.modeling_tf_auto import (
      TF_MODEL_FOR_CAUSAL_LM_MAPPING,
      TF_MODEL_FOR_MASKED_LM_MAPPING,
      TF_MODEL_FOR_PRETRAINING_MAPPING,
      TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
      TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
      TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
      TF_MODEL_MAPPING,
  )
  from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST
  from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST
  from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST
  from transformers.models.tapas.modeling_tf_tapas import TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST






class 					_SCREAMING_SNAKE_CASE(   A  ):
       SCREAMING_SNAKE_CASE_   :      int							=  '''new-model'''


if is_tf_available():






  class 					_SCREAMING_SNAKE_CASE(   A  ):
         SCREAMING_SNAKE_CASE_   :      Union[str, Any]							=  NewModelConfig






@require_tf
class 					_SCREAMING_SNAKE_CASE(   unittest.TestCase  ):




       @slow
       def     _UpperCamelCase     (						self							)			->      List[str]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :Tuple						=  '''bert-base-cased'''
             __SCREAMING_SNAKE_CASE   :int						=  AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__							)
             self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
             self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :List[str]						=  TFAutoModel.from_pretrained(SCREAMING_SNAKE_CASE__							)
             self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
             self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)




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





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :Tuple						=  '''bert-base-cased'''
             __SCREAMING_SNAKE_CASE   :List[str]						=  AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__							)
             self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
             self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :str						=  TFAutoModelForPreTraining.from_pretrained(SCREAMING_SNAKE_CASE__							)
             self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
             self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)




       @slow
       def     _UpperCamelCase     (						self							)			->      Dict:





             """simple docstring"""






             for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   __SCREAMING_SNAKE_CASE   :List[str]						=  AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

                   __SCREAMING_SNAKE_CASE   :Optional[int]						=  TFAutoModelForCausalLM.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   __SCREAMING_SNAKE_CASE				,__SCREAMING_SNAKE_CASE   :Dict						=  TFAutoModelForCausalLM.from_pretrained(SCREAMING_SNAKE_CASE__		,output_loading_info=SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)




       @slow
       def     _UpperCamelCase     (						self							)			->      int:





             """simple docstring"""






             for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   __SCREAMING_SNAKE_CASE   :List[str]						=  AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

                   __SCREAMING_SNAKE_CASE   :Any						=  TFAutoModelWithLMHead.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)




       @slow
       def     _UpperCamelCase     (						self							)			->      Optional[int]:





             """simple docstring"""






             for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

                   __SCREAMING_SNAKE_CASE   :Tuple						=  TFAutoModelForMaskedLM.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   __SCREAMING_SNAKE_CASE				,__SCREAMING_SNAKE_CASE   :Tuple						=  TFAutoModelForMaskedLM.from_pretrained(SCREAMING_SNAKE_CASE__		,output_loading_info=SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)




       @slow
       def     _UpperCamelCase     (						self							)			->      Dict:





             """simple docstring"""






             for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   __SCREAMING_SNAKE_CASE   :Optional[Any]						=  AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

                   __SCREAMING_SNAKE_CASE   :str						=  TFAutoModelForSeqaSeqLM.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   __SCREAMING_SNAKE_CASE				,__SCREAMING_SNAKE_CASE   :Optional[int]						=  TFAutoModelForSeqaSeqLM.from_pretrained(SCREAMING_SNAKE_CASE__		,output_loading_info=SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)




       @slow
       def     _UpperCamelCase     (						self							)			->      Tuple:





             """simple docstring"""






             for model_name in ["bert-base-uncased"]:
                   __SCREAMING_SNAKE_CASE   :Optional[int]						=  AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

                   __SCREAMING_SNAKE_CASE   :List[str]						=  TFAutoModelForSequenceClassification.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)




       @slow
       def     _UpperCamelCase     (						self							)			->      Tuple:





             """simple docstring"""






             for model_name in ["bert-base-uncased"]:
                   __SCREAMING_SNAKE_CASE   :Optional[int]						=  AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

                   __SCREAMING_SNAKE_CASE   :Optional[Any]						=  TFAutoModelForQuestionAnswering.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)




       @slow
       @require_tensorflow_probability
       def     _UpperCamelCase     (						self							)			->      int:





             """simple docstring"""






             for model_name in TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST[5:6]:
                   __SCREAMING_SNAKE_CASE   :int						=  AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

                   __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  TFAutoModelForTableQuestionAnswering.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   __SCREAMING_SNAKE_CASE				,__SCREAMING_SNAKE_CASE   :Optional[int]						=  TFAutoModelForTableQuestionAnswering.from_pretrained(
                       SCREAMING_SNAKE_CASE__		,output_loading_info=SCREAMING_SNAKE_CASE__							)
                   self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)




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





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :int						=  TFAutoModelWithLMHead.from_pretrained(SCREAMING_SNAKE_CASE__							)
             self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)
             self.assertEqual(model.num_parameters()		,1_44_10							)
             self.assertEqual(model.num_parameters(only_trainable=SCREAMING_SNAKE_CASE__							)		,1_44_10							)




       def     _UpperCamelCase     (						self							)			->      str:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  TFAutoModelWithLMHead.from_pretrained(SCREAMING_SNAKE_CASE__							)
             self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)
             self.assertEqual(model.num_parameters()		,1_44_10							)
             self.assertEqual(model.num_parameters(only_trainable=SCREAMING_SNAKE_CASE__							)		,1_44_10							)




       def     _UpperCamelCase     (						self							)			->      Tuple:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  TFAutoModel.from_pretrained('''sgugger/funnel-random-tiny'''							)
             self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :str						=  copy.deepcopy(model.config							)
             __SCREAMING_SNAKE_CASE   :List[str]						=  ['''FunnelBaseModel''']
             __SCREAMING_SNAKE_CASE   :int						=  TFAutoModel.from_config(SCREAMING_SNAKE_CASE__							)
             self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

             with tempfile.TemporaryDirectory() as tmp_dir:
                   model.save_pretrained(SCREAMING_SNAKE_CASE__							)
                   __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  TFAutoModel.from_pretrained(SCREAMING_SNAKE_CASE__							)
                   self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)




       def     _UpperCamelCase     (						self							)			->      Optional[Any]:





             """simple docstring"""






             try:
                   AutoConfig.register('''new-model'''		,SCREAMING_SNAKE_CASE__							)

                   __SCREAMING_SNAKE_CASE   :Tuple						=  [
                       TFAutoModel,
                       TFAutoModelForCausalLM,
                       TFAutoModelForMaskedLM,
                       TFAutoModelForPreTraining,
                       TFAutoModelForQuestionAnswering,
                       TFAutoModelForSequenceClassification,
                       TFAutoModelForTokenClassification,
                   ]

                   for auto_class in auto_classes:
                         with self.subTest(auto_class.__name__							):
                               # Wrong config class will raise an error
                               with self.assertRaises(SCREAMING_SNAKE_CASE__							):
                                     auto_class.register(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)
                               auto_class.register(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)
                               # Trying to register something existing in the Transformers library will raise an error
                               with self.assertRaises(SCREAMING_SNAKE_CASE__							):
                                     auto_class.register(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

                               # Now that the config is registered, it can be used as any other config with the auto-API
                               __SCREAMING_SNAKE_CASE   :Any						=  BertModelTester(self							).get_config()
                               __SCREAMING_SNAKE_CASE   :Dict						=  NewModelConfig(**tiny_config.to_dict()							)
                               __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  auto_class.from_config(SCREAMING_SNAKE_CASE__							)
                               self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

                               with tempfile.TemporaryDirectory() as tmp_dir:
                                     model.save_pretrained(SCREAMING_SNAKE_CASE__							)
                                     __SCREAMING_SNAKE_CASE   :str						=  auto_class.from_pretrained(SCREAMING_SNAKE_CASE__							)
                                     self.assertIsInstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

             finally:
                   if "new-model" in CONFIG_MAPPING._extra_content:
                         del CONFIG_MAPPING._extra_content["new-model"]
                   for mapping in (
                       TF_MODEL_MAPPING,
                       TF_MODEL_FOR_PRETRAINING_MAPPING,
                       TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
                       TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
                       TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
                       TF_MODEL_FOR_CAUSAL_LM_MAPPING,
                       TF_MODEL_FOR_MASKED_LM_MAPPING,
                   ):
                         if NewModelConfig in mapping._extra_content:
                               del mapping._extra_content[NewModelConfig]




       def     _UpperCamelCase     (						self							)			->      int:





             """simple docstring"""






             with self.assertRaisesRegex(
                 SCREAMING_SNAKE_CASE__		,'''bert-base is not a local folder and is not a valid model identifier'''							):
                   __SCREAMING_SNAKE_CASE   :int						=  TFAutoModel.from_pretrained('''bert-base'''							)




       def     _UpperCamelCase     (						self							)			->      Any:





             """simple docstring"""






             with self.assertRaisesRegex(
                 SCREAMING_SNAKE_CASE__		,R'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'''							):
                   __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  TFAutoModel.from_pretrained(SCREAMING_SNAKE_CASE__		,revision='''aaaaaa'''							)




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





             """simple docstring"""






             with self.assertRaisesRegex(
                 SCREAMING_SNAKE_CASE__		,'''hf-internal-testing/config-no-model does not appear to have a file named pytorch_model.bin'''		,):
                   __SCREAMING_SNAKE_CASE   :Optional[Any]						=  TFAutoModel.from_pretrained('''hf-internal-testing/config-no-model'''							)




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





             """simple docstring"""






             with self.assertRaisesRegex(SCREAMING_SNAKE_CASE__		,'''Use `from_pt=True` to load this model'''							):
                   __SCREAMING_SNAKE_CASE   :List[str]						=  TFAutoModel.from_pretrained('''hf-internal-testing/tiny-bert-pt-only'''							)




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





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :int						=  TFAutoModel.from_pretrained('''hf-internal-testing/tiny-random-bert'''							)
             with RequestCounter() as counter:
                   __SCREAMING_SNAKE_CASE   :int						=  TFAutoModel.from_pretrained('''hf-internal-testing/tiny-random-bert'''							)
                   self.assertEqual(counter.get_request_count		,0							)
                   self.assertEqual(counter.head_request_count		,1							)
                   self.assertEqual(counter.other_request_count		,0							)

             # With a sharded checkpoint
             __SCREAMING_SNAKE_CASE   :Dict						=  TFAutoModel.from_pretrained('''ArthurZ/tiny-random-bert-sharded'''							)
             with RequestCounter() as counter:
                   __SCREAMING_SNAKE_CASE   :Optional[Any]						=  TFAutoModel.from_pretrained('''ArthurZ/tiny-random-bert-sharded'''							)
                   self.assertEqual(counter.get_request_count		,0							)
                   self.assertEqual(counter.head_request_count		,1							)
                   self.assertEqual(counter.other_request_count		,0							)