o
    	۷i-                     @   s  d Z ddlZddlZddlmZ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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) ddl*m+Z+ e',e-Z.dd Z/G dd dej0Z1G dd dej0Z2G dd dej0Z3G dd dej0Z4G dd dej0Z5G dd dej0Z6G d d! d!ej0Z7G d"d# d#eZ8G d$d% d%ej0Z9G d&d' d'ej0Z:G d(d) d)ej0Z;G d*d+ d+ej0Z<e&G d,d- d-e Z=e&d.d/G d0d1 d1e=Z>e&G d2d3 d3e=Z?e&d4d/G d5d6 d6e=eZ@e&d7d/G d8d9 d9e=ZAe&G d:d; d;e=ZBe&G d<d= d=e=ZCe&G d>d? d?e=ZDg d@ZEdS )AzPyTorch RemBERT model.    N)OptionalUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)CacheDynamicCacheEncoderDecoderCache)GenerationMixin)GradientCheckpointingLayer))BaseModelOutputWithPastAndCrossAttentions,BaseModelOutputWithPoolingAndCrossAttentions!CausalLMOutputWithCrossAttentionsMaskedLMOutputMultipleChoiceModelOutputQuestionAnsweringModelOutputSequenceClassifierOutputTokenClassifierOutput)PreTrainedModel)apply_chunking_to_forward find_pruneable_heads_and_indicesprune_linear_layer)auto_docstringlogging)deprecate_kwarg   )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 ).0denynamer!   b/home/ubuntu/vllm_env/lib/python3.10/site-packages/transformers/models/rembert/modeling_rembert.py	<genexpr>G   s    z-load_tf_weights_in_rembert.<locals>.<genexpr>)adam_vadam_moutput_embeddingclszLoading TF weight z with shape zbert/zrembert//c                 s   s    | ]}|d v V  qdS ))r(   r)   AdamWeightDecayOptimizerAdamWeightDecayOptimizer_1global_stepNr!   )r"   nr!   r!   r&   r'   X   s
    
z	Skipping z[A-Za-z]+_\d+z_(\d+)kernelgammaweightoutput_biasbetabiasoutput_weightssquad
classifierzSkipping {}   r   i_embeddingszPointer shape z and array shape z mismatchedzInitialize PyTorch weight )!renumpy
tensorflowImportErrorloggererrorospathabspathinfotrainlist_variablesanyload_variableappendzipreplacesplitjoin	fullmatchgetattrAttributeErrorformatlenint	transposeshape
ValueErrorAssertionErrorargstorch
from_numpydata)modelconfigtf_checkpoint_pathr<   nptftf_path	init_varsnamesarraysrV   arraypointerm_namescope_namesnumer!   r$   r&   load_tf_weights_in_rembert1   s   



rl   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epsposition_ids)r   F)
persistent)super__init__r   	Embedding
vocab_sizeinput_embedding_sizepad_token_idword_embeddingsmax_position_embeddingsposition_embeddingstype_vocab_sizetoken_type_embeddings	LayerNormlayer_norm_epsDropouthidden_dropout_probdropoutregister_bufferrZ   arangeexpandselfr^   	__class__r!   r&   ru      s   

zRemBertEmbeddings.__init__Nr   	input_idstoken_type_idsrq   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 )Nrr   r   dtypedevice)sizerq   rZ   zeroslongr   rz   r~   r|   r   r   )r   r   r   rq   r   r   input_shape
seq_lengthr~   
embeddingsr|   r!   r!   r&   forward   s"   





zRemBertEmbeddings.forward)NNNNr   )__name__
__module____qualname____doc__ru   r   rZ   
LongTensorFloatTensorrT   Tensorr   __classcell__r!   r!   r   r&   rm      s*    rm   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    )rt   ru   r   Linearhidden_sizedenseTanh
activationr   r   r!   r&   ru      s   
zRemBertPooler.__init__hidden_statesr   c                 C   s(   |d d df }|  |}| |}|S )Nr   )r   r   )r   r   first_token_tensorpooled_outputr!   r!   r&   r      s   

