o
    Zh@                     @   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 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# ddl$m%Z% e#&e'Z(dd Z)G dd de	j*Z+G dd de	j*Z,G dd de	j*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*Z6e"G d)d* d*eZ7e"d+d,G d-d. d.e7Z8e"G d/d0 d0e7Z9e"d1d,G d2d3 d3e7eZ:e"d4d,G d5d6 d6e7Z;e"G d7d8 d8e7Z<e"G d9d: d:e7Z=e"G d;d< d<e7Z>g d=Z?dS )>zPyTorch RemBERT model.    N)OptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)GenerationMixin))BaseModelOutputWithPastAndCrossAttentions,BaseModelOutputWithPoolingAndCrossAttentions!CausalLMOutputWithCrossAttentionsMaskedLMOutputMultipleChoiceModelOutputQuestionAnsweringModelOutputSequenceClassifierOutputTokenClassifierOutput)PreTrainedModel)apply_chunking_to_forward find_pruneable_heads_and_indicesprune_linear_layer)auto_docstringlogging   )RemBertConfigc                    s  zddl }ddl}ddl}W n ty   td  w tj|}t	d|  |j
|}g }g }	|D ],\ }
t fdddD rFq6t	d  d	|
  |j
| }|  |	| q6t||	D ]\ } d
d  d tdd  D rt	dd   qh| } D ]}}|d|r|d|}n|g}|d dks|d dkrt|d}nH|d dks|d dkrt|d}n6|d dkrt|d}n*|d dkrt|d}nz	t||d }W n ty   t	dd  Y qw t|dkrt|d }|| }q|dd dkrt|d}n
|dkr'||}z|j|jkr<td|j d |j d!W n tyV } z| j|j|jf7  _ d}~ww t	d"   t||_ qh| 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    | ]}| v V  qd S N ).0Zdenynamer   [/var/www/auris/lib/python3.10/site-packages/transformers/models/rembert/modeling_rembert.py	<genexpr>E   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 v V  qdS ))r#   r$   ZAdamWeightDecayOptimizerZAdamWeightDecayOptimizer_1Zglobal_stepNr   )r   nr   r   r!   r"   V   s
    
z	Skipping z[A-Za-z]+_\d+z_(\d+)Z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 )!renumpyZ
tensorflowImportErrorloggererrorospathabspathinfo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_pathr.   nptfZtf_pathZ	init_varsnamesZarraysrE   arrayZpointerZm_nameZscope_namesnumer   r   r!   load_tf_weights_in_rembert/   s   



