U
    ,-e                     @   s  d Z ddlZddlZddlZddlmZmZmZmZm	Z	 ddl
Z
ddl
mZ ddlmZ ddlmZ ddlmZ dd	lmZmZmZmZ dd
lmZ ddlmZmZmZ ddlmZmZm Z m!Z!m"Z"m#Z#m$Z$ ddl%m&Z& e#'e(Z)dZ*dZ+ddddgZ,dZe
j-e.e.e.e
j-dddZ/e
j-e.e.e
j-dddZ0d[e
j-e.e.e.e
j-dddZ1e.e
j-dddZ2e
j-e.e
j-d d!d"Z3e
j-e.e
j4e
j-d#d$d%Z5e
j-e.ee
j-e
j-f d&d'd(Z6e
j-e.e
j-d&d)d*Z7e
j-e
j-e.e
j-d+d,d-Z8G d.d/ d/ej9Z:zdd0l;m<Z< e<Z:e)=d1 W n4 e>k
r   Y n  e?k
r<   e)@d2 Y nX eAe: G d3d4 d4ej9ZBG d5d6 d6ej9ZCG d7d8 d8ej9ZDG d9d: d:ej9ZEG d;d< d<ej9ZFG d=d> d>ej9ZGG d?d@ d@ej9ZHG dAdB dBej9ZIG dCdD dDej9ZJG dEdF dFej9ZKG dGdH dHej9ZLG dIdJ dJeZMG dKdL dLeMZNdMZOdNZPdOZQdPZRe dQeOG dRdS dSeMZSe dTeOG dUdV dVeMZTe dWeOG dXdY dYeMZUdS )\z PyTorch LongT5 model.    N)AnyListOptionalTupleUnion)nn)CrossEntropyLoss)
checkpoint   )ACT2FN)BaseModelOutput)BaseModelOutputWithPastAndCrossAttentionsSeq2SeqLMOutputSeq2SeqModelOutput)PreTrainedModel)ALL_LAYERNORM_LAYERS find_pruneable_heads_and_indicesprune_linear_layer)DUMMY_INPUTS
DUMMY_MASKadd_start_docstrings%add_start_docstrings_to_model_forwardis_torch_fx_proxyloggingreplace_return_docstrings   )LongT5Configr   zgoogle/long-t5-local-basezgoogle/long-t5-local-largezgoogle/long-t5-tglobal-basezgoogle/long-t5-tglobal-large)x	block_lendim	pad_valuereturnc                 C   s   | j |  | }t| j sDt| j }||  |7  < tj|| jdS dg| j }d|f||< t|ddd d}tj	j
| |d|d} | S )	zHPad a tensor so that a sequence length will be a multiple of `block_len`dtyper   r   r   N constantpadmodevalue)shapealllisttorchzerosr#   ndimsumr   
functionalr)   )r   r   r   r    Zpad_lenZ	new_shaper)   r&   r&   k/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/transformers/models/longt5/modeling_longt5.py_pad_to_multiple?   s    

r5   )r   r   r   r!   c                 C   s~   | j | | dkr"t| ||dd} | j | | }| j d| ||f | j |d d  }d|krttj|| j| jdS | |S )zSplit an input tensor into blocks of a given `block_len` along the given `dim`. If the dimension length
    is not a multiple of `block_len`, it will be padded first with selected `pad_value`.
    r   )r    Nr   r#   device)r,   r5   r/   emptyr#   r7   reshape)r   r   r   
num_blocksZoutput_shaper&   r&   r4   _split_into_blocksO   s    (r;   )r   	block_dimsequence_dimr    r!   c           	      C   s   | j | }dg| j }d||< t|ddd d}tjj| |d|d} g }tdD ]>}td	dg| j }t||| ||< t|}|	| |  qRt
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.
    r$   )r   r   Nr%   r&   r'   r(   r
   r   r   )r,   r1   r2   r   r3   r)   rangeslicetupleappendr/   cat)	r   r<   r=   r    r:   r)   Zblocks_listiindicesr&   r&   r4   _concatenate_3_blocks^   s    
rF   )r   r!   c                 C   s:   t jd|  t jd}|| |   }|d|d }|S )z:Makes 3-blocked relative position ids for local attention.r
   r"   r   r   )r/   arangeZint32	unsqueeze)r   Zposition_idsZcenter_position_idsrelative_position_idsr&   r&   r4   "_make_3block_relative_position_idsw   s    rJ   )local_attention_maskr   r!   c                 C   sF   t |}t||k }|ddddddf }|| j}t| |S )znMask local attention mask to enforce that tokens are not allowed to attend tokens farther than ``local_radius.N)rJ   r/   abstor7   logical_and)rK   r   rI   Zlocality_maskr&   r&   r4   _mask_local_attention_mask   s
    rO   )attention_maskr   r7   r!   c                 C   sV   t | |dd}t|ddd}|d}|d}t||}t||}|d|S )z;Prepare attention mask to be applied for a local attention.r   r>      r<   r=   r%   )r;   rF   rH   r/   rN   rO   rM   )rP   r   r7   Z_blocked_attention_maskZ_3blocked_attention_maskrK   r&   r&   r4   _get_local_attention_mask   s    


rT   )rP   global_block_sizer!   c                    s\  | j dd \}tjtjd fdd}tj| | jd  }tj|dd| }t| d	kd
d| j}t	|| d
 | j}tj
d|j|jd}t||k||}||  | d  }||}  }|dkrtj|ddj|ddd}	ntj|d|j|jd}	tjt||ddd }
|
| j}
t|
|	kdd}
|tj|
tjfS )a  Obtain the "fixed block" global id corresponding to each input token.

    This implementation is a simlified 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.
    NrQ   )	block_idsr!   c                    sd   t    d k}|| j}t || dk}|dd| jd }t 	| |k | |} | S )Nr   r   r%   )
