codingutf8 2022 the realm s and 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 pytorch realm model import math import os from dataclasses import dataclass from typing import optional tuple union import torch from torch import nn from torch nn import crossentropyloss from activations import act2fn from modelingoutputs import basemodeloutputwithpastandcrossattentions basemodeloutputwithpoolingandcrossattentions maskedlmoutput modeloutput from modelingutils import pretrainedmodel from pytorchutils import applychunkingtoforward findpruneableheadsandindices prunelinearlayer from utils import addstartdocstrings addstartdocstringstomodelforward logging replacereturndocstrings from configurationrealm import realmconfig logger logging getloggername embeddercheckpointfordoc googlerealmccnewspretrainedembedder encodercheckpointfordoc googlerealmccnewspretrainedencoder scorercheckpointfordoc googlerealmccnewspretrainedscorer configfordoc realmconfig realmpretrainedmodelarchivelist googlerealmccnewspretrainedembedder googlerealmccnewspretrainedencoder googlerealmccnewspretrainedscorer googlerealmccnewspretrainedopenqa googlerealmorqanqopenqa googlerealmorqanqreader googlerealmorqawqopenqa googlerealmorqawqreader see all realm models at https huggingface comodels filterrealm def loadtfweightsinrealmmodel config tfcheckpointpath load weights from tf model for pretrained openqa reader for pretrained encoder for finetuned reader for embedder and scorer adamv and adamm are variables used in adamweightdecayoptimizer to calculated m and v which are not required for using pretrained model copied from transformers models bert modelingbert bertembeddings with bertrealm construct the embeddings from word position and tokentype embeddings def initself config super init self wordembeddings nn embeddingconfig vocabsize config hiddensize paddingidxconfig padtokenid self positionembeddings nn embeddingconfig maxpositionembeddings config hiddensize self tokentypeembeddings nn embeddingconfig typevocabsize config hiddensize self layernorm is not snakecased to stick with tensorflow model variable name and be able to load any tensorflow checkpoint file self layernorm nn layernormconfig hiddensize epsconfig layernormeps self dropout nn dropoutconfig hiddendropoutprob positionids 1 len position emb is contiguous in memory and exported when serialized self positionembeddingtype getattrconfig positionembeddingtype absolute self registerbuffer positionids torch arangeconfig maxpositionembeddings expand1 1 persistentfalse self registerbuffer tokentypeids torch zerosself positionids size dtypetorch long persistentfalse def forward self inputids optionaltorch longtensor none tokentypeids optionaltorch longtensor none positionids optionaltorch longtensor none inputsembeds optionaltorch floattensor none pastkeyvalueslength int 0 torch tensor if inputids is not none inputshape inputids size else inputshape inputsembeds size 1 seqlength inputshape1 if positionids is none positionids self positionids pastkeyvalueslength seqlength pastkeyvalueslength setting the tokentypeids to the registered buffer in constructor where it is all zeros which usually occurs when its autogenerated registered buffer helps users when tracing the model without passing tokentypeids solves issue 5664 if tokentypeids is none if hasattrself tokentypeids bufferedtokentypeids self tokentypeids seqlength bufferedtokentypeidsexpanded bufferedtokentypeids expandinputshape0 seqlength tokentypeids bufferedtokentypeidsexpanded else tokentypeids torch zerosinputshape dtypetorch long deviceself positionids device if inputsembeds is none inputsembeds self wordembeddingsinputids tokentypeembeddings self tokentypeembeddingstokentypeids embeddings inputsembeds tokentypeembeddings if self positionembeddingtype absolute positionembeddings self positionembeddingspositionids embeddings positionembeddings embeddings self layernormembeddings embeddings self dropoutembeddings return embeddings copied from transformers models bert modelingbert bertselfattention with bertrealm class realmselfattentionnn module def initself config positionembeddingtypenone super init if config hiddensize config numattentionheads 0 and not hasattrconfig embeddingsize raise valueerror fthe hidden size config hiddensize is not a multiple of the number of attention fheads config numattentionheads self numattentionheads config numattentionheads self attentionheadsize intconfig hiddensize config numattentionheads self allheadsize self numattentionheads self attentionheadsize self query nn linearconfig hiddensize self allheadsize self key nn linearconfig hiddensize self allheadsize self value nn linearconfig hiddensize self allheadsize self dropout nn dropoutconfig attentionprobsdropoutprob self positionembeddingtype positionembeddingtype or getattr config positionembeddingtype absolute if self positionembeddingtype relativekey or self positionembeddingtype relativekeyquery self maxpositionembeddings config maxpositionembeddings self distanceembedding nn embedding2 config maxpositionembeddings 1 self attentionheadsize self isdecoder config isdecoder def transposeforscoresself x torch tensor torch tensor newxshape x size 1 self numattentionheads self attentionheadsize x x viewnewxshape return x permute0 2 1 3 def forward self hiddenstates torch tensor attentionmask optionaltorch floattensor none headmask optionaltorch floattensor none encoderhiddenstates optionaltorch floattensor none encoderattentionmask optionaltorch floattensor none pastkeyvalue optionaltupletupletorch floattensor none outputattentions optionalbool false tupletorch tensor mixedquerylayer self queryhiddenstates if this is instantiated as a crossattention module the keys and values come from an encoder the attention mask needs to be such that the encoder s padding tokens are not attended to iscrossattention encoderhiddenstates is not none if iscrossattention and pastkeyvalue is not none reuse k v crossattentions keylayer pastkeyvalue0 valuelayer pastkeyvalue1 attentionmask encoderattentionmask elif iscrossattention keylayer self transposeforscoresself keyencoderhiddenstates valuelayer self transposeforscoresself valueencoderhiddenstates attentionmask encoderattentionmask elif pastkeyvalue is not none keylayer self transposeforscoresself keyhiddenstates valuelayer self transposeforscoresself valuehiddenstates keylayer torch catpastkeyvalue0 keylayer dim2 valuelayer torch catpastkeyvalue1 valuelayer dim2 else keylayer self transposeforscoresself keyhiddenstates valuelayer self transposeforscoresself valuehiddenstates querylayer self transposeforscoresmixedquerylayer usecache pastkeyvalue is not none if self isdecoder if crossattention save tupletorch tensor torch tensor of all cross attention keyvaluestates further calls to crossattention layer can then reuse all crossattention keyvaluestates first if case if unidirectional selfattention decoder save tupletorch tensor torch tensor of all previous decoder keyvaluestates further calls to unidirectional selfattention can concat previous decoder keyvaluestates to current projected keyvaluestates third elif case if encoder bidirectional selfattention pastkeyvalue is always none pastkeyvalue keylayer valuelayer take the dot product between query and key to get the raw attention scores attentionscores torch matmulquerylayer keylayer transpose1 2 if self positionembeddingtype relativekey or self positionembeddingtype relativekeyquery querylength keylength querylayer shape2 keylayer shape2 if usecache positionidsl torch tensorkeylength 1 dtypetorch long devicehiddenstates device view 1 1 else positionidsl torch arangequerylength dtypetorch long devicehiddenstates device view1 1 positionidsr torch arangekeylength dtypetorch long devicehiddenstates device view1 1 distance positionidsl positionidsr positionalembedding self distanceembeddingdistance self maxpositionembeddings 1 positionalembedding positionalembedding todtypequerylayer dtype fp16 compatibility if self positionembeddingtype relativekey relativepositionscores torch einsumbhld lrdbhlr querylayer positionalembedding attentionscores attentionscores relativepositionscores elif self positionembeddingtype relativekeyquery relativepositionscoresquery torch einsumbhld lrdbhlr querylayer positionalembedding relativepositionscoreskey torch einsumbhrd lrdbhlr keylayer positionalembedding attentionscores attentionscores relativepositionscoresquery relativepositionscoreskey attentionscores attentionscores math sqrtself attentionheadsize if attentionmask is not none apply the attention mask is precomputed for all layers in realmmodel forward function attentionscores attentionscores attentionmask normalize the attention scores to probabilities attentionprobs nn functional softmaxattentionscores dim1 this is actually dropping out entire tokens to attend to which might seem a bit unusual but is taken from the original transformer paper attentionprobs self dropoutattentionprobs mask heads if we want to if headmask is not none attentionprobs attentionprobs headmask contextlayer torch matmulattentionprobs valuelayer contextlayer contextlayer permute0 2 1 3 contiguous newcontextlayershape contextlayer size 2 self allheadsize contextlayer contextlayer viewnewcontextlayershape outputs contextlayer attentionprobs if outputattentions else contextlayer if self isdecoder outputs outputs pastkeyvalue return outputs copied from transformers models bert modelingbert bertselfoutput with bertrealm class realmselfoutputnn module def initself config super init self dense nn linearconfig hiddensize config hiddensize self layernorm nn layernormconfig hiddensize epsconfig layernormeps self dropout nn dropoutconfig hiddendropoutprob def forwardself hiddenstates torch tensor inputtensor torch tensor torch tensor hiddenstates self densehiddenstates hiddenstates self dropouthiddenstates hiddenstates self layernormhiddenstates inputtensor return hiddenstates copied from transformers models bert modelingbert bertattention with bertrealm class realmattentionnn module def initself config positionembeddingtypenone super init self self realmselfattentionconfig positionembeddingtypepositionembeddingtype self output realmselfoutputconfig self prunedheads set def pruneheadsself heads if lenheads 0 return heads index findpruneableheadsandindices heads self self numattentionheads self self attentionheadsize self prunedheads prune linear layers self self query prunelinearlayerself self query index self self key prunelinearlayerself self key index self self value prunelinearlayerself self value index self output dense prunelinearlayerself output dense index dim1 update hyper params and store pruned heads self self numattentionheads self self numattentionheads lenheads self self allheadsize self self attentionheadsize self self numattentionheads self prunedheads self prunedheads unionheads def forward self hiddenstates torch tensor attentionmask optionaltorch floattensor none headmask optionaltorch floattensor none encoderhiddenstates optionaltorch floattensor none encoderattentionmask optionaltorch floattensor none pastkeyvalue optionaltupletupletorch floattensor none outputattentions optionalbool false tupletorch tensor selfoutputs self self hiddenstates attentionmask headmask encoderhiddenstates encoderattentionmask pastkeyvalue outputattentions attentionoutput self outputselfoutputs0 hiddenstates outputs attentionoutput selfoutputs1 add attentions if we output them return outputs copied from transformers models bert modelingbert bertintermediate with bertrealm class realmintermediatenn module def initself config super init self dense nn linearconfig hiddensize config intermediatesize if isinstanceconfig hiddenact str self intermediateactfn act2fnconfig hiddenact else self intermediateactfn config hiddenact def forwardself hiddenstates torch tensor torch tensor hiddenstates self densehiddenstates hiddenstates self intermediateactfnhiddenstates return hiddenstates copied from transformers models bert modelingbert bertoutput with bertrealm class realmoutputnn module def initself config super init self dense nn linearconfig intermediatesize config hiddensize self layernorm nn layernormconfig hiddensize epsconfig layernormeps self dropout nn dropoutconfig hiddendropoutprob def forwardself hiddenstates torch tensor inputtensor torch tensor torch tensor hiddenstates self densehiddenstates hiddenstates self dropouthiddenstates hiddenstates self layernormhiddenstates inputtensor return hiddenstates copied from transformers models bert modelingbert bertlayer with bertrealm class realmlayernn module def initself config super init self chunksizefeedforward config chunksizefeedforward self seqlendim 1 self attention realmattentionconfig self isdecoder config isdecoder self addcrossattention config addcrossattention if self addcrossattention if not self isdecoder raise valueerrorfself should be used as a decoder model if cross attention is added self crossattention realmattentionconfig positionembeddingtypeabsolute self intermediate realmintermediateconfig self output realmoutputconfig def forward self hiddenstates torch tensor attentionmask optionaltorch floattensor none headmask optionaltorch floattensor none encoderhiddenstates optionaltorch floattensor none encoderattentionmask optionaltorch floattensor none pastkeyvalue optionaltupletupletorch floattensor none outputattentions optionalbool false tupletorch tensor decoder unidirectional selfattention cached keyvalues tuple is at positions 1 2 selfattnpastkeyvalue pastkeyvalue 2 if pastkeyvalue is not none else none selfattentionoutputs self attention hiddenstates attentionmask headmask outputattentionsoutputattentions pastkeyvalueselfattnpastkeyvalue attentionoutput selfattentionoutputs0 if decoder the last output is tuple of selfattn cache if self isdecoder outputs selfattentionoutputs1 1 presentkeyvalue selfattentionoutputs1 else outputs selfattentionoutputs1 add self attentions if we output attention weights crossattnpresentkeyvalue none if self isdecoder and encoderhiddenstates is not none if not hasattrself crossattention raise valueerror fif encoderhiddenstates are passed self has to be instantiated with crossattention layers by setting config addcrossattentiontrue crossattn cached keyvalues tuple is at positions 3 4 of pastkeyvalue tuple crossattnpastkeyvalue pastkeyvalue2 if pastkeyvalue is not none else none crossattentionoutputs self crossattention attentionoutput attentionmask headmask encoderhiddenstates encoderattentionmask crossattnpastkeyvalue outputattentions attentionoutput crossattentionoutputs0 outputs outputs crossattentionoutputs1 1 add cross attentions if we output attention weights add crossattn cache to positions 3 4 of presentkeyvalue tuple crossattnpresentkeyvalue crossattentionoutputs1 presentkeyvalue presentkeyvalue crossattnpresentkeyvalue layeroutput applychunkingtoforward self feedforwardchunk self chunksizefeedforward self seqlendim attentionoutput outputs layeroutput outputs if decoder return the attn keyvalues as the last output if self isdecoder outputs outputs presentkeyvalue return outputs def feedforwardchunkself attentionoutput intermediateoutput self intermediateattentionoutput layeroutput self outputintermediateoutput attentionoutput return layeroutput copied from transformers models bert modelingbert bertencoder with bertrealm class realmencodernn module def initself config super init self config config self layer nn modulelistrealmlayerconfig for in rangeconfig numhiddenlayers self gradientcheckpointing false def forward self hiddenstates torch tensor attentionmask optionaltorch floattensor none headmask optionaltorch floattensor none encoderhiddenstates optionaltorch floattensor none encoderattentionmask optionaltorch floattensor none pastkeyvalues optionaltupletupletorch floattensor none usecache optionalbool none outputattentions optionalbool false outputhiddenstates optionalbool false returndict optionalbool true uniontupletorch tensor basemodeloutputwithpastandcrossattentions allhiddenstates if outputhiddenstates else none allselfattentions if outputattentions else none allcrossattentions if outputattentions and self config addcrossattention else none if self gradientcheckpointing and self training if usecache logger warningonce usecachetrue is incompatible with gradient checkpointing setting usecachefalse usecache false nextdecodercache if usecache else none for i layermodule in enumerateself layer if outputhiddenstates allhiddenstates allhiddenstates hiddenstates layerheadmask headmaski if headmask is not none else none pastkeyvalue pastkeyvaluesi if pastkeyvalues is not none else none if self gradientcheckpointing and self training layeroutputs self gradientcheckpointingfunc layermodule call hiddenstates attentionmask layerheadmask encoderhiddenstates encoderattentionmask pastkeyvalue outputattentions else layeroutputs layermodule hiddenstates attentionmask layerheadmask encoderhiddenstates encoderattentionmask pastkeyvalue outputattentions hiddenstates layeroutputs0 if usecache nextdecodercache layeroutputs1 if outputattentions allselfattentions allselfattentions layeroutputs1 if self config addcrossattention allcrossattentions allcrossattentions layeroutputs2 if outputhiddenstates allhiddenstates allhiddenstates hiddenstates if not returndict return tuple v for v in hiddenstates nextdecodercache allhiddenstates allselfattentions allcrossattentions if v is not none return basemodeloutputwithpastandcrossattentions lasthiddenstatehiddenstates pastkeyvaluesnextdecodercache hiddenstatesallhiddenstates attentionsallselfattentions crossattentionsallcrossattentions copied from transformers models bert modelingbert bertpooler with bertrealm class realmpoolernn module def initself config super init self dense nn linearconfig hiddensize config hiddensize self activation nn tanh def forwardself hiddenstates torch tensor torch tensor we pool the model by simply taking the hidden state corresponding to the first token firsttokentensor hiddenstates 0 pooledoutput self densefirsttokentensor pooledoutput self activationpooledoutput return pooledoutput dataclass class realmembedderoutputmodeloutput projectedscore torch floattensor none hiddenstates optionaltupletorch floattensor none attentions optionaltupletorch floattensor none dataclass class realmscoreroutputmodeloutput relevancescore torch floattensor none queryscore torch floattensor none candidatescore torch floattensor none dataclass class realmreaderoutputmodeloutput loss torch floattensor none retrieverloss torch floattensor none readerloss torch floattensor none retrievercorrect torch booltensor none readercorrect torch booltensor none blockidx torch longtensor none candidate torch longtensor none startpos torch int32 none endpos torch int32 none hiddenstates optionaltupletorch floattensor none attentions optionaltupletorch floattensor none dataclass class realmforopenqaoutputmodeloutput readeroutput dict none predictedanswerids torch longtensor none class realmpredictionheadtransformnn module def initself config super init self dense nn linearconfig hiddensize config hiddensize if isinstanceconfig hiddenact str self transformactfn act2fnconfig hiddenact else self transformactfn config hiddenact self layernorm nn layernormconfig hiddensize epsconfig layernormeps def forwardself hiddenstates hiddenstates self densehiddenstates hiddenstates self transformactfnhiddenstates hiddenstates self layernormhiddenstates return hiddenstates class realmlmpredictionheadnn module def initself config super init self transform realmpredictionheadtransformconfig the output weights are the same as the input embeddings but there is an outputonly bias for each token self decoder nn linearconfig hiddensize config vocabsize biasfalse self bias nn parametertorch zerosconfig vocabsize need a link between the two variables so that the bias is correctly resized with resizetokenembeddings self decoder bias self bias def forwardself hiddenstates hiddenstates self transformhiddenstates hiddenstates self decoderhiddenstates return hiddenstates class realmonlymlmheadnn module def initself config super init self predictions realmlmpredictionheadconfig def forwardself sequenceoutput predictionscores self predictionssequenceoutput return predictionscores class realmscorerprojectionnn module def initself config super init self predictions realmlmpredictionheadconfig self dense nn linearconfig hiddensize config retrieverprojsize self layernorm nn layernormconfig retrieverprojsize epsconfig layernormeps def forwardself hiddenstates hiddenstates self densehiddenstates hiddenstates self layernormhiddenstates return hiddenstates class realmreaderprojectionnn module def initself config super init self config config self denseintermediate nn linearconfig hiddensize config spanhiddensize 2 self denseoutput nn linearconfig spanhiddensize 1 self layernormalization nn layernormconfig spanhiddensize epsconfig readerlayernormeps self relu nn relu def forwardself hiddenstates blockmask def spancandidatesmasks maxsequencelen masks shape def spansgivenwidthwidth currentstarts torch arangemaxsequencelen width 1 devicemasks device currentends torch arangewidth 1 maxsequencelen devicemasks device return currentstarts currentends starts ends zipspansgivenwidthw 1 for w in rangeself config maxspanwidth numspans starts torch catstarts 0 ends torch catends 0 numretrievals numspans startmasks torch indexselectmasks dim1 indexstarts endmasks torch indexselectmasks dim1 indexends spanmasks startmasks endmasks return starts ends spanmasks def masktoscoremask dtypetorch float32 return 1 0 mask typedtype torch finfodtype min readerbeamsize maxsequencelen spanhiddensize 2 hiddenstates self denseintermediatehiddenstates readerbeamsize maxsequencelen spanhiddensize startprojection endprojection hiddenstates chunk2 dim1 candidatestarts candidateends candidatemask spancandidatesblockmask candidatestartprojections torch indexselectstartprojection dim1 indexcandidatestarts candidateendprojections torch indexselectendprojection dim1 indexcandidateends candidatehidden candidatestartprojections candidateendprojections readerbeamsize numcandidates spanhiddensize candidatehidden self relucandidatehidden readerbeamsize numcandidates spanhiddensize candidatehidden self layernormalizationcandidatehidden readerbeamsize numcandidates readerlogits self denseoutputcandidatehidden squeeze1 readerbeamsize numcandidates readerlogits masktoscorecandidatemask dtypereaderlogits dtype return readerlogits candidatestarts candidateends realmstartdocstring r this model is a pytorch torch nn modulehttps pytorch orgdocsstablenn htmltorch nn module subclass use it as a regular pytorch module and refer to the pytorch documentation for all matter related to general usage and behavior parameters config realmconfig model configuration class with all the parameters of the model initializing with a config file does not load the weights associated with the model only the configuration check out the pretrainedmodel frompretrained method to load the model weights class realmpretrainedmodelpretrainedmodel configclass realmconfig loadtfweights loadtfweightsinrealm basemodelprefix realm def initweightsself module slightly different from the tf version which uses truncatednormal for initialization cf https github compytorchpytorchpull5617 flatten inputs shape to 1 inputshape1 flattenedinputs for tensor in inputs if tensor is none flattenedinputs appendnone else inputshape tensor shape if leninputshape 2 tensor tensor view1 inputshape1 flattenedinputs appendtensor return flattenedinputs class realmbertmodelrealmpretrainedmodel def initself config addpoolinglayertrue super initconfig self config config self embeddings realmembeddingsconfig self encoder realmencoderconfig self pooler realmpoolerconfig if addpoolinglayer else none weights initialization is mostly managed by other realm models but we also have them initialized here to keep a consistency self postinit def getinputembeddingsself return self embeddings wordembeddings def setinputembeddingsself value self embeddings wordembeddings value def pruneheadsself headstoprune for layer heads in headstoprune items self encoder layerlayer attention pruneheadsheads def forward self inputidsnone attentionmasknone tokentypeidsnone positionidsnone headmasknone inputsembedsnone encoderhiddenstatesnone encoderattentionmasknone pastkeyvaluesnone usecachenone outputattentionsnone outputhiddenstatesnone returndictnone outputattentions outputattentions if outputattentions is not none else self config outputattentions outputhiddenstates outputhiddenstates if outputhiddenstates is not none else self config outputhiddenstates returndict returndict if returndict is not none else self config usereturndict if self config isdecoder usecache usecache if usecache is not none else self config usecache else usecache false if inputids is not none and inputsembeds is not none raise valueerroryou cannot specify both inputids and inputsembeds at the same time elif inputids is not none self warnifpaddingandnoattentionmaskinputids attentionmask inputshape inputids size elif inputsembeds is not none inputshape inputsembeds size 1 else raise valueerroryou have to specify either inputids or inputsembeds batchsize seqlength inputshape device inputids device if inputids is not none else inputsembeds device pastkeyvalueslength pastkeyvalueslength pastkeyvalues00 shape2 if pastkeyvalues is not none else 0 if attentionmask is none attentionmask torch onesbatchsize seqlength pastkeyvalueslength devicedevice if tokentypeids is none if hasattrself embeddings tokentypeids bufferedtokentypeids self embeddings tokentypeids seqlength bufferedtokentypeidsexpanded bufferedtokentypeids expandbatchsize seqlength tokentypeids bufferedtokentypeidsexpanded else tokentypeids torch zerosinputshape dtypetorch long devicedevice we can provide a selfattention mask of dimensions batchsize fromseqlength toseqlength ourselves in which case we just need to make it broadcastable to all heads extendedattentionmask torch tensor self getextendedattentionmaskattentionmask inputshape if a 2d or 3d attention mask is provided for the crossattention we need to make broadcastable to batchsize numheads seqlength seqlength if self config isdecoder and encoderhiddenstates is not none encoderbatchsize encodersequencelength encoderhiddenstates size encoderhiddenshape encoderbatchsize encodersequencelength if encoderattentionmask is none encoderattentionmask torch onesencoderhiddenshape devicedevice encoderextendedattentionmask self invertattentionmaskencoderattentionmask else encoderextendedattentionmask none prepare head mask if needed 1 0 in headmask indicate we keep the head attentionprobs has shape bsz x nheads x n x n input headmask has shape numheads or numhiddenlayers x numheads and headmask is converted to shape numhiddenlayers x batch x numheads x seqlength x seqlength headmask self getheadmaskheadmask self config numhiddenlayers embeddingoutput self embeddings inputidsinputids positionidspositionids tokentypeidstokentypeids inputsembedsinputsembeds pastkeyvalueslengthpastkeyvalueslength encoderoutputs self encoder embeddingoutput attentionmaskextendedattentionmask headmaskheadmask encoderhiddenstatesencoderhiddenstates encoderattentionmaskencoderextendedattentionmask pastkeyvaluespastkeyvalues usecacheusecache outputattentionsoutputattentions outputhiddenstatesoutputhiddenstates returndictreturndict sequenceoutput encoderoutputs0 pooledoutput self poolersequenceoutput if self pooler is not none else none if not returndict return sequenceoutput pooledoutput encoderoutputs1 return basemodeloutputwithpoolingandcrossattentions lasthiddenstatesequenceoutput pooleroutputpooledoutput pastkeyvaluesencoderoutputs pastkeyvalues hiddenstatesencoderoutputs hiddenstates attentionsencoderoutputs attentions crossattentionsencoderoutputs crossattentions addstartdocstrings the embedder of realm outputting projected score that will be used to calculate relevance score realmstartdocstring class realmembedderrealmpretrainedmodel tiedweightskeys cls predictions decoder bias def initself config super initconfig self realm realmbertmodelself config self cls realmscorerprojectionself config self postinit def getinputembeddingsself return self realm embeddings wordembeddings def setinputembeddingsself value self realm embeddings wordembeddings value addstartdocstringstomodelforwardrealminputsdocstring formatbatchsize sequencelength replacereturndocstringsoutputtyperealmembedderoutput configclassconfigfordoc def forward self inputids optionaltorch longtensor none attentionmask optionaltorch floattensor none tokentypeids optionaltorch longtensor none positionids optionaltorch longtensor none headmask optionaltorch floattensor none inputsembeds optionaltorch floattensor none outputattentions optionalbool none outputhiddenstates optionalbool none returndict optionalbool none uniontuple realmembedderoutput r returns example python from transformers import autotokenizer realmembedder import torch tokenizer autotokenizer frompretrainedgooglerealmccnewspretrainedembedder model realmembedder frompretrainedgooglerealmccnewspretrainedembedder inputs tokenizerhello my dog is cute returntensorspt outputs modelinputs projectedscore outputs projectedscore batchsize hiddensize batchsize retrieverprojsize def initself config queryembeddernone super initconfig self embedder realmembedderself config self queryembedder queryembedder if queryembedder is not none else self embedder self postinit addstartdocstringstomodelforwardrealminputsdocstring formatbatchsize sequencelength replacereturndocstringsoutputtyperealmscoreroutput configclassconfigfordoc def forward self inputids optionaltorch longtensor none attentionmask optionaltorch floattensor none tokentypeids optionaltorch longtensor none positionids optionaltorch longtensor none candidateinputids optionaltorch longtensor none candidateattentionmask optionaltorch floattensor none candidatetokentypeids optionaltorch longtensor none candidateinputsembeds optionaltorch floattensor none headmask optionaltorch floattensor none inputsembeds optionaltorch floattensor none outputattentions optionalbool none outputhiddenstates optionalbool none returndict optionalbool none uniontuple realmscoreroutput r candidateinputids torch longtensor of shape batchsize numcandidates sequencelength indices of candidate input sequence tokens in the vocabulary indices can be obtained using autotokenizer see pretrainedtokenizer encode and pretrainedtokenizer call for details what are input ids glossaryinputids candidateattentionmask torch floattensor of shape batchsize numcandidates sequencelength optional mask to avoid performing attention on padding token indices mask values selected in 0 1 1 for tokens that are not masked 0 for tokens that are masked what are attention masks glossaryattentionmask candidatetokentypeids torch longtensor of shape batchsize numcandidates sequencelength optional segment token indices to indicate first and second portions of the inputs indices are selected in 0 1 0 corresponds to a sentence a token 1 corresponds to a sentence b token what are token type ids glossarytokentypeids candidateinputsembeds torch floattensor of shape batchsize numcandidates sequencelength hiddensize optional optionally instead of passing candidateinputids you can choose to directly pass an embedded representation this is useful if you want more control over how to convert candidateinputids indices into associated vectors than the model s internal embedding lookup matrix returns example python import torch from transformers import autotokenizer realmscorer tokenizer autotokenizer frompretrainedgooglerealmccnewspretrainedscorer model realmscorer frompretrainedgooglerealmccnewspretrainedscorer numcandidates2 batchsize 2 numcandidates 2 inputtexts how are you what is the item in the picture candidatestexts hello world nice to meet you a cute cat an adorable dog inputs tokenizerinputtexts returntensorspt candidatesinputs tokenizer batchencodecandidatescandidatestexts maxlength10 returntensorspt outputs model inputs candidateinputidscandidatesinputs inputids candidateattentionmaskcandidatesinputs attentionmask candidatetokentypeidscandidatesinputs tokentypeids relevancescore outputs relevancescore returndict returndict if returndict is not none else self config usereturndict if inputids is none and inputsembeds is none raise valueerroryou have to specify either inputids or inputembeds if candidateinputids is none and candidateinputsembeds is none raise valueerroryou have to specify either candidateinputids or candidateinputsembeds queryoutputs self queryembedder inputids attentionmaskattentionmask tokentypeidstokentypeids positionidspositionids headmaskheadmask inputsembedsinputsembeds outputattentionsoutputattentions outputhiddenstatesoutputhiddenstates returndictreturndict batchsize numcandidates candidateseqlen flattenedinputids flattenedattentionmask flattenedtokentypeids self flatteninputs candidateinputids candidateattentionmask candidatetokentypeids candidateoutputs self embedder flattenedinputids attentionmaskflattenedattentionmask tokentypeidsflattenedtokentypeids positionidspositionids headmaskheadmask inputsembedscandidateinputsembeds outputattentionsoutputattentions outputhiddenstatesoutputhiddenstates returndictreturndict batchsize retrieverprojsize queryscore queryoutputs0 batchsize numcandidates retrieverprojsize candidatescore candidateoutputs0 batchsize numcandidates retrieverprojsize candidatescore candidatescore view1 self config numcandidates self config retrieverprojsize batchsize numcandidates relevancescore torch einsumbd bndbn queryscore candidatescore if not returndict return relevancescore queryscore candidatescore return realmscoreroutput relevancescorerelevancescore queryscorequeryscore candidatescorecandidatescore addstartdocstrings the knowledgeaugmented encoder of realm outputting masked language model logits and marginal loglikelihood loss realmstartdocstring class realmknowledgeaugencoderrealmpretrainedmodel tiedweightskeys cls predictions decoder def initself config super initconfig self realm realmbertmodelself config self cls realmonlymlmheadself config self postinit def getinputembeddingsself return self realm embeddings wordembeddings def setinputembeddingsself value self realm embeddings wordembeddings value def getoutputembeddingsself return self cls predictions decoder def setoutputembeddingsself newembeddings self cls predictions decoder newembeddings addstartdocstringstomodelforward realminputsdocstring formatbatchsize numcandidates sequencelength replacereturndocstringsoutputtypemaskedlmoutput configclassconfigfordoc def forward self inputids optionaltorch longtensor none attentionmask optionaltorch floattensor none tokentypeids optionaltorch longtensor none positionids optionaltorch longtensor none headmask optionaltorch floattensor none inputsembeds optionaltorch floattensor none relevancescore optionaltorch floattensor none labels optionaltorch longtensor none mlmmask optionaltorch longtensor none outputattentions optionalbool none outputhiddenstates optionalbool none returndict optionalbool none uniontuple maskedlmoutput r relevancescore torch floattensor of shape batchsize numcandidates optional relevance score derived from realmscorer must be specified if you want to compute the masked language modeling loss labels torch longtensor of shape batchsize sequencelength optional labels for computing the masked language modeling loss indices should be in 100 0 config vocabsize see inputids docstring tokens with indices set to 100 are ignored masked the loss is only computed for the tokens with labels in 0 config vocabsize mlmmask torch longtensor of shape batchsize sequencelength optional mask to avoid calculating joint loss on certain positions if not specified the loss will not be masked mask values selected in 0 1 1 for tokens that are not masked 0 for tokens that are masked returns example python import torch from transformers import autotokenizer realmknowledgeaugencoder tokenizer autotokenizer frompretrainedgooglerealmccnewspretrainedencoder model realmknowledgeaugencoder frompretrained googlerealmccnewspretrainedencoder numcandidates2 batchsize 2 numcandidates 2 text hello world nice to meet you the cute cat the adorable dog inputs tokenizer batchencodecandidatestext maxlength10 returntensorspt outputs modelinputs logits outputs logits returndict returndict if returndict is not none else self config usereturndict flattenedinputids flattenedattentionmask flattenedtokentypeids self flatteninputs inputids attentionmask tokentypeids jointoutputs self realm flattenedinputids attentionmaskflattenedattentionmask tokentypeidsflattenedtokentypeids positionidspositionids headmaskheadmask inputsembedsinputsembeds outputattentionsoutputattentions outputhiddenstatesoutputhiddenstates returndictreturndict batchsize numcandidates jointseqlen hiddensize jointoutput jointoutputs0 batchsize numcandidates jointseqlen vocabsize predictionscores self clsjointoutput batchsize numcandidates candidatescore relevancescore maskedlmloss none if labels is not none if candidatescore is none raise valueerror you have to specify relevancescore when labels is specified in order to compute loss batchsize seqlength labels size if mlmmask is none mlmmask torch oneslikelabels dtypetorch float32 else mlmmask mlmmask typetorch float32 compute marginal loglikelihood lossfct crossentropylossreductionnone 100 index padding token batchsize numcandidates jointseqlen vocabsize mlmlogits predictionscores view1 self config vocabsize batchsize numcandidates jointseqlen mlmtargets labels tile1 self config numcandidates view1 batchsize numcandidates jointseqlen maskedlmlogprob lossfctmlmlogits mlmtargets view batchsize self config numcandidates seqlength batchsize numcandidates 1 candidatelogprob candidatescore logsoftmax1 unsqueeze1 batchsize numcandidates jointseqlen jointgoldlogprob candidatelogprob maskedlmlogprob batchsize jointseqlen marginalgoldlogprobs jointgoldlogprob logsumexp1 maskedlmloss torch nansumtorch summarginalgoldlogprobs mlmmask torch summlmmask if not returndict output predictionscores jointoutputs2 4 return maskedlmloss output if maskedlmloss is not none else output return maskedlmoutput lossmaskedlmloss logitspredictionscores hiddenstatesjointoutputs hiddenstates attentionsjointoutputs attentions addstartdocstringsthe reader of realm realmstartdocstring class realmreaderrealmpretrainedmodel def initself config super initconfig self numlabels config numlabels self realm realmbertmodelconfig self cls realmonlymlmheadconfig self qaoutputs realmreaderprojectionconfig self postinit addstartdocstringstomodelforwardrealminputsdocstring formatreaderbeamsize sequencelength replacereturndocstringsoutputtyperealmreaderoutput configclassconfigfordoc def forward self inputids optionaltorch longtensor none attentionmask optionaltorch floattensor none tokentypeids optionaltorch longtensor none positionids optionaltorch longtensor none headmask optionaltorch floattensor none inputsembeds optionaltorch floattensor none relevancescore optionaltorch floattensor none blockmask optionaltorch booltensor none startpositions optionaltorch longtensor none endpositions optionaltorch longtensor none hasanswers optionaltorch booltensor none outputattentions optionalbool none outputhiddenstates optionalbool none returndict optionalbool none uniontuple realmreaderoutput r relevancescore torch floattensor of shape searcherbeamsize optional relevance score which must be specified if you want to compute the logits and marginal log loss blockmask torch booltensor of shape searcherbeamsize sequencelength optional the mask of the evidence block which must be specified if you want to compute the logits and marginal log loss startpositions torch longtensor of shape searcherbeamsize optional labels for position index of the start of the labelled span for computing the token classification loss positions are clamped to the length of the sequence sequencelength position outside of the sequence are not taken into account for computing the loss endpositions torch longtensor of shape searcherbeamsize optional labels for position index of the end of the labelled span for computing the token classification loss positions are clamped to the length of the sequence sequencelength position outside of the sequence are not taken into account for computing the loss hasanswers torch booltensor of shape searcherbeamsize optional whether or not the evidence block has answers returns readerbeamsize jointseqlen hiddensize readerbeamsize numcandidates numcandidates numcandidates searcherbeamsize 1 readerbeamsize numcandidates 1 1 compute correct span readerbeamsize numanswers numcandidates isgoldstart torch eq torch unsqueezetorch unsqueezecandidatestarts 0 0 torch unsqueezegoldstarts 1 isgoldend torch eq torch unsqueezetorch unsqueezecandidateends 0 0 torch unsqueezegoldends 1 readerbeamsize numcandidates return torch anytorch logicalandisgoldstart isgoldend 1 def marginalloglosslogits iscorrect sometimes the startend positions are outside our model inputs we ignore these terms 1 is reserved for no answer addstartdocstrings realmforopenqa for endtoend open domain question answering realmstartdocstring class realmforopenqarealmpretrainedmodel def initself config retrievernone super initconfig self embedder realmembedderconfig self reader realmreaderconfig self registerbuffer blockemb torch zeros newempty sizeconfig numblockrecords config retrieverprojsize dtypetorch float32 devicetorch devicecpu self retriever retriever self postinit property def searcherbeamsizeself if self training return self config searcherbeamsize return self config readerbeamsize def blockembeddingtoself device self blockemb self blockemb todevice addstartdocstringstomodelforwardrealmforopenqadocstring format1 sequencelength replacereturndocstringsoutputtyperealmforopenqaoutput configclassconfigfordoc def forward self inputids optionaltorch longtensor attentionmask optionaltorch floattensor none tokentypeids optionaltorch longtensor none answerids optionaltorch longtensor none returndict optionalbool none uniontuple realmforopenqaoutput r returns example python import torch from transformers import realmforopenqa realmretriever autotokenizer retriever realmretriever frompretrainedgooglerealmorqanqopenqa tokenizer autotokenizer frompretrainedgooglerealmorqanqopenqa model realmforopenqa frompretrainedgooglerealmorqanqopenqa retrieverretriever question who is the pioneer in modern computer science questionids tokenizerquestion returntensorspt answerids tokenizer alan mathison turing addspecialtokensfalse returntokentypeidsfalse returnattentionmaskfalse inputids readeroutput predictedanswerids modelquestionids answeridsanswerids returndictfalse predictedanswer tokenizer decodepredictedanswerids loss readeroutput loss returndict returndict if returndict is not none else self config usereturndict if inputids is not none and inputids shape0 1 raise valueerrorthe batchsize of the inputs must be 1 questionoutputs self embedder inputidsinputids tokentypeidstokentypeids attentionmaskattentionmask returndicttrue 1 projectionsize questionprojection questionoutputs0 cpu computation starts 1 blockembsize batchscores torch einsumbd qdqb self blockemb questionprojection toself blockemb device 1 searcherbeamsize retrievedblockids torch topkbatchscores kself searcherbeamsize dim1 searcherbeamsize retrievedblockids retrievedblockids squeeze searcherbeamsize projectionsize retrievedblockemb torch indexselectself blockemb dim0 indexretrievedblockids cpu computation ends retrieve possible answers hasanswers startpos endpos concatinputs self retriever retrievedblockids cpu inputids answerids maxlengthself config readerseqlen concatinputs concatinputs toself reader device blockmask concatinputs specialtokensmask typetorch bool todeviceself reader device blockmask logicalnot logicalandconcatinputs tokentypeids typetorch bool if hasanswers is not none hasanswers torch tensorhasanswers dtypetorch bool deviceself reader device startpos torch tensorstartpos dtypetorch long deviceself reader device endpos torch tensorendpos dtypetorch long deviceself reader device searcherbeamsize retrievedlogits torch einsum d bdb questionprojection squeeze retrievedblockemb toself reader device readeroutput self reader inputidsconcatinputs inputids0 self config readerbeamsize attentionmaskconcatinputs attentionmask0 self config readerbeamsize tokentypeidsconcatinputs tokentypeids0 self config readerbeamsize relevancescoreretrievedlogits blockmaskblockmask hasanswershasanswers startpositionsstartpos endpositionsendpos returndicttrue predictedblock concatinputs inputidsreaderoutput blockidx predictedanswerids predictedblockreaderoutput startpos readeroutput endpos 1 if not returndict return readeroutput predictedanswerids return realmforopenqaoutput readeroutputreaderoutput predictedansweridspredictedanswerids coding utf 8 2022 the realm s and 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 pytorch realm model see all realm models at https huggingface co models filter realm load tf checkpoints in a pytorch model load weights from tf model for pretrained openqa reader for pretrained encoder for finetuned reader for embedder and scorer finetuned pretrained adam_v and adam_m are variables used in adamweightdecayoptimizer to calculated m and v which are not required for using pretrained model copied from transformers models bert modeling_bert bertembeddings with bert realm construct the embeddings from word position and token_type embeddings self layernorm is not snake cased to stick with tensorflow model variable name and be able to load any tensorflow checkpoint file position_ids 1 len position emb is contiguous in memory and exported when serialized setting the token_type_ids to the registered buffer in constructor where it is all zeros which usually occurs when its auto generated registered buffer helps users when tracing the model without passing token_type_ids solves issue 5664 copied from transformers models bert modeling_bert bertselfattention with bert realm if this is instantiated as a cross attention module the keys and values come from an encoder the attention mask needs to be such that the encoder s padding tokens are not attended to reuse k v cross_attentions if cross_attention save tuple torch tensor torch tensor of all cross attention key value_states further calls to cross_attention layer can then reuse all cross attention key value_states first if case if uni directional self attention decoder save tuple torch tensor torch tensor of all previous decoder key value_states further calls to uni directional self attention can concat previous decoder key value_states to current projected key value_states third elif case if encoder bi directional self attention past_key_value is always none take the dot product between query and key to get the raw attention scores fp16 compatibility apply the attention mask is precomputed for all layers in realmmodel forward function normalize the attention scores to probabilities this is actually dropping out entire tokens to attend to which might seem a bit unusual but is taken from the original transformer paper mask heads if we want to copied from transformers models bert modeling_bert bertselfoutput with bert realm copied from transformers models bert modeling_bert bertattention with bert realm prune linear layers update hyper params and store pruned heads add attentions if we output them copied from transformers models bert modeling_bert bertintermediate with bert realm copied from transformers models bert modeling_bert bertoutput with bert realm copied from transformers models bert modeling_bert bertlayer with bert realm decoder uni directional self attention cached key values tuple is at positions 1 2 if decoder the last output is tuple of self attn cache add self attentions if we output attention weights cross_attn cached key values tuple is at positions 3 4 of past_key_value tuple add cross attentions if we output attention weights add cross attn cache to positions 3 4 of present_key_value tuple if decoder return the attn key values as the last output copied from transformers models bert modeling_bert bertencoder with bert realm copied from transformers models bert modeling_bert bertpooler with bert realm we pool the model by simply taking the hidden state corresponding to the first token outputs of realmembedder models args projected_score torch floattensor of shape batch_size config retriever_proj_size projected score hidden_states tuple torch floattensor optional returned when output_hidden_states true is passed or when config output_hidden_states true tuple of torch floattensor one for the output of the embeddings one for the output of each layer of shape batch_size sequence_length hidden_size hidden states of the model at the output of each layer plus the initial embedding outputs attentions tuple torch floattensor optional returned when output_attentions true is passed or when config output_attentions true tuple of torch floattensor one for each layer of shape batch_size num_heads sequence_length sequence_length attentions weights after the attention softmax used to compute the weighted average in the self attention heads outputs of realmscorer models args relevance_score torch floattensor of shape batch_size config num_candidates the relevance score of document candidates before softmax query_score torch floattensor of shape batch_size config retriever_proj_size query score derived from the query embedder candidate_score torch floattensor of shape batch_size config num_candidates config retriever_proj_size candidate score derived from the embedder outputs of realmreader models args loss torch floattensor of shape 1 optional returned when start_positions end_positions has_answers are provided total loss retriever_loss torch floattensor of shape 1 optional returned when start_positions end_positions has_answers are provided retriever loss reader_loss torch floattensor of shape 1 optional returned when start_positions end_positions has_answers are provided reader loss retriever_correct torch booltensor of shape config searcher_beam_size optional whether or not an evidence block contains answer reader_correct torch booltensor of shape config reader_beam_size num_candidates optional whether or not a span candidate contains answer block_idx torch longtensor of shape the index of the retrieved evidence block in which the predicted answer is most likely candidate torch longtensor of shape the index of the retrieved span candidates in which the predicted answer is most likely start_pos torch inttensor of shape predicted answer starting position in realmreader s inputs end_pos torch inttensor of shape predicted answer ending position in realmreader s inputs hidden_states tuple torch floattensor optional returned when output_hidden_states true is passed or when config output_hidden_states true tuple of torch floattensor one for the output of the embeddings one for the output of each layer of shape batch_size sequence_length hidden_size hidden states of the model at the output of each layer plus the initial embedding outputs attentions tuple torch floattensor optional returned when output_attentions true is passed or when config output_attentions true tuple of torch floattensor one for each layer of shape batch_size num_heads sequence_length sequence_length attentions weights after the attention softmax used to compute the weighted average in the self attention heads outputs of realmforopenqa models args reader_output dict reader output predicted_answer_ids torch longtensor of shape answer_sequence_length predicted answer ids the output weights are the same as the input embeddings but there is an output only bias for each token need a link between the two variables so that the bias is correctly resized with resize_token_embeddings generate span candidates args masks bool num_retrievals max_sequence_len returns starts int32 num_spans ends int32 num_spans span_masks int32 num_retrievals num_spans whether spans locate in evidence block num_spans num_retrievals num_spans reader_beam_size max_sequence_len span_hidden_size 2 reader_beam_size max_sequence_len span_hidden_size reader_beam_size num_candidates span_hidden_size reader_beam_size num_candidates span_hidden_size reader_beam_size num_candidates reader_beam_size num_candidates this model is a pytorch torch nn module https pytorch org docs stable nn html torch nn module sub class use it as a regular pytorch module and refer to the pytorch documentation for all matter related to general usage and behavior parameters config realmconfig model configuration class with all the parameters of the model initializing with a config file does not load the weights associated with the model only the configuration check out the pretrainedmodel from_pretrained method to load the model weights args input_ids torch longtensor of shape 0 indices of input sequence tokens in the vocabulary indices can be obtained using autotokenizer see pretrainedtokenizer encode and pretrainedtokenizer __call__ for details what are input ids glossary input ids attention_mask torch floattensor of shape 0 optional mask to avoid performing attention on padding token indices mask values selected in 0 1 1 for tokens that are not masked 0 for tokens that are masked what are attention masks glossary attention mask token_type_ids torch longtensor of shape 0 optional segment token indices to indicate first and second portions of the inputs indices are selected in 0 1 0 corresponds to a sentence a token 1 corresponds to a sentence b token what are token type ids glossary token type ids position_ids torch longtensor of shape 0 optional indices of positions of each input sequence tokens in the position embeddings selected in the range 0 config max_position_embeddings 1 what are position ids glossary position ids head_mask torch floattensor of shape num_heads or num_layers num_heads optional mask to nullify selected heads of the self attention modules mask values selected in 0 1 1 indicates the head is not masked 0 indicates the head is masked inputs_embeds torch floattensor of shape 0 hidden_size optional optionally instead of passing input_ids you can choose to directly pass an embedded representation this is useful if you want more control over how to convert input_ids indices into associated vectors than the model s internal embedding lookup matrix output_attentions bool optional whether or not to return the attentions tensors of all attention layers see attentions under returned tensors for more detail output_hidden_states bool optional whether or not to return the hidden states of all layers see hidden_states under returned tensors for more detail return_dict bool optional whether or not to return a utils modeloutput instead of a plain tuple an abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models initialize the weights slightly different from the tf version which uses truncated_normal for initialization cf https github com pytorch pytorch pull 5617 flatten inputs shape to 1 input_shape 1 same as the original bertmodel but remove docstrings weights initialization is mostly managed by other realm models but we also have them initialized here to keep a consistency prunes heads of the model heads_to_prune dict of layer_num list of heads to prune in this layer see base class pretrainedmodel past_key_values_length we can provide a self attention mask of dimensions batch_size from_seq_length to_seq_length ourselves in which case we just need to make it broadcastable to all heads if a 2d or 3d attention mask is provided for the cross attention we need to make broadcastable to batch_size num_heads seq_length seq_length prepare head mask if needed 1 0 in head_mask indicate we keep the head attention_probs has shape bsz x n_heads x n x n input head_mask has shape num_heads or num_hidden_layers x num_heads and head_mask is converted to shape num_hidden_layers x batch x num_heads x seq_length x seq_length returns example python from transformers import autotokenizer realmembedder import torch tokenizer autotokenizer from_pretrained google realm cc news pretrained embedder model realmembedder from_pretrained google realm cc news pretrained embedder inputs tokenizer hello my dog is cute return_tensors pt outputs model inputs projected_score outputs projected_score batch_size hidden_size batch_size retriever_proj_size args query_embedder realmembedder embedder for input sequences if not specified it will use the same embedder as candidate sequences candidate_input_ids torch longtensor of shape batch_size num_candidates sequence_length indices of candidate input sequence tokens in the vocabulary indices can be obtained using autotokenizer see pretrainedtokenizer encode and pretrainedtokenizer __call__ for details what are input ids glossary input ids candidate_attention_mask torch floattensor of shape batch_size num_candidates sequence_length optional mask to avoid performing attention on padding token indices mask values selected in 0 1 1 for tokens that are not masked 0 for tokens that are masked what are attention masks glossary attention mask candidate_token_type_ids torch longtensor of shape batch_size num_candidates sequence_length optional segment token indices to indicate first and second portions of the inputs indices are selected in 0 1 0 corresponds to a sentence a token 1 corresponds to a sentence b token what are token type ids glossary token type ids candidate_inputs_embeds torch floattensor of shape batch_size num_candidates sequence_length hidden_size optional optionally instead of passing candidate_input_ids you can choose to directly pass an embedded representation this is useful if you want more control over how to convert candidate_input_ids indices into associated vectors than the model s internal embedding lookup matrix returns example python import torch from transformers import autotokenizer realmscorer tokenizer autotokenizer from_pretrained google realm cc news pretrained scorer model realmscorer from_pretrained google realm cc news pretrained scorer num_candidates 2 batch_size 2 num_candidates 2 input_texts how are you what is the item in the picture candidates_texts hello world nice to meet you a cute cat an adorable dog inputs tokenizer input_texts return_tensors pt candidates_inputs tokenizer batch_encode_candidates candidates_texts max_length 10 return_tensors pt outputs model inputs candidate_input_ids candidates_inputs input_ids candidate_attention_mask candidates_inputs attention_mask candidate_token_type_ids candidates_inputs token_type_ids relevance_score outputs relevance_score batch_size num_candidates candidate_seq_len batch_size retriever_proj_size batch_size num_candidates retriever_proj_size batch_size num_candidates retriever_proj_size batch_size num_candidates relevance_score torch floattensor of shape batch_size num_candidates optional relevance score derived from realmscorer must be specified if you want to compute the masked language modeling loss labels torch longtensor of shape batch_size sequence_length optional labels for computing the masked language modeling loss indices should be in 100 0 config vocab_size see input_ids docstring tokens with indices set to 100 are ignored masked the loss is only computed for the tokens with labels in 0 config vocab_size mlm_mask torch longtensor of shape batch_size sequence_length optional mask to avoid calculating joint loss on certain positions if not specified the loss will not be masked mask values selected in 0 1 1 for tokens that are not masked 0 for tokens that are masked returns example python import torch from transformers import autotokenizer realmknowledgeaugencoder tokenizer autotokenizer from_pretrained google realm cc news pretrained encoder model realmknowledgeaugencoder from_pretrained google realm cc news pretrained encoder num_candidates 2 batch_size 2 num_candidates 2 text hello world nice to meet you the cute cat the adorable dog inputs tokenizer batch_encode_candidates text max_length 10 return_tensors pt outputs model inputs logits outputs logits batch_size num_candidates joint_seq_len hidden_size batch_size num_candidates joint_seq_len vocab_size batch_size num_candidates compute marginal log likelihood 100 index padding token batch_size num_candidates joint_seq_len vocab_size batch_size num_candidates joint_seq_len batch_size num_candidates joint_seq_len batch_size num_candidates 1 batch_size num_candidates joint_seq_len batch_size joint_seq_len relevance_score torch floattensor of shape searcher_beam_size optional relevance score which must be specified if you want to compute the logits and marginal log loss block_mask torch booltensor of shape searcher_beam_size sequence_length optional the mask of the evidence block which must be specified if you want to compute the logits and marginal log loss start_positions torch longtensor of shape searcher_beam_size optional labels for position index of the start of the labelled span for computing the token classification loss positions are clamped to the length of the sequence sequence_length position outside of the sequence are not taken into account for computing the loss end_positions torch longtensor of shape searcher_beam_size optional labels for position index of the end of the labelled span for computing the token classification loss positions are clamped to the length of the sequence sequence_length position outside of the sequence are not taken into account for computing the loss has_answers torch booltensor of shape searcher_beam_size optional whether or not the evidence block has answer s returns reader_beam_size joint_seq_len hidden_size reader_beam_size num_candidates num_candidates num_candidates searcher_beam_size 1 reader_beam_size num_candidates 1 1 compute correct span reader_beam_size num_answers num_candidates reader_beam_size num_candidates loss based on the negative marginal log likelihood sometimes the start end positions are outside our model inputs we ignore these terms 1 is reserved for no answer args input_ids torch longtensor of shape 0 indices of input sequence tokens in the vocabulary indices can be obtained using autotokenizer see pretrainedtokenizer encode and pretrainedtokenizer __call__ for details what are input ids glossary input ids attention_mask torch floattensor of shape 0 optional mask to avoid performing attention on padding token indices mask values selected in 0 1 1 for tokens that are not masked 0 for tokens that are masked what are attention masks glossary attention mask token_type_ids torch longtensor of shape 0 optional segment token indices to indicate first and second portions of the inputs indices are selected in 0 1 0 corresponds to a sentence a token 1 corresponds to a sentence b token should not be used in this model by design what are token type ids glossary token type ids answer_ids list of shape num_answers answer_length optional answer ids for computing the marginal log likelihood loss indices should be in 1 0 config vocab_size see input_ids docstring tokens with indices set to 1 are ignored masked the loss is only computed for the tokens with labels in 0 config vocab_size return_dict bool optional whether or not to return a utils modeloutput instead of a plain tuple send self block_emb to a specific device args device str or torch device the device to which self block_emb will be sent returns example python import torch from transformers import realmforopenqa realmretriever autotokenizer retriever realmretriever from_pretrained google realm orqa nq openqa tokenizer autotokenizer from_pretrained google realm orqa nq openqa model realmforopenqa from_pretrained google realm orqa nq openqa retriever retriever question who is the pioneer in modern computer science question_ids tokenizer question return_tensors pt answer_ids tokenizer alan mathison turing add_special_tokens false return_token_type_ids false return_attention_mask false input_ids reader_output predicted_answer_ids model question_ids answer_ids answer_ids return_dict false predicted_answer tokenizer decode predicted_answer_ids loss reader_output loss 1 projection_size cpu computation starts 1 block_emb_size 1 searcher_beam_size searcher_beam_size searcher_beam_size projection_size cpu computation ends retrieve possible answers searcher_beam_size
import math
import os
from dataclasses import dataclass
from typing import Optional, Tuple, Union

