
    sg4{                        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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 ddlmZmZ ddlmZm Z m!Z! ddl"m#Z#m$Z$ ddl%m&Z&  e$jN                  e(      Z)dZ*dZ+dZ,dZ- G d dej\                        Z/ G d dej\                        Z0 G d dej\                        Z1 G d dejd                        Z3 G d dej\                        Z4 G d d e       Z5 G d! d"ej\                        Z6 G d# d$e5      Z7 e!e7e*ee+        e#d%e,       G d& d'ej\                               Z8 e#d(e,       G d) d*e5             Z9 e!e9e*ee+       y)+zFlax OPT model.    )partial)OptionalTupleN)
FrozenDictfreezeunfreeze)combine_masksmake_causal_mask)dot_product_attention_weights)flatten_dictunflatten_dict)lax)PRNGKey   )FlaxBaseModelOutputFlaxMaskedLMOutput)ACT2FNFlaxPreTrainedModelappend_call_sample_docstring)add_start_docstringslogging   )	OPTConfigzfacebook/opt-350mr   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 ([`OPTConfig`]): 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 (`jnp.ndarray` of shape `(batch_size, sequence_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 (`jnp.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]`.
        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                   P   e Zd ZU eed<   eed<   eed<   dZeed<   dZe	ed<   dZ
e	ed	<   ej                  Zej                  ed
<   ddZd Zd Zej$                  d        Z	 	 	 	 ddej(                  deej(                     deej(                     de	de	deej(                     fdZy)FlaxOPTAttentionconfig	embed_dim	num_heads        dropoutFcausalTbiasdtypereturnNc           	         | j                   | j                  z  | _        | j                  | j                  z  | j                   k7  r&t        d| j                    d| j                   d      t	        t
        j                  | j                   | j                  | j                  t        j
                  j                  j                  | j                  j                              } |        |        |       c| _        | _        | _         |       | _        t        j$                  | j&                        | _        | j*                  r>t-        t/        j0                  d| j                  j2                  fd      d      | _        y y )	Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).use_biasr#   kernel_initrater   boolr#   )r   r   head_dim
ValueErrorr   nnDenser"   r#   jaxinitializersnormalr   init_stdq_projk_projv_projout_projDropoutr    dropout_layerr!   r
   jnponesmax_position_embeddingscausal_mask)selfdenses     \/var/www/html/venv/lib/python3.12/site-packages/transformers/models/opt/modeling_flax_opt.pysetupzFlaxOPTAttention.setupu   s   $..8==4>>)T^^;MdnnM]$T^^$4B8 
 HHNNYY**++224;;3G3GH
 16%'-T[$+ZZT\\:;;/!T[[@@APX^ D     c                 p    |j                  |j                  d d | j                  | j                  fz         S N   )reshapeshaper   r-   r?   hidden_statess     rA   _split_headszFlaxOPTAttention._split_heads   s5    $$]%8%8!%<PTP]P]?^%^__rC   c                 Z    |j                  |j                  d d | j                  fz         S rE   )rG   rH   r   rI   s     rA   _merge_headszFlaxOPTAttention._merge_heads   s,    $$]%8%8!%<?P%PQQrC   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   r,   )r;   arrayint32 rC   rA   <lambda>z8FlaxOPTAttention._concatenate_to_cache.<locals>.<lambda>   s    CIIaWZW`W`Da rC   )r   r   r   )has_variablevariabler;   zerosrH   r#   valuelenr   dynamic_update_slicebroadcast_toarangetupler	   )r?   keyr[   queryattention_maskis_initializedrP   rQ   rR   
batch_dims
max_lengthr   depth_per_head	cur_indexindicesnum_updated_cache_vectorspad_masks                    rA   _concatenate_to_cachez&FlaxOPTAttention._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>))rC   rJ   key_value_statesrc   
init_cachedeterministicc                    |du}|j                   d   }| j                  |      }|r#| j                  |      }	| j                  |      }
n"| j                  |      }	| j                  |      }
| j	                  |      }| j	                  |	      }	| j	                  |
      }
| j
                  r|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   }t        j                  ||f|j                   dd z         }|N| j
                  rBt        j                  t        j                  |d      j                         }t        ||      }n(| j
                  r}n|t        j                  |d      }| j
                  r,| j                  dd      s|r| j                  |	|
||      \  }	}
}|t        j                   |dkD  t        j"                  |j                   d	      j%                  | j&                        t        j"                  |j                   t        j(                  | j&                        j*                        j%                  | j&                              }nd}d}|s | j,                  d	kD  r| j/                  d
      }t1        ||	||| j,                  d|| j&                  d	      }t        j2                  d||
      }| j5                  |      }| j7                  |      }||fS )z#Input shape: Batch x Time x ChannelNr   r   rO   rP   rR   )axisr   r    T)r"   dropout_rngdropout_ratebroadcast_dropoutro   r#   	precisionz...hqk,...khd->...qhd)rH   r5   r6   r7   rK   r!   rX   	variablesr   dynamic_slicer>   r;   r^   expand_dimsr	   rl   selectfullastyper#   finfominr    make_rngr   einsumrM   r8   )r?   rJ   rm   rc   rn   ro   is_cross_attention
batch_sizequery_states
key_statesvalue_statesquery_length
key_length
mask_shiftmax_decoder_lengthr>   attention_biasru   attn_weightsattn_outputs                       rA   __call__zFlaxOPTAttention.__call__   s,    .T9"((+
 {{=1%56J;;'78L ]3J;;}5L((6&&z2
((6 ;;'3'9'9!'<j>N>Nq>Q*L  ,7!^^G4]C
%)^^G%<\%J%P%PQR%S"!//$$q!Z&;aLRd=e #..q!]l]KZK/OP**;HYHYZ[Z\H]8]^K %$++ --coonS[.\^i^o^opN*>;GN[[(N' __^(KN ;;D--g|D
7;7Q7QL,84Jn
 % ZZ"--s3::4::F--syy/D/H/HIPPQUQ[Q[\N "N!3--	2K4#"'**

 jj!8,U''4mmK0L((rC   r$   N)NNFT)__name__
__module____qualname__r   __annotations__intr    floatr!   r+   r"   r;   float32r#   rB   rK   rM   r/   compactrl   ndarrayr   r   r   rV   rC   rA   r   r   l   s    NNGUFDD${{E399"4`R ZZ* *D 3704 "[){{[) #3;;/[) !-	[)
 [) [) 