r/   rG   rM   r7   rN   r2   rH   typer#   where)rV   Z
block_endsZtrue_block_endsZfull_blocksrU   Zseq_lenr&   r4   handle_orphan_tokens   s    z:_make_global_fixed_block_ids.<locals>.handle_orphan_tokensr7   r   )Zaxis              ?g     @r%   r6   r   r>   )r,   r/   TensorZ	ones_liker7   ZcumsumrX   rW   r#   floortensormaxvaluesrepeat	transposer0   onesrM   int)rP   rU   
batch_sizerZ   Zfixed_block_maskmaskZglobal_block_idsZ_global_block_ids_lower_boundZnum_globalsZ_sequence_block_ids_maxglobal_segment_idsr&   rY   r4   _make_global_fixed_block_ids   s6      "   rj   c                 C   s@   t | |\}}|jd }tj||jd}||d  }|tjS )zBCreate the relative position tensor for local -> global attention.r%   r[   .N)rj   r,   r/   rG   r7   rW   int64)rP   rU   rV   ri   global_seq_lenZglobal_positionsside_relative_positionr&   r&   r4    _make_side_relative_position_ids   s
    
ro   )hidden_statesrV   rm   r!   c                 C   sf   | |dktj||j|jd}tj|tj	|d ddddddf }t
d| || jS )zFCompute individual block aggregates by summing over individual blocks.r   r6   r   Nr%   z...nd,...ng->...gd)rX   r/   r`   r#   r7   r   r3   Zone_hotrW   rl   einsum)rp   rV   rm   Zone_hot_block_idsr&   r&   r4   _create_global_aggregates   s     0rr   c                       s&   e Zd Zd fdd	Zdd Z  ZS )LongT5LayerNormư>c                    s&   t    tt|| _|| _dS )zg
        Construct a layernorm module in the LongT5 style. No bias and no subtraction of mean.
        N)super__init__r   	Parameterr/   re   weightvariance_epsilon)selfZhidden_sizeeps	__class__r&   r4   rv      s    
zLongT5LayerNorm.__init__c                 C   s\   | tjdjddd}|t|| j  }| jjtj	tj
fkrR| | jj}| j| S )NrQ   r%   T)Zkeepdim)rM   r/   Zfloat32powmeanZrsqrtry   rx   r#   float16Zbfloat16)rz   rp   Zvariancer&   r&   r4   forward   s
    zLongT5LayerNorm.forward)rt   __name__
__module____qualname__rv   r   __classcell__r&   r&   r|   r4   rs      s   rs   )FusedRMSNormzSDiscovered apex.normalization.FusedRMSNorm - will use it instead of LongT5LayerNormzFdiscovered apex but it failed to load, falling back to LongT5LayerNormc                       s*   e Zd Zed fddZdd Z  ZS )LongT5DenseActDenseconfigc                    sT   t    tj|j|jdd| _tj|j|jdd| _t|j	| _
t|j | _d S NFbias)ru   rv   r   Lineard_modeld_ffwiwoDropoutdropout_ratedropoutr   dense_act_fnactrz   r   r|   r&   r4   rv     s
    
zLongT5DenseActDense.__init__c                 C   sl   |  |}| |}| |}t| jjtjr^|j| jjjkr^| jjjtj	kr^|
| jjj}| |}|S N)r   r   r   
isinstancer   rx   r/   r^   r#   Zint8rM   )rz   rp   r&   r&   r4   r     s    



zLongT5DenseActDense.forwardr   r   r   r   rv   r   r   r&   r&   r|   r4   r   
  s   r   c                       s*   e Zd Zed fddZdd Z  ZS )LongT5DenseGatedActDenser   c                    sj   t    tj|j|jdd| _tj|j|jdd| _tj|j|jdd| _t	|j
| _t|j | _d S r   )ru   rv   r   r   r   r   wi_0wi_1r   r   r   r   r   r   r   r   r|   r&   r4   rv   !  s    
z!LongT5DenseGatedActDense.__init__c                 C   s:   |  | |}| |}|| }| |}| |}|S r   )r   r   r   r   r   )rz   rp   Zhidden_geluZhidden_linearr&   r&   r4   r   )  s    


z LongT5DenseGatedActDense.forwardr   r&   r&   r|   r4   r      s   r   c                       s*   e Zd Zed fddZdd Z  ZS )LongT5LayerFFr   c                    sJ   t    |jrt|| _n
t|| _t|j|jd| _	t
|j| _d S )Nr{   )ru   rv   Zis_gated_actr   DenseReluDenser   rs   r   layer_norm_epsilon
layer_normr   r   r   r   r   r|   r&   r4   rv   4  s    

zLongT5LayerFF.__init__c                 C   s&   |  |}| |}|| | }|S r   )r   r   r   )rz   rp   Zforwarded_statesr&   r&   r4   r   >  s    

zLongT5LayerFF.forwardr   r&   r&   r|   r4   r   3  s   
r   c                       sN   e Zd Zded fddZdd Zedd
dZdddZdddZ	  Z
S )LongT5AttentionFr   c                    s   t    |j| _|| _|j| _|j| _|j| _|j| _|j	| _
|j| _| j
| j | _tj| j| jdd| _tj| j| jdd| _tj| j| jdd| _tj| j| jdd| _| jrt| j| j
| _t | _d| _d S r   )ru   rv   
is_decoderhas_relative_attention_biasrelative_attention_num_bucketsrelative_attention_max_distancer   d_kvkey_value_proj_dim	num_headsn_headsr   r   	inner_dimr   r   qkvo	Embeddingrelative_attention_biassetpruned_headsgradient_checkpointingrz   r   r   r|   r&   r4   rv   G  s$    
zLongT5Attention.__init__c                 C   s   t |dkrd S t|| j| j| j\}}t| j|| _t| j|| _t| j|| _t| j	|dd| _	| jt | | _| j| j | _
| j|| _d S Nr   r   r>   lenr   r   r   r   r   r   r   r   r   r   unionrz   headsindexr&   r&   r4   prune_heads^  s       zLongT5Attention.prune_headsT       c                 C   s   d}|r4|d }|| dk tj| 7 }t| } nt| t|  } |d }| |k }|t|  | t||  ||   tj }t|t	||d }|t
|| |7 }|S a  
        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

        Args:
            relative_position: an int32 Tensor
            bidirectional: a boolean - whether the attention is bidirectional
            num_buckets: an integer
            max_distance: an integer

        Returns:
            a Tensor with the same shape as relative_position, containing int32 values in the range [0, num_buckets)
        r   rQ   r   rM   r/   longrL   minZ
zeros_likelogfloatmathZ	full_likerX   relative_positionbidirectionalnum_bucketsmax_distanceZrelative_bucketsZ	max_exactZis_smallZrelative_position_if_larger&   r&   r4   _relative_position_bucketn  s.     z)LongT5Attention._relative_position_bucketNc           	      C   s   |dkr| j jj}tj|tj|ddddf }tj|tj|ddddf }|| }| j|| j | j| j	d}|  |}|
dddgd}|S )%Compute binned relative position biasNr6   r   r   r   rQ   r   r   )r   rx   r7   r/   rG   r   r   r   r   r   permuterH   )	rz   query_length
key_lengthr7   context_positionmemory_positionr   relative_position_bucketrb   r&   r&   r4   compute_bias  s    

zLongT5Attention.compute_biasc
                    s~  |j dd \ }
|
}|dk	r\t|dkr>tdt| d||dkrV|d j d n|7 }|dkrh|n|j d } fdd fd	d
}fdd}|}||j||dk	r|d nd}||j||dk	r|d nd}t||dd}|dkrj	sDtj
dj||f|j|jd}jrVjrVd|_nj|||jd}|dk	r|dddd|d dddf }|dk	r|| }jrt|j d }d|tj< |dd| f }n|}||7 }tjj| dd|}tjj|jjd}|dk	r$|| }|t||}|}jrT|rT||fnd}|f|f |f }|	rz||f }|S )z
        Self-attention (if key_value_states is None) or attention over source sentence (provided by key_value_states).
        NrQ   z?past_key_value should have 2 past states: keys and values. Got z past statesr   r   c                    s   |   djjddS )
projectionr%   r   rQ   )viewr   r   rd   Zstatesrg   rz   r&   r4   r,     s    z&LongT5Attention.forward.<locals>.shapec                    s   |  dd  djS )r9   r   rQ   r%   )rd   
contiguousr   r   r   r   r&   r4   unshape  s    z(LongT5Attention.forward.<locals>.unshapec                    sx   |dkr || } n|dkr* ||} |dk	rt|dkrNt j|| gdd} n&|jd |jd krp ||} n|} | S )z4projects hidden states correctly to key/query statesNrQ   r>   r   )r/   rC   r,   )rp   Z
proj_layerkey_value_statespast_key_value)r,   r&   r4   project  s    z(LongT5Attention.forward.<locals>.projectr
   r7   r#   Tr[   r%   r>   ptraining)r,   r   
ValueErrorr   r   r   r/   matmulrd   r   r0   r   r7   r#   r   r   requires_gradr   sizer   re   r.   boolr   r3   softmaxr   type_asr   r   r   )rz   rp   rh   r   position_biasr   layer_head_maskr   	use_cacheoutput_attentions
seq_lengthZreal_seq_lengthr   r   r   query_states
key_statesvalue_statesscoresZposition_bias_maskedattn_weightsattn_outputpresent_key_value_stateoutputsr&   )rg   rz   r,   r4   r     s           

  
(
  


zLongT5Attention.forward)F)Tr   r   )N)NNNNNNFF)r   r   r   r   rv   r   staticmethodr   r   r   r   r&   r&   r|   r4   r   F  s   /
        r   c                       sV   e Zd Zdeedd fddZdd ZedddZe	dddZ
dddZ  ZS )LongT5LocalAttentionFNr   r   r!   c                    s   t    |j| _|| _|j| _|j| _|j| _|j| _|j	| _
|j| _| jd | _|j| _| j
| j | _tj| j| jdd| _tj| j| jdd| _tj| j| jdd| _tj| j| jdd| _| jrt| j| j
| _t | _d| _d S )Nr   Fr   )ru   rv   r   r   r   r   r   r   r   r   r   local_radiusr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r|   r&   r4   rv   2  s(    
zLongT5LocalAttention.__init__c                 C   s   t |dkrd S t|| j| j| j\}}t| j|| _t| j|| _t| j|| _t| j	|dd| _	| jt | | _| j| j | _
| j|| _d S r   r   r   r&   r&   r4   r   L  s       z LongT5LocalAttention.prune_headsTr   r   c                 C   s   d}|r4|d }|| dk tj| 7 }t| } nt| t|  } |d }| |k }|t|  | t||  ||   tj }t|t	||d }|t
|| |7 }|S r   r   r   r&   r&   r4   r   \  s.     z.LongT5LocalAttention._relative_position_bucketblock_lengthc                 C   s   | j jjjdkr| j jjnd}tjd| tj|d}|||  }|dddf |dddf  }| j|| j | j	| j
d}|  |}|dddgdd}|S 	r   metaNr
   r6   r   rQ   r   r   r   rx   r7   rW   r/   rG   r   r   r   r   r   r   rH   rz   r   Ztarget_devicer   r   r   r   rb   r&   r&   r4   r     s      
z!LongT5LocalAttention.compute_biasc                    s  |j d d \ } fdd} fdd}||}	||}
||}t|	jdd}	t|
jdd}
t|jdd}t|
ddd}
t|ddd}td	|	|
}|d kr6j	stj
ddjjd
j f|j|jd}jrjrd|_nj}|d k	r6t|dkdd}||dd }||7 }tjj| dd|}tjj|jjd}|d k	r|| }||j}|td||}|d d d |d d f }|}d }|f|f |f }|r||f }|S )NrQ   c                    s   |   djjS r   r%   r   r   r   r   r   r&   r4   r,     s    z+LongT5LocalAttention.forward.<locals>.shapec                    s   |    djS r9   r%   r   r   r   r   r   r&   r4   r     s    z-LongT5LocalAttention.forward.<locals>.unshaper   r>   rR   ...qhd,...khd->...hqkr
   r   Tr   r\       _r%   r   ...hqk,...khd->...qhd)r,   r   r   r   r;   r   rF   r/   rq   r   r0   r   r7   r#   r   r   r   r   rX   rd   r   r3   r   r   r   r   rW   r   )rz   rp   rh   r   r   r   r   r,   r   r   r   r   r   r   r   r   r   r&   r   r4   r     sV      
  



zLongT5LocalAttention.forward)F)Tr   r   )NNNF)r   r   r   r   r   rv   r   r   r   rf   r   r   r   r&   r&   r|   r4   r   1  s   /    r   c                       sn   e Zd Zdeedd fddZdd ZedddZe	dddZ
ejejejdddZdddZ  ZS )LongT5TransientGlobalAttentionFNr   c                    s   t    |j| _|| _|j| _|j| _|j| _|j| _|j	| _
|j| _| jd | _|j| _|j| _| j
| j | _tj| j| jdd| _tj| j| jdd| _tj| j| jdd| _tj| j| jdd| _| jrt| j| j
| _t | _d| _| jr
t| j| j
| _t|j|jd| _d S )Nr   Fr   r   ) ru   rv   r   r   r   r   r   r   r   r   r   r   r   rU   r   r   r   r   r   r   r   r   r   r   r   r   r   r   global_relative_attention_biasrs   r   global_input_layer_normr   r|   r&   r4   rv     s0    
z'LongT5TransientGlobalAttention.__init__c                 C   s   t |dkrd S t|| j| j| j\}}t| j|| _t| j|| _t| j|| _t| j	|dd| _	| jt | | _| j| j | _
| j|| _d S r   r   r   r&   r&   r4   r     s       z*LongT5TransientGlobalAttention.prune_headsTr   r   c                 C   s   d}|r4|d }|| dk tj| 7 }t| } nt| t|  } |d }| |k }|t|  | t||  ||   tj }t|t	||d }|t
|| |7 }|S r   r   r   r&   r&   r4   r   "  s.     z8LongT5TransientGlobalAttention._relative_position_bucketr   c                 C   s   | j jjjdkr| j jjnd}tjd| tj|d}|||  }|dddf |dddf  }| j|| j | j	| j
d}|  |}|dddgdd}|S r   r  r  r&   r&   r4   r   S  s      
z+LongT5TransientGlobalAttention.compute_bias)rh   ri   r!   c                 C   s   t |d |d d d d d f d d d df }t |dkdd}t|| j}| j|| j | j| jd}| 	|}|
dddd	g}|| }|S )
Nrk   .r   r\   r  r   r
   r   rQ   )r/   eqrX   ro   rU   r   r   r   r   r  r   )rz   rh   ri   Zside_attention_maskZattention_side_biasrn   Zside_relative_position_bucketZ	side_biasr&   r&   r4   compute_side_biask  s    0
z0LongT5TransientGlobalAttention.compute_side_biasc                    sH  |j d d \ } fdd} fdd}t|d k	r<|nt|j d d j\}	}
|
j d }t||	|}|}||}||}|	|}||}|	|}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< |d|}|d|}tj||gdd}tj||gdd}td
||}|d k	rt|j|j}t|dkdd}nd }|d krjs tjddjjdj f|j|jd}jrjrd|_nj}|d k	r&||dd }||j}|d krHt |}||
}t
|jdddd}||j |j}tj||gdd}||7 }t!j"j#|$ dd%|}t!j"j&|j&jd}|d k	r|| }||j}|td||}|d d d |d d f }'|}d }|f|f |f }|rD||f }|S )NrQ   c                    s   |   djjS r  r  r   r   r&   r4   r,     s    z5LongT5TransientGlobalAttention.forward.<locals>.shapec                    s   |    djS r  r  r   r   r&   r4   r     s    z7LongT5TransientGlobalAttention.forward.<locals>.unshaper%   r   r>   rR   r  r   r\   r  r
   r   TrS   r   r	  )(r,   rj   r/   re   rU   rr   r  r   r   r   r;   r   rF   r1   rH   rc   rC   rq   rT   r7   rX   r   r0   r   r#   r   r   r   r   rd   rW   r  rM   r   r3   r   r   r   r   r   )rz   rp   rh   r   r   r   r   r,   r   rV   ri   Z_global_seq_lenZglobal_inputsr   r   r   Zside_key_statesZside_value_statesZrepsr   rK   Zside_position_biasr   r   r   r   r&   r   r4   r     s    








z&LongT5TransientGlobalAttention.forward)F)Tr   r   )NNNF)r   r   r   r   r   rv   r   r   r   rf   r   r/   r^   r  r   r   r&   r&   r|   r4   r
    s    /    r
  c                       s(   e Zd Zd fdd	ZdddZ  ZS )	LongT5LayerSelfAttentionFc                    s<   t    t||d| _t|j|jd| _t	|j
| _d S Nr   r   )ru   rv   r   SelfAttentionrs   r   r   r   r   r   r   r   r   r|   r&   r4   rv     s    
z!LongT5LayerSelfAttention.__init__Nc              	   C   sJ   |  |}| j|||||||d}	|| |	d  }|f|	dd   }
|
S )N)rh   r   r   r   r   r   r   r   )r   r  r   )rz   rp   rP   r   r   r   r   r   normed_hidden_statesattention_outputr   r&   r&   r4   r     s    

	z LongT5LayerSelfAttention.forward)F)NNNNFFr   r&   r&   r|   r4   r    s   	      r  c                       s2   e Zd ZdZd	 fdd	Zd
edddZ  ZS )LongT5LayerLocalSelfAttentionz$Local self attention used in encoderFc                    s<   t    t||d| _t|j|jd| _t	|j
| _d S r  )ru   rv   r   LocalSelfAttentionrs   r   r   r   r   r   r   r   r   r|   r&   r4   rv     s    
z&LongT5LayerLocalSelfAttention.__init__Nkwargsc           
      K   sF   |  |}| j|||||d}|| |d  }|f|dd   }	|	S N)rh   r   r   r   r   r   )r   r  r   
rz   rp   rP   r   r   r   r  r  r  r   r&   r&   r4   r   #  s    	
z%LongT5LayerLocalSelfAttention.forward)F)NNNFr   r   r   __doc__rv   r   r   r   r&   r&   r|   r4   r    s   	    r  c                       s2   e Zd ZdZd	 fdd	Zd
edddZ  ZS )'LongT5LayerTransientGlobalSelfAttentionz/Transient-Global self attention used in encoderFc                    s<   t    t||d| _t|j|jd| _t	|j
| _d S r  )ru   rv   r
  TransientGlobalSelfAttentionrs   r   r   r   r   r   r   r   r   r|   r&   r4   rv   <  s    
 z0LongT5LayerTransientGlobalSelfAttention.__init__Nr  c           
      K   sF   |  |}| j|||||d}|| |d  }|f|dd   }	|	S r  )r   r  r   r  r&   r&   r4   r   D  s    	
z/LongT5LayerTransientGlobalSelfAttention.forward)F)NNNFr  r&   r&   r|   r4   r  9  s       r  c                       s&   e Zd Z fddZdddZ  ZS )LongT5LayerCrossAttentionc                    s<   t    t|dd| _t|j|jd| _t	|j
| _d S )NFr  r   )ru   rv   r   EncDecAttentionrs   r   r   r   r   r   r   r   r   r|   r&   r4   rv   \  s    
z"LongT5LayerCrossAttention.__init__NFc
                 C   sN   |  |}
| j|
||||||||	d	}|| |d  }|f|dd   }|S )N)rh   r   r   r   r   r   r   r   r   r   )r   r   r   )rz   rp   r   rP   r   r   r   r   r   r   r  r  Zlayer_outputr   r&   r&   r4   r   b  s    
z!LongT5LayerCrossAttention.forward)NNNNFNFr   r&   r&   r|   r4   r  [  s   
       r  c                       s(   e Zd Zd fdd	Zd	ddZ  ZS )
LongT5BlockFc                    s   t    |j| _|jrt}n2|jdkr.t}n"|jdkr>t}ntd|j dt	 | _
| j
|||d | jr| j
t| | j
t| d S )Nlocalztransient-globalzjFor encoder attention mechanism, either `local` or `transient-global` attention type is expected, but got .r  )ru   rv   r   r  encoder_attention_typer  r  r   r   
ModuleListlayerrB   r  r   )rz   r   r   Zattention_layerr|   r&   r4   rv     s     



zLongT5Block.__init__NTc                 C   s4  |	d k	rz| j std |d kr$dnd}t|	|kr`td| d|dkrJdnd dt|	 d	|	d d }|	dd  }nd
\}}| jd ||||||
|d}|d d \}}|dd  }|jtjkrt	|
 rt|jjd }tj|| |d}| j o|d k	}|r|d k	r(|d jd }nd }| jd ||||||||
