


'''simple docstring'''



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 				snake_case__						(      self):
								UpperCAmelCase__  :					Tuple        =     tempfile.mkdtemp()
								UpperCAmelCase__  :					int        =     8

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

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




					def 				snake_case__						(      self):
								return DPRQuestionEncoderTokenizer.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)




					@require_tokenizers
					def 				snake_case__						(      self):
								UpperCAmelCase__  :					str        =     os.path.join(self.tmpdirname							,							"""rag_tokenizer""")
								UpperCAmelCase__  :					Tuple        =     RagConfig(question_encoder=DPRConfig().to_dict()							,							generator=BartConfig().to_dict())
								UpperCAmelCase__  :					Dict        =     RagTokenizer(question_encoder=self.get_dpr_tokenizer()							,							generator=self.get_bart_tokenizer())
								rag_config.save_pretrained(_lowerCamelCase)
								rag_tokenizer.save_pretrained(_lowerCamelCase)
								UpperCAmelCase__  :					str        =     RagTokenizer.from_pretrained(_lowerCamelCase							,							config=_lowerCamelCase)
								self.assertIsInstance(new_rag_tokenizer.question_encoder							,							_lowerCamelCase)
								self.assertEqual(new_rag_tokenizer.question_encoder.get_vocab()							,							rag_tokenizer.question_encoder.get_vocab())
								self.assertIsInstance(new_rag_tokenizer.generator							,							_lowerCamelCase)
								self.assertEqual(new_rag_tokenizer.generator.get_vocab()							,							rag_tokenizer.generator.get_vocab())




					@slow
					def 				snake_case__						(      self):
								UpperCAmelCase__  :					Any        =     RagTokenizer.from_pretrained("""facebook/rag-token-nq""")
								UpperCAmelCase__  :					Optional[int]        =     [
								    """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__  :					Optional[Any]        =     tokenizer(_lowerCamelCase)
								self.assertIsNotNone(_lowerCamelCase)




					@slow
					def 				snake_case__						(      self):
								UpperCAmelCase__  :					Optional[Any]        =     RagTokenizer.from_pretrained("""facebook/rag-sequence-nq""")
								UpperCAmelCase__  :					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""",
								]
								UpperCAmelCase__  :					Dict        =     tokenizer(_lowerCamelCase)
								self.assertIsNotNone(_lowerCamelCase)



'''simple docstring'''



import re

from flax.core.frozen_dict import freeze
from flax.traverse_util import flatten_dict, unflatten_dict
from jax.experimental import PartitionSpec as P


# Sentinels
__A	=object()

# For specifying empty leaf dict `{}`
__A	=object()







def     _UpperCamelCase      (		UpperCamelCase__ ,      UpperCamelCase__					):
			UpperCAmelCase__  :					Union[str, Any]        =     tuple((re.compile(x + """$"""					) for x in qs)					)
			for i in range(len(UpperCamelCase__					) - len(UpperCamelCase__					) + 1					):
						UpperCAmelCase__  :					Optional[Any]        =     [x.match(UpperCamelCase__					) for x, y in zip(UpperCamelCase__ ,      ks[i:]					)]
						if matches and all(UpperCamelCase__					):
									return True
			return False







def     _UpperCamelCase      (		UpperCamelCase__					):
			def replace(UpperCamelCase__ ,      UpperCamelCase__					):
						for rule, replacement in rules:
									if _match(UpperCamelCase__ ,      UpperCamelCase__					):
												return replacement
						return val

			return replace







def     _UpperCamelCase      (		):
			return [
			    # embeddings
			    (("transformer", "wpe", "embedding"), P("""mp""" ,      UpperCamelCase__					)),
			    (("transformer", "wte", "embedding"), P("""mp""" ,      UpperCamelCase__					)),
			    # atention
			    (("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(UpperCamelCase__ ,      """mp"""					)),
			    (("attention", "out_proj", "kernel"), P("""mp""" ,      UpperCamelCase__					)),
			    (("attention", "out_proj", "bias"), None),
			    # mlp
			    (("mlp", "c_fc", "kernel"), P(UpperCamelCase__ ,      """mp"""					)),
			    (("mlp", "c_fc", "bias"), P("""mp"""					)),
			    (("mlp", "c_proj", "kernel"), P("""mp""" ,      UpperCamelCase__					)),
			    (("mlp", "c_proj", "bias"), None),
			    # layer norms
			    ((r"ln_\d+", "bias"), None),
			    ((r"\d+", r"ln_\d+", "scale"), None),
			    (("ln_f", "bias"), None),
			    (("ln_f", "scale"), None),
			]







def     _UpperCamelCase      (		UpperCamelCase__					):
			UpperCAmelCase__  :					Optional[int]        =     _get_partition_rules()
			UpperCAmelCase__  :					Optional[int]        =     _replacement_rules(UpperCamelCase__					)
			UpperCAmelCase__  :					List[Any]        =     {k: _unmatched for k in flatten_dict(UpperCamelCase__					)}
			UpperCAmelCase__  :					Tuple        =     {k: replace(UpperCamelCase__ ,      UpperCamelCase__					) for k, v in initd.items()}
			assert _unmatched not in result.values(), "Incomplete partition spec."
			return freeze(unflatten_dict(UpperCamelCase__					)					)