o
    Zh                    @   s  d Z ddlZddlZddlZddlZddlmZmZmZm	Z	 ddl
Z
ddl
mZ ddlmZmZmZ ddlmZ ddlmZmZmZ dd	lmZ dd
lmZ ddlmZmZmZmZmZm Z m!Z! ddl"m#Z# ddl$m%Z%m&Z& ddl'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/ ddl0m1Z1m2Z2 ddl3m4Z4 e, rddl5m6Z6 ddl7m8Z8 e/9e:Z;dZ<dZ=G dd dej>Z?G dd dej>Z@G dd dej>ZAG dd dej>ZBG dd dej>ZCG d d! d!ej>ZDG d"d# d#ej>ZEG d$d% d%ej>ZFd&d' ZGG d(d) d)ej>ZHe+G d*d+ d+e#ZIG d,d- d-eIZJd.ZKe+G d/d0 d0eIZLe+d1d2G d3d4 d4eIeZMe+G d5d6 d6eIZNe+d7d2G d8d9 d9eIZOe+G d:d; d;eIZPe+G d<d= d=eIZQg d>ZRdS )?zPyTorch mT5 model.    N)ListOptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)CacheDynamicCacheEncoderDecoderCache)GenerationMixin)AttentionMaskConverter)BaseModelOutput)BaseModelOutputWithPastAndCrossAttentionsSeq2SeqLMOutputSeq2SeqModelOutput#Seq2SeqQuestionAnsweringModelOutputSeq2SeqSequenceClassifierOutputTokenClassifierOutput)PreTrainedModel) find_pruneable_heads_and_indicesprune_linear_layer)DUMMY_INPUTS
DUMMY_MASKadd_start_docstringsauto_docstringis_torch_flex_attn_availableis_torch_fx_proxyis_torchdynamo_compilinglogging)assert_device_mapget_device_map   )	MT5Config)	BlockMask)make_flex_block_causal_maska  
    This is an experimental feature and is a subject to change at a moment's notice.

    Uses a device map to distribute attention modules of the model across several devices. If no device map is given,
    it will evenly distribute blocks across all devices.

    Args:
        device_map (`Dict[int, list]`, *optional*):
            A dictionary that maps attention modules to devices. Note that the embedding module and LMHead are always
            automatically mapped to the first device (for esoteric reasons). That means that the first device should
            have fewer attention modules mapped to it than other devices. For reference, the mt5 models have the
            following number of attention modules:

                - mt5-small: 6
                - mt5-base: 12
                - mt5-large: 24
                - mt5-xl: 24
                - mt5-xxl: 24

    Example:

    ```python
    # Here is an example of a device map on a machine with 4 GPUs using mt5-xl, which has a total of 24 attention modules:
    model = MT5ForConditionalGeneration.from_pretrained("mt5-xl")
    device_map = {
        0: [0, 1, 2],
        1: [3, 4, 5, 6, 7, 8, 9],
        2: [10, 11, 12, 13, 14, 15, 16],
        3: [17, 18, 19, 20, 21, 22, 23],
    }
    model.parallelize(device_map)
    ```
a#  
    Moves the model to cpu from a model parallel state.

    Example:

    ```python
    # On a 4 GPU machine with mt5-xl:
    model = MT5ForConditionalGeneration.from_pretrained("Mt5-xl")
    device_map = {
        0: [0, 1, 2],
        1: [3, 4, 5, 6, 7, 8, 9],
        2: [10, 11, 12, 13, 14, 15, 16],
        3: [17, 18, 19, 20, 21, 22, 23],
    }
    model.parallelize(device_map)  # Splits the model across several devices
    model.deparallelize()  # Put the model back on cpu and cleans memory by calling torch.cuda.empty_cache()
    ```
c                       s&   e Zd Zd fdd	Zdd Z  ZS )MT5LayerNormư>c                    s&   t    tt|| _|| _dS )zd
        Construct a layernorm module in the MT5 style. No bias and no subtraction of mean.
        N)super__init__r   	Parametertorchonesweightvariance_epsilon)selfhidden_sizeeps	__class__ S/var/www/auris/lib/python3.10/site-packages/transformers/models/mt5/modeling_mt5.pyr,   |   s   

zMT5LayerNorm.__init__c                 C   s\   | tjdjddd}|t|| j  }| jjtj	tj
fv r)| | jj}| j| S )N   T)Zkeepdim)tor.   float32powmeanZrsqrtr1   r0   dtypefloat16Zbfloat16)r2   hidden_statesZvariancer7   r7   r8   forward   s
   
zMT5LayerNorm.forward)r*   )__name__
__module____qualname__r,   rB   __classcell__r7   r7   r5   r8   r)   {   s    r)   c                       *   e Zd Zdef fddZdd Z  ZS )MT5DenseActDenseconfigc                    sT   t    tj|j|jdd| _tj|j|jdd| _t|j	| _
t|j | _d S NFbias)r+   r,   r   Lineard_modeld_ffwiwoDropoutdropout_ratedropoutr   dense_act_fnactr2   rI   r5   r7   r8   r,      s
   
zMT5DenseActDense.__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)rP   rV   rT   
isinstancerQ   r0   r.   Tensorr?   int8r;   r2   rA   r7   r7   r8   rB      s   



zMT5DenseActDense.forwardrC   rD   rE   r&   r,   rB   rF   r7   r7   r5   r8   rH      s    rH   c                       rG   )MT5DenseGatedActDenserI   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 rJ   )r+   r,   r   rM   rN   rO   wi_0wi_1rQ   rR   rS   rT   r   rU   rV   rW   r5   r7   r8   r,      s   
zMT5DenseGatedActDense.__init__c                 C   sz   |  | |}| |}|| }| |}t| jjtjr6|j	| jjj	kr6| jjj	tj
kr6|| jjj	}| |}|S rX   )rV   r_   r`   rT   rY   rQ   r0   r.   rZ   r?   r[   r;   )r2   rA   Zhidden_geluZhidden_linearr7   r7   r8   rB      s   


zMT5DenseGatedActDense.forwardr]   r7   r7   r5   r8   r^      s    r^   c                       rG   )
MT5LayerFFrI   c                    sJ   t    |jrt|| _nt|| _t|j|jd| _	t
|j| _d S )Nr4   )r+   r,   Zis_gated_actr^   DenseReluDenserH   r)   rN   layer_norm_epsilon
layer_normr   rR   rS   rT   rW   r5   r7   r8   r,      s   

zMT5LayerFF.__init__c                 C   s&   |  |}| |}|| | }|S rX   )re   rc   rT   )r2   rA   Zforwarded_statesr7   r7   r8   rB      s   

zMT5LayerFF.forwardr]   r7   r7   r5   r8   ra      s    
ra   c                       sl   e Zd Z		ddedee f fddZdd ZedddZ	dddZ
									dddZ  ZS )MT5AttentionFNrI   	layer_idxc                    s  t    |j| _|| _|j| _|j| _|j| _|j| _|j	| _
|j| _| j
| j | _|| _|d u r@| jr@td| jj d 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rxt| j| j
| _t | _d| _d S )NzInstantiating a decoder z without passing `layer_idx` is not recommended and will to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` when creating this class.FrK   )r+   r,   
is_decoderhas_relative_attention_biasrelative_attention_num_bucketsrelative_attention_max_distancerN   d_kvkey_value_proj_dim	num_headsn_headsrS   rT   	inner_dimrg   loggerwarning_oncer6   rC   r   rM   qkvo	Embeddingrelative_attention_biassetpruned_headsgradient_checkpointingr2   rI   ri   rg   r5   r7   r8   r,      s.   

