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&m'Z' ddl(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0 ddl1m2Z2m3Z3 ddl4m5Z5 e- rddl6m7Z7 ddl8m9Z9 e0:e;Z<dd Z=dZ>dZ?G dd dej@ZAzddlBmCZC eCZAe<Dd W n eEy   Y n eFy   e<Gd Y nw e%HeA G dd dej@ZIG dd  d ej@ZJG d!d" d"ej@ZKG d#d$ d$ej@ZLG d%d& d&ej@ZMG d'd( d(ej@ZNG d)d* d*ej@ZOG d+d, d,ej@ZPe,G d-d. d.e#ZQG d/d0 d0eQZRd1ZSe,G d2d3 d3eQZTe,d4d5G d6d7 d7eQeZUe,G d8d9 d9eQZVe,d:d5G d;d< d<eQZWe,G d=d> d>eQZXe,G d?d@ d@eQZYg dAZZdS )BzPyTorch T5 model.    N)ListOptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)CacheDynamicCacheEncoderDecoderCache)GenerationMixin)AttentionMaskConverter)BaseModelOutput)BaseModelOutputWithPastAndCrossAttentionsSeq2SeqLMOutputSeq2SeqModelOutput#Seq2SeqQuestionAnsweringModelOutputSeq2SeqSequenceClassifierOutputTokenClassifierOutput)PreTrainedModel)ALL_LAYERNORM_LAYERS 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   )T5Config)	BlockMask)make_flex_block_causal_maskc                 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rt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_stepN ).0nr+   r+   Q/var/www/auris/lib/python3.10/site-packages/transformers/models/t5/modeling_t5.py	<genexpr>h   s
    
z(load_tf_weights_in_t5.<locals>.<genexpr>z	Skipping Z_slot_z[A-Za-z]+_\d+z_(\d+))Zkernelscale	embeddingweightZself_attentionlayerZenc_dec_attentionr&   Zdense_relu_dense   Zrms_norm
layer_normfinal_layer_normr1   Zoutput_biasbetabiasZsquad
classifierdecoderlogitslm_headwiZwi_r2   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ImportErrorloggererrorospathabspathinfotrainZlist_variablesZload_variableappendsplitanyjoinpop	fullmatchgetattrhasattrlenisdigitAttributeErrorintshape	transpose
ValueErrorAssertionErrorargstorchZ
from_numpyZastypefloat32datakeys)modelconfigZtf_checkpoint_pathrA   nptfZtf_pathZ	init_varsnamesZ
tf_weightsnamerW   arrayZtxt_nameZpointerZm_nameZscope_namesnumer+   r+   r.   load_tf_weights_in_t5K   s   












*

ri   aR  
    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 t5 models have the
            following number of attention modules:

                - google-t5/t5-small: 6
                - google-t5/t5-base: 12
                - google-t5/t5-large: 24
                - google-t5/t5-3b: 24
                - google-t5/t5-11b: 24

    Example:

    ```python
    # Here is an example of a device map on a machine with 4 GPUs using google-t5/t5-3b, which has a total of 24 attention modules:
    model = T5ForConditionalGeneration.from_pretrained("google-t5/t5-3b")
    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)
    ```
