
    sg                        d Z ddlmZ ddlmZ ddlmZmZmZm	Z	 ddl
ZddlZddlmZ ddlmZmZmZ dd	l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-2 model.    )annotations)	dataclass)ListOptionalTupleUnionN   )get_tf_activation)+TFBaseModelOutputWithPastAndCrossAttentions#TFCausalLMOutputWithCrossAttentions"TFSequenceClassifierOutputWithPast)
TFCausalLanguageModelingLossTFConv1DTFModelInputTypeTFPreTrainedModelTFSequenceClassificationLossTFSequenceSummary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   )
GPT2Configzopenai-community/gpt2r"   c                  \     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 |j                  | _        || _        || _        |j
                  | _        || _        | j                  r@t        |dz  ||j                  d      | _	        t        |||j                  d      | _
        n!t        |dz  ||j                  d      | _	        t        |||j                  d      | _        t        j                  j                  |j                        | _        t        j                  j                  |j"                        | _        t'               | _        || _        y )	Nr      c_attninitializer_rangenameq_attnr	   c_proj )super__init__n_head
split_sizescaleoutput_attentionsis_cross_attentionr   r)   r'   r+   r,   r   layersDropout
attn_pdropattn_dropoutresid_pdropresid_dropoutsetpruned_heads	embed_dim)selfnxconfigr2   r4   kwargsn_state	__class__s          \/var/www/html/venv/lib/python3.12/site-packages/transformers/models/gpt2/modeling_tf_gpt2.pyr/   zTFAttention.__init__?   s   "6"&!+++mm!
!'!9!9"4"""7Q;fF^F^emnDK"7B&BZBZaijDK"7Q;fF^F^emnDKwf>V>V]ef!LL001B1BC"\\11&2D2DEE     c                     y Nr-   )r>   headss     rD   prune_headszTFAttention.prune_headsX   s    rE   c                    t        j                  |       dddf   }t        j                  |      }|||z
  | z   k\  }t        j                  ||      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cast)ndnsdtypeijms         rD   causal_attention_maskz!TFAttention.causal_attention_mask[   sJ     HHRLD!HHRLR"wwq%  rE   c                   t        j                  ||d      }| j                  rOt        j                  t	        |      d   |j
                        }	|t         j                  j                  |	      z  }| j                  sVt	        |      \  }
}
}}| 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rP   r!   g     @axistraining)rK   matmulr2   rM   r   rP   mathsqrtr4   rT   reshaper   r8   append)r>   qkvattention_mask	head_maskr3   r]   wdk_rN   rO   boutputss                  rD   _attnzTFAttention._attnf   s0   IIa-::Ar*!'':BBGGLL$$A&& &a=LAq"b**2r*AA

1q!Rn-AAq1u%A%WW^177CNN"A12&a(3  IA99Q?#NN1rE   c                    t        j                  |g d      }t        |      }|d d |d   |d   z  gz   }t        j                  ||      S )Nr   r&   r!   r	   rX   )rK   	transposer   ra   r>   xx_shapenew_x_shapes       rD   merge_headszTFAttention.merge_heads   sL    LLL)Q-crlgbkGBK&?%@@zz![))rE   c                    t        |      }|d d | j                  |d   | j                  z  gz   }t        j                  ||      }t        j                  |d      S )NrX   ro   )r   r0   rK   ra   rq   rr   s       rD   split_headszTFAttention.split_heads   sR    Q-crldkk72;$++3M%NNJJq+&||A|,,rE   c
           	     
   |Wt        | d      st        d      | j                  |      }
| j                  |      }t	        j
                  |dd      \  }}|}n-| j                  |      }t	        j
                  |dd      \  }
}}| j                  |
      }