zMT5Attention.__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%   dim)lenr   ro   rm   rz   r   rs   rt   ru   rv   rp   union)r2   headsindexr7   r7   r8   prune_heads  s   zMT5Attention.prune_headsT       c                 C   s   d}|r|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   r9   r%   )r;   r.   longabsminZ
zeros_likelogfloatmathZ	full_likewhere)relative_positionbidirectionalnum_bucketsmax_distanceZrelative_bucketsZ	max_exactZis_smallZrelative_position_if_larger7   r7   r8   _relative_position_bucket  s*   z&MT5Attention._relative_position_bucketc           
      C   s   |du r	| j jj}|du rtj|tj|ddddf }n|dddf |}tj|tj|ddddf }|| }| j|| j | j	| j
d}|  |}	|	g dd}	|	S )z%Compute binned relative position biasN)r?   device)r   r   r   )r9   r   r%   r   )rx   r0   r   r.   aranger   r;   r   rh   rj   rk   ZpermuteZ	unsqueeze)
r2   query_length
key_lengthr   cache_positionZcontext_positionZmemory_positionr   Zrelative_position_bucketvaluesr7   r7   r8   compute_biasA  s    
 
zMT5Attention.compute_biasc                 C   s  |j dd \}}|du}| |}||d| j| jdd}|dur4|j| j}|r1|j	}n|j
}|r8|n|}|rO|durO|rO|j| j }|j| j }nE| |}| |}||d| j| jdd}||d| j| jdd}|dur|s}|
nd}
|||| jd|
i\}}|rd|j| j< t||dd}|du r|j d }|dur|n|
d d }| jstjd| j||f|j|jd	}| jr| jrd|_n| j|||j|
d
}|dddd| dddf }|dur|ddddddd|j d f }|| }| jr%t|j d }d|t| j< |dd| f }n|}||7 }tjj |! dd"|}tjj#|| j#| jd}|durL|| }t||}|dd$ }||d| j%}| &|}|||f}|	rt||f }|S )z
        Self-attention (if key_value_states is None) or attention over source sentence (provided by key_value_states).
        Nr9   r:   r%   r   Tr
   r   r?   )r   r   r   r}   )ptraining)'shapers   viewro   rm   	transpose
is_updatedgetrg   Zcross_attention_cacheself_attention_cacheZ	key_cacheZvalue_cachert   ru   updater.   matmulri   Zzerosr   r?   r{   r   Zrequires_gradr   rz   r/   listboolr   Z
functionalZsoftmaxr   Ztype_asrT   
contiguousrp   rv   )r2   rA   maskkey_value_statesposition_biaspast_key_valuelayer_head_maskr   	use_cacheoutput_attentionsr   
batch_size
seq_lengthZis_cross_attentionZquery_statesr   Zcurr_past_key_valueZcurrent_statesZ
key_statesZvalue_statesZscoresr   Zreal_seq_lengthcausal_maskZposition_bias_maskedZattn_weightsZattn_outputoutputsr7   r7   r8   rB   U  sx   





"
&



zMT5Attention.forwardFN)Tr   r   )NN)	NNNNNNFFN)rC   rD   rE   r&   r   intr,   r   staticmethodr   r   rB   rF   r7   r7   r5   r8   rf      s,    #
/rf   c                       s@   e Zd Zddee f fddZ							d	ddZ  ZS )
MT5LayerSelfAttentionFNrg   c                    s>   t    t|||d| _t|j|jd| _t	|j
| _d S )Nri   rg   rb   )r+   r,   rf   SelfAttentionr)   rN   rd   re   r   rR   rS   rT   r|   r5   r7   r8   r,     s   
zMT5LayerSelfAttention.__init__c	              
   C   sL   |  |}	| j|	|||||||d}
|| |
d  }|f|
dd   }|S )N)r   r   r   r   r   r   r   r   r%   )re   r   rT   )r2   rA   attention_maskr   r   r   r   r   r   normed_hidden_statesattention_outputr   r7   r7   r8   rB     s   

