
    sg                      d Z ddlmZ ddlZddlmZ ddlmZmZm	Z	m
Z
 ddlZddlZddlmZ ddlmZmZmZmZmZmZmZ dd	lmZmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$ dd
l%m&Z&m'Z'm(Z( ddl)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/ ddl0m1Z1  e.jd                  e3      Z4dZ5dZ6 G d d      Z7 G d de"jp                  jr                        Z: G d de"jp                  jr                        Z; G d de"jp                  jr                        Z< G d de"jp                  jr                        Z= G d de"jp                  jr                        Z> G d de      Z? G d de"jp                  jr                        Z@e# G d  d!e"jp                  jr                               ZAe G d" d#e*             ZBd$ZCd%ZD e,d&eC       G d' d(e?             ZE e,d)eC       G d* d+e?e7             ZF G d, d-e"jp                  jr                        ZG e,d.eC       G d/ d0e?e             ZH e,d1eC       G d2 d3e?e             ZI e,d4eC       G d5 d6e?e              ZJ e,d7eC       G d8 d9e?e             ZK e,d:eC       G d; d<e?e             ZLg d=ZMy)>zTF 2.0 ALBERT model.    )annotationsN)	dataclass)DictOptionalTupleUnion   )get_tf_activation)TFBaseModelOutputTFBaseModelOutputWithPoolingTFMaskedLMOutputTFMultipleChoiceModelOutputTFQuestionAnsweringModelOutputTFSequenceClassifierOutputTFTokenClassifierOutput)TFMaskedLanguageModelingLossTFModelInputTypeTFMultipleChoiceLossTFPreTrainedModelTFQuestionAnsweringLossTFSequenceClassificationLossTFTokenClassificationLossget_initializerkeraskeras_serializableunpack_inputs)check_embeddings_within_bounds
shape_liststable_softmax)ModelOutputadd_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardloggingreplace_return_docstrings   )AlbertConfigzalbert/albert-base-v2r'   c                      e Zd ZdZddZy)TFAlbertPreTrainingLossz
    Loss function suitable for ALBERT pretraining, that is, the task of pretraining a language model by combining SOP +
    MLM. .. note:: Any label of -100 will be ignored (along with the corresponding logits) in the loss computation.
    c           
         t         j                  j                  dt         j                  j                  j                        }| j
                  j                  r~t        j                  t        j                  |d   d      d      }t        j                  t        j                  |d   dt        |d         d	   f      |
      }t        j                  t        j                  |d   d      |
      }t        j                  t        j                  |d   d      d      }t        j                  t        j                  |d   d      |
      }t        j                  t        j                  |d   d      |
      }	 |||      }
 ||	|      }t        j                  |
dt        |      d   f      }
t        j                  |
d      }
|
|z   S  |t        j                  j                  |d         |d         }t        j                  |d   dk7  |j                         }||z  }t        j"                  |      t        j"                  |      z  }t        j                  |d   d      } |t        j                  j                  |d         |      }t        j                  |d   dk7  |j                         }||z  }t        j"                  |      t        j"                  |      z  }t        j                  ||z   d      S )NT)from_logits	reductionlabels)tensorshapeir   r.      )r0   masksentence_order_labelr&   )r.   r2   )y_truey_pred)input_tensoraxisdtype)r&   )r   lossesSparseCategoricalCrossentropy	ReductionNONEconfigtf_legacy_losstf	not_equalreshapeboolean_maskr   reduce_meannnrelucastr:   
reduce_sum)selfr-   logitsloss_fnmasked_lm_active_lossmasked_lm_reduced_logitsmasked_lm_labelssentence_order_active_losssentence_order_reduced_logitsr4   masked_lm_losssentence_order_lossunmasked_lm_losseslm_loss_maskmasked_lm_lossesreduced_masked_lm_loss
sop_logitsunmasked_sop_losssop_loss_maskmasked_sop_lossreduced_masked_sop_losss                        `/var/www/html/venv/lib/python3.12/site-packages/transformers/models/albert/modeling_tf_albert.pyhf_compute_lossz'TFAlbertPreTrainingLoss.hf_compute_lossJ   s   ,,<<Y^YeYeYoYoYtYt<u;;%% %'LL6(CS[`1acg$h!')zz2z&QR)?TUV?W:XY*($  "zz)9GNc  *,

&)?"@NPT*& -/OOzz'BIc-) $&??zz0F)GuU\v$  %,<E]^N")1ENk"lZZ~b*UhJijkJlEmnN^^aPN!$777 %BEEJJvh7G,HQWXYQZ[ wwvh/47?Q?W?WX-<!#/?!@2==Q]C^!^ZZq	73
#255::f=S6T+U^hi'= >$ FN_NeNef+m;"$--"@2==Q^C_"_zz03JJDQQ    N)r-   	tf.TensorrK   r`   returnr`   )__name__
__module____qualname____doc__r^    r_   r]   r)   r)   D   s    
-Rr_   r)   c                  X     e Zd ZdZd fdZddZ	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 ddZ xZS )	TFAlbertEmbeddingszGConstruct the embeddings from word, position and token_type embeddings.c                V   t        |   di | || _        |j                  | _        |j                  | _        |j
                  | _        t        j                  j                  |j                  d      | _
        t        j                  j                  |j                        | _        y )N	LayerNormepsilonnameraterf   )super__init__r?   embedding_sizemax_position_embeddingsinitializer_ranger   layersLayerNormalizationlayer_norm_epsrj   Dropouthidden_dropout_probdropoutrJ   r?   kwargs	__class__s      r]   rq   zTFAlbertEmbeddings.__init__}   s    "6"$33'-'E'E$!'!9!988AVAV]h8i||++1K1K+Lr_   c                   t        j                  d      5  | j                  d| j                  j                  | j
                  gt        | j                              | _        d d d        t        j                  d      5  | j                  d| j                  j                  | j
                  gt        | j                              | _
        d d d        t        j                  d      5  | j                  d| j                  | j
                  gt        | j                              | _        d d d        | j                  ry d| _        t        | dd       et        j                  | j                  j                         5  | j                  j#                  d d | j                  j
                  g       d d d        y y # 1 sw Y   [xY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   y xY w)	Nword_embeddingsweight)rm   r1   initializertoken_type_embeddings
