
    sgmo                        d dl mZ d dlmZmZ d dlmZ d dlZd dl	m
Z d dl
Zd dlmZmZmZ d dlmZmZ d dlmZ d dlmZmZ d dlmZ d	d
lmZmZ d	dlmZmZmZ d	dl m!Z!m"Z"m#Z# ddl$m%Z%  e#jL                  e'      Z(dZ)dZ*dZ+dZ,d Z-d Z.d Z/ G d dej`                        Z1 G d dej`                        Z2 G d dej`                        Z3 G d de      Z4 G d dej`                        Z5 G d  d!ej`                        Z6 e!d"e+       G d# d$e4             Z7 ee7e)ee*        G d% d&ej`                        Z8 e!d'e+       G d( d)e4             Z9 ee9e)ee*       y)*    )partial)OptionalTupleN)
FrozenDictfreezeunfreeze)combine_masksmake_causal_mask)dot_product_attention_weights)flatten_dictunflatten_dict)lax   )FlaxBaseModelOutputFlaxCausalLMOutput)ACT2FNFlaxPreTrainedModelappend_call_sample_docstring)add_start_docstrings%add_start_docstrings_to_model_forwardlogging   )
GPTJConfiggptjr   a  

    This model inherits from [`FlaxPreTrainedModel`]. 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 Flax Linen
    [flax.nn.Module](https://flax.readthedocs.io/en/latest/_autosummary/flax.nn.module.html) subclass. Use it as a
    regular Flax Module and refer to the Flax documentation for all matter related to general usage and behavior.

    Finally, this model supports inherent JAX features such as:

    - [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
    - [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
    - [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
    - [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)

    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 [`~FlaxPreTrainedModel.from_pretrained`] method to load the model weights.
        dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):
            The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and
            `jax.numpy.bfloat16` (on TPUs).

            This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
            specified all the computation will be performed with the given `dtype`.

            **Note that this only specifies the dtype of the computation and does not influence the dtype of model
            parameters.**

            If you wish to change the dtype of the model parameters, see [`~FlaxPreTrainedModel.to_fp16`] and
            [`~FlaxPreTrainedModel.to_bf16`].
a  
    Args:
        input_ids (`numpy.ndarray` of shape `(batch_size, input_ids_length)`):
            `input_ids_length` = `sequence_length`. Indices of input sequence tokens in the vocabulary.

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

            [What are input IDs?](../glossary#input-ids)
        attention_mask (`numpy.ndarray` 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)
        position_ids (`numpy.ndarray` 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]`.
        past_key_values (`Dict[str, np.ndarray]`, *optional*, returned by `init_cache` or when passing previous `past_key_values`):
            Dictionary of pre-computed hidden-states (key and values in the attention blocks) that can be used for fast
            auto-regressive decoding. Pre-computed key and value hidden-states are of shape *[batch_size, max_length]*.
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        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.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
c                    ddt        j                  d|d      |z  z  z  }t        j                  dt        j                  |       |      j                  d      }t        j                  |      t        j
                  |      }}|dz  |dz  z   }t        j                  | |f      }||d d d|f<   ||d d |d f<   t        j                  |      S )Ng      ?i'  r      zi , j -> i jfloat32)	nparangeeinsumastypesincoszerosjnparray)num_posdiminv_freqsinusoid_inpr"   r#   sentinelouts           ^/var/www/html/venv/lib/python3.12/site-packages/transformers/models/gptj/modeling_flax_gptj.pycreate_sinusoidal_positionsr.   m   s    e		!S! 4s :;<H99^RYYw-?JQQR[\Lvvl#RVVL%9Cax#'!H
((GS>
"CC1X:C8999S>    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      }|j                  |j                  d d dz         }|S )Nr   r   axis)r1   )r%   stackreshapeshape)tensorrotate_half_tensors     r-   rotate_every_twor:   z   sk    VAq!QTTM%:$:F1aCaC<<P#QXZ[+334F4L4LSb4QTY4YZr/   c                     |\  }}|d d d d d d d f   j                  dd      }|d d d d d d d f   j                  dd      }| |z  t        |       |z  z   S )Nr   r   )repeatr:   )r8   sincossin_poscos_poss       r-   apply_rotary_pos_embr@      se    GWaD!m$++Aq1GaD!m$++Aq1GW!1&!9G!CDDr/   c                       e Zd ZU eed<   ej                  Zej                  ed<   dZe	ed<   dZ
e	ed<   d Zd Zd	 Zej                  d
        Z	 	 	 dde	de	de	fdZy)FlaxGPTJAttentionconfigdtypeTcausalFis_cross_attentionc           	         | j                   }|j                  | _        |j                  | _        | j                  | j                  z  | _        |j                  | _        t        t        j                  | j                  d| j                  t        j                  j                  j                  | j                   j                              } |        |        |       c| _        | _        | _         |       | _        t        j&                  |j(                        | _        t-        t/        j0                  d|j2                  fd      d      | _        | j                  xs | j                  }t7        |j2                  |      | _        y )NF)use_biasrD   kernel_initrater   boolrD   )rC   hidden_size	embed_dimnum_attention_heads	num_headshead_dim
rotary_dimr   nnDenserD   jaxinitializersnormalinitializer_rangeq_projk_projv_projout_projDropoutresid_pdropresid_dropoutr
   r%   onesmax_position_embeddingscausal_maskr.   embed_positions)selfrC   densepos_embd_dims       r-   setupzFlaxGPTJAttention.setup   s   ++33$..8 ++HHNN**++224;;3P3PQ
 16%'-T[$+ZZV-?-?@+CHHa9W9W5X`f,gouv8$..:6;Y;Y[ghr/   c                 p    |j                  |j                  d d | j                  | j                  fz         S Nr   )r6   r7   rQ   rR   re   hidden_statess     r-   _split_headszFlaxGPTJAttention._split_heads   s5    $$]%8%8!%<PTP]P]?^%^__r/   c                 Z    |j                  |j                  d d | j                  fz         S rj   )r6   r7   rO   rk   s     r-   _merge_headszFlaxGPTJAttention._merge_heads   s,    $$]%8%8!%<?P%PQQr/   c                 (   | j                  dd      }| j                  ddt        j                  |j                  |j
                        }| j                  ddt        j                  |j                  |j
                        }| j                  ddd       }|r|j                  j                  ^ }	}
}}|j                  }dt        |	      z  |ddfz   }t        j                  |j                  ||      }t        j                  |j                  ||      }||_        ||_        |j                  d   }|j                  |z   |_        t        j                  t        j                  |
      ||z   k  t        |	      d||