zMT5LayerSelfAttention.forwardr   )NNNNFFNrC   rD   rE   r   r   r,   rB   rF   r7   r7   r5   r8   r     s    r   c                       sB   e Zd Zddee f fddZ								d	ddZ  ZS )
MT5LayerCrossAttentionNrg   c                    s>   t    t|d|d| _t|j|jd| _t	|j
| _d S )NFr   rb   )r+   r,   rf   EncDecAttentionr)   rN   rd   re   r   rR   rS   rT   )r2   rI   rg   r5   r7   r8   r,     s   
zMT5LayerCrossAttention.__init__Fc                 C   sP   |  |}| j|||||||||	|
d
}|| |d  }|f|dd   }|S )N)	r   r   r   r   r   r   r   r   r   r   r%   )re   r   rT   )r2   rA   r   r   r   r   r   r   r   r   r   r   r   Zlayer_outputr   r7   r7   r8   rB     s    
zMT5LayerCrossAttention.forwardrX   )NNNNFNFNr   r7   r7   r5   r8   r     s    
r   c                       sJ   e Zd Zd	dee f fddZ												d
ddZ  ZS )MT5BlockFNrg   c                    s`   t    |j| _t | _| jt|||d | jr&| jt||d | jt	| d S )Nr   )rg   )
r+   r,   rh   r   
ModuleListlayerappendr   r   ra   r|   r5   r7   r8   r,     s   

zMT5Block.__init__Tc                 C   s  | j d |||||	|
||d}|d d \}}	|dd  }|jtjkrDtt| t|jjd t|jj}tj	|| |d}| j
oJ|d u}|r| j d ||||||	|d d |
|d	}|d d \}}	|jtjkrtt| t|jjd t|jj}tj	|| |d}||dd   }| j d |}|jtjkrtt| t|jjd t|jj}tj	|| |d}|f}|
r||	f | }|S || }|S )	Nr   )r   r   r   r   r   r   r   r9   i  )r   maxr%   r:   )r   r   r   r   r   r   r   r   )r   r?   r.   r@   r   isinfanyfinfor   clamprh   )r2   rA   r   r   encoder_hidden_statesencoder_attention_maskencoder_decoder_position_biasr   cross_attn_layer_head_maskr   r   r   return_dictr   Zself_attention_outputsZattention_outputsZclamp_valueZdo_cross_attentionZcross_attention_outputsr   r7   r7   r8   rB     sn   

zMT5Block.forwardr   )NNNNNNNNFFTNr   r7   r7   r5   r8   r     s    r   c                 C   s@  zddl }ddl}ddl}W n ty   td  w tj|}t	d|  |j
|}g }i }	|D ]\}
}t	d|
 d|  |j
||
}||
 ||	|
< q6|D ]}|d}
tdd	 |
D r{t	d
d|
  |	|d qXd|
d v rt	d
d|
  |	|d qX| }|	| }|
D ]}|d|r|d|}n|g}|d dv rt|d}n|d dkrt|d}|d }n|d dkrt|d}|d }n|d dkrt|d}|d }n|d dkrt|drt|d}nt|drt|d}n|d dkrt|d}n||d dks#|d dkr)t|d}nh|d dkr6t|d}n[|d d krE|
d d!krEq|d d!krRt|d"}n?|d d#krrt|dkrr|d  rrt|d$|d  }qz	t||d }W n ty   t	d
d|
  Y qw t|dkrt|d }|| }q|d dvrt|d}|d d%krt	d&|j d'|
  ||}z|j|jksJ d(|j d)|j d*W n ty } z| j|j|jf7  _ d}~ww t	d+|
  t||j |_!|	|d qXt	d,d-|	"  d. | S )/z'Load tf checkpoints in a pytorch model.r   NzLoading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.z&Converting TensorFlow checkpoint from zLoading TF weight z with shape /c                 s   s    | ]}|d v V  qdS ))Zadam_vZadam_mZAdamWeightDecayOptimizerZAdamWeightDecayOptimizer_1Zglobal_stepNr7   ).0nr7   r7   r8   	<genexpr>  s
    
z)load_tf_weights_in_mt5.<locals>.<genexpr>z	Skipping Z_slot_r:   z[A-Za-z]+_\d+z_(\d+))Zkernelscale	embeddingr0   Zself_attentionr   Zenc_dec_attentionr%   Zdense_relu_denser9   Zrms_normre   final_layer_normr   Zoutput_biasbetarL   Zsquad
classifierdecoderlogitslm_headrP   Zwi_r   z"Transposing numpy weight of shape z for zPointer shape z and array shape  mismatchedzInitialize PyTorch weight z%Weights not copied to PyTorch model: z, .)#renumpyZ
tensorflowImportErrorrq   errorospathabspathinfotrainZlist_variablesZload_variabler   splitr   joinpop	fullmatchgetattrhasattrr   isdigitAttributeErrorr   r   r   AssertionErrorargsr.   Z
from_numpyZastyper<   datakeys)modelrI   Ztf_checkpoint_pathr   nptfZtf_pathZ	init_varsnamesZ
tf_weightsnamer   arrayZtxt_nameZpointerZm_nameZscope_namesnumer7   r7   r8   load_tf_weights_in_mt5r  s   












*

r   c                       s<   e Zd ZdZdef fddZdejdejfddZ  Z	S )	MT5ClassificationHeadz-Head for sentence-level classification tasks.rI   c                    sB   t    t|j|j| _tj|jd| _t|j|j	| _
d S )N)r   )r+   r,   r   rM   rN   denserR   classifier_dropoutrT   
num_labelsout_projrW   r5   r7   r8   r,     s   
zMT5ClassificationHead.__init__rA   returnc                 C   s6   |  |}| |}t|}|  |}| |}|S rX   )rT   r   r.   tanhr   r\   r7   r7   r8   rB     s   




zMT5ClassificationHead.forward)
rC   rD   rE   __doc__r&   r,   r.   rZ   rB   rF   r7   r7   r5   r8   r     s    r   c                   @   sT   e Zd ZeZeZdZdZdZ	dZ
dZdZdgZdgZedd Zdd	 Zd
d ZdS )MT5PreTrainedModeltransformerTFr   rQ   c                 C   s$   t t}t t}|||d}|S )N)decoder_input_ids	input_idsdecoder_attention_mask)r.   Ztensorr   r   )r2   r  Z
input_maskdummy_inputsr7   r7   r8   r    s   

zMT5PreTrainedModel.dummy_inputsc                 C   s
  | j j}t|tr|jj|d  d	S t|ttt	t
fr^|jjjjd|d d t|dr>| j js>|jjjjd|d d t|dr\|jjjjd|| j jd  d |jjj  d	S d	S t|trt|dr}|jjjjd|d d |jjj  d	S d	S t|tr|jjjjd|| j jd  d t|jdr|jjd	ur|jjj  |jjjjd|| j jd  d t|jdr|jjd	ur|jjj  d	S d	S d	S t|tr$|jjjjd|| j jd  d t|jdr|jjd	ur|jjj  |jjjjd|| j jd  d t|jdr |jjd	ur"|jjj  d	S d	S d	S t|tr|jjjjd|| j jd  d t|jdrO|jjd	urO|jjj  |jjjjd|| j jd  d t|jdrt|jjd	urt|jjj  |jjjjd|| j jd  d t|jdr|jjd	ur|jjj  d	S d	S d	S t|t 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 d	S d	S d	S )
zInitialize the weights      ?        )r>   Zstdr   
qa_outputs      r   rL   N))rI   Zinitializer_factorrY   r)   r0   r   Zfill_MT5ModelMT5ForConditionalGenerationMT5EncoderModelMT5ForQuestionAnsweringsharedZnormal_r   tie_word_embeddingsr   r	  rN   rL   Zzero_MT5ForTokenClassificationr   r   r   r   rH   rP   rQ   rO   r^   r_   r`   rf   rl   rn   rs   rt   ru   rv   ri   rx   )r2   modulefactorrN   rm   ro   r7   r7   r8   _init_weights  st   


 


          
z MT5PreTrainedModel._init_weightsc                 C   s   | j j}| j j}|d u rtdt|r1t|jd d d |}tj||dd df gdd}n|	|j}|dd df 
 |ddd f< ||d< |d u rStd||d	k| |S )
Nzself.model.config.decoder_start_token_id has to be defined. In MT5 it is usually set to the pad_token_id. See MT5 docs for more information.r:   )r%   .r}   r%   ).r   z1self.model.config.pad_token_id has to be defined.)rI   decoder_start_token_idpad_token_id
ValueErrorr    r.   fullr   catZ	new_zeroscloneZmasked_fill_)r2   r  r  r  Zshifted_input_idsr7   r7   r8   _shift_rightE  s      zMT5PreTrainedModel._shift_rightN)rC   rD   rE   r&   config_classr   Zload_tf_weightsZbase_model_prefixZis_parallelizableZsupports_gradient_checkpointingZ_supports_quantized_cacheZ_supports_static_cacheZ_supports_cache_classZ_no_split_modulesZ_keep_in_fp32_modulespropertyr  r  r  r7   r7   r7   r8   r    s    

