




# Note: if you intend to run this script make sure you look under scripts/fsmt/
# to locate the appropriate script to do the work correctly. There is a set of scripts to:
# - download and prepare data and run the conversion script
# - perform eval to get the best hparam into the config
# - generate model_cards - useful if you have multiple models from the same paper

import argparse
import json
import os
import re
from collections import OrderedDict
from os.path import basename, dirname

import fairseq
import torch
from fairseq import hub_utils
from fairseq.data.dictionary import Dictionary

from transformers import FSMTConfig, FSMTForConditionalGeneration
from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES
from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE
from transformers.utils import WEIGHTS_NAME, logging


logging.set_verbosity_warning()

UpperCAmelCase_						=2

# based on the results of a search on a range of `num_beams`, `length_penalty` and `early_stopping`
# values against wmt19 test data to obtain the best BLEU scores, we will use the following defaults:
#
# * `num_beams`: 5 (higher scores better, but requires more memory/is slower, can be adjusted by users)
# * `early_stopping`: `False` consistently scored better
# * `length_penalty` varied, so will assign the best one depending on the model
UpperCAmelCase_						={
    # fairseq:
    """wmt19-ru-en""": {"""length_penalty""": 1.1},
    """wmt19-en-ru""": {"""length_penalty""": 1.15},
    """wmt19-en-de""": {"""length_penalty""": 1.0},
    """wmt19-de-en""": {"""length_penalty""": 1.1},
    # allenai:
    """wmt16-en-de-dist-12-1""": {"""length_penalty""": 0.6},
    """wmt16-en-de-dist-6-1""": {"""length_penalty""": 0.6},
    """wmt16-en-de-12-1""": {"""length_penalty""": 0.8},
    """wmt19-de-en-6-6-base""": {"""length_penalty""": 0.6},
    """wmt19-de-en-6-6-big""": {"""length_penalty""": 0.6},
}

# this remaps the different models to their organization names
UpperCAmelCase_						={}
for m in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]:
		UpperCAmelCase_						="""facebook"""
for m in [
    "wmt16-en-de-dist-12-1",
    "wmt16-en-de-dist-6-1",
    "wmt16-en-de-12-1",
    "wmt19-de-en-6-6-base",
    "wmt19-de-en-6-6-big",
]:
		UpperCAmelCase_						="""allenai"""



def       UpperCAmelCase       (     _snake_case							):
							# (1) remove word breaking symbol, (2) add word ending symbol where the word is not broken up,
							# e.g.: d = {'le@@': 5, 'tt@@': 6, 'er': 7} => {'le': 5, 'tt': 6, 'er</w>': 7}
							lowerCAmelCase   =		dict((re.sub(R'''@@$'''						, ''''''						, _snake_case							), v) if k.endswith('''@@'''							) else (re.sub(R'''$'''						, '''</w>'''						, _snake_case							), v) for k, v in d.items()							)
							lowerCAmelCase   =		'''<s> <pad> </s> <unk>'''.split()
							# restore the special tokens
							for k in keep_keys:
														del da[F"""{k}</w>"""]
														lowerCAmelCase   =		d[k]  # restore
							return da