fz         }t        ||      }|||fS )	a[  
        This function takes projected key, value states from a single input token and concatenates the states to cached
        states from previous steps. This function is slighly adapted from the official Flax repository:
        https://github.com/google/flax/blob/491ce18759622506588784b4fca0e4bf05f8c8cd/flax/linen/attention.py#L252
        cache
cached_keycached_valuecache_indexc                  L    t        j                  dt         j                        S )Nr   rM   )r%   r&   int32 r/   r-   <lambda>z9FlaxGPTJAttention._concatenate_to_cache.<locals>.<lambda>   s    CIIaWZW`W`Da r/   )r   r   r   )has_variablevariabler%   r$   r7   rD   valuelenr   dynamic_update_slicebroadcast_tor   tupler	   )re   keyr{   queryattention_maskis_initializedrr   rs   rt   
batch_dims
max_lengthrQ   depth_per_head	cur_indexindicesnum_updated_cache_vectorspad_masks                    r-   _concatenate_to_cachez'FlaxGPTJAttention._concatenate_to_cache   st    **7LA]]7L#))SYYPSPYPYZ
}}WnciiV[VaVabmmG]<abAKAQAQAWAW>ZY#))IS_,	1a/@@G**:+;+;S'JC,,\-?-?PE"J!&L(-A% + 1 14M MK ''

:&5N)NNj!Q(A:$NNH +8^DNE>))r/   deterministic
init_cacheoutput_attentionsc           
      X   | j                  |      }| j                  |      }| j                  |      }	| j                  |      }| j                  |      }| j                  |	      }	t	        j
                  | j                  |d      }
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                  ||gd      }t	        j                  ||gd      }nt        ||
      }t        ||
      }|j                  d   |j                  d   }}| j                  dd      r[| j                  d   d   }| j                  d   d   j                  d   }t        j                  | j                   dd|dfdd||f      }n| j                   d d d d d |d |f   }|j                  d   }t	        j"                  ||f|j                  dd  z         }t	        j"                  t	        j$                  |d	      |j                        }t'        ||      }d }|s*| j(                  j*                  d
