U
    5Af-
                    @   s  d 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Zddlm	Z	 ddl
mZmZmZ ddlmZ ddlmZmZmZ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+dd Z,G dd de	j-Z.G dd de	j-Z/G dd de	j-Z0G dd de	j-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	j-Z8G d(d) d)e	j-Z9G d*d+ d+eZ:d,Z;d-Z<e!d.e;G d/d0 d0e:Z=e!d1e;G d2d3 d3e:Z>e!d4e;G d5d6 d6e:Z?e!d7e;G d8d9 d9e:Z@e!d:e;G d;d< d<e:ZAe!d=e;G d>d? d?e:ZBe!d@e;G dAdB dBe:ZCdS )CzPyTorch RemBERT model.    N)OptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN))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   )RemBertConfigr   google/rembertc                    s   zddl }ddl}ddl}W n  tk
r<   td  Y nX tj|}t	d|  |j
|}g }g }	|D ]X\ }
t fdddD rqrt	d  d	|
  |j
| }|  |	| qrt||	D ]"\ } d
d  d tdd  D r"t	dd   q| } D ]}|d|rL|d|}n|g}|d dksn|d dkrzt|d}n|d dks|d dkrt|d}nz|d dkrt|d}n`|d dkrt|d}nFzt||d }W n2 tk
r   t	dd  Y q*Y nX t|dkr*t|d }|| }q*|dd dkr`t|d}n|dkrt||}z,|j|jkrtd|j d |j d!W n< tk
r } z| j|j|jf7  _ W 5 d}~X Y nX t	d"   t||_ q| 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 c                 3   s   | ]}| kV  qd S N ).0Zdenynamer    P/tmp/pip-unpacked-wheel-zw5xktn0/transformers/models/rembert/modeling_rembert.py	<genexpr>M   s     z-load_tf_weights_in_rembert.<locals>.<genexpr>)adam_vadam_mZoutput_embeddingclszLoading TF weight z with shape zbert/zrembert//c                 s   s   | ]}|d kV  qdS ))r&   r'   ZAdamWeightDecayOptimizerZAdamWeightDecayOptimizer_1Zglobal_stepNr    )r!   nr    r    r$   r%   ^   s   z	Skipping z[A-Za-z]+_\d+z_(\d+)kernelgammaweightZoutput_biasbetabiasZoutput_weightsZsquad
classifierzSkipping {}   r   iZ_embeddingszPointer shape z and array shape z mismatchedzInitialize PyTorch weight )!reZnumpyZ
tensorflowImportErrorloggererrorospathabspathinfoZtrainZlist_variablesanyZload_variableappendzipreplacesplitjoin	fullmatchgetattrAttributeErrorformatlenint	transposeshape
ValueErrorAssertionErrorargstorchZ
from_numpydata)modelconfigZtf_checkpoint_pathr2   nptfZtf_pathZ	init_varsnamesZarraysrG   arraypointerZm_nameZscope_namesnumer    r"   r$   load_tf_weights_in_rembert7   s~    





rV   c                       sT   e Zd ZdZ fddZd	eej eej eej eej e	ej
dddZ  ZS )
RemBertEmbeddingszGConstruct the embeddings from word, position and token_type embeddings.c                    s   t    tj|j|j|jd| _t|j|j| _	t|j
|j| _tj|j|jd| _t|j| _| jdt|jddd d S )N)padding_idxZepsposition_ids)r   F)
persistent)super__init__r   	Embedding
vocab_sizeinput_embedding_sizepad_token_idword_embeddingsZmax_position_embeddingsposition_embeddingsZtype_vocab_sizetoken_type_embeddings	LayerNormlayer_norm_epsDropouthidden_dropout_probdropoutZregister_bufferrK   ZarangeexpandselfrN   	__class__r    r$   r^      s    
    zRemBertEmbeddings.__init__Nr   )	input_idstoken_type_idsrZ   inputs_embedspast_key_values_lengthreturnc                 C   s   |d k	r|  }n|  d d }|d }|d krL| jd d ||| f }|d krjtj|tj| jjd}|d kr|| |}| |}|| }	| |}
|	|
7 }	| 	|	}	| 
|	}	|	S )Nr[   r   dtypedevice)sizerZ   rK   zeroslongrw   rc   re   rd   rf   rj   )rm   rp   rq   rZ   rr   rs   input_shape
seq_lengthre   
embeddingsrd   r    r    r$   forward   s"    





zRemBertEmbeddings.forward)NNNNr   )__name__
__module____qualname____doc__r^   r   rK   
LongTensorFloatTensorrE   Tensorr~   __classcell__r    r    rn   r$   rW      s        rW   c                       s0   e Zd Z fddZejejdddZ  ZS )RemBertPoolerc                    s*   t    t|j|j| _t | _d S r   )r]   r^   r   Linearhidden_sizedenseZTanh
activationrl   rn   r    r$   r^      s    
zRemBertPooler.__init__hidden_statesrt   c                 C   s(   |d d df }|  |}| |}|S )Nr   )r   r   )rm   r   Zfirst_token_tensorpooled_outputr    r    r$   r~      s    

zRemBertPooler.forwardr   r   r   r^   rK   r   r~   r   r    r    rn   r$   r      s   r   c                
       sf   e Zd Z 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j  e
e	ddd	Z  ZS )RemBertSelfAttentionc                    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| _|j| _d S )Nr   Zembedding_sizezThe hidden size (z6) is not a multiple of the number of attention heads ())r]   r^   r   num_attention_headshasattrrH   rE   attention_head_sizeall_head_sizer   r   querykeyvaluerh   Zattention_probs_dropout_probrj   
is_decoderrl   rn   r    r$   r^      s    
zRemBertSelfAttention.__init__c                 C   s6   |  d d | j| jf }|j| }|ddddS )Nr[   r   r1   r   r	   )rx   r   r   viewpermute)rm   xZnew_x_shaper    r    r$   transpose_for_scores   s    
z)RemBertSelfAttention.transpose_for_scoresNFr   attention_mask	head_maskencoder_hidden_statesencoder_attention_maskpast_key_valueoutput_attentionsrt   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 | | |}
| | |}| |}| jr|
|f}t||
dd}|t	
| j }|d k	r"|| }tjj|dd}| |}|d k	rN|| }t||}|dddd }| d d | jf }|j| }|r||fn|f}| jr||f }|S )Nr   r   r1   Zdimr[   r	   )r   r   r   r   rK   catr   matmulrF   mathsqrtr   r   Z
functionalZsoftmaxrj   r   
contiguousrx   r   r   )rm   r   r   r   r   r   r   r   Zmixed_query_layerZis_cross_attentionZ	key_layerZvalue_layerZquery_layerZattention_scoresZattention_probsZcontext_layerZnew_context_layer_shapeoutputsr    r    r$   r~      sH    







zRemBertSelfAttention.forward)NNNNNF)r   r   r   r^   r   rK   r   r   r   r   boolr~   r   r    r    rn   r$   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 )RemBertSelfOutputc                    sB   t    t|j|j| _tj|j|jd| _t|j	| _
d S NrY   )r]   r^   r   r   r   r   rf   rg   rh   ri   rj   rl   rn   r    r$   r^   ;  s    
zRemBertSelfOutput.__init__r   input_tensorrt   c                 C   s&   |  |}| |}| || }|S r   r   rj   rf   rm   r   r   r    r    r$   r~   A  s    

zRemBertSelfOutput.forwardr   r    r    rn   r$   r   :  s   r   c                
       st   e Zd Z 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 )RemBertAttentionc                    s*   t    t|| _t|| _t | _d S r   )r]   r^   r   rm   r   outputsetpruned_headsrl   rn   r    r$   r^   I  s    


zRemBertAttention.__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   r   )rD   r   rm   r   r   r   r   r   r   r   r   r   r   union)rm   headsindexr    r    r$   prune_headsP  s       zRemBertAttention.prune_headsNFr   c              	   C   s<   |  |||||||}| |d |}	|	f|dd   }
|
S )Nr   r   )rm   r   )rm   r   r   r   r   r   r   r   Zself_outputsattention_outputr   r    r    r$   r~   c  s    
	zRemBertAttention.forward)NNNNNF)r   r   r   r^   r   rK   r   r   r   r   r   r~   r   r    r    rn   r$   r   H  s$         r   c                       s0   e Zd Z fddZejejdddZ  ZS )RemBertIntermediatec                    sB   t    t|j|j| _t|jt	r6t
|j | _n|j| _d S r   )r]   r^   r   r   r   intermediate_sizer   
isinstance
hidden_actstrr
   intermediate_act_fnrl   rn   r    r$   r^   }  s
    
zRemBertIntermediate.__init__r   c                 C   s   |  |}| |}|S r   )r   r   rm   r   r    r    r$   r~     s    

zRemBertIntermediate.forwardr   r    r    rn   r$   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 )RemBertOutputc                    sB   t    t|j|j| _tj|j|jd| _t	|j
| _d S r   )r]   r^   r   r   r   r   r   rf   rg   rh   ri   rj   rl   rn   r    r$   r^     s    
zRemBertOutput.__init__r   c                 C   s&   |  |}| |}| || }|S r   r   r   r    r    r$   r~     s    

zRemBertOutput.forwardr   r    r    rn   r$   r     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 )RemBertLayerc                    sn   t    |j| _d| _t|| _|j| _|j| _| jrV| jsLt|  dt|| _	t
|| _t|| _d S )Nr   z> should be used as a decoder model if cross attention is added)r]   r^   chunk_size_feed_forwardseq_len_dimr   	attentionr   add_cross_attentionrH   crossattentionr   intermediater   r   rl   rn   r    r$   r^     s    



zRemBertLayer.__init__NFr   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 )
Nr1   )r   r   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`r   )	r   r   r   rH   r   r   feed_forward_chunkr   r   )rm   r   r   r   r   r   r   r   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_outputr    r    r$   r~     sV    


	   