rS   c                       sh   e Zd ZdZ fddZ					ddeej deej deej d	eej d
e	dej
f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_bufferrI   ZarangeexpandselfrL   	__class__r   r!   r[      s   

zRemBertEmbeddings.__init__Nr   	input_idstoken_type_idsrW   inputs_embedspast_key_values_lengthreturnc                 C   s   |d ur	|  }n|  d d }|d }|d u r&| jd d ||| f }|d u r5tj|tj| jjd}|d u r>| |}| |}|| }	| |}
|	|
7 }	| 	|	}	| 
|	}	|	S )NrX   r   dtypedevice)sizerW   rI   zeroslongrt   r`   rb   ra   rc   rg   )rj   rm   rn   rW   ro   rp   input_shape
seq_lengthrb   
embeddingsra   r   r   r!   forward   s"   





zRemBertEmbeddings.forward)NNNNr   )__name__
__module____qualname____doc__r[   r   rI   
LongTensorFloatTensorrC   Tensorr{   __classcell__r   r   rk   r!   rT      s*    rT   c                       2   e Zd Z fddZdejdejfddZ  ZS )RemBertPoolerc                    s*   t    t|j|j| _t | _d S r   )rZ   r[   r   Linearhidden_sizedenseZTanh
activationri   rk   r   r!   r[      s   
zRemBertPooler.__init__hidden_statesrq   c                 C   s(   |d d df }|  |}| |}|S )Nr   )r   r   )rj   r   Zfirst_token_tensorpooled_outputr   r   r!   r{      s   

zRemBertPooler.forwardr|   r}   r~   r[   rI   r   r{   r   r   r   rk   r!   r      s    r   c                       s   e Zd Z fddZdd Z						ddejdeej d	eej d
eej deej dee	e	ej   de
de	f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 ())rZ   r[   r   num_attention_headshasattrrF   rC   attention_head_sizeall_head_sizer   r   querykeyvaluere   Zattention_probs_dropout_probrg   
is_decoderri   rk   r   r!   r[      s   

zRemBertSelfAttention.__init__c                 C   s6   |  d d | j| jf }|j| }|ddddS )NrX   r   r-   r   r	   )ru   r   r   viewpermute)rj   xZnew_x_shaper   r   r!   transpose_for_scores   s   
z)RemBertSelfAttention.transpose_for_scoresNFr   attention_mask	head_maskencoder_hidden_statesencoder_attention_maskpast_key_valueoutput_attentionsrq   c                 C   s  |  |}|d u}	|	r|d ur|d }
|d }|}nP|	r/| | |}
| | |}|}n;|d urZ| | |}
| | |}tj|d |
gdd}
tj|d |gdd}n| | |}
| | |}| |}| jrv|
|f}t||
dd}|t	
| j }|d ur|| }tjj|dd}| |}|d ur|| }t||}|dddd }| d d | jf }|j| }|r||fn|f}| jr||f }|S )Nr   r   r-   dimrX   r	   )r   r   r   r   rI   catr   matmulrD   mathsqrtr   r   Z
functionalZsoftmaxrg   r   
contiguousru   r   r   )rj   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   rI   r   r   r   r   boolr{   r   r   r   rk   r!   r      s4    	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 )RemBertSelfOutputc                    sB   t    t|j|j| _tj|j|jd| _t|j	| _
d S NrV   )rZ   r[   r   r   r   r   rc   rd   re   rf   rg   ri   rk   r   r!   r[   3     
zRemBertSelfOutput.__init__r   input_tensorrq   c                 C   &   |  |}| |}| || }|S r   r   rg   rc   rj   r   r   r   r   r!   r{   9     

zRemBertSelfOutput.forwardr   r   r   rk   r!   r   2      $r   c                       s   e Zd Z fddZdd Z						ddejdeej d	eej d
eej deej dee	e	ej   dee
 de	ej fddZ  ZS )RemBertAttentionc                    s*   t    t|| _t|| _t | _d S r   )rZ   r[   r   rj   r   outputsetpruned_headsri   rk   r   r!   r[   A  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   )rB   r   rj   r   r   r   r   r   r   r   r   r   r   union)rj   headsindexr   r   r!   prune_headsH  s   zRemBertAttention.prune_headsNFr   r   r   r   r   r   r   rq   c              	   C   s<   |  |||||||}| |d |}	|	f|dd   }
|
S )Nr   r   )rj   r   )rj   r   r   r   r   r   r   r   Zself_outputsattention_outputr   r   r   r!   r{   [  s   
	zRemBertAttention.forwardr   )r|   r}   r~   r[   r   rI   r   r   r   r   r   r{   r   r   r   rk   r!   r   @  s4    	r   c                       r   )RemBertIntermediatec                    sD   t    t|j|j| _t|jt	rt
|j | _d S |j| _d S r   )rZ   r[   r   r   r   intermediate_sizer   
isinstance
hidden_actstrr
   intermediate_act_fnri   rk   r   r!   r[   u  s
   
zRemBertIntermediate.__init__r   rq   c                 C   s   |  |}| |}|S r   )r   r   rj   r   r   r   r!   r{   }  s   

zRemBertIntermediate.forwardr   r   r   rk   r!   r   t  s    r   c                       r   )RemBertOutputc                    sB   t    t|j|j| _tj|j|jd| _t	|j
| _d S r   )rZ   r[   r   r   r   r   r   rc   rd   re   rf   rg   ri   rk   r   r!   r[     r   zRemBertOutput.__init__r   r   rq   c                 C   r   r   r   r   r   r   r!   r{     r   zRemBertOutput.forwardr   r   r   rk   r!   r     r   r   c                       s   e Zd Z fddZ						ddejdeej deej deej d	eej d
eeeej   dee	 deej fddZ
dd Z  ZS )RemBertLayerc                    sn   t    |j| _d| _t|| _|j| _|j| _| jr+| js&t|  dt|| _	t
|| _t|| _d S )Nr   z> should be used as a decoder model if cross attention is added)rZ   r[   chunk_size_feed_forwardseq_len_dimr   	attentionr   add_cross_attentionrF   crossattentionr   intermediater   r   ri   rk   r   r!   r[     s   



zRemBertLayer.__init__NFr   r   r   r   r   r   r   rq   c              	   C   s  |d ur
|d d nd }| j |||||d}	|	d }
| jr(|	dd }|	d }n|	dd  }d }| jro|d urot| dsDtd|  d|d urN|d	d  nd }| |
||||||}|d }
||dd  }|d }|| }t| j| j| j|
}|f| }| jr||f }|S )
Nr-   )r   r   r   r   rX   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   rF   r   r   feed_forward_chunkr   r   )rj   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{     sP   


	

zRemBertLayer.forwardc                 C   s   |  |}| ||}|S r   )r   r   )rj   r   Zintermediate_outputr   r   r   r!   r     s   
zRemBertLayer.feed_forward_chunkr   )r|   r}   r~   r[   rI   r   r   r   r   r   r{   r   r   r   r   rk   r!   r     s4    	
Br   c                       s   e Zd Z fddZ									ddejdeej deej d	eej d
eej deeeej   dee	 de	de	de	de
eef f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   _rL   r   r!   
<listcomp>  s    z+RemBertEncoder.__init__.<locals>.<listcomp>F)rZ   r[   rL   r   r   r^   r   embedding_hidden_mapping_inZ
ModuleListrangenum_hidden_layerslayergradient_checkpointingri   rk   r   r!   r[     s
   
 
zRemBertEncoder.__init__NFTr   r   r   r   r   past_key_values	use_cacher   output_hidden_statesreturn_dictrq   c                 C   sh  | j r| jr|rtd d}| |}|	rdnd }|rdnd }|r(| jjr(dnd }|r.dnd }t| jD ]^\}}|	r@||f }|d urH|| nd }|d urR|| nd }| j rh| jrh| 	|j
|||||||}n
||||||||}|d }|r||d f7 }|r||d f }| jjr||d f }q5|	r||f }|
stdd	 |||||fD S t|||||d
S )NzZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fr   r   rX   r   r-   c                 s   s    | ]	}|d ur|V  qd S r   r   )r   vr   r   r!   r"   5  s    z)RemBertEncoder.forward.<locals>.<genexpr>)last_hidden_stater   r   
attentionscross_attentions)r   Ztrainingr1   Zwarning_oncer   rL   r   	enumerater   Z_gradient_checkpointing_func__call__tupler   )rj   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{     s|   



zRemBertEncoder.forward)	NNNNNNFFT)r|   r}   r~   r[   rI   r   r   r   r   r   r   r   r{   r   r   r   rk   r!   r     sD    	

r   c                       r   )RemBertPredictionHeadTransformc                    sV   t    t|j|j| _t|jtrt	|j | _
n|j| _
tj|j|jd| _d S r   )rZ   r[   r   r   r   r   r   r   r   r
   transform_act_fnrc   rd   ri   rk   r   r!   r[   K  s   
z'RemBertPredictionHeadTransform.__init__r   rq   c                 C   s"   |  |}| |}| |}|S r   )r   r   rc   r   r   r   r!   r{   T  s   


z&RemBertPredictionHeadTransform.forwardr   r   r   rk   r!   r   J  s    	r   c                       r   )RemBertLMPredictionHeadc                    sR   t    t|j|j| _t|j|j| _t	|j
 | _tj|j|jd| _d S r   )rZ   r[   r   r   r   Zoutput_embedding_sizer   r]   decoderr
   r   r   rc   rd   ri   rk   r   r!   r[   \  s
   
z RemBertLMPredictionHead.__init__r   rq   c                 C   s,   |  |}| |}| |}| |}|S r   )r   r   rc   r   r   r   r   r!   r{   c  s
   



zRemBertLMPredictionHead.forwardr   r   r   rk   r!   r   [  s    r   c                       r   )RemBertOnlyMLMHeadc                    s   t    t|| _d S r   )rZ   r[   r   predictionsri   rk   r   r!   r[   m  s   
zRemBertOnlyMLMHead.__init__sequence_outputrq   c                 C   s   |  |}|S r   )r   )rj   r   prediction_scoresr   r   r!   r{   q  s   
zRemBertOnlyMLMHead.forwardr   r   r   rk   r!   r   l  s    r   c                   @   s$   e Zd ZeZeZdZdZdd Z	dS )RemBertPreTrainedModelrembertTc                 C   s   t |tjr |jjjd| jjd |jdur|jj	  dS dS t |tj
rC|jjjd| jjd |jdurA|jj|j 	  dS dS t |tjrX|jj	  |jjd dS dS )zInitialize the weightsg        )meanZstdNg      ?)r   r   r   r)   rJ   Znormal_rL   Zinitializer_ranger+   Zzero_r\   rU   rc   Zfill_)rj   moduler   r   r!   _init_weights}  s   

z$RemBertPreTrainedModel._init_weightsN)
r|   r}   r~   r   Zconfig_classrS   Zload_tf_weightsZbase_model_prefixZsupports_gradient_checkpointingr   r   r   r   r!   r   v  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://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.
    )Zcustom_introc                        s   e Zd Zd fdd	Zdd Zdd Zdd	 Ze	
	
	
	
	
	
	
	
	
	
	
	
	
ddee	j
 dee	j
 dee	j
 dee	j
 dee	j dee	j dee	j dee	j deeee	j   dee dee dee dee deeef fddZ  ZS )RemBertModelTc                    sD   t  | || _t|| _t|| _|rt|nd| _| 	  dS )zv
        add_pooling_layer (bool, *optional*, defaults to `True`):
            Whether to add a pooling layer
        N)
rZ   r[   rL   rT   rz   r   encoderr   pooler	post_init)rj   rL   add_pooling_layerrk   r   r!   r[     s   

zRemBertModel.__init__c                 C   s   | j jS r   rz   r`   rj   r   r   r!   get_input_embeddings  s   z!RemBertModel.get_input_embeddingsc                 C   s   || j _d S r   r   )rj   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   )rj   Zheads_to_pruner   r   r   r   r!   _prune_heads  s   zRemBertModel._prune_headsNrm   r   rn   rW   r   ro   r   r   r   r   r   r   r   rq   c                 C   s  |d ur|n| j j}|d ur|n| j j}|d ur|n| j j}| j jr-|
d ur(|
n| j j}
nd}
|d ur;|d ur;td|d urJ| || | }n|d urW| d d }ntd|\}}|d urf|j	n|j	}|	d urv|	d d j
d nd}|d u rtj||| f|d}|d u rtj|tj|d}| ||}| j jr|d ur| \}}}||f}|d u rtj||d}| |}nd }| || j j}| j|||||d	}| j||||||	|
|||d

}|d }| jd ur| |nd }|s||f|dd   S t|||j|j|j|jdS )NFzDYou cannot specify both input_ids and inputs_embeds at the same timerX   z5You have to specify either input_ids or inputs_embedsr   r-   )rt   rr   )rm   rW   rn   ro   rp   )	r   r   r   r   r   r   r   r   r   r   )r   Zpooler_outputr   r   r   r   )rL   r   r   use_return_dictr   r   rF   Z%warn_if_padding_and_no_attention_maskru   rt   rE   rI   Zonesrv   rw   Zget_extended_attention_maskZinvert_attention_maskZget_head_maskr   rz   r   r   r   r   r   r   r   )rj   rm   r   rn   rW   r   ro   r   r   r   r   r   r   r   rx   Z
batch_sizery   rt   rp   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   rI   r   r   r   r   r   r   r{   r   r   r   rk   r!   r     s`    	

r   c                       s   e Zd ZdgZ fddZdd Zdd Ze												dd	ee	j
 d
ee	j
 dee	j
 dee	j
 dee	j dee	j dee	j dee	j dee	j
 dee dee dee deeef fddZdddZedef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   
rZ   r[   r   r1   warningr   r   r   r%   r   ri   rk   r   r!   r[   '  s   
zRemBertForMaskedLM.__init__c                 C   
   | j jjS r   r%   r   r   r   r   r   r!   get_output_embeddings6     
z(RemBertForMaskedLM.get_output_embeddingsc                 C      || j j_d S r   r  rj   Znew_embeddingsr   r   r!   set_output_embeddings9     z(RemBertForMaskedLM.set_output_embeddingsNrm   r   rn   rW   r   ro   r   r   labelsr   r   r   rq   c                 C   s   |dur|n| j j}| j|||||||||
||d}|d }| |}d}|	dur:t }||d| j j|	d}|sP|f|dd  }|durN|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   rn   rW   r   ro   r   r   r   r   r   r   rX   r-   losslogitsr   r   )
rL   r   r   r%   r   r   r]   r   r   r   )rj   rm   r   rn   rW   r   ro   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 usJ 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   rX   r   rr   )rm   r   )	rE   rL   r_   rI   r   Z	new_zerosfullrw   rt   )rj   rm   r   Zmodel_kwargsrx   Zeffective_batch_sizeZdummy_tokenr   r   r!   prepare_inputs_for_generationu  s   "
z0RemBertForMaskedLM.prepare_inputs_for_generationc                 C   s   dS )z
        Legacy correction: RemBertForMaskedLM can't call `generate()` from `GenerationMixin`, even though it has a
        `prepare_inputs_for_generation` method.
        Fr   )r%   r   r   r!   can_generate  s   zRemBertForMaskedLM.can_generate)NNNNNNNNNNNNr   )r|   r}   r~   _tied_weights_keysr[   r  r	  r   r   rI   r   r   r   r   r   r   r{   r  classmethodr  r   r   r   rk   r!   r   #  s`    	


8r   zS
    RemBERT 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														dd	ee	j
 d
ee	j
 dee	j
 dee	j
 dee	j dee	j dee	j dee	j deeee	j   dee	j
 dee dee dee dee deeef f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  ri   rk   r   r!   r[     s   

zRemBertForCausalLM.__init__c                 C   r  r   r  r   r   r   r!   r    r  z(RemBertForCausalLM.get_output_embeddingsc                 C   r  r   r  r  r   r   r!   r	    r
  z(RemBertForCausalLM.set_output_embeddingsNrm   r   rn   rW   r   ro   r   r   r   r  r   r   r   r   rq   c                 K   s   |dur|n| j j}| j|||||||||	||||d}|d }| |}d}|
