o
    Zhg                    @   s&  d Z ddlZddlmZmZmZ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 ddlmZmZ dd	lmZ d
dlm Z m!Z!m"Z"m#Z#m$Z$ d
dl%m&Z&m'Z'm(Z(m)Z)m*Z* d
dl+m,Z,m-Z-m.Z.m/Z/ ddl0m1Z1 e.2e3Z4dZ5dZ6ej7Z7dej8de9de9dej8fddZ:dhdej8de9de9de9dej8f
ddZ;dej8de9de9dej8fddZ<dhdej8d e9d!e9de9dej8f
d"d#Z=de9dej8fd$d%Z>d&ej8de9dej8fd'd(Z?d)ej8de9dej8fd*d+Z@d)ej8d,e9deej8ej8f fd-d.ZAd)ej8d,e9dej8fd/d0ZBd1ej8d2ej8d3e9dej8fd4d5ZCG d6d7 d7e
jDZEG d8d9 d9e
jDZFG d:d; d;e
jDZGG d<d= d=e
jDZHG d>d? d?e
jDZIG d@dA dAe
jDZJG dBdC dCe
jDZKG dDdE dEe
jDZLG dFdG dGe
jDZMG dHdI dIe
jDZNG dJdK dKe
jDZOG dLdM dMe
jDZPG dNdO dOe
jDZQG dPdQ dQe
jDZRG dRdS dSe
jDZSdTZTdUZUdVZVG dWdX dXe'ZWdYZXe,dZeXG d[d\ d\e
jDZYG d]d^ d^eWZZe(eZe5e$e6 d_Z[e*eZeVe[  e)eZe#e6d` e,daeXG dbdc dce
jDZ\G ddde deeWZ]dfZ^e*e]eVe^  e)e]e#e6d` g dgZ_dS )izFlax LongT5 model.    N)AnyCallableListOptionalTuple)
FrozenDictfreezeunfreeze)combine_masksmake_causal_mask)partitioning)dot_product_attention_weights)flatten_dictunflatten_dict)PRNGKey   )FlaxBaseModelOutput-FlaxBaseModelOutputWithPastAndCrossAttentions%FlaxCausalLMOutputWithCrossAttentionsFlaxSeq2SeqLMOutputFlaxSeq2SeqModelOutput)ACT2FNFlaxPreTrainedModelappend_call_sample_docstring append_replace_return_docstringsoverwrite_call_docstring)add_start_docstrings%add_start_docstrings_to_model_forwardloggingreplace_return_docstrings   )LongT5Configzgoogle/long-t5-local-baser!   	input_idspad_token_iddecoder_start_token_idreturnc                 C   sd   t | }|jddddf | ddddf }|jdddf |}t |dk||}|S )z1
    Shift input ids one token to the right.
    Nr    r   i)jnp
zeros_likeatsetwhere)r"   r#   r$   Zshifted_input_ids r,   ^/var/www/auris/lib/python3.10/site-packages/transformers/models/longt5/modeling_flax_longt5.pyshift_tokens_right:   s
   
,r.   x	block_lenaxis	pad_valuec                 C   s>   | j |  | }dg| j }d|f||< tj| |d|d} | S )zHPad an array so that a sequence length will be a multiple of `block_len`r   r   r   constantZ	pad_widthmodeZconstant_values)shapendimr'   pad)r/   r0   r1   r2   Zpad_lenr9   r,   r,   r-   _pad_to_multipleF   s
   r:   c                 C   sb   | j | | dkrt| ||dd} | j | | }| j d| ||f | j |d d  }| |S )zSplit an input array into blocks of a given `block_len` along the given `axis`. If the dimension length
    is not a multiple of `block_len`, it will be padded first with selected `pad_value`.
    r   )r2   Nr    )r7   r:   reshape)r/   r0   r1   
num_blocksZoutput_shaper,   r,   r-   _split_into_blocksO   s
   (
r=   
block_axissequence_axisc           	      C   s   | j | }dg| j }d||< tj| |d|d} g }tdD ]}tddg| j }t||| ||< t|}|| |  qtj||dS )	zConcatenate three consecutive blocks for each input block for local attentiont.
    For more information, see: https://arxiv.org/pdf/2112.07916.pdf.
    r3   r    r    r4   r5   r   r   Nr1   )	r7   r8   r'   r9   rangeslicetupleappendconcatenate)	r/   r>   r?   r2   r<   r9   Zblocks_listiindicesr,   r,   r-   _concatenate_3_blocks[   s   
rI   c                 C   sF   t jd|  t jd}|| |   }|dddf |dddf  }|S )z:Makes 3-blocked relative position ids for local attention.r   dtypeN)r'   arangeint32)r0   Zposition_idsZcenter_position_idsrelative_position_idsr,   r,   r-   "_make_3block_relative_position_idsq   s    rO   local_attention_maskc                 C   s:   t |}t||k }|ddddddf }t| |S )znMask local attention mask to enforce that tokens are not allowed to attend tokens farther than ``local_radius.N)rO   r'   abslogical_and)rP   r0   rN   Zlocality_maskr,   r,   r-   _mask_local_attention_masky   s   rS   attention_maskc                 C   s^   t | |dd}t|ddd}|d }|ddddf }t||}t||}|ddddf S )z;Prepare attention mask to be applied for a local attention.r    rA      r>   r?   .N.N)r=   rI   r'   rR   rS   )rT   r0   Z_blocked_attention_maskZ_3blocked_attention_maskrP   r,   r,   r-   _get_local_attention_mask   s   
rX   global_block_sizec           
         s  | j dd \}dtjdtjf fdd}t|   }tj|dd| }t| d	kd
d}tt|| d
 tj	d| j
d}||  | d  }||}  }|dkrjtj|jdddddf |dd}n
tj|df|j
d}tjt||fddd }	t|	|kdd}	||	fS )a  Obtain the "fixed block" global id corresponding to each input token.

    This implementation is a simplified version of the original Flaxformr implementation adopted from:
    https://github.com/google/flaxformer/blob/main/flaxformer/architectures/longt5/long_attention.py.

    In our scenario, as we use this strategy only for a decoder, orphan tokens, i.e. those tokens which do not make for
    the whole fixed block, are assigned to the preceding block.

    Padding tokens from the original sequence are represented by -1.
    NrU   	block_idsr%   c                    sH   t    d k}t || dk}|dd }t | |d } | S )Nr    r   r&   rW   )r'   rL   rR   summinimum)rZ   Z
block_endsZtrue_block_endsZfull_blocksrY   Zseq_lenr,   r-   handle_orphan_tokens   s
   z:_make_global_fixed_block_ids.<locals>.handle_orphan_tokensr    rA                 ?g     @g      rJ   r   r&   )Zrepeatsr1   )r7   npndarrayr'   	ones_likeZcumsumr+   maximumfloorarrayrK   repeatmaxzerosones)
