



"""simple docstring"""







import argparse
import json
from pathlib import Path

import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image

from transformers import (
    BertTokenizer,
    ViltConfig,
    ViltForImageAndTextRetrieval,
    ViltForImagesAndTextClassification,
    ViltForMaskedLM,
    ViltForQuestionAnswering,
    ViltImageProcessor,
    ViltProcessor,
)
from transformers.utils import logging


logging.set_verbosity_info()
lowerCAmelCase_   						=   logging.get_logger(__name__)



def      __UpperCAmelCase      (    __lowerCamelCase						,     __lowerCamelCase=False						,     __lowerCamelCase=False						,     __lowerCamelCase=False	)							->      str:
		lowercase__   :    Dict				=			[]
		for i in range(config.num_hidden_layers	):
				# encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
				rename_keys.append((f"""transformer.blocks.{i}.norm1.weight""", f"""vilt.encoder.layer.{i}.layernorm_before.weight""")	)
				rename_keys.append((f"""transformer.blocks.{i}.norm1.bias""", f"""vilt.encoder.layer.{i}.layernorm_before.bias""")	)
				rename_keys.append(
				    (f"""transformer.blocks.{i}.attn.proj.weight""", f"""vilt.encoder.layer.{i}.attention.output.dense.weight""")	)
				rename_keys.append(
				    (f"""transformer.blocks.{i}.attn.proj.bias""", f"""vilt.encoder.layer.{i}.attention.output.dense.bias""")	)
				rename_keys.append((f"""transformer.blocks.{i}.norm2.weight""", f"""vilt.encoder.layer.{i}.layernorm_after.weight""")	)
				rename_keys.append((f"""transformer.blocks.{i}.norm2.bias""", f"""vilt.encoder.layer.{i}.layernorm_after.bias""")	)
				rename_keys.append(
				    (f"""transformer.blocks.{i}.mlp.fc1.weight""", f"""vilt.encoder.layer.{i}.intermediate.dense.weight""")	)
				rename_keys.append((f"""transformer.blocks.{i}.mlp.fc1.bias""", f"""vilt.encoder.layer.{i}.intermediate.dense.bias""")	)
				rename_keys.append((f"""transformer.blocks.{i}.mlp.fc2.weight""", f"""vilt.encoder.layer.{i}.output.dense.weight""")	)
				rename_keys.append((f"""transformer.blocks.{i}.mlp.fc2.bias""", f"""vilt.encoder.layer.{i}.output.dense.bias""")	)

		# embeddings
		rename_keys.extend(
		    [
		        # text embeddings
		        ('''text_embeddings.word_embeddings.weight''', '''vilt.embeddings.text_embeddings.word_embeddings.weight'''),
		        (
		            '''text_embeddings.position_embeddings.weight''',
		            '''vilt.embeddings.text_embeddings.position_embeddings.weight''',
		        ),
		        ('''text_embeddings.position_ids''', '''vilt.embeddings.text_embeddings.position_ids'''),
		        (
		            '''text_embeddings.token_type_embeddings.weight''',
		            '''vilt.embeddings.text_embeddings.token_type_embeddings.weight''',
		        ),
		        ('''text_embeddings.LayerNorm.weight''', '''vilt.embeddings.text_embeddings.LayerNorm.weight'''),
		        ('''text_embeddings.LayerNorm.bias''', '''vilt.embeddings.text_embeddings.LayerNorm.bias'''),
		        # patch embeddings
		        ('''transformer.cls_token''', '''vilt.embeddings.cls_token'''),
		        ('''transformer.patch_embed.proj.weight''', '''vilt.embeddings.patch_embeddings.projection.weight'''),
		        ('''transformer.patch_embed.proj.bias''', '''vilt.embeddings.patch_embeddings.projection.bias'''),
		        ('''transformer.pos_embed''', '''vilt.embeddings.position_embeddings'''),
		        # token type embeddings
		        ('''token_type_embeddings.weight''', '''vilt.embeddings.token_type_embeddings.weight'''),
		    ]	)

		# final layernorm + pooler
		rename_keys.extend(
		    [
		        ('''transformer.norm.weight''', '''vilt.layernorm.weight'''),
		        ('''transformer.norm.bias''', '''vilt.layernorm.bias'''),
		        ('''pooler.dense.weight''', '''vilt.pooler.dense.weight'''),
		        ('''pooler.dense.bias''', '''vilt.pooler.dense.bias'''),
		    ]	)

		# classifier head(s)
		if vqa_model:
				# classification head
				rename_keys.extend(
				    [
				        ('''vqa_classifier.0.weight''', '''classifier.0.weight'''),
				        ('''vqa_classifier.0.bias''', '''classifier.0.bias'''),
				        ('''vqa_classifier.1.weight''', '''classifier.1.weight'''),
				        ('''vqa_classifier.1.bias''', '''classifier.1.bias'''),
				        ('''vqa_classifier.3.weight''', '''classifier.3.weight'''),
				        ('''vqa_classifier.3.bias''', '''classifier.3.bias'''),
				    ]	)
		elif nlvr_model:
				# classification head
				rename_keys.extend(
				    [
				        ('''nlvr2_classifier.0.weight''', '''classifier.0.weight'''),
				        ('''nlvr2_classifier.0.bias''', '''classifier.0.bias'''),
				        ('''nlvr2_classifier.1.weight''', '''classifier.1.weight'''),
				        ('''nlvr2_classifier.1.bias''', '''classifier.1.bias'''),
				        ('''nlvr2_classifier.3.weight''', '''classifier.3.weight'''),
				        ('''nlvr2_classifier.3.bias''', '''classifier.3.bias'''),
				    ]	)
		else:
				pass

		return rename_keys



