o
    ei                     @   s  d dl mZ d dlZd dlmZ d dlmZmZmZ ddlm	Z
 ddlmZmZ 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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& ddl'm(Z( ddl)m*Z*m+Z+m,Z, ddl-m.Z.m/Z/ ddl0m1Z1 ddl2m3Z3 e,4e5Z6G dd dej7Z8		dLdej7dej9dej9dej9dej9dB de:dB de:de&e* fdd Z;G d!d" d"ej7Z<G d#d$ d$ej7Z=G d%d& d&ej7Z>G d'd( d(ej7Z?G d)d* d*ej7Z@G d+d, d,ej7ZAG d-d. d.eZBe+G d/d0 d0e$ZCG d1d2 d2ej7ZDG d3d4 d4ej7ZEe+d5d6G d7d8 d8eCZFe+d9d6G d:d; d;eCeZGe+G d<d= d=eCZHG d>d? d?ej7ZIe+d@d6G dAdB dBeCZJe+G dCdD dDeCZKe+G dEdF dFeCZLG dGdH dHej7ZMe+G dIdJ dJeCZNg dKZOdS )M    )CallableN)BCEWithLogitsLossCrossEntropyLossMSELoss   )initialization)ACT2FNgelu)CacheDynamicCacheEncoderDecoderCache)GenerationMixin)create_bidirectional_maskcreate_causal_mask)GradientCheckpointingLayer))BaseModelOutputWithPastAndCrossAttentions,BaseModelOutputWithPoolingAndCrossAttentions!CausalLMOutputWithCrossAttentionsMaskedLMOutputMultipleChoiceModelOutputQuestionAnsweringModelOutputSequenceClassifierOutputTokenClassifierOutput)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)apply_chunking_to_forward)TransformersKwargsauto_docstringlogging)can_return_tuplemerge_with_config_defaults)capture_outputs   )RobertaConfigc                       s   e Zd ZdZ fddZ					ddejdB dejdB dejdB d	ejdB d
edej	fddZ
edd ZedddZ  ZS )RobertaEmbeddingszGConstruct the embeddings from word, position and token_type embeddings.c                    s   t    tj|j|j|jd| _t|j|j| _	tj
|j|jd| _
t|j| _| 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epsposition_idsr#   F)
persistenttoken_type_ids)dtype)super__init__nn	Embedding
vocab_sizehidden_sizepad_token_idword_embeddingstype_vocab_sizetoken_type_embeddings	LayerNormlayer_norm_epsDropouthidden_dropout_probdropoutregister_buffertorcharangemax_position_embeddingsexpandzerosr)   sizelongr&   position_embeddingsselfconfig	__class__ j/home/ubuntu/transcripts/venv/lib/python3.10/site-packages/transformers/models/roberta/modeling_roberta.pyr0   ;   s   
zRobertaEmbeddings.__init__Nr   	input_idsr-   r)   inputs_embedspast_key_values_lengthreturnc                 C   s  |d u r|d ur|  || j|}n| || j}|d ur!| }n| d d }|\}}|d u rZt| drO| j|jd d}	tj	|	d|d}	|	||}ntj
|tj| jjd}|d u rc| |}| |}
||
 }| |}|| }| |}| |}|S )Nr+   r-   r   r#   )dimindexr.   device)"create_position_ids_from_input_idsr&   &create_position_ids_from_inputs_embedsrD   hasattrr-   rB   shaper?   gatherrC   rE   r)   rU   r6   r8   rF   r9   r=   )rH   rN   r-   r)   rO   rP   input_shape
batch_size
seq_lengthbuffered_token_type_idsr8   
embeddingsrF   rL   rL   rM   forwardO   s2   






