codingutf8 2022 the huggingface inc team licensed under the apache license version 2 0 the license you may not use this file except in compliance with the license you may obtain a copy of the license at http www apache orglicenseslicense2 0 unless required by applicable law or agreed to in writing software distributed under the license is distributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and limitations under the license testing suite for the pytorch rocbert model import unittest from transformers import rocbertconfig istorchavailable from transformers models auto import getvalues from transformers testingutils import requiretorch slow torchdevice from testconfigurationcommon import configtester from testmodelingcommon import modeltestermixin floatstensor idstensor randomattentionmask from testpipelinemixin import pipelinetestermixin if istorchavailable import torch from transformers import modelforpretrainingmapping rocbertforcausallm rocbertformaskedlm rocbertformultiplechoice rocbertforpretraining rocbertforquestionanswering rocbertforsequenceclassification rocbertfortokenclassification rocbertmodel from transformers models rocbert modelingrocbert import rocbertpretrainedmodelarchivelist class rocbertmodeltester def init self parent batchsize13 seqlength7 istrainingtrue useinputmasktrue usetokentypeidstrue uselabelstrue vocabsize99 pronunciationvocabsize99 shapevocabsize99 pronunciationembeddim32 shapeembeddim32 hiddensize32 numhiddenlayers2 numattentionheads4 intermediatesize37 hiddenactgelu hiddendropoutprob0 1 attentionprobsdropoutprob0 1 maxpositionembeddings512 typevocabsize16 typesequencelabelsize2 initializerrange0 02 numlabels3 numchoices4 scopenone self parent parent self batchsize batchsize self seqlength seqlength self istraining istraining self useinputmask useinputmask self usetokentypeids usetokentypeids self uselabels uselabels self vocabsize vocabsize self pronunciationvocabsize pronunciationvocabsize self shapevocabsize shapevocabsize self pronunciationembeddim pronunciationembeddim self shapeembeddim shapeembeddim self hiddensize hiddensize self numhiddenlayers numhiddenlayers self numattentionheads numattentionheads self intermediatesize intermediatesize self hiddenact hiddenact self hiddendropoutprob hiddendropoutprob self attentionprobsdropoutprob attentionprobsdropoutprob self maxpositionembeddings maxpositionembeddings self typevocabsize typevocabsize self typesequencelabelsize typesequencelabelsize self initializerrange initializerrange self numlabels numlabels self numchoices numchoices self scope scope def prepareconfigandinputsself inputids idstensorself batchsize self seqlength self vocabsize inputshapeids idstensorself batchsize self seqlength self shapevocabsize inputpronunciationids idstensorself batchsize self seqlength self pronunciationvocabsize inputmask none if self useinputmask inputmask randomattentionmaskself batchsize self seqlength tokentypeids none if self usetokentypeids tokentypeids idstensorself batchsize self seqlength self typevocabsize sequencelabels none tokenlabels none choicelabels none if self uselabels sequencelabels idstensorself batchsize self typesequencelabelsize tokenlabels idstensorself batchsize self seqlength self numlabels choicelabels idstensorself batchsize self numchoices config self getconfig return config inputids inputshapeids inputpronunciationids tokentypeids inputmask sequencelabels tokenlabels choicelabels def getconfigself return rocbertconfig vocabsizeself vocabsize shapevocabsizeself shapevocabsize pronunciationvocabsizeself pronunciationvocabsize shapeembeddimself shapeembeddim pronunciationembeddimself pronunciationembeddim hiddensizeself hiddensize numhiddenlayersself numhiddenlayers numattentionheadsself numattentionheads intermediatesizeself intermediatesize hiddenactself hiddenact hiddendropoutprobself hiddendropoutprob attentionprobsdropoutprobself attentionprobsdropoutprob maxpositionembeddingsself maxpositionembeddings typevocabsizeself typevocabsize isdecoderfalse initializerrangeself initializerrange def prepareconfigandinputsfordecoderself config inputids inputshapeids inputpronunciationids tokentypeids inputmask sequencelabels tokenlabels choicelabels self prepareconfigandinputs config isdecoder true encoderhiddenstates floatstensorself batchsize self seqlength self hiddensize encoderattentionmask idstensorself batchsize self seqlength vocabsize2 return config inputids inputshapeids inputpronunciationids tokentypeids inputmask sequencelabels tokenlabels choicelabels encoderhiddenstates encoderattentionmask def createandcheckmodel self config inputids inputshapeids inputpronunciationids tokentypeids inputmask sequencelabels tokenlabels choicelabels model rocbertmodelconfigconfig model totorchdevice model eval result model inputids inputshapeidsinputshapeids inputpronunciationidsinputpronunciationids attentionmaskinputmask tokentypeidstokentypeids result model inputids inputshapeidsinputshapeids inputpronunciationidsinputpronunciationids tokentypeidstokentypeids result modelinputids inputshapeidsinputshapeids inputpronunciationidsinputpronunciationids self parent assertequalresult lasthiddenstate shape self batchsize self seqlength self hiddensize def createandcheckmodelasdecoder self config inputids inputshapeids inputpronunciationids tokentypeids inputmask sequencelabels tokenlabels choicelabels encoderhiddenstates encoderattentionmask config addcrossattention true model rocbertmodelconfig model totorchdevice model eval result model inputids inputshapeidsinputshapeids inputpronunciationidsinputpronunciationids attentionmaskinputmask tokentypeidstokentypeids encoderhiddenstatesencoderhiddenstates encoderattentionmaskencoderattentionmask result model inputids inputshapeidsinputshapeids inputpronunciationidsinputpronunciationids attentionmaskinputmask tokentypeidstokentypeids encoderhiddenstatesencoderhiddenstates result model inputids inputshapeidsinputshapeids inputpronunciationidsinputpronunciationids attentionmaskinputmask tokentypeidstokentypeids self parent assertequalresult lasthiddenstate shape self batchsize self seqlength self hiddensize def createandcheckforcausallm self config inputids inputshapeids inputpronunciationids tokentypeids inputmask sequencelabels tokenlabels choicelabels encoderhiddenstates encoderattentionmask model rocbertforcausallmconfigconfig model totorchdevice model eval result model inputids inputshapeidsinputshapeids inputpronunciationidsinputpronunciationids attentionmaskinputmask tokentypeidstokentypeids labelstokenlabels self parent assertequalresult logits shape self batchsize self seqlength self vocabsize def createandcheckformaskedlm self config inputids inputshapeids inputpronunciationids tokentypeids inputmask sequencelabels tokenlabels choicelabels model rocbertformaskedlmconfigconfig model totorchdevice model eval result model inputids inputshapeidsinputshapeids inputpronunciationidsinputpronunciationids attentionmaskinputmask tokentypeidstokentypeids labelstokenlabels self parent assertequalresult logits shape self batchsize self seqlength self vocabsize def createandcheckdecodermodelpastlargeinputs self config inputids inputshapeids inputpronunciationids tokentypeids inputmask sequencelabels tokenlabels choicelabels encoderhiddenstates encoderattentionmask config isdecoder true config addcrossattention true model rocbertforcausallmconfigconfig model totorchdevice model eval first forward pass outputs model inputids inputshapeidsinputshapeids inputpronunciationidsinputpronunciationids attentionmaskinputmask encoderhiddenstatesencoderhiddenstates encoderattentionmaskencoderattentionmask usecachetrue pastkeyvalues outputs pastkeyvalues create hypothetical multiple next token and extent to nextinputids nexttokens idstensorself batchsize 3 config vocabsize nextshapetokens idstensorself batchsize 3 config shapevocabsize nextpronunciationtokens idstensorself batchsize 3 config pronunciationvocabsize nextmask idstensorself batchsize 3 vocabsize2 append to next inputids and nextinputids torch catinputids nexttokens dim1 nextinputshapeids torch catinputshapeids nextshapetokens dim1 nextinputpronunciationids torch catinputpronunciationids nextpronunciationtokens dim1 nextattentionmask torch catinputmask nextmask dim1 outputfromnopast model nextinputids inputshapeidsnextinputshapeids inputpronunciationidsnextinputpronunciationids attentionmasknextattentionmask encoderhiddenstatesencoderhiddenstates encoderattentionmaskencoderattentionmask outputhiddenstatestrue hiddenstates0 outputfrompast model nexttokens inputshapeidsnextshapetokens inputpronunciationidsnextpronunciationtokens attentionmasknextattentionmask encoderhiddenstatesencoderhiddenstates encoderattentionmaskencoderattentionmask pastkeyvaluespastkeyvalues outputhiddenstatestrue hiddenstates0 select random slice randomsliceidx idstensor1 outputfrompast shape1 item outputfromnopastslice outputfromnopast 3 randomsliceidx detach outputfrompastslice outputfrompast randomsliceidx detach self parent asserttrueoutputfrompastslice shape1 nexttokens shape1 test that outputs are equal for slice self parent asserttruetorch allcloseoutputfrompastslice outputfromnopastslice atol1e3 def createandcheckforquestionanswering self config inputids inputshapeids inputpronunciationids tokentypeids inputmask sequencelabels tokenlabels choicelabels model rocbertforquestionansweringconfigconfig model totorchdevice model eval result model inputids inputshapeidsinputshapeids inputpronunciationidsinputpronunciationids attentionmaskinputmask tokentypeidstokentypeids startpositionssequencelabels endpositionssequencelabels self parent assertequalresult startlogits shape self batchsize self seqlength self parent assertequalresult endlogits shape self batchsize self seqlength def createandcheckforsequenceclassification self config inputids inputshapeids inputpronunciationids tokentypeids inputmask sequencelabels tokenlabels choicelabels config numlabels self numlabels model rocbertforsequenceclassificationconfig model totorchdevice model eval result model inputids inputshapeidsinputshapeids inputpronunciationidsinputpronunciationids attentionmaskinputmask tokentypeidstokentypeids labelssequencelabels self parent assertequalresult logits shape self batchsize self numlabels def createandcheckfortokenclassification self config inputids inputshapeids inputpronunciationids tokentypeids inputmask sequencelabels tokenlabels choicelabels config numlabels self numlabels model rocbertfortokenclassificationconfigconfig model totorchdevice model eval result model inputids inputshapeidsinputshapeids inputpronunciationidsinputpronunciationids attentionmaskinputmask tokentypeidstokentypeids labelstokenlabels self parent assertequalresult logits shape self batchsize self seqlength self numlabels def createandcheckformultiplechoice self config inputids inputshapeids inputpronunciationids tokentypeids inputmask sequencelabels tokenlabels choicelabels config numchoices self numchoices model rocbertformultiplechoiceconfigconfig model totorchdevice model eval multiplechoiceinputsids inputids unsqueeze1 expand1 self numchoices 1 contiguous multiplechoiceinputsshapeids inputshapeids unsqueeze1 expand1 self numchoices 1 contiguous multiplechoiceinputspronunciationids inputpronunciationids unsqueeze1 expand1 self numchoices 1 contiguous multiplechoicetokentypeids tokentypeids unsqueeze1 expand1 self numchoices 1 contiguous multiplechoiceinputmask inputmask unsqueeze1 expand1 self numchoices 1 contiguous result model multiplechoiceinputsids inputshapeidsmultiplechoiceinputsshapeids inputpronunciationidsmultiplechoiceinputspronunciationids attentionmaskmultiplechoiceinputmask tokentypeidsmultiplechoicetokentypeids labelschoicelabels self parent assertequalresult logits shape self batchsize self numchoices def prepareconfigandinputsforcommonself configandinputs self prepareconfigandinputs config inputids inputshapeids inputpronunciationids tokentypeids inputmask sequencelabels tokenlabels choicelabels configandinputs inputsdict inputids inputids inputshapeids inputshapeids inputpronunciationids inputpronunciationids tokentypeids tokentypeids attentionmask inputmask return config inputsdict def createandcheckforpretraining self config inputids inputshapeids inputpronunciationids tokentypeids inputmask sequencelabels tokenlabels choicelabels model rocbertforpretrainingconfigconfig model totorchdevice model eval result model inputids inputshapeids inputpronunciationids attentionmaskinputmask tokentypeidstokentypeids attackinputidsinputids attackinputshapeidsinputshapeids attackinputpronunciationidsinputpronunciationids attackattentionmaskinputmask attacktokentypeidstokentypeids labelsinputidstokenlabels labelsinputshapeidsinputshapeids labelsinputpronunciationidsinputpronunciationids labelsattentionmaskinputmask labelstokentypeidstokentypeids self parent assertequalresult logits shape self batchsize self seqlength self vocabsize requiretorch class rocbertmodeltestmodeltestermixin pipelinetestermixin unittest testcase allmodelclasses rocbertmodel rocbertformaskedlm rocbertforcausallm rocbertformultiplechoice rocbertforquestionanswering rocbertforsequenceclassification rocbertfortokenclassification rocbertforpretraining if istorchavailable else allgenerativemodelclasses rocbertforcausallm if istorchavailable else pipelinemodelmapping featureextraction rocbertmodel fillmask rocbertformaskedlm questionanswering rocbertforquestionanswering textclassification rocbertforsequenceclassification textgeneration rocbertforcausallm tokenclassification rocbertfortokenclassification zeroshot rocbertforsequenceclassification if istorchavailable else todo fix the failed tests when this model gets more usage def ispipelinetesttoskip self pipelinetestcassename configclass modelarchitecture tokenizername processorname if pipelinetestcassename in fillmaskpipelinetests featureextractionpipelinetests textclassificationpipelinetests tokenclassificationpipelinetests get error indexerror index out of range in self wordshapefile and wordpronunciationfile should be shrunk during tiny model creation otherwise indexerror could occur in some embedding layers skip for now until this model has more usage return true return false special case for forpretraining model def prepareforclassself inputsdict modelclass returnlabelsfalse inputsdict super prepareforclassinputsdict modelclass returnlabelsreturnlabels if returnlabels if modelclass in getvaluesmodelforpretrainingmapping inputsdictlabelsinputids torch zeros self modeltester batchsize self modeltester seqlength dtypetorch long devicetorchdevice inputsdictlabelsinputshapeids torch zeros self modeltester batchsize self modeltester seqlength dtypetorch long devicetorchdevice inputsdictlabelsinputpronunciationids torch zeros self modeltester batchsize self modeltester seqlength dtypetorch long devicetorchdevice inputsdictattackinputids torch zeros self modeltester batchsize self modeltester seqlength dtypetorch long devicetorchdevice inputsdictattackinputshapeids torch zeros self modeltester batchsize self modeltester seqlength dtypetorch long devicetorchdevice inputsdictattackinputpronunciationids torch zeros self modeltester batchsize self modeltester seqlength dtypetorch long devicetorchdevice return inputsdict def setupself self modeltester rocbertmodeltesterself self configtester configtesterself configclassrocbertconfig hiddensize37 def testconfigself self configtester runcommontests def testmodelself configandinputs self modeltester prepareconfigandinputs self modeltester createandcheckmodelconfigandinputs def testmodelvariousembeddingsself configandinputs self modeltester prepareconfigandinputs for type in absolute relativekey relativekeyquery configandinputs0 positionembeddingtype type self modeltester createandcheckmodelconfigandinputs def testformaskedlmself configandinputs self modeltester prepareconfigandinputs self modeltester createandcheckformaskedlmconfigandinputs def testformultiplechoiceself configandinputs self modeltester prepareconfigandinputs self modeltester createandcheckformultiplechoiceconfigandinputs def testdecodermodelpastwithlargeinputsself configandinputs self modeltester prepareconfigandinputsfordecoder self modeltester createandcheckdecodermodelpastlargeinputsconfigandinputs def testdecodermodelpastwithlargeinputsrelativeposembself configandinputs self modeltester prepareconfigandinputsfordecoder configandinputs0 positionembeddingtype relativekey self modeltester createandcheckdecodermodelpastlargeinputsconfigandinputs def testforquestionansweringself configandinputs self modeltester prepareconfigandinputs self modeltester createandcheckforquestionansweringconfigandinputs def testforsequenceclassificationself configandinputs self modeltester prepareconfigandinputs self modeltester createandcheckforsequenceclassificationconfigandinputs def testfortokenclassificationself configandinputs self modeltester prepareconfigandinputs self modeltester createandcheckfortokenclassificationconfigandinputs def testforpretrainingself configandinputs self modeltester prepareconfigandinputs self modeltester createandcheckforpretrainingconfigandinputs def testmodelasdecoderself configandinputs self modeltester prepareconfigandinputsfordecoder self modeltester createandcheckmodelasdecoderconfigandinputs def testmodelasdecoderwithdefaultinputmaskself this regression test was failing with pytorch 1 3 config inputids inputshapeids inputpronunciationids tokentypeids inputmask sequencelabels tokenlabels choicelabels encoderhiddenstates encoderattentionmask self modeltester prepareconfigandinputsfordecoder inputmask none self modeltester createandcheckmodelasdecoder config inputids inputshapeids inputpronunciationids tokentypeids inputmask sequencelabels tokenlabels choicelabels encoderhiddenstates encoderattentionmask slow def testmodelfrompretrainedself for modelname in rocbertpretrainedmodelarchivelist 1 model rocbertmodel frompretrainedmodelname self assertisnotnonemodel requiretorch class rocbertmodelintegrationtestunittest testcase slow def testinferencemaskedlmself model rocbertformaskedlm frompretrainedweiweishirocbertbasezh inputtext cls b a mask sep is the adversarial text of cls mask sep means paris is the mask of france in english inputids torch tensor101 144 143 7027 5143 103 1744 4638 7674 6963 102 inputshapeids torch tensor2 20324 23690 8740 706 1 10900 23343 20205 5850 2 inputpronunciationids torch tensor2 718 397 52 61 1 168 273 180 243 2 output modelinputids inputshapeids inputpronunciationids outputids torch argmaxoutput logits dim2 convert to tokens is cls sep expectedoutput torch tensor101 2349 115 7944 3221 3791 1744 4638 7674 6963 102 assert torch allcloseoutputids expectedoutput coding utf 8 2022 the huggingface inc team licensed under the apache license version 2 0 the license you may not use this file except in compliance with the license you may obtain a copy of the license at http www apache org licenses license 2 0 unless required by applicable law or agreed to in writing software distributed under the license is distributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and limitations under the license testing suite for the pytorch rocbert model first forward pass create hypothetical multiple next token and extent to next_input_ids append to next input_ids and select random slice test that outputs are equal for slice todo fix the failed tests when this model gets more usage get error indexerror index out of range in self word_shape_file and word_pronunciation_file should be shrunk during tiny model creation otherwise indexerror could occur in some embedding layers skip for now until this model has more usage special case for forpretraining model this regression test was failing with pytorch 1 3 input_text cls b a 里 系 mask 国 的 首 都 sep is the adversarial text of cls 巴 黎 是 mask 国 的 首 都 sep means paris is the mask of france in english convert to tokens is cls 巴 黎 是 法 国 的 首 都 sep
import unittest

