o
    ߥi.                    @   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 ddl	Z	ddl	m
Z
 ddlmZ ddlmZ ddlmZ ddlmZmZmZ dd	lmZmZmZmZmZmZ dd
l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(m)Z) ddl*m+Z+ ddl,m-Z- ddl.m/Z/ e- Z0dd Z1G dd de
j2Z3G dd de
j2Z4G dd de
j2Z5G dd de
j2Z6G dd de
j2Z7G dd  d e
j2Z8G d!d" d"e
j2Z9G d#d$ d$e
j2Z:G d%d& d&e$eZ;G d'd( d(e;Z<d)Z=e&j>e+j?e j@d*G d+d, d,e;ZAdS )-z PyTorch T5 model.    N)OptionalTupleUnion)nn)
checkpoint)ACT2FN))BaseModelOutputWithPastAndCrossAttentions)PreTrainedModel 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replace_return_docstrings)assert_device_mapget_device_map)Models)ModelTensor
TorchModel)MODELS)AttentionBackboneModelOutputSeq2SeqModelOutput)Tasks)
get_logger   )T5Configc                 C   s@  zddl }ddl}ddl}W n ty   td  w tj|}t	d|  |j
|}g }i }	|D ]\}
}t	d|
 d|  |j
||
}||
 ||	|
< q6|D ]}|d}
tdd	 |
D r{t	d
d|
  |	|d qXd|
d v rt	d
d|
  |	|d qX| }|	| }|
D ]}|d|r|d|}n|g}|d dv rt|d}n|d dkrt|d}|d }n|d dkrt|d}|d }n|d dkrt|d}|d }n|d dkrt|drt|d}nt|drt|d}n|d dkrt|d}n||d dks#|d dkr)t|d}nh|d dkr6t|d}n[|d d krE|
d d!krEq|d d!krRt|d"}n?|d d#krrt|dkrr|d  rrt|d$|d  }qz	t||d }W n ty   t	d
d|
  Y qw t|dkrt|d }|| }q|d dvrt|d}|d d%krt	d&|j d'|
  ||}z|j|jksJ d(|j d)|j d*W n ty } z| j|j|jf7  _ d}~ww t	d+|
  t||j |_!|	|d qXt	d,d-|	"  d. | S )/z'Load tf checkpoints in a pytorch model.r   NzLoading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.z&Converting TensorFlow checkpoint from zLoading TF weight z with shape /c                 s   s    | ]}|d v V  qdS ))adam_vadam_mAdamWeightDecayOptimizerAdamWeightDecayOptimizer_1global_stepN ).0nr%   r%   U/home/ubuntu/.local/lib/python3.10/site-packages/modelscope/models/nlp/T5/backbone.py	<genexpr>R   s    z(load_tf_weights_in_t5.<locals>.<genexpr>z	Skipping _slot_z[A-Za-z]+_\d+z_(\d+))kernelscale	embeddingweightself_attentionlayerenc_dec_attentionr   dense_relu_dense   rms_norm
