
    sg                    R   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$jP                  e)      Z*dZ+dZ,dZ-dZ.dZ/dZ0dZ1dZ2dZ3dZ4dZ5dZ6dZ7d Z8 G d de
jr                        Z:e
jv                  e:dZ< G d d e
jr                        Z= G d! d"e
jr                        Z> G d# d$e
jr                        Z? G d% d&e
jr                        Z@ G d' d(e
jr                        ZA G d) d*e
jr                        ZB G d+ d,e
jr                        ZC G d- d.e
jr                        ZD G d/ d0e
jr                        ZE G d1 d2e
jr                        ZF G d3 d4e
jr                        ZG G d5 d6e
jr                        ZH G d7 d8e
jr                        ZI G d9 d:e
jr                        ZJ G d; d<e
jr                        ZK G d= d>e
jr                        ZL G d? d@e
jr                        ZM G dA dBe
jr                        ZN G dC dDe      ZOe G dE dFe              ZPdGZQdHZR e"dIeQ       G dJ dKeO             ZS e"dLeQ       G dM dNeO             ZT e"dOeQ       G dP dQeO             ZU G dR dSe
jr                        ZV e"dTeQ       G dU dVeO             ZW e"dWeQ       G dX dYeO             ZX e"dZeQ       G d[ d\eO             ZY e"d]eQ       G d^ d_eO             ZZ e"d`eQ       G da dbeO             Z[y)c    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           	         	 ddl }ddl}ddl}t        j                  j                  |      }t        j                  d|        |j                  j                  |      }g }g }	|D ]^  \  }
}t        j                  d|
 d|        |j                  j                  ||
      }|j                  |
       |	j                  |       ` t        ||	      D ]  \  }
}|
j                  dd      }
|
j                  d	d
      }
|
j                  dd      }
|
j                  dd      }
|
j!                  d      }
t#        d |
D              r(t        j                  ddj%                  |
              | }|
D ]  }|j'                  d|      r|j!                  d|      }n|g}|d   dk(  s|d   dk(  rt)        |d      }nW|d   dk(  s|d   dk(  rt)        |d      }n:|d   dk(  rt)        |d      }n%|d   dk(  rt)        |d      }n	 t)        ||d         }t-        |      dk\  st/        |d         }||   } dd d k(  rt)        |d      }n|dk(  r|j1                  |      }	 |j2                  |j2                  k(  s"J d!|j2                   d"|j2                   d#       	 t        j                  d$|
        t9        j:                  |      |_         | S # t        $ r t        j                  d        w xY w# t*        $ r+ t        j                  ddj%                  |
              Y w xY w# t4        $ r1}|xj6                  |j2                  |j2                  fz  c_         d}~ww xY w)%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 	ffn_layerffnFakeLayerNorm	LayerNormextra_output_weightszdense/kernelbert
mobilebert/c              3   $   K   | ]  }|d v  
 yw))adam_vadam_mAdamWeightDecayOptimizerAdamWeightDecayOptimizer_1global_stepN ).0ns     e/var/www/html/venv/lib/python3.12/site-packages/transformers/models/mobilebert/modeling_mobilebert.py	<genexpr>z0load_tf_weights_in_mobilebert.<locals>.<genexpr>q   s      
 nn
s   z	Skipping z[A-Za-z]+_\d+z_(\d+)kernelgammaweightoutput_biasbetabiasoutput_weightssquad
classifier   r   i_embeddingszPointer shape z and array shape z mismatchedzInitialize PyTorch weight )renumpy
tensorflowImportErrorloggererrorospathabspathinfotrainlist_variablesload_variableappendzipreplacesplitanyjoin	fullmatchgetattrAttributeErrorlenint	transposeshapeAssertionErrorargstorch
from_numpydata)modelconfigtf_checkpoint_pathrA   nptftf_path	init_varsnamesarraysnamerZ   arraypointerm_namescope_namesnumes                     r4   load_tf_weights_in_mobilebertrp   P   sj   
 ggoo01G
KK8	BC''0IEF  e(l5'BC&&w5Te	 5&) 1/e||K/||O[9||2NC||FL1zz#  

 
 KK)CHHTN#345 	'F||,f5 hhy&9%h1~)[^w-F!'84Q=0KNf4L!'62Q#33!'84Q7*!'<8%g{1~>G ;1$+a.)!#,+	', #$<=(gx0GxLL'E	,Y.?}KXY,
 	078''.c1/d LI  Q	
 	b & KK)CHHTN+; <=  	FFw}}ekk22F	s5   K K6 ;L- K360L*)L*-	M'6,M""M'c                   X     e Zd Zd fd	Zdej
                  dej
                  fdZ xZS )NoNormc                     t         |           t        j                  t	        j
                  |            | _        t        j                  t	        j                  |            | _        y N)	super__init__r   	Parameterr]   zerosr;   onesr8   )self	feat_sizeeps	__class__s      r4   rv   zNoNorm.__init__   s@    LLY!78	ll5::i#89    input_tensorreturnc                 :    || j                   z  | j                  z   S rt   )r8   r;   )rz   r   s     r4   forwardzNoNorm.forward   s    dkk)DII55r~   rt   __name__
__module____qualname__rv   r]   Tensorr   __classcell__r}   s   @r4   rr   rr      s#    :
6ELL 6U\\ 6r~   rr   )
layer_normno_normc                        e Zd ZdZ fdZ	 	 	 	 d	deej                     deej                     deej                     deej                     dej                  f
dZ
 xZS )
MobileBertEmbeddingszGConstruct the embeddings from word, position and token_type embeddings.c                 X   t         |           |j                  | _        |j                  | _        |j                  | _        t        j                  |j                  |j                  |j                        | _	        t        j                  |j                  |j                        | _        t        j                  |j                  |j                        | _        | j                  rdnd}| j                  |z  }t        j                  ||j                        | _        t!        |j"                     |j                        | _        t        j&                  |j(                        | _        | j-                  dt/        j0                  |j                        j3                  d      d       y )N)padding_idxr   r   position_ids)r   F)
persistent)ru   rv   trigram_inputembedding_sizehidden_sizer   	Embedding
vocab_sizepad_token_idword_embeddingsmax_position_embeddingsposition_embeddingstype_vocab_sizetoken_type_embeddingsLinearembedding_transformationNORM2FNnormalization_typer&   Dropouthidden_dropout_probdropoutregister_bufferr]   arangeexpand)rz   ra   embed_dim_multiplierembedded_input_sizer}   s       r4   rv   zMobileBertEmbeddings.__init__   sF   #11$33!--!||F,=,=v?T?Tbhbubuv#%<<0N0NPVPbPb#c %'\\&2H2H&J\J\%]"$($6$6qA"114HH(*		2EvGYGY(Z% !:!:;F<N<NOzz&"<"<= 	ELL)G)GHOOPWXej 	 	
r~   	input_idstoken_type_idsr   inputs_embedsr   c           
      $   ||j                         }n|j                         d d }|d   }|| j                  d d d |f   }|:t        j                  |t        j                  | j                  j
                        }|| j                  |      }| j                  rpt        j                  t        j                  j                  |d d dd f   g dd      |t        j                  j                  |d d d df   g dd      gd	      }| j                  s| j                  | j                  k7  r| j                  |      }| j                  |      }| j!                  |      }||z   |z   }	| j#                  |	      }	| j%                  |	      }	|	S )
Nr   r   dtypedevice)r   r   r   r   r   r           )value)r   r   r   r   r   r   r?   dim)sizer   r]   rx   longr   r   r   catr   
functionalpadr   r   r   r   r   r&   r   )
rz   r   r   r   r   input_shape
seq_lengthr   r   
embeddingss
             r4   r   zMobileBertEmbeddings.forward   s     #..*K',,.s3K ^
,,Q^<L!"[[EJJtO`O`OgOghN  00;M "IIMM%%mAqrE&:<NVY%Z!MM%%mAssF&;=OWZ%[
 M !4!48H8H!H 99-HM #66|D $ : :> J"%88;PP
^^J/
\\*-
r~   )NNNN)r   r   r   __doc__rv   r   r]   
LongTensorFloatTensorr   r   r   r   s   @r4   r   r      s~    Q
0 155937590E,,-0 !!1!120 u//0	0
   1 120 
0r~   r   c                        e Zd Z fdZd Z	 	 	 ddej                  dej                  dej                  deej                     deej                     dee	   d	e
ej                     fd
Z xZS )MobileBertSelfAttentionc                 `   t         |           |j                  | _        t        |j                  |j                  z        | _        | j                  | j
                  z  | _        t        j                  |j                  | j                        | _	        t        j                  |j                  | j                        | _
        t        j                  |j                  r|j                  n|j                  | j                        | _        t        j                  |j                        | _        y rt   )ru   rv   num_attention_headsrX   true_hidden_sizeattention_head_sizeall_head_sizer   r   querykeyuse_bottleneck_attentionr   r   r   attention_probs_dropout_probr   rz   ra   r}   s     r4   rv   z MobileBertSelfAttention.__init__   s    #)#=#= #&v'>'>A[A['[#\ !558P8PPYYv668J8JK
