
import random
import timeit
from functools import wraps
from typing import Callable, Optional

from ..configuration_utils import PretrainedConfig
from ..models.auto.modeling_tf_auto import TF_MODEL_MAPPING, TF_MODEL_WITH_LM_HEAD_MAPPING
from ..utils import is_pyanvml_available, is_tf_available, logging
from .benchmark_utils import (
    Benchmark,
    Memory,
    MemorySummary,
    measure_peak_memory_cpu,
    start_memory_tracing,
    stop_memory_tracing,
)


if is_tf_available():
						import tensorflow as tf
						from tensorflow.python.framework.errors_impl import ResourceExhaustedError

						from .benchmark_args_tf import TensorFlowBenchmarkArguments

if is_pyanvml_available():
						import pyanvml.pyanvml as nvml

__a         =   logging.get_logger(__name__)




def 							a		(				snake_case__:   bool		,  snake_case__:   bool   ):


				'''simple docstring'''
				def run_func(snake_case__:   List[Any]   ):
								@wraps(snake_case__   )
								def run_in_eager_mode(*snake_case__:   List[Any]		,  **snake_case__:   str   ):
												return func(*snake_case__		,  **snake_case__   )

								@wraps(snake_case__   )
								@tf.function(experimental_compile=snake_case__   )
								def run_in_graph_mode(*snake_case__:   str		,  **snake_case__:   Dict   ):
												return func(*snake_case__		,  **snake_case__   )

								if do_eager_mode is True:
												if use_xla is not False:
																raise ValueError(
																    '''Cannot run model in XLA, if `args.eager_mode` is set to `True`. Please set `args.eager_mode=False`.'''   )
												return run_in_eager_mode
								else:
												return run_in_graph_mode

				return run_func




def 							a		(				snake_case__:   int		,  snake_case__:   int		,  snake_case__:   int   ):


				'''simple docstring'''
				lowercase_	    =   random.Random()
				lowercase_	    =   [rng.randint(0		,  vocab_size - 1   ) for i in range(batch_size * sequence_length   )]
				return tf.constant(snake_case__		,  shape=(batch_size, sequence_length)		,  dtype=tf.intaa   )