dur9| j||
fd| j ji|}|sO|f|dd  }|durM|f| S |S t|||j|j|j	|j
dS )a  
        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]`.

        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   rn   rW   r   ro   r   r   r   r   r   r   r   r   r]   r-   )r  r  r   r   r   r   )rL   r   r   r%   Zloss_functionr]   r   r   r   r   r   )rj   rm   r   rn   rW   r   ro   r   r   r   r  r   r   r   r   kwargsr   r   r   Zlm_lossr   r   r   r!   r{     sN   )
zRemBertForCausalLM.forwardc                    sB   d}|D ]}|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tort   )r   Z
past_statebeam_idxr   r!   r"     s   " z4RemBertForCausalLM._reorder_cache.<locals>.<genexpr>r-   )r   )rj   r   r  Zreordered_pastZ
layer_pastr   r  r!   _reorder_cache  s   
z!RemBertForCausalLM._reorder_cache)NNNNNNNNNNNNNN)r|   r}   r~   r  r[   r  r	  r   r   rI   r   r   r   r   r   r   r{   r  r   r   r   rk   r!   r    sh    	

Sr  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                          e Zd Z fddZe										ddeej deej deej deej deej d	eej d
eej dee	 dee	 dee	 de
eef fddZ  ZS ) RemBertForSequenceClassificationc                    sJ   t  | |j| _t|| _t|j| _t	|j
|j| _|   d S r   rZ   r[   
num_labelsr   r   r   re   classifier_dropout_probrg   r   r   r,   r   ri   rk   r   r!   r[     s   
z)RemBertForSequenceClassification.__init__Nrm   r   rn   rW   r   ro   r  r   r   r   rq   c                 C   sr  |
dur|
n| j j}
| j||||||||	|
d	}|d }| |}| |}d}|dur| j jdu rV| jdkr<d| j _n| jdkrR|jtj	ksM|jtj
krRd| j _nd| j _| j jdkrtt }| jdkrn|| | }n+|||}n%| j jdkrt }||d| j|d}n| j jdkrt }|||}|
s|f|dd  }|dur|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   rn   rW   r   ro   r   r   r   r   Z
regressionZsingle_label_classificationZmulti_label_classificationrX   r-   r  )rL   r   r   rg   r,   Zproblem_typer  rs   rI   rw   rC   r   squeezer   r   r   r   r   r   )rj   rm   r   rn   rW   r   ro   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   rI   r   r   r   r   r   r   r{   r   r   r   rk   r!   r    sH    
	

r  c                       r  )RemBertForMultipleChoicec                    s@   t  | t|| _t|j| _t|j	d| _
|   d S )Nr   )rZ   r[   r   r   r   re   r  rg   r   r   r,   r   ri   rk   r   r!   r[   `  s
   