import torch
from torch import nn
from torch.nn import CrossEntropyLoss

from ...activations import ACT2FN
from ...modeling_outputs import (
    BaseModelOutputWithPastAndCrossAttentions,
    BaseModelOutputWithPoolingAndCrossAttentions,
    MaskedLMOutput,
    ModelOutput,
)
from ...modeling_utils import PreTrainedModel
from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
from .configuration_realm import RealmConfig


logger = logging.get_logger(__name__)
_EMBEDDER_CHECKPOINT_FOR_DOC = "google/realm-cc-news-pretrained-embedder"
_ENCODER_CHECKPOINT_FOR_DOC = "google/realm-cc-news-pretrained-encoder"
_SCORER_CHECKPOINT_FOR_DOC = "google/realm-cc-news-pretrained-scorer"
_CONFIG_FOR_DOC = "RealmConfig"

REALM_PRETRAINED_MODEL_ARCHIVE_LIST = [
    "google/realm-cc-news-pretrained-embedder",
    "google/realm-cc-news-pretrained-encoder",
    "google/realm-cc-news-pretrained-scorer",
    "google/realm-cc-news-pretrained-openqa",
    "google/realm-orqa-nq-openqa",
    "google/realm-orqa-nq-reader",
    "google/realm-orqa-wq-openqa",
    "google/realm-orqa-wq-reader",
    
]


