
    sg;                       d Z ddlmZ ddlZddl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 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) ddl*m+Z+  e)jX                  e-      Z.dZ/dZ0 G d dejb                  jd                        Z3 G d dejb                  jd                        Z4 G d dejb                  jd                        Z5 G d dejb                  jd                        Z6 G d dejb                  jd                        Z7e G d dejb                  jd                               Z8 G d de      Z9dZ:dZ; e'de:       G d  d!e9             Z< G d" d#ejb                  jd                        Z= e'd$e:       G d% d&e9e             Z> e'd'e:       G d( d)e9e             Z? e'd*e:       G d+ d,e9e             Z@ e'd-e:       G d. d/e9e             ZA e'd0e:       G d1 d2e9e             ZBy)3z
TF 2.0 DistilBERT model
    )annotationsN)OptionalTupleUnion   )get_tf_activation)TFBaseModelOutput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)add_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardlogging   )DistilBertConfigzdistilbert-base-uncasedr"   c                  2     e Zd ZdZ fdZddZddZ xZS )TFEmbeddingszGConstruct the embeddings from word, position and token_type embeddings.c                B   t        |   di | || _        |j                  | _        |j                  | _        |j
                  | _        t        j                  j                  dd      | _	        t        j                  j                  |j                        | _        y )N-q=	LayerNormepsilonname)rate )super__init__configdiminitializer_rangemax_position_embeddingsr   layersLayerNormalizationr'   Dropoutdropoutselfr/   kwargs	__class__s      h/var/www/html/venv/lib/python3.12/site-packages/transformers/models/distilbert/modeling_tf_distilbert.pyr.   zTFEmbeddings.__init__D   sy    "6"::!'!9!9'-'E'E$88[8Y||+++@    c                   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   y xY w)	Nword_embeddingsweight)r1   )r*   shapeinitializerposition_embeddings
embeddingsTr'   )tf
name_scope
add_weightr/   
vocab_sizer0   r   r1   r?   r2   rB   builtgetattrr'   r*   buildr8   input_shapes     r;   rJ   zTFEmbeddings.buildM   s:   ]],- 	//{{--txx8+d>T>TU * DK	 ]]01 	'+!33TXX>+d>T>TU (7 (D$	 ::
4d+7t~~223 D$$dD$++//%BCD D 8#	 		 	D Ds%   AEAE 3E,E E),E5c                   ||J |At        || j                  j                         t        j                  | j
                  |      }t        |      dd }|/t        j                  t        j                  d|d         d      }t        j                  | j                  |      }||z   }| j                  |      }| j                  ||      }|S )	z
        Applies embedding based on inputs tensor.

        Returns:
            final_embeddings (`tf.Tensor`): output embedding tensor.
        N)paramsindicesr   )startlimitaxis)inputs)rU   training)r   r/   rG   rD   gatherr?   r   expand_dimsrangerB   r'   r6   )r8   	input_idsposition_idsinputs_embedsrV   rL   position_embedsfinal_embeddingss           r;   callzTFEmbeddings.callc   s     %-*?@@ *9dkk6L6LMIIT[[)LM /4>>"((+b/*RYZ[L))4+C+C\Z(?:>>1A>B<</?(<Sr<   N)NNNF)__name__