layer_normfinal_layer_normr-   output_biasbetabiassquad
classifierdecoderlogitslm_headwiwi_r.   z"Transposing numpy weight of shape z for zPointer shape z and array shape z mismatchedzInitialize PyTorch weight z%Weights not copied to PyTorch model: z, .)#renumpy
tensorflowImportErrorloggererrorospathabspathinfotrainlist_variablesload_variableappendsplitanyjoinpop	fullmatchgetattrhasattrlenisdigitAttributeErrorintshape	transposeAssertionErrorargstorch
from_numpyastypefloat32datakeys)modelconfigtf_checkpoint_pathrC   nptftf_path	init_varsnames
tf_weightsnamer\   arraytxt_namepointerm_namescope_namesnumer%   r%   r(   load_tf_weights_in_t55   s   















rw   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`   onesr/   variance_epsilon)selfhidden_sizeeps	__class__r%   r(   r{      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 )Nr4   r+   T)keepdim)tor`   rc   powmeanrsqrtr~   r/   dtypefloat16bfloat16)r   hidden_statesvariancer%   r%   r(   forward   s   
zT5LayerNorm.forward)ry   __name__
__module____qualname__r{   r   __classcell__r%   r%   r   r(   rx      s    rx   c                       *   e Zd Zdef fddZdd Z  ZS )T5DenseReluDenserg   c                    sH   t    tj|j|jdd| _tj|j|jdd| _t|j	| _
d S NFr:   )rz   r{   r   Lineard_modeld_ffr@   woDropoutdropout_ratedropoutr   rg   r   r%   r(   r{      s   
zT5DenseReluDense.__init__c                 C   s.   |  |}tj|}| |}| |}|S N)r@   r   
functionalrelur   r   )r   r   r%   r%   r(   r      s
   


zT5DenseReluDense.forwardr   r   r   r   r{   r   r   r%   r%   r   r(   r      s    r   c                       r   )T5DenseGatedGeluDenserg   c                    sh   t    tj|j|jdd| _tj|j|jdd| _tj|j|jdd| _t	|j
| _td | _d S )NFr   gelu_new)rz   r{   r   r   r   r   wi_0wi_1r   r   r   r   r   gelu_actr   r   r%   r(   r{      s   
zT5DenseGatedGeluDense.__init__c                 C   s:   |  | |}| |}|| }| |}| |}|S r   )r   r   r   r   r   )r   r   hidden_geluhidden_linearr%   r%   r(   r      s   


zT5DenseGatedGeluDense.forwardr   r%   r%   r   r(   r      s    r   c                       r   )	T5LayerFFrg   c                    sl   t    |jdkrt|| _n|jdkrt|| _n	t| jj dt|j	|j
d| _t|j| _d S )Nr   z
gated-geluz9 is not supported. Choose between `relu` and `gated-gelu`r   )rz   r{   feed_forward_projr   DenseReluDenser   
ValueErrorrg   rx   r   layer_norm_epsilonr6   r   r   r   r   r   r   r%   r(   r{      s   


zT5LayerFF.__init__c                 C   s&   |  |}| |}|| | }|S r   )r6   r   r   )r   r   forwarded_statesr%   r%   r(   r      s   

zT5LayerFF.forwardr   r%   r%   r   r(   r      s    r   c                       sb   e Zd Zddef fddZdd Ze				dd
dZdd Z								dddZ	  Z
S )T5AttentionFrg   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rct| j| j
| _t | _d| _d S r   )rz   r{   
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r   rg   r   r   r%   r(   r{      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)rX   r
   r   r   r   r   r   r   r   r   r   union)r   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   r4   r   )r   r`   longabsmin
zeros_likelogfloatmath	full_likewhere)relative_positionbidirectionalnum_bucketsmax_distancerelative_buckets	max_exactis_smallrelateive_pos_logmax_dis_logorigin_relative_positionrelative_postion_if_larger%   r%   r(   _relative_position_bucket$  s<   

z%T5Attention._relative_position_bucketc                 C   s   t j|t j| jjjddddf }t j|t j| jjjddddf }|| }| j|| j | j| j	d}| |}|
g dd}|S )z%Compute binned relative position bias)r   deviceN)r   r   r   )r4   r   r   r   )r`   aranger   r   r/   r   r   r   r   r   permute	unsqueeze)r   query_length
key_lengthcontext_positionmemory_positionr   relative_position_bucketvaluesr%   r%   r(   compute_bias\  s8   

zT5Attention.compute_biasNc
                    s&  |j dd \ }
|
}|dur.t|dksJ dt| d||du r+|d j d n|7 }|du r4|n|j d } fdd fd	d
}fdd}|}||j||dura|d nd}||j||durq|d nd}t||dd}|du rĈjstj	dj
||f|j|jd}jrjrd|_n||}|dur|dddd|d dddf }|dur|| }||7 }tjj| dd|}tjj|jjd}|dur|| }|t||}|}jr|r||fnd}|f|f |f }|	r||f }|S )z
        Self-attention (if key_value_states is None) or attention over source sentence (provided by key_value_states).
        Nr4   z?past_key_value should have 2 past states: keys and values. Got z past statesr   r   c                    s   |   djjddS )
