U
    9%e                    @   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 dd	l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( ddl)m*Z*m+Z+ ddl,m-Z- e'.e/Z0dZ1dZ2dddddgZ3dd Z4dZ5dZ6G dd dej7Z8zddl9m:Z: e:Z8e0;d W n4 e<k
rr   Y n  e=k
r   e0>d Y nX e?e8 G dd  d ej7Z@G d!d" d"ej7ZAG d#d$ d$ej7ZBG d%d& d&ej7ZCG d'd( d(ej7ZDG d)d* d*ej7ZEG d+d, d,ej7ZFG d-d. d.ej7ZGG d/d0 d0eZHG d1d2 d2eHZId3ZJd4ZKd5ZLd6ZMe$d7eJG d8d9 d9eHZNe$d:eJG d;d< d<eHZOe$d=eJG d>d? d?eHZPe$d@eJG dAdB dBeHZQe$dCeJG dDdE dEeHZRdS )Fz PyTorch T5 model.    N)ListOptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss)
checkpoint   )ACT2FN)BaseModelOutput)BaseModelOutputWithPastAndCrossAttentionsSeq2SeqLMOutputSeq2SeqModelOutput#Seq2SeqQuestionAnsweringModelOutputSeq2SeqSequenceClassifierOutput)PreTrainedModel)ALL_LAYERNORM_LAYERS find_pruneable_heads_and_indicesprune_linear_layer)DUMMY_INPUTS
DUMMY_MASKadd_start_docstrings%add_start_docstrings_to_model_forwardis_torch_fx_proxyloggingreplace_return_docstrings)assert_device_mapget_device_map   )T5Configr!   zt5-smallzt5-basezt5-largezt5-3bzt5-11bc                 C   s|  zddl }ddl}ddl}W n  tk
r<   td  Y nX tj|}t	d|  |j
|}g }i }	|D ]>\}
}t	d|
 d|  |j
||
}||
 ||	|
< qr|D ]}|d}
tdd	 |
D rt	d
d|
  |	|d qd|
d kr.t	d
d|
  |	|d q| }|	| }|
D ]6}|d|r`|d|}n|g}|d dkrt|d}n|d dkrt|d}|d }n|d dkrt|d}|d }n|d dkrt|d}|d }nd|d dkr.t|drt|d}nt|drRt|d}n$|d dkrJt|d}n|d dksf|d dkrrt|d}n|d dkrt|d}n|d d kr|
d d!krq>n|d d!krt|d"}n|d d#krt|dkr|d  rt|d$|d  }q>nFzt||d }W n2 tk
rP   t	d
d|
  Y q>Y nX t|dkr>t|d }|| }q>|d dkrt|d}|d d%krt	d&|j d'|
  ||}z,|j|jkrtd(|j d)|j d*W n< tk
r( } z| j|j|jf7  _ W 5 d}~X Y nX t	d+|
  t| |j!|_"|	|d qt	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 kV  qdS ))Zadam_vZadam_mZAdamWeightDecayOptimizerZAdamWeightDecayOptimizer_1Zglobal_stepN ).0nr#   r#   a/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/transformers/models/t5/modeling_t5.py	<genexpr>i   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_normr)   Zoutput_biasbetabiasZsquad
classifierdecoderlogitslm_headwiZ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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_pathr9   nptfZtf_pathZ	init_varsnamesZ
tf_weightsnamerO   arrayZtxt_nameZpointerZm_nameZscope_namesnumer#   r#   r&   load_tf_weights_in_t5L   s    







*

ra   a  
    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, defaults to None):
            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:

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

    Example:

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

    Example:

    ```python
    # On a 4 GPU machine with t5-3b:
    model = T5ForConditionalGeneration.from_pretrained("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   	ParameterrT   onesr+   variance_epsilon)selfhidden_sizeeps	__class__r#   r&   re      s    
zT5LayerNorm.__init__c                 C   s\   | tjdjddd}|t|| j  }| jjtj	tj
fkrR| | jj}| j| S )Nr-   r(   T)Zkeepdim)torT   rU   powmeanZrsqrtrh   r+   dtypefloat16Zbfloat16)ri   hidden_statesZvariancer#   r#   r&   forward   s
    zT5LayerNorm.forward)rc   __name__
__module____qualname__re   rt   __classcell__r#   r#   rl   r&   rb      s   rb   )FusedRMSNormzODiscovered apex.normalization.FusedRMSNorm - will use it instead of T5LayerNormzBdiscovered apex but it failed to load, falling back to T5LayerNormc                       s*   e Zd Zed fddZdd Z  ZS )T5DenseActDenserY   c                    sT   t    tj|j|jdd| _tj|j|jdd| _t|j	| _
t|j | _d S NFr1   )rd   re   r   Lineard_modeld_ffr6   woDropoutdropout_ratedropoutr   dense_act_fnactri   rY   rl   r#   r&   re     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)r6   r   r   
isinstancer   r+   rT   Tensorrq   int8rn   ri   rs   r#   r#   r&   rt      s    



zT5DenseActDense.forwardrv   rw   rx   r!   re   rt   ry   r#   r#   rl   r&   r{     s   r{   c                       s*   e Zd Zed fddZdd Z  ZS )T5DenseGatedActDenser|   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}   )rd   re   r   r   r   r   wi_0wi_1r   r   r   r   r   r   r   r   rl   r#   r&   re   /  s    
zT5DenseGatedActDense.__init__c                 C   sz   |  | |}| |}|| }| |}t| jjtjrl|j	| jjj	krl| jjj	tj
krl|| jjj	}| |}|S r   )r   r   r   r   r   r   r+   rT   r   rq   r   rn   )ri   rs   Zhidden_geluZhidden_linearr#   r#   r&   rt   7  s    