rT   rY   
batch_sizer^   Zfixed_block_maskmaskZglobal_block_idsZnum_globalsZ_sequence_block_ids_maxglobal_segment_idsr,   r]   r-   _make_global_fixed_block_ids   s"   &rn   c                 C   s2   t | |\}}|jd }t|}||d  }|S )zBCreate the relative position tensor for local -> global attention.r&   rW   )rn   r7   r'   rL   )rT   rY   rZ   rm   global_seq_lenZglobal_positionsside_relative_positionr,   r,   r-    _make_side_relative_position_ids   s
   

rq   hidden_statesrZ   ro   c                 C   s   t j||}td| |S )zFCompute individual block aggregates by summing over individual blocks.z...nd,...ng->...gd)jaxnnZone_hotr'   einsum)rr   rZ   ro   Zone_hot_block_idsr,   r,   r-   _create_global_aggregates   s   rv   c                   @   s^   e Zd ZU eed< ejZejed< dZe	ed< e
jjjZedejf ed< dd Zd	d
 ZdS )FlaxLongT5LayerNormhidden_sizerK   gư>eps.weight_initc                 C   s   |  d| j| jf| _d S )Nweight)paramrz   rx   r{   selfr,   r,   r-   setup   s   zFlaxLongT5LayerNorm.setupc                 C   s:   t |ddjddd}|t || j  }| j| S )zg
        Construct a layernorm module in the LongT5 style; No bias and no subtraction of mean.
        Zf4rU   r&   T)r1   Zkeepdims)r'   powerastypemeansqrtry   r{   )r~   rr   Zvariancer,   r,   r-   __call__   s   
zFlaxLongT5LayerNorm.__call__N)__name__
__module____qualname__int__annotations__r'   float32rK   ry   floatrs   rt   initializersrj   rz   r   ra   rb   r   r   r,   r,   r,   r-   rw      s   
 rw   c                   @   8   e Zd ZU eed< ejZejed< dd Zd	ddZ	dS )
FlaxLongT5DenseActDenseconfigrK   c                 C   s   | j j| j jd  }| j j| j jd  }tj| j jdtjj|| j	d| _
tj| j jdtjj|| j	d| _t| j j| _t| j j | _d S N      FZuse_biasZkernel_initrK   )r   initializer_factord_modeld_ffrt   Densers   r   normalrK   wiwoDropoutdropout_ratedropoutr   dense_act_fnactr~   Zwi_init_stdZwo_init_stdr,   r,   r-   r      s    zFlaxLongT5DenseActDense.setupTc                 C   s0   |  |}| |}| j||d}| |}|S Ndeterministic)r   r   r   r   )r~   rr   r   r,   r,   r-   r      s
   


z FlaxLongT5DenseActDense.__call__NT
r   r   r   r!   r   r'   r   rK   r   r   r,   r,   r,   r-   r      s
   
 r   c                   @   s6   e Zd ZU eed< ejZejed< dd Zdd Z	dS )FlaxLongT5DenseGatedActDenser   rK   c                 C   s   | j j| j jd  }| j j| j jd  }tj| j jdtjj|| j	d| _
tj| j jdtjj|| j	d| _tj| j jdtjj|| j	d| _t| j j| _t| j j | _d S r   )r   r   r   r   rt   r   rs   r   r   rK   wi_0wi_1r   r   r   r   r   r   r   r   r,   r,   r-   r     s,   z"FlaxLongT5DenseGatedActDense.setupc                 C   s>   |  | |}| |}|| }| j||d}| |}|S r   )r   r   r   r   r   )r~   rr   r   Zhidden_geluZhidden_linearr,   r,   r-   r     s   

z%FlaxLongT5DenseGatedActDense.__call__Nr   r,   r,   r,   r-   r     s
   
 r   c                   @   r   )
FlaxLongT5LayerFFr   rK   c                 C   s\   | j jrt| j | jd| _n	t| j | jd| _t| j j| j j| jd| _	t
| j j| _d S )NrJ   ry   rK   )r   Zis_gated_actr   rK   DenseReluDenser   rw   r   layer_norm_epsilon
layer_normrt   r   r   r   r}   r,   r,   r-   r   ,  s   zFlaxLongT5LayerFF.setupTc                 C   s.   |  |}| j||d}|| j||d }|S r   )r   r   r   )r~   rr   r   Zforwarded_statesr,   r,   r-   r   7  s   
zFlaxLongT5LayerFF.__call__Nr   r   r,   r,   r,   r-   r   (  s
   
 r   c                   @   s   e Zd ZU eed< dZeed< dZeed< ej	Z
ej
ed< dd ZedddZdd Zdd Zdd Zejdd Zdd Z							dddZdS )FlaxLongT5Attentionr   Fhas_relative_attention_biascausalrK   c                 C   s@  | j j| _| j j| _| j j| _| j j| _| j j| _| j j| _	| j| j | _
| j j| j
| j d  }| j j| j
d  }| j j| j
d  }tj| j
dtjj|| jd| _tj| j
dtjj|| jd| _tj| j
dtjj|| jd| _tj| jdtjj|| jd| _| jrtj| j| jtjj|| jd| _d S d S )Nr   Fr   embedding_initrK   )r   relative_attention_num_bucketsrelative_attention_max_distancer   d_kvkey_value_proj_dim	num_headsn_headsr   r   	inner_dimr   rt   r   rs   r   r   rK   qkvor   Embedrelative_attention_biasr~   Z
q_init_stdZkv_init_stdZ
o_init_stdr,   r,   r-   r   E  sT   





zFlaxLongT5Attention.setupT       c                 C      d}|r|d }|| dk| 7 }t | } nt j| dd } |d }| |k }|t | | t ||  ||   }t j||d d}|t || |7 }|dS av  
        Adapted from Mesh Tensorflow:
        https://github.com/tensorflow/mesh/blob/0cb87fe07da627bf0b7e60475d59f95ed6b5be3d/mesh_tensorflow/transformer/transformer_layers.py#L593

        Translate relative position to a bucket number for relative attention. The relative position is defined as
        memory_position - query_position, i.e. the distance in tokens from the attending position to the attended-to
        position. If bidirectional=False, then positive relative positions are invalid. We use smaller buckets for
        small absolute relative_position and larger buckets for larger absolute relative_positions. All relative
        positions >=max_distance map to the same bucket. All relative positions <=-max_distance map to the same bucket.
        This should allow for more graceful generalization to longer sequences than the model has been trained on
        r   rU   )Za_maxr    i4r'   rQ   Zcliplogr+   r   relative_positionbidirectionalnum_bucketsmax_distanceZrelative_bucketsZ	max_exactZis_smallZrelative_position_if_larger,   r,   r-   _relative_position_buckets  s   "
