U
    9%e                    @   s  d dl Z d dlZd dlZd dlmZ d dlmZmZmZ d dl	Z	d dl	m
Z
 d dlmZmZmZ ddlmZ ddlmZmZmZmZmZmZmZmZ dd	lmZ dd
lmZmZ ddlm Z m!Z!m"Z"m#Z#m$Z$m%Z% ddl&m'Z' e$(e)Z*dZ+dZ,dZ-dZ.dZ/dZ0dZ1dZ2dZ3dZ4dZ5dZ6dZ7dgZ8dd Z9G dd de
j:Z;e
j<e;dZ=G d d! d!e
j:Z>G d"d# d#e
j:Z?G d$d% d%e
j:Z@G d&d' d'e
j:ZAG d(d) d)e
j:ZBG d*d+ d+e
j:ZCG d,d- d-e
j:ZDG d.d/ d/e
j:ZEG d0d1 d1e
j:ZFG d2d3 d3e
j:ZGG d4d5 d5e
j:ZHG d6d7 d7e
j:ZIG d8d9 d9e
j:ZJG d:d; d;e
j:ZKG d<d= d=e
j:ZLG d>d? d?e
j:ZMG d@dA dAe
j:ZNG dBdC dCe
j:ZOG dDdE dEeZPeG dFdG dGe ZQdHZRdIZSe"dJeRG dKdL dLePZTe"dMeRG dNdO dOePZUe"dPeRG dQdR dRePZVG dSdT dTe
j:ZWe"dUeRG dVdW dWePZXe"dXeRG dYdZ dZePZYe"d[eRG d\d] d]ePZZe"d^eRG d_d` d`ePZ[e"daeRG dbdc dcePZ\dS )d    N)	dataclass)OptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)BaseModelOutputBaseModelOutputWithPoolingMaskedLMOutputMultipleChoiceModelOutputNextSentencePredictorOutputQuestionAnsweringModelOutputSequenceClassifierOutputTokenClassifierOutput)PreTrainedModel) find_pruneable_heads_and_indicesprune_linear_layer)ModelOutputadd_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardloggingreplace_return_docstrings   )MobileBertConfigzgoogle/mobilebert-uncasedr   z mrm8488/mobilebert-finetuned-nerzK['I-ORG', 'I-ORG', 'O', 'O', 'O', 'O', 'O', 'I-LOC', 'O', 'I-LOC', 'I-LOC']gQ?z#csarron/mobilebert-uncased-squad-v2z'a nice puppet'gףp=
@      zlordtt13/emo-mobilebertz'others'z4.72c                 C   s  zddl }ddl}ddl}W n  tk
r<   td  Y nX tj|}t	d|  |j
|}g }g }	|D ]@\}
}t	d|
 d|  |j
||
}||
 |	| qrt||	D ]F\}
}|
dd}
|
d	d
}
|
dd}
|
dd}
|
d}
tdd |
D r.t	dd|
  q| }|
D ]}|d|rX|d|}n|g}|d dksz|d dkrt|d}n|d dks|d dkrt|d}nz|d dkrt|d}n`|d dkrt|d}nFzt||d }W n2 tk
r&   t	dd|
  Y q6Y nX t|dkr6t|d }|| }q6|d d d!krlt|d}n|dkr||}z,|j|jkstd"|j d#|j d$W n< tk
r } z| j|j|jf7  _ W 5 d}~X Y nX t	d%|
  t||_q| S )&z'Load tf checkpoints in a pytorch model.r   NzLoading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.z&Converting TensorFlow checkpoint from zLoading TF weight z with shape Z	ffn_layerffnZFakeLayerNorm	LayerNormZextra_output_weightszdense/kernelZbert
mobilebert/c                 s   s   | ]}|d kV  qdS ))Zadam_vZadam_mZAdamWeightDecayOptimizerZAdamWeightDecayOptimizer_1Zglobal_stepN ).0nr%   r%   q/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/transformers/models/mobilebert/modeling_mobilebert.py	<genexpr>s   s   z0load_tf_weights_in_mobilebert.<locals>.<genexpr>z	Skipping z[A-Za-z]+_\d+z_(\d+)ZkernelgammaweightZoutput_biasbetabiasZoutput_weightsZsquad
classifier   r   iZ_embeddingszPointer shape z and array shape z mismatchedzInitialize PyTorch weight )renumpyZ
tensorflowImportErrorloggererrorospathabspathinfotrainZlist_variablesZload_variableappendzipreplacesplitanyjoin	fullmatchgetattrAttributeErrorlenint	transposeshapeAssertionErrorargstorchZ
from_numpydata)modelconfigZtf_checkpoint_pathr0   nptfZtf_pathZ	init_varsnamesZarraysnamerF   arrayZpointerZm_nameZscope_namesnumer%   r%   r(   load_tf_weights_in_mobilebertR   s    






rT   c                       s2   e Zd Zd fdd	ZejejdddZ  ZS )NoNormNc                    s2   t    tt|| _tt|| _d S N)	super__init__r   	ParameterrI   zerosr-   onesr+   )selfZ	feat_sizeeps	__class__r%   r(   rX      s    
zNoNorm.__init__)input_tensorreturnc                 C   s   || j  | j S rV   )r+   r-   )r\   r`   r%   r%   r(   forward   s    zNoNorm.forward)N__name__
__module____qualname__rX   rI   Tensorrb   __classcell__r%   r%   r^   r(   rU      s   rU   )
layer_normZno_normc                       sR   e Zd ZdZ fddZdeej eej eej eej ej	dddZ
  ZS )	MobileBertEmbeddingszGConstruct the embeddings from word, position and token_type embeddings.c                    s   t    |j| _|j| _|j| _tj|j|j|jd| _	t|j
