
    sg׻                       d Z ddlmZ ddlmZmZmZ ddlZddl	Z
ddlmZ ddlmZmZmZ ddlmZmZmZmZ dd	lmZ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& ddl'm(Z(  e&jR                  e*      Z+dZ,dZ-d+dZ.d,dZ/d-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      Z7dZ8dZ9 ede8       G d  d!e7             Z: ed"e8       G d# d$e7e             Z; ed%e8       G d& d'e7e             Z< ed(e8       G d) d*e7e             Z=y).zTF 2.0 GPT-J model.    )annotations)OptionalTupleUnionN   )get_tf_activation)add_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forward)TFBaseModelOutputWithPastTFCausalLMOutputWithPastTFQuestionAnsweringModelOutput"TFSequenceClassifierOutputWithPast)
TFCausalLanguageModelingLossTFModelInputTypeTFPreTrainedModelTFQuestionAnsweringLossTFSequenceClassificationLossTFSharedEmbeddingsget_initializerkeraskeras_serializableunpack_inputs)check_embeddings_within_bounds
shape_liststable_softmax)logging   )
GPTJConfigzEleutherAI/gpt-j-6Br   c           	        t        j                  ddt        j                  d|d      |z  z  z  t         j                        }t        j                  t        j                  dt        j                  | t         j                        |      t         j                        }t        j
                  |      t        j                  |      }}t        j                  ||fd      }|S )	N      ?i'  r      zi , j -> i jdtyper   axis)tfcastrangefloat32einsumsincosconcat)num_posdiminv_freqsinusoid_inpr,   r-   outs          \/var/www/html/venv/lib/python3.12/site-packages/transformers/models/gptj/modeling_tf_gptj.pycreate_sinusoidal_positionsr5   ;   s    wwseC(;c(ABCRZZPH77299^RXXgRZZ5XZbcegeoeopLvvl#RVVL%9C
))S#JQ
'CJ    c           
        t        j                  | d d d d d d dd df    | d d d d d d d d df   fd      }t        |      d d t         j                  j	                  t        |      dd        gz   }t        j
                  ||      }|S )Nr   r"   r%   )r'   stackr   mathreduce_prodreshape)xrotate_half_tensor	new_shapes      r4   rotate_every_tworA   C   s    AaAqt!tm$4#4a1a1o"FRP-.s3rww7J7J:VhKijljmKn7o6ppI$6	Br6   c                    |\  }}t        j                  |d d d d d d d f   dd      }t        j                  |d d d d d d d f   dd      }| |z  t        |       |z  z   S )Nr"   r   )r'   repeatrA   )tensorsincossin_poscos_poss       r4   apply_rotary_pos_embrH   J   se    GWii1dA.15Gii1dA.15GW!1&!9G!CDDr6   c                       e Zd Zd	 fdZd
dZedd       ZddZddZ	 	 d	 	 	 	 	 	 	 	 	 	 	 ddZ		 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ
ddZ xZS )TFGPTJAttentionc           
     <   t        |   di | |j                  | _        |j                  | _        | j                  | j                  z  | _        | j
                  | j                  z  | j                  k7  r&t        d| j                   d| j                   d      | j
                  dz  | _        |j                  | _        t        j                  j                  |j                        | _        t        j                  j                  |j                        | _        t        j                  j!                  | j                  dt#        |j$                        d      | _        t        j                  j!                  | j                  dt#        |j$                        d      | _        t        j                  j!                  | j                  dt#        |j$                        d	      | _        t        j                  j!                  | j                  dt#        |j$                        d
      | _        |j.                  | _        t3        j4                  t3        j6                  t2        j8                  j:                  j=                  t3        j>                  | j0                  | j0                  f            t2        j@                        dd| j0                  | j0                  f      | _!        | j                  xs | j                  }tE        | j0                  |      | _#        y )NzEembed_dim must be divisible by num_attention_heads (got `embed_dim`: z and `num_attention_heads`: z).g      ?Fq_projuse_biaskernel_initializernamek_projv_projout_projr    )$super__init__hidden_size	embed_dimnum_attention_headshead_dim
