U
    5AfT                    @   s  d Z ddlZddlmZmZmZmZ ddlZddlZddlm	Z	 ddl
mZmZmZ ddlmZmZ ddlmZmZmZmZmZmZmZmZ dd	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% ddl&m'Z' e$(e)Z*dZ+dZ,G dd de	j-Z.G dd de	j-Z/G dd de	j-Z0de/iZ1G dd de	j-Z2G dd de	j-Z3G dd de	j-Z4G dd de	j-Z5G dd  d e	j-Z6G d!d" d"e	j-Z7G d#d$ d$eZ8d%Z9d&Z:e"d'e9G d(d) d)e8Z;e"d*e9G d+d, d,e8Z<e"d-e9G d.d/ d/e8Z=G d0d1 d1e	j-Z>e"d2e9G d3d4 d4e8Z?e"d5e9G d6d7 d7e8Z@e"d8e9G d9d: d:e8ZAG d;d< d<e	j-ZBe"d=e9G d>d? d?e8ZCdBd@dAZDdS )CzPyTorch RoBERTa model.    N)ListOptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FNgelu))BaseModelOutputWithPastAndCrossAttentions,BaseModelOutputWithPoolingAndCrossAttentions!CausalLMOutputWithCrossAttentionsMaskedLMOutputMultipleChoiceModelOutputQuestionAnsweringModelOutputSequenceClassifierOutputTokenClassifierOutput)PreTrainedModel)apply_chunking_to_forward find_pruneable_heads_and_indicesprune_linear_layer)add_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardloggingreplace_return_docstrings   )RobertaConfigzFacebookAI/roberta-baser   c                       s2   e Zd ZdZ fddZd
ddZdd	 Z  ZS )RobertaEmbeddingszV
    Same as BertEmbeddings with a tiny tweak for positional embeddings indexing.
    c                    s   t    tj|j|j|jd| _t|j|j| _	t|j
|j| _tj|j|jd| _t|j| _t|dd| _| jdt|jddd | jd	tj| j tjd
dd |j| _tj|j|j| jd| _	d S )N)padding_idxZepsposition_embedding_typeabsoluteposition_ids)r   F)
persistenttoken_type_idsdtype)super__init__r   	Embedding
vocab_sizehidden_sizeZpad_token_idword_embeddingsmax_position_embeddingsposition_embeddingsZtype_vocab_sizetoken_type_embeddings	LayerNormlayer_norm_epsDropouthidden_dropout_probdropoutgetattrr#   Zregister_buffertorcharangeexpandzerosr%   sizelongr!   selfconfig	__class__ P/tmp/pip-unpacked-wheel-zw5xktn0/transformers/models/roberta/modeling_roberta.pyr,   =   s.    
      zRobertaEmbeddings.__init__Nr   c                 C   s   |d kr*|d k	r t || j|}n
| |}|d k	r<| }n| d d }|d }|d krt| dr| jd d d |f }||d |}	|	}ntj|tj	| j
jd}|d kr| |}| |}
||
 }| jdkr| |}||7 }| |}| |}|S )Nr&   r   r(   r   r*   devicer$   )"create_position_ids_from_input_idsr!   &create_position_ids_from_inputs_embedsr>   hasattrr(   r<   r:   r=   r?   r%   rH   r0   r3   r#   r2   r4   r8   )rA   	input_idsr(   r%   inputs_embedspast_key_values_lengthinput_shape
seq_lengthbuffered_token_type_ids buffered_token_type_ids_expandedr3   
embeddingsr2   rE   rE   rF   forwardV   s0    








zRobertaEmbeddings.forwardc                 C   sN   |  dd }|d }tj| jd || j d tj|jd}|d|S )z
        We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.

        Args:
            inputs_embeds: torch.Tensor

        Returns: torch.Tensor
        Nr&   r   rG   r   )r>   r:   r;   r!   r?   rH   Z	unsqueezer<   )rA   rM   rO   Zsequence_lengthr%   rE   rE   rF   rJ   ~   s    	   z8RobertaEmbeddings.create_position_ids_from_inputs_embeds)NNNNr   )__name__