z-FlaxLongT5Attention._relative_position_bucketc                 C   s   t j|dddddf }t j|dddddf }|| }| j|| j | j| jd}| |}|ddddddddf }|S )%Compute binned relative position biasr   rJ   Nr   r   r   rU   r   r    )r'   rL   r   r   r   r   r   	transpose)r~   query_length
key_lengthcontext_positionmemory_positionr   relative_position_bucketvaluesr,   r,   r-   compute_bias  s   
"z FlaxLongT5Attention.compute_biasc                 C       | |jd d | j| jf S NrU   r;   r7   r   r   r~   rr   r,   r,   r-   _split_heads      z FlaxLongT5Attention._split_headsc                 C   s   | |jd d | jf S r   r;   r7   r   r   r,   r,   r-   _merge_heads  s   z FlaxLongT5Attention._merge_headsc                 C   s  |  dd}| ddtj|j|j}| ddtj|j|j}| dddd }|r||jj^ }	}
}}|j}dt|	 |ddf }tj	
|j||}tj	
|j||}||_||_|jd	 }|j| |_tt|
|| k t|	d	||
f }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 slightly 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                   S   s   t jdt jdS )Nr   rJ   )r'   rf   rM   r,   r,   r,   r-   <lambda>  s    z;FlaxLongT5Attention._concatenate_to_cache.<locals>.<lambda>r   r   r    )has_variablevariabler'   ri   r7   rK   valuelenrs   laxdynamic_update_slicebroadcast_torL   rD   r
   )r~   keyr   queryrT   Zis_initializedr   r   r   Z
batch_dims
max_lengthr   Zdepth_per_headZ	cur_indexrH   Znum_updated_cache_vectorsZpad_maskr,   r,   r-   _concatenate_to_cache  s(   


z)FlaxLongT5Attention._concatenate_to_cachec                 C   s   | j o| ddo| }|jd }|r|n|jd }	| jr$| |	|}
n|d ur.t|}
ntjd| j|	|f| j	d}
|rX| j
d d jd }tj|
dd|dfd| j||f}
|
S )Nr   r   r    rJ   r   )r   r   r7   r   r   r'   r(   ri   r   rK   	variablesrs   r   dynamic_slice)r~   
key_statesquery_statesrT   
init_cache
seq_lengthcausal_attention_mask_shiftZcache_is_filledr   r   position_biasmax_decoder_lengthr,   r,   r-   _create_position_bias  s    

z)FlaxLongT5Attention._create_position_biasNc	              
   C   sr  |j dd \}	}
| |}|du r| |n| |}|du r%| |n| |}| |}| |}| |}|t|j d 9 }| ddrS| jrS| j	d d nd}| jrt
|dd	}| ddr~| j	d d j d
 }tj|dd|dfd
d
|
|f}t||	f|j d
d  }ttj|dd|j }t||}n|durtj|dd}| jr| dds|r| ||||\}}}|durt| jj}tj|dkt|j d| jt|j || j}|du r| |||||
|}|dur|| }d}|s| jdkr| d}t||||| jd|| jd}td||}| |}| |}||f}|r7||f }|S )
        Self-attention (if key_value_states is None) or attention over source sentence (provided by key_value_states).
        NrU   r&   r   r   r   r   boolrJ   r    )rA   r_   r   TZbiasdropout_rngr   Zbroadcast_dropoutr   rK   ...hqk,...khd->...qhd)r7   r   r   r   r   r'   r   r   r   r   r   rs   r   r   r   Zexpand_dimsr
   r   ZfinforK   minselectfullr   r   r   make_rngr   ru   r   r   )r~   rr   rT   key_value_statesr   	use_cacheoutput_attentionsr   r   rk   r   r   r   value_statesr   Zcausal_attention_maskr   Z
mask_valuer   attn_weightsattn_outputoutputsr,   r,   r-   r     s   



"






zFlaxLongT5Attention.__call__Tr   r   )NNNFFTF)r   r   r   r!   r   r   r   r   r'   r   rK   r   staticmethodr   r   r   r   rt   compactr   r   r   r,   r,   r,   r-   r   ?  s,   
 .#
 r   c                   @   s   e Zd ZU eed< dZeed< ejZ	ej	ed< dd Z