|j| _t|j|j| _| jrhdnd}| j| }t||j| _t|j |j| _t|j| _| jdt|j
ddd d S )N)padding_idxr
   r   position_ids)r   F)
persistent)rW   rX   trigram_inputembedding_sizehidden_sizer   	Embedding
vocab_sizeZpad_token_idword_embeddingsZmax_position_embeddingsposition_embeddingsZtype_vocab_sizetoken_type_embeddingsLinearembedding_transformationNORM2FNnormalization_typer"   Dropouthidden_dropout_probdropoutZregister_bufferrI   Zarangeexpand)r\   rL   Zembed_dim_multiplierZembedded_input_sizer^   r%   r(   rX      s"    

  zMobileBertEmbeddings.__init__N)	input_idstoken_type_idsrl   inputs_embedsra   c           
      C   s<  |d k	r|  }n|  d d }|d }|d krH| jd d d |f }|d krftj|tj| jjd}|d krx| |}| jrtjt	j
j|d d dd f ddddddgdd|t	j
j|d d d df ddddddgddgdd}| js| j| jkr| |}| |}| |}|| | }	| |	}	| |	}	|	S )	Nrm   r   dtypedevicer           )valuer/   dim)sizerl   rI   rZ   longr   rt   ro   catr   
functionalpadrp   rq   rx   ru   rv   r"   r}   )
r\   r   r   rl   r   input_shapeZ
seq_lengthru   rv   
embeddingsr%   r%   r(   rb      s4    

,,




zMobileBertEmbeddings.forward)NNNN)rd   re   rf   __doc__rX   r   rI   
LongTensorFloatTensorrg   rb   rh   r%   r%   r^   r(   rj      s       rj   c                	       s\   e Zd Z fddZdd Zd	ejejejeej eej ee	 e
ej dddZ  ZS )
MobileBertSelfAttentionc                    s   t    |j| _t|j|j | _| j| j | _t|j| j| _	t|j| j| _
t|jrf|jn|j| j| _t|j| _d S rV   )rW   rX   num_attention_headsrD   true_hidden_sizeattention_head_sizeall_head_sizer   rw   querykeyuse_bottleneck_attentionrq   r   r{   Zattention_probs_dropout_probr}   r\   rL   r^   r%   r(   rX      s    
 z MobileBertSelfAttention.__init__c                 C   s6   |  d d | j| jf }||}|ddddS )Nrm   r   r/   r   r
   )r   r   r   viewpermute)r\   xZnew_x_shaper%   r%   r(   transpose_for_scores  s    
z,MobileBertSelfAttention.transpose_for_scoresN)query_tensor
key_tensorvalue_tensorattention_mask	head_maskoutput_attentionsra   c                 C   s   |  |}| |}| |}	| |}
| |}| |	}t|
|dd}|t| j	 }|d k	rp|| }t
jj|dd}| |}|d k	r|| }t||}|dddd }| d d | jf }||}|r||fn|f}|S )Nrm   r   r   r/   r   r
   )r   r   r   r   rI   matmulrE   mathsqrtr   r   r   Zsoftmaxr}   r   
contiguousr   r   r   )r\   r   r   r   r   r   r   Zmixed_query_layerZmixed_key_layerZmixed_value_layerZquery_layerZ	key_layerZvalue_layerZattention_scoresZattention_probsZcontext_layerZnew_context_layer_shapeoutputsr%   r%   r(   rb     s(    	







zMobileBertSelfAttention.forward)NNN)rd   re   rf   rX   r   rI   rg   r   r   boolr   rb   rh   r%   r%   r^   r(   r      s   
   r   c                       s4   e Zd Z fddZejejejdddZ  ZS )MobileBertSelfOutputc                    sT   t    |j| _t|j|j| _t|j |j|j	d| _
| jsPt|j| _d S Nr]   )rW   rX   use_bottleneckr   rw   r   densery   rz   layer_norm_epsr"   r{   r|   r}   r   r^   r%   r(   rX   4  s    
zMobileBertSelfOutput.__init__hidden_statesresidual_tensorra   c                 C   s,   |  |}| js| |}| || }|S rV   )r   r   r}   r"   r\   r   r   layer_outputsr%   r%   r(   rb   <  s
    

