



import copy
import unittest

from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
					import torch

					from transformers import (
					    MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
					    MODEL_FOR_QUESTION_ANSWERING_MAPPING,
					    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
					    MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
					    LayoutLMvaConfig,
					    LayoutLMvaForQuestionAnswering,
					    LayoutLMvaForSequenceClassification,
					    LayoutLMvaForTokenClassification,
					    LayoutLMvaModel,
					)
					from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
					from PIL import Image

					from transformers import LayoutLMvaImageProcessor






class 							lowercase__     :





	def __init__(			self :    Tuple			,lowerCamelCase__ :    Tuple			,lowerCamelCase__ :    int=2			,lowerCamelCase__ :    str=3			,lowerCamelCase__ :    int=4			,lowerCamelCase__ :    str=2			,lowerCamelCase__ :    Optional[int]=7			,lowerCamelCase__ :    int=True			,lowerCamelCase__ :    List[str]=True			,lowerCamelCase__ :    Union[str, Any]=True			,lowerCamelCase__ :    int=True			,lowerCamelCase__ :    Any=99			,lowerCamelCase__ :    Any=36			,lowerCamelCase__ :    Union[str, Any]=3			,lowerCamelCase__ :    Optional[Any]=4			,lowerCamelCase__ :    List[str]=37			,lowerCamelCase__ :    Optional[Any]="gelu"			,lowerCamelCase__ :    Optional[Any]=0.1			,lowerCamelCase__ :    Any=0.1			,lowerCamelCase__ :    Any=512			,lowerCamelCase__ :    Optional[int]=16			,lowerCamelCase__ :    Tuple=2			,lowerCamelCase__ :    Tuple=0.0_2			,lowerCamelCase__ :    List[Any]=6			,lowerCamelCase__ :    Optional[int]=6			,lowerCamelCase__ :    str=3			,lowerCamelCase__ :    List[str]=4			,lowerCamelCase__ :    Tuple=None			,lowerCamelCase__ :    Union[str, Any]=1000			,):







							'''simple docstring'''
							_UpperCamelCase :		Union[str, Any]			    =       parent
							_UpperCamelCase :		int			    =       batch_size
							_UpperCamelCase :		Optional[Any]			    =       num_channels
							_UpperCamelCase :		str			    =       image_size
							_UpperCamelCase :		int			    =       patch_size
							_UpperCamelCase :		Tuple			    =       text_seq_length
							_UpperCamelCase :		Any			    =       is_training
							_UpperCamelCase :		Tuple			    =       use_input_mask
							_UpperCamelCase :		Dict			    =       use_token_type_ids
							_UpperCamelCase :		List[str]			    =       use_labels
							_UpperCamelCase :		Dict			    =       vocab_size
							_UpperCamelCase :		Tuple			    =       hidden_size
							_UpperCamelCase :		Optional[int]			    =       num_hidden_layers
							_UpperCamelCase :		Any			    =       num_attention_heads
							_UpperCamelCase :		List[str]			    =       intermediate_size
							_UpperCamelCase :		int			    =       hidden_act
							_UpperCamelCase :		Any			    =       hidden_dropout_prob
							_UpperCamelCase :		int			    =       attention_probs_dropout_prob
							_UpperCamelCase :		Any			    =       max_position_embeddings
							_UpperCamelCase :		str			    =       type_vocab_size
							_UpperCamelCase :		Optional[int]			    =       type_sequence_label_size
							_UpperCamelCase :		Union[str, Any]			    =       initializer_range
							_UpperCamelCase :		Optional[Any]			    =       coordinate_size
							_UpperCamelCase :		str			    =       shape_size
							_UpperCamelCase :		Tuple			    =       num_labels
							_UpperCamelCase :		Union[str, Any]			    =       num_choices
							_UpperCamelCase :		Any			    =       scope
							_UpperCamelCase :		str			    =       range_bbox

							# LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token)
							_UpperCamelCase :		Dict			    =       text_seq_length
							_UpperCamelCase :		Dict			    =       (image_size // patch_size) ** 2 + 1
							_UpperCamelCase :		List[Any]			    =       self.text_seq_length + self.image_seq_length





	def      UpperCamelCase_  (			self :    int			):







							'''simple docstring'''
							_UpperCamelCase :		Tuple			    =       ids_tensor([self.batch_size, self.text_seq_length]			,self.vocab_size			)

							_UpperCamelCase :		Optional[int]			    =       ids_tensor([self.batch_size, self.text_seq_length, 4]			,self.range_bbox			)
							# Ensure that bbox is legal
							for i in range(bbox.shape[0]			):
													for j in range(bbox.shape[1]			):
																			if bbox[i, j, 3] < bbox[i, j, 1]:
																									_UpperCamelCase :		List[Any]			    =       bbox[i, j, 3]
																									_UpperCamelCase :		List[str]			    =       bbox[i, j, 1]
																									_UpperCamelCase :		str			    =       t
																			if bbox[i, j, 2] < bbox[i, j, 0]:
																									_UpperCamelCase :		Optional[Any]			    =       bbox[i, j, 2]
																									_UpperCamelCase :		Tuple			    =       bbox[i, j, 0]
																									_UpperCamelCase :		List[str]			    =       t

							_UpperCamelCase :		str			    =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

							_UpperCamelCase :		Optional[Any]			    =       None
							if self.use_input_mask:
													_UpperCamelCase :		List[Any]			    =       random_attention_mask([self.batch_size, self.text_seq_length]			)

							_UpperCamelCase :		Any			    =       None
							if self.use_token_type_ids:
													_UpperCamelCase :		Tuple			    =       ids_tensor([self.batch_size, self.text_seq_length]			,self.type_vocab_size			)

							_UpperCamelCase :		List[str]			    =       None
							_UpperCamelCase :		Any			    =       None
							if self.use_labels:
													_UpperCamelCase :		Optional[Any]			    =       ids_tensor([self.batch_size]			,self.type_sequence_label_size			)
													_UpperCamelCase :		Dict			    =       ids_tensor([self.batch_size, self.text_seq_length]			,self.num_labels			)

							_UpperCamelCase :		Tuple			    =       LayoutLMvaConfig(
							    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			,initializer_range=self.initializer_range			,coordinate_size=self.coordinate_size			,shape_size=self.shape_size			,input_size=self.image_size			,patch_size=self.patch_size			,)

							return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels





	def      UpperCamelCase_  (			self :    Dict			,lowerCamelCase__ :    List[Any]			,lowerCamelCase__ :    Optional[Any]			,lowerCamelCase__ :    str			,lowerCamelCase__ :    Tuple			,lowerCamelCase__ :    int			,lowerCamelCase__ :    Optional[int]			,lowerCamelCase__ :    Any			,lowerCamelCase__ :    Optional[int]			):







							'''simple docstring'''
							_UpperCamelCase :		Tuple			    =       LayoutLMvaModel(config=lowerCamelCase__			)
							model.to(lowerCamelCase__			)
							model.eval()

							# text + image
							_UpperCamelCase :		Dict			    =       model(lowerCamelCase__			,pixel_values=lowerCamelCase__			)
							_UpperCamelCase :		Optional[int]			    =       model(
							    lowerCamelCase__			,bbox=lowerCamelCase__			,pixel_values=lowerCamelCase__			,attention_mask=lowerCamelCase__			,token_type_ids=lowerCamelCase__			)
							_UpperCamelCase :		Union[str, Any]			    =       model(lowerCamelCase__			,bbox=lowerCamelCase__			,pixel_values=lowerCamelCase__			,token_type_ids=lowerCamelCase__			)
							_UpperCamelCase :		List[str]			    =       model(lowerCamelCase__			,bbox=lowerCamelCase__			,pixel_values=lowerCamelCase__			)

							self.parent.assertEqual(result.last_hidden_state.shape			,(self.batch_size, self.seq_length, self.hidden_size)			)

							# text only
							_UpperCamelCase :		int			    =       model(lowerCamelCase__			)
							self.parent.assertEqual(
							    result.last_hidden_state.shape			,(self.batch_size, self.text_seq_length, self.hidden_size)			)

							# image only
							_UpperCamelCase :		Optional[int]			    =       model(pixel_values=lowerCamelCase__			)
							self.parent.assertEqual(
							    result.last_hidden_state.shape			,(self.batch_size, self.image_seq_length, self.hidden_size)			)





	def      UpperCamelCase_  (			self :    List[str]			,lowerCamelCase__ :    Any			,lowerCamelCase__ :    Any			,lowerCamelCase__ :    List[str]			,lowerCamelCase__ :    Any			,lowerCamelCase__ :    Any			,lowerCamelCase__ :    Any			,lowerCamelCase__ :    str			,lowerCamelCase__ :    Optional[Any]			):







							'''simple docstring'''
							_UpperCamelCase :		Dict			    =       self.num_labels
							_UpperCamelCase :		List[Any]			    =       LayoutLMvaForSequenceClassification(lowerCamelCase__			)
							model.to(lowerCamelCase__			)
							model.eval()
							_UpperCamelCase :		str			    =       model(
							    lowerCamelCase__			,bbox=lowerCamelCase__			,pixel_values=lowerCamelCase__			,attention_mask=lowerCamelCase__			,token_type_ids=lowerCamelCase__			,labels=lowerCamelCase__			,)
							self.parent.assertEqual(result.logits.shape			,(self.batch_size, self.num_labels)			)





	def      UpperCamelCase_  (			self :    Union[str, Any]			,lowerCamelCase__ :    Optional[int]			,lowerCamelCase__ :    List[str]			,lowerCamelCase__ :    Tuple			,lowerCamelCase__ :    str			,lowerCamelCase__ :    List[Any]			,lowerCamelCase__ :    Tuple			,lowerCamelCase__ :    List[str]			,lowerCamelCase__ :    Union[str, Any]			):







							'''simple docstring'''
							_UpperCamelCase :		Any			    =       self.num_labels
							_UpperCamelCase :		Dict			    =       LayoutLMvaForTokenClassification(config=lowerCamelCase__			)
							model.to(lowerCamelCase__			)
							model.eval()
							_UpperCamelCase :		Optional[int]			    =       model(
							    lowerCamelCase__			,bbox=lowerCamelCase__			,pixel_values=lowerCamelCase__			,attention_mask=lowerCamelCase__			,token_type_ids=lowerCamelCase__			,labels=lowerCamelCase__			,)
							self.parent.assertEqual(result.logits.shape			,(self.batch_size, self.text_seq_length, self.num_labels)			)





	def      UpperCamelCase_  (			self :    int			,lowerCamelCase__ :    int			,lowerCamelCase__ :    str			,lowerCamelCase__ :    Tuple			,lowerCamelCase__ :    Optional[int]			,lowerCamelCase__ :    int			,lowerCamelCase__ :    List[str]			,lowerCamelCase__ :    Optional[Any]			,lowerCamelCase__ :    Dict			):







							'''simple docstring'''
							_UpperCamelCase :		int			    =       LayoutLMvaForQuestionAnswering(config=lowerCamelCase__			)
							model.to(lowerCamelCase__			)
							model.eval()
							_UpperCamelCase :		str			    =       model(
							    lowerCamelCase__			,bbox=lowerCamelCase__			,pixel_values=lowerCamelCase__			,attention_mask=lowerCamelCase__			,token_type_ids=lowerCamelCase__			,start_positions=lowerCamelCase__			,end_positions=lowerCamelCase__			,)
							self.parent.assertEqual(result.start_logits.shape			,(self.batch_size, self.seq_length)			)
							self.parent.assertEqual(result.end_logits.shape			,(self.batch_size, self.seq_length)			)





	def      UpperCamelCase_  (			self :    List[Any]			):







							'''simple docstring'''
							_UpperCamelCase :		List[str]			    =       self.prepare_config_and_inputs()
							(
							    _UpperCamelCase      
							) :		Any			    =       config_and_inputs
							_UpperCamelCase :		str			    =       {
							    'input_ids': input_ids,
							    'bbox': bbox,
							    'pixel_values': pixel_values,
							    'token_type_ids': token_type_ids,
							    'attention_mask': input_mask,
							}
							return config, inputs_dict






@require_torch
class 							lowercase__     (							lowercase						, lowercase						, unittest.TestCase       ):
	lowercase__      =      False
	lowercase__      =      False
	lowercase__      =      False

	lowercase__      =      (
	    (
	        LayoutLMvaModel,
	        LayoutLMvaForSequenceClassification,
	        LayoutLMvaForTokenClassification,
	        LayoutLMvaForQuestionAnswering,
	    )
	    if is_torch_available()
	    else ()
	)
	lowercase__      =      (
	    {"""document-question-answering""": LayoutLMvaForQuestionAnswering, """feature-extraction""": LayoutLMvaModel}
	    if is_torch_available()
	    else {}
	)





	def      UpperCamelCase_  (			self :    Tuple			,lowerCamelCase__ :    Optional[int]			,lowerCamelCase__ :    int			,lowerCamelCase__ :    Any			,lowerCamelCase__ :    Optional[int]			,lowerCamelCase__ :    str			):







							'''simple docstring'''
							return True





	def      UpperCamelCase_  (			self :    Optional[Any]			):







							'''simple docstring'''
							_UpperCamelCase :		List[str]			    =       LayoutLMvaModelTester(self			)
							_UpperCamelCase :		Optional[int]			    =       ConfigTester(self			,config_class=lowerCamelCase__			,hidden_size=37			)





	def      UpperCamelCase_  (			self :    Optional[Any]			,lowerCamelCase__ :    Dict			,lowerCamelCase__ :    List[str]			,lowerCamelCase__ :    Union[str, Any]=False			):







							'''simple docstring'''
							_UpperCamelCase :		List[Any]			    =       copy.deepcopy(lowerCamelCase__			)
							if model_class in get_values(lowerCamelCase__			):
													_UpperCamelCase :		Any			    =       {
													    k: v.unsqueeze(1			).expand(-1			,self.model_tester.num_choices			,-1			).contiguous()
													    if isinstance(lowerCamelCase__			,torch.Tensor			) and v.ndim > 1
													    else v
													    for k, v in inputs_dict.items()
													}
							if return_labels:
													if model_class in get_values(lowerCamelCase__			):
																			_UpperCamelCase :		Dict			    =       torch.ones(self.model_tester.batch_size			,dtype=torch.long			,device=lowerCamelCase__			)
													elif model_class in get_values(lowerCamelCase__			):
																			_UpperCamelCase :		Union[str, Any]			    =       torch.zeros(
																			    self.model_tester.batch_size			,dtype=torch.long			,device=lowerCamelCase__			)
																			_UpperCamelCase :		Optional[int]			    =       torch.zeros(
																			    self.model_tester.batch_size			,dtype=torch.long			,device=lowerCamelCase__			)
													elif model_class in [
													    *get_values(lowerCamelCase__			),
													]:
																			_UpperCamelCase :		Any			    =       torch.zeros(
																			    self.model_tester.batch_size			,dtype=torch.long			,device=lowerCamelCase__			)
													elif model_class in [
													    *get_values(lowerCamelCase__			),
													]:
																			_UpperCamelCase :		Optional[int]			    =       torch.zeros(
																			    (self.model_tester.batch_size, self.model_tester.text_seq_length)			,dtype=torch.long			,device=lowerCamelCase__			,)

							return inputs_dict





	def      UpperCamelCase_  (			self :    Dict			):







							'''simple docstring'''
							self.config_tester.run_common_tests()





	def      UpperCamelCase_  (			self :    Any			):







							'''simple docstring'''
							_UpperCamelCase :		Any			    =       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*lowerCamelCase__			)





	def      UpperCamelCase_  (			self :    Tuple			):







							'''simple docstring'''
							_UpperCamelCase :		Dict			    =       self.model_tester.prepare_config_and_inputs()
							for type in ["absolute", "relative_key", "relative_key_query"]:
													_UpperCamelCase :		str			    =       type
													self.model_tester.create_and_check_model(*lowerCamelCase__			)





	def      UpperCamelCase_  (			self :    Optional[int]			):







							'''simple docstring'''
							_UpperCamelCase :		List[Any]			    =       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_sequence_classification(*lowerCamelCase__			)





	def      UpperCamelCase_  (			self :    int			):







							'''simple docstring'''
							_UpperCamelCase :		int			    =       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_token_classification(*lowerCamelCase__			)





	def      UpperCamelCase_  (			self :    List[str]			):







							'''simple docstring'''
							_UpperCamelCase :		Optional[int]			    =       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_question_answering(*lowerCamelCase__			)





	@slow
	def      UpperCamelCase_  (			self :    List[str]			):







							'''simple docstring'''
							for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													_UpperCamelCase :		int			    =       LayoutLMvaModel.from_pretrained(lowerCamelCase__			)
													self.assertIsNotNone(lowerCamelCase__			)