def load_tf_weights_in_realm(model, config, tf_checkpoint_path):
    
    try:
        import re

        import numpy as np
        import tensorflow as tf
    except ImportError:
        logger.error(
            "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
            "https://www.tensorflow.org/install/ for installation instructions."
        )
        raise
    tf_path = os.path.abspath(tf_checkpoint_path)
    logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
    
    init_vars = tf.train.list_variables(tf_path)
    names = []
    arrays = []

    for name, shape in init_vars:
        logger.info(f"Loading TF weight {name} with shape {shape}")
        array = tf.train.load_variable(tf_path, name)
        names.append(name)
        arrays.append(array)

    for name, array in zip(names, arrays):
        if isinstance(model, RealmReader) and "reader" not in name:
            logger.info(f"Skipping {name} as it is not {model.__class__.__name__}'s parameter")
            continue

        
        if (name.startswith("bert") or name.startswith("cls")) and isinstance(model, RealmForOpenQA):
            name = name.replace("bert/", "reader/realm/")
            name = name.replace("cls/", "reader/cls/")

        
        if (name.startswith("bert") or name.startswith("cls")) and isinstance(model, RealmKnowledgeAugEncoder):
            name = name.replace("bert/", "realm/")

        
        if name.startswith("reader"):
            reader_prefix = "" if isinstance(model, RealmReader) else "reader/"
            name = name.replace("reader/module/bert/", f"{reader_prefix}realm/")
            name = name.replace("reader/module/cls/", f"{reader_prefix}cls/")
            name = name.replace("reader/dense/", f"{reader_prefix}qa_outputs/dense_intermediate/")
            name = name.replace("reader/dense_1/", f"{reader_prefix}qa_outputs/dense_output/")
            name = name.replace("reader/layer_normalization", f"{reader_prefix}qa_outputs/layer_normalization")

        
        if name.startswith("module/module/module/"):  
            embedder_prefix = "" if isinstance(model, RealmEmbedder) else "embedder/"
            name = name.replace("module/module/module/module/bert/", f"{embedder_prefix}realm/")
            name = name.replace("module/module/module/LayerNorm/", f"{embedder_prefix}cls/LayerNorm/")
            name = name.replace("module/module/module/dense/", f"{embedder_prefix}cls/dense/")
            name = name.replace("module/module/module/module/cls/predictions/", f"{embedder_prefix}cls/predictions/")
            name = name.replace("module/module/module/bert/", f"{embedder_prefix}realm/")
            name = name.replace("module/module/module/cls/predictions/", f"{embedder_prefix}cls/predictions/")
        elif name.startswith("module/module/"):  
            embedder_prefix = "" if isinstance(model, RealmEmbedder) else "embedder/"
            name = name.replace("module/module/LayerNorm/", f"{embedder_prefix}cls/LayerNorm/")
            name = name.replace("module/module/dense/", f"{embedder_prefix}cls/dense/")

        name = name.split("/")
        
        
        if any(
            n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"]
            for n in name
        ):
            logger.info(f"Skipping {'/'.join(name)}")
            continue
        pointer = model
        for m_name in name:
            if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
                scope_names = re.split(r"_(\d+)", m_name)
            else:
                scope_names = [m_name]
            if scope_names[0] == "kernel" or scope_names[0] == "gamma":
                pointer = getattr(pointer, "weight")
            elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
                pointer = getattr(pointer, "bias")
            else:
                try:
                    pointer = getattr(pointer, scope_names[0])
                except AttributeError:
                    logger.info(f"Skipping {'/'.join(name)}")
                    continue
            if len(scope_names) >= 2:
                num = int(scope_names[1])
                pointer = pointer[num]
        if m_name[-11:] == "_embeddings":
            pointer = getattr(pointer, "weight")
        elif m_name == "kernel":
            array = np.transpose(array)
        try:
            assert (
                pointer.shape == array.shape
            ), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"
        except AssertionError as e:
            e.args += (pointer.shape, array.shape)
            raise
        logger.info(f"Initialize PyTorch weight {name}")
        pointer.data = torch.from_numpy(array)
    return model



