
    sg`                        d Z ddlm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 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mZmZmZ dd
lm Z m!Z!m"Z" ddl#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z) dd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                        Z5e G d dejb                  jd                               Z6 G d de      Z7e G d de$             Z8dZ9dZ: e&de9       G d d e7             Z; e&d!e9       G d" d#e7e             Z< e&d$e9       G d% d&e7             Z= e&d'e9       G d( d)e7e             Z>y)*zTF 2.0 OpenAI GPT model.    )annotations)	dataclass)OptionalTupleUnionN   )get_tf_activation)TFBaseModelOutputTFCausalLMOutputTFSequenceClassifierOutput)TFCausalLanguageModelingLossTFConv1DTFModelInputTypeTFPreTrainedModelTFSequenceClassificationLossTFSequenceSummaryTFSharedEmbeddingsget_initializerkeraskeras_serializableunpack_inputs)check_embeddings_within_bounds
shape_liststable_softmax)ModelOutputadd_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardloggingreplace_return_docstrings   )OpenAIGPTConfigzopenai-community/openai-gptr"   c                  Z     e Zd Zd	 fd	Zd Zed        Zd	dZd Zd Z	d	dZ
d
dZ xZS )TFAttentionc                <   t        |   di | |}||j                  z  dk(  sJ d| d|j                          |j                  | _        || _        || _        |j
                  | _        t        |dz  ||j                  d      | _        t        |||j                  d      | _	        t        j                  j                  |j                        | _        t        j                  j                  |j                        | _        || _        t%               | _        y )	Nr   zHidden dimension z" not dividable by number of heads r   c_attninitializer_rangenamec_proj )super__init__n_head
split_sizescaleoutput_attentionsr   r(   r&   r*   r   layersDropout
attn_pdropattn_dropoutresid_pdropresid_dropoutn_statesetpruned_heads)selfnxconfigr0   kwargsr8   	__class__s         `/var/www/html/venv/lib/python3.12/site-packages/transformers/models/openai/modeling_tf_openai.pyr-   zTFAttention.__init__<   s    "6" fmm#q(	Zwi'I&--Y	Z(mm!
!'!9!9w{B&BZBZaijwf>V>V]ef!LL001B1BC"\\11&2D2DEE    c                     y Nr+   )r;   headss     r@   prune_headszTFAttention.prune_headsP   s    rA   c                ~    t        j                  |       dddf   }t        j                  |      }|||z
  | z   k\  }|S )z
        1's in the lower triangle, counting from the lower right corner. Same as tf.matrix_band_part(tf.ones([nd, ns]),
        -1, ns-nd), but doesn't produce garbage on TPUs.
        N)tfrange)ndnsijms        r@   causal_attention_maskz!TFAttention.causal_attention_maskS   s>     HHRLD!HHRLR"rA   c                   t        j                  ||d      }| j                  rOt        j                  t	        |      d   |j
                        }	|t         j                  j                  |	      z  }t	        |      \  }
}
}}t        j                  | j                  ||      |j
                        }t        j                  |dd||g      }||z  dd|z
  z  z
  }|&t        j                  ||j
                        }||z   }t        |d      }| j                  ||      }|||z  }t        j                  ||      g}|r|j                  |       |S )	NT)transpose_bdtyper!   g     @axistraining)rG   matmulr0   castr   rS   mathsqrtrN   reshaper   r5   append)r;   qkvattention_mask	head_maskr1   rW   wdk_rI   rJ   boutputss                  r@   _attnzTFAttention._attn^   s-   IIa-::Ar*!'':BBGGLL$$A "!}1b"GGD..r26aggFJJq1aR.)EC1q5M!%WW^177CNN"A12&a(3  IA99Q?#NN1rA   c                    t        j                  |g d      }t        |      }|d d |d   |d   z  gz   }t        j                  ||      S )Nr      r!   r   rQ   )rG   	transposer   r\   r;   xx_shapenew_x_shapes       r@   merge_headszTFAttention.merge_heads|   sL    LLL)Q-crlgbkGBK&?%@@zz![))rA   c                    t        |      }|d d | j                  |d   | j                  z  gz   }t        j                  ||      }t        j                  |d      S )NrQ   rj   )r   r.   rG   r\   rm   rn   s       r@   split_headszTFAttention.split_heads   sR    Q-crldkk72;$++3M%NNJJq+&||A|,,rA   c           	     |   | j                  |      }t        j                  |dd      \  }}}| j                  |      }| j                  |      }| j                  |      }| j	                  |||||||      }	|	d   }