def      __UpperCAmelCase      (    __lowerCamelCase						,     __lowerCamelCase	)							->      Tuple:
		for i in range(config.num_hidden_layers	):
				lowercase__   :    List[str]				=			'''vilt.'''
				# read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
				lowercase__   :    Tuple				=			state_dict.pop(f"""transformer.blocks.{i}.attn.qkv.weight"""	)
				lowercase__   :    int				=			state_dict.pop(f"""transformer.blocks.{i}.attn.qkv.bias"""	)
				# next, add query, keys and values (in that order) to the state dict
				lowercase__   :    str				=			in_proj_weight[
				    : config.hidden_size, :
				]
				lowercase__   :    Any				=			in_proj_bias[: config.hidden_size]
				lowercase__   :    Dict				=			in_proj_weight[
				    config.hidden_size : config.hidden_size * 2, :
				]
				lowercase__   :    str				=			in_proj_bias[
				    config.hidden_size : config.hidden_size * 2
				]
				lowercase__   :    List[Any]				=			in_proj_weight[
				    -config.hidden_size :, :
				]
				lowercase__   :    List[str]				=			in_proj_bias[-config.hidden_size :]



def      __UpperCAmelCase      (    __lowerCamelCase	)							->      Optional[int]:
		lowercase__   :    Tuple				=			['''head.weight''', '''head.bias''']
		for k in ignore_keys:
				state_dict.pop(__lowerCamelCase						,     __lowerCamelCase	)



def      __UpperCAmelCase      (    __lowerCamelCase						,     __lowerCamelCase						,     __lowerCamelCase	)							->      str:
		lowercase__   :    int				=			dct.pop(__lowerCamelCase	)
		lowercase__   :    Optional[Any]				=			val