zRobertaEmbeddings.forwardc                 C   sJ   |   dd }|d }tj|d || 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#   rT   r   )rD   r?   r@   rE   rU   	unsqueezerB   )rO   r&   r[   sequence_lengthr)   rL   rL   rM   rW      s   
z8RobertaEmbeddings.create_position_ids_from_inputs_embedsc                 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#   rR   )neintr?   cumsumtype_asrE   )rN   r&   rP   maskincremental_indicesrL   rL   rM   rV      s   z4RobertaEmbeddings.create_position_ids_from_input_ids)NNNNr   )r   )__name__
__module____qualname____doc__r0   r?   
LongTensorFloatTensorre   Tensorr`   staticmethodrW   rV   __classcell__rL   rL   rJ   rM   r%   8   s2    
0
r%           modulequerykeyvalueattention_maskscalingr=   kwargsc           
      K   s   |d u r| dd }t||dd| }|d ur|| }tjj|dd}tjj||| jd}t||}	|	dd	 }	|	|fS )Nr+            r   rc   )ptrainingr#   )
rD   r?   matmul	transposer1   
functionalsoftmaxr=   r~   
contiguous)
rt   ru   rv   rw   rx   ry   r=   rz   attn_weightsattn_outputrL   rL   rM   eager_attention_forward   s   
r   c                       sd   e Zd Zd fdd	Z			ddejdejdB dedB dejdB d	ee	 d
e
ej fddZ  ZS )RobertaSelfAttentionFNc                    s   t    |j|j dkrt|dstd|j d|j d|| _|j| _t|j|j | _| j| j | _	| jd | _
t|j| j	| _t|j| j	| _t|j| j	| _t|j| _|j| _|| _|| _d S Nr   embedding_sizezThe hidden size (z6) is not a multiple of the number of attention heads ()r{   )r/   r0   r4   num_attention_headsrX   
ValueErrorrI   re   attention_head_sizeall_head_sizery   r1   Linearru   rv   rw   r;   attention_probs_dropout_probr=   
is_decoder	is_causal	layer_idxrH   rI   r   r   rJ   rL   rM   r0      s&   


zRobertaSelfAttention.__init__hidden_statesrx   past_key_valuescache_positionrz   rQ   c                 K   s  |j d d }g |d| jR }| |j| dd}| |j| dd}	| |j| dd}
|d urP|}t|trC|j	}|
|	|
| jd|i\}	}
t| jjt}|| ||	|
|f| jsddn| jj| jd|\}}|jg |dR   }||fS )Nr+   r#   r|   r   rs   r=   ry   )rY   r   ru   viewr   rv   rw   
isinstancer   self_attention_cacheupdater   r   get_interfacerI   _attn_implementationr   r~   r=   r}   ry   reshaper   )rH   r   rx   r   r   rz   r[   hidden_shapequery_layer	key_layervalue_layercurrent_past_key_valuesattention_interfacer   r   rL   rL   rM   r`      s@   


zRobertaSelfAttention.forwardFNNNNrj   rk   rl   r0   r?   rp   ro   r
   r   r   tupler`   rr   rL   rL   rJ   rM   r      s$    r   c                       sd   e Zd Zd fdd	Z			ddejdejdB dejdB dedB d	ee	 d
e
ej fddZ  ZS )RobertaCrossAttentionFNc                    s   t    |j|j dkrt|dstd|j d|j d|| _|j| _t|j|j | _| j| j | _	| jd | _
t|j| j	| _t|j| j	| _t|j| j	| _t|j| _|| _|| _d S r   )r/   r0   r4   r   rX   r   rI   re   r   r   ry   r1   r   ru   rv   rw   r;   r   r=   r   r   r   rJ   rL   rM   r0     s$   


zRobertaCrossAttention.__init__r   encoder_hidden_statesrx   r   rz   rQ   c                 K   sN  |j d d \}}|j d }||d| jf}	||d| jf}
| |j|	 dd}|d ur3|j| jnd}|d urL|rL|jj	| j j
}|jj	| j j}n-| |j|
 dd}| |j|
 dd}|d ury|j||| j\}}d|j| j< t| jjt}|| ||||f| jsdn| jj| jd|\}}|||d }||fS )Nr+   r#   r|   FTrs   r   )rY   r   ru   r   r   
is_updatedgetr   cross_attention_cachelayerskeysvaluesrv   rw   r   r   r   rI   r   r   r~   r=   r}   ry   r   r   )rH   r   r   rx   r   rz   bsztgt_lensrc_lenq_input_shapekv_input_shaper   r   r   r   r   r   r   rL   rL   rM   r`     sB   	