__module____qualname____doc__r.   rJ   r_   __classcell__r:   s   @r;   r$   r$   A   s    QAD, r<   r$   c                  4     e Zd Z fdZd ZddZddZ xZS )TFMultiHeadSelfAttentionc                   t        |   d	i | |j                  | _        |j                  | _        t        j
                  j                  |j                        | _        |j                  | _	        | j                  | j                  z  dk(  s!J d| j                   d| 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#               | _        || _        y )
Nr   Hidden size " not dividable by number of heads q_linkernel_initializerr*   k_linv_linout_linr,   )r-   r.   n_headsr0   r   r3   r5   attention_dropoutr6   output_attentionsDenser   r1   rl   ro   rp   rq   setpruned_headsr/   r7   s      r;   r.   z!TFMultiHeadSelfAttention.__init__~   sn   "6"~~::||++F,D,DE!'!9!9xx$,,&!+v|DHH:Eghlhthtgu-vv+\\''JJ?6;S;S+T[b ( 

 \\''JJ?6;S;S+T[b ( 

 \\''JJ?6;S;S+T[b ( 

 ||))JJ?6;S;S+T[d * 
  Er<   c                    t         r`   NotImplementedError)r8   headss     r;   prune_headsz$TFMultiHeadSelfAttention.prune_heads       !!r<   c           	     ,    t        |      \  }}	t        |      d   }
t         j                   j                  z        t	        j
                  t        j                        dd|
g} fd} fd} | j                  |            } | j                  |            } | j                  |            }t	        j
                  |t        j                        }t	        j                  |t        j                  j                  t	        j
                  t        j                                    }t	        j
                  ||j                        }t	        j                  ||d      }t	        j                   ||      }t	        j
                  ||j                        }|dd|z
  z  z
  }t#        |d	
      } j%                  ||      }|||z  }t	        j                  ||      } ||      } j'                  |      }|r||fS |fS )a  
        Parameters:
            query: tf.Tensor(bs, seq_length, dim)
            key: tf.Tensor(bs, seq_length, dim)
            value: tf.Tensor(bs, seq_length, dim)
            mask: tf.Tensor(bs, seq_length)

        Returns:
            weights: tf.Tensor(bs, n_heads, seq_length, seq_length) Attention weights context: tf.Tensor(bs,
            seq_length, dim) Contextualized layer. Optional: only if `output_attentions=True`
        r!   dtypec           	     v    t        j                  t        j                  | dj                  f      d      S )zseparate headsrP   r      r!   r   perm)rD   	transposereshaperr   xbsdim_per_headr8   s    r;   r@   z,TFMultiHeadSelfAttention.call.<locals>.shape   s-    <<

1r2t||\.R SZfggr<   c                z    t        j                  t        j                  | d      dj                  z  f      S )zgroup headsr   r   rP   )rD   r   r   rr   r   s    r;   unshapez.TFMultiHeadSelfAttention.call.<locals>.unshape   s0    ::bll1<@2r4<<ZfKfBghhr<   T)transpose_bgꌠ9Y>)Fg      ?rP   rS   rV   )r   intr0   rr   rD   castint32rl   ro   rp   float32multiplymathrsqrtr   matmulr   r   r6   rq   )r8   querykeyvaluemask	head_maskrt   rV   q_lengthr0   k_lengthmask_reshaper@   r   qkvscoresweightscontextr   r   s   `                   @@r;   r_   zTFMultiHeadSelfAttention.call   s    'u-Hcc?1% 488dll23ww|288<Aq(+	h	i $**U#$$**S/"$**U#$GGARZZ(KK277==RZZ)PQRGGAQWW%1aT2zz$- wwt6<<0$#*-- b1,,w,:  	)G))GQ''",,w'W%%: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       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)NTrl   ro   rp   rq   )rH   rI   rD   rE   rl   r*   rJ   r/   r0   ro   rp   rq   rK   s     r;   rJ   zTFMultiHeadSelfAttention.build   s   ::
4$'3tzz/ @

  $dkkoo!>?@4$'3tzz/ @

  $dkkoo!>?@4$'3tzz/ @

  $dkkoo!>?@4D)5t||001 B""D$#@AB B 6@ @@ @@ @B Bs0   3G<3G(-3G43H G%(G14G= H	Fr`   )ra   rb   rc   r.   r|   r_   rJ   re   rf   s   @r;   rh   rh   }   s    4"6pBr<   rh   c                  .     e Zd Z fdZddZddZ xZS )TFFFNc                   t        |   di | t        j                  j	                  |j
                        | _        t        j                  j                  |j                  t        |j                        d      | _
        t        j                  j                  |j                  t        |j                        d      | _        t        |j                        | _        || _        y )Nlin1rm   lin2r,   )r-   r.   r   r3   r5   r6   ru   
hidden_dimr   r1   r   r0   r   r   
activationr/   r7   s      r;   r.   zTFFFN.__init__   s    "6"||++FNN;LL&&/&BZBZ2[bh ' 
	 LL&&JJ?6;S;S+T[a ' 
	 ,F,=,=>r<   c                    | j                  |      }| j                  |      }| j                  |      }| j                  ||      }|S )Nr   )r   r   r   r6   )r8   inputrV   r   s       r;   r_   z