@torch.no_grad()
def      __UpperCAmelCase      (    __lowerCamelCase						,     __lowerCamelCase	)							->      str:
		lowercase__   :    Tuple				=			ViltConfig(image_size=3_84						,     patch_size=32						,     tie_word_embeddings=__lowerCamelCase	)
		lowercase__   :    Optional[Any]				=			False
		lowercase__   :    List[str]				=			False
		lowercase__   :    Union[str, Any]				=			False
		lowercase__   :    Optional[Any]				=			False
		if "vqa" in checkpoint_url:
				lowercase__   :    Union[str, Any]				=			True
				lowercase__   :    Optional[int]				=			31_29
				lowercase__   :    Tuple				=			'''huggingface/label-files'''
				lowercase__   :    Tuple				=			'''vqa2-id2label.json'''
				lowercase__   :    Optional[Any]				=			json.load(open(hf_hub_download(__lowerCamelCase						,     __lowerCamelCase						,     repo_type='''dataset'''	)						,     '''r'''	)	)
				lowercase__   :    Any				=			{int(__lowerCamelCase	): v for k, v in idalabel.items()}
				lowercase__   :    int				=			idalabel
				lowercase__   :    int				=			{v: k for k, v in idalabel.items()}
				lowercase__   :    Tuple				=			ViltForQuestionAnswering(__lowerCamelCase	)
		elif "nlvr" in checkpoint_url:
				lowercase__   :    Union[str, Any]				=			True
				lowercase__   :    int				=			2
				lowercase__   :    Any				=			{0: '''False''', 1: '''True'''}
				lowercase__   :    List[str]				=			{v: k for k, v in config.idalabel.items()}
				lowercase__   :    Dict				=			3
				lowercase__   :    List[Any]				=			ViltForImagesAndTextClassification(__lowerCamelCase	)
		elif "irtr" in checkpoint_url:
				lowercase__   :    List[Any]				=			True
				lowercase__   :    Tuple				=			ViltForImageAndTextRetrieval(__lowerCamelCase	)
		elif "mlm_itm" in checkpoint_url:
				lowercase__   :    Dict				=			True
				lowercase__   :    int				=			ViltForMaskedLM(__lowerCamelCase	)
		else:
				raise ValueError('''Unknown model type'''	)

		# load state_dict of original model, remove and rename some keys
		lowercase__   :    int				=			torch.hub.load_state_dict_from_url(__lowerCamelCase						,     map_location='''cpu'''	)['''state_dict''']
		lowercase__   :    Optional[int]				=			create_rename_keys(__lowerCamelCase						,     __lowerCamelCase						,     __lowerCamelCase						,     __lowerCamelCase	)
		for src, dest in rename_keys:
				rename_key(__lowerCamelCase						,     __lowerCamelCase						,     __lowerCamelCase	)
		read_in_q_k_v(__lowerCamelCase						,     __lowerCamelCase	)
		if mlm_model or irtr_model:
				lowercase__   :    Dict				=			['''itm_score.fc.weight''', '''itm_score.fc.bias''']
				for k in ignore_keys:
						state_dict.pop(__lowerCamelCase						,     __lowerCamelCase	)

    # load state dict into HuggingFace model
		model.eval()
		if mlm_model:
				lowercase__		,			lowercase__   :    str				=			model.load_state_dict(__lowerCamelCase						,     strict=__lowerCamelCase	)
				assert missing_keys == ["mlm_score.decoder.bias"]
		else:
				model.load_state_dict(__lowerCamelCase	)

		# Define processor
		lowercase__   :    Union[str, Any]				=			ViltImageProcessor(size=3_84	)
		lowercase__   :    Dict				=			BertTokenizer.from_pretrained('''bert-base-uncased'''	)
		lowercase__   :    Union[str, Any]				=			ViltProcessor(__lowerCamelCase						,     __lowerCamelCase	)

		# Forward pass on example inputs (image + text)
		if nlvr_model:
				lowercase__   :    str				=			Image.open(requests.get('''https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg'''						,     stream=__lowerCamelCase	).raw	)
				lowercase__   :    Any				=			Image.open(requests.get('''https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg'''						,     stream=__lowerCamelCase	).raw	)
				lowercase__   :    Optional[Any]				=			(
				    '''The left image contains twice the number of dogs as the right image, and at least two dogs in total are'''
				    ''' standing.'''
				)
				lowercase__   :    Any				=			processor(__lowerCamelCase						,     __lowerCamelCase						,     return_tensors='''pt'''	)
				lowercase__   :    Any				=			processor(__lowerCamelCase						,     __lowerCamelCase						,     return_tensors='''pt'''	)
				lowercase__   :    Union[str, Any]				=			model(
				    input_ids=encoding_a.input_ids						,     pixel_values=encoding_a.pixel_values						,     pixel_values_a=encoding_a.pixel_values						,     )
		else:
				lowercase__   :    str				=			Image.open(requests.get('''http://images.cocodataset.org/val2017/000000039769.jpg'''						,     stream=__lowerCamelCase	).raw	)
				if mlm_model:
						lowercase__   :    Union[str, Any]				=			'''a bunch of [MASK] laying on a [MASK].'''
				else:
						lowercase__   :    Union[str, Any]				=			'''How many cats are there?'''
				lowercase__   :    int				=			processor(__lowerCamelCase						,     __lowerCamelCase						,     return_tensors='''pt'''	)
				lowercase__   :    Optional[int]				=			model(**__lowerCamelCase	)

		# Verify outputs
		if mlm_model:
				lowercase__   :    str				=			torch.Size([1, 11, 3_05_22]	)
				lowercase__   :    Dict				=			torch.tensor([-1_2.5_0_6_1, -1_2.5_1_2_3, -1_2.5_1_7_4]	)
				assert outputs.logits.shape == expected_shape
				assert torch.allclose(outputs.logits[0, 0, :3]						,     __lowerCamelCase						,     atol=1E-4	)

				# verify masked token prediction equals "cats"
				lowercase__   :    List[Any]				=			outputs.logits[0, 4, :].argmax(-1	).item()
				assert tokenizer.decode([predicted_id]	) == "cats"
		elif vqa_model:
				lowercase__   :    Tuple				=			torch.Size([1, 31_29]	)
				lowercase__   :    List[str]				=			torch.tensor([-1_5.9_4_9_5, -1_8.1_4_7_2, -1_0.3_0_4_1]	)
				assert torch.allclose(outputs.logits[0, :3]						,     __lowerCamelCase						,     atol=1E-4	)
				assert outputs.logits.shape == expected_shape
				assert torch.allclose(outputs.logits[0, 0, :3]						,     __lowerCamelCase						,     atol=1E-4	)

				# verify vqa prediction equals "2"
				lowercase__   :    Optional[Any]				=			outputs.logits.argmax(-1	).item()
				assert model.config.idalabel[predicted_idx] == "2"
		elif nlvr_model:
				lowercase__   :    Dict				=			torch.Size([1, 2]	)
				lowercase__   :    Dict				=			torch.tensor([-2.8_7_2_1, 2.1_2_9_1]	)
				assert torch.allclose(outputs.logits[0, :3]						,     __lowerCamelCase						,     atol=1E-4	)
				assert outputs.logits.shape == expected_shape

		Path(__lowerCamelCase	).mkdir(exist_ok=__lowerCamelCase	)
		print(f"""Saving model and processor to {pytorch_dump_folder_path}"""	)
		model.save_pretrained(__lowerCamelCase	)
		processor.save_pretrained(__lowerCamelCase	)