| j                  |
      }
| j                  |
      }
| j                  |
|      }
|
g|	dd  z   }|S )Nr   rk   rT   rV   r   r!   )r&   rG   splitrt   rh   rr   r*   r7   )r;   ro   ra   rb   r1   rW   querykeyvalueattn_outputsarg   s               r@   callzTFAttention.call   s    KKNHHQ2sE  's#  'zz%e^YPaltzuOQKKNq84#QR((rA   c                    | j                   ry d| _         t        | dd       ]t        j                  | j                  j
                        5  | j                  j                  d d | j                  dz  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*   )	builtgetattrrG   
name_scoper&   r)   buildr8   r*   r;   input_shapes     r@   r   zTFAttention.build   s    ::
44(4t{{//0 B!!4t||a/?"@AB44(4t{{//0 >!!4t||"<=> > 5B B> >s   ,C(5)C4(C14C=FrC   )__name__
__module____qualname__r-   rE   staticmethodrN   rh   rr   rt   r|   r   __classcell__r?   s   @r@   r$   r$   ;   s:    "(  <*-"	>rA   r$   c                  .     e Zd Z fdZddZddZ xZS )TFMLPc                L   t        |   di | |j                  }t        |||j                  d      | _        t        |||j                  d      | _        t        d      | _        t        j                  j                  |j                        | _        || _        || _        y )Nc_fcr'   r*   gelur+   )r,   r-   n_embdr   r(   r   r*   r	   actr   r2   r3   r6   dropoutr<   r8   )r;   r8   r=   r>   r<   r?   s        r@   r-   zTFMLP.__init__   s    "6"]]WbF<T<T[ab	r7f>V>V]ef$V,||++F,>,>?rA   c                    | j                  | j                  |            }| j                  |      }| j                  ||      }|S )NrV   )r   r   r*   r   )r;   ro   rW   hh2s        r@   r|   z
TFMLP.call   s<    HHTYYq\"[[^\\"x\0	rA   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   rG   r   r   r)   r   r8   r*   r<   r   s     r@   r   zTFMLP.build   s    ::
4&2tyy~~. <		tT\\ :;<44(4t{{//0 9!!4tww"789 9 5< <9 9s   )C%2)C1%C.1C:r   rC   r   r   r   r-   r|   r   r   r   s   @r@   r   r      s    	9rA   r   c                  0     e Zd Zd fd	ZddZddZ xZS )TFBlockc                ^   t        |   di | |j                  }t        |||d      | _        t
        j                  j                  |j                  d      | _	        t        d|z  |d      | _        t
        j                  j                  |j                  d      | _        || _        y )	Nattnr)   ln_1)epsilonr)      mlpln_2r+   )r,   r-   r   r$   r   r   r2   LayerNormalizationlayer_norm_epsilonr   r   r   r   r<   )r;   r=   r0   r>   r<   r?   s        r@   r-   zTFBlock.__init__   s    "6"]]FE?	LL33F<U<U\b3c	Re4LL33F<U<U\b3c	rA   c                    | j                  |||||      }|d   }| j                  ||z         }| j                  ||      }	| j                  ||	z         }
|
g|dd  z   }|S )NrV   r   r!   )r   r   r   r   )r;   ro   ra   rb   r1   rW   output_attnr{   nrM   r   rg   s               r@   r|   zTFBlock.call   sr    ii>9>OZbicNIIa!eHHQH*IIa!e#AB'rA   c                   | j                   ry 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       Mt        j                  | j                  j
                        5  | j                  j                  d        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   rG   r   r   r)   r   r   r<   r   r   r   s     r@   r   zTFBlock.build   sS   ::
