
    sgӚ                       d Z ddlmZ ddlmZmZmZ ddlZddl	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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 jF                  e$      Z%dZ&dZ'd Z(d Z)d(dZ* G d dejV                  jX                        Z- G d dejV                  jX                        Z. G d dejV                  jX                        Z/e G d dejV                  jX                               Z0 G d de      Z1dZ2dZ3 ede2       G d de1             Z4 G d  d!ejV                  jX                        Z5 ed"e2       G d# d$e1e             Z6 ed%e2       G d& d'e1e             Z7y))zTF 2.0 CTRL model.    )annotations)OptionalTupleUnionN   )TFBaseModelOutputWithPastTFCausalLMOutputWithPastTFSequenceClassifierOutput)TFCausalLanguageModelingLossTFModelInputTypeTFPreTrainedModelTFSequenceClassificationLoss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   )
CTRLConfigzSalesforce/ctrlr   c                P    dt        j                  dd|dz  z  |z        z  }| |z  S )Nr   i'     )nppower)posid_model_sizeangle_ratess       \/var/www/html/venv/lib/python3.12/site-packages/transformers/models/ctrl/modeling_tf_ctrl.py
angle_defnr%   /   s/    bhhuqAF||&CDDK    c                   t        t        j                  |       d d t        j                  f   t        j                  |      t        j                  d d f   |      }t        j                  |d d dd df         }t        j
                  |d d dd df         }t        j                  t        j                  ||gd            }|S )Nr   r   r   axis)	r%   r   arangenewaxissincostfconvert_to_tensorconcatenate)positionr"   
angle_radssinescosinespos_encodings         r$   positional_encodingr7   4   s    BIIh/2::>		,@WXZXbXbdeXe@fhtuJFF:aAg&'EffZ14a4()G''w7Gb(QRLr&   c                   t        j                  | |d      }t        j                  t        |      d   |j                        }|t         j
                  j                  |      z  }|'|t        j                  |dz  |j                        z  }|&t        j                  ||j                        }||z   }t        |d      }	||	|z  }	t        j                  |	|      }
|
|	fS )NTtranspose_br(   dtype     r)   )r/   matmulcastr   r<   mathsqrtr   )qkvmaskattention_mask	head_mask	matmul_qkdkscaled_attention_logitsattention_weightsoutputs              r$   scaled_dot_product_attentionrM   ?   s    		!QD1I	Ar")//	:B'"'',,r*::2774$;>U>[>[#\\!7N7T7TU"9N"J&'>RH -	9YY(!,F$$$r&   c                  6     e Zd Zd fd	Zd ZddZddZ xZS )TFMultiHeadAttentionc                   t        |   di | || _        || _        || _        t        || j                  z        | _        t        j                  j                  |d      | _
        t        j                  j                  |d      | _        t        j                  j                  |d      | _        t        j                  j                  |d      | _        y )NWqnameWkWvdense )super__init__	num_headsr"   output_attentionsintdepthr   layersDenserQ   rT   rU   rV   )selfr"   rZ   r[   kwargs	__class__s        r$   rY   zTFMultiHeadAttention.__init__Z   s    "6""(!267
,,$$\$=,,$$\$=,,$$\$=\\''7'C
r&   c                    t        j                  ||d| j                  | j                  f      }t        j                  |g d      S )Nr(   r   r   r   r   perm)r/   reshaperZ   r]   	transpose)r`   x
batch_sizes      r$   split_into_headsz%TFMultiHeadAttention.split_into_headsh   s4    JJq:r4>>4::FG||AL11r&   c                   t        |      d   }| j                  |      }| j                  |      }| j                  |      }| j	                  ||      }| j	                  ||      }| j	                  ||      }|Lt        j                  |d      \  }}t        j                  ||fd      }t        j                  ||fd      }|rt        j                  ||fd      }nd}t        ||||||      }t        j                  |d   g d      }|d   }t        j                  ||d| j                  f      }| j                  |      }||f}|	r||fz   }|S )	Nr   r)   Nrd   re   r   r(   )r   rQ   rT   rU   rk   r/   unstackconcatstackrM   rh   rg   r"   rV   )r`   rD   rC   rB   rE   
layer_pastrF   rG   	use_cacher[   trainingrj   past_key
past_valuepresentrL   scaled_attentionattnoriginal_size_attentionoutputss                       r$   callzTFMultiHeadAttention.calll   sK   ]1%
GGAJGGAJGGAJ!!!Z0!!!Z0!!!Z0!#%::jq#A Hj		8Q-b1A		:q/3Ahh1vA.GG-aAt^YW<<q	Eay"$**-=
BPTPaPa?b"c347#'Gr&   c                   | j                   ry d| _         t        | dd       Zt        j                  | j                  j
                        5  | j                  j                  d d | j                  g       d d d        t        | dd       Zt        j                  | j                  j
                        5  | j                  j                  d d | j                  g       d d d        t        | dd       Zt        j                  | j                  j
                        5  | j                  j                  d d | j                  g       d d d        t        | dd       [t        j                  | j                  j
                        5  | j                  j                  d d | j                  g       d d d        y y # 1 sw Y   AxY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   y xY w)NTrQ   rT   rU   rV   )builtgetattrr/   
name_scoperQ   rS   buildr"   rT   rU   rV   r`   input_shapes     r$   r   zTFMultiHeadAttention.build   sx   ::
4t$0tww||, ?tT4+<+<=>?4t$0tww||, ?tT4+<+<=>?4t$0tww||, ?tT4+<+<=>?4$'3tzz/ B

  $d.?.?!@AB B 4? ?? ?? ?B Bs0   )F32)G )G )G3F= G	GG!Frn   )__name__
