
    sgiw                        d Z 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$jN                  e(      Z)dZ*dZ+dZ,dZ-dZ.d Z/d Z0d Z1 G d dejd                        Z3 G d dejd                        Z4 G d dejd                        Z5 G d dejd                        Z6 G d  d!ejd                        Z7 G d" d#e      Z8 G d$ d%ejd                        Z9 G d& d'ejd                        Z: e"d(e-       G d) d*e8             Z; e e;e+ee*e,+        G d, d-ejd                        Z< e"d.e-       G d/ d0e8             Z= e e=e+ee*e,+       y)1zFlax LLaMA model.    )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   )LlamaConfigr   zafmck/testing-llama-tinyz openlm-research/open_llama_3b_v2a  

    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 ([`LlamaConfig`]): 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`, or
            `jax.numpy.bfloat16`.

            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)`):
            Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
            it.

            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)

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

            If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
            `past_key_values`).

            If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
            and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
            information on the default strategy.

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.
        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.n_positions - 1]`.

            [What are position IDs?](../glossary#position-ids)
        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                  ||fd      }t        j                  t        j
                  |      d d d d d f   t        j                  |      d d d d d f   fd      }t        j                  |d d d d d | f         S )	Ng      ?i'  r      zi , j -> i jfloat32axis)	nparangeeinsumastypeconcatenatesincosjnparray)num_posdiminv_freqfreqsembouts         `/var/www/html/venv/lib/python3.12/site-packages/transformers/models/llama/modeling_flax_llama.pycreate_sinusoidal_positionsr0      s    e		!S! 4s :;<HIInbii&8(CJJ9UE
..%b
1C
.."&&+aqj1266#;q$z3JKRT
UC99SAxx())    c                     t        j                  | d| j                  d   dz  df    | dd| j                  d   dz  f   fd      }|S )z*Rotates half the hidden dims of the input..r   r   Nr   )r'   r$   shape)tensorrotate_half_tensors     r/   rotate_halfr6      sa    
fll2&!+--
.	.s<Sfll2>NRS>S<S7S0TU\^ r1   c                 *    | |z  t        |       |z  z   S N)r6   )r4   sin_poscos_poss      r/   apply_rotary_pos_embr;      s    WV!4w!>??r1   c                   Z    e Zd ZU eed<   ej                  Zej                  ed<   d Zd Z	y)FlaxLlamaRMSNormconfigdtypec                     | j                   j                  | _        | j                  dd | j                   j                        | _        y )Nweightc                 ,    t        j                  |      S r8   )r'   ones)_r3   s     r/   <lambda>z(FlaxLlamaRMSNorm.setup.<locals>.<lambda>   s    CHHUO r1   )r>   rms_norm_epsepsilonparamhidden_sizerA   selfs    r/   setupzFlaxLlamaRMSNorm.setup   s2    {{//jj+KT[[MdMder1   c                 D   t        j                  |t         j                        }t        j                  |d      }|j	                  dd      }|t        j
                  || j                  z         z  }| j                  t        j                  || j                        z  S )Nr?   r   r   T)keepdims)	r'   asarrayr   powermeansqrtrG   rA   r?   )rK   hidden_statesvariances      r/   __call__zFlaxLlamaRMSNorm.__call__   sr    ;;}CKK@99Xq)==d=3%DLL1H(II{{S[[djjIIIr1   N
__name__
__module____qualname__r   __annotations__r'   r   r?   rL   rV    r1   r/   r=   r=      s&    {{E399"fJr1   r=   c                   Z    e Zd ZU eed<   ej                  Zej                  ed<   d Zd Z	y)FlaxLlamaRotaryEmbeddingr>   r?   c                     | j                   j                  | j                   j                  z  }t        | j                   j                  |      | _        y r8   )r>   rI   num_attention_headsr0   max_position_embeddingssincos)rK   head_dims     r/   rL   zFlaxLlamaRotaryEmbedding.setup   s9    ;;**dkk.M.MM1$++2U2UW_`r1   c                    | j                   |   }t        j                  |dd      \  }}t        |||      }t        |||      }t        j                  || j
                        }t        j                  || j
                        }||fS )Nr   r   r   rN   )rb   r'   splitr;   rP   r?   )rK   keyqueryposition_idsrb   r9   r:   s          r/   rV   z!FlaxLlamaRotaryEmbedding.__call__   su    \*99VQR8"39$UGW=kk#TZZ0E4Ezr1   NrW   r\   r1   r/   r^   r^      s%    {{E399"a