4&2tyy~~. &		%&4&2tyy~~. 7		tTWW 5674%1txx}}- %t$%4&2tyy~~. 7		tTWW 567 7 3& &7 7% %7 7s0   F%)F&F2&)F>F#&F/2F;>Gr   rC   r   r   s   @r@   r   r      s    	7rA   r   c                       e Zd ZeZ fdZddZd Zd Zd Z	e
	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d	d       Z xZS )
TFOpenAIGPTMainLayerc           	     X   t        |   |i | || _        |j                  | _        |j                  | _        |j
                  | _        |j                  | _        |j                  | _	        |j                  | _
        |j                  | _        t        |j                  |j                  |j                  d      | _        t        j                   j#                  |j$                        | _        t)        |j                        D cg c]  }t+        |dd|        c}| _        y c c}w )Ntokens_embedr'   Tzh_._)r0   r)   )r,   r-   r=   output_hidden_statesr1   use_return_dictreturn_dictn_layernum_hidden_layersr   n_positionsr(   r   
vocab_sizer   r   r2   r3   
embd_pdropdroprH   r   r   )r;   r=   inputsr>   rK   r?   s        r@   r-   zTFOpenAIGPTMainLayer.__init__   s    &+F+$*$?$?!!'!9!9!11!'mm!--!'!9!9.v}}@X@X_m
 LL(():):;	HMfnnH]^1'&T!:>^^s   D'c                   t        j                  d      5  | j                  d| j                  | j                  gt        | j                              | _        d d d        | j                  ry d| _        t        | dd       Mt        j                  | j                  j                        5  | j                  j                  d        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)Npositions_embed
embeddings)r)   shapeinitializerTr   r   )rG   r   
add_weightr   r   r   r(   r   r~   r   r   r)   r   r   )r;   r   layers      r@   r   zTFOpenAIGPTMainLayer.build   s   ]],- 	#'??!''5+D,B,BC $3 $D 	 ::
4.:t00556 .!!''-.4d#/ &]]5::. &KK%& && 0	 	. .& &s$   AD(+D4
E (D14D= E		c                    | j                   S rC   )r   r;   s    r@   get_input_embeddingsz)TFOpenAIGPTMainLayer.get_input_embeddings  s       rA   c                `    || j                   _        t        |      d   | j                   _        y )Nr   )r   weightr   r   r;   ry   s     r@   set_input_embeddingsz)TFOpenAIGPTMainLayer.set_input_embeddings  s(    #( '1%'8';$rA   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!TFOpenAIGPTMainLayer._prune_heads  s
     "!rA   c                $   ||t        d      |'t        |      }t        j                  |d|d   g      }n|t        |      d d }nt        d      |-t        j                  t        j
                  |d         d      }|t        j                  ||d   dd|d   f      }t        j                  d      }t        j                  ||j                        }t        j                  t        j                  ||      t        j                  d	            }nd }|t        d g| j                  z  }t        j                  |dt        |      d   g      }|3t        || j                  j                         | j!                  |d
      }t        j"                  | j$                  |      }|Yt        j                  |dt        |      d   g      }t        || j                  j                  d       | j!                  |d
      }nd}||z   |z   }| j'                  ||
      }|t        |      d   gz   }|rdnd }|rdnd }t)        | j*                        D ]B  \  }}|r|t        j                  ||      fz   } |||||   ||
      }|d   }|s:||d   fz   }D t        j                  ||      }|r||fz   }|r/|d d dgz   t        |d         dd  z   t-        fd|D              }|	st-        d |||fD              S t/        |||      S )NzDYou cannot specify both input_ids and inputs_embeds at the same timerQ   z5You have to specify either input_ids or inputs_embedsr   rT   r!   g      ?rR   g     	embeddingmodetoken_type_idsrV   r+   rl   c              3  J   K   | ]  }t        j                  |        y wrC   )rG   r\   ).0tattention_output_shapes     r@   	<genexpr>z,TFOpenAIGPTMainLayer.call.<locals>.<genexpr>  s     "aQ2::a1G#H"as    #c              3  &   K   | ]	  }||  y wrC   r+   )r   r`   s     r@   r   z,TFOpenAIGPTMainLayer.call.<locals>.<genexpr>  s     hqZ[Zghs   )last_hidden_statehidden_states