99V44d6H6HIYY'-'F'FF##FL^L^`d`r`r

 zz&"E"EFr~   c                     |j                         d d | j                  | j                  fz   }|j                  |      }|j	                  dddd      S )Nr   r   r?   r   r   )r   r   r   viewpermute)rz   xnew_x_shapes      r4   transpose_for_scoresz,MobileBertSelfAttention.transpose_for_scores  sL    ffhsmt'?'?AYAY&ZZFF;yyAq!$$r~   query_tensor
key_tensorvalue_tensorattention_mask	head_maskoutput_attentionsr   c                    | j                  |      }| j                  |      }| j                  |      }	| j                  |      }
| j                  |      }| j                  |	      }t	        j
                  |
|j                  dd            }|t        j                  | j                        z  }|||z   }t        j                  j                  |d      }| j                  |      }|||z  }t	        j
                  ||      }|j                  dddd      j                         }|j!                         d d | j"                  fz   }|j%                  |      }|r||f}|S |f}|S )Nr   r   r   r?   r   r   )r   r   r   r   r]   matmulrY   mathsqrtr   r   r   softmaxr   r   
contiguousr   r   r   )rz   r   r   r   r   r   r   mixed_query_layermixed_key_layermixed_value_layerquery_layer	key_layervalue_layerattention_scoresattention_probscontext_layernew_context_layer_shapeoutputss                     r4   r   zMobileBertSelfAttention.forward
  sm    !JJ|4((:. JJ|4//0AB--o>	//0AB !<<Y5H5HR5PQ+dii8P8P.QQ%/.@--//0@b/I ,,7 -	9O_kB%--aAq9DDF"/"4"4"6s";t?Q?Q>S"S%**+BC6G=/2 O\M]r~   NNN)r   r   r   rv   r   r]   r   r   r   boolr   r   r   r   s   @r4   r   r      s    G% 7;15,0$ll$ LL$ ll	$
 !!2!23$ E--.$ $D>$ 
u||	$r~   r   c                   n     e Zd Z fdZdej
                  dej
                  dej
                  fdZ xZS )MobileBertSelfOutputc                 j   t         |           |j                  | _        t        j                  |j
                  |j
                        | _        t        |j                     |j
                  |j                        | _
        | j                  s%t        j                  |j                        | _        y y Nr|   )ru   rv   use_bottleneckr   r   r   denser   r   layer_norm_epsr&   r   r   r   r   s     r4   rv   zMobileBertSelfOutput.__init__2  s    $33YYv668O8OP
 !:!:;F<S<SY_YnYno""::f&@&@ADL #r~   hidden_statesresidual_tensorr   c                     | j                  |      }| j                  s| j                  |      }| j                  ||z         }|S rt   )r   r   r   r&   rz   r   r   layer_outputss       r4   r   zMobileBertSelfOutput.forward:  s@    

=1"" LL7M}'FGr~   r   r   s   @r4   r   r   1  s2    BU\\ ELL UZUaUa r~   r   c                        e Zd Z fdZd Z	 	 	 ddej                  dej                  dej                  dej                  deej                     deej                     d	ee	   d
e
ej                     fdZ xZS )MobileBertAttentionc                     t         |           t        |      | _        t	        |      | _        t               | _        y rt   )ru   rv   r   rz   r   outputsetpruned_headsr   s     r4   rv   zMobileBertAttention.__init__C  s0    +F3	*62Er~   c                 >   t        |      dk(  ry t        || j                  j                  | j                  j                  | j
                        \  }}t        | j                  j                  |      | j                  _        t        | j                  j                  |      | j                  _        t        | j                  j                  |      | j                  _	        t        | j                  j                  |d      | j                  _        | j                  j                  t        |      z
  | j                  _        | j                  j                  | j                  j                  z  | j                  _        | j
                  j                  |      | _        y )Nr   r   r   )rW   r   rz   r   r   r   r   r   r   r   r   r   r   union)rz   headsindexs      r4   prune_headszMobileBertAttention.prune_headsI  s   u:?749900$))2O2OQUQbQb