__module____qualname____doc__r,   rT   rJ   __classcell__rE   rE   rC   rF   r    7   s            
(r    c                
       s   e Zd Zd fdd	ZejejdddZdejeej eej eej eej ee	e	ej   ee
 e	ej dd	d
Z  ZS )RobertaSelfAttentionNc                    s   t    |j|j dkr>t|ds>td|j d|j d|j| _t|j|j | _| j| j | _t	
|j| j| _t	
|j| j| _t	
|j| j| _t	|j| _|pt|dd| _| jdks| jd	kr|j| _t	d
|j d | j| _|j| _d S )Nr   Zembedding_sizezThe hidden size (z6) is not a multiple of the number of attention heads ()r#   r$   relative_keyrelative_key_query   r   )r+   r,   r/   num_attention_headsrK   
ValueErrorintattention_head_sizeall_head_sizer   Linearquerykeyvaluer6   Zattention_probs_dropout_probr8   r9   r#   r1   r-   distance_embedding
is_decoderrA   rB   r#   rC   rE   rF   r,      s*    
  zRobertaSelfAttention.__init__)xreturnc                 C   s6   |  d d | j| jf }||}|ddddS )Nr&   r   r^   r   r
   )r>   r_   rb   viewpermute)rA   rk   Znew_x_shaperE   rE   rF   transpose_for_scores   s    
z)RobertaSelfAttention.transpose_for_scoresFhidden_statesattention_mask	head_maskencoder_hidden_statesencoder_attention_maskpast_key_valueoutput_attentionsrl   c                 C   s  |  |}|d k	}	|	r4|d k	r4|d }
|d }|}n|	r^| | |}
| | |}|}nv|d k	r| | |}
| | |}tj|d |
gdd}
tj|d |gdd}n | | |}
| | |}| |}|d k	}| jr|
|f}t||
dd}| j	dks | j	dkr|j
d |
j
d  }}|r^tj|d tj|jd	dd}ntj|tj|jd	dd}tj|tj|jd	dd}|| }| || j d }|j|jd
}| j	dkrtd||}|| }n4| j	dkrtd||}td|
|}|| | }|t| j }|d k	r:|| }tjj|dd}| |}|d k	rf|| }t||}|dddd }| d d | jf }||}|r||fn|f}| jr||f }|S )Nr   r   r^   Zdimr&   r\   r]   rG   r)   zbhld,lrd->bhlrzbhrd,lrd->bhlrr
   ) re   ro   rf   rg   r:   catri   matmulZ	transposer#   shapeZtensorr?   rH   rm   r;   rh   r1   tor*   Zeinsummathsqrtrb   r   Z
functionalZsoftmaxr8   rn   
contiguousr>   rc   )rA   rq   rr   rs   rt   ru   rv   rw   Zmixed_query_layerZis_cross_attentionZ	key_layerZvalue_layerZquery_layer	use_cacheZattention_scoresZquery_lengthZ
key_lengthZposition_ids_lZposition_ids_rZdistanceZpositional_embeddingZrelative_position_scoresZrelative_position_scores_queryZrelative_position_scores_keyZattention_probsZcontext_layerZnew_context_layer_shapeoutputsrE   rE   rF   rT      sp    


 





zRobertaSelfAttention.forward)N)NNNNNF)rU   rV   rW   r,   r:   Tensorro   r   FloatTensorr   boolrT   rY   rE   rE   rC   rF   rZ      s$         rZ   c                       s4   e Zd Z fddZejejejdddZ  ZS )RobertaSelfOutputc                    sB   t    t|j|j| _tj|j|jd| _t|j	| _
d S Nr"   )r+   r,   r   rd   r/   denser4   r5   r6   r7   r8   r@   rC   rE   rF   r,     s    
zRobertaSelfOutput.__init__rq   input_tensorrl   c                 C   s&   |  |}| |}| || }|S Nr   r8   r4   rA   rq   r   rE   rE   rF   rT     s    

zRobertaSelfOutput.forwardrU   rV   rW   r,   r:   r   rT   rY   rE   rE   rC   rF   r     s   r   eagerc                
       sv   e Zd Zd
 fdd	Zdd Zdejeej eej eej eej ee	e	ej   ee
 e	ej ddd	Z  ZS )RobertaAttentionNc                    s4   t    t|j ||d| _t|| _t | _d S )Nr#   )	r+   r,   ROBERTA_SELF_ATTENTION_CLASSESZ_attn_implementationrA   r   outputsetpruned_headsrj   rC   rE   rF   r,   -  s    
 