edd
dZdefddZdd Zdd Zdedeej dejfddZ					dddZdS )FlaxLongT5LocalAttentionr   Fr   rK   c                 C   sR  | j j| _| j j| _| j j| _| j j| _| j j| _| j j| _| jd | _	| j j
| _| j| j | _| j j| j| j d  }| j j| jd  }| j j| jd  }tj| jdtjj|| jd| _tj| jdtjj|| jd| _tj| jdtjj|| jd| _tj| jdtjj|| jd| _| jrtj| j| jtjj|d| _d S d S )Nr    r   Fr   r   )r   r   r   r   r   r   r   r   local_radiusr0   r   r   r   r   rt   r   rs   r   r   rK   r   r   r   r   r   r   r   r   r,   r,   r-   r   `  sV   






zFlaxLongT5LocalAttention.setupTr   r   c                 C   r   r   r   r   r,   r,   r-   r        "
z2FlaxLongT5LocalAttention._relative_position_bucketblock_lengthc                 C      t jd| dd}|||  }|dddf |dddf  }| j|d| j| jd}| |}|dddddddddf }|S r   r   r   rJ   NTr   r   r'   rL   r   r   r   r   r   r~   r  r   r   r   r   r   r,   r,   r-   r         
$z%FlaxLongT5LocalAttention.compute_biasc                 C   r   r   r   r   r,   r,   r-   r     r   z%FlaxLongT5LocalAttention._split_headsc                 C      | |jd d| jS Nr   r&   r   r   r,   r,   r-   r        z%FlaxLongT5LocalAttention._merge_headsr0   rT   r%   c                 C   N   | j r
| |}|S |d urt|}|S tjdd| j|d| f| jd}|S Nr    r   rJ   r   r   r'   r(   ri   r   rK   r~   r0   rT   r   r,   r,   r-   r        

 z.FlaxLongT5LocalAttention._create_position_biasNc              
   C   s  |j dd \}}| |}	|du r| |n| |}
|du r%| |n| |}| |	}	| |
}
| |}t|	| jdd}	t|
| jdd}
t|| jdd}t|
ddd}
t|ddd}|	t	|	j d 9 }	|durt
|| j}tj|dkt|j d| jt|j d	| j}|du r| | j|}|dur||dd }d}|s| jdkr| d
}t|	|
||| jd|| jd}td||}| |}|ddd|ddf }| |}||f}|r||f }|S )r   NrU   r    rA   rV   r&   r   r_       _r   Tr   r  )r7   r   r   r   r   r=   r0   rI   r'   r   rX   rs   r   r  r  r   rK   r   swapaxesr   r  r   ru   r   r   )r~   rr   rT   r  r   r  r   rk   r   r   r   r	  r   r
  r  r  r,   r,   r-   r     sZ   







z!FlaxLongT5LocalAttention.__call__r  NNNFT)r   r   r   r!   r   r   r   r'   r   rK   r   r  r   r   r   r   r   r   ra   rb   r   r   r,   r,   r,   r-   r  [  s"   
 /#r  c                   @   s   e Zd ZU eed< dZeed< ejZ	ej	ed< dd Z
edd
dZdefddZdejdejdejfddZdd Zdd Zdedeej dejfddZ					dddZdS ) "FlaxLongT5TransientGlobalAttentionr   Fr   rK   c                 C   s  | j j| _| j j| _| j j| _| j j| _| j j| _| j j| _| jd | _	| j j
| _
| j j| _| j| j | _| j j| j| j d  }| j j| jd  }| j j| jd  }tj| jdtjj|| jd| _tj| jdtjj|| jd| _tj| jdtjj|| jd| _tj| jdtjj|| jd| _| jrtj| j| jtjj|d| _| jrtj| j| jtjj|d| _t| j j| j j| jd| _d S )Nr    r   Fr   r  r   ) r   r   r   r   r   r   r   r   r  r0   rY   r   r   r   r   rt   r   rs   r   r   rK   r   r   r   r   r   r   r   global_relative_attention_biasrw   r   global_input_layer_normr   r,   r,   r-   r   3  sh   







z(FlaxLongT5TransientGlobalAttention.setupTr   r   c                 C   r   r   r   r   r,   r,   r-   r   n  r  z<FlaxLongT5TransientGlobalAttention._relative_position_bucketr  c                 C   r  r  r  r  r,   r,   r-   r     r  z/FlaxLongT5TransientGlobalAttention.compute_biasrT   rm   r%   c                 C   s   t |d |d d d d d f d d d df }tj|dkt |jd| jt |jd| j}t	|| j
}| j|d| j| jd}| |}t |d}|| }|S )	NrW   .r   r_   r"  Tr   )r   r   r    rU   )r'   equalrs   r   r  r  r7   r   rK   rq   rY   r   r   r   r&  r   )r~   rT   rm   Zside_attention_maskZattention_side_biasrp   Zside_relative_position_bucketZ	side_biasr,   r,   r-   compute_side_bias  s"   0
z4FlaxLongT5TransientGlobalAttention.compute_side_biasc                 C   r   r   r   r   r,   r,   r-   r     r   z/FlaxLongT5TransientGlobalAttention._split_headsc                 C   r  r  r   r   r,   r,   r-   r     r  z/FlaxLongT5TransientGlobalAttention._merge_headsr0   c                 C   r  r  r  r   r,   r,   r-   r     r!  z8FlaxLongT5TransientGlobalAttention._create_position_biasNc              
   C   s$  |j dd \}}t|dur|nt||f| j\}	}
|
j d }t||	|}| |}| |}|du r:| |n| |}|du rH| 	|n| 	|}| 
|}| 
|}| 
|}| |}| 	|}| 
|}| 
|}t|| jdd}t|| jdd}t|| jdd}t|ddd}t|ddd}dg|jd  }|j d |d< t|ddddf |}t|ddddf |}tj||fdd}tj||fdd}|t|j d 9 }|durt|| j}tj|dkt|j d	| jt|j d
| j}nd}|du rH| | j|}|dur||dd }|du r*t||f}| ||
}t|| jdd}t|dd}tj||fdd}d}|sX| jd	krX| d}t||||| jd|| jd}td||}|  |}|ddd|ddf }| !|}||f}|r||f }|S )r   NrU   r&   r    rA   rV   .r   r_   r"  r   r   Tr   r  )"r7   rn   r'   rj   rY   rv   r'  r   r   r   r   r=   r0   rI   r8   ZtilerF   r   rX   rs   r   r  r  r   rK   r   r#  r)  r   r  r   ru   r   r   )r~   rr   rT   r  r   r  r   rk   r   rZ   rm   Z_global_seq_lenZglobal_inputsr   r   r	  Zside_key_statesZside_value_statesZrepsrP   Zside_position_biasr   r
  r  r  r,   r,   r-   r     s   

















z+FlaxLongT5TransientGlobalAttention.__call__r  r$  )r   r   r   r!   r   r   r   r'   r   rK   r   r  r   r   r   ra   rb   r)  r   r   r   r   r   r,   r,   r,   r-   r%  .  s$   
 ;#r%  c                   @   V   e Zd ZU dZeed< dZeed< ej	Z
ej
ed< dd Z					dd
efddZdS )!FlaxLongT5LayerLocalSelfAttentionz$Local self attention used in encoderr   Fr   rK   c                 C   D   t | j| j| jd| _t| jj| jj| jd| _t	
| jj| _d S Nr   rK   r   )r  r   r   rK   LocalSelfAttentionrw   r   r   r   rt   r   r   r   r}   r,   r,   r-   r   U     z'FlaxLongT5LayerLocalSelfAttention.setupNTkwargsc           
      K   J   |  |}| j|||||d}|| j|d |d }|f|dd   }	|	S N)rT   r   r  r   r   r   r    )r   r/  r   
r~   rr   rT   r   r  r   r1  normed_hidden_statesattention_outputr  r,   r,   r-   r   ^     
	z*FlaxLongT5LayerLocalSelfAttention.__call__NNFTr   r   r   __doc__r!   r   r   r   r'   r   rK   r   r   r   r,   r,   r,   r-   r+  N     
 r+  c                   @   r*  )+FlaxLongT5LayerTransientGlobalSelfAttentionz/Transient-Global self attention used in encoderr   Fr   rK   c                 C   r,  r-  )r%  r   r   rK   TransientGlobalSelfAttentionrw   r   r   r   rt   r   r   r   r}   r,   r,   r-   r   {  r0  z1FlaxLongT5LayerTransientGlobalSelfAttention.setupNTr1  c           
      K   r2  r3  )r   r=  r   r4  r,   r,   r-   r     r7  z4FlaxLongT5LayerTransientGlobalSelfAttention.__call__r8  r9  r,   r,   r,   r-   r<  t  r;  r<  c                   @   sN   e Zd ZU eed< dZeed< ejZ	ej	ed< dd Z
					dd	d
ZdS )FlaxLongT5LayerSelfAttentionr   Fr   rK   c                 C   sJ   t | j| j| jj| jd| _t| jj| jj| jd| _	t
| jj| _d S )Nr   r   rK   r   )r   r   r   r   rK   SelfAttentionrw   r   r   r   rt   r   r   r   r}   r,   r,   r-   r     s   z"FlaxLongT5LayerSelfAttention.setupNTc           
      C   sL   |  |}| j||||||d}|| j|d |d }|f|dd   }	|	S )NrT   r   r  r   r   r   r   r    )r   r@  r   )
r~   rr   rT   r   r  r   r   r5  r6  r  r,   r,   r-   r     s   
	z%FlaxLongT5LayerSelfAttention.__call__)NNFTFr   r   r   r!   r   r   r   r'   r   rK   r   r   r,   r,   r,   r-   r>    s   
 r>  c                   @   s@   e Zd ZU eed< ejZejed< dd Z				d
dd	Z	dS )FlaxLongT5LayerCrossAttentionr   rK   c                 C   sD   t | jdd| jd| _t| jj| jj| jd| _t	| jj
| _d S )NFr?  r   )r   r   rK   EncDecAttentionrw   r   r   r   rt   r   r   r   r}   r,   r,   r-   r     r0  z#FlaxLongT5LayerCrossAttention.setupNFTc           
      C   sJ   |  |}| j|||||d}|| j|d |d }|f|dd   }	|	S )N)rT   r  r   r  r   r   r    )r   rD  r   )
r~   rr   r  rT   r   r  r   r5  r6  r  r,   r,   r-   r     r7  z&FlaxLongT5LayerCrossAttention.__call__r8  r   r,   r,   r,   r-   rC    s   
 rC  c                   @   sV   e Zd ZU eed< dZeed< ejZ	ej	ed< dd Z
									dd	d
ZdS )FlaxLongT5Blockr   Fr   rK   c                 C   s   | j j| _| jrt}n| j jdkrt}n| j jdkrt}n
td| j j d|| j | jtd| j	df| _
d}| jrP|  j
t| j td| j	df7  _
|d7 }|  j
t| j t|| j	df7  _
d S )	Nlocalztransient-globalzjFor encoder attention mechanism, either `local` or `transient-global` attention type is expected, but got .r   )r   namerK   r    )rH  rK   )r   r   r>  Zencoder_attention_typer+  r<  
ValueErrorr   strrK   layerrC  r   )r~   Zattention_layerZfeed_forward_indexr,   r,   r-   r     s0   
"&zFlaxLongT5Block.setupNTc                 C   s   | j d |||||	|
d}|d }|dd  }| jo|d u}|r9| j d ||||||	d}|d }||dd   }| j d ||	d}|f}|| }|S )Nr   rA  r    )r  rT   r   r  r   r&   r   )rK  r   )r~   rr   rT   r   encoder_hidden_statesencoder_attention_maskencoder_decoder_position_biasr  return_dictr   r   Zself_attention_outputsZattention_outputsZdo_cross_attentionZcross_attention_outputsr  r,   r,   r-   r   	  s4   zFlaxLongT5Block.__call__)	NNNNNFTTFrB  r,   r,   r,   r-   rE    s   
  rE  c                   @   sP   e Zd ZU eed< eed< ejZejed< dd Z									dd	d
Z
dS )FlaxLongT5LayerCollectionr   r   rK   c                 C   s   t | j| j| jd| _d S )Nr.  )rE  r   r   rK   rK  r}   r,   r,   r-   r   B  s   zFlaxLongT5LayerCollection.setupNFTc
           
      C   s   | j |||||||||	d	S )N)rT   r   rL  rM  rN  r  r   r   )rK  )
r~   rr   rT   r   rL  rM  rN  r  r   r   r,   r,   r-   r   G  s   z"FlaxLongT5LayerCollection.__call__)NNNNNFTF)r   r   r   r!   r   r   r'   r   rK   r   r   r,   r,   r,   r-   rP  =  s   
 rP  c                	   @   sf   e Zd ZU eed< ejZejed< dZe	ed< dd Z
								dd	e	d
e	de	de	fddZdS )FlaxLongT5BlockCollectionr   rK   Fgradient_checkpointingc                    s^   j j_jrttdd  fddtj jD _d S fddtj jD _d S )N)         )Zstatic_argnumsc                    s(   g | ]} j |d kjt|dqS r   )r   rK   rH  )r   rK   rJ  .0rG   ZFlaxLongT5CheckpointLayerr~   r,   r-   
<listcomp>j      z3FlaxLongT5BlockCollection.setup.<locals>.<listcomp>c                    s(   g | ]}t  j|d k jt|dqS rV  )rP  r   rK   rJ  rW  r}   r,   r-   rZ  t  r[  )r   r   rR  rematrP  rB   
num_layersblocksr}   r,   rY  r-   r   f  s   




zFlaxLongT5BlockCollection.setupNTr  output_hidden_statesr   r   c	                 C   s   |rdnd }	|r
dnd }
|r| j rdnd }d }d }t| jD ]A\}}|r)|	|f }	||||||||||	}|d }|d }| j rL|d urL||rIdnd }|r_|
|d f }
| j r_||d f }qt||	|
|dS )Nr,   r   r    r   rU      last_hidden_staterr   
attentionscross_attentions)r   	enumerater^  r   )r~   rr   rT   rL  rM  r  r_  r   r   all_hidden_statesZall_attentionsZall_cross_attentionsr   rN  rG   Zlayer_moduleZlayer_outputsr,   r,   r-   r   ~  sD   
z"FlaxLongT5BlockCollection.__call__)NNNNFFTF)r   r   r   r!   r   r'   r   rK   rR  r   r   r   r,   r,   r,   r-   rQ  a  s,   
 	rQ  c                   @   sv   e Zd ZU eed< ejed< ejZ	ej	ed< dZ
eed< dd Z											dd
ededededef
ddZdS )FlaxLongT5Stackr   embed_tokensrK   FrR  c                 C   sN   | j j| _t| j | j| jd| _t| j j| j j| jd| _	t
| j j| _d S )NrK   rR  r   )r   r   rQ  rK   rR  blockrw   r   r   final_layer_normrt   r   r   r   r}   r,   r,   r-   r     s   
zFlaxLongT5Stack.setupNTr  r_  rO  r   r   c
              
   C   s   |  |}
| j|
|d}
| j|
|||||||	d}|d }
| |
}
| j|
|d}
d }|r5|j}||
f }|sL|rC|
|f|dd   S |
f|dd   S t|
||j|jdS )Nr   )rT   rL  rM  r  r_  r   r   r   rU   r    ra  )rh  r   rj  rk  rr   r   rc  rd  )r~   r"   rT   rL  rM  r  r_  rO  r   r   rr   r  rf  r,   r,   r-   r     sB   



zFlaxLongT5Stack.__call__)	NNNNFFTTF)r   r   r   r!   r   rt   r   r'   r   rK   rR  r   r   r   r,   r,   r,   r-   rg    s4   
 
	
rg  a  
    Args:
        input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. LongT5 is a model with relative position embeddings so
            you should be able to pad the inputs on both the right and the left.

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

            To know more on how to prepare `input_ids` for pretraining take a look a [LONGT5
            Training](./longt5#training).
        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)
        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.
a1
  
    Args:
        decoder_input_ids (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`):
            Indices of decoder input sequence tokens in the vocabulary.

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

            [What are decoder input IDs?](../glossary#decoder-input-ids)

            For training, `decoder_input_ids` should be provided.
        encoder_outputs (`tuple(tuple(jnp.ndarray)`):
            Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
            `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
            hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
        encoder_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)
        decoder_attention_mask (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*):
            Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
            be used by default.

            If you want to change padding behavior, you should modify to your needs. See diagram 1 in [the
            paper](https://arxiv.org/abs/1910.13461) for more information on the default strategy.
        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.
a  
    Args:
        input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. LongT5 is a model with relative position embeddings so
            you should be able to pad the inputs on both the right and the left.

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

            [What are input IDs?](../glossary#input-ids)

            To know more on how to prepare `input_ids` for pretraining take a look a [LONGT5
            Training](./longt5#training).
        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)
        decoder_input_ids (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*):
            Indices of decoder input sequence tokens in the vocabulary.

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

            [What are decoder input IDs?](../glossary#decoder-input-ids)

            LONGT5 uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If
            `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
            `past_key_values`).

            To know more on how to prepare `decoder_input_ids` for pretraining take a look at [LONGT5
            Training](./longt5#training).
        decoder_attention_mask (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*):
            Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
            be used by default.
        encoder_outputs (`tuple(tuple(jnp.ndarray)`, *optional*):
            Tuple consists of (`last_hidden_state`, `optional`: *hidden_states*, `optional`: *attentions*)
            `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)` is a sequence of hidden states at
            the output of the last layer of the encoder. Used in the cross-attention of the decoder.
        past_key_values (`tuple(tuple(jnp.ndarray))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
            Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.

            If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
            don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
            `decoder_input_ids` of shape `(batch_size, sequence_length)`.


        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                       s  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e d
edejdef
 fddZdd Zd+dejjd	ededefddZee									d,dejdeej dejdeej dee dee dee dedee defd d!Zd"d# Zee e!e"ed$							d-dejdeej dee dee dee dedee defd%d&Z#ee$e!e%ed$									d,d'eej deej d(ee dee dee dee dedee defd)d*Z&  Z'S ).FlaxLongT5PreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    ZtransformerNmodule_classr@   r   Tr   input_shapeseedrK   _do_initc                    s2   | j d||d|}t j||||||d d S )N)r   rK   )rn  ro  rK   rp  r,   )rm  super__init__)r~   r   rn  ro  rK   rp  r1  module	__class__r,   r-   rr    s   	z"FlaxLongT5PreTrainedModel.__init__c                 C   s   | j | j| jdd| _d S )NT)r   rK   rR  )rm  r   rK   _moduler}   r,   r,   r-   enable_gradient_checkpointing  s
   z7FlaxLongT5PreTrainedModel.enable_gradient_checkpointingrngparamsr%   c                 C   s   t j|dd}t |}t |}t |}tj|\}}	||	d}
| j|
||||d }|d urUtt	|}tt	|}| j
D ]}|| ||< qBt | _
tt|S |S )Nr   rJ   )ry  r   ry  )r'   ri   rc   rs   randomsplitrs  initr   r	   Z_missing_keysr*   r   r   )r~   rx  rn  ry  r"   rT   decoder_input_idsdecoder_attention_maskZ
params_rngr   rngsZrandom_paramsZmissing_keyr,   r,   r-   init_weights  s.   




z&FlaxLongT5PreTrainedModel.init_weightsFr"   rT   r}  r~  r  r_  rO  trainr   c                 C   s   |d ur|n| j j}|d ur|n| j j}|d ur|n| j j}|d u r&td|d u r/t|}|d u r8t|}|
d ur@d|
ini }| jjd|	pJ| j	itj
|ddtj
|ddtj
|ddtj
|dd|||| |d
S )NzfMake sure to provide both `input_ids` and `decoder_input_ids`. `decoder_input_ids` is not passed here.r   ry  r   rJ   )	r"   rT   r}  r~  r  r_  rO  r   r  )r   r  r_  rO  rI  r'   rc   rs  applyry  rf   )r~   r"   rT   r}  r~  r  r_  rO  r  ry  r   r  r,   r,   r-   r     s2   

z"FlaxLongT5PreTrainedModel.__call__c                 C   sT   t j||fdd}t |}dd }| jjtjd|||d d|d}t|d S )	a+  
        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.
            encoder_outputs (`Union[FlaxBaseModelOutput, tuple(tuple(jnp.ndarray)]`):
                `encoder_outputs` consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*:
                `attentions`). `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*)
                is a sequence of hidden-states at the output of the last layer of the encoder. Used in the
                cross-attention of the decoder.
        r   rJ   c                 [      |   }|||fi |S N_get_decoder_modulers  r}  r~  r1  decoder_moduler,   r,   r-   _decoder_forward     z>FlaxLongT5PreTrainedModel.init_cache.<locals>._decoder_forwardr   T)r}  r~  rL  r   methodr   )	r'   rj   rc   rs  r|  rs   rz  r   r	   )r~   rk   r   encoder_outputsr}  r~  r  Zinit_variablesr,   r,   r-   r     s   

