




import inspect
import unittest

from transformers import YolosConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch
 from torch import nn

 from transformers import YolosForObjectDetection, YolosModel
 from transformers.models.yolos.modeling_yolos import YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import AutoImageProcessor







class 						A:



 '''simple docstring'''


 def __init__(       self      :						Dict		,							A_      :						List[Any]		,							A_      :						Any=13		,							A_      :						Union[str, Any]=[30, 30]		,							A_      :						str=2		,							A_      :						Tuple=3		,							A_      :						int=True		,							A_      :						Tuple=True		,							A_      :						Union[str, Any]=32		,							A_      :						str=5		,							A_      :						List[Any]=4		,							A_      :						Optional[int]=37		,							A_      :						List[Any]="gelu"		,							A_      :						int=0.1		,							A_      :						List[Any]=0.1		,							A_      :						Optional[int]=10		,							A_      :						List[Any]=0.02		,							A_      :						List[Any]=3		,							A_      :						Dict=None		,							A_      :						Optional[Any]=8		,							A_      :						List[str]=10		,							)     ->			str:

       """simple docstring"""






       lowerCamelCase_	  =					parent
       lowerCamelCase_	  =					batch_size
       lowerCamelCase_	  =					image_size
       lowerCamelCase_	  =					patch_size
       lowerCamelCase_	  =					num_channels
       lowerCamelCase_	  =					is_training
       lowerCamelCase_	  =					use_labels
       lowerCamelCase_	  =					hidden_size
       lowerCamelCase_	  =					num_hidden_layers
       lowerCamelCase_	  =					num_attention_heads
       lowerCamelCase_	  =					intermediate_size
       lowerCamelCase_	  =					hidden_act
       lowerCamelCase_	  =					hidden_dropout_prob
       lowerCamelCase_	  =					attention_probs_dropout_prob
       lowerCamelCase_	  =					type_sequence_label_size
       lowerCamelCase_	  =					initializer_range
       lowerCamelCase_	  =					num_labels
       lowerCamelCase_	  =					scope
       lowerCamelCase_	  =					n_targets
       lowerCamelCase_	  =					num_detection_tokens
       # we set the expected sequence length (which is used in several tests)
       # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) + num_detection_tokens
       lowerCamelCase_	  =					(image_size[1] // patch_size) * (image_size[0] // patch_size)
       lowerCamelCase_	  =					num_patches + 1 + self.num_detection_tokens

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

       """simple docstring"""






       lowerCamelCase_	  =					floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]						)

       lowerCamelCase_	  =					None
       if self.use_labels:
             # labels is a list of Dict (each Dict being the labels for a given example in the batch)
             lowerCamelCase_	  =					[]
             for i in range(self.batch_size						):
                   lowerCamelCase_	  =					{}
                   lowerCamelCase_	  =					torch.randint(
                       high=self.num_labels		,							size=(self.n_targets,)		,							device=_UpperCamelCase						)
                   lowerCamelCase_	  =					torch.rand(self.n_targets		,							4		,							device=_UpperCamelCase						)
                   labels.append(_UpperCamelCase						)

       lowerCamelCase_	  =					self.get_config()

       return config, pixel_values, labels

 def        a__				(       self      :						Any						)     ->			str:

       """simple docstring"""






       return YolosConfig(
           image_size=self.image_size		,							patch_size=self.patch_size		,							num_channels=self.num_channels		,							hidden_size=self.hidden_size		,							num_hidden_layers=self.num_hidden_layers		,							num_attention_heads=self.num_attention_heads		,							intermediate_size=self.intermediate_size		,							hidden_act=self.hidden_act		,							hidden_dropout_prob=self.hidden_dropout_prob		,							attention_probs_dropout_prob=self.attention_probs_dropout_prob		,							is_decoder=_UpperCamelCase		,							initializer_range=self.initializer_range		,							num_detection_tokens=self.num_detection_tokens		,							num_labels=self.num_labels		,							)

 def        a__				(       self      :						Dict		,							A_      :						Optional[Any]		,							A_      :						int		,							A_      :						Optional[Any]						)     ->			List[str]:

       """simple docstring"""






       lowerCamelCase_	  =					YolosModel(config=_UpperCamelCase						)
       model.to(_UpperCamelCase						)
       model.eval()
       lowerCamelCase_	  =					model(_UpperCamelCase						)
       self.parent.assertEqual(
           result.last_hidden_state.shape		,							(self.batch_size, self.expected_seq_len, self.hidden_size)						)

 def        a__				(       self      :						Dict		,							A_      :						Optional[int]		,							A_      :						Optional[int]		,							A_      :						List[Any]						)     ->			Optional[Any]:

       """simple docstring"""






       lowerCamelCase_	  =					YolosForObjectDetection(_UpperCamelCase						)
       model.to(_UpperCamelCase						)
       model.eval()

       lowerCamelCase_	  =					model(pixel_values=_UpperCamelCase						)
       lowerCamelCase_	  =					model(_UpperCamelCase						)

       self.parent.assertEqual(result.logits.shape		,							(self.batch_size, self.num_detection_tokens, self.num_labels + 1)						)
       self.parent.assertEqual(result.pred_boxes.shape		,							(self.batch_size, self.num_detection_tokens, 4)						)

       lowerCamelCase_	  =					model(pixel_values=_UpperCamelCase		,							labels=_UpperCamelCase						)

       self.parent.assertEqual(result.loss.shape		,							()						)
       self.parent.assertEqual(result.logits.shape		,							(self.batch_size, self.num_detection_tokens, self.num_labels + 1)						)
       self.parent.assertEqual(result.pred_boxes.shape		,							(self.batch_size, self.num_detection_tokens, 4)						)





 def        a__				(       self      :						Tuple						)     ->			List[str]:

       """simple docstring"""






       lowerCamelCase_	  =					self.prepare_config_and_inputs()
       lowerCamelCase_	  =					config_and_inputs
       lowerCamelCase_	  =					{"""pixel_values""": pixel_values}
       return config, inputs_dict