zT5DenseGatedActDense.forwardr   r#   r#   rl   r&   r   .  s   r   c                       s*   e Zd Zed fddZdd Z  ZS )	T5LayerFFr|   c                    sJ   t    |jrt|| _n
t|| _t|j|jd| _	t
|j| _d S )Nrk   )rd   re   Zis_gated_actr   DenseReluDenser{   rb   r   layer_norm_epsilonr.   r   r   r   r   r   rl   r#   r&   re   L  s    

zT5LayerFF.__init__c                 C   s&   |  |}| |}|| | }|S r   )r.   r   r   )ri   rs   Zforwarded_statesr#   r#   r&   rt   V  s    

zT5LayerFF.forwardr   r#   r#   rl   r&   r   K  s   
r   c                       sN   e Zd Zded fddZdd Zedd
dZdddZdddZ	  Z
S )T5AttentionFr|   c                    s   t    |j| _|| _|j| _|j| _|j| _|j| _|j	| _
|j| _| j
| j | _tj| j| jdd| _tj| j| jdd| _tj| j| jdd| _tj| j| jdd| _| jrt| j| j
| _t | _d| _d S r}   )rd   re   
is_decoderhas_relative_attention_biasrelative_attention_num_bucketsrelative_attention_max_distancer   d_kvkey_value_proj_dim	num_headsn_headsr   r   	inner_dimr   r   qkvo	Embeddingrelative_attention_biassetpruned_headsgradient_checkpointingri   rY   r   rl   r#   r&   re   ^  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)rK   r   r   r   r   r   r   r   r   r   r   union)ri   headsindexr#   r#   r&   prune_headsu  s       zT5Attention.prune_headsT       c                 C   s   d}|r4|d }|| dk tj| 7 }t| } nt| t|  } |d }| |k }|t|  | t||  ||   tj }t|t	||d }|t
|| |7 }|S )a  
        Adapted from Mesh Tensorflow:
        https://github.com/tensorflow/mesh/blob/0cb87fe07da627bf0b7e60475d59f95ed6b5be3d/mesh_tensorflow/transformer/transformer_layers.py#L593

        Translate relative position to a bucket number for relative attention. The relative position is defined as
        memory_position - query_position, i.e. the distance in tokens from the attending position to the attended-to
        position. If bidirectional=False, then positive relative positions are invalid. We use smaller buckets for
        small absolute relative_position and larger buckets for larger absolute relative_positions. All relative
        positions >=max_distance map to the same bucket. All relative positions <=-max_distance map to the same bucket.
        This should allow for more graceful generalization to longer sequences than the model has been trained on

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

        Returns:
            a Tensor with the same shape as relative_position, containing int32 values in the range [0, num_buckets)
        r   r-   r    )rn   rT   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_bucketNc           	      C   s   |dkr| j jj}tj|tj|ddddf }tj|tj|ddddf }|| }| j|| j | j| j	d}|  |}|
dddgd}|S )z%Compute binned relative position biasN)rq   device)r   r   r   r-   r   r    )r   r+   r   rT   Zaranger   r   r   r   r   ZpermuteZ	unsqueeze)	ri   query_length
key_lengthr   Zcontext_positionZmemory_positionr   Zrelative_position_bucketvaluesr#   r#   r&   compute_bias  s    

zT5Attention.compute_biasc
                    s~  |j dd \ }
|
}|dk	r\t|dkr>tdt| d||dkrV|d j d n|7 }|dkrh|n|j d } fdd fd	d
}fdd}|}||j||dk	r|d nd}||j||dk	r|d nd}t||dd}|dkrj	sDtj
dj||f|j|jd}jrVjrVd|_nj|||jd}|dk	r|dddd|d dddf }|dk	r|| }jrt|j d }d|tj< |dd| f }n|}||7 }tjj| dd|}tjj|jjd}|dk	r$|| }|t||}|}jrT|rT||fnd}|f|f |f }|	rz||f }|S )z
        Self-attention (if key_value_states is None) or attention over source sentence (provided by key_value_states).
        Nr-   z?past_key_value should have 2 past states: keys and values. Got z past statesr   r    c                    s   |   djjddS )Z
projectionr(   r    r-   )viewr   r   rP   Zstates
batch_sizeri   r#   r&   rO     s    z"T5Attention.forward.<locals>.shapec                    s   |  dd  djS )Zreshaper    r-   r(   )rP   
contiguousr   r   r   r   r#   r&   unshape  s    z$T5Attention.forward.<locals>.unshapec                    sx   |dkr || } n|dkr* ||} |dk	rt|dkrNt j|| gdd} n&|jd |jd krp ||} n|} | S )z4projects hidden states correctly to key/query statesNr-   r   r    )rT   catrO   )rs   Z
proj_layerkey_value_statespast_key_value)rO   r#   r&   project  s    z$T5Attention.forward.<locals>.projectr   r   rq   Tr   r(   r   )ptraining)rO   rK   rQ   r   r   r   rT   matmulrP   r   Zzerosr   r   rq   r   r   Zrequires_gradr   sizer   rg   listboolr   Z
functionalZsoftmaxr   Ztype_asr   r   r   )ri   rs   maskr   position_biasr   layer_head_maskr   	use_cacheoutput_attentions
seq_lengthZreal_seq_lengthr   r   r   Zquery_statesZ
key_statesZvalue_statesZscoresZposition_bias_maskedZattn_weightsZattn_outputpresent_key_value_stateoutputsr#   )r   ri   rO   r&   rt     s           

  
(
  


zT5Attention.forward)F)Tr   r   )N)NNNNNNFF)rv   rw   rx   r!   re   r   staticmethodr   r   rt   ry   r#   r#   rl   r&   r   ]  s   /
        r   c                       s(   e Zd Zd fdd	ZdddZ  ZS )	T5LayerSelfAttentionFc                    s<   t    t||d| _t|j|jd| _t	|j