from transformers import RoCBertConfig, is_torch_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device

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


if is_torch_available():
    import torch

    from transformers import (
        MODEL_FOR_PRETRAINING_MAPPING,
        RoCBertForCausalLM,
        RoCBertForMaskedLM,
        RoCBertForMultipleChoice,
        RoCBertForPreTraining,
        RoCBertForQuestionAnswering,
        RoCBertForSequenceClassification,
        RoCBertForTokenClassification,
        RoCBertModel,
    )
    from transformers.models.roc_bert.modeling_roc_bert import ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST


class RoCBertModelTester:
    def __init__(
        self,
        parent,
        batch_size=13,
        seq_length=7,
        is_training=True,
        use_input_mask=True,
        use_token_type_ids=True,
        use_labels=True,
        vocab_size=99,
        pronunciation_vocab_size=99,
        shape_vocab_size=99,
        pronunciation_embed_dim=32,
        shape_embed_dim=32,
        hidden_size=32,
        num_hidden_layers=2,
        num_attention_heads=4,
        intermediate_size=37,
        hidden_act="gelu",
        hidden_dropout_prob=0.1,
        attention_probs_dropout_prob=0.1,
        max_position_embeddings=512,
        type_vocab_size=16,
        type_sequence_label_size=2,
        initializer_range=0.02,
        num_labels=3,
        num_choices=4,
        scope=None,
    ):
        self.parent = parent
        self.batch_size = batch_size
        self.seq_length = seq_length
        self.is_training = is_training
        self.use_input_mask = use_input_mask
        self.use_token_type_ids = use_token_type_ids
        self.use_labels = use_labels
        self.vocab_size = vocab_size
        self.pronunciation_vocab_size = pronunciation_vocab_size
        self.shape_vocab_size = shape_vocab_size
        self.pronunciation_embed_dim = pronunciation_embed_dim
        self.shape_embed_dim = shape_embed_dim
        self.hidden_size = hidden_size
        self.num_hidden_layers = num_hidden_layers
        self.num_attention_heads = num_attention_heads
        self.intermediate_size = intermediate_size
        self.hidden_act = hidden_act
        self.hidden_dropout_prob = hidden_dropout_prob
        self.attention_probs_dropout_prob = attention_probs_dropout_prob
        self.max_position_embeddings = max_position_embeddings
        self.type_vocab_size = type_vocab_size
        self.type_sequence_label_size = type_sequence_label_size
        self.initializer_range = initializer_range
        self.num_labels = num_labels
        self.num_choices = num_choices
        self.scope = scope

    def prepare_config_and_inputs(self):
        input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
        input_shape_ids = ids_tensor([self.batch_size, self.seq_length], self.shape_vocab_size)
        input_pronunciation_ids = ids_tensor([self.batch_size, self.seq_length], self.pronunciation_vocab_size)

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

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

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

        config = self.get_config()

        return (
            config,
            input_ids,
            input_shape_ids,
            input_pronunciation_ids,
            token_type_ids,
            input_mask,
            sequence_labels,
            token_labels,
            choice_labels,
        )

    def get_config(self):
        return RoCBertConfig(
            vocab_size=self.vocab_size,
            shape_vocab_size=self.shape_vocab_size,
            pronunciation_vocab_size=self.pronunciation_vocab_size,
            shape_embed_dim=self.shape_embed_dim,
            pronunciation_embed_dim=self.pronunciation_embed_dim,
            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,
            type_vocab_size=self.type_vocab_size,
            is_decoder=False,
            initializer_range=self.initializer_range,
        )

    def prepare_config_and_inputs_for_decoder(self):
        (
            config,
            input_ids,
            input_shape_ids,
            input_pronunciation_ids,
            token_type_ids,
            input_mask,
            sequence_labels,
            token_labels,
            choice_labels,
        ) = self.prepare_config_and_inputs()

        config.is_decoder = True
        encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size])
        encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2)

        return (
            config,
            input_ids,
            input_shape_ids,
            input_pronunciation_ids,
            token_type_ids,
            input_mask,
            sequence_labels,
            token_labels,
            choice_labels,
            encoder_hidden_states,
            encoder_attention_mask,
        )

    def create_and_check_model(
        self,
        config,
        input_ids,
        input_shape_ids,
        input_pronunciation_ids,
        token_type_ids,
        input_mask,
        sequence_labels,
        token_labels,
        choice_labels,
    ):
        model = RoCBertModel(config=config)
        model.to(torch_device)
        model.eval()
        result = model(
            input_ids,
            input_shape_ids=input_shape_ids,
            input_pronunciation_ids=input_pronunciation_ids,
            attention_mask=input_mask,
            token_type_ids=token_type_ids,
        )
        result = model(
            input_ids,
            input_shape_ids=input_shape_ids,
            input_pronunciation_ids=input_pronunciation_ids,
            token_type_ids=token_type_ids,
        )
        result = model(input_ids, input_shape_ids=input_shape_ids, input_pronunciation_ids=input_pronunciation_ids)
        self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))

    def create_and_check_model_as_decoder(
        self,
        config,
        input_ids,
        input_shape_ids,
        input_pronunciation_ids,
        token_type_ids,
        input_mask,
        sequence_labels,
        token_labels,
        choice_labels,
        encoder_hidden_states,
        encoder_attention_mask,
    ):
        config.add_cross_attention = True
        model = RoCBertModel(config)
        model.to(torch_device)
        model.eval()
        result = model(
            input_ids,
            input_shape_ids=input_shape_ids,
            input_pronunciation_ids=input_pronunciation_ids,
            attention_mask=input_mask,
            token_type_ids=token_type_ids,
            encoder_hidden_states=encoder_hidden_states,
            encoder_attention_mask=encoder_attention_mask,
        )
        result = model(
            input_ids,
            input_shape_ids=input_shape_ids,
            input_pronunciation_ids=input_pronunciation_ids,
            attention_mask=input_mask,
            token_type_ids=token_type_ids,
            encoder_hidden_states=encoder_hidden_states,
        )
        result = model(
            input_ids,
            input_shape_ids=input_shape_ids,
            input_pronunciation_ids=input_pronunciation_ids,
            attention_mask=input_mask,
            token_type_ids=token_type_ids,
        )
        self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))

    def create_and_check_for_causal_lm(
        self,
        config,
        input_ids,
        input_shape_ids,
        input_pronunciation_ids,
        token_type_ids,
        input_mask,
        sequence_labels,
        token_labels,
        choice_labels,
        encoder_hidden_states,
        encoder_attention_mask,
    ):
        model = RoCBertForCausalLM(config=config)
        model.to(torch_device)
        model.eval()
        result = model(
            input_ids,
            input_shape_ids=input_shape_ids,
            input_pronunciation_ids=input_pronunciation_ids,
            attention_mask=input_mask,
            token_type_ids=token_type_ids,
            labels=token_labels,
        )
        self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))

    def create_and_check_for_masked_lm(
        self,
        config,
        input_ids,
        input_shape_ids,
        input_pronunciation_ids,
        token_type_ids,
        input_mask,
        sequence_labels,
        token_labels,
        choice_labels,
    ):
        model = RoCBertForMaskedLM(config=config)
        model.to(torch_device)
        model.eval()
        result = model(
            input_ids,
            input_shape_ids=input_shape_ids,
            input_pronunciation_ids=input_pronunciation_ids,
            attention_mask=input_mask,
            token_type_ids=token_type_ids,
            labels=token_labels,
        )
        self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))

    def create_and_check_decoder_model_past_large_inputs(
        self,
        config,
        input_ids,
        input_shape_ids,
        input_pronunciation_ids,
        token_type_ids,
        input_mask,
        sequence_labels,
        token_labels,
        choice_labels,
        encoder_hidden_states,
        encoder_attention_mask,
    ):
        config.is_decoder = True
        config.add_cross_attention = True
        model = RoCBertForCausalLM(config=config)
        model.to(torch_device)
        model.eval()

        
        outputs = model(
            input_ids,
            input_shape_ids=input_shape_ids,
            input_pronunciation_ids=input_pronunciation_ids,
            attention_mask=input_mask,
            encoder_hidden_states=encoder_hidden_states,
            encoder_attention_mask=encoder_attention_mask,
            use_cache=True,
        )
        past_key_values = outputs.past_key_values

        
        next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
        next_shape_tokens = ids_tensor((self.batch_size, 3), config.shape_vocab_size)
        next_pronunciation_tokens = ids_tensor((self.batch_size, 3), config.pronunciation_vocab_size)
        next_mask = ids_tensor((self.batch_size, 3), vocab_size=2)

        
        next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
        next_input_shape_ids = torch.cat([input_shape_ids, next_shape_tokens], dim=-1)
        next_input_pronunciation_ids = torch.cat([input_pronunciation_ids, next_pronunciation_tokens], dim=-1)
        next_attention_mask = torch.cat([input_mask, next_mask], dim=-1)

        output_from_no_past = model(
            next_input_ids,
            input_shape_ids=next_input_shape_ids,
            input_pronunciation_ids=next_input_pronunciation_ids,
            attention_mask=next_attention_mask,
            encoder_hidden_states=encoder_hidden_states,
            encoder_attention_mask=encoder_attention_mask,
            output_hidden_states=True,
        )["hidden_states"][0]
        output_from_past = model(
            next_tokens,
            input_shape_ids=next_shape_tokens,
            input_pronunciation_ids=next_pronunciation_tokens,
            attention_mask=next_attention_mask,
            encoder_hidden_states=encoder_hidden_states,
            encoder_attention_mask=encoder_attention_mask,
            past_key_values=past_key_values,
            output_hidden_states=True,
        )["hidden_states"][0]

        
        random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
        output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
        output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()

        self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])

        
        self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))

    def create_and_check_for_question_answering(
        self,
        config,
        input_ids,
        input_shape_ids,
        input_pronunciation_ids,
        token_type_ids,
        input_mask,
        sequence_labels,
        token_labels,
        choice_labels,
    ):
        model = RoCBertForQuestionAnswering(config=config)
        model.to(torch_device)
        model.eval()
        result = model(
            input_ids,
            input_shape_ids=input_shape_ids,
            input_pronunciation_ids=input_pronunciation_ids,
            attention_mask=input_mask,
            token_type_ids=token_type_ids,
            start_positions=sequence_labels,
            end_positions=sequence_labels,
        )
        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 create_and_check_for_sequence_classification(
        self,
        config,
        input_ids,
        input_shape_ids,
        input_pronunciation_ids,
        token_type_ids,
        input_mask,
        sequence_labels,
        token_labels,
        choice_labels,
    ):
        config.num_labels = self.num_labels
        model = RoCBertForSequenceClassification(config)
        model.to(torch_device)
        model.eval()
        result = model(
            input_ids,
            input_shape_ids=input_shape_ids,
            input_pronunciation_ids=input_pronunciation_ids,
            attention_mask=input_mask,
            token_type_ids=token_type_ids,
            labels=sequence_labels,
        )
        self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))

    def create_and_check_for_token_classification(
        self,
        config,
        input_ids,
        input_shape_ids,
        input_pronunciation_ids,
        token_type_ids,
        input_mask,
        sequence_labels,
        token_labels,
        choice_labels,
    ):
        config.num_labels = self.num_labels
        model = RoCBertForTokenClassification(config=config)
        model.to(torch_device)
        model.eval()
        result = model(
            input_ids,
            input_shape_ids=input_shape_ids,
            input_pronunciation_ids=input_pronunciation_ids,
            attention_mask=input_mask,
            token_type_ids=token_type_ids,
            labels=token_labels,
        )
        self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))

    def create_and_check_for_multiple_choice(
        self,
        config,
        input_ids,
        input_shape_ids,
        input_pronunciation_ids,
        token_type_ids,
        input_mask,
        sequence_labels,
        token_labels,
        choice_labels,
    ):
        config.num_choices = self.num_choices
        model = RoCBertForMultipleChoice(config=config)
        model.to(torch_device)
        model.eval()
        multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
        multiple_choice_inputs_shape_ids = input_shape_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
        multiple_choice_inputs_pronunciation_ids = (
            input_pronunciation_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
        )
        multiple_choice_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
        multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
        result = model(
            multiple_choice_inputs_ids,
            input_shape_ids=multiple_choice_inputs_shape_ids,
            input_pronunciation_ids=multiple_choice_inputs_pronunciation_ids,
            attention_mask=multiple_choice_input_mask,
            token_type_ids=multiple_choice_token_type_ids,
            labels=choice_labels,
        )
        self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices))

    def prepare_config_and_inputs_for_common(self):
        config_and_inputs = self.prepare_config_and_inputs()
        (
            config,
            input_ids,
            input_shape_ids,
            input_pronunciation_ids,
            token_type_ids,
            input_mask,
            sequence_labels,
            token_labels,
            choice_labels,
        ) = config_and_inputs
        inputs_dict = {
            "input_ids": input_ids,
            "input_shape_ids": input_shape_ids,
            "input_pronunciation_ids": input_pronunciation_ids,
            "token_type_ids": token_type_ids,
            "attention_mask": input_mask,
        }
        return config, inputs_dict

    def create_and_check_for_pretraining(
        self,
        config,
        input_ids,
        input_shape_ids,
        input_pronunciation_ids,
        token_type_ids,
        input_mask,
        sequence_labels,
        token_labels,
        choice_labels,
    ):
        model = RoCBertForPreTraining(config=config)
        model.to(torch_device)
        model.eval()
        result = model(
            input_ids,
            input_shape_ids,
            input_pronunciation_ids,
            attention_mask=input_mask,
            token_type_ids=token_type_ids,
            attack_input_ids=input_ids,
            attack_input_shape_ids=input_shape_ids,
            attack_input_pronunciation_ids=input_pronunciation_ids,
            attack_attention_mask=input_mask,
            attack_token_type_ids=token_type_ids,
            labels_input_ids=token_labels,
            labels_input_shape_ids=input_shape_ids,
            labels_input_pronunciation_ids=input_pronunciation_ids,
            labels_attention_mask=input_mask,
            labels_token_type_ids=token_type_ids,
        )
        self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))