__module____qualname__rY   rk   r|   r   __classcell__rb   s   @r$   rO   rO   Y   s    D2BBr&   rO   c                  .     e Zd Z fdZddZddZ xZS )TFPointWiseFeedForwardLayerc                    t        |   di | t        j                  j	                  |dd      | _        t        j                  j	                  |d      | _        || _        || _        y )Nrelu0)
activationrS   2rR   rW   )	rX   rY   r   r^   r_   dense_0dense_2r"   dff)r`   r"   r   ra   rb   s       r$   rY   z$TFPointWiseFeedForwardLayer.__init__   sZ    "6"||))#&s)K||)),S)A(r&   c                J    | j                  |      }| j                  |      }|S rn   )r   r   )r`   inputs	trainabledense_0_outputdense_2_outputs        r$   r|   z TFPointWiseFeedForwardLayer.call   s$    f-n5r&   c                   | j                   ry d| _         t        | dd       Zt        j                  | j                  j
                        5  | j                  j                  d d | j                  g       d d d        t        | dd       [t        j                  | j                  j
                        5  | j                  j                  d d | j                  g       d d d        y y # 1 sw Y   rxY w# 1 sw Y   y xY w)NTr   r   )
r~   r   r/   r   r   rS   r   r"   r   r   r   s     r$   r   z!TFPointWiseFeedForwardLayer.build   s    ::
4D)5t||001 D""D$0A0A#BCD4D)5t||001 ;""D$#9:; ; 6D D; ;s   )C%2)C1%C.1C:r   rn   r   r   r   rY   r|   r   r   r   s   @r$   r   r      s    	;r&   r   c                  2     e Zd Z	 d fd	ZddZddZ xZS )TFEncoderLayerc                   t        |   di | || _        t        ||| j                  d      | _        t        ||d      | _        t        j                  j                  |d      | _
        t        j                  j                  |d      | _        t        j                  j                  |      | _        t        j                  j                  |      | _        || _        y )	Nmulti_head_attention)r[   rS   ffnrR   
layernorm1epsilonrS   
layernorm2rW   )rX   rY   r[   rO   r   r   r   r   r^   LayerNormalizationr   r   Dropoutdropout1dropout2r"   )	r`   r"   rZ   r   ratelayer_norm_epsilonr[   ra   rb   s	           r$   rY   zTFEncoderLayer.__init__   s     	"6"!2$8)t7M7MTj%
! /|SuM,,99BT[g9h,,99BT[g9h,,T2,,T2(r&   c	                   | j                  |      }	| j                  |	|	|	|||||||
      }
|
d   }| j                  ||      }||z   }| j                  |      }| j	                  |      }| j                  ||      }||z   }|f|
dd  z   }|S )Nrt   r   r   )r   r   r   r   r   r   )r`   ri   rE   rr   rF   rG   rs   r[   rt   normedattn_outputsattn_outputout1out2
ffn_outputr{   s                   r$   r|   zTFEncoderLayer.call   s    #00 1 
 #1ommK(mC;t$XXd^
]]:]A
j 'L,,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       Zt        j                  | j                  j
                        5  | j                  j                  d d | j                  g       d d d        t        | dd       [t        j                  | j                  j
                        5  | j                  j                  d d | j                  g       d d d        y y # 1 sw Y   4x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   r/   r   r   rS   r   r   r   r"   r   r   s     r$   r   zTFEncoderLayer.build   sq   ::
4/6Bt88==> 6))//564%1txx}}- %t$%4t,8t334 G%%tT43D3D&EFG4t,8t334 G%%tT43D3D&EFG G 96 6% %G GG Gs0   F%F&?)F2&)F>F#&F/2F;>G)g?gư>Fr   rn   r   r   s   @r$   r   r      s    af)&4Gr&   r   c                       e Zd ZeZ fdZd Zd Zd Ze		 	 	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd       Z
d	dZ xZS )
TFCTRLMainLayerc                   t        |   di | || _        |j                  | _        |j                  | _        |j
                  | _        |j                  | _        |j                  | _	        |j                  | _        t        |j                  | j                        | _        t        j                   j#                  |j$                  |j                  t'        |j(                        d      | _        t        j                   j-                  |j.                        | _        t3        |j                        D cg c]S  }t5        |j                  |j6                  |j8                  |j:                  |j<                  | j                  d|       U c}| _        t        j                   jA                  |j<                  d      | _!        y c c}w )Nw)	input_dim
output_dimembeddings_initializerrS   zh_._rR   	layernormr   rW   )"rX   rY   configoutput_hidden_statesr[   rs   use_return_dictreturn_dictn_embdr"   n_layer
num_layersr7   n_positionsr6   r   r^   	Embedding
vocab_sizer   initializer_ranger   r   
embd_pdropdropoutranger   n_headr   resid_pdropr   hr   r   )r`   r   ra   r!   rb   s       r$   rY   zTFCTRLMainLayer.__init__   sk   "6"$*$?$?!!'!9!9))!11"MM ../0B0BDDUDUV''''}}#263K3K#L	 ( 
 ||++F,=,=> 6>>*
  

""))&&A3Z
 88AZAZal8m
s   7AGc                    | j                   S rn   r   r`   s    r$   get_input_embeddingsz$TFCTRLMainLayer.get_input_embeddings"  s    vvr&   c                    || _         y rn   r   )r`   new_embeddingss     r$   set_input_embeddingsz$TFCTRLMainLayer.set_input_embeddings%  s	    r&   c                    t         )zv
        Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer}
        )NotImplementedError)r`   heads_to_prunes     r$   _prune_headszTFCTRLMainLayer._prune_heads(  s
     "!r&   c                h	   |'||d d dd f   }||d d dd f   }||d d dd f   }||t        d      |'t        |      }t        j                  |d|d   g      }n|t        |      d d }nt        d      |d}d gt	        | j
                        z  }nt        |d   d         d   }|\t        j                  t        j                  ||d   |z   t        j                        d      }t        j                  ||d   dg      }|t        j                  ||d   dd|d   |z   f      }t        j                  d	      }t        j                  d
      }t        j                  ||j                        }t        j                  t        j                  ||      |      }|t        d g| j                   z  }|t        j                  |dt        |      d   g      }| j#                  |      }|t        j$                  j'                  t        j                  | j(                  |j                              z  }nt        j                  d      }t        j                  |dt        |      d   g      }|1t+        || j"                  j,                         | j#                  |      }|d   }dt        j.                  j1                  t        j2                  ||f      dd      z
  }|t        j$                  j'                  t        j                  | j(                  |j                              z  }t        j4                  | j6                  |      }t        j                  ||j                        }||z   |z   }| j9                  ||      }|t        |      d   gz   }|rdnd }|
rdnd }|	rdnd }t;        t=        | j
                  |            D ]S  \  }\  }}|
r|t        j                  ||      fz   } |||||||   ||	|      }|d d \  }}|r||fz   }|	sK||d   fz   }U | j?                  |      }t        j                  ||      }|
r||fz   }|	r/|d d dgz   t        |d         dd  z   tA        fd|D              }|stA        d ||||fD              S tC        ||||      S )Nr(   zDYou cannot specify both input_ids and inputs_embeds at the same timez5You have to specify either input_ids or inputs_embedsr   rm   r;   r)   r   g      ?r=   g        r   rW   r   c              3  J   K   | ]  }t        j                  |        y wrn   )r/   rg   ).0tattention_output_shapes     r$   	<genexpr>z'TFCTRLMainLayer.call.<locals>.<genexpr>  s     "aQ2::a1G#H"as    #c              3  &   K   | ]	  }||  y wrn   rW   )r   rD   s     r$   r   z'TFCTRLMainLayer.call.<locals>.<genexpr>  s     rqdedqrs   )last_hidden_statepast_key_valueshidden_states
attentions)"
ValueErrorr   r/   rg   lenr   expand_dimsr   int32tileconstantr?   r<   multiplysubtractr   r   r   r@   rA   r"   r   r   linalg	band_partonesgatherr6   r   	enumeratezipr   tupler   ) r`   	input_idsr   rF   token_type_idsposition_idsrG   inputs_embedsrs   r[   r   r   rt   r   past_lengthone_cstten_thousand_csttoken_type_embedsseq_lenrE   
pos_embedsr   output_shapepresentsall_hidden_statesall_attentionsr!   r   rr   r{   rw   r   s                                   @r$   r|   zTFCTRLMainLayer.call.  s   $ &$%af-	( -af 5)!/23!7 ]%>cdd"$Y/K

9r;r?.CDI&$]3CR8KTUU"K#fs466{2O$_Q%7%:;B?K>>"((;BR]@]egemem*nuvwL77<+a.!1DEL %  ZZQA{[\~`kOk8lmN kk#&G!{{84WW^7==IN[[Wn)MO_`N  %%0I%ZZZ=WXZ=[8\]N $~ 6bggd6G6GO`OfOf.g!hh "C 0zz,Z5Mb5Q0RS *9dff6F6FG FF9-Mb/299&&rww/A'BBJJbggd.?.?ATAT&UVVYYt00,?
WWZ/@/F/FG
%
25FF]XF"j&?&C%DD"2"6BD0d"+C,H"I 	@A:#$5MS_9`8b$b!!!!	G &-Ra["M7#wj0 !/71:-!?'	@* }5

=,? 1]4D D%0"%5%<z.YZJ[?\]_]`?a%a"""aR`"aaNr]H>OQ_$`rrr(+$+%	
 	
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       K| j                  D ];  }t        j                  |j
                        5  |j                  d        d d d        = y y # 1 sw Y   xY w# 1 sw Y   nxY w# 1 sw Y   axY w)NTr   r   r   )r~   r   r/   r   r   rS   r   r   r   r   r   )r`   r   layers      r$   r   zTFCTRLMainLayer.build  s   ::
4d#/tvv{{+ #T"#4d+7t~~223 G$$dD$++2D2D%EFG4d#/ &]]5::. &KK%& && 0# #G G& &s$   D9%3EE9EEE	NNNNNNNNNNNFr   TFModelInputType | Noner   4Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]]rF   np.ndarray | tf.Tensor | Noner   r  r   r  rG   r  r   r  rs   Optional[bool]r[   r  r   r  r   r  rt   r  returnz'Union[Tuple, TFBaseModelOutputWithPast]rn   )r   r   r   r   config_classrY   r   r   r   r   r|   r   r   r   s   @r$   r   r      s    L"nH "  .2PT8<8<6:377;$(,0/3&*#(J
*J
 NJ
 6	J

 6J
 4J
 1J
 5J
 "J
 *J
 -J
 $J
 !J
 
1J
 J
X&r&   r   c                      e Zd ZdZeZdZy)TFCTRLPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    transformerN)r   r   r   __doc__r   r  base_model_prefixrW   r&   r$   r
  r
    s    
 L%r&   r
  az	  

    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 ([`CTRLConfig`]): 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.
aZ  
    Args:
        input_ids (`Numpy array` or `tf.Tensor` of shape `(batch_size, input_ids_length)`):
            `input_ids_length` = `sequence_length` if `past` is `None` else `past[0].shape[-2]` (`sequence_length` of
            input past key value states).

            Indices of input sequence tokens in the vocabulary.

            If `past` is used, only input IDs that do not have their past calculated should be passed as `input_ids`.

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

            [What are input IDs?](../glossary#input-ids)
        past (`List[tf.Tensor]` of length `config.n_layers`):
            Contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model (see
            `past` output below). Can be used to speed up sequential decoding. The token ids which have their past
            given to this model should not be passed as input ids as they have already been computed.
        attention_mask (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

            [What are attention masks?](../glossary#attention-mask)
        token_type_ids (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length)`, *optional*):
            Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
            1]`:

            - 0 corresponds to a *sentence A* token,
            - 1 corresponds to a *sentence B* token.

            [What are token type IDs?](../glossary#token-type-ids)
        position_ids (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.max_position_embeddings - 1]`.

            [What are position IDs?](../glossary#position-ids)
        head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
            Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.

        inputs_embeds (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length, 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.
        use_cache (`bool`, *optional*):
            If set to `True`, `past` key value states are returned and can be used to speed up decoding (see `past`).
        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 CTRL Model transformer outputting raw hidden-states without any specific head on top.c                       e Zd Z fdZe ee       eee	e
      	 	 	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd                     ZddZ xZS )TFCTRLModelc                P    t        |   |g|i | t        |d      | _        y )Nr  rR   )rX   rY   r   r  r`   r   r   ra   rb   s       r$   rY   zTFCTRLModel.__init__G  s)    3&3F3*6Fr&   
checkpointoutput_typer  c                @    | j                  |||||||||	|
||      }|S )Nr   r   rF   r   r   rG   r   rs   r[   r   r   rt   )r  )r`   r   r   rF   r   r   rG   r   rs   r[   r   r   rt   r{   s                 r$   r|   zTFCTRLModel.callK  sD    , ""+))%'/!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   r/   r   r  rS   r   r   s     r$   r   zTFCTRLModel.buildq  sm    ::
4-9t//445 -  &&t,- - :- -s   A11A:r  r  rn   )r   r   r   rY   r   r   CTRL_INPUTS_DOCSTRINGr   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOCr|   r   r   r   s   @r$   r  r  B  s    
G *+@A&-$ .2PT8<8<6:377;$(,0/3&*#(* N 6	
 6 4 1 5 " * - $ ! 
1 B >-r&   r  c                  2     e Zd ZdZ fdZ fdZd Z xZS )TFCTRLBiasLayerz
    Bias as a layer. It is used for serialization purposes: `keras.Model.save_weights` stores on a per-layer basis,
    so all weights have to be registered in a layer.
    c                R    t        |   dd|i| || _        || _        || _        y )NrS   rW   )rX   rY   shapeinitializerr   )r`   r  r  r   rS   ra   rb   s         r$   rY   zTFCTRLBiasLayer.__init__  s.    -d-f-
&"r&   c                    | j                  d| j                  | j                  | j                        | _        t
        |   |       y )NbiasrS   r  r  r   )
add_weightr  r  r   r!  rX   r   )r`   r   rb   s     r$   r   zTFCTRLBiasLayer.build  s@    OOtzzt7G7GSWSaSa $ 
	 	k"r&   c                     || j                   z   S rn   )r!  )r`   ri   s     r$   r|   zTFCTRLBiasLayer.call  s    499}r&   )r   r   r   r  rY   r   r|   r   r   s   @r$   r  r  z  s    
##r&   r  z
    The CTRL Model transformer with a language modeling head on top (linear layer with weights tied to the input
    embeddings).
    c                       e Zd Z fdZd Zd Zd Zd Zd
dZe	 e
e       eeee      	 	 	 	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd                     Zdd	Z xZS )TFCTRLLMHeadModelc                    t        |   |g|i | t        |d      | _        t	        dd|j
                  gdd      | _        y )Nr  rR   lm_headr   zerosTr"  )rX   rY   r   r  r  r   
bias_layerr  s       r$   rY   zTFCTRLLMHeadModel.__init__  sJ    3&3F3*6F)1f&7&7"8gY]
r&   c                "    | j                         S rn   )r   r   s    r$   get_output_embeddingsz'TFCTRLLMHeadModel.get_output_embeddings  s    ((**r&   c                &    | j                  |       y rn   )r   )r`   values     r$   set_output_embeddingsz'TFCTRLLMHeadModel.set_output_embeddings  s    !!%(r&   c                2    d| j                   j                  iS )Nlm_head.bias)r*  r!  r   s    r$   get_biaszTFCTRLLMHeadModel.get_bias  s     4 455r&   c                    |d   j                   d   }t        dd|gdd      | _        | j                  j                  d        | j                  j                  j                  |d          y )Nr1  r(   final_logits_biasr   r)  Tr"  )r  r  r*  r   r!  assign)r`   r.  r   s      r$   set_biaszTFCTRLLMHeadModel.set_bias  sb    >*004
)$Q
O\`
 	d###E.$9:r&   c                   |j                  dd       }|r<t        j                  |d d df   d      }|t        j                  |d d df   d      }|j                  dd       }|j                  dd       }|C|At        j                  j	                  |dd      }|rt        j                  |d d df   d      }||||||dS )Nr   r(   r   rF   T)r*   	exclusive)r   rF   r   r   rs   r   )getr/   r   r@   cumsum)r`   r   r   rs   ra   r   r   rF   s           r$   prepare_inputs_for_generationz/TFCTRLLMHeadModel.prepare_inputs_for_generation  s    $4d;^^F1b5M26F)!#q"u0Er!Jzz.$7$4d;%,*>77>>.rT>RL!~~l1b5.A2F  ,(.",
 	
r&   r  c                   | j                  |||||||||	|
||      }|d   }t        j                  || j                   j                  j                  d      }| j                  |      }d}|(|ddddf   }|ddddf   }| j                  ||      }|s|f|dd z   }||f|z   S |S t        |||j                  |j                  |j                        S )	
        labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the cross entropy classification loss. Indices should be in `[0, ...,
            config.vocab_size - 1]`.
        r  r   Tr9   Nr(   r   )losslogitsr   r   r   )r  r/   r>   r   weightsr*  hf_compute_lossr	   r   r   r   )r`   r   r   rF   r   r   rG   r   rs   r[   r   r   labelsrt   transformer_outputsr   r?  r>  shifted_logitsrL   s                       r$   r|   zTFCTRLLMHeadModel.call  s   8 #..+))%'/!5# / 
 ,A.=$*:*:*<*<*D*DRVW(#AssF^NAqrE]F''?DY!4QR!88F)-)9TGf$EvE'/??-;;*55
 	
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   r/   r   r  rS   r   r*  r   s     r$   r   zTFCTRLLMHeadModel.build  s    ::
4-9t//445 -  &&t,-4t,8t334 ,%%d+, , 9- -, ,s   C%CCC NNNNNNNNNNNNNNF)r   r  r   r  rF   r  r   r  r   r  rG   r  r   r  rs   r  r[   r  r   r  r   r  rB  r  rt   r  r  z&Union[Tuple, TFCausalLMOutputWithPast]rn   )r   r   r   rY   r,  r/  r2  r6  r;  r   r   r  r   r  r	   r  r|   r   r   r   s   @r$   r&  r&    s   
+)6;
2 *+@A&,$ .2PT8<8<6:377;$(,0/3&*04#(8
*8
 N8
 6	8

 68
 48
 18
 58
 "8
 *8
 -8
 $8
 .8
 !8
 
08
 B 8
t	,r&   r&  a  
    The CTRL Model transformer with a sequence classification head on top (linear layer).

    [`TFCTRLForSequenceClassification`] uses the last token in order to do the classification, as other causal models
    (e.g. GPT-1, GPT-2) do.

    Since it does classification on the last token, it requires to know the position of the last token. If a
    `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
    no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
    padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
    each row of the batch).
    c                       e Zd Z fdZd Ze ee       ee	e
e      	 	 	 	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd                     ZddZ xZS )	TFCTRLForSequenceClassificationc                
   t        |   |g|i | |j                  | _        t        j                  j                  |j                  t        |j                        dd      | _        t        |d      | _
        || _        y )N
classifierF)kernel_initializerrS   use_biasr  rR   )rX   rY   
num_labelsr   r^   r_   r   r   rK  r   r  r   r  s       r$   rY   z(TFCTRLForSequenceClassification.__init__(  sw    3&3F3 ++,,,,.v/G/GH	 - 
 +6Fr&   c                X    t         j                  d       | j                  j                  S )Nz}Sequence classification models do not have output embeddings. `.get_output_embeddings` will be removed in transformers v4.32.)loggerwarningr  r   r   s    r$   r,  z5TFCTRLForSequenceClassification.get_output_embeddings4  s'    %	
 !!!r&   r  c                @   | j                  |||||||||	|
||      }|d   }| j                  |      }d}| j                  j                  d}n|t	        j
                  t	        j                  t        j                  j                  || j                  j                        |j                        d      dz
  }t	        j                  |dk\  ||j                  d   dz
        }t	        j                  ||dd      }n.d}t        j                  | j                  j                    d       d}||t#        |      dd	 \  }}nt#        |      dd	 \  }}| j                  j                  |dk7  rt%        d
      t	        j&                  |      s	|d||f   }| j)                  t	        j*                  |ddg      t	        j*                  |d| j,                  g            }||n|}|s|f|dd z   }||f|z   S |S t/        |||j0                  |j2                        S )r=  r  r   Nr(   r)   r   )
batch_dimsr*   z will not detect padding tokens in `inputs_embeds`. Results may be unexpected if using padding tokens in conjunction with `inputs_embeds.`r   z=Cannot handle batch sizes > 1 if no padding token is defined.)r>  r?  r   r   )r  rK  r   pad_token_idr/   argmaxr?   r@   equalr<   wherer  r   rP  warning_oncerb   r   r   r   	is_tensorrA  rg   rN  r
   r   r   )r`   r   r   rF   r   r   rG   r   rs   r[   r   r   rB  rt   rC  r   r?  	in_logitssequence_lengthsr>  rj   sequence_lengthpooled_logitsrL   s                           r$   r|   z$TFCTRLForSequenceClassification.call<  sQ   : #..+))%'/!5# / 
 ,A./	;;##+!$IIbggbggmmIt{{?W?W&XZcZiZijqst ! $&88,<,ACSU^UdUdegUhklUl#m IIf.>1STU	#% ##~~../ 0^ ^ $.8.CBQ.G+
O.8.G.K+
O{{''/J!O !`aa<< 01"1Z<1A#AB	''

6B7(CRZZPY\^`d`o`o[pEqrD%.%:	#%(;AB(??F)-)9TGf$EvE) -;;*55	
 	
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       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)NTrK  r  )
r~   r   r/   r   rK  rS   r   r   r   r  r   s     r$   r   z%TFCTRLForSequenceClassification.build  s    ::
4t,8t334 H%%tT4;;3E3E&FGH4-9t//445 -  &&t,- - :H H- -s   3C"<C."C+.C7rG  )r   r  r   r  rF   r  r   r  r   r  rG   r  r   r  rs   r  r[   r  r   r  r   r  rB  r  rt   r  r  z(Union[Tuple, TFSequenceClassifierOutput]rn   )r   r   r   rY   r,  r   r   r  r   r  r
   r  r|   r   r   r   s   @r$   rI  rI    s    
" *+@A&.$ .2PT8<8<6:377;$(,0/3&*04#(R
*R
 NR
 6	R

 6R
 4R
 1R
 5R
 "R
 *R
 -R
 $R
 .R
 !R
 
2R
 B R
h	-r&   rI  rF  )8r  
__future__r   typingr   r   r   numpyr   
tensorflowr/   modeling_tf_outputsr   r	   r
   modeling_tf_utilsr   r   r   r   r   r   r   r   tf_utilsr   r   r   utilsr   r   r   r   configuration_ctrlr   
get_loggerr   rP  r  r  r%   r7   rM   r^   LayerrO   r   r   r   r
  CTRL_START_DOCSTRINGr  r  r  r&  rI  rW   r&   r$   <module>rk     s     " ) )   r r	 	 	 S R u u * 
		H	%' 
%4CB5<<-- CBL;%,,"4"4 ;6=GU\\'' =G@ M&ell(( M& M&`&- &( T@ F d1-' 1-	1-hell(( ,  ~,-/K ~,~,B  y-&;=Y y-y-r&   