TFFFN.call   sB    IIeOOAIIaLLLXL.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       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   )rH   rI   rD   rE   r   r*   rJ   r/   r0   r   r   rK   s     r;   rJ   zTFFFN.build   s    ::
4&2tyy~~. ?		tT[[__ =>?4&2tyy~~. F		tT[[-C-C DEF F 3? ?F Fs   3C9<3D9DDr   r`   ra   rb   rc   r.   r_   rJ   re   rf   s   @r;   r   r      s    
	Fr<   r   c                  .     e Zd Z fdZddZddZ xZS )TFTransformerBlockc                   t        |   di | |j                  | _        |j                  | _        |j                  | _        t
        j                  j                  |j                        | _        |j                  | _	        |j                  | _
        |j                  |j                  z  dk(  s!J d|j                   d|j                          t        |d      | _        t
        j                  j                  dd      | _        t        |d	      | _        t
        j                  j                  dd
      | _        || _        y )Nr   rj   rk   	attentionr*   r&   sa_layer_normr(   ffnoutput_layer_normr,   )r-   r.   rr   r0   r   r   r3   r5   r6   r   rt   rh   r   r4   r   r   r   r   r/   r7   s      r;   r.   zTFTransformerBlock.__init__  s
   "6"~~:: ++||++FNN; ++!'!9!9 JJ'1,	Y&**%GGWX	Y, 2&{K"\\<<UQ`<ae,!&!@!@Uh!@!ir<   c           	         | j                  |||||||      }|r|\  }}n|d   }| j                  ||z         }| j                  ||      }| j                  ||z         }|f}	|rf|	z   }	|	S )aI  
        Parameters:
            x: tf.Tensor(bs, seq_length, dim)
            attn_mask: tf.Tensor(bs, seq_length)

        Outputs: sa_weights: tf.Tensor(bs, n_heads, seq_length, seq_length) The attention weights ffn_output:
        tf.Tensor(bs, seq_length, dim) The output of the transformer block contextualization.
        r   r   )r   r   r   r   )
r8   r   	attn_maskr   rt   rV   	sa_output
sa_weights
ffn_outputoutputs
             r;   r_   zTFTransformerBlock.call  s     NN1aIyBS^fNg	$-!Iz "!I&&y1}5	 XXi(X;
++J,BC
 ]V+F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       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   Hx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   )rH   rI   rD   rE   r   r*   rJ   r   r/   r0   r   r   rK   s     r;   rJ   zTFTransformerBlock.build6  sz   ::
4d+7t~~223 +$$T*+4$/;t11667 H""(($dkkoo)FGH4%1txx}}- %t$%4,d3?t55::; L&&,,dD$++//-JKL L @+ +H H% %L Ls0   F-%3F:G03G-F7:GGGr   r`   r   rf   s   @r;   r   r     s    *6Lr<   r   c                  .     e Zd Z fdZddZddZ xZS )TFTransformerc                    t        |   di | |j                  | _        |j                  | _        |j                  | _        t        |j                        D cg c]  }t        |d|        c}| _        y c c}w )Nzlayer_._r   r,   )r-   r.   n_layersoutput_hidden_statesrt   rY   r   layer)r8   r/   r9   ir:   s       r;   r.   zTFTransformer.__init__I  si    "6"$*$?$?!!'!9!9OTU[UdUdOef!(nEf
fs   A;c                l   |rdnd}|rdnd}	|}
t        | j                        D ]b  \  }}|r||
fz   } ||
|||   ||      }|d   }
|rt        |      dk(  sJ |d   }|	|fz   }	At        |      dk(  rPJ dt        |       d	        |r||
fz   }|st        d
 |