=r  c                       s   e Zd Zd fdd	ZeedddZeedd Zdd	 Z	d
d Z
													dddZ	ddeejdf dejdejdedef
ddZedejdededejdejdefddZ  ZS ) MT5StackNc                    sx   t    || _ j| _t fddt jD | _t	 j
 jd| _t j| _|   d| _d | _d| _d S )Nc                    s"   g | ]}t  t|d k|dqS )r   r   )r   r   )r   irI   r7   r8   
<listcomp>j  s   " z%MT5Stack.__init__.<locals>.<listcomp>rb   F)r+   r,   embed_tokensrh   r   r   range
num_layersblockr)   rN   rd   r   rR   rS   rT   	post_initmodel_parallel
device_mapr{   )r2   rI   r#  r5   r!  r8   r,   c  s   
zMT5Stack.__init__c                 C   s   t dt |d u rtt| jttj	 n|| _
t| j
t| j d| _d| j
 v r/dn
dtt| j
  | _dtt| j
  | _| j
 D ]\}}|D ]}dt| }| j| || j|< qRqL| j| j| _| j| j| _d S )Na=  `MT5Stack.parallelize` is deprecated and will be removed in v5 of Transformers, you should load your model with `device_map='balanced'` in the call to `from_pretrained`. You can also provide your own `device_map` but it needs to be a dictionary module_name to device, so for instance {'block.0': 0, 'block.1': 1, ...}Tcpucuda:)warningswarnFutureWarningr$   r   r&  r$  r.   cudadevice_countr)  r#   r(  r   strr   first_devicer   last_deviceitemsr;   r#  r   )r2   r)  rt   ru   r   Zcuda_devicer7   r7   r8   parallelizev  s"   $	*zMT5Stack.parallelizec                 C   sx   t dt d| _d | _d| _d| _tt| j	D ]}| j	| 
d| j	|< q| j
d| _| j
d| _tj  d S )N\Like `parallelize`, `deparallelize` is deprecated and will be removed in v5 of Transformers.Fr*  )r,  r-  r.  r(  r)  r2  r3  r$  r   r&  r;   r#  r   r.   r/  empty_cache)r2   r   r7   r7   r8   deparallelize  s   zMT5Stack.deparallelizec                 C      | j S rX   r#  r2   r7   r7   r8   get_input_embeddings     zMT5Stack.get_input_embeddingsc                 C   
   || _ d S rX   r:  r2   Znew_embeddingsr7   r7   r8   set_input_embeddings     
zMT5Stack.set_input_embeddingsc           +      C   s0  | j rtj| j | j| j| _|	d ur|	n| jj}	|
d ur"|
n| jj	}
|d ur,|n| jj
}|d ur6|n| jj}|d urT|d urT| jrGdnd}td| d| d|d ure| }|d|d }n|d urr| d d }n| jrwdnd}td| d| d	| jr| jr|	rtd
 d}	|d u r| jd u rtd| |}|\}}|	du r| jstd|  dd}d}| jr|	s|d urt|trt|tsd}t|t }n#t|tsd}td t|}n|d u rtt t }n| jsd }|d ur| nd}|d u rtj||| |jd}|d u r,t s,|| }tj|||jd}| jjrC| ||||d ur>|jnd |
}n&|d urg|d d d d d d f }|j|j d}d| t!|j j" }nd }| jr|d ur| \}}}||f}|d u rtj||jtj#d}| $|}nd }| %|| jj&}| %|| jj&}|rdnd }|
rdnd }|
r| jrdnd }d }d } | '|}!t(| j)D ]\}"}#||" }$||" }%| j r0tj|!j |d ur||!j}|d ur||!j}|d ur||!j}|d ur||!j}| d ur| |!j} |$d ur%|$|!j}$|%d ur0|%|!j}%|r8||!f }| jrT| jrT| *|#j+|!||||| |$|%d |	|
||}&n|#|!||||| |$|%||	|
||d}&|	du rx|&d d d |&dd   }&|&d d \}!}'|&d }| jr|d ur|&|
rdnd } |
r||&d f }| jr||&d f }| j r| j,- D ]!\}(})|"|)d krdt.|( | j/kr|!dt.|(d  }!qq| 0|!}!| '|!}!|r||!f }|	r|'nd }*|r|j}*|r|1 }*|st2dd  |!|*|||fD S t3|!|*|||d!S )"NZdecoder_ 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_embedszZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fz<You have to initialize the model with valid token embeddingsTz)`use_cache` can only be set to `True` if z is used as a decoderzPassing a tuple of `past_key_values` is deprecated and will be removed in Transformers v4.48.0. You should pass an instance of `EncoderDecoderCache` instead, e.g. `past_key_values=EncoderDecoderCache.from_legacy_cache(past_key_values)`.r   r   )r?   r  r   r7   )r   r   r   r   r   r   r   r   r   r   r   r   r%   rX   r9      r
      r+  c                 s   s    | ]	}|d ur|V  qd S rX   r7   )r   ru   r7   r7   r8   r     s    z#MT5Stack.forward.<locals>.<genexpr>)last_hidden_statepast_key_valuesrA   
attentionscross_attentions)4r(  r.   r/  
set_devicer2  r#  r;   rI   r   r   output_hidden_statesuse_return_dictrh   r  sizer   r{   r   rq   rr   rY   r   r   r   Zfrom_legacy_cacheget_seq_lengthr   r   r!   r/   _update_causal_maskr   r?   r   r   r   Zinvert_attention_maskZget_head_maskr%  rT   	enumerater&  Z_gradient_checkpointing_funcrB   r)  r4  r1  r3  r   Zto_legacy_cachetupler   )+r2   r  r   r   r   rC  	head_maskcross_attn_head_maskrH  r   r   rL  r   r   Zerr_msg_prefixZinput_shaper   r   Zreturn_legacy_cacheZreturn_self_attention_cachepast_key_values_lengthZmask_seq_lengthr   Zencoder_batch_sizeZencoder_sequence_length_Zencoder_hidden_shapeZencoder_extended_attention_maskZall_hidden_statesZall_attentionsZall_cross_attentionsr   r   rA   r   Zlayer_moduler   r   Zlayer_outputsZnext_decoder_cachert   ru   Z
next_cacher7   r7   r8   rB     sl  

















"


zMT5Stack.forwardFr   r'   input_tensorr   rH  r   c                 C   s:  | j jdkr|d ur|dk r|S d S | j jdkr&t|tjr$t|}|S |d ur.| nd}|d ur7|jnd}| j jdkrO|sO|sOt	j
|||| jdrOd S |j}|jd }	|r^| }
nt|tjri|jd	 n||	 d }
| j||	|
|||jd d
}| j jdkr|d ur|jjdv r|st|j}t	||}|S )NZflash_attention_2r  Zflex_attentionr   FZsdpa)rC  rU  Zis_trainingr%   r:   )sequence_lengthtarget_lengthr?   r   r   )r/  ZxpuZnpu)rI   Z_attn_implementationr   rY   r.   rZ   r(   rO  Zis_compileabler   Z_ignore_causal_mask_sdpar   r?   r   Zget_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positionr   typer   r   Z_unmask_unattended)r2   r   rW  r   rH  r   Zpast_seen_tokensZusing_compilable_cacher?   rX  rY  r   	min_dtyper7   r7   r8   rP    sT   