class 					lowercase__(							UpperCAmelCase				):



	"""simple docstring"""




	a     :TensorFlowBenchmarkArguments
	a     :PretrainedConfig
	a     :str       	=      "TensorFlow"
	@property
	def 		_lowercase    (			self    :     Tuple			)			->	Dict:
					return tf.__version__
	def 		_lowercase    (			self    :     List[Any]			,				SCREAMING_SNAKE_CASE_    :     str			,				SCREAMING_SNAKE_CASE_    :     int			,				SCREAMING_SNAKE_CASE_    :     int			)			->	float:
					# initialize GPU on separate process
					lowercase_	    =   self.args.strategy
					if strategy is None:
									raise ValueError('''A device strategy has to be initialized before using TensorFlow.'''			)
					lowercase_	    =   self._prepare_inference_func(SCREAMING_SNAKE_CASE_			,				SCREAMING_SNAKE_CASE_			,				SCREAMING_SNAKE_CASE_			)
					return self._measure_speed(_inference			)
	def 		_lowercase    (			self    :     List[Any]			,				SCREAMING_SNAKE_CASE_    :     str			,				SCREAMING_SNAKE_CASE_    :     int			,				SCREAMING_SNAKE_CASE_    :     int			)			->	float:
					lowercase_	    =   self.args.strategy
					if strategy is None:
									raise ValueError('''A device strategy has to be initialized before using TensorFlow.'''			)
					lowercase_	    =   self._prepare_train_func(SCREAMING_SNAKE_CASE_			,				SCREAMING_SNAKE_CASE_			,				SCREAMING_SNAKE_CASE_			)
					return self._measure_speed(_train			)
	def 		_lowercase    (			self    :     Any			,				SCREAMING_SNAKE_CASE_    :     str			,				SCREAMING_SNAKE_CASE_    :     int			,				SCREAMING_SNAKE_CASE_    :     int			)			->	[Memory, Optional[MemorySummary]]:
					# initialize GPU on separate process
					if self.args.is_gpu:
									tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx]			,				SCREAMING_SNAKE_CASE_			)
					lowercase_	    =   self.args.strategy
					if strategy is None:
									raise ValueError('''A device strategy has to be initialized before using TensorFlow.'''			)
					lowercase_	    =   self._prepare_inference_func(SCREAMING_SNAKE_CASE_			,				SCREAMING_SNAKE_CASE_			,				SCREAMING_SNAKE_CASE_			)
					return self._measure_memory(_inference			)
	def 		_lowercase    (			self    :     str			,				SCREAMING_SNAKE_CASE_    :     str			,				SCREAMING_SNAKE_CASE_    :     int			,				SCREAMING_SNAKE_CASE_    :     int			)			->	[Memory, Optional[MemorySummary]]:
					if self.args.is_gpu:
									tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx]			,				SCREAMING_SNAKE_CASE_			)
					lowercase_	    =   self.args.strategy
					if strategy is None:
									raise ValueError('''A device strategy has to be initialized before using TensorFlow.'''			)

					lowercase_	    =   self._prepare_train_func(SCREAMING_SNAKE_CASE_			,				SCREAMING_SNAKE_CASE_			,				SCREAMING_SNAKE_CASE_			)
					return self._measure_memory(_train			)
	def 		_lowercase    (			self    :     List[Any]			,				SCREAMING_SNAKE_CASE_    :     str			,				SCREAMING_SNAKE_CASE_    :     int			,				SCREAMING_SNAKE_CASE_    :     int			)			->	Callable[[], None]:
					lowercase_	    =   self.config_dict[model_name]

					if self.args.fpaa:
									raise NotImplementedError('''Mixed precision is currently not supported.'''			)

					lowercase_	    =   (
					    hasattr(SCREAMING_SNAKE_CASE_			,				'''architectures'''			)
					    and isinstance(config.architectures			,				SCREAMING_SNAKE_CASE_			)
					    and len(config.architectures			) > 0
					)
					if not self.args.only_pretrain_model and has_model_class_in_config:
									try:
													lowercase_	    =   '''TF''' + config.architectures[0]  # prepend 'TF' for tensorflow model
													lowercase_	    =   __import__('''transformers'''			,				fromlist=[model_class]			)
													lowercase_	    =   getattr(SCREAMING_SNAKE_CASE_			,				SCREAMING_SNAKE_CASE_			)
													lowercase_	    =   model_cls(SCREAMING_SNAKE_CASE_			)
									except ImportError:
													raise ImportError(
													    f'''{model_class} does not exist. If you just want to test the pretrained model, you might want to'''
													    ''' set `--only_pretrain_model` or `args.only_pretrain_model=True`.'''			)
					else:
									lowercase_	    =   TF_MODEL_MAPPING[config.__class__](SCREAMING_SNAKE_CASE_			)

					# encoder-decoder has vocab size saved differently
					lowercase_	    =   config.vocab_size if hasattr(SCREAMING_SNAKE_CASE_			,				'''vocab_size'''			) else config.encoder.vocab_size
					lowercase_	    =   random_input_ids(SCREAMING_SNAKE_CASE_			,				SCREAMING_SNAKE_CASE_			,				SCREAMING_SNAKE_CASE_			)

					@run_with_tf_optimizations(self.args.eager_mode			,				self.args.use_xla			)
					def encoder_decoder_forward():
									return model(SCREAMING_SNAKE_CASE_			,				decoder_input_ids=SCREAMING_SNAKE_CASE_			,				training=SCREAMING_SNAKE_CASE_			)

					@run_with_tf_optimizations(self.args.eager_mode			,				self.args.use_xla			)
					def encoder_forward():
									return model(SCREAMING_SNAKE_CASE_			,				training=SCREAMING_SNAKE_CASE_			)

					lowercase_	    =   encoder_decoder_forward if config.is_encoder_decoder else encoder_forward

					return _inference
	def 		_lowercase    (			self    :     Dict			,				SCREAMING_SNAKE_CASE_    :     str			,				SCREAMING_SNAKE_CASE_    :     int			,				SCREAMING_SNAKE_CASE_    :     int			)			->	Callable[[], None]:
					lowercase_	    =   self.config_dict[model_name]

					if self.args.eager_mode is not False:
									raise ValueError('''Training cannot be done in eager mode. Please make sure that `args.eager_mode = False`.'''			)

					if self.args.fpaa:
									raise NotImplementedError('''Mixed precision is currently not supported.'''			)

					lowercase_	    =   (
					    hasattr(SCREAMING_SNAKE_CASE_			,				'''architectures'''			)
					    and isinstance(config.architectures			,				SCREAMING_SNAKE_CASE_			)
					    and len(config.architectures			) > 0
					)
					if not self.args.only_pretrain_model and has_model_class_in_config:
									try:
													lowercase_	    =   '''TF''' + config.architectures[0]  # prepend 'TF' for tensorflow model
													lowercase_	    =   __import__('''transformers'''			,				fromlist=[model_class]			)
													lowercase_	    =   getattr(SCREAMING_SNAKE_CASE_			,				SCREAMING_SNAKE_CASE_			)
													lowercase_	    =   model_cls(SCREAMING_SNAKE_CASE_			)
									except ImportError:
													raise ImportError(
													    f'''{model_class} does not exist. If you just want to test the pretrained model, you might want to'''
													    ''' set `--only_pretrain_model` or `args.only_pretrain_model=True`.'''			)
					else:
									lowercase_	    =   TF_MODEL_WITH_LM_HEAD_MAPPING[config.__class__](SCREAMING_SNAKE_CASE_			)

					# encoder-decoder has vocab size saved differently
					lowercase_	    =   config.vocab_size if hasattr(SCREAMING_SNAKE_CASE_			,				'''vocab_size'''			) else config.encoder.vocab_size
					lowercase_	    =   random_input_ids(SCREAMING_SNAKE_CASE_			,				SCREAMING_SNAKE_CASE_			,				SCREAMING_SNAKE_CASE_			)

					@run_with_tf_optimizations(self.args.eager_mode			,				self.args.use_xla			)
					def encoder_decoder_train():
									lowercase_	    =   model(SCREAMING_SNAKE_CASE_			,				decoder_input_ids=SCREAMING_SNAKE_CASE_			,				labels=SCREAMING_SNAKE_CASE_			,				training=SCREAMING_SNAKE_CASE_			)[0]
									lowercase_	    =   tf.gradients(SCREAMING_SNAKE_CASE_			,				model.trainable_variables			)
									return gradients

					@run_with_tf_optimizations(self.args.eager_mode			,				self.args.use_xla			)
					def encoder_train():
									lowercase_	    =   model(SCREAMING_SNAKE_CASE_			,				labels=SCREAMING_SNAKE_CASE_			,				training=SCREAMING_SNAKE_CASE_			)[0]
									lowercase_	    =   tf.gradients(SCREAMING_SNAKE_CASE_			,				model.trainable_variables			)
									return gradients

					lowercase_	    =   encoder_decoder_train if config.is_encoder_decoder else encoder_train

					return _train
	def 		_lowercase    (			self    :     str			,				SCREAMING_SNAKE_CASE_    :     Tuple			)			->	float:
					with self.args.strategy.scope():
									try:
													if self.args.is_tpu or self.args.use_xla:
																	# run additional 10 times to stabilize compilation for tpu
																	logger.info('''Do inference on TPU. Running model 5 times to stabilize compilation'''			)
																	timeit.repeat(SCREAMING_SNAKE_CASE_			,				repeat=1			,				number=5			)

													# as written in https://docs.python.org/2/library/timeit.html#timeit.Timer.repeat, min should be taken rather than the average
													lowercase_	    =   timeit.repeat(
													    SCREAMING_SNAKE_CASE_			,				repeat=self.args.repeat			,				number=1_0			,				)

													return min(SCREAMING_SNAKE_CASE_			) / 10.0
									except ResourceExhaustedError as e:
													self.print_fn(f'''Doesn\'t fit on GPU. {e}'''			)




	def 		_lowercase    (			self    :     Tuple			,				SCREAMING_SNAKE_CASE_    :     Callable[[], None]			)			->	[Memory, MemorySummary]:
					logger.info(
					    '''Note that TensorFlow allocates more memory than '''
					    '''it might need to speed up computation. '''
					    '''The memory reported here corresponds to the memory '''
					    '''reported by `nvidia-smi`, which can vary depending '''
					    '''on total available memory on the GPU that is used.'''			)
					with self.args.strategy.scope():
									try:
													if self.args.trace_memory_line_by_line:
																	if not self.args.eager_mode:
																					raise ValueError(
																					    '''`args.eager_mode` is set to `False`. Make sure to run model in eager mode to measure memory'''
																					    ''' consumption line by line.'''			)
																	lowercase_	    =   start_memory_tracing('''transformers'''			)

													if self.args.is_tpu:
																	# tpu
																	raise NotImplementedError(
																	    '''Memory Benchmarking is currently not implemented for TPU. Please disable memory benchmarking'''
																	    ''' with `args.memory=False`'''			)
													elif self.args.is_gpu:
																	# gpu
																	if not is_pyanvml_available():
																					logger.warning(
																					    '''py3nvml not installed, we won\'t log GPU memory usage. '''
																					    '''Install py3nvml (pip install py3nvml) to log information about GPU.'''			)
																					lowercase_	    =   '''N/A'''
																	else:
																					logger.info(
																					    '''Measuring total GPU usage on GPU device. Make sure to not have additional processes'''
																					    ''' running on the same GPU.'''			)
																					# init nvml
																					nvml.nvmlInit()
																					func()
																					lowercase_	    =   nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx			)
																					lowercase_	    =   nvml.nvmlDeviceGetMemoryInfo(SCREAMING_SNAKE_CASE_			)
																					lowercase_	    =   meminfo.used
																					lowercase_	    =   Memory(SCREAMING_SNAKE_CASE_			)
																					# shutdown nvml
																					nvml.nvmlShutdown()
													else:
																	# cpu
																	if self.args.trace_memory_line_by_line:
																					logger.info(
																					    '''When enabling line by line tracing, the max peak memory for CPU is inaccurate in'''
																					    ''' TensorFlow.'''			)
																					lowercase_	    =   None
																	else:
																					lowercase_	    =   measure_peak_memory_cpu(SCREAMING_SNAKE_CASE_			)
																					lowercase_	    =   Memory(SCREAMING_SNAKE_CASE_			) if isinstance(SCREAMING_SNAKE_CASE_			,				SCREAMING_SNAKE_CASE_			) else memory_bytes
													if self.args.trace_memory_line_by_line:
																	lowercase_	    =   stop_memory_tracing(SCREAMING_SNAKE_CASE_			)
																	if memory is None:
																					lowercase_	    =   summary.total
													else:
																	lowercase_	    =   None

													return memory, summary
									except ResourceExhaustedError as e:
													self.print_fn(f'''Doesn\'t fit on GPU. {e}'''			)
													return "N/A", None







