


"""simple docstring"""
import argparse

from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt


if __name__ == "__main__":
			SCREAMING_SNAKE_CASE :    Optional[Any]									=				argparse.ArgumentParser()

			parser.add_argument(
			    """--checkpoint_path""", default=None, type=str, required=True, help="""Path to the checkpoint to convert."""
			)
			parser.add_argument(
			    """--original_config_file""",
			    type=str,
			    required=True,
			    help="""The YAML config file corresponding to the original architecture.""",
			)
			parser.add_argument(
			    """--num_in_channels""",
			    default=None,
			    type=int,
			    help="""The number of input channels. If `None` number of input channels will be automatically inferred.""",
			)
			parser.add_argument(
			    """--image_size""",
			    default=512,
			    type=int,
			    help=(
			        """The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2"""
			        """ Base. Use 768 for Stable Diffusion v2."""
			    ),
			)
			parser.add_argument(
			    """--extract_ema""",
			    action="""store_true""",
			    help=(
			        """Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights"""
			        """ or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield"""
			        """ higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning."""
			    ),
			)
			parser.add_argument(
			    """--upcast_attention""",
			    action="""store_true""",
			    help=(
			        """Whether the attention computation should always be upcasted. This is necessary when running stable"""
			        """ diffusion 2.1."""
			    ),
			)
			parser.add_argument(
			    """--from_safetensors""",
			    action="""store_true""",
			    help="""If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.""",
			)
			parser.add_argument(
			    """--to_safetensors""",
			    action="""store_true""",
			    help="""Whether to store pipeline in safetensors format or not.""",
			)
			parser.add_argument("""--dump_path""", default=None, type=str, required=True, help="""Path to the output model.""")
			parser.add_argument("""--device""", type=str, help="""Device to use (e.g. cpu, cuda:0, cuda:1, etc.)""")






			def 		lowercase							(     _snake_case						:      Optional[int]     )     ->Tuple:
				"""simple docstring"""





				if string == "True":
					return True
				elif string == "False":
					return False
				else:
					raise ValueError(f"""could not parse string as bool {string}"""     )

			parser.add_argument(
			    """--use_linear_projection""", help="""Override for use linear projection""", required=False, type=parse_bool
			)

			parser.add_argument("""--cross_attention_dim""", help="""Override for cross attention_dim""", required=False, type=int)

			SCREAMING_SNAKE_CASE :    Union[str, Any]									=				parser.parse_args()

			SCREAMING_SNAKE_CASE :    Tuple									=				download_controlnet_from_original_ckpt(
			    checkpoint_path=args.checkpoint_path,
			    original_config_file=args.original_config_file,
			    image_size=args.image_size,
			    extract_ema=args.extract_ema,
			    num_in_channels=args.num_in_channels,
			    upcast_attention=args.upcast_attention,
			    from_safetensors=args.from_safetensors,
			    device=args.device,
			    use_linear_projection=args.use_linear_projection,
			    cross_attention_dim=args.cross_attention_dim,
			)

			controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)









"""simple docstring"""
from __future__ import annotations

import copy
import tempfile
import unittest

from transformers import CONFIG_MAPPING, AutoConfig, BertConfig, GPTaConfig, TaConfig, TapasConfig, is_tf_available
from transformers.testing_utils import (
    DUMMY_UNKNOWN_IDENTIFIER,
    SMALL_MODEL_IDENTIFIER,
    RequestCounter,
    require_tensorflow_probability,
    require_tf,
    slow,
)

from ..bert.test_modeling_bert import BertModelTester


if is_tf_available():
			from transformers import (
			    TFAutoModel,
			    TFAutoModelForCausalLM,
			    TFAutoModelForMaskedLM,
			    TFAutoModelForPreTraining,
			    TFAutoModelForQuestionAnswering,
			    TFAutoModelForSeqaSeqLM,
			    TFAutoModelForSequenceClassification,
			    TFAutoModelForTableQuestionAnswering,
			    TFAutoModelForTokenClassification,
			    TFAutoModelWithLMHead,
			    TFBertForMaskedLM,
			    TFBertForPreTraining,
			    TFBertForQuestionAnswering,
			    TFBertForSequenceClassification,
			    TFBertModel,
			    TFFunnelBaseModel,
			    TFFunnelModel,
			    TFGPTaLMHeadModel,
			    TFRobertaForMaskedLM,
			    TFTaForConditionalGeneration,
			    TFTapasForQuestionAnswering,
			)
			from transformers.models.auto.modeling_tf_auto import (
			    TF_MODEL_FOR_CAUSAL_LM_MAPPING,
			    TF_MODEL_FOR_MASKED_LM_MAPPING,
			    TF_MODEL_FOR_PRETRAINING_MAPPING,
			    TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
			    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
			    TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
			    TF_MODEL_MAPPING,
			)
			from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST
			from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST
			from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST
			from transformers.models.tapas.modeling_tf_tapas import TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST



class 			_UpperCAmelCase (							__snake_case				):






		'''simple docstring'''

		lowerCamelCase__				='new-model'