embeddingsposition_embeddingsTrj   )rA   
name_scope
add_weightr?   
vocab_sizerr   r   rt   r   type_vocab_sizer   rs   r   builtgetattrrj   rm   buildrJ   input_shapes     r]   r   zTFAlbertEmbeddings.build   s   ]],- 	//{{--t/B/BC+D,B,BC * DK	 ]]23 	)-!{{22D4G4GH+D,B,BC *9 *D&	 ]]01 	'+!33T5H5HI+D,B,BC (7 (D$	 ::
4d+7t~~223 O$$dD$++2L2L%MNO O 81	 		 		 	O Os2   AF< AG	*AG?3G!<G	GG!G*c                >   ||t        d      |At        || j                  j                         t	        j
                  | j                  |      }t        |      dd }|t	        j                  |d      }|2t	        j                  t	        j                  ||d   |z         d	      }t	        j
                  | j                  |      }t	        j
                  | j                  |      }	||z   |	z   }
| j                  |

      }
| j                  |
|      }
|
S )z
        Applies embedding based on inputs tensor.

        Returns:
            final_embeddings (`tf.Tensor`): output embedding tensor.
        Nz5Need to provide either `input_ids` or `input_embeds`.)paramsindicesr.   r   dimsvaluer&   )startlimit)r8   inputsr   training)
ValueErrorr   r?   r   rA   gatherr   r   fillexpand_dimsranger   r   rj   rz   )rJ   	input_idsposition_idstoken_type_idsinputs_embedspast_key_values_lengthr   r   position_embedstoken_type_embedsfinal_embeddingss              r]   callzTFAlbertEmbeddings.call   s    !6TUU *9dkk6L6LMIIT[[)LM /4!WW+Q?N>>5[^Nd=delmL ))4+C+C\ZIIT-G-GQ_`(?:=NN>>1A>B<</?(<Sr_   r?   r'   N)NNNNr   F)r   r`   r   r`   r   r`   r   r`   r   boolra   r`   )rb   rc   rd   re   rq   r   r   __classcell__r}   s   @r]   rh   rh   z   sf    QMO@  $"&$(#' & &   &  "	& 
 !&  &  
& r_   rh   c                  V     e Zd ZdZd fdZddZ	 d	 	 	 	 	 	 	 	 	 	 	 d	dZd
dZ xZS )TFAlbertAttentionzQContains the complete attention sublayer, including both dropouts and layer norm.c                   t        |   di | |j                  |j                  z  dk7  r&t	        d|j                   d|j                   d      |j                  | _        t        |j                  |j                  z        | _        | j                  | j                  z  | _        t        j                  | j                        | _
        |j                  | _        t        j                  j                  | j                  t        |j                         d      | _        t        j                  j                  | j                  t        |j                         d      | _        t        j                  j                  | j                  t        |j                         d      | _        t        j                  j                  |j                  t        |j                         d	      | _        t        j                  j+                  |j,                  d
      | _        t        j                  j1                  |j2                        | _        t        j                  j1                  |j6                        | _        || _        y )Nr   zThe hidden size (z6) is not a multiple of the number of attention heads ()queryunitskernel_initializerrm   keyr   denserj   rk   rn   rf   )rp   rq   hidden_sizenum_attention_headsr   intattention_head_sizeall_head_sizemathsqrtsqrt_att_head_sizeoutput_attentionsr   ru   Denser   rt   r   r   r   r   rv   rw   rj   rx   attention_probs_dropout_probattention_dropoutry   output_dropoutr?   r{   s      r]   rq   zTFAlbertAttention.__init__   s   "6" : ::a?#F$6$6#7 8''-'A'A&B!E 
 $*#=#= #&v'9'9F<V<V'V#W !558P8PP"&))D,D,D"E!'!9!9\\''$$IaIa9bip ( 

 <<%%$$IaIa9bin & 
 \\''$$IaIa9bip ( 

 \\''$$IaIa9bip ( 

 88AVAV]h8i!&!5!56;^;^!5!_#ll228R8R2Sr_   c                    t        j                  ||d| j                  | j                  f      }t        j                  |g d      S )Nr.   r/   r   r2   r&   r	   perm)rA   rC   r   r   	transpose)rJ   r0   
batch_sizes      r]   transpose_for_scoresz&TFAlbertAttention.transpose_for_scores   s;    6*b$BZBZ\`\t\t1uv ||F66r_   c                   t        |      d   }| j                  |      }| j                  |      }| j                  |      }	| j	                  ||      }
| j	                  ||      }| j	                  |	|      }t        j                  |
|d      }t        j                  | j                  |j                        }t        j                  ||      }|t        j                  ||      }t        |d      }| j                  ||      }|t        j                  ||      }t        j                  ||      }t        j                  |g d	
      }t        j                   ||d| j"                  f      }|r||fn|f}|d   }| j%                  |      }| j'                  ||      }| j)                  ||z         }|f|dd  z   }|S )Nr   r   T)transpose_br9   r.   )rK   r8   r   r   r   r/   r&   )r   r   r   r   r   rA   matmulrH   r   r:   divideaddr   r   multiplyr   rC   r   r   r   rj   )rJ   r7   attention_mask	head_maskr   r   r   mixed_query_layermixed_key_layermixed_value_layerquery_layer	key_layervalue_layerattention_scoresdkattention_probscontext_layerself_outputshidden_statesattention_outputoutputss                        r]   r   zTFAlbertAttention.call   s     -a0
 JJlJ;((,(7 JJlJ;//0A:N--ozJ	//0A:N 99[)NWWT,,4D4J4JK99%5r:%!vv&6G )0@rJ 00RZ0[   kk/9EO		/;?]F 

-
BPTPbPb?cd;L7S`Rb$Q

-
8++=8+T>>1M>N $%QR(88r_   c                   | j                   ry d| _         t        | dd       dt        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        t        | dd       dt        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        t        | dd       dt        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        t        | dd       dt        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        t        | dd       et        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        y y # 1 sw Y   xY w# 1 sw Y   lxY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   y xY w)NTr   r   r   r   rj   )r   r   rA   r   r   rm   r   r?   r   r   r   r   rj   r   s     r]   r   zTFAlbertAttention.build.  s   ::
4$'3tzz/ H

  $dkk.E.E!FGH4%1txx}}- FdDKK,C,CDEF4$'3tzz/ H

  $dkk.E.E!FGH4$'3tzz/ H

  $dkk.E.E!FGH4d+7t~~223 L$$dD$++2I2I%JKL L 8H HF FH HH HL Ls<   3I<3I-3I&3I33I?II#&I03I<?Jr   )r0   r`   r   r   ra   r`   F)r7   r`   r   r`   r   r`   r   r   r   r   ra   Tuple[tf.Tensor]r   )	rb   rc   rd   re   rq   r   r   r   r   r   s   @r]   r   r      s\    [B7 33 "3 	3
  3 3 