import argparse
import json
import os
from collections import OrderedDict

import torch

from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer
from transformers.tokenization_utils_base import AddedToken



@torch.no_grad()
def   __UpperCAmelCase					(      __a :     Tuple						,__a :     Dict						,__a :     List[str]						,__a :     Optional[Any]						,__a :     Tuple      )     ->	Dict:

					"""simple docstring"""

					with open(__a      ) as metadata_file:
										_a      :       Optional[Any]   =						json.load(__a      )
					_a      :       List[Any]   =						LukeConfig(use_entity_aware_attention=__a						,**metadata['''model_config''']      )

					# Load in the weights from the checkpoint_path
					_a      :       Optional[Any]   =						torch.load(__a						,map_location='''cpu'''      )['''module''']

					# Load the entity vocab file
					_a      :       Any   =						load_original_entity_vocab(__a      )
					# add an entry for [MASK2]
					_a      :       Union[str, Any]   =						max(entity_vocab.values()      ) + 1
					config.entity_vocab_size += 1

					_a      :       Dict   =						XLMRobertaTokenizer.from_pretrained(metadata['''model_config''']['''bert_model_name''']      )

					# Add special tokens to the token vocabulary for downstream tasks
					_a      :       Optional[int]   =						AddedToken('''<ent>'''						,lstrip=__a						,rstrip=__a      )
					_a      :       Tuple   =						AddedToken('''<ent2>'''						,lstrip=__a						,rstrip=__a      )
					tokenizer.add_special_tokens({'''additional_special_tokens''': [entity_token_a, entity_token_a]}      )
					config.vocab_size += 2

					print(F"""Saving tokenizer to {pytorch_dump_folder_path}"""      )
					tokenizer.save_pretrained(__a      )
					with open(os.path.join(__a						,'''tokenizer_config.json'''      )						,'''r'''      ) as f:
										_a      :       List[str]   =						json.load(__a      )
					_a      :       Tuple   =						'''MLukeTokenizer'''
					with open(os.path.join(__a						,'''tokenizer_config.json'''      )						,'''w'''      ) as f:
										json.dump(__a						,__a      )

					with open(os.path.join(__a						,MLukeTokenizer.vocab_files_names['''entity_vocab_file''']      )						,'''w'''      ) as f:
										json.dump(__a						,__a      )

					_a      :       Optional[int]   =						MLukeTokenizer.from_pretrained(__a      )

					# Initialize the embeddings of the special tokens
					_a      :       str   =						tokenizer.convert_tokens_to_ids(['''@''']      )[0]
					_a      :       Tuple   =						tokenizer.convert_tokens_to_ids(['''#''']      )[0]

					_a      :       Any   =						state_dict['''embeddings.word_embeddings.weight''']
					_a      :       Optional[int]   =						word_emb[ent_init_index].unsqueeze(0      )
					_a      :       Any   =						word_emb[enta_init_index].unsqueeze(0      )
					_a      :       Union[str, Any]   =						torch.cat([word_emb, ent_emb, enta_emb]      )
					# add special tokens for 'entity_predictions.bias'
					for bias_name in ["lm_head.decoder.bias", "lm_head.bias"]:
										_a      :       Tuple   =						state_dict[bias_name]
										_a      :       Optional[Any]   =						decoder_bias[ent_init_index].unsqueeze(0      )
										_a      :       Optional[int]   =						decoder_bias[enta_init_index].unsqueeze(0      )
										_a      :       Dict   =						torch.cat([decoder_bias, ent_decoder_bias, enta_decoder_bias]      )

					# Initialize the query layers of the entity-aware self-attention mechanism
					for layer_index in range(config.num_hidden_layers      ):
										for matrix_name in ["query.weight", "query.bias"]:
															_a      :       Tuple   =						F"""encoder.layer.{layer_index}.attention.self."""
															_a      :       List[Any]   =						state_dict[prefix + matrix_name]
															_a      :       Dict   =						state_dict[prefix + matrix_name]
															_a      :       List[Any]   =						state_dict[prefix + matrix_name]

    # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks
					_a      :       Union[str, Any]   =						state_dict['''entity_embeddings.entity_embeddings.weight''']
					_a      :       Optional[int]   =						entity_emb[entity_vocab['''[MASK]''']].unsqueeze(0      )
					_a      :       Any   =						torch.cat([entity_emb, entity_mask_emb]      )
					# add [MASK2] for 'entity_predictions.bias'
					_a      :       int   =						state_dict['''entity_predictions.bias''']
					_a      :       int   =						entity_prediction_bias[entity_vocab['''[MASK]''']].unsqueeze(0      )
					_a      :       Optional[Any]   =						torch.cat([entity_prediction_bias, entity_mask_bias]      )

					_a      :       Optional[int]   =						LukeForMaskedLM(config=__a      ).eval()

					state_dict.pop('''entity_predictions.decoder.weight'''      )
					state_dict.pop('''lm_head.decoder.weight'''      )
					state_dict.pop('''lm_head.decoder.bias'''      )
					_a      :       int   =						OrderedDict()
					for key, value in state_dict.items():
										if not (key.startswith('''lm_head'''      ) or key.startswith('''entity_predictions'''      )):
															_a      :       Optional[int]   =						state_dict[key]
										else:
															_a      :       Tuple   =						state_dict[key]

					_a ,   _a      :       int   =						model.load_state_dict(__a						,strict=__a      )

					if set(__a      ) != {"luke.embeddings.position_ids"}:
										raise ValueError(F"""Unexpected unexpected_keys: {unexpected_keys}"""      )
					if set(__a      ) != {
					    "lm_head.decoder.weight",
					    "lm_head.decoder.bias",
					    "entity_predictions.decoder.weight",
					}:
										raise ValueError(F"""Unexpected missing_keys: {missing_keys}"""      )

					model.tie_weights()
					assert (model.luke.embeddings.word_embeddings.weight == model.lm_head.decoder.weight).all()
					assert (model.luke.entity_embeddings.entity_embeddings.weight == model.entity_predictions.decoder.weight).all()

					# Check outputs
					_a      :       Optional[int]   =						MLukeTokenizer.from_pretrained(__a						,task='''entity_classification'''      )

					_a      :       int   =						'''ISO 639-3 uses the code fas for the dialects spoken across Iran and アフガニスタン (Afghanistan).'''
					_a      :       List[Any]   =						(0, 9)
					_a      :       Tuple   =						tokenizer(__a						,entity_spans=[span]						,return_tensors='''pt'''      )

					_a      :       int   =						model(**__a      )

					# Verify word hidden states
					if model_size == "large":
										raise NotImplementedError
					else:  # base
										_a      :       List[str]   =						torch.Size((1, 33, 768)      )
										_a      :       Union[str, Any]   =						torch.tensor([[0.08_92, 0.05_96, -0.28_19], [0.01_34, 0.11_99, 0.05_73], [-0.01_69, 0.09_27, 0.06_44]]      )

					if not (outputs.last_hidden_state.shape == expected_shape):
										raise ValueError(
										    F"""Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}"""      )
					if not torch.allclose(outputs.last_hidden_state[0, :3, :3]						,__a						,atol=1E-4      ):
										raise ValueError

					# Verify entity hidden states
					if model_size == "large":
										raise NotImplementedError
					else:  # base
										_a      :       str   =						torch.Size((1, 1, 768)      )
										_a      :       List[Any]   =						torch.tensor([[-0.14_82, 0.06_09, 0.03_22]]      )

					if not (outputs.entity_last_hidden_state.shape == expected_shape):
										raise ValueError(
										    F"""Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is"""
										    F""" {expected_shape}"""      )
					if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3]						,__a						,atol=1E-4      ):
										raise ValueError

					# Verify masked word/entity prediction
					_a      :       Optional[int]   =						MLukeTokenizer.from_pretrained(__a      )
					_a      :       Dict   =						'''Tokyo is the capital of <mask>.'''
					_a      :       List[str]   =						(24, 30)
					_a      :       Optional[int]   =						tokenizer(__a						,entity_spans=[span]						,return_tensors='''pt'''      )

					_a      :       Optional[Any]   =						model(**__a      )

					_a      :       Any   =						encoding['''input_ids'''][0].tolist()
					_a      :       Optional[Any]   =						input_ids.index(tokenizer.convert_tokens_to_ids('''<mask>'''      )      )
					_a      :       Any   =						outputs.logits[0][mask_position_id].argmax(dim=-1      )
					assert "Japan" == tokenizer.decode(__a      )

					_a      :       Any   =						outputs.entity_logits[0][0].argmax().item()
					_a      :       Optional[Any]   =						[
					    entity for entity, entity_id in tokenizer.entity_vocab.items() if entity_id == predicted_entity_id
					]
					assert [e for e in multilingual_predicted_entities if e.startswith('''en:'''      )][0] == "en:Japan"

					# Finally, save our PyTorch model and tokenizer
					print('''Saving PyTorch model to {}'''.format(__a      )      )
					model.save_pretrained(__a      )