| j                  |      }| j                  |      }|Mt	        j                  |dd      \  }}t	        j                  ||gd      }t	        j                  ||gd      }|rt	        j                  ||gd      }nd	}| j                  |
||||||	
      }|d   }| j                  |      }| j                  |      }| j                  ||	
      }||g|dd  z   }|S )Nr+   zIf class is used as cross attention, the weights `q_attn` have to be defined. Please make sure to instantiate class with `GPT2Attention(..., is_cross_attention=True)`.r&   rZ   r	   r   )r[   numrp   rG   r\   r!   )hasattr
ValueErrorr+   r'   rK   splitrx   unstackconcatstackrm   rv   r,   r:   )r>   rs   
layer_pastrf   rg   encoder_hidden_statesencoder_attention_mask	use_cacher3   r]   querykv_outkeyvaluepast_key
past_valuepresentattn_outputsarl   s                       rD   callzTFAttention.call   s    !,4* p 
 KKNE[[!67F&!!4JC3NAA "AA 6E3  's#  '!#%::jqa#H Hj))XsO"5CIIz51;E hhU|!4GGzz%e^YPaltzuOQKKNq84g,ab!11rE   c                "   | j                   ry d| _         | j                  rd| j                  z  }nd| j                  z  }t        | dd       Zt	        j
                  | j                  j                        5  | j                  j                  d d | j                  g       d d d        t        | dd       Pt	        j
                  | j                  j                        5  | j                  j                  d d |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   xY w# 1 sw Y   ~xY w# 1 sw Y   y xY w)NTr&   r	   r,   r'   r+   )builtr4   r=   getattrrK   
name_scoper,   r*   buildr'   r+   )r>   input_shapec_attn_shapes      rD   r   zTFAttention.build   sL   ::
""t~~-Lt~~-L44(4t{{//0 @!!4t~~">?@44(4t{{//0 >!!4|"<=>44(4t{{//0 @!!4t~~">?@ @ 5@ @> >@ @s$   6)E-E9:)F-E69FF)FFFrG   )__name__
__module____qualname__r/   rI   staticmethodrT   rm   rv   rx   r   r   __classcell__rC   s   @rD   r$   r$   >   sB    !2 ! !B*-  1f@rE   r$   c                  .     e Zd Z fdZddZddZ xZS )TFMLPc                `   t        |   di | |j                  }t        |||j                  d      | _        t        |||j                  d      | _        t        |j                        | _	        t        j                  j                  |j                        | _        || _        || _        y )Nc_fcr(   r,   r-   )r.   r/   n_embdr   r)   r   r,   r
   activation_functionactr   r5   r6   r9   dropoutintermediate_sizer=   )r>   rB   r@   rA   r?   rC   s        rD   r/   zTFMLP.__init__   s    "6"]]WbF<T<T[ab	r7f>V>V]ef$V%?%?@||++F,>,>?!(rE   c                    | j                  | j                  |            }| j                  |      }| j                  ||      }|S )Nr\   )r   r   r,   r   )r>   rs   r]   hh2s        rD   r   z
TFMLP.call   s<    HHTYYq\"[[^\\"x\0	rE   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   rK   r   r   r*   r   r   r,   r=   r>   r   s     rD   r   zTFMLP.build   s    ::
4&2tyy~~. F		tT-C-C DEF44(4t{{//0 @!!4t~~">?@ @ 5F F@ @s   )C%2)C1%C.1C:r   rG   r   r   r   r/   r   r   r   r   s   @rD   r   r      s    	@rE   r   c                  2     e Zd Zd fd	Z	 ddZddZ xZS )TFBlockc                H   t        |   di | |j                  }|j                  |j                  nd|z  }t        j
                  j                  |j                  d      | _        t        |||d      | _
        t        j
                  j                  |j                  d      | _        |j                  rEt        |||dd	      | _        t        j
                  j                  |j                  d
      | _        t        ||d      | _        |j"                  | _        y )N   ln_1epsilonr*   attnr*   ln_2crossattentionT)r*   r4   ln_cross_attnmlpr-   )r.   r/   r   n_innerr   r5   LayerNormalizationlayer_norm_epsilonr   r$   r   r   add_cross_attentionr   r   r   r   hidden_size)r>   r@   r2   rA   r?   	inner_dimrC   s         rD   r/   zTFBlock.__init__   s    "6"]]&,nn&@FNNa"f	LL33F<U<U\b3c	FE?	LL33F<U<U\b3c	%%"-b&%FVko"pD!&!@!@11 "A "D F7!--rE   c
                   | j                  |      }
| j                  |
|||d d |||		      }|d   }
|dd  }||
z   }|Xt        | d      st        d|  d      | j	                  |      }| j                  |d ||||d||		      }|d   }||z   }||dd  z   }| j                  |      }| j                  ||		      }||z   }|g|z   }|S )
N)r   rf   rg   r   r   r   r3   r]   r   r!   r   z'If `encoder_hidden_states` are passed, z` has to be instantiated with cross-attention layers by setting `config.add_cross_attention=True`Fr&   r\   )r   r   r{   r|   r   r   r   r   )r>   rs   r   rf   rg   r   r   r   r3   r]   r   output_attnrl   caoutput_cross_attnrS   s                   rD   r   zTFBlock.call  s4    IIaLii!)"&#'/   

 Nab/E !,4!12 =dV DZ Z 
 ##A&B $ 3 3-#&;'="3! !4 
! #1%BBA 1!" 55GIIaLHHQH*E#-rE   c                J   | j                   ry 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       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       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   xY w# 1 sw Y   xY w# 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)NTr   r   r   r   r   r   )r   r   rK   r   r   r*   r   r   r   r   r   r   r   r   s     rD   r   zTFBlock.buildD  s   ::
4&2tyy~~. @		tT-=-= >?@4&2tyy~~. &		%&4&2tyy~~. @		tT-=-= >?@4%1txx}}- %t$%4)40<t22778 0##))$/04$/;t11667 I""(($d6F6F)GHI I <@ @& &@ @% %0 0I IsH   )I2I')I43JJ')JI$'I14I>J
JJ"r   rG   r   r   s   @rD   r   r      s    .6 :xIrE   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 )
TFGPT2MainLayerc           	        t        |   |i | || _        |j                  | _        |j                  | _        |j
                  | _        |j                  | _        |j                  | _	        |j                  | _
        |j                  | _        |j                  | _        t        j                  j                  |j                   |j"                  t%        |j                        d      | _        t        j                  j                  |j                  |j                  t%        |j                        d      | _        t        j                  j+                  |j,                        | _        t1        |j                        D cg c]  }t3        |dd|        c}| _        t        j                  j7                  |j8                  d      | _        |j"                  | _        y c c}w )	Nwte)	input_dim