ValueError
scale_attn
rotary_dimr   layersDropout
attn_pdropattn_dropoutresid_pdropresid_dropoutDenser   initializer_rangerL   rQ   rR   rS   max_position_embeddingsmax_positionsr'   r=   r(   experimentalnumpytrilonesint8lower_triangle_maskr5   embed_positions)selfconfigkwargspos_embd_dim	__class__s       r4   rV   zTFGPTJAttention.__init__R   sr   "6"++#)#=#= $*B*BB==4333t~~EWX\XfXfWg h++/+C+C*DBH  --, ++!LL001B1BC"\\11&2D2DEll((NN.v/G/GH	 ) 
 ll((NN.v/G/GH	 ) 
 ll((NN.v/G/GH	 ) 
 **NN.v/G/GH	 + 
 $;;#%::GGBOO))..rww8J8JDL^L^7_/`acecjcjk4%%t'9'9:$
  8$..:4;M;M|\r6   c                    t        j                  | j                  d d d d ||z
  |d |f   t         j                        S N)r'   r(   rm   bool)ro   
key_lengthquery_lengths      r4   get_causal_maskzTFGPTJAttention.get_causal_mask   s@    wwt//1j<6OR\6\^i_i^i0ijlnlslsttr6   c                T    t        j                  t        j                  d      |       S )Ng    e)r'   r(   constantr#   s    r4   get_masked_biaszTFGPTJAttention.get_masked_bias   s    wwr{{4(%00r6   c                x   t        |      dd | j                  | j                  gz   }t        j                  ||      }|r|S t        t        |            dk(  rt        j                  |d      S t        t        |            dk(  rt        j                  |d      S t        dt        t        |                   )zO
        Splits hidden dim into attn_head_size and num_attention_heads
        Nr8      r   r"   r   r      r   r   r   r"   r~   3Input tensor rank should be one of [4, 5], but is: )r   rY   rZ   r'   r=   len	transposer[   )ro   hidden_statesrotaryr@   s       r4   _split_headszTFGPTJAttention._split_heads   s     }-cr2d6N6NPTP]P]5^^	

=)<  z-()Q.<<|<<z-()Q.<<??NsS]^kSlOmNnoppr6   c                x   t        t        |            dk(  rt        j                  |d      }nNt        t        |            dk(  rt        j                  |d      }n t	        dt        t        |                   t        |      dd | j
                  | j                  z  gz   }t        j                  ||      S )zR
        Merges attn_head_size dim and num_attn_heads dim into hidden dim
        r~   r   r   r   r   Nr9   )r   r   r'   r   r[   rY   rZ   r=   )ro   r   r@   s      r4   _merge_headszTFGPTJAttention._merge_heads   s     z-()Q.LLEMM*+q0LLHMRSVWaboWpSqRrstt}-cr2d6N6NQUQ^Q^6^5__	zz-33r6   c                h   t        |      d   t        |      d   }}| j                  ||      }t        j                  |t        j                        }t        j                  |t        j                        }t        j
                  ||d      }	t        j                  ||	| j                  |	j                              }	|	| j                  z  }	||	|z   }	t        |	d      }	t        j                  |	|j                        }	| j                  |	      }	||	|z  }	t        j
                  |	|      }
|
|	fS )Nr9   T)transpose_br8   r%   )r   ry   r'   r(   r*   matmulwherer|   r$   r\   r   ra   )ro   querykeyvalueattention_mask	head_maskrx   rw   causal_maskattn_weightsattn_outputs              r4   _attnzTFGPTJAttention._attn   s    $.e#4R#8*S/":Mj**:|D rzz*ggc2::&yy>xx\4;O;OP\PbPb;cd#doo5%'.8L%l<ww|U[[9((6  ')3Liie4L((r6   c                   | j                  |      }| j                  |      }	| j                  |      }
| j                  |d      }| j                  |	d      }	| j                  |
d      }
t	        j
                  t	        j                  | j                  |d      |j                        }t	        j                  |dd      }| j                  |	d d d d d d d | j                  f   }|	d d d d d d | j                  d f   }|d d d d d d d | j                  f   }|d d d d d d | j                  d f   }t        ||      }t        ||      }t	        j                  ||fd      }	t	        j                  ||fd      }nt        |	|      }	t        ||      }t	        j                  |	d      }	t	        j                  |d      }|<|d   }|d   }t	        j                  ||	fd	      }	t	        j                  ||