attentions)
ValueErrorr   rG   r\   expand_dimsrH   constantrY   rS   multiplysubtractr   r   r   r=   r   r   gatherr   r   	enumerater   tupler
   )r;   	input_idsra   r   position_idsrb   inputs_embedsr1   r   r   rW   r   one_cstposition_embedstoken_type_embedsr   output_shapeall_attentionsall_hidden_statesrK   blockrg   r   s                         @r@   r|   zTFOpenAIGPTMainLayer.call  s:     ]%>cdd"$Y/K

9r;r?.CDI&$]3CR8KTUU>>"((;r?*C!LL%  ZZQA{[\~8^_N kk#&GWW^7==IN[[Wn)Mr{{[cOdeN!N  %%!7!77I zz,Z5Mb5Q0RS *9dkk6L6LM --ik-JM))D$8$8,G%ZZZ=WXZ=[8\]N*>4;;;Q;QScd $ 1 1.{ 1 S !%7:KK		-(	C"j&?&C%DD0d"6BD!$&&) 	@HAu#$5MS_9`8b$b!!!!G $AJM !/71:-!?	@ 

=,? 1]4D D%0"%5%<z.YZJ[?\]_]`?a%a"""aR`"aaNh]4E~$Vhhh ++%
 	
rA   rC   
NNNNNNNNNFr   TFModelInputType | Nonera   np.ndarray | tf.Tensor | Noner   r   r   r   rb   r   r   r   r1   Optional[bool]r   r   r   r   rW   r   returnzUnion[Tuple, TFBaseModelOutput])r   r   r   r"   config_classr-   r   r   r   r   r   r|   r   r   s   @r@   r   r      s    "L_$&&!<"  .28<8<6:377;,0/3&*#(l
*l
 6l
 6	l

 4l
 1l
 5l
 *l
 -l
 $l
 !l
 
)l
 l
rA   r   c                      e Zd ZdZeZdZy)TFOpenAIGPTPreTrainedModelz
    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_prefixr+   rA   r@   r   r     s    
 #L%rA   r   c                  J    e Zd ZU dZdZded<   dZded<   dZded<   dZded<   y)	!TFOpenAIGPTDoubleHeadsModelOutputaG  
    Base class for outputs of models predicting if two sentences are consecutive or not.

    Args:
        logits (`tf.Tensor` of shape `(batch_size, num_choices, sequence_length, config.vocab_size)`):
            Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
        mc_logits (`tf.Tensor` of shape `(batch_size, num_choices)`):
            Prediction scores of the multiple choice classification head (scores for each choice before SoftMax).
        hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
            `(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the initial embedding outputs.
        attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.
    Nz	tf.Tensorlogits	mc_logitszTuple[tf.Tensor] | Noner   r   )	r   r   r   r   r   __annotations__r   r   r   r+   rA   r@   r   r     s3    * FIIy-1M*1*.J'.rA   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 ([`OpenAIGPTConfig`]): 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 `(batch_size, sequence_length)`):
            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 (`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 (`tf.Tensor` or `Numpy array` 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.
        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).
zdThe bare OpenAI GPT transformer model 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 )TFOpenAIGPTModelc                P    t        |   |g|i | t        |d      | _        y )Nr   r   )r,   r-   r   r   r;   r=   r   r>   r?   s       r@   r-   zTFOpenAIGPTModel.__init__  s)    3&3F3/]KrA   
checkpointoutput_typer   c                <    | j                  |||||||||	|

      }|S )N
r   ra   r   r   rb   r   r1   r   r   rW   )r   )r;   r   ra   r   r   rb   r   r1   r   r   rW   rg   s               r@   r|   zTFOpenAIGPTModel.call!  s>    ( ""))%'/!5# # 
 rA   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   rG   r   r   r)   r   r   s     r@   r   zTFOpenAIGPTModel.buildC  m    ::
4-9t//445 -  &&t,- - :- -   A11A:r   r   rC   )r   r   r   r-   r   r   OPENAI_GPT_INPUTS_DOCSTRINGr   _CHECKPOINT_FOR_DOCr
   _CONFIG_FOR_DOCr|   r   r   r   s   @r@   r   r     s    
L *+FG&%$ .28<8<6:377;,0/3&*#(* 6 6	
 4 1 5 * - $ ! 
) H 6-rA   r   z
    OpenAI GPT 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e ee       e	e
ee      	 	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d	d                     Zd Zd
dZ xZS )TFOpenAIGPTLMHeadModelc                ^    t        |   |g|i | t        |d      | _        d| _        y )Nr   r   F)r,   r-   r   r   supports_xla_generationr   s       r@   r-   zTFOpenAIGPTLMHeadModel.__init__T  s1    3&3F3/]K',$rA   c                "    | j                         S rC   )r   r   s    r@   get_output_embeddingsz,TFOpenAIGPTLMHeadModel.get_output_embeddingsZ  s    ((**rA   c                &    | j                  |       y rC   )r   r   s     r@   set_output_embeddingsz,TFOpenAIGPTLMHeadModel.set_output_embeddings]  s    !!%(rA   r   c                D   | j                  |||||||||	|
      }|d   }| j                   j                  |d      }d}|
(|ddddf   }|
ddddf   }
| j                  |
|      }|	s|f|dd z   }||f|z   S |S t        |||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   linearr   NrQ   r!   lossr   r   r   )r   r   hf_compute_lossr   r   r   )r;   r   ra   r   r   rb   r   r1   r   r   labelsrW   transformer_outputsr   r   r  shifted_logitsoutputs                     r@   r|   zTFOpenAIGPTLMHeadModel.call`  s    6 #..))%'/!5# / 
 ,A.!!..}8.L#AssF^NAqrE]F''?DY!4QR!88F)-)9TGf$EvE-;;*55	
 	