| _d S )Nr   r   )rd   re   r   SelfAttentionrb   r   r   r.   r   r   r   r   r   rl   r#   r&   re   I  s    
zT5LayerSelfAttention.__init__Nc              	   C   sJ   |  |}| j|||||||d}	|| |	d  }|f|	dd   }
|
S )N)r   r   r   r   r   r   r   r    )r.   r   r   )ri   rs   attention_maskr   r   r   r   r   normed_hidden_statesattention_outputr   r#   r#   r&   rt   O  s    

	zT5LayerSelfAttention.forward)F)NNNNFFru   r#   r#   rl   r&   r   H  s   	      r   c                       s&   e Zd Z fddZdddZ  ZS )T5LayerCrossAttentionc                    s<   t    t|dd| _t|j|jd| _t	|j
| _d S )NFr   r   )rd   re   r   EncDecAttentionrb   r   r   r.   r   r   r   r   r   rl   r#   r&   re   i  s    
zT5LayerCrossAttention.__init__NFc
                 C   sN   |  |}
| j|
||||||||	d	}|| |d  }|f|dd   }|S )N)r   r   r   r   r   r   r   r   r   r    )r.   r   r   )ri   rs   r   r   r   r   r   r   r   r   r   r   Zlayer_outputr   r#   r#   r&   rt   o  s    
zT5LayerCrossAttention.forward)NNNNFNFru   r#   r#   rl   r&   r   h  s   
       r   c                       s(   e Zd Zd fdd	Zd	ddZ  ZS )
T5BlockFc                    sZ   t    |j| _t | _| jt||d | jrF| jt| | jt	| d S )Nr   )
rd   re   r   r   
ModuleListr,   rC   r   r   r   r   rl   r#   r&   re     s    