@require_torch
class 						A(		__lowerCAmelCase							,   __lowerCAmelCase							,   unittest.TestCase     ):



 '''simple docstring'''


 UpperCamelCase		     =		(YolosModel, YolosForObjectDetection) if is_torch_available() else ()
 UpperCamelCase		     =		(
     {'''feature-extraction''': YolosModel, '''object-detection''': YolosForObjectDetection} if is_torch_available() else {}
 )

 UpperCamelCase		     =		False
 UpperCamelCase		     =		False
 UpperCamelCase		     =		False
 UpperCamelCase		     =		False

 def        a__				(       self      :						str		,							A_      :						List[str]		,							A_      :						Optional[Any]		,							A_      :						Dict=False						)     ->			Optional[int]:

       """simple docstring"""






       lowerCamelCase_	  =					super()._prepare_for_class(_UpperCamelCase		,							_UpperCamelCase		,							return_labels=_UpperCamelCase						)

       if return_labels:
             if model_class.__name__ == "YolosForObjectDetection":
                   lowerCamelCase_	  =					[]
                   for i in range(self.model_tester.batch_size						):
                         lowerCamelCase_	  =					{}
                         lowerCamelCase_	  =					torch.ones(
                             size=(self.model_tester.n_targets,)		,							device=_UpperCamelCase		,							dtype=torch.long						)
                         lowerCamelCase_	  =					torch.ones(
                             self.model_tester.n_targets		,							4		,							device=_UpperCamelCase		,							dtype=torch.float						)
                         labels.append(_UpperCamelCase						)
                   lowerCamelCase_	  =					labels

       return inputs_dict

 def        a__				(       self      :						int						)     ->			Dict:

       """simple docstring"""






       lowerCamelCase_	  =					YolosModelTester(self						)
       lowerCamelCase_	  =					ConfigTester(self		,							config_class=_UpperCamelCase		,							has_text_modality=_UpperCamelCase		,							hidden_size=37						)

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

       """simple docstring"""






       self.config_tester.run_common_tests()

 def        a__				(       self      :						Optional[Any]						)     ->			str:

       """simple docstring"""






       pass

 def        a__				(       self      :						Union[str, Any]						)     ->			Tuple:

       """simple docstring"""






       lowerCamelCase_	  =					self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
             lowerCamelCase_	  =					model_class(_UpperCamelCase						)
             self.assertIsInstance(model.get_input_embeddings()		,							(nn.Module)						)
             lowerCamelCase_	  =					model.get_output_embeddings()
             self.assertTrue(x is None or isinstance(_UpperCamelCase		,							nn.Linear						)						)

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

       """simple docstring"""






       lowerCamelCase_	  =					self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
             lowerCamelCase_	  =					model_class(_UpperCamelCase						)
             lowerCamelCase_	  =					inspect.signature(model.forward						)
             # signature.parameters is an OrderedDict => so arg_names order is deterministic
             lowerCamelCase_	  =					[*signature.parameters.keys()]

             lowerCamelCase_	  =					["""pixel_values"""]
             self.assertListEqual(arg_names[:1]		,							_UpperCamelCase						)

 def        a__				(       self      :						List[str]						)     ->			Any:

       """simple docstring"""






       lowerCamelCase_	  =					self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*_UpperCamelCase						)

 def        a__				(       self      :						Tuple						)     ->			Union[str, Any]:

       """simple docstring"""






       lowerCamelCase_	  =					self.model_tester.prepare_config_and_inputs_for_common()
       lowerCamelCase_	  =					True

       # in YOLOS, the seq_len is different
       lowerCamelCase_	  =					self.model_tester.expected_seq_len
       for model_class in self.all_model_classes:
             lowerCamelCase_	  =					True
             lowerCamelCase_	  =					False
             lowerCamelCase_	  =					True
             lowerCamelCase_	  =					model_class(_UpperCamelCase						)
             model.to(_UpperCamelCase						)
             model.eval()
             with torch.no_grad():
                   lowerCamelCase_	  =					model(**self._prepare_for_class(_UpperCamelCase		,							_UpperCamelCase						)						)
             lowerCamelCase_	  =					outputs.attentions
             self.assertEqual(len(_UpperCamelCase						)		,							self.model_tester.num_hidden_layers						)

             # check that output_attentions also work using config
             del inputs_dict["output_attentions"]
             lowerCamelCase_	  =					True
             lowerCamelCase_	  =					model_class(_UpperCamelCase						)
             model.to(_UpperCamelCase						)
             model.eval()
             with torch.no_grad():
                   lowerCamelCase_	  =					model(**self._prepare_for_class(_UpperCamelCase		,							_UpperCamelCase						)						)
             lowerCamelCase_	  =					outputs.attentions
             self.assertEqual(len(_UpperCamelCase						)		,							self.model_tester.num_hidden_layers						)

             self.assertListEqual(
                 list(attentions[0].shape[-3:]						)		,							[self.model_tester.num_attention_heads, seq_len, seq_len]		,							)
             lowerCamelCase_	  =					len(_UpperCamelCase						)

             # Check attention is always last and order is fine
             lowerCamelCase_	  =					True
             lowerCamelCase_	  =					True
             lowerCamelCase_	  =					model_class(_UpperCamelCase						)
             model.to(_UpperCamelCase						)
             model.eval()
             with torch.no_grad():
                   lowerCamelCase_	  =					model(**self._prepare_for_class(_UpperCamelCase		,							_UpperCamelCase						)						)

             lowerCamelCase_	  =					1
             self.assertEqual(out_len + added_hidden_states		,							len(_UpperCamelCase						)						)

             lowerCamelCase_	  =					outputs.attentions

             self.assertEqual(len(_UpperCamelCase						)		,							self.model_tester.num_hidden_layers						)
             self.assertListEqual(
                 list(self_attentions[0].shape[-3:]						)		,							[self.model_tester.num_attention_heads, seq_len, seq_len]		,							)

 def        a__				(       self      :						Tuple						)     ->			Any:

       """simple docstring"""






       def check_hidden_states_output(A_      :						Union[str, Any]		,							A_      :						Optional[int]		,							A_      :						int						):
             lowerCamelCase_	  =					model_class(_UpperCamelCase						)
             model.to(_UpperCamelCase						)
             model.eval()

             with torch.no_grad():
                   lowerCamelCase_	  =					model(**self._prepare_for_class(_UpperCamelCase		,							_UpperCamelCase						)						)

             lowerCamelCase_	  =					outputs.hidden_states

             lowerCamelCase_	  =					getattr(
                 self.model_tester		,							'expected_num_hidden_layers'		,							self.model_tester.num_hidden_layers + 1						)
             self.assertEqual(len(_UpperCamelCase						)		,							_UpperCamelCase						)

             # YOLOS has a different seq_length
             lowerCamelCase_	  =					self.model_tester.expected_seq_len

             self.assertListEqual(
                 list(hidden_states[0].shape[-2:]						)		,							[seq_length, self.model_tester.hidden_size]		,							)

       lowerCamelCase_	  =					self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
             lowerCamelCase_	  =					True
             check_hidden_states_output(_UpperCamelCase		,							_UpperCamelCase		,							_UpperCamelCase						)

             # check that output_hidden_states also work using config
             del inputs_dict["output_hidden_states"]
             lowerCamelCase_	  =					True

             check_hidden_states_output(_UpperCamelCase		,							_UpperCamelCase		,							_UpperCamelCase						)

 def        a__				(       self      :						int						)     ->			List[Any]:

       """simple docstring"""






       lowerCamelCase_	  =					self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_object_detection(*_UpperCamelCase						)





 @slow
 def        a__				(       self      :						List[Any]						)     ->			Optional[int]:

       """simple docstring"""






       for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             lowerCamelCase_	  =					YolosModel.from_pretrained(_UpperCamelCase						)
             self.assertIsNotNone(_UpperCamelCase						)

