"""simple docstring"""


import collections
import inspect
import unittest

from transformers import FocalNetConfig
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_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
    import torch
    from torch import nn

    from transformers import (
        FocalNetBackbone,
        FocalNetForImageClassification,
        FocalNetForMaskedImageModeling,
        FocalNetModel,
    )
    from transformers.models.focalnet.modeling_focalnet import FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
    from PIL import Image

    from transformers import AutoImageProcessor




class  UpperCamelCase					:







       def __init__( self,							lowerCAmelCase__,							lowerCAmelCase__=13,							lowerCAmelCase__=32,							lowerCAmelCase__=2,							lowerCAmelCase__=3,							lowerCAmelCase__=16,							lowerCAmelCase__=[32, 64, 128],							lowerCAmelCase__=[1, 2, 1],							lowerCAmelCase__=[2, 2, 4],							lowerCAmelCase__=2,							lowerCAmelCase__=2.0,							lowerCAmelCase__=True,							lowerCAmelCase__=0.0,							lowerCAmelCase__=0.0,							lowerCAmelCase__=0.1,							lowerCAmelCase__="gelu",							lowerCAmelCase__=False,							lowerCAmelCase__=True,							lowerCAmelCase__=0.02,							lowerCAmelCase__=1e-5,							lowerCAmelCase__=True,							lowerCAmelCase__=None,							lowerCAmelCase__=True,							lowerCAmelCase__=10,							lowerCAmelCase__=8,							lowerCAmelCase__=["stage1", "stage2"],							lowerCAmelCase__=[1, 2],							)      ->      Optional[Any]:
            snake_case_					       =					parent
            snake_case_					       =					batch_size
            snake_case_					       =					image_size
            snake_case_					       =					patch_size
            snake_case_					       =					num_channels
            snake_case_					       =					embed_dim
            snake_case_					       =					hidden_sizes
            snake_case_					       =					depths
            snake_case_					       =					num_heads
            snake_case_					       =					window_size
            snake_case_					       =					mlp_ratio
            snake_case_					       =					qkv_bias
            snake_case_					       =					hidden_dropout_prob
            snake_case_					       =					attention_probs_dropout_prob
            snake_case_					       =					drop_path_rate
            snake_case_					       =					hidden_act
            snake_case_					       =					use_absolute_embeddings
            snake_case_					       =					patch_norm
            snake_case_					       =					layer_norm_eps
            snake_case_					       =					initializer_range
            snake_case_					       =					is_training
            snake_case_					       =					scope
            snake_case_					       =					use_labels
            snake_case_					       =					type_sequence_label_size
            snake_case_					       =					encoder_stride
            snake_case_					       =					out_features
            snake_case_					       =					out_indices







       def 		a_						( self)      ->      Dict:
            snake_case_					       =					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

            snake_case_					       =					None
            if self.use_labels:
                 snake_case_					       =					ids_tensor([self.batch_size],							self.type_sequence_label_size)

            snake_case_					       =					self.get_config()

            return config, pixel_values, labels







       def 		a_						( self)      ->      int:
            return FocalNetConfig(
                image_size=self.image_size,							patch_size=self.patch_size,							num_channels=self.num_channels,							embed_dim=self.embed_dim,							hidden_sizes=self.hidden_sizes,							depths=self.depths,							num_heads=self.num_heads,							window_size=self.window_size,							mlp_ratio=self.mlp_ratio,							qkv_bias=self.qkv_bias,							hidden_dropout_prob=self.hidden_dropout_prob,							attention_probs_dropout_prob=self.attention_probs_dropout_prob,							drop_path_rate=self.drop_path_rate,							hidden_act=self.hidden_act,							use_absolute_embeddings=self.use_absolute_embeddings,							path_norm=self.patch_norm,							layer_norm_eps=self.layer_norm_eps,							initializer_range=self.initializer_range,							encoder_stride=self.encoder_stride,							out_features=self.out_features,							out_indices=self.out_indices,							)







       def 		a_						( self,							lowerCAmelCase__,							lowerCAmelCase__,							lowerCAmelCase__)      ->      List[Any]:
            snake_case_					       =					FocalNetModel(config=lowerCAmelCase__)
            model.to(lowerCAmelCase__)
            model.eval()
            snake_case_					       =					model(lowerCAmelCase__)

            snake_case_					       =					((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths) - 1))
            snake_case_					       =					int(config.embed_dim * 2 ** (len(config.depths) - 1))

            self.parent.assertEqual(result.last_hidden_state.shape,							(self.batch_size, expected_seq_len, expected_dim))







       def 		a_						( self,							lowerCAmelCase__,							lowerCAmelCase__,							lowerCAmelCase__)      ->      List[Any]:
            snake_case_					       =					FocalNetBackbone(config=lowerCAmelCase__)
            model.to(lowerCAmelCase__)
            model.eval()
            snake_case_					       =					model(lowerCAmelCase__)

            # verify feature maps
            self.parent.assertEqual(len(result.feature_maps),							len(config.out_features))
            self.parent.assertListEqual(list(result.feature_maps[0].shape),							[self.batch_size, self.image_size, 8, 8])

            # verify channels
            self.parent.assertEqual(len(model.channels),							len(config.out_features))
            self.parent.assertListEqual(model.channels,							config.hidden_sizes[:-1])

            # verify backbone works with out_features=None
            snake_case_					       =					None
            snake_case_					       =					FocalNetBackbone(config=lowerCAmelCase__)
            model.to(lowerCAmelCase__)
            model.eval()
            snake_case_					       =					model(lowerCAmelCase__)

            # verify feature maps
            self.parent.assertEqual(len(result.feature_maps),							1)
            self.parent.assertListEqual(list(result.feature_maps[0].shape),							[self.batch_size, self.image_size * 2, 4, 4])

            # verify channels
            self.parent.assertEqual(len(model.channels),							1)
            self.parent.assertListEqual(model.channels,							[config.hidden_sizes[-1]])







       def 		a_						( self,							lowerCAmelCase__,							lowerCAmelCase__,							lowerCAmelCase__)      ->      List[str]:
            snake_case_					       =					FocalNetForMaskedImageModeling(config=lowerCAmelCase__)
            model.to(lowerCAmelCase__)
            model.eval()
            snake_case_					       =					model(lowerCAmelCase__)
            self.parent.assertEqual(
                result.reconstruction.shape,							(self.batch_size, self.num_channels, self.image_size, self.image_size))

            # test greyscale images
            snake_case_					       =					1
            snake_case_					       =					FocalNetForMaskedImageModeling(lowerCAmelCase__)
            model.to(lowerCAmelCase__)
            model.eval()

            snake_case_					       =					floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
            snake_case_					       =					model(lowerCAmelCase__)
            self.parent.assertEqual(result.reconstruction.shape,							(self.batch_size, 1, self.image_size, self.image_size))







       def 		a_						( self,							lowerCAmelCase__,							lowerCAmelCase__,							lowerCAmelCase__)      ->      Optional[int]:
            snake_case_					       =					self.type_sequence_label_size
            snake_case_					       =					FocalNetForImageClassification(lowerCAmelCase__)
            model.to(lowerCAmelCase__)
            model.eval()
            snake_case_					       =					model(lowerCAmelCase__,							labels=lowerCAmelCase__)
            self.parent.assertEqual(result.logits.shape,							(self.batch_size, self.type_sequence_label_size))

            # test greyscale images
            snake_case_					       =					1
            snake_case_					       =					FocalNetForImageClassification(lowerCAmelCase__)
            model.to(lowerCAmelCase__)
            model.eval()

            snake_case_					       =					floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
            snake_case_					       =					model(lowerCAmelCase__)
            self.parent.assertEqual(result.logits.shape,							(self.batch_size, self.type_sequence_label_size))







       def 		a_						( self)      ->      Any:
            snake_case_					       =					self.prepare_config_and_inputs()

            snake_case_       ,	snake_case_       ,	snake_case_					       =					config_and_inputs
            snake_case_					       =					{'pixel_values': pixel_values}
            return config, inputs_dict