fd	      }
|du r|	|
f}nd }| j                  ||	|
||      \  }}| j                  |      }| j!                  |      }| j#                  |      }||f}|r||fz  }|S )
NTFr   r%   r"   r8   r   r   r9   )rL   rQ   rR   r   r'   r(   gatherrn   r$   splitr]   rH   r.   r   r   r   rS   rc   )ro   r   
layer_pastr   position_idsr   	use_cacheoutput_attentionsr   r   r   rE   k_rotk_passq_rotq_passpast_key
past_valuepresentr   r   outputss                         r4   callzTFGPTJAttention.call   sQ    M*kk-(M*!!%.T*!!%/4#7#7ANP]PcPcd&!"-??&1a!24??!223EAq$//"334F!Q#4T__#445E1aDOO$556F(7E(7E))UFO"5CIIufoB7E&sF3C(7Ell3-UL1!!!}H#AJ))XsO"5CIIz51;EElGG %)JJuc5.R[$\!\''4mmK0((5(&Gr6   c                   | j                   ry d| _         t        | dd       Zt        j                  | j                  j
                        5  | j                  j                  d d | j                  g       d d d        t        | dd       Zt        j                  | j                  j
                        5  | j                  j                  d d | j                  g       d d d        t        | dd       Zt        j                  | j                  j
                        5  | j                  j                  d d | j                  g       d d d        t        | dd       [t        j                  | j                  j
                        5  | j                  j                  d d | j                  g       d d d        y y # 1 sw Y   AxY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   y xY w)NTrL   rQ   rR   rS   )builtgetattrr'   
name_scoperL   rP   buildrX   rQ   rR   rS   ro   input_shapes     r4   r   zTFGPTJAttention.build
  s   ::
44(4t{{//0 @!!4t~~">?@44(4t{{//0 @!!4t~~">?@44(4t{{//0 @!!4t~~">?@4T*6t}}112 B##T4$@AB B 7@ @@ @@ @B Bs0   )F32)G )G )G3F= G	GG!rp   r   )return	tf.Tensor)r$   ztf.DTyper   r   )r   r   r   rv   r   r   r   r   r   r   NN)r   r   r   r   r   r   r   tf.Tensor | Noner   r   r   zTuple[tf.Tensor, tf.Tensor]NNNNFF)r   r   r   z%Optional[Tuple[tf.Tensor, tf.Tensor]]r   r   r   r   r   r   r   rv   r   rv   ru   )__name__
__module____qualname__rV   ry   staticmethodr|   r   r   r   r   r   __classcell__rs   s   @r4   rJ   rJ   Q   s    0]du 1 1q4$ ,0&*#)#) #) 	#)
 )#) $#) 
%#)P =A+/)-&*"'= = := )	=
 '= $= =  =~Br6   rJ   c                  0     e Zd Zd fdZddZddZ xZS )	TFGPTJMLPc                   t        |   di | |j                  }t        j                  j                  |t        |j                        d      | _        t        j                  j                  |t        |j                        d      | _	        t        |j                        | _        t        j                  j                  |j                        | _        |j                  | _        || _        y )Nfc_inrO   rP   fc_outrT   )rU   rV   n_embdr   r^   rd   r   re   r   r   r   activation_functionactr_   
embd_pdropdropoutrX   intermediate_size)ro   r   rp   rq   rX   rs   s        r4   rV   zTFGPTJMLP.__init__  s    "6"MM	\\''/&BZBZ2[bi ( 

 ll((/&:R:R*SZb ) 
 %V%?%?@||++F,=,=>!2r6   c                    | j                  |      }| j                  |      }| j                  |      }| j                  |      }|S ru   )r   r   r   r   )ro   r   s     r4   r   zTFGPTJMLP.call-  s@    

