



import argparse
import json
import os

import torch

from transformers import LukeConfig, LukeModel, LukeTokenizer, RobertaTokenizer
from transformers.tokenization_utils_base import AddedToken




@torch.no_grad()
def    A_(			A				,      A				,      A				,      A				,      A   ):
	# Load configuration defined in the metadata file
	with open(a_   ) as metadata_file:
		UpperCAmelCase_								=     json.load(a_   )
	UpperCAmelCase_								=     LukeConfig(use_entity_aware_attention=a_				,      **metadata["""model_config"""]   )

	# Load in the weights from the checkpoint_path
	UpperCAmelCase_								=     torch.load(a_				,      map_location="""cpu"""   )

	# Load the entity vocab file
	UpperCAmelCase_								=     load_entity_vocab(a_   )

	UpperCAmelCase_								=     RobertaTokenizer.from_pretrained(metadata["""model_config"""]["""bert_model_name"""]   )

	# Add special tokens to the token vocabulary for downstream tasks
	UpperCAmelCase_								=     AddedToken("""<ent>"""				,      lstrip=a_				,      rstrip=a_   )
	UpperCAmelCase_								=     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_				,      LukeTokenizer.vocab_files_names["""entity_vocab_file"""]   )				,      """w"""   ) as f:
		json.dump(a_				,      a_   )

	UpperCAmelCase_								=     LukeTokenizer.from_pretrained(a_   )

	# Initialize the embeddings of the special tokens
	UpperCAmelCase_								=     state_dict['''embeddings.word_embeddings.weight''']
	UpperCAmelCase_								=     word_emb[tokenizer.convert_tokens_to_ids(["""@"""]   )[0]].unsqueeze(0   )
	UpperCAmelCase_								=     word_emb[tokenizer.convert_tokens_to_ids(["""#"""]   )[0]].unsqueeze(0   )
	UpperCAmelCase_								=     torch.cat([word_emb, ent_emb, enta_emb]   )

	# 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"]:
			UpperCAmelCase_								=     f"""encoder.layer.{layer_index}.attention.self."""
			UpperCAmelCase_								=     state_dict[prefix + matrix_name]
			UpperCAmelCase_								=     state_dict[prefix + matrix_name]
			UpperCAmelCase_								=     state_dict[prefix + matrix_name]

    # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks
	UpperCAmelCase_								=     state_dict['''entity_embeddings.entity_embeddings.weight''']
	UpperCAmelCase_								=     entity_emb[entity_vocab['''[MASK]''']]

	UpperCAmelCase_								=     LukeModel(config=a_   ).eval()

	UpperCAmelCase_								=     model.load_state_dict(a_				,      strict=a_   )
	if not (len(a_   ) == 1 and missing_keys[0] == "embeddings.position_ids"):
		raise ValueError(f"""Missing keys {', '.join(a_   )}. Expected only missing embeddings.position_ids"""   )
	if not (all(key.startswith("""entity_predictions"""   ) or key.startswith("""lm_head"""   ) for key in unexpected_keys   )):
		raise ValueError(
		    """Unexpected keys"""
		    f""" {', '.join([key for key in unexpected_keys if not (key.startswith('entity_predictions'   ) or key.startswith('lm_head'   ))]   )}"""   )

	# Check outputs
	UpperCAmelCase_								=     LukeTokenizer.from_pretrained(a_				,      task="""entity_classification"""   )

	UpperCAmelCase_								=     (
	    '''Top seed Ana Ivanovic said on Thursday she could hardly believe her luck as a fortuitous netcord helped the'''
	    ''' new world number one avoid a humiliating second- round exit at Wimbledon .'''
	)
	UpperCAmelCase_								=     (39, 42)
	UpperCAmelCase_								=     tokenizer(a_				,      entity_spans=[span]				,      add_prefix_space=a_				,      return_tensors="""pt"""   )

	UpperCAmelCase_								=     model(**a_   )

	# Verify word hidden states
	if model_size == "large":
		UpperCAmelCase_								=     torch.Size((1, 42, 1024)   )
		UpperCAmelCase_								=     torch.tensor(
		    [[0.0_133, 0.0_865, 0.0_095], [0.3_093, -0.2_576, -0.7_418], [-0.1_720, -0.2_117, -0.2_869]]   )
	else:  # base
		UpperCAmelCase_								=     torch.Size((1, 42, 768)   )
		UpperCAmelCase_								=     torch.tensor([[0.0_037, 0.1_368, -0.0_091], [0.1_099, 0.3_329, -0.1_095], [0.0_765, 0.5_335, 0.1_179]]   )

	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":
		UpperCAmelCase_								=     torch.Size((1, 1, 1024)   )
		UpperCAmelCase_								=     torch.tensor([[0.0_466, -0.0_106, -0.0_179]]   )
	else:  # base
		UpperCAmelCase_								=     torch.Size((1, 1, 768)   )
		UpperCAmelCase_								=     torch.tensor([[0.1_457, 0.1_044, 0.0_174]]   )

	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

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