z!RemBertForMultipleChoice.__init__Nrm   r   rn   rW   r   ro   r  r   r   r   rq   c                 C   sn  |
dur|
n| j j}
|dur|jd n|jd }|dur%|d|dnd}|dur4|d|dnd}|durC|d|dnd}|durR|d|dnd}|dure|d|d|dnd}| j||||||||	|
d	}|d }| |}| |}|d|}d}|durt }|||}|
s|f|dd  }|dur|f| S |S 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.

            [What are token type IDs?](../glossary#token-type-ids)
        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.
        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   rX   r   r   r-   r  )rL   r   rE   r   ru   r   rg   r,   r   r   r   r   )rj   rm   r   rn   rW   r   ro   r  r   r   r   Znum_choicesr   r   r  Zreshaped_logitsr  r  r   r   r   r!   r{   j  sL   ,


z RemBertForMultipleChoice.forwardr"  )r|   r}   r~   r[   r   r   rI   r   r   r   r   r   r   r{   r   r   r   rk   r!   r#  ^  sH    
	

r#  c                       r  )RemBertForTokenClassificationc                    sN   t  | |j| _t|dd| _t|j| _t	|j
|j| _|   d S NFr   r  ri   rk   r   r!   r[     s   z&RemBertForTokenClassification.__init__Nrm   r   rn   rW   r   ro   r  r   r   r   rq   c                 C   s   |
dur|
n| j j}
| j||||||||	|
d	}|d }| |}| |}d}|dur<t }||d| j|d}|
sR|f|dd  }|durP|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   rX   r-   r  )rL   r   r   rg   r,   r   r   r  r   r   r   )rj   rm   r   rn   rW   r   ro   r  r   r   r   r   r   r  r  r  r   r   r   r!   r{     s8   

z%RemBertForTokenClassification.forwardr"  )r|   r}   r~   r[   r   r   rI   r   r   r   r   r   r   r{   r   r   r   rk   r!   r$    sH    	

r$  c                       s   e Zd Z fddZe											ddeej deej deej deej deej d	eej d
eej deej dee	 dee	 dee	 de
eef fddZ  ZS )RemBertForQuestionAnsweringc                    s@   t  | |j| _t|dd| _t|j|j| _| 	  d S r%  )
rZ   r[   r  r   r   r   r   r   
qa_outputsr   ri   rk   r   r!   r[     s
   z$RemBertForQuestionAnswering.__init__Nrm   r   rn   rW   r   ro   start_positionsend_positionsr   r   r   rq   c                 C   s@  |d ur|n| j j}| j|||||||	|
|d	}|d }| |}|jddd\}}|d}|d}d }|d ur~|d ur~t| dkrK|d}t| dkrX|d}|d}|d| |d| t	|d}|||}|||}|| d }|s||f|dd   }|d ur|f| S |S t
||||j|jdS )	Nr   r   r   rX   r   )Zignore_indexr-   )r  start_logits
end_logitsr   r   )rL   r   r   r'  r<   r!  rB   ru   Zclamp_r   r   r   r   )rj   rm   r   rn   rW   r   ro   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   rI   r   r   r   r   r   r   r{   r   r   r   rk   r!   r&  	  sN    	

r&  )
r  r   r#  r&  r  r$  r   r   r   rS   )@r   r   r3   typingr   r   r   rI   Ztorch.utils.checkpointr   Ztorch.nnr   r   r   Zactivationsr
   Z
generationr   Zmodeling_outputsr   r   r   r   r   r   r   r   Zmodeling_utilsr   Zpytorch_utilsr   r   r   utilsr   r   Zconfiguration_rembertr   Z
get_loggerr|   r1   rS   ModulerT   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r#  r$  r&  __all__r   r   r   r!   <module>   sj   (

S7j4X`
 
hsTgBN