zRobertaCrossAttention.forwardr   r   )rj   rk   rl   r0   r?   rp   ro   r   r   r   r   r`   rr   rL   rL   rJ   rM   r     s$    r   c                       8   e Zd Z fddZdejdejdejfddZ  ZS )RobertaSelfOutputc                    sB   t    t|j|j| _tj|j|jd| _t|j	| _
d S Nr'   )r/   r0   r1   r   r4   denser9   r:   r;   r<   r=   rG   rJ   rL   rM   r0   U     
zRobertaSelfOutput.__init__r   input_tensorrQ   c                 C   &   |  |}| |}| || }|S Nr   r=   r9   rH   r   r   rL   rL   rM   r`   [     

zRobertaSelfOutput.forwardrj   rk   rl   r0   r?   rp   r`   rr   rL   rL   rJ   rM   r   T      $r   c                       s|   e Zd Zd fdd	Z					ddejdejdB dejdB dejdB d	edB d
ejdB dee	 de
ej fddZ  ZS )RobertaAttentionFNc                    s:   t    || _|rtnt}||||d| _t|| _d S )Nr   r   )r/   r0   is_cross_attentionr   r   rH   r   output)rH   rI   r   r   r   attention_classrJ   rL   rM   r0   c  s
   
zRobertaAttention.__init__r   rx   r   encoder_attention_maskr   r   rz   rQ   c           
      K   sB   | j s|n|}| j|f||||d|\}}	| ||}||	fS )N)r   rx   r   r   )r   rH   r   )
rH   r   rx   r   r   r   r   rz   attention_outputr   rL   rL   rM   r`   j  s   

zRobertaAttention.forward)FNFNNNNNr   rL   rL   rJ   rM   r   b  s0    
	r   c                       2   e Zd Z fddZdejdejfddZ  ZS )RobertaIntermediatec                    sD   t    t|j|j| _t|jt	rt
|j | _d S |j| _d S r   )r/   r0   r1   r   r4   intermediate_sizer   r   
hidden_actstrr   intermediate_act_fnrG   rJ   rL   rM   r0     s
   
zRobertaIntermediate.__init__r   rQ   c                 C   s   |  |}| |}|S r   )r   r   )rH   r   rL   rL   rM   r`     s   

zRobertaIntermediate.forwardr   rL   rL   rJ   rM   r     s    r   c                       r   )RobertaOutputc                    sB   t    t|j|j| _tj|j|jd| _t	|j
| _d S r   )r/   r0   r1   r   r   r4   r   r9   r:   r;   r<   r=   rG   rJ   rL   rM   r0     r   zRobertaOutput.__init__r   r   rQ   c                 C   r   r   r   r   rL   rL   rM   r`     r   zRobertaOutput.forwardr   rL   rL   rJ   rM   r     r   r   c                       s   e Zd Zd fdd	Z					ddejdejdB dejdB dejdB dedB d	ejdB d
ee	 de
ej fddZdd Z  ZS )RobertaLayerNc                    s~   t    |j| _d| _t||j|d| _|j| _|j| _| jr3| js*t|  dt|d|dd| _	t
|| _t|| _d S )Nr#   r   z> should be used as a decoder model if cross attention is addedFT)r   r   r   )r/   r0   chunk_size_feed_forwardseq_len_dimr   r   	attentionadd_cross_attentionr   crossattentionr   intermediater   r   )rH   rI   r   rJ   rL   rM   r0     s"   

zRobertaLayer.__init__r   rx   r   r   r   r   rz   rQ   c                 K   s   | j ||f||d|\}}	|}
| jr7|d ur7t| ds%td|  d| j|d ||fd|i|\}}	|}
t| j| j| j|
}|S )N)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`r   )	r   r   rX   r   r   r   feed_forward_chunkr   r   )rH   r   rx   r   r   r   r   rz   self_attention_output_r   cross_attention_outputlayer_outputrL   rL   rM   r`     s<   