zRobertaAttention.__init__c                 C   s   t |dkrd S t|| jj| jj| j\}}t| jj|| j_t| jj|| j_t| jj	|| j_	t| j
j|dd| j
_| jjt | | j_| jj| jj | j_| j|| _d S )Nr   r   rx   )lenr   rA   r_   rb   r   r   re   rf   rg   r   r   rc   union)rA   headsindexrE   rE   rF   prune_heads5  s       zRobertaAttention.prune_headsFrp   c              	   C   s<   |  |||||||}| |d |}	|	f|dd   }
|
S )Nr   r   )rA   r   )rA   rq   rr   rs   rt   ru   rv   rw   Zself_outputsattention_outputr   rE   rE   rF   rT   G  s    
	zRobertaAttention.forward)N)NNNNNF)rU   rV   rW   r,   r   r:   r   r   r   r   r   rT   rY   rE   rE   rC   rF   r   ,  s$         r   c                       s0   e Zd Z fddZejejdddZ  ZS )RobertaIntermediatec                    sB   t    t|j|j| _t|jt	r6t
|j | _n|j| _d S r   )r+   r,   r   rd   r/   intermediate_sizer   
isinstanceZ
hidden_actstrr   intermediate_act_fnr@   rC   rE   rF   r,   a  s
    
zRobertaIntermediate.__init__rq   rl   c                 C   s   |  |}| |}|S r   )r   r   )rA   rq   rE   rE   rF   rT   i  s    

zRobertaIntermediate.forwardr   rE   rE   rC   rF   r   `  s   r   c                       s4   e Zd Z fddZejejejdddZ  ZS )RobertaOutputc                    sB   t    t|j|j| _tj|j|jd| _t	|j
| _d S r   )r+   r,   r   rd   r   r/   r   r4   r5   r6   r7   r8   r@   rC   rE   rF   r,   q  s    
zRobertaOutput.__init__r   c                 C   s&   |  |}| |}| || }|S r   r   r   rE   rE   rF   rT   w  s    

zRobertaOutput.forwardr   rE   rE   rC   rF   r   p  s   r   c                
       st   e Zd Z fddZd
ejeej eej eej eej eeeej   ee	 eej dddZ
dd	 Z  ZS )RobertaLayerc                    sr   t    |j| _d| _t|| _|j| _|j| _| jrZ| jsLt|  dt|dd| _	t
|| _t|| _d S )Nr   z> should be used as a decoder model if cross attention is addedr$   r   )r+   r,   chunk_size_feed_forwardseq_len_dimr   	attentionri   add_cross_attentionr`   crossattentionr   intermediater   r   r@   rC   rE   rF   r,     s    


zRobertaLayer.__init__NFrp   c              	   C   s  |d k	r|d d nd }| j |||||d}	|	d }
| jrP|	dd }|	d }n|	dd  }d }| jr|d k	rt| dstd|  d|d k	r|d	d  nd }| |
||||||}|d }
||dd  }|d }|| }t| j| j| j|
}|f| }| jr||f }|S )
Nr^   )rw   rv   r   r   r&   r   z'If `encoder_hidden_states` are passed, z` has to be instantiated with cross-attention layers by setting `config.add_cross_attention=True`ry   )	r   ri   rK   r`   r   r   feed_forward_chunkr   r   )rA   rq   rr   rs   rt   ru   rv   rw   Zself_attn_past_key_valueZself_attention_outputsr   r   Zpresent_key_valueZcross_attn_present_key_valueZcross_attn_past_key_valueZcross_attention_outputslayer_outputrE   rE   rF   rT     sV    


	   

