import math
import os
import unittest

from transformers import MegatronBertConfig, is_torch_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
      import torch

      from transformers import (
          MODEL_FOR_PRETRAINING_MAPPING,
          MegatronBertForCausalLM,
          MegatronBertForMaskedLM,
          MegatronBertForMultipleChoice,
          MegatronBertForNextSentencePrediction,
          MegatronBertForPreTraining,
          MegatronBertForQuestionAnswering,
          MegatronBertForSequenceClassification,
          MegatronBertForTokenClassification,
          MegatronBertModel,
      )

class       snake_case					:




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




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				int			=		parent
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		batch_size
       SCREAMING_SNAKE_CASE__				:				str			=		seq_length
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		is_training
       SCREAMING_SNAKE_CASE__				:				Dict			=		use_input_mask
       SCREAMING_SNAKE_CASE__				:				int			=		use_token_type_ids
       SCREAMING_SNAKE_CASE__				:				Tuple			=		use_labels
       SCREAMING_SNAKE_CASE__				:				int			=		vocab_size
       SCREAMING_SNAKE_CASE__				:				int			=		hidden_size
       SCREAMING_SNAKE_CASE__				:				str			=		embedding_size
       SCREAMING_SNAKE_CASE__				:				Tuple			=		num_hidden_layers
       SCREAMING_SNAKE_CASE__				:				Tuple			=		num_attention_heads
       SCREAMING_SNAKE_CASE__				:				List[str]			=		intermediate_size
       SCREAMING_SNAKE_CASE__				:				List[str]			=		hidden_act
       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		hidden_dropout_prob
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		attention_probs_dropout_prob
       SCREAMING_SNAKE_CASE__				:				Any			=		max_position_embeddings
       SCREAMING_SNAKE_CASE__				:				str			=		type_vocab_size
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		type_sequence_label_size
       SCREAMING_SNAKE_CASE__				:				Dict			=		initializer_range
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		num_labels
       SCREAMING_SNAKE_CASE__				:				Dict			=		num_choices
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		scope




  def 	__lowercase(      self     :	List[Any]				)->       Any:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				int			=		ids_tensor([self.batch_size, self.seq_length]     , self.vocab_size				)

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

       SCREAMING_SNAKE_CASE__				:				Tuple			=		None
       if self.use_token_type_ids:
            SCREAMING_SNAKE_CASE__				:				Any			=		ids_tensor([self.batch_size, self.seq_length]     , self.type_vocab_size				)

       SCREAMING_SNAKE_CASE__				:				Any			=		None
       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		None
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		None
       if self.use_labels:
            SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		ids_tensor([self.batch_size]     , self.type_sequence_label_size				)
            SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		ids_tensor([self.batch_size, self.seq_length]     , self.num_labels				)
            SCREAMING_SNAKE_CASE__				:				Optional[int]			=		ids_tensor([self.batch_size]     , self.num_choices				)

       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		self.get_config()

       return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels




  def 	__lowercase(      self     :	Tuple				)->       Tuple:




       """simple docstring"""
       return MegatronBertConfig(
           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     , embedding_size=self.embedding_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     , type_vocab_size=self.type_vocab_size     , is_decoder=a_     , initializer_range=self.initializer_range     , )




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




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		MegatronBertModel(config=a_				)
       model.to(a_				)
       model.eval()
       SCREAMING_SNAKE_CASE__				:				Dict			=		model(a_     , attention_mask=a_     , token_type_ids=a_				)
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		model(a_     , token_type_ids=a_				)
       SCREAMING_SNAKE_CASE__				:				str			=		model(a_				)

       self.parent.assertEqual(result.last_hidden_state.shape     , (self.batch_size, self.seq_length, self.hidden_size)				)
       self.parent.assertEqual(result.pooler_output.shape     , (self.batch_size, self.hidden_size)				)




  def 	__lowercase(      self     :	str     , a_     :	Tuple     , a_     :	str     , a_     :	int     , a_     :	Any     , a_     :	str     , a_     :	Optional[int]     , a_     :	Union[str, Any]				)->       str:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Dict			=		MegatronBertForMaskedLM(config=a_				)
       model.to(a_				)
       model.eval()
       SCREAMING_SNAKE_CASE__				:				List[str]			=		model(a_     , attention_mask=a_     , token_type_ids=a_     , labels=a_				)
       self.parent.assertEqual(result.logits.shape     , (self.batch_size, self.seq_length, self.vocab_size)				)




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




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		MegatronBertForCausalLM(config=a_				)
       model.to(a_				)
       model.eval()
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		model(a_     , attention_mask=a_     , token_type_ids=a_     , labels=a_				)
       self.parent.assertEqual(result.logits.shape     , (self.batch_size, self.seq_length, self.vocab_size)				)




  def 	__lowercase(      self     :	Optional[int]     , a_     :	Union[str, Any]     , a_     :	List[Any]     , a_     :	int     , a_     :	str     , a_     :	Union[str, Any]     , a_     :	Optional[int]     , a_     :	Dict				)->       str:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		MegatronBertForNextSentencePrediction(config=a_				)
       model.to(a_				)
       model.eval()
       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		model(
           a_     , attention_mask=a_     , token_type_ids=a_     , labels=a_     , )
       self.parent.assertEqual(result.logits.shape     , (self.batch_size, 2)				)




  def 	__lowercase(      self     :	Dict     , a_     :	List[Any]     , a_     :	Optional[Any]     , a_     :	List[str]     , a_     :	Optional[Any]     , a_     :	Union[str, Any]     , a_     :	Optional[Any]     , a_     :	Dict				)->       List[str]:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				List[str]			=		MegatronBertForPreTraining(config=a_				)
       model.to(a_				)
       model.eval()
       SCREAMING_SNAKE_CASE__				:				List[str]			=		model(
           a_     , attention_mask=a_     , token_type_ids=a_     , labels=a_     , next_sentence_label=a_     , )
       self.parent.assertEqual(result.prediction_logits.shape     , (self.batch_size, self.seq_length, self.vocab_size)				)
       self.parent.assertEqual(result.seq_relationship_logits.shape     , (self.batch_size, 2)				)




  def 	__lowercase(      self     :	str     , a_     :	Optional[int]     , a_     :	int     , a_     :	Any     , a_     :	str     , a_     :	Optional[int]     , a_     :	Dict     , a_     :	List[str]				)->       List[Any]:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				int			=		MegatronBertForQuestionAnswering(config=a_				)
       model.to(a_				)
       model.eval()
       SCREAMING_SNAKE_CASE__				:				Any			=		model(
           a_     , attention_mask=a_     , token_type_ids=a_     , start_positions=a_     , end_positions=a_     , )
       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 	__lowercase(      self     :	Optional[Any]     , a_     :	List[str]     , a_     :	List[Any]     , a_     :	int     , a_     :	Union[str, Any]     , a_     :	Union[str, Any]     , a_     :	List[Any]     , a_     :	str				)->       Union[str, Any]:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		self.num_labels
       SCREAMING_SNAKE_CASE__				:				str			=		MegatronBertForSequenceClassification(a_				)
       model.to(a_				)
       model.eval()
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		model(a_     , attention_mask=a_     , token_type_ids=a_     , labels=a_				)
       self.parent.assertEqual(result.logits.shape     , (self.batch_size, self.num_labels)				)




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




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Dict			=		self.num_labels
       SCREAMING_SNAKE_CASE__				:				Any			=		MegatronBertForTokenClassification(config=a_				)
       model.to(a_				)
       model.eval()
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		model(a_     , attention_mask=a_     , token_type_ids=a_     , labels=a_				)
       self.parent.assertEqual(result.logits.shape     , (self.batch_size, self.seq_length, self.num_labels)				)




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




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Any			=		self.num_choices
       SCREAMING_SNAKE_CASE__				:				Tuple			=		MegatronBertForMultipleChoice(config=a_				)
       model.to(a_				)
       model.eval()
       SCREAMING_SNAKE_CASE__				:				Dict			=		input_ids.unsqueeze(1				).expand(-1     , self.num_choices     , -1				).contiguous()
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		token_type_ids.unsqueeze(1				).expand(-1     , self.num_choices     , -1				).contiguous()
       SCREAMING_SNAKE_CASE__				:				List[str]			=		input_mask.unsqueeze(1				).expand(-1     , self.num_choices     , -1				).contiguous()
       SCREAMING_SNAKE_CASE__				:				str			=		model(
           a_     , attention_mask=a_     , token_type_ids=a_     , labels=a_     , )
       self.parent.assertEqual(result.logits.shape     , (self.batch_size, self.num_choices)				)




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




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				str			=		self.prepare_config_and_inputs()
       (
           (
           SCREAMING_SNAKE_CASE__
       )			,							(
           SCREAMING_SNAKE_CASE__
       )			,							(
           SCREAMING_SNAKE_CASE__
       )			,							(
           SCREAMING_SNAKE_CASE__
       )			,							(
           SCREAMING_SNAKE_CASE__
       )			,							(
           SCREAMING_SNAKE_CASE__
       )			,							(
           SCREAMING_SNAKE_CASE__
       )			,							
       )				:				Any			=		config_and_inputs
       SCREAMING_SNAKE_CASE__				:				Any			=		{'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
       return config, inputs_dict




@require_torch
class       snake_case					(      UpperCamelCase_   ,						UpperCamelCase_   ,						unittest.TestCase						):
  lowercase_			=     (
      (
          MegatronBertModel,
          MegatronBertForMaskedLM,
          MegatronBertForCausalLM,
          MegatronBertForMultipleChoice,
          MegatronBertForNextSentencePrediction,
          MegatronBertForPreTraining,
          MegatronBertForQuestionAnswering,
          MegatronBertForSequenceClassification,
          MegatronBertForTokenClassification,
      )
      if is_torch_available()
      else ()
  )
  lowercase_			=     (
      {
          'feature-extraction': MegatronBertModel,
          'fill-mask': MegatronBertForMaskedLM,
          'question-answering': MegatronBertForQuestionAnswering,
          'text-classification': MegatronBertForSequenceClassification,
          'text-generation': MegatronBertForCausalLM,
          'token-classification': MegatronBertForTokenClassification,
          'zero-shot': MegatronBertForSequenceClassification,
      }
      if is_torch_available()
      else {}
  )
  lowercase_			=     True
  # test_resize_embeddings = False
  lowercase_			=     False




  def 	__lowercase(      self     :	str     , a_     :	Union[str, Any]     , a_     :	List[str]     , a_     :	List[str]=False				)->       Union[str, Any]:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Any			=		super()._prepare_for_class(a_     , a_     , return_labels=a_				)

       if return_labels:
            if model_class in get_values(a_				):
                 SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		torch.zeros(
                     (self.model_tester.batch_size, self.model_tester.seq_length)     , dtype=torch.long     , device=a_				)
                 SCREAMING_SNAKE_CASE__				:				str			=		torch.zeros(
                     self.model_tester.batch_size     , dtype=torch.long     , device=a_				)
       return inputs_dict




  def 	__lowercase(      self     :	List[str]				)->       Union[str, Any]:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		MegatronBertModelTester(self				)
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		ConfigTester(self     , config_class=a_     , hidden_size=37				)




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




       """simple docstring"""
       self.config_tester.run_common_tests()




  def 	__lowercase(      self     :	List[Any]				)->       Tuple:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_megatron_bert_model(*a_				)




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




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_megatron_bert_for_masked_lm(*a_				)




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




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				str			=		self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_megatron_bert_for_multiple_choice(*a_				)




  def 	__lowercase(      self     :	int				)->       Any:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_megatron_bert_for_next_sequence_prediction(*a_				)




  def 	__lowercase(      self     :	Tuple				)->       Dict:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Any			=		self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_megatron_bert_for_pretraining(*a_				)




  def 	__lowercase(      self     :	int				)->       int:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Dict			=		self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_megatron_bert_for_question_answering(*a_				)




  def 	__lowercase(      self     :	List[Any]				)->       Dict:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_megatron_bert_for_sequence_classification(*a_				)




  def 	__lowercase(      self     :	Dict				)->       List[str]:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_megatron_bert_for_token_classification(*a_				)







def     _a				(      lowercase__  :			Union[str, Any] ):







     '''simple docstring'''


     return torch.tensor(
         lowercase__     ,  dtype=torch.long     ,  device=lowercase__     ,  )


SCREAMING_SNAKE_CASE__		:					Optional[Any]						=					1E-4







@require_torch
@require_sentencepiece
@require_tokenizers
class       snake_case					(      unittest.TestCase						):




  @slow
  @unittest.skip('Model is not available.'				)
  def 	__lowercase(      self     :	int				)->       Dict:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		'nvidia/megatron-bert-uncased-345m'
       if "MYDIR" in os.environ:
            SCREAMING_SNAKE_CASE__				:				Optional[int]			=		os.path.join(os.environ['MYDIR']     , a_				)
       SCREAMING_SNAKE_CASE__				:				Dict			=		MegatronBertModel.from_pretrained(a_				)
       model.to(a_				)
       model.half()
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		_long_tensor([[101, 7110, 1005, 1056, 2023, 1_1333, 1_7413, 1029, 102]]				)
       with torch.no_grad():
            SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		model(a_				)[0]
       SCREAMING_SNAKE_CASE__				:				List[str]			=		torch.Size((1, 9, 1024)				)
       self.assertEqual(output.shape     , a_				)

       SCREAMING_SNAKE_CASE__				:				Tuple			=		[-0.6040, -0.2517, -0.1025, 0.3420, -0.6758, -0.0017, -0.1089, -0.1990, 0.5728]
       for ii in range(3				):
            for jj in range(3				):
                 SCREAMING_SNAKE_CASE__				:				List[str]			=		output[0, ii, jj]
                 SCREAMING_SNAKE_CASE__				:				List[Any]			=		expected[3 * ii + jj]
                 SCREAMING_SNAKE_CASE__				:				Dict			=		'ii={} jj={} a={} b={}'.format(a_     , a_     , a_     , a_				)
                 self.assertTrue(math.isclose(a_     , a_     , rel_tol=a_     , abs_tol=a_				)     , msg=a_				)




import unittest

from transformers import PegasusTokenizer, PegasusTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow
from transformers.utils import cached_property

from ...test_tokenization_common import TokenizerTesterMixin


SCREAMING_SNAKE_CASE__		:					List[Any]						=					get_tests_dir("fixtures/test_sentencepiece_no_bos.model")

@require_sentencepiece
@require_tokenizers
class       snake_case					(      UpperCamelCase_   ,						unittest.TestCase						):
  lowercase_			=     PegasusTokenizer
  lowercase_			=     PegasusTokenizerFast
  lowercase_			=     True
  lowercase_			=     True




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




       """simple docstring"""
       super().setUp()

       # We have a SentencePiece fixture for testing
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		PegasusTokenizer(a_				)
       tokenizer.save_pretrained(self.tmpdirname				)




  @cached_property
  def 	__lowercase(      self     :	Optional[Any]				)->       Optional[int]:




       """simple docstring"""
       return PegasusTokenizer.from_pretrained('google/pegasus-large'				)




  def 	__lowercase(      self     :	Any     , **a_     :	Optional[Any]				)->       PegasusTokenizer:




       """simple docstring"""
       return PegasusTokenizer.from_pretrained(self.tmpdirname     , **a_				)




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




       """simple docstring"""
       return ("This is a test", "This is a test")




  def 	__lowercase(      self     :	Optional[int]				)->       Dict:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				List[str]			=		'</s>'
       SCREAMING_SNAKE_CASE__				:				Any			=		1

       self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_				)     , a_				)
       self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_				)     , a_				)




  def 	__lowercase(      self     :	Dict				)->       Any:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Any			=		list(self.get_tokenizer().get_vocab().keys()				)

       self.assertEqual(vocab_keys[0]     , '<pad>'				)
       self.assertEqual(vocab_keys[1]     , '</s>'				)
       self.assertEqual(vocab_keys[-1]     , 'v'				)
       self.assertEqual(len(a_				)     , 1103				)




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




       """simple docstring"""
       self.assertEqual(self.get_tokenizer().vocab_size     , 1103				)




  def 	__lowercase(      self     :	List[Any]				)->       Union[str, Any]:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				int			=		self.rust_tokenizer_class.from_pretrained(self.tmpdirname				)
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		self.tokenizer_class.from_pretrained(self.tmpdirname				)
       SCREAMING_SNAKE_CASE__				:				Tuple			=		(
           'Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important'
           ' </s> <pad> <pad> <pad>'
       )
       SCREAMING_SNAKE_CASE__				:				List[str]			=		rust_tokenizer([raw_input_str]     , return_tensors=a_     , add_special_tokens=a_				).input_ids[0]
       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		py_tokenizer([raw_input_str]     , return_tensors=a_     , add_special_tokens=a_				).input_ids[0]
       self.assertListEqual(a_     , a_				)




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




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				int			=		self._large_tokenizer
       # <mask_1> masks whole sentence while <mask_2> masks single word
       SCREAMING_SNAKE_CASE__				:				Any			=		'<mask_1> To ensure a <mask_2> flow of bank resolutions.'
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		[2, 413, 615, 114, 3, 1971, 113, 1679, 1_0710, 107, 1]
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		tokenizer([raw_input_str]     , return_tensors=a_				).input_ids[0]
       self.assertListEqual(a_     , a_				)




  def 	__lowercase(      self     :	int				)->       int:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Any			=		self._large_tokenizer
       # The tracebacks for the following asserts are **better** without messages or self.assertEqual
       assert tokenizer.vocab_size == 9_6103
       assert tokenizer.pad_token_id == 0
       assert tokenizer.eos_token_id == 1
       assert tokenizer.offset == 103
       assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105
       assert tokenizer.unk_token == "<unk>"
       assert tokenizer.model_max_length == 1024
       SCREAMING_SNAKE_CASE__				:				int			=		'To ensure a smooth flow of bank resolutions.'
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		[413, 615, 114, 2291, 1971, 113, 1679, 1_0710, 107, 1]
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		tokenizer([raw_input_str]     , return_tensors=a_				).input_ids[0]
       self.assertListEqual(a_     , a_				)
       assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3]				) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"]




  @require_torch
  def 	__lowercase(      self     :	Union[str, Any]				)->       Optional[Any]:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Tuple			=		['This is going to be way too long.' * 150, 'short example']
       SCREAMING_SNAKE_CASE__				:				int			=		['not super long but more than 5 tokens', 'tiny']
       SCREAMING_SNAKE_CASE__				:				int			=		self._large_tokenizer(a_     , padding=a_     , truncation=a_     , return_tensors='pt'				)
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		self._large_tokenizer(
           text_target=a_     , max_length=5     , padding=a_     , truncation=a_     , return_tensors='pt'				)

       assert batch.input_ids.shape == (2, 1024)
       assert batch.attention_mask.shape == (2, 1024)
       assert targets["input_ids"].shape == (2, 5)
       assert len(a_				) == 2  # input_ids, attention_mask.




  @slow
  def 	__lowercase(      self     :	Any				)->       str:




       """simple docstring"""
       # fmt: off
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		{'input_ids': [[3_8979, 143, 1_8485, 606, 130, 2_6669, 8_7686, 121, 5_4189, 1129, 111, 2_6669, 8_7686, 121, 9114, 1_4787, 121, 1_3249, 158, 592, 956, 121, 1_4621, 3_1576, 143, 6_2613, 108, 9688, 930, 4_3430, 1_1562, 6_2613, 304, 108, 1_1443, 897, 108, 9314, 1_7415, 6_3399, 108, 1_1443, 7614, 1_8316, 118, 4284, 7148, 1_2430, 143, 1400, 2_5703, 158, 111, 4284, 7148, 1_1772, 143, 2_1297, 1064, 158, 122, 204, 3506, 1754, 1133, 1_4787, 1581, 115, 3_3224, 4482, 111, 1355, 110, 2_9173, 317, 5_0833, 108, 2_0147, 9_4665, 111, 7_7198, 107, 1], [110, 6_2613, 117, 638, 112, 1133, 121, 2_0098, 1355, 7_9050, 1_3872, 135, 1596, 5_3541, 1352, 141, 1_3039, 5542, 124, 302, 518, 111, 268, 2956, 115, 149, 4427, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [139, 1235, 2799, 1_8289, 1_7780, 204, 109, 9474, 1296, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]}  # noqa: E501
       # fmt: on

       self.tokenizer_integration_test_util(
           expected_encoding=a_     , model_name='google/bigbird-pegasus-large-arxiv'     , revision='ba85d0851d708441f91440d509690f1ab6353415'     , )




@require_sentencepiece
@require_tokenizers
class       snake_case					(      UpperCamelCase_   ,						unittest.TestCase						):
  lowercase_			=     PegasusTokenizer
  lowercase_			=     PegasusTokenizerFast
  lowercase_			=     True
  lowercase_			=     True




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




       """simple docstring"""
       super().setUp()

       # We have a SentencePiece fixture for testing
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		PegasusTokenizer(a_     , offset=0     , mask_token_sent=a_     , mask_token='[MASK]'				)
       tokenizer.save_pretrained(self.tmpdirname				)




  @cached_property
  def 	__lowercase(      self     :	Optional[Any]				)->       List[str]:




       """simple docstring"""
       return PegasusTokenizer.from_pretrained('google/bigbird-pegasus-large-arxiv'				)




  def 	__lowercase(      self     :	List[str]     , **a_     :	Optional[Any]				)->       PegasusTokenizer:




       """simple docstring"""
       return PegasusTokenizer.from_pretrained(self.tmpdirname     , **a_				)




  def 	__lowercase(      self     :	Optional[Any]     , a_     :	Tuple				)->       str:




       """simple docstring"""
       return ("This is a test", "This is a test")




  def 	__lowercase(      self     :	str				)->       str:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		self.rust_tokenizer_class.from_pretrained(self.tmpdirname				)
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		self.tokenizer_class.from_pretrained(self.tmpdirname				)
       SCREAMING_SNAKE_CASE__				:				Tuple			=		(
           'Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>'
           ' <pad> <pad> <pad>'
       )
       SCREAMING_SNAKE_CASE__				:				str			=		rust_tokenizer([raw_input_str]     , return_tensors=a_     , add_special_tokens=a_				).input_ids[0]
       SCREAMING_SNAKE_CASE__				:				str			=		py_tokenizer([raw_input_str]     , return_tensors=a_     , add_special_tokens=a_				).input_ids[0]
       self.assertListEqual(a_     , a_				)




  @require_torch
  def 	__lowercase(      self     :	List[str]				)->       Union[str, Any]:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		['This is going to be way too long.' * 1000, 'short example']
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		['not super long but more than 5 tokens', 'tiny']
       SCREAMING_SNAKE_CASE__				:				str			=		self._large_tokenizer(a_     , padding=a_     , truncation=a_     , return_tensors='pt'				)
       SCREAMING_SNAKE_CASE__				:				int			=		self._large_tokenizer(
           text_target=a_     , max_length=5     , padding=a_     , truncation=a_     , return_tensors='pt'				)

       assert batch.input_ids.shape == (2, 4096)
       assert batch.attention_mask.shape == (2, 4096)
       assert targets["input_ids"].shape == (2, 5)
       assert len(a_				) == 2  # input_ids, attention_mask.




  def 	__lowercase(      self     :	Dict				)->       str:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				int			=		(
           'This is an example string that is used to test the original TF implementation against the HF'
           ' implementation'
       )

       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		self._large_tokenizer(a_				).input_ids

       self.assertListEqual(
           a_     , [182, 117, 142, 587, 4211, 120, 117, 263, 112, 804, 109, 856, 2_5016, 3137, 464, 109, 2_6955, 3137, 1]     , )