def     _SCREAMING_SNAKE_CASE    (							)     ->   Any:


      '''simple docstring'''



      lowerCamelCase_	  =					Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'  )
      return image







@require_torch
@require_vision
class 						A(		unittest.TestCase     ):



 '''simple docstring'''


 @cached_property
 def        a__				(       self      :						Any						)     ->			List[str]:

       """simple docstring"""






       return AutoImageProcessor.from_pretrained('hustvl/yolos-small'						) if is_vision_available() else None





 @slow
 def        a__				(       self      :						Union[str, Any]						)     ->			Dict:

       """simple docstring"""






       lowerCamelCase_	  =					YolosForObjectDetection.from_pretrained('hustvl/yolos-small'						).to(_UpperCamelCase						)

       lowerCamelCase_	  =					self.default_image_processor
       lowerCamelCase_	  =					prepare_img()
       lowerCamelCase_	  =					image_processor(images=_UpperCamelCase		,							return_tensors='pt'						).to(_UpperCamelCase						)

       # forward pass
       with torch.no_grad():
             lowerCamelCase_	  =					model(inputs.pixel_values						)

       # verify outputs
       lowerCamelCase_	  =					torch.Size((1, 100, 92)						)
       self.assertEqual(outputs.logits.shape		,							_UpperCamelCase						)

       lowerCamelCase_	  =					torch.tensor(
           [[-24.0248, -10.3024, -14.8290], [-42.0392, -16.8200, -27.4334], [-27.2743, -11.8154, -18.7148]]		,							device=_UpperCamelCase		,							)
       lowerCamelCase_	  =					torch.tensor(
           [[0.2559, 0.5455, 0.4706], [0.2989, 0.7279, 0.1875], [0.7732, 0.4017, 0.4462]]		,							device=_UpperCamelCase						)
       self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]		,							_UpperCamelCase		,							atol=1E-4						)						)
       self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3]		,							_UpperCamelCase		,							atol=1E-4						)						)

       # verify postprocessing
       lowerCamelCase_	  =					image_processor.post_process_object_detection(
           _UpperCamelCase		,							threshold=0.3		,							target_sizes=[image.size[::-1]]						)[0]
       lowerCamelCase_	  =					torch.tensor([0.9994, 0.9790, 0.9964, 0.9972, 0.9861]						).to(_UpperCamelCase						)
       lowerCamelCase_	  =					[75, 75, 17, 63, 17]
       lowerCamelCase_	  =					torch.tensor([335.0609, 79.3848, 375.4216, 187.2495]						).to(_UpperCamelCase						)

       self.assertEqual(len(results['scores']						)		,							5						)
       self.assertTrue(torch.allclose(results['scores']		,							_UpperCamelCase		,							atol=1E-4						)						)
       self.assertSequenceEqual(results['labels'].tolist()		,							_UpperCamelCase						)
       self.assertTrue(torch.allclose(results['boxes'][0, :]		,							_UpperCamelCase						)						)









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 						A(		UpperCamelCase     ):



 '''simple docstring'''


 UpperCamelCase		     =		'''new-model'''


