

"""simple docstring"""


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

import transformers
from transformers import (
    CONFIG_MAPPING,
    IMAGE_PROCESSOR_MAPPING,
    AutoConfig,
    AutoImageProcessor,
    CLIPConfig,
    CLIPImageProcessor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER


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

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_image_processing import CustomImageProcessor  # noqa E402





class     snake_case	(				unittest.TestCase  ):

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



						'''simple docstring'''


						__lowerCAmelCase:       int          =			0

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



						'''simple docstring'''


						__lowerCAmelCase:       List[str]          =			AutoImageProcessor.from_pretrained("openai/clip-vit-base-patch32")
						self.assertIsInstance(UpperCamelCase__     ,  UpperCamelCase__)

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



						'''simple docstring'''


						with tempfile.TemporaryDirectory() as tmpdirname:
								__lowerCAmelCase:       int          =			Path(UpperCamelCase__) / "preprocessor_config.json"
								__lowerCAmelCase:       str          =			Path(UpperCamelCase__) / "config.json"
								json.dump(
								    {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"}     ,  open(UpperCamelCase__     ,  "w")     ,  )
								json.dump({"model_type": "clip"}     ,  open(UpperCamelCase__     ,  "w"))

								__lowerCAmelCase:       Optional[Any]          =			AutoImageProcessor.from_pretrained(UpperCamelCase__)
								self.assertIsInstance(UpperCamelCase__     ,  UpperCamelCase__)

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



						'''simple docstring'''


						with tempfile.TemporaryDirectory() as tmpdirname:
								__lowerCAmelCase:       Any          =			Path(UpperCamelCase__) / "preprocessor_config.json"
								__lowerCAmelCase:       List[Any]          =			Path(UpperCamelCase__) / "config.json"
								json.dump(
								    {"feature_extractor_type": "CLIPFeatureExtractor", "processor_class": "CLIPProcessor"}     ,  open(UpperCamelCase__     ,  "w")     ,  )
								json.dump({"model_type": "clip"}     ,  open(UpperCamelCase__     ,  "w"))

								__lowerCAmelCase:       Optional[int]          =			AutoImageProcessor.from_pretrained(UpperCamelCase__)
								self.assertIsInstance(UpperCamelCase__     ,  UpperCamelCase__)

				def 							lowercase_     (	self							:				Any)->   Any:



						'''simple docstring'''


						with tempfile.TemporaryDirectory() as tmpdirname:
								__lowerCAmelCase:       str          =			CLIPConfig()

								# Create a dummy config file with image_proceesor_type
								__lowerCAmelCase:       Union[str, Any]          =			Path(UpperCamelCase__) / "preprocessor_config.json"
								__lowerCAmelCase:       Dict          =			Path(UpperCamelCase__) / "config.json"
								json.dump(
								    {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"}     ,  open(UpperCamelCase__     ,  "w")     ,  )
								json.dump({"model_type": "clip"}     ,  open(UpperCamelCase__     ,  "w"))

								# remove image_processor_type to make sure config.json alone is enough to load image processor locally
								__lowerCAmelCase:       int          =			AutoImageProcessor.from_pretrained(UpperCamelCase__).to_dict()

								config_dict.pop("image_processor_type")
								__lowerCAmelCase:       Any          =			CLIPImageProcessor(**UpperCamelCase__)

								# save in new folder
								model_config.save_pretrained(UpperCamelCase__)
								config.save_pretrained(UpperCamelCase__)

								__lowerCAmelCase:       Any          =			AutoImageProcessor.from_pretrained(UpperCamelCase__)

								# make sure private variable is not incorrectly saved
								__lowerCAmelCase:       Tuple          =			json.loads(config.to_json_string())
								self.assertTrue("_processor_class" not in dict_as_saved)

						self.assertIsInstance(UpperCamelCase__     ,  UpperCamelCase__)

				def 							lowercase_     (	self							:				str)->   str:



						'''simple docstring'''


						with tempfile.TemporaryDirectory() as tmpdirname:
								__lowerCAmelCase:       Any          =			Path(UpperCamelCase__) / "preprocessor_config.json"
								json.dump(
								    {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"}     ,  open(UpperCamelCase__     ,  "w")     ,  )

								__lowerCAmelCase:       Any          =			AutoImageProcessor.from_pretrained(UpperCamelCase__)
								self.assertIsInstance(UpperCamelCase__     ,  UpperCamelCase__)

				def 							lowercase_     (	self							:				Dict)->   Optional[int]:



						'''simple docstring'''


						with self.assertRaisesRegex(
						    UpperCamelCase__     ,  "clip-base is not a local folder and is not a valid model identifier"):
								__lowerCAmelCase:       Any          =			AutoImageProcessor.from_pretrained("clip-base")

				def 							lowercase_     (	self							:				Dict)->   List[str]:



						'''simple docstring'''


						with self.assertRaisesRegex(
						    UpperCamelCase__     ,  R"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"):
								__lowerCAmelCase:       Dict          =			AutoImageProcessor.from_pretrained(UpperCamelCase__     ,  revision="aaaaaa")

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



						'''simple docstring'''


						with self.assertRaisesRegex(
						    UpperCamelCase__     ,  "hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json."     ,  ):
								__lowerCAmelCase:       List[str]          =			AutoImageProcessor.from_pretrained("hf-internal-testing/config-no-model")

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



						'''simple docstring'''


						with self.assertRaises(UpperCamelCase__):
								__lowerCAmelCase:       List[str]          =			AutoImageProcessor.from_pretrained("hf-internal-testing/test_dynamic_image_processor")
						# If remote code is disabled, we can't load this config.
						with self.assertRaises(UpperCamelCase__):
								__lowerCAmelCase:       Dict          =			AutoImageProcessor.from_pretrained(
								    "hf-internal-testing/test_dynamic_image_processor"     ,  trust_remote_code=UpperCamelCase__)

						__lowerCAmelCase:       Optional[Any]          =			AutoImageProcessor.from_pretrained(
						    "hf-internal-testing/test_dynamic_image_processor"     ,  trust_remote_code=UpperCamelCase__)
						self.assertEqual(image_processor.__class__.__name__     ,  "NewImageProcessor")

						# Test image processor can be reloaded.
						with tempfile.TemporaryDirectory() as tmp_dir:
								image_processor.save_pretrained(UpperCamelCase__)
								__lowerCAmelCase:       List[Any]          =			AutoImageProcessor.from_pretrained(UpperCamelCase__     ,  trust_remote_code=UpperCamelCase__)
						self.assertEqual(reloaded_image_processor.__class__.__name__     ,  "NewImageProcessor")

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



						'''simple docstring'''


						try:
								AutoConfig.register("custom"     ,  UpperCamelCase__)
								AutoImageProcessor.register(UpperCamelCase__     ,  UpperCamelCase__)
								# Trying to register something existing in the Transformers library will raise an error
								with self.assertRaises(UpperCamelCase__):
										AutoImageProcessor.register(UpperCamelCase__     ,  UpperCamelCase__)

								with tempfile.TemporaryDirectory() as tmpdirname:
										__lowerCAmelCase:       List[str]          =			Path(UpperCamelCase__) / "preprocessor_config.json"
										__lowerCAmelCase:       Optional[Any]          =			Path(UpperCamelCase__) / "config.json"
										json.dump(
										    {"feature_extractor_type": "CLIPFeatureExtractor", "processor_class": "CLIPProcessor"}     ,  open(UpperCamelCase__     ,  "w")     ,  )
										json.dump({"model_type": "clip"}     ,  open(UpperCamelCase__     ,  "w"))

										__lowerCAmelCase:       Any          =			CustomImageProcessor.from_pretrained(UpperCamelCase__)

								# Now that the config is registered, it can be used as any other config with the auto-API
								with tempfile.TemporaryDirectory() as tmp_dir:
										image_processor.save_pretrained(UpperCamelCase__)
										__lowerCAmelCase:       str          =			AutoImageProcessor.from_pretrained(UpperCamelCase__)
										self.assertIsInstance(UpperCamelCase__     ,  UpperCamelCase__)

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




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



						'''simple docstring'''


						class     snake_case	(				__snake_case  ):
										SCREAMING_SNAKE_CASE_   :      List[Any]         =  True

						try:
								AutoConfig.register("custom"     ,  UpperCamelCase__)
								AutoImageProcessor.register(UpperCamelCase__     ,  UpperCamelCase__)
								# If remote code is not set, the default is to use local
								__lowerCAmelCase:       List[str]          =			AutoImageProcessor.from_pretrained("hf-internal-testing/test_dynamic_image_processor")
								self.assertEqual(image_processor.__class__.__name__     ,  "NewImageProcessor")
								self.assertTrue(image_processor.is_local)

								# If remote code is disabled, we load the local one.
								__lowerCAmelCase:       Dict          =			AutoImageProcessor.from_pretrained(
								    "hf-internal-testing/test_dynamic_image_processor"     ,  trust_remote_code=UpperCamelCase__)
								self.assertEqual(image_processor.__class__.__name__     ,  "NewImageProcessor")
								self.assertTrue(image_processor.is_local)

								# If remote is enabled, we load from the Hub
								__lowerCAmelCase:       Tuple          =			AutoImageProcessor.from_pretrained(
								    "hf-internal-testing/test_dynamic_image_processor"     ,  trust_remote_code=UpperCamelCase__)
								self.assertEqual(image_processor.__class__.__name__     ,  "NewImageProcessor")
								self.assertTrue(not hasattr(UpperCamelCase__     ,  "is_local"))

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





"""simple docstring"""


from ...configuration_utils import PretrainedConfig
from ...utils import logging


__A						   =			logging.get_logger(__name__)

__A						   =			{
    "google/switch-base-8": "https://huggingface.co/google/switch-base-8/blob/main/config.json",
}





class     snake_case	(				__snake_case  ):
				SCREAMING_SNAKE_CASE_   :      Union[str, Any]         =  """switch_transformers"""
				SCREAMING_SNAKE_CASE_   :      Tuple         =  ["""past_key_values"""]
				SCREAMING_SNAKE_CASE_   :      Any         =  {"""hidden_size""": """d_model""", """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers"""}

				def __init__(	self							:				List[str]     ,  UpperCamelCase__							:				List[str]=3_2_1_2_8     ,  UpperCamelCase__							:				str=7_6_8     ,  UpperCamelCase__							:				Union[str, Any]=6_4     ,  UpperCamelCase__							:				Optional[int]=2_0_4_8     ,  UpperCamelCase__							:				Dict=6_4     ,  UpperCamelCase__							:				List[str]=1_2     ,  UpperCamelCase__							:				Dict=3     ,  UpperCamelCase__							:				Any=1_2     ,  UpperCamelCase__							:				Dict=3     ,  UpperCamelCase__							:				Dict=1_2     ,  UpperCamelCase__							:				List[str]=8     ,  UpperCamelCase__							:				Optional[Any]=False     ,  UpperCamelCase__							:				Optional[int]=0.01     ,  UpperCamelCase__							:				Optional[int]="float32"     ,  UpperCamelCase__							:				Any=False     ,  UpperCamelCase__							:				Dict=3_2     ,  UpperCamelCase__							:				Union[str, Any]=1_2_8     ,  UpperCamelCase__							:				Union[str, Any]=0.1     ,  UpperCamelCase__							:				Optional[int]=1e-6     ,  UpperCamelCase__							:				Optional[Any]=0.001     ,  UpperCamelCase__							:				Dict=0.001     ,  UpperCamelCase__							:				int=1.0     ,  UpperCamelCase__							:				str="relu"     ,  UpperCamelCase__							:				int=True     ,  UpperCamelCase__							:				Any=False     ,  UpperCamelCase__							:				str=True     ,  UpperCamelCase__							:				Tuple=0     ,  UpperCamelCase__							:				str=1     ,  **UpperCamelCase__							:				Tuple     ,  )->   Optional[Any]:



						'''simple docstring'''


						__lowerCAmelCase:       int          =			vocab_size
						__lowerCAmelCase:       str          =			d_model
						__lowerCAmelCase:       str          =			d_kv
						__lowerCAmelCase:       str          =			d_ff

						__lowerCAmelCase:       List[str]          =			num_sparse_encoder_layers

						__lowerCAmelCase:       List[Any]          =			num_layers
						__lowerCAmelCase:       Optional[Any]          =			(
						    num_decoder_layers if num_decoder_layers is not None else self.num_layers
						)  # default = symmetry
						__lowerCAmelCase:       Tuple          =			num_sparse_decoder_layers

						# This tells us, each how many encoder layer we'll have to set a sparse layer.
						if self.num_sparse_encoder_layers > 0:
								__lowerCAmelCase:       int          =			self.num_layers // self.num_sparse_encoder_layers
						else:
								__lowerCAmelCase:       Union[str, Any]          =			self.num_layers  # HACK: this will create 0 sparse layers

						# This tells us, each how many encoder layer we'll have to set a sparse layer.
						if self.num_sparse_decoder_layers > 0:
								__lowerCAmelCase:       Dict          =			self.num_decoder_layers // self.num_sparse_decoder_layers
						else:
								__lowerCAmelCase:       Any          =			self.num_decoder_layers  # HACK: this will create 0 sparse layers

						__lowerCAmelCase:       Dict          =			num_heads
						__lowerCAmelCase:       Dict          =			num_experts
						__lowerCAmelCase:       Any          =			expert_capacity
						__lowerCAmelCase:       List[Any]          =			router_bias
						__lowerCAmelCase:       int          =			router_jitter_noise
						if router_dtype not in ["float32", "float16", "bfloat16"]:
								raise ValueError(f"`router_dtype` must be one of 'float32', 'float16' or 'bfloat16', got {router_dtype}")
						__lowerCAmelCase:       Dict          =			router_dtype

						__lowerCAmelCase:       Optional[Any]          =			router_ignore_padding_tokens
						__lowerCAmelCase:       Union[str, Any]          =			relative_attention_num_buckets
						__lowerCAmelCase:       str          =			relative_attention_max_distance

						__lowerCAmelCase:       Optional[int]          =			dropout_rate
						__lowerCAmelCase:       Optional[Any]          =			layer_norm_epsilon
						__lowerCAmelCase:       int          =			initializer_factor
						__lowerCAmelCase:       Tuple          =			feed_forward_proj
						__lowerCAmelCase:       int          =			use_cache
						__lowerCAmelCase:       int          =			add_router_probs

						__lowerCAmelCase:       Optional[Any]          =			router_z_loss_coef
						__lowerCAmelCase:       Dict          =			router_aux_loss_coef

						__lowerCAmelCase:       Union[str, Any]          =			self.feed_forward_proj.split("-")
						__lowerCAmelCase:       Tuple          =			act_info[-1]
						__lowerCAmelCase:       str          =			act_info[0] == "gated"

						if len(UpperCamelCase__) > 1 and act_info[0] != "gated" or len(UpperCamelCase__) > 2:
								raise ValueError(
								    f"`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer."
								    "Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. "
								    "'gated-gelu' or 'relu'")

						# for backwards compatibility
						if feed_forward_proj == "gated-gelu":
								__lowerCAmelCase:       List[str]          =			"gelu_new"

						super().__init__(
						    pad_token_id=UpperCamelCase__     ,  eos_token_id=UpperCamelCase__     ,  is_encoder_decoder=UpperCamelCase__     ,  **UpperCamelCase__     ,  )