3jLr_   r   c                  J     e Zd Zd fdZ	 d	 	 	 	 	 	 	 	 	 	 	 ddZddZ xZS )TFAlbertLayerc                   t        |   d	i | t        |d      | _        t        j
                  j                  |j                  t        |j                        d      | _
        t        |j                  t              rt        |j                        | _        n|j                  | _        t        j
                  j                  |j                   t        |j                        d      | _        t        j
                  j%                  |j&                  d      | _        t        j
                  j+                  |j,                        | _        || _        y )
N	attentionrm   ffnr   
ffn_outputfull_layer_layer_normrk   rn   rf   )rp   rq   r   r   r   ru   r   intermediate_sizer   rt   r   
isinstance
hidden_actstrr
   
activationr   r   rv   rw   r   rx   ry   rz   r?   r{   s      r]   rq   zTFAlbertLayer.__init__D  s   "6"*6D<<%%**vOgOg?hot & 
 f''-/0A0ABDO$//DO,,,,$$IaIa9biu - 
 &+\\%D%D))0G &E &
" ||++1K1K+Lr_   c                
   | j                  |||||      }| j                  |d         }| j                  |      }| j                  |      }| j	                  ||      }| j                  ||d   z         }|f|dd  z   }|S )N)r7   r   r   r   r   r   r   r   r&   )r   r   r   r   rz   r   )	rJ   r   r   r   r   r   attention_outputsr   r   s	            r]   r   zTFAlbertLayer.callZ  s     !NN&)/ + 
 XX%6q%9X:
__Z0
__J_7
\\h\G
22*GXYZG[:[2\ !"%6qr%::r_   c                   | j                   ry d| _         t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       dt        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        t        | dd       dt        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        t        | dd       et        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        y y # 1 sw Y   _xY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   y xY w)NTr   r   r   r   )r   r   rA   r   r   rm   r   r   r?   r   r   r   r   r   s     r]   r   zTFAlbertLayer.buildt  s   ::
4d+7t~~223 +$$T*+4%1txx}}- FdDKK,C,CDEF4t,8t334 S%%tT4;;3P3P&QRS40$7Ct99>>? X**00$dkk>U>U1VWX X D+ +F FS SX Xs0   G%3G3G3G)GGG&)G2r   r   )r   r`   r   r`   r   r`   r   r   r   r   ra   r   r   rb   rc   rd   rq   r   r   r   r   s   @r]   r   r   C  sR    8   " 	
    
4Xr_   r   c                  N     e Zd Zd fdZ	 d	 	 	 	 	 	 	 	 	 	 	 	 	 ddZddZ xZS )TFAlbertLayerGroupc                    t        |   di | t        |j                        D cg c]  }t	        |d|        c}| _        y c c}w )Nzalbert_layers_._r   rf   )rp   rq   r   inner_group_numr   albert_layersrJ   r?   r|   ir}   s       r]   rq   zTFAlbertLayerGroup.__init__  sN    "6" INfNdNdHe
CDM&)9!'=>
 
s   Ac                    |rdnd }|rdnd }t        | j                        D ].  \  }	}
|r||fz   } |
||||	   ||      }|d   }|s&||d   fz   }0 |r||fz   }t        d |||fD              S )Nrf   )r   r   r   r   r   r   r&   c              3  &   K   | ]	  }||  y wr   rf   .0vs     r]   	<genexpr>z*TFAlbertLayerGroup.call.<locals>.<genexpr>  s     h1Z[ZgQh   )	enumerater   tuple)rJ   r   r   r   r   output_hidden_statesr   layer_hidden_stateslayer_attentionslayer_indexalbert_layerlayer_outputs               r]   r   zTFAlbertLayerGroup.call  s     %9bd!22)243E3E)F 	I%K#&9]<L&L#'+-#K0"3!L )OM #3|A6H#H 	I"  "58H"Hh0CEU Vhhhr_   c                    | j                   ry d| _         t        | dd       K| j                  D ];  }t        j                  |j
                        5  |j                  d        d d d        = y y # 1 sw Y   IxY w)NTr   )r   r   r   rA   r   rm   r   rJ   r   layers      r]   r   zTFAlbertLayerGroup.build  sr    ::
4$/;++ &]]5::. &KK%& && <& &s   A..A7	r   r   )r   r`   r   r`   r   r`   r   r   r  r   r   r   ra   *Union[TFBaseModelOutput, Tuple[tf.Tensor]]r   r   r   s   @r]   r   r     sd    
  i  i " i 	 i
   i # i  i 
4 iD&r_   r   c                  R     e Zd Zd fdZ	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZddZ xZS )TFAlbertTransformerc                   t        |   di | |j                  | _        |j                  | _        t	        |j                  |j                  z        | _        t        j                  j                  |j                  t        |j                        d      | _        t        |j                        D cg c]  }t        |d|        c}| _        || _        y c c}w )Nembedding_hidden_mapping_inr   zalbert_layer_groups_._r   rf   )rp   rq   num_hidden_layersnum_hidden_groupsr   layers_per_groupr   ru   r   r   r   rt   r  r   r   albert_layer_groupsr?   r   s       r]   rq   zTFAlbertTransformer.__init__  s    "6"!'!9!9!'!9!9 #F$<$<v?W?W$W X+0<<+=+=$$.v/G/GH. ,> ,
( TYY_YqYqSr$
NOv.DQC,HI$
  $
s   5Cc           	        | j                  |      }|rdnd }|r|fnd }	t        | j                        D ]z  }
t        |
| j                  | j                  z  z        } | j
                  |   ||||| j                  z  |dz   | j                  z   |||      }|d   }|r||d   z   }|su|	|fz   }	| |st        d ||	|fD              S t        ||	|      S )	Nr   rf   r&   )r   r   r   r   r  r   r   r.   c              3  &   K   | ]	  }||  y wr   rf   r   s     r]   r  z+TFAlbertTransformer.call.<locals>.<genexpr>  s     hqZ[Zghr  )last_hidden_stater   
attentions)	r  r   r  r   r  r  r  r  r   )rJ   r   r   r   r   r  return_dictr   all_attentionsall_hidden_statesr   	group_idxlayer_group_outputs                r]   r   zTFAlbertTransformer.call  s    888N0d0D],$t--. 	IAA!7!7$:P:P!PQRI!D!9!9)!D+-#I0E0E$EUVZ^ZoZoHop"3%9!" /q1M !/2DR2H!H#$58H$H!#	I& h]4E~$Vhhh +;LYg
 	