u
 -TYY__eD		*499==%@		,TYY__eD		.t{{/@/@%QO )-		(E(EE
(R		%"&))"?"?$))B_B_"_		 --33E:r~   r   r   r   layer_inputr   r   r   r   c                 n    | j                  ||||||      }| j                  |d   |      }	|	f|dd  z   }
|
S )Nr   r   )rz   r   )rz   r   r   r   r  r   r   r   self_outputsattention_outputr   s              r4   r   zMobileBertAttention.forward[  sT     yy
  ;;|AD#%QR(88r~   r   )r   r   r   rv   r  r]   r   r   r   r   r   r   r   r   s   @r4   r   r   B  s    ";0 7;15,0ll LL ll	
 \\ !!2!23 E--. $D> 
u||	r~   r   c                   V     e Zd Z fdZdej
                  dej
                  fdZ xZS )MobileBertIntermediatec                    t         |           t        j                  |j                  |j
                        | _        t        |j                  t              rt        |j                     | _        y |j                  | _        y rt   )ru   rv   r   r   r   intermediate_sizer   
isinstance
hidden_actstrr   intermediate_act_fnr   s     r4   rv   zMobileBertIntermediate.__init__u  s]    YYv668P8PQ
f''-'-f.?.?'@D$'-'8'8D$r~   r   r   c                 J    | j                  |      }| j                  |      }|S rt   )r   r  rz   r   s     r4   r   zMobileBertIntermediate.forward}  s&    

=100?r~   r   r   s   @r4   r	  r	  t  s#    9U\\ ell r~   r	  c                   n     e Zd Z fdZdej
                  dej
                  dej
                  fdZ xZS )OutputBottleneckc                 .   t         |           t        j                  |j                  |j
                        | _        t        |j                     |j
                  |j                        | _
        t        j                  |j                        | _        y r   )ru   rv   r   r   r   r   r   r   r   r   r&   r   r   r   r   s     r4   rv   zOutputBottleneck.__init__  sh    YYv668J8JK
 !:!:;F<N<NTZTiTijzz&"<"<=r~   r   r   r   c                 r    | j                  |      }| j                  |      }| j                  ||z         }|S rt   )r   r   r&   r   s       r4   r   zOutputBottleneck.forward  s7    

=1]3}'FGr~   r   r   s   @r4   r  r    s1    >U\\ ELL UZUaUa r~   r  c                        e Zd Z fdZdej
                  dej
                  dej
                  dej
                  fdZ xZS )MobileBertOutputc                 r   t         |           |j                  | _        t        j                  |j
                  |j                        | _        t        |j                     |j                        | _
        | j                  s%t        j                  |j                        | _        y t        |      | _        y rt   )ru   rv   r   r   r   r  r   r   r   r   r&   r   r   r   r  
bottleneckr   s     r4   rv   zMobileBertOutput.__init__  s    $33YYv779P9PQ
 !:!:;F<S<ST""::f&@&@ADL.v6DOr~   intermediate_statesresidual_tensor_1residual_tensor_2r   c                     | j                  |      }| j                  s'| j                  |      }| j                  ||z         }|S | j                  ||z         }| j	                  ||      }|S rt   )r   r   r   r&   r  )rz   r  r  r  layer_outputs        r4   r   zMobileBertOutput.forward  ss     zz"56""<<5L>>,9J*JKL   >>,9J*JKL??<9JKLr~   r   r   s   @r4   r  r    s?    7
#(<<
DILL
ejeqeq
	
r~   r  c                   V     e Zd Z fdZdej
                  dej
                  fdZ xZS )BottleneckLayerc                     t         |           t        j                  |j                  |j
                        | _        t        |j                     |j
                  |j                        | _
        y r   )ru   rv   r   r   r   intra_bottleneck_sizer   r   r   r   r&   r   s     r4   rv   zBottleneckLayer.__init__  sR    YYv1163O3OP
 !:!:;F<X<X^d^s^str~   r   r   c                 J    | j                  |      }| j                  |      }|S rt   r   r&   )rz   r   r  s      r4   r   zBottleneckLayer.forward  s$    jj/nn[1r~   r   r   s   @r4   r   r     s$    u
U\\ ell r~   r   c                   \     e Zd Z fdZdej
                  deej
                     fdZ xZS )
Bottleneckc                     t         |           |j                  | _        |j                  | _        t	        |      | _        | j                  rt	        |      | _        y y rt   )ru   rv   key_query_shared_bottleneckr   r   input	attentionr   s     r4   rv   zBottleneck.__init__  sP    +1+M+M((.(G(G%$V,
++,V4DN ,r~   r   r   c                     | j                  |      }| j                  r|fdz  S | j                  r| j                  |      }||||fS ||||fS )N   )r)  r   r(  r*  )rz   r   bottlenecked_hidden_statesshared_attention_inputs       r4   r   zBottleneck.forward  sc    " &*ZZ%>"((.0144--%)^^M%B"*,BMSmnn!=-A[\\r~   	r   r   r   rv   r]   r   r   r   r   r   s   @r4   r&  r&    s+    5]U\\ ]eELL6I ]r~   r&  c                   n     e Zd Z fdZdej
                  dej
                  dej
                  fdZ xZS )	FFNOutputc                     t         |           t        j                  |j                  |j
                        | _        t        |j                     |j
                  |j                        | _
        y r   )ru   rv   r   r   r  r   r   r   r   r   r&   r   s     r4   rv   zFFNOutput.__init__  sR    YYv779P9PQ
 !:!:;F<S<SY_YnYnor~   r   r   r   c                 P    | j                  |      }| j                  ||z         }|S rt   r$  r   s       r4   r   zFFNOutput.forward  s)    

=1}'FGr~   r   r   s   @r4   r1  r1    s2    p
U\\ ELL UZUaUa r~   r1  c                   V     e Zd Z fdZdej
                  dej
                  fdZ xZS )FFNLayerc                 b    t         |           t        |      | _        t	        |      | _        y rt   )ru   rv   r	  intermediater1  r   r   s     r4   rv   zFFNLayer.__init__  s'    26:'r~   r   r   c                 L    | j                  |      }| j                  ||      }|S rt   )r7  r   )rz   r   intermediate_outputr   s       r4   r   zFFNLayer.forward  s*    "//>$7Gr~   r   r   s   @r4   r5  r5    s#    (
U\\ ell r~   r5  c                        e Zd Z fdZ	 	 	 ddej
                  deej                     deej                     dee   de	ej
                     f