zRemBertLayer.forwardc                 C   s   |  |}| ||}|S r   )r   r   )rm   r   Zintermediate_outputr   r    r    r$   r     s    
zRemBertLayer.feed_forward_chunk)NNNNNF)r   r   r   r^   rK   r   r   r   r   r   r~   r   r   r    r    rn   r$   r     s$         Br   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	e	e
eef dddZ  ZS )
RemBertEncoderc                    sL   t     | _t j j| _t fddt	 j
D | _d| _d S )Nc                    s   g | ]}t  qS r    )r   )r!   _rN   r    r$   
<listcomp>  s     z+RemBertEncoder.__init__.<locals>.<listcomp>F)r]   r^   rN   r   r   ra   r   embedding_hidden_mapping_inZ
ModuleListrangenum_hidden_layerslayergradient_checkpointingrl   rn   r   r$   r^     s
    
 zRemBertEncoder.__init__NFT)r   r   r   r   r   past_key_values	use_cacher   output_hidden_statesreturn_dictrt   c                 C   sl  | j r| jr|rtd d}| |}|	r0dnd }|r<dnd }|rP| jjrPdnd }|r\dnd }t| jD ]\}}|	r||f }|d k	r|| nd }|d k	r|| nd }| j r| jr| 	|j
|||||||}n||||||||}|d }|r||d f7 }|rj||d f }| jjrj||d f }qj|	r8||f }|
sZtdd	 |||||fD S t|||||d
S )NzZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fr    r   r[   r   r1   c                 s   s   | ]}|d k	r|V  qd S r   r    )r!   vr    r    r$   r%   =  s   z)RemBertEncoder.forward.<locals>.<genexpr>)last_hidden_stater   r   
attentionscross_attentions)r   Ztrainingr4   Zwarning_oncer   rN   r   	enumerater   Z_gradient_checkpointing_func__call__tupler   )rm   r   r   r   r   r   r   r   r   r   r   Zall_hidden_statesZall_self_attentionsZall_cross_attentionsZnext_decoder_cacheiZlayer_moduleZlayer_head_maskr   Zlayer_outputsr    r    r$   r~     sz    