z$FlaxLongT5PreTrainedModel.init_cacheoutput_typeconfig_classc	                 C   s   |dur|n| j j}|dur|n| j j}|dur|n| j j}|du r't|}i }	|dur1||	d< dd }
| jjd|p=| jitj	|ddtj	|dd|||| |	|
d	S )	a  
        Returns:

        Example:

        ```python
        >>> from transformers import AutoTokenizer, FlaxLongT5ForConditionalGeneration

        >>> tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-base")
        >>> model = FlaxLongT5ForConditionalGeneration.from_pretrained("google/long-t5-local-base")

        >>> text = "My friends are cool but they eat too many carbs."
        >>> inputs = tokenizer(text, return_tensors="np")
        >>> encoder_outputs = model.encode(**inputs)
        ```Nr   c                 [   r  r  )_get_encoder_module)rs  r"   rT   r1  Zencode_moduler,   r,   r-   _encoder_forward;  s   z:FlaxLongT5PreTrainedModel.encode.<locals>._encoder_forwardry  r   rJ   )r"   rT   r  r_  rO  r   r  r  )
r   r  r_  rO  r'   rc   rs  r  ry  rf   )r~   r"   rT   r  r_  rO  r  ry  r   r  r  r,   r,   r-   encode  s*   
z FlaxLongT5PreTrainedModel.encoderM  past_key_valuesc                 C   sx  |dur|n| j j}|dur|n| j j}|dur|n| j j}|d }|du r6|jdd \}}t||f}|j\}}|du rFt||f}i }|durP||d< d|
pU| ji}|ra||d< dg}nd}dd	 }| jj	|tj
|d
dtj
|d
d|tj
|d
d||||	 |||d}|dur|r|\}}t|d |d< |S |dur|s|\}}|dd t|d f |dd  }|S )aG  
        Returns:

        Example:

        ```python
        >>> from transformers import AutoTokenizer, FlaxLongT5ForConditionalGeneration
        >>> import jax.numpy as jnp

        >>> tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-base")
        >>> model = FlaxLongT5ForConditionalGeneration.from_pretrained("google/long-t5-local-base")

        >>> text = "My friends are cool but they eat too many carbs."
        >>> inputs = tokenizer(text, return_tensors="np")
        >>> encoder_outputs = model.encode(**inputs)

        >>> decoder_start_token_id = model.config.decoder_start_token_id
        >>> decoder_input_ids = jnp.ones((inputs.input_ids.shape[0], 1), dtype="i4") * decoder_start_token_id

        >>> outputs = model.decode(decoder_input_ids, encoder_outputs)
        >>> logits = outputs.logits
        ```Nr   rU   r   ry  r   Fc                 [   r  r  r  r  r,   r,   r-   r    r  z:FlaxLongT5PreTrainedModel.decode.<locals>._decoder_forwardr   rJ   r}  r~  rL  rM  r  r_  rO  r   r  mutabler  r  r    )r   r  r_  rO  r7   r'   rj   ry  rs  r  rf   r	   )r~   r}  r  rM  r~  r  r  r_  rO  r  ry  r   rL  rk   sequence_lengthr  inputsr  r  r  pastr,   r,   r-   decodeK  sT   &