zT5Block.__init__NTc                 C   sb  |	d k	rz| j std |d kr$dnd}t|	|kr`td| d|dkrJdnd dt|	 d	|	d d }|	dd  }nd
\}}| jd ||||||
|d}|d d \}}|dd  }|jtjkr
t	t
| t|jjd t|jj}tj|| |d}| j o|d k	}|r|d k	r:|d jd }nd }| jd ||||||||
|d	}|d }|jtjkrt	t
| t|jjd t|jj}tj|| |d}|d k	r||d  }||dd   }| jd |}|jtjkr:t	t
| t|jjd t|jj}tj|| |d}|f}|
rV||f | }n|| }|S )NzN`past_key_values` is passed to the encoder. Please make sure this is intended.r-      zThere should be z past states. z$2 (past / key) for cross attention.  zGot z past key / value states)NNr   )r   r   r   r   r   r   i  )r   maxr    )r   r   r   r   r   r   r   r   r(   )r   r<   warningrK   rQ   r,   rq   rT   rr   r   isinfrE   Zfinfor   clamprO   )ri   rs   r   r   encoder_hidden_statesencoder_attention_maskencoder_decoder_position_biasr   cross_attn_layer_head_maskr   r   r   return_dictZexpected_num_past_key_valuesZself_attn_past_key_valueZcross_attn_past_key_valueZself_attention_outputsr   Zattention_outputsZclamp_valueZdo_cross_attentionr   Zcross_attention_outputsr   r#   r#   r&   rt     s    
&	

zT5Block.forward)F)NNNNNNNNFFTru   r#   r#   rl   r&   r     s              r   c                       s:   e Zd ZdZed fddZejejdddZ  Z	S )T5ClassificationHeadz-Head for sentence-level classification tasks.r|   c                    sB   t    t|j|j| _tj|jd| _t|j|j	| _
d S )N)r   )rd   re   r   r   r   denser   Zclassifier_dropoutr   
num_labelsout_projr   rl   r#   r&   re     s    
zT5ClassificationHead.__init__)rs   returnc                 C   s6   |  |}| |}t|}|  |}| |}|S r   )r   r   rT   tanhr   r   r#   r#   r&   rt     s    




zT5ClassificationHead.forward)
rv   rw   rx   __doc__r!   re   rT   r   rt   ry   r#   r#   rl   r&   r     s   r   c                   @   sV   e Zd ZdZeZeZdZdZ	dZ
dgZdgZedd Zdd	 ZdddZdd ZdS )T5PreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    transformerTr   r   c                 C   s$   t t}t t}|||d}|S )N)decoder_input_ids	input_idsdecoder_attention_mask)rT   Ztensorr   r   )ri   r   Z
input_maskdummy_inputsr#   r#   r&   r   (  s    

zT5PreTrainedModel.dummy_inputsc                 C   s  | j j}t|tr(|jj|d  nt|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  nt|tr\|jjjjd|| j jd  d t|jdr|jjdk	r|jjj  |jjjjd|| j jd  d t|jdr|jjdk	r|jjj  nPt|tr |jjjjd|| j jd  d t|jdr|jjdk	r|jjj  |jjjjd|| j jd  d t|jdr|jjdk	r|jjj  nt|tr|jjjjd|| j jd  d t|jdrV|jjdk	rV|jjj  |jjjjd|| j jd  d t|jdr|jjdk	r|jjj  |jjjjd|| j jd  d t|jdr|jjdk	r|jjj  nt|t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 )	zInitialize the weightsg      ?g        )rp   Zstdr5   
qa_outputs      r1   N)'rY   Zinitializer_factorr   rb   r+   rV   Zfill_T5ModelT5ForConditionalGenerationT5EncoderModelT5ForQuestionAnsweringsharedZnormal_rJ   tie_word_embeddingsr5   r   r   r1   Zzero_r   r   r   r{   r6   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )ri   modulefactorr   r   r   r#   r#   r&   _init_weights3  s^    


          zT5PreTrainedModel._init_weightsFc                 C   s   t |ttfr||_d S r   )r   r   T5Stackr   )ri   r  valuer#   r#   r&   _set_gradient_checkpointingl  s    z-T5PreTrainedModel._set_gradient_checkpointingc                 C   s   | j j}| j j}|d kr tdt|rbt|jd d d |}tj||dd df gdd}n4|	|j}|dd df 
 |ddd f< ||d< |d krtd||d	k| |S )
Nzself.model.config.decoder_start_token_id has to be defined. In T5 it is usually set to the pad_token_id.See T5 docs for more information.r(   )r    .r   r    ).r   z1self.model.config.pad_token_id has to be defined.)rY   decoder_start_token_idpad_token_idrQ   r   rT   fullrO   r   Z	new_zeroscloneZmasked_fill_)ri   r   r  r  Zshifted_input_idsr#   r#   r&   _shift_rightp  s       zT5PreTrainedModel._shift_rightN)F)rv   rw   rx   r   r!   config_classra   Zload_tf_weightsZbase_model_prefixZis_parallelizableZsupports_gradient_checkpointingZ_no_split_modulesZ_keep_in_fp32_modulespropertyr   r
  r  r  r#   r#   r#   r&   r     s   

9
r   c                       sZ   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  ZS )r  Nc                    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$   ir|   r#   r&   
<listcomp>  s     z$T5Stack.__init__.<locals>.<listcomp>r   F)rd   re   embed_tokensr   r   r   range
num_layersblockrb   r   r   r/   r   r   r   	post_initmodel_parallel
device_mapr   )ri   rY   r  rl   r|   r&   re     s    zT5Stack.__init__c                 C   s   t dt |d kr.tt| jttj	 n|| _
t| j
t| j d| _d| j
 kr^dndtt| j
  | _dtt| j
  | _| j
 D ]4\}}|D ]&}dt| }| j| || j|< qq| 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   rK   r  r  rT   cudadevice_countr  r   r  rW   strr   first_devicer   last_deviceitemsrn   r  r/   )ri   r  r   r   r,   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	|< q2| 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  r'  r(  r  rK   r  rn   r  r/   rT   r$  empty_cache)ri   r  r#   r#   r&   deparallelize  s    zT5Stack.deparallelizec                 C   s   | j S r   r  ri   r#   r#   r&   get_input_embeddings  s    zT5Stack.get_input_embeddingsc                 C   s
   || _ d S r   r.  ri   Znew_embeddingsr#   r#   r&   set_input_embeddings  s    zT5Stack.set_input_embeddingsc           *         s~  | j r$tj| j | j| j| _d k	r0n| jj d k	rD n| jj	 |d k	rX|n| jj
}|d k	rl|n| jj}|d k	r|d k	r| jrdnd}td| d| dn`|d k	r| }|d|d }n>|d k	r| d d }n$| jrdnd}td| d| d	|d kr2| jd kr(td
| |}|\}}|d k	rZ|d d jd | n|}dkr| jstd|  d|d krtj|||jd}| jr|d kr|d k	r|jd }tj|||jtjd}|d krd gt| j }| ||}| jrL|d k	rL| \}}}||f}|d kr@tj||jd}| |}nd }| jrt| jrtrttd d| || jj}| || jj}rdnd }|rdnd } rdnd } r| jrdnd }d }d }| |}tt | j|D ],\} \}!}"||  }#||  }$| j rtj|j |d k	r@||j}|d k	rV||j}|d k	rl||j}|d k	r||j}|d k	r||j}|#d k	r|#|j}#|$d k	r|$|j}$|r||f }| jr| jr fdd}%t!|%|!|||||||#|$d 
}&n|!|||||||#|$|" d}&dkrV|&d d d |&dd   }&|&d d \}}'|&d }| jr|d k	r|& rdnd }r||'f } r||&d f }| jr||&d f }| j r| j"# D ]B\}(})| |)d krdt$|( | j%kr|dt$|(d  }qސq| &|}| |}|rJ||f }|slt'dd |||||fD S t(|||||d S )!NZdecoder_r   zYou cannot specify both zinput_ids and zinputs_embeds at the same timer(   zYou have to specify either zinput_ids or inputs_embedsz<You have to initialize the model with valid token embeddingsr   r-   Tz)`use_cache` can only be set to `True` if z is used as a decoderr   r    r   zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fr#   c                    s    fdd}|S )Nc                     s   t  | f S r   )tuple)inputs)r  r   r   r#   r&   custom_forwardQ  s    zFT5Stack.forward.<locals>.create_custom_forward.<locals>.custom_forwardr#   )r  r6  r   r   )r  r&   create_custom_forwardP  s    z.T5Stack.forward.<locals>.create_custom_forward)
r   r   r   r   r   r   r   r   r   r   r   r   r      r   c                 s   s   | ]}|d k	r|V  qd S r   r#   )r$   r   r#   r#   r&   r'     s   z"T5Stack.forward.<locals>.<genexpr>)last_hidden_statepast_key_valuesrs   
attentionscross_attentions))r  rT   r$  
set_devicer'  r  rn   rY   r   r   output_hidden_statesuse_return_dictr   rQ   r   r   rO   rg   r   r   rK   r  Zget_extended_attention_maskZinvert_attention_maskr   r   r<   Zwarning_onceZget_head_maskr  r   	enumeratezipr
   r  r)  r&  r(  r/   r4  r   )*ri   r   r   r   r   r3  	head_maskcross_attn_head_maskr;  r   r   r?  r   Zerr_msg_prefixZinput_shaper   r   Zmask_seq_lengthZencoder_seq_lengthZextended_attention_maskZencoder_batch_sizeZencoder_sequence_length_Zencoder_hidden_shapeZencoder_extended_attention_maskZpresent_key_value_statesZall_hidden_statesZall_attentionsZall_cross_attentionsr   r   rs   r  Zlayer_moduler   r   r   r8  Zlayer_outputsr   r   r   r#   r7  r&   rt     s(   