kD  r| j-                  d      }| j                  dd      s|r| j/                  ||	||      \  }}	}t        j0                  |dkD  t	        j2                  |j                  d
      j5                  | j6                        t	        j2                  |j                  t	        j8                  | j6                        j:                        j5                  | j6                              }t=        ||||| j(                  j*                  || j6                  d       }t	        j>                  d||	      }| jA                  |      }| jC                  |      }| jE                  ||      }|r||f}|S |f}|S )Nr   r2   r   r1   r   rq   rr   rt   )r4   g        dropout)biasdropout_rngdropout_rater   rD   	precisionz...hqk,...khd->...qhdr   )#rZ   r[   r\   rm   r%   takerd   splitrS   r@   concatenater7   ry   	variablesr   dynamic_slicerc   r~   expand_dimsr	   rC   
attn_pdropmake_rngr   selectfullr!   rD   finfominr   r    ro   r]   r`   )re   rl   r   position_idsr   r   r   r   r   r{   r=   k_rotk_passq_rotq_passquery_length
key_length
mask_shiftmax_decoder_lengthrc   
batch_sizer   attention_biasattn_weightsattn_outputoutputss                             r-   __call__zFlaxGPTJAttention.__call__   s    M*kk-(M*!!%($!!%($..1E612.??&1a!24??!223EAq$//"334F!Q#4T__#445E1aDOO$556F(7E(7E//5&/;COOUFO"=E&sF3C(7E#(;;q>399Q<jWl30?J!%!8!F!L!LQ!O++  1aQ"7!QN`9aK **1a,+KLK"((+
&&{ZMKDUDUVWVXDY4YZ))#//.x*XZeZkZkl&~{C!7!7#!=--	2K Wl3z)-)C)CCPUWe)f&C QHH^))3/66tzzBHH^))399TZZ+@+D+DELLTZZX
 5#//'**	
 jj!8,N''4mmK0((M(R1B;- JUr/   N)TFF)__name__
__module____qualname__r   __annotations__r%   r   rD   rE   rL   rF   rh   rm   ro   rT   compactr   r   rw   r/   r-   rB   rB      s    {{E399"FD$$i4`R ZZ* *J # "'V
 V V  Vr/   rB   c                   l    e Zd ZU eed<   eed<   ej                  Zej                  ed<   d Z	dde
fdZy)	FlaxGPTJMLPrC   intermediate_sizerD   c                    | j                   j                  }t        j                  j                  j                  | j                   j                        }t        j                  | j                  | j                  |      | _
        t        j                  || j                  |      | _        t        | j                   j                     | _        t        j                  | j                   j                         | _        y )NrD   rI   rJ   )rC   rN   rV   rT   rW   rX   rY   rU   r   rD   fc_infc_outr   activation_functionactr^   r_   r   )re   rO   rI   s      r-   rh   zFlaxGPTJMLP.setup,  s    KK++	ff))001N1NOXXd44DJJT_`
hhy

T$++99:zzt{{'>'>?r/   r   c                     | j                  |      }| j                  |      }| j                  |      }| j                  ||      }|S )Nr   )r   r   r   r   )re   rl   r   s      r-   r   zFlaxGPTJMLP.__call__6  sD    

=1/M2]-Pr/   N)T)r   r   r   r   r   intr%   r   rD   rh   rL   r   rw   r/   r-   r   r   '  s2    {{E399"@T r/   r   c                   t    e Zd ZU eed<   ej                  Zej                  ed<   d Z	 	 	 	 	 d	de	de	de	fdZ
y)
FlaxGPTJBlockrC   rD   c                    | j                   j                  }| j                   j                  | j                   j                  nd|z  }t        j                  | j                   j
                  | j                        | _        t        | j                   | j                        | _	        t        | j                   || j                        | _        y )N   epsilonrD   rM   )rC   rN   n_innerrT   	LayerNormlayer_norm_epsilonrD   ln_1rB   attnr   mlp)re   rN   	inner_dims      r-   rh   zFlaxGPTJBlock.setupB  s    kk--+/;;+>+>+JDKK''PQT_P_	LL)G)GtzzZ	%dkkD	t{{ITZZHr/   Nr   r   r   c                     |}| j                  |      }| j                  ||||||      }|d   }	| j                  ||      }
|	|
z   |z   }|f|dd  z   S )N)r   r   r   r   r   r   r   r   )r   r   r   )re   rl   r   r   r   r   r   residualattn_outputsr   feed_forward_hidden_statess              r-   r   zFlaxGPTJBlock.__call__K  s     !		-0yy)%'!/ ! 
 #1o%)XXm=X%Y"#&@@8K,qr"222r/   )NNTFFr   r   r   r   r   r%   r   rD   rh   rL   r   rw   r/   r-   r   r   >  sT    {{E399"I " "'3
 3 3  3r/   r   c                   f    e Zd ZU dZeZdZdZej                  e
d<   ddej                  dfded	ed
edej                  def
 fdZddej&                  j(                  d	ededefdZd Z ee      	 	 	 	 	 	 	 	 	 ddededej&                  j(                  dedee   dee   dee   fd       Z xZS )FlaxGPTJPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    transformerNmodule_class)r   r   r   TrC   input_shapeseedrD   _do_initc                 Z     | j                   d||d|}t        | 	  ||||||       y )N)rC   rD   )r   r   rD   r   rw   )r   super__init__)	re   rC   r   r   rD   r   kwargsmodule	__class__s	           r-   r   z FlaxGPTJPreTrainedModel.__init__q  s=     #""H&HH[tSXcklr/   rngparamsreturnc           	      $   t        j                  |d      }t        j                  |      }t        j                  t        j                  t        j
                  |      j                  d         |      }t        j                  j                  |      \  }}||d}	| j                  j                  rRt        j                  || j                  j                  fz         }
|}| j                  j                  |	||||
|d      }n | j                  j                  |	|||d      }|d   }|dt        t!        |            }t        t!        |            }| j"                  D ]
  }||   ||<    t%               | _        t'        t)        |            S |S )Ni4rM   r1   )r   r   F)return_dictr   )r%   r$   	ones_liker~   r   
atleast_2dr7   rV   randomr   rC   add_cross_attentionn_embdr   initr   r   _missing_keyssetr   r   )re   r   r   r   	input_idsr   r   
params_rngr   rngsencoder_hidden_statesencoder_attention_maskmodule_init_outputsrandom_paramsmissing_keys                  r-   init_weightsz$FlaxGPTJPreTrainedModel.init_weights}  so   IIk6	y1''

3>>)3L3R3RSU3V(WYde"%**"2"23"7
K$=;;**$'IIkT[[=O=O<Q.Q$R!%3""&++"2"2%&! #3 # #'++"2"24NT`ns"2"t+H5(-)@AM!(6"23F#11 A&3K&@{#A!$D.011  r/   c                    t        j                  ||f      }t        j                  |      }t        j                  t        j                  t        j
                  |      j                  d         |j                        }| j                  j                  t        j                  j                  d      |||dd      }|d   S )aW  
        Args:
            batch_size (`int`):
                batch_size used for fast auto-regressive decoding. Defines the batch size of the initialized cache.
            max_length (`int`):
                maximum possible length for auto-regressive decoding. Defines the sequence length of the initialized
                cache.
        r1   r   FT)r   r   rq   )r%   ra   r   r~   r   r   r7   r   r   rV   r   PRNGKey)re   r   r   r   r   r   init_variabless          r-   r   z"FlaxGPTJPreTrainedModel.init_cache  s     HHj*56	y1''