&z FlaxLongT5PreTrainedModel.decoder  	NNNNNNFNN)NNNNFNN)(r   r   r   r:  r!   r  Zbase_model_prefixrm  rt   Moduler   r'   r   r   r   rK   r   rr  rw  rs   rz  r   r   r  r   LONGT5_INPUTS_DOCSTRINGrb   r   dictr   r   r   LONGT5_ENCODE_INPUTS_DOCSTRINGr   r   r  LONGT5_DECODE_INPUTS_DOCSTRINGr   r  __classcell__r,   r,   rt  r-   rl    s   
  	
1$
	8
	
rl  a
  
    The LongT5 model was proposed in [LongT5: Efficient Text-To-Text Transformer for Long
    Sequences](https://arxiv.org/abs/2112.07916) by Mandy Guo, Joshua Ainslie, David Uthus, Santiago Ontanon, Jianmo
    Ni, Yun-Hsuan Sung and Yinfei Yang. It's an encoder-decoder transformer pre-trained in a text-to-text denoising
    generative setting. LongT5 model is an extension of T5 model, and it enables using one of the two different
    efficient attention mechanisms - (1) Local attention, or (2) Transient-Global attention.

    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 ([`LongT5Config`]): 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`].
z_The bare LONGT5 Model transformer outputting raw hidden-stateswithout any specific head on top.c                   @   l   e Zd ZU eed< ejZejed< dZe	ed< dd Z
dd Zd	d
 Z									dde	fddZdS )FlaxLongT5Moduler   rK   FrR  c                 C      | j S r  encoderr}   r,   r,   r-   r       z$FlaxLongT5Module._get_encoder_modulec                 C   r  r  decoderr}   r,   r,   r-   r    r  z$FlaxLongT5Module._get_decoder_modulec                 C   s   t j| jj| jjtj j| jjd | j	d| _
t| j}d|_t|| j
| j	| jd| _t| j}d|_| jj|_t|| j
| j	| jd| _d S )Nr`   r   F)rh  rK   rR  T)rt   r   r   
vocab_sizer   rs   r   r   r   rK   sharedcopydeepcopyr   rg  rR  r  num_decoder_layersr]  r  r~   Zencoder_configZdecoder_configr,   r,   r-   r     s.   
zFlaxLongT5Module.setupNTr   c
              
   C   s|   |d ur|n| j j}| j||||||	d}| j|||d |||||	d}