if __name__ == "__main__":
							lowerCAmelCase_   						=   argparse.ArgumentParser()
							# Required parameters
							parser.add_argument(
							    '--checkpoint_url',
							    default='https://github.com/dandelin/ViLT/releases/download/200k/vilt_200k_mlm_itm.ckpt',
							    type=str,
							    help='URL of the checkpoint you\'d like to convert.',
							)
							parser.add_argument(
							    '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.'
							)

							lowerCAmelCase_   						=   parser.parse_args()
							convert_vilt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)





"""simple docstring"""







from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import ResNetConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
							import tensorflow as tf

							from transformers import TFResNetForImageClassification, TFResNetModel
							from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
							from PIL import Image

							from transformers import AutoImageProcessor
class        __A       :







		'''simple docstring'''





		def __init__(	self						:  str			,_snake_case						:  List[Any]			,_snake_case						:  Optional[int]=3			,_snake_case						:  Optional[int]=32			,_snake_case						:  Union[str, Any]=3			,_snake_case						:  int=10			,_snake_case						:  List[str]=[10, 20, 30, 40]			,_snake_case						:  Any=[1, 1, 2, 1]			,_snake_case						:  int=True			,_snake_case						:  Optional[Any]=True			,_snake_case						:  Union[str, Any]="relu"			,_snake_case						:  Dict=3			,_snake_case						:  Any=None			,)					->		str:






				"""simple docstring"""



				lowercase__   :    int				=			parent
				lowercase__   :    Optional[Any]				=			batch_size
				lowercase__   :    Optional[Any]				=			image_size
				lowercase__   :    Optional[Any]				=			num_channels
				lowercase__   :    Optional[Any]				=			embeddings_size
				lowercase__   :    Optional[Any]				=			hidden_sizes
				lowercase__   :    str				=			depths
				lowercase__   :    Tuple				=			is_training
				lowercase__   :    List[Any]				=			use_labels
				lowercase__   :    Union[str, Any]				=			hidden_act
				lowercase__   :    Union[str, Any]				=			num_labels
				lowercase__   :    Tuple				=			scope
				lowercase__   :    Optional[Any]				=			len(_snake_case						)







		def 					UpperCAmelCase    (	self						:  Optional[int]						)					->		Tuple:






				"""simple docstring"""



				lowercase__   :    List[Any]				=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

				lowercase__   :    Tuple				=			None
				if self.use_labels:
						lowercase__   :    Dict				=			ids_tensor([self.batch_size]			,self.num_labels						)

				lowercase__   :    int				=			self.get_config()

				return config, pixel_values, labels







		def 					UpperCAmelCase    (	self						:  Tuple						)					->		Optional[Any]:






				"""simple docstring"""



				return ResNetConfig(
				    num_channels=self.num_channels			,embeddings_size=self.embeddings_size			,hidden_sizes=self.hidden_sizes			,depths=self.depths			,hidden_act=self.hidden_act			,num_labels=self.num_labels			,image_size=self.image_size			,)







		def 					UpperCAmelCase    (	self						:  List[str]			,_snake_case						:  Optional[int]			,_snake_case						:  int			,_snake_case						:  Tuple						)					->		List[Any]:






				"""simple docstring"""



				lowercase__   :    Optional[int]				=			TFResNetModel(config=_snake_case						)
				lowercase__   :    List[str]				=			model(_snake_case						)
				# expected last hidden states: B, C, H // 32, W // 32
				self.parent.assertEqual(
				    result.last_hidden_state.shape			,(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)			,)







		def 					UpperCAmelCase    (	self						:  Optional[int]			,_snake_case						:  Optional[Any]			,_snake_case						:  int			,_snake_case						:  Any						)					->		Tuple:






				"""simple docstring"""



				lowercase__   :    Tuple				=			self.num_labels
				lowercase__   :    Union[str, Any]				=			TFResNetForImageClassification(_snake_case						)
				lowercase__   :    List[str]				=			model(_snake_case			,labels=_snake_case						)
				self.parent.assertEqual(result.logits.shape			,(self.batch_size, self.num_labels)						)







		def 					UpperCAmelCase    (	self						:  Tuple						)					->		str:






				"""simple docstring"""



				lowercase__   :    Dict				=			self.prepare_config_and_inputs()
				lowercase__		,			lowercase__		,			lowercase__   :    Union[str, Any]				=			config_and_inputs
				lowercase__   :    Dict				=			{'''pixel_values''': pixel_values}
				return config, inputs_dict