3>>)3L3R3RSU3V(WYbYhYhi))JJq!9nlX]jn * 
 g&&r/   past_key_valuesr   trainr   output_hidden_statesr   c                    ||n| j                   j                  }|	|	n| j                   j                  }	|
|
n| j                   j                  }
|j                  \  }}|?|t        d      t        j                  t        j                  |      d d d f   ||f      }|t        j                  ||f      }i }|||d<   d|xs | j                  i}|r	||d<   dg}nd}| j                  j                  |t        j                  |d      t        j                  |d      t        j                  |d      | d||	|
||      }||
r|\  }}t        |d         |d	<   |S |"|
s |\  }}|d d
 t        |d         fz   |d
d  z   }|S )NzCMake sure to provide `position_ids` when passing `past_key_values`.r   r   rq   Fr   rM   )r   mutabler   r   )rC   r   r   r   r7   
ValueErrorr%   r~   r   ra   r   r   applyr&   r   )re   r   r   r   r   r   r   r   r   r   r   r   sequence_lengthr   inputsr   r   s                    r-   r   z FlaxGPTJPreTrainedModel.__call__  s    2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++BYBY&/oo#
O* !fgg++CJJ,Ga,PS]_nRopL! XXz?&CDN ")DOF1dkk2 -F7OiGG++##IIit,IInD1IIl$/I  $ 
 &;'.$G_)1/'2J)KG%&N('.$G_bqkXog.F%G$IIGTUTVKWGr/   N)	NNNNNFNNN)r   r   r   __doc__r   config_classbase_model_prefixr   rT   Moduler   r%   r   r   r   rD   rL   r   rV   r   r   r   r   r   r   GPTJ_INPUTS_DOCSTRINGdictr   r   __classcell__)r   s   @r-   r   r   g  sD   
 L%"L"))"
 $;;