r_   c                   | j                   ry d| _         t        | dd       dt        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        t        | dd       K| j                  D ];  }t        j                  |j
                        5  |j                  d        d d d        = y y # 1 sw Y   bxY w# 1 sw Y   UxY w)NTr  r  )
r   r   rA   r   r  rm   r   r?   rr   r  r  s      r]   r   zTFAlbertTransformer.build  s    ::
46=It??DDE a0066dDKKD^D^7_`a4.5A11 &]]5::. &KK%& && Ba a& &s   3CC+C(+C4	r   r   )r   r`   r   r`   r   r`   r   r   r  r   r  r   r   r   ra   r  r   r   r   s   @r]   r  r    sf    2 &
 &
 "&
 	&

  &
 #&
 &
 &
 
4&
P
&r_   r  c                      e Zd ZdZeZdZy)TFAlbertPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    albertN)rb   rc   rd   re   r'   config_classbase_model_prefixrf   r_   r]   r"  r"    s    
  L r_   r"  c                  P     e Zd Zd fdZd	dZd
dZddZddZddZddZ	 xZ
S )TFAlbertMLMHeadc                   t        |   di | || _        |j                  | _        t        j
                  j                  |j                  t        |j                        d      | _	        t        |j                  t              rt        |j                        | _        n|j                  | _        t        j
                  j                  |j                   d      | _        || _        y )Nr   )r   rm   rj   rk   rf   )rp   rq   r?   rr   r   ru   r   r   rt   r   r   r   r   r
   r   rv   rw   rj   decoder)rJ   r?   input_embeddingsr|   r}   s       r]   rq   zTFAlbertMLMHead.__init__  s    "6"$33\\''!!ofF^F^6_fm ( 

 f''-/0A0ABDO$//DO88AVAV]h8i (r_   c                   | j                  | j                  j                  fddd      | _        | j                  | j                  j                  fddd      | _        | j
                  ry d| _        t        | dd       dt        j                  | j                  j                        5  | j                  j                  d d | j                  j                  g       d d d        t        | dd       et        j                  | j                  j                        5  | j                  j                  d d | j                  j                  g       d d d        y y # 1 sw Y   |xY w# 1 sw Y   y xY w)NzerosTbias)r1   r   	trainablerm   zdecoder/biasr   rj   )r   r?   r   r-  decoder_biasr   r   rA   r   r   rm   r   r   rj   rr   r   s     r]   r   zTFAlbertMLMHead.build  s5   OO4;;+A+A*CQXdhouOv	 OO;;))+DWe , 
 ::
4$'3tzz/ H

  $dkk.E.E!FGH4d+7t~~223 O$$dD$++2L2L%MNO O 8H HO Os   )3E3E#E #E,c                    | j                   S r   )r)  rJ   s    r]   get_output_embeddingsz%TFAlbertMLMHead.get_output_embeddings/  s    ||r_   c                `    || j                   _        t        |      d   | j                   _        y Nr   )r)  r   r   r   rJ   r   s     r]   set_output_embeddingsz%TFAlbertMLMHead.set_output_embeddings2  s$    #",U"3A"6r_   c                4    | j                   | j                  dS )Nr-  r/  r8  r1  s    r]   get_biaszTFAlbertMLMHead.get_bias6  s    		43D3DEEr_   c                l    |d   | _         |d   | _        t        |d         d   | j                  _        y )Nr-  r/  r   )r-  r/  r   r?   r   r5  s     r]   set_biaszTFAlbertMLMHead.set_bias9  s4    &M	!.1!+E&M!:1!=r_   c                   | j                  |      }| j                  |      }| j                  |      }t        |      d   }t	        j
                  |d| j                  g      }t	        j                  || j                  j                  d      }t	        j
                  |d|| j                  j                  g      }t        j                  j                  || j                        }|S )	Nr   )r0   r&   r.   r/   T)abr   )r   r-  )r   r   rj   r   rA   rC   rr   r   r)  r   r?   r   rF   bias_addr/  )rJ   r   
seq_lengths      r]   r   zTFAlbertMLMHead.call>  s    

-
86m<}5a8


-DDWDW?XY		MT\\5H5HVZ[

-JPTP[P[PfPf?gh]ARARSr_   )r?   r'   r*  keras.layers.Layerr   ra   rA  r   ztf.Variable)ra   zDict[str, tf.Variable])r   r`   ra   r`   )rb   rc   rd   rq   r   r2  r6  r9  r;  r   r   r   s   @r]   r'  r'    s(    (&O 7F>

r_   r'  c                       e Zd ZeZdd fdZd	dZd
dZd Ze		 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd       Z
ddZ xZS )TFAlbertMainLayerc                   t        |   di | || _        t        |d      | _        t        |d      | _        |rFt        j                  j                  |j                  t        |j                        dd      | _        y d | _        y )Nr   r   encodertanhpooler)r   r   r   rm   rf   )rp   rq   r?   rh   r   r  rG  r   ru   r   r   r   rt   rI  )rJ   r?   add_pooling_layerr|   r}   s       r]   rq   zTFAlbertMainLayer.__init__O  s    "6",V,G*6	B ! LL((#263K3K#L!	   	  	r_   c                    | j                   S r   )r   r1  s    r]   get_input_embeddingsz&TFAlbertMainLayer.get_input_embeddingsa  s    r_   c                `    || j                   _        t        |      d   | j                   _        y r4  )r   r   r   r   r5  s     r]   set_input_embeddingsz&TFAlbertMainLayer.set_input_embeddingsd  s$    !&%/%6q%9"r_   c                    t         )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
        )NotImplementedError)rJ   heads_to_prunes     r]   _prune_headszTFAlbertMainLayer._prune_headsh  s
    
 "!r_   c           	        ||t        d      |t        |      }n|t        |      d d }nt        d      |t        j                  |d      }|t        j                  |d      }| j	                  |||||
      }t        j
                  ||d   dd|d   f      }t        j                  ||j                        }t        j                  d	|j                        }t        j                  d