=1/M2]3r6   c                   | j                   ry d| _         t        | dd       Zt        j                  | j                  j
                        5  | j                  j                  d d | j                  g       d d d        t        | dd       [t        j                  | j                  j
                        5  | j                  j                  d d | j                  g       d d d        y y # 1 sw Y   rxY w# 1 sw Y   y xY w)NTr   r   )
r   r   r'   r   r   rP   r   rX   r   r   r   s     r4   r   zTFGPTJMLP.build4  s    ::
4$'3tzz/ ?

  $dnn!=>?44(4t{{//0 H!!4t/E/E"FGH H 5? ?H Hs   )C%2)C1%C.1C:)r   intrp   r   r   ru   r   r   r   rV   r   r   r   r   s   @r4   r   r     s    3 	Hr6   r   c                  X     e Zd Zd fdZ	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 ddZddZ xZS )TFGPTJBlockc                *   t        |   di | |j                  |j                  nd|j                  z  }t        j
                  j                  |j                  d      | _        t        |d      | _
        t        ||d      | _        || _        y )Nr~   ln_1epsilonrP   attnrP   mlprT   )rU   rV   n_innerr   r   r^   LayerNormalizationlayer_norm_epsilonr   rJ   r   r   r   rp   )ro   rp   rq   	inner_dimrs   s       r4   rV   zTFGPTJBlock.__init__A  sw    "6"&,nn&@FNNa&--FW	LL33F<U<U\b3c	#F8	YU;r6   c           	         |}| j                  |      }| j                  |||||||      }	|	d   }
|	dd  }| j                  |      }|
|z   |z   }|r|f|z   }|S |f|dd  z   }|S )N)r   r   r   r   r   r   r   r   r   )r   r   r   )ro   r   r   r   r   r   r   r   residualattn_outputsr   r   feed_forward_hidden_statess                r4   r   zTFGPTJBlock.callI  s     !		-0yy'!)%/ ! 
 #1oqr"%)XXm%<"#&@@8K$&0G  %&4Gr6   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       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       Nt        j                  | j                  j
                        5  | j                  j                  d        d d d        y y # 1 sw Y   xY w# 1 sw Y   qxY w# 1 sw Y   y xY w)NTr   r   r   )r   r   r'   r   r   rP   r   rp   r   r   r   r   s     r4   r   zTFGPTJBlock.buildj  s
   ::
4&2tyy~~. B		tT[[-?-? @AB4&2tyy~~. &		%&4%1txx}}- %t$% % 2B B& &% %s$   3D<<EE<EEEr   r   )r   r   r   r   r   r   r   r   r   r   r   rv   r   rv   ru   r   r   s   @r4   r   r   @  sk     (,+/)-&*"'  % )	
 ' $   B%r6   r   c                  n     e Zd ZeZd fdZd ZddZd Ze		 	 	 	 	 	 	 	 	 	 	 	 d		 d
d       Z
ddZ xZS )TFGPTJMainLayerc                   t        |   |i | || _        |j                  | _        |j                  | _        |j
                  | _        |j                  | _        |j                  | _	        |j                  | _
        |j                  | _        |j                  | _        t        |j                  |j                  |j                  d      | _        t"        j$                  j'                  |j(                        | _        t-        |j                        D cg c]  }t/        |d|        c}| _        t"        j$                  j3                  |j4                  d      | _        |j                  | _        y c c}w )Nwte)re   rP   zh_._r   ln_fr   )rU   rV   rp   r   output_hidden_statesr   use_return_dictreturn_dictn_layernum_hidden_layersr   n_positionsre   r   