zRobertaLayer.forwardc                 C   s   |  |}| ||}|S r   )r   r   )rA   r   Zintermediate_outputr   rE   rE   rF   r     s    
zRobertaLayer.feed_forward_chunk)NNNNNF)rU   rV   rW   r,   r:   r   r   r   r   r   rT   r   rY   rE   rE   rC   rF   r     s$         Ar   c                       s   e Zd Z fddZd	ejeej eej eej eej eeeej   ee	 ee	 ee	 ee	 e
eej ef dddZ  ZS )
RobertaEncoderc                    s:   t     | _t fddt jD | _d| _d S )Nc                    s   g | ]}t  qS rE   )r   ).0_rB   rE   rF   
<listcomp>  s     z+RobertaEncoder.__init__.<locals>.<listcomp>F)	r+   r,   rB   r   Z
ModuleListrangenum_hidden_layerslayergradient_checkpointingr@   rC   r   rF   r,     s    
 zRobertaEncoder.__init__NFT)rq   rr   rs   rt   ru   past_key_valuesr   rw   output_hidden_statesreturn_dictrl   c                 C   sb  |	rdnd }|rdnd }|r(| j jr(dnd }| jrJ| jrJ|rJtd d}|rRdnd }t| jD ]\}}|	rv||f }|d k	r|| nd }|d k	r|| nd }| jr| jr| |j	|||||||}n||||||||}|d }|r||d f7 }|r`||d f }| j jr`||d f }q`|	r.||f }|
sPt
dd	 |||||fD S t|||||d
S )NrE   zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fr   r&   r   r^   c                 s   s   | ]}|d k	r|V  qd S r   rE   )r   vrE   rE   rF   	<genexpr>  s   z)RobertaEncoder.forward.<locals>.<genexpr>)last_hidden_stater   rq   
attentionscross_attentions)rB   r   r   ZtrainingloggerZwarning_once	enumerater   Z_gradient_checkpointing_func__call__tupler   )rA   rq   rr   rs   rt   ru   r   r   rw   r   r   Zall_hidden_statesZall_self_attentionsZall_cross_attentionsZnext_decoder_cacheiZlayer_moduleZlayer_head_maskrv   Zlayer_outputsrE   rE   rF   rT     sx    


zRobertaEncoder.forward)	NNNNNNFFT)rU   rV   rW   r,   r:   r   r   r   r   r   r   r   rT   rY   rE   rE   rC   rF   r     s.   	         r   c                       s0   e Zd Z fddZejejdddZ  ZS )RobertaPoolerc                    s*   t    t|j|j| _t | _d S r   )r+   r,   r   rd   r/   r   ZTanh
activationr@   rC   rE   rF   r,   5  s    
zRobertaPooler.__init__r   c                 C   s(   |d d df }|  |}| |}|S Nr   )r   r   )rA   rq   Zfirst_token_tensorpooled_outputrE   rE   rF   rT   :  s    

zRobertaPooler.forwardr   rE   rE   rC   rF   r   4  s   r   c                   @   s,   e Zd ZdZeZdZdZddgZdd Z	dS )	RobertaPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    robertaTr    rZ   c                 C   s   t |tjr:|jjjd| jjd |jdk	r|jj	  nft |tj
rz|jjjd| jjd |jdk	r|jj|j 	  n&t |tjr|jj	  |jjd dS )zInitialize the weightsg        )ZmeanZstdNg      ?)r   r   rd   ZweightdataZnormal_rB   Zinitializer_rangebiasZzero_r-   r!   r4   Zfill_)rA   modulerE   rE   rF   _init_weightsO  s    

z$RobertaPreTrainedModel._init_weightsN)
rU   rV   rW   rX   r   config_classZbase_model_prefixZsupports_gradient_checkpointingZ_no_split_modulesr   rE   rE   rE   rF   r   C  s   r   aA  

    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 ([`RobertaConfig`]): 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 `({0})`):
            Indices of input sequence tokens in the vocabulary.

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

            [What are input IDs?](../glossary#input-ids)
        attention_mask (`torch.FloatTensor` of shape `({0})`, *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)
        token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
            Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:

            - 0 corresponds to a *sentence A* token,
            - 1 corresponds to a *sentence B* token.
            This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
            >= 2. All the value in this tensor should be always < type_vocab_size.

            [What are token type IDs?](../glossary#token-type-ids)
        position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.max_position_embeddings - 1]`.

            [What are position IDs?](../glossary#position-ids)
        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 `({0}, 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.
zaThe bare RoBERTa Model transformer outputting raw hidden-states without any specific head on top.c                       s   e Zd ZdZd fdd	Zdd Zdd Zd	d
 Zee	
d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j eeej  ee ee ee ee eeej ef dddZ  ZS )RobertaModela*  

    The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
    cross-attention is added between the self-attention layers, following the architecture described in *Attention is
    all you need*_ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz
    Kaiser and Illia Polosukhin.

    To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
    to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
    `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.

    .. _*Attention is all you need*: https://arxiv.org/abs/1706.03762

    Tc                    sD   t  | || _t|| _t|| _|r2t|nd | _| 	  d S r   )
r+   r,   rB   r    rS   r   encoderr   pooler	post_init)rA   rB   add_pooling_layerrC   rE   rF   r,     s    