dZ
 xZS )	MobileBertLayerc                    t         |           |j                  | _        |j                  | _        t	        |      | _        t        |      | _        t        |      | _	        | j                  rt        |      | _        |j                  dkD  rHt        j                  t        |j                  dz
        D cg c]  }t        |       c}      | _        y y c c}w Nr   )ru   rv   r   num_feedforward_networksr   r*  r	  r7  r  r   r&  r  r   
ModuleListranger5  r$   rz   ra   _r}   s      r4   rv   zMobileBertLayer.__init__  s    $33(.(G(G%,V426:&v.(0DO**Q.}}fFeFehiFi@j%k1hv&6%klDH /%ks   6Cr   r   r   r   r   c           	         | j                   r| j                  |      \  }}}}n|gdz  \  }}}}| j                  |||||||      }	|	d   }
|
f}|	dd  }| j                  dk7  r+t	        | j
                        D ]  \  }} ||
      }
||
fz  } | j                  |
      }| j                  ||
|      }|f|z   t        j                  d      |||||
|fz   |z   }|S )Nr,  )r   r   r   i  )
r   r  r*  r>  	enumerater$   r7  r   r]   tensor)rz   r   r   r   r   r   r   r   r  self_attention_outputsr  sr   i
ffn_moduler9  r  s                    r4   r   zMobileBertLayer.forward  s>    BF//R_B`?L*lKCP/TUBU?L*lK!%/ "0 "
 2!4(,((A-!*488!4 ):#-.>#? &(() #//0@A{{#68H-XO T" #
  	 r~   r   )r   r   r   rv   r]   r   r   r   r   r   r   r   r   s   @r4   r;  r;    sp    m  7;15,0.||. !!2!23. E--.	.
 $D>. 
u||	.r~   r;  c                        e Zd Z fdZ	 	 	 	 	 d
dej
                  deej                     deej                     dee   dee   dee   de	e
ef   fd	Z xZS )MobileBertEncoderc                     t         |           t        j                  t	        |j
                        D cg c]  }t        |       c}      | _        y c c}w rt   )ru   rv   r   r?  r@  num_hidden_layersr;  layerrA  s      r4   rv   zMobileBertEncoder.__init__1  s<    ]]U6KcKcEd#eOF$;#ef
#es   Ar   r   r   r   output_hidden_statesreturn_dictr   c                     |rdnd }|rdnd }t        | j                        D ],  \  }	}
|r||fz   } |
||||	   |      }|d   }|s$||d   fz   }. |r||fz   }|st        d |||fD              S t        |||      S )Nr1   r   r   c              3   &   K   | ]	  }||  y wrt   r1   )r2   vs     r4   r5   z,MobileBertEncoder.forward.<locals>.<genexpr>T  s     hqZ[Zghs   )last_hidden_stater   
attentions)rD  rN  tupler   )rz   r   r   r   r   rO  rP  all_hidden_statesall_attentionsrH  layer_moduler   s               r4   r   zMobileBertEncoder.forward5  s     #7BD0d(4 	FOA|#$58H$H!(!!	M *!,M !/=3C2E!E	F    1]4D Dh]4E~$Vhhh+;LYg
 	
r~   )NNFFT)r   r   r   rv   r]   r   r   r   r   r   r   r   r   r   r   s   @r4   rK  rK  0  s    g 7;15,1/4&*"
||"
 !!2!23"
 E--.	"

 $D>"
 'tn"
 d^"
 
uo%	&"
r~   rK  c                   V     e Zd Z fdZdej
                  dej
                  fdZ xZS )MobileBertPoolerc                     t         |           |j                  | _        | j                  r0t	        j
                  |j                  |j                        | _        y y rt   )ru   rv   classifier_activationdo_activater   r   r   r   r   s     r4   rv   zMobileBertPooler.__init__[  sH    !776#5#5v7I7IJDJ r~   r   r   c                     |d d df   }| j                   s|S | j                  |      }t        j                  |      }|S )Nr   )r^  r   r]   tanh)rz   r   first_token_tensorpooled_outputs       r4   r   zMobileBertPooler.forwarda  sE     +1a40%% JJ'9:M!JJ}5M  r~   r   r   s   @r4   r[  r[  Z  s$    K	!U\\ 	!ell 	!r~   r[  c                   V     e Zd Z fdZdej
                  dej
                  fdZ xZS )!MobileBertPredictionHeadTransformc                 Z   t         |           t        j                  |j                  |j                        | _        t        |j                  t              rt        |j                     | _
        n|j                  | _
        t        d   |j                  |j                        | _        y )Nr   r   )ru   rv   r   r   r   r   r  r  r  r   transform_act_fnr   r   r&   r   s     r4   rv   z*MobileBertPredictionHeadTransform.__init__n  s|    YYv1163E3EF
f''-$*6+<+<$=D!$*$5$5D! .v/A/AvG\G\]r~   r   r   c                 l    | j                  |      }| j                  |      }| j                  |      }|S rt   )r   rf  r&   r  s     r4   r   z)MobileBertPredictionHeadTransform.forwardw  s4    

=1--m<}5r~   r   r   s   @r4   rd  rd  m  s$    ^U\\ ell r~   rd  c                   ^     e Zd Z fdZddZdej                  dej                  fdZ xZS )MobileBertLMPredictionHeadc                    t         |           t        |      | _        t	        j
                  |j                  |j                  |j                  z
  d      | _	        t	        j
                  |j                  |j                  d      | _
        t	        j                  t        j                  |j                              | _        | j                  | j                  _        y )NF)r;   )ru   rv   rd  	transformr   r   r   r   r   r   decoderrw   r]   rx   r;   r   s     r4   rv   z#MobileBertLMPredictionHead.__init__  s    :6B YYv00&2D2DvG\G\2\chi