|j                        }t        j                  t        j                  ||      |      }|t        d g| j                  j                  z  }| j                  ||||||	|
      }|d   }| j                  | j                  |d d df         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_embedsr&   r   r   )r   r   r   r   r   r9   g      ?g     )r   r   r   r   r  r  r   r   )r  pooler_outputr   r  )r   r   rA   r   r   rC   rH   r:   constantr   subtractrP  r?   r  rG  rI  r   r   r  )rJ   r   r   r   r   r   r   r   r  r  r   r   embedding_outputextended_attention_maskone_cstten_thousand_cstencoder_outputssequence_outputpooled_outputs                      r]   r   zTFAlbertMainLayer.callo  s     ]%>cdd"$Y/K&$]3CR8KTUU!WW+Q?N!WW+Q?N??%)' + 
 #%**^k!naQRT_`aTb=c"d #%''*AIYI_I_"`++c)9)?)?@;;x7G7M7MN"$++bkk'CZ.[]m"n  %%!>!>>I,,*2/!5# ' 
 *!,EI[[E\?1a4+@Abf  #$ $
 ,-')77&11	
 	
r_   c                   | j                   ry d| _         t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       et        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        y y # 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   y xY w)NTr   rG  rI  )r   r   rA   r   r   rm   r   rG  rI  r?   r   r   s     r]   r   zTFAlbertMainLayer.build  s   ::
4t,8t334 ,%%d+,4D)5t||001 )""4()44(4t{{//0 I!!4t{{/F/F"GHI I 5, ,) )I Is$   D<%E?3E<EEE)T)r?   r'   rJ  r   rB  rC  
NNNNNNNNNF)r   TFModelInputType | Noner   np.ndarray | tf.Tensor | Noner   ra  r   ra  r   ra  r   ra  r   Optional[bool]r  rb  r  rb  r   r   ra   5Union[TFBaseModelOutputWithPooling, Tuple[tf.Tensor]]r   )rb   rc   rd   r'   r$  rq   rL  rN  rR  r   r   r   r   r   s   @r]   rE  rE  K  s    L
$:"  .28<8<6:377;,0/3&*W
*W
 6W
 6	W

 4W
 1W
 5W
 *W
 -W
 $W
 W
 
?W
 W
rIr_   rE  c                  X    e Zd ZU dZdZded<   dZded<   dZded<   dZded<   dZ	ded	<   y)
TFAlbertForPreTrainingOutputa4  
    Output type of [`TFAlbertForPreTraining`].

    Args:
        prediction_logits (`tf.Tensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
            Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
        sop_logits (`tf.Tensor` of shape `(batch_size, 2)`):
            Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
            before SoftMax).
        hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `tf.Tensor` (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(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `tf.Tensor` (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.
    Nr`   lossprediction_logitsrX   zTuple[tf.Tensor] | Noner   r  )
rb   rc   rd   re   rf  __annotations__rg  rX   r   r  rf   r_   r]   re  re    s>    , D)#'y' J	 -1M*1*.J'.r_   re  av	  

    This model inherits from [`TFPreTrainedModel`]. 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 [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
    as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
    behavior.

    <Tip>

    TensorFlow models and layers in `transformers` accept two formats as input:

    - having all inputs as keyword arguments (like PyTorch models), or
    - having all inputs as a list, tuple or dict in the first positional argument.

    The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
    and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
    pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
    format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
    the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
    positional argument:

    - a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
    - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
    `model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
    - a dictionary with one or several input Tensors associated to the input names given in the docstring:
    `model({"input_ids": input_ids, "token_type_ids": token_type_ids})`

    Note that when creating models and layers with
    [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
    about any of this, as you can just pass inputs like you would to any other Python function!

    </Tip>

    Args:
        config ([`AlbertConfig`]): 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.
a  
    Args:
        input_ids (`Numpy array` or `tf.Tensor` of shape `({0})`):
            Indices of input sequence tokens in the vocabulary.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
            [`PreTrainedTokenizer.encode`] for details.

            [What are input IDs?](../glossary#input-ids)
        attention_mask (`Numpy array` or `tf.Tensor` 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 (`Numpy array` or `tf.Tensor` 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 (`Numpy array` or `tf.Tensor` 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 (`Numpy array` or `tf.Tensor` 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 (`tf.Tensor` 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. This argument can be used only in eager mode, in graph mode the value in the
            config will be used instead.
        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. This argument can be used only in eager mode, in graph mode the value in the config will be
            used instead.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
            eager mode, in graph mode the value will always be set to True.
        training (`bool`, *optional*, defaults to `False`):
            Whether or not to use the model in training mode (some modules like dropout modules have different
            behaviors between training and evaluation).
z`The bare Albert Model transformer outputting raw hidden-states without any specific head on top.c                       e Zd Zd fdZe eej                  d             ee	e
e      	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd                     Zd	dZ xZS )
TFAlbertModelc                P    t        |   |g|i | t        |d      | _        y )Nr#  r   )rp   rq   rE  r#  rJ   r?   r   r|   r}   s       r]   rq   zTFAlbertModel.__init__^  s(    3&3F3'X>r_   batch_size, sequence_length
checkpointoutput_typer$  c                <    | j                  |||||||||	|

      }|S )N
r   r   r   r   r   r   r   r  r  r   )r#  )rJ   r   r   r   r   r   r   r   r  r  r   r   s               r]   r   zTFAlbertModel.callc  s<    ( ++))%'/!5#  
 r_   c                    | j                   ry d| _         t        | dd       Nt        j                  | j                  j
                        5  | j                  j                  d        d d d        y y # 1 sw Y   y xY w)NTr#  )r   r   rA   r   r#  rm   r   r   s     r]   r   zTFAlbertModel.build  si    ::
44(4t{{//0 (!!$'( ( 5( (s   A11A:r   r_  )r   r`  r   ra  r   ra  r   ra  r   ra  r   ra  r   rb  r  rb  r  rb  r   rb  ra   rc  r   )rb   rc   rd   rq   r   r#   ALBERT_INPUTS_DOCSTRINGformatr!   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOCr   r   r   r   s   @r]   rj  rj  Y  s    
?
 *+B+I+IJg+hi&0$ .28<8<6:377;,0/3&*#(* 6 6	
 4 1 5 * - $ ! 
? j 8(r_   rj  z
    Albert Model with two heads on top for pretraining: a `masked language modeling` head and a `sentence order
    prediction` (classification) head.
    c                       e Zd ZdgZd fdZd	dZe eej                  d             e
ee      	 	 	 	 	 	 	 	 	 	 	 	 d
	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd                     ZddZ xZS )TFAlbertForPreTrainingpredictions.decoder.weightc                    t        |   |g|i | |j                  | _        t        |d      | _        t        || j                  j                  d      | _        t        |d      | _	        y )Nr#  r   predictionsr*  rm   sop_classifier)
rp   rq   
num_labelsrE  r#  r'  r   r|  TFAlbertSOPHeadr~  rl  s       r]   rq   zTFAlbertForPreTraining.__init__  sa    3&3F3 ++'X>*6DKKDZDZano-f;KLr_   c                    | j                   S r   r|  r1  s    r]   get_lm_headz"TFAlbertForPreTraining.get_lm_head      r_   rm  rp  r$  c                N   | j                  |||||||||	|
      }|dd \  }}| j                  |      }| j                  ||      }d}|
 |d|