output_dimembeddings_initializerr*   wpeTzh_._)r2   r*   ln_fr   )r.   r/   r@   r3   output_hidden_statesr   use_return_dictreturn_dictn_layernum_hidden_layersr   n_positionsr)   r   r5   	Embedding
vocab_sizer   r   r   r   r6   
embd_pdropdroprL   r   r   r   r   r   r=   )r>   r@   inputsrA   rQ   rC   s        rD   r/   zTFGPT2MainLayer.__init__`  s   &+F+!'!9!9$*$?$?!))!11!'mm!--!'!9!9<<))''))#263K3K#L	 * 
 <<))((}}#263K3K#L	 * 
 LL(():):;	HMfnnH]^1'&T!:>^LL33F<U<U\b3c	++ _s   G%c                    | j                   S rG   r   r>   s    rD   get_input_embeddingsz$TFGPT2MainLayer.get_input_embeddings  s    xxrE   c                    || _         y rG   r   )r>   new_embeddingss     rD   set_input_embeddingsz$TFGPT2MainLayer.set_input_embeddings  s	    !rE   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     rD   _prune_headszTFGPT2MainLayer._prune_heads  s
     "!rE   c                  " ||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   }|1t        j                  t        j                  ||d   |z         d      }|t        |      }t        j                  ||d   dd|d   f      }t        j                  d      }t        j                  ||j                  	      }t        j                  t        j                  ||      t        j                  d
            }| j                  j                  rf|	dt        j                  |	|j                  	      }	t	        t        |	            }|dk(  r|	d d d d d d d f   }|dk(  r|	d d d d d d f   }dz
  d
z  }nd }|}	|t        d g| j                   z  }t        j                  |dt        |      d   g      }|1t#        || j                  j$                         | j'                  |      }| j)                  |      }|6t        j                  |dt        |      d   g      }| j'                  |      }nt        j                  d      }t        j                  ||j                  	      }t        j                  ||j                  	      }||z   |z   }| j+                  ||      }|t        |      d   gz   }|
rdnd }|rdnd }|r| j                  j                  rdnd }|rdnd }t-        t/        | j
                  |            D ]w  \  }\  }}|r|t        j                  ||      fz   } ||||||   ||	|
||	      } | d d \  }}!|
r||!fz   }|sL|| d   fz   }| j                  j                  sl|o|| d   fz   }y | j1                  |      }t        j                  ||      }|r||fz   }|r/|d d dgz   t        |d         dd  z   "t3        "fd|D              }|st3        d |||||fD              S t5        |||||      S )NzDYou cannot specify both input_ids and inputs_embeds at the same timerX   z5You have to specify either input_ids or inputs_embedsr   rp   rZ   r!   g      ?rY   g     r	   r&   g        r\   r-   c              3  J   K   | ]  }t        j                  |        y wrG   )rK   ra   ).0tattention_output_shapes     rD   	<genexpr>z'TFGPT2MainLayer.call.<locals>.<genexpr>   s     "aQ2::a1G#H"as    #c              3  $   K   | ]  }|| 
 y wrG   r-   )r   re   s     rD   r   z'TFGPT2MainLayer.call.<locals>.<genexpr>#  s      = s   )last_hidden_statepast_key_valueshidden_states
attentionscross_attentions)r|   r   rK   ra   lenr   expand_dimsrL   constantrM   rP   multiplysubtractr@   r   r   r   r   r   r   r   r   	enumeratezipr   tupler   )#r>   	input_idsr   rf   token_type_idsposition_idsrg   inputs_embedsr   r   r   r3   r   r   r]   r   past_lengthattention_mask_shapeone_cstnum_dims_encoder_attention_maskencoder_extended_attention_maskposition_embedstoken_type_embedsr   output_shapepresentsall_attentionsall_cross_attentionsall_hidden_statesrQ   blockr   rl   r   r   s#                                     @rD   r   zTFGPT2MainLayer.call  s   $  ]%>cdd"$Y/K

9r;r?.CDI&$]3CR8KTUU"K#fs466{2O$_Q%7%:;B?K>>"((;BR]@]*^efgL% $.n#= ZZ9Ma9PRSUVXlmnXo8pqN kk#&GWW^7==IN[[Wn)Mr{{[cOdeN ;;**/E/Q &(WW-CK`KfKf%g".1*=S2T.U+.!32HDRSUV2W/.!32HDRVXYIY2Z/ 035T/TX`.`+.2+!@  %%!7!77I zz,Z5Mb5Q0RS *9dkk6L6LM HHY/M((<0%ZZZ=WXZ=[8\]N $ 8 "C 0''/9L9LMGG$5]=P=PQ%7:KK		-(	C"j&?&C%DD"20d%64;;;Z;Zr`d"6BD&/DFFO0L&M 	P"A"z#$5MS_9`8b$b!!%&!!
G &-Ra["M7#wj0 !/71:-!?;;227L7X+?71:-+O(/	P2 		-0

=,? 1]4D D%0"%5%<z.YZJ[?\]_]`?a%a"""aR`"aaN '3DnVjk   ;+$+%1
 	
rE   c                t   | 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       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   xY w# 1 sw Y   {xY w# 1 sw Y   nxY w)NTr   r   r   r   )r   r   rK   r   r   r*   r   r   r   r=   r   )r>   r   layers      rD   r   zTFGPT2MainLayer.build1  sS   ::
4%1txx}}- %t$%4%1txx}}- %t$%4&2tyy~~. >		tT^^ <=>4d#/ &]]5::. &KK%& && 0% %% %> >& &s0   F	%F?)F"+F.	FF"F+.F7	NNNNNNNNNNNNNFr   TFModelInputType | Noner   4Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]]rf   np.ndarray | tf.Tensor | Noner   r  r   r  rg   r  r   r  r   r  r   r  r   Optional[bool]r3   r  r   r  r   r  r]   r  returnzDUnion[TFBaseModelOutputWithPastAndCrossAttentions, Tuple[tf.Tensor]]rG   )r   r   r   r"   config_classr/   r   r   r   r   r   r   r   r   s   @rD   r   r   \  s	   L,>""  .2PT8<8<6:377;?C@D$(,0/3&*#(c
*c
 Nc
 6	c

 6c
 4c
 1c
 5c
  =c
 !>c
 "c
 *c
 -c
 $c
 !c
  
N!c
 c
J&rE   r   c                  0    e Zd ZdZeZdZddgZed        Z	y)TFGPT2PreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    transformerzh.\d+.attn.biaszh.\d+.crossattention.biasc                    t        j                  dt         j                  d      t        j                  dt         j                  d      dS )NNNr   r   rf   )r   rf   rK   
TensorSpecint32r   s    rD   input_signaturez%TFGPT2PreTrainedModel.input_signatureO  s7     |RXXKP mmL"((IYZ
 	
rE   N)
r   r   r   __doc__r"   r  base_model_prefix"_keys_to_ignore_on_load_unexpectedpropertyr  r-   rE   rD   r  r  D  s2    
 L%*<>Z)[&
 
rE   r  c                  X    e Zd ZU dZdZded<   dZded<   dZded<   dZded	<   dZ	ded
<   y)TFGPT2DoubleHeadsModelOutputa(  
    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).
        past_key_values (`List[tf.Tensor]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            List of `tf.Tensor` of length `config.n_layers`, with each tensor of shape `(2, batch_size, num_heads,
            sequence_length, embed_size_per_head)`).

            Contains pre-computed hidden-states (key and values in the attention blocks) that can be used (see
            `past_key_values` input) to speed up sequential decoding.
        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List[tf.Tensor] | Noner   zTuple[tf.Tensor] | Noner   r   )