zRobertaLayer.forwardc                 C   s   |  |}| ||}|S r   )r   r   )rH   r   intermediate_outputr   rL   rL   rM   r     s   
zRobertaLayer.feed_forward_chunkr   r   )rj   rk   rl   r0   r?   rp   ro   r
   r   r   r   r`   r   rr   rL   rL   rJ   rM   r     s2    	
)r   c                       sL   e Zd ZeZdZdZdZdZdZ	dZ
eeedZe  fddZ  ZS )RobertaPreTrainedModelrobertaT)r   
attentionscross_attentionsc                    sf   t  | t|trt|j dS t|tr1t|j	t
|j	jd d t|j dS dS )zInitialize the weightsr+   r*   N)r/   _init_weightsr   RobertaLMHeadinitzeros_biasr%   copy_r)   r?   r@   rY   rB   r-   )rH   rt   rJ   rL   rM   r     s   

"z$RobertaPreTrainedModel._init_weights)rj   rk   rl   r$   config_classbase_model_prefixsupports_gradient_checkpointing_supports_flash_attn_supports_sdpa_supports_flex_attn_supports_attention_backendr   r   r   _can_record_outputsr?   no_gradr   rr   rL   rL   rJ   rM   r     s    r   c                       s   e Zd Z fddZ						ddejdejdB dejdB dejdB dedB d	edB d
ejdB de	e
 deej eB fddZ  ZS )RobertaEncoderc                    s4   t     | _t fddt jD | _d S )Nc                    s   g | ]}t  |d qS ))r   )r   ).0irI   rL   rM   
<listcomp>  s    z+RobertaEncoder.__init__.<locals>.<listcomp>)r/   r0   rI   r1   
ModuleListrangenum_hidden_layerslayerrG   rJ   r   rM   r0     s   
$zRobertaEncoder.__init__Nr   rx   r   r   r   	use_cacher   rz   rQ   c                 K   sH   t | jD ]\}	}
|
|||f|||d|}qt||r |dS d dS )N)r   r   r   )last_hidden_stater   )	enumerater   r   )rH   r   rx   r   r   r   r   r   rz   r   layer_modulerL   rL   rM   r`     s$   
zRobertaEncoder.forwardNNNNNN)rj   rk   rl   r0   r?   rp   ro   r
   boolr   r   r   r   r`   rr   rL   rL   rJ   rM   r     s6    	
r   c                       r   )RobertaPoolerc                    s*   t    t|j|j| _t | _d S r   )r/   r0   r1   r   r4   r   Tanh
activationrG   rJ   rL   rM   r0     s   
zRobertaPooler.__init__r   rQ   c                 C   s(   |d d df }|  |}| |}|S Nr   )r   r  )rH   r   first_token_tensorpooled_outputrL   rL   rM   r`   #  s   

zRobertaPooler.forwardr   rL   rL   rJ   rM   r    s    r  a
  
    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](https://huggingface.co/papers/1706.03762) 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.
    )custom_introc                       s   e Zd ZddgZd fdd	Zdd Zdd	 Zeee		
	
	
	
	
	
	
	
	
	
dde
jd
B de
jd
B de
jd
B de
jd
B de
jd
B de
jd
B de
jd
B ded
B ded
B de
jd
B dee dee
j eB fddZdd Z  ZS )RobertaModelr%   r   Tc                    sJ   t  | || _d| _t|| _t|| _|rt|nd| _	| 
  dS )zv
        add_pooling_layer (bool, *optional*, defaults to `True`):
            Whether to add a pooling layer
        FN)r/   r0   rI   gradient_checkpointingr%   r_   r   encoderr  pooler	post_init)rH   rI   add_pooling_layerrJ   rL   rM   r0   ;  s   

zRobertaModel.__init__c                 C      | j jS r   r_   r6   rH   rL   rL   rM   get_input_embeddingsL     z!RobertaModel.get_input_embeddingsc                 C      || j _d S r   r  )rH   rw   rL   rL   rM   set_input_embeddingsO     z!RobertaModel.set_input_embeddingsNrN   rx   r-   r)   rO   r   r   r   r   r   rz   rQ   c              
   K   sT  | j jr|	d ur