i}||d<   | j                  |||f      }|	s||f|dd z   }||f|z   S |S t	        ||||j
                  |j                  	      S )
ao  
        Return:

        Example:

        ```python
        >>> import tensorflow as tf
        >>> from transformers import AutoTokenizer, TFAlbertForPreTraining

        >>> tokenizer = AutoTokenizer.from_pretrained("albert/albert-base-v2")
        >>> model = TFAlbertForPreTraining.from_pretrained("albert/albert-base-v2")

        >>> input_ids = tf.constant(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True))[None, :]
        >>> # Batch size 1
        >>> outputs = model(input_ids)

        >>> prediction_logits = outputs.prediction_logits
        >>> sop_logits = outputs.sop_logits
        ```rr  Nr2   )r   )r]  r   r-   r4   r-   rK   )rf  rg  rX   r   r  )r#  r|  r~  r^   re  r   r  )rJ   r   r   r   r   r   r   r   r  r  r-   r4   r   r   r\  r]  prediction_scores
sop_scores
total_lossd_labelsoutputs                        r]   r   zTFAlbertForPreTraining.call  s
   L ++))%'/!5#  
 *1!& ,,?,K((}x(X

"6"B &)H/CH+,--XGXZdFe-fJ'4wqr{BF/9/EZMF*Q6Q+/!!//))
 	
r_   c                   | j                   ry d| _         t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       Nt        j                  | j                  j
                        5  | j                  j                  d        d d d        y y # 1 sw Y   xY w# 1 sw Y   qxY w# 1 sw Y   y xY w)NTr#  r|  r~  )	r   r   rA   r   r#  rm   r   r|  r~  r   s     r]   r   zTFAlbertForPreTraining.build  s
   ::
44(4t{{//0 (!!$'(4-9t//445 -  &&t,-4)40<t22778 0##))$/0 0 =( (- -0 0s$   D%%D1?D=%D.1D:=Er   rB  NNNNNNNNNNNF)r   r`  r   ra  r   ra  r   ra  r   ra  r   ra  r   rb  r  rb  r  rb  r-   ra  r4   ra  r   rb  ra   z5Union[TFAlbertForPreTrainingOutput, Tuple[tf.Tensor]]r   )rb   rc   rd   "_keys_to_ignore_on_load_unexpectedrq   r  r   r#   rt  ru  r%   re  rw  r   r   r   r   s   @r]   ry  ry    s    +H)H&M  *+B+I+IJg+hi+GVef .28<8<6:377;,0/3&*04>B#(C
*C
 6C
 6	C

 4C
 1C
 5C
 *C
 -C
 $C
 .C
 <C
 !C
 
?C
 g j C
J0r_   ry  c                  0     e Zd Zd fdZddZddZ xZS )r  c                   t        |   di | t        j                  j	                  |j
                        | _        t        j                  j                  |j                  t        |j                        d      | _        || _        y )Nrn   
classifierr   rf   )rp   rq   r   ru   rx   classifier_dropout_probrz   r   r  r   rt   r  r?   r{   s      r]   rq   zTFAlbertSOPHead.__init__  sp    "6"||++1O1O+P,,,,##.v/G/GH - 

 r_   c                P    | j                  ||      }| j                  |      }|S )Nr   r   )rz   r  )rJ   r]  r   dropout_pooled_outputrK   s        r]   r   zTFAlbertSOPHead.call	  s+     $MH U(=>r_   c                (   | j                   ry d| _         t        | dd       et        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        y y # 1 sw Y   y xY w)NTr  )	r   r   rA   r   r  rm   r   r?   r   r   s     r]   r   zTFAlbertSOPHead.build  s    ::
4t,8t334 M%%tT4;;3J3J&KLM M 9M Ms   3BBr   )r]  r`   r   r   ra   r`   r   r   r   s   @r]   r  r    s    	Mr_   r  z4Albert Model with a `language modeling` head on top.c                       e Zd ZddgZd	 fdZd
dZe eej                  d             e
ee      	 	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd                     ZddZ xZS )TFAlbertForMaskedLMrI  rz  c                    t        |   |g|i | t        |dd      | _        t	        || j                  j
                  d      | _        y )NFr#  rJ  rm   r|  r}  )rp   rq   rE  r#  r'  r   r|  rl  s       r]   rq   zTFAlbertForMaskedLM.__init__  sF    3&3F3'%hW*6DKKDZDZanor_   c                    | j                   S r   r  r1  s    r]   r  zTFAlbertForMaskedLM.get_lm_head#  r  r_   rm  r  c                   | j                  |||||||||	|
      }|d   }| j                  ||      }|
dn| j                  |
|      }|	s|f|dd z   }||f|z   S |S t        |||j                  |j
                        S )a  
        labels (`tf.Tensor` 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]`

        Returns:

        Example:

        ```python
        >>> import tensorflow as tf
        >>> from transformers import AutoTokenizer, TFAlbertForMaskedLM

        >>> tokenizer = AutoTokenizer.from_pretrained("albert/albert-base-v2")
        >>> model = TFAlbertForMaskedLM.from_pretrained("albert/albert-base-v2")

        >>> # add mask_token
        >>> inputs = tokenizer(f"The capital of [MASK] is Paris.", return_tensors="tf")
        >>> logits = model(**inputs).logits

        >>> # retrieve index of [MASK]
        >>> mask_token_index = tf.where(inputs.input_ids == tokenizer.mask_token_id)[0][1]
        >>> predicted_token_id = tf.math.argmax(logits[0, mask_token_index], axis=-1)
        >>> tokenizer.decode(predicted_token_id)
        'france'
        ```

        ```python
        >>> labels = tokenizer("The capital of France is Paris.", return_tensors="tf")["input_ids"]
        >>> labels = tf.where(inputs.input_ids == tokenizer.mask_token_id, labels, -100)
        >>> outputs = model(**inputs, labels=labels)
        >>> round(float(outputs.loss), 2)
        0.81
        ```
        rr  r   )r   r   Nr  r2   rf  rK   r   r  )r#  r|  r^   r   r   r  )rJ   r   r   r   r   r   r   r   r  r  r-   r   r   r\  r  rf  r  s                    r]   r   zTFAlbertForMaskedLM.call&  s    j ++))%'/!5#  
 "!* ,,?U],^~t4+?+?vVg+?+h')GABK7F)-)9TGf$EvE$!//))	
 	
r_   c                   | j                   ry d| _         t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       Nt        j                  | j                  j
                        5  | j                  j                  d        d d d        y y # 1 sw Y   exY w# 1 sw Y   y xY w)NTr#  r|  )r   r   rA   r   r#  rm   r   r|  r   s     r]   r   zTFAlbertForMaskedLM.buildw  s    ::
44(4t{{//0 (!!$'(4-9t//445 -  &&t,- - :( (- -s   C%CCC r   rB  NNNNNNNNNNF)r   r`  r   ra  r   ra  r   ra  r   ra  r   ra  r   rb  r  rb  r  rb  r-   ra  r   rb  ra   z)Union[TFMaskedLMOutput, Tuple[tf.Tensor]]r   )rb   rc   rd   r  rq   r  r   r#   rt  ru  r%   r   rw  r   r   r   r   s   @r]   r  r    s	    +45R)S&p  *+B+I+IJg+hi+;/Z .28<8<6:377;,0/3&*04#(L
*L
 6L
 6	L

 4L
 1L
 5L
 *L
 -L
 $L
 .L
 !L
 