zMT5Stack._update_causal_maskrX  rY  r?   r   c                 K   sD  | dur|   dkr| }|S t|j}tj||f|||jd}|dkr+tj|dd}|tj||jd|ddk9 }|ddddddf 	|ddd}| dur|
 }| jd }	|ddddddd|	f | ddddddf |j }
|
dk}
|ddddddd|	f |
||ddddddd|	f< |S )	aM  
        Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
        `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

        Args:
            attention_mask (`torch.Tensor`):
                A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
                `(batch_size, 1, query_length, key_value_length)`.
            sequence_length (`int`):
                The sequence length being processed.
            target_length (`int`):
                The target length: when generating with static cache, the mask should be as long as the static cache,
                to account for the 0 padding, the part of the cache that is not filled yet.
            dtype (`torch.dtype`):
                The dtype to use for the 4D attention mask.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
        NrE  )Z
fill_valuer?   r   r%   )ZdiagonalrD  r:   r   )r~   r.   r   r   r  r   Ztriur   Zreshapeexpandr  r   r;   Zmasked_fill)r   rX  rY  r?   r   r   kwargsr   r\  Zmask_lengthZpadding_maskr7   r7   r8   rZ    s,    $
6  z>MT5Stack._prepare_4d_causal_attention_mask_with_cache_positionrX   )NNNNNNNNNNNNN)F)rC   rD   rE   r,   r   PARALLELIZE_DOCSTRINGr5  DEPARALLELIZE_DOCSTRINGr8  r<  r@  rB   r   r.   rZ   r   r   rP  r   r   r?   rZ  rF   r7   r7   r5   r8   r  b  sb    

 
Dr  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)`.
c                &       sp  e Zd ZdZdZeZdgZddgZdef fddZ	e
ed+d
dZe
edd Zdd Zdd Zdd Zdd Zdd Ze																																d,deej deej deej deej deej deej deej deeeej   d eeeej   d!eej d"eej d#ee d$ee d%ee d&ee d'eej d(eeej ef f"d)d*Z  Z S )-r  aw  
    Examples:

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

    >>> model = MT5Model.from_pretrained("google/mt5-small")
    >>> tokenizer = AutoTokenizer.from_pretrained("google/mt5-small")
    >>> article = "UN Offizier sagt, dass weiter verhandelt werden muss in Syrien."
    >>> summary = "Weiter Verhandlung in Syrien."
    >>> inputs = tokenizer(article, return_tensors="pt")
    >>> labels = tokenizer(text_target=summary, return_tensors="pt")

    >>> outputs = model(input_ids=inputs["input_ids"], decoder_input_ids=labels["input_ids"])
    >>> hidden_states = outputs.last_hidden_state
    ```mt5Fdecoder.block.0.layer.1.EncDecAttention.relative_attention_bias.weightencoder.embed_tokens.weightdecoder.embed_tokens.weightrI   c                    s   t  | t|j|j| _t|}d|_	d|_
d|_t|| j| _t|}d|_	d|_|j|_t|| j| _|   d| _d | _d S NFT)r+   r,   r   rw   
vocab_sizerN   r  copydeepcopyrh   r   is_encoder_decoderr  encodernum_decoder_layersr%  r   r'  r(  r)  r2   rI   encoder_configZdecoder_configr5   r7   r8   r,   ?  s   


zMT5Model.__init__Nc                 C   sp   t dt |d u rtt| jjttj	
 n|| _t| jt| jj | j| j | j| j d| _d S )NaL  `T5Model.parallelize` is deprecated and will be removed in v5 of Transformers, you should load your model with `device_map='balanced'` in the call to `from_pretrained`. You can also provide your own `device_map` but it needs to be a dictionary module_name to device, so for instance {'encoder.block.0': 0, 'encoder.block.1': 1, ...}T)r,  r-  r.  r$   r   rj  r&  r$  r.   r/  r0  r)  r#   r5  r   r(  r2   r)  r7   r7   r8   r5  V  s   	
zMT5Model.parallelizec                 C   sV   t dt | j  | j  | jd| _| jd| _d| _d | _t	j
  d S Nr6  r*  F)r,  r-  r.  rj  r8  r   r;   r(  r)  r.   r/  r7  r;  r7   r7   r8   r8  j  s   

zMT5Model.deparallelizec                 C   r9  rX   r  r;  r7   r7   r8   r<  z  r=  zMT5Model.get_input_embeddingsc                 C   "   || _ | j| | j| d S rX   r  rj  r@  r   r?  r7   r7   r8   r@  ~     zMT5Model.set_input_embeddingsc                 C   r9  rX   rj  r;  r7   r7   r8   get_encoder  r=  zMT5Model.get_encoderc                 C   r9  rX   r   r;  r7   r7   r8   get_decoder  r=  zMT5Model.get_decoderc                 C   s*   |  D ]\}}| jj| j| qdS )
        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)r4  rj  r   Z	attentionr   r2   Zheads_to_pruner   r   r7   r7   r8   _prune_heads  s   zMT5Model._prune_headsr  r   r  r  rS  decoder_head_maskrT  encoder_outputsrH  rC  decoder_inputs_embedsr   r   rL  r   r   r   c                 C   s  |dur|n| j j}|dur|n| j j}|dur,|du r,| j j| j jkr,ttt |}|du r=| j	|||
||||d}n$|rat
|tsat|d t|dkrR|d ndt|dkr]|d ndd}|d }| jrtj| jj || jj}|dur|| jj}|dur|| jj}|dur|| jj}| j||||	|||||||||d}|s|| S t|j|j|j|j|j|j|j|jdS )	a  
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. MT5 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 [MT5 Training](./mt5#training).
        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)

            MT5 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 [MT5
            Training](./mt5#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.
        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**.

        Example:

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

        >>> tokenizer = AutoTokenizer.from_pretrained("google/mt5-small")
        >>> model = MT5Model.from_pretrained("google/mt5-small")

        >>> input_ids = tokenizer(
        ...     "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

        >>> # preprocess: Prepend decoder_input_ids with start token which is pad token for MT5Model.
        >>> # This is not needed for torch's MT5ForConditionalGeneration as it does this internally using labels arg.
        >>> decoder_input_ids = model._shift_right(decoder_input_ids)

        >>> # forward pass
        >>> outputs = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids)
        >>> last_hidden_states = outputs.last_hidden_state
        ```Nr  r   rC  rS  r   rL  r   r   r%   r9   rG  rA   rI  r  r   rC  rH  r   r   rS  rT  r   r   rL  r   r   )rG  rH  decoder_hidden_statesdecoder_attentionsrJ  encoder_last_hidden_stater   encoder_attentions)rI   r   rM  r%  rk  r,  r-  Z _MT5Model__HEAD_MASK_WARNING_MSGr.  rj  rY   r   r   r(  r.   r/  rK  r   r2  r;   r   rG  rH  rA   rI  rJ  )r2   r  r   r  r  rS  r{  rT  r|  rH  rC  r}  r   r   rL  r   r   rA   decoder_outputsr7   r7   r8   rB     sv   R	zMT5Model.forwardrX   NNNNNNNNNNNNNNNN)!rC   rD   rE   r   