rA   c                
    d|iS )Nr   r+   )r;   r   r>   s      r@   prepare_inputs_for_generationz4TFOpenAIGPTLMHeadModel.prepare_inputs_for_generation  s    V$$rA   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r  r  r   s     r@   r   zTFOpenAIGPTLMHeadModel.build  r  r  NNNNNNNNNNF)r   r   ra   r   r   r   r   r   rb   r   r   r   r1   r   r   r   r   r   r  r   rW   r   r   zUnion[Tuple, TFCausalLMOutput]rC   )r   r   r   r-   r  r  r   r   r  r   r  r   r	  r|   r  r   r   r   s   @r@   r  r  L  s    -+) *+FG&$$ .28<8<6:377;,0/3&*04#(4
*4
 64
 6	4

 44
 14
 54
 *4
 -4
 $4
 .4
 !4
 
(4
 H 4
l%-rA   r  a}  
    OpenAI GPT Model transformer with a language modeling and a multiple-choice classification head on top e.g. for
    RocStories/SWAG tasks. The two heads are two linear layers. The language modeling head has its weights tied to the
    input embeddings, the classification head takes as input the input of a specified classification token index in the
    input sequence).
    c                       e Zd Z fdZe ee       eee	      	 	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd                     Z
ed        ZddZ xZS )	TFOpenAIGPTDoubleHeadsModelc                    t        |   |g|i | d|_        t        |d      | _        t        ||j                  d      | _        y )Nr!   r   r   multiple_choice_headr'   )r,   r-   
num_labelsr   r   r   r(   r#  r   s       r@   r-   z$TFOpenAIGPTDoubleHeadsModel.__init__  sL    3&3F3/]K$5f&>&>E[%
!rA   )r   r   c                   |t        |      }nt        |      dd }|d   }|t        j                  |d|f      nd}|t        j                  |d|f      nd}|t        j                  |d|f      nd}|t        j                  |d|f      nd}| j                  ||||||||	|
|
      }|d   }t        j                  ||t        |      dd z         }|