r   r   r   r  r!  __annotations__r"  r   r   r   r-   rE   rD   r   r   Z  s>    6 FIIy.2O+2-1M*1*.J'.rE   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 ([`GPT2Config`]): 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, input_ids_length)`):
            `input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values[0].shape[-2]`
            (`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary.

            If `past_key_values` 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_key_values (`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_key_values` 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**.

            If `past_key_values` is used, `attention_mask` needs to contain the masking strategy that was used for
            `past_key_values`. In other words, the `attention_mask` always has to have the length:
            `len(past_key_values) + len(input_ids)`

            [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 (`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 `(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).
z^The bare GPT2 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 )TFGPT2Modelc                P    t        |   |g|i | t        |d      | _        y Nr  r   r.   r/   r   r  r>   r@   r   rA   rC   s       rD   r/   zTFGPT2Model.__init__  )    3&3F3*6FrE   
checkpointoutput_typer  c                D    | j                  |||||||||	|
||||      }|S )a  
        encoder_hidden_states  (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
            the model is configured as a decoder.
        encoder_attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
            the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:

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

        past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers`)
            contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
            If `past` are used, the user can optionally input only the last `decoder_input_ids` (those that don't have
            their past key value states given to this model) of shape `(batch_size, 1)` instead of all
            `decoder_input_ids` of shape `(batch_size, sequence_length)`.
        use_cache (`bool`, *optional*, defaults to `True`):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past`). Set to `False` during training, `True` during generation
        r   r   rf   r   r   rg   r   r   r   r   r3   r   r   r]   )r  )r>   r   r   rf   r   r   rg   r   r   r   r   r3   r   r   r]   rl   s                   rD   r   zTFGPT2Model.call  sK    Z ""+))%'"7#9/!5# # 
" rE   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   rK   r   r  r*   r   r   s     rD   r   zTFGPT2Model.build5  m    ::
4-9t//445 -  &&t,- - :- -   A11A:r
  r  rG   )r   r   r   r/   r   r   GPT2_INPUTS_DOCSTRINGr   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOCr   r   r   r   s   @rD   r%  r%    s
   
G *+@A&?$ .2PT8<8<6:377;?C@D$(,0/3&*#(7*7 N7 6	7
 67 47 17 57  =7 !>7 "7 *7 -7 $7 !7  
N!7 B 7r-rE   r%  z
    The GPT2 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dZe ee	       e
eee      	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d
d                     ZddZ xZS )TFGPT2LMHeadModelc                P    t        |   |g|i | t        |d      | _        y r'  r(  r)  s       rD   r/   zTFGPT2LMHeadModel.__init__F  r*  rE   c                "    | j                         S rG   )r   r   s    rD   get_output_embeddingsz'TFGPT2LMHeadModel.get_output_embeddingsJ  s    ((**rE   c                &    | j                  |       y rG   )r   )r>   r   s     rD   set_output_embeddingsz'TFGPT2LMHeadModel.set_output_embeddingsM  s    !!%(rE   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   rX   r   rf   T)r[   	exclusive)r   rf   r   r   r   r   )getrK   r   r_   cumsum)r>   r   r   r   rA   r   r   rf   s           rD   prepare_inputs_for_generationz/TFGPT2LMHeadModel.prepare_inputs_for_generationP  s    $4d;^^F1b5M26F)!#q"u0Er!Jzz.$7$4d;%,*>77>>.rT>RL!~~l1b5.A2F  ,(.",
 	
rE   r+  c                   | j                  |||||||||	|
||||      }|d   }t        j                  || j                   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                  |j                  |j                        S )	a  
        encoder_hidden_states  (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
            the model is configured as a decoder.
        encoder_attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
            the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:

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

        past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers`)
            contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
            If `past` are used, the user can optionally input only the last `decoder_input_ids` (those that don't have
            their past key value states given to this model) of shape `(batch_size, 1)` instead of all
            `decoder_input_ids` of shape `(batch_size, sequence_length)`.
        use_cache (`bool`, *optional*, defaults to `True`):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past`). Set to `False` during training, `True` during generation
        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   TrV   NrX   r!   )lossr!  r   r   r   r   )r  rK   r^   r   weightshf_compute_lossr   r   r   r   r   )r>   r   r   rf   r   r   rg   r   r   r   r   r3   r   r   labelsr]   transformer_outputsr   r!  rE  shifted_logitsoutputs                         rD   r   zTFGPT2LMHeadModel.calli  s   b #..+))%'"7#9/!5# / 
  ,A.=$*:*:*>*>*F*FTXY#AssF^NAqrE]F''?DY!4QR!88F)-)9TGf$EvE2/??-;;*550AA
 	
rE   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r1  r2  r   s     rD   r   zTFGPT2LMHeadModel.build  r3  r4  r  )NNNNNNNNNNNNNNF) r   r  r   r  rf   r  r   r  r   r  rg   r  r   r  r   r  r   r  r   r  r3   r  r   r  r   r  rH  r  r]   r  r  z<Union[TFCausalLMOutputWithCrossAttentions, Tuple[tf.Tensor]]rG   )r   r   r   r/   r<  r>  rC  r   r   r5  r   r6  r   r7  r   r   r   r   s   @rD   r9  r9  >  s8   G+)
2 *+@A&7$ .2PT8<8<6:377;?C@D$(,0/3&*04#(!O
*O
 NO
 6	O

 6O
 4O
 1O
 5O
  =O
 !>O
 "O
 *O
 -O
 $O
 .O
  !!O
" 
F#O
 B O
b-rE   r9  a{  
    The GPT2 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 )	TFGPT2DoubleHeadsModelc                    t        |   |g|i | d|_        t        |d      | _        t        ||j                  d      | _        y )Nr!   r  r   multiple_choice_headr(   )r.   r/   
num_labelsr   r  r   r)   rP  r)  s       rD   r/   zTFGPT2DoubleHeadsModel.__init__  sL    3&3F3*6F$5f&>&>E[%
!rE   )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d|	|
|||      }|d   }t        j                  ||t        |      dd z         }|r|r|j                  dd |fz   }nd}t        j
                  || j                  j                  j                  d      }| j                  |||      }t        j                  |d      }|s
||f|d	d z   S t        |||j                  ||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, TFGPT2DoubleHeadsModel

        >>> tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
        >>> model = TFGPT2DoubleHeadsModel.from_pretrained("openai-community/gpt2")

        >>> # Add a [CLS] to the vocabulary (we should train it also!)
        >>> num_added_tokens = tokenizer.add_special_tokens({"cls_token": "[CLS]"})

        >>> embedding_layer = model.resize_token_embeddings(
        ...     len(tokenizer)
        ... )  # Update the model embeddings with the new vocabulary size

        >>> choices = ["Hello, my dog is cute [CLS]", "Hello, my cat is cute [CLS]"]
        >>> encoded_choices = [tokenizer.encode(s) for s in choices]
        >>> cls_token_location = [tokens.index(tokenizer.cls_token_id) for tokens in encoded_choices]

        >>> input_ids = tf.constant(encoded_choices)[None, :]  # Batch size: 1, number of choices: 2
        >>> mc_token_ids = tf.constant([cls_token_location])  # Batch size: 1

        >>> outputs = model(input_ids, mc_token_ids=mc_token_ids)
        >>> lm_prediction_scores, mc_prediction_scores = outputs[:2]
        ```NrX   r/  r   TrV   r\   rZ   r!   )r!  r"  r   r   r   )r   rK   ra   r  r   r^   r   rF  rP  squeezer   r   r   )r>   r   r   rf   r   r   rg   r   mc_token_idsr   r3   r   r   r]   input_shapes
