
"""simple docstring"""



import inspect
import unittest

import numpy as np

from tests.test_modeling_common import floats_tensor
from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property

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


if is_torch_available():
 import torch

 from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel

 if is_vision_available():
  from transformers import MaskFormerImageProcessor

if is_vision_available():
 from PIL import Image

class  lowerCAmelCase__							:







     def __init__(				self     :     List[Any]       , _lowerCamelCase     :     List[Any]       , _lowerCamelCase     :     Optional[Any]=2       , _lowerCamelCase     :     Tuple=True       , _lowerCamelCase     :     Optional[int]=False       , _lowerCamelCase     :     Dict=10       , _lowerCamelCase     :     Dict=3       , _lowerCamelCase     :     List[str]=32 * 4       , _lowerCamelCase     :     Union[str, Any]=32 * 6       , _lowerCamelCase     :     List[Any]=4       , _lowerCamelCase     :     Union[str, Any]=32       , ):
       _snake_case   	=			parent
       _snake_case   	=			batch_size
       _snake_case   	=			is_training
       _snake_case   	=			use_auxiliary_loss
       _snake_case   	=			num_queries
       _snake_case   	=			num_channels
       _snake_case   	=			min_size
       _snake_case   	=			max_size
       _snake_case   	=			num_labels
       _snake_case   	=			mask_feature_size







     def 	lowercase      (				self     :     str     ):
       _snake_case   	=			floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]     ).to(
           _lowercase     )

       _snake_case   	=			torch.ones([self.batch_size, self.min_size, self.max_size]       , device=_lowercase     )

       _snake_case   	=			(
           torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size]       , device=_lowercase     ) > 0.5
       ).float()
       _snake_case   	=			(torch.rand((self.batch_size, self.num_labels)       , device=_lowercase     ) > 0.5).long()

       _snake_case   	=			self.get_config()
       return config, pixel_values, pixel_mask, mask_labels, class_labels







     def 	lowercase      (				self     :     Tuple     ):
       return MaskFormerConfig.from_backbone_and_decoder_configs(
           backbone_config=SwinConfig(
               depths=[1, 1, 1, 1]       , )       , decoder_config=DetrConfig(
               decoder_ffn_dim=128       , num_queries=self.num_queries       , decoder_attention_heads=2       , d_model=self.mask_feature_size       , )       , mask_feature_size=self.mask_feature_size       , fpn_feature_size=self.mask_feature_size       , num_channels=self.num_channels       , num_labels=self.num_labels       , )







     def 	lowercase      (				self     :     int     ):
       _snake_case   	=			self.prepare_config_and_inputs()
       _snake_case   	=			{'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask}
       return config, inputs_dict







     def 	lowercase      (				self     :     Union[str, Any]       , _lowerCamelCase     :     Optional[int]       , _lowerCamelCase     :     int     ):
       _snake_case   	=			output.encoder_hidden_states
       _snake_case   	=			output.pixel_decoder_hidden_states
       _snake_case   	=			output.transformer_decoder_hidden_states

       self.parent.assertTrue(len(_lowercase     )       , len(config.backbone_config.depths     )     )
       self.parent.assertTrue(len(_lowercase     )       , len(config.backbone_config.depths     )     )
       self.parent.assertTrue(len(_lowercase     )       , config.decoder_config.decoder_layers     )







     def 	lowercase      (				self     :     Optional[int]       , _lowerCamelCase     :     Optional[Any]       , _lowerCamelCase     :     Optional[int]       , _lowerCamelCase     :     List[Any]       , _lowerCamelCase     :     Optional[int]=False     ):



       with torch.no_grad():
         _snake_case   	=			MaskFormerModel(config=_lowercase     )
         model.to(_lowercase     )
         model.eval()

         _snake_case   	=			model(pixel_values=_lowercase       , pixel_mask=_lowercase     )
         _snake_case   	=			model(_lowercase       , output_hidden_states=_lowercase     )
       # the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the
       # encoder and pixel decoder
       self.parent.assertEqual(
           output.transformer_decoder_last_hidden_state.shape       , (self.batch_size, self.num_queries, self.mask_feature_size)       , )
       # let's ensure the other two hidden state exists
       self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None     )
       self.parent.assertTrue(output.encoder_last_hidden_state is not None     )

       if output_hidden_states:
         self.check_output_hidden_state(_lowercase       , _lowercase     )







     def 	lowercase      (				self     :     str       , _lowerCamelCase     :     Any       , _lowerCamelCase     :     Optional[int]       , _lowerCamelCase     :     Optional[Any]       , _lowerCamelCase     :     Union[str, Any]       , _lowerCamelCase     :     Optional[Any]     ):
       _snake_case   	=			MaskFormerForInstanceSegmentation(config=_lowercase     )
       model.to(_lowercase     )
       model.eval()

       def comm_check_on_output(_lowerCamelCase     :     Optional[Any]     ):
         # let's still check that all the required stuff is there
         self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None     )
         self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None     )
         self.parent.assertTrue(result.encoder_last_hidden_state is not None     )
         # okay, now we need to check the logits shape
         # due to the encoder compression, masks have a //4 spatial size
         self.parent.assertEqual(
             result.masks_queries_logits.shape       , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4)       , )
         # + 1 for null class
         self.parent.assertEqual(
             result.class_queries_logits.shape       , (self.batch_size, self.num_queries, self.num_labels + 1)     )

       with torch.no_grad():
         _snake_case   	=			model(pixel_values=_lowercase       , pixel_mask=_lowercase     )
         _snake_case   	=			model(_lowercase     )

         comm_check_on_output(_lowercase     )

         _snake_case   	=			model(
             pixel_values=_lowercase       , pixel_mask=_lowercase       , mask_labels=_lowercase       , class_labels=_lowercase     )

       comm_check_on_output(_lowercase     )

       self.parent.assertTrue(result.loss is not None     )
       self.parent.assertEqual(result.loss.shape       , torch.Size([1]     )     )