|	n| j j}	nd}	|	r2|d u r2|d us| j jr,tt| j dt| j dnt| j d}|d u |d uA r>td|d urK|j}|jd }n|j}|jd }|d ur[|	 nd}|
d u rkt
j||| |d}
| j|||||d}| j|||||
|d\}}| j|f|||||	|
|d	|}|j}| jd ur| |nd }t|||jd
S )NFr   z:You must specify exactly one of input_ids or inputs_embedsr#   r   )rU   )rN   r)   r-   rO   rP   )rx   r   embedding_outputr   r   r   )rx   r   r   r   r   r   r)   )r   pooler_outputr   )rI   r   r   is_encoder_decoderr   r   r   rU   rY   get_seq_lengthr?   r@   r_   _create_attention_masksr  r   r  r   r   )rH   rN   rx   r-   r)   rO   r   r   r   r   r   rz   rU   r]   rP   r  encoder_outputssequence_outputr  rL   rL   rM   r`   R  sj   


		zRobertaModel.forwardc                 C   sP   | j jrt| j ||||d}nt| j ||d}|d ur$t| j |||d}||fS )N)rI   rO   rx   r   r   )rI   rO   rx   )rI   rO   rx   r   )rI   r   r   r   )rH   rx   r   r  r   r   r   rL   rL   rM   r    s*   	z$RobertaModel._create_attention_masks)T)
NNNNNNNNNN)rj   rk   rl   _no_split_modulesr0   r  r  r!   r"   r   r?   rp   r
   r  r   r   r   r   r`   r  rr   rL   rL   rJ   rM   r	  ,  sX    	
Mr	  zS
    RoBERTa Model with a `language modeling` head on top for CLM fine-tuning.
    c                        s   e Zd ZdddZ fddZdd Zdd	 Zee	
	
	
	
	
	
	
	
	
	
	
	dde	j
d
B de	jd
B de	j
d
B de	j
d
B de	jd
B de	jd
B de	jd
B de	j
d
B deee	j  d
B ded
B de	jd
B dee	jB dee dee	j eB fddZ  ZS )RobertaForCausalLM)roberta.embeddings.word_embeddings.weightlm_head.biaszlm_head.decoder.weightz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/   r0   r   loggerwarningr	  r   r   lm_headr  rG   rJ   rL   rM   r0     s   

zRobertaForCausalLM.__init__c                 C   r  r   r'  decoderr  rL   rL   rM   get_output_embeddings  r  z(RobertaForCausalLM.get_output_embeddingsc                 C   r  r   r(  rH   new_embeddingsrL   rL   rM   set_output_embeddings  r  z(RobertaForCausalLM.set_output_embeddingsNr   rN   rx   r-   r)   rO   r   r   labelsr   r   r   logits_to_keeprz   rQ   c                 K   s   |durd}
| j |f|||||||	|
|dd
|}|j}t|tr(t| dn|}| |dd|ddf }d}|durL| jd||| jjd|}t	|||j
|j|j|jdS )am  
        token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *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)
        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]`

        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
        ```NFT)
rx   r-   r)   rO   r   r   r   r   r   return_dict)logitsr.  r3   )lossr1  r   r   r   r   rL   )r   r   r   re   slicer'  loss_functionrI   r3   r   r   r   r   r   )rH   rN   rx   r-   r)   rO   r   r   r.  r   r   r   r/  rz   outputsr   slice_indicesr1  r2  rL   rL   rM   r`     s@   1zRobertaForCausalLM.forward)NNNNNNNNNNNr   )rj   rk   rl   _tied_weights_keysr0   r*  r-  r    r   r?   rn   ro   r   r  rp   re   r   r   r   r`   rr   rL   rL   rJ   rM   r    sd    	
r  c                       s   e Zd ZdddZ fddZdd Zdd	 Zee	
	
	
	
	
	
	
	
dde	j
d
B de	jd
B de	j
d
B de	j
d
B de	jd
B de	jd
B de	jd
B de	j
d
B dee dee	j eB fddZ  ZS )RobertaForMaskedLMr   r!  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$  rG   rJ   rL   rM   r0   ?  s   
zRobertaForMaskedLM.__init__c                 C   r  r   r(  r  rL   rL   rM   r*  N  r  z(RobertaForMaskedLM.get_output_embeddingsc                 C   r  r   r(  r+  rL   rL   rM   r-  Q  r  z(RobertaForMaskedLM.set_output_embeddingsNrN   rx   r-   r)   rO   r   r   r.  rz   rQ   c	              
   K   s   | j |f||||||dd|	}
|
d }| |}d}|dur7||j}t }||d| jj|d}t|||
j	|
j
dS )a  
        token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *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)
        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]`
        T)rx   r-   r)   rO   r   r   r0  r   Nr+   r2  r1  r   r   )r   r'  torU   r   r   rI   r3   r   r   r   )rH   rN   rx   r-   r)   rO   r   r   r.  rz   r5  r  prediction_scoresmasked_lm_lossloss_fctrL   rL   rM   r`   T  s4   	