$


   












"


zT5Stack.forward)N)N)NNNNNNNNNNNN)rv   rw   rx   re   r   PARALLELIZE_DOCSTRINGr*  DEPARALLELIZE_DOCSTRINGr-  r0  r2  rt   ry   r#   r#   rl   r&   r    s(   
            r  a  

    The T5 model was proposed in [Exploring the Limits of Transfer Learning with a Unified Text-to-Text
    Transformer](https://arxiv.org/abs/1910.10683) by Colin Raffel, Noam Shazeer, Adam Roberts, Katherine Lee, Sharan
    Narang, Michael Matena, Yanqi Zhou, Wei Li, Peter J. Liu. It's an encoder decoder transformer pre-trained in a
    text-to-text denoising generative setting.

    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    Parameters:
        config ([`T5Config`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
a\  
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. 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).
        attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

            [What are attention masks?](../glossary#attention-mask)
        decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
            Indices of decoder input sequence tokens in the vocabulary.

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

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

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

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

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

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

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

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

        encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):
            Tuple consists of (`last_hidden_state`, `optional`: *hidden_states*, `optional`: *attentions*)
            `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)` is a sequence of hidden states at
            the output of the last layer of the encoder. Used in the cross-attention of the decoder.
        past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
            Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.

            If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
            don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
            `decoder_input_ids` of shape `(batch_size, sequence_length)`.
        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.
        decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded
            representation. If `past_key_values` is used, optionally only the last `decoder_inputs_embeds` have to be
            input (see `past_key_values`). This is useful if you want more control over how to convert
            `decoder_input_ids` indices into associated vectors than the model's internal embedding lookup matrix.

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

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

        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
a  
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. 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).
        attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

            [What are attention masks?](../glossary#attention-mask)
        head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
            Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:

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

        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
a_  
The input argument `head_mask` was split into two arguments `head_mask` and `decoder_head_mask`. Currently,
`decoder_head_mask` is set to copy `head_mask`, but this feature is deprecated and will be removed in future versions.
If you do not want to use any `decoder_head_mask` now, please set `decoder_head_mask = torch.ones(num_layers,
num_heads)`.
z\The bare T5 Model transformer outputting raw hidden-states without any specific head on top.c                       s,  e Zd ZdgZddgZed fddZ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eeeeddeej eej eej eej eej eej eej eeeej   eeeej   eej eej ee ee ee ee eeej ef dddZ  Z S )r  Fdecoder.block.0.layer.1.EncDecAttention.relative_attention_bias.weightencoder.embed_tokens.weightdecoder.embed_tokens.weightr|   c                    s   t  | t|j|j| _t|}d|_	d|_
d|_t|| j| _t|}d|_	d|_|j|_t|| j| _|   d| _d | _d S NFT)rd   re   r   r   
vocab_sizer   r  copydeepcopyr   r   is_encoder_decoderr  encodernum_decoder_layersr  r3   r  r  r  ri   rY   encoder_configZdecoder_configrl   r#   r&   re   S  s    

zT5Model.__init__Nc                 C   sp   t dt |d kr0t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   rK   rP  r  r  rT   r$  r%  r  r   r*  r3   r  ri   r  r#   r#   r&   r*  j  s    	zT5Model.parallelizec                 C   sV   t dt | j  | j  | jd| _| jd| _d| _d | _t	j
  d S Nr+  r  F)r!  r"  r#  rP  r-  r3   rn   r  r  rT   r$  r,  r/  r#   r#   r&   r-  }  s    