s{{	[)rC   r   c                       e Zd ZU eed<   ej                  Zej                  ed<   ddZ	 	 	 ddej                  dej                  de
d	e
d
e
deej                     fdZy)FlaxOPTDecoderLayerr   r#   r$   Nc                 &   | j                   j                  | _        t        | j                   | j                  | j                   j                  | j                   j
                  d| j                        | _        | j                   j                  | _        t        j                  | j                   j                        | _        t        | j                   j                     | _        t        j                   | j                  d      | _        t        j$                  | j                   j&                  | j                  t(        j                  j*                  j-                  | j                   j.                              | _        t        j$                  | j                  | j                  t(        j                  j*                  j-                  | j                   j.                              | _        t        j                   | j                  d      | _        y )NT)r   r   r   r    r!   r#   r)   h㈵>r#   epsilon)r#   r(   )r   hidden_sizer   r   num_attention_headsattention_dropoutr#   	self_attndo_layer_norm_beforer/   r9   r    r:   r   activation_functionactivation_fn	LayerNormself_attn_layer_normr0   ffn_dimr1   r2   r3   r4   fc1fc2final_layer_normr?   s    rA   rB   zFlaxOPTDecoderLayer.setup  sP   00);;nnkk55KK11**
 %)KK$D$D!ZZT[[-@-@A#DKK$C$CD$&LLtzz5$Q!88KK**++224;;3G3GH

 88NN$**#&&:M:M:T:TUYU`U`UiUi:j
 !#4::u MrC   rJ   rc   rn   output_attentionsro   c                 v   |}| j                   r| j                  |      }| j                  ||||      \  }}| j                  ||      }||z   }| j                   s| j                  |      }|j                  }|j                  d|j                  d         }|}| j                   r| j                  |      }| j                  |      }| j                  |      }| j                  |      }| j                  ||      }||z   j                  |      }| j                   s| j                  |      }|f}	|r|	|fz  }	|	S )N)rJ   rc   rn   ro   )ro   )
r   r   r   r:   rH   rG   r   r   r   r   )
r?   rJ   rc   rn   r   ro   residualself_attn_weightshidden_states_shapeoutputss
             rA   r   zFlaxOPTDecoderLayer.__call__0  s`    ! $$ 55mDM ,0>>')!'	 ,: ,
(( **=*V =0(( 55mDM ,11%--b-2E2Eb2IJ  $$ 11-@M/**=9/**=*V!M1::;NO (( 11-@M ")++GrC   r   )FTT)r   r   r   r   r   r;   r   r#   rB   r   r+   r   r   rV   rC   rA   r   r     s{    {{E399"N: !"&"5{{5 5 	5
  5 5 
s{{	5rC   r   c            	       v    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	)FlaxOPTDecoderLayerCollectionr   r#   c           	          t        | j                  j                        D cg c]-  }t        | j                  t	        |      | j
                        / c}| _        | j                  j                  | _        y c c}w )N)namer#   )ranger   num_hidden_layersr   strr#   layers	layerdrop)r?   is     rA   rB   z#FlaxOPTDecoderLayerCollection.setupl  sZ     4;;889
  #a&

K
 ..	
s   2A8ro   rn   r   output_hidden_statesc                     |rdnd }|rdnd }| j                   D ](  }	|r||fz  } |	|||||      }
|
d   }|s ||
d   fz  }* |||g}|S )NrV   )rc   rn   r   ro   r   r   )r   )r?   rJ   rc   ro   rn   r   r   all_hidden_statesall_self_attnsdecoder_layerlayer_outputsr   s               rA   r   z&FlaxOPTDecoderLayerCollection.__call__s  s     #7BD0d![[ 	6M#!m%55!)-%"3+M *!,M =#3"55	6  !"3^DrC   N)TFFFr   r   r   r   r   r;   r   r#   rB   r+   r   rV   rC   rA   r   r   h  sZ    {{E399"/ # "'%* 	
    #rC   r   c                   (     e Zd ZdZd Z fdZ xZS )!FlaxOPTLearnedPositionalEmbeddingzN
    This module learns positional embeddings up to a fixed maximum size.
    c                     d| _         | j                  d| j                  | j                  | j                   z   | j                  f| j
                        | _        y )NrF   	embedding)offsetparamembedding_initnum_embeddingsfeaturesparam_dtyper   r   s    rA   rB   z'FlaxOPTLearnedPositionalEmbedding.setup  sJ    ,,t/B/BT[[/PRVR_R_.`bfbrbr
rC   c                 <    t         |   || j                  z         S )z3`input_ids_shape` is expected to be [bsz x seqlen].)superr   r   )r?   	positions	__class__s     rA   r   z*FlaxOPTLearnedPositionalEmbedding.__call__  s     w	DKK 788rC   )r   r   r   __doc__rB   r   __classcell__r   s   @rA   r   r     s    
9 9rC   r   c                       e Zd ZU eed<   ej                  Zej                  ed<   dZe	ed<   d Z
	 	 	 	 	 ddededed	ed