r|	r|j                  dd |fz   }nd}| j                  j                  |d      }| j                  |||      }t        j                  |d      }|
s
||f|d	d z   S t        ||||j                  
      S )a  
        mc_token_ids (`tf.Tensor` or `Numpy array` of shape `(batch_size, num_choices)`, *optional*, default to index of the last token of the input):
            Index of the classification token in each input sequence. Selected in the range `[0, input_ids.size(-1) -
            1]`.

        Return:

        Examples:

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

        >>> tokenizer = AutoTokenizer.from_pretrained("openai-community/openai-gpt")
        >>> model = TFOpenAIGPTDoubleHeadsModel.from_pretrained("openai-community/openai-gpt")

        >>> # Add a [CLS] to the vocabulary (we should train it also!)
        >>> tokenizer.add_special_tokens({"cls_token": "[CLS]"})
        >>> model.resize_token_embeddings(len(tokenizer))  # Update the model embeddings with the new vocabulary size
        >>> print(tokenizer.cls_token_id, len(tokenizer))  # The newly token the last token of the vocabulary

        >>> choices = ["Hello, my dog is cute [CLS]", "Hello, my cat is cute [CLS]"]
        >>> encoding = tokenizer(choices, return_tensors="tf")
        >>> inputs = {k: tf.expand_dims(v, 0) for k, v in encoding.items()}
        >>> inputs["mc_token_ids"] = tf.constant(
        ...     [inputs["input_ids"].shape[-1] - 1, inputs["input_ids"].shape[-1] - 1]
        ... )[
        ...     None, :
        ... ]  # Batch size 1
        >>> outputs = model(inputs)
        >>> lm_prediction_scores, mc_prediction_scores = outputs[:2]
        ```NrQ   )r   rW   r   r  r   rV   rT   r!   )r   r   r   r   )
r   rG   r\   r   r   r   r#  squeezer   r   )r;   r   ra   r   r   rb   r   mc_token_idsr1   r   r   rW   input_shapes
seq_lengthflat_input_idsflat_attention_maskflat_token_type_idsflat_position_idsr  r   r   	lm_logitsr   s                          r@   r|   z TFOpenAIGPTDoubleHeadsModel.call  s   d  %i0L%m4Sb9L!"%
DMDYIJ/?@_cN\Nhbjj"j9IJnrN\Nhbjj"j9IJnrJVJbBJJ|b*5EFhl".. # / 
 ,A.

=,MAZ[][^A_2_`/ !4 A A#2 F-IY Y $$$11-h1O	--m\T\-]	JJyr2	y),?,CCC0+*55	
 	
rA   c                    t        j                  dt         j                  d      t        j                  dt         j                  d      t        j                  dt         j                  d      dS )N)NNNr   r   ra   )NNr   )r   ra   r'  )rG   
TensorSpecint32r   s    r@   input_signaturez+TFOpenAIGPTDoubleHeadsModel.input_signature  sN     '9288+V mm,>O_`MM,GWX
 	