zRemBertPooler.forwardr   r   r   ru   rZ   r   r   r   r!   r!   r   r&   r      s    r   c                       s   e Zd Zd fdd	Zedddd						dd	ejd
eej deej deej dee	 de
deej defddZ  ZS )RemBertSelfAttentionNc                    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   embedding_sizezThe hidden size (z6) is not a multiple of the number of attention heads ())rt   ru   r   num_attention_headshasattrrW   rT   attention_head_sizeall_head_sizer   r   querykeyvaluer   attention_probs_dropout_probr   
is_decoder	layer_idxr   r^   r   r   r!   r&   ru      s    


zRemBertSelfAttention.__init__past_key_valuepast_key_valuesz4.58)new_nameversionFr   attention_mask	head_maskencoder_hidden_statesoutput_attentionscache_positionr   c                 C   s  |j \}}	}
| ||d| j| jdd}d}|d u}|d ur9t|tr7|j	| j
}|r3|j}n|j}n|}|r=|n|}|rV|d urV|rV|j| j
 j}|j| j
 j}nF| ||d| j| jdd}| ||d| j| jdd}|d ur|s|nd }|||| j
d|i\}}|rt|trd|j| j
< 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| }||fS )Nrr   r   r:   Fr   Tdimr   r   )rV   r   viewr   r   rU   
isinstancer   
is_updatedgetr   cross_attention_cacheself_attention_cachelayerskeysvaluesr   r   updaterZ   matmulmathsqrtr   
functionalsoftmaxr   permute
contiguousr   r   )r   r   r   r   r   r   r   r   
batch_sizer   _query_layerr   is_cross_attentioncurr_past_key_valuecurrent_states	key_layervalue_layerattention_scoresattention_probscontext_layernew_context_layer_shaper!   r!   r&   r      s\   


zRemBertSelfAttention.forwardr    NNNNFN)r   r   r   ru   r   rZ   r   r   r   r
   booltupler   r   r!   r!   r   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 Nro   )rt   ru   r   r   r   r   r   r   r   r   r   r   r   r!   r&   ru   8     
zRemBertSelfOutput.__init__r   input_tensorr   c                 C   &   |  |}| |}| || }|S r    r   r   r   r   r   r   r!   r!   r&   r   >     

zRemBertSelfOutput.forwardr   r!   r!   r   r&   r   7      $r   c                       s   e Zd Zd 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	 dee
 deej deej fddZ  ZS )RemBertAttentionNc                    s.   t    t||d| _t|| _t | _d S )Nr   )rt   ru   r   r   r   outputsetpruned_headsr   r   r!   r&   ru   F  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   )rS   r   r   r   r   r   r   r   r   r   r   r   r   union)r   headsindexr!   r!   r&   prune_headsM  s   zRemBertAttention.prune_headsFr   r   r   r   r   r   r   r   c              	   C   s>   | j |||||||d}| |d |}	|	f|dd   }