r1   r^   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)FlaxLlamaAttentionr>   r?   TcausalFis_cross_attentionc                    | j                   }|j                  | _        |j                  | _        | j                  | j                  z  | _        |j                  | _        | j                  | j                  z  | _        | j                  t        j                  u| _        t        t        j                  |j                  | j                  t         j                  j"                  j%                  | j                   j&                              } || j                  | j
                  z        | _         || j                  | j
                  z        | _         || j                  | j
                  z        | _         || j                        | _        t1        t        j2                  d|j4                  fd      d      | _        t9        || j                        | _        y )Nuse_biasr?   kernel_initr   boolrN   )r>   rI   	embed_dimr`   	num_headsrc   num_key_value_headsnum_key_value_groupsr?   r'   r   attention_softmax_in_fp32r   nnDenseattention_biasjaxinitializersnormalinitializer_rangeq_projk_projv_projo_projr
   rC   ra   causal_maskr^   
rotary_emb)rK   r>   denses      r/   rL   zFlaxLlamaAttention.setup   sP   ++33$..8#)#=#= $(NNd6N6N$N!)-3;;)F&HH****++224;;3P3PQ	
 DNNT]]:;D44t}}DED44t}}DEDNN++CHHa9W9W5X`f,gouv26Lr1   c                 \    |j                  |j                  d d || j                  fz         S Nr   )reshaper3   rc   )rK   rT   rs   s      r/   _split_headszFlaxLlamaAttention._split_heads   s.    $$]%8%8!%<	4==?Y%YZZr1   c                 Z    |j                  |j                  d d | j                  fz         S r   )r   r3   rr   )rK   rT   s     r/   _merge_headszFlaxLlamaAttention._merge_heads   s,    $$]%8%8!%<?P%PQQr1   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   rN   )r'   r(   int32r\   r1   r/   rE   z:FlaxLlamaAttention._concatenate_to_cache.<locals>.<lambda>   s    CIIaWZW`W`Da r1   )r   r   r   )has_variablevariabler'   zerosr3   r?   valuelenr   dynamic_update_slicebroadcast_tor!   tupler	   )rK   rf   r   rg   attention_maskis_initializedr   r   r   
batch_dims
max_lengthrs   depth_per_head	cur_indexindicesnum_updated_cache_vectorspad_masks                    r/   _concatenate_to_cachez(FlaxLlamaAttention._concatenate_to_cache   sr    **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>))r1   deterministic
init_cacheoutput_attentionsc           
         | j                  |      }| j                  |      }| j                  |      }	| j                  || j                        }| j                  || j
                        }| j                  |	| j
                        }	| j                  |||      \  }}|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        j*                  || j,                  d
      }t        j*                  |	| j,                  d
      }	t        j.                  |dkD  t        j0                  |j                  d      j3                  | j4                        t        j0                  |j                  t        j6                  | j4                        j8                        j3                  | j4                              }| j:                  rt        j<                  n| j4                  }t?        ||||| j"                  j$                  ||      }| j:                  r|j3                  | j4                        }t        j@                  d||	      }| jC                  |      }| jE                  |      }|r||f}|S |f}|S )Nr   r   r   r   r   )r   g        dropoutr   )biasdropout_rngdropout_rater   r?   z...hqk,...khd->...qhd)#r~   r   r   r   rs   rt   r   r3   r   	variablesr   dynamic_slicer   r'   r   expand_dimsr	   r>   attention_dropoutmake_rngr   repeatru   selectfullr#   r?   finfominrv   r   r   r"   r   r   )rK   rT   r   rh   r   r   r   rg   rf   r   query_length