if is_tf_available():







 class 						A(		UpperCamelCase     ):



  '''simple docstring'''


  UpperCamelCase		     =		NewModelConfig







@require_tf
class 						A(		unittest.TestCase     ):



 '''simple docstring'''


 @slow
 def        a__				(       self      :						str						)     ->			Union[str, Any]:

       """simple docstring"""






       lowerCamelCase_	  =					'bert-base-cased'
       lowerCamelCase_	  =					AutoConfig.from_pretrained(A_						)
       self.assertIsNotNone(A_						)
       self.assertIsInstance(A_		,							A_						)

       lowerCamelCase_	  =					TFAutoModel.from_pretrained(A_						)
       self.assertIsNotNone(A_						)
       self.assertIsInstance(A_		,							A_						)

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

       """simple docstring"""






       lowerCamelCase_	  =					'bert-base-cased'
       lowerCamelCase_	  =					AutoConfig.from_pretrained(A_						)
       self.assertIsNotNone(A_						)
       self.assertIsInstance(A_		,							A_						)

       lowerCamelCase_	  =					TFAutoModelForPreTraining.from_pretrained(A_						)
       self.assertIsNotNone(A_						)
       self.assertIsInstance(A_		,							A_						)

 @slow
 def        a__				(       self      :						Union[str, Any]						)     ->			str:

       """simple docstring"""






       for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             lowerCamelCase_	  =					AutoConfig.from_pretrained(A_						)
             self.assertIsNotNone(A_						)
             self.assertIsInstance(A_		,							A_						)

             lowerCamelCase_	  =					TFAutoModelForCausalLM.from_pretrained(A_						)
             lowerCamelCase_  ,       lowerCamelCase_	  =					TFAutoModelForCausalLM.from_pretrained(A_		,							output_loading_info=A_						)
             self.assertIsNotNone(A_						)
             self.assertIsInstance(A_		,							A_						)

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

       """simple docstring"""






       for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             lowerCamelCase_	  =					AutoConfig.from_pretrained(A_						)
             self.assertIsNotNone(A_						)
             self.assertIsInstance(A_		,							A_						)

             lowerCamelCase_	  =					TFAutoModelWithLMHead.from_pretrained(A_						)
             self.assertIsNotNone(A_						)
             self.assertIsInstance(A_		,							A_						)

 @slow
 def        a__				(       self      :						int						)     ->			str:

       """simple docstring"""






       for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             lowerCamelCase_	  =					AutoConfig.from_pretrained(A_						)
             self.assertIsNotNone(A_						)
             self.assertIsInstance(A_		,							A_						)

             lowerCamelCase_	  =					TFAutoModelForMaskedLM.from_pretrained(A_						)
             lowerCamelCase_  ,       lowerCamelCase_	  =					TFAutoModelForMaskedLM.from_pretrained(A_		,							output_loading_info=A_						)
             self.assertIsNotNone(A_						)
             self.assertIsInstance(A_		,							A_						)

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

       """simple docstring"""






       for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             lowerCamelCase_	  =					AutoConfig.from_pretrained(A_						)
             self.assertIsNotNone(A_						)
             self.assertIsInstance(A_		,							A_						)

             lowerCamelCase_	  =					TFAutoModelForSeqaSeqLM.from_pretrained(A_						)
             lowerCamelCase_  ,       lowerCamelCase_	  =					TFAutoModelForSeqaSeqLM.from_pretrained(A_		,							output_loading_info=A_						)
             self.assertIsNotNone(A_						)
             self.assertIsInstance(A_		,							A_						)

 @slow
 def        a__				(       self      :						Tuple						)     ->			str:

       """simple docstring"""






       for model_name in ["bert-base-uncased"]:
             lowerCamelCase_	  =					AutoConfig.from_pretrained(A_						)
             self.assertIsNotNone(A_						)
             self.assertIsInstance(A_		,							A_						)

             lowerCamelCase_	  =					TFAutoModelForSequenceClassification.from_pretrained(A_						)
             self.assertIsNotNone(A_						)
             self.assertIsInstance(A_		,							A_						)

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

       """simple docstring"""






       for model_name in ["bert-base-uncased"]:
             lowerCamelCase_	  =					AutoConfig.from_pretrained(A_						)
             self.assertIsNotNone(A_						)
             self.assertIsInstance(A_		,							A_						)

             lowerCamelCase_	  =					TFAutoModelForQuestionAnswering.from_pretrained(A_						)
             self.assertIsNotNone(A_						)
             self.assertIsInstance(A_		,							A_						)

 @slow
 @require_tensorflow_probability
 def        a__				(       self      :						int						)     ->			Union[str, Any]:

       """simple docstring"""






       for model_name in TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST[5:6]:
             lowerCamelCase_	  =					AutoConfig.from_pretrained(A_						)
             self.assertIsNotNone(A_						)
             self.assertIsInstance(A_		,							A_						)

             lowerCamelCase_	  =					TFAutoModelForTableQuestionAnswering.from_pretrained(A_						)
             lowerCamelCase_  ,       lowerCamelCase_	  =					TFAutoModelForTableQuestionAnswering.from_pretrained(
                 A_		,							output_loading_info=A_						)
             self.assertIsNotNone(A_						)
             self.assertIsInstance(A_		,							A_						)

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

       """simple docstring"""






       lowerCamelCase_	  =					TFAutoModelWithLMHead.from_pretrained(A_						)
       self.assertIsInstance(A_		,							A_						)
       self.assertEqual(model.num_parameters()		,							14410						)
       self.assertEqual(model.num_parameters(only_trainable=A_						)		,							14410						)

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

       """simple docstring"""






       lowerCamelCase_	  =					TFAutoModelWithLMHead.from_pretrained(A_						)
       self.assertIsInstance(A_		,							A_						)
       self.assertEqual(model.num_parameters()		,							14410						)
       self.assertEqual(model.num_parameters(only_trainable=A_						)		,							14410						)

 def        a__				(       self      :						Tuple						)     ->			Optional[Any]:

       """simple docstring"""






       lowerCamelCase_	  =					TFAutoModel.from_pretrained('sgugger/funnel-random-tiny'						)
       self.assertIsInstance(A_		,							A_						)

       lowerCamelCase_	  =					copy.deepcopy(model.config						)
       lowerCamelCase_	  =					['FunnelBaseModel']
       lowerCamelCase_	  =					TFAutoModel.from_config(A_						)
       self.assertIsInstance(A_		,							A_						)

       with tempfile.TemporaryDirectory() as tmp_dir:
             model.save_pretrained(A_						)
             lowerCamelCase_	  =					TFAutoModel.from_pretrained(A_						)
             self.assertIsInstance(A_		,							A_						)

 def        a__				(       self      :						Any						)     ->			Tuple:

       """simple docstring"""






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

             lowerCamelCase_	  =					[
                 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(A_						):
                               auto_class.register(A_		,							A_						)
                         auto_class.register(A_		,							A_						)
                         # Trying to register something existing in the Transformers library will raise an error
                         with self.assertRaises(A_						):
                               auto_class.register(A_		,							A_						)

                         # Now that the config is registered, it can be used as any other config with the auto-API
                         lowerCamelCase_	  =					BertModelTester(self						).get_config()
                         lowerCamelCase_	  =					NewModelConfig(**tiny_config.to_dict()						)
                         lowerCamelCase_	  =					auto_class.from_config(A_						)
                         self.assertIsInstance(A_		,							A_						)

                         with tempfile.TemporaryDirectory() as tmp_dir:
                               model.save_pretrained(A_						)
                               lowerCamelCase_	  =					auto_class.from_pretrained(A_						)
                               self.assertIsInstance(A_		,							A_						)

       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        a__				(       self      :						int						)     ->			int:

       """simple docstring"""






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

 def        a__				(       self      :						Any						)     ->			Dict:

       """simple docstring"""






       with self.assertRaisesRegex(
           A_		,							r'aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'						):
             lowerCamelCase_	  =					TFAutoModel.from_pretrained(A_		,							revision='aaaaaa'						)

 def        a__				(       self      :						str						)     ->			int:

       """simple docstring"""






       with self.assertRaisesRegex(
           A_		,							'hf-internal-testing/config-no-model does not appear to have a file named pytorch_model.bin'		,							):
             lowerCamelCase_	  =					TFAutoModel.from_pretrained('hf-internal-testing/config-no-model'						)

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

       """simple docstring"""






       with self.assertRaisesRegex(A_		,							'Use `from_pt=True` to load this model'						):
             lowerCamelCase_	  =					TFAutoModel.from_pretrained('hf-internal-testing/tiny-bert-pt-only'						)





 def        a__				(       self      :						Tuple						)     ->			Union[str, Any]:

       """simple docstring"""






       lowerCamelCase_	  =					TFAutoModel.from_pretrained('hf-internal-testing/tiny-random-bert'						)
       with RequestCounter() as counter:
             lowerCamelCase_	  =					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
       lowerCamelCase_	  =					TFAutoModel.from_pretrained('ArthurZ/tiny-random-bert-sharded'						)
       with RequestCounter() as counter:
             lowerCamelCase_	  =					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						)