zMobileBertSelfOutput.forwardrc   r%   r%   r^   r(   r   3  s   r   c                
       s`   e Zd Z fddZdd Zd	ejejejejeej eej ee	 e
ej dddZ  ZS )
MobileBertAttentionc                    s*   t    t|| _t|| _t | _d S rV   )rW   rX   r   r\   r   outputsetpruned_headsr   r^   r%   r(   rX   E  s    


zMobileBertAttention.__init__c                 C   s   t |dkrd S t|| jj| jj| j\}}t| jj|| j_t| jj|| j_t| jj	|| j_	t| j
j|dd| j
_| jjt | | j_| jj| jj | j_| j|| _d S )Nr   r   r   )rC   r   r\   r   r   r   r   r   r   r   r   r   r   union)r\   headsindexr%   r%   r(   prune_headsK  s       zMobileBertAttention.prune_headsN)r   r   r   layer_inputr   r   r   ra   c                 C   s:   |  ||||||}| |d |}	|	f|dd   }
|
S )Nr   r   )r\   r   )r\   r   r   r   r   r   r   r   Zself_outputsattention_outputr   r%   r%   r(   rb   ]  s    

zMobileBertAttention.forward)NNN)rd   re   rf   rX   r   rI   rg   r   r   r   r   rb   rh   r%   r%   r^   r(   r   D  s      r   c                       s0   e Zd Z fddZejejdddZ  ZS )MobileBertIntermediatec                    sB   t    t|j|j| _t|jt	r6t
|j | _n|j| _d S rV   )rW   rX   r   rw   r   intermediate_sizer   
isinstance
hidden_actstrr   intermediate_act_fnr   r^   r%   r(   rX   w  s
    
zMobileBertIntermediate.__init__r   ra   c                 C   s   |  |}| |}|S rV   )r   r   r\   r   r%   r%   r(   rb     s    

zMobileBertIntermediate.forwardrc   r%   r%   r^   r(   r   v  s   r   c                       s4   e Zd Z fddZejejejdddZ  ZS )OutputBottleneckc                    sF   t    t|j|j| _t|j |j|j	d| _
t|j| _d S r   )rW   rX   r   rw   r   rq   r   ry   rz   r   r"   r{   r|   r}   r   r^   r%   r(   rX     s    
zOutputBottleneck.__init__r   c                 C   s&   |  |}| |}| || }|S rV   )r   r}   r"   r   r%   r%   r(   rb     s    

zOutputBottleneck.forwardrc   r%   r%   r^   r(   r     s   r   c                       s8   e Zd Z fddZejejejejdddZ  ZS )MobileBertOutputc                    sZ   t    |j| _t|j|j| _t|j	 |j| _
| jsLt|j| _n
t|| _d S rV   )rW   rX   r   r   rw   r   r   r   ry   rz   r"   r{   r|   r}   r   
bottleneckr   r^   r%   r(   rX     s    
zMobileBertOutput.__init__)intermediate_statesresidual_tensor_1residual_tensor_2ra   c                 C   sH   |  |}| js*| |}| || }n| || }| ||}|S rV   )r   r   r}   r"   r   )r\   r   r   r   layer_outputr%   r%   r(   rb     s    

zMobileBertOutput.forwardrc   r%   r%   r^   r(   r     s     r   c                       s0   e Zd Z fddZejejdddZ  ZS )BottleneckLayerc                    s8   t    t|j|j| _t|j |j|j	d| _
d S r   )rW   rX   r   rw   rq   Zintra_bottleneck_sizer   ry   rz   r   r"   r   r^   r%   r(   rX     s    
zBottleneckLayer.__init__r   c                 C   s   |  |}| |}|S rV   r   r"   )r\   r   r   r%   r%   r(   rb     s    

zBottleneckLayer.forwardrc   r%   r%   r^   r(   r     s   r   c                       s4   e Zd Z fddZejeej dddZ  ZS )
Bottleneckc                    s8   t    |j| _|j| _t|| _| jr4t|| _d S rV   )rW   rX   key_query_shared_bottleneckr   r   input	attentionr   r^   r%   r(   rX     s    

zBottleneck.__init__r   c                 C   sF   |  |}| jr|fd S | jr6| |}||||fS ||||fS d S )N   )r   r   r   r   )r\   r   Zbottlenecked_hidden_statesZshared_attention_inputr%   r%   r(   rb     s    


zBottleneck.forward	rd   re   rf   rX   rI   rg   r   rb   rh   r%   r%   r^   r(   r     s   r   c                       s4   e Zd Z fddZejejejdddZ  ZS )	FFNOutputc                    s8   t    t|j|j| _t|j |j|j	d| _
d S r   )rW   rX   r   rw   r   r   r   ry   rz   r   r"   r   r^   r%   r(   rX     s    
zFFNOutput.__init__r   c                 C   s   |  |}| || }|S rV   r   r   r%   r%   r(   rb     s    
zFFNOutput.forwardrc   r%   r%   r^   r(   r     s   r   c                       s0   e Zd Z fddZejejdddZ  ZS )FFNLayerc                    s"   t    t|| _t|| _d S rV   )rW   rX   r   intermediater   r   r   r^   r%   r(   rX     s    

zFFNLayer.__init__r   c                 C   s   |  |}| ||}|S rV   )r   r   )r\   r   intermediate_outputr   r%   r%   r(   rb     s    
zFFNLayer.forwardrc   r%   r%   r^   r(   r     s   r   c                       sL   e Zd Z fddZdejeej eej ee e	ej dddZ
  ZS )MobileBertLayerc                    sz   t     j| _ j| _t | _t | _t | _	| jrHt
 | _ jdkrvt fddt jd D | _d S )Nr   c                    s   g | ]}t  qS r%   )r   r&   _rL   r%   r(   
<listcomp>  s     z,MobileBertLayer.__init__.<locals>.<listcomp>)rW   rX   r   num_feedforward_networksr   r   r   r   r   r   r   r   r   
ModuleListranger!   r   r^   r   r(   rX     s    





zMobileBertLayer.__init__N)r   r   r   r   ra   c              	   C   s   | j r| |\}}}}n|gd \}}}}| j|||||||d}	|	d }
|
f}|	dd  }| jdkrt| jD ]\}}||
}
||
f7 }qr| |
}| ||
|}|f| t	d|||||
|f | }|S )Nr   )r   r   r   i  )
r   r   r   r   	enumerater!   r   r   rI   Ztensor)r\   r   r   r   r   r   r   r   r   Zself_attention_outputsr   sr   iZ
ffn_moduler   r   r%   r%   r(   rb     sJ    	

zMobileBertLayer.forward)NNN)rd   re   rf   rX   rI   rg   r   r   r   r   rb   rh   r%   r%   r^   r(   r     s      r   c                
       sZ   e Zd Z fddZd	ejeej eej ee ee ee e	e
ef dddZ  ZS )
MobileBertEncoderc                    s.   t    t fddt jD | _d S )Nc                    s   g | ]}t  qS r%   )r   r   r   r%   r(   r   5  s     z.MobileBertEncoder.__init__.<locals>.<listcomp>)rW   rX   r   r   r   num_hidden_layerslayerr   r^   r   r(   rX   3  s    
zMobileBertEncoder.__init__NFT)r   r   r   r   output_hidden_statesreturn_dictra   c                 C   s   |rdnd }|rdnd }t | jD ]B\}	}
|r8||f }|
||||	 |}|d }|r"||d f }q"|rt||f }|stdd |||fD S t|||dS )Nr%   r   r   c                 s   s   | ]}|d k	r|V  qd S rV   r%   )r&   vr%   r%   r(   r)   V  s      z,MobileBertEncoder.forward.<locals>.<genexpr>)last_hidden_stater   
attentions)r   r   tupler   )r\   r   r   r   r   r   r   Zall_hidden_statesZall_attentionsr   Zlayer_moduler   r%   r%   r(   rb   7  s.    	

  zMobileBertEncoder.forward)NNFFT)rd   re   rf   rX   rI   rg   r   r   r   r   r   r   rb   rh   r%   r%   r^   r(   r   2  s        
r   c                       s0   e Zd Z fddZejejdddZ  ZS )MobileBertPoolerc                    s.   t    |j| _| jr*t|j|j| _d S rV   )rW   rX   Zclassifier_activationdo_activater   rw   rq   r   r   r^   r%   r(   rX   ]  s    
zMobileBertPooler.__init__r   c                 C   s6   |d d df }| j s|S | |}t|}|S d S )Nr   )r   r   rI   tanh)r\   r   Zfirst_token_tensorpooled_outputr%   r%   r(   rb   c  s    

zMobileBertPooler.forwardrc   r%   r%   r^   r(   r   \  s   r   c                       s0   e Zd Z fddZejejdddZ  ZS )!MobileBertPredictionHeadTransformc                    sX   t    t|j|j| _t|jtr6t	|j | _
n|j| _
td |j|jd| _d S )Nri   r   )rW   rX   r   rw   rq   r   r   r   r   r   transform_act_fnry   r   r"   r   r^   r%   r(   rX   p  s    
z*MobileBertPredictionHeadTransform.__init__r   c                 C   s"   |  |}| |}| |}|S rV   )r   r   r"   r   r%   r%   r(   rb   y  s    


z)MobileBertPredictionHeadTransform.forwardrc   r%   r%   r^   r(   r   o  s   	r   c                       s0   e Zd Z fddZejejdddZ  ZS )MobileBertLMPredictionHeadc                    sh   t    t|| _tj|j|j|j dd| _	tj|j|jdd| _
tt|j| _| j| j
_d S )NF)r-   )rW   rX   r   	transformr   rw   rs   rq   rp   r   decoderrY   rI   rZ   r-   r   r^   r%   r(   rX     s    

z#MobileBertLMPredictionHead.__init__r   c                 C   s>   |  |}|tj| jj | jjgdd}|| jj7 }|S )Nr   r   )	r   r   rI   r   r   r+   tr   r-   r   r%   r%   r(   rb     s    
$z"MobileBertLMPredictionHead.forwardrc   r%   r%   r^   r(   r     s   r   c                       s0   e Zd Z fddZejejdddZ  ZS )MobileBertOnlyMLMHeadc                    s   t    t|| _d S rV   )rW   rX   r   predictionsr   r^   r%   r(   rX     s    
zMobileBertOnlyMLMHead.__init__)sequence_outputra   c                 C   s   |  |}|S rV   )r   )r\   r   prediction_scoresr%   r%   r(   rb     s    
zMobileBertOnlyMLMHead.forwardrc   r%   r%   r^   r(   r     s   r   c                       s8   e Zd Z fddZejejeej dddZ  ZS )MobileBertPreTrainingHeadsc                    s(   t    t|| _t|jd| _d S Nr/   )rW   rX   r   r   r   rw   rq   seq_relationshipr   r^   r%   r(   rX     s    

z#MobileBertPreTrainingHeads.__init__)r   r   ra   c                 C   s   |  |}| |}||fS rV   )r   r  )r\   r   r   r   seq_relationship_scorer%   r%   r(   rb     s    

z"MobileBertPreTrainingHeads.forwardr   r%   r%   r^   r(   r     s   r   c                   @   s(   e Zd ZdZeZeZeZ	dZ
dd ZdS )MobileBertPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    r#   c                 C   s   t |tjr:|jjjd| jjd |jdk	r|jj	  njt |tj
rz|jjjd| jjd |jdk	r|jj|j 	  n*t |tjtfr|jj	  |jjd dS )zInitialize the weightsr   )ZmeanZstdNg      ?)r   r   rw   r+   rJ   Znormal_rL   Zinitializer_ranger-   Zzero_rr   rk   r"   rU   Zfill_)r\   moduler%   r%   r(   _init_weights  s    

z'MobileBertPreTrainedModel._init_weightsN)rd   re   rf   r   r   config_class(MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LISTZpretrained_model_archive_maprT   Zload_tf_weightsZbase_model_prefixr  r%   r%   r%   r(   r    s   r  c                   @   sl   e Zd ZU dZdZeej ed< dZ	ejed< dZ
ejed< dZeeej  ed< dZeeej  ed< dS )MobileBertForPreTrainingOutputab  
    Output type of [`MobileBertForPreTraining`].

    Args:
        loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
            Total loss as the sum of the masked language modeling loss and the next sequence prediction
            (classification) loss.
        prediction_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
            Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
        seq_relationship_logits (`torch.FloatTensor` of shape `(batch_size, 2)`):
            Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
            before SoftMax).
        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.
    Nlossprediction_logitsseq_relationship_logitsr   r   )rd   re   rf   r   r	  r   rI   r   __annotations__r
  r  r   r   r   r%   r%   r%   r(   r    s   
r  aD  

    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.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 ([`MobileBertConfig`]): 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.
a5
  
    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.
zdThe bare MobileBert Model transformer outputting raw hidden-states without any specific head on top.c                       s   e Zd ZdZd fdd	Zdd Zdd Zd	d
 Zee	
deeeeddeej eej eej eej eej eej ee ee ee eeef d
ddZ  ZS )MobileBertModelz.
    https://arxiv.org/pdf/2004.02984.pdf
    Tc                    sD   t  | || _t|| _t|| _|r2t|nd | _| 	  d S rV   )
rW   rX   rL   rj   r   r   encoderr   pooler	post_init)r\   rL   add_pooling_layerr^   r%   r(   rX   2  s    

zMobileBertModel.__init__c                 C   s   | j jS rV   r   rt   r\   r%   r%   r(   get_input_embeddings=  s    z$MobileBertModel.get_input_embeddingsc                 C   s   || j _d S rV   r  )r\   r   r%   r%   r(   set_input_embeddings@  s    z$MobileBertModel.set_input_embeddingsc                 C   s*   |  D ]\}}| jj| j| qdS )z
        Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
        class PreTrainedModel
        N)itemsr  r   r   r   )r\   Zheads_to_pruner   r   r%   r%   r(   _prune_headsC  s    zMobileBertModel._prune_headsbatch_size, sequence_length
checkpointoutput_typer  N)
r   r   r   rl   r   r   r   r   r   ra   c
                 C   sn  |d k	r|n| j j}|d k	r |n| j j}|	d k	r4|	n| j j}	|d k	rV|d k	rVtdn@|d k	rt| || | }
n"|d k	r| d d }
ntd|d k	r|jn|j}|d krtj	|
|d}|d krtj
|
tj|d}| ||
}| || j j}| j||||d}| j||||||	d}|d }| jd k	r<| |nd }|	sZ||f|d	d   S t|||j|jd
S )NzDYou cannot specify both input_ids and inputs_embeds at the same timerm   z5You have to specify either input_ids or inputs_embeds)r   r   )r   rl   r   r   )r   r   r   r   r   r   r   )r   Zpooler_outputr   r   )rL   r   r   use_return_dict
ValueErrorZ%warn_if_padding_and_no_attention_maskr   r   rI   r[   rZ   r   Zget_extended_attention_maskZget_head_maskr   r   r  r  r   r   r   )r\   r   r   r   rl   r   r   r   r   r   r   r   Zextended_attention_maskZembedding_outputZencoder_outputsr   r   r%   r%   r(   rb   K  sV    

   zMobileBertModel.forward)T)	NNNNNNNNN)rd   re   rf   r   rX   r  r  r  r   MOBILEBERT_INPUTS_DOCSTRINGformatr   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOCr   rI   r   r   r   r   r   rb   rh   r%   r%   r^   r(   r  )  s@            
r  z
    MobileBert Model with two heads on top as done during the pretraining: a `masked language modeling` head and a
    `next sentence prediction (classification)` head.
    c                       s   e Zd ZddgZ fddZdd Zdd Zdee e	j
d
 fddZeedeeeddeej eej eej eej eej eej eej eej eej eej eej eeef dddZ  ZS )MobileBertForPreTrainingcls.predictions.decoder.weightcls.predictions.decoder.biasc                    s,   t  | t|| _t|| _|   d S rV   )rW   rX   r  r#   r   clsr  r   r^   r%   r(   rX     s    

z!MobileBertForPreTraining.__init__c                 C   s
   | j jjS rV   r%  r   r   r  r%   r%   r(   get_output_embeddings  s    z.MobileBertForPreTraining.get_output_embeddingsc                 C   s   || j j_d S rV   r&  r\   Znew_embeddigsr%   r%   r(   set_output_embeddings  s    z.MobileBertForPreTraining.set_output_embeddingsNnew_num_tokensra   c                    s*   | j | jjj|dd| jj_t j|dS NT)r+  Z
transposed)r+  Z_get_resized_lm_headr%  r   r   rW   resize_token_embeddingsr\   r+  r^   r%   r(   r.    s      z0MobileBertForPreTraining.resize_token_embeddingsr  r  r  )r   r   r   rl   r   r   labelsnext_sentence_labelr   r   r   ra   c                 C   s   |dk	r|n| j j}| j|||||||	|
|d	}|dd \}}| ||\}}d}|dk	r|dk	rt }||d| j j|d}||dd|d}|| }|s||f|dd  }|dk	r|f| S |S t||||j|j	dS )a  
        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]`
        next_sentence_label (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
            (see `input_ids` docstring) Indices should be in `[0, 1]`:

            - 0 indicates sequence B is a continuation of sequence A,
            - 1 indicates sequence B is a random sequence.

        Returns:

        Examples:

        ```python
        >>> from transformers import AutoTokenizer, MobileBertForPreTraining
        >>> import torch

        >>> tokenizer = AutoTokenizer.from_pretrained("google/mobilebert-uncased")
        >>> model = MobileBertForPreTraining.from_pretrained("google/mobilebert-uncased")

        >>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0)
        >>> # Batch size 1
        >>> outputs = model(input_ids)

        >>> prediction_logits = outputs.prediction_logits
        >>> seq_relationship_logits = outputs.seq_relationship_logits
        ```Nr   r   rl   r   r   r   r   r   r/   rm   )r	  r
  r  r   r   )