key_length
mask_shiftmax_decoder_lengthr   
batch_sizer   ry   attention_dtypeattn_weightsattn_outputoutputss                         r/   rV   zFlaxLlamaAttention.__call__  sN    M*kk-(M*!!%8T%=%=>!!%)A)AB__S%>
U#(;;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!>!>!D--	2K Wl3z)-)C)CCPUWe)f&Cjjd77a@

5$";";!D QHH^))3/66tzzBHH^))399TZZ+@+D+DELLTZZX
 *.)G)G#++TZZ4#66'!
 ))'..tzz:Ljj!8,N''4kk+.1B;- JUr1   N)TFF)rX   rY   rZ   r   r[   r'   r   r?   rk   rq   rl   rL   r   r   rw   compactr   rV   r\   r1   r/   rj   rj      s    {{E399"FD$$M.[R ZZ* *H # "'K
 K K  Kr1   rj   c                   Z    e Zd ZU eed<   ej                  Zej                  ed<   d Zd Z	y)FlaxLlamaMLPr>   r?   c                 @   | j                   j                  }| j                   j                  | j                   j                  nd|z  }t        j                  j
                  j                  | j                   j                        }t        | j                   j                     | _
        t	        j                  |d| j                  |      | _        t	        j                  |d| j                  |      | _        t	        j                  |d| j                  |      | _        y )N   Frn   )r>   rI   intermediate_sizerz   rw   r{   r|   r}   r   
