
"""simple docstring"""



import unittest

import numpy as np

from transformers import BertConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask


if is_flax_available():
 from transformers.models.bert.modeling_flax_bert import (
     FlaxBertForMaskedLM,
     FlaxBertForMultipleChoice,
     FlaxBertForNextSentencePrediction,
     FlaxBertForPreTraining,
     FlaxBertForQuestionAnswering,
     FlaxBertForSequenceClassification,
     FlaxBertForTokenClassification,
     FlaxBertModel,
 )

class  lowerCAmelCase__							(		unittest.TestCase      ):







     def __init__(				self     :     Tuple       , _lowerCamelCase     :     List[str]       , _lowerCamelCase     :     Dict=13       , _lowerCamelCase     :     Any=7       , _lowerCamelCase     :     List[str]=True       , _lowerCamelCase     :     Any=True       , _lowerCamelCase     :     Optional[int]=True       , _lowerCamelCase     :     int=True       , _lowerCamelCase     :     str=99       , _lowerCamelCase     :     Union[str, Any]=32       , _lowerCamelCase     :     Any=5       , _lowerCamelCase     :     Dict=4       , _lowerCamelCase     :     Tuple=37       , _lowerCamelCase     :     Optional[Any]="gelu"       , _lowerCamelCase     :     Optional[int]=0.1       , _lowerCamelCase     :     Any=0.1       , _lowerCamelCase     :     Union[str, Any]=512       , _lowerCamelCase     :     Dict=16       , _lowerCamelCase     :     int=2       , _lowerCamelCase     :     Union[str, Any]=0.0_2       , _lowerCamelCase     :     Dict=4       , ):
       _snake_case   	=			parent
       _snake_case   	=			batch_size
       _snake_case   	=			seq_length
       _snake_case   	=			is_training
       _snake_case   	=			use_attention_mask
       _snake_case   	=			use_token_type_ids
       _snake_case   	=			use_labels
       _snake_case   	=			vocab_size
       _snake_case   	=			hidden_size
       _snake_case   	=			num_hidden_layers
       _snake_case   	=			num_attention_heads
       _snake_case   	=			intermediate_size
       _snake_case   	=			hidden_act
       _snake_case   	=			hidden_dropout_prob
       _snake_case   	=			attention_probs_dropout_prob
       _snake_case   	=			max_position_embeddings
       _snake_case   	=			type_vocab_size
       _snake_case   	=			type_sequence_label_size
       _snake_case   	=			initializer_range
       _snake_case   	=			num_choices







     def 	lowercase      (				self     :     Optional[Any]     ):
       _snake_case   	=			ids_tensor([self.batch_size, self.seq_length]       , self.vocab_size     )

       _snake_case   	=			None
       if self.use_attention_mask:
         _snake_case   	=			random_attention_mask([self.batch_size, self.seq_length]     )

       _snake_case   	=			None
       if self.use_token_type_ids:
         _snake_case   	=			ids_tensor([self.batch_size, self.seq_length]       , self.type_vocab_size     )

       _snake_case   	=			BertConfig(
           vocab_size=self.vocab_size       , 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       , max_position_embeddings=self.max_position_embeddings       , type_vocab_size=self.type_vocab_size       , is_decoder=_lowercase       , initializer_range=self.initializer_range       , )

       return config, input_ids, token_type_ids, attention_mask







     def 	lowercase      (				self     :     Optional[Any]     ):
       _snake_case   	=			self.prepare_config_and_inputs()
       _snake_case   	=			config_and_inputs
       _snake_case   	=			{'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask}
       return config, inputs_dict







     def 	lowercase      (				self     :     Dict     ):
       _snake_case   	=			self.prepare_config_and_inputs()
       _snake_case   	=			config_and_inputs

       _snake_case   	=			True
       _snake_case   	=			floats_tensor([self.batch_size, self.seq_length, self.hidden_size]     )
       _snake_case   	=			ids_tensor([self.batch_size, self.seq_length]       , vocab_size=2     )

       return (
           config,
           input_ids,
           attention_mask,
           encoder_hidden_states,
           encoder_attention_mask,
       )






@require_flax
class  lowerCAmelCase__							(		__a					,      unittest.TestCase      ):
     __a         =   True

     __a         =   (
         (
             FlaxBertModel,
             FlaxBertForPreTraining,
             FlaxBertForMaskedLM,
             FlaxBertForMultipleChoice,
             FlaxBertForQuestionAnswering,
             FlaxBertForNextSentencePrediction,
             FlaxBertForSequenceClassification,
             FlaxBertForTokenClassification,
             FlaxBertForQuestionAnswering,
         )
         if is_flax_available()
         else ()
     )







     def 	lowercase      (				self     :     Dict     ):
       _snake_case   	=			FlaxBertModelTester(self     )







     @slow
     def 	lowercase      (				self     :     Tuple     ):
       _snake_case   	=			FlaxBertModel.from_pretrained('''bert-base-cased'''     )
       _snake_case   	=			model(np.ones((1, 1)     )     )
       self.assertIsNotNone(_lowercase     )




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"]