def       UpperCAmelCase       (     _snake_case						, _snake_case							):
							# prep
							assert os.path.exists(_snake_case							)
							os.makedirs(_snake_case						, exist_ok=_snake_case							)
							print(F"""Writing results to {pytorch_dump_folder_path}"""							)

							# handle various types of models

							lowerCAmelCase   =		basename(_snake_case							)
							lowerCAmelCase   =		dirname(_snake_case							)

							lowerCAmelCase   =		fairseq.model_parallel.models.transformer.ModelParallelTransformerModel
							lowerCAmelCase   =		cls.hub_models()
							lowerCAmelCase   =		{'''bpe''': '''fastbpe''', '''tokenizer''': '''moses'''}
							lowerCAmelCase   =		'''.'''
							# note: since the model dump is old, fairseq has upgraded its model some
							# time later, and it does a whole lot of rewrites and splits on the saved
							# weights, therefore we can't use torch.load() directly on the model file.
							# see: upgrade_state_dict(state_dict) in fairseq_model.py
							print(F"""using checkpoint {checkpoint_file}"""							)
							lowerCAmelCase   =		hub_utils.from_pretrained(
							    _snake_case						, _snake_case						, _snake_case						, archive_map=_snake_case						, **_snake_case							)

							lowerCAmelCase   =		vars(chkpt['''args''']['''model''']							)

							lowerCAmelCase   =		args['''source_lang''']
							lowerCAmelCase   =		args['''target_lang''']

							lowerCAmelCase   =		dirname(_snake_case							)
							lowerCAmelCase   =		basename(_snake_case							)

							# dicts
							lowerCAmelCase   =		os.path.join(_snake_case						, F"""dict.{src_lang}.txt"""							)
							lowerCAmelCase   =		os.path.join(_snake_case						, F"""dict.{tgt_lang}.txt"""							)

							lowerCAmelCase   =		Dictionary.load(_snake_case							)
							lowerCAmelCase   =		rewrite_dict_keys(src_dict.indices							)
							lowerCAmelCase   =		len(_snake_case							)
							lowerCAmelCase   =		os.path.join(_snake_case						, '''vocab-src.json'''							)
							print(F"""Generating {src_vocab_file} of {src_vocab_size} of {src_lang} records"""							)
							with open(_snake_case						, '''w'''						, encoding='''utf-8'''							) as f:
														f.write(json.dumps(_snake_case						, ensure_ascii=_snake_case						, indent=_snake_case							)							)

							# detect whether this is a do_lower_case situation, which can be derived by checking whether we
							# have at least one uppercase letter in the source vocab
							lowerCAmelCase   =		True
							for k in src_vocab.keys():
														if not k.islower():
																					lowerCAmelCase   =		False
																					break

							lowerCAmelCase   =		Dictionary.load(_snake_case							)
							lowerCAmelCase   =		rewrite_dict_keys(tgt_dict.indices							)
							lowerCAmelCase   =		len(_snake_case							)
							lowerCAmelCase   =		os.path.join(_snake_case						, '''vocab-tgt.json'''							)
							print(F"""Generating {tgt_vocab_file} of {tgt_vocab_size} of {tgt_lang} records"""							)
							with open(_snake_case						, '''w'''						, encoding='''utf-8'''							) as f:
														f.write(json.dumps(_snake_case						, ensure_ascii=_snake_case						, indent=_snake_case							)							)

							# merges_file (bpecodes)
							lowerCAmelCase   =		os.path.join(_snake_case						, VOCAB_FILES_NAMES['''merges_file''']							)
							for fn in ["bpecodes", "code"]:  # older fairseq called the merges file "code"
														lowerCAmelCase   =		os.path.join(_snake_case						, _snake_case							)
														if os.path.exists(_snake_case							):
																					break
							with open(_snake_case						, encoding='''utf-8'''							) as fin:
														lowerCAmelCase   =		fin.read()
							lowerCAmelCase   =		re.sub(R''' \d+$'''						, ''''''						, _snake_case						, 0						, re.M							)  # remove frequency number
							print(F"""Generating {merges_file}"""							)
							with open(_snake_case						, '''w'''						, encoding='''utf-8'''							) as fout:
														fout.write(_snake_case							)

							# model config
							lowerCAmelCase   =		os.path.join(_snake_case						, '''config.json'''							)

							# validate bpe/tokenizer config, as currently it's hardcoded to moses+fastbpe -
							# may have to modify the tokenizer if a different type is used by a future model
							assert args["bpe"] == "fastbpe", F"""need to extend tokenizer to support bpe={args["bpe"]}"""
							assert args["tokenizer"] == "moses", F"""need to extend tokenizer to support bpe={args["tokenizer"]}"""

							lowerCAmelCase   =		{
							    '''architectures''': ['''FSMTForConditionalGeneration'''],
							    '''model_type''': '''fsmt''',
							    '''activation_dropout''': args['''activation_dropout'''],
							    '''activation_function''': '''relu''',
							    '''attention_dropout''': args['''attention_dropout'''],
							    '''d_model''': args['''decoder_embed_dim'''],
							    '''dropout''': args['''dropout'''],
							    '''init_std''': 0.02,
							    '''max_position_embeddings''': args['''max_source_positions'''],
							    '''num_hidden_layers''': args['''encoder_layers'''],
							    '''src_vocab_size''': src_vocab_size,
							    '''tgt_vocab_size''': tgt_vocab_size,
							    '''langs''': [src_lang, tgt_lang],
							    '''encoder_attention_heads''': args['''encoder_attention_heads'''],
							    '''encoder_ffn_dim''': args['''encoder_ffn_embed_dim'''],
							    '''encoder_layerdrop''': args['''encoder_layerdrop'''],
							    '''encoder_layers''': args['''encoder_layers'''],
							    '''decoder_attention_heads''': args['''decoder_attention_heads'''],
							    '''decoder_ffn_dim''': args['''decoder_ffn_embed_dim'''],
							    '''decoder_layerdrop''': args['''decoder_layerdrop'''],
							    '''decoder_layers''': args['''decoder_layers'''],
							    '''bos_token_id''': 0,
							    '''pad_token_id''': 1,
							    '''eos_token_id''': 2,
							    '''is_encoder_decoder''': True,
							    '''scale_embedding''': not args['''no_scale_embedding'''],
							    '''tie_word_embeddings''': args['''share_all_embeddings'''],
							}

							# good hparam defaults to start with
							lowerCAmelCase   =		5
							lowerCAmelCase   =		False
							if model_dir in best_score_hparams and "length_penalty" in best_score_hparams[model_dir]:
														lowerCAmelCase   =		best_score_hparams[model_dir]['''length_penalty''']
							else:
														lowerCAmelCase   =		1.0

							print(F"""Generating {fsmt_model_config_file}"""							)
							with open(_snake_case						, '''w'''						, encoding='''utf-8'''							) as f:
														f.write(json.dumps(_snake_case						, ensure_ascii=_snake_case						, indent=_snake_case							)							)

							# tokenizer config
							lowerCAmelCase   =		os.path.join(_snake_case						, _snake_case							)

							lowerCAmelCase   =		{
							    '''langs''': [src_lang, tgt_lang],
							    '''model_max_length''': 1024,
							    '''do_lower_case''': do_lower_case,
							}

							print(F"""Generating {fsmt_tokenizer_config_file}"""							)
							with open(_snake_case						, '''w'''						, encoding='''utf-8'''							) as f:
														f.write(json.dumps(_snake_case						, ensure_ascii=_snake_case						, indent=_snake_case							)							)

							# model
							lowerCAmelCase   =		chkpt['''models'''][0]
							lowerCAmelCase   =		model.state_dict()

							# rename keys to start with 'model.'
							lowerCAmelCase   =		OrderedDict(('''model.''' + k, v) for k, v in model_state_dict.items()							)

							# remove unneeded keys
							lowerCAmelCase   =		[
							    '''model.model''',
							    '''model.encoder.version''',
							    '''model.decoder.version''',
							    '''model.encoder_embed_tokens.weight''',
							    '''model.decoder_embed_tokens.weight''',
							    '''model.encoder.embed_positions._float_tensor''',
							    '''model.decoder.embed_positions._float_tensor''',
							]
							for k in ignore_keys:
														model_state_dict.pop(_snake_case						, _snake_case							)

							lowerCAmelCase   =		FSMTConfig.from_pretrained(_snake_case							)
							lowerCAmelCase   =		FSMTForConditionalGeneration(_snake_case							)

							# check that it loads ok
							model_new.load_state_dict(_snake_case						, strict=_snake_case							)

							# save
							lowerCAmelCase   =		os.path.join(_snake_case						, _snake_case							)
							print(F"""Generating {pytorch_weights_dump_path}"""							)
							torch.save(_snake_case						, _snake_case							)

							print('''Conversion is done!'''							)
							print('''\nLast step is to upload the files to s3'''							)
							print(F"""cd {data_root}"""							)
							print(F"""transformers-cli upload {model_dir}"""							)