projectionr+   r   r4   )viewr   r   r]   states
batch_sizer   r%   r(   r\     s
   z"T5Attention.forward.<locals>.shapec                    s   |  dd  djS )reshaper   r4   r+   )r]   
contiguousr   r   r   r   r%   r(   unshape  s   z$T5Attention.forward.<locals>.unshapec                    sX   |du r || } n
|du r ||} |dur*|du r(t j|| gdd} | S |} | S )z4projects hidden states correctly to key/query statesNr4   r   )r`   cat)r   
proj_layerkey_value_statespast_key_value)r\   r%   r(   project  s   
z$T5Attention.forward.<locals>.project   r   r   Tr+   r   )ptraining)r\   rX   r   r   r   r`   matmulr]   r   zerosr   r   r   r   r   requires_gradr   sizer   r   softmaxr   type_asr   r   r   )r   r   maskr   position_biasr   layer_head_maskr   	use_cacheoutput_attentions
seq_lengthreal_seq_lengthr   r   r   query_states
key_statesvalue_statesscoresattn_weightsattn_outputpresent_key_value_stateoutputsr%   )r   r   r\   r(   r   t  s   (



zT5Attention.forwardF)Tr   r   )NNNNNNFF)r   r   r   r   r{   r   staticmethodr   r   r   r   r%   r%   r   r(   r      s$    7r   c                       s4   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   )rz   r{   r   SelfAttentionrx   r   r   r6   r   r   r   r   r   r   r%   r(   r{        
zT5LayerSelfAttention.__init__Nc              	   C   sJ   |  |}| j|||||||d}	|| |	d  }|f|	dd   }
|
S )N)r  r  r  r   r	  r
  r   r   )r6   r  r   )r   r   attention_maskr  r  r   r	  r
  normed_hidden_statesattention_outputr  r%   r%   r(   r     s   

	
zT5LayerSelfAttention.forwardr  )NNNNFFr   r%   r%   r   r(   r    s    r  c                       s4   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   )rz   r{   r   EncDecAttentionrx   r   r   r6   r   r   r   r   r   r   r%   r(   r{     r  zT5LayerCrossAttention.__init__NFc
                 C   sN   |  |}
| j|
||||||||	d	}|| |d  }|f|dd   }|S )N)r  r   r  r  r   r	  r   r
  r   r   )r6   r  r   )r   r   r   r  r  r  r   r	  r   r
  r  r  layer_outputr  r%   r%   r(   r   "  s"   

zT5LayerCrossAttention.forward)NNNNFNFr   r%   r%   r   r(   r    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r#| jt| | jt	| d S )Nr  )
rz   r{   r   r   
ModuleListr1   rP   r  r  r   r   r   r%   r(   r{   B  s   

zT5Block.__init__NTc                 C   s&  |	d ur=| j std |d u rdnd}t|	|kr0td| d|dkr%dnd dt|	 d	|	d d }|	dd  }nd
\}}| jd ||||||
|d}|d d \}}|dd  }|jtjkr|t	|
 r|t|jjd }tj|| |d}| j o|d u}|r|d ur|d jd }nd }| jd ||||||||
|d	}|d }|jtjkrt	|
 rt|jjd }tj|| |d}|d ur||d  }||dd   }| jd |}|jtjkrt	|
 rt|jjd }tj|| |d}|f}|