rL   r  r#   r%  r   r   rs   r  r   r   )r\   r   r   r   rl   r   r   r1  r2  r   r   r   r   r   r   r   r  
total_lossloss_fctmasked_lm_lossnext_sentence_lossr   r%   r%   r(   rb     s<    .z MobileBertForPreTraining.forward)N)NNNNNNNNNNN)rd   re   rf   _tied_weights_keysrX   r'  r)  r   rD   r   rr   r.  r   r  r  r   r  r!  rI   r   r   r   r   rb   rh   r%   r%   r^   r(   r"    s@   
           
r"  z8MobileBert Model with a `language modeling` head on top.c                       s   e Zd ZddgZ fddZdd Zdd Zdee e	j
d
 fddZeedeeeeddddeej eej eej eej eej eej eej ee ee ee eeef dddZ  ZS )MobileBertForMaskedLMr#  r$  c                    s6   t  | t|dd| _t|| _|| _|   d S NF)r  )rW   rX   r  r#   r   r%  rL   r  r   r^   r%   r(   rX     s
    
zMobileBertForMaskedLM.__init__c                 C   s
   | j jjS rV   r&  r  r%   r%   r(   r'    s    z+MobileBertForMaskedLM.get_output_embeddingsc                 C   s   || j j_d S rV   r&  r(  r%   r%   r(   r)    s    z+MobileBertForMaskedLM.set_output_embeddingsNr*  c                    s*   | j | jjj|dd| jj_t j|dS r,  r-  r/  r^   r%   r(   r.    s      z-MobileBertForMaskedLM.resize_token_embeddingsr  z'paris'g=
ףp=?r  r  r  expected_outputexpected_lossr   r   r   rl   r   r   r1  r   r   r   ra   c                 C   s   |
dk	r|
n| j j}
| j||||||||	|
d	}|d }| |}d}|dk	rpt }||d| j j|d}|
s|f|dd  }|dk	r|f| S |S t|||j|j	dS )a  
        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]`
        Nr3  r   rm   r/   r	  logitsr   r   )
rL   r  r#   r%  r   r   rs   r   r   r   )r\   r   r   r   rl   r   r   r1  r   r   r   r   r   r   r6  r5  r   r%   r%   r(   rb   $  s6    
zMobileBertForMaskedLM.forward)N)
NNNNNNNNNN)rd   re   rf   r8  rX   r'  r)  r   rD   r   rr   r.  r   r  r  r   r   r   r!  rI   r   r   r   r   r   rb   rh   r%   r%   r^   r(   r9  
  sH   		          
r9  c                       s0   e Zd Z fddZejejdddZ  ZS )MobileBertOnlyNSPHeadc                    s   t    t|jd| _d S r   )rW   rX   r   rw   rq   r  r   r^   r%   r(   rX   b  s    
zMobileBertOnlyNSPHead.__init__)r   ra   c                 C   s   |  |}|S rV   )r  )r\   r   r  r%   r%   r(   rb   f  s    
zMobileBertOnlyNSPHead.forwardrc   r%   r%   r^   r(   rA  a  s   rA  zPMobileBert Model with a `next sentence prediction (classification)` head on top.c                       s   e Zd Z fddZeedeee	dd	e
ej e
ej e
ej e
ej e
ej e
ej e
ej e
e e
e e
e eeef dddZ  ZS )
#MobileBertForNextSentencePredictionc                    s,   t  | t|| _t|| _|   d S rV   )rW   rX   r  r#   rA  r%  r  r   r^   r%   r(   rX   p  s    

z,MobileBertForNextSentencePrediction.__init__r  r0  Nr>  c                 K   s   d|krt dt |d}|
dk	r*|
n| jj}
| j||||||||	|
d	}|d }| |}d}|dk	rt }||	dd|	d}|
s|f|dd  }|dk	r|f| S |S t
|||j|jdS )	a  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
            (see `input_ids` docstring) Indices should be in `[0, 1]`.

            - 0 indicates sequence B is a continuation of sequence A,
            - 1 indicates sequence B is a random sequence.

        Returns:

        Examples:

        ```python
        >>> from transformers import AutoTokenizer, MobileBertForNextSentencePrediction
        >>> import torch

        >>> tokenizer = AutoTokenizer.from_pretrained("google/mobilebert-uncased")
        >>> model = MobileBertForNextSentencePrediction.from_pretrained("google/mobilebert-uncased")

        >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
        >>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
        >>> encoding = tokenizer(prompt, next_sentence, return_tensors="pt")

        >>> outputs = model(**encoding, labels=torch.LongTensor([1]))
        >>> loss = outputs.loss
        >>> logits = outputs.logits
        ```r2  zoThe `next_sentence_label` argument is deprecated and will be removed in a future version, use `labels` instead.Nr3  r   rm   r/   r?  )warningswarnFutureWarningpoprL   r  r#   r%  r   r   r   r   r   )r\   r   r   r   rl   r   r   r1  r   r   r   kwargsr   r   r  r7  r5  r   r%   r%   r(   rb   y  sB    ,

z+MobileBertForNextSentencePrediction.forward)
NNNNNNNNNN)rd   re   rf   rX   r   r  r  r   r   r!  r   rI   r   r   r   r   r   rb   rh   r%   r%   r^   r(   rB  k  s4   	
          
rB  z
    MobileBert Model transformer with a sequence classification/regression head on top (a linear layer on top of the
    pooled output) e.g. for GLUE tasks.
    c                       s   e Zd Z fddZeedeee	e
eedd	eej eej eej eej eej eej eej ee ee ee eeej e	f dddZ  ZS )
#MobileBertForSequenceClassificationc                    sd   t  | |j| _|| _t|| _|jd k	r4|jn|j}t	|| _
t|j|j| _|   d S rV   )rW   rX   
num_labelsrL   r  r#   classifier_dropoutr|   r   r{   r}   rw   rq   r.   r  r\   rL   rJ  r^   r%   r(   rX     s    
z,MobileBertForSequenceClassification.__init__r  r;  Nr>  c                 C   s|  |
dk	r|
n| j j}
| j||||||||	|
d	}|d }| |}| |}d}|dk	r8| j jdkr| jdkrzd| j _n4| jdkr|jtj	ks|jtj
krd| j _nd| j _| j jdkrt }| jdkr|| | }n
|||}nN| j jdkrt }||d| j|d}n| j jdkr8t }|||}|
sh|f|dd  }|dk	rd|f| S |S t|||j|jd	S )
a  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        Nr3  r   Z
regressionZsingle_label_classificationZmulti_label_classificationrm   r/   r?  )rL   r  r#   r}   r.   Zproblem_typerI  r   rI   r   rD   r	   squeezer   r   r   r   r   r   )r\   r   r   r   rl   r   r   r1  r   r   r   r   r   r@  r	  r5  r   r%   r%   r(   rb     sV    




"


z+MobileBertForSequenceClassification.forward)
NNNNNNNNNN)rd   re   rf   rX   r   r  r  r   '_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATIONr   r!  _SEQ_CLASS_EXPECTED_OUTPUT_SEQ_CLASS_EXPECTED_LOSSr   rI   rg   r   r   r   rb   rh   r%   r%   r^   r(   rH    s@   		          rH  z
    MobileBert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a
    linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
    c                       s   e Zd Z fddZeedeee	e
eeeedd	eej eej eej eej eej eej eej eej ee ee ee eeej e	f dddZ  ZS )
MobileBertForQuestionAnsweringc                    s@   t  | |j| _t|dd| _t|j|j| _| 	  d S r:  )
rW   rX   rI  r  r#   r   rw   rq   
qa_outputsr  r   r^   r%   r(   rX   @  s
    z'MobileBertForQuestionAnswering.__init__r  )r  r  r  Zqa_target_start_indexZqa_target_end_indexr<  r=  N)r   r   r   rl   r   r   start_positionsend_positionsr   r   r   ra   c                 C   sP  |dk	r|n| j j}| j|||||||	|
|d	}|d }| |}|jddd\}}|d }|d }d}|dk	r|dk	rt| dkr|d}t| dkr|d}|d}|	d|}|	d|}t
|d}|||}|||}|| d }|s:||f|dd  }|dk	r6|f| S |S t||||j|jd	S )
a  
        start_positions (`torch.LongTensor` of shape `(batch_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 `(batch_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.
        Nr3  r   r   rm   r   )Zignore_indexr/   )r	  start_logits
end_logitsr   r   )rL   r  r#   rQ  r=   rL  r   rC   r   clampr   r   r   r   )r\   r   r   r   rl   r   r   rR  rS  r   r   r   r   r   r@  rT  rU  r4  Zignored_indexr5  Z
start_lossZend_lossr   r%   r%   r(   rb   J  sP    "






z&MobileBertForQuestionAnswering.forward)NNNNNNNNNNN)rd   re   rf   rX   r   r  r  r   _CHECKPOINT_FOR_QAr   r!  _QA_TARGET_START_INDEX_QA_TARGET_END_INDEX_QA_EXPECTED_OUTPUT_QA_EXPECTED_LOSSr   rI   rg   r   r   r   rb   rh   r%   r%   r^   r(   rP  7  sH   	
           rP  z
    MobileBert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and
    a softmax) e.g. for RocStories/SWAG tasks.
    c                       s   e Zd Z fddZeedeee	e
dd	eej eej eej eej eej eej eej ee ee ee eeej e	f dddZ  ZS )
MobileBertForMultipleChoicec                    sT   t  | t|| _|jd k	r&|jn|j}t|| _t	|j
d| _|   d S )Nr   )rW   rX   r  r#   rJ  r|   r   r{   r}   rw   rq   r.   r  rK  r^   r%   r(   rX     s    
z$MobileBertForMultipleChoice.__init__z(batch_size, num_choices, sequence_lengthr  Nr>  c                 C   st  |
dk	r|
n| j j}
|dk	r&|jd n|jd }|dk	rJ|d|dnd}|dk	rh|d|dnd}|dk	r|d|dnd}|dk	r|d|dnd}|dk	r|d|d|dnd}| j||||||||	|
d	}|d }| |}| |}|d|}d}|dk	r0t }|||}|
s`|f|dd  }|dk	r\|f| S |S t	|||j
|jdS )aJ  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
            num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
            `input_ids` above)
        Nr   rm   r   r3  r/   r?  )rL   r  rF   r   r   r#   r}   r.   r   r   r   r   )r\   r   r   r   rl   r   r   r1  r   r   r   Znum_choicesr   r   r@  Zreshaped_logitsr	  r5  r   r%   r%   r(   rb     sL    