zT5Model.deparallelizec                 C   s   | j S r   r  r/  r#   r#   r&   r0    s    zT5Model.get_input_embeddingsc                 C   s"   || _ | j| | j| d S r   r  rP  r2  r3   r1  r#   r#   r&   r2    s    zT5Model.set_input_embeddingsc                 C   s   | j S r   rP  r/  r#   r#   r&   get_encoder  s    zT5Model.get_encoderc                 C   s   | j S r   r3   r/  r#   r#   r&   get_decoder  s    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)r)  rP  r,   Z	attentionr   ri   Zheads_to_pruner,   r   r#   r#   r&   _prune_heads  s    zT5Model._prune_headsoutput_typer  )r   r   r   r   rC  decoder_head_maskrD  encoder_outputsr;  r3  decoder_inputs_embedsr   r   r?  r   r   c                 C   s  |dk	r|n| j j}|dk	r |n| j j}|dk	rX|dkrX| j j| j jkrXttt |}|dkrz| j	|||
||||d}nH|rt
|tst|d t|dkr|d ndt|dkr|d ndd}|d }| jr8tj| jj || jj}|dk	r|| jj}|dk	r || jj}|dk	r8|| jj}| j||||	||||||||d}|sh|| S t|j|j|j|j|j|j|j|jdS )	a  
        Returns:

        Example:

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

        >>> tokenizer = AutoTokenizer.from_pretrained("t5-small")
        >>> model = T5Model.from_pretrained("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   r3  rC  r   r?  r   r   r    r-   r:  rs   r<  r   r   r3  r;  r   r   rC  rD  r   r   r?  r   )r:  r;  decoder_hidden_statesdecoder_attentionsr=  encoder_last_hidden_stater   encoder_attentions)rY   r   r@  r  rQ  r!  r"  Z_T5Model__HEAD_MASK_WARNING_MSGr#  rP  r   r   rK   r  rT   r$  r>  r3   r'  rn   r   r:  r;  rs   r<  r=  )ri   r   r   r   r   rC  ra  rD  rb  r;  r3  rc  r   r   r?  r   rs   decoder_outputsr#   r#   r&   rt     st    ,	


zT5Model.forward)N)NNNNNNNNNNNNNNN)!rv   rw   rx   "_keys_to_ignore_on_load_unexpected_tied_weights_keysr!   re   r   rF  r*  rG  r-  r0  r2  rY  r[  r^  r   T5_INPUTS_DOCSTRINGr   r   _CONFIG_FOR_DOCr   rT   
LongTensorFloatTensor
BoolTensorr   r   r   r   rt   ry   r#   r#   rl   r&   r  I  s`   

               r  z0T5 Model with a `language modeling` head on top.c                       s`  e Zd ZdgZdddgZed fddZ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eeeedd%eej eej eej eej eej eej eej eeeej   eeeej   eej eej eej ee ee ee ee eeej ef dddZ d&ddZ!ejdd d!Z"d"d# Z#  Z$S )'r  rH  rI  rJ  zlm_head.weightr|   c                    s   t  | |j| _t|j|j| _t	|}d|_
d|_d|_t|| j| _t	|}d|_
d|_|j|_t|| j| _tj|j|jdd| _|   d| _d | _d S )NFTr~   )rd   re   r   	model_dimr   r   rL  r  rM  rN  r   r   rO  r  rP  rQ  r  r3   r   r5   r  r  r  rR  rl   r#   r&   re     s"    

z#T5ForConditionalGeneration.__init__Nc                 C   s   t dt |d kr0t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   rK   rP  r  r  rT   r$  r%  r  r   r*  r3   r5   rn   r'  r  rT  r#   r#   r&   r*  6  s    	z&T5ForConditionalGeneration.parallelizec                 C   sd   t dt | j  | j  | jd| _| jd| _| jd| _d| _d | _	t
j  d S rU  )r!  r"  r#  rP  r-  r3   rn   r5   r  r  rT   r$  r,  r/  r#   r#   r&   r-  J  s    

z(T5ForConditionalGeneration.deparallelizec                 C   s   | j S r   rV  r/  r#   r#   r&   r0  Y  s    z/T5ForConditionalGeneration.get_input_embeddingsc                 C   s"   || _ | j| | j| d S r   rW  r1  r#   r#   r&   r2  \  s    z/T5ForConditionalGeneration.set_input_embeddingsc                 C   s
   || _ d S r   r5   r1  r#   r#   r&   set_output_embeddingsa  s    z0T5ForConditionalGeneration.set_output_embeddingsc                 C   s   | j S r   rt  r/  r#   r#   r&   get_output_embeddingsd  s    z0T5ForConditionalGeneration.get_output_embeddingsc                 C   s   | j S r   rX  r/  r#   r#   r&   rY  g  s    z&T5ForConditionalGeneration.get_encoderc                 C   s   | j S r   rZ  r/  r#   r#   r&   r[  j  s    z&T5ForConditionalGeneration.get_decoderr_  )r   r   r   r   rC  ra  rD  rb  r;  r3  rc  labelsr   r   r?  r   r   c                 C   s  |dk	r|n| j j}|dk	r |n| j j}|dk	rX|dkrX| j j| j jkrXttt |}|dkrz| j	|||
||||d}nH|rt
|tst|d t|dkr|d ndt|dkr|d ndd}|d }| jrtj| jj |dk	r|dkr|dkr| |}| jrvtj| jj || jj}|dk	rF|| jj}|dk	r^|| jj}|dk	rv|| jj}| j||||	||||||||d}|d }| jrtj| j	j | j| j	j| _|| jjj}| j jr|| jd  }| |}d}|dk	r>td	d
}||j}||d|d|d}|sr|f|dd  | }|dk	rn|f| S |S t|||j|j|j |j!|j"|j|j d	S )a  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[-100, 0, ...,
            config.vocab_size - 1]`. All labels set to `-100` are ignored (masked), the loss is only computed for
            labels in `[0, ..., config.vocab_size]`

        Returns:

        Examples:

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

        >>> tokenizer = AutoTokenizer.from_pretrained("t5-small")
        >>> model = T5ForConditionalGeneration.from_pretrained("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.
        ```Nrd  r   r    r-   re  rf  r  r  Zignore_indexr(   	lossr4   r;  rg  rh  r=  ri  r   rj  )#rY   r   r@  r  rQ  r!  r"  Z2_T5ForConditionalGeneration__HEAD_MASK_WARNING_MSGr#  rP  r   r   rK   r  rT   r$  r>  r3   r'  r  rn   r5   r+   r   r  rs  r   r   r   r   r;  rs   r<  r=  r:  )ri   r   r   r   r   rC  ra  rD  rb  r;  r3  rc  rw  r   r   r?  r   rs   rk  sequence_outputZ	lm_logitsrz  loss_fctoutputr#   r#   r&   rt   m  s    4	







z"T5ForConditionalGeneration.forwardc
              
   K   s4   |d k	r|d d dd f }|||	||||||d	S )Nr(   )	r   r;  rb  r   rC  ra  r   rD  r   r#   )ri   r   r;  r   rC  ra  r   rD  r   rb  kwargsr#   r#   r&   prepare_inputs_for_generation  s    z8T5ForConditionalGeneration.prepare_inputs_for_generation)rw  c                 C   s
   |  |S r   )r  )ri   rw  r#   r#   r&   %prepare_decoder_input_ids_from_labels%  s    z@T5ForConditionalGeneration.prepare_decoder_input_ids_from_labelsc              	   C   s   |d krt d |S d}|D ]}d}|D ]}||d||jf }q*|d j|d jkrtd|d j d|d j dt|t|krt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 r7   z&length of reordered_layer_past_states z! and length of layer_past_states )r<   r   Zindex_selectrn   r   rO   rQ   rK   )ri   r;  Zbeam_idxZreordered_decoder_pastZlayer_past_statesZreordered_layer_past_statesZlayer_past_stater#   r#   r&   _reorder_cache(  s(    
z)T5ForConditionalGeneration._reorder_cache)N)NNNNNNNNNNNNNNNN)NNNNNNNN)%rv   rw   rx   rl  rm  r!   re   r   rF  r*  rG  r-  r0  r2  ru  rv  rY  r[  r   rn  r   r   ro  r   rT   rp  rq  rr  r   r   r   r   rt   r  r  r  ry   r#   r#   rl   r&   r    s~   


                         
r  zfThe bare T5 Model transformer outputting encoder's raw hidden-states without any specific head on top.c                       s   e Zd ZdgZdgZed fddZeedddZ	ee
d	d
 Zdd Zdd Zdd Zdd Zeeeeeddeej eej eej eej ee ee ee eeej ef dddZ  ZS )r  rI  r3   r|   c                    sZ   t  | t|j|j| _t|}d|_	d|_
t|| j| _|   d| _d | _d S NF)rd   re   r   r   rL  r   r  rM  rN  r   rO  r  rP  r  r  r  )ri   rY   rS  rl   r#   r&   re   O  s    
zT5EncoderModel.__init__Nc                 C   sb   t dt |d kr0t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   rK   rP  r  r  rT   r$  r%  r  r   r*  r  rT  r#   r#   r&   r*  _  s    	zT5EncoderModel.parallelizec                 C   s>   t dt | j  | jd| _d| _d | _tj	
  d S rU  )r!  r"  r#  rP  r-  rn   r  r  rT   r$  r,  r/  r#   r#   r&   r-  q  s    
zT5EncoderModel.deparallelizec                 C   s   | j S r   rV  r/  r#   r#   r&   r0  }  s    z#T5EncoderModel.get_input_embeddingsc                 C   s   || _ | j| d S r   )r  rP  r2  r1  r#   r#   r&   r2    s    z#T5EncoderModel.set_input_embeddingsc                 C   s   | j S r   rX  r/  r#   r#   r&   rY    s    zT5EncoderModel.get_encoderc                 C   s0   |  D ]"\}}| jj| jd j| qdS )r\  r   N)r)  rP  r  r,   r   r   r]  r#   r#   r&   r^    s    zT5EncoderModel._prune_headsr_  )r   r   rC  r3  r   r?  r   r   c           	   	   C   s0   |dk	r|n| j j}| j|||||||d}|S )a  
        Returns:

        Example:

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

        >>> tokenizer = AutoTokenizer.from_pretrained("t5-small")
        >>> model = T5EncoderModel.from_pretrained("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
        ```Nrd  )rY   r@  rP  )	ri   r   r   rC  r3  r   r?  r   rb  r#   r#   r&   rt     s    