vocab_sizerW   r   r   r^   r_   r   dropr)   r   hr   r   r   rX   )ro   rp   inputsrq   irs   s        r4   rV   zTFGPTJMainLayer.__init__}  s'   &+F+!'!9!9$*$?$?!))!11!'mm!--!'!9!9%v11VE]E]di
 LL(():):;	@Efnn@UV1+fT!:6VLL33F<U<U\b3c	 Ws   E8c                    | j                   S ru   )r   ro   s    r4   get_input_embeddingsz$TFGPTJMainLayer.get_input_embeddings  s    xxr6   c                `    || j                   _        t        |      d   | j                   _        y )Nr   )r   weightr   r   )ro   r   s     r4   set_input_embeddingsz$TFGPTJMainLayer.set_input_embeddings  s#    (/2r6   c                    t         )zv
        Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer}
        )NotImplementedError)ro   heads_to_prunes     r4   _prune_headszTFGPTJMainLayer._prune_heads  s
     "!r6   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
            }|t        d g| j                  z  }t        j                  |dt        |      d   g      }|3t        || j                   j"                         | j!                  |d      }|8t        j                  |dt        |      d   g      }| j!                  |d      }nt        j                  d      }t        j                  ||j                  	      }||z   }| j%                  ||      }|t        |      d   gz   }|rdnd }|	rdnd }|
rdnd }t'        t)        | j
                  |            D ]W  \  }\  }}|
r|t        j                  ||      fz   } |||||||   ||	|      }|d   }|r	||d   fz   }|	sK|||rdnd   fz   }Y | j+                  |      }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 timer8   z5You have to specify either input_ids or inputs_embedsr   r9   r%   r   r!   r#   g     	embedding)modeg        )trainingrT   )r   r   r   r   r   r   r   r   r"   c              3  J   K   | ]  }t        j                  |        y wru   )r'   r=   ).0tattention_output_shapes     r4   	<genexpr>z'TFGPTJMainLayer.call.<locals>.<genexpr>  s     "aQ2::a1G#H"as    #c              3  &   K   | ]	  }||  y wru   rT   )r   vs     r4   r   z'TFGPTJMainLayer.call.<locals>.<genexpr>  s     rqdedqrs   )last_hidden_statepast_key_valuesr   
attentions)r[   r   r'   r=   r   r   expand_dimsr)   r{   r(   r$   multiplysubtractr   r   r   r   r   r   	enumeratezipr   tupler   )ro   	input_idsr  r   token_type_idsr   r   inputs_embedsr   r   r   r   r   r   past_lengthattention_mask_shapeone_csttoken_type_embedsr   output_shapepresentsall_attentionsall_hidden_statesr   blockr   r   r   s                              @r4   r   zTFGPTJMainLayer.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  %%!7!77I zz,Z5Mb5Q0RS *9dhh6I6IJ HHY[HAM%ZZZ=WXZ=[8\]N $k J "C 0GG$5]=P=PQ%(99		-(	C"j&?&C%DD"20d"6BD&/DFFO0L&M 	T"A"z#$5MS_9`8b$b!+%-)#A,#"3!	G $AJM#wqzm3 !/7	1q3Q2S!S)	T, 		-0

=,? 1]4D D%0"%5%<z.YZJ[?\]_]`?a%a"""aR`"aaNr]H>OQ_$`rrr(+$+%	
 	
r6   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       K| j                  D ];  }t        j                  |j
                        5  |j                  d        d d d        = y y # 1 sw Y   xY w# 1 sw Y   nxY w# 1 sw Y   axY w)NTr   r   r   )
r   r   r'   r   r   rP   r   r   rX   r   )ro   r   layers      r4   r   zTFGPTJMainLayer.build!  s   ::
4%1txx}}- %t$%4&2tyy~~. >		tT^^ <=>4d#/ &]]5::. &KK%& && 0% %> >& &s$   D/%)D;E/D8;EE	r   )r   r   NNNNNNNNNNNF)r   2Union[TFBaseModelOutputWithPast, Tuple[tf.Tensor]]ru   )r   r   r   r   config_classrV   r   r   r   r   r   r   r   r   s   @r4   r   r   y  si    L',3"  !~
 
<~
 ~