model_typer&   r  "_keys_to_ignore_on_load_unexpected_tied_weights_keysr,   r   r_  r5  r`  r8  r<  r@  ru  rw  rz  r   r   r.   
LongTensorFloatTensor
BoolTensorrZ   r   r   r   r   rB   rF   r7   r7   r5   r8   r  &  s    
	
r  z;
    MT5 Model with a `language modeling` head on top.
    )Zcustom_introc                (       s  e Zd ZdZdZeZdgZg dZdef fddZ	e
ed1d	d
Ze
edd Zdd Zdd Zdd Zdd Zdd Zdd Ze																	d2deej deej deej deej deej deej deej d eeeej   d!eeeej   d"eej d#eej d$eej d%ee d&ee d'ee d(ee d)eej d*eeej ef f$d+d,Z d$ejfd-d.Z!d/d0 Z"  Z#S )3r  a  
    Examples:

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

    >>> model = MT5ForConditionalGeneration.from_pretrained("google/mt5-small")
    >>> tokenizer = AutoTokenizer.from_pretrained("google/mt5-small")
    >>> article = "UN Offizier sagt, dass weiter verhandelt werden muss in Syrien."
    >>> summary = "Weiter Verhandlung in Syrien."
    >>> inputs = tokenizer(article, text_target=summary, return_tensors="pt")

    >>> outputs = model(**inputs)
    >>> loss = outputs.loss
    ```ra  rb  )rc  rd  zlm_head.weightrI   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| _d | _d S )NFTrK   )r+   r,   rN   	model_dimr   rw   rf  r  rg  rh  rh   r   ri  r  rj  rk  r%  r   rM   r   r'  r(  r)  rl  r5   r7   r8   r,   J  s"   


z$MT5ForConditionalGeneration.__init__Nc                 C   s   t dt |d u rtt| jjttj	
 n|| _t| jt| jj | j| j | j| j | j| jj| _d| _d S )Na_  `T5ForConditionalGeneration.parallelize` is deprecated and will be removed in v5 of Transformers, you should load your model with `device_map='balanced'` in the call to `from_pretrained`. You can also provide your own `device_map` but it needs to be a dictionary module_name to device, so for instance {'encoder.block.0': 0, 'encoder.block.1': 1, ...}T)r,  r-  r.  r$   r   rj  r&  r$  r.   r/  r0  r)  r#   r5  r   r   r;   r2  r(  rn  r7   r7   r8   r5  e  s   	
z'MT5ForConditionalGeneration.parallelizec                 C   sd   t dt | j  | j  | jd| _| jd| _| jd| _d| _d | _	t
j  d S ro  )r,  r-  r.  rj  r8  r   r;   r   r(  r)  r.   r/  r7  r;  r7   r7   r8   r8  z  s   

z)MT5ForConditionalGeneration.deparallelizec                 C   r9  rX   rp  r;  r7   r7   r8   r<    r=  z0MT5ForConditionalGeneration.get_input_embeddingsc                 C   rq  rX   rr  r?  r7   r7   r8   r@    rs  z0MT5ForConditionalGeneration.set_input_embeddingsc                 C   r>  rX   r   r?  r7   r7   r8   set_output_embeddings  rA  z1MT5ForConditionalGeneration.set_output_embeddingsc                 C   r9  rX   r  r;  r7   r7   r8   get_output_embeddings  r=  z1MT5ForConditionalGeneration.get_output_embeddingsc                 C   r9  rX   rt  r;  r7   r7   r8   ru    r=  z'MT5ForConditionalGeneration.get_encoderc                 C   r9  rX   rv  r;  r7   r7   r8   rw    r=  z'MT5ForConditionalGeneration.get_decoderr  r   r  r  rS  r{  rT  r|  rH  rC  r}  labelsr   r   rL  r   r   r   c                 C   s  |dur|n| j j}|dur|n| j j}|dur,|du r,| j j| j jkr,ttt |}|du r=| j	|||
||||d}n$|rat
|tsat|d t|dkrR|d ndt|dkr]|d ndd}|d }| jrptj| jj |dur|du r|du r| |}| jrtj| jj || jj}|dur|| jj}|dur|| jj}|dur|| jj}| j||||	|||||||||d}|d }| jrtj| j	j | j| j	j| _|| jjj}| j jr|| jd  }| |}d}|durtd	d
}||j}||d|d|d}|s1|f|dd  | }|dur/|f| S |S t|||j|j|j |j!|j"|j|j d	S )a  
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. MT5 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 [MT5 Training](./mt5#training).
        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)

            MT5 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 [MT5
            Training](./mt5#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.
        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**.
        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]`

        Examples:

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

        >>> tokenizer = AutoTokenizer.from_pretrained("google/mt5-small")
        >>> model = MT5ForConditionalGeneration.from_pretrained("google/mt5-small")

        >>> # training
        >>> input_ids = tokenizer("The <extra_id_0> walks in <extra_id_1> park", return_tensors="pt").input_ids
        >>> labels = tokenizer("<extra_id_0> cute dog <extra_id_1> the <extra_id_2>", return_tensors="pt").input_ids
        >>> outputs = model(input_ids=input_ids, labels=labels)
        >>> loss = outputs.loss
        >>> logits = outputs.logits

        >>> # inference
        >>> input_ids = tokenizer(
        ...     "summarize: studies have shown that owning a dog is good for you", return_tensors="pt"
        ... ).input_ids  # Batch size 1
        >>> outputs = model.generate(input_ids)
        >>> print(tokenizer.decode(outputs[0], skip_special_tokens=True))
        >>> # studies have shown that owning a dog is good for you.
        ```Nr~  r   r%   r9   r  r  r
  r  Zignore_indexr:   	lossr   rH  r  r  rJ  r  r   r  )#rI   r   rM  r%  rk  r,  r-  Z3_MT5ForConditionalGeneration__HEAD_MASK_WARNING_MSGr.  rj  rY   r   r   r(  r.   r/  rK  r   r2  r  r;   r   r0   r   r  r  r   r   rN  r   rH  rA   rI  rJ  rG  )r2   r  r   r  r  rS  r{  rT  r|  rH  rC  r}  r  r   r   rL  r   r   rA   r  sequence_outputZ	lm_logitsr  loss_fctoutputr7   r7   r8   rB     s   Y	



z#MT5ForConditionalGeneration.forwardc                 C   s
   |  |S rX   )r  )r2   r  r7   r7   r8   %prepare_decoder_input_ids_from_labelsf  rA  zAMT5ForConditionalGeneration.prepare_decoder_input_ids_from_labelsc              	   C   s   |d u rt d |S d}|D ]M}d}|D ]}||d||jf }q|d j|d jkr@td|d j d|d j dt|t|krWtdt| dt| d||f }q|S )	NzHYou might want to consider setting `use_cache=True` to speed up decodingr7   r   z%reordered_layer_past_states[0] shape z  and layer_past_states[0] shape r   z&length of reordered_layer_past_states z! and length of layer_past_states )rq   warningZindex_selectr;   r   r   r  r   )r2   rH  Zbeam_idxZreordered_decoder_pastZlayer_past_statesZreordered_layer_past_statesZlayer_past_stater7   r7   r8   _reorder_cachej  s(   
z*MT5ForConditionalGeneration._reorder_cacherX   )NNNNNNNNNNNNNNNNN)$rC   rD   rE   r   r  r&   r  r  r  r,   r   r_  r5  r`  r8  r<  r@  r  r  ru  rw  r   r   r.   r  r  r  rZ   r   r   r   r   rB   r  r  rF   r7   r7   r5   r8   r  .  s    
	
 Ar  c                       s   e Zd ZdZdZeZdgZdef fddZe	e
ddd	Ze	ed
d Zdd Zdd Zdd Zdd Ze							ddeej deej deej deej dee dee dee deeej ef fddZ  ZS ) r  a  
    Examples:

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

    >>> model = MT5EncoderModel.from_pretrained("google/mt5-small")
    >>> tokenizer = AutoTokenizer.from_pretrained("google/mt5-small")
    >>> article = "UN Offizier sagt, dass weiter verhandelt werden muss in Syrien."
    >>> input_ids = tokenizer(article, return_tensors="pt").input_ids
    >>> outputs = model(input_ids)
    >>> hidden_state = outputs.last_hidden_state
    ```ra  rc  rI   c                    sZ   t  | t|j|j| _t|}d|_	d|_
t|| j| _|   d| _d | _d S NF)r+   r,   r   rw   rf  rN   r  rg  rh  r   ri  r  rj  r'  r(  r)  )r2   rI   rm  r5   r7   r8   r,     s   

zMT5EncoderModel.__init__Nc                 C   sb   t dt |d u rtt| jjttj	
 n|| _t| jt| jj | j| j d| _d S )NaC  `T5EncoderModel.parallelize` is deprecated and will be removed in v5 of Transformers, you should load your model with `device_map='balanced'` in the call to `from_pretrained`. You can also provide your own `device_map` but it needs to be a dictionary module_name to device, so for instance {'block.0': 0, 'block.1': 1, ...}T)r,  r-  r.  r$   r   rj  r&  r$  r.   r/  r0  r)  r#   r5  r(  rn  r7   r7   r8   r5    s   	
zMT5EncoderModel.parallelizec                 C   s>   t dt | j  | jd| _d| _d | _tj	
  d S ro  )r,  r-  r.  rj  r8  r;   r(  r)  r.   r/  r7  r;  r7   r7   r8   r8    s   
zMT5EncoderModel.deparallelizec                 C   r9  rX   rp  r;  r7   r7   r8   r<    r=  z$MT5EncoderModel.get_input_embeddingsc                 C   s   || _ | j| d S rX   )r  rj  r@  r?  r7   r7   r8   r@    s   z$MT5EncoderModel.set_input_embeddingsc                 C   r9  rX   rt  r;  r7   r7   r8   ru    r=  zMT5EncoderModel.get_encoderc                 C   s0   |  D ]\}}| jj| jd j| qdS )rx  r   N)r4  rj  r&  r   r   r   ry  r7   r7   r8   rz    s   zMT5EncoderModel._prune_headsr  r   rS  rC  r   rL  r   r   c           	   	   C   s0   |dur|n| j j}| j|||||||d}|S )aJ  
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. MT5 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 [MT5 Training](./mt5#training).

        Example:

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

        >>> tokenizer = AutoTokenizer.from_pretrained("google/mt5-small")
        >>> model = MT5EncoderModel.from_pretrained("google/mt5-small")
        >>> input_ids = tokenizer(
        ...     "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~  )rI   rM  rj  )	r2   r  r   rS  rC  r   rL  r   r|  r7   r7   r8   rB     s   #
zMT5EncoderModel.forwardrX   )NNNNNNN)rC   rD   rE   r   r  r&   r  r  r,   r   r_  r5  r`  r8  r<  r@  ru  rz  r   r   r.   r  r  r   r   r   r   rB   rF   r7   r7   r5   r8   r    sN    
	r  z
    MT5 model with a sequence classification/head on top (a linear layer on top of the pooled output) e.g. for GLUE
    tasks.
    c                $       s   e Zd ZdgZddgZdef fddZe															ddee	j
 d	ee	j d