|d	}|d }|jtjkrt	|
 rt|jjd }tj|| |d}|d k	r||d  }||dd   }| jd |}|jtjkrt	|
 rt|jjd }tj|| |d}|f}|
r(||f | }n|| }|S )NzN`past_key_values` is passed to the encoder. Please make sure this is intended.rQ      zThere should be z past states. z$2 (past / key) for cross attention.  zGot z past key / value states)NNr   )rP   r   r   r   r   r   i  )r   ra   r   )r   rP   r   r   r   r   r   r   r%   )r   loggerwarningr   r   r&  r#   r/   r   isinfanyZfinfora   clampr,   )rz   rp   rP   r   encoder_hidden_statesencoder_attention_maskencoder_decoder_position_biasr   cross_attn_layer_head_maskr   r   r   return_dictZexpected_num_past_key_valuesZself_attn_past_key_valueZcross_attn_past_key_valueZself_attention_outputsr   Zattention_outputsZclamp_valueZdo_cross_attentionr   Zcross_attention_outputsr   r&   r&   r4   r     sr    
&	

zLongT5Block.forward)F)NNNNNNNNFFTr   r&   r&   r|   r4   r!    s              r!  c                   @   sH   e Zd ZdZeZdZdZdgZe	dd Z
dd Zdd
dZdd ZdS )LongT5PreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    ZtransformerTr!  c                 C   s$   t t}t t}|||d}|S )N)decoder_input_ids	input_idsdecoder_attention_mask)r/   r`   r   r   )rz   r5  Z
input_maskdummy_inputsr&   r&   r4   r7    s    

z"LongT5PreTrainedModel.dummy_inputsc                 C   s  | j j}t|tr(|jj|d  nt|ttt	frT|j
jjjd|d d ntt|tr|jjjjd|| j jd  d t|jdr|jjdk	r|jjj  |jjjjd|| j jd  d t|jdr|jjdk	r|jjj  nt|tr|jjjjd|| j jd  d t|jdrD|jjdk	rD|jjj  |jjjjd|| j jd  d t|jdr|jjdk	r|jjj  |jjjjd|| j jd  d t|jdr|jjdk	r|jjj  nt|tttfr| j j}| j j}| j j}|jjjjd||| d  d |jjjjd||d  d |jjjjd||d  d |jjjjd||| d  d |j r|j!jjjd||d  d t|tr|j"jjjd||d  d dS )zInitialize the weightsr]   r\   )r   Zstd      r   N)#r   Zinitializer_factorr   rs   rx   dataZfill_LongT5ModelLongT5ForConditionalGenerationLongT5EncoderModelsharedZnormal_r   r   r   hasattrr   Zzero_r   r   r   r   r   r   r   r
  r   r   r   r   r   r   r   r   r  )rz   modulefactorr   r   r   r&   r&   r4   _init_weights  sJ    

       
 
z#LongT5PreTrainedModel._init_weightsFc                 C   s   t |ttfr||_d S r   )r   r   LongT5Stackr   )rz   r?  r+   r&   r&   r4   _set_gradient_checkpointing@  s    z1LongT5PreTrainedModel._set_gradient_checkpointingc                 C   s   | j j}| j j}|d kr tdt|rbt|jd d d |}tj||dd df gdd}n4|	|j}|dd df 
 |ddd f< ||d< |d krtd||d	k| |S )
Nzself.model.config.decoder_start_token_id has to be defined. In LongT5 it is usually set to the pad_token_id.See LongT5 docs for more information.r%   )r   .r>   r   ).r   z1self.model.config.pad_token_id has to be defined.)r   decoder_start_token_idpad_token_idr   r   r/   fullr,   rC   Z	new_zeroscloneZmasked_fill_)rz   r5  rE  rF  Zshifted_input_idsr&   r&   r4   _shift_rightE  s       z"LongT5PreTrainedModel._shift_rightN)F)r   r   r   r  r   config_classZbase_model_prefixZsupports_gradient_checkpointingZ_no_split_modulespropertyr7  rA  rC  rI  r&   r&   r&   r4   r3    s   

/
r3  c                       s8   e Zd Zd
 fdd	Zdd Zdd Zddd	Z  ZS )rB  Nc                    s   t    t j j| _|d k	r0|j| j_ j| _ j	| _	| j	d | _
t fddt jD | _t j jd| _t j| _|   d| _d S )Nr   c                    s    g | ]}t  t|d kdqS )r   r  )r!  r   ).0rD   r   r&   r4   
<listcomp>n  s     z(LongT5Stack.__init__.<locals>.<listcomp>r   F)ru   rv   r   r   
vocab_sizer   embed_tokensrx   r   r   r   r%  r?   
num_layersblockrs   r   final_layer_normr   r   r   	post_initr   )rz   r   rO  r|   r   r4   rv   b  s    
zLongT5Stack.__init__c                 C   s   | j S r   rO  rz   r&   r&   r4   get_input_embeddingsy  s    z LongT5Stack.get_input_embeddingsc                 C   s
   || _ d S r   rT  rz   Znew_embeddingsr&   r&   r4   set_input_embeddings}  s    z LongT5Stack.set_input_embeddingsc           '         sJ  d k	rn| j j d k	r  n| j j |d k	r4|n| j j}|d k	rH|n| j j}|d k	r|d k	r| jrjdnd}td| d| dn`|d k	r| }|d|d }n>|d k	r| d d }n$| jrdnd}td| d| d	|d kr| j	d k	st