a4  
    Moves the model to cpu from a model parallel state.

    Example:

    ```python
    # On a 4 GPU machine with google-t5/t5-3b:
    model = T5ForConditionalGeneration.from_pretrained("google-t5/t5-3b")
    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 )T5LayerNormư>c                    s&   t    tt|| _|| _dS )zc
        Construct a layernorm module in the T5 style. No bias and no subtraction of mean.
        N)super__init__r   	Parameterr\   onesr3   variance_epsilon)selfhidden_sizeeps	__class__r+   r.   rm      s   

zT5LayerNorm.__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 )Nr5   r0   T)Zkeepdim)tor\   r]   powmeanZrsqrtrp   r3   dtypefloat16Zbfloat16)rq   hidden_statesZvariancer+   r+   r.   forward   s
   
zT5LayerNorm.forward)rk   )__name__
__module____qualname__rm   r|   __classcell__r+   r+   rt   r.   rj      s    rj   )FusedRMSNormzODiscovered apex.normalization.FusedRMSNorm - will use it instead of T5LayerNormzBdiscovered apex but it failed to load, falling back to T5LayerNormc                       *   e Zd Zdef fddZdd Z  ZS )T5DenseActDensera   c                    sT   t    tj|j|jdd| _tj|j|jdd| _t|j	| _
t|j | _d S NFr9   )rl   rm   r   Lineard_modeld_ffr>   woDropoutdropout_ratedropoutr   dense_act_fnactrq   ra   rt   r+   r.   rm     s
   
zT5DenseActDense.__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   r3   r\   Tensorry   int8rv   rq   r{   r+   r+   r.   r|     s   



zT5DenseActDense.forwardr}   r~   r   r'   rm   r|   r   r+   r+   rt   r.   r     s    r   c                       r   )T5DenseGatedActDensera   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   )rl   rm   r   r   r   r   wi_0wi_1r   r   r   r   r   r   r   r   rt   r+   r.   rm   .  s   
zT5DenseGatedActDense.__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 r   )r   r   r   r   r   r   r3   r\   r   ry   r   rv   )rq   r{   Zhidden_geluZhidden_linearr+   r+   r.   r|   6  s   


zT5DenseGatedActDense.forwardr   r+   r+   rt   r.   r   -  s    r   c                       r   )	T5LayerFFra   c                    sJ   t    |jrt|| _nt|| _t|j|jd| _	t
|j| _d S )Nrs   )rl   rm   Zis_gated_actr   DenseReluDenser   rj   r   layer_norm_epsilonr6   r   r   r   r   r   rt   r+   r.   rm   K  s   

zT5LayerFF.__init__c                 C   s&   |  |}| |}|| | }|S r   )r6   r   r   )rq   r{   Zforwarded_statesr+   r+   r.   r|   U  s   

zT5LayerFF.forwardr   r+   r+   rt   r.   r   J  s    
r   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 )T5AttentionFNra   	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.Fr   )rl   rm   
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   rD   warning_onceru   r}   r   r   qkvo	Embeddingrelative_attention_biassetpruned_headsgradient_checkpointingrq   ra   r   r   rt   r+   r.   rm   ]  s.   

zT5Attention.__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)rS   r   r   r   r   r   r   r   r   r   r   union)rq   headsindexr+   r+   r.   prune_heads  s   zT5Attention.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   r5   r&   )rv   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_larger+   r+   r.   _relative_position_bucket  s*   z%T5Attention._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)ry   device)r   r   r   )r5   r   r&   r   )r   r3   r   r\   aranger   rv   r   r   r   r   ZpermuteZ	unsqueeze)
rq   query_length
key_lengthr   cache_positionZcontext_positionZmemory_positionr   Zrelative_position_bucketvaluesr+   r+   r.   compute_bias  s    
 
zT5Attention.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).
        Nr5   r0   r&   r   Tr
   r   ry   )r   r   r   r   )ptraining)'rW   r   viewr   r   rX   
is_updatedgetr   Zcross_attention_cacheself_attention_cacheZ	key_cacheZvalue_cacher   r   updater\   matmulr   Zzerosr   ry   r   r   Zrequires_gradr   r   ro   listboolr   Z
functionalZsoftmaxr   Ztype_asr   
contiguousr   r   )rq   r{   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outputsr+   r+   r.   r|     sx   





"
&



zT5Attention.forwardFN)Tr   r   )NN)	NNNNNNFFN)r}   r~   r   r'   r   rV   rm   r   staticmethodr   r   r|   r   r+   r+   rt   r.   r   \  s,    #
/r   c                       s@   e Zd Zddee f fddZ							d	ddZ  ZS )
T5LayerSelfAttentionFNr   c                    s>   t    t|||d| _t|j|jd| _t	|j
| _d S )Nr   r   r   )rl   rm   r   SelfAttentionrj   r   r   r6   r   r   r   r   r   rt   r+   r.   rm   A  s   
zT5LayerSelfAttention.__init__c	              
   C   sL   |  |}	| j|	|||||||d}
|| |
d  }|f|
dd   }|S )N)r   r   r   r   r   r   r   r   r&   )r6   r   r   )rq   r{   attention_maskr   r   r   r   r   r   normed_hidden_statesattention_outputr   r+   r+   r.   r|   I  s   

zT5LayerSelfAttention.forwardr   )NNNNFFNr}   r~   r   r   rV   rm   r|   r   r+   r+   rt   r.   r   @  s    r   c                       sB   e Zd Zddee f fddZ								d	ddZ  ZS )
T5LayerCrossAttentionNr   c                    s>   t    t|d|d| _t|j|jd| _t	|j
| _d S )NFr   r   )rl   rm   r   EncDecAttentionrj   r   r   r6   r   r   r   r   )rq   ra   r   rt   r+   r.   rm   e  s   
zT5LayerCrossAttention.__init__Fc                 C   sP   |  |}| j|||||||||	|
d
}|| |d  }|f|dd   }|S )N)	r   r   r   r   r   r   r   r   r   r   r&   )r6   r   r   )rq   r{   r   r   r   r   r   r   r   r   r   r   r   Zlayer_outputr   r+   r+   r.   r|   k  s    
zT5LayerCrossAttention.forwardr   )NNNNFNFNr   r+   r+   rt   r.   r   d  s    
r   c                       sJ   e Zd Zd	dee f fddZ												d
ddZ  ZS )T5BlockFNr   c                    s`   t    |j| _t | _| jt|||d | jr&| jt||d | jt	| d S )Nr   )r   )
rl   rm   r   r   
ModuleListr4   rK   r   r   r   r   rt   r+   r.   rm     s   