r||f | }|S || }|S )NzN`past_key_values` is passed to the encoder. Please make sure this is intended.r4      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   rG   warningrX   r   r1   r   r`   r   isinfrR   finfor%  clampr\   )r   r   r  r  encoder_hidden_statesencoder_attention_maskencoder_decoder_position_biasr  cross_attn_layer_head_maskr   r	  r
  return_dictexpected_num_past_key_valuesself_attn_past_key_valuecross_attn_past_key_valueself_attention_outputsr  attention_outputsclamp_valuedo_cross_attentionr   cross_attention_outputsr  r%   r%   r(   r   O  s   	zT5Block.forwardr  )NNNNNNNNFFTr   r%   r%   r   r(   r!  @  s    r!  c                       sj   e Zd ZdZeZeZdZdZ	dZ
 fddZedd Zdd	 ZdddZdd Ze fddZ  ZS )T5PreTrainedModelz
    An abstract class to handle weights initialization and a simple interface
    for downloading and loading pretrained models.
    transformerTc                    s*   t  j|jfi | t t| | d S r   )rz   r{   name_or_pathr   )r   rg   kwargsr   r%   r(   r{     s   zT5PreTrainedModel.__init__c                 C   s$   t t}t t}|||d}|S )N)decoder_input_ids	input_idsdecoder_attention_mask)r`   tensorr   r   )r   r<  
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r'|jjjj	d|d d dS t|t
rx|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rv|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  |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rN| 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rP|jjjj	d||d  d dS dS dS )zInitialize the weightsg      ?g        )r   stdg      r:   N)rg   initializer_factor
isinstancerx   r/   rd   fill_T5Modelsharednormal_r   r@   r   rW   r:   zero_r   r   r   r   r   r   r   r   r   r   r   r   r   r   )r   modulefactorr   r   r   r%   r%   r(   _init_weights  sp   














zT5PreTrainedModel._init_weightsFc                 C   s   t |ttfr||_d S d S r   )rC  r   T5Stackr   )r   rI  valuer%   r%   r(   _set_gradient_checkpointing  s   
z-T5PreTrainedModel._set_gradient_checkpointingc                 C   s   | j j}| j j}|d usJ 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sSJ d|
|d	k| t|d
k shJ d|S )Nz;self.model.config.decoder_start_token_id has to be defined.r+   )r   .r   r   ).r   z1self.model.config.pad_token_id has to be defined.ir   z8Verify that `shifted_input_ids` has only positive values)rg   decoder_start_token_idpad_token_idr   r`   fullr\   r   	new_zerosclonemasked_fill_allitem)r   r<  rO  rP  shifted_input_idsr%   r%   r(   _shift_right  s*   
 zT5PreTrainedModel._shift_rightc                    sT   | dd}|du rtdi |}| |}ni }tt| jdd|i|}||_|S )a  Instantiate the model.

        Args:
            kwargs: Input args.
                    model_dir: The model dir used to load the checkpoint and the
                    label information. num_labels: An optional arg to tell the
                    model how many classes to initialize.
                                    Method will call utils.parse_label_mapping
                                    if num_labels not supplied. If num_labels is
                                    not found, the model will use the default
                                    setting (2 classes).

        Returns:
            The loaded model, which is initialized by
            transformers.PreTrainedModel.from_pretrained
        	model_dirNpretrained_model_name_or_pathr%   )getr   rz   r   from_pretrainedrY  )clsr:  rY  rg   rf   model_kwargsr   r%   r(   _instantiate3  s   
zT5PreTrainedModel._instantiater  )r   r   r   __doc__r   config_classrw   load_tf_weightsbase_model_prefixis_parallelizablesupports_gradient_checkpointingr{   propertyr@  rK  rN  rX  classmethodr_  r   r%   r%   r   r(   r7    s    


6r7  c                       sb   e Zd Zd fdd	ZdddZdd Zdd	 Zd
d Z												dddZ  Z	S )rL  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!  bool)r&   irg   r%   r(   
<listcomp>Z  s    z$T5Stack.__init__.<locals>.<listcomp>r   F)rz   r{   embed_tokensr   r   r"  range
num_layersblockrx   r   r   r7   r   r   r   	post_initmodel_parallel
device_mapr   )r   rg   rl  r   rj  r(   r{   T  s   

zT5Stack.__init__c                 C   s   |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|< qLqF| j| j| _| j| j| _dS )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:

        >>> # 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)
        >>> # all of the parallelize methods in this file are the same

        NTcpucuda:)r   rX   ro  rm  r`   cudadevice_countrr  r   rq  re   strr   first_devicer%  last_deviceitemsr   rl  r7   )r   rr  r   r   r1   cuda_devicer%   r%   r(   parallelizei  s"   )zT5Stack.parallelizec                 C   sl   d| _ d| _d| _d| _tt| jD ]}| j| d| j|< q| jd| _| j	d| _	t
j  dS )a  
        Moves the model to cpu from a model parallel state.

        Example:

        >>> # 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()
        >>> # all of the deparallelize methods in this file are the same
        FNrs  )rq  rr  rx  ry  rm  rX   ro  r   rl  r7   r`   ru  empty_cache)r   ri  r%   r%   r(   deparallelize  s   zT5Stack.deparallelizec                 C      | j S r   rl  r   r%   r%   r(   get_input_embeddings     zT5Stack.get_input_embeddingsc                 C   s
   || _ d S r   r  r   new_embeddingsr%   r%   r(   set_input_embeddings  s   
zT5Stack.set_input_embeddingsc           *         s^  | 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	|d u r| jd usJ d
| |}|\}}|d ur|d d jd | n|}du r| jsJ d|  d|d u rt|||j}| jr|d u r|d ur|jd }tj|||jtjd}|d u rd gt| j }| |||j}| jr|d ur| \}}}||f}|d u rtj||jd}| |}nd }| || jj}| || jj}r5dnd }|r<dnd } rCdnd } rN| jrNdnd }d }d }| |}tt| j|D ] \} \}!}"||  }#||  }$| j rt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r|$|j}$|r||f }| jr| jrrt d d fdd}%t!|%|!|||||||#|$d 
}&n|!|||||||#|$|" d}&du r|&d d d |&dd   }&|&d d \}}'|&d }| jr9|d ur9|& r6dnd }rA||'f } rV||&d f }| jrV||&d f }| j r| j"# D ]!\}(})| |)d krdt$|( | j%kr|dt$|(d  }q_qa| &|}| |}|r||f }|st'dd |||||fD S t(|||||d S )!N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   r4   Tz)`use_cache` can only be set to `True` if z is used as a decoderr   r   )r   r%   zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fc                    s    fdd}|S )Nc                     s   t  g | R  S r   )tuple)inputs)rI  r
  r	  r%   r(   custom_forwardS  s   zFT5Stack.forward.<locals>.create_custom_forward.<locals>.custom_forwardr%   )rI  r  r
  r	  )rI  r(   create_custom_forwardQ  s   z.T5Stack.forward.<locals>.create_custom_forward)
r  r  r*  r+  r,  r  r-  r   r	  r
  r   r#  r      rt  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))rq  r`   ru  
