





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


lowercase      :       Optional[int]									=  get_tests_dir("""fixtures/dummy-config.json""")





class  A__    (							unittest.TestCase	):




   """simple docstring"""



   def 							__lowercase		(					self)			->						Dict:







          '''simple docstring'''

          a__						:	Tuple =				0

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







          '''simple docstring'''

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

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







          '''simple docstring'''

          a__						:	List[Any] =				AutoConfig.from_pretrained('bert-base-uncased')
          self.assertIsInstance(lowercase					,  lowercase)

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







          '''simple docstring'''

          a__						:	Optional[Any] =				AutoConfig.from_pretrained(lowercase)
          self.assertIsInstance(lowercase					,  lowercase)

   def 							__lowercase		(					self)			->						Optional[int]:







          '''simple docstring'''

          a__						:	Any =				AutoConfig.from_pretrained(lowercase)
          self.assertIsInstance(lowercase					,  lowercase)

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







          '''simple docstring'''

          a__						:	Tuple =				AutoConfig.for_model('roberta')
          self.assertIsInstance(lowercase					,  lowercase)

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







          '''simple docstring'''

          with tempfile.TemporaryDirectory() as tmp_dir:
                 # This model name contains bert and roberta, but roberta ends up being picked.
                 a__						:	List[str] =				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({}))
                 a__						:	List[str] =				AutoConfig.from_pretrained(lowercase)
                 self.assertEqual(type(lowercase)					,  lowercase)

   def 							__lowercase		(					self)			->						Optional[int]:







          '''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
                 a__						:	int =				CustomConfig()
                 with tempfile.TemporaryDirectory() as tmp_dir:
                        config.save_pretrained(lowercase)
                        a__						:	Optional[int] =				AutoConfig.from_pretrained(lowercase)
                        self.assertIsInstance(lowercase					,  lowercase)

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

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







          '''simple docstring'''

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

   def 							__lowercase		(					self)			->						int:







          '''simple docstring'''

          with self.assertRaisesRegex(
              lowercase					,  r'aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'):
                 a__						:	Union[str, Any] =				AutoConfig.from_pretrained(lowercase					,  revision='aaaaaa')

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







          '''simple docstring'''

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

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







          '''simple docstring'''

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

          a__						:	Tuple =				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)
                 a__						:	Optional[int] =				AutoConfig.from_pretrained(lowercase					,  trust_remote_code=lowercase)
          self.assertEqual(reloaded_config.__class__.__name__					,  'NewModelConfig')

   def 							__lowercase		(					self)			->						str:







          '''simple docstring'''

          class  A__    (							__UpperCAmelCase	):




             """simple docstring"""



             __A   :				Tuple         =  '''new-model'''

          try:
                 AutoConfig.register('new-model'					,  lowercase)
                 # If remote code is not set, the default is to use local
                 a__						:	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.
                 a__						:	Optional[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
                 a__						:	int =				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"]









from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


lowercase      :       List[Any]									=  {
    """configuration_nllb_moe""": [
        """NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP""",
        """NllbMoeConfig""",
    ]
}

try:
    if not is_torch_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    lowercase      :       Dict									=  [
        """NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST""",
        """NllbMoeForConditionalGeneration""",
        """NllbMoeModel""",
        """NllbMoePreTrainedModel""",
        """NllbMoeTop2Router""",
        """NllbMoeSparseMLP""",
    ]


if TYPE_CHECKING:
    from .configuration_nllb_moe import (
        NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP,
        NllbMoeConfig,
    )

    try:
        if not is_torch_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_nllb_moe import (
            NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST,
            NllbMoeForConditionalGeneration,
            NllbMoeModel,
            NllbMoePreTrainedModel,
            NllbMoeSparseMLP,
            NllbMoeTopaRouter,
        )


else:
    import sys

    lowercase      :       List[Any]									=  _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)