z#MobileBertForMultipleChoice.forward)
NNNNNNNNNN)rd   re   rf   rX   r   r  r  r   r   r   r!  r   rI   rg   r   r   r   rb   rh   r%   r%   r^   r(   r\    s@   	          r\  z
    MobileBert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g.
    for Named-Entity-Recognition (NER) tasks.
    c                       s   e Zd Z fddZeedeee	e
eedd	eej eej eej eej eej eej eej ee ee ee eeej e	f dddZ  ZS )
 MobileBertForTokenClassificationc                    sb   t  | |j| _t|dd| _|jd k	r2|jn|j}t|| _	t
|j|j| _|   d S r:  )rW   rX   rI  r  r#   rJ  r|   r   r{   r}   rw   rq   r.   r  rK  r^   r%   r(   rX   	  s    z)MobileBertForTokenClassification.__init__r  r;  Nr>  c                 C   s   |
dk	r|
n| j j}
| j||||||||	|
d	}|d }| |}| |}d}|dk	rxt }||d| j|d}|
s|f|dd  }|dk	r|f| S |S t|||j	|j
dS )z
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
        Nr3  r   rm   r/   r?  )rL   r  r#   r}   r.   r   r   rI  r   r   r   )r\   r   r   r   rl   r   r   r1  r   r   r   r   r   r@  r	  r5  r   r%   r%   r(   rb     s8    

z(MobileBertForTokenClassification.forward)
NNNNNNNNNN)rd   re   rf   rX   r   r  r  r   $_CHECKPOINT_FOR_TOKEN_CLASSIFICATIONr   r!  _TOKEN_CLASS_EXPECTED_OUTPUT_TOKEN_CLASS_EXPECTED_LOSSr   rI   rg   r   r   r   rb   rh   r%   r%   r^   r(   r]     s@   		          r]  )]r   r5   rC  dataclassesr   typingr   r   r   rI   r   Ztorch.nnr   r   r	   Zactivationsr   Zmodeling_outputsr   r   r   r   r   r   r   r   Zmodeling_utilsr   Zpytorch_utilsr   r   utilsr   r   r   r   r   r   Zconfiguration_mobilebertr   Z
get_loggerrd   r3   r   r!  r^  r_  r`  rW  rZ  r[  rX  rY  rM  rN  rO  r  rT   ModulerU   r"   ry   rj   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  ZMOBILEBERT_START_DOCSTRINGr  r  r"  r9  rA  rB  rH  rP  r\  r]  r%   r%   r%   r(   <module>   s   (
 
N
L:2$?*
!2kkV
```Y