





'''simple docstring'''


import os
import re
import unicodedata
from shutil import copyfile
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import is_torch_available, logging


if is_torch_available():
 import torch


if TYPE_CHECKING:
 from transformers.pipelines.conversational import Conversation


lowerCAmelCase					:     Union[str, Any]												=logging.get_logger(__name__)
lowerCAmelCase					:     Tuple												={'''vocab_file''': '''spiece.model'''}

lowerCAmelCase					:     Any												={
    '''vocab_file''': {
        '''AI-Sweden/gpt-sw3-126m''': '''https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model''',
        '''AI-Sweden/gpt-sw3-350m''': '''https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model''',
        '''AI-Sweden/gpt-sw3-1.6b''': '''https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model''',
        '''AI-Sweden/gpt-sw3-6.7b''': '''https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model''',
        '''AI-Sweden/gpt-sw3-20b''': '''https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model''',
    }
}

lowerCAmelCase					:     Union[str, Any]												={
    '''AI-Sweden/gpt-sw3-126m''': 2_048,
    '''AI-Sweden/gpt-sw3-350m''': 2_048,
    '''AI-Sweden/gpt-sw3-1.6b''': 2_048,
    '''AI-Sweden/gpt-sw3-6.7b''': 2_048,
    '''AI-Sweden/gpt-sw3-20b''': 2_048,
}
class       a_   (				_lowerCAmelCase							):
     __A      =			VOCAB_FILES_NAMES
     __A      =			PRETRAINED_VOCAB_FILES_MAP
     __A      =			PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     __A      =			["input_ids", "attention_mask"]





     def __init__( self		:					Tuple	,      lowercase		:					str	,      lowercase		:					List[str]=False	,      lowercase		:					Optional[Any]=False	,      lowercase		:					Tuple=False	,      lowercase		:					str=None	,      lowercase		:					Optional[int]=None	,      lowercase		:					Optional[int]=None	,      lowercase		:					Optional[int]=None	,      lowercase		:					Optional[int] = None	,      **lowercase		:					List[str]	,      ):





        """simple docstring"""




        lowercase_			:Tuple    			= {} if sp_model_kwargs is None else sp_model_kwargs

        lowercase_			:str    			= kwargs.get("name_or_path"						)
        if name_or_path is None:
           logger.warning(
               "name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b,"
               " you are testing the model, this can safely be ignored"						)
           lowercase_			:Union[str, Any]    			= "None"

        # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing
        lowercase_			:List[str]    			= "<|endoftext|>" if eos_token is None else eos_token
        lowercase_			:Any    			= "<unk>" if unk_token is None else unk_token
        if "gpt-sw3-7b" in name_or_path:
           lowercase_			:Dict    			= unk_token if pad_token is None else pad_token
           lowercase_			:Optional[int]    			= eos_token if bos_token is None else bos_token
        else:
           lowercase_			:Any    			= "<pad>" if pad_token is None else pad_token
           lowercase_			:Union[str, Any]    			= "<s>" if bos_token is None else bos_token

        super().__init__(
            do_lower_case=__lowerCAmelCase	,      remove_space=__lowerCAmelCase	,      keep_accents=__lowerCAmelCase	,      bos_token=__lowerCAmelCase	,      eos_token=__lowerCAmelCase	,      unk_token=__lowerCAmelCase	,      pad_token=__lowerCAmelCase	,      sp_model_kwargs=self.sp_model_kwargs	,      **__lowerCAmelCase	,      )

        lowercase_			:Optional[Any]    			= do_lower_case
        lowercase_			:Any    			= remove_space
        lowercase_			:int    			= keep_accents
        lowercase_			:List[str]    			= vocab_file

        lowercase_			:int    			= spm.SentencePieceProcessor(**self.sp_model_kwargs						)
        self.sp_model.Load(__lowerCAmelCase						)

        # Used for whitespace normalization in input texts
        # fmt : off
        lowercase_			:Dict    			= {" ", " ", " ", " ", " ", "　", " ", " ", " ", " ", "￼", ""}
        # fmt : on

        # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing
        lowercase_			:int    			= re.compile(
            F'[{"".join(map(__lowerCAmelCase	,      list(range(0	,      9						)						) + list(range(11	,      32						)						) + list(range(127	,      160						)						) + [160, 173, 8_203]						)						)}]'						)





     def __getstate__( self		:					Optional[int]						):





        """simple docstring"""




        lowercase_			:Dict    			= self.__dict__.copy()
        lowercase_			:Union[str, Any]    			= None
        return state





     def __setstate__( self		:					List[str]	,      lowercase		:					Tuple						):





        """simple docstring"""




        lowercase_			:Tuple    			= d

        # for backward compatibility
        if not hasattr(self	,      "sp_model_kwargs"						):
           lowercase_			:List[Any]    			= {}

        lowercase_			:Any    			= spm.SentencePieceProcessor(**self.sp_model_kwargs						)
        self.sp_model.Load(self.vocab_file						)





     @property
     # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size
     def 							lowercase__      ( self		:					Any						):





        """simple docstring"""




        return len(self.sp_model						)





     def 							lowercase__      ( self		:					List[str]	,      lowercase		:					Optional[int]						):





        """simple docstring"""




        lowercase_			:Union[str, Any]    			= self.non_printing_characters_re.sub(""	,      __lowerCAmelCase						)

        # Normalize whitespaces
        lowercase_			:str    			= "".join([char if char not in self.whitespaces else " " for char in text]						)

        # NFC Unicode normalization
        lowercase_			:str    			= unicodedata.normalize("NFC"	,      __lowerCAmelCase						)
        return text





     def 							lowercase__      ( self		:					Tuple	,      lowercase		:					Any	,      **lowercase		:					Optional[int]						):





        """simple docstring"""




        lowercase_			:List[str]    			= self.preprocess_text(__lowerCAmelCase						)
        return self.sp_model.encode(__lowerCAmelCase	,      out_type=__lowerCAmelCase						)





     def 							lowercase__      ( self		:					Union[str, Any]	,      lowercase		:					List[str]						):





        """simple docstring"""




        return self.sp_model.PieceToId(__lowerCAmelCase						)





     def 							lowercase__      ( self		:					Optional[int]	,      lowercase		:					Optional[Any]						):





        """simple docstring"""




        return self.sp_model.IdToPiece(__lowerCAmelCase						)





     @staticmethod
     def 							lowercase__      ( lowercase		:					Dict						):





        """simple docstring"""




        return out_string





     def 							lowercase__      ( self		:					Tuple	,      lowercase		:					Any						):





        """simple docstring"""




        lowercase_			:int    			= []
        lowercase_			:Dict    			= ""
        lowercase_			:int    			= False
        for token in tokens:
           # make sure that special tokens are not decoded using sentencepiece model
           if token in self.all_special_tokens:
              # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document
              if not prev_is_special:
                 out_string += " "

              out_string += self.sp_model.decode(__lowerCAmelCase						) + token
              lowercase_			:Optional[int]    			= True
              lowercase_			:Dict    			= []
           else:
              current_sub_tokens.append(__lowerCAmelCase						)
              lowercase_			:List[Any]    			= False
        out_string += self.sp_model.decode(__lowerCAmelCase						)

        return out_string





     def 							lowercase__      ( self		:					Tuple						):





        """simple docstring"""




        lowercase_			:Optional[Any]    			= {self.convert_ids_to_tokens(__lowerCAmelCase						): i for i in range(self.vocab_size						)}
        vocab.update(self.added_tokens_encoder						)
        return vocab





     def 							lowercase__      ( self		:					Any	,      lowercase		:					Any	,      lowercase		:					Dict = None						):





        """simple docstring"""




        if not os.path.isdir(__lowerCAmelCase						):
           logger.error(F'Vocabulary path ({save_directory}) should be a directory'						)
           return
        lowercase_			:Dict    			= os.path.join(
            __lowerCAmelCase	,      (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]						)

        if os.path.abspath(self.vocab_file						) != os.path.abspath(__lowerCAmelCase						) and os.path.isfile(self.vocab_file						):
           copyfile(self.vocab_file	,      __lowerCAmelCase						)
        elif not os.path.isfile(self.vocab_file						):
           with open(__lowerCAmelCase	,      "wb"						) as fi:
              lowercase_			:Dict    			= self.sp_model.serialized_model_proto()
              fi.write(__lowerCAmelCase						)

        return (out_vocab_file,)





     def 							lowercase__      ( self		:					Tuple	,      lowercase		:					Optional[int]	,      lowercase		:					int = False						):





        """simple docstring"""




        if isinstance(__lowerCAmelCase	,      __lowerCAmelCase						):
           lowercase_			:List[Any]    			= self.preprocess_text(__lowerCAmelCase						)
           lowercase_			:Tuple    			= self.sp_model.encode(__lowerCAmelCase						)
        else:
           lowercase_			:List[Any]    			= [self.preprocess_text(__lowerCAmelCase						) for t in text]
           lowercase_			:int    			= self.sp_model.encode(__lowerCAmelCase						)

        if return_tensors is True or return_tensors == "pt":
           lowercase_			:Union[str, Any]    			= torch.tensor(__lowerCAmelCase						)

        return token_ids





     def 							lowercase__      ( self		:					Dict	,      lowercase		:					List[Any]						):





        """simple docstring"""




        return self.sp_model.decode(__lowerCAmelCase						)







     def 							lowercase__      ( self		:					int	,      lowercase		:					str						):





        """simple docstring"""




        lowercase_			:List[str]    			= [F'User: {text}' if is_user else F'Bot: {text}' for is_user, text in conversation.iter_texts()]
        lowercase_			:List[str]    			= (
            F'{self.eos_token}{self.bos_token}' + F'{self.bos_token}'.join(__lowerCAmelCase						) + F'{self.bos_token}Bot:'
        )
        return self.encode(text=__lowerCAmelCase						)









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

			'''simple docstring'''







			def __init__(    self       ,  __lowerCAmelCase       ,  __lowerCAmelCase=1_3       ,  __lowerCAmelCase=7       ,  __lowerCAmelCase=True       ,  __lowerCAmelCase=True       ,  __lowerCAmelCase=True       ,  __lowerCAmelCase=True       ,  __lowerCAmelCase=9_9       ,  __lowerCAmelCase=6_4       ,  __lowerCAmelCase=3_2       ,  __lowerCAmelCase=5       ,  __lowerCAmelCase=4       ,  __lowerCAmelCase=3_7       ,  __lowerCAmelCase="gelu"       ,  __lowerCAmelCase=0.1       ,  __lowerCAmelCase=0.1       ,  __lowerCAmelCase=5_1_2       ,  __lowerCAmelCase=1_6       ,  __lowerCAmelCase=2       ,  __lowerCAmelCase=0.02       ,  __lowerCAmelCase=3       ,  __lowerCAmelCase=4       ,  __lowerCAmelCase=None       ,  ):



				'''simple docstring'''







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





			def 		__lowerCamelCase				(    self							):



				'''simple docstring'''







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

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

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

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

				lowerCamelCase__								=		self.get_config()

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





			def 		__lowerCamelCase				(    self							):



				'''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=__lowerCAmelCase       ,  initializer_range=self.initializer_range       ,  )





			def 		__lowerCamelCase				(    self       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase							):



				'''simple docstring'''







				lowerCamelCase__								=		MegatronBertModel(config=__lowerCAmelCase							)
				model.to(__lowerCAmelCase							)
				model.eval()
				lowerCamelCase__								=		model(__lowerCAmelCase       ,  attention_mask=__lowerCAmelCase       ,  token_type_ids=__lowerCAmelCase							)
				lowerCamelCase__								=		model(__lowerCAmelCase       ,  token_type_ids=__lowerCAmelCase							)
				lowerCamelCase__								=		model(__lowerCAmelCase							)

				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 		__lowerCamelCase				(    self       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase							):



				'''simple docstring'''







				lowerCamelCase__								=		MegatronBertForMaskedLM(config=__lowerCAmelCase							)
				model.to(__lowerCAmelCase							)
				model.eval()
				lowerCamelCase__								=		model(__lowerCAmelCase       ,  attention_mask=__lowerCAmelCase       ,  token_type_ids=__lowerCAmelCase       ,  labels=__lowerCAmelCase							)
				self.parent.assertEqual(result.logits.shape       ,  (self.batch_size, self.seq_length, self.vocab_size)							)





			def 		__lowerCamelCase				(    self       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase							):



				'''simple docstring'''







				lowerCamelCase__								=		MegatronBertForCausalLM(config=__lowerCAmelCase							)
				model.to(__lowerCAmelCase							)
				model.eval()
				lowerCamelCase__								=		model(__lowerCAmelCase       ,  attention_mask=__lowerCAmelCase       ,  token_type_ids=__lowerCAmelCase       ,  labels=__lowerCAmelCase							)
				self.parent.assertEqual(result.logits.shape       ,  (self.batch_size, self.seq_length, self.vocab_size)							)





			def 		__lowerCamelCase				(    self       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase							):



				'''simple docstring'''







				lowerCamelCase__								=		MegatronBertForNextSentencePrediction(config=__lowerCAmelCase							)
				model.to(__lowerCAmelCase							)
				model.eval()
				lowerCamelCase__								=		model(
				    __lowerCAmelCase       ,  attention_mask=__lowerCAmelCase       ,  token_type_ids=__lowerCAmelCase       ,  labels=__lowerCAmelCase       ,  )
				self.parent.assertEqual(result.logits.shape       ,  (self.batch_size, 2)							)





			def 		__lowerCamelCase				(    self       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase							):



				'''simple docstring'''







				lowerCamelCase__								=		MegatronBertForPreTraining(config=__lowerCAmelCase							)
				model.to(__lowerCAmelCase							)
				model.eval()
				lowerCamelCase__								=		model(
				    __lowerCAmelCase       ,  attention_mask=__lowerCAmelCase       ,  token_type_ids=__lowerCAmelCase       ,  labels=__lowerCAmelCase       ,  next_sentence_label=__lowerCAmelCase       ,  )
				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 		__lowerCamelCase				(    self       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase							):



				'''simple docstring'''







				lowerCamelCase__								=		MegatronBertForQuestionAnswering(config=__lowerCAmelCase							)
				model.to(__lowerCAmelCase							)
				model.eval()
				lowerCamelCase__								=		model(
				    __lowerCAmelCase       ,  attention_mask=__lowerCAmelCase       ,  token_type_ids=__lowerCAmelCase       ,  start_positions=__lowerCAmelCase       ,  end_positions=__lowerCAmelCase       ,  )
				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 		__lowerCamelCase				(    self       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase							):



				'''simple docstring'''







				lowerCamelCase__								=		self.num_labels
				lowerCamelCase__								=		MegatronBertForSequenceClassification(__lowerCAmelCase							)
				model.to(__lowerCAmelCase							)
				model.eval()
				lowerCamelCase__								=		model(__lowerCAmelCase       ,  attention_mask=__lowerCAmelCase       ,  token_type_ids=__lowerCAmelCase       ,  labels=__lowerCAmelCase							)
				self.parent.assertEqual(result.logits.shape       ,  (self.batch_size, self.num_labels)							)





			def 		__lowerCamelCase				(    self       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase							):



				'''simple docstring'''







				lowerCamelCase__								=		self.num_labels
				lowerCamelCase__								=		MegatronBertForTokenClassification(config=__lowerCAmelCase							)
				model.to(__lowerCAmelCase							)
				model.eval()
				lowerCamelCase__								=		model(__lowerCAmelCase       ,  attention_mask=__lowerCAmelCase       ,  token_type_ids=__lowerCAmelCase       ,  labels=__lowerCAmelCase							)
				self.parent.assertEqual(result.logits.shape       ,  (self.batch_size, self.seq_length, self.num_labels)							)





			def 		__lowerCamelCase				(    self       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase							):



				'''simple docstring'''







				lowerCamelCase__								=		self.num_choices
				lowerCamelCase__								=		MegatronBertForMultipleChoice(config=__lowerCAmelCase							)
				model.to(__lowerCAmelCase							)
				model.eval()
				lowerCamelCase__								=		input_ids.unsqueeze(1							).expand(-1       ,  self.num_choices       ,  -1							).contiguous()
				lowerCamelCase__								=		token_type_ids.unsqueeze(1							).expand(-1       ,  self.num_choices       ,  -1							).contiguous()
				lowerCamelCase__								=		input_mask.unsqueeze(1							).expand(-1       ,  self.num_choices       ,  -1							).contiguous()
				lowerCamelCase__								=		model(
				    __lowerCAmelCase       ,  attention_mask=__lowerCAmelCase       ,  token_type_ids=__lowerCAmelCase       ,  labels=__lowerCAmelCase       ,  )
				self.parent.assertEqual(result.logits.shape       ,  (self.batch_size, self.num_choices)							)





			def 		__lowerCamelCase				(    self							):



				'''simple docstring'''







				lowerCamelCase__								=		self.prepare_config_and_inputs()
				(
				    (
				    lowerCamelCase__
				)				,	(
				    lowerCamelCase__
				)				,	(
				    lowerCamelCase__
				)				,	(
				    lowerCamelCase__
				)				,	(
				    lowerCamelCase__
				)				,	(
				    lowerCamelCase__
				)				,	(
				    lowerCamelCase__
				)				,	
				)								=		config_and_inputs
				lowerCamelCase__								=		{'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
				return config, inputs_dict






@require_torch
class 					__A    (    lowerCAmelCase			,				lowerCAmelCase			,				unittest.TestCase ):

			'''simple docstring'''







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





			def 		__lowerCamelCase				(    self       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase=False							):



				'''simple docstring'''







				lowerCamelCase__								=		super()._prepare_for_class(__lowerCAmelCase       ,  __lowerCAmelCase       ,  return_labels=__lowerCAmelCase							)

				if return_labels:
					if model_class in get_values(__lowerCAmelCase							):
						lowerCamelCase__								=		torch.zeros(
						    (self.model_tester.batch_size, self.model_tester.seq_length)       ,  dtype=torch.long       ,  device=__lowerCAmelCase							)
						lowerCamelCase__								=		torch.zeros(
						    self.model_tester.batch_size       ,  dtype=torch.long       ,  device=__lowerCAmelCase							)
				return inputs_dict





			def 		__lowerCamelCase				(    self							):



				'''simple docstring'''







				lowerCamelCase__								=		MegatronBertModelTester(self							)
				lowerCamelCase__								=		ConfigTester(self       ,  config_class=__lowerCAmelCase       ,  hidden_size=3_7							)





			def 		__lowerCamelCase				(    self							):



				'''simple docstring'''







				self.config_tester.run_common_tests()





			def 		__lowerCamelCase				(    self							):



				'''simple docstring'''







				lowerCamelCase__								=		self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_megatron_bert_model(*__lowerCAmelCase							)





			def 		__lowerCamelCase				(    self							):



				'''simple docstring'''







				lowerCamelCase__								=		self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_megatron_bert_for_masked_lm(*__lowerCAmelCase							)





			def 		__lowerCamelCase				(    self							):



				'''simple docstring'''







				lowerCamelCase__								=		self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_megatron_bert_for_multiple_choice(*__lowerCAmelCase							)





			def 		__lowerCamelCase				(    self							):



				'''simple docstring'''







				lowerCamelCase__								=		self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_megatron_bert_for_next_sequence_prediction(*__lowerCAmelCase							)





			def 		__lowerCamelCase				(    self							):



				'''simple docstring'''







				lowerCamelCase__								=		self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_megatron_bert_for_pretraining(*__lowerCAmelCase							)





			def 		__lowerCamelCase				(    self							):



				'''simple docstring'''







				lowerCamelCase__								=		self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_megatron_bert_for_question_answering(*__lowerCAmelCase							)





			def 		__lowerCamelCase				(    self							):



				'''simple docstring'''







				lowerCamelCase__								=		self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_megatron_bert_for_sequence_classification(*__lowerCAmelCase							)





			def 		__lowerCamelCase				(    self							):



				'''simple docstring'''







				lowerCamelCase__								=		self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_megatron_bert_for_token_classification(*__lowerCAmelCase							)





def lowerCAmelCase__(__snake_case							)				->      List[str]:







	'''simple docstring'''







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


_a 						=      1e-4






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

			'''simple docstring'''







			@slow
			@unittest.skip('''Model is not available.'''							)
			def 		__lowerCamelCase				(    self							):



				'''simple docstring'''







				lowerCamelCase__								=		'''nvidia/megatron-bert-uncased-345m'''
				if "MYDIR" in os.environ:
					lowerCamelCase__								=		os.path.join(os.environ['''MYDIR''']       ,  __lowerCAmelCase							)
				lowerCamelCase__								=		MegatronBertModel.from_pretrained(__lowerCAmelCase							)
				model.to(__lowerCAmelCase							)
				model.half()
				lowerCamelCase__								=		_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():
					lowerCamelCase__								=		model(__lowerCAmelCase							)[0]
				lowerCamelCase__								=		torch.Size((1, 9, 1_0_2_4)							)
				self.assertEqual(output.shape       ,  __lowerCAmelCase							)

				lowerCamelCase__								=		[-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							):
						lowerCamelCase__								=		output[0, ii, jj]
						lowerCamelCase__								=		expected[3 * ii + jj]
						lowerCamelCase__								=		'''ii={} jj={} a={} b={}'''.format(__lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase							)
						self.assertTrue(math.isclose(__lowerCAmelCase       ,  __lowerCAmelCase       ,  rel_tol=__lowerCAmelCase       ,  abs_tol=__lowerCAmelCase							)       ,  msg=__lowerCAmelCase							)