3L
 [ j L
\	-r_   r  z
    Albert 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dgZdgZd fdZe eej                  d             e
deedd      	 	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd	                     Zdd
Z xZS )!TFAlbertForSequenceClassificationr|  rz   c                f   t        |   |g|i | |j                  | _        t        |d      | _        t
        j                  j                  |j                        | _	        t
        j                  j                  |j                  t        |j                        d      | _        || _        y )Nr#  r   rn   r  r   )rp   rq   r  rE  r#  r   ru   rx   r  rz   r   r   rt   r  r?   rl  s       r]   rq   z*TFAlbertForSequenceClassification.__init__  s    3&3F3 ++'X>||++1O1O+P,,,,##H`H`8aht - 
 r_   rm  zvumichien/albert-base-v2-imdbz	'LABEL_1'gQ?)ro  rp  r$  expected_outputexpected_lossc                *   | j                  |||||||||	|
      }|d   }| j                  ||      }| j                  |      }|
dn| j                  |
|      }|	s|f|dd z   }||f|z   S |S t	        |||j
                  |j                        S )	a  
        labels (`tf.Tensor` 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).
        rr  r&   r   r   Nr  r2   r  )r#  rz   r  r^   r   r   r  )rJ   r   r   r   r   r   r   r   r  r  r-   r   r   r]  rK   rf  r  s                    r]   r   z&TFAlbertForSequenceClassification.call  s    : ++))%'/!5#  
  
MHM6~t4+?+?vV\+?+]Y,F)-)9TGf$EvE)!//))	
 	
r_   c                   | j                   ry d| _         t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       et        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        y y # 1 sw Y   |xY w# 1 sw Y   y xY wNTr#  r  
r   r   rA   r   r#  rm   r   r  r?   r   r   s     r]   r   z'TFAlbertForSequenceClassification.build      ::
44(4t{{//0 (!!$'(4t,8t334 M%%tT4;;3J3J&KLM M 9( (M M   C"%3C."C+.C7r   r  )r   r`  r   ra  r   ra  r   ra  r   ra  r   ra  r   rb  r  rb  r  rb  r-   ra  r   rb  ra   z3Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]r   )rb   rc   rd   r  _keys_to_ignore_on_load_missingrq   r   r#   rt  ru  r!   r   rw  r   r   r   r   s   @r]   r  r    s    +9)9&'1l#
 *+B+I+IJg+hi2.$# .28<8<6:377;,0/3&*04#(/
*/
 6/
 6	/

 4/
 1/
 5/
 */
 -/
 $/
 ./
 !/
 
=/
 j /
b	Mr_   r  z
    Albert 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ddgZdgZd	 fdZe eej                  d             e
eee      	 	 	 	 	 	 	 	 	 	 	 d
	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd                     ZddZ xZS )TFAlbertForTokenClassificationrI  r|  rz   c                   t        |   |g|i | |j                  | _        t        |dd      | _        |j
                  |j
                  n|j                  }t        j                  j                  |      | _
        t        j                  j                  |j                  t        |j                        d      | _        || _        y )NFr#  r  rn   r  r   )rp   rq   r  rE  r#  r  ry   r   ru   rx   rz   r   r   rt   r  r?   )rJ   r?   r   r|   r  r}   s        r]   rq   z'TFAlbertForTokenClassification.__init__  s    3&3F3 ++'%hW --9 **++ 	 
 ||++1H+I,,,,##H`H`8aht - 
 r_   rm  rn  c                *   | j                  |||||||||	|
      }|d   }| j                  ||      }| j                  |      }|
dn| j                  |
|      }|	s|f|dd z   }||f|z   S |S t	        |||j
                  |j                        S )	z
        labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
        rr  r   r   r   Nr  r2   r  )r#  rz   r  r^   r   r   r  )rJ   r   r   r   r   r   r   r   r  r  r-   r   r   r\  rK   rf  r  s                    r]   r   z#TFAlbertForTokenClassification.call  s    2 ++))%'/!5#  
 "!*,,o,Q8~t4+?+?vV\+?+]Y,F)-)9TGf$EvE&!//))	
 	
r_   c                   | j                   ry d| _         t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       et        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        y y # 1 sw Y   |xY w# 1 sw Y   y xY wr  r  r   s     r]   r   z$TFAlbertForTokenClassification.build4  r  r  r   r  )r   r`  r   ra  r   ra  r   ra  r   ra  r   ra  r   rb  r  rb  r  rb  r-   ra  r   rb  ra   z0Union[TFTokenClassifierOutput, Tuple[tf.Tensor]]r   )rb   rc   rd   r  r  rq   r   r#   rt  ru  r!   rv  r   rw  r   r   r   r   s   @r]   r  r    s    +4^)D&'1l#" *+B+I+IJg+hi&+$ .28<8<6:377;,0/3&*04#(-
*-
 6-
 6	-

 4-
 1-
 5-
 *-
 --
 $-
 .-
 !-
 
:-
 j -
^	Mr_   r  z
    Albert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
    layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
    c                       e Zd ZddgZd fdZe eej                  d             e	de
edddd	
      	 	 	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd                     ZddZ xZS )TFAlbertForQuestionAnsweringrI  r|  c                
   t        |   |g|i | |j                  | _        t        |dd      | _        t
        j                  j                  |j                  t        |j                        d      | _
        || _        y )NFr#  r  
qa_outputsr   )rp   rq   r  rE  r#  r   ru   r   r   rt   r  r?   rl  s       r]   rq   z%TFAlbertForQuestionAnswering.__init__K  st    3&3F3 ++'%hW,,,,##H`H`8aht - 
 r_   rm  zvumichien/albert-base-v2-squad2      z'a nice puppet'gq=