d
| 	|}|\}}|d k	r6|d d jd | n|}dkr\| js\t
d|  d|d krxtj|||jd}|d krd gt| j }| jr| |||j}n$| j jdkrt|| j|j}n|}| jr|d k	r| \}}}||f}|d krtj||jd}| |}nd }| jrF| jrFrFtd d| || j j}| || j j}rpdnd }|r~dnd } rdnd } r| jrdnd }d }d }| |}tt| j|D ]&\}\} }!|| }"|| }#|r||f }| jr4| jr4 fdd}$t|$| |||||||"|#d 
}%n| |||||||"|#|! d}%dkrx|%d d d |%dd   }%|%d d \}}&|%d }| jr|d k	r|% rdnd }r||&f } r||%d f }| jr||%d f }q|  |}| |}|r||f }|s8t!dd |||||fD S t"|||||dS ) NZdecoder_r(  zYou cannot specify both zinput_ids and zinputs_embeds at the same timer%   zYou have to specify either zinput_ids or inputs_embedsz<You have to initialize the model with valid token embeddingsr   rQ   Tz)`use_cache` can only be set to `True` if z is used as a decoderr[   r"  zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fr&   c                    s    fdd}|S )Nc                     s   t  | f S r   )rA   )inputs)r?  r   r   r&   r4   custom_forward  s    zJLongT5Stack.forward.<locals>.create_custom_forward.<locals>.custom_forwardr&   )r?  r[  r   r   )r?  r4   create_custom_forward  s    z2LongT5Stack.forward.<locals>.create_custom_forward)
rP   r   r.  r/  r0  r   r1  r   r   r   r   r   r'  r
      c                 s   s   | ]}|d k	r|V  qd S r   r&   )rL  r   r&   r&   r4   	<genexpr>)  s   z&LongT5Stack.forward.<locals>.<genexpr>)last_hidden_statepast_key_valuesrp   