|s*|
| S t|
j|
j|
j|
j|
j	|j|j|jdS )Nr"   rT   r  r_  rO  r   r   r"   rT   rL  rM  r  r_  rO  r   )rb  r  decoder_hidden_statesdecoder_attentionsrd  encoder_last_hidden_staterL  encoder_attentions)
r   use_return_dictr  r  r   rb  r  rr   rc  rd  )r~   r"   rT   r}  r~  r  r  r_  rO  r   decoder_outputsr,   r,   r-   r     s>   
zFlaxLongT5Module.__call__	NNNNNNNNTr   r   r   r!   r   r'   r   rK   rR  r   r  r  r   r   r,   r,   r,   r-   r    s&   
 
r  c                   @   s   e Zd ZeZdS )FlaxLongT5ModelN)r   r   r   r  rm  r,   r,   r,   r-   r  ;  s    r  a  
    Returns:

    Example:

    ```python
    >>> from transformers import AutoTokenizer, FlaxLongT5Model

    >>> tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-base")
    >>> model = FlaxLongT5Model.from_pretrained("google/long-t5-local-base")

    >>> input_ids = tokenizer(
    ...     "Studies have been shown that owning a dog is good for you", return_tensors="np"
    ... ).input_ids
    >>> decoder_input_ids = tokenizer("Studies show that", return_tensors="np").input_ids

    >>> # forward pass
    >>> outputs = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids)
    >>> last_hidden_states = outputs.last_hidden_state
    ```
r  z4LONGT5 Model with a `language modeling` head on top.c                   @   r  )(FlaxLongT5ForConditionalGenerationModuler   rK   FrR  c                 C   r  r  r  r}   r,   r,   r-   r  c  r  z<FlaxLongT5ForConditionalGenerationModule._get_encoder_modulec                 C   r  r  r  r}   r,   r,   r-   r  f  r  z<FlaxLongT5ForConditionalGenerationModule._get_decoder_modulec                 C   s   | j j| _tj| j j| j jtjj| j j	| j
d| _t| j }d|_d|_d|_t|| j| j
| jd| _t| j }d|_d|_| j j|_t|| j| j
| jd| _tj| j jdtjj| j j	| j
d| _d S )Nr   Fri  Tr   )r   r   	model_dimrt   r   r  rs   r   r   r   rK   r  r  r  r   r  Zis_encoder_decoderrg  rR  r  r  r]  r  r   lm_headr  r,   r,   r-   r   i  s6   