zRemBertEncoder.forward)	NNNNNNFFT)r   r   r   r^   rK   r   r   r   r   r   r   r   r~   r   r    r    rn   r$   r     s.            
r   c                       s0   e Zd Z fddZejejdddZ  ZS )RemBertPredictionHeadTransformc                    sV   t    t|j|j| _t|jtr6t	|j | _
n|j| _
tj|j|jd| _d S r   )r]   r^   r   r   r   r   r   r   r   r
   transform_act_fnrf   rg   rl   rn   r    r$   r^   S  s    
z'RemBertPredictionHeadTransform.__init__r   c                 C   s"   |  |}| |}| |}|S r   )r   r   rf   r   r    r    r$   r~   \  s    


z&RemBertPredictionHeadTransform.forwardr   r    r    rn   r$   r   R  s   	r   c                       s0   e Zd Z fddZejejdddZ  ZS )RemBertLMPredictionHeadc                    sR   t    t|j|j| _t|j|j| _t	|j
 | _tj|j|jd| _d S r   )r]   r^   r   r   r   Zoutput_embedding_sizer   r`   decoderr
   r   r   rf   rg   rl   rn   r    r$   r^   d  s
    
z RemBertLMPredictionHead.__init__r   c                 C   s,   |  |}| |}| |}| |}|S r   )r   r   rf   r   r   r    r    r$   r~   k  s
    



zRemBertLMPredictionHead.forwardr   r    r    rn   r$   r   c  s   r   c                       s0   e Zd Z fddZejejdddZ  ZS )RemBertOnlyMLMHeadc                    s   t    t|| _d S r   )r]   r^   r   predictionsrl   rn   r    r$   r^   u  s    
zRemBertOnlyMLMHead.__init__)sequence_outputrt   c                 C   s   |  |}|S r   )r   )rm   r   prediction_scoresr    r    r$   r~   y  s    
zRemBertOnlyMLMHead.forwardr   r    r    rn   r$   r   t  s   r   c                   @   s(   e Zd ZdZeZeZdZdZ	dd Z
dS )RemBertPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    rembertTc                 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   r   r-   rL   Znormal_rN   Zinitializer_ranger/   Zzero_r_   rX   rf   Zfill_)rm   moduler    r    r$   _init_weights  s    

z$RemBertPreTrainedModel._init_weightsN)r   r   r   r   r   config_classrV   Zload_tf_weightsZbase_model_prefixZsupports_gradient_checkpointingr   r    r    r    r$   r   ~  s   r   aJ  
    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
    it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
    behavior.

    Parameters:
        config ([`RemBertConfig`]): 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.
a5
  
    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.

            [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 RemBERT 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deeddejeej eej eej eej eej eej eej eeeej   ee ee ee ee eeef dddZ  ZS )RemBertModela  

    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://arxiv.org/abs/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.
    Tc                    sD   t  | || _t|| _t|| _|r2t|nd | _| 	  d S r   )
r]   r^   rN   rW   r}   r   encoderr   pooler	post_init)rm   rN   add_pooling_layerrn   r    r$   r^     s    

zRemBertModel.__init__c                 C   s   | j jS r   r}   rc   rm   r    r    r$   get_input_embeddings  s    z!RemBertModel.get_input_embeddingsc                 C   s   || j _d S r   r   )rm   r   r    r    r$   set_input_embeddings  s    z!RemBertModel.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   )rm   Zheads_to_pruner   r   r    r    r$   _prune_heads  s    zRemBertModel._prune_headsbatch_size, sequence_lengthr   
checkpointoutput_typer   N)rp   r   rq   rZ   r   rr   r   r   r   r   r   r   r   rt   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r.tj|tj|d	}| ||}| j jr|dk	r| \}}}||f}|dkr|tj||d}| |}nd}| || j j}| j|||||d
}| j||||||	|
|||d
}|d }| jdk	r| |nd}|s
||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   r1   )rw   ru   )rp   rZ   rq   rr   rs   )	r   r   r   r   r   r   r   r   r   r   )r   Zpooler_outputr   r   r   r   )rN   r   r   use_return_dictr   r   rH   Z%warn_if_padding_and_no_attention_maskrx   rw   rG   rK   Zonesry   rz   Zget_extended_attention_maskZinvert_attention_maskZget_head_maskr   r}   r   r   r   r   r   r   r   )rm   rp   r   rq   rZ   r   rr   r   r   r   r   r   r   r   r{   Z
batch_sizer|   rw   rs   Zextended_attention_maskZencoder_batch_sizeZencoder_sequence_lengthr   Zencoder_hidden_shapeZencoder_extended_attention_maskZembedding_outputZencoder_outputsr   r   r    r    r$   r~     s|    )




zRemBertModel.forward)T)NNNNNNNNNNNNN)r   r   r   r   r^   r   r   r   r   REMBERT_INPUTS_DOCSTRINGrC   r   r   _CONFIG_FOR_DOCrK   r   r   r   r   r   r   r   r~   r   r    r    rn   r$   r     sP                
r   z5RemBERT Model with a `language modeling` head on top.c                       s   e Zd ZdgZ fddZdd Zdd Zee	de
d	eed
dejeej eej eej eej eej eej eej eej ee ee ee eeef dddZdddZ  ZS )RemBertForMaskedLMcls.predictions.decoder.weightc                    s@   t  | |jrtd t|dd| _t|| _| 	  d S )NznIf you want to use `RemBertForMaskedLM` make sure `config.is_decoder=False` for bi-directional self-attention.Fr   
r]   r^   r   r4   warningr   r   r   r(   r   rl   rn   r    r$   r^     s    
zRemBertForMaskedLM.__init__c                 C   s
   | j jjS r   r(   r   r   r   r    r    r$   get_output_embeddings  s    z(RemBertForMaskedLM.get_output_embeddingsc                 C   s   || j j_d S r   r  rm   Znew_embeddingsr    r    r$   set_output_embeddings  s    z(RemBertForMaskedLM.set_output_embeddingsr   r   r   N)rp   r   rq   rZ   r   rr   r   r   labelsr   r   r   rt   c                 C   s   |dk	r|n| j j}| j|||||||||
||d}|d }| |}d}|	dk	rtt }||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]`.
        N)