attentionscross_attentions)#r   r   r   output_hidden_statesuse_return_dictr   r   r   r   rO  AssertionErrorr,   r/   re   r7   r   rQ  Zget_extended_attention_maskr$  rT   r   Zinvert_attention_maskr   r   r)  Zwarning_onceZget_head_maskrP  r   	enumeratezipr	   rR  rA   r   )'rz   r5  rP   r.  r/  rY  	head_maskcross_attn_head_maskra  r   r   rd  r2  Zerr_msg_prefixZinput_shaperg   r   Zmask_seq_lengthZextended_attention_maskZencoder_batch_sizeZencoder_sequence_length_Zencoder_hidden_shapeZencoder_extended_attention_maskZpresent_key_value_statesZall_hidden_statesZall_attentionsZall_cross_attentionsr   r0  rp   rD   Zlayer_moduler   r   r1  r]  Zlayer_outputsr   r&   r\  r4   r     s    

$


  







zLongT5Stack.forward)N)NNNNNNNNNNNN)r   r   r   rv   rV  rX  r   r   r&   r&   r|   r4   rB  a  s                rB  aQ  

    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 [`PreTrainedModel`]. 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 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    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 [`~PreTrainedModel.from_pretrained`] method to load the model weights.
a  
    Args:
        input_ids (`torch.LongTensor` 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 (`torch.FloatTensor` 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 (`torch.LongTensor` 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 (`torch.BoolTensor` 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.
        head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
            Mask to nullify selected heads of the self-attention modules in the encoder. Mask values selected in `[0,
            1]`:

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.

        decoder_head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
            Mask to nullify selected heads of the self-attention modules in the decoder. Mask values selected in `[0,
            1]`:

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.

        cross_attn_head_mask (`torch.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
                Mask to nullify selected heads of the cross-attention modules in the decoder. Mask values selected in
                `[0, 1]`:

                - 1 indicates the head is **not masked**,
                - 0 indicates the head is **masked**.

        encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *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(torch.FloatTensor))` 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)`.
        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.
        decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded
            representation. If `past_key_values` is used, optionally only the last `decoder_inputs_embeds` have to be
            input (see `past_key_values`). This is useful if you want more control over how to convert
            `decoder_input_ids` indices into associated vectors than the model's internal embedding lookup matrix.

            If `decoder_input_ids` and `decoder_inputs_embeds` are both unset, `decoder_inputs_embeds` takes the value
            of `inputs_embeds`.

        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`).

        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 (`torch.LongTensor` 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 (`torch.FloatTensor` 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)
        head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
            Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.

        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        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_  
The input argument `head_mask` was split into two arguments `head_mask` and `decoder_head_mask`. Currently,
`decoder_head_mask` is set to copy `head_mask`, but this feature is deprecated and will be removed in future versions.
If you do not want to use any `decoder_head_mask` now, please set `decoder_head_mask = torch.ones(num_layers,
num_heads)`.
z`The bare LONGT5 Model transformer outputting raw hidden-states without any specific head on top.c                       s
  e Zd ZdgZddgZed fddZdd Zd	d
 Zdd Z	dd Z
dd Zeeeeeddeej eej eej eej eej eej eej eeeej   eeeej   eej eej ee ee ee ee eeej ef dddZ  ZS )r:  Fdecoder.block.0.layer.1.EncDecAttention.relative_attention_bias.weightencoder.embed_tokens.weightdecoder.embed_tokens.weightr   c                    s   t  | t|j|j| _t|}d|_	d|_
d|_t|| j| _t|}d|_	d|_|j|_t|| j| _|   d S )NFT)ru   rv   r   r   rN  r   r=  copydeepcopyr   r   is_encoder_decoderrB  encodernum_decoder_layersrP  decoderrS  rz   r   encoder_configZdecoder_configr|   r&   r4   rv     s    

zLongT5Model.__init__c                 C   s   | j S r   r=  rU  r&   r&   r4   rV    s    z LongT5Model.get_input_embeddingsc                 C   s"   || _ | j| | j| d S r   r=  rr  rX  rt  rW  r&   r&   r4   rX    s    z LongT5Model.set_input_embeddingsc                 C   s   | j S r   rr  rU  r&   r&   r4   get_encoder  s    zLongT5Model.get_encoderc                 C   s   | j S r   rt  rU  r&   r&   r4   get_decoder	  s    zLongT5Model.get_decoderc                 C   s*   |  D ]\}}| jj| j| qdS z
        Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
        class PreTrainedModel
        Nitemsrr  r&  Z	attentionr   rz   Zheads_to_pruner&  r   r&   r&   r4   _prune_heads  s    zLongT5Model._prune_headsoutput_typerJ  N)r5  rP   r4  r6  ri  decoder_head_maskrj  encoder_outputsra  rY  decoder_inputs_embedsr   r   rd  r2  r!   c                 C   s   |dk	r|n| j j}|dk	r |n| j j}|dk	rX|dkrX| j j| j jkrXttt |}|dkrz| j	|||
||||d}nH|rt
|tst|d t|dkr|d ndt|dkr|d ndd}|d }| j||||	||||||||d}|s|| S t|j|j|j|j|j|j|j|jdS )	a%  
        Returns:

        Example:

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

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

        >>> # Let's try a very long encoder input.
        >>> input_ids = tokenizer(
        ...     100 * "Studies have been shown that owning a dog is good for you", return_tensors="pt"
        ... ).input_ids  # Batch size 1

        >>> decoder_input_ids = tokenizer("Studies show that", return_tensors="pt").input_ids  # Batch size 1

        >>> # forward pass
        >>> outputs = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids)
        >>> last_hidden_states = outputs.last_hidden_state
        ```Nr5  rP   rY  ri  r   rd  r2  r   r   rQ   r`  rp   rb  r5  rP   rY  ra  r.  r/  ri  rj  r   r   rd  r2  )r`  ra  decoder_hidden_statesdecoder_attentionsrc  encoder_last_hidden_stater.  encoder_attentions)r   r   re  rP  rs  warningswarnZ#_LongT5Model__HEAD_MASK_WARNING_MSGFutureWarningrr  r   r   r   rt  r   r`  ra  rp   rb  rc  )rz   r5  rP   r4  r6  ri  r  rj  r  ra  rY  r  r   r   rd  r2  rp   decoder_outputsr&   r&   r4   r     sb    *	zLongT5Model.forward)NNNNNNNNNNNNNNN)r   r   r   "_keys_to_ignore_on_load_unexpected_tied_weights_keysr   rv   rV  rX  rz  r|  r  r   LONGT5_INPUTS_DOCSTRINGr   r   _CONFIG_FOR_DOCr   r/   
LongTensorFloatTensor
BoolTensorr^   r   r   r   r   r   r&   r&   r|   r4   r:    sX   
               r:  z4LONGT5 Model with a `language modeling` head on top.c                       s>  e Zd ZdgZdddgZed fddZdd	 Zd
d Zdd Z	dd Z
dd Zdd Zeeeeedd eej eej eej eej eej eej eej eeeej   eeeej   eej eej eej ee ee ee ee eeej ef dddZd!ddZejdddZdd Z  ZS )"r;  rl  rm  rn  zlm_head.weightr   c                    s   t  | |j| _t|j|j| _t	|}d|_
d|_d|_t|| j| _t	|}d|_
d|_|j|_t|| j| _tj|j|jdd| _|   d S )NFTr   )ru   rv   r   	model_dimr   r   rN  r=  ro  rp  r   r   rq  rB  rr  rs  rP  rt  r   lm_headrS  ru  r|   r&   r4   rv     s    