seq_lengthflat_input_idsflat_attention_maskflat_token_type_idsflat_position_idsrI  r   r  	lm_logitsr"  s                            rD   r   zTFGPT2DoubleHeadsModel.call  s   j  %i0L%m4Sb9L!"%
DMDYIJ/?@_cN\Nhbjj"j9IJnrN\Nhbjj"j9IJnrJVJbBJJ|b*5EFhl"..$+..*'"&#'/!5# / 
  ,A.

=,MAZ[][^A_2_`/ !4 A A#2 F-IY Y $IImT-=-=-A-A-I-IW[\	--m\T\-]	JJyr2	y),?,CCC+/??+*55
 	
rE   c                    t        j                  dt         j                  d      t        j                  dt         j                  d      t        j                  dt         j                  d      dS )N)NNNr   r   rf   r  rT  )r   rf   rT  r  r   s    rD   r  z&TFGPT2DoubleHeadsModel.input_signatureB  sM     '9288+V mm,>O_`MM,~V
 	
rE   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  rP  )r   r   rK   r   r  r*   r   rP  r   s     rD   r   zTFGPT2DoubleHeadsModel.buildJ  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 NNNNNNNNNNNNF)r   r  r   r  rf   r  r   r  r   r  rg   r  r   r  rT  r  r   r  r3   r  r   r  r   r  r]   r  r  z5Union[TFGPT2DoubleHeadsModelOutput, Tuple[tf.Tensor]]rG   )r   r   r   r/   r   r   r5  r    r   r7  r   r  r  r   r   r   s   @rD   rN  rN    s   
 *+@A+GVef .2PT8<8<6:377;6:$(,0/3&*#(a
*a
 Na
 6	a

 6a
 4a
 1a
 5a
 4a
 "a
 *a
 -a
 $a
 !a
 
?a
 g B a
F 
 
	6rE   rN  a  
    The GPT2 Model transformer with a sequence classification head on top (linear layer).

    [`TFGPT2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
    (e.g. GPT-1) 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dee	      	 	 	 	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd                     Z
ddZ xZS )	TFGPT2ForSequenceClassificationc                
   t        |   |g|i | |j                  | _        t        j                  j                  |j                  t        |j                        dd      | _        t        |d      | _
        || _        y )NscoreF)kernel_initializerr*   use_biasr  r   )r.   r/   rQ  r   r5   Denser   r)   rb  r   r  r@   r)  s       rD   r/   z(TFGPT2ForSequenceClassification.__init__f  sw    3&3F3 ++\\''.v/G/GH	 ( 

 +6FrE   zmicrosoft/DialogRPT-updownr+  c                $   | j                  |||||||||	|
||      }|d   }| j                  |      }t        |      }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}|| j                  j                  |d   dk(  sJ d	       t        j$                  |      s|d|d   |f   }| j'                  t        j(                  |dg      t        j(                  |d| j*                  g            }||n|}|s|f|dd z   }||f|z   S |S t-        |||j.                  |j0                  |j2                  
      S )z
        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   rf   r   r   rg   r   r   r3   r   r   r]   r   NrX   rZ   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.`z=Cannot handle batch sizes > 1 if no padding token is defined.)rE  r!  r   r   r   )r  rb  r   r@   pad_token_idrK   argmaxrM   r_   equalrP   whereshapegatherloggerwarning_oncerC   r   	is_tensorrG  ra   rQ  r   r   r   r   )r>   r   r   rf   r   r   rg   r   r   r3   r   r   rH  r]   rI  r   r!  logits_shape	in_logitssequence_lengthsrE  pooled_logitsrK  s                          rD   r   z$TFGPT2ForSequenceClassification.callr  sA   8 #..+))%'/!5# / 
 ,A.M*!&)	;;##+!$IIbggbggmmIt{{?W?W&XZcZiZijqst ! $&88,<,ACSU^UdUdegUhklUl#m IIf.>1STU	#% ##~~../ 0^ ^ ((4Q18LONOL << 01"1|A#68H#HI	''