@require_torch
class  UpperCamelCase					(				lowerCAmelCase__    ,		lowerCAmelCase__    ,		unittest.TestCase   ):
       SCREAMING_SNAKE_CASE_			=      (
           (
               FocalNetModel,
               FocalNetForImageClassification,
               FocalNetForMaskedImageModeling,
               FocalNetBackbone,
           )
           if is_torch_available()
           else ()
       )
       SCREAMING_SNAKE_CASE_			=      (
           {"feature-extraction": FocalNetModel, "image-classification": FocalNetForImageClassification}
           if is_torch_available()
           else {}
       )
       SCREAMING_SNAKE_CASE_			=      False

       SCREAMING_SNAKE_CASE_			=      False
       SCREAMING_SNAKE_CASE_			=      False
       SCREAMING_SNAKE_CASE_			=      False
       SCREAMING_SNAKE_CASE_			=      False







       def 		a_						( self)      ->      Any:
            snake_case_					       =					FocalNetModelTester(self)
            snake_case_					       =					ConfigTester(self,							config_class=lowerCAmelCase__,							embed_dim=37,							has_text_modality=lowerCAmelCase__)







       def 		a_						( self)      ->      Dict:
            self.create_and_test_config_common_properties()
            self.config_tester.create_and_test_config_to_json_string()
            self.config_tester.create_and_test_config_to_json_file()
            self.config_tester.create_and_test_config_from_and_save_pretrained()
            self.config_tester.create_and_test_config_with_num_labels()
            self.config_tester.check_config_can_be_init_without_params()
            self.config_tester.check_config_arguments_init()







       def 		a_						( self)      ->      List[str]:
            return







       def 		a_						( self)      ->      Tuple:
            snake_case_					       =					self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*lowerCAmelCase__)







       def 		a_						( self)      ->      int:
            snake_case_					       =					self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_backbone(*lowerCAmelCase__)







       def 		a_						( self)      ->      List[Any]:
            snake_case_					       =					self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_masked_image_modeling(*lowerCAmelCase__)







       def 		a_						( self)      ->      List[Any]:
            snake_case_					       =					self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__)







       @unittest.skip(reason='FocalNet does not use inputs_embeds')
       def 		a_						( self)      ->      Optional[Any]:
            pass







       @unittest.skip(reason='FocalNet does not use feedforward chunking')
       def 		a_						( self)      ->      int:
            pass







       def 		a_						( self)      ->      List[Any]:
            snake_case_       ,	snake_case_					       =					self.model_tester.prepare_config_and_inputs_for_common()

            for model_class in self.all_model_classes[:-1]:
                 snake_case_					       =					model_class(lowerCAmelCase__)
                 self.assertIsInstance(model.get_input_embeddings(),							(nn.Module))
                 snake_case_					       =					model.get_output_embeddings()
                 self.assertTrue(x is None or isinstance(lowerCAmelCase__,							nn.Linear))







       def 		a_						( self)      ->      str:
            snake_case_       ,	snake_case_					       =					self.model_tester.prepare_config_and_inputs_for_common()

            for model_class in self.all_model_classes[:-1]:
                 snake_case_					       =					model_class(lowerCAmelCase__)
                 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],							lowerCAmelCase__)







       def 		a_						( self,							lowerCAmelCase__,							lowerCAmelCase__,							lowerCAmelCase__,							lowerCAmelCase__)      ->      Any:
            snake_case_					       =					model_class(lowerCAmelCase__)
            model.to(lowerCAmelCase__)
            model.eval()

            with torch.no_grad():
                 snake_case_					       =					model(**self._prepare_for_class(lowerCAmelCase__,							lowerCAmelCase__))

            snake_case_					       =					outputs.hidden_states

            snake_case_					       =					getattr(
                self.model_tester,							'expected_num_hidden_layers',							len(self.model_tester.depths) + 1)
            self.assertEqual(len(lowerCAmelCase__),							lowerCAmelCase__)

            # FocalNet has a different seq_length
            snake_case_					       =					(
                config.patch_size
                if isinstance(config.patch_size,							collections.abc.Iterable)
                else (config.patch_size, config.patch_size)
            )

            snake_case_					       =					(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

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

            snake_case_					       =					outputs.reshaped_hidden_states
            self.assertEqual(len(lowerCAmelCase__),							lowerCAmelCase__)

            snake_case_       ,	snake_case_       ,	snake_case_       ,	snake_case_					       =					reshaped_hidden_states[0].shape
            snake_case_					       =					(
                reshaped_hidden_states[0].view(lowerCAmelCase__,							lowerCAmelCase__,							height * width).permute(0,							2,							1)
            )
            self.assertListEqual(
                list(reshaped_hidden_states.shape[-2:]),							[num_patches, self.model_tester.embed_dim],							)







       def 		a_						( self)      ->      Tuple:
            snake_case_       ,	snake_case_					       =					self.model_tester.prepare_config_and_inputs_for_common()

            snake_case_					       =					(
                self.model_tester.image_size
                if isinstance(self.model_tester.image_size,							collections.abc.Iterable)
                else (self.model_tester.image_size, self.model_tester.image_size)
            )

            for model_class in self.all_model_classes[:-1]:
                 snake_case_					       =					True
                 self.check_hidden_states_output(lowerCAmelCase__,							lowerCAmelCase__,							lowerCAmelCase__,							lowerCAmelCase__)

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

                 self.check_hidden_states_output(lowerCAmelCase__,							lowerCAmelCase__,							lowerCAmelCase__,							lowerCAmelCase__)







       def 		a_						( self)      ->      Optional[Any]:
            snake_case_       ,	snake_case_					       =					self.model_tester.prepare_config_and_inputs_for_common()
            snake_case_					       =					3

            snake_case_					       =					(
                self.model_tester.image_size
                if isinstance(self.model_tester.image_size,							collections.abc.Iterable)
                else (self.model_tester.image_size, self.model_tester.image_size)
            )
            snake_case_					       =					(
                config.patch_size
                if isinstance(config.patch_size,							collections.abc.Iterable)
                else (config.patch_size, config.patch_size)
            )

            snake_case_					       =					image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
            snake_case_					       =					image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

            for model_class in self.all_model_classes[:-1]:
                 snake_case_					       =					True
                 self.check_hidden_states_output(lowerCAmelCase__,							lowerCAmelCase__,							lowerCAmelCase__,							(padded_height, padded_width))

                 # check that output_hidden_states also work using config
                 del inputs_dict["output_hidden_states"]
                 snake_case_					       =					True
                 self.check_hidden_states_output(lowerCAmelCase__,							lowerCAmelCase__,							lowerCAmelCase__,							(padded_height, padded_width))







       @slow
       def 		a_						( self)      ->      List[str]:
            for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 snake_case_					       =					FocalNetModel.from_pretrained(lowerCAmelCase__)
                 self.assertIsNotNone(lowerCAmelCase__)







       def 		a_						( self)      ->      Union[str, Any]:
            snake_case_       ,	snake_case_					       =					self.model_tester.prepare_config_and_inputs_for_common()

            snake_case_					       =					_config_zero_init(lowerCAmelCase__)
            for model_class in self.all_model_classes:
                 snake_case_					       =					model_class(config=lowerCAmelCase__)
                 for name, param in model.named_parameters():
                      if "embeddings" not in name and param.requires_grad:
                           self.assertIn(
                               ((param.data.mean() * 1e9).round() / 1e9).item(),							[0.0, 1.0],							msg=f'Parameter {name} of model {model_class} seems not properly initialized',							)




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







       @cached_property
       def 		a_						( self)      ->      Union[str, Any]:
            # TODO update organization
            return AutoImageProcessor.from_pretrained('microsoft/focalnet-tiny') if is_vision_available() else None







       @slow
       def 		a_						( self)      ->      str:
            snake_case_					       =					FocalNetForImageClassification.from_pretrained('microsoft/focalnet-tiny').to(lowerCAmelCase__)
            snake_case_					       =					self.default_image_processor

            snake_case_					       =					Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png')
            snake_case_					       =					image_processor(images=lowerCAmelCase__,							return_tensors='pt').to(lowerCAmelCase__)

            # forward pass
            with torch.no_grad():
                 snake_case_					       =					model(**lowerCAmelCase__)

            # verify the logits
            snake_case_					       =					torch.Size((1, 1000))
            self.assertEqual(outputs.logits.shape,							lowerCAmelCase__)
            snake_case_					       =					torch.tensor([0.2166, -0.4368, 0.2191]).to(lowerCAmelCase__)
            self.assertTrue(torch.allclose(outputs.logits[0, :3],							lowerCAmelCase__,							atol=1e-4))
            self.assertTrue(outputs.logits.argmax(dim=-1).item(),							281)




@require_torch
class  UpperCamelCase					(				lowerCAmelCase__    ,		unittest.TestCase   ):
       SCREAMING_SNAKE_CASE_			=      (FocalNetBackbone,) if is_torch_available() else ()
       SCREAMING_SNAKE_CASE_			=      FocalNetConfig

       SCREAMING_SNAKE_CASE_			=      False







       def 		a_						( self)      ->      int:
            snake_case_					       =					FocalNetModelTester(self)








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


SCREAMING_SNAKE_CASE_						   =       get_tests_dir("""fixtures/dummy-config.json""")

class 		UpperCamelCase__ (      unittest.TestCase   ):



     '''simple docstring'''

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




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						0






     def 				SCREAMING_SNAKE_CASE__  (							self						:    Any       )     ->		str:




           '''simple docstring'''


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






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




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						AutoConfig.from_pretrained("""bert-base-uncased"""       )
           self.assertIsInstance(lowerCamelCase__						,lowerCamelCase__       )






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




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						AutoConfig.from_pretrained(lowerCamelCase__       )
           self.assertIsInstance(lowerCamelCase__						,lowerCamelCase__       )






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




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						AutoConfig.from_pretrained(lowerCamelCase__       )
           self.assertIsInstance(lowerCamelCase__						,lowerCamelCase__       )






     def 				SCREAMING_SNAKE_CASE__  (							self						:    Tuple       )     ->		Optional[int]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						AutoConfig.for_model("""roberta"""       )
           self.assertIsInstance(lowerCamelCase__						,lowerCamelCase__       )






     def 				SCREAMING_SNAKE_CASE__  (							self						:    int       )     ->		int:




           '''simple docstring'''


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






     def 				SCREAMING_SNAKE_CASE__  (							self						:    Dict       )     ->		str:




           '''simple docstring'''


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

                 # Now that the config is registered, it can be used as any other config with the auto-API
                 SCREAMING_SNAKE_CASE		=						CustomConfig()
                 with tempfile.TemporaryDirectory() as tmp_dir:
                       config.save_pretrained(lowerCamelCase__       )
                       SCREAMING_SNAKE_CASE		=						AutoConfig.from_pretrained(lowerCamelCase__       )
                       self.assertIsInstance(lowerCamelCase__						,lowerCamelCase__       )

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






     def 				SCREAMING_SNAKE_CASE__  (							self						:    str       )     ->		Dict:




           '''simple docstring'''


           with self.assertRaisesRegex(
               lowerCamelCase__						,"""bert-base is not a local folder and is not a valid model identifier"""       ):
                 SCREAMING_SNAKE_CASE		=						AutoConfig.from_pretrained("""bert-base"""       )






     def 				SCREAMING_SNAKE_CASE__  (							self						:    Dict       )     ->		str:




           '''simple docstring'''


           with self.assertRaisesRegex(
               lowerCamelCase__						,R"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"""       ):
                 SCREAMING_SNAKE_CASE		=						AutoConfig.from_pretrained(lowerCamelCase__						,revision="""aaaaaa"""       )






     def 				SCREAMING_SNAKE_CASE__  (							self						:    Tuple       )     ->		List[Any]:




           '''simple docstring'''


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






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




           '''simple docstring'''


           with self.assertRaises(lowerCamelCase__       ):
                 SCREAMING_SNAKE_CASE		=						AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model"""       )
           # If remote code is disabled, we can't load this config.
           with self.assertRaises(lowerCamelCase__       ):
                 SCREAMING_SNAKE_CASE		=						AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model"""						,trust_remote_code=lowerCamelCase__       )

           SCREAMING_SNAKE_CASE		=						AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model"""						,trust_remote_code=lowerCamelCase__       )
           self.assertEqual(config.__class__.__name__						,"""NewModelConfig"""       )

           # Test config can be reloaded.
           with tempfile.TemporaryDirectory() as tmp_dir:
                 config.save_pretrained(lowerCamelCase__       )
                 SCREAMING_SNAKE_CASE		=						AutoConfig.from_pretrained(lowerCamelCase__						,trust_remote_code=lowerCamelCase__       )
           self.assertEqual(reloaded_config.__class__.__name__						,"""NewModelConfig"""       )






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




           '''simple docstring'''


           class 		UpperCamelCase__ (      lowerCAmelCase_   ):



                '''simple docstring'''

                __snake_case    :	Union[str, Any]			=			"new-model"

           try:
                 AutoConfig.register("""new-model"""						,lowerCamelCase__       )
                 # If remote code is not set, the default is to use local
                 SCREAMING_SNAKE_CASE		=						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.
                 SCREAMING_SNAKE_CASE		=						AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model"""						,trust_remote_code=lowerCamelCase__       )
                 self.assertEqual(config.__class__.__name__						,"""NewModelConfigLocal"""       )

                 # If remote is enabled, we load from the Hub
                 SCREAMING_SNAKE_CASE		=						AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model"""						,trust_remote_code=lowerCamelCase__       )
                 self.assertEqual(config.__class__.__name__						,"""NewModelConfig"""       )

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