r   rq   rZ   r   rr   r   r   r   r   r   r   r[   r1   losslogitsr   r   )
rN   r   r   r(   r   r   r`   r   r   r   )rm   rp   r   rq   rZ   r   rr   r   r   r  r   r   r   r   r   r   Zmasked_lm_lossloss_fctr   r    r    r$   r~     s:    
zRemBertForMaskedLM.forwardc                 K   s~   |j }|d }| jjd k	s"tdtj|||j d dfgdd}tj|df| jjtj|j	d}tj||gdd}||dS )Nr   z.The PAD token should be defined for generationr   r[   r   ru   )rp   r   )
rG   rN   rb   rI   rK   r   Z	new_zerosfullrz   rw   )rm   rp   r   model_kwargsr{   Zeffective_batch_sizeZdummy_tokenr    r    r$   prepare_inputs_for_generation  s    "   z0RemBertForMaskedLM.prepare_inputs_for_generation)NNNNNNNNNNNN)N)r   r   r   _tied_weights_keysr^   r  r
  r   r   rC   r   r   r  rK   r   r   r   r   r   r   r~   r  r   r    r    rn   r$   r    sL               
8r  zIRemBERT Model with a `language modeling` head on top for CLM fine-tuning.c                       s   e Zd ZdgZ fddZdd Zdd Zee	de
eed	dejeej eej eej eej eej eej eej eeeej   eej ee ee ee ee eeef dddZdddZdd Z  ZS )RemBertForCausalLMr  c                    s@   t  | |jstd t|dd| _t|| _| 	  d S )NzOIf you want to use `RemBertForCausalLM` as a standalone, add `is_decoder=True.`Fr  r  rl   rn   r    r$   r^     s    

zRemBertForCausalLM.__init__c                 C   s
   | j jjS r   r  r   r    r    r$   r    s    z(RemBertForCausalLM.get_output_embeddingsc                 C   s   || j j_d S r   r  r	  r    r    r$   r
    s    z(RemBertForCausalLM.set_output_embeddingsr   )r   r   N)rp   r   rq   rZ   r   rr   r   r   r   r  r   r   r   r   rt   c                 C   s   |dk	r|n| j j}| j|||||||||	||||d}|d }| |}d}|
dk	r|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 )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)`.
        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 n `[0, ..., config.vocab_size]`.
        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, RemBertForCausalLM, RemBertConfig
        >>> import torch

        >>> tokenizer = AutoTokenizer.from_pretrained("google/rembert")
        >>> config = RemBertConfig.from_pretrained("google/rembert")
        >>> config.is_decoder = True
        >>> model = RemBertForCausalLM.from_pretrained("google/rembert", config=config)

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

        >>> prediction_logits = outputs.logits
        ```N)r   rq   rZ   r   rr   r   r   r   r   r   r   r   r   r[   r   r1   )r  r  r   r   r   r   )rN   r   r   r(   r   r   r   r`   r   r   r   r   r   )rm   rp   r   rq   rZ   r   rr   r   r   r   r  r   r   r   r   r   r   r   Zlm_lossZshifted_prediction_scoresr  r   r    r    r$   r~     sF    <