||	fD              S t	        |
||	      S )a  
        Parameters:
            x: tf.Tensor(bs, seq_length, dim) Input sequence embedded.
            attn_mask: tf.Tensor(bs, seq_length) Attention mask on the sequence.

        Returns:
            hidden_state: tf.Tensor(bs, seq_length, dim)
                Sequence of hidden states in the last (top) layer
            all_hidden_states: Tuple[tf.Tensor(bs, seq_length, dim)]
                Tuple of length n_layers with the hidden states from each layer.
                Optional: only if output_hidden_states=True
            all_attentions: Tuple[tf.Tensor(bs, n_heads, seq_length, seq_length)]
                Tuple of length n_layers with the attention weights from each layer
                Optional: only if output_attentions=True
        r,   Nr   rP   r   r   r!   zIncorrect number of outputs z instead of 1c              3  &   K   | ]	  }||  y wr`   r,   ).0r   s     r;   	<genexpr>z%TFTransformer.call.<locals>.<genexpr>y  s     gqYZYfgs   )last_hidden_statehidden_states
attentions)	enumerater   lentupler	   )r8   r   r   r   rt   r   return_dictrV   all_hidden_statesall_attentionshidden_stater   layer_modulelayer_outputsr   s                  r;   r_   zTFTransformer.callQ  s   " #7BD0d(4 	qOA|#$5$G!(y)A,PaltuM(,L =)Q...*1-
!/:-!?=)Q.p2NsS`OaNbbo0pp.	q   1\O Cg\3Dn$Uggg *:KXf
 	
r<   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   )rH   rI   r   rD   rE   r*   rJ   )r8   rL   r   s      r;   rJ   zTFTransformer.build~  sp    ::
4$'3 &]]5::. &KK%& && 4& &s   A..A7	r   r`   r   rf   s   @r;   r   r   H  s    g+
Z&r<   r   c                  ^     e Zd ZeZ fdZd Zd Zd Ze		 	 	 	 	 	 	 	 dd       Z
ddZ xZS )	TFDistilBertMainLayerc                   t        |   di | || _        |j                  | _        |j                  | _        |j
                  | _        |j                  | _        t        |d      | _	        t        |d      | _        y )NrC   r   transformerr,   )r-   r.   r/   num_hidden_layersrt   r   use_return_dictr   r$   rC   r   r   r7   s      r;   r.   zTFDistilBertMainLayer.__init__  so    "6"!'!9!9!'!9!9$*$?$?!!11&vLA(mDr<   c                    | j                   S r`   )rC   r8   s    r;   get_input_embeddingsz*TFDistilBertMainLayer.get_input_embeddings  s    r<   c                b    || j                   _        |j                  d   | j                   _        y Nr   )rC   r?   r@   rG   r8   r   s     r;   set_input_embeddingsz*TFDistilBertMainLayer.set_input_embeddings  s"    !&%*[[^"r<   c                    t         r`   ry   )r8   heads_to_prunes     r;   _prune_headsz"TFDistilBertMainLayer._prune_heads  r}   r<   c	           	     v   ||t        d      |t        |      }	n|t        |      d d }	nt        d      |t        j                  |	      }t        j                  |t        j
                        }|t        d g| j                  z  }| j                  ||      }
| j                  |
||||||      }|S )NzDYou cannot specify both input_ids and inputs_embeds at the same timerP   z5You have to specify either input_ids or inputs_embedsr   )r\   r   )

ValueErrorr   rD   onesr   r   rz   r   rC   r   )r8   rZ   attention_maskr   r\   rt   r   r   rV   rL   embedding_outputtfmr_outputs               r;   r_   zTFDistilBertMainLayer.call  s      ]%>cdd"$Y/K&$]3CR8KTUU!WW[1NrzzB  %%!7!77I??9M?R&&  ' 
 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)NTrC   r   )rH   rI   rD   rE   rC   r*   rJ   r   rK   s     r;   rJ   zTFDistilBertMainLayer.build  s    ::
4t,8t334 ,%%d+,4-9t//445 -  &&t,- - :, ,- -s   C%CCC NNNNNNNFr`   )ra   rb   rc   r"   config_classr.   r   r   r   r   r_   rJ   re   rf   s   @r;   r   r     sQ    #L
E4"  !. .`	-r<   r   c                      e Zd ZdZeZdZy)TFDistilBertPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    
distilbertN)ra   rb   rc   rd   r"   r   base_model_prefixr,   r<   r;   r   r     s    
 $L$r<   r   a	  

    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>

    Parameters:
        config ([`DistilBertConfig`]): 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)
        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).