rA   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   rG   r   r   r)   r   r#  r   s     r@   r   z!TFOpenAIGPTDoubleHeadsModel.build!  s    ::
4-9t//445 -  &&t,-4/6Bt88==> 6))//56 6 C- -6 6s   C%CCC r  )r   r   ra   r   r   r   r   r   rb   r   r   r   r'  r   r1   r   r   r   r   r   rW   r   r   z/Union[Tuple, TFOpenAIGPTDoubleHeadsModelOutput]rC   )r   r   r   r-   r   r   r  r    r   r	  r|   propertyr2  r   r   r   s   @r@   r!  r!    s    
 *+FG+L[jk .28<8<6:377;6:,0/3&*#(Y
*Y
 6Y
 6	Y

 4Y
 1Y
 5Y
 4Y
 *Y
 -Y
 $Y
 !Y
 
9Y
 l H Y
v 
 
	6rA   r!  a  
    The OpenAI GPT Model transformer with a sequence classification head on top (linear layer).

    [`TFOpenAIGPTForSequenceClassification`] uses the last token in order to do the classification, as other causal
    models (e.g. 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e ee       eee	e
      	 	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd                     ZddZ xZS )$TFOpenAIGPTForSequenceClassificationc                
   t        |   |g|i | |j                  | _        t        j                  j                  |j                  t        |j                        dd      | _        t        |d      | _
        || _        y )NscoreF)kernel_initializerr)   use_biasr   r   )r,   r-   r$  r   r2   Denser   r(   r8  r   r   r=   r   s       r@   r-   z-TFOpenAIGPTForSequenceClassification.__init__=  sw    3&3F3 ++\\''.v/G/GH	 ( 

 0]KrA   r   c                4   | 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k(  sJ 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-        |||j.                  |j0                        S )r  r  r   NrQ   rT   r!   )
batch_dimsrU   z will not detect padding tokens in `inputs_embeds`. Results may be unexpected if using padding tokens in conjunction with `inputs_embeds.`rk   z=Cannot handle batch sizes > 1 if no padding token is defined.r  )r   r8  r=   pad_token_idrG   argmaxrY   rZ   equalrS   wherer   r   loggerwarning_oncer?   r   r   	is_tensorr  r\   r$  r   r   r   )r;   r   ra   r   r   rb   r   r1   r   r   r  rW   r  r   r   	in_logitssequence_lengthsr  
batch_sizesequence_lengthpooled_logitsr  s                         r@   r|   z)TFOpenAIGPTForSequenceClassification.callI  sS   4 #..))%'/!5# / 
 ,A.M*	;;##+!$IIbggbggmmIt{{?W?W&XZcZiZijqst ! $&88,<,ACSU^UdUdegUhklUl#m IIf.>1STU	#% ##~~../ 0^ ^ $.8.CBQ.G+
O.8.G.K+
O((4
aONOG << 01"1Z<1A#AB	''

6B7(CRZZPY\^`d`o`o[pEqrD%.%:	#%(;AB(??F)-)9TGf$EvE) -;;*55	
 	
rA   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)NTr8  r   )
r~   r   rG   r   r8  r)   r   r=   r   r   r   s     r@   r   z*TFOpenAIGPTForSequenceClassification.build  s    ::
4$'3tzz/ C

  $dkk.@.@!ABC4-9t//445 -  &&t,- - :C C- -s   3C"<C."C+.C7r  )r   r   ra   r   r   r   r   r   rb   r   r   r   r1   r   r   r   r   r   r  r   rW   r   r   z(Union[Tuple, TFSequenceClassifierOutput]rC   )r   r   r   r-   r   r   r  r   r  r   r	  r|   r   r   r   s   @r@   r6  r6  -  s     
 *+FG&.$ .28<8<6:377;,0/3&*04#(N
*N
 6N
 6	N

 4N
 1N
 5N
 *N
 -N
 $N
 .N
 !N
 
2N
 H N
`	-rA   r6  )?r   
__future__r   dataclassesr   typingr   r   r   numpynp
tensorflowrG   activations_tfr	   modeling_tf_outputsr
   r   r   modeling_tf_utilsr   r   r   r   r   r   r   r   r   r   r   tf_utilsr   r   r   utilsr   r   r   r   r   r    configuration_openair"   
get_loggerr   rB  r  r	  r2   Layerr$   r   r   r   r   r   OPENAI_GPT_START_DOCSTRINGr  r   r  r!  r6  r+   rA   r@   <module>rZ     s     " ! ) )   / b b    S R  2 
		H	%3 #g>%,,$$ g>T9ELL 9:$7ell   $7N b
5<<-- b
 b
J&!2 & / / /8( T5 p j--1 --	--`  S-79U S-S-l  x6"< x6x6v  m-+EGc m-m-rA   