yy!6!68I8IPUVLLV->->!?@	 IIr~   r   c                 :    | j                   | j                  _         y rt   )r;   rl  rz   s    r4   _tie_weightsz'MobileBertLMPredictionHead._tie_weights  s     IIr~   r   c                    | j                  |      }|j                  t        j                  | j                  j
                  j                         | j                  j
                  gd            }|| j                  j                  z  }|S )Nr   r   )	rk  r   r]   r   rl  r8   tr   r;   r  s     r4   r   z"MobileBertLMPredictionHead.forward  sk    }5%,,UYY8K8K8M8M8OQUQ[Q[QbQb7cij-kl***r~   )r   N)	r   r   r   rv   ro  r]   r   r   r   r   s   @r4   ri  ri  ~  s(    	&&U\\ ell r~   ri  c                   V     e Zd Z fdZdej
                  dej
                  fdZ xZS )MobileBertOnlyMLMHeadc                 B    t         |           t        |      | _        y rt   )ru   rv   ri  predictionsr   s     r4   rv   zMobileBertOnlyMLMHead.__init__  s    5f=r~   sequence_outputr   c                 (    | j                  |      }|S rt   )ru  )rz   rv  prediction_scoress      r4   r   zMobileBertOnlyMLMHead.forward  s     ,,_=  r~   r   r   s   @r4   rs  rs    s#    >!u|| ! !r~   rs  c                   t     e Zd Z fdZdej
                  dej
                  deej
                     fdZ xZS )MobileBertPreTrainingHeadsc                     t         |           t        |      | _        t	        j
                  |j                  d      | _        y Nr?   )ru   rv   ri  ru  r   r   r   seq_relationshipr   s     r4   rv   z#MobileBertPreTrainingHeads.__init__  s4    5f= "		&*<*<a @r~   rv  rb  r   c                 N    | j                  |      }| j                  |      }||fS rt   )ru  r}  )rz   rv  rb  rx  seq_relationship_scores        r4   r   z"MobileBertPreTrainingHeads.forward  s0     ,,_=!%!6!6}!E "888r~   r/  r   s   @r4   rz  rz    s8    A
9u|| 9ELL 9UZ[`[g[gUh 9r~   rz  c                   "    e Zd ZdZeZeZdZd Z	y)MobileBertPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    r)   c                    t        |t        j                        rm|j                  j                  j                  d| j                  j                         |j                  %|j                  j                  j                          yyt        |t        j                        rz|j                  j                  j                  d| j                  j                         |j                  2|j                  j                  |j                     j                          yyt        |t        j                  t        f      rJ|j                  j                  j                          |j                  j                  j                  d       yy)zInitialize the weightsr   )meanstdNg      ?)r  r   r   r8   r_   normal_ra   initializer_ranger;   zero_r   r   r&   rr   fill_)rz   modules     r4   _init_weightsz'MobileBertPreTrainedModel._init_weights  s   fbii( MM&&CT[[5R5R&S{{&  &&( '-MM&&CT[[5R5R&S!!-""6#5#56<<> .v 67KK""$MM$$S) 8r~   N)
r   r   r   r   r   config_classrp   load_tf_weightsbase_model_prefixr  r1   r~   r4   r  r    s    
 $L3O$*r~   r  c                       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<   y)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   rU  )r   r   r   r   r  r   r]   r   __annotations__r  r  r   r   rU  r1   r~   r4   r  r    st    2 )-D(5$$
%,+/u((/15U..58<M8E%"3"345<59Ju00129r~   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                       e Zd ZdZd fd	Zd Zd Zd Z ee	j                  d             eeee      	 	 	 	 	 	 	 	 	 ddeej"                     d	eej$                     d
eej"                     deej"                     deej$                     deej$                     dee   dee   dee   deeef   fd              Z xZS )MobileBertModelz.
    https://arxiv.org/pdf/2004.02984.pdf
    c                     t         |   |       || _        t        |      | _        t        |      | _        |rt        |      nd | _        | j                          y rt   )
ru   rv   ra   r   r   rK  encoderr[  pooler	post_init)rz   ra   add_pooling_layerr}   s      r4   rv   zMobileBertModel.__init__2  sL     .v6(02C&v. 	r~   c                 .    | j                   j                  S rt   r   r   rn  s    r4   get_input_embeddingsz$MobileBertModel.get_input_embeddings=  s    ...r~   c                 &    || j                   _        y rt   r  )rz   r   s     r4   set_input_embeddingsz$MobileBertModel.set_input_embeddings@  s    */'r~   c                     |j                         D ]7  \  }}| j                  j                  |   j                  j	                  |       9 y)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  rN  r*  r  )rz   heads_to_prunerN  r  s       r4   _prune_headszMobileBertModel._prune_headsC  sE    
 +002 	CLE5LLu%//;;EB	Cr~   batch_size, sequence_length
checkpointoutput_typer  r   r   r   r   r   r   rO  r   rP  r   c
                 l   ||n| j                   j                  }||n| j                   j                  }|	|	n| j                   j                  }	||t	        d      |#| j                  ||       |j                         }
n!||j                         d d }
nt	        d      ||j                  n|j                  }|t        j                  |
|      }|&t        j                  |
t        j                  |      }| j                  ||
      }| j                  || j                   j                        }| j                  ||||      }| j!                  ||||||	      }|d   }| j"                  | j#                  |      nd }|	s
||f|d	d  z   S t%        |||j&                  |j(                  
      S )NzDYou cannot specify both input_ids and inputs_embeds at the same timer   z5You have to specify either input_ids or inputs_embeds)r   r   )r   r   r   r   )r   r   r   rO  rP  r   r   )rT  pooler_outputr   rU  )ra   r   rO  use_return_dict
ValueError%warn_if_padding_and_no_attention_maskr   r   r]   ry   rx   r   get_extended_attention_maskget_head_maskrM  r   r  r  r   r   rU  )rz   r   r   r   r   r   r   rO  r   rP  r   r   extended_attention_maskembedding_outputencoder_outputsrv  rb  s                    r4   r   zMobileBertModel.forwardK  s   $ 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B] ]%>cdd"66y.Q#..*K&',,.s3KTUU%.%:!!@T@T!"ZZFCN!"[[EJJvVN 150P0PQ_al0m &&y$++2O2OP	??l>iv + 
 ,,2/!5# ' 
 *!,8<8OO4UY#]3oab6III)-')77&11	
 	
r~   )T)	NNNNNNNNN)r   r   r   r   rv   r  r  r  r   MOBILEBERT_INPUTS_DOCSTRINGformatr   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOCr   r]   r   r   r   r   r   r   r   r   s   @r4   r  r  )  s>   
	/0C ++F+M+MNk+lm&.$ 156:59371559/3,0&*D
E,,-D
 !!2!23D
 !!1!12	D

 u//0D
 E--.D
   1 12D
 'tnD
 $D>D
 d^D
 
u00	1D
 nD
r~   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                   (    e Zd ZddgZ fdZd Zd Zddee   de	j                  f fdZ eej                  d	             eee
      	 	 	 	 	 	 	 	 	 	 	 ddeej&                     deej(                     deej&                     deej&                     deej(                     deej(                     deej&                     deej&                     deej(                     deej(                     deej(                     deeef   fd              Z xZS )MobileBertForPreTrainingcls.predictions.decoder.weightcls.predictions.decoder.biasc                     t         |   |       t        |      | _        t	        |      | _        | j                          y rt   )ru   rv   r  r)   rz  clsr  r   s     r4   rv   z!MobileBertForPreTraining.__init__  s4     )&1-f5 	r~   c                 B    | j                   j                  j                  S rt   r  ru  rl  rn  s    r4   get_output_embeddingsz.MobileBertForPreTraining.get_output_embeddings      xx##+++r~   c                     || j                   j                  _        |j                  | j                   j                  _        y rt   r  ru  rl  r;   rz   new_embeddingss     r4   set_output_embeddingsz.MobileBertForPreTraining.set_output_embeddings  ,    '5$$2$7$7!r~   new_num_tokensr   c                     | j                  | j                  j                  j                  |d      | j                  j                  _        t        |   |      S NT)r  
transposed)r  _get_resized_lm_headr  ru  r   ru   resize_token_embeddingsrz   r  r}   s     r4   r  z0MobileBertForPreTraining.resize_token_embeddings  sR    %)%>%>HH  &&~RV &? &
" w.n.MMr~   r  r  r  r   r   r   r   r   r   labelsnext_sentence_labelr   rO  rP  c                 
   ||n| j                   j                  }| j                  |||||||	|
|	      }|dd \  }}| j                  ||      \  }}d}|u|st	               } ||j                  d| j                   j                        |j                  d            } ||j                  dd      |j                  d            }||z   }|s||f|dd z   }||f|z   S |S t        ||||j                  |j                        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   r   r   r   r   rO  rP  r?   r   )r  r  r  r   rU  )
ra   r  r)   r  r	   r   r   r  r   rU  )rz   r   r   r   r   r   r   r  r  r   rO  rP  r   rv  rb  rx  r  
total_lossloss_fctmasked_lm_lossnext_sentence_lossr   s                         r4   r   z MobileBertForPreTraining.forward  sG   \ &1%<k$++B]B]//))%'/!5# " 

 *1!&48HH_m4\11
"5"A')H%&7&<&<RAWAW&XZ`ZeZefhZijN!)*@*E*Eb!*LNaNfNfgiNj!k'*<<J')?@712;NF/9/EZMF*Q6Q-/$:!//))
 	