ee	j
 dee	j
 dee	j dee	j dee	j deee	j  dee	j dee	j dee	j
 dee dee dee dee deeef f ddZ  ZS )MT5ForSequenceClassificationrb  rc  rd  rI   c                    s2   t  | t|| _t|| _|   d| _d S r  )r+   r,   r  r  r   classification_headr'  r(  rW   r5   r7   r8   r,   !  s
   


z%MT5ForSequenceClassification.__init__Nr  r   r  r  rS  r{  rT  r|  rC  r}  r  r   r   rL  r   r   c                 C   sh  |dur|n| j j}|durd}|du r!|	dur!td| jj |du r6|
du r6|du r1td| |}| j|||||||||	|
||||d}|d }|| j j	
|j}tt|ddkrhtd|j\}}}||ddf |d	|ddd	ddf }| |}d}|dur|
|j}| j jdu r| j jdkrd
| j _n| j jdkr|jtjks|jtjkrd| j _nd| j _| j jd
krt }| j jdkr|| | }n-|||}n'| j jdkrt }||d	| j j|d	}n| j jdkrt }|||}|s |f|dd  }|dur|f| S |S t|||j|j|j|j |j!|j"|j#d	S )am
  
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. MT5 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 [MT5 Training](./mt5#training).
        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)

            MT5 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 [MT5
            Training](./mt5#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.
        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**.
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        NFz8Passing input embeddings is currently not supported for If no `decoder_input_ids` or `decoder_inputs_embeds` are passed, `input_ids` cannot be `None`. Please pass either `input_ids` or `decoder_input_ids` or `decoder_inputs_embeds`.)r   r  r  rS  r{  rT  r|  rC  r}  r   r   rL  r   r   r%   z7All examples must have the same number of <eos> tokens.r:   Z
regressionZsingle_label_classificationZmulti_label_classificationr  )$rI   rM  NotImplementedErrorr6   rC   r  r  r  eqZeos_token_idr;   r   r   r.   Zunique_consecutivesumr   r   r  Zproblem_typer   r?   r   r   r	   squeezer   r   r   rH  r  r  rJ  r  r   r  )r2   r  r   r  r  rS  r{  rT  r|  rC  r}  r  r   r   rL  r   r   r  Zeos_maskr   rV  r3   Zsentence_representationr   r  r  r  r7   r7   r8   rB   +  s   ?
,