zT5EncoderModel.forward)N)NNNNNNN)rv   rw   rx   rm  rl  r!   re   r   rF  r*  rG  r-  r0  r2  rY  r^  r   T5_ENCODER_INPUTS_DOCSTRINGr   r   ro  r   rT   rp  rq  r   r   r   rt   ry   r#   r#   rl   r&   r  G  s<   

       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ed fddZeee	e
eddejeej eej eej eej eej eej eeej  eej eej eej ee ee ee ee eee
f d	d
dZ  ZS )T5ForSequenceClassificationrH  rI  rJ  r|   c                    s2   t  | t|| _t|| _|   d| _d S r  )rd   re   r  r   r   classification_headr  r  r   rl   r#   r&   re     s
    

z$T5ForSequenceClassification.__init__r_  N)r   r   r   r   rC  ra  rD  rb  r3  rc  rw  r   r   r?  r   r   c                 C   sx  |dk	r|n| j j}|dk	r d}|dkrB|	dk	rBtd| jj |dkrl|
dkrl|dkrbtd| |}| j|||||||||	|
||||d}|d }|| j j	
|j}tt|ddkrtd|j\}}}||ddf |d	|ddd	ddf }| |}d}|dk	r |
|j}| j jdkr| j jdkrRd
| 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
|||}nP| j jdkrt }||d	| j j|d	}n| j jdkr t }|||}|sP|f|dd  }|dk	rL|f| S |S t|||j|j|j|j |j!|j"|j#d	S )aD  
        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).
        Returns:
        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   rC  ra  rD  rb  r3  rc  r   r   r?  r   r   r    z7All examples must have the same number of <eos> tokens.r(   Z
regressionZsingle_label_classificationZmulti_label_classificationry  )$rY   r@  NotImplementedErrorrm   rv   rQ   r  r   eqZeos_token_idrn   r   rK   rT   Zunique_consecutivesumrO   r   r  Zproblem_typer   rq   r   rN   r	   squeezer   r   r   r;  rg  rh  r=  ri  r   rj  )ri   r   r   r   r   rC  ra  rD  rb  r3  rc  rw  r   r   r?  r   r   r{  Zeos_maskr   rE  rj   Zsentence_representationr4   rz  r|  r}  r#   r#   r&   rt     s    
,