zT5Block.__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   r5   i  )r   maxr&   r0   )r   r   r   r   r   r   r   r   )r4   ry   r\   rz   r   isinfrM   finfor   clampr   )rq   r{   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   r+   r+   r.   r|     sn   

zT5Block.forwardr   )NNNNNNNNFFTNr   r+   r+   rt   r.   r     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 )	T5ClassificationHeadz-Head for sentence-level classification tasks.ra   c                    sB   t    t|j|j| _tj|jd| _t|j|j	| _
d S )N)r   )rl   rm   r   r   r   denser   classifier_dropoutr   
num_labelsout_projr   rt   r+   r.   rm     s   
zT5ClassificationHead.__init__r{   returnc                 C   s6   |  |}| |}t|}|  |}| |}|S r   )r   r   r\   tanhr   r   r+   r+   r.   r|     s   




zT5ClassificationHead.forward)
r}   r~   r   __doc__r'   rm   r\   r   r|   r   r+   r+   rt   r.   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 )T5PreTrainedModeltransformerTFr   r   c                 C   s$   t t}t t}|||d}|S )N)decoder_input_ids	input_idsdecoder_attention_mask)r\   Ztensorr   r   )rq   r  Z
input_maskdummy_inputsr+   r+   r.   r	    s   

zT5PreTrainedModel.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      ?        )rx   Zstdr=   
qa_outputs      r:   r9   N))ra   Zinitializer_factorr   rj   r3   r^   Zfill_T5ModelT5ForConditionalGenerationT5EncoderModelT5ForQuestionAnsweringsharedZnormal_rR   tie_word_embeddingsr=   r  r   r9   Zzero_T5ForTokenClassificationr:   r   r   r   r   r>   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )rq   modulefactorr   r   r   r+   r+   r.   _init_weights  st   


 


          
zT5PreTrainedModel._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 T5 it is usually set to the pad_token_id. See T5 docs for more information.r0   )r&   .r   r&   ).r   z1self.model.config.pad_token_id has to be defined.)ra   decoder_start_token_idpad_token_idrY   r!   r\   fullrW   catZ	new_zeroscloneZmasked_fill_)rq   r  r  r  Zshifted_input_idsr+   r+   r.   _shift_rightU  s      zT5PreTrainedModel._shift_rightN)r}   r~   r   r'   Zconfig_classri   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  r+   r+   r+   r.   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 ) T5StackNc                    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ra   r+   r.   
<listcomp>y  s   " z$T5Stack.__init__.<locals>.<listcomp>r   F)rl   rm   embed_tokensr   r   r   range
num_layersblockrj   r   r   r7   r   r   r   	post_initmodel_parallel
device_mapr   )rq   ra   r$  rt   r"  r.   rm   r  s   
zT5Stack.__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<  `T5Stack.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%   rS   r'  r%  r\   cudadevice_countr*  r$   r)  r_   strr   first_devicer   last_deviceitemsrv   r$  r7   )rq   r*  r   r   r4   Zcuda_devicer+   r+   r.   parallelize  s"   $	*zT5Stack.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*  r3  r4  r%  rS   r'  rv   r$  r7   r\   r0  empty_cache)rq   r!  r+   r+   r.   deparallelize  s   zT5Stack.deparallelizec                 C      | j S r   r$  rq   r+   r+   r.   get_input_embeddings     zT5Stack.get_input_embeddingsc                 C   
   || _ d S r   r;  rq   Znew_embeddingsr+   r+   r.   set_input_embeddings     
zT5Stack.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 timer0   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   )ry   r
  r   r+   )r   r   r   r   r   r   r   r   r   r   r   r   r&   r   r5      r
      r,  c                 s   s    | ]	}|d ur|V  qd S r   r+   )r,   r   r+   r+   r.   r/     s    z"T5Stack.forward.<locals>.<genexpr>)last_hidden_statepast_key_valuesr{   
attentionscross_attentions)4r)  r\   r0  
set_devicer3  r$  rv   ra   r   r   output_hidden_statesuse_return_dictr   rY   sizer   r   r   rD   r   r   r   r   r   Zfrom_legacy_cacheget_seq_lengthr   r   r"   ro   _update_causal_maskr   ry   r   r   r   Zinvert_attention_maskZget_head_maskr&  r   	enumerater'  Z_gradient_checkpointing_funcr|   r*  r5  r2  r4  r7   Zto_legacy_cachetupler   )+rq   r  r   r   r   rD  	head_maskcross_attn_head_maskrI  r   r   rM  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   r{   r!  Zlayer_moduler   r   Zlayer_outputsZnext_decoder_cacher   r   Z
next_cacher+   r+   r.   r|     sl  

















"


zT5Stack.forwardFr   r(   input_tensorr   rI  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)rD  rV  Zis_trainingr&   r0   )sequence_lengthtarget_lengthry   r   r   )r0  ZxpuZnpu)ra   Z_attn_implementationrM   r   r\   r   r)   rP  Zis_compileabler   Z_ignore_causal_mask_sdpar   ry   rW   Zget_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positionr   typer   r   Z_unmask_unattended)rq   r   rX  r   rI  r   Zpast_seen_tokensZusing_compilable_cachery   rY  rZ  r   	min_dtyper+   r+   r.   rQ    sT   




zT5Stack._update_causal_maskrY  rZ  ry   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.
        NrF  )Z
fill_valuery   r   r&   )ZdiagonalrE  r0   r   )r   r\   r   r   r  r   Ztriur   Zreshapeexpandr  rW   rv   Zmasked_fill)r   rY  rZ  ry   r   r   kwargsr   r]  Zmask_lengthZpadding_maskr+   r+   r.   r[    s,    $
6  z=T5Stack._prepare_4d_causal_attention_mask_with_cache_positionr   )NNNNNNNNNNNNN)F)r}   r~   r   rm   r   PARALLELIZE_DOCSTRINGr6  DEPARALLELIZE_DOCSTRINGr9  r=  rA  r|   r   r\   r   r   r   rQ  r   rV   ry   r[  r   r+   r+   rt   r.   r   q  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                &       sl  e Zd 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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  Fdecoder.block.0.layer.1.EncDecAttention.relative_attention_bias.weightencoder.embed_tokens.weightdecoder.embed_tokens.weightra   c                    s   t  | t|j|j| _t|}d|_	d|_
d|_t|| j| _t|}d|_	d|_|j|_t|| j| _|   d| _d | _d S NFT)rl   rm   r   r   
vocab_sizer   r  copydeepcopyr   r   is_encoder_decoderr   encodernum_decoder_layersr&  r;   r(  r)  r*  rq   ra   encoder_configZdecoder_configrt   r+   r.   rm   <  s   


zT5Model.__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%   rS   rj  r'  r%  r\   r0  r1  r*  r$   r6  r;   r)  rq   r*  r+   r+   r.   r6  S  s   	
zT5Model.parallelizec                 C   sV   t dt | j  | j  | jd| _| jd| _d| _d | _t	j
  d S Nr7  r+  F)r-  r.  r/  rj  r9  r;   rv   r)  r*  r\   r0  r8  r<  r+   r+   r.   r9  f  s   

zT5Model.deparallelizec                 C   r:  r   r  r<  r+   r+   r.   r=  t  r>  zT5Model.get_input_embeddingsc                 C   "   || _ | j| | j| d S r   r  rj  rA  r;   r@  r+   r+   r.   rA  w     zT5Model.set_input_embeddingsc                 C   4   | j jr| | jj| j | | jj| j d S d S r   ra   r  _tie_or_clone_weightsrj  r$  r  r;   r<  r+   r+   r.   _tie_weights|     zT5Model._tie_weightsc                 C   r:  r   rj  r<  r+   r+   r.   get_encoder  r>  zT5Model.get_encoderc                 C   r:  r   r;   r<  r+   r+   r.   get_decoder  r>  zT5Model.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)r5  rj  r4   Z	attentionr   rq   Zheads_to_pruner4   r   r+   r+   r.   _prune_heads  s   zT5Model._prune_headsr  r   r  r  rT  decoder_head_maskrU  encoder_outputsrI  rD  decoder_inputs_embedsr   r   rM  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. 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**.

        Example:

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

        >>> tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-small")
        >>> model = T5Model.from_pretrained("google-t5/t5-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 T5Model.
        >>> # This is not needed for torch's T5ForConditionalGeneration 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   rD  rT  r   rM  r   r   r&   r5   rH  r{   rJ  r  r   rD  rI  r   r   rT  rU  r   r   rM  r   r   )rH  rI  decoder_hidden_statesdecoder_attentionsrK  encoder_last_hidden_stater   encoder_attentions)ra   r   rN  r&  rk  r-  r.  Z_T5Model__HEAD_MASK_WARNING_MSGr/  rj  r   r   rS   r)  r\   r0  rL  r;   r3  rv   r   rH  rI  r{   rJ  rK  )rq   r  r   r  r  rT  r  rU  r  rI  rD  r  r   r   rM  r   r   r{   decoder_outputsr+   r+   r.   r|     sv   Q	zT5Model.forwardr   NNNNNNNNNNNNNNNN)r}   r~   r   "_keys_to_ignore_on_load_unexpected_tied_weights_keysr'   rm   r   r`  r6  ra  r9  r=  rA  rw  rz  r|  r  r   r   r\   