zRemBertForCausalLM.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   r1   r   )rp   r   r   )rG   Znew_ones)rm   rp   r   r   r  r{   Zpast_lengthZremove_prefix_lengthr    r    r$   r  h  s    
z0RemBertForCausalLM.prepare_inputs_for_generationc                    sB   d}|D ]4}|t  fdd|d d D |dd   f7 }q|S )Nr    c                 3   s"   | ]}| d  |jV  qdS )r   N)Zindex_selecttorw   )r!   Z
past_statebeam_idxr    r$   r%     s     z4RemBertForCausalLM._reorder_cache.<locals>.<genexpr>r1   )r   )rm   r   r  Zreordered_pastZ
layer_pastr    r  r$   _reorder_cache~  s    
z!RemBertForCausalLM._reorder_cache)NNNNNNNNNNNNNN)NN)r   r   r   r  r^   r  r
  r   r   rC   r   r   r  rK   r   r   r   r   r   r   r~   r  r  r   r    r    rn   r$   r    sN   
              
d
r  z
    RemBERT 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
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f ddd	Z  ZS ) RemBertForSequenceClassificationc                    sJ   t  | |j| _t|| _t|j| _t	|j
|j| _|   d S r   r]   r^   
num_labelsr   r   r   rh   classifier_dropout_probrj   r   r   r0   r   rl   rn   r    r$   r^     s    
z)RemBertForSequenceClassification.__init__r   r   r   Nrp   r   rq   rZ   r   rr   r  r   r   r   rt   c                 C   s|  |
dk	r|
n| j j}
| j||||||||	|
d	}|d }| |}| |}d}|dk	r8| j jdkr| jdkrzd| 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r8t }|||}|
sh|f|dd  }|dk	rd|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r   rq   rZ   r   rr   r   r   r   r   Z
regressionZsingle_label_classificationZmulti_label_classificationr[   r1   r  )rN   r   r   rj   r0   Zproblem_typer  rv   rK   rz   rE   r   squeezer   r   r   r   r   r   )rm   rp   r   rq   rZ   r   rr   r  r   r   r   r   r   r  r  r  r   r    r    r$   r~     sV    