def A__   (					):
						_UpperCamelCase :		Dict			    =       Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'							)
						return image






@require_torch
class 							lowercase__     (							unittest.TestCase       ):





	@cached_property
	def      UpperCamelCase_  (			self :    List[str]			):







							'''simple docstring'''
							return LayoutLMvaImageProcessor(apply_ocr=lowerCamelCase__			) if is_vision_available() else None





	@slow
	def      UpperCamelCase_  (			self :    int			):







							'''simple docstring'''
							_UpperCamelCase :		Optional[int]			    =       LayoutLMvaModel.from_pretrained('microsoft/layoutlmv3-base'			).to(lowerCamelCase__			)

							_UpperCamelCase :		Any			    =       self.default_image_processor
							_UpperCamelCase :		Tuple			    =       prepare_img()
							_UpperCamelCase :		Optional[Any]			    =       image_processor(images=lowerCamelCase__			,return_tensors='pt'			).pixel_values.to(lowerCamelCase__			)

							_UpperCamelCase :		Tuple			    =       torch.tensor([[1, 2]]			)
							_UpperCamelCase :		List[Any]			    =       torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]]			).unsqueeze(0			)

							# forward pass
							_UpperCamelCase :		List[Any]			    =       model(
							    input_ids=input_ids.to(lowerCamelCase__			)			,bbox=bbox.to(lowerCamelCase__			)			,pixel_values=pixel_values.to(lowerCamelCase__			)			,)

							# verify the logits
							_UpperCamelCase :		int			    =       torch.Size((1, 199, 768)			)
							self.assertEqual(outputs.last_hidden_state.shape			,lowerCamelCase__			)

							_UpperCamelCase :		int			    =       torch.tensor(
							    [[-0.0_5_2_9, 0.3_6_1_8, 0.1_6_3_2], [-0.1_5_8_7, -0.1_6_6_7, -0.0_4_0_0], [-0.1_5_5_7, -0.1_6_7_1, -0.0_5_0_5]]			).to(lowerCamelCase__			)

							self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3]			,lowerCamelCase__			,atol=1E-4			)			)