zfThe bare DistilBERT encoder/transformer outputting raw hidden-states without any specific head on top.c                       e Zd Z fdZe eej                  d             ee	e
e      	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd                     ZddZ xZS )	TFDistilBertModelc                P    t        |   |g|i | t        |d      | _        y )Nr   r   )r-   r.   r   r   r8   r/   rU   r9   r:   s       r;   r.   zTFDistilBertModel.__init__D  s(    3&3F3/\Jr<   batch_size, sequence_length
checkpointoutput_typer   c	           
     8    | j                  ||||||||      }	|	S )NrZ   r   r   r\   rt   r   r   rV   )r   )
r8   rZ   r   r   r\   rt   r   r   rV   outputss
             r;   r_   zTFDistilBertModel.callH  s6    $ //)'/!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   )rH   rI   rD   rE   r   r*   rJ   rK   s     r;   rJ   zTFDistilBertModel.buildf  si    ::
4t,8t334 ,%%d+, , 9, ,s   A11A:r   )rZ   TFModelInputType | Noner   np.ndarray | tf.Tensor | Noner   r  r\   r  rt   Optional[bool]r   r  r   r  rV   r  returnz*Union[TFBaseModelOutput, Tuple[tf.Tensor]]r`   )ra   rb   rc   r.   r   r   DISTILBERT_INPUTS_DOCSTRINGformatr   _CHECKPOINT_FOR_DOCr	   _CONFIG_FOR_DOCr_   rJ   re   rf   s   @r;   r   r   ?  s    
K *+F+M+MNk+lm&%$ .28<377;,0/3&*#(* 6 1	
 5 * - $ ! 
4 n .,r<   r   c                  F     e Zd Z fdZ fdZd Zd Zd Zd Zd Z	 xZ
S )TFDistilBertLMHeadc                b    t        |   di | || _        |j                  | _        || _        y )Nr,   )r-   r.   r/   r0   input_embeddings)r8   r/   r  r9   r:   s       r;   r.   zTFDistilBertLMHead.__init__p  s/    "6":: !1r<   c                    | j                  | j                  j                  fddd      | _        t        |   |       y )NzerosTbias)r@   rA   	trainabler*   )rF   r/   rG   r  r-   rJ   )r8   rL   r:   s     r;   rJ   zTFDistilBertLMHead.buildz  s7    OO4;;+A+A*CQXdhouOv	k"r<   c                    | j                   S r`   )r  r   s    r;   get_output_embeddingsz(TFDistilBertLMHead.get_output_embeddings  s    $$$r<   c                `    || j                   _        t        |      d   | j                   _        y r   )r  r?   r   rG   r   s     r;   set_output_embeddingsz(TFDistilBertLMHead.set_output_embeddings  s(    ',$+5e+<Q+?(r<   c                    d| j                   iS )Nr  )r  r   s    r;   get_biaszTFDistilBertLMHead.get_bias  s    		""r<   c                X    |d   | _         t        |d         d   | j                  _        y )Nr  r   )r  r   r/   rG   r   s     r;   set_biaszTFDistilBertLMHead.set_bias  s'    &M	!+E&M!:1!=r<   c                t   t        |      d   }t        j                  |d| j                  g      }t        j                  || j
                  j                  d      }t        j                  |d|| j                  j                  g      }t        j                  j                  || j                        }|S )N)tensorr!   rP   )r  r@   T)abr   )r   r  )r   rD   r   r0   r   r  r?   r/   rG   nnbias_addr  )r8   r   
seq_lengths      r;   r_   zTFDistilBertLMHead.call  s    }5a8


-DHH~N		MT5J5J5Q5Q_cd

-JPTP[P[PfPf?gh]Kr<   )ra   rb   rc   r.   rJ   r  r  r  r  r_   re   rf   s   @r;   r  r  o  s'    1#
%@#>r<   r  z?DistilBert Model with a `masked language modeling` head on top.c                       e Zd Z fdZd Zd Ze eej                  d             e
eee      	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d	d                     Zd
dZ xZS )TFDistilBertForMaskedLMc                   t        |   |g|i | || _        t        |d      | _        t
        j                  j                  |j                  t        |j                        d      | _        t        |j                        | _        t
        j                  j                  dd      | _        t#        || j                  j$                  d      | _        y )	Nr   r   vocab_transformrm   r&   vocab_layer_normr(   vocab_projector)r-   r.   r/   r   r   r   r3   ru   r0   r   r1   r%  r   r   actr4   r&  r  rC   r'  r   s       r;   r.   z TFDistilBertForMaskedLM.__init__  s    3&3F3/\J$||11JJ?6;S;S+T[l  2  
 %V%6%67 % ? ?Tf ? g1&$//:T:T[lmr<   c                    | j                   S r`   )r'  r   s    r;   get_lm_headz#TFDistilBertForMaskedLM.get_lm_head  s    ###r<   c                    t        j                  dt               | j                  dz   | j                  j                  z   S )NzMThe method get_prefix_bias_name is deprecated. Please use `get_bias` instead./)warningswarnFutureWarningr*   r'  r   s    r;   get_prefix_bias_namez,TFDistilBertForMaskedLM.get_prefix_bias_name  s1    egtuyy3!5!5!:!:::r<   r   r   c
           
     b   | j                  ||||||||	      }