m
m 
m 	
m
 yy
m 
m!!

 2 2 !! !!PZ !!fp !!F'& ++@A  $*.,0/3&*C
 C C ZZ''C C $D>C 'tnC d^C BCr/   r   c                       e Zd ZU eed<   ej                  Zej                  ed<   d Z	 	 	 	 	 	 	 dde	de	de	de	d	e	f
d
Z
y)FlaxGPTJBlockCollectionrC   rD   c           	          t        | j                  j                        D cg c]-  }t        | j                  t	        |      | j
                        / c}| _        y c c}w )N)namerD   )rangerC   num_hidden_layersr   strrD   blocks)re   is     r-   rh   zFlaxGPTJBlockCollection.setup  sE    OTUYU`U`UrUrOs
JKM$++CF$**E
 
s   2ANr   r   r   r   r   c	           	          |rdnd }	|rdnd }
| j                   D ])  }|r|
|fz  }
 |||||||      }|d   }|s!|	|d   fz  }	+ ||
|	f}|S )Nrw   )r   r   r   r   r   r   )r  )re   rl   r   r   r   r   r   r   r   all_attentionsall_hidden_statesblocklayer_outputsr   s                 r-   r   z FlaxGPTJBlockCollection.__call__  s      1d"6BD[[ 	6E#!m%55!!)+%"3M *!,M =#3"55	6$ !"3^Dr/   )NNTFFFTr   rw   r/   r-   r  r    sm    {{E399"
 " "'%* "
 " "  " #" "r/   r  c            	       x    e Zd ZU eed<   ej                  Zej                  ed<   d Z	 	 	 	 	 d
de	de	de	de	fdZ
y	)FlaxGPTJModulerC   rD   c                 Z   | j                   j                  | _        t        j                  | j                   j
                  | j                   j                  t        j                  j                  j                  | j                   j                              | _
        t        j                  | j                   j                        | _        t        | j                   | j                        | _        t        j"                  | j                   j$                  | j                        | _        y )Nstddev)embedding_initrJ   rM   r   )rC   rN   rO   rT   Embed
vocab_sizerV   rW   rX   rY   wter^   
embd_pdropr   r  rD   hr   r   ln_fre   s    r-   rh   zFlaxGPTJModule.setup,  s    0088KK""KK##66..55T[[=Z=Z5[

 zzt{{'='=>(DJJGLL)G)GtzzZ	r/   r   r   r   r   c	           
      T   | j                  |j                  d            }	| j                  |	|      }
| j                  |
|||||||      }|d   }
| j	                  |
      }
|r|d   |
fz   }|
|f|dd  z   }n	|
f|dd  z   }|st        d |D              S t        |
|d   |d   	      S )
Nr   r   )r   r   r   r   r   r   r   r   r   c              3   &   K   | ]	  }||  y wr  rw   ).0vs     r-   	<genexpr>z*FlaxGPTJModule.__call__.<locals>.<genexpr>\  s     =qq}=s   r1   )last_hidden_staterl   
attentions)r"  r!   r   r$  r%  r   r   )re   r   r   r   r   r   r   r   r   input_embedsrl   r   r  s                r-   r   zFlaxGPTJModule.__call__8  s     xx	 0 0 67\O&&%'!/!5#  	
  
		-0 '
m-= =$&78712;FG$&4G=G==="+!!*r{
 	