|
S )Nr   r   r   r   r   r   r   r   )r   r   )r   r   r   r   r   r   r   r   self_outputsattention_outputoutputsr!   r!   r&   r   `  s   
	zRemBertAttention.forwardr    r   )r   r   r   ru   r   rZ   r   r   r   r
   r   r   r   r   r!   r!   r   r&   r   E  s4    	r   c                       r   )RemBertIntermediatec                    sD   t    t|j|j| _t|jt	rt
|j | _d S |j| _d S r    )rt   ru   r   r   r   intermediate_sizer   r   
hidden_actstrr	   intermediate_act_fnr   r   r!   r&   ru   z  s
   
zRemBertIntermediate.__init__r   r   c                 C   s   |  |}| |}|S r    )r   r  r   r   r!   r!   r&   r     s   

zRemBertIntermediate.forwardr   r!   r!   r   r&   r   y  s    r   c                       r   )RemBertOutputc                    sB   t    t|j|j| _tj|j|jd| _t	|j
| _d S r   )rt   ru   r   r   r   r   r   r   r   r   r   r   r   r   r!   r&   ru     r   zRemBertOutput.__init__r   r   r   c                 C   r   r    r   r   r!   r!   r&   r     r   zRemBertOutput.forwardr   r!   r!   r   r&   r    r   r  c                       s   e Zd Zd 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 dee	 deej de
ej fddZdd Z  ZS )RemBertLayerNc                    st   t    |j| _d| _t||| _|j| _|j| _| jr.| js't|  dt||d| _	t
|| _t|| _d S )Nr   z> should be used as a decoder model if cross attention is addedr   )rt   ru   chunk_size_feed_forwardseq_len_dimr   	attentionr   add_cross_attentionrW   crossattentionr   intermediater  r   r   r   r!   r&   ru     s   

zRemBertLayer.__init__Fr   r   r   r   encoder_attention_maskr   r   r   r   c	              	   C   s   | j ||||||d}	|	d }
|	dd  }| jrA|d urAt| ds)td|  d| j|
||||||d}|d }
||dd   }t| j| j| j|
}|f| }|S )N)r   r   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   rW   r
  r   feed_forward_chunkr  r  )r   r   r   r   r   r  r   r   r   self_attention_outputsr   r   cross_attention_outputslayer_outputr!   r!   r&   r     s>   

	
zRemBertLayer.forwardc                 C   s   |  |}| ||}|S r    )r  r   )r   r   intermediate_outputr  r!   r!   r&   r    s   
zRemBertLayer.feed_forward_chunkr    )NNNNNFN)r   r   r   ru   rZ   r   r   r   r
   r   r   r   r  r   r!   r!   r   r&   r    s:    	

1r  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 dee	 de	de	de	deej 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  |d qS )r   )r  )r"   ir^   r!   r&   
<listcomp>  s    z+RemBertEncoder.__init__.<locals>.<listcomp>F)rt   ru   r^   r   r   rx   r   embedding_hidden_mapping_in
ModuleListrangenum_hidden_layerslayergradient_checkpointingr   r   r  r&   ru     s
   
 
zRemBertEncoder.__init__NFTr   r   r   r   r  r   	use_cacher   output_hidden_statesreturn_dictr   r   c              	   C   sV  | j r| jr|rtd d}|r"|d u r"tt| jdt| jd}|r3t|tr3td t	|}| 
|}|	r<dnd }|rBdnd }|rL| jjrLdnd }t| jD ]7\}}|	r^||f }|d urf|| nd }||||||||}|d }|r||d f }| jjr||d f }qS|	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  zPassing a tuple of `past_key_values` is deprecated and will be removed in Transformers v4.58.0. You should pass an instance of `EncoderDecoderCache` instead, e.g. `past_key_values=EncoderDecoderCache.from_legacy_cache(past_key_values)`.r!   r   r   r:   c                 s   s    | ]	}|d u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  trainingr@   warning_oncer   r   r^   r   r   from_legacy_cacher  r	  	enumerater  r   )r   r   r   r   r   r  r   r  r   r  r  r   all_hidden_statesall_self_attentionsall_cross_attentionsr  layer_modulelayer_head_masklayer_outputsr!   r!   r&   r     sl   




zRemBertEncoder.forward)
NNNNNNFFTN)r   r   r   ru   rZ   r   r   r   r
   r   r   r   r   r   r   r!   r!   r   r&   r    sJ    	

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   )rt   ru   r   r   r   r   r   r   r  r	   transform_act_fnr   r   r   r   r!   r&   ru   ;  s   
z'RemBertPredictionHeadTransform.__init__r   r   c                 C   s"   |  |}| |}| |}|S r    )r   r.  r   r  r!   r!   r&   r   D  s   


z&RemBertPredictionHeadTransform.forwardr   r!   r!   r   r&   r-  :  s    	r-  c                       r   )RemBertLMPredictionHeadc                    sR   t    t|j|j| _t|j|j| _t	|j
 | _tj|j|jd| _d S r   )rt   ru   r   r   r   output_embedding_sizer   rw   decoderr	   r   r   r   r   r   r   r!   r&   ru   L  s
   
z RemBertLMPredictionHead.__init__r   r   c                 C   s,   |  |}| |}| |}| |}|S r    )r   r   r   r1  r  r!   r!   r&   r   S  s
   



zRemBertLMPredictionHead.forwardr   r!   r!   r   r&   r/  K  s    r/  c                       r   )RemBertOnlyMLMHeadc                    s   t    t|| _d S r    )rt   ru   r/  predictionsr   r   r!   r&   ru   ]  s   
zRemBertOnlyMLMHead.__init__sequence_outputr   c                 C   s   |  |}|S r    )r3  )r   r4  prediction_scoresr!   r!   r&   r   a  s   
zRemBertOnlyMLMHead.forwardr   r!   r!   r   r&   r2  \  s    r2  c                   @   s*   e Zd ZU eed< eZdZdZdd Z	dS )RemBertPreTrainedModelr^   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        )meanstdNg      ?)r   r   r   r3   r\   normal_r^   initializer_ranger6   zero_rv   rn   r   fill_)r   moduler!   r!   r&   _init_weightsm  s   

z$RemBertPreTrainedModel._init_weightsN)
r   r   r   r   __annotations__rl   load_tf_weightsbase_model_prefixsupports_gradient_checkpointingr?  r!   r!   r!   r&   r6  f  s   
 r6  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 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 dee dee dee dee dee	j 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)
rt   ru   r^   rm   r   r  encoderr   pooler	post_init)r   r^   add_pooling_layerr   r!   r&   ru     s   

zRemBertModel.__init__c                 C   s   | j jS r    r   rz   r   r!   r!   r&   get_input_embeddings  s   z!RemBertModel.get_input_embeddingsc                 C   s   || j _d S r    rJ  )r   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)itemsrF  r  r  r   )r   heads_to_pruner  r   r!   r!   r&   _prune_heads  s   zRemBertModel._prune_headsNr   r   r   rq   r   r   r   r  r   r  r   r  r  r   r   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}|	d urt
|	ts}|	d d jd n|	 }|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 timerr   z5You have to specify either input_ids or inputs_embedsr   r   )r   r   )r   rq   r   r   r   )
r   r   r   r  r   r  r   r  r  r   r   )r   pooler_outputr   r   r!  r"  )r^   r   r  use_return_dictr   r  rW   %warn_if_padding_and_no_attention_maskr   r   r   r
   rV   get_seq_lengthrZ   onesr   r   get_extended_attention_maskinvert_attention_maskget_head_maskr  r   rF  rG  r   r   r   r!  r"  )r   r   r   r   rq   r   r   r   r  r   r  r   r  r  r   r   r   r   r   r   extended_attention_maskencoder_batch_sizeencoder_sequence_lengthr   encoder_hidden_shapeencoder_extended_attention_maskembedding_outputencoder_outputsr4  r   r!   r!   r&   r     s   
zRemBertModel.forward)TNNNNNNNNNNNNNN)r   r   r   ru   rL  rM  rP  r   r   rZ   r   r   r
   r   r   r   r   r   r   r   r!   r!   r   r&   rE  ~  sf    	

rE  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rI  
rt   ru   r   r@   warningrE  r7  r2  r+   rH  r   r   r!   r&   ru     s   
zRemBertForMaskedLM.__init__c                 C   
   | j jjS r    r+   r3  r1  rK  r!   r!   r&   get_output_embeddings-     
z(RemBertForMaskedLM.get_output_embeddingsc                 C      || j j_d S r    rg  r   new_embeddingsr!   r!   r&   set_output_embeddings0     z(RemBertForMaskedLM.set_output_embeddingsNr   r   r   rq   r   r   r   r  labelsr   r  r  r   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   r   rq   r   r   r   r  r   r  r  r   rr   r:   losslogitsr   r!  )
r^   rR  r7  r+   r   r   rw   r   r   r!  )r   r   r   r   rq   r   r   r   r  ro  r   r  r  r   r4  r5  masked_lm_lossloss_fctr   r!   r!   r&   r   3  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   rr   r   r   )r   r   )	rV   r^   ry   rZ   cat	new_zerosfullr   r   )r   r   r   model_kwargsr   effective_batch_sizedummy_tokenr!   r!   r&   prepare_inputs_for_generationl  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_generatez  s   zRemBertForMaskedLM.can_generate)NNNNNNNNNNNNr    )r   r   r   _tied_weights_keysru   rh  rm  r   r   rZ   r   r   r   r   r   r   r   r{  classmethodr|  r   r!   r!   r   r&   ra    s`    	