|
d   }| j                  |      }| j                  |      }| 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, 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]`
        r   r   Nr!   losslogitsr   r   )	r   r%  r(  r&  r'  hf_compute_lossr
   r   r   )r8   rZ   r   r   r\   rt   r   r   labelsrV   distilbert_outputr   prediction_logitsr3  r   s                  r;   r_   zTFDistilBertForMaskedLM.call  s    2 !OO)'/!5# , 	
 *!, 00? HH%67 112CD 001BC~t4+?+?HY+Z'),=ab,AAF)-)9TGf$EvE$+99(33	
 	
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       Nt        j                  | j                  j
                        5  | j                  j                  d        d d d        y y # 1 sw Y   Hx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'  )rH   rI   rD   rE   r   r*   rJ   r%  r/   r0   r&  r'  rK   s     r;   rJ   zTFDistilBertForMaskedLM.build  s   ::
4t,8t334 ,%%d+,4*D1=t33889 J$$**D$+HIJ4+T2>t4499: K%%++T4,IJK4*D1=t33889 1$$**401 1 >, ,J JK K1 1s0   F-%3F:3GG-F7:GGG	NNNNNNNNF)rZ   r  r   r  r   r  r\   r  rt   r  r   r  r   r  r6  r  rV   r  r  z)Union[TFMaskedLMOutput, Tuple[tf.Tensor]]r`   )ra   rb   rc   r.   r*  r0  r   r   r  r  r   r	  r
   r
  r_   rJ   re   rf   s   @r;   r#  r#    s    

n$; *+F+M+MNk+lm&$$ .28<377;,0/3&*04#(-
*-
 6-
 1	-

 5-
 *-
 --
 $-
 .-
 !-
 
3-
 n -
^1r<   r#  z
    DistilBert 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ej                  d             ee	e
e      	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd                     ZddZ xZS )	%TFDistilBertForSequenceClassificationc                   t        |   |g|i | |j                  | _        t        |d      | _        t
        j                  j                  |j                  t        |j                        dd      | _        t
        j                  j                  |j                  t        |j                        d      | _        t
        j                  j                  |j                        | _        || _        y )Nr   r   relupre_classifierrn   r   r*   
classifierrm   )r-   r.   
num_labelsr   r   r   r3   ru   r0   r   r1   r?  rA  r5   seq_classif_dropoutr6   r/   r   s       r;   r.   z.TFDistilBertForSequenceClassification.__init__  s    3&3F3 ++/\J#ll00JJ.v/G/GH!	 1 
  ,,,,/&BZBZ2[bn - 
 ||++F,F,FGr<   r   r   c
           
     V   | j                  ||||||||	      }