zRobertaModel.__init__c                 C   s   | j jS r   rS   r0   rA   rE   rE   rF   get_input_embeddings  s    z!RobertaModel.get_input_embeddingsc                 C   s   || j _d S r   r   )rA   rg   rE   rE   rF   set_input_embeddings  s    z!RobertaModel.set_input_embeddingsc                 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)itemsr   r   r   r   )rA   Zheads_to_pruner   r   rE   rE   rF   _prune_heads  s    zRobertaModel._prune_headsbatch_size, sequence_length
checkpointoutput_typer   N)rL   rr   r(   r%   rs   rM   rt   ru   r   r   rw   r   r   rl   c                 C   s^  |dk	r|n| j j}|dk	r |n| j j}|dk	r4|n| j j}| j jrZ|
dk	rP|
n| j j}
nd}
|dk	rx|dk	rxtdn@|dk	r| || | }n"|dk	r| dd }ntd|\}}|dk	r|j	n|j	}|	dk	r|	d d j
d nd}|dkrtj||| f|d}|dkrft| jd	rT| jjddd|f }|||}|}ntj|tj|d
}| ||}| j jr|dk	r| \}}}||f}|dkrtj||d}| |}nd}| || j j}| j|||||d}| j||||||	|
|||d
}|d }| jdk	r$| |nd}|sB||f|dd  S t|||j|j|j|jdS )a  
        encoder_hidden_states  (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
            the model is configured as a decoder.
        encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
            the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.
        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)`.
        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`).
        NFzDYou cannot specify both input_ids and inputs_embeds at the same timer&   z5You have to specify either input_ids or inputs_embedsr   r^   )rH   r(   rG   )rL   r%   r(   rM   rN   )	rr   rs   rt   ru   r   r   rw   r   r   r   )r   Zpooler_outputr   rq   r   r   )rB   rw   r   use_return_dictri   r   r`   Z%warn_if_padding_and_no_attention_maskr>   rH   r|   r:   ZonesrK   rS   r(   r<   r=   r?   Zget_extended_attention_maskZinvert_attention_maskZget_head_maskr   r   r   r   r   rq   r   r   )rA   rL   rr   r(   r%   rs   rM   rt   ru   r   r   rw   r   r   rO   Z
batch_sizerP   rH   rN   rQ   rR   Zextended_attention_maskZencoder_batch_sizeZencoder_sequence_lengthr   Zencoder_hidden_shapeZencoder_extended_attention_maskZembedding_outputZencoder_outputssequence_outputr   rE   rE   rF   rT     s    +




zRobertaModel.forward)T)NNNNNNNNNNNNN)rU   rV   rW   rX   r,   r   r   r   r   ROBERTA_INPUTS_DOCSTRINGformatr   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOCr   r:   r   r   r   r   r   r   rT   rY   rE   rE   rC   rF   r     sP                r   zIRoBERTa Model with a `language modeling` head on top for CLM fine-tuning.c                       s   e Zd ZddgZ fddZdd Zdd Zee	d	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j eej e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dd Z  ZS )RobertaForCausalLMlm_head.decoder.weightlm_head.decoder.biasc                    s@   t  | |jstd t|dd| _t|| _| 	  d S )NzOIf you want to use `RobertaLMHeadModel` as a standalone, add `is_decoder=True.`Fr   
r+   r,   ri   r   warningr   r   RobertaLMHeadlm_headr   r@   rC   rE   rF   r,   b  s    

zRobertaForCausalLM.__init__c                 C   s   | j jS r   r   decoderr   rE   rE   rF   get_output_embeddingsn  s    z(RobertaForCausalLM.get_output_embeddingsc                 C   s   || j _d S r   r   rA   Znew_embeddingsrE   rE   rF   set_output_embeddingsq  s    z(RobertaForCausalLM.set_output_embeddingsr   )r   r   N)rL   rr   r(   r%   rs   rM   rt   ru   labelsr   r   rw   r   r   rl   c                 C   s  |dk	r|n| j j}|	dk	r d}| j|||||||||
||||d}|d }| |}d}|	dk	r|	|j}	|ddddddf  }|	ddddf  }	t }||d| j j	|	d}|s|f|dd  }|dk	r|f| S |S t
|||j|j|j|jdS )	a2
  
        encoder_hidden_states  (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
            the model is configured as a decoder.
        encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
            the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:

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

        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
            `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
            ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
        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)`.
        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`).

        Returns:

        Example:

        ```python
        >>> from transformers import AutoTokenizer, RobertaForCausalLM, AutoConfig
        >>> import torch

        >>> tokenizer = AutoTokenizer.from_pretrained("FacebookAI/roberta-base")
        >>> config = AutoConfig.from_pretrained("FacebookAI/roberta-base")
        >>> config.is_decoder = True
        >>> model = RobertaForCausalLM.from_pretrained("FacebookAI/roberta-base", config=config)

        >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
        >>> outputs = model(**inputs)

        >>> prediction_logits = outputs.logits
        ```NF)rr   r(   r%   rs   rM   rt   ru   r   r   rw   r   r   r   r&   r   r^   )losslogitsr   rq   r   r   )rB   r   r   r   r}   rH   r   r   rm   r.   r   r   rq   r   r   )rA   rL   rr   r(   r%   rs   rM   rt   ru   r   r   r   rw   r   r   r   r   prediction_scoresZlm_lossZshifted_prediction_scoresloss_fctr   rE   rE   rF   rT   t  sL    >
zRobertaForCausalLM.forwardc                 K   st   |j }|d kr||}|d k	rh|d d j d }|j d |krF|}n|j d d }|d d |d f }|||dS )Nr   r^   r   )rL   rr   r   )r|   Znew_ones)rA   rL   r   rr   Zmodel_kwargsrO   Zpast_lengthZremove_prefix_lengthrE   rE   rF   prepare_inputs_for_generation  s    
z0RobertaForCausalLM.prepare_inputs_for_generationc                    s.   d}|D ] }|t  fdd|D f7 }q|S )NrE   c                 3   s"   | ]}| d  |jV  qdS )r   N)Zindex_selectr}   rH   )r   Z
past_statebeam_idxrE   rF   r     s     z4RobertaForCausalLM._reorder_cache.<locals>.<genexpr>)r   )rA   r   r   Zreordered_pastZ
layer_pastrE   r   rF   _reorder_cache  s    z!RobertaForCausalLM._reorder_cache)NNNNNNNNNNNNNN)NN)rU   rV   rW   _tied_weights_keysr,   r   r   r   r   r   r   r   r   r   r:   
LongTensorr   r   r   r   r   rT   r   r   rY   rE   rE   rC   rF   r   \  sN   
              j