ef
dZy)FlaxOPTDecoderr   r#   rF   r   c                     t        j                  | j                  j                        | _        | j                  j
                  }| j                  j                  | _        | j                  j                  | _	        t        j                  | j                  j                  | j                  j                  t        j                   j                  j                  | j                  j                         | j"                        | _        t'        | j                  j                  |t        j                   j                  j                  | j                  j                         | j"                        | _        | j                  j                  | j                  j
                  k7  rat        j*                  | j                  j
                  d      | _        t        j*                  | j                  j                  d      | _        nd | _        d | _        | j                  j0                  r=| j                  j2                  s't        j4                  | j"                  d      | _        nd | _        t9        | j                  | j"                        | _        y )Nr)   )r   r#   F)r'   r   r   )r/   r9   r   r    r:   r   pad_token_idpadding_idxr=   max_target_positionsEmbed
vocab_sizeword_embed_proj_dimr1   r2   r3   r4   r#   embed_tokensr   embed_positionsr0   
project_inproject_outr   _remove_final_layer_normr   r   r   r   )r?   r   s     rA   rB   zFlaxOPTDecoder.setup  s   ZZT[[-@-@AKK++	;;33$(KK$G$G!HHKK""KK++66..55dkk6J6JK**	
  AKK//66..55dkk6J6JK**	 
 ;;**dkk.E.EE hht{{'>'>ODO!xx(G(GRWXD #DO#D
 ;;++DKK4X4X$&LLtzz5$QD!$(D!3DKKLrC   rn   r   r   return_dictro   c	                    |j                   }	|j                  d|	d         }| j                  |      }
| j                  | j                  |
      }
| j	                  |      }|
|z   }| j                  ||||||      \  }}}| j                  | j                  |      }| j                  | j                  |      }|r||fz  }|||g}|st        d |D              S t        |||      S )Nr   )ro   rn   r   r   c              3   &   K   | ]	  }||  y wNrV   ).0vs     rA   	<genexpr>z*FlaxOPTDecoder.__call__.<locals>.<genexpr>  s     =qq}=s   last_hidden_staterJ   
attentions)
rH   rG   r   r   r   r   r   r   r`   r   )r?   	input_idsrc   position_idsrn   r   r   r   ro   input_shapeinputs_embedsr   rJ   hidden_stater   r   r   s                    rA   r   zFlaxOPTDecoder.__call__  s     oo%%b+b/:	)))4??& OOM:M((6	%	16:kk'!/!5 7B 7
3'   ,00>L'++L9L,0!2J?=G==="*+!
 	
rC   NFFFTT)r   r   r   r   r   r;   r   r#   r   r   rB   r+   r   rV   rC   rA   r   r     sr    {{E399"FCO%MX !"'%* "1

 1
  1
 #1
 1
 1
rC   r   c                       e Zd ZU eZdZeed<   dZe	j                  ed<   ddej                  dfded	e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	 	 	 	 	 	 	 	 	 ddej0                  deej0                     deej0                     dededee   dee   dee   dedefdZ xZS )FlaxOPTPreTrainedModelmodelbase_model_prefixNmodule_class)r   r   r   Tr   r   seedr#   _do_initc                 Z     | j                   d||d|}t        | 	  ||||||       y )Nr   r#   )r   r   r#   r   rV   )r   r   __init__)	r?   r   r   r   r#   r   kwargsmoduler   s	           rA   r   zFlaxOPTPreTrainedModel.__init__
  s=     #""H&HH[tSXcklrC   rngparamsr$   c                 D   t        j                  |d      }t        j                  |      }|j                  \  }}t        j                  t        j
                  |      d d d f   ||f      }t        j                  j                  |      \  }	}
|	|
d}| j                  j                  ||||d      }|d   }|dt        t        |            }t        t        |            }| j                  D ]
  }||   ||<    t               | _        t        t!        |            S |S )Ni4r,   )r  r    F)r   r  )r;   rZ   	ones_likerH   r^   r_   r1   randomsplitr   initr   r   _missing_keyssetr   r   )r?   r  r   r  r   rc   r   sequence_lengthr   
params_rngru   rngsmodule_init_outputsrandom_paramsmissing_keys                  rA   init_weightsz#FlaxOPTPreTrainedModel.init_weights  s   IIk6	y1&/oo#
O''

?(CD!G(Lz[jNkl"%**"2"23"7
K$="kk.. / 
 ,H5(-)@AM!(6"23F#11 A&3K&@{#A!$D.011  rC   c                    t        j                  ||fd      }t        j                  |d      }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,   r   r   FT)r   rn   rO   )r;   r<   r  r^   r_   
atleast_2drH   r   r  r1   r  r   r   )r?   r   rf   r   rc   r   init_variabless          rA   rn   z!FlaxOPTPreTrainedModel.init_cache4  s     HHj*5TB	y=''

3>>)3L3R3RSU3V(WYbYhYhi))JJq!9nlX]jn * 
 w/00rC   r   rc   r   past_key_valuesr   r   r   ru   ro   c                    ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }|t	        j
                  |      }||j                  d      |z  dz
  }|	d|	ini }d|xs | j                  i}|r	||d<   dg}nd}| j                  j                  |t	        j                  |d      t	        j                  |d      t	        j                  |d      ||||
||	
      }||r|\  }}t        |d         |d
<   |S |"|s |\  }}|d d t        |d         fz   |dd  z   }|S )Nr   rs   r    r  rO   Fr  r,   )	r   rc   r   r   r   r   ro   r  mutabler  )r   r   r   r   r;   r  cumsumr  r   applyrT   r   )r?   r   rc   r   r  r  r   r   r   ru   ro   r  inputsr  r   s                  rA   r   zFlaxOPTPreTrainedModel.__call__G  s    2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++BYBY! ]]95N*11q19NJaOL ,7+B	;'F1dkk2
 -F7OiGG++##ii	699^4@<t</!5#' $ 
 &;'.$G_)1/'2J)KG%&N('.$G_bqkXog.F%G$IIGTUTVKWGrC   r   )	NNNNNNNNT)r   r   r   r   config_classr   r   r   r   r/   Moduler;   r   r   r   r#   r+   r   r1   r  r   r   r  rn   r   r   dictr   r   r   s   @rA   r   r     sN   L$s$"L"))"
 #);;
m
m 3Z
m 	
m
 yy
m 
m!

 2 2 ! !PZ !fp !<1, 15.2 $,0/3&*#"=;;= !-= s{{+	=
 = = $D>= 'tn= d^= = =rC   r   c            	       ~    e Zd ZU eed<   ej                  Zej                  ed<   d Zd Z		 	 	 	 	 dde
de
de
de
fd	Zy
)FlaxOPTModuler   r#   c                 P    t        | j                  | j                        | _        y )Nr,   )r   r   r#   decoderr   s    rA   rB   zFlaxOPTModule.setup  s    %dkkDrC   c                     | j                   S r   )r!  r   s    rA   _get_decoder_modulez!FlaxOPTModule._get_decoder_module  s    ||rC   r   r   r   ro   c	           
          | j                  ||||||||      }	|s|	S t        |	j                  |	j                  |	j                        S )N)r   rc   r   r   r   r   ro   rn   r   )r!  r   r   rJ   r   )
r?   r   rc   r   r   r   r   ro   rn   decoder_outputss
             rA   r   zFlaxOPTModule.__call__  sb     ,,)%/!5#'! ' 	
 """-??)77&11
 	
rC   N)FFTTF)r   r   r   r   r   r;   r   r#   rB   r#  r+   r   rV   rC   rA   r  r    sc    {{E399"E #(%* "

  
 #
 
 
rC   r  c                   R    e Zd ZU eed<   ej                  Zej                  ed<   eZ	y)FlaxOPTModelr   r#   N)
r   r   r   r   r   r;   r   r#   r  r   rV   rC   rA   r'  r'    s    {{E399" LrC   r'  z]The bare OPT Model transformer outputting raw hidden-states without any specific head on top.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
)FlaxOPTForCausalLMModuler   r#   c                 >   t        | j                  | j                        | _        t	        j
                  | j                  j                  d| j                  t        j                  j                  j                  | j                  j                              | _        y )Nr   Fr&   )r  r   r#   r   r/   r0   r   r1   r2   r3   r4   lm_headr   s    rA   rB   zFlaxOPTForCausalLMModule.setup  sa    "$++TZZH
xxKK""**++224;;3G3GH	
rC   rn   r   r   r   ro   c	           
         | j                  ||||||||      }	|	d   }
| j                  j                  rM| j                   j                  d   d   d   d   }| j                  j                  dd|j                  ii|
      }n| j	                  |
      }|s	|f|	dd  z   S t        ||	j                  |	j                  	      S )
N)rn   r   r   r   ro   r   r  r!  r   r   kernelr   )logitsrJ   r   )
r   r   tie_word_embeddingsry   r+  r  Tr   rJ   r   )r?   r   rc   r   rn   r   r   r   ro   r   rJ   shared_embedding	lm_logitss                rA   r   z!FlaxOPTForCausalLMModule.__call__  s     **!/!5#'  	
  
;;**#zz33H=iHXYde**HxAQASAS6T+UWdeI]3I<'!"+--!!//))
 	
rC   Nr   r   rV   rC   rA   r)  r)    si    
 {{E399"
 !"'%* "%

 %
  %
 #%
 %
 %
rC   r)  z
    OPT Model with a language modeling head on top (linear layer with weights tied to the input embeddings) e.g for
    autoregressive tasks.
    c                   >    e Zd ZeZddeej                     fdZd Z	y)FlaxOPTForCausalLMNrc   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  r,   r   rs   )r   r   )r  rc   r   )	rH   rn   r;   r<   r  r   r]   r^   r_   )	r?   r   rf   rc   r   
seq_lengthr  extended_attention_maskr   s	            rA   prepare_inputs_for_generationz0FlaxOPTForCausalLM.prepare_inputs_for_generation  s    !*
J//*jA #&((J
+C4"P%)00a081<L&)&>&>?VXfhn&o#++CJJz,NtUVw,WZdfpYqrL  /5(
 	
rC   c                 L    |j                   |d<   |d   d d dd f   dz   |d<   |S )Nr  r   r   r   )r  )r?   model_outputsmodel_kwargss      rA   update_inputs_for_generationz/FlaxOPTForCausalLM.update_inputs_for_generation  s8    *7*G*G&''3N'CArsF'Ka'O^$rC   r   )
r   r   r   r)  r   r   r1   Arrayr8  r<  rV   rC   rA   r4  r4    s'     ,L
S[\_\e\eSf 
,rC   r4  ):r   	functoolsr   typingr   r   
flax.linenlinenr/   r1   	jax.numpynumpyr;   flax.core.frozen_dictr   r   r   r	   r
   flax.linen.attentionr   flax.traverse_utilr   r   r   
jax.randomr   modeling_flax_outputsr   r   modeling_flax_utilsr   r   r   utilsr   r   configuration_optr   
get_loggerr   logger_CHECKPOINT_FOR_DOC_CONFIG_FOR_DOCOPT_START_DOCSTRINGOPT_INPUTS_DOCSTRINGr  r   r   r   r   r   r   r   r  r'  r)  r4  rV   rC   rA   <module>rR     su     "  
  > > 6 > ;   L \ \ 2 ( 
		H	%)   D @d)ryy d)NR")) Rj)BII )X9 9"]
RYY ]
@0 D'
BII '
V!) ! \+>@SUd e c2
ryy 2
	2
j  / > 	rC   