|
d   }|dddf   }| j                  |      }| 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).
        r   r   Nr   r!   r2  )r   r?  r6   rA  r5  r   r   r   )r8   rZ   r   r   r\   rt   r   r   r6  rV   r7  r   pooled_outputr4  r3  r   s                   r;   r_   z*TFDistilBertForSequenceClassification.call  s    2 !OO)'/!5# , 	
 )+$QT*++M:]XF/~t4+?+?+OY!212!66F)-)9TGf$EvE)+99(33	
 	
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       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   r?  rA  rH   rI   rD   rE   r   r*   rJ   r?  r/   r0   rA  rK   s     r;   rJ   z+TFDistilBertForSequenceClassification.buildF  -   ::
4t,8t334 ,%%d+,4)40<t22778 I##))4t{{*GHI4t,8t334 E%%tT4;;??&CDE E 9, ,I IE E$   E%3E3E+EE(+E4r:  )rZ   r  r   r  r   r  r\   r  rt   r  r   r  r   r  r6  r  rV   r  r  z3Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]r`   )ra   rb   rc   r.   r   r   r  r  r   r	  r   r
  r_   rJ   re   rf   s   @r;   r<  r<    s    " *+F+M+MNk+lm&.$ .28<377;,0/3&*04#(-
*-
 6-
 1	-

 5-
 *-
 --
 $-
 .-
 !-
 
=-
 n -
^Er<   r<  z
    DistilBert 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ej                  d             ee	e
e      	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd                     ZddZ xZS )	"TFDistilBertForTokenClassificationc                d   t        |   |g|i | |j                  | _        t        |d      | _        t
        j                  j                  |j                        | _        t
        j                  j                  |j                  t        |j                        d      | _        || _        y )Nr   r   rA  rm   )r-   r.   rB  r   r   r   r3   r5   r6   ru   r   r1   rA  r/   r   s       r;   r.   z+TFDistilBertForTokenClassification.__init__]  s    3&3F3 ++/\J||++FNN;,,,,/&BZBZ2[bn - 
 r<   r   r   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]`.
        r   r   r   Nr!   r2  )r   r6   rA  r5  r   r   r   )r8   rZ   r   r   r\   rt   r   r   r6  rV   r  sequence_outputr4  r3  r   s                  r;   r_   z'TFDistilBertForTokenClassification.callh  s    . //)'/!5# " 	
 "!*,,,J1~t4+?+?+O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   rA  )
rH   rI   rD   rE   r   r*   rJ   rA  r/   hidden_sizerK   s     r;   rJ   z(TFDistilBertForTokenClassification.build  s    ::
4t,8t334 ,%%d+,4t,8t334 M%%tT4;;3J3J&KLM M 9, ,M M   C"%3C."C+.C7r:  )rZ   r  r   r  r   r  r\   r  rt   r  r   r  r   r  r6  r  rV   r  r  z0Union[TFTokenClassifierOutput, Tuple[tf.Tensor]]r`   )ra   rb   rc   r.   r   r   r  r  r   r	  r   r
  r_   rJ   re   rf   s   @r;   rL  rL  U  s    	 *+F+M+MNk+lm&+$ .28<377;,0/3&*04#((