@require_tf
class        __A       (	A_     ,A_     ,unittest.TestCase    ):







		'''simple docstring'''





		lowerCAmelCase			:					Optional[int]   	=				(TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
		lowerCAmelCase			:					Any   	=				(
		    {"feature-extraction": TFResNetModel, "image-classification": TFResNetForImageClassification}
		    if is_tf_available()
		    else {}
		)

		lowerCAmelCase			:					List[Any]   	=				False
		lowerCAmelCase			:					List[Any]   	=				False
		lowerCAmelCase			:					int   	=				False
		lowerCAmelCase			:					Union[str, Any]   	=				False
		lowerCAmelCase			:					List[str]   	=				False







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






				"""simple docstring"""



				lowercase__   :    Optional[Any]				=			TFResNetModelTester(self						)
				lowercase__   :    int				=			ConfigTester(self			,config_class=_snake_case			,has_text_modality=_snake_case						)







		def 					UpperCAmelCase    (	self						:  Optional[Any]						)					->		str:






				"""simple docstring"""



				self.create_and_test_config_common_properties()
				self.config_tester.create_and_test_config_to_json_string()
				self.config_tester.create_and_test_config_to_json_file()
				self.config_tester.create_and_test_config_from_and_save_pretrained()
				self.config_tester.create_and_test_config_with_num_labels()
				self.config_tester.check_config_can_be_init_without_params()
				self.config_tester.check_config_arguments_init()







		def 					UpperCAmelCase    (	self						:  List[Any]						)					->		List[str]:






				"""simple docstring"""



				return







		@unittest.skip(reason='''ResNet does not use inputs_embeds'''						)
		def 					UpperCAmelCase    (	self						:  Optional[int]						)					->		Dict:






				"""simple docstring"""



				pass







		@unittest.skip(reason='''ResNet does not support input and output embeddings'''						)
		def 					UpperCAmelCase    (	self						:  Tuple						)					->		Optional[Any]:






				"""simple docstring"""



				pass







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






				"""simple docstring"""



				lowercase__		,			lowercase__   :    Dict				=			self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
						lowercase__   :    str				=			model_class(_snake_case						)
						lowercase__   :    Dict				=			inspect.signature(model.call						)
						# signature.parameters is an OrderedDict => so arg_names order is deterministic
						lowercase__   :    Optional[int]				=			[*signature.parameters.keys()]

						lowercase__   :    Any				=			['''pixel_values''']
						self.assertListEqual(arg_names[:1]			,_snake_case						)







		def 					UpperCAmelCase    (	self						:  Tuple						)					->		Any:






				"""simple docstring"""



				lowercase__   :    Optional[int]				=			self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*_snake_case						)







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






				"""simple docstring"""



				def check_hidden_states_output(_snake_case						:  Optional[int]			,_snake_case						:  List[str]			,_snake_case						:  Optional[Any]						):
						lowercase__   :    str				=			model_class(_snake_case						)
						lowercase__   :    Union[str, Any]				=			model(**self._prepare_for_class(_snake_case			,_snake_case						)						)

						lowercase__   :    List[Any]				=			outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

						lowercase__   :    Tuple				=			self.model_tester.num_stages
						self.assertEqual(len(_snake_case						)			,expected_num_stages + 1						)

						# ResNet's feature maps are of shape (batch_size, num_channels, height, width)
						self.assertListEqual(
						    list(hidden_states[0].shape[-2:]						)			,[self.model_tester.image_size // 4, self.model_tester.image_size // 4]			,)

				lowercase__		,			lowercase__   :    int				=			self.model_tester.prepare_config_and_inputs_for_common()
				lowercase__   :    List[Any]				=			['''basic''', '''bottleneck''']
				for model_class in self.all_model_classes:
						for layer_type in layers_type:
								lowercase__   :    List[Any]				=			layer_type
								lowercase__   :    Dict				=			True
								check_hidden_states_output(_snake_case			,_snake_case			,_snake_case						)

								# check that output_hidden_states also work using config
								del inputs_dict["output_hidden_states"]
								lowercase__   :    Dict				=			True

								check_hidden_states_output(_snake_case			,_snake_case			,_snake_case						)







		def 					UpperCAmelCase    (	self						:  Dict						)					->		Any:






				"""simple docstring"""



				lowercase__   :    Optional[Any]				=			self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_image_classification(*_snake_case						)







		@slow
		def 					UpperCAmelCase    (	self						:  Optional[Any]						)					->		int:






				"""simple docstring"""



				for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
						lowercase__   :    Optional[Any]				=			TFResNetModel.from_pretrained(_snake_case						)
						self.assertIsNotNone(_snake_case						)





def      __UpperCAmelCase      (    )							->      Dict:
		lowercase__   :    List[str]				=			Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''	)
		return image





@require_tf
@require_vision
class        __A       (	unittest.TestCase    ):







		'''simple docstring'''





		@cached_property
		def 					UpperCAmelCase    (	self						:  str						)					->		Any:






				"""simple docstring"""



				return (
				    AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]						)
				    if is_vision_available()
				    else None
				)







		@slow
		def 					UpperCAmelCase    (	self						:  Union[str, Any]						)					->		Dict:






				"""simple docstring"""



				lowercase__   :    Tuple				=			TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]						)

				lowercase__   :    Any				=			self.default_image_processor
				lowercase__   :    int				=			prepare_img()
				lowercase__   :    Tuple				=			image_processor(images=_snake_case			,return_tensors='''tf'''						)

				# forward pass
				lowercase__   :    Dict				=			model(**_snake_case						)

				# verify the logits
				lowercase__   :    List[str]				=			tf.TensorShape((1, 1_000)						)
				self.assertEqual(outputs.logits.shape			,_snake_case						)

				lowercase__   :    Any				=			tf.constant([-11.1069, -9.7877, -8.3777]						)

				self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()			,_snake_case			,atol=1e-4						)						)