6B4(@"**YY[]a]l]lXmBnoD%.%:	#%(;AB(??F)-)9TGf$EvE1 /??-;;*55
 	
rE   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)NTrb  r  )
r   r   rK   r   rb  r*   r   r@   r   r  r   s     rD   r   z%TFGPT2ForSequenceClassification.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  r   r  rf   r  r   r  r   r  rg   r  r   r  r   r  r3   r  r   r  r   r  rH  r  r]   r  r  z;Union[TFSequenceClassifierOutputWithPast, Tuple[tf.Tensor]]rG   )r   r   r   r/   r   r   r5  r   r   r7  r   r   r   r   s   @rD   r`  r`  V  s    
 *+@A/6$ .2PT8<8<6:377;$(,0/3&*04#(O
*O
 NO
 6	O

 6O
 4O
 1O
 5O
 "O
 *O
 -O
 $O
 .O
 !O
 
EO
 B O
b	-rE   r`  )?r  
__future__r   dataclassesr   typingr   r   r   r   numpynp
tensorflowrK   activations_tfr
   modeling_tf_outputsr   r   r   modeling_tf_utilsr   r   r   r   r   r   r   r   r   r   tf_utilsr   r   r   utilsr   r   r   r   r   r    configuration_gpt2r"   
get_loggerr   rn  r6  r7  r5   Layerr$   r   r   r   r  r   GPT2_START_DOCSTRINGr5  r%  r9  rN  r`  r-   rE   rD   <module>r     s    ! " ! / /   / 
   S R  + 
		H	%- X@%,,$$ X@v@ELL @:cIell   cIL d&ell(( d& d&N
- 
,  /;  /  /F( TA H dK-' K-	K-\  B--/K B-B-J  @62 @6@6F  n-&;=Y n-n-rE   