hidden_actactrx   r?   	gate_proj	down_projup_proj)rK   rr   	inner_dimrp   s       r/   rL   zFlaxLlamaMLP.setupU  s    KK++	59[[5R5R5^DKK11dehqdq	ff))001N1NO$++001)e4::[fg)e4::[fgxx	EYder1   c                     | j                  |      }| j                  | j                  |            }| j                  ||z        }|S r8   )r   r   r   r   )rK   rT   up_proj_statesgate_statess       r/   rV   zFlaxLlamaMLP.__call__`  s@    m4hht~~m<=~'CDr1   NrW   r\   r1   r/   r   r   Q  s%    {{E399"	fr1   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)
FlaxLlamaDecoderLayerr>   r?   c                 4   t        | j                  | j                        | _        t	        | j                  | j                        | _        t        | j                  | j                        | _        t        | j                  | j                        | _        y )NrN   )	r=   r>   r?   input_layernormrj   	self_attnpost_attention_layernormr   mlprJ   s    r/   rL   zFlaxLlamaDecoderLayer.setupl  s\    /4::N+DKKtzzJ(8DJJ(W%4::>r1   Nr   r   r   c                     |}| j                  |      }| j                  ||||||      }|d   }	||	z   }|}| j                  |      }| j                  |      }||z   }|f|dd  z   S )Nr   rh   r   r   r   r   r   )r   r   r   r   )
rK   rT   r   rh   r   r   r   residualr   r   s
             r/   rV   zFlaxLlamaDecoderLayer.__call__r  s     !,,];..)%'!/ ! 
 aj ;. 55mD/ =0'!"+--r1   )NNTFFrX   rY   rZ   r   r[   r'   r   r?   rL   rq   rV   r\   r1   r/   r   r   h  sS    {{E399"? " "'.
 . .  .r1   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 )FlaxLlamaPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    modelNmodule_class)r   r   r   Tr>   input_shapeseedr?   _do_initc                 Z     | j                   d||d|}t        | 	  ||||||       y )N)r>   r?   )r   r   r?   r   r\   )r   super__init__)	rK   r>   r   r   r?   r   kwargsmodule	__class__s	           r/   r   z!FlaxLlamaPreTrainedModel.__init__  s=     #""H&HH[tSXcklr1   rngparamsreturnc                 P   t        j                  |d      }t        j                  |      }t        j                  t        j                  t        j
                  |      j                  d         |      }t        j                  j                  |      \  }}||d}	| j                  j                  |	|||d      d   }
|dt        t        |
            }
t        t        |            }| j                  D ]
  }|
|   ||<    t               | _        t!        t#        |            S |
S )Ni4rN   r   )r   r   F)return_dictr   )r'   r   	ones_liker   r!   
atleast_2dr3   rz   randomre   r   initr   r   _missing_keyssetr   r   )rK   r   r   r   	input_idsr   rh   
params_rngr   rngsrandom_paramsmissing_keys               r/   init_weightsz%FlaxLlamaPreTrainedModel.init_weights  s   IIk6	y1''

3>>)3L3R3RSU3V(WYde"%**"2"23"7
K$=((y.,di(jkst(-)@AM!(6"23F#11 A&3K&@{#A!$D.011  r1   c                    t        j                  ||f      }t        j                  |      }t        j                  t        j                  t        j
                  |      j                  d         |j                        }| j                  j                  t        j                  j                  d      |||dd      }t        |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.
        r   r   FT)r   r   r   )r'   rC   r   r   r!   r   r3   r   r   rz   r   PRNGKeyr   )rK   r   r   r   r   rh   init_variabless          r/   r   z#FlaxLlamaPreTrainedModel.init_cache  s     HHj*56	y1''

3>>)3L3R3RSU3V(WYbYhYhi))JJq!9nlX]jn * 
 w/00r1   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   r   Fr   rN   )r   mutabler   r   )r>   r   r   r   r3   
ValueErrorr'   r   r!   rC   r   r   applyr(   r   )rK   r   r   rh   r   r   r   r   r   r   r   r   sequence_lengthr   inputsr  r   s                    r/   rV   z!FlaxLlamaPreTrainedModel.__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r1   r8   )	NNNNNFNNN)rX   rY   rZ   __doc__r   config_classbase_model_prefixr   rw   Moduler[   r'   r   r   intr?   rq   r   rz   r   r   r   r   r   r   LLAMA_INPUTS_DOCSTRINGdictr   rV   __classcell__)r   s   @r/   r   r     sC   
 L"L"))"
 $;;
m
m 
m 	
m
 yy
m 
m!

 2 2 ! !PZ !fp !(1& ++AB  $*.,0/3&*C
 C C ZZ''C C $D>C 'tnC d^C CCr1   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)FlaxLlamaLayerCollectionr>   r?   c           
          t        | j                  j                        D cg c]-  }t        | j                  | j                  t        |            / c}| _        y c c}w )N)r?   name)ranger>   num_hidden_layersr   r?   strblocks)rK   is     r/   rL   zFlaxLlamaLayerCollection.setup  sG     4;;889
 "$++TZZc!fM
 
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 )Nr\   r   r   r   )r  )rK   rT   r   rh   r   r   r   r   r   all_attentionsall_hidden_statesblocklayer_outputsr   s                 r/   rV   z!FlaxLlamaLayerCollection.__call__!  s      1d"6BD[[ 	6E#!m%55!!-)+%"3M *!,M =#3"55	6" !"3^Dr1   )NNTFFFFr   r\   r1   r/   r  r    sm    {{E399"
 " "'%*!!
 ! !  ! #! !r1   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	fd	Z
y)FlaxLlamaModuler>   r?   c                    | j                   j                  | _        t        j                  j                  j                  | j                   j                        }t        j                  | j                   j                  | j                  || j                        | _
        t        | j                   | j                        | _        t        | j                   | j                        | _        y )Nstddev)embedding_initr?   rN   )r>   rI   rz   rw   r{   r|   r}   Embed
vocab_sizer?   embed_tokensr  layersr=   norm)rK   r!  s     r/   rL   zFlaxLlamaModule.setupI  s    ;;22,,334;;;X;X3YHHKK"")**	
 /t{{$**M$T[[

C	r1   Nr   r   r   r   c	           
      .   | j                  |j                  d            }	| 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   rh   r   r   r   r   r   r   r   r   r   c              3   &   K   | ]	  }||  y wr8   r\   ).0vs     r/   	<genexpr>z+FlaxLlamaModule.__call__.<locals>.<genexpr>w  s     =qq}=s   r   )last_hidden_staterT   
attentions)r$  r#   r%  r&  r   r   )rK   r   r   rh   r   r   r   r   r   input_embedsr   rT   r  s                r/   rV   zFlaxLlamaModule.__call__U  s     (()9)9$)?@++%)'!/!5#  	
  
		-0 '
m-= =$&78712;FG$&4G=G==="+!!*r{
 	
r1   NNTFFFTr   r\   r1   r/   r  r  E  sd    {{E399"
D  "'%* (
 (
  (
 #(
 (
r1   r  z_The bare Llama Model transformer outputting raw hidden-states without any specific head on top.c                       e Zd ZeZy)FlaxLlamaModelN)rX   rY   rZ   r  r   r\   r1   r/   r2  r2    s	    
 #Lr1   r2  )real_checkpointc                       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)FlaxLlamaForCausalLMModuler>   r?   c                 @   t        | j                  | j                        | _        t	        j
                  | j                  j                  d| j                  t        j                  j                  j                  | j                  j                              | _        y )NrN   Fr  rn   )r  r>   r?   r   rw   rx   r#  rz   r{   r|   r}   lm_headrJ   s    r/   rL   z FlaxLlamaForCausalLMModule.setup  sd    $T[[

C
xxKK""**++22$++:W:W2X	
r1   Nr   r   r   r   r   c	           
          | j                  ||||||||      }	|	d   }
| j                  |
      }|s	|f|	dd  z   S t        ||	j                  |	j                        S )Nr(  r   r   )logitsrT   r.  )r   r7  r   rT   r.  )rK   r   r   rh   r   r   r   r   r   r   rT   	lm_logitss               r/   rV   z#FlaxLlamaForCausalLMModule.__call__  sz     **%)'!/!5#  	
  
LL/	<'!"+--!'BWBWdkdvdvwwr1   r0  r   r\   r1   r/   r5  r5    ss    {{E399"
 " "'%* x
 x x  x #x xr1   r5  zZ
    The Llama Model transformer with a language modeling head (linear layer) on top.
    c                   >    e Zd ZeZddeej                     fdZd Z	y)FlaxLlamaForCausalLMNr   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   rN   r   r   r   )r   r   )r   r   rh   )	r3   r   r'   rC   cumsumr   r   r   r!   )	rK   r   r   r   r   
seq_lengthr   extended_attention_maskrh   s	            r/   prepare_inputs_for_generationz2FlaxLlamaForCausalLM.prepare_inputs_for_generation  s    !*
J//*jA #&((J
+C4"P%)00b09A=L&)&>&>?VXfhn&o#++CJJz,NtUVw,WZdfpYqrL  /5(
 	
r1   c                 L    |j                   |d<   |d   d d dd f   dz   |d<   |S )Nr   rh   r   r   )r   )rK   model_outputsmodel_kwargss      r/   update_inputs_for_generationz1FlaxLlamaForCausalLM.update_inputs_for_generation  s8    *7*G*G&''3N'CArsF'Ka'O^$r1   r8   )
rX   rY   rZ   r5  r   r   rz   ArrayrA  rE  r\   r1   r/   r<  r<    s'     .L
S[\_\e\eSf 
*r1   r<  )>r  	functoolsr   typingr   r   
flax.linenlinenrw   rz   	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_llamar   
get_loggerrX   logger_CONFIG_FOR_DOC_CHECKPOINT_FOR_DOC_REAL_CHECKPOINT_FOR_DOCLLAMA_START_DOCSTRINGr  r0   r6   r;   r	  r=   r^   rj   r   r   r   r  r  r2  r5  r<  r\   r1   r/   <module>rZ     s  (   "  
   > > 6 > ;  L \ \ Y Y , 
		H	%0 = ! F. b*@Jryy J$ryy *O Od299 .'.BII '.VA2 AH+ryy +\8
bii 8
v e#- #	# ,)x )xX  	3 < ,r1   