class RealmEmbeddings(nn.Module):
    

    def __init__(self, config):
        super().__init__()
        self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
        self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
        self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)

        
        
        self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
        self.dropout = nn.Dropout(config.hidden_dropout_prob)
        
        self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
        self.register_buffer(
            "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
        )
        self.register_buffer(
            "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
        )

    def forward(
        self,
        input_ids: Optional[torch.LongTensor] = None,
        token_type_ids: Optional[torch.LongTensor] = None,
        position_ids: Optional[torch.LongTensor] = None,
        inputs_embeds: Optional[torch.FloatTensor] = None,
        past_key_values_length: int = 0,
    ) -> torch.Tensor:
        if input_ids is not None:
            input_shape = input_ids.size()
        else:
            input_shape = inputs_embeds.size()[:-1]

        seq_length = input_shape[1]

        if position_ids is None:
            position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]

        
        
        
        if token_type_ids is None:
            if hasattr(self, "token_type_ids"):
                buffered_token_type_ids = self.token_type_ids[:, :seq_length]
                buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
                token_type_ids = buffered_token_type_ids_expanded
            else:
                token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)

        if inputs_embeds is None:
            inputs_embeds = self.word_embeddings(input_ids)
        token_type_embeddings = self.token_type_embeddings(token_type_ids)

        embeddings = inputs_embeds + token_type_embeddings
        if self.position_embedding_type == "absolute":
            position_embeddings = self.position_embeddings(position_ids)
            embeddings += position_embeddings
        embeddings = self.LayerNorm(embeddings)
        embeddings = self.dropout(embeddings)
        return embeddings



