






import gc
import random
import tempfile
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    ControlNetModel,
    DDIMScheduler,
    StableDiffusionControlNetImgaImgPipeline,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet import MultiControlNetModel
from diffusers.utils import floats_tensor, load_image, load_numpy, randn_tensor, slow, torch_device
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import (
    IMAGE_TO_IMAGE_IMAGE_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import (
    PipelineKarrasSchedulerTesterMixin,
    PipelineLatentTesterMixin,
    PipelineTesterMixin,
)


enable_full_determinism()





class        snake_case__					(							__snake_case						,  __snake_case						,  __snake_case						,  unittest.TestCase      ):
	lowercase__						:     str							      =    StableDiffusionControlNetImgaImgPipeline
	lowercase__						:     List[str]							      =    TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''}
	lowercase__						:     List[str]							      =    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
	lowercase__						:     str							      =    IMAGE_TO_IMAGE_IMAGE_PARAMS.union({'''control_image'''}      )
	lowercase__						:     List[Any]							      =    IMAGE_TO_IMAGE_IMAGE_PARAMS
	def 			__magic_name__				(				self )							->      List[str]:
							torch.manual_seed(0 )
							__magic_name__			:   List[Any]   						=					UNetaDConditionModel(
							    block_out_channels=(32, 64)			,   layers_per_block=2			,   sample_size=32			,   in_channels=4			,   out_channels=4			,   down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")			,   up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""")			,   cross_attention_dim=32			,   )
							torch.manual_seed(0 )
							__magic_name__			:   Optional[Any]   						=					ControlNetModel(
							    block_out_channels=(32, 64)			,   layers_per_block=2			,   in_channels=4			,   down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")			,   cross_attention_dim=32			,   conditioning_embedding_out_channels=(16, 32)			,   )
							torch.manual_seed(0 )
							__magic_name__			:   Any   						=					DDIMScheduler(
							    beta_start=0.0_0_0_8_5			,   beta_end=0.0_1_2			,   beta_schedule="""scaled_linear"""			,   clip_sample=a_			,   set_alpha_to_one=a_			,   )
							torch.manual_seed(0 )
							__magic_name__			:   Any   						=					AutoencoderKL(
							    block_out_channels=[32, 64]			,   in_channels=3			,   out_channels=3			,   down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]			,   up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]			,   latent_channels=4			,   )
							torch.manual_seed(0 )
							__magic_name__			:   List[str]   						=					CLIPTextConfig(
							    bos_token_id=0			,   eos_token_id=2			,   hidden_size=32			,   intermediate_size=37			,   layer_norm_eps=1e-0_5			,   num_attention_heads=4			,   num_hidden_layers=5			,   pad_token_id=1			,   vocab_size=10_00			,   )
							__magic_name__			:   Any   						=					CLIPTextModel(a_ )
							__magic_name__			:   List[str]   						=					CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" )

							__magic_name__			:   Tuple   						=					{
							    '''unet''': unet,
							    '''controlnet''': controlnet,
							    '''scheduler''': scheduler,
							    '''vae''': vae,
							    '''text_encoder''': text_encoder,
							    '''tokenizer''': tokenizer,
							    '''safety_checker''': None,
							    '''feature_extractor''': None,
							}
							return components
	def 			__magic_name__				(				self			,   lowerCAmelCase__			,   lowerCAmelCase__=0 )							->      Union[str, Any]:

							if str(a_ ).startswith("""mps""" ):
													__magic_name__			:   int   						=					torch.manual_seed(a_ )
							else:
													__magic_name__			:   int   						=					torch.Generator(device=a_ ).manual_seed(a_ )

							__magic_name__			:   List[str]   						=					2
							__magic_name__			:   List[str]   						=					randn_tensor(
							    (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor)			,   generator=a_			,   device=torch.device(a_ )			,   )
							__magic_name__			:   Any   						=					floats_tensor(control_image.shape			,   rng=random.Random(a_ ) ).to(a_ )
							__magic_name__			:   str   						=					image.cpu().permute(0			,   2			,   3			,   1 )[0]
							__magic_name__			:   int   						=					Image.fromarray(np.uinta(a_ ) ).convert("""RGB""" ).resize((64, 64) )
							__magic_name__			:   Any   						=					{
							    '''prompt''': '''A painting of a squirrel eating a burger''',
							    '''generator''': generator,
							    '''num_inference_steps''': 2,
							    '''guidance_scale''': 6.0,
							    '''output_type''': '''numpy''',
							    '''image''': image,
							    '''control_image''': control_image,
							}

							return inputs
	def 			__magic_name__				(				self )							->      Optional[int]:
							return self._test_attention_slicing_forward_pass(expected_max_diff=2e-3 )
	@unittest.skipIf(
	    torch_device != """cuda""" or not is_xformers_available()			,   reason="""XFormers attention is only available with CUDA and `xformers` installed"""			,   )
	def 			__magic_name__				(				self )							->      List[str]:
							self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3 )







	def 			__magic_name__				(				self )							->      Tuple:
							self._test_inference_batch_single_identical(expected_max_diff=2e-3 )