"


z(RemBertForSequenceClassification.forward)
NNNNNNNNNN)r   r   r   r^   r   r   rC   r   r   r  rK   r   r   r   r   r   r   r~   r   r    r    rn   r$   r    s<   
          
r  z
    RemBERT 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dee	dd
e
jee
j ee
j ee
j ee
j ee
j ee
j ee ee ee eeef ddd	Z  ZS )RemBertForMultipleChoicec                    s@   t  | t|| _t|j| _t|j	d| _
|   d S )Nr   )r]   r^   r   r   r   rh   r  rj   r   r   r0   r   rl   rn   r    r$   r^     s
    
z!RemBertForMultipleChoice.__init__z(batch_size, num_choices, sequence_lengthr   r   Nr  c                 C   st  |
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	r0t }|||}|
s`|f|dd  }|dk	r\|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[   r   r  r1   r  )rN   r   rG   r   rx   r   rj   r0   r   r   r   r   )rm   rp   r   rq   rZ   r   rr   r  r   r   r   Znum_choicesr   r   r  Zreshaped_logitsr  r  r   r    r    r$   r~     sL    



z RemBertForMultipleChoice.forward)
NNNNNNNNNN)r   r   r   r^   r   r   rC   r   r   r  rK   r   r   r   r   r   r   r~   r   r    r    rn   r$   r     s<   
          
r   z
    RemBERT 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
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f ddd	Z  ZS )RemBertForTokenClassificationc                    sN   t  | |j| _t|dd| _t|j| _t	|j
|j| _|   d S NFr  r  rl   rn   r    r$   r^   K  s    z&RemBertForTokenClassification.__init__r   r   r   Nr  c                 C   s   |
dk	r|
n| j j}
| j||||||||	|
d	}|d }| |}| |}d}|dk	rxt }||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[   r1   r  )rN   r   r   rj   r0   r   r   r  r   r   r   )rm   rp   r   rq   rZ   r   rr   r  r   r   r   r   r   r  r  r  r   r    r    r$   r~   V  s8    

z%RemBertForTokenClassification.forward)
NNNNNNNNNN)r   r   r   r^   r   r   rC   r   r   r  rK   r   r   r   r   r   r   r~   r   r    r    rn   r$   r!  C  s<             
r!  z
    RemBERT 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
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f ddd	Z  ZS )RemBertForQuestionAnsweringc                    s@   t  | |j| _t|dd| _t|j|j| _| 	  d S r"  )
r]   r^   r  r   r   r   r   r   
qa_outputsr   rl   rn   r    r$   r^     s
    z$RemBertForQuestionAnswering.__init__r   r   r   N)rp   r   rq   rZ   r   rr   start_positionsend_positionsr   r   r   rt   c                 C   sD  |dk	r|n| j j}| j|||||||	|
|d	}|d }| |}|jddd\}}|d}|d}d}|dk	r|dk	rt| dkr|d}t| dkr|d}|d}|d| |d| t	|d}|||}|||}|| d }|s.||f|dd  }|dk	r*|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[   r   )Zignore_indexr1   )r  start_logits
end_logitsr   r   )rN   r   r   r$  r>   r  rD   rx   Zclamp_r   r   r   r   )rm   rp   r   rq   rZ   r   rr   r%  r&  r   r   r   r   r   r  r'  r(  Z
total_lossZignored_indexr  Z
start_lossZend_lossr   r    r    r$   r~     sP    








z#RemBertForQuestionAnswering.forward)NNNNNNNNNNN)r   r   r   r^   r   r   rC   r   r   r  rK   r   r   r   r   r   r   r~   r   r    r    rn   r$   r#    s@              
r#  )Dr   r   r6   typingr   r   r   rK   Ztorch.utils.checkpointr   Ztorch.nnr   r   r   Zactivationsr
   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_rembertr   Z
get_loggerr   r4   r  Z_CHECKPOINT_FOR_DOCrV   ModulerW   r   r   r   r   r   r   r   r   r   r   r   r   ZREMBERT_START_DOCSTRINGr   r   r  r  r  r   r!  r#  r    r    r    r$   <module>   s   (

S7j4X`
2 *e  YTG