r~   rt   NNNNNNNNNNN)r   r   r   _tied_weights_keysrv   r  r  r   rX   r   r   r  r   r  r  r   r  r  r]   r   r   r   r   r   r   r   s   @r4   r  r    s    ;<Z[,8Nhsm Nr|| N ++F+M+MNk+lm+IXgh 156:59371559-1:>9=<@37M
E,,-M
 !!2!23M
 !!1!12	M

 u//0M
 E--.M
   1 12M
 ))*M
 &e&6&67M
 $E$5$56M
 'u'8'89M
 e//0M
 
u44	5M
 i nM
r~   r  z8MobileBert Model with a `language modeling` head on top.c                       e Zd ZddgZ fdZd Zd Zddee   de	j                  f fdZ eej                  d	             eeeed
d      	 	 	 	 	 	 	 	 	 	 ddeej(                     deej*                     deej(                     deej(                     deej*                     deej*                     deej(                     dee   dee   dee   deeef   fd              Z xZS )MobileBertForMaskedLMr  r  c                     t         |   |       t        |d      | _        t	        |      | _        || _        | j                          y NF)r  )ru   rv   r  r)   rs  r  ra   r  r   s     r4   rv   zMobileBertForMaskedLM.__init__  s=     )&EJ(0 	r~   c                 B    | j                   j                  j                  S rt   r  rn  s    r4   r  z+MobileBertForMaskedLM.get_output_embeddings  r  r~   c                     || j                   j                  _        |j                  | j                   j                  _        y rt   r  r  s     r4   r  z+MobileBertForMaskedLM.set_output_embeddings  r  r~   r  r   c                     | j                  | j                  j                  j                  |d      | j                  j                  _        t        |   |      S r  r  r  s     r4   r  z-MobileBertForMaskedLM.resize_token_embeddings  sR    %)%>%>HH  &&~RV &? &
" w.n.MMr~   r  z'paris'g=
ףp=?r  r  r  expected_outputexpected_lossr   r   r   r   r   r   r  r   rO  rP  c                    |
|
n| j                   j                  }
| j                  ||||||||	|
	      }|d   }| j                  |      }d}|Ft	               } ||j                  d| j                   j                        |j                  d            }|
s|f|dd z   }||f|z   S |S t        |||j                  |j                        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]`
        Nr  r   r   r?   r  logitsr   rU  )
ra   r  r)   r  r	   r   r   r   r   rU  )rz   r   r   r   r   r   r   r  r   rO  rP  r   rv  rx  r  r  r   s                    r4   r   zMobileBertForMaskedLM.forward&  s    6 &1%<k$++B]B]//))%'/!5# " 

 "!* HH_5')H%&7&<&<RAWAW&XZ`ZeZefhZijN')GABK7F3A3M^%.YSYY$!//))	
 	
r~   rt   
NNNNNNNNNN)r   r   r   r  rv   r  r  r   rX   r   r   r  r   r  r  r   r  r   r  r]   r   r   r   r   r   r   r   r   s   @r4   r  r    sn   :<Z[,8Nhsm Nr|| N ++F+M+MNk+lm&"$! 156:59371559-1,0/3&*2
E,,-2
 !!2!232
 !!1!12	2

 u//02
 E--.2
   1 122
 ))*2
 $D>2
 'tn2
 d^2
 
un$	%2
 n2
r~   r  c                   V     e Zd Z fdZdej
                  dej
                  fdZ xZS )MobileBertOnlyNSPHeadc                 l    t         |           t        j                  |j                  d      | _        y r|  )ru   rv   r   r   r   r}  r   s     r4   rv   zMobileBertOnlyNSPHead.__init__d  s'     "		&*<*<a @r~   rb  r   c                 (    | j                  |      }|S rt   )r}  )rz   rb  r  s      r4   r   zMobileBertOnlyNSPHead.forwardh  s    !%!6!6}!E%%r~   r   r   s   @r4   r  r  c  s$    A&U\\ &ell &r~   r  zPMobileBert Model with a `next sentence prediction (classification)` head on top.c                       e Zd Z fdZ eej                  d             eee	      	 	 	 	 	 	 	 	 	 	 dde
ej                     de
ej                     de
ej                     de
ej                     de
ej                     d	e
ej                     d
e
ej                     de
e   de
e   de
e   deeef   fd              Z xZS )#MobileBertForNextSentencePredictionc                     t         |   |       t        |      | _        t	        |      | _        | j                          y rt   )ru   rv   r  r)   r  r  r  r   s     r4   rv   z,MobileBertForNextSentencePrediction.__init__r  s4     )&1(0 	r~   r  r  r   r   r   r   r   r   r  r   rO  rP  r   c                    d|v r+t        j                  dt               |j                  d      }|
|
n| j                  j
                  }