z'LongT5ForConditionalGeneration.__init__c                 C   s   | j S r   rw  rU  r&   r&   r4   rV    s    z3LongT5ForConditionalGeneration.get_input_embeddingsc                 C   s"   || _ | j| | j| d S r   rx  rW  r&   r&   r4   rX    s    z3LongT5ForConditionalGeneration.set_input_embeddingsc                 C   s
   || _ d S r   r  rW  r&   r&   r4   set_output_embeddings  s    z4LongT5ForConditionalGeneration.set_output_embeddingsc                 C   s   | j S r   r  rU  r&   r&   r4   get_output_embeddings  s    z4LongT5ForConditionalGeneration.get_output_embeddingsc                 C   s   | j S r   ry  rU  r&   r&   r4   rz    s    z*LongT5ForConditionalGeneration.get_encoderc                 C   s   | j S r   r{  rU  r&   r&   r4   r|    s    z*LongT5ForConditionalGeneration.get_decoderr  N)r5  rP   r4  r6  ri  r  rj  r  ra  rY  r  labelsr   r   rd  r2  r!   c                 C   s  |dk	r|n| j j}|dk	r |n| j j}|dk	rX|dkrX| j j| j jkrXttt |}|dkrz| j	|||
||||d}nH|rt
|tst|d t|dkr|d ndt|dkr|d ndd}|d }|dk	r|dkr|dkr| |}| j||||	||||||||d}|d }| j jr.|| jd  }| |}d}|dk	rztd	d
}||j}||d|d|d}|s|f|dd  | }|dk	r|f| S |S t|||j|j|j|j|j|j|jd	S )a  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[-100, 0, ...,
            config.vocab_size - 1]`. All labels set to `-100` are ignored (masked), the loss is only computed for
            labels in `[0, ..., config.vocab_size]`

        Returns:

        Examples:

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

        >>> tokenizer = AutoTokenizer.from_pretrained("Stancld/longt5-tglobal-large-16384-pubmed-3k_steps")
        >>> model = LongT5ForConditionalGeneration.from_pretrained(
        ...     "Stancld/longt5-tglobal-large-16384-pubmed-3k_steps"
        ... )

        >>> # Let's try a very long input.
        >>> inputs = tokenizer(100 * "studies have shown that owning a dog is good for you ", return_tensors="pt")
        >>> input_ids = inputs.input_ids

        >>> outputs = model.generate(input_ids)
        >>> print(tokenizer.decode(outputs[0], skip_special_tokens=True))
        abstractthe aim of this article is to provide an overview of the literature on the role of dog
        ```Nr  r   r   rQ   r  r  r8  rD  )Zignore_indexr%   )	lossZlogitsra  r  r  rc  r  r.  r  )r   r   re  rP  rs  r  r  Z6_LongT5ForConditionalGeneration__HEAD_MASK_WARNING_MSGr  rr  r   r   r   rI  rt  Ztie_word_embeddingsr  r  r   rM   r7   r   r   r   ra  rp   rb  rc  r`  )rz   r5  rP   r4  r6  ri  r  rj  r  ra  rY  r  r  r   r   rd  r2  rp   r  Zsequence_outputZ	lm_logitsr  Zloss_fctoutputr&   r&   r4   r     s|    /	




z&LongT5ForConditionalGeneration.forwardc	           
   	   K   s2   |d k	r|d d dd f }||||||||dS )Nr%   )r4  ra  r  rP   ri  r  rj  r   r&   )
rz   r5  ra  rP   ri  r  rj  r   r  r  r&   r&   r4   prepare_inputs_for_generation.  s    z<LongT5ForConditionalGeneration.prepare_inputs_for_generation)r  c                 C   s
   |  |S r   )rI  )rz   r  r&   r&   r4   %prepare_decoder_input_ids_from_labelsI  s    zDLongT5ForConditionalGeneration.prepare_decoder_input_ids_from_labelsc              	   C   s   |d krt d |S d}|D ]b}d}|D ]}||d||jf }q*|d j|d jksbtt|t|ksvt||f }q|S )NzHYou might want to consider setting `use_cache=True` to speed up decodingr&   r   )r)  r*  Zindex_selectrM   r7   r,   rf  r   )rz   ra  Zbeam_idxZreordered_decoder_pastZlayer_past_statesZreordered_layer_past_statesZlayer_past_stater&   r&   r4   _reorder_cacheL  s    
z-LongT5ForConditionalGeneration._reorder_cache)NNNNNNNNNNNNNNNN)NNNNNNN) r   r   r   r  r  r   rv   rV  rX  r  r  rz  r|  r   r  r   r   r  r   r/   r  r  r  r^   r   r   r   r   r  r  r  r   r&   r&   r|   r4   r;  z  st   

                        
r;  zjThe bare LONGT5 Model transformer outputting encoder's raw hidden-states without any specific head on top.c                       s   e Zd ZdgZdgZed fddZdd Zdd	 Zd
d Z	dd Z
eeeeeddeej eej eej eej ee ee ee eeej ef dddZ  ZS )r<  rm  rt  r   c                    sN   t  | t|j|j| _t|}d|_	d|_
t|| j| _|   d S )NF)ru   rv   r   r   rN  r   r=  ro  rp  r   rq  rB  rr  rS  )rz   r   rv  r|   r&   r4   rv   m  s    
zLongT5EncoderModel.__init__c                 C   s   | j S r   rw  rU  r&   r&   r4   rV  y  s    z'LongT5EncoderModel.get_input_embeddingsc                 C   s   || _ | j| d S r   )r=  rr  rX  rW  r&   r&   r4   rX  |  s    z'LongT5EncoderModel.set_input_embeddingsc                 C   s   | j S r   ry  rU  r&   r&   r4   rz    s    zLongT5EncoderModel.get_encoderc                 C   s*   |  D ]\}}| jj| j| qdS r}  r~  r  r&   r&   r4   r    s    zLongT5EncoderModel._prune_headsr  N)r5  rP   ri  rY  r   rd  r2  r!   c           	   	   C   s0   |dk	r|n| j j}| j|||||||d}|S )a\  
        Returns:

        Example:

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

        >>> tokenizer = AutoTokenizer.from_pretrained("google/long-t5-local-base")
        >>> model = LongT5EncoderModel.from_pretrained("google/long-t5-local-base")
        >>> input_ids = tokenizer(
        ...     100 * "Studies have been shown that owning a dog is good for you ", return_tensors="pt"
        ... ).input_ids  # Batch size 1
        >>> outputs = model(input_ids=input_ids)
        >>> last_hidden_states = outputs.last_hidden_state
        ```Nr  )r   re  rr  )	rz   r5  rP   ri  rY  r   rd  r2  r  r&   r&   r4   r     s    