z.FlaxLongT5ForConditionalGenerationModule.setupNTr   c
              
   C   s   |d ur|n| j j}| j||||||	d}|d }
| j|||
|||||	d}|d }| j jr5|| jd  }| j jrN| jjd d }| j	dd|j
ii|}n| |}|s`|f|dd   | S t||j|j|j|j|j|j|jd	S )
Nr  r   r  r   ry  	embeddingkernelr    )logitsr  r  r  rd  r  rL  r  )r   r  r  r  tie_word_embeddingsr  r  r   r  r  Tr   r  rr   rc  rd  rb  )r~   r"   rT   r}  r~  r  r  r_  rO  r   rr   r  sequence_outputshared_embedding	lm_logitsr,   r,   r-   r     sN   	
z1FlaxLongT5ForConditionalGenerationModule.__call__r  r  r,   r,   r,   r-   r  \  s&   
 #
r  c                   @   s   e Zd ZeZeeeee	d									dde
ej de
ej de
e de
e de
e d	e
e d
ede
e defddZ			dde
ej de
ej fddZdd ZdS )"FlaxLongT5ForConditionalGenerationr  NFrM  r~  r  r  r_  rO  r  ry  r   c                    s  |dur|n j j}|dur|n j j}|dur|n j j}|d }|du r6|jdd \}}t||f}|j\}}|du rFt||f}i }|durP||d< d|
pU ji}|ra||d< dg}nd} fdd	} jj	|tj
|d
dtj
|d
d|tj
|d
d||||	 |||d}|du r|\}}n|\\}}}|rt||j|j|jd}n	|f|dd  }|dur|rt|d |d< |S |dur|s|dd t|d f |dd  }|S )aR  
        Returns:

        Example:

        ```python
        >>> from transformers import AutoTokenizer, FlaxLongT5ForConditionalGeneration
        >>> import jax.numpy as jnp

        >>> tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-base")
        >>> model = FlaxLongT5ForConditionalGeneration.from_pretrained("google/long-t5-local-base")

        >>> text = "summarize: My friends are cool but they eat too many carbs."
        >>> inputs = tokenizer(text, return_tensors="np")
        >>> encoder_outputs = model.encode(**inputs)

        >>> decoder_start_token_id = model.config.decoder_start_token_id
        >>> decoder_input_ids = jnp.ones((inputs.input_ids.shape[0], 1), dtype="i4") * decoder_start_token_id

        >>> outputs = model.decode(decoder_input_ids, encoder_outputs)
        >>> logits = outputs.logits
        ```Nr   rU   r   ry  r   Fc           	         s   |   }|||fi |}|d } jjr| jjd  } jjr9| jjd d }| jdd|jii|}||fS | |}||fS )Nr   r   ry  r  r  )	r  r   r  r   r  r   r  r  r  )	rs  r}  r~  r1  r  r  r  r  r  r}   r,   r-   r  	  s    
zCFlaxLongT5ForConditionalGeneration.decode.<locals>._decoder_forwardr   rJ   r  )r  rr   rc  rd  r    r  )r   r  r_  rO  r7   r'   rj   ry  rs  r  rf   r   rr   rc  rd  r	   )r~   r}  r  rM  r~  r  r  r_  rO  r  ry  r   rL  rk   r  r  r  r  r  r  r  r  r  r,   r}   r-   r    sf   &

&z)FlaxLongT5ForConditionalGeneration.decoderT   c                 K   sP   |j \}}| |||}	tj||fdd}
|d ur!tj|
|d}
|	|||
dS )Nr   rJ   r3   )r  r  rM  r~  )r7   r   r'   rj   rs   r   r   )r~   r}  r   rT   r~  r  r1  rk   r   r  Zextended_attention_maskr,   r,   r-   prepare_inputs_for_generationR	  s   

z@FlaxLongT5ForConditionalGeneration.prepare_inputs_for_generationc                 C   s   |j |d< |S )Nr  )r  )r~   Zmodel_outputsZmodel_kwargsr,   r,   r-   update_inputs_for_generationo	  s   
z?FlaxLongT5ForConditionalGeneration.update_inputs_for_generationr  )NNN)r   r   r   r  rm  r   r  r   r   r!   r   r'   rb   r  r   r   r  rs   ZArrayr  r  r,   r,   r,   r-   r    sT    
	
 
r  a  
    Returns:

    Example:

    ```python
    >>> from transformers import AutoTokenizer, FlaxLongT5ForConditionalGeneration

    >>> tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-base")
    >>> model = FlaxLongT5ForConditionalGeneration.from_pretrained("google/long-t5-local-base")

    >>> ARTICLE_TO_SUMMARIZE = "summarize: My friends are cool but they eat too many carbs."
    >>> inputs = tokenizer([ARTICLE_TO_SUMMARIZE], return_tensors="np")

    >>> # Generate Summary
    >>> summary_ids = model.generate(inputs["input_ids"]).sequences
    >>> print(tokenizer.decode(summary_ids[0], skip_special_tokens=True, clean_up_tokenization_spaces=False))
    ```
)r  r  rl  r   )`r:  r  typingr   r   r   r   r   Z
flax.linenZlinenrt   rs   Z	jax.numpynumpyr'   ra   Zflax.core.frozen_dictr   r   r	   r
   r   r   Znn_partitioningZflax.linen.attentionr   Zflax.traverse_utilr   r   Z
jax.randomr   Zmodeling_flax_outputsr   r   r   r   r   Zmodeling_flax_utilsr   r   r   r   r   utilsr   r   r   r   Zconfiguration_longt5r!   Z
get_loggerr   loggerZ_CHECKPOINT_FOR_DOCZ_CONFIG_FOR_DOCr\  rb   r   r.   r:   r=   rI   rO   rS   rX   rn   rq   rv   r  rw   r   r   r   r   r  r%  r+  r<  r>  rC  rE  rP  rQ  rg  r  r  r  rl  ZLONGT5_START_DOCSTRINGr  r  ZFLAX_LONGT5_MODEL_DOCSTRINGr  r  Z,FLAX_LONGT5_CONDITIONAL_GENERATION_DOCSTRING__all__r,   r,   r,   r-   <module>   s   
$	$$* 	 '   T  "&')#V$WG*<  4)Zn )