8ra  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 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  ZS )RemBertForCausalLMrb  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.`Frc  rd  r   r   r!   r&   ru     s   

zRemBertForCausalLM.__init__c                 C   rf  r    rg  rK  r!   r!   r&   rh    ri  z(RemBertForCausalLM.get_output_embeddingsc                 C   rj  r    rg  rk  r!   r!   r&   rm    rn  z(RemBertForCausalLM.set_output_embeddingsNr   r   r   rq   r   r   r   r  r   ro  r  r   r  r  r   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   r   rq   r   r   r   r  r   r  r   r  r  r   rw   r:   )rq  rr  r   r   r!  r"  )r^   rR  r7  r+   loss_functionrw   r   r   r   r!  r"  )r   r   r   r   rq   r   r   r   r  r   ro  r  r   r  r  kwargsr   r4  r5  lm_lossr   r!   r!   r&   r     sN   )
zRemBertForCausalLM.forwardr`  )r   r   r   r}  ru   rh  rm  r   r   rZ   r   r   r
   r   r   r   r   r   r   r!   r!   r   r&   r    sf    	

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                          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    rt   ru   
num_labelsrE  r7  r   r   classifier_dropout_probr   r   r   r9   rH  r   r   r!   r&   ru     s   
z)RemBertForSequenceClassification.__init__Nr   r   r   rq   r   r   ro  r   r  r  r   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   r   rq   r   r   r   r  r  r   
regressionsingle_label_classificationmulti_label_classificationrr   r:   rp  )r^   rR  r7  r   r9   problem_typer  r   rZ   r   rT   r   squeezer   r   r   r   r   r!  )r   r   r   r   rq   r   r   ro  r   r  r  r   r   rr  rq  rt  r   r!   r!   r&   r     sV   