| j                  ||||||||	|
	      }|d   }| j                  |      }d}|2t               } ||j                  dd      |j                  d            }|
s|f|dd z   }||f|z   S |S t        |||j                  |j                        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
        ```r  zoThe `next_sentence_label` argument is deprecated and will be removed in a future version, use `labels` instead.Nr  r   r   r?   r  )warningswarnFutureWarningpopra   r  r)   r  r	   r   r   r   rU  )rz   r   r   r   r   r   r   r  r   rO  rP  kwargsr   rb  r  r  r  r   s                     r4   r   z+MobileBertForNextSentencePrediction.forward{  s   X !F*MM%
 ZZ 56F%0%<k$++B]B]//))%'/!5# " 

  
!%-!8!')H!)*@*E*Eb!*LfkkZ\o!^,.<F7I7U')F2a[aa*#)!//))	
 	
r~   r  )r   r   r   rv   r   r  r  r   r   r  r   r]   r   r   r   r   r   r   r   r   s   @r4   r  r  m  s>   
 ++F+M+MNk+lm+FUde 156:59371559-1,0/3&*Q
E,,-Q
 !!2!23Q
 !!1!12	Q

 u//0Q
 E--.Q
   1 12Q
 ))*Q
 $D>Q
 'tnQ
 d^Q
 
u11	2Q
 f nQ
r~   r  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                       e Zd Z fdZ eej                  d             eee	e
ee      	 	 	 	 	 	 	 	 	 	 ddeej                     deej                     deej                     deej                     deej                     d	eej                     d
eej                     dee   dee   dee   deeej                     e	f   fd              Z xZS )#MobileBertForSequenceClassificationc                 n   t         |   |       |j                  | _        || _        t	        |      | _        |j                  |j                  n|j                  }t        j                  |      | _
        t        j                  |j                  |j                        | _        | j                          y rt   )ru   rv   
num_labelsra   r  r)   classifier_dropoutr   r   r   r   r   r   r>   r  rz   ra   r  r}   s      r4   rv   z,MobileBertForSequenceClassification.__init__  s      ++)&1)/)B)B)NF%%TZTnTn 	 zz"45))F$6$68I8IJ 	r~   r  r  r   r   r   r   r   r   r  r   rO  rP  r   c                 @   |
|
n| j                   j                  }
| j                  ||||||||	|
	      }|d   }| j                  |      }| j	                  |      }d}|| j                   j
                  | j                  dk(  rd| j                   _        nl| j                  dkD  rL|j                  t        j                  k(  s|j                  t        j                  k(  rd| j                   _        nd| j                   _        | j                   j
                  dk(  rIt               }| j                  dk(  r& ||j                         |j                               }n |||      }n| j                   j
                  dk(  r=t               } ||j                  d| j                        |j                  d            }n,| j                   j
                  dk(  rt               } |||      }|
s|f|dd z   }||f|z   S |S t!        |||j"                  |j$                  	      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).
        Nr  r   
regressionsingle_label_classificationmulti_label_classificationr   r?   r  )ra   r  r)   r   r>   problem_typer  r   r]   r   rX   r
   squeezer	   r   r   r   r   rU  )rz   r   r   r   r   r   r   r  r   rO  rP  r   rb  r  r  r  r   s                    r4   r   z+MobileBertForSequenceClassification.forward  s   6 &1%<k$++B]B]//))%'/!5# " 

  
]3/{{''/??a'/;DKK,__q(fllejj.HFLL\a\e\eLe/LDKK,/KDKK,{{''<7"9??a'#FNN$4fnn6FGD#FF3D))-JJ+-B @&++b/R))-II,./Y,F)-)9TGf$EvE'!//))	
 	
r~   r  )r   r   r   rv   r   r  r  r   '_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATIONr   r  _SEQ_CLASS_EXPECTED_OUTPUT_SEQ_CLASS_EXPECTED_LOSSr   r]   r   r   r   r   r   r   r   s   @r4   r  r    sC    ++F+M+MNk+lm:,$2. -11515/3,004)-,0/3&*E
ELL)E
 !.E
 !.	E

 u||,E
 ELL)E
  -E
 &E
 $D>E
 'tnE
 d^E
 
uU\\"$<<	=E
 nE
r~   r  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                       e Zd Z fdZ eej                  d             eee	e
eeee      	 	 	 	 	 	 	 	 	 	 	 ddeej"                     deej"                     deej"                     deej"                     deej"                     d	eej"                     d
eej"                     deej"                     dee   dee   dee   deeej"                     e	f   fd              Z xZS )MobileBertForQuestionAnsweringc                     t         |   |       |j                  | _        t        |d      | _        t        j                  |j                  |j                        | _        | j                          y r  )
ru   rv   r  r  r)   r   r   r   
qa_outputsr  r   s     r4   rv   z'MobileBertForQuestionAnswering.__init__B  sU      ++)&EJ))F$6$68I8IJ 	r~   r  )r  r  r  qa_target_start_indexqa_target_end_indexr  r  r   r   r   r   r   r   start_positionsend_positionsr   rO  rP  r   c                 (   ||n| j                   j                  }| j                  |||||||	|
|	      }|d   }| j                  |      }|j	                  dd      \  }}|j                  d      j                         }|j                  d      j                         }d}||t        |j                               dkD  r|j                  d      }t        |j                               dkD  r|j                  d      }|j                  d      }|j                  d|      }|j                  d|      }t        |      } |||      } |||      }||z   dz  }|s||f|dd z   }||f|z   S |S t        ||||j                  |j                  	      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.
        Nr  r   r   r   r   )ignore_indexr?   )r  start_logits
end_logitsr   rU  )ra   r  r)   r  rQ   r  r   rW   r   clampr	   r   r   rU  )rz   r   r   r   r   r   r   r	  r
  r   rO  rP  r   rv  r  r  r  r  ignored_indexr  
start_lossend_lossr   s                          r4   r   z&MobileBertForQuestionAnswering.forwardL  s   D &1%<k$++B]B]//))%'/!5# " 

 "!*1#)<<r<#: j#++B/::<''+668

&=+D?'')*Q."1"9"9""==%%'(1, - 5 5b 9(--a0M-33A}EO)//=AM']CH!,@J
M:H$x/14J"J/'!"+=F/9/EZMF*Q6Q+%!!//))
 	
r~   r  )r   r   r   rv   r   r  r  r   _CHECKPOINT_FOR_QAr   r  _QA_TARGET_START_INDEX_QA_TARGET_END_INDEX_QA_EXPECTED_OUTPUT_QA_EXPECTED_LOSSr   r]   r   r   r   r   r   r   r   s   @r4   r  r  9  s`    ++F+M+MNk+lm%0$40+' -11515/3,0042604,0/3&*H
ELL)H
 !.H
 !.	H

 u||,H
 ELL)H
  -H
 "%,,/H
  -H
 $D>H
 'tnH
 d^H
 
