



'''simple docstring'''







import json
import os
import re
import warnings
from pathlib import Path
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple, Union

import sentencepiece

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


SCREAMING_SNAKE_CASE__     : Dict				=   logging.get_logger(__name__)

SCREAMING_SNAKE_CASE__     : Dict				=   {
    """source_spm""": """source.spm""",
    """target_spm""": """target.spm""",
    """vocab""": """vocab.json""",
    """target_vocab_file""": """target_vocab.json""",
    """tokenizer_config_file""": """tokenizer_config.json""",
}

SCREAMING_SNAKE_CASE__     : Optional[Any]				=   {
    """source_spm""": {
        """Helsinki-NLP/opus-mt-en-de""": """https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/source.spm"""
    },
    """target_spm""": {
        """Helsinki-NLP/opus-mt-en-de""": """https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/target.spm"""
    },
    """vocab""": {
        """Helsinki-NLP/opus-mt-en-de""": """https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/vocab.json"""
    },
    """tokenizer_config_file""": {
        """Helsinki-NLP/opus-mt-en-de""": (
            """https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/tokenizer_config.json"""
        )
    },
}

SCREAMING_SNAKE_CASE__     : Dict				=   {"""Helsinki-NLP/opus-mt-en-de""": 5_12}
SCREAMING_SNAKE_CASE__     : Union[str, Any]				=   {}