class RealmSelfAttention(nn.Module):
    def __init__(self, config, position_embedding_type=None):
        super().__init__()
        if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
            raise ValueError(
                f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
                f"heads ({config.num_attention_heads})"
            )

        self.num_attention_heads = config.num_attention_heads
        self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
        self.all_head_size = self.num_attention_heads * self.attention_head_size

        self.query = nn.Linear(config.hidden_size, self.all_head_size)
        self.key = nn.Linear(config.hidden_size, self.all_head_size)
        self.value = nn.Linear(config.hidden_size, self.all_head_size)

        self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
        self.position_embedding_type = position_embedding_type or getattr(
            config, "position_embedding_type", "absolute"
        )
        if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
            self.max_position_embeddings = config.max_position_embeddings
            self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)

        self.is_decoder = config.is_decoder

    def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
        new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
        x = x.view(new_x_shape)
        return x.permute(0, 2, 1, 3)

    def forward(
        self,
        hidden_states: torch.Tensor,
        attention_mask: Optional[torch.FloatTensor] = None,
        head_mask: Optional[torch.FloatTensor] = None,
        encoder_hidden_states: Optional[torch.FloatTensor] = None,
        encoder_attention_mask: Optional[torch.FloatTensor] = None,
        past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
        output_attentions: Optional[bool] = False,
    ) -> Tuple[torch.Tensor]:
        mixed_query_layer = self.query(hidden_states)

        
        
        
        is_cross_attention = encoder_hidden_states is not None

        if is_cross_attention and past_key_value is not None:
            
            key_layer = past_key_value[0]
            value_layer = past_key_value[1]
            attention_mask = encoder_attention_mask
        elif is_cross_attention:
            key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
            value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
            attention_mask = encoder_attention_mask
        elif past_key_value is not None:
            key_layer = self.transpose_for_scores(self.key(hidden_states))
            value_layer = self.transpose_for_scores(self.value(hidden_states))
            key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
            value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
        else:
            key_layer = self.transpose_for_scores(self.key(hidden_states))
            value_layer = self.transpose_for_scores(self.value(hidden_states))

        query_layer = self.transpose_for_scores(mixed_query_layer)

        use_cache = past_key_value is not None
        if self.is_decoder:
            
            
            
            
            
            
            
            past_key_value = (key_layer, value_layer)

        
        attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))

        if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
            query_length, key_length = query_layer.shape[2], key_layer.shape[2]
            if use_cache:
                position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view(
                    -1, 1
                )
            else:
                position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
            position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
            distance = position_ids_l - position_ids_r

            positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
            positional_embedding = positional_embedding.to(dtype=query_layer.dtype)  

            if self.position_embedding_type == "relative_key":
                relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
                attention_scores = attention_scores + relative_position_scores
            elif self.position_embedding_type == "relative_key_query":
                relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
                relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
                attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key

        attention_scores = attention_scores / math.sqrt(self.attention_head_size)
        if attention_mask is not None:
            
            attention_scores = attention_scores + attention_mask

        
        attention_probs = nn.functional.softmax(attention_scores, dim=-1)

        
        
        attention_probs = self.dropout(attention_probs)

        
        if head_mask is not None:
            attention_probs = attention_probs * head_mask

        context_layer = torch.matmul(attention_probs, value_layer)

        context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
        new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
        context_layer = context_layer.view(new_context_layer_shape)

        outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)

        if self.is_decoder:
            outputs = outputs + (past_key_value,)
        return outputs