uU\\"$@@	AH
 nH
r~   r  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                       e Zd Z fdZ eej                  d             eee	e
      	 	 	 	 	 	 	 	 	 	 ddeej                     deej                     deej                     deej                     deej                     d	eej                     d
eej                     dee   dee   dee   deeej                     e	f   fd              Z xZS )MobileBertForMultipleChoicec                 *   t         |   |       t        |      | _        |j                  |j                  n|j
                  }t        j                  |      | _        t        j                  |j                  d      | _        | j                          y r=  )ru   rv   r  r)   r  r   r   r   r   r   r   r>   r  r  s      r4   rv   z$MobileBertForMultipleChoice.__init__  su     )&1)/)B)B)NF%%TZTnTn 	 zz"45))F$6$6: 	r~   z(batch_size, num_choices, sequence_lengthr  r   r   r   r   r   r   r  r   rO  rP  r   c                 L   |
|
n| j                   j                  }
||j                  d   n|j                  d   }|!|j                  d|j	                  d            nd}|!|j                  d|j	                  d            nd}|!|j                  d|j	                  d            nd}|!|j                  d|j	                  d            nd}|1|j                  d|j	                  d      |j	                  d            nd}| j                  ||||||||	|
	      }|d   }| j                  |      }| j                  |      }|j                  d|      }d}|t               } |||      }|
s|f|dd z   }||f|z   S |S t        |||j                  |j                        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   r   r   r  r?   r  )ra   r  rZ   r   r   r)   r   r>   r	   r   r   rU  )rz   r   r   r   r   r   r   r  r   rO  rP  num_choicesr   rb  r  reshaped_logitsr  r  r   s                      r4   r   z#MobileBertForMultipleChoice.forward  s   6 &1%<k$++B]B],5,Aiooa(}GZGZ[\G]>G>SINN2y~~b'9:Y]	M[Mg,,R1D1DR1HImqM[Mg,,R1D1DR1HImqGSG_|((\->->r-BCei ( r=#5#5b#9=;M;Mb;QR 	 //))%'/!5# " 

  
]3/ ++b+6')HOV4D%''!"+5F)-)9TGf$EvE("!//))	
 	
r~   r  )r   r   r   rv   r   r  r  r   r  r   r  r   r]   r   r   r   r   r   r   r   s   @r4   r  r    s@    +#**+UV  &-$ -11515/3,004)-,0/3&*@
ELL)@
 !.@
 !.	@

 u||,@
 ELL)@
  -@
 &@
 $D>@
 'tn@
 d^@
 
uU\\"$==	>@
@
r~   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                       e Zd Z fdZ eej                  d             eee	e
ee      	 	 	 	 	 	 	 	 	 	 ddeej                     deej                     deej                     deej                     deej                     d	eej                     d
eej                     dee   dee   dee   deeej                     e	f   fd              Z xZS ) MobileBertForTokenClassificationc                 d   t         |   |       |j                  | _        t        |d      | _        |j
                  |j
                  n|j                  }t        j                  |      | _	        t        j                  |j                  |j                        | _        | j                          y r  )ru   rv   r  r  r)   r  r   r   r   r   r   r   r>   r  r  s      r4   rv   z)MobileBertForTokenClassification.__init__  s      ++)&EJ)/)B)B)NF%%TZTnTn 	 zz"45))F$6$68I8IJ 	r~   r  r  r   r   r   r   r   r   r  r   rO  rP  r   c                    |
|
n| j                   j                  }
| j                  ||||||||	|
	      }|d   }| j                  |      }| j	                  |      }d}|<t               } ||j                  d| j                        |j                  d            }|
s|f|dd z   }||f|z   S |S t        |||j                  |j                        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]`.
        Nr  r   r   r?   r  )ra   r  r)   r   r>   r	   r   r  r   r   rU  )rz   r   r   r   r   r   r   r  r   rO  rP  r   rv  r  r  r  r   s                    r4   r   z(MobileBertForTokenClassification.forward  s    2 &1%<k$++B]B]//))%'/!5# " 

 "!*,,71')HFKKDOO<fkk"oNDY,F)-)9TGf$EvE$!//))	
 	
r~   r  )r   r   r   rv   r   r  r  r   $_CHECKPOINT_FOR_TOKEN_CLASSIFICATIONr   r  _TOKEN_CLASS_EXPECTED_OUTPUT_TOKEN_CLASS_EXPECTED_LOSSr   r]   r   r   r   r   r   r   r   s   @r4   r  r    s6    ++F+M+MNk+lm7)$40 -11515/3,004)-,0/3&*2
ELL)2
 !.2
 !.	2

 u||,2
 ELL)2
  -2
 &2
 $D>2
 'tn2
 d^2
 
uU\\"$99	:2
 n2
r~   r  )\r   rG   r  dataclassesr   typingr   r   r   r]   r   torch.nnr   r	   r
   activationsr   modeling_outputsr   r   r   r   r   r   r   r   modeling_utilsr   pytorch_utilsr   r   utilsr   r   r   r   r   r   configuration_mobilebertr   
get_loggerr   rE   r  r  r"  r#  r$  r  r  r  r  r  r   r  r  rp   Modulerr   r&   r   r   r   r   r   r	  r  r  r   r&  r1  r5  r;  rK  r[  rd  ri  rs  rz  r  r  MOBILEBERT_START_DOCSTRINGr  r  r  r  r  r  r  r  r  r  r1   r~   r4   <module>r1     s  .  	  ! ) )   A A !	 	 	 . Q  7 
		H	%1 $ (J $l !  ; '     +D '' ! K\6RYY 6 &
9I299 IX7bii 7t299 "/")) /dRYY ryy ryy 0	bii 	!] !]H			 		ryy 	<bii <~'
		 '
T!ryy !&		 " ,!BII !	9 	9* *6 :[ : :B  / d jh
/ h
	h
V  i
8 i
i
X TVpqT
5 T
 rT
n&BII & Z]
*C ]
	]
@  ]
*C ]
]
@  ]
%> ]
]
@  V
"; V
V
r  I
'@ I
I
r~   