ףp@)ro  rp  r$  qa_target_start_indexqa_target_end_indexr  r  c                   | j                  |||||||||	|
      }|d   }| j                  |      }t        j                  |dd      \  }}t        j                  |d      }t        j                  |d      }d}|
 |d	|
i}||d
<   | j                  |||f      }|	s||f|dd z   }||f|z   S |S t        ||||j                  |j                        S )a  
        start_positions (`tf.Tensor` 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 (`tf.Tensor` 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.
        rr  r   r   r2   r.   )r   num_or_size_splitsr8   )inputr8   Nstart_positionend_positionr  )rf  start_logits
end_logitsr   r  )	r#  r  rA   splitsqueezer^   r   r   r  )rJ   r   r   r   r   r   r   r   r  r  start_positionsend_positionsr   r   r\  rK   r  r  rf  r-   r  s                        r]   r   z!TFAlbertForQuestionAnswering.callV  s   H ++))%'/!5#  
 "!*8#%88&QUW#X jzz2>ZZjr:
&=+D&8F%2F>"''v|Z>X'YD"J/'!"+=F)-)9TGf$EvE-%!!//))
 	
r_   c                   | j                   ry d| _         t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       et        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        y y # 1 sw Y   |xY w# 1 sw Y   y xY w)NTr#  r  )
r   r   rA   r   r#  rm   r   r  r?   r   r   s     r]   r   z"TFAlbertForQuestionAnswering.build  r  r  r   r  )r   r`  r   ra  r   ra  r   ra  r   ra  r   ra  r   rb  r  rb  r  rb  r  ra  r  ra  r   rb  ra   z7Union[TFQuestionAnsweringModelOutput, Tuple[tf.Tensor]]r   )rb   rc   rd   r  rq   r   r#   rt  ru  r!   r   rw  r   r   r   r   s   @r]   r  r  @  s    +4^)D&	 *+B+I+IJg+hi42$ ) .28<8<6:377;,0/3&*9=7;#(<
*<
 6<
 6	<

 4<
 1<
 5<
 *<
 -<
 $<
 7<
 5<
 !<
 
A<
 j <
|	Mr_   r  z
    Albert 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ddgZdgZd	 fdZe eej                  d             e
eee      	 	 	 	 	 	 	 	 	 	 	 d
	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd                     ZddZ xZS )TFAlbertForMultipleChoicerI  r|  rz   c                0   t        |   |g|i | t        |d      | _        t        j
                  j                  |j                        | _        t        j
                  j                  dt        |j                        d      | _        || _        y )Nr#  r   rn   r&   r  r   )rp   rq   rE  r#  r   ru   rx   ry   rz   r   r   rt   r  r?   rl  s       r]   rq   z"TFAlbertForMultipleChoice.__init__  s~    3&3F3'X>||++1K1K+L,,,,8P8P(QXd - 
 r_   z(batch_size, num_choices, sequence_lengthrn  c                   |t        |      d   }t        |      d   }nt        |      d   }t        |      d   }|t        j                  |d|f      nd}|t        j                  |d|f      nd}|t        j                  |d|f      nd}|t        j                  |d|f      nd}|&t        j                  |d|t        |      d   f      nd}| j                  |||||||||	|
      }|d   }| j	                  ||      }| j                  |	      }t        j                  |d|f      }|
dn| j                  |
|
      }|	s|f|dd z   }||f|z   S |S t        |||j                  |j                        S )a5  
        labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`
            where `num_choices` is the size of the second dimension of the input tensors. (See `input_ids` above)
        Nr&   r2   r.   r/   r	   rr  r   r   r  r  )
r   rA   rC   r#  rz   r  r^   r   r   r  )rJ   r   r   r   r   r   r   r   r  r  r-   r   num_choicesr@  flat_input_idsflat_attention_maskflat_token_type_idsflat_position_idsflat_inputs_embedsr   r]  rK   reshaped_logitsrf  r  s                            r]   r   zTFAlbertForMultipleChoice.call  s   6  $Y/2K#I.q1J$]3A6K#M215JDMDYIJ/?@_cIWIcBJJnR4DEim 	 JXIcBJJnR4DEim 	 HTG_BJJl2z2BCei 	
 ( JJmB
J}D]^_D`3ab 	
 ++$..*,/!5#  
  
MHM6**F2{:KL~t4+?+?vVe+?+f%''!"+5F)-)9TGf$EvE*"!//))	
 	
r_   c                   | j                   ry d| _         t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       et        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        y y # 1 sw Y   |xY w# 1 sw Y   y xY wr  r  r   s     r]   r   zTFAlbertForMultipleChoice.build  r  r  r   r  )r   r`  r   ra  r   ra  r   ra  r   ra  r   ra  r   rb  r  rb  r  rb  r-   ra  r   rb  ra   z4Union[TFMultipleChoiceModelOutput, Tuple[tf.Tensor]]r   )rb   rc   rd   r  r  rq   r   r#   rt  ru  r!   rv  r   rw  r   r   r   r   s   @r]   r  r    s    +4^)D&'1l# *+B+I+IJt+uv&/$ .28<8<6:377;,0/3&*04#(E
*E
 6E
 6	E

 4E
 1E
 5E
 *E
 -E
 $E
 .E
 !E
 
>E
 w E
N	Mr_   r  )	r"  rj  ry  r  r  r  r  r  rE  )Nre   
__future__r   r   dataclassesr   typingr   r   r   r   numpynp
tensorflowrA   activations_tfr
   modeling_tf_outputsr   r   r   r   r   r   r   modeling_tf_utilsr   r   r   r   r   r   r   r   r   r   r   tf_utilsr   r   r   utilsr    r!   r"   r#   r$   r%   configuration_albertr'   
get_loggerrb   loggerrv  rw  r)   ru   Layerrh   r   r   r   r  r"  r'  rE  re  ALBERT_START_DOCSTRINGrt  rj  ry  r  r  r  r  r  r  __all__rf   r_   r]   <module>r     s     "  ! / /   /      S R  / 
		H	%-  3R 3RlQ ++ Q hrL** rLj@XELL&& @XF1&++ 1&hD&%,,,, D&N!/ !=ell(( =@ II** II IIX /; / /<( T5 p f/(+ /(	/(d  d046M d0d0NMell(( M6 PRhig-13O g- jg-T  TM(?A] TMTMn  UM%<>W UMUMp  aM#:<S aMaMH  fM 79M fMfMR
r_   