@&r6   r   c                      e Zd ZdZeZdZdgZy)TFGPTJPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    transformerh.\d+.attn.biasN)r   r   r   __doc__r   r  base_model_prefix"_keys_to_ignore_on_load_unexpectedrT   r6   r4   r  r  1  s    
 L%*<)=&r6   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 ([`GPTJConfig`]): 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 [`~TFPreTrainedModel.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` is `None` else `past[0].shape[-2]` (`sequence_length` of
            input past key value states). Indices of input sequence tokens in the vocabulary.

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

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

            [What are input IDs?](../glossary#input-ids)
        past_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` output below). Can be used to speed up sequential decoding. The token ids which have their past
            given to this model should not be passed as input ids as they have already been computed.
        attention_mask (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

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

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

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

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

            [What are position IDs?](../glossary#position-ids)
        head_mask (`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 [`~file_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 GPT-J 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 )TFGPTJModelc                P    t        |   |g|i | t        |d      | _        y )Nr  r   )rU   rV   r   r  ro   rp   r   rq   rs   s       r4   rV   zTFGPTJModel.__init__  s)    3&3F3*6Fr6   
checkpointoutput_typer  c                @    | j                  |||||||||	|
||      }|S )a  
        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  r   r  r   r   r  r   r   r   r   r   )r  )ro   r  r  r   r  r   r   r  r   r   r   r   r   r   s                 r4   r   zTFGPTJModel.call  sD    8 ""+))%'/!5# # 
 r6   c                    | j                   ry d| _         t        | dd       Nt        j                  | j                  j
                        5  | j                  j                  d        d d d        y y # 1 sw Y   y xY w)NTr  )r   r   r'   r   r  rP   r   r   s     r4   r   zTFGPTJModel.build  sm    ::
4-9t//445 -  &&t,- - :- -s   A11A:r  )r  TFModelInputType | Noner  4Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]]r   np.ndarray | tf.Tensor | Noner  r/  r   r/  r   r/  r  r/  r   Optional[bool]r   r0  r   r0  r   r0  r   r0  r   r  ru   )r   r   r   rV   r   r   GPTJ_INPUTS_DOCSTRINGr	   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOCr   r   r   r   s   @r4   r$  r$    s    
G *+@A&-$ .2PT8<8<6:377;$(,0/3&*#($*$ N$ 6	$
 6$ 4$ 1$ 5$ "$ *$ -$ $$ !$ 
<$ B $L-r6   r$  zK
    The GPT-J Model transformer with a language modeling head on top.
    c                       e Zd Z fdZd Zd Zd	dZe ee	j                  d             eeee      	 	 	 	 	 	 	 	 	 	 	 	 	 d
	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd                     ZddZ xZS )TFGPTJForCausalLMc                    t        |   |g|i | t        |d      | _        t        j
                  j                  |j                  t        |j                        d      | _
        || _        y )Nr  r   lm_headr   )rU   rV   r   r  r   r^   rd   r   r   re   r7  rp   r&  s       r4   rV   zTFGPTJForCausalLM.__init__  sf    3&3F3*6F||))/&BZBZ2[bk * 
 r6   c                    | j                   S ru   r7  r   s    r4   get_output_embeddingsz'TFGPTJForCausalLM.get_output_embeddings  s    ||r6   c                    || _         y ru   r9  )ro   new_embeddingss     r4   set_output_embeddingsz'TFGPTJForCausalLM.set_output_embeddings  s	    %r6   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  r8   r   r   T)r&   	exclusive)r  r   r   r  r   r  )getr'   r  r;   cumsum)ro   r   r  r   rq   r  r   r   s           r4   prepare_inputs_for_generationz/TFGPTJForCausalLM.prepare_inputs_for_generation  s    $4d;^^F1b5M26F)!#q"u0Er!Jzz.$7$4d;%,*>77>>.rT>RL!~~l1b5.A2F  ,(.",
 	
r6   batch_size, sequence_lengthr'  c                F   | j                  ||||||||	|
|||      }|d   }| j                  |      }d}|(|ddddf   }|ddddf   }| j                  ||      }|s|f|dd z   }||f|z   S |S t        |||j                  |j
                  |j                        S )a  
        labels (`np.ndarray` or `tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
            `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
            are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
        r+  r   Nr8   r   losslogitsr  r   r  )r  r7  hf_compute_lossr   r  r   r  )ro   r  r  r   r  r   r   r  labelsr   r   r   r   r   transformer_outputsr   	lm_logitsrF  shifted_logitsoutputs                       r4   r   zTFGPTJForCausalLM.call  s    < #..+))%'/!5# / 
 ,A.LL/	&q#2#v.NAqrE]F''?D\$7$;;F)-)9TGf$EvE'/??-;;*55
 	
r6   c                   | j                   ry d| _         t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       et        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        y y # 1 sw Y   |xY w# 1 sw Y   y xY w)NTr  r7  )
r   r   r'   r   r  rP   r   r7  rp   r   r   s     r4   r   zTFGPTJForCausalLM.buildU  s    ::
4-9t//445 -  &&t,-4D)5t||001 E""D$0B0B#CDE E 6- -E E   C"%3C."C+.C7r   NNNNNNNNNNNNF)r  r-  r  r.  r   r/  r  r/  r   r/  r   r/  r  r/  rI  r/  r   r0  r   r0  r   r0  r   r0  r   r0  r   z1Union[TFCausalLMOutputWithPast, Tuple[tf.Tensor]]ru   )r   r   r   rV   r:  r=  rB  r   r   r1  formatr	   r2  r   r3  r   r   r   r   s   @r4   r5  r5    s   &
2 *+@+G+GHe+fg&,$ .2PT8<8<6:377;04$(,0/3&*#(9
*9
 N9
 6	9

 69
 49
 19
 59
 .9
 "9
 *9
 -9
 $9
 !9
 
;9
 h 9
v	Er6   r5  a  
    The GPT-J Model transformer with a sequence classification head on top (linear layer).

    [`GPTJForSequenceClassification`] uses the last token in order to do the classification, as other causal models
    (e.g. GPT, GPT-2, GPT-Neo) 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g dZ fdZe eej                  d             e	e
ee      	 	 	 	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd                     Zd	dZ xZS )
TFGPTJForSequenceClassificationzh.\d+.attn.masked_biasr  zlm_head.weightc                
   t        |   |g|i | |j                  | _        t        |d      | _        t
        j                  j                  | j                  dt        |j                        d      | _
        || _        y )Nr  r   FscorerM   )rU   rV   
num_labelsr   r  r   r^   rd   r   re   rV  rp   r&  s       r4   rV   z(TFGPTJForSequenceClassification.__init__s  su    3&3F3 ++*6F\\''OO.v/G/GH	 ( 

 r6   rC  r'  c                ~   |3| j                   j                  |j                  d   dk7  rt        d      | 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\  |t        j                  t        |d         |j                        dz
        }t        j                  ||dd      }n.d}t        j!                  | j"                  j$                   d	       d}|ht        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/        |||j0                  |j2                  |j4                  
      S )a  
        labels (`np.ndarray` or `tf.Tensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        Nr   r   z=Cannot handle batch sizes > 1 if no padding token is defined.r+  r8   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.`rE  )rp   pad_token_idshaper[   r  rV  r   r'   argmaxr(   r;   equalr$   r   r   loggerwarning_oncers   r   	is_tensorrH  r=   rW  r   r  r   r  )ro   r  r  r   r  r   r   r  rI  r   r   r   r   r   rJ  r   rG  logits_shape	in_logitssequence_lengthsrF  pooled_logitsrM  s                          r4   r   z$TFGPTJForSequenceClassification.call  sX   : $++":":"ByWXGY]^G^\]]"..+))%'/!5# / 
 ,A.M*!&)	;;##+!$IIbggbggmmIt{{?W?W&XZcZiZijqst ! $&88$)$GGJy}57G7M7MNQRR$ 
 IIf.>1STU	#% ##~~../ 0^ ^ << 01"1|A#68H#HI	''

6B4(@"**YY[]a]l]lXmBnoD%.%:	#%(;AB(??F)-)9TGf$EvE1 /??-;;*55
 	
r6   c                   | j                   ry d| _         t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       et        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        y y # 1 sw Y   |xY w# 1 sw Y   y xY w)NTr  rV  )
r   r   r'   r   r  rP   r   rV  rp   r   r   s     r4   r   z%TFGPTJForSequenceClassification.build  s    ::
4-9t//445 -  &&t,-4$'3tzz/ C

  $dkk.@.@!ABC C 4- -C CrO  rP  )r  r-  r  r.  r   r/  r  r/  r   r/  r   r/  r  r/  rI  r/  r   r0  r   r0  r   r0  r   r0  r   r0  r   z;Union[TFSequenceClassifierOutputWithPast, Tuple[tf.Tensor]]ru   )r   r   r   _keys_to_ignore_on_load_missingrV   r   r   r1  rQ  r	   r2  r   r3  r   r   r   r   s   @r4   rS  rS  a  s"     'i#
 *+@+G+GHe+fg&6$ .2PT8<8<6:377;04$(,0/3&*#(R
*R
 NR
 6	R

 6R
 4R
 1R
 5R
 .R
 "R
 *R
 -R
 $R
 !R
 
ER
 h R
h	Cr6   rS  z
    The GPT-J Model transformer with a span classification head on top for extractive question-answering tasks like
    SQuAD (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
    c                       e Zd Zg dZ fdZe eej                  d             e	e
ee      	 	 	 	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd                     Zd	dZ xZS )
TFGPTJForQuestionAnsweringrT  c                   t        |   |g|i | |j                  | _        t        |d      | _        t
        j                  j                  | j                  t        |j                        d      | _
        || _        y )Nr  r   
qa_outputsr   )rU   rV   rW  r   r  r   r^   rd   r   re   rj  rp   r&  s       r4   rV   z#TFGPTJForQuestionAnswering.__init__  sq    3&3F3 ++*6F,,,,OO@X@X0Y`l - 
 r6   rC  r'  c                   | j                  ||||||||
|||      }|d   }| j                  |      }t        j                  |dd      \  }}t        j                  |d      }t        j                  |d      }d}||	d|i}|	|d<   | j                  |||f      }|s||f|dd z   }||f|z   S |S t        ||||j                  |j                  	      S )
a  
        start_positions (`np.ndarray` or `tf.Tensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the start of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.
        end_positions (`np.ndarray` or `tf.Tensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the end of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.
        )r  r  r   r  r   r   r  r   r   r   r   r   r"   r8   r%   Nstart_positionend_position)rF  start_logits