'''simple docstring'''
import argparse
import os

from . import (
    ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    BART_PRETRAINED_MODEL_ARCHIVE_LIST,
    BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP,
    DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
    DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
    DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST,
    ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP,
    FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP,
    LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST,
    LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP,
    T5_PRETRAINED_CONFIG_ARCHIVE_MAP,
    TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP,
    WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP,
    XLM_PRETRAINED_CONFIG_ARCHIVE_MAP,
    XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP,
    XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP,
    AlbertConfig,
    BartConfig,
    BertConfig,
    CamembertConfig,
    CTRLConfig,
    DistilBertConfig,
    DPRConfig,
    ElectraConfig,
    FlaubertConfig,
    GPTaConfig,
    LayoutLMConfig,
    LxmertConfig,
    OpenAIGPTConfig,
    RobertaConfig,
    TaConfig,
    TFAlbertForPreTraining,
    TFBartForConditionalGeneration,
    TFBartForSequenceClassification,
    TFBertForPreTraining,
    TFBertForQuestionAnswering,
    TFBertForSequenceClassification,
    TFCamembertForMaskedLM,
    TFCTRLLMHeadModel,
    TFDistilBertForMaskedLM,
    TFDistilBertForQuestionAnswering,
    TFDPRContextEncoder,
    TFDPRQuestionEncoder,
    TFDPRReader,
    TFElectraForPreTraining,
    TFFlaubertWithLMHeadModel,
    TFGPTaLMHeadModel,
    TFLayoutLMForMaskedLM,
    TFLxmertForPreTraining,
    TFLxmertVisualFeatureEncoder,
    TFOpenAIGPTLMHeadModel,
    TFRobertaForCausalLM,
    TFRobertaForMaskedLM,
    TFRobertaForSequenceClassification,
    TFTaForConditionalGeneration,
    TFTransfoXLLMHeadModel,
    TFWavaVecaModel,
    TFXLMRobertaForMaskedLM,
    TFXLMWithLMHeadModel,
    TFXLNetLMHeadModel,
    TransfoXLConfig,
    WavaVecaConfig,
    WavaVecaModel,
    XLMConfig,
    XLMRobertaConfig,
    XLNetConfig,
    is_torch_available,
    load_pytorch_checkpoint_in_tfa_model,
)
from .utils import CONFIG_NAME, WEIGHTS_NAME, cached_file, logging