@require_torch
class RoCBertModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
    all_model_classes = (
        (
            RoCBertModel,
            RoCBertForMaskedLM,
            RoCBertForCausalLM,
            RoCBertForMultipleChoice,
            RoCBertForQuestionAnswering,
            RoCBertForSequenceClassification,
            RoCBertForTokenClassification,
            RoCBertForPreTraining,
        )
        if is_torch_available()
        else ()
    )
    all_generative_model_classes = (RoCBertForCausalLM,) if is_torch_available() else ()
    pipeline_model_mapping = (
        {
            "feature-extraction": RoCBertModel,
            "fill-mask": RoCBertForMaskedLM,
            "question-answering": RoCBertForQuestionAnswering,
            "text-classification": RoCBertForSequenceClassification,
            "text-generation": RoCBertForCausalLM,
            "token-classification": RoCBertForTokenClassification,
            "zero-shot": RoCBertForSequenceClassification,
        }
        if is_torch_available()
        else {}
    )

    
    def is_pipeline_test_to_skip(
        self, pipeline_test_casse_name, config_class, model_architecture, tokenizer_name, processor_name
    ):
        if pipeline_test_casse_name in [
            "FillMaskPipelineTests",
            "FeatureExtractionPipelineTests",
            "TextClassificationPipelineTests",
            "TokenClassificationPipelineTests",
        ]:
            
            
            
            
            return True

        return False

    
    def _prepare_for_class(self, inputs_dict, model_class, return_labels=False):
        inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels)

        if return_labels:
            if model_class in get_values(MODEL_FOR_PRETRAINING_MAPPING):
                inputs_dict["labels_input_ids"] = torch.zeros(
                    (self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device
                )
                inputs_dict["labels_input_shape_ids"] = torch.zeros(
                    (self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device
                )
                inputs_dict["labels_input_pronunciation_ids"] = torch.zeros(
                    (self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device
                )
                inputs_dict["attack_input_ids"] = torch.zeros(
                    (self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device
                )
                inputs_dict["attack_input_shape_ids"] = torch.zeros(
                    (self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device
                )
                inputs_dict["attack_input_pronunciation_ids"] = torch.zeros(
                    (self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device
                )
        return inputs_dict

    def setUp(self):
        self.model_tester = RoCBertModelTester(self)
        self.config_tester = ConfigTester(self, config_class=RoCBertConfig, hidden_size=37)

    def test_config(self):
        self.config_tester.run_common_tests()

    def test_model(self):
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*config_and_inputs)

    def test_model_various_embeddings(self):
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
        for type in ["absolute", "relative_key", "relative_key_query"]:
            config_and_inputs[0].position_embedding_type = type
            self.model_tester.create_and_check_model(*config_and_inputs)

    def test_for_masked_lm(self):
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_masked_lm(*config_and_inputs)

    def test_for_multiple_choice(self):
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs)

    def test_decoder_model_past_with_large_inputs(self):
        config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
        self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs)

    def test_decoder_model_past_with_large_inputs_relative_pos_emb(self):
        config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
        config_and_inputs[0].position_embedding_type = "relative_key"
        self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs)

    def test_for_question_answering(self):
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_question_answering(*config_and_inputs)

    def test_for_sequence_classification(self):
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_sequence_classification(*config_and_inputs)

    def test_for_token_classification(self):
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_token_classification(*config_and_inputs)

    def test_for_pretraining(self):
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_pretraining(*config_and_inputs)

    def test_model_as_decoder(self):
        config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
        self.model_tester.create_and_check_model_as_decoder(*config_and_inputs)

    def test_model_as_decoder_with_default_input_mask(self):
        
        (
            config,
            input_ids,
            input_shape_ids,
            input_pronunciation_ids,
            token_type_ids,
            input_mask,
            sequence_labels,
            token_labels,
            choice_labels,
            encoder_hidden_states,
            encoder_attention_mask,
        ) = self.model_tester.prepare_config_and_inputs_for_decoder()

        input_mask = None

        self.model_tester.create_and_check_model_as_decoder(
            config,
            input_ids,
            input_shape_ids,
            input_pronunciation_ids,
            token_type_ids,
            input_mask,
            sequence_labels,
            token_labels,
            choice_labels,
            encoder_hidden_states,
            encoder_attention_mask,
        )

    @slow
    def test_model_from_pretrained(self):
        for model_name in ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            model = RoCBertModel.from_pretrained(model_name)
            self.assertIsNotNone(model)


@require_torch
class RoCBertModelIntegrationTest(unittest.TestCase):
    @slow
    def test_inference_masked_lm(self):
        model = RoCBertForMaskedLM.from_pretrained("weiweishi/roc-bert-base-zh")

        
        
        
        input_ids = torch.tensor([[101, 144, 143, 7027, 5143, 103, 1744, 4638, 7674, 6963, 102]])
        input_shape_ids = torch.tensor([[2, 20324, 23690, 8740, 706, 1, 10900, 23343, 20205, 5850, 2]])
        input_pronunciation_ids = torch.tensor([[2, 718, 397, 52, 61, 1, 168, 273, 180, 243, 2]])

        output = model(input_ids, input_shape_ids, input_pronunciation_ids)
        output_ids = torch.argmax(output.logits, dim=2)

        
        expected_output = torch.tensor([[101, 2349, 115, 7944, 3221, 3791, 1744, 4638, 7674, 6963, 102]])

        assert torch.allclose(output_ids, expected_output)