


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 		_snake_case  (      __a							):




 def        SCREAMING_SNAKE_CASE__				(		self    ):
       a						:Tuple 							=       tempfile.mkdtemp()
       a						:List[str] 							=       8

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

       a						:Dict 							=       os.path.join(self.tmpdirname					,  '''bart_tokenizer'''    )
       os.makedirs(_UpperCamelCase					,  exist_ok=_UpperCamelCase    )
       a						:Any 							=       os.path.join(_UpperCamelCase					,  BART_VOCAB_FILES_NAMES['''vocab_file''']    )
       a						:Optional[int] 							=       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        SCREAMING_SNAKE_CASE__				(		self    ):
       return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname					,  '''dpr_tokenizer'''    )    )




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




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




 @require_tokenizers
 def        SCREAMING_SNAKE_CASE__				(		self    ):
       a						:int 							=       os.path.join(self.tmpdirname					,  '''rag_tokenizer'''    )
       a						:Optional[int] 							=       RagConfig(question_encoder=DPRConfig().to_dict()					,  generator=BartConfig().to_dict()    )
       a						:Union[str, Any] 							=       RagTokenizer(question_encoder=self.get_dpr_tokenizer()					,  generator=self.get_bart_tokenizer()    )
       rag_config.save_pretrained(_UpperCamelCase    )
       rag_tokenizer.save_pretrained(_UpperCamelCase    )
       a						:Union[str, Any] 							=       RagTokenizer.from_pretrained(_UpperCamelCase					,  config=_UpperCamelCase    )
       self.assertIsInstance(new_rag_tokenizer.question_encoder					,  _UpperCamelCase    )
       self.assertEqual(new_rag_tokenizer.question_encoder.get_vocab()					,  rag_tokenizer.question_encoder.get_vocab()    )
       self.assertIsInstance(new_rag_tokenizer.generator					,  _UpperCamelCase    )
       self.assertEqual(new_rag_tokenizer.generator.get_vocab()					,  rag_tokenizer.generator.get_vocab()    )




 @slow
 def        SCREAMING_SNAKE_CASE__				(		self    ):
       a						:int 							=       RagTokenizer.from_pretrained('''facebook/rag-token-nq'''    )
       a						:List[Any] 							=       [
           '''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''',
       ]
       a						:Dict 							=       tokenizer(_UpperCamelCase    )
       self.assertIsNotNone(_UpperCamelCase    )




 @slow
 def        SCREAMING_SNAKE_CASE__				(		self    ):
       a						:Optional[Any] 							=       RagTokenizer.from_pretrained('''facebook/rag-sequence-nq'''    )
       a						:str 							=       [
           '''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''',
       ]
       a						:int 							=       tokenizer(_UpperCamelCase    )
       self.assertIsNotNone(_UpperCamelCase    )







from ...configuration_utils import PretrainedConfig
from ...utils import logging


_A   =     logging.get_logger(__name__)

_A   =     {
    # See all MEGATRON_BERT models at https://huggingface.co/models?filter=bert
}





class 	_lowerCAmelCase					(	__a       ):
				_lowercase					='''megatron-bert'''




				def __init__(					self				,				_UpperCamelCase=29_056				,				_UpperCamelCase=1_024				,				_UpperCamelCase=24				,				_UpperCamelCase=16				,				_UpperCamelCase=4_096				,				_UpperCamelCase="gelu"				,				_UpperCamelCase=0.1				,				_UpperCamelCase=0.1				,				_UpperCamelCase=512				,				_UpperCamelCase=2				,				_UpperCamelCase=0.02				,				_UpperCamelCase=1e-1_2				,				_UpperCamelCase=0				,				_UpperCamelCase="absolute"				,				_UpperCamelCase=True				,				**_UpperCamelCase				,				)				->      int:
							super().__init__(pad_token_id=_UpperCamelCase				,				**_UpperCamelCase     )

							lowerCAmelCase_						=	vocab_size
							lowerCAmelCase_						=	hidden_size
							lowerCAmelCase_						=	num_hidden_layers
							lowerCAmelCase_						=	num_attention_heads
							lowerCAmelCase_						=	hidden_act
							lowerCAmelCase_						=	intermediate_size
							lowerCAmelCase_						=	hidden_dropout_prob
							lowerCAmelCase_						=	attention_probs_dropout_prob
							lowerCAmelCase_						=	max_position_embeddings
							lowerCAmelCase_						=	type_vocab_size
							lowerCAmelCase_						=	initializer_range
							lowerCAmelCase_						=	layer_norm_eps
							lowerCAmelCase_						=	position_embedding_type
							lowerCAmelCase_						=	use_cache