class        snake_case__					(							__snake_case						,  __snake_case						,  unittest.TestCase      ):
	lowercase__						:     Union[str, Any]							      =    StableDiffusionControlNetImgaImgPipeline
	lowercase__						:     int							      =    TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''}
	lowercase__						:     Union[str, Any]							      =    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
	lowercase__						:     Optional[int]							      =    frozenset([]      )  # TO_DO: add image_params once refactored VaeImageProcessor.preprocess
	def 			__magic_name__				(				self )							->      Dict:
							torch.manual_seed(0 )
							__magic_name__			:   Optional[int]   						=					UNetaDConditionModel(
							    block_out_channels=(32, 64)			,   layers_per_block=2			,   sample_size=32			,   in_channels=4			,   out_channels=4			,   down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")			,   up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""")			,   cross_attention_dim=32			,   )
							torch.manual_seed(0 )

							def init_weights(lowerCAmelCase__ ):
													if isinstance(a_			,   torch.nn.Convad ):
																			torch.nn.init.normal(m.weight )
																			m.bias.data.fill_(1.0 )

							__magic_name__			:   Dict   						=					ControlNetModel(
							    block_out_channels=(32, 64)			,   layers_per_block=2			,   in_channels=4			,   down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")			,   cross_attention_dim=32			,   conditioning_embedding_out_channels=(16, 32)			,   )
							controlneta.controlnet_down_blocks.apply(a_ )

							torch.manual_seed(0 )
							__magic_name__			:   Any   						=					ControlNetModel(
							    block_out_channels=(32, 64)			,   layers_per_block=2			,   in_channels=4			,   down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")			,   cross_attention_dim=32			,   conditioning_embedding_out_channels=(16, 32)			,   )
							controlneta.controlnet_down_blocks.apply(a_ )

							torch.manual_seed(0 )
							__magic_name__			:   List[Any]   						=					DDIMScheduler(
							    beta_start=0.0_0_0_8_5			,   beta_end=0.0_1_2			,   beta_schedule="""scaled_linear"""			,   clip_sample=a_			,   set_alpha_to_one=a_			,   )
							torch.manual_seed(0 )
							__magic_name__			:   Union[str, Any]   						=					AutoencoderKL(
							    block_out_channels=[32, 64]			,   in_channels=3			,   out_channels=3			,   down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]			,   up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]			,   latent_channels=4			,   )
							torch.manual_seed(0 )
							__magic_name__			:   Optional[Any]   						=					CLIPTextConfig(
							    bos_token_id=0			,   eos_token_id=2			,   hidden_size=32			,   intermediate_size=37			,   layer_norm_eps=1e-0_5			,   num_attention_heads=4			,   num_hidden_layers=5			,   pad_token_id=1			,   vocab_size=10_00			,   )
							__magic_name__			:   Dict   						=					CLIPTextModel(a_ )
							__magic_name__			:   List[str]   						=					CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" )

							__magic_name__			:   Any   						=					MultiControlNetModel([controlneta, controlneta] )

							__magic_name__			:   Any   						=					{
							    '''unet''': unet,
							    '''controlnet''': controlnet,
							    '''scheduler''': scheduler,
							    '''vae''': vae,
							    '''text_encoder''': text_encoder,
							    '''tokenizer''': tokenizer,
							    '''safety_checker''': None,
							    '''feature_extractor''': None,
							}
							return components
	def 			__magic_name__				(				self			,   lowerCAmelCase__			,   lowerCAmelCase__=0 )							->      Any:

							if str(a_ ).startswith("""mps""" ):
													__magic_name__			:   Dict   						=					torch.manual_seed(a_ )
							else:
													__magic_name__			:   Optional[int]   						=					torch.Generator(device=a_ ).manual_seed(a_ )

							__magic_name__			:   Union[str, Any]   						=					2

							__magic_name__			:   Any   						=					[
							    randn_tensor(
							        (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor)			,   generator=a_			,   device=torch.device(a_ )			,   ),
							    randn_tensor(
							        (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor)			,   generator=a_			,   device=torch.device(a_ )			,   ),
							]

							__magic_name__			:   List[str]   						=					floats_tensor(control_image[0].shape			,   rng=random.Random(a_ ) ).to(a_ )
							__magic_name__			:   Union[str, Any]   						=					image.cpu().permute(0			,   2			,   3			,   1 )[0]
							__magic_name__			:   Optional[Any]   						=					Image.fromarray(np.uinta(a_ ) ).convert("""RGB""" ).resize((64, 64) )
							__magic_name__			:   Any   						=					{
							    '''prompt''': '''A painting of a squirrel eating a burger''',
							    '''generator''': generator,
							    '''num_inference_steps''': 2,
							    '''guidance_scale''': 6.0,
							    '''output_type''': '''numpy''',
							    '''image''': image,
							    '''control_image''': control_image,
							}

							return inputs
	def 			__magic_name__				(				self )							->      Any:
							__magic_name__			:   str   						=					self.get_dummy_components()
							__magic_name__			:   List[Any]   						=					self.pipeline_class(**a_ )
							pipe.to(a_ )

							__magic_name__			:   List[Any]   						=					1_0.0
							__magic_name__			:   List[str]   						=					4

							__magic_name__			:   Optional[Any]   						=					self.get_dummy_inputs(a_ )
							__magic_name__			:   int   						=					steps
							__magic_name__			:   Union[str, Any]   						=					scale
							__magic_name__			:   str   						=					pipe(**a_ )[0]

							__magic_name__			:   int   						=					self.get_dummy_inputs(a_ )
							__magic_name__			:   Tuple   						=					steps
							__magic_name__			:   Any   						=					scale
							__magic_name__			:   str   						=					pipe(**a_			,   control_guidance_start=0.1			,   control_guidance_end=0.2 )[0]

							__magic_name__			:   str   						=					self.get_dummy_inputs(a_ )
							__magic_name__			:   Union[str, Any]   						=					steps
							__magic_name__			:   Tuple   						=					scale
							__magic_name__			:   List[str]   						=					pipe(**a_			,   control_guidance_start=[0.1, 0.3]			,   control_guidance_end=[0.2, 0.7] )[0]

							__magic_name__			:   int   						=					self.get_dummy_inputs(a_ )
							__magic_name__			:   Tuple   						=					steps
							__magic_name__			:   List[Any]   						=					scale
							__magic_name__			:   str   						=					pipe(**a_			,   control_guidance_start=0.4			,   control_guidance_end=[0.5, 0.8] )[0]

							# make sure that all outputs are different
							assert np.sum(np.abs(output_a - output_a ) ) > 1e-3
							assert np.sum(np.abs(output_a - output_a ) ) > 1e-3
							assert np.sum(np.abs(output_a - output_a ) ) > 1e-3
	def 			__magic_name__				(				self )							->      Optional[Any]:
							return self._test_attention_slicing_forward_pass(expected_max_diff=2e-3 )
	@unittest.skipIf(
	    torch_device != """cuda""" or not is_xformers_available()			,   reason="""XFormers attention is only available with CUDA and `xformers` installed"""			,   )
	def 			__magic_name__				(				self )							->      str:
							self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3 )
	def 			__magic_name__				(				self )							->      List[str]:
							self._test_inference_batch_single_identical(expected_max_diff=2e-3 )







	def 			__magic_name__				(				self )							->      List[Any]:
							__magic_name__			:   str   						=					self.get_dummy_components()
							__magic_name__			:   Union[str, Any]   						=					self.pipeline_class(**a_ )
							pipe.to(a_ )
							pipe.set_progress_bar_config(disable=a_ )
							with tempfile.TemporaryDirectory() as tmpdir:
													try:
																			# save_pretrained is not implemented for Multi-ControlNet
																			pipe.save_pretrained(a_ )
													except NotImplementedError:
																			pass