class 				__lowerCAmelCase(							lowerCAmelCase__      ):
			__snake_case  :		Any		=      VOCAB_FILES_NAMES
			__snake_case  :		Union[str, Any]		=      PRETRAINED_VOCAB_FILES_MAP
			__snake_case  :		List[str]		=      PRETRAINED_INIT_CONFIGURATION
			__snake_case  :		Dict		=      PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
			__snake_case  :		Any		=      ['input_ids', 'attention_mask']
			__snake_case  :		List[Any]		=      re.compile('>>.+<<'      )  # type: re.Pattern






			def __init__(   self  :							str      ,       SCREAMING_SNAKE_CASE  :							List[str]      ,       SCREAMING_SNAKE_CASE  :							Union[str, Any]      ,       SCREAMING_SNAKE_CASE  :							Optional[Any]      ,       SCREAMING_SNAKE_CASE  :							int=None      ,       SCREAMING_SNAKE_CASE  :							Optional[Any]=None      ,       SCREAMING_SNAKE_CASE  :							Union[str, Any]=None      ,       SCREAMING_SNAKE_CASE  :							Any="<unk>"      ,       SCREAMING_SNAKE_CASE  :							List[str]="</s>"      ,       SCREAMING_SNAKE_CASE  :							Dict="<pad>"      ,       SCREAMING_SNAKE_CASE  :							List[Any]=512      ,       SCREAMING_SNAKE_CASE  :							Optional[Dict[str, Any]] = None      ,       SCREAMING_SNAKE_CASE  :							Dict=False      ,       **SCREAMING_SNAKE_CASE  :							Optional[Any]      ,       ):




					"""simple docstring"""







					SCREAMING_SNAKE_CASE_						:Optional[Any]										=      {} if sp_model_kwargs is None else sp_model_kwargs

					super().__init__(
					    # bos_token=bos_token,  unused. Start decoding with config.decoder_start_token_id
					    source_lang=SCREAMING_SNAKE_CASE      ,       target_lang=SCREAMING_SNAKE_CASE      ,       unk_token=SCREAMING_SNAKE_CASE      ,       eos_token=SCREAMING_SNAKE_CASE      ,       pad_token=SCREAMING_SNAKE_CASE      ,       model_max_length=SCREAMING_SNAKE_CASE      ,       sp_model_kwargs=self.sp_model_kwargs      ,       target_vocab_file=SCREAMING_SNAKE_CASE      ,       separate_vocabs=SCREAMING_SNAKE_CASE      ,       **SCREAMING_SNAKE_CASE      ,       )
					assert Path(SCREAMING_SNAKE_CASE	).exists(), f'cannot find spm source {source_spm}'

					SCREAMING_SNAKE_CASE_						:List[Any]										=      separate_vocabs
					SCREAMING_SNAKE_CASE_						:str										=      load_json(SCREAMING_SNAKE_CASE	)
					if self.unk_token not in self.encoder:
							raise KeyError('<unk> token must be in vocab'	)
					assert self.pad_token in self.encoder

					if separate_vocabs:
							SCREAMING_SNAKE_CASE_						:str										=      load_json(SCREAMING_SNAKE_CASE	)
							SCREAMING_SNAKE_CASE_						:Optional[Any]										=      {v: k for k, v in self.target_encoder.items()}
							SCREAMING_SNAKE_CASE_						:Tuple										=      []
					else:
							SCREAMING_SNAKE_CASE_						:Dict										=      {v: k for k, v in self.encoder.items()}
							SCREAMING_SNAKE_CASE_						:list										=      [k for k in self.encoder if k.startswith('>>'	) and k.endswith('<<'	)]

					SCREAMING_SNAKE_CASE_						:Union[str, Any]										=      source_lang
					SCREAMING_SNAKE_CASE_						:Dict										=      target_lang
					SCREAMING_SNAKE_CASE_						:int										=      [source_spm, target_spm]

					# load SentencePiece model for pre-processing
					SCREAMING_SNAKE_CASE_						:Dict										=      load_spm(SCREAMING_SNAKE_CASE      ,       self.sp_model_kwargs	)
					SCREAMING_SNAKE_CASE_						:List[Any]										=      load_spm(SCREAMING_SNAKE_CASE      ,       self.sp_model_kwargs	)
					SCREAMING_SNAKE_CASE_						:int										=      self.spm_source
					SCREAMING_SNAKE_CASE_						:List[Any]										=      self.encoder

					# Multilingual target side: default to using first supported language code.

					self._setup_normalizer()






			def 				_lowercase	(   self  :							int	):




					"""simple docstring"""







					try:
							from sacremoses import MosesPunctNormalizer

							SCREAMING_SNAKE_CASE_						:Dict										=      MosesPunctNormalizer(self.source_lang	).normalize
					except (ImportError, FileNotFoundError):
							warnings.warn('Recommended: pip install sacremoses.'	)
							SCREAMING_SNAKE_CASE_						:Tuple										=      lambda SCREAMING_SNAKE_CASE	: x






			def 				_lowercase	(   self  :							List[Any]      ,       SCREAMING_SNAKE_CASE  :							str	):




					"""simple docstring"""







					return self.punc_normalizer(SCREAMING_SNAKE_CASE	) if x else ""






			def 				_lowercase	(   self  :							int      ,       SCREAMING_SNAKE_CASE  :							str	):




					"""simple docstring"""







					return self.current_encoder.get(SCREAMING_SNAKE_CASE      ,       self.current_encoder[self.unk_token]	)






			def 				_lowercase	(   self  :							int      ,       SCREAMING_SNAKE_CASE  :							str	):




					"""simple docstring"""







					SCREAMING_SNAKE_CASE_						:Dict										=      self.language_code_re.match(SCREAMING_SNAKE_CASE	)
					SCREAMING_SNAKE_CASE_						:list										=      [match.group(0	)] if match else []
					return code, self.language_code_re.sub(''      ,       SCREAMING_SNAKE_CASE	)






			def 				_lowercase	(   self  :							List[Any]      ,       SCREAMING_SNAKE_CASE  :							str	):




					"""simple docstring"""







					SCREAMING_SNAKE_CASE_						,		SCREAMING_SNAKE_CASE_						:str										=      self.remove_language_code(SCREAMING_SNAKE_CASE	)
					SCREAMING_SNAKE_CASE_						:List[str]										=      self.current_spm.encode(SCREAMING_SNAKE_CASE      ,       out_type=SCREAMING_SNAKE_CASE	)
					return code + pieces






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




					"""simple docstring"""







					return self.decoder.get(SCREAMING_SNAKE_CASE      ,       self.unk_token	)






			def 				_lowercase	(   self  :							int      ,       SCREAMING_SNAKE_CASE  :							Dict      ,       **SCREAMING_SNAKE_CASE  :							List[str]	):




					"""simple docstring"""







					return super().batch_decode(SCREAMING_SNAKE_CASE      ,       **SCREAMING_SNAKE_CASE	)






			def 				_lowercase	(   self  :							Optional[Any]      ,       SCREAMING_SNAKE_CASE  :							Dict      ,       **SCREAMING_SNAKE_CASE  :							Optional[Any]	):




					"""simple docstring"""







					return super().decode(SCREAMING_SNAKE_CASE      ,       **SCREAMING_SNAKE_CASE	)






			def 				_lowercase	(   self  :							Dict      ,       SCREAMING_SNAKE_CASE  :							List[str]	):




					"""simple docstring"""







					SCREAMING_SNAKE_CASE_						:Tuple										=      self.spm_source if self._decode_use_source_tokenizer else self.spm_target
					SCREAMING_SNAKE_CASE_						:List[str]										=      []
					SCREAMING_SNAKE_CASE_						:str										=      ''
					for token in tokens:
							# make sure that special tokens are not decoded using sentencepiece model
							if token in self.all_special_tokens:
									out_string += sp_model.decode_pieces(SCREAMING_SNAKE_CASE	) + token + " "
									SCREAMING_SNAKE_CASE_						:int										=      []
							else:
									current_sub_tokens.append(SCREAMING_SNAKE_CASE	)
					out_string += sp_model.decode_pieces(SCREAMING_SNAKE_CASE	)
					return out_string.strip()






			def 				_lowercase	(   self  :							Optional[int]      ,       SCREAMING_SNAKE_CASE  :							Any      ,       SCREAMING_SNAKE_CASE  :							Optional[Any]=None	):




					"""simple docstring"""







					if token_ids_a is None:
							return token_ids_a + [self.eos_token_id]
					# We don't expect to process pairs, but leave the pair logic for API consistency
					return token_ids_a + token_ids_a + [self.eos_token_id]






			def 				_lowercase	(   self  :							List[Any]	):




					"""simple docstring"""







					SCREAMING_SNAKE_CASE_						:Dict										=      self.spm_source
					SCREAMING_SNAKE_CASE_						:Optional[Any]										=      self.encoder






			def 				_lowercase	(   self  :							Tuple	):




					"""simple docstring"""







					SCREAMING_SNAKE_CASE_						:str										=      self.spm_target
					if self.separate_vocabs:
							SCREAMING_SNAKE_CASE_						:Optional[Any]										=      self.target_encoder






			@property
			def 				_lowercase	(   self  :							List[str]	):




					"""simple docstring"""







					return len(self.encoder	)






			def 				_lowercase	(   self  :							List[str]      ,       SCREAMING_SNAKE_CASE  :							str      ,       SCREAMING_SNAKE_CASE  :							Optional[str] = None	):




					"""simple docstring"""







					if not os.path.isdir(SCREAMING_SNAKE_CASE	):
							logger.error(f'Vocabulary path ({save_directory}) should be a directory'	)
							return
					SCREAMING_SNAKE_CASE_						:List[Any]										=      []

					if self.separate_vocabs:
							SCREAMING_SNAKE_CASE_						:Any										=      os.path.join(
							    SCREAMING_SNAKE_CASE      ,       (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab']      ,       )
							SCREAMING_SNAKE_CASE_						:List[str]										=      os.path.join(
							    SCREAMING_SNAKE_CASE      ,       (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['target_vocab_file']      ,       )
							save_json(self.encoder      ,       SCREAMING_SNAKE_CASE	)
							save_json(self.target_encoder      ,       SCREAMING_SNAKE_CASE	)
							saved_files.append(SCREAMING_SNAKE_CASE	)
							saved_files.append(SCREAMING_SNAKE_CASE	)
					else:
							SCREAMING_SNAKE_CASE_						:List[str]										=      os.path.join(
							    SCREAMING_SNAKE_CASE      ,       (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab']	)
							save_json(self.encoder      ,       SCREAMING_SNAKE_CASE	)
							saved_files.append(SCREAMING_SNAKE_CASE	)

					for spm_save_filename, spm_orig_path, spm_model in zip(
					    [VOCAB_FILES_NAMES['source_spm'], VOCAB_FILES_NAMES['target_spm']]      ,       self.spm_files      ,       [self.spm_source, self.spm_target]      ,       ):
							SCREAMING_SNAKE_CASE_						:int										=      os.path.join(
							    SCREAMING_SNAKE_CASE      ,       (filename_prefix + '-' if filename_prefix else '') + spm_save_filename	)
							if os.path.abspath(SCREAMING_SNAKE_CASE	) != os.path.abspath(SCREAMING_SNAKE_CASE	) and os.path.isfile(SCREAMING_SNAKE_CASE	):
									copyfile(SCREAMING_SNAKE_CASE      ,       SCREAMING_SNAKE_CASE	)
									saved_files.append(SCREAMING_SNAKE_CASE	)
							elif not os.path.isfile(SCREAMING_SNAKE_CASE	):
									with open(SCREAMING_SNAKE_CASE      ,       'wb'	) as fi:
											SCREAMING_SNAKE_CASE_						:Dict										=      spm_model.serialized_model_proto()
											fi.write(SCREAMING_SNAKE_CASE	)
									saved_files.append(SCREAMING_SNAKE_CASE	)

					return tuple(SCREAMING_SNAKE_CASE	)






			def 				_lowercase	(   self  :							Dict	):




					"""simple docstring"""







					return self.get_src_vocab()






			def 				_lowercase	(   self  :							Optional[int]	):




					"""simple docstring"""







					return dict(self.encoder      ,       **self.added_tokens_encoder	)






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




					"""simple docstring"""







					return dict(self.target_encoder      ,       **self.added_tokens_decoder	)






			def __getstate__(   self  :							List[Any]	):




					"""simple docstring"""







					SCREAMING_SNAKE_CASE_						:Any										=      self.__dict__.copy()
					state.update(
					    {k: None for k in ['spm_source', 'spm_target', 'current_spm', 'punc_normalizer', 'target_vocab_file']}	)
					return state






			def __setstate__(   self  :							Any      ,       SCREAMING_SNAKE_CASE  :							Dict	):




					"""simple docstring"""







					SCREAMING_SNAKE_CASE_						:Optional[int]										=      d

					# for backward compatibility
					if not hasattr(self      ,       'sp_model_kwargs'	):
							SCREAMING_SNAKE_CASE_						:List[str]										=      {}

					SCREAMING_SNAKE_CASE_						,		SCREAMING_SNAKE_CASE_						:Tuple										=      (load_spm(SCREAMING_SNAKE_CASE      ,       self.sp_model_kwargs	) for f in self.spm_files)
					SCREAMING_SNAKE_CASE_						:Any										=      self.spm_source
					self._setup_normalizer()






			def 				_lowercase	(   self  :							List[Any]      ,       *SCREAMING_SNAKE_CASE  :							Optional[int]      ,       **SCREAMING_SNAKE_CASE  :							List[Any]	):




					"""simple docstring"""







					return 1






			def 				_lowercase	(   self  :							List[str]      ,       SCREAMING_SNAKE_CASE  :							Optional[Any]	):




					"""simple docstring"""







					SCREAMING_SNAKE_CASE_						:str										=      set(self.all_special_ids	)  # call it once instead of inside list comp
					all_special_ids.remove(self.unk_token_id	)  # <unk> is only sometimes special
					return [1 if x in all_special_ids else 0 for x in seq]






			def 				_lowercase	(   self  :							Any      ,       SCREAMING_SNAKE_CASE  :							List      ,       SCREAMING_SNAKE_CASE  :							Optional[List] = None      ,       SCREAMING_SNAKE_CASE  :							bool = False	):




					"""simple docstring"""







					if already_has_special_tokens:
							return self._special_token_mask(SCREAMING_SNAKE_CASE	)
					elif token_ids_a is None:
							return self._special_token_mask(SCREAMING_SNAKE_CASE	) + [1]
					else:
							return self._special_token_mask(token_ids_a + token_ids_a	) + [1]







def  SCREAMING_SNAKE_CASE__ (				SCREAMING_SNAKE_CASE ,		SCREAMING_SNAKE_CASE     ):
		SCREAMING_SNAKE_CASE_						:List[str]										=      sentencepiece.SentencePieceProcessor(**SCREAMING_SNAKE_CASE     )
		spm.Load(SCREAMING_SNAKE_CASE     )
		return spm







def  SCREAMING_SNAKE_CASE__ (				SCREAMING_SNAKE_CASE ,		SCREAMING_SNAKE_CASE     ):
		with open(SCREAMING_SNAKE_CASE ,		'w'     ) as f:
				json.dump(SCREAMING_SNAKE_CASE ,		SCREAMING_SNAKE_CASE ,		indent=2     )







def  SCREAMING_SNAKE_CASE__ (				SCREAMING_SNAKE_CASE     ):
		with open(SCREAMING_SNAKE_CASE ,		'r'     ) as f:
				return json.load(SCREAMING_SNAKE_CASE     )






"""simple docstring"""



from __future__ import annotations

import unittest

from transformers import MPNetConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
      import tensorflow as tf

      from transformers.models.mpnet.modeling_tf_mpnet import (
          TFMPNetForMaskedLM,
          TFMPNetForMultipleChoice,
          TFMPNetForQuestionAnswering,
          TFMPNetForSequenceClassification,
          TFMPNetForTokenClassification,
          TFMPNetModel,
      )




class       UpperCAmelCase_    :




    def __init__(       self		:			Dict      ,					snake_case_		:			List[str]      ,					snake_case_		:			List[Any]=13      ,					snake_case_		:			int=7      ,					snake_case_		:			List[Any]=True      ,					snake_case_		:			Tuple=True      ,					snake_case_		:			Tuple=False      ,					snake_case_		:			str=True      ,					snake_case_		:			str=99      ,					snake_case_		:			int=64      ,					snake_case_		:			Tuple=2      ,					snake_case_		:			Optional[int]=4      ,					snake_case_		:			List[Any]=64      ,					snake_case_		:			Any="gelu"      ,					snake_case_		:			List[Any]=0.1      ,					snake_case_		:			List[Any]=0.1      ,					snake_case_		:			Dict=512      ,					snake_case_		:			Dict=16      ,					snake_case_		:			Tuple=2      ,					snake_case_		:			Tuple=0.02      ,					snake_case_		:			Optional[Any]=3      ,					snake_case_		:			Dict=4      ,					snake_case_		:			List[str]=None      ,					) ->				Any:




     '''simple docstring'''

     A__			=							parent
     A__			=							batch_size
     A__			=							seq_length
     A__			=							is_training
     A__			=							use_input_mask
     A__			=							use_token_type_ids
     A__			=							use_labels
     A__			=							vocab_size
     A__			=							hidden_size
     A__			=							num_hidden_layers
     A__			=							num_attention_heads
     A__			=							intermediate_size
     A__			=							hidden_act
     A__			=							hidden_dropout_prob
     A__			=							attention_probs_dropout_prob
     A__			=							max_position_embeddings
     A__			=							type_vocab_size
     A__			=							type_sequence_label_size
     A__			=							initializer_range
     A__			=							num_labels
     A__			=							num_choices
     A__			=							scope




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




     '''simple docstring'''

     A__			=							ids_tensor([self.batch_size, self.seq_length]      ,					self.vocab_size )

     A__			=							None
     if self.use_input_mask:
      A__			=							random_attention_mask([self.batch_size, self.seq_length] )

     A__			=							None
     A__			=							None
     A__			=							None
     if self.use_labels:
      A__			=							ids_tensor([self.batch_size]      ,					self.type_sequence_label_size )
      A__			=							ids_tensor([self.batch_size, self.seq_length]      ,					self.num_labels )
      A__			=							ids_tensor([self.batch_size]      ,					self.num_choices )

     A__			=							MPNetConfig(
         vocab_size=self.vocab_size      ,					hidden_size=self.hidden_size      ,					num_hidden_layers=self.num_hidden_layers      ,					num_attention_heads=self.num_attention_heads      ,					intermediate_size=self.intermediate_size      ,					hidden_act=self.hidden_act      ,					hidden_dropout_prob=self.hidden_dropout_prob      ,					attention_probs_dropout_prob=self.attention_probs_dropout_prob      ,					max_position_embeddings=self.max_position_embeddings      ,					initializer_range=self.initializer_range      ,					)
     return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels




    def 				__magic_name__				(       self		:			str      ,					snake_case_		:			int      ,					snake_case_		:			int      ,					snake_case_		:			Union[str, Any]      ,					snake_case_		:			Optional[Any]      ,					snake_case_		:			Any      ,					snake_case_		:			str ) ->				int:




     '''simple docstring'''

     A__			=							TFMPNetModel(config=snake_case_ )
     A__			=							{"input_ids": input_ids, "attention_mask": input_mask}
     A__			=							model(snake_case_ )
     A__			=							[input_ids, input_mask]
     A__			=							model(snake_case_ )
     self.parent.assertEqual(result.last_hidden_state.shape      ,					(self.batch_size, self.seq_length, self.hidden_size) )




    def 				__magic_name__				(       self		:			List[Any]      ,					snake_case_		:			Union[str, Any]      ,					snake_case_		:			List[str]      ,					snake_case_		:			Optional[int]      ,					snake_case_		:			Union[str, Any]      ,					snake_case_		:			str      ,					snake_case_		:			str ) ->				int:




     '''simple docstring'''

     A__			=							TFMPNetForMaskedLM(config=snake_case_ )
     A__			=							{"input_ids": input_ids, "attention_mask": input_mask}
     A__			=							model(snake_case_ )
     self.parent.assertEqual(result.logits.shape      ,					(self.batch_size, self.seq_length, self.vocab_size) )




    def 				__magic_name__				(       self		:			List[Any]      ,					snake_case_		:			Union[str, Any]      ,					snake_case_		:			Tuple      ,					snake_case_		:			Any      ,					snake_case_		:			str      ,					snake_case_		:			Union[str, Any]      ,					snake_case_		:			Dict ) ->				Tuple:




     '''simple docstring'''

     A__			=							TFMPNetForQuestionAnswering(config=snake_case_ )
     A__			=							{
         "input_ids": input_ids,
         "attention_mask": input_mask,
     }
     A__			=							model(snake_case_ )
     self.parent.assertEqual(result.start_logits.shape      ,					(self.batch_size, self.seq_length) )
     self.parent.assertEqual(result.end_logits.shape      ,					(self.batch_size, self.seq_length) )




    def 				__magic_name__				(       self		:			List[Any]      ,					snake_case_		:			Union[str, Any]      ,					snake_case_		:			List[str]      ,					snake_case_		:			Dict      ,					snake_case_		:			Optional[int]      ,					snake_case_		:			Optional[int]      ,					snake_case_		:			Optional[int] ) ->				Tuple:




     '''simple docstring'''

     A__			=							self.num_labels
     A__			=							TFMPNetForSequenceClassification(snake_case_ )
     A__			=							{"input_ids": input_ids, "attention_mask": input_mask}
     A__			=							model(snake_case_ )
     self.parent.assertEqual(result.logits.shape      ,					(self.batch_size, self.num_labels) )




    def 				__magic_name__				(       self		:			Dict      ,					snake_case_		:			Tuple      ,					snake_case_		:			int      ,					snake_case_		:			List[Any]      ,					snake_case_		:			Optional[int]      ,					snake_case_		:			str      ,					snake_case_		:			Dict ) ->				Optional[Any]:




     '''simple docstring'''

     A__			=							self.num_choices
     A__			=							TFMPNetForMultipleChoice(snake_case_ )
     A__			=							tf.tile(tf.expand_dims(snake_case_      ,					1 )      ,					(1, self.num_choices, 1) )
     A__			=							tf.tile(tf.expand_dims(snake_case_      ,					1 )      ,					(1, self.num_choices, 1) )
     A__			=							{
         "input_ids": multiple_choice_inputs_ids,
         "attention_mask": multiple_choice_input_mask,
     }
     A__			=							model(snake_case_ )
     self.parent.assertEqual(result.logits.shape      ,					(self.batch_size, self.num_choices) )




    def 				__magic_name__				(       self		:			List[str]      ,					snake_case_		:			str      ,					snake_case_		:			Tuple      ,					snake_case_		:			Union[str, Any]      ,					snake_case_		:			List[str]      ,					snake_case_		:			Optional[Any]      ,					snake_case_		:			List[Any] ) ->				int:




     '''simple docstring'''

     A__			=							self.num_labels
     A__			=							TFMPNetForTokenClassification(snake_case_ )
     A__			=							{"input_ids": input_ids, "attention_mask": input_mask}
     A__			=							model(snake_case_ )
     self.parent.assertEqual(result.logits.shape      ,					(self.batch_size, self.seq_length, self.num_labels) )




    def 				__magic_name__				(       self		:			Tuple ) ->				Dict:




     '''simple docstring'''

     A__			=							self.prepare_config_and_inputs()
     ((A__), (A__), (A__), (A__), (A__), (A__))			=							config_and_inputs
     A__			=							{"input_ids": input_ids, "attention_mask": input_mask}
     return config, inputs_dict






@require_tf
class       UpperCAmelCase_    (		A_,  A_,  unittest.TestCase				):
    lowercase__		   = (
        (
            TFMPNetForMaskedLM,
            TFMPNetForMultipleChoice,
            TFMPNetForQuestionAnswering,
            TFMPNetForSequenceClassification,
            TFMPNetForTokenClassification,
            TFMPNetModel,
        )
        if is_tf_available()
        else ()
    )
    lowercase__		   = (
        {
            '''feature-extraction''': TFMPNetModel,
            '''fill-mask''': TFMPNetForMaskedLM,
            '''question-answering''': TFMPNetForQuestionAnswering,
            '''text-classification''': TFMPNetForSequenceClassification,
            '''token-classification''': TFMPNetForTokenClassification,
            '''zero-shot''': TFMPNetForSequenceClassification,
        }
        if is_tf_available()
        else {}
    )
    lowercase__		   = False
    lowercase__		   = False




    def 				__magic_name__				(       self		:			Any ) ->				List[str]:




     '''simple docstring'''

     A__			=							TFMPNetModelTester(self )
     A__			=							ConfigTester(self      ,					config_class=snake_case_      ,					hidden_size=37 )




    def 				__magic_name__				(       self		:			Union[str, Any] ) ->				Tuple:




     '''simple docstring'''

     self.config_tester.run_common_tests()




    def 				__magic_name__				(       self		:			Union[str, Any] ) ->				Dict:




     '''simple docstring'''

     A__			=							self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_mpnet_model(*snake_case_ )




    def 				__magic_name__				(       self		:			Optional[int] ) ->				List[Any]:




     '''simple docstring'''

     A__			=							self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_mpnet_for_masked_lm(*snake_case_ )




    def 				__magic_name__				(       self		:			Dict ) ->				Optional[Any]:




     '''simple docstring'''

     A__			=							self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_mpnet_for_question_answering(*snake_case_ )




    def 				__magic_name__				(       self		:			int ) ->				List[Any]:




     '''simple docstring'''

     A__			=							self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_mpnet_for_sequence_classification(*snake_case_ )




    def 				__magic_name__				(       self		:			Optional[Any] ) ->				int:




     '''simple docstring'''

     A__			=							self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_mpnet_for_multiple_choice(*snake_case_ )




    def 				__magic_name__				(       self		:			Tuple ) ->				Any:




     '''simple docstring'''

     A__			=							self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_mpnet_for_token_classification(*snake_case_ )




    @slow
    def 				__magic_name__				(       self		:			Dict ) ->				Tuple:




     '''simple docstring'''

     for model_name in ["microsoft/mpnet-base"]:
      A__			=							TFMPNetModel.from_pretrained(snake_case_ )
      self.assertIsNotNone(snake_case_ )






@require_tf
class       UpperCAmelCase_    (		unittest.TestCase				):




    @slow
    def 				__magic_name__				(       self		:			str ) ->				List[str]:




     '''simple docstring'''

     A__			=							TFMPNetModel.from_pretrained("microsoft/mpnet-base" )
     A__			=							tf.constant([[0, 1, 2, 3, 4, 5]] )
     A__			=							model(snake_case_ )[0]

     A__			=							[1, 6, 768]
     self.assertEqual(output.shape      ,					snake_case_ )

     A__			=							tf.constant(
         [
             [
                 [-0.106_7172, 0.0821_6473, 0.002_4543],
                 [-0.0346_5879, 0.835_4118, -0.0325_2288],
                 [-0.0656_9476, -0.1242_4111, -0.049_4436],
             ]
         ] )
     tf.debugging.assert_near(output[:, :3, :3]      ,					snake_case_      ,					atol=1e-4 )





