




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 		__lowercase						:




      """simple docstring"""





      def __init__( self							, A							, A=1_3							, A=7							, A=True							, A=True							, A=True							, A=True							, A=9_9							, A=6_4							, A=3_2							, A=5							, A=4							, A=3_7							, A="gelu"							, A=0.1							, A=0.1							, A=5_1_2							, A=1_6							, A=2							, A=0.02							, A=3							, A=4							, A=None							, )						->							Tuple:
         snake_case :							Union[str, Any]           =			parent
         snake_case :							Optional[int]           =			batch_size
         snake_case :							str           =			seq_length
         snake_case :							Optional[Any]           =			is_training
         snake_case :							Any           =			use_input_mask
         snake_case :							Any           =			use_token_type_ids
         snake_case :							Any           =			use_labels
         snake_case :							List[str]           =			vocab_size
         snake_case :							Any           =			hidden_size
         snake_case :							int           =			embedding_size
         snake_case :							int           =			num_hidden_layers
         snake_case :							Optional[Any]           =			num_attention_heads
         snake_case :							Optional[Any]           =			intermediate_size
         snake_case :							List[Any]           =			hidden_act
         snake_case :							Tuple           =			hidden_dropout_prob
         snake_case :							List[Any]           =			attention_probs_dropout_prob
         snake_case :							List[str]           =			max_position_embeddings
         snake_case :							Tuple           =			type_vocab_size
         snake_case :							List[Any]           =			type_sequence_label_size
         snake_case :							List[Any]           =			initializer_range
         snake_case :							Dict           =			num_labels
         snake_case :							Any           =			num_choices
         snake_case :							List[Any]           =			scope

      def       UpperCAmelCase ( self      )						->							List[str]:
         snake_case :							Dict           =			ids_tensor([self.batch_size, self.seq_length]							, self.vocab_size      )

         snake_case :							List[str]           =			None
         if self.use_input_mask:
            snake_case :							Dict           =			random_attention_mask([self.batch_size, self.seq_length]      )

         snake_case :							int           =			None
         if self.use_token_type_ids:
            snake_case :							List[str]           =			ids_tensor([self.batch_size, self.seq_length]							, self.type_vocab_size      )

         snake_case :							List[str]           =			None
         snake_case :							Optional[Any]           =			None
         snake_case :							Tuple           =			None
         if self.use_labels:
            snake_case :							List[str]           =			ids_tensor([self.batch_size]							, self.type_sequence_label_size      )
            snake_case :							Tuple           =			ids_tensor([self.batch_size, self.seq_length]							, self.num_labels      )
            snake_case :							Any           =			ids_tensor([self.batch_size]							, self.num_choices      )

         snake_case :							str           =			self.get_config()

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

      def       UpperCAmelCase ( self      )						->							List[Any]:
         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=snake_case_							, initializer_range=self.initializer_range							, )

      def       UpperCAmelCase ( self							, A							, A							, A							, A							, A							, A							, A      )						->							List[str]:
         snake_case :							Any           =			MegatronBertModel(config=snake_case_      )
         model.to(snake_case_      )
         model.eval()
         snake_case :							Union[str, Any]           =			model(snake_case_							, attention_mask=snake_case_							, token_type_ids=snake_case_      )
         snake_case :							Any           =			model(snake_case_							, token_type_ids=snake_case_      )
         snake_case :							Tuple           =			model(snake_case_      )

         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       UpperCAmelCase ( self							, A							, A							, A							, A							, A							, A							, A      )						->							List[str]:
         snake_case :							Optional[Any]           =			MegatronBertForMaskedLM(config=snake_case_      )
         model.to(snake_case_      )
         model.eval()
         snake_case :							Tuple           =			model(snake_case_							, attention_mask=snake_case_							, token_type_ids=snake_case_							, labels=snake_case_      )
         self.parent.assertEqual(result.logits.shape							, (self.batch_size, self.seq_length, self.vocab_size)      )

      def       UpperCAmelCase ( self							, A							, A							, A							, A							, A							, A							, A      )						->							int:
         snake_case :							Optional[Any]           =			MegatronBertForCausalLM(config=snake_case_      )
         model.to(snake_case_      )
         model.eval()
         snake_case :							List[Any]           =			model(snake_case_							, attention_mask=snake_case_							, token_type_ids=snake_case_							, labels=snake_case_      )
         self.parent.assertEqual(result.logits.shape							, (self.batch_size, self.seq_length, self.vocab_size)      )

      def       UpperCAmelCase ( self							, A							, A							, A							, A							, A							, A							, A      )						->							Tuple:
         snake_case :							Union[str, Any]           =			MegatronBertForNextSentencePrediction(config=snake_case_      )
         model.to(snake_case_      )
         model.eval()
         snake_case :							List[str]           =			model(
             snake_case_							, attention_mask=snake_case_							, token_type_ids=snake_case_							, labels=snake_case_							, )
         self.parent.assertEqual(result.logits.shape							, (self.batch_size, 2)      )

      def       UpperCAmelCase ( self							, A							, A							, A							, A							, A							, A							, A      )						->							Optional[int]:
         snake_case :							int           =			MegatronBertForPreTraining(config=snake_case_      )
         model.to(snake_case_      )
         model.eval()
         snake_case :							List[Any]           =			model(
             snake_case_							, attention_mask=snake_case_							, token_type_ids=snake_case_							, labels=snake_case_							, next_sentence_label=snake_case_							, )
         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       UpperCAmelCase ( self							, A							, A							, A							, A							, A							, A							, A      )						->							Any:
         snake_case :							int           =			MegatronBertForQuestionAnswering(config=snake_case_      )
         model.to(snake_case_      )
         model.eval()
         snake_case :							Optional[Any]           =			model(
             snake_case_							, attention_mask=snake_case_							, token_type_ids=snake_case_							, start_positions=snake_case_							, end_positions=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       UpperCAmelCase ( self							, A							, A							, A							, A							, A							, A							, A      )						->							Optional[int]:
         snake_case :							Optional[int]           =			self.num_labels
         snake_case :							Dict           =			MegatronBertForSequenceClassification(snake_case_      )
         model.to(snake_case_      )
         model.eval()
         snake_case :							Optional[int]           =			model(snake_case_							, attention_mask=snake_case_							, token_type_ids=snake_case_							, labels=snake_case_      )
         self.parent.assertEqual(result.logits.shape							, (self.batch_size, self.num_labels)      )

      def       UpperCAmelCase ( self							, A							, A							, A							, A							, A							, A							, A      )						->							Dict:
         snake_case :							List[str]           =			self.num_labels
         snake_case :							List[Any]           =			MegatronBertForTokenClassification(config=snake_case_      )
         model.to(snake_case_      )
         model.eval()
         snake_case :							int           =			model(snake_case_							, attention_mask=snake_case_							, token_type_ids=snake_case_							, labels=snake_case_      )
         self.parent.assertEqual(result.logits.shape							, (self.batch_size, self.seq_length, self.num_labels)      )

      def       UpperCAmelCase ( self							, A							, A							, A							, A							, A							, A							, A      )						->							Dict:
         snake_case :							List[str]           =			self.num_choices
         snake_case :							Any           =			MegatronBertForMultipleChoice(config=snake_case_      )
         model.to(snake_case_      )
         model.eval()
         snake_case :							int           =			input_ids.unsqueeze(1      ).expand(-1							, self.num_choices							, -1      ).contiguous()
         snake_case :							Union[str, Any]           =			token_type_ids.unsqueeze(1      ).expand(-1							, self.num_choices							, -1      ).contiguous()
         snake_case :							Union[str, Any]           =			input_mask.unsqueeze(1      ).expand(-1							, self.num_choices							, -1      ).contiguous()
         snake_case :							Optional[Any]           =			model(
             snake_case_							, attention_mask=snake_case_							, token_type_ids=snake_case_							, labels=snake_case_							, )
         self.parent.assertEqual(result.logits.shape							, (self.batch_size, self.num_choices)      )

      def       UpperCAmelCase ( self      )						->							Union[str, Any]:
         snake_case :							Optional[int]           =			self.prepare_config_and_inputs()
         (
             (
             snake_case			
         )      ,   (
             snake_case			
         )      ,   (
             snake_case			
         )      ,   (
             snake_case			
         )      ,   (
             snake_case			
         )      ,   (
             snake_case			
         )      ,   (
             snake_case			
         )      ,   			
         ) :							List[Any]           =			config_and_inputs
         snake_case :							int           =			{"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
         return config, inputs_dict




@require_torch
class 		__lowercase						(lowerCAmelCase__	,						lowerCAmelCase__	,						unittest.TestCase				):




      """simple docstring"""





      _snake_case					=		(
          (
              MegatronBertModel,
              MegatronBertForMaskedLM,
              MegatronBertForCausalLM,
              MegatronBertForMultipleChoice,
              MegatronBertForNextSentencePrediction,
              MegatronBertForPreTraining,
              MegatronBertForQuestionAnswering,
              MegatronBertForSequenceClassification,
              MegatronBertForTokenClassification,
          )
          if is_torch_available()
          else ()
      )
      _snake_case					=		(
          {
              """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 {}
      )
      _snake_case					=		True
      # test_resize_embeddings = False
      _snake_case					=		False

      def       UpperCAmelCase ( self							, A							, A							, A=False      )						->							Tuple:
         snake_case :							str           =			super()._prepare_for_class(snake_case_							, snake_case_							, return_labels=snake_case_      )

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

      def       UpperCAmelCase ( self      )						->							List[Any]:
         snake_case :							Dict           =			MegatronBertModelTester(self      )
         snake_case :							Optional[int]           =			ConfigTester(self							, config_class=snake_case_							, hidden_size=3_7      )

      def       UpperCAmelCase ( self      )						->							int:
         self.config_tester.run_common_tests()

      def       UpperCAmelCase ( self      )						->							List[str]:
         snake_case :							List[Any]           =			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_megatron_bert_model(*snake_case_      )

      def       UpperCAmelCase ( self      )						->							Optional[int]:
         snake_case :							Optional[Any]           =			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_megatron_bert_for_masked_lm(*snake_case_      )

      def       UpperCAmelCase ( self      )						->							str:
         snake_case :							Optional[Any]           =			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_megatron_bert_for_multiple_choice(*snake_case_      )

      def       UpperCAmelCase ( self      )						->							List[Any]:
         snake_case :							List[Any]           =			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_megatron_bert_for_next_sequence_prediction(*snake_case_      )

      def       UpperCAmelCase ( self      )						->							Dict:
         snake_case :							Union[str, Any]           =			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_megatron_bert_for_pretraining(*snake_case_      )

      def       UpperCAmelCase ( self      )						->							Optional[Any]:
         snake_case :							Tuple           =			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_megatron_bert_for_question_answering(*snake_case_      )

      def       UpperCAmelCase ( self      )						->							List[Any]:
         snake_case :							str           =			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_megatron_bert_for_sequence_classification(*snake_case_      )

      def       UpperCAmelCase ( self      )						->							Dict:
         snake_case :							str           =			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_megatron_bert_for_token_classification(*snake_case_      )




def 		SCREAMING_SNAKE_CASE__   (       lowercase	)    ->  Dict:
   return torch.tensor(
       _UpperCamelCase		,dtype=torch.long		,device=_UpperCamelCase		,)


lowerCamelCase			:			Optional[Any]								=       1e-4




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




      """simple docstring"""





      @slow
      @unittest.skip("""Model is not available."""      )
      def       UpperCAmelCase ( self      )						->							Tuple:
         snake_case :							Optional[Any]           =			"""nvidia/megatron-bert-uncased-345m"""
         if "MYDIR" in os.environ:
            snake_case :							int           =			os.path.join(os.environ["""MYDIR"""]							, snake_case_      )
         snake_case :							List[str]           =			MegatronBertModel.from_pretrained(snake_case_      )
         model.to(snake_case_      )
         model.half()
         snake_case :							Optional[int]           =			_long_tensor([[1_0_1, 7_1_1_0, 1_0_0_5, 1_0_5_6, 2_0_2_3, 1_1_3_3_3, 1_7_4_1_3, 1_0_2_9, 1_0_2]]      )
         with torch.no_grad():
            snake_case :							Dict           =			model(snake_case_      )[0]
         snake_case :							Tuple           =			torch.Size((1, 9, 1_0_2_4)      )
         self.assertEqual(output.shape							, snake_case_      )

         snake_case :							Any           =			[-0.60_40, -0.25_17, -0.10_25, 0.34_20, -0.67_58, -0.00_17, -0.10_89, -0.19_90, 0.57_28]
         for ii in range(3      ):
            for jj in range(3      ):
               snake_case :							Optional[int]           =			output[0, ii, jj]
               snake_case :							Dict           =			expected[3 * ii + jj]
               snake_case :							Any           =			"""ii={} jj={} a={} b={}""".format(snake_case_							, snake_case_							, snake_case_							, snake_case_      )
               self.assertTrue(math.isclose(snake_case_							, snake_case_							, rel_tol=snake_case_							, abs_tol=snake_case_      )							, msg=snake_case_      )









import unittest

import numpy as np

from transformers.testing_utils import is_flaky, require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
	import torch

if is_vision_available():
	from PIL import Image

	from transformers import DonutImageProcessor
class 						lowerCamelCase_							(					unittest.TestCase					):



					'''simple docstring'''







					def __init__(					self			,							snake_case_			,							snake_case_=7			,							snake_case_=3			,							snake_case_=1_8			,							snake_case_=3_0			,							snake_case_=4_0_0			,							snake_case_=True			,							snake_case_=None			,							snake_case_=True			,							snake_case_=False			,							snake_case_=True			,							snake_case_=True			,							snake_case_=[0.5, 0.5, 0.5]			,							snake_case_=[0.5, 0.5, 0.5]			,							) ->      Optional[Any]:







								'''simple docstring'''

								__lowercase			       = parent
								__lowercase			       = batch_size
								__lowercase			       = num_channels
								__lowercase			       = image_size
								__lowercase			       = min_resolution
								__lowercase			       = max_resolution
								__lowercase			       = do_resize
								__lowercase			       = size if size is not None else {'''height''': 1_8, '''width''': 2_0}
								__lowercase			       = do_thumbnail
								__lowercase			       = do_align_axis
								__lowercase			       = do_pad
								__lowercase			       = do_normalize
								__lowercase			       = image_mean
								__lowercase			       = image_std






					def A   (					self    ) ->      Dict:







								'''simple docstring'''

								return {
								    "do_resize": self.do_resize,
								    "size": self.size,
								    "do_thumbnail": self.do_thumbnail,
								    "do_align_long_axis": self.do_align_axis,
								    "do_pad": self.do_pad,
								    "do_normalize": self.do_normalize,
								    "image_mean": self.image_mean,
								    "image_std": self.image_std,
								}




@require_torch
@require_vision
class 						lowerCamelCase_							(					lowerCAmelCase__  ,  unittest.TestCase					):



					'''simple docstring'''







					__UpperCAmelCase							  =					DonutImageProcessor if is_vision_available() else None






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







								'''simple docstring'''

								__lowercase			       = DonutImageProcessingTester(self    )






					@property
					def A   (					self    ) ->      str:







								'''simple docstring'''

								return self.image_processor_tester.prepare_image_processor_dict()






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







								'''simple docstring'''

								__lowercase			       = self.image_processing_class(**self.image_processor_dict    )
								self.assertTrue(hasattr(snake_case_			,							'''do_resize'''    )    )
								self.assertTrue(hasattr(snake_case_			,							'''size'''    )    )
								self.assertTrue(hasattr(snake_case_			,							'''do_thumbnail'''    )    )
								self.assertTrue(hasattr(snake_case_			,							'''do_align_long_axis'''    )    )
								self.assertTrue(hasattr(snake_case_			,							'''do_pad'''    )    )
								self.assertTrue(hasattr(snake_case_			,							'''do_normalize'''    )    )
								self.assertTrue(hasattr(snake_case_			,							'''image_mean'''    )    )
								self.assertTrue(hasattr(snake_case_			,							'''image_std'''    )    )






					def A   (					self    ) ->      List[str]:







								'''simple docstring'''

								__lowercase			       = self.image_processing_class.from_dict(self.image_processor_dict    )
								self.assertEqual(image_processor.size			,							{'''height''': 1_8, '''width''': 2_0}    )

								__lowercase			       = self.image_processing_class.from_dict(self.image_processor_dict			,							size=4_2    )
								self.assertEqual(image_processor.size			,							{'''height''': 4_2, '''width''': 4_2}    )

								# Previous config had dimensions in (width, height) order
								__lowercase			       = self.image_processing_class.from_dict(self.image_processor_dict			,							size=(4_2, 8_4)    )
								self.assertEqual(image_processor.size			,							{'''height''': 8_4, '''width''': 4_2}    )






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







								'''simple docstring'''

								pass






					@is_flaky()
					def A   (					self    ) ->      Optional[Any]:







								'''simple docstring'''

								__lowercase			       = self.image_processing_class(**self.image_processor_dict    )
								# create random PIL images
								__lowercase			       = prepare_image_inputs(self.image_processor_tester			,							equal_resolution=snake_case_    )
								for image in image_inputs:
											self.assertIsInstance(snake_case_			,							Image.Image    )

								# Test not batched input
								__lowercase			       = image_processing(image_inputs[0]			,							return_tensors='''pt'''    ).pixel_values
								self.assertEqual(
								    encoded_images.shape			,							(
								        1,
								        self.image_processor_tester.num_channels,
								        self.image_processor_tester.size['''height'''],
								        self.image_processor_tester.size['''width'''],
								    )			,							)

								# Test batched
								__lowercase			       = image_processing(snake_case_			,							return_tensors='''pt'''    ).pixel_values
								self.assertEqual(
								    encoded_images.shape			,							(
								        self.image_processor_tester.batch_size,
								        self.image_processor_tester.num_channels,
								        self.image_processor_tester.size['''height'''],
								        self.image_processor_tester.size['''width'''],
								    )			,							)






					@is_flaky()
					def A   (					self    ) ->      Dict:







								'''simple docstring'''

								__lowercase			       = self.image_processing_class(**self.image_processor_dict    )
								# create random numpy tensors
								__lowercase			       = prepare_image_inputs(self.image_processor_tester			,							equal_resolution=snake_case_			,							numpify=snake_case_    )
								for image in image_inputs:
											self.assertIsInstance(snake_case_			,							np.ndarray    )

								# Test not batched input
								__lowercase			       = image_processing(image_inputs[0]			,							return_tensors='''pt'''    ).pixel_values
								self.assertEqual(
								    encoded_images.shape			,							(
								        1,
								        self.image_processor_tester.num_channels,
								        self.image_processor_tester.size['''height'''],
								        self.image_processor_tester.size['''width'''],
								    )			,							)

								# Test batched
								__lowercase			       = image_processing(snake_case_			,							return_tensors='''pt'''    ).pixel_values
								self.assertEqual(
								    encoded_images.shape			,							(
								        self.image_processor_tester.batch_size,
								        self.image_processor_tester.num_channels,
								        self.image_processor_tester.size['''height'''],
								        self.image_processor_tester.size['''width'''],
								    )			,							)






					@is_flaky()
					def A   (					self    ) ->      Dict:







								'''simple docstring'''

								__lowercase			       = self.image_processing_class(**self.image_processor_dict    )
								# create random PyTorch tensors
								__lowercase			       = prepare_image_inputs(self.image_processor_tester			,							equal_resolution=snake_case_			,							torchify=snake_case_    )
								for image in image_inputs:
											self.assertIsInstance(snake_case_			,							torch.Tensor    )

								# Test not batched input
								__lowercase			       = image_processing(image_inputs[0]			,							return_tensors='''pt'''    ).pixel_values
								self.assertEqual(
								    encoded_images.shape			,							(
								        1,
								        self.image_processor_tester.num_channels,
								        self.image_processor_tester.size['''height'''],
								        self.image_processor_tester.size['''width'''],
								    )			,							)

								# Test batched
								__lowercase			       = image_processing(snake_case_			,							return_tensors='''pt'''    ).pixel_values
								self.assertEqual(
								    encoded_images.shape			,							(
								        self.image_processor_tester.batch_size,
								        self.image_processor_tester.num_channels,
								        self.image_processor_tester.size['''height'''],
								        self.image_processor_tester.size['''width'''],
								    )			,							)