LongTensorFloatTensor
BoolTensorr   r   r   r   r   r|   r   r+   r+   rt   r.   r  5  s    
	
r  z:
    T5 Model with a `language modeling` head on top.
    )Zcustom_introc                (       s  e Zd 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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  rb  )rc  rd  zlm_head.weightra   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 )NFTr   )rl   rm   r   	model_dimr   r   rf  r  rg  rh  r   r   ri  r   rj  rk  r&  r;   r   r=   r(  r)  r*  rl  rt   r+   r.   rm   3  s"   


z#T5ForConditionalGeneration.__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%   rS   rj  r'  r%  r\   r0  r1  r*  r$   r6  r;   r=   rv   r3  r)  rn  r+   r+   r.   r6  N  s   	
z&T5ForConditionalGeneration.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  r9  r;   rv   r=   r)  r*  r\   r0  r8  r<  r+   r+   r.   r9  b  s   

z(T5ForConditionalGeneration.deparallelizec                 C   r:  r   rp  r<  r+   r+   r.   r=  q  r>  z/T5ForConditionalGeneration.get_input_embeddingsc                 C   rq  r   rr  r@  r+   r+   r.   rA  t  rs  z/T5ForConditionalGeneration.set_input_embeddingsc                 C   rt  r   ru  r<  r+   r+   r.   rw  y  rx  z'T5ForConditionalGeneration._tie_weightsc                 C   r?  r   r=   r@  r+   r+   r.   set_output_embeddings~  rB  z0T5ForConditionalGeneration.set_output_embeddingsc                 C   r:  r   r  r<  r+   r+   r.   get_output_embeddings  r>  z0T5ForConditionalGeneration.get_output_embeddingsc                 C   r:  r   ry  r<  r+   r+   r.   rz    r>  z&T5ForConditionalGeneration.get_encoderc                 C   r:  r   r{  r<  r+   r+   r.   r|    r>  z&T5ForConditionalGeneration.get_decoderr  r   r  r  rT  r  rU  r  rI  rD  r  labelsr   r   rM  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. 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**.
        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, T5ForConditionalGeneration

        >>> tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-small")
        >>> model = T5ForConditionalGeneration.from_pretrained("google-t5/t5-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&   r5   r  r  r  r  Zignore_indexr0   	lossr<   rI  r  r  rK  r  r   r  )#ra   r   rN  r&  rk  r-  r.  Z2_T5ForConditionalGeneration__HEAD_MASK_WARNING_MSGr/  rj  r   r   rS   r)  r\   r0  rL  r;   r3  r  rv   r=   r3   r   r  r  r   r   rO  r   rI  r{   rJ  rK  rH  )rq   r  r   r  r  rT  r  rU  r  rI  rD  r  r  r   r   rM  r   r   r{   r  sequence_outputZ	lm_logitsr  loss_fctoutputr+   r+   r.   r|     s   X	



z"T5ForConditionalGeneration.forwardc                 C   s
   |  |S r   )r  )rq   r  r+   r+   r.   %prepare_decoder_input_ids_from_labelsJ  rB  z@T5ForConditionalGeneration.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 decodingr+   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 )rD   warningZindex_selectrv   r   rW   rY   rS   )rq   rI  Zbeam_idxZreordered_decoder_pastZlayer_past_statesZreordered_layer_past_statesZlayer_past_stater+   r+   r.   _reorder_cacheM  s(   
z)T5ForConditionalGeneration._reorder_cacher   )NNNNNNNNNNNNNNNNN)"r}   r~   r   r  r  r'   rm   r   r`  r6  ra  r9  r=  rA  rw  r  r  rz  r|  r   r   r\   r  r  r  r   r   r   r   r   r|   r  r  r   r+   r+   rt   r.   r  (  s    
	
 @r  c                       s   e Zd Zdg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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  rc  r;   ra   c                    sZ   t  | t|j|j| _t|}d|_	d|_