@require_torch
class  lowerCAmelCase__							(		__a					,      __a					,      unittest.TestCase      ):
     __a         =   (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else ()
     __a         =   (
         {'''feature-extraction''': MaskFormerModel, '''image-segmentation''': MaskFormerForInstanceSegmentation}
         if is_torch_available()
         else {}
     )

     __a         =   False
     __a         =   False
     __a         =   False
     __a         =   False







     def 	lowercase      (				self     :     Any     ):
       _snake_case   	=			MaskFormerModelTester(self     )
       _snake_case   	=			ConfigTester(self       , config_class=_lowercase       , has_text_modality=_lowercase     )







     def 	lowercase      (				self     :     Optional[Any]     ):
       self.config_tester.run_common_tests()







     def 	lowercase      (				self     :     str     ):
       _snake_case   	=			self.model_tester.prepare_config_and_inputs_for_common()
       self.model_tester.create_and_check_maskformer_model(_lowercase       , **_lowercase       , output_hidden_states=_lowercase     )







     def 	lowercase      (				self     :     List[str]     ):
       _snake_case   	=			self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*_lowercase     )







     @unittest.skip(reason='''MaskFormer does not use inputs_embeds'''     )
     def 	lowercase      (				self     :     Tuple     ):
       pass







     @unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method'''     )
     def 	lowercase      (				self     :     Any     ):
       pass







     @unittest.skip(reason='''MaskFormer is not a generative model'''     )
     def 	lowercase      (				self     :     Union[str, Any]     ):
       pass







     @unittest.skip(reason='''MaskFormer does not use token embeddings'''     )
     def 	lowercase      (				self     :     Optional[Any]     ):
       pass







     @require_torch_multi_gpu
     @unittest.skip(
         reason='''MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`'''     )
     def 	lowercase      (				self     :     Dict     ):
       pass







     @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''     )
     def 	lowercase      (				self     :     Optional[int]     ):
       pass







     def 	lowercase      (				self     :     List[Any]     ):
       _snake_case   	=			self.model_tester.prepare_config_and_inputs_for_common()

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

         _snake_case   	=			['''pixel_values''']
         self.assertListEqual(arg_names[:1]       , _lowercase     )







     @slow
     def 	lowercase      (				self     :     str     ):



       for model_name in ["facebook/maskformer-swin-small-coco"]:
         _snake_case   	=			MaskFormerModel.from_pretrained(_lowercase     )
         self.assertIsNotNone(_lowercase     )







     def 	lowercase      (				self     :     List[str]     ):
       _snake_case   	=			(self.model_tester.min_size,) * 2
       _snake_case   	=			{
           '''pixel_values''': torch.randn((2, 3, *size)       , device=_lowercase     ),
           '''mask_labels''': torch.randn((2, 10, *size)       , device=_lowercase     ),
           '''class_labels''': torch.zeros(2       , 10       , device=_lowercase     ).long(),
       }

       _snake_case   	=			MaskFormerForInstanceSegmentation(MaskFormerConfig()     ).to(_lowercase     )
       _snake_case   	=			model(**_lowercase     )
       self.assertTrue(outputs.loss is not None     )







     def 	lowercase      (				self     :     Optional[Any]     ):
       _snake_case   	=			self.model_tester.prepare_config_and_inputs_for_common()
       self.model_tester.create_and_check_maskformer_model(_lowercase       , **_lowercase       , output_hidden_states=_lowercase     )







     def 	lowercase      (				self     :     Dict     ):
       _snake_case   	=			self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
         _snake_case   	=			model_class(_lowercase     ).to(_lowercase     )
         _snake_case   	=			model(**_lowercase       , output_attentions=_lowercase     )
         self.assertTrue(outputs.attentions is not None     )







     def 	lowercase      (				self     :     Optional[Any]     ):



       if not self.model_tester.is_training:
         return
       # only MaskFormerForInstanceSegmentation has the loss
       _snake_case   	=			self.all_model_classes[1]
       _snake_case   	=			self.model_tester.prepare_config_and_inputs()

       _snake_case   	=			model_class(_lowercase     )
       model.to(_lowercase     )
       model.train()

       _snake_case   	=			model(_lowercase       , mask_labels=_lowercase       , class_labels=_lowercase     ).loss
       loss.backward()







     def 	lowercase      (				self     :     int     ):
       _snake_case   	=			self.all_model_classes[1]
       _snake_case   	=			self.model_tester.prepare_config_and_inputs()
       _snake_case   	=			True
       _snake_case   	=			True

       _snake_case   	=			model_class(_lowercase     )
       model.to(_lowercase     )
       model.train()

       _snake_case   	=			model(_lowercase       , mask_labels=_lowercase       , class_labels=_lowercase     )

       _snake_case   	=			outputs.encoder_hidden_states[0]
       encoder_hidden_states.retain_grad()

       _snake_case   	=			outputs.pixel_decoder_hidden_states[0]
       pixel_decoder_hidden_states.retain_grad()
       # we requires_grad=True in inputs_embeds (line 2152), the original implementation don't
       _snake_case   	=			outputs.transformer_decoder_hidden_states[0]
       transformer_decoder_hidden_states.retain_grad()

       _snake_case   	=			outputs.attentions[0]
       attentions.retain_grad()

       outputs.loss.backward(retain_graph=_lowercase     )

       self.assertIsNotNone(encoder_hidden_states.grad     )
       self.assertIsNotNone(pixel_decoder_hidden_states.grad     )
       self.assertIsNotNone(transformer_decoder_hidden_states.grad     )
       self.assertIsNotNone(attentions.grad     )






UpperCAmelCase__        =					1e-4
def    _UpperCAmelCase (					)	->   Union[str, Any]:
  _snake_case   	=			Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''						)
  return image

@require_vision
@slow
class  lowerCAmelCase__							(		unittest.TestCase      ):







     @cached_property
     def 	lowercase      (				self     :     List[Any]     ):
       return (
           MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco'''     )
           if is_vision_available()
           else None
       )







     def 	lowercase      (				self     :     Tuple     ):
       _snake_case   	=			MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco'''     ).to(_lowercase     )
       _snake_case   	=			self.default_image_processor
       _snake_case   	=			prepare_img()
       _snake_case   	=			image_processor(_lowercase       , return_tensors='''pt'''     ).to(_lowercase     )
       _snake_case   	=			inputs['''pixel_values'''].shape
       # check size is divisible by 32
       self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0     )
       # check size
       self.assertEqual(_lowercase       , (1, 3, 800, 1088)     )

       with torch.no_grad():
         _snake_case   	=			model(**_lowercase     )

       _snake_case   	=			torch.tensor(
           [[-0.0_4_8_2, 0.9_2_2_8, 0.4_9_5_1], [-0.2_5_4_7, 0.8_0_1_7, 0.8_5_2_7], [-0.0_0_6_9, 0.3_3_8_5, -0.0_0_8_9]]     ).to(_lowercase     )
       self.assertTrue(
           torch.allclose(
               outputs.encoder_last_hidden_state[0, 0, :3, :3]       , _lowercase       , atol=_lowercase     )     )

       _snake_case   	=			torch.tensor(
           [[-0.8_4_2_2, -0.8_4_3_4, -0.9_7_1_8], [-1.0_1_4_4, -0.5_5_6_5, -0.4_1_9_5], [-1.0_0_3_8, -0.4_4_8_4, -0.1_9_6_1]]     ).to(_lowercase     )
       self.assertTrue(
           torch.allclose(
               outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3]       , _lowercase       , atol=_lowercase     )     )

       _snake_case   	=			torch.tensor(
           [[0.2_8_5_2, -0.0_1_5_9, 0.9_7_3_5], [0.6_2_5_4, 0.1_8_5_8, 0.8_5_2_9], [-0.0_6_8_0, -0.4_1_1_6, 1.8_4_1_3]]     ).to(_lowercase     )
       self.assertTrue(
           torch.allclose(
               outputs.transformer_decoder_last_hidden_state[0, :3, :3]       , _lowercase       , atol=_lowercase     )     )







     def 	lowercase      (				self     :     Tuple     ):
       _snake_case   	=			(
           MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco'''     )
           .to(_lowercase     )
           .eval()
       )
       _snake_case   	=			self.default_image_processor
       _snake_case   	=			prepare_img()
       _snake_case   	=			image_processor(_lowercase       , return_tensors='''pt'''     ).to(_lowercase     )
       _snake_case   	=			inputs['''pixel_values'''].shape
       # check size is divisible by 32
       self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0     )
       # check size
       self.assertEqual(_lowercase       , (1, 3, 800, 1088)     )

       with torch.no_grad():
         _snake_case   	=			model(**_lowercase     )
       # masks_queries_logits
       _snake_case   	=			outputs.masks_queries_logits
       self.assertEqual(
           masks_queries_logits.shape       , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)       , )
       _snake_case   	=			[
           [-1.3_7_3_7_1_2_4, -1.7_7_2_4_9_3_7, -1.9_3_6_4_2_3_3],
           [-1.5_9_7_7_2_8_1, -1.9_8_6_7_9_3_9, -2.1_5_2_3_6_9_5],
           [-1.5_7_9_5_3_9_8, -1.9_2_6_9_8_3_2, -2.0_9_3_9_4_2],
       ]
       _snake_case   	=			torch.tensor(_lowercase     ).to(_lowercase     )
       self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]       , _lowercase       , atol=_lowercase     )     )
       # class_queries_logits
       _snake_case   	=			outputs.class_queries_logits
       self.assertEqual(
           class_queries_logits.shape       , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1)     )
       _snake_case   	=			torch.tensor(
           [
               [1.6512e00, -5.2572e00, -3.3519e00],
               [3.6169e-02, -5.9025e00, -2.9313e00],
               [1.0766e-04, -7.7630e00, -5.1263e00],
           ]     ).to(_lowercase     )
       self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]       , _lowercase       , atol=_lowercase     )     )







     def 	lowercase      (				self     :     Any     ):
       _snake_case   	=			(
           MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff'''     )
           .to(_lowercase     )
           .eval()
       )
       _snake_case   	=			self.default_image_processor
       _snake_case   	=			prepare_img()
       _snake_case   	=			image_processor(_lowercase       , return_tensors='''pt'''     ).to(_lowercase     )
       _snake_case   	=			inputs['''pixel_values'''].shape
       # check size is divisible by 32
       self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0     )
       # check size
       self.assertEqual(_lowercase       , (1, 3, 800, 1088)     )

       with torch.no_grad():
         _snake_case   	=			model(**_lowercase     )
       # masks_queries_logits
       _snake_case   	=			outputs.masks_queries_logits
       self.assertEqual(
           masks_queries_logits.shape       , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)       , )
       _snake_case   	=			[[-0.9_0_4_6, -2.6_3_6_6, -4.6_0_6_2], [-3.4_1_7_9, -5.7_8_9_0, -8.8_0_5_7], [-4.9_1_7_9, -7.6_5_6_0, -1_0.7_7_1_1]]
       _snake_case   	=			torch.tensor(_lowercase     ).to(_lowercase     )
       self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]       , _lowercase       , atol=_lowercase     )     )
       # class_queries_logits
       _snake_case   	=			outputs.class_queries_logits
       self.assertEqual(
           class_queries_logits.shape       , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1)     )
       _snake_case   	=			torch.tensor(
           [[4.7_1_8_8, -3.2_5_8_5, -2.8_8_5_7], [6.6_8_7_1, -2.9_1_8_1, -1.2_4_8_7], [7.2_4_4_9, -2.2_7_6_4, -2.1_8_7_4]]     ).to(_lowercase     )
       self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]       , _lowercase       , atol=_lowercase     )     )







     def 	lowercase      (				self     :     List[Any]     ):
       _snake_case   	=			(
           MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco'''     )
           .to(_lowercase     )
           .eval()
       )
       _snake_case   	=			self.default_image_processor

       _snake_case   	=			image_processor(
           [np.zeros((3, 800, 1333)     ), np.zeros((3, 800, 1333)     )]       , segmentation_maps=[np.zeros((384, 384)     ).astype(np.floataa     ), np.zeros((384, 384)     ).astype(np.floataa     )]       , return_tensors='''pt'''       , )

       _snake_case   	=			inputs['''pixel_values'''].to(_lowercase     )
       _snake_case   	=			[el.to(_lowercase     ) for el in inputs['''mask_labels''']]
       _snake_case   	=			[el.to(_lowercase     ) for el in inputs['''class_labels''']]

       with torch.no_grad():
         _snake_case   	=			model(**_lowercase     )

       self.assertTrue(outputs.loss is not None     )




import importlib
import json
import os
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
import transformers.models.auto
from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig
from transformers.models.bert.configuration_bert import BertConfig
from transformers.models.roberta.configuration_roberta import RobertaConfig
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir


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

from test_module.custom_configuration import CustomConfig  # noqa E402


UpperCAmelCase_           =				get_tests_dir('''fixtures/dummy-config.json''')




class 			__magic_name__	(		unittest.TestCase     ):





   """simple docstring"""




   def 	lowerCAmelCase    (						self       :	str				):



    """simple docstring"""



    _UpperCamelCase:  Dict    						=			0



   def 	lowerCAmelCase    (						self       :	Any				):



    """simple docstring"""



    self.assertIsNotNone(transformers.models.auto.__spec__				)
    self.assertIsNotNone(importlib.util.find_spec('''transformers.models.auto'''				)				)



   def 	lowerCAmelCase    (						self       :	Union[str, Any]				):



    """simple docstring"""



    _UpperCamelCase:  List[str]    						=			AutoConfig.from_pretrained('''bert-base-uncased'''				)
    self.assertIsInstance(_lowercase		,	_lowercase				)



   def 	lowerCAmelCase    (						self       :	int				):



    """simple docstring"""



    _UpperCamelCase:  int    						=			AutoConfig.from_pretrained(_lowercase				)
    self.assertIsInstance(_lowercase		,	_lowercase				)



   def 	lowerCAmelCase    (						self       :	List[Any]				):



    """simple docstring"""



    _UpperCamelCase:  List[Any]    						=			AutoConfig.from_pretrained(_lowercase				)
    self.assertIsInstance(_lowercase		,	_lowercase				)



   def 	lowerCAmelCase    (						self       :	Optional[int]				):



    """simple docstring"""



    _UpperCamelCase:  List[str]    						=			AutoConfig.for_model('''roberta'''				)
    self.assertIsInstance(_lowercase		,	_lowercase				)



   def 	lowerCAmelCase    (						self       :	List[str]				):



    """simple docstring"""



    with tempfile.TemporaryDirectory() as tmp_dir:
     # This model name contains bert and roberta, but roberta ends up being picked.
     _UpperCamelCase:  Union[str, Any]    						=			os.path.join(_lowercase		,	'''fake-roberta'''				)
     os.makedirs(_lowercase		,	exist_ok=_lowercase				)
     with open(os.path.join(_lowercase		,	'''config.json'''				)		,	'''w'''				) as f:
      f.write(json.dumps({}				)				)
     _UpperCamelCase:  Union[str, Any]    						=			AutoConfig.from_pretrained(_lowercase				)
     self.assertEqual(type(_lowercase				)		,	_lowercase				)



   def 	lowerCAmelCase    (						self       :	Dict				):



    """simple docstring"""



    try:
     AutoConfig.register('''custom'''		,	_lowercase				)
     # Wrong model type will raise an error
     with self.assertRaises(_lowercase				):
      AutoConfig.register('''model'''		,	_lowercase				)
     # Trying to register something existing in the Transformers library will raise an error
     with self.assertRaises(_lowercase				):
      AutoConfig.register('''bert'''		,	_lowercase				)

     # Now that the config is registered, it can be used as any other config with the auto-API
     _UpperCamelCase:  Union[str, Any]    						=			CustomConfig()
     with tempfile.TemporaryDirectory() as tmp_dir:
      config.save_pretrained(_lowercase				)
      _UpperCamelCase:  Any    						=			AutoConfig.from_pretrained(_lowercase				)
      self.assertIsInstance(_lowercase		,	_lowercase				)

    finally:
     if "custom" in CONFIG_MAPPING._extra_content:
      del CONFIG_MAPPING._extra_content["custom"]



   def 	lowerCAmelCase    (						self       :	Optional[int]				):



    """simple docstring"""



    with self.assertRaisesRegex(
        _lowercase		,	'''bert-base is not a local folder and is not a valid model identifier'''				):
     _UpperCamelCase:  Optional[int]    						=			AutoConfig.from_pretrained('''bert-base'''				)



   def 	lowerCAmelCase    (						self       :	Tuple				):



    """simple docstring"""



    with self.assertRaisesRegex(
        _lowercase		,	R'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'''				):
     _UpperCamelCase:  str    						=			AutoConfig.from_pretrained(_lowercase		,	revision='''aaaaaa'''				)



   def 	lowerCAmelCase    (						self       :	Union[str, Any]				):



    """simple docstring"""



    with self.assertRaisesRegex(
        _lowercase		,	'''hf-internal-testing/no-config-test-repo does not appear to have a file named config.json.'''		,	):
     _UpperCamelCase:  int    						=			AutoConfig.from_pretrained('''hf-internal-testing/no-config-test-repo'''				)



   def 	lowerCAmelCase    (						self       :	Dict				):



    """simple docstring"""



    with self.assertRaises(_lowercase				):
     _UpperCamelCase:  List[str]    						=			AutoConfig.from_pretrained('''hf-internal-testing/test_dynamic_model'''				)
    # If remote code is disabled, we can't load this config.
    with self.assertRaises(_lowercase				):
     _UpperCamelCase:  Optional[int]    						=			AutoConfig.from_pretrained('''hf-internal-testing/test_dynamic_model'''		,	trust_remote_code=_lowercase				)

    _UpperCamelCase:  Union[str, Any]    						=			AutoConfig.from_pretrained('''hf-internal-testing/test_dynamic_model'''		,	trust_remote_code=_lowercase				)
    self.assertEqual(config.__class__.__name__		,	'''NewModelConfig'''				)

    # Test config can be reloaded.
    with tempfile.TemporaryDirectory() as tmp_dir:
     config.save_pretrained(_lowercase				)
     _UpperCamelCase:  str    						=			AutoConfig.from_pretrained(_lowercase		,	trust_remote_code=_lowercase				)
    self.assertEqual(reloaded_config.__class__.__name__		,	'''NewModelConfig'''				)



   def 	lowerCAmelCase    (						self       :	Any				):



    """simple docstring"""



    class 			__magic_name__	(		__a     ):





       """simple docstring"""




       lowerCAmelCase   :     List[Any]	      = '''new-model'''

    try:
     AutoConfig.register('''new-model'''		,	_lowercase				)
     # If remote code is not set, the default is to use local
     _UpperCamelCase:  List[Any]    						=			AutoConfig.from_pretrained('''hf-internal-testing/test_dynamic_model'''				)
     self.assertEqual(config.__class__.__name__		,	'''NewModelConfigLocal'''				)

     # If remote code is disabled, we load the local one.
     _UpperCamelCase:  Union[str, Any]    						=			AutoConfig.from_pretrained('''hf-internal-testing/test_dynamic_model'''		,	trust_remote_code=_lowercase				)
     self.assertEqual(config.__class__.__name__		,	'''NewModelConfigLocal'''				)

     # If remote is enabled, we load from the Hub
     _UpperCamelCase:  Any    						=			AutoConfig.from_pretrained('''hf-internal-testing/test_dynamic_model'''		,	trust_remote_code=_lowercase				)
     self.assertEqual(config.__class__.__name__		,	'''NewModelConfig'''				)

    finally:
     if "new-model" in CONFIG_MAPPING._extra_content:
      del CONFIG_MAPPING._extra_content["new-model"]