zLongT5EncoderModel.forward)NNNNNNN)r   r   r   r  r  r   rv   rV  rX  rz  r  r   LONGT5_ENCODER_INPUTS_DOCSTRINGr   r   r  r   r/   r  r  r   r   r   r   r   r&   r&   r|   r4   r<  e  s4   
       r<  )r   )r   )Vr  ro  r   r  typingr   r   r   r   r   r/   r   Ztorch.nnr   Ztorch.utils.checkpointr	   Zactivationsr   Zmodeling_outputsr   r   r   r   Zmodeling_utilsr   Zpytorch_utilsr   r   r   utilsr   r   r   r   r   r   r   Zconfiguration_longt5r   Z
get_loggerr   r)  r  Z_CHECKPOINT_FOR_DOCZ$LONGT5_PRETRAINED_MODEL_ARCHIVE_LISTr^   rf   r5   r;   rF   rJ   rO   r7   rT   rj   ro   rr   Modulers   Zapex.normalizationr   infoImportError	Exceptionr*  rB   r   r   r   r   r   r
  r  r  r  r  r!  r3  rB  ZLONGT5_START_DOCSTRINGr  r  Z__HEAD_MASK_WARNING_MSGr:  r;  r<  r&   r&   r&   r4   <module>   s   $	
		 1
  

 l A   "${g ]_'  k