t|| j| _|   d| _d | _d S NF)rl   rm   r   r   rf  r   r  rg  rh  r   ri  r   rj  r(  r)  r*  )rq   ra   rm  rt   r+   r.   rm   q  s   

zT5EncoderModel.__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%   rS   rj  r'  r%  r\   r0  r1  r*  r$   r6  r)  rn  r+   r+   r.   r6    s   	
zT5EncoderModel.parallelizec                 C   s>   t dt | j  | jd| _d| _d | _tj	
  d S ro  )r-  r.  r/  rj  r9  rv   r)  r*  r\   r0  r8  r<  r+   r+   r.   r9    s   
zT5EncoderModel.deparallelizec                 C   r:  r   rp  r<  r+   r+   r.   r=    r>  z#T5EncoderModel.get_input_embeddingsc                 C   s   || _ | j| d S r   )r  rj  rA  r@  r+   r+   r.   rA    s   z#T5EncoderModel.set_input_embeddingsc                 C   s"   | j jr| | jj| j d S d S r   )ra   r  rv  rj  r$  r  r<  r+   r+   r.   rw    s   zT5EncoderModel._tie_weightsc                 C   r:  r   ry  r<  r+   r+   r.   rz    r>  zT5EncoderModel.get_encoderc                 C   s0   |  D ]\}}| jj| jd j| qdS )r}  r   N)r5  rj  r'  r4   r   r   r~  r+   r+   r.   r    s   zT5EncoderModel._prune_headsr  r   rT  rD  r   rM  r   r  c           	   	   C   s0   |dur|n| j j}| j|||||||d}|S )aI  
        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.

            To know more on how to prepare `input_ids` for pretraining take a look a [T5 Training](./t5#training).

        Example:

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

        >>> tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-small")
        >>> model = T5EncoderModel.from_pretrained("google-t5/t5-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  )ra   rN  rj  )	rq   r  r   rT  rD  r   rM  r   r  r+   r+   r.   r|     s   "
zT5EncoderModel.forwardr   )NNNNNNN)r}   r~   r   r  r  r'   rm   r   r`  r6  ra  r9  r=  rA  rw  rz  r  r   r   r\   r  r  r   r   r   r   r|   r   r+   r+   rt   r.   r  l  sL    
	r  z
    T5 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 )T5ForSequenceClassificationrb  rc  rd  ra   c                    s2   t  | t|| _t|| _|   d| _d S r  )rl   rm   r  r  r   classification_headr(  r)  r   rt   r+   r.   rm     s
   