r/   NTFFFTr   rw   r/   r-   r  r  (  s^    {{E399"
["  "'%* *
 *
  *
 #*
 *
r/   r  z^The bare GPTJ Model transformer outputting raw hidden-states without any specific head on top.c                       e Zd ZeZy)FlaxGPTJModelN)r   r   r   r  r   rw   r/   r-   r1  r1  e  s	    
 "Lr/   r1  c                   |    e Zd ZU eed<   ej                  Zej                  ed<   d Z	 	 	 	 	 dde	de	de	de	de	f
d	Z
y
)FlaxGPTJForCausalLMModulerC   rD   c                 >   t        | j                  | j                        | _        t	        j
                  | j                  j                  | j                  t        j                  j                  j                  | j                  j                              | _        y )NrM   r  r   )r  rC   rD   r   rT   rU   r!  rV   rW   rX   rY   lm_headr&  s    r-   rh   zFlaxGPTJForCausalLMModule.setupy  sb    )$++TZZHxxKK""**++22$++:W:W2X
r/   r   r   r   r   r   c	           
      z   | j                  ||||||||      }	|	d   }
| j                  j                  rJ| j                   j                  d   d   d   j                  }| j
                  j                  dd|ii|
      }n| j                  |
      }|s	|f|	dd  z   S t        ||	j                  |	j                        S )	N)r   r   r   r   r   r   r   r"  	embeddingkernelr   )logitsrl   r-  )
r   rC   tie_word_embeddingsr   Tr5  r  r   rl   r-  )re   r   r   r   r   r   r   r   r   r   rl   shared_kernel	lm_logitss                r-   r   z"FlaxGPTJForCausalLMModule.__call__  s     ""'!/!5# # 	
  
;;** ,,66x@GTVVM**Hx6O+PR_`I]3I<'!"+--!'BWBWdkdvdvwwr/   Nr/  r   rw   r/   r-   r3  r3  u  sm    {{E399"
 # "'%* !x
 !x !x  !x #!x !xr/   r3  zJ
    The GPTJ Model transformer with a language modeling head on top.
    c                   >    e Zd ZeZddeej                     fdZd Z	y)FlaxGPTJForCausalLMNr   c                 H   |j                   \  }}| j                  ||      }t        j                  ||fd      }|-|j	                  d      dz
  }t        j                  ||d      }n4t        j                  t        j                  |d      d d d f   ||f      }|||dS )Nr   rM   r1   r2   r   )r   r   )r   r   r   )	r7   r   r%   ra   cumsumr   r}   r~   r   )	re   r   r   r   r   
seq_lengthr   extended_attention_maskr   s	            r-   prepare_inputs_for_generationz1FlaxGPTJForCausalLM.prepare_inputs_for_generation  s    !*
J//*jA #&((J
+C4"P%)00b09A=L&)&>&>?VXfhn&o#++CJJz,NtUVw,WZdfpYqrL  /5(
 	
r/   c                 L    |j                   |d<   |d   d d dd f   dz   |d<   |S )Nr   r   r1   r   )r   )re   model_outputsmodel_kwargss      r-   update_inputs_for_generationz0FlaxGPTJForCausalLM.update_inputs_for_generation  s8    *7*G*G&''3N'CArsF'Ka'O^$r/   r  )
r   r   r   r3  r   r   rV   ArrayrD  rH  rw   r/   r-   r?  r?    s'     -L
S[\_\e\eSf 
*r/   r?  ):	functoolsr   typingr   r   
flax.linenlinenrT   rV   	jax.numpynumpyr%   r   flax.core.frozen_dictr   r   r   r	   r
   flax.linen.attentionr   flax.traverse_utilr   r   r   modeling_flax_outputsr   r   modeling_flax_utilsr   r   r   utilsr   r   r   configuration_gptjr   
get_loggerr   logger_CHECKPOINT_FOR_DOC_CONFIG_FOR_DOCGPTJ_START_DOCSTRINGr	  r.   r:   r@   r  rB   r   r   r   r  r  r1  r3  r?  rw   r/   r-   <module>r\     su     "  
   > > 6 > ;  L \ \ Y Y * 
		H	% ! F B
E]		 ]@")) .&3BII &3RP1 Pf+bii +\:
RYY :
z d"+ "	" 	-x		 -x`  	1 < 	r/   