*

z#T5ForSequenceClassification.forward)NNNNNNNNNNNNNNN)rv   rw   rx   rl  rm  r!   re   r   rn  r   r   ro  rT   rp  r   r   r   rq  r   r   r   rt   ry   r#   r#   rl   r&   r    sL   

               
r  z
    T5 Model with a span classification head on top for extractive question-answering tasks like SQuAD (linear layers
    on top of the hidden-states output to compute `span start logits` and `span end logits`).
    c                       s  e Zd ZdgZddgZed fddZdd Zd	d
 Zdd Z	dd Z
eeeeeddeej eej eej eej eej eej eej eeeej   eej eej eej eej ee ee ee ee eeej ef dddZ  ZS )r  rH  rI  rJ  r|   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 rK  )rd   re   r   rs  r   r   rL  r  rM  rN  r   r   rO  r  rP  rQ  r  r3   r   r   rj   r   r  r  rR  rl   r#   r&   re   J  s"    

zT5ForQuestionAnswering.__init__c                 C   s   | j S r   rV  r/  r#   r#   r&   r0  d  s    z+T5ForQuestionAnswering.get_input_embeddingsc                 C   s"   || _ | j| | j| d S r   rW  r1  r#   r#   r&   r2  g  s    z+T5ForQuestionAnswering.set_input_embeddingsc                 C   s   | j S r   rX  r/  r#   r#   r&   rY  l  s    z"T5ForQuestionAnswering.get_encoderc                 C   s   | j S r   rZ  r/  r#   r#   r&   r[  o  s    z"T5ForQuestionAnswering.get_decoderr_  N)r   r   r   r   rC  ra  rD  rb  start_positionsend_positionsr3  rc  r   r   r?  r   r   c                 C   s  |dk	r|n| j j}|dk	r |n| j j}|	dk	r<|
dk	r<d}|dkrf|dkrf|dkr\td| |}|dk	rr|n| j j}|dk	r|n| j j}|dk	r|dkr| j j| j jkrtt	t
 |}|dkr| j|||||||d}nP|r0t|ts0t|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k	rF|
dk	rFt|	 dkr|	d
|j}	t|
 dkr|
d
|j}
|d}|	d|}	|
d|}
t|d}|||	}|||
}|| d }|s|||f|dd  | }|dk	rx|f| S |S t||||j|j|j|j|j|j|jd
S )a  
        start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the start of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (*sequence_length*). Position outside of the sequence
            are not taken into account for computing the loss.
        end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the end of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (*sequence_length*). Position outside of the sequence
            are not taken into account for computing the loss.
        Returns:
        NFr  rd  r   r    r-   re  rf  r(   r   rx  )
rz  start_logits
end_logitsr;  rg  rh  r=  ri  r   rj  )rY   r@  r   rQ   r  r  rQ  r!  r"  Z._T5ForQuestionAnswering__HEAD_MASK_WARNING_MSGr#  rP  r   r   rK   r3   r   rD   r  r   r   rn   r   r   r   r   r;  rs   r<  r=  r:  )ri   r   r   r   r   rC  ra  rD  rb  r  r  r3  rc  r   r   r?  r   rs   rk  r{  r4   r  r  Z
total_lossZignored_indexr|  Z
start_lossZend_lossr}  r#   r#   r&   rt   r  s     
	




zT5ForQuestionAnswering.forward)NNNNNNNNNNNNNNNN)rv   rw   rx   rl  rm  r!   re   r0  r2  rY  r[  r   rn  r   r   ro  r   rT   rp  rq  rr  r   r   r   r   rt   ry   r#   r#   rl   r&   r  ?  sX   
                r  )Sr   rM  r   r>   r!  typingr   r   r   r   rT   r   Ztorch.nnr   r   r	   Ztorch.utils.checkpointr
   Zactivationsr   Zmodeling_outputsr   r   r   r   r   r   Zmodeling_utilsr   Zpytorch_utilsr   r   r   utilsr   r   r   r   r   r   r   Zutils.model_parallel_utilsr   r   Zconfiguration_t5r!   Z
get_loggerrv   r<   ro  Z_CHECKPOINT_FOR_DOCZ T5_PRETRAINED_MODEL_ARCHIVE_LISTra   rF  rG  Modulerb   Zapex.normalizationrz   rA   r;   	Exceptionr   rC   r{   r   r   r   r   r   r   r   r   r  ZT5_START_DOCSTRINGrn  r  Z__HEAD_MASK_WARNING_MSGr  r  r  r  r  r#   r#   r#   r&   <module>   s    $	
n!

 l $|r  ]& H  4o~