if is_tf_available():



			class 			_UpperCAmelCase (							__snake_case				):






					'''simple docstring'''

					lowerCamelCase__				=NewModelConfig



@require_tf
class 			_UpperCAmelCase (							unittest.TestCase				):






		'''simple docstring'''

		@slow
		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						Optional[int]						=				'''bert-base-cased'''
			__snake_case	:						Dict						=				AutoConfig.from_pretrained(a_					)
			self.assertIsNotNone(a_					)
			self.assertIsInstance(a_				,       a_					)

			__snake_case	:						int						=				TFAutoModel.from_pretrained(a_					)
			self.assertIsNotNone(a_					)
			self.assertIsInstance(a_				,       a_					)



		@slow
		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						Optional[int]						=				'''bert-base-cased'''
			__snake_case	:						Optional[Any]						=				AutoConfig.from_pretrained(a_					)
			self.assertIsNotNone(a_					)
			self.assertIsInstance(a_				,       a_					)

			__snake_case	:						List[Any]						=				TFAutoModelForPreTraining.from_pretrained(a_					)
			self.assertIsNotNone(a_					)
			self.assertIsInstance(a_				,       a_					)



		@slow
		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
				__snake_case	:						int						=				AutoConfig.from_pretrained(a_					)
				self.assertIsNotNone(a_					)
				self.assertIsInstance(a_				,       a_					)

				__snake_case	:						Dict						=				TFAutoModelForCausalLM.from_pretrained(a_					)
				__snake_case	,							__snake_case	:						int						=				TFAutoModelForCausalLM.from_pretrained(a_				,       output_loading_info=a_					)
				self.assertIsNotNone(a_					)
				self.assertIsInstance(a_				,       a_					)



		@slow
		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
				__snake_case	:						Tuple						=				AutoConfig.from_pretrained(a_					)
				self.assertIsNotNone(a_					)
				self.assertIsInstance(a_				,       a_					)

				__snake_case	:						Tuple						=				TFAutoModelWithLMHead.from_pretrained(a_					)
				self.assertIsNotNone(a_					)
				self.assertIsInstance(a_				,       a_					)



		@slow
		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
				__snake_case	:						List[str]						=				AutoConfig.from_pretrained(a_					)
				self.assertIsNotNone(a_					)
				self.assertIsInstance(a_				,       a_					)

				__snake_case	:						Optional[Any]						=				TFAutoModelForMaskedLM.from_pretrained(a_					)
				__snake_case	,							__snake_case	:						int						=				TFAutoModelForMaskedLM.from_pretrained(a_				,       output_loading_info=a_					)
				self.assertIsNotNone(a_					)
				self.assertIsInstance(a_				,       a_					)



		@slow
		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
				__snake_case	:						int						=				AutoConfig.from_pretrained(a_					)
				self.assertIsNotNone(a_					)
				self.assertIsInstance(a_				,       a_					)

				__snake_case	:						List[Any]						=				TFAutoModelForSeqaSeqLM.from_pretrained(a_					)
				__snake_case	,							__snake_case	:						Union[str, Any]						=				TFAutoModelForSeqaSeqLM.from_pretrained(a_				,       output_loading_info=a_					)
				self.assertIsNotNone(a_					)
				self.assertIsInstance(a_				,       a_					)



		@slow
		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			for model_name in ["bert-base-uncased"]:
				__snake_case	:						Any						=				AutoConfig.from_pretrained(a_					)
				self.assertIsNotNone(a_					)
				self.assertIsInstance(a_				,       a_					)

				__snake_case	:						Dict						=				TFAutoModelForSequenceClassification.from_pretrained(a_					)
				self.assertIsNotNone(a_					)
				self.assertIsInstance(a_				,       a_					)



		@slow
		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			for model_name in ["bert-base-uncased"]:
				__snake_case	:						Optional[int]						=				AutoConfig.from_pretrained(a_					)
				self.assertIsNotNone(a_					)
				self.assertIsInstance(a_				,       a_					)

				__snake_case	:						Optional[Any]						=				TFAutoModelForQuestionAnswering.from_pretrained(a_					)
				self.assertIsNotNone(a_					)
				self.assertIsInstance(a_				,       a_					)



		@slow
		@require_tensorflow_probability
		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			for model_name in TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST[5:6]:
				__snake_case	:						Dict						=				AutoConfig.from_pretrained(a_					)
				self.assertIsNotNone(a_					)
				self.assertIsInstance(a_				,       a_					)

				__snake_case	:						List[str]						=				TFAutoModelForTableQuestionAnswering.from_pretrained(a_					)
				__snake_case	,							__snake_case	:						Dict						=				TFAutoModelForTableQuestionAnswering.from_pretrained(
				    a_				,       output_loading_info=a_					)
				self.assertIsNotNone(a_					)
				self.assertIsInstance(a_				,       a_					)



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						Any						=				TFAutoModelWithLMHead.from_pretrained(a_					)
			self.assertIsInstance(a_				,       a_					)
			self.assertEqual(model.num_parameters()				,       1_44_10					)
			self.assertEqual(model.num_parameters(only_trainable=a_					)				,       1_44_10					)



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						Union[str, Any]						=				TFAutoModelWithLMHead.from_pretrained(a_					)
			self.assertIsInstance(a_				,       a_					)
			self.assertEqual(model.num_parameters()				,       1_44_10					)
			self.assertEqual(model.num_parameters(only_trainable=a_					)				,       1_44_10					)



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						Dict						=				TFAutoModel.from_pretrained('''sgugger/funnel-random-tiny'''					)
			self.assertIsInstance(a_				,       a_					)

			__snake_case	:						Optional[Any]						=				copy.deepcopy(model.config					)
			__snake_case	:						int						=				['''FunnelBaseModel''']
			__snake_case	:						Any						=				TFAutoModel.from_config(a_					)
			self.assertIsInstance(a_				,       a_					)

			with tempfile.TemporaryDirectory() as tmp_dir:
				model.save_pretrained(a_					)
				__snake_case	:						Dict						=				TFAutoModel.from_pretrained(a_					)
				self.assertIsInstance(a_				,       a_					)



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			try:
				AutoConfig.register('''new-model'''				,       a_					)

				__snake_case	:						List[str]						=				[
				    TFAutoModel,
				    TFAutoModelForCausalLM,
				    TFAutoModelForMaskedLM,
				    TFAutoModelForPreTraining,
				    TFAutoModelForQuestionAnswering,
				    TFAutoModelForSequenceClassification,
				    TFAutoModelForTokenClassification,
				]

				for auto_class in auto_classes:
					with self.subTest(auto_class.__name__					):
						# Wrong config class will raise an error
						with self.assertRaises(a_					):
							auto_class.register(a_				,       a_					)
						auto_class.register(a_				,       a_					)
						# Trying to register something existing in the Transformers library will raise an error
						with self.assertRaises(a_					):
							auto_class.register(a_				,       a_					)

						# Now that the config is registered, it can be used as any other config with the auto-API
						__snake_case	:						Union[str, Any]						=				BertModelTester(self					).get_config()
						__snake_case	:						str						=				NewModelConfig(**tiny_config.to_dict()					)
						__snake_case	:						Optional[int]						=				auto_class.from_config(a_					)
						self.assertIsInstance(a_				,       a_					)

						with tempfile.TemporaryDirectory() as tmp_dir:
							model.save_pretrained(a_					)
							__snake_case	:						Optional[int]						=				auto_class.from_pretrained(a_					)
							self.assertIsInstance(a_				,       a_					)

			finally:
				if "new-model" in CONFIG_MAPPING._extra_content:
					del CONFIG_MAPPING._extra_content["new-model"]
				for mapping in (
				    TF_MODEL_MAPPING,
				    TF_MODEL_FOR_PRETRAINING_MAPPING,
				    TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
				    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
				    TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
				    TF_MODEL_FOR_CAUSAL_LM_MAPPING,
				    TF_MODEL_FOR_MASKED_LM_MAPPING,
				):
					if NewModelConfig in mapping._extra_content:
						del mapping._extra_content[NewModelConfig]



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			with self.assertRaisesRegex(
			    a_				,       '''bert-base is not a local folder and is not a valid model identifier'''					):
				__snake_case	:						Any						=				TFAutoModel.from_pretrained('''bert-base'''					)



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			with self.assertRaisesRegex(
			    a_				,       R'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'''					):
				__snake_case	:						Dict						=				TFAutoModel.from_pretrained(a_				,       revision='''aaaaaa'''					)



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			with self.assertRaisesRegex(
			    a_				,       '''hf-internal-testing/config-no-model does not appear to have a file named pytorch_model.bin'''				,       ):
				__snake_case	:						Any						=				TFAutoModel.from_pretrained('''hf-internal-testing/config-no-model'''					)



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			with self.assertRaisesRegex(a_				,       '''Use `from_pt=True` to load this model'''					):
				__snake_case	:						Dict						=				TFAutoModel.from_pretrained('''hf-internal-testing/tiny-bert-pt-only'''					)



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						Optional[Any]						=				TFAutoModel.from_pretrained('''hf-internal-testing/tiny-random-bert'''					)
			with RequestCounter() as counter:
				__snake_case	:						List[Any]						=				TFAutoModel.from_pretrained('''hf-internal-testing/tiny-random-bert'''					)
				self.assertEqual(counter.get_request_count				,       0					)
				self.assertEqual(counter.head_request_count				,       1					)
				self.assertEqual(counter.other_request_count				,       0					)

			# With a sharded checkpoint
			__snake_case	:						Dict						=				TFAutoModel.from_pretrained('''ArthurZ/tiny-random-bert-sharded'''					)
			with RequestCounter() as counter:
				__snake_case	:						Dict						=				TFAutoModel.from_pretrained('''ArthurZ/tiny-random-bert-sharded'''					)
				self.assertEqual(counter.get_request_count				,       0					)
				self.assertEqual(counter.head_request_count				,       1					)
				self.assertEqual(counter.other_request_count				,       0					)