z$T5ForSequenceClassification.__init__Nr  r   r  r  rT  r  rU  r  rD  r  r  r   r   rM  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 )ag
  
        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**.
        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  rT  r  rU  r  rD  r  r   r   rM  r   r   r&   z7All examples must have the same number of <eos> tokens.r0   Z
regressionZsingle_label_classificationZmulti_label_classificationr  )$ra   rN  NotImplementedErrorru   r}   rY   r  r  eqZeos_token_idrv   r   rS   r\   Zunique_consecutivesumrW   r   r  Zproblem_typer   ry   r   rV   r	   squeezer   r   r   rI  r  r  rK  r  r   r  )rq   r  r   r  r  rT  r  rU  r  rD  r  r  r   r   rM  r   r   r  Zeos_maskr   rW  rr   Zsentence_representationr<   r  r  r  r+   r+   r.   r|     s   >
,


$

z#T5ForSequenceClassification.forward)NNNNNNNNNNNNNNN)r}   r~   r   r  r  r'   rm   r   r   r\   r  r   r   r  r   r   r   r   r|   r   r+   r+   rt   r.   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.weightra   c                    sJ   t  | |j| _t|| _t|j| _t	|j
|j| _|   d S r   )rl   rm   r   r  r  r   r   r   r   r   rr   r:   r(  r   rt   r+   r.   rm     s   
z!T5ForTokenClassification.__init__Nr  r   rT  rD  r  r   rM  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. 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).
        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   rT  rD  r   rM  r   r   r0   r5   )r  r<   r{   rJ  )ra   rN  r  r   r:   r   r   r   r   r{   rJ  )rq   r  r   rT  rD  r  r   rM  r   r   r{   r<   r  r  r  r+   r+   r.   r|     s4   


z T5ForTokenClassification.forward)NNNNNNNN)r}   r~   r   r  r'   rm   r   r   r\   r   r   r   r   r   r|   r   r+   r+   rt   r.   r    s>    	
r  c                &       s:  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
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  ra   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  )rl   rm   r   r  r   r   rf  r  rg  rh  r   r   ri  r   rj  rk  r&  r;   r   r   rr   r  r(  r)  rl  rt   r+   r.   rm     s"   