@slow
@require_torch_gpu
class        snake_case__					(							unittest.TestCase      ):
	def 			__magic_name__				(				self )							->      Any:
							super().tearDown()
							gc.collect()
							torch.cuda.empty_cache()







	def 			__magic_name__				(				self )							->      Optional[int]:
							__magic_name__			:   Any   						=					ControlNetModel.from_pretrained("""lllyasviel/sd-controlnet-canny""" )

							__magic_name__			:   Union[str, Any]   						=					StableDiffusionControlNetImgaImgPipeline.from_pretrained(
							    """runwayml/stable-diffusion-v1-5"""			,   safety_checker=a_			,   controlnet=a_ )
							pipe.enable_model_cpu_offload()
							pipe.set_progress_bar_config(disable=a_ )

							__magic_name__			:   Any   						=					torch.Generator(device="""cpu""" ).manual_seed(0 )
							__magic_name__			:   List[Any]   						=					'''evil space-punk bird'''
							__magic_name__			:   Union[str, Any]   						=					load_image(
							    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png""" ).resize((5_12, 5_12) )
							__magic_name__			:   List[str]   						=					load_image(
							    """https://huggingface.co/lllyasviel/sd-controlnet-canny/resolve/main/images/bird.png""" ).resize((5_12, 5_12) )

							__magic_name__			:   Any   						=					pipe(
							    a_			,   a_			,   control_image=a_			,   generator=a_			,   output_type="""np"""			,   num_inference_steps=50			,   strength=0.6			,   )

							__magic_name__			:   List[str]   						=					output.images[0]

							assert image.shape == (5_12, 5_12, 3)

							__magic_name__			:   Union[str, Any]   						=					load_numpy(
							    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/img2img.npy""" )

							assert np.abs(expected_image - image ).max() < 9e-2




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