$

z$MT5ForSequenceClassification.forward)NNNNNNNNNNNNNNN)rC   rD   rE   r  r  r&   r,   r   r   r.   r  rZ   r   r  r   r   r   r   rB   rF   r7   r7   r5   r8   r    sj    
	

r  c                       s   e Zd ZdgZdef fddZe								ddeej	 deej	 deej	 d	eej	 d
eej	 dee
 dee
 dee
 deeej	 ef fddZ  ZS )r  z'transformer.encoder.embed_tokens.weightrI   c                    sJ   t  | |j| _t|| _t|j| _t	|j
|j| _|   d S rX   )r+   r,   r   r  r  r   rR   r   rT   rM   r3   r   r'  rW   r5   r7   r8   r,     s   
z"MT5ForTokenClassification.__init__Nr  r   rS  rC  r  r   rL  r   r   c	              	   C   s   |dur|n| j j}| j|||||||d}	|	d }
| |
}
| |
}d}|dur:t }||d| j|d}|sO||	dd f}|durM|f| S |S t|||	j	|	j
dS )a>  
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. MT5 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 [MT5 Training](./t5#training).
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
        N)r   rS  rC  r   rL  r   r   r:   r9   )r  r   rA   rI  )rI   rM  r  rT   r   r   r   r   r   rA   rI  )r2   r  r   rS  rC  r  r   rL  r   r   rA   r   r  r  r  r7   r7   r8   rB     s4   


z!MT5ForTokenClassification.forward)NNNNNNNN)rC   rD   rE   r  r&   r,   r   r   r.   rZ   r   r   r   r   rB   rF   r7   r7   r5   r8   r    s>    	
r  c                &       s2  e Zd ZdgZddgZdef fddZdd Zd	d
 Zdd Z	dd Z
e																d#deej deej deej deej deej deej deej deeeej   deej deej deej deej dee dee dee dee d eeej ef f"d!d"Z  ZS )$r  rb  rc  rd  rI   c                    s   t  | |j| _t|j|j| _t	|}d|_
d|_d|_t|| j| _t	|}d|_
d|_|j|_t|| j| _|j| _t|j|j| _|   d| _d S re  )r+   r,   rN   r  r   rw   rf  r  rg  rh  rh   r   ri  r  rj  rk  r%  r   r   rM   r3   r	  r'  r(  rl  r5   r7   r8   r,   	  s"   


z MT5ForQuestionAnswering.__init__c                 C   r9  rX   rp  r;  r7   r7   r8   r<  -	  r=  z,MT5ForQuestionAnswering.get_input_embeddingsc                 C   rq  rX   rr  r?  r7   r7   r8   r@  1	  rs  z,MT5ForQuestionAnswering.set_input_embeddingsc                 C   r9  rX   rt  r;  r7   r7   r8   ru  7	  r=  z#MT5ForQuestionAnswering.get_encoderc                 C   r9  rX   rv  r;  r7   r7   r8   rw  ;	  r=  z#MT5ForQuestionAnswering.get_decoderNr  r   r  r  rS  r{  rT  r|  start_positionsend_positionsrC  r}  r   r   rL  r   r   c                 C   s  |dur|n| j j}|dur|n| j j}|	dur|
durd}|du r3|du r3|du r.td| |}|dur9|n| j j}|durC|n| j j}|dur_|du r_| j j| j jkr_tt	t
 |}|du rp| j|||||||d}n$|rt|tst|d t|dkr|d ndt|dkr|d ndd}|d }| j|||d||||||||d	}|d }| |}|jdd
d\}}|d
 }|d
 }d}|	dur|
durt|	 dkr|	d
|j}	t|
 dkr|
d
|j}
|d}|	d|}	|
d|}
t|d}|||	}|||
}|| d }|s8||f|dd  | }|dur6|f| S |S t||||j|j|j|j|j|j|jd
S )a=	  
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. T5 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 [T5 Training](./t5#training).
        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)

            T5 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 [T5
            Training](./t5#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.
        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**.
        NFr  r~  r   r%   r9   r  )r  r   rC  rH  r   r   rS  rT  r   r   rL  r   r:   r}   r  )
r  start_logits
end_logitsrH  r  r  rJ  r  r   r  )rI   rM  r   r  r  r%  rk  r,  r-  Z/_MT5ForQuestionAnswering__HEAD_MASK_WARNING_MSGr.  rj  rY   r   r   r   r	  r   r  r   rN  r;   r   r   r   r   rH  rA   rI  rJ  rG  )r2   r  r   r  r  rS  r{  rT  r|  r  r  rC  r}  r   r   rL  r   rA   r  r  r   r  r  Z
total_lossZignored_indexr  Z
start_lossZend_lossr  r7   r7   r8   rB   >	  s   =
	




zMT5ForQuestionAnswering.forwardr  )rC   rD   rE   r  r  r&   r,   r<  r@  ru  rw  r   r   r.   r  r  r  rZ   r   r   r   r   rB   rF   r7   r7   r5   r8   r  	  sx    	
r  )r  r  r  r  r  r  r  )Sr   rg  r   r   r,  typingr   r   r   r   r.   r   Ztorch.nnr   r   r	   Zactivationsr   Zcache_utilsr   r   r   Z
generationr   Zmodeling_attn_mask_utilsr   Zmodeling_outputsr   r   r   r   r   r   r   Zmodeling_utilsr   Zpytorch_utilsr   r   utilsr   r   r   r   r   r    r!   r"   Zutils.model_parallel_utilsr#   r$   Zconfiguration_mt5r&   Z!torch.nn.attention.flex_attentionr'   Zintegrations.flex_attentionr(   Z
get_loggerrC   rq   r_  r`  Moduler)   rH   r^   ra   rf   r   r   r   r   r   r  r  Z__HEAD_MASK_WARNING_MSGr  r  r  r  r  r  __all__r7   r7   r7   r8   <module>   s   $	(

! f%'dkq   ?  	  X  %K W