class RealmSelfOutput(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.dense = nn.Linear(config.hidden_size, config.hidden_size)
        self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
        self.dropout = nn.Dropout(config.hidden_dropout_prob)

    def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
        hidden_states = self.dense(hidden_states)
        hidden_states = self.dropout(hidden_states)
        hidden_states = self.LayerNorm(hidden_states + input_tensor)
        return hidden_states



class RealmAttention(nn.Module):
    def __init__(self, config, position_embedding_type=None):
        super().__init__()
        self.self = RealmSelfAttention(config, position_embedding_type=position_embedding_type)
        self.output = RealmSelfOutput(config)
        self.pruned_heads = set()

    def prune_heads(self, heads):
        if len(heads) == 0:
            return
        heads, index = find_pruneable_heads_and_indices(
            heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
        )

        
        self.self.query = prune_linear_layer(self.self.query, index)
        self.self.key = prune_linear_layer(self.self.key, index)
        self.self.value = prune_linear_layer(self.self.value, index)
        self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)

        
        self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
        self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
        self.pruned_heads = self.pruned_heads.union(heads)

    def forward(
        self,
        hidden_states: torch.Tensor,
        attention_mask: Optional[torch.FloatTensor] = None,
        head_mask: Optional[torch.FloatTensor] = None,
        encoder_hidden_states: Optional[torch.FloatTensor] = None,
        encoder_attention_mask: Optional[torch.FloatTensor] = None,
        past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
        output_attentions: Optional[bool] = False,
    ) -> Tuple[torch.Tensor]:
        self_outputs = self.self(
            hidden_states,
            attention_mask,
            head_mask,
            encoder_hidden_states,
            encoder_attention_mask,
            past_key_value,
            output_attentions,
        )
        attention_output = self.output(self_outputs[0], hidden_states)
        outputs = (attention_output,) + self_outputs[1:]  
        return outputs



