




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       a__	( UpperCamelCase__				):







     def       lowerCAmelCase_    (     self			)  ->   Optional[int]:



          '''simple docstring'''



          a     =				tempfile.mkdtemp()
          a     =				8

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

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







     def       lowerCAmelCase_    (     self			)  ->   DPRQuestionEncoderTokenizer:



          '''simple docstring'''



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







     def       lowerCAmelCase_    (     self			)  ->   BartTokenizer:



          '''simple docstring'''



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







     def       lowerCAmelCase_    (     self			)  ->   Optional[Any]:



          '''simple docstring'''



          shutil.rmtree(self.tmpdirname			)







     @require_tokenizers
     def       lowerCAmelCase_    (     self			)  ->   List[Any]:



          '''simple docstring'''



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







     @slow
     def       lowerCAmelCase_    (     self			)  ->   Any:



          '''simple docstring'''



          a     =				RagTokenizer.from_pretrained("facebook/rag-token-nq"			)
          a     =				[
              "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     =				tokenizer(A			)
          self.assertIsNotNone(A			)







     @slow
     def       lowerCAmelCase_    (     self			)  ->   str:



          '''simple docstring'''



          a     =				RagTokenizer.from_pretrained("facebook/rag-sequence-nq"			)
          a     =				[
              "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     =				tokenizer(A			)
          self.assertIsNotNone(A			)







import functools
import operator

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


lowercase__				:      Any	   = logging.get_logger(__name__)

lowercase__				:      int	   = {
    "asapp/sew-d-tiny-100k": "https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json",
    # See all SEW-D models at https://huggingface.co/models?filter=sew-d
}




class       a__	( UpperCamelCase__				):
     a		:      Optional[Any]		 =     """sew-d"""







     def __init__(     self  ,		A=32  ,		A=768  ,		A=12  ,		A=12  ,		A=3072  ,		A=2  ,		A=512  ,		A=256  ,		A=True  ,		A=True  ,		A=("p2c", "c2p")  ,		A="layer_norm"  ,		A="gelu_python"  ,		A=0.1  ,		A=0.1  ,		A=0.1  ,		A=0.0  ,		A=0.1  ,		A=0.0_2  ,		A=1e-7  ,		A=1e-5  ,		A="group"  ,		A="gelu"  ,		A=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512)  ,		A=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1)  ,		A=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1)  ,		A=False  ,		A=128  ,		A=16  ,		A=True  ,		A=0.0_5  ,		A=10  ,		A=2  ,		A=0.0  ,		A=10  ,		A=0  ,		A="mean"  ,		A=False  ,		A=False  ,		A=256  ,		A=0  ,		A=1  ,		A=2  ,		**A  ,		)  ->   Dict:



          '''simple docstring'''



          super().__init__(**A  ,		pad_token_id=A  ,		bos_token_id=A  ,		eos_token_id=A			)
          a     =				hidden_size
          a     =				feat_extract_norm
          a     =				feat_extract_activation
          a     =				list(A			)
          a     =				list(A			)
          a     =				list(A			)
          a     =				conv_bias
          a     =				num_conv_pos_embeddings
          a     =				num_conv_pos_embedding_groups
          a     =				len(self.conv_dim			)
          a     =				num_hidden_layers
          a     =				intermediate_size
          a     =				squeeze_factor
          a     =				max_position_embeddings
          a     =				position_buckets
          a     =				share_att_key
          a     =				relative_attention
          a     =				norm_rel_ebd
          a     =				list(A			)
          a     =				hidden_act
          a     =				num_attention_heads
          a     =				hidden_dropout
          a     =				attention_dropout
          a     =				activation_dropout
          a     =				feat_proj_dropout
          a     =				final_dropout
          a     =				layer_norm_eps
          a     =				feature_layer_norm_eps
          a     =				initializer_range
          a     =				vocab_size

          if (
              (len(self.conv_stride			) != self.num_feat_extract_layers)
              or (len(self.conv_kernel			) != self.num_feat_extract_layers)
              or (len(self.conv_dim			) != self.num_feat_extract_layers)
          ):
               raise ValueError(
                   "Configuration for convolutional layers is incorrect."
                   "It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,"
                   F'''but is `len(config.conv_dim) = {len(self.conv_dim			)}`, `len(config.conv_stride)'''
                   F'''= {len(self.conv_stride			)}`, `len(config.conv_kernel) = {len(self.conv_kernel			)}`.'''			)

          # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
          a     =				apply_spec_augment
          a     =				mask_time_prob
          a     =				mask_time_length
          a     =				mask_time_min_masks
          a     =				mask_feature_prob
          a     =				mask_feature_length
          a     =				mask_feature_min_masks

          # ctc loss
          a     =				ctc_loss_reduction
          a     =				ctc_zero_infinity

          # sequence classification
          a     =				use_weighted_layer_sum
          a     =				classifier_proj_size







     @property
     def       lowerCAmelCase_    (     self			)  ->   List[str]:



          '''simple docstring'''



          return functools.reduce(operator.mul  ,		self.conv_stride  ,		1			)