zT5ForQuestionAnswering.__init__c                 C   r:  r   rp  r<  r+   r+   r.   r=    r>  z+T5ForQuestionAnswering.get_input_embeddingsc                 C   rq  r   rr  r@  r+   r+   r.   rA    rs  z+T5ForQuestionAnswering.set_input_embeddingsc                 C   rt  r   ru  r<  r+   r+   r.   rw    rx  z#T5ForQuestionAnswering._tie_weightsc                 C   r:  r   ry  r<  r+   r+   r.   rz  	  r>  z"T5ForQuestionAnswering.get_encoderc                 C   r:  r   r{  r<  r+   r+   r.   r|  	  r>  z"T5ForQuestionAnswering.get_decoderNr  r   r  r  rT  r  rU  r  start_positionsend_positionsrD  r  r   r   rM  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&   r5   r  )r  r   rD  rI  r   r   rT  rU  r   r   rM  r   r0   r   r  )
r  start_logits
end_logitsrI  r  r  rK  r  r   r  )ra   rN  r   rY   r  r&  rk  r-  r.  Z._T5ForQuestionAnswering__HEAD_MASK_WARNING_MSGr/  rj  r   r   rS   r;   r  rL   r  r   rO  rv   r   r   r   r   rI  r{   rJ  rK  rH  )rq   r  r   r  r  rT  r  rU  r  r  r  rD  r  r   r   rM  r   r{   r  r  r<   r  r  Z
total_lossZignored_indexr  Z
start_lossZend_lossr  r+   r+   r.   r|   
	  s   <
	




zT5ForQuestionAnswering.forwardr  )r}   r~   r   r  r  r'   rm   r=  rA  rw  rz  r|  r   r   r\   r  r  r  r   r   r   r   r   r|   r   r+   r+   rt   r.   r    sz    	
r  )r  r  r  r  ri   r  r  r  )[r  rg  r   rF   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   r   utilsr   r   r   r   r    r!   r"   r#   Zutils.model_parallel_utilsr$   r%   Zconfiguration_t5r'   Z!torch.nn.attention.flex_attentionr(   Zintegrations.flex_attentionr)   Z
get_loggerr}   rD   ri   r`  ra  Modulerj   Zapex.normalizationr   rI   rC   	Exceptionr  rK   r   r   r   r   r   r   r   r   r  r   Z__HEAD_MASK_WARNING_MSGr  r  r  r  r  r  __all__r+   r+   r+   r.   <module>   s   $	(

n!

 e$&dp   ? s  Ay #I V