zRobertaForMaskedLM.forward)NNNNNNNN)rj   rk   rl   r7  r0   r*  r-  r    r   r?   rn   ro   r   r   r   rp   r   r`   rr   rL   rL   rJ   rM   r8  8  sL    	
r8  c                       (   e Zd ZdZ fddZdd Z  ZS )r   z*Roberta Head for masked language modeling.c                    sZ   t    t|j|j| _tj|j|jd| _t|j|j	| _
tt|j	| _d S r   )r/   r0   r1   r   r4   r   r9   r:   
layer_normr3   r)  	Parameterr?   rC   r   rG   rJ   rL   rM   r0     s
   
zRobertaLMHead.__init__c                 K   s*   |  |}t|}| |}| |}|S r   )r   r	   r?  r)  rH   featuresrz   xrL   rL   rM   r`     s
   


zRobertaLMHead.forwardrj   rk   rl   rm   r0   r`   rr   rL   rL   rJ   rM   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                          e Zd Z fddZee						ddejdB dejdB dejdB dejdB dejdB d	ejdB d
e	e
 deej eB fddZ  ZS ) RobertaForSequenceClassificationc                    s>   t  | |j| _|| _t|dd| _t|| _|   d S NFr#  )	r/   r0   
num_labelsrI   r	  r   RobertaClassificationHead
classifierr  rG   rJ   rL   rM   r0     s   
z)RobertaForSequenceClassification.__init__NrN   rx   r-   r)   rO   r.  rz   rQ   c                 K   s6  | j |f||||dd|}|d }	| |	}
d}|dur||
j}| jjdu rN| jdkr4d| j_n| jdkrJ|jtj	ksE|jtj
krJd| j_nd| j_| jjdkrlt }| jdkrf||
 | }n+||
|}n%| jjdkrt }||
d	| j|d	}n| jjdkrt }||
|}t||
|j|jd
S )a  
        token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *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)
        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).
        Trx   r-   r)   rO   r0  r   Nr#   
regressionsingle_label_classificationmulti_label_classificationr+   r9  )r   rJ  r:  rU   rI   problem_typerH  r.   r?   rE   re   r   squeezer   r   r   r   r   r   rH   rN   rx   r-   r)   rO   r.  rz   r5  r  r1  r2  r=  rL   rL   rM   r`     sN   	


"


z(RobertaForSequenceClassification.forwardr   )rj   rk   rl   r0   r    r   r?   rn   ro   r   r   r   rp   r   r`   rr   rL   rL   rJ   rM   rF    s6    	rF  c                       s   e Zd Z fddZee						ddejdB dejdB dejdB dejdB dejdB d	ejdB d
e	e
 deej eB fddZ  ZS )RobertaForMultipleChoicec                    s@   t  | t|| _t|j| _t|j	d| _
|   d S )Nr#   )r/   r0   r	  r   r1   r;   r<   r=   r   r4   rJ  r  rG   rJ   rL   rM   r0      s
   
z!RobertaForMultipleChoice.__init__NrN   r-   rx   r.  r)   rO   rz   rQ   c                 K   s<  |dur	|j d n|j d }|dur|d|dnd}	|dur*|d|dnd}
|dur9|d|dnd}|durH|d|dnd}|dur[|d|d|dnd}| j|	f|
|||dd|}|d }| |}| |}|d|}d}|dur||j}t }|||}t	|||j
|jdS )a  
        input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
            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)
        token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *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)
        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)
        position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *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)
        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, 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.
        Nr#   r+   T)r)   r-   rx   rO   r0  r9  )rY   r   rD   r   r=   rJ  r:  rU   r   r   r   r   )rH   rN   r-   rx   r.  r)   rO   rz   num_choicesflat_input_idsflat_position_idsflat_token_type_idsflat_attention_maskflat_inputs_embedsr5  r  r1  reshaped_logitsr2  r=  rL   rL   rM   r`   
  sF   +	