"


z(RemBertForSequenceClassification.forward
NNNNNNNNNN)r   r   r   ru   r   r   rZ   r   r   r   r   r   r   r   r   r!   r!   r   r&   r    sH    
	

r  c                       r  )RemBertForMultipleChoicec                    s@   t  | t|| _t|j| _t|j	d| _
|   d S )Nr   )rt   ru   rE  r7  r   r   r  r   r   r   r9   rH  r   r   r!   r&   ru   N  s
   
z!RemBertForMultipleChoice.__init__Nr   r   r   rq   r   r   ro  r   r  r  r   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   rr   r   r  r:   rp  )r^   rR  rV   r   r   r7  r   r9   r   r   r   r!  )r   r   r   r   rq   r   r   ro  r   r  r  num_choicesr   r   rr  reshaped_logitsrq  rt  r   r!   r!   r&   r   X  sL   ,


z RemBertForMultipleChoice.forwardr  )r   r   r   ru   r   r   rZ   r   r   r   r   r   r   r   r   r!   r!   r   r&   r  L  sH    
	

r  c                       r  )RemBertForTokenClassificationc                    sN   t  | |j| _t|dd| _t|j| _t	|j
|j| _|   d S NFrc  r  r   r   r!   r&   ru     s   z&RemBertForTokenClassification.__init__Nr   r   r   rq   r   r   ro  r   r  r  r   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   rr   r:   rp  )r^   rR  r7  r   r9   r   r   r  r   r   r!  )r   r   r   r   rq   r   r   ro  r   r  r  r   r4  rr  rq  rt  r   r!   r!   r&   r     s8   

z%RemBertForTokenClassification.forwardr  )r   r   r   ru   r   r   rZ   r   r   r   r   r   r   r   r   r!   r!   r   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  )
rt   ru   r  rE  r7  r   r   r   
qa_outputsrH  r   r   r!   r&   ru     s
   z$RemBertForQuestionAnswering.__init__Nr   r   r   rq   r   r   start_positionsend_positionsr   r  r  r   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   rr   r   )ignore_indexr:   )rq  start_logits
end_logitsr   r!  )r^   rR  r7  r  rM   r  rS   r   clamp_r   r   r   r!  )r   r   r   r   rq   r   r   r  r  r   r  r  r   r4  rr  r  r  
total_lossignored_indexrt  
start_lossend_lossr   r!   r!   r&   r     sP   








z#RemBertForQuestionAnswering.forward)NNNNNNNNNNN)r   r   r   ru   r   r   rZ   r   r   r   r   r   r   r   r   r!   r!   r   r&   r    sN    	

r  )
r  ra  r  r  r  r  r  rE  r6  rl   )Fr   r   rB   typingr   r   rZ   r   torch.nnr   r   r   activationsr	   cache_utilsr
   r   r   
generationr   modeling_layersr   modeling_outputsr   r   r   r   r   r   r   r   modeling_utilsr   pytorch_utilsr   r   r   utilsr   r   utils.deprecationr   configuration_rembertr   
get_loggerr   r@   rl   Modulerm   r   r   r   r   r   r  r  r  r-  r/  r2  r6  rE  ra  r  r  r  r  r  __all__r!   r!   r!   r&   <module>   sn   (

S7m4G\
 hjTgBN