if is_torch_available():
					import numpy as np
					import torch

					from . import (
					    AlbertForPreTraining,
					    BartForConditionalGeneration,
					    BertForPreTraining,
					    BertForQuestionAnswering,
					    BertForSequenceClassification,
					    CamembertForMaskedLM,
					    CTRLLMHeadModel,
					    DistilBertForMaskedLM,
					    DistilBertForQuestionAnswering,
					    DPRContextEncoder,
					    DPRQuestionEncoder,
					    DPRReader,
					    ElectraForPreTraining,
					    FlaubertWithLMHeadModel,
					    GPTaLMHeadModel,
					    LayoutLMForMaskedLM,
					    LxmertForPreTraining,
					    LxmertVisualFeatureEncoder,
					    OpenAIGPTLMHeadModel,
					    RobertaForMaskedLM,
					    RobertaForSequenceClassification,
					    TaForConditionalGeneration,
					    TransfoXLLMHeadModel,
					    XLMRobertaForMaskedLM,
					    XLMWithLMHeadModel,
					    XLNetLMHeadModel,
					)


logging.set_verbosity_info()

snake_case_			:     Dict  	=  {
    'bart': (
        BartConfig,
        TFBartForConditionalGeneration,
        TFBartForSequenceClassification,
        BartForConditionalGeneration,
        BART_PRETRAINED_MODEL_ARCHIVE_LIST,
    ),
    'bert': (
        BertConfig,
        TFBertForPreTraining,
        BertForPreTraining,
        BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    'bert-large-uncased-whole-word-masking-finetuned-squad': (
        BertConfig,
        TFBertForQuestionAnswering,
        BertForQuestionAnswering,
        BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    'bert-large-cased-whole-word-masking-finetuned-squad': (
        BertConfig,
        TFBertForQuestionAnswering,
        BertForQuestionAnswering,
        BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    'bert-base-cased-finetuned-mrpc': (
        BertConfig,
        TFBertForSequenceClassification,
        BertForSequenceClassification,
        BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    'dpr': (
        DPRConfig,
        TFDPRQuestionEncoder,
        TFDPRContextEncoder,
        TFDPRReader,
        DPRQuestionEncoder,
        DPRContextEncoder,
        DPRReader,
        DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
        DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
        DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST,
    ),
    'gpt2': (
        GPTaConfig,
        TFGPTaLMHeadModel,
        GPTaLMHeadModel,
        GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    'xlnet': (
        XLNetConfig,
        TFXLNetLMHeadModel,
        XLNetLMHeadModel,
        XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    'xlm': (
        XLMConfig,
        TFXLMWithLMHeadModel,
        XLMWithLMHeadModel,
        XLM_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    'xlm-roberta': (
        XLMRobertaConfig,
        TFXLMRobertaForMaskedLM,
        XLMRobertaForMaskedLM,
        XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    'transfo-xl': (
        TransfoXLConfig,
        TFTransfoXLLMHeadModel,
        TransfoXLLMHeadModel,
        TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    'openai-gpt': (
        OpenAIGPTConfig,
        TFOpenAIGPTLMHeadModel,
        OpenAIGPTLMHeadModel,
        OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    'roberta': (
        RobertaConfig,
        TFRobertaForCausalLM,
        TFRobertaForMaskedLM,
        RobertaForMaskedLM,
        ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    'layoutlm': (
        LayoutLMConfig,
        TFLayoutLMForMaskedLM,
        LayoutLMForMaskedLM,
        LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST,
    ),
    'roberta-large-mnli': (
        RobertaConfig,
        TFRobertaForSequenceClassification,
        RobertaForSequenceClassification,
        ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    'camembert': (
        CamembertConfig,
        TFCamembertForMaskedLM,
        CamembertForMaskedLM,
        CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    'flaubert': (
        FlaubertConfig,
        TFFlaubertWithLMHeadModel,
        FlaubertWithLMHeadModel,
        FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    'distilbert': (
        DistilBertConfig,
        TFDistilBertForMaskedLM,
        DistilBertForMaskedLM,
        DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    'distilbert-base-distilled-squad': (
        DistilBertConfig,
        TFDistilBertForQuestionAnswering,
        DistilBertForQuestionAnswering,
        DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    'lxmert': (
        LxmertConfig,
        TFLxmertForPreTraining,
        LxmertForPreTraining,
        LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    'lxmert-visual-feature-encoder': (
        LxmertConfig,
        TFLxmertVisualFeatureEncoder,
        LxmertVisualFeatureEncoder,
        LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    'ctrl': (
        CTRLConfig,
        TFCTRLLMHeadModel,
        CTRLLMHeadModel,
        CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    'albert': (
        AlbertConfig,
        TFAlbertForPreTraining,
        AlbertForPreTraining,
        ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    't5': (
        TaConfig,
        TFTaForConditionalGeneration,
        TaForConditionalGeneration,
        T5_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    'electra': (
        ElectraConfig,
        TFElectraForPreTraining,
        ElectraForPreTraining,
        ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    'wav2vec2': (
        WavaVecaConfig,
        TFWavaVecaModel,
        WavaVecaModel,
        WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
}






def A__   (					UpperCAmelCase_  ,  UpperCAmelCase_  ,  UpperCAmelCase_  ,  UpperCAmelCase_  ,  UpperCAmelCase_=False  ,  UpperCAmelCase_=True							):
						if model_type not in MODEL_CLASSES:
												raise ValueError(f'Unrecognized model type, should be one of {list(MODEL_CLASSES.keys()							)}.'							)

						_UpperCamelCase    ,      _UpperCamelCase    ,      _UpperCamelCase    ,      _UpperCamelCase :		List[str]			    =       MODEL_CLASSES[model_type]

						# Initialise TF model
						if config_file in aws_config_map:
												_UpperCamelCase :		Optional[int]			    =       cached_file(UpperCAmelCase_  ,  UpperCAmelCase_  ,  force_download=not use_cached_models							)
						_UpperCamelCase :		Optional[Any]			    =       config_class.from_json_file(UpperCAmelCase_							)
						_UpperCamelCase :		Optional[Any]			    =       True
						_UpperCamelCase :		List[str]			    =       True
						print(f'Building TensorFlow model from configuration: {config}'							)
						_UpperCamelCase :		Any			    =       model_class(UpperCAmelCase_							)

						# Load weights from tf checkpoint
						if pytorch_checkpoint_path in aws_config_map.keys():
												_UpperCamelCase :		Union[str, Any]			    =       cached_file(
												    UpperCAmelCase_  ,  UpperCAmelCase_  ,  force_download=not use_cached_models							)
						# Load PyTorch checkpoint in tf2 model:
						_UpperCamelCase :		List[Any]			    =       load_pytorch_checkpoint_in_tfa_model(UpperCAmelCase_  ,  UpperCAmelCase_							)

						if compare_with_pt_model:
												_UpperCamelCase :		Optional[int]			    =       tf_model(tf_model.dummy_inputs  ,  training=UpperCAmelCase_							)  # build the network

												_UpperCamelCase :		Optional[Any]			    =       torch.load(UpperCAmelCase_  ,  map_location='cpu'							)
												_UpperCamelCase :		List[str]			    =       pt_model_class.from_pretrained(
												    pretrained_model_name_or_path=UpperCAmelCase_  ,  config=UpperCAmelCase_  ,  state_dict=UpperCAmelCase_							)

												with torch.no_grad():
																		_UpperCamelCase :		Optional[Any]			    =       pt_model(**pt_model.dummy_inputs							)

												_UpperCamelCase :		int			    =       pto[0].numpy()
												_UpperCamelCase :		Any			    =       tfo[0].numpy()
												_UpperCamelCase :		Dict			    =       np.amax(np.abs(np_pt - np_tf							)							)
												print(f'Max absolute difference between models outputs {diff}'							)
												assert diff <= 2E-2, f'Error, model absolute difference is >2e-2: {diff}'

						# Save pytorch-model
						print(f'Save TensorFlow model to {tf_dump_path}'							)
						tf_model.save_weights(UpperCAmelCase_  ,  save_format='h5'							)






def A__   (					UpperCAmelCase_  ,  UpperCAmelCase_  ,  UpperCAmelCase_=None  ,  UpperCAmelCase_=None  ,  UpperCAmelCase_=False  ,  UpperCAmelCase_=False  ,  UpperCAmelCase_=False  ,  UpperCAmelCase_=False  ,  ):
						if args_model_type is None:
												_UpperCamelCase :		List[Any]			    =       list(MODEL_CLASSES.keys()							)
						else:
												_UpperCamelCase :		Tuple			    =       [args_model_type]

						for j, model_type in enumerate(UpperCAmelCase_  ,  start=1							):
												print('=' * 1_0_0							)
												print(f' Converting model type {j}/{len(UpperCAmelCase_							)}: {model_type}'							)
												print('=' * 1_0_0							)
												if model_type not in MODEL_CLASSES:
																		raise ValueError(f'Unrecognized model type {model_type}, should be one of {list(MODEL_CLASSES.keys()							)}.'							)

												_UpperCamelCase    ,      _UpperCamelCase    ,      _UpperCamelCase    ,      _UpperCamelCase    ,      _UpperCamelCase :		Any			    =       MODEL_CLASSES[model_type]

												if model_shortcut_names_or_path is None:
																		_UpperCamelCase :		List[Any]			    =       list(aws_model_maps.keys()							)
												if config_shortcut_names_or_path is None:
																		_UpperCamelCase :		int			    =       model_shortcut_names_or_path

												for i, (model_shortcut_name, config_shortcut_name) in enumerate(
												    zip(UpperCAmelCase_  ,  UpperCAmelCase_							)  ,  start=1							):
																		print('-' * 1_0_0							)
																		if "-squad" in model_shortcut_name or "-mrpc" in model_shortcut_name or "-mnli" in model_shortcut_name:
																								if not only_convert_finetuned_models:
																														print(f'    Skipping finetuned checkpoint {model_shortcut_name}'							)
																														continue
																								_UpperCamelCase :		Dict			    =       model_shortcut_name
																		elif only_convert_finetuned_models:
																								print(f'    Skipping not finetuned checkpoint {model_shortcut_name}'							)
																								continue
																		print(
																		    f'    Converting checkpoint {i}/{len(UpperCAmelCase_							)}: {model_shortcut_name} - model_type {model_type}'							)
																		print('-' * 1_0_0							)

																		if config_shortcut_name in aws_config_map:
																								_UpperCamelCase :		Any			    =       cached_file(UpperCAmelCase_  ,  UpperCAmelCase_  ,  force_download=not use_cached_models							)
																		else:
																								_UpperCamelCase :		str			    =       config_shortcut_name

																		if model_shortcut_name in aws_model_maps:
																								_UpperCamelCase :		int			    =       cached_file(UpperCAmelCase_  ,  UpperCAmelCase_  ,  force_download=not use_cached_models							)
																		else:
																								_UpperCamelCase :		List[str]			    =       model_shortcut_name

																		if os.path.isfile(UpperCAmelCase_							):
																								_UpperCamelCase :		Union[str, Any]			    =       'converted_model'

																		convert_pt_checkpoint_to_tf(
																		    model_type=UpperCAmelCase_  ,  pytorch_checkpoint_path=UpperCAmelCase_  ,  config_file=UpperCAmelCase_  ,  tf_dump_path=os.path.join(UpperCAmelCase_  ,  model_shortcut_name + '-tf_model.h5'							)  ,  compare_with_pt_model=UpperCAmelCase_  ,  )
																		if remove_cached_files:
																								os.remove(UpperCAmelCase_							)
																								os.remove(UpperCAmelCase_							)


if __name__ == "__main__":
					snake_case_			:     Optional[Any]  	=  argparse.ArgumentParser()
					# Required parameters
					parser.add_argument(
					    '--tf_dump_path', default=None, type=str, required=True, help='Path to the output Tensorflow dump file.'
					)
					parser.add_argument(
					    '--model_type',
					    default=None,
					    type=str,
					    help=(
					        F"""Model type selected in the list of {list(MODEL_CLASSES.keys())}. If not given, will download and """
					        'convert all the models from AWS.'
					    ),
					)
					parser.add_argument(
					    '--pytorch_checkpoint_path',
					    default=None,
					    type=str,
					    help=(
					        'Path to the PyTorch checkpoint path or shortcut name to download from AWS. '
					        'If not given, will download and convert all the checkpoints from AWS.'
					    ),
					)
					parser.add_argument(
					    '--config_file',
					    default=None,
					    type=str,
					    help=(
					        'The config json file corresponding to the pre-trained model. \n'
					        'This specifies the model architecture. If not given and '
					        '--pytorch_checkpoint_path is not given or is a shortcut name '
					        'use the configuration associated to the shortcut name on the AWS'
					    ),
					)
					parser.add_argument(
					    '--compare_with_pt_model', action='store_true', help='Compare Tensorflow and PyTorch model predictions.'
					)
					parser.add_argument(
					    '--use_cached_models',
					    action='store_true',
					    help='Use cached models if possible instead of updating to latest checkpoint versions.',
					)
					parser.add_argument(
					    '--remove_cached_files',
					    action='store_true',
					    help='Remove pytorch models after conversion (save memory when converting in batches).',
					)
					parser.add_argument('--only_convert_finetuned_models', action='store_true', help='Only convert finetuned models.')
					snake_case_			:     Optional[int]  	=  parser.parse_args()

					# if args.pytorch_checkpoint_path is not None:
					#     convert_pt_checkpoint_to_tf(args.model_type.lower(),
					#                                 args.pytorch_checkpoint_path,
					#                                 args.config_file if args.config_file is not None else args.pytorch_checkpoint_path,
					#                                 args.tf_dump_path,
					#                                 compare_with_pt_model=args.compare_with_pt_model,
					#                                 use_cached_models=args.use_cached_models)
					# else:
					convert_all_pt_checkpoints_to_tf(
					    args.model_type.lower() if args.model_type is not None else None,
					    args.tf_dump_path,
					    model_shortcut_names_or_path=[args.pytorch_checkpoint_path]
					    if args.pytorch_checkpoint_path is not None
					    else None,
					    config_shortcut_names_or_path=[args.config_file] if args.config_file is not None else None,
					    compare_with_pt_model=args.compare_with_pt_model,
					    use_cached_models=args.use_cached_models,
					    remove_cached_files=args.remove_cached_files,
					    only_convert_finetuned_models=args.only_convert_finetuned_models,
					)