def    A_(			A   ):
	UpperCAmelCase_								=     {}
	with open(a_				,      """r"""				,      encoding="""utf-8"""   ) as f:
		for index, line in enumerate(a_   ):
			UpperCAmelCase_								=     line.rstrip().split("""\t"""   )
			UpperCAmelCase_								=     index

	return entity_vocab


if __name__ == "__main__":
				UpperCamelCase__   : Optional[int]					  = 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."""
				)
				UpperCamelCase__   : Any					  = parser.parse_args()
				convert_luke_checkpoint(
				    args.checkpoint_path,
				    args.metadata_path,
				    args.entity_vocab_path,
				    args.pytorch_dump_folder_path,
				    args.model_size,
				)









import json
import os
import shutil
import tempfile
from unittest import TestCase

from transformers import BartTokenizer, BartTokenizerFast, DPRQuestionEncoderTokenizer, DPRQuestionEncoderTokenizerFast
from transformers.models.bart.configuration_bart import BartConfig
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES
from transformers.models.dpr.configuration_dpr import DPRConfig
from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES
from transformers.testing_utils import require_faiss, require_tokenizers, require_torch, slow
from transformers.utils import is_datasets_available, is_faiss_available, is_torch_available


if is_torch_available() and is_datasets_available() and is_faiss_available():
				from transformers.models.rag.configuration_rag import RagConfig
				from transformers.models.rag.tokenization_rag import RagTokenizer







@require_faiss
@require_torch
class   _UpperCamelCase  (       A_  ):







					'''simple docstring'''

					def        SCREAMING_SNAKE_CASE							(						self    :  Optional[Any]		):






						'''simple docstring'''







						UpperCAmelCase_								=     tempfile.mkdtemp()
						UpperCAmelCase_								=     8

						# DPR tok
						UpperCAmelCase_								=     [
						    """[UNK]""",
						    """[CLS]""",
						    """[SEP]""",
						    """[PAD]""",
						    """[MASK]""",
						    """want""",
						    """##want""",
						    """##ed""",
						    """wa""",
						    """un""",
						    """runn""",
						    """##ing""",
						    """,""",
						    """low""",
						    """lowest""",
						]
						UpperCAmelCase_								=     os.path.join(self.tmpdirname ,					"""dpr_tokenizer"""		)
						os.makedirs(__lowercase ,					exist_ok=__lowercase		)
						UpperCAmelCase_								=     os.path.join(__lowercase ,					DPR_VOCAB_FILES_NAMES["""vocab_file"""]		)
						with open(self.vocab_file ,					"""w""" ,					encoding="""utf-8"""		) as vocab_writer:
							vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens]		)		)

						# BART tok
						UpperCAmelCase_								=     [
						    """l""",
						    """o""",
						    """w""",
						    """e""",
						    """r""",
						    """s""",
						    """t""",
						    """i""",
						    """d""",
						    """n""",
						    """\u0120""",
						    """\u0120l""",
						    """\u0120n""",
						    """\u0120lo""",
						    """\u0120low""",
						    """er""",
						    """\u0120lowest""",
						    """\u0120newer""",
						    """\u0120wider""",
						    """<unk>""",
						]
						UpperCAmelCase_								=     dict(zip(__lowercase ,					range(len(__lowercase		)		)		)		)
						UpperCAmelCase_								=     ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""]
						UpperCAmelCase_								=     {"""unk_token""": """<unk>"""}

						UpperCAmelCase_								=     os.path.join(self.tmpdirname ,					"""bart_tokenizer"""		)
						os.makedirs(__lowercase ,					exist_ok=__lowercase		)
						UpperCAmelCase_								=     os.path.join(__lowercase ,					BART_VOCAB_FILES_NAMES["""vocab_file"""]		)
						UpperCAmelCase_								=     os.path.join(__lowercase ,					BART_VOCAB_FILES_NAMES["""merges_file"""]		)
						with open(self.vocab_file ,					"""w""" ,					encoding="""utf-8"""		) as fp:
							fp.write(json.dumps(__lowercase		) + """\n"""		)
						with open(self.merges_file ,					"""w""" ,					encoding="""utf-8"""		) as fp:
							fp.write("""\n""".join(__lowercase		)		)





					def        SCREAMING_SNAKE_CASE							(						self    :  Union[str, Any]		):






						'''simple docstring'''







						return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname ,					"""dpr_tokenizer"""		)		)





					def        SCREAMING_SNAKE_CASE							(						self    :  List[Any]		):






						'''simple docstring'''







						return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname ,					"""bart_tokenizer"""		)		)





					def        SCREAMING_SNAKE_CASE							(						self    :  str		):






						'''simple docstring'''







						shutil.rmtree(self.tmpdirname		)





					@require_tokenizers
					def        SCREAMING_SNAKE_CASE							(						self    :  Union[str, Any]		):






						'''simple docstring'''







						UpperCAmelCase_								=     os.path.join(self.tmpdirname ,					"""rag_tokenizer"""		)
						UpperCAmelCase_								=     RagConfig(question_encoder=DPRConfig().to_dict() ,					generator=BartConfig().to_dict()		)
						UpperCAmelCase_								=     RagTokenizer(question_encoder=self.get_dpr_tokenizer() ,					generator=self.get_bart_tokenizer()		)
						rag_config.save_pretrained(__lowercase		)
						rag_tokenizer.save_pretrained(__lowercase		)
						UpperCAmelCase_								=     RagTokenizer.from_pretrained(__lowercase ,					config=__lowercase		)
						self.assertIsInstance(new_rag_tokenizer.question_encoder ,					__lowercase		)
						self.assertEqual(new_rag_tokenizer.question_encoder.get_vocab() ,					rag_tokenizer.question_encoder.get_vocab()		)
						self.assertIsInstance(new_rag_tokenizer.generator ,					__lowercase		)
						self.assertEqual(new_rag_tokenizer.generator.get_vocab() ,					rag_tokenizer.generator.get_vocab()		)





					@slow
					def        SCREAMING_SNAKE_CASE							(						self    :  List[Any]		):






						'''simple docstring'''







						UpperCAmelCase_								=     RagTokenizer.from_pretrained("""facebook/rag-token-nq"""		)
						UpperCAmelCase_								=     [
						    """who got the first nobel prize in physics""",
						    """when is the next deadpool movie being released""",
						    """which mode is used for short wave broadcast service""",
						    """who is the owner of reading football club""",
						    """when is the next scandal episode coming out""",
						    """when is the last time the philadelphia won the superbowl""",
						    """what is the most current adobe flash player version""",
						    """how many episodes are there in dragon ball z""",
						    """what is the first step in the evolution of the eye""",
						    """where is gall bladder situated in human body""",
						    """what is the main mineral in lithium batteries""",
						    """who is the president of usa right now""",
						    """where do the greasers live in the outsiders""",
						    """panda is a national animal of which country""",
						    """what is the name of manchester united stadium""",
						]
						UpperCAmelCase_								=     tokenizer(__lowercase		)
						self.assertIsNotNone(__lowercase		)





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






						'''simple docstring'''







						UpperCAmelCase_								=     RagTokenizer.from_pretrained("""facebook/rag-sequence-nq"""		)
						UpperCAmelCase_								=     [
						    """who got the first nobel prize in physics""",
						    """when is the next deadpool movie being released""",
						    """which mode is used for short wave broadcast service""",
						    """who is the owner of reading football club""",
						    """when is the next scandal episode coming out""",
						    """when is the last time the philadelphia won the superbowl""",
						    """what is the most current adobe flash player version""",
						    """how many episodes are there in dragon ball z""",
						    """what is the first step in the evolution of the eye""",
						    """where is gall bladder situated in human body""",
						    """what is the main mineral in lithium batteries""",
						    """who is the president of usa right now""",
						    """where do the greasers live in the outsiders""",
						    """panda is a national animal of which country""",
						    """what is the name of manchester united stadium""",
						]
						UpperCAmelCase_								=     tokenizer(__lowercase		)
						self.assertIsNotNone(__lowercase		)