def   __UpperCAmelCase					(      __a :     List[Any]      )     ->	int:

					"""simple docstring"""

					_a      :       Union[str, Any]   =						['''[MASK]''', '''[PAD]''', '''[UNK]''']

					_a      :       int   =						[json.loads(__a      ) for line in open(__a      )]

					_a      :       List[Any]   =						{}
					for entry in data:
										_a      :       int   =						entry['''id''']
										for entity_name, language in entry["entities"]:
															if entity_name in SPECIAL_TOKENS:
																				_a      :       List[Any]   =						entity_id
																				break
															_a      :       Dict   =						F"""{language}:{entity_name}"""
															_a      :       int   =						entity_id
					return new_mapping


if __name__ == "__main__":
			a__												=						argparse.ArgumentParser()
			# Required parameters
			parser.add_argument('''--checkpoint_path''', type=str, help='''Path to a pytorch_model.bin file.''')
			parser.add_argument(
			    '''--metadata_path''', default=None, type=str, help='''Path to a metadata.json file, defining the configuration.'''
			)
			parser.add_argument(
			    '''--entity_vocab_path''',
			    default=None,
			    type=str,
			    help='''Path to an entity_vocab.tsv file, containing the entity vocabulary.''',
			)
			parser.add_argument(
			    '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to where to dump the output PyTorch model.'''
			)
			parser.add_argument(
			    '''--model_size''', default='''base''', type=str, choices=['''base''', '''large'''], help='''Size of the model to be converted.'''
			)
			a__												=						parser.parse_args()
			convert_luke_checkpoint(
			    args.checkpoint_path,
			    args.metadata_path,
			    args.entity_vocab_path,
			    args.pytorch_dump_folder_path,
			    args.model_size,
			)