if __name__ == "__main__":
		UpperCAmelCase_						=argparse.ArgumentParser()
		# Required parameters
		parser.add_argument(
		    """--fsmt_checkpoint_path""",
		    default=None,
		    type=str,
		    required=True,
		    help=(
		        """Path to the official PyTorch checkpoint file which is expected to reside in the dump dir with dicts,"""
		        """ bpecodes, etc."""
		    ),
		)
		parser.add_argument(
		    """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model."""
		)
		UpperCAmelCase_						=parser.parse_args()
		convert_fsmt_checkpoint_to_pytorch(args.fsmt_checkpoint_path, args.pytorch_dump_folder_path)









import json
import os
import pickle
import shutil
import tempfile
from unittest import TestCase
from unittest.mock import patch

import numpy as np
from datasets import Dataset

from transformers import is_faiss_available
from transformers.models.bart.configuration_bart import BartConfig
from transformers.models.bart.tokenization_bart import BartTokenizer
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.dpr.tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer
from transformers.models.rag.configuration_rag import RagConfig
from transformers.models.rag.retrieval_rag import CustomHFIndex, RagRetriever
from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES
from transformers.testing_utils import require_faiss, require_sentencepiece, require_tokenizers, require_torch


if is_faiss_available():
		import faiss


@require_faiss
class 							__UpperCamelCase			( __UpperCAmelCase  ):





				'''simple docstring'''



				def       __snake_case		( self						):
											lowerCAmelCase   =		tempfile.mkdtemp()
											lowerCAmelCase   =		8

											# DPR tok
											lowerCAmelCase   =		[
											    '''[UNK]''',
											    '''[CLS]''',
											    '''[SEP]''',
											    '''[PAD]''',
											    '''[MASK]''',
											    '''want''',
											    '''##want''',
											    '''##ed''',
											    '''wa''',
											    '''un''',
											    '''runn''',
											    '''##ing''',
											    ''',''',
											    '''low''',
											    '''lowest''',
											]
											lowerCAmelCase   =		os.path.join(self.tmpdirname       , '''dpr_tokenizer'''						)
											os.makedirs(UpperCAmelCase_       , exist_ok=UpperCAmelCase_						)
											lowerCAmelCase   =		os.path.join(UpperCAmelCase_       , 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
											lowerCAmelCase   =		[
											    '''l''',
											    '''o''',
											    '''w''',
											    '''e''',
											    '''r''',
											    '''s''',
											    '''t''',
											    '''i''',
											    '''d''',
											    '''n''',
											    '''\u0120''',
											    '''\u0120l''',
											    '''\u0120n''',
											    '''\u0120lo''',
											    '''\u0120low''',
											    '''er''',
											    '''\u0120lowest''',
											    '''\u0120newer''',
											    '''\u0120wider''',
											    '''<unk>''',
											]
											lowerCAmelCase   =		dict(zip(UpperCAmelCase_       , range(len(UpperCAmelCase_						)						)						)						)
											lowerCAmelCase   =		['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', '''''']
											lowerCAmelCase   =		{'''unk_token''': '''<unk>'''}

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



				def       __snake_case		( self						):
											return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname       , '''dpr_tokenizer'''						)						)



				def       __snake_case		( self						):
											return DPRContextEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname       , '''dpr_tokenizer'''						)						)



				def       __snake_case		( self						):
											return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname       , '''bart_tokenizer'''						)						)



				def       __snake_case		( self						):
											shutil.rmtree(self.tmpdirname						)



				def       __snake_case		( self						):
											lowerCAmelCase   =		Dataset.from_dict(
											    {
											        '''id''': ['''0''', '''1'''],
											        '''text''': ['''foo''', '''bar'''],
											        '''title''': ['''Foo''', '''Bar'''],
											        '''embeddings''': [np.ones(self.retrieval_vector_size						), 2 * np.ones(self.retrieval_vector_size						)],
											    }						)
											dataset.add_faiss_index('''embeddings'''       , string_factory='''Flat'''       , metric_type=faiss.METRIC_INNER_PRODUCT						)
											return dataset



				def       __snake_case		( self						):
											lowerCAmelCase   =		self.get_dummy_dataset()
											lowerCAmelCase   =		RagConfig(
											    retrieval_vector_size=self.retrieval_vector_size       , question_encoder=DPRConfig().to_dict()       , generator=BartConfig().to_dict()       , )
											with patch('''transformers.models.rag.retrieval_rag.load_dataset'''						) as mock_load_dataset:
																		lowerCAmelCase   =		dataset
																		lowerCAmelCase   =		RagRetriever(
																		    UpperCAmelCase_       , question_encoder_tokenizer=self.get_dpr_tokenizer()       , generator_tokenizer=self.get_bart_tokenizer()       , )
											return retriever



				def       __snake_case		( self       , UpperCAmelCase_						):
											lowerCAmelCase   =		self.get_dummy_dataset()
											lowerCAmelCase   =		RagConfig(
											    retrieval_vector_size=self.retrieval_vector_size       , question_encoder=DPRConfig().to_dict()       , generator=BartConfig().to_dict()       , index_name='''custom'''       , )
											if from_disk:
																		lowerCAmelCase   =		os.path.join(self.tmpdirname       , '''dataset'''						)
																		lowerCAmelCase   =		os.path.join(self.tmpdirname       , '''index.faiss'''						)
																		dataset.get_index('''embeddings'''						).save(os.path.join(self.tmpdirname       , '''index.faiss'''						)						)
																		dataset.drop_index('''embeddings'''						)
																		dataset.save_to_disk(os.path.join(self.tmpdirname       , '''dataset'''						)						)
																		del dataset
																		lowerCAmelCase   =		RagRetriever(
																		    UpperCAmelCase_       , question_encoder_tokenizer=self.get_dpr_tokenizer()       , generator_tokenizer=self.get_bart_tokenizer()       , )
											else:
																		lowerCAmelCase   =		RagRetriever(
																		    UpperCAmelCase_       , question_encoder_tokenizer=self.get_dpr_tokenizer()       , generator_tokenizer=self.get_bart_tokenizer()       , index=CustomHFIndex(config.retrieval_vector_size       , UpperCAmelCase_						)       , )
											return retriever



				def       __snake_case		( self						):
											lowerCAmelCase   =		Dataset.from_dict(
											    {
											        '''id''': ['''0''', '''1'''],
											        '''text''': ['''foo''', '''bar'''],
											        '''title''': ['''Foo''', '''Bar'''],
											        '''embeddings''': [np.ones(self.retrieval_vector_size + 1						), 2 * np.ones(self.retrieval_vector_size + 1						)],
											    }						)
											dataset.add_faiss_index('''embeddings'''       , string_factory='''Flat'''       , metric_type=faiss.METRIC_INNER_PRODUCT						)

											lowerCAmelCase   =		os.path.join(self.tmpdirname       , '''hf_bert_base.hnswSQ8_correct_phi_128.c_index'''						)
											dataset.save_faiss_index('''embeddings'''       , index_file_name + '''.index.dpr'''						)
											pickle.dump(dataset['''id''']       , open(index_file_name + '''.index_meta.dpr'''       , '''wb'''						)						)

											lowerCAmelCase   =		os.path.join(self.tmpdirname       , '''psgs_w100.tsv.pkl'''						)
											lowerCAmelCase   =		{sample['''id''']: [sample['''text'''], sample['''title''']] for sample in dataset}
											pickle.dump(UpperCAmelCase_       , open(UpperCAmelCase_       , '''wb'''						)						)

											lowerCAmelCase   =		RagConfig(
											    retrieval_vector_size=self.retrieval_vector_size       , question_encoder=DPRConfig().to_dict()       , generator=BartConfig().to_dict()       , index_name='''legacy'''       , index_path=self.tmpdirname       , )
											lowerCAmelCase   =		RagRetriever(
											    UpperCAmelCase_       , question_encoder_tokenizer=self.get_dpr_tokenizer()       , generator_tokenizer=self.get_bart_tokenizer()						)
											return retriever



				def       __snake_case		( self						):
											lowerCAmelCase   =		1
											lowerCAmelCase   =		self.get_dummy_canonical_hf_index_retriever()
											lowerCAmelCase   =		np.array(
											    [np.ones(self.retrieval_vector_size						), -np.ones(self.retrieval_vector_size						)]       , dtype=np.floataa						)
											lowerCAmelCase   ,     lowerCAmelCase   ,     lowerCAmelCase   =		retriever.retrieve(UpperCAmelCase_       , n_docs=UpperCAmelCase_						)
											self.assertEqual(retrieved_doc_embeds.shape       , (2, n_docs, self.retrieval_vector_size)						)
											self.assertEqual(len(UpperCAmelCase_						)       , 2						)
											self.assertEqual(sorted(doc_dicts[0]						)       , ['''embeddings''', '''id''', '''text''', '''title''']						)
											self.assertEqual(len(doc_dicts[0]['''id''']						)       , UpperCAmelCase_						)
											self.assertEqual(doc_dicts[0]['''id'''][0]       , '''1'''						)  # max inner product is reached with second doc
											self.assertEqual(doc_dicts[1]['''id'''][0]       , '''0'''						)  # max inner product is reached with first doc
											self.assertListEqual(doc_ids.tolist()       , [[1], [0]]						)



				def       __snake_case		( self						):
											lowerCAmelCase   =		self.get_dummy_canonical_hf_index_retriever()
											with tempfile.TemporaryDirectory() as tmp_dirname:
																		with patch('''transformers.models.rag.retrieval_rag.load_dataset'''						) as mock_load_dataset:
																									lowerCAmelCase   =		self.get_dummy_dataset()
																									retriever.save_pretrained(UpperCAmelCase_						)
																									lowerCAmelCase   =		RagRetriever.from_pretrained(UpperCAmelCase_						)
																									self.assertIsInstance(UpperCAmelCase_       , UpperCAmelCase_						)
																									lowerCAmelCase   =		np.array(
																									    [np.ones(self.retrieval_vector_size						), -np.ones(self.retrieval_vector_size						)]       , dtype=np.floataa						)
																									lowerCAmelCase   =		retriever.retrieve(UpperCAmelCase_       , n_docs=1						)
																									self.assertTrue(out is not None						)



				def       __snake_case		( self						):
											lowerCAmelCase   =		1
											lowerCAmelCase   =		self.get_dummy_custom_hf_index_retriever(from_disk=UpperCAmelCase_						)
											lowerCAmelCase   =		np.array(
											    [np.ones(self.retrieval_vector_size						), -np.ones(self.retrieval_vector_size						)]       , dtype=np.floataa						)
											lowerCAmelCase   ,     lowerCAmelCase   ,     lowerCAmelCase   =		retriever.retrieve(UpperCAmelCase_       , n_docs=UpperCAmelCase_						)
											self.assertEqual(retrieved_doc_embeds.shape       , (2, n_docs, self.retrieval_vector_size)						)
											self.assertEqual(len(UpperCAmelCase_						)       , 2						)
											self.assertEqual(sorted(doc_dicts[0]						)       , ['''embeddings''', '''id''', '''text''', '''title''']						)
											self.assertEqual(len(doc_dicts[0]['''id''']						)       , UpperCAmelCase_						)
											self.assertEqual(doc_dicts[0]['''id'''][0]       , '''1'''						)  # max inner product is reached with second doc
											self.assertEqual(doc_dicts[1]['''id'''][0]       , '''0'''						)  # max inner product is reached with first doc
											self.assertListEqual(doc_ids.tolist()       , [[1], [0]]						)



				def       __snake_case		( self						):
											lowerCAmelCase   =		self.get_dummy_custom_hf_index_retriever(from_disk=UpperCAmelCase_						)
											with tempfile.TemporaryDirectory() as tmp_dirname:
																		retriever.save_pretrained(UpperCAmelCase_						)
																		lowerCAmelCase   =		RagRetriever.from_pretrained(UpperCAmelCase_						)
																		self.assertIsInstance(UpperCAmelCase_       , UpperCAmelCase_						)
																		lowerCAmelCase   =		np.array(
																		    [np.ones(self.retrieval_vector_size						), -np.ones(self.retrieval_vector_size						)]       , dtype=np.floataa						)
																		lowerCAmelCase   =		retriever.retrieve(UpperCAmelCase_       , n_docs=1						)
																		self.assertTrue(out is not None						)



				def       __snake_case		( self						):
											lowerCAmelCase   =		1
											lowerCAmelCase   =		self.get_dummy_custom_hf_index_retriever(from_disk=UpperCAmelCase_						)
											lowerCAmelCase   =		np.array(
											    [np.ones(self.retrieval_vector_size						), -np.ones(self.retrieval_vector_size						)]       , dtype=np.floataa						)
											lowerCAmelCase   ,     lowerCAmelCase   ,     lowerCAmelCase   =		retriever.retrieve(UpperCAmelCase_       , n_docs=UpperCAmelCase_						)
											self.assertEqual(retrieved_doc_embeds.shape       , (2, n_docs, self.retrieval_vector_size)						)
											self.assertEqual(len(UpperCAmelCase_						)       , 2						)
											self.assertEqual(sorted(doc_dicts[0]						)       , ['''embeddings''', '''id''', '''text''', '''title''']						)
											self.assertEqual(len(doc_dicts[0]['''id''']						)       , UpperCAmelCase_						)
											self.assertEqual(doc_dicts[0]['''id'''][0]       , '''1'''						)  # max inner product is reached with second doc
											self.assertEqual(doc_dicts[1]['''id'''][0]       , '''0'''						)  # max inner product is reached with first doc
											self.assertListEqual(doc_ids.tolist()       , [[1], [0]]						)



				def       __snake_case		( self						):
											lowerCAmelCase   =		self.get_dummy_custom_hf_index_retriever(from_disk=UpperCAmelCase_						)
											with tempfile.TemporaryDirectory() as tmp_dirname:
																		retriever.save_pretrained(UpperCAmelCase_						)
																		lowerCAmelCase   =		RagRetriever.from_pretrained(UpperCAmelCase_						)
																		self.assertIsInstance(UpperCAmelCase_       , UpperCAmelCase_						)
																		lowerCAmelCase   =		np.array(
																		    [np.ones(self.retrieval_vector_size						), -np.ones(self.retrieval_vector_size						)]       , dtype=np.floataa						)
																		lowerCAmelCase   =		retriever.retrieve(UpperCAmelCase_       , n_docs=1						)
																		self.assertTrue(out is not None						)



				def       __snake_case		( self						):
											lowerCAmelCase   =		1
											lowerCAmelCase   =		self.get_dummy_legacy_index_retriever()
											lowerCAmelCase   =		np.array(
											    [np.ones(self.retrieval_vector_size						), -np.ones(self.retrieval_vector_size						)]       , dtype=np.floataa						)
											lowerCAmelCase   ,     lowerCAmelCase   ,     lowerCAmelCase   =		retriever.retrieve(UpperCAmelCase_       , n_docs=UpperCAmelCase_						)
											self.assertEqual(retrieved_doc_embeds.shape       , (2, n_docs, self.retrieval_vector_size)						)
											self.assertEqual(len(UpperCAmelCase_						)       , 2						)
											self.assertEqual(sorted(doc_dicts[0]						)       , ['''text''', '''title''']						)
											self.assertEqual(len(doc_dicts[0]['''text''']						)       , UpperCAmelCase_						)
											self.assertEqual(doc_dicts[0]['''text'''][0]       , '''bar'''						)  # max inner product is reached with second doc
											self.assertEqual(doc_dicts[1]['''text'''][0]       , '''foo'''						)  # max inner product is reached with first doc
											self.assertListEqual(doc_ids.tolist()       , [[1], [0]]						)



				def       __snake_case		( self						):
											lowerCAmelCase   =		self.get_dummy_legacy_index_retriever()
											with tempfile.TemporaryDirectory() as tmp_dirname:
																		retriever.save_pretrained(UpperCAmelCase_						)
																		lowerCAmelCase   =		RagRetriever.from_pretrained(UpperCAmelCase_						)
																		self.assertIsInstance(UpperCAmelCase_       , UpperCAmelCase_						)
																		lowerCAmelCase   =		np.array(
																		    [np.ones(self.retrieval_vector_size						), -np.ones(self.retrieval_vector_size						)]       , dtype=np.floataa						)
																		lowerCAmelCase   =		retriever.retrieve(UpperCAmelCase_       , n_docs=1						)
																		self.assertTrue(out is not None						)



				@require_torch
				@require_tokenizers
				@require_sentencepiece
				def       __snake_case		( self						):
											import torch

											lowerCAmelCase   =		1
											lowerCAmelCase   =		self.get_dummy_canonical_hf_index_retriever()
											lowerCAmelCase   =		[[5, 7], [10, 11]]
											lowerCAmelCase   =		np.array(
											    [np.ones(self.retrieval_vector_size						), -np.ones(self.retrieval_vector_size						)]       , dtype=np.floataa						)
											lowerCAmelCase   =		retriever(UpperCAmelCase_       , UpperCAmelCase_       , prefix=retriever.config.generator.prefix       , n_docs=UpperCAmelCase_						)
											lowerCAmelCase   ,     lowerCAmelCase   ,     lowerCAmelCase   =		(
											    out['''context_input_ids'''],
											    out['''context_attention_mask'''],
											    out['''retrieved_doc_embeds'''],
											)
											self.assertEqual(retrieved_doc_embeds.shape       , (2, n_docs, self.retrieval_vector_size)						)
											self.assertIsInstance(UpperCAmelCase_       , UpperCAmelCase_						)
											self.assertIsInstance(UpperCAmelCase_       , UpperCAmelCase_						)
											self.assertIsInstance(UpperCAmelCase_       , np.ndarray						)

											lowerCAmelCase   =		retriever(
											    UpperCAmelCase_       , UpperCAmelCase_       , prefix=retriever.config.generator.prefix       , n_docs=UpperCAmelCase_       , return_tensors='''pt'''       , )
											lowerCAmelCase   ,     lowerCAmelCase   ,     lowerCAmelCase   ,     lowerCAmelCase   =		(  # noqa: F841
											    out['''context_input_ids'''],
											    out['''context_attention_mask'''],
											    out['''retrieved_doc_embeds'''],
											    out['''doc_ids'''],
											)
											self.assertEqual(retrieved_doc_embeds.shape       , (2, n_docs, self.retrieval_vector_size)						)
											self.assertIsInstance(UpperCAmelCase_       , torch.Tensor						)
											self.assertIsInstance(UpperCAmelCase_       , torch.Tensor						)
											self.assertIsInstance(UpperCAmelCase_       , torch.Tensor						)






				@require_torch
				@require_tokenizers
				@require_sentencepiece
				def       __snake_case		( self						):
											lowerCAmelCase   =		self.get_dpr_ctx_encoder_tokenizer()
											lowerCAmelCase   =		1
											lowerCAmelCase   =		self.get_dummy_custom_hf_index_retriever(from_disk=UpperCAmelCase_						)
											retriever.set_ctx_encoder_tokenizer(UpperCAmelCase_						)

											lowerCAmelCase   =		[[5, 7], [10, 11]]
											lowerCAmelCase   =		np.array(
											    [np.ones(self.retrieval_vector_size						), -np.ones(self.retrieval_vector_size						)]       , dtype=np.floataa						)
											lowerCAmelCase   =		retriever(UpperCAmelCase_       , UpperCAmelCase_       , prefix=retriever.config.generator.prefix       , n_docs=UpperCAmelCase_						)

											self.assertEqual(
											    len(UpperCAmelCase_						)       , 6						)  # check whether the retriever output consist of 6 attributes including tokenized docs
											self.assertEqual(
											    all(k in out for k in ('''tokenized_doc_ids''', '''tokenized_doc_attention_mask''')						)       , UpperCAmelCase_						)  # check for doc token related keys in dictionary.