r   z5RoBERTa Model with a `language modeling` head on top.c                       s   e Zd ZddgZ fddZdd Zdd Zee	d	e
eeed
dd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j eej ee ee ee eeej ef dddZ  ZS )RobertaForMaskedLMr   r   c                    s@   t  | |jrtd t|dd| _t|| _| 	  d S )NznIf you want to use `RobertaForMaskedLM` make sure `config.is_decoder=False` for bi-directional self-attention.Fr   r   r@   rC   rE   rF   r,     s    
zRobertaForMaskedLM.__init__c                 C   s   | j jS r   r   r   rE   rE   rF   r     s    z(RobertaForMaskedLM.get_output_embeddingsc                 C   s   || j _d S r   r   r   rE   rE   rF   r     s    z(RobertaForMaskedLM.set_output_embeddingsr   z<mask>z' Paris'g?)r   r   r   maskexpected_outputexpected_lossN)rL   rr   r(   r%   rs   rM   rt   ru   r   rw   r   r   rl   c                 C   s   |dk	r|n| j j}| j|||||||||
||d}|d }| |}d}|	dk	r|	|j}	t }||d| j j|	d}|s|f|dd  }|dk	r|f| S |S t	|||j
|jdS )a(  
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
            config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
            loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
        kwargs (`Dict[str, any]`, *optional*, defaults to `{}`):
            Used to hide legacy arguments that have been deprecated.
        N)
rr   r(   r%   rs   rM   rt   ru   rw   r   r   r   r&   r^   r   r   rq   r   )rB   r   r   r   r}   rH   r   rm   r.   r   rq   r   )rA   rL   rr   r(   r%   rs   rM   rt   ru   r   rw   r   r   r   r   r   Zmasked_lm_lossr   r   rE   rE   rF   rT     s<     
zRobertaForMaskedLM.forward)NNNNNNNNNNNN)rU   rV   rW   r   r,   r   r   r   r   r   r   r   r   r   r   r:   r   r   r   r   r   r   rT   rY   rE   rE   rC   rF   r     sP   
            r   c                       s0   e Zd ZdZ fddZdd Zdd Z  ZS )r   z*Roberta Head for masked language modeling.c                    sd   t    t|j|j| _tj|j|jd| _t|j|j	| _
tt|j	| _| j| j
_d S r   )r+   r,   r   rd   r/   r   r4   r5   
layer_normr.   r   	Parameterr:   r=   r   r@   rC   rE   rF   r,   _  s    
zRobertaLMHead.__init__c                 K   s*   |  |}t|}| |}| |}|S r   )r   r   r   r   rA   featureskwargsrk   rE   rE   rF   rT   h  s
    