set_devicerx  rl  r   rg   r	  r
  output_hidden_statesuse_return_dictr   r   r  r   r\   r}   r   r   rX   ro  get_extended_attention_maskinvert_attention_maskget_head_maskrn  r   	enumeratezipr   r   rG   r&  r   rr  rz  rw  ry  r7   r  r   )*r   r<  r  r*  r+  r  	head_maskcross_attn_head_maskr  r	  r
  r  r.  err_msg_prefixinput_shaper   r  mask_seq_lengthencoder_seq_lengthextended_attention_maskencoder_batch_sizeencoder_sequence_length_encoder_hidden_shapeencoder_extended_attention_maskpresent_key_value_statesall_hidden_statesall_attentionsall_cross_attentionsr  r,  r   ri  layer_moduler   r  r-  r  layer_outputsr  r   r   r%   r  r(   r     sz  













"



zT5Stack.forwardr   )NNNNNNNNNNNN)
r   r   r   r{   r|  r~  r  r  r   r   r%   r%   r   r(   rL  R  s&    
:rL  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)`.
)	group_keymodule_namec                #       sH  e Zd ZdZddgZdgZdef fddZd)d	d
Zdd Z	dd Z
dd Zdd Zdd Zdd Z															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ej ef f d'd(Z  ZS )+rE  aM  The bare T5 Model transformer outputting raw hidden-states without any
    specific head on top.

    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.
    zencoder\.embed_tokens\.weightzdecoder\.embed_tokens\.weightzMdecoder\.block\.0\.layer\.1\.EncDecAttention\.relative_attention_bias\.weightrg   c                    s   t  | t|j|j| _t|}d|_	d|_
d|_t|| j| _t|}d|_	d|_|j|_t|| j| _|   d| _d | _d S )NFT)rz   r{   r   r   
vocab_sizer   rF  copydeepcopyr   r	  is_encoder_decoderrL  encodernum_decoder_layersrn  r=   rp  rq  rr  )r   rg   encoder_configdecoder_configr   r%   r(   r{     s   


zT5Model.__init__Nc                 C   sd   |d u rt t| jjttj n|| _t	| jt| jj | j
| j | j
| j d| _d S )NT)r   rX   r  ro  rm  r`   ru  rv  rr  r   r|  r=   rq  )r   rr  r%   r%   r(   r|    s   
zT5Model.parallelizec                 C   sJ   | j   | j  | j d| _ | jd| _d| _d | _tj  d S )Nrs  F)	r  r~  r=   r   rq  rr  r`   ru  r}  r  r%   r%   r(   r~    s   

zT5Model.deparallelizec                 C   r  r   )rF  r  r%   r%   r(   r    r  zT5Model.get_input_embeddingsc                 C   s"   || _ | j| | j| d S r   )rF  r  r  r=   r  r%   r%   r(   r  
  s   zT5Model.set_input_embeddingsc                 C   r  r   )r  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 )z
        Prunes heads of the model. heads_to_prune: dict of {layer_num: list of
        heads to prune in this layer} See base class PreTrainedModel
        N)rz  r  r1   	attentionr   )r   heads_to_pruner1   r   r%   r%   r(   _prune_heads  s   zT5Model._prune_headsr<  r  r;  r=  r  decoder_head_maskr  encoder_outputsr  r  decoder_inputs_embedsr	  r
  r  r.  returnc                 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 | 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  
        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 [`T5Tokenizer`]. 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 [`T5Tokenizer`]. 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.
        Returns:

        Example:

        >>> from transformers import T5Tokenizer, T5Model

        >>> tokenizer = T5Tokenizer.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

        >>> # forward pass
        >>> outputs = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids)
        >>> last_hidden_states = outputs.last_hidden_state
        N)r<  r  r  r  r
  r  r.  r   r   r4   )r  r   r  )r<  r  r  r  r*  r+  r  r  r	  r
  r  r.  )r  r  decoder_hidden_statesdecoder_attentionsr  encoder_last_hidden_stater*  encoder_attentions)rg   r	  r  rn  r  warningswarn_T5Model__HEAD_MASK_WARNING_MSGFutureWarningr  rC  r   rX   rq  r`   ru  r  r=   rx  r   r   r  r  r   r  r  )r   r<  r  r;  r=  r  r  r  r  r  r  r  r	  r
  r  r.  r   decoder_outputsr%   r%   r(   r     s    	zT5Model.forwardr   )NNNNNNNNNNNNNNN)r   r   r   r`  _keys_to_ignore_on_load_missing"_keys_to_ignore_on_load_unexpectedr   r{   r|  r~  r  r  r  r  r  r   r`   
LongTensorFloatTensor
BoolTensorr   r   rh  r   r   r   r   r%   r%   r   r(   rE    s~    

	
	
rE  )Br`  r  r   rI   r  typingr   r   r   r`   r   torch.utils.checkpointr   transformers.activationsr   transformers.modeling_outputsr   transformers.modeling_utilsr	   r
   r   transformers.utilsr   r   r   r   r   r   'transformers.utils.model_parallel_utilsr   r   modelscope.metainfor   modelscope.models.baser   r   r   modelscope.models.builderr   modelscope.outputsr   r   modelscope.utils.constantr   modelscope.utils.loggerr   configurationr   rG   rw   Modulerx   r   r   r   r   r  r  r!  r7  rL  __HEAD_MASK_WARNING_MSGregister_modulebackboneT5rE  r%   r%   r%   r(   <module>   sR    n z$(    _	