end_logitsr   r  )	r  rj  r'   r   squeezerH  r   r   r  )ro   r  r  r   r  r   r   r  start_positionsend_positionsr   r   r   r   rJ  sequence_outputrG  rn  ro  rF  rI  rM  s                         r4   r   zTFGPTJForQuestionAnswering.call  s!   D #..+))%'/!5# / 
 .a01#%88FAB#? jzz,R8ZZ
4
&=+D&8F%2F>"''z0JKD"J/2Eab2IIF)-)9TGf$EvE-%!-;;*55
 	
r6   c                   | j                   ry d| _         t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       et        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        y y # 1 sw Y   |xY w# 1 sw Y   y xY w)NTr  rj  )
r   r   r'   r   r  rP   r   rj  rp   rW   r   s     r4   r   z TFGPTJForQuestionAnswering.buildA  s    ::
4-9t//445 -  &&t,-4t,8t334 M%%tT4;;3J3J&KLM M 9- -M MrO  rP  )r  r-  r  r.  r   r/  r  r/  r   r/  r   r/  r  r/  rq  r/  rr  r/  r   r0  r   r0  r   r0  r   r0  r   z7Union[TFQuestionAnsweringModelOutput, Tuple[tf.Tensor]]ru   )r   r   r   rf  rV   r   r   r1  rQ  r	   r2  r   r3  r   r   r   r   s   @r4   rh  rh    s    'i# *+@+G+GHe+fg&2$ .2PT8<8<6:377;9=7;,0/3&*#(?
*?
 N?
 6	?

 6?
 4?
 1?
 5?
 7?
 5?
 *?
 -?
 $?
 !?
 
A?
 h ?
B	Mr6   rh  )r/   r   r0   r   r   r   )r>   r   r   r   )rD   r   rE   r   r   r   )>r   
__future__r   typingr   r   r   ri   np
tensorflowr'   activations_tfr   
file_utilsr	   r
   r   modeling_tf_outputsr   r   r   r   modeling_tf_utilsr   r   r   r   r   r   r   r   r   r   tf_utilsr   r   r   utilsr   configuration_gptjr   
get_loggerr   r^  r2  r3  r5   rA   rH   r^   LayerrJ   r   r   r   r  GPTJ_START_DOCSTRINGr1  r$  r5  rS  rh  rT   r6   r4   <module>r     s    " ) )   / 
    S R  * 
		H	%+ EHBell(( HBV!H"" !HH6%%,,$$ 6%r t&ell(( t& t&n	>- 	>( T< ~ e8-' 8-	8-v  	sE-/K sEsEl  sC&;=Y sCsCl  ]M!68O ]M]Mr6   