zRobertaLMHead.forwardc                 C   s*   | j jjjdkr| j| j _n
| j j| _d S )Nmeta)r   r   rH   typer   rE   rE   rF   _tie_weightsr  s    zRobertaLMHead._tie_weights)rU   rV   rW   rX   r,   rT   r  rY   rE   rE   rC   rF   r   \  s   	
r   z
    RoBERTa Model transformer with a sequence classification/regression head on top (a linear layer on top of the
    pooled output) e.g. for GLUE tasks.
    c                       s   e Zd Z fddZeededee	dd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 e
e eeej ef d	d
dZ  ZS ) RobertaForSequenceClassificationc                    s>   t  | |j| _|| _t|dd| _t|| _|   d S NFr   )	r+   r,   
num_labelsrB   r   r   RobertaClassificationHead
classifierr   r@   rC   rE   rF   r,     s    
z)RobertaForSequenceClassification.__init__r   z'cardiffnlp/twitter-roberta-base-emotionz
'optimism'g{Gz?r   r   r   r   r   NrL   rr   r(   r%   rs   rM   r   rw   r   r   rl   c                 C   s~  |
dk	r|
n| j j}
| j||||||||	|
d	}|d }| |}d}|dk	r:||j}| j jdkr| jdkr|d| j _n4| jdkr|jt	j
ks|jt	jkrd| j _nd| j _| j jdkrt }| jdkr|| | }n
|||}nN| j jdkrt }||d| j|d}n| j jdkr:t }|||}|
sj|f|d	d  }|dk	rf|f| S |S t|||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 `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        Nrr   r(   r%   rs   rM   rw   r   r   r   r   Z
regressionZsingle_label_classificationZmulti_label_classificationr&   r^   r   )rB   r   r   r  r}   rH   Zproblem_typer	  r*   r:   r?   ra   r	   squeezer   rm   r   r   rq   r   rA   rL   rr   r(   r%   rs   rM   r   rw   r   r   r   r   r   r   r   r   rE   rE   rF   rT     sV    



"


z(RobertaForSequenceClassification.forward)
NNNNNNNNNN)rU   rV   rW   r,   r   r   r   r   r   r   r   r:   r   r   r   r   r   r   rT   rY   rE   rE   rC   rF   r  {  s@   	          r  z
    Roberta Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
    softmax) e.g. for RocStories/SWAG tasks.
    c                       s   e Zd Z fddZeed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 ee eeej e	f dddZ  ZS )
RobertaForMultipleChoicec                    s@   t  | t|| _t|j| _t|j	d| _
|   d S )Nr   )r+   r,   r   r   r   r6   r7   r8   rd   r/   r  r   r@   rC   rE   rF   r,     s
    
z!RobertaForMultipleChoice.__init__z(batch_size, num_choices, sequence_lengthr   N)rL   r(   rr   r   r%   rs   rM   rw   r   r   rl   c                 C   s  |
dk	r|
n| j j}
|dk	r&|jd n|jd }|dk	rJ|d|dnd}|dk	rh|d|dnd}|dk	r|d|dnd}|dk	r|d|dnd}|dk	r|d|d|dnd}| j||||||||	|
d	}|d }| |}| |}|d|}d}|dk	r<||j	}t
 }|||}|
sl|f|dd  }|dk	rh|f| S |S t|||j|jdS )aJ  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
            num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
            `input_ids` above)
        Nr   r&   ry   )r%   r(   rr   rs   rM   rw   r   r   r^   r   )rB   r   r|   rm   r>   r   r8   r  r}   rH   r   r   rq   r   )rA   rL   r(   rr   r   r%   rs   rM   rw   r   r   Znum_choicesZflat_input_idsZflat_position_idsZflat_token_type_idsZflat_attention_maskZflat_inputs_embedsr   r   r   Zreshaped_logitsr   r   r   rE   rE   rF   rT     sN    



z RobertaForMultipleChoice.forward)
NNNNNNNNNN)rU   rV   rW   r,   r   r   r   r   r   r   r   r   r:   r   r   r   r   r   r   rT   rY   rE   rE   rC   rF   r    s<   
          r  z
    Roberta Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
    Named-Entity-Recognition (NER) tasks.
    c                       s   e Zd Z fddZeededee	dd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 e
e eeej ef d	d
dZ  ZS )RobertaForTokenClassificationc                    sb   t  | |j| _t|dd| _|jd k	r2|jn|j}t|| _	t
|j|j| _|   d S r  )r+   r,   r	  r   r   classifier_dropoutr7   r   r6   r8   rd   r/   r  r   rA   rB   r  rC   rE   rF   r,   B  s    z&RobertaForTokenClassification.__init__r   z'Jean-Baptiste/roberta-large-ner-englishzF['O', 'ORG', 'ORG', 'O', 'O', 'O', 'O', 'O', 'LOC', 'O', 'LOC', 'LOC']g{Gz?r  Nr  c                 C   s   |
dk	r|
n| j j}
| j||||||||	|
d	}|d }| |}| |}d}|dk	r||j}t }||d| j	|d}|
s|f|dd  }|dk	r|f| S |S t
|||j|jdS )z
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
        Nr  r   r&   r^   r   )rB   r   r   r8   r  r}   rH   r   rm   r	  r   rq   r   r  rE   rE   rF   rT   P  s:    

z%RobertaForTokenClassification.forward)
NNNNNNNNNN)rU   rV   rW   r,   r   r   r   r   r   r   r   r:   r   r   r   r   r   r   rT   rY   rE   rE   rC   rF   r  :  s@   	          r  c                       s(   e Zd ZdZ fddZdd Z  ZS )r
  z-Head for sentence-level classification tasks.c                    sT   t    t|j|j| _|jd k	r,|jn|j}t|| _	t|j|j
| _d S r   )r+   r,   r   rd   r/   r   r  r7   r6   r8   r	  out_projr  rC   rE   rF   r,     s    
z"RobertaClassificationHead.__init__c                 K   sL   |d d dd d f }|  |}| |}t|}|  |}| |}|S r   )r8   r   r:   tanhr  r  rE   rE   rF   rT     s    




z!RobertaClassificationHead.forward)rU   rV   rW   rX   r,   rT   rY   rE   rE   rC   rF   r
    s   	r
  z
    Roberta Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
    layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
    c                       s   e Zd Z fddZeededee	dd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j e
e e
e e
e eeej ef d	d
dZ  ZS )RobertaForQuestionAnsweringc                    s@   t  | |j| _t|dd| _t|j|j| _| 	  d S r  )
r+   r,   r	  r   r   r   rd   r/   
qa_outputsr   r@   rC   rE   rF   r,     s
    z$RobertaForQuestionAnswering.__init__r   zdeepset/roberta-base-squad2z	' puppet'gQ?r  N)rL   rr   r(   r%   rs   rM   start_positionsend_positionsrw   r   r   rl   c                 C   sP  |dk	r|n| j j}| j|||||||	|
|d	}|d }| |}|jddd\}}|d }|d }d}|dk	r|dk	rt| dkr|d}t| dkr|d}|d}|	d|}|	d|}t
|d}|||}|||}|| d }|s:||f|dd  }|dk	r6|f| S |S t||||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.
        Nr  r   r   r&   rx   )Zignore_indexr^   )r   start_logits
end_logitsrq   r   )rB   r   r   r  splitr  r   r   r>   clampr   r   rq   r   )rA   rL   rr   r(   r%   rs   rM   r  r  rw   r   r   r   r   r   r  r  Z
total_lossZignored_indexr   Z
start_lossZend_lossr   rE   rE   rF   rT     sP     






z#RobertaForQuestionAnswering.forward)NNNNNNNNNNN)rU   rV   rW   r,   r   r   r   r   r   r   r   r:   r   r   r   r   r   r   rT   rY   rE   rE   rC   rF   r    sD   
	           r  c                 C   s6   |  | }tj|dd|| | }| | S )a  
    Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
    are ignored. This is modified from fairseq's `utils.make_positions`.

    Args:
        x: torch.Tensor x:

    Returns: torch.Tensor
    r   rx   )nera   r:   ZcumsumZtype_asr?   )rL   r!   rN   r   Zincremental_indicesrE   rE   rF   rI   
  s    rI   )r   )ErX   r~   typingr   r   r   r   r:   Ztorch.utils.checkpointr   Ztorch.nnr   r   r	   Zactivationsr   r   Zmodeling_outputsr   r   r   r   r   r   r   r   Zmodeling_utilsr   Zpytorch_utilsr   r   r   utilsr   r   r   r   r   Zconfiguration_robertar   Z
get_loggerrU   r   r   r   Moduler    rZ   r   r   r   r   r   r   r   r   r   ZROBERTA_START_DOCSTRINGr   r   r   r   r   r  r  r  r
  r  rI   rE   rE   rE   rF   <module>   s   (

Z  4W^3 6   ]\UN^