class RealmIntermediate(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
        if isinstance(config.hidden_act, str):
            self.intermediate_act_fn = ACT2FN[config.hidden_act]
        else:
            self.intermediate_act_fn = config.hidden_act

    def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
        hidden_states = self.dense(hidden_states)
        hidden_states = self.intermediate_act_fn(hidden_states)
        return hidden_states



class RealmOutput(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
        self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
        self.dropout = nn.Dropout(config.hidden_dropout_prob)

    def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
        hidden_states = self.dense(hidden_states)
        hidden_states = self.dropout(hidden_states)
        hidden_states = self.LayerNorm(hidden_states + input_tensor)
        return hidden_states



class RealmLayer(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.chunk_size_feed_forward = config.chunk_size_feed_forward
        self.seq_len_dim = 1
        self.attention = RealmAttention(config)
        self.is_decoder = config.is_decoder
        self.add_cross_attention = config.add_cross_attention
        if self.add_cross_attention:
            if not self.is_decoder:
                raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
            self.crossattention = RealmAttention(config, position_embedding_type="absolute")
        self.intermediate = RealmIntermediate(config)
        self.output = RealmOutput(config)

    def forward(
        self,
        hidden_states: torch.Tensor,
        attention_mask: Optional[torch.FloatTensor] = None,
        head_mask: Optional[torch.FloatTensor] = None,
        encoder_hidden_states: Optional[torch.FloatTensor] = None,
        encoder_attention_mask: Optional[torch.FloatTensor] = None,
        past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
        output_attentions: Optional[bool] = False,
    ) -> Tuple[torch.Tensor]:
        
        self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
        self_attention_outputs = self.attention(
            hidden_states,
            attention_mask,
            head_mask,
            output_attentions=output_attentions,
            past_key_value=self_attn_past_key_value,
        )
        attention_output = self_attention_outputs[0]

        
        if self.is_decoder:
            outputs = self_attention_outputs[1:-1]
            present_key_value = self_attention_outputs[-1]
        else:
            outputs = self_attention_outputs[1:]  

        cross_attn_present_key_value = None
        if self.is_decoder and encoder_hidden_states is not None:
            if not hasattr(self, "crossattention"):
                raise ValueError(
                    f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
                    " by setting `config.add_cross_attention=True`"
                )

            
            cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
            cross_attention_outputs = self.crossattention(
                attention_output,
                attention_mask,
                head_mask,
                encoder_hidden_states,
                encoder_attention_mask,
                cross_attn_past_key_value,
                output_attentions,
            )
            attention_output = cross_attention_outputs[0]
            outputs = outputs + cross_attention_outputs[1:-1]  

            
            cross_attn_present_key_value = cross_attention_outputs[-1]
            present_key_value = present_key_value + cross_attn_present_key_value

        layer_output = apply_chunking_to_forward(
            self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
        )
        outputs = (layer_output,) + outputs

        
        if self.is_decoder:
            outputs = outputs + (present_key_value,)

        return outputs

    def feed_forward_chunk(self, attention_output):
        intermediate_output = self.intermediate(attention_output)
        layer_output = self.output(intermediate_output, attention_output)
        return layer_output



class RealmEncoder(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.config = config
        self.layer = nn.ModuleList([RealmLayer(config) for _ in range(config.num_hidden_layers)])
        self.gradient_checkpointing = False

    def forward(
        self,
        hidden_states: torch.Tensor,
        attention_mask: Optional[torch.FloatTensor] = None,
        head_mask: Optional[torch.FloatTensor] = None,
        encoder_hidden_states: Optional[torch.FloatTensor] = None,
        encoder_attention_mask: Optional[torch.FloatTensor] = None,
        past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
        use_cache: Optional[bool] = None,
        output_attentions: Optional[bool] = False,
        output_hidden_states: Optional[bool] = False,
        return_dict: Optional[bool] = True,
    ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
        all_hidden_states = () if output_hidden_states else None
        all_self_attentions = () if output_attentions else None
        all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None

        if self.gradient_checkpointing and self.training:
            if use_cache:
                logger.warning_once(
                    "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
                )
                use_cache = False

        next_decoder_cache = () if use_cache else None
        for i, layer_module in enumerate(self.layer):
            if output_hidden_states:
                all_hidden_states = all_hidden_states + (hidden_states,)

            layer_head_mask = head_mask[i] if head_mask is not None else None
            past_key_value = past_key_values[i] if past_key_values is not None else None

            if self.gradient_checkpointing and self.training:
                layer_outputs = self._gradient_checkpointing_func(
                    layer_module.__call__,
                    hidden_states,
                    attention_mask,
                    layer_head_mask,
                    encoder_hidden_states,
                    encoder_attention_mask,
                    past_key_value,
                    output_attentions,
                )
            else:
                layer_outputs = layer_module(
                    hidden_states,
                    attention_mask,
                    layer_head_mask,
                    encoder_hidden_states,
                    encoder_attention_mask,
                    past_key_value,
                    output_attentions,
                )

            hidden_states = layer_outputs[0]
            if use_cache:
                next_decoder_cache += (layer_outputs[-1],)
            if output_attentions:
                all_self_attentions = all_self_attentions + (layer_outputs[1],)
                if self.config.add_cross_attention:
                    all_cross_attentions = all_cross_attentions + (layer_outputs[2],)

        if output_hidden_states:
            all_hidden_states = all_hidden_states + (hidden_states,)

        if not return_dict:
            return tuple(
                v
                for v in [
                    hidden_states,
                    next_decoder_cache,
                    all_hidden_states,
                    all_self_attentions,
                    all_cross_attentions,
                ]
                if v is not None
            )
        return BaseModelOutputWithPastAndCrossAttentions(
            last_hidden_state=hidden_states,
            past_key_values=next_decoder_cache,
            hidden_states=all_hidden_states,
            attentions=all_self_attentions,
            cross_attentions=all_cross_attentions,
        )



class RealmPooler(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.dense = nn.Linear(config.hidden_size, config.hidden_size)
        self.activation = nn.Tanh()

    def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
        
        
        first_token_tensor = hidden_states[:, 0]
        pooled_output = self.dense(first_token_tensor)
        pooled_output = self.activation(pooled_output)
        return pooled_output


@dataclass
class RealmEmbedderOutput(ModelOutput):
    

    projected_score: torch.FloatTensor = None
    hidden_states: Optional[Tuple[torch.FloatTensor]] = None
    attentions: Optional[Tuple[torch.FloatTensor]] = None


@dataclass
class RealmScorerOutput(ModelOutput):
    

    relevance_score: torch.FloatTensor = None
    query_score: torch.FloatTensor = None
    candidate_score: torch.FloatTensor = None


@dataclass
class RealmReaderOutput(ModelOutput):
    

    loss: torch.FloatTensor = None
    retriever_loss: torch.FloatTensor = None
    reader_loss: torch.FloatTensor = None
    retriever_correct: torch.BoolTensor = None
    reader_correct: torch.BoolTensor = None
    block_idx: torch.LongTensor = None
    candidate: torch.LongTensor = None
    start_pos: torch.int32 = None
    end_pos: torch.int32 = None
    hidden_states: Optional[Tuple[torch.FloatTensor]] = None
    attentions: Optional[Tuple[torch.FloatTensor]] = None


@dataclass
class RealmForOpenQAOutput(ModelOutput):
    

    reader_output: dict = None
    predicted_answer_ids: torch.LongTensor = None


class RealmPredictionHeadTransform(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.dense = nn.Linear(config.hidden_size, config.hidden_size)
        if isinstance(config.hidden_act, str):
            self.transform_act_fn = ACT2FN[config.hidden_act]
        else:
            self.transform_act_fn = config.hidden_act
        self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)

    def forward(self, hidden_states):
        hidden_states = self.dense(hidden_states)
        hidden_states = self.transform_act_fn(hidden_states)
        hidden_states = self.LayerNorm(hidden_states)
        return hidden_states


class RealmLMPredictionHead(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.transform = RealmPredictionHeadTransform(config)

        
        
        self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)

        self.bias = nn.Parameter(torch.zeros(config.vocab_size))

        
        self.decoder.bias = self.bias

    def forward(self, hidden_states):
        hidden_states = self.transform(hidden_states)
        hidden_states = self.decoder(hidden_states)
        return hidden_states


class RealmOnlyMLMHead(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.predictions = RealmLMPredictionHead(config)

    def forward(self, sequence_output):
        prediction_scores = self.predictions(sequence_output)
        return prediction_scores


class RealmScorerProjection(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.predictions = RealmLMPredictionHead(config)
        self.dense = nn.Linear(config.hidden_size, config.retriever_proj_size)
        self.LayerNorm = nn.LayerNorm(config.retriever_proj_size, eps=config.layer_norm_eps)

    def forward(self, hidden_states):
        hidden_states = self.dense(hidden_states)
        hidden_states = self.LayerNorm(hidden_states)
        return hidden_states


class RealmReaderProjection(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.config = config
        self.dense_intermediate = nn.Linear(config.hidden_size, config.span_hidden_size * 2)
        self.dense_output = nn.Linear(config.span_hidden_size, 1)
        self.layer_normalization = nn.LayerNorm(config.span_hidden_size, eps=config.reader_layer_norm_eps)
        self.relu = nn.ReLU()

    def forward(self, hidden_states, block_mask):
        def span_candidates(masks):
            
            _, max_sequence_len = masks.shape

            def _spans_given_width(width):
                current_starts = torch.arange(max_sequence_len - width + 1, device=masks.device)
                current_ends = torch.arange(width - 1, max_sequence_len, device=masks.device)
                return current_starts, current_ends

            starts, ends = zip(*(_spans_given_width(w + 1) for w in range(self.config.max_span_width)))

            
            starts = torch.cat(starts, 0)
            ends = torch.cat(ends, 0)

            
            start_masks = torch.index_select(masks, dim=-1, index=starts)
            end_masks = torch.index_select(masks, dim=-1, index=ends)
            span_masks = start_masks * end_masks

            return starts, ends, span_masks

        def mask_to_score(mask, dtype=torch.float32):
            return (1.0 - mask.type(dtype)) * torch.finfo(dtype).min

        
        hidden_states = self.dense_intermediate(hidden_states)
        
        start_projection, end_projection = hidden_states.chunk(2, dim=-1)

        candidate_starts, candidate_ends, candidate_mask = span_candidates(block_mask)

        candidate_start_projections = torch.index_select(start_projection, dim=1, index=candidate_starts)
        candidate_end_projections = torch.index_select(end_projection, dim=1, index=candidate_ends)
        candidate_hidden = candidate_start_projections + candidate_end_projections

        
        candidate_hidden = self.relu(candidate_hidden)
        
        candidate_hidden = self.layer_normalization(candidate_hidden)
        
        reader_logits = self.dense_output(candidate_hidden).squeeze(-1)
        
        reader_logits += mask_to_score(candidate_mask, dtype=reader_logits.dtype)

        return reader_logits, candidate_starts, candidate_ends


REALM_START_DOCSTRING = r

REALM_INPUTS_DOCSTRING = r


class RealmPreTrainedModel(PreTrainedModel):
    

    config_class = RealmConfig
    load_tf_weights = load_tf_weights_in_realm
    base_model_prefix = "realm"

    def _init_weights(self, module):
        
        if isinstance(module, nn.Linear):
            
            
            module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
            if module.bias is not None:
                module.bias.data.zero_()
        elif isinstance(module, nn.Embedding):
            module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
            if module.padding_idx is not None:
                module.weight.data[module.padding_idx].zero_()
        elif isinstance(module, nn.LayerNorm):
            module.bias.data.zero_()
            module.weight.data.fill_(1.0)

    def _flatten_inputs(self, *inputs):
        
        flattened_inputs = []
        for tensor in inputs:
            if tensor is None:
                flattened_inputs.append(None)
            else:
                input_shape = tensor.shape
                if len(input_shape) > 2:
                    tensor = tensor.view((-1, input_shape[-1]))
                flattened_inputs.append(tensor)
        return flattened_inputs


class RealmBertModel(RealmPreTrainedModel):
    

    def __init__(self, config, add_pooling_layer=True):
        super().__init__(config)
        self.config = config

        self.embeddings = RealmEmbeddings(config)
        self.encoder = RealmEncoder(config)

        self.pooler = RealmPooler(config) if add_pooling_layer else None

        
        
        self.post_init()

    def get_input_embeddings(self):
        return self.embeddings.word_embeddings

    def set_input_embeddings(self, value):
        self.embeddings.word_embeddings = value

    def _prune_heads(self, heads_to_prune):
        
        for layer, heads in heads_to_prune.items():
            self.encoder.layer[layer].attention.prune_heads(heads)

    def forward(
        self,
        input_ids=None,
        attention_mask=None,
        token_type_ids=None,
        position_ids=None,
        head_mask=None,
        inputs_embeds=None,
        encoder_hidden_states=None,
        encoder_attention_mask=None,
        past_key_values=None,
        use_cache=None,
        output_attentions=None,
        output_hidden_states=None,
        return_dict=None,
    ):
        output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
        output_hidden_states = (
            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
        )
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        if self.config.is_decoder:
            use_cache = use_cache if use_cache is not None else self.config.use_cache
        else:
            use_cache = False

        if input_ids is not None and inputs_embeds is not None:
            raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
        elif input_ids is not None:
            self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
            input_shape = input_ids.size()
        elif inputs_embeds is not None:
            input_shape = inputs_embeds.size()[:-1]
        else:
            raise ValueError("You have to specify either input_ids or inputs_embeds")

        batch_size, seq_length = input_shape
        device = input_ids.device if input_ids is not None else inputs_embeds.device

        
        past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0

        if attention_mask is None:
            attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)

        if token_type_ids is None:
            if hasattr(self.embeddings, "token_type_ids"):
                buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
                buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
                token_type_ids = buffered_token_type_ids_expanded
            else:
                token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)

        
        
        extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)

        
        
        if self.config.is_decoder and encoder_hidden_states is not None:
            encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
            encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
            if encoder_attention_mask is None:
                encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
            encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
        else:
            encoder_extended_attention_mask = None

        
        
        
        
        
        head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)

        embedding_output = self.embeddings(
            input_ids=input_ids,
            position_ids=position_ids,
            token_type_ids=token_type_ids,
            inputs_embeds=inputs_embeds,
            past_key_values_length=past_key_values_length,
        )
        encoder_outputs = self.encoder(
            embedding_output,
            attention_mask=extended_attention_mask,
            head_mask=head_mask,
            encoder_hidden_states=encoder_hidden_states,
            encoder_attention_mask=encoder_extended_attention_mask,
            past_key_values=past_key_values,
            use_cache=use_cache,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )
        sequence_output = encoder_outputs[0]
        pooled_output = self.pooler(sequence_output) if self.pooler is not None else None

        if not return_dict:
            return (sequence_output, pooled_output) + encoder_outputs[1:]

        return BaseModelOutputWithPoolingAndCrossAttentions(
            last_hidden_state=sequence_output,
            pooler_output=pooled_output,
            past_key_values=encoder_outputs.past_key_values,
            hidden_states=encoder_outputs.hidden_states,
            attentions=encoder_outputs.attentions,
            cross_attentions=encoder_outputs.cross_attentions,
        )


@add_start_docstrings(
    "The embedder of REALM outputting projected score that will be used to calculate relevance score.",
    REALM_START_DOCSTRING,
)
class RealmEmbedder(RealmPreTrainedModel):
    _tied_weights_keys = ["cls.predictions.decoder.bias"]

    def __init__(self, config):
        super().__init__(config)

        self.realm = RealmBertModel(self.config)
        self.cls = RealmScorerProjection(self.config)
        self.post_init()

    def get_input_embeddings(self):
        return self.realm.embeddings.word_embeddings

    def set_input_embeddings(self, value):
        self.realm.embeddings.word_embeddings = value

    @add_start_docstrings_to_model_forward(REALM_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
    @replace_return_docstrings(output_type=RealmEmbedderOutput, config_class=_CONFIG_FOR_DOC)
    def forward(
        self,
        input_ids: Optional[torch.LongTensor] = None,
        attention_mask: Optional[torch.FloatTensor] = None,
        token_type_ids: Optional[torch.LongTensor] = None,
        position_ids: Optional[torch.LongTensor] = None,
        head_mask: Optional[torch.FloatTensor] = None,
        inputs_embeds: Optional[torch.FloatTensor] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
    ) -> Union[Tuple, RealmEmbedderOutput]:
        r

        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        realm_outputs = self.realm(
            input_ids,
            attention_mask=attention_mask,
            token_type_ids=token_type_ids,
            position_ids=position_ids,
            head_mask=head_mask,
            inputs_embeds=inputs_embeds,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )

        
        pooler_output = realm_outputs[1]
        
        projected_score = self.cls(pooler_output)

        if not return_dict:
            return (projected_score,) + realm_outputs[2:4]
        else:
            return RealmEmbedderOutput(
                projected_score=projected_score,
                hidden_states=realm_outputs.hidden_states,
                attentions=realm_outputs.attentions,
            )


@add_start_docstrings(
    "The scorer of REALM outputting relevance scores representing the score of document candidates (before softmax).",
    REALM_START_DOCSTRING,
)
class RealmScorer(RealmPreTrainedModel):
    r

    def __init__(self, config, query_embedder=None):
        super().__init__(config)

        self.embedder = RealmEmbedder(self.config)

        self.query_embedder = query_embedder if query_embedder is not None else self.embedder

        self.post_init()

    @add_start_docstrings_to_model_forward(REALM_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
    @replace_return_docstrings(output_type=RealmScorerOutput, config_class=_CONFIG_FOR_DOC)
    def forward(
        self,
        input_ids: Optional[torch.LongTensor] = None,
        attention_mask: Optional[torch.FloatTensor] = None,
        token_type_ids: Optional[torch.LongTensor] = None,
        position_ids: Optional[torch.LongTensor] = None,
        candidate_input_ids: Optional[torch.LongTensor] = None,
        candidate_attention_mask: Optional[torch.FloatTensor] = None,
        candidate_token_type_ids: Optional[torch.LongTensor] = None,
        candidate_inputs_embeds: Optional[torch.FloatTensor] = None,
        head_mask: Optional[torch.FloatTensor] = None,
        inputs_embeds: Optional[torch.FloatTensor] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
    ) -> Union[Tuple, RealmScorerOutput]:
        r

        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        if input_ids is None and inputs_embeds is None:
            raise ValueError("You have to specify either input_ids or input_embeds.")

        if candidate_input_ids is None and candidate_inputs_embeds is None:
            raise ValueError("You have to specify either candidate_input_ids or candidate_inputs_embeds.")

        query_outputs = self.query_embedder(
            input_ids,
            attention_mask=attention_mask,
            token_type_ids=token_type_ids,
            position_ids=position_ids,
            head_mask=head_mask,
            inputs_embeds=inputs_embeds,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )

        
        (flattened_input_ids, flattened_attention_mask, flattened_token_type_ids) = self._flatten_inputs(
            candidate_input_ids, candidate_attention_mask, candidate_token_type_ids
        )

        candidate_outputs = self.embedder(
            flattened_input_ids,
            attention_mask=flattened_attention_mask,
            token_type_ids=flattened_token_type_ids,
            position_ids=position_ids,
            head_mask=head_mask,
            inputs_embeds=candidate_inputs_embeds,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )

        
        query_score = query_outputs[0]
        
        candidate_score = candidate_outputs[0]
        
        candidate_score = candidate_score.view(-1, self.config.num_candidates, self.config.retriever_proj_size)
        
        relevance_score = torch.einsum("bd,bnd->bn", query_score, candidate_score)

        if not return_dict:
            return relevance_score, query_score, candidate_score

        return RealmScorerOutput(
            relevance_score=relevance_score, query_score=query_score, candidate_score=candidate_score
        )


@add_start_docstrings(
    "The knowledge-augmented encoder of REALM outputting masked language model logits and marginal log-likelihood"
    " loss.",
    REALM_START_DOCSTRING,
)
class RealmKnowledgeAugEncoder(RealmPreTrainedModel):
    _tied_weights_keys = ["cls.predictions.decoder"]

    def __init__(self, config):
        super().__init__(config)
        self.realm = RealmBertModel(self.config)
        self.cls = RealmOnlyMLMHead(self.config)
        self.post_init()

    def get_input_embeddings(self):
        return self.realm.embeddings.word_embeddings

    def set_input_embeddings(self, value):
        self.realm.embeddings.word_embeddings = value

    def get_output_embeddings(self):
        return self.cls.predictions.decoder

    def set_output_embeddings(self, new_embeddings):
        self.cls.predictions.decoder = new_embeddings

    @add_start_docstrings_to_model_forward(
        REALM_INPUTS_DOCSTRING.format("batch_size, num_candidates, sequence_length")
    )
    @replace_return_docstrings(output_type=MaskedLMOutput, config_class=_CONFIG_FOR_DOC)
    def forward(
        self,
        input_ids: Optional[torch.LongTensor] = None,
        attention_mask: Optional[torch.FloatTensor] = None,
        token_type_ids: Optional[torch.LongTensor] = None,
        position_ids: Optional[torch.LongTensor] = None,
        head_mask: Optional[torch.FloatTensor] = None,
        inputs_embeds: Optional[torch.FloatTensor] = None,
        relevance_score: Optional[torch.FloatTensor] = None,
        labels: Optional[torch.LongTensor] = None,
        mlm_mask: Optional[torch.LongTensor] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
    ) -> Union[Tuple, MaskedLMOutput]:
        r

        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        (flattened_input_ids, flattened_attention_mask, flattened_token_type_ids) = self._flatten_inputs(
            input_ids, attention_mask, token_type_ids
        )

        joint_outputs = self.realm(
            flattened_input_ids,
            attention_mask=flattened_attention_mask,
            token_type_ids=flattened_token_type_ids,
            position_ids=position_ids,
            head_mask=head_mask,
            inputs_embeds=inputs_embeds,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )

        
        joint_output = joint_outputs[0]
        
        prediction_scores = self.cls(joint_output)
        
        candidate_score = relevance_score

        masked_lm_loss = None
        if labels is not None:
            if candidate_score is None:
                raise ValueError(
                    "You have to specify `relevance_score` when `labels` is specified in order to compute loss."
                )

            batch_size, seq_length = labels.size()

            if mlm_mask is None:
                mlm_mask = torch.ones_like(labels, dtype=torch.float32)
            else:
                mlm_mask = mlm_mask.type(torch.float32)

            
            loss_fct = CrossEntropyLoss(reduction="none")  

            
            mlm_logits = prediction_scores.view(-1, self.config.vocab_size)
            
            mlm_targets = labels.tile(1, self.config.num_candidates).view(-1)
            
            masked_lm_log_prob = -loss_fct(mlm_logits, mlm_targets).view(
                batch_size, self.config.num_candidates, seq_length
            )
            
            candidate_log_prob = candidate_score.log_softmax(-1).unsqueeze(-1)
            
            joint_gold_log_prob = candidate_log_prob + masked_lm_log_prob
            
            marginal_gold_log_probs = joint_gold_log_prob.logsumexp(1)
            
            masked_lm_loss = -torch.nansum(torch.sum(marginal_gold_log_probs * mlm_mask) / torch.sum(mlm_mask))

        if not return_dict:
            output = (prediction_scores,) + joint_outputs[2:4]
            return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output

        return MaskedLMOutput(
            loss=masked_lm_loss,
            logits=prediction_scores,
            hidden_states=joint_outputs.hidden_states,
            attentions=joint_outputs.attentions,
        )


@add_start_docstrings("The reader of REALM.", REALM_START_DOCSTRING)
class RealmReader(RealmPreTrainedModel):
    def __init__(self, config):
        super().__init__(config)
        self.num_labels = config.num_labels

        self.realm = RealmBertModel(config)
        self.cls = RealmOnlyMLMHead(config)
        self.qa_outputs = RealmReaderProjection(config)

        self.post_init()

    @add_start_docstrings_to_model_forward(REALM_INPUTS_DOCSTRING.format("reader_beam_size, sequence_length"))
    @replace_return_docstrings(output_type=RealmReaderOutput, config_class=_CONFIG_FOR_DOC)
    def forward(
        self,
        input_ids: Optional[torch.LongTensor] = None,
        attention_mask: Optional[torch.FloatTensor] = None,
        token_type_ids: Optional[torch.LongTensor] = None,
        position_ids: Optional[torch.LongTensor] = None,
        head_mask: Optional[torch.FloatTensor] = None,
        inputs_embeds: Optional[torch.FloatTensor] = None,
        relevance_score: Optional[torch.FloatTensor] = None,
        block_mask: Optional[torch.BoolTensor] = None,
        start_positions: Optional[torch.LongTensor] = None,
        end_positions: Optional[torch.LongTensor] = None,
        has_answers: Optional[torch.BoolTensor] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
    ) -> Union[Tuple, RealmReaderOutput]:
        r
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        if relevance_score is None:
            raise ValueError("You have to specify `relevance_score` to calculate logits and loss.")
        if block_mask is None:
            raise ValueError("You have to specify `block_mask` to separate question block and evidence block.")
        if token_type_ids.size(1) < self.config.max_span_width:
            raise ValueError("The input sequence length must be greater than or equal to config.max_span_width.")
        outputs = self.realm(
            input_ids,
            attention_mask=attention_mask,
            token_type_ids=token_type_ids,
            position_ids=position_ids,
            head_mask=head_mask,
            inputs_embeds=inputs_embeds,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )

        
        sequence_output = outputs[0]

        
        reader_logits, candidate_starts, candidate_ends = self.qa_outputs(
            sequence_output, block_mask[0 : self.config.reader_beam_size]
        )
        
        retriever_logits = torch.unsqueeze(relevance_score[0 : self.config.reader_beam_size], -1)
        
        reader_logits += retriever_logits
        
        predicted_block_index = torch.argmax(torch.max(reader_logits, dim=1).values)
        
        predicted_candidate = torch.argmax(torch.max(reader_logits, dim=0).values)
        
        predicted_start = torch.index_select(candidate_starts, dim=0, index=predicted_candidate)
        
        predicted_end = torch.index_select(candidate_ends, dim=0, index=predicted_candidate)

        total_loss = None
        retriever_loss = None
        reader_loss = None
        retriever_correct = None
        reader_correct = None
        if start_positions is not None and end_positions is not None and has_answers is not None:

            def compute_correct_candidates(candidate_starts, candidate_ends, gold_starts, gold_ends):
                
                
                is_gold_start = torch.eq(
                    torch.unsqueeze(torch.unsqueeze(candidate_starts, 0), 0), torch.unsqueeze(gold_starts, -1)
                )
                is_gold_end = torch.eq(
                    torch.unsqueeze(torch.unsqueeze(candidate_ends, 0), 0), torch.unsqueeze(gold_ends, -1)
                )

                
                return torch.any(torch.logical_and(is_gold_start, is_gold_end), 1)

            def marginal_log_loss(logits, is_correct):
                

                def mask_to_score(mask, dtype=torch.float32):
                    return (1.0 - mask.type(dtype)) * torch.finfo(dtype).min

                
                log_numerator = torch.logsumexp(logits + mask_to_score(is_correct, dtype=logits.dtype), dim=-1)
                log_denominator = torch.logsumexp(logits, dim=-1)
                return log_denominator - log_numerator

            
            
            ignored_index = sequence_output.size(1)
            start_positions = start_positions.clamp(-1, ignored_index)
            end_positions = end_positions.clamp(-1, ignored_index)

            retriever_correct = has_answers
            any_retriever_correct = torch.any(retriever_correct)

            reader_correct = compute_correct_candidates(
                candidate_starts=candidate_starts,
                candidate_ends=candidate_ends,
                gold_starts=start_positions[0 : self.config.reader_beam_size],
                gold_ends=end_positions[0 : self.config.reader_beam_size],
            )
            any_reader_correct = torch.any(reader_correct)

            retriever_loss = marginal_log_loss(relevance_score, retriever_correct)
            reader_loss = marginal_log_loss(reader_logits.view(-1), reader_correct.view(-1))
            retriever_loss *= any_retriever_correct.type(torch.float32)
            reader_loss *= any_reader_correct.type(torch.float32)

            total_loss = (retriever_loss + reader_loss).mean()

        if not return_dict:
            output = (predicted_block_index, predicted_candidate, predicted_start, predicted_end) + outputs[2:]
            return (
                ((total_loss, retriever_loss, reader_loss, retriever_correct, reader_correct) + output)
                if total_loss is not None
                else output
            )

        return RealmReaderOutput(
            loss=total_loss,
            retriever_loss=retriever_loss,
            reader_loss=reader_loss,
            retriever_correct=retriever_correct,
            reader_correct=reader_correct,
            block_idx=predicted_block_index,
            candidate=predicted_candidate,
            start_pos=predicted_start,
            end_pos=predicted_end,
            hidden_states=outputs.hidden_states,
            attentions=outputs.attentions,
        )


REALM_FOR_OPEN_QA_DOCSTRING = r


@add_start_docstrings(
    "`RealmForOpenQA` for end-to-end open domain question answering.",
    REALM_START_DOCSTRING,
)
class RealmForOpenQA(RealmPreTrainedModel):
    def __init__(self, config, retriever=None):
        super().__init__(config)
        self.embedder = RealmEmbedder(config)
        self.reader = RealmReader(config)
        self.register_buffer(
            "block_emb",
            torch.zeros(()).new_empty(
                size=(config.num_block_records, config.retriever_proj_size),
                dtype=torch.float32,
                device=torch.device("cpu"),
            ),
        )
        self.retriever = retriever

        self.post_init()

    @property
    def searcher_beam_size(self):
        if self.training:
            return self.config.searcher_beam_size
        return self.config.reader_beam_size

    def block_embedding_to(self, device):
        

        self.block_emb = self.block_emb.to(device)

    @add_start_docstrings_to_model_forward(REALM_FOR_OPEN_QA_DOCSTRING.format("1, sequence_length"))
    @replace_return_docstrings(output_type=RealmForOpenQAOutput, config_class=_CONFIG_FOR_DOC)
    def forward(
        self,
        input_ids: Optional[torch.LongTensor],
        attention_mask: Optional[torch.FloatTensor] = None,
        token_type_ids: Optional[torch.LongTensor] = None,
        answer_ids: Optional[torch.LongTensor] = None,
        return_dict: Optional[bool] = None,
    ) -> Union[Tuple, RealmForOpenQAOutput]:
        r

        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        if input_ids is not None and input_ids.shape[0] != 1:
            raise ValueError("The batch_size of the inputs must be 1.")

        question_outputs = self.embedder(
            input_ids=input_ids, token_type_ids=token_type_ids, attention_mask=attention_mask, return_dict=True
        )
        
        question_projection = question_outputs[0]

        
        
        batch_scores = torch.einsum("BD,QD->QB", self.block_emb, question_projection.to(self.block_emb.device))
        
        _, retrieved_block_ids = torch.topk(batch_scores, k=self.searcher_beam_size, dim=-1)
        
        retrieved_block_ids = retrieved_block_ids.squeeze()
        
        retrieved_block_emb = torch.index_select(self.block_emb, dim=0, index=retrieved_block_ids)
        

        
        has_answers, start_pos, end_pos, concat_inputs = self.retriever(
            retrieved_block_ids.cpu(), input_ids, answer_ids, max_length=self.config.reader_seq_len
        )

        concat_inputs = concat_inputs.to(self.reader.device)
        block_mask = concat_inputs.special_tokens_mask.type(torch.bool).to(device=self.reader.device)
        block_mask.logical_not_().logical_and_(concat_inputs.token_type_ids.type(torch.bool))

        if has_answers is not None:
            has_answers = torch.tensor(has_answers, dtype=torch.bool, device=self.reader.device)
            start_pos = torch.tensor(start_pos, dtype=torch.long, device=self.reader.device)
            end_pos = torch.tensor(end_pos, dtype=torch.long, device=self.reader.device)

        
        retrieved_logits = torch.einsum(
            "D,BD->B", question_projection.squeeze(), retrieved_block_emb.to(self.reader.device)
        )

        reader_output = self.reader(
            input_ids=concat_inputs.input_ids[0 : self.config.reader_beam_size],
            attention_mask=concat_inputs.attention_mask[0 : self.config.reader_beam_size],
            token_type_ids=concat_inputs.token_type_ids[0 : self.config.reader_beam_size],
            relevance_score=retrieved_logits,
            block_mask=block_mask,
            has_answers=has_answers,
            start_positions=start_pos,
            end_positions=end_pos,
            return_dict=True,
        )

        predicted_block = concat_inputs.input_ids[reader_output.block_idx]
        predicted_answer_ids = predicted_block[reader_output.start_pos : reader_output.end_pos + 1]

        if not return_dict:
            return reader_output, predicted_answer_ids

        return RealmForOpenQAOutput(
            reader_output=reader_output,
            predicted_answer_ids=predicted_answer_ids,
        )