*(
 6(
 1	(

 5(
 *(
 -(
 $(
 .(
 !(
 
:(
 n (
T	Mr<   rL  z
    DistilBert 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ej                  d             ee	e
e      	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd                     ZddZ xZS )	TFDistilBertForMultipleChoicec                   t        |   |g|i | t        |d      | _        t        j
                  j                  |j                        | _        t        j
                  j                  |j                  t        |j                        dd      | _        t        j
                  j                  dt        |j                        d      | _        || _        y )	Nr   r   r>  r?  r@  r!   rA  rm   )r-   r.   r   r   r   r3   r5   rC  r6   ru   r0   r   r1   r?  rA  r/   r   s       r;   r.   z&TFDistilBertForMultipleChoice.__init__  s    3&3F3/\J||++F,F,FG#ll00JJ.v/G/GH!	 1 
  ,,,,/&2J2J"KR^ - 
 r<   z(batch_size, num_choices, sequence_lengthr   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|t        |      d   f      nd}| j                  ||||||||	      }|d   }|dddf   }| j	                  |      }| 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!   r   rP   r   )r   rV   r   r   r2  )r   rD   r   r   r?  r6   rA  r5  r   r   r   )r8   rZ   r   r   r\   rt   r   r   r6  rV   num_choicesr!  flat_input_idsflat_attention_maskflat_inputs_embedsr7  r   rE  r4  reshaped_logitsr3  r   s                         r;   r_   z"TFDistilBertForMultipleChoice.call  s   4  $Y/2K#I.q1J$]3A6K#M215JDMDYIJ/?@_cN\Nhbjj"j9IJnr ( JJ}r:z-7PQR7S&TU 	
 !OO # , 	
 )+$QT*++M:]XF/**Vb+->?~t4+?+?+X%'*;AB*??F)-)9TGf$EvE*"+99(33	
 	
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       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rG  rH  rK   s     r;   rJ   z#TFDistilBertForMultipleChoice.build  rI  rJ  r:  )rZ   r  r   r  r   r  r\   r  rt   r  r   r  r   r  r6  r  rV   r  r  z4Union[TFMultipleChoiceModelOutput, Tuple[tf.Tensor]]r`   )ra   rb   rc   r.   r   r   r  r  r   r	  r   r
  r_   rJ   re   rf   s   @r;   rT  rT    s      *#**+UV  &/$ .28<377;,0/3&*04#(;
*;
 6;
 1	;

 5;
 *;
 -;
 $;
 .;
 !;
 
>;
 ;
zEr<   rT  z
    DistilBert 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 fdZe eej                  d             ee	e
e      	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd                     ZddZ xZS )	 TFDistilBertForQuestionAnsweringc                   t        |   |g|i | t        |d      | _        t        j
                  j                  |j                  t        |j                        d      | _
        |j                  dk(  sJ d|j                   d       t        j
                  j                  |j                        | _        || _        y )Nr   r   
qa_outputsrm   r   zIncorrect number of labels z instead of 2)r-   r.   r   r   r   r3   ru   rB  r   r1   r`  r5   
qa_dropoutr6   r/   r   s       r;   r.   z)TFDistilBertForQuestionAnswering.__init__  s    3&3F3/\J,,,,/&BZBZ2[bn - 
   A%e)DVEVEVDWWd'ee%||++F,=,=>r<   r   r   c           
        | j                  ||||||||
      }|d   }| j                  ||
      }| 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.
        r   r   r   r   rP   rS   Nstart_positionend_positionr!   )r3  start_logits
end_logitsr   r   )
r   r6   r`  rD   splitsqueezer5  r   r   r   )r8   rZ   r   r   r\   rt   r   r   start_positionsend_positionsrV   r7  r   r4  re  rf  r3  r6  r   s                      r;   r_   z%TFDistilBertForQuestionAnswering.call%  s'   < !OO)'/!5# , 	
 *!,]XF/#%88FAB#? jzz,R8ZZ
4
&=+D&8F%2F>"''z0JKD"J/2CAB2GGF)-)9TGf$EvE-%!+99(33
 	
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`  )
rH   rI   rD   rE   r   r*   rJ   r`  r/   r0   rK   s     r;   rJ   z&TFDistilBertForQuestionAnswering.buildf  s    ::
4t,8t334 ,%%d+,4t,8t334 E%%tT4;;??&CDE E 9, ,E ErR  )
NNNNNNNNNF)rZ   r  r   r  r   r  r\   r  rt   r  r   r  r   r  ri  r  rj  r  rV   r  r  z7Union[TFQuestionAnsweringModelOutput, Tuple[tf.Tensor]]r`   )ra   rb   rc   r.   r   r   r  r  r   r	  r   r
  r_   rJ   re   rf   s   @r;   r^  r^    s    	 *+F+M+MNk+lm&2$ .28<377;,0/3&*9=7;#(8
*8
 68
 1	8

 58
 *8
 -8
 $8
 78
 58
 !8
 
A8
 n 8
t	Er<   r^  )Crd   
__future__r   r-  typingr   r   r   numpynp
tensorflowrD   activations_tfr   modeling_tf_outputsr	   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    configuration_distilbertr"   
get_loggerra   loggerr	  r
  r3   Layerr$   rh   r   r   r   r   r   DISTILBERT_START_DOCSTRINGr  r   r  r#  r<  rL  rT  r^  r,   r<   r;   <module>r{     s{   #  ) )   /     S R  7 
		H	%/ $9 5<<%% 9 xeBu||11 eBPFELL F@@L++ @LF=&ELL&& =&@ S-ELL.. S- S-n%"3 %( T( V l),3 ),	),X%++ %P IY19;W Y1	Y1x  TE,GIe TETEn  FM)DF_ FMFMR  cE$?AU cEcEL  VE'BD[ VEVEr<   