z RobertaForMultipleChoice.forwardr   )rj   rk   rl   r0   r    r   r?   rn   ro   r   r   r   rp   r   r`   rr   rL   rL   rJ   rM   rR    s6    
	rR  c                       rE  )RobertaForTokenClassificationc                    sb   t  | |j| _t|dd| _|jd ur|jn|j}t|| _	t
|j|j| _|   d S rG  )r/   r0   rH  r	  r   classifier_dropoutr<   r1   r;   r=   r   r4   rJ  r  rH   rI   r\  rJ   rL   rM   r0   a  s   z&RobertaForTokenClassification.__init__NrN   rx   r-   r)   rO   r.  rz   rQ   c                 K   s   | j |f||||dd|}|d }	| |	}	| |	}
d}|dur9||
j}t }||
d| j|d}t||
|j	|j
dS )a-  
        token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *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)
        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]`.
        TrK  r   Nr+   r9  )r   r=   rJ  r:  rU   r   r   rH  r   r   r   rQ  rL   rL   rM   r`   o  s2   


z%RobertaForTokenClassification.forwardr   )rj   rk   rl   r0   r    r   r?   rn   ro   r   r   r   rp   r   r`   rr   rL   rL   rJ   rM   r[  _  s6    	r[  c                       r>  )rI  z-Head for sentence-level classification tasks.c                    sT   t    t|j|j| _|jd ur|jn|j}t|| _	t|j|j
| _d S r   )r/   r0   r1   r   r4   r   r\  r<   r;   r=   rH  out_projr]  rJ   rL   rM   r0     s   
z"RobertaClassificationHead.__init__c                 K   sL   |d d dd d f }|  |}| |}t|}|  |}| |}|S r  )r=   r   r?   tanhr^  rA  rL   rL   rM   r`     s   




z!RobertaClassificationHead.forwardrD  rL   rL   rJ   rM   rI    s    	rI  c                       s   e Zd Z fddZee							ddejdB dejdB dejdB dejdB dejdB d	ejdB d
ejdB de	e
 deej eB fddZ  ZS )RobertaForQuestionAnsweringc                    s@   t  | |j| _t|dd| _t|j|j| _| 	  d S rG  )
r/   r0   rH  r	  r   r1   r   r4   
qa_outputsr  rG   rJ   rL   rM   r0     s
   z$RobertaForQuestionAnswering.__init__NrN   rx   r-   r)   rO   start_positionsend_positionsrz   rQ   c                 K   s  | j |f||||dd|}	|	d }
| |
}|jddd\}}|d }|d }d}|dury|duryt| dkrF|d}t| dkrS|d}|d}|d|}|d|}t|d}|||}|||}|| d	 }t	||||	j
|	jd
S )a[  
        token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *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)
        TrK  r   r#   r+   rc   N)ignore_indexr|   )r2  start_logits
end_logitsr   r   )r   ra  splitrP  r   lenrD   clampr   r   r   r   )rH   rN   rx   r-   r)   rO   rb  rc  rz   r5  r  r1  re  rf  
total_lossignored_indexr=  
start_lossend_lossrL   rL   rM   r`     sH   







z#RobertaForQuestionAnswering.forward)NNNNNNN)rj   rk   rl   r0   r    r   r?   rn   ro   r   r   r   rp   r   r`   rr   rL   rL   rJ   rM   r`    s<    
	
r`  )r  r8  rR  r`  rF  r[  r	  r   )Nrs   )Pcollections.abcr   r?   torch.nnr1   r   r   r    r   r   activationsr   r	   cache_utilsr
   r   r   
generationr   masking_utilsr   r   modeling_layersr   modeling_outputsr   r   r   r   r   r   r   r   modeling_utilsr   r   processing_utilsr   pytorch_utilsr   utilsr   r   r   utils.genericr    r!   utils.output_capturingr"   configuration_robertar$   
get_loggerrj   r%  Moduler%   rp   floatr   r   r   r   r   r   r   r   r   r   r  r	  r  r8  r   rF  rR  r[  rI  r`  __all__rL   rL   rL   rM   <module>   s   (

p
IMC" nUT`FN