U
    &cP                    @   s  d Z ddlZddlZddlZddlZddlmZ ddlmZmZ ddl	m
Z
mZmZ ddlmZ ddlmZmZ dd	lmZmZ eeZd
dddddddddddddddddddddd Zd!d" Zd#d$ Ze
ejjjeeed%Zej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 Z%G d0d1 d1ej Z&G d2d3 d3ej Z'G d4d5 d5ej Z(G d6d7 d7ej Z)G d8d9 d9e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@dA dAej Z.G dBdC dCeZ/dDZ0dEZ1edFe0G dGdH dHe/Z2edIe0G dJdK dKe/Z3edLe0G dMdN dNe/Z4edOe0G dPdQ dQe/Z5edRe0G dSdT dTe/Z6edUe0G dVdW dWe/Z7edXe0G dYdZ dZe/Z8ed[e0G d\d] d]e/Z9dS )^zPyTorch BERT model.     N)nn)CrossEntropyLossMSELoss   )gelugelu_newswish)
BertConfig)add_start_docstrings add_start_docstrings_to_callable)PreTrainedModelprune_linear_layerz>https://cdn.huggingface.co/bert-base-uncased-pytorch_model.binz?https://cdn.huggingface.co/bert-large-uncased-pytorch_model.binz<https://cdn.huggingface.co/bert-base-cased-pytorch_model.binz=https://cdn.huggingface.co/bert-large-cased-pytorch_model.binzKhttps://cdn.huggingface.co/bert-base-multilingual-uncased-pytorch_model.binzIhttps://cdn.huggingface.co/bert-base-multilingual-cased-pytorch_model.binz>https://cdn.huggingface.co/bert-base-chinese-pytorch_model.binzChttps://cdn.huggingface.co/bert-base-german-cased-pytorch_model.binzRhttps://cdn.huggingface.co/bert-large-uncased-whole-word-masking-pytorch_model.binzPhttps://cdn.huggingface.co/bert-large-cased-whole-word-masking-pytorch_model.binzbhttps://cdn.huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad-pytorch_model.binz`https://cdn.huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad-pytorch_model.binzKhttps://cdn.huggingface.co/bert-base-cased-finetuned-mrpc-pytorch_model.binzIhttps://cdn.huggingface.co/bert-base-german-dbmdz-cased-pytorch_model.binzKhttps://cdn.huggingface.co/bert-base-german-dbmdz-uncased-pytorch_model.binzIhttps://cdn.huggingface.co/cl-tohoku/bert-base-japanese/pytorch_model.binz\https://cdn.huggingface.co/cl-tohoku/bert-base-japanese-whole-word-masking/pytorch_model.binzNhttps://cdn.huggingface.co/cl-tohoku/bert-base-japanese-char/pytorch_model.binzahttps://cdn.huggingface.co/cl-tohoku/bert-base-japanese-char-whole-word-masking/pytorch_model.binzPhttps://cdn.huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/pytorch_model.binzRhttps://cdn.huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/pytorch_model.binzKhttps://cdn.huggingface.co/wietsedv/bert-base-dutch-cased/pytorch_model.bin)zbert-base-uncasedzbert-large-uncasedzbert-base-casedzbert-large-casedzbert-base-multilingual-uncasedzbert-base-multilingual-casedzbert-base-chinesezbert-base-german-casedz%bert-large-uncased-whole-word-maskingz#bert-large-cased-whole-word-maskingz5bert-large-uncased-whole-word-masking-finetuned-squadz3bert-large-cased-whole-word-masking-finetuned-squadzbert-base-cased-finetuned-mrpczbert-base-german-dbmdz-casedzbert-base-german-dbmdz-uncasedzbert-base-japanesez%bert-base-japanese-whole-word-maskingzbert-base-japanese-charz*bert-base-japanese-char-whole-word-maskingzbert-base-finnish-cased-v1zbert-base-finnish-uncased-v1zbert-base-dutch-casedc                 C   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 ]<\}
}t	d
|
| |j||
}||
 |	| qrt||	D ]\}
}|
d}
tdd |
D rt	d	
d|
 q| }|
D ]}|d
|r"|d|}n|g}|d dksD|d dkrPt|d}n|d dksl|d dkrxt|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r6t|d}n|dkrJ||}z|j|jks^t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 {}z"Loading TF weight {} with shape {}/c                 s   s   | ]}|d kV  qdS ))Zadam_vZadam_mZAdamWeightDecayOptimizerZAdamWeightDecayOptimizer_1Zglobal_stepN ).0nr   r   >/tmp/pip-unpacked-wheel-ymerj3tt/transformers/modeling_bert.py	<genexpr>Z   s   z*load_tf_weights_in_bert.<locals>.<genexpr>zSkipping {}z[A-Za-z]+_\d+z_(\d+)kernelgammaweightZoutput_biasbetabiasZoutput_weightsZsquad
classifier   r   iZ_embeddingszInitialize PyTorch weight {})reZnumpyZ
tensorflowImportErrorloggererrorospathabspathinfoformatZtrainZlist_variablesZload_variableappendzipsplitanyjoin	fullmatchgetattrAttributeErrorlenint	transposeshapeAssertionErrorargstorchZ
from_numpydata)modelconfigZtf_checkpoint_pathr   nptfZtf_pathZ	init_varsnamesZarraysnamer/   arraypointerZm_nameZscope_namesnumer   r   r   load_tf_weights_in_bert=   sv    




r>   c                 C   s   | t tj|  S N)r2   tanhr   
functionalZsoftplus)xr   r   r   mish   s    rC   )r   relur   r   rC   c                       s*   e Zd ZdZ fddZdddZ  ZS )BertEmbeddingszLConstruct the embeddings from word, position and token_type embeddings.
    c                    sj   t    tj|j|j|jd| _t|j|j| _	t|j
|j| _t|j|jd| _t|j| _d S )N)Zpadding_idxZeps)super__init__r   	Embedding
vocab_sizehidden_sizepad_token_idword_embeddingsZmax_position_embeddingsposition_embeddingsZtype_vocab_sizetoken_type_embeddingsBertLayerNormlayer_norm_eps	LayerNormDropouthidden_dropout_probdropoutselfr5   	__class__r   r   rH      s    
zBertEmbeddings.__init__Nc                 C   s   |d k	r|  }n|  d d }|d }|d k	r8|jn|j}|d krhtj|tj|d}|d|}|d krtj|tj|d}|d kr| |}| 	|}| 
|}	|| |	 }
| |
}
| |
}
|
S )Nr   Zdtypedevicer   )sizer\   r2   arangelongZ	unsqueezeexpandzerosrM   rN   rO   rR   rU   )rW   	input_idstoken_type_idsposition_idsinputs_embedsinput_shapeZ
seq_lengthr\   rN   rO   
embeddingsr   r   r   forward   s$    





zBertEmbeddings.forward)NNNN)__name__
__module____qualname____doc__rH   rh   __classcell__r   r   rX   r   rE      s   rE   c                       s.   e Zd Z fddZdd ZdddZ  ZS )	BertSelfAttentionc                    s   t    |j|j dkr8t|ds8td|j|jf |j| _|j| _t|j|j | _| j| j | _	t
|j| j	| _t
|j| j	| _t
|j| j	| _t
|j| _d S )Nr   Zembedding_sizezLThe hidden size (%d) is not a multiple of the number of attention heads (%d))rG   rH   rK   num_attention_headshasattr
ValueErroroutput_attentionsr-   attention_head_sizeall_head_sizer   LinearquerykeyvaluerS   Zattention_probs_dropout_probrU   rV   rX   r   r   rH      s    

zBertSelfAttention.__init__c                 C   s6   |  d d | j| jf }|j| }|ddddS )NrZ   r   r   r      )r]   ro   rs   viewpermute)rW   rB   Znew_x_shaper   r   r   transpose_for_scores   s    
z&BertSelfAttention.transpose_for_scoresNc                 C   s  |  |}|d k	r,| |}| |}|}n| |}| |}| |}	| |}
| |}t|	|
dd}|t| j	 }|d k	r|| }t
jdd|}| |}|d k	r|| }t||}|dddd }| d d | jf }|j| }| jr||fn|f}|S )NrZ   Zdimr   r   r   ry   )rv   rw   rx   r|   r2   matmulr.   mathsqrtrs   r   ZSoftmaxrU   r{   
contiguousr]   rt   rz   rr   )rW   hidden_statesattention_mask	head_maskencoder_hidden_statesencoder_attention_maskZmixed_query_layerZmixed_key_layerZmixed_value_layerZquery_layerZ	key_layerZvalue_layerZattention_scoresZattention_probsZcontext_layerZnew_context_layer_shapeoutputsr   r   r   rh      s0    









zBertSelfAttention.forward)NNNN)ri   rj   rk   rH   r|   rh   rm   r   r   rX   r   rn      s       rn   c                       s$   e Zd Z fddZdd Z  ZS )BertSelfOutputc                    s@   t    t|j|j| _t|j|jd| _t	|j
| _d S NrF   )rG   rH   r   ru   rK   denserP   rQ   rR   rS   rT   rU   rV   rX   r   r   rH     s    
zBertSelfOutput.__init__c                 C   s&   |  |}| |}| || }|S r?   r   rU   rR   rW   r   Zinput_tensorr   r   r   rh     s    

zBertSelfOutput.forwardri   rj   rk   rH   rh   rm   r   r   rX   r   r     s   r   c                       s.   e Zd Z fddZdd ZdddZ  ZS )	BertAttentionc                    s*   t    t|| _t|| _t | _d S r?   )rG   rH   rn   rW   r   outputsetpruned_headsrV   rX   r   r   rH     s    


zBertAttention.__init__c                    s  t |dkrd S t| jj| jj}t|| j }|D ](  t fdd| jD   d| < q6|	d
 d}tt ||  }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   c                 3   s   | ]}| k rd ndV  qdS )r   r   Nr   )r   hheadr   r   r   !  s     z,BertAttention.prune_heads.<locals>.<genexpr>rZ   r   r~   )r,   r2   onesrW   ro   rs   r   r   sumrz   r   eqr^   r_   r   rv   rw   rx   r   r   rt   union)rW   headsmaskindexr   r   r   prune_heads  s     
zBertAttention.prune_headsNc           	      C   s8   |  |||||}| |d |}|f|dd   }|S Nr   r   )rW   r   )	rW   r   r   r   r   r   Zself_outputsattention_outputr   r   r   r   rh   1  s        zBertAttention.forward)NNNN)ri   rj   rk   rH   r   rh   rm   r   r   rX   r   r     s       r   c                       s$   e Zd Z fddZdd Z  ZS )BertIntermediatec                    sB   t    t|j|j| _t|jt	r6t
|j | _n|j| _d S r?   )rG   rH   r   ru   rK   intermediate_sizer   
isinstance
hidden_actstrACT2FNintermediate_act_fnrV   rX   r   r   rH   B  s
    
zBertIntermediate.__init__c                 C   s   |  |}| |}|S r?   )r   r   rW   r   r   r   r   rh   J  s    

zBertIntermediate.forwardr   r   r   rX   r   r   A  s   r   c                       s$   e Zd Z fddZdd Z  ZS )
BertOutputc                    s@   t    t|j|j| _t|j|jd| _	t
|j| _d S r   )rG   rH   r   ru   r   rK   r   rP   rQ   rR   rS   rT   rU   rV   rX   r   r   rH   Q  s    
zBertOutput.__init__c                 C   s&   |  |}| |}| || }|S r?   r   r   r   r   r   rh   W  s    

zBertOutput.forwardr   r   r   rX   r   r   P  s   r   c                       s&   e Zd Z fddZdddZ  ZS )	BertLayerc                    sD   t    t|| _|j| _| jr,t|| _t|| _t|| _	d S r?   )
rG   rH   r   	attention
is_decodercrossattentionr   intermediater   r   rV   rX   r   r   rH   _  s    



zBertLayer.__init__Nc                 C   s~   |  |||}|d }|dd  }| jrZ|d k	rZ| |||||}	|	d }||	dd   }| |}
| |
|}|f| }|S r   )r   r   r   r   r   )rW   r   r   r   r   r   Zself_attention_outputsr   r   Zcross_attention_outputsZintermediate_outputZlayer_outputr   r   r   rh   h  s"        

zBertLayer.forward)NNNNr   r   r   rX   r   r   ^  s       r   c                       s&   e Zd Z fddZdddZ  ZS )BertEncoderc                    s>   t     j| _ j| _t fddt jD | _d S )Nc                    s   g | ]}t  qS r   )r   )r   _r5   r   r   
<listcomp>  s     z(BertEncoder.__init__.<locals>.<listcomp>)	rG   rH   rr   output_hidden_statesr   Z
ModuleListrangenum_hidden_layerslayerrV   rX   r   r   rH     s    
zBertEncoder.__init__Nc                 C   s   d}d}t | jD ]H\}}	| jr*||f }|	|||| ||}
|
d }| jr||
d f }q| jrl||f }|f}| jr||f }| jr||f }|S )Nr   r   r   )	enumerater   r   rr   )rW   r   r   r   r   r   Zall_hidden_statesZall_attentionsiZlayer_moduleZlayer_outputsr   r   r   r   rh     s.    
    


zBertEncoder.forward)NNNNr   r   r   rX   r   r     s   	    r   c                       s$   e Zd Z fddZdd Z  ZS )
BertPoolerc                    s*   t    t|j|j| _t | _d S r?   )rG   rH   r   ru   rK   r   ZTanh
activationrV   rX   r   r   rH     s    
zBertPooler.__init__c                 C   s(   |d d df }|  |}| |}|S )Nr   )r   r   )rW   r   Zfirst_token_tensorpooled_outputr   r   r   rh     s    

zBertPooler.forwardr   r   r   rX   r   r     s   r   c                       s$   e Zd Z fddZdd Z  ZS )BertPredictionHeadTransformc                    sT   t    t|j|j| _t|jtr6t	|j | _
n|j| _
t|j|jd| _d S r   )rG   rH   r   ru   rK   r   r   r   r   r   transform_act_fnrP   rQ   rR   rV   rX   r   r   rH     s    
z$BertPredictionHeadTransform.__init__c                 C   s"   |  |}| |}| |}|S r?   )r   r   rR   r   r   r   r   rh     s    


z#BertPredictionHeadTransform.forwardr   r   r   rX   r   r     s   	r   c                       s$   e Zd Z fddZdd Z  ZS )BertLMPredictionHeadc                    sL   t    t|| _tj|j|jdd| _t	t
|j| _| j| j_d S )NF)r   )rG   rH   r   	transformr   ru   rK   rJ   decoder	Parameterr2   ra   r   rV   rX   r   r   rH     s
    

zBertLMPredictionHead.__init__c                 C   s   |  |}| |}|S r?   )r   r   r   r   r   r   rh     s    

zBertLMPredictionHead.forwardr   r   r   rX   r   r     s   r   c                       s$   e Zd Z fddZdd Z  ZS )BertOnlyMLMHeadc                    s   t    t|| _d S r?   )rG   rH   r   predictionsrV   rX   r   r   rH     s    
zBertOnlyMLMHead.__init__c                 C   s   |  |}|S r?   )r   )rW   sequence_outputprediction_scoresr   r   r   rh     s    
zBertOnlyMLMHead.forwardr   r   r   rX   r   r     s   r   c                       s$   e Zd Z fddZdd Z  ZS )BertOnlyNSPHeadc                    s   t    t|jd| _d S Nr   )rG   rH   r   ru   rK   seq_relationshiprV   rX   r   r   rH     s    
zBertOnlyNSPHead.__init__c                 C   s   |  |}|S r?   )r   )rW   r   seq_relationship_scorer   r   r   rh     s    
zBertOnlyNSPHead.forwardr   r   r   rX   r   r     s   r   c                       s$   e Zd Z fddZdd Z  ZS )BertPreTrainingHeadsc                    s(   t    t|| _t|jd| _d S r   )rG   rH   r   r   r   ru   rK   r   rV   rX   r   r   rH     s    

zBertPreTrainingHeads.__init__c                 C   s   |  |}| |}||fS r?   )r   r   )rW   r   r   r   r   r   r   r   rh     s    

zBertPreTrainingHeads.forwardr   r   r   rX   r   r     s   r   c                   @   s(   e Zd ZdZeZeZeZ	dZ
dd ZdS )BertPreTrainedModelz An abstract class to handle weights initialization and
        a simple interface for downloading and loading pretrained models.
    bertc                 C   st   t |tjtjfr*|jjjd| jjd n$t |t	rN|j
j  |jjd t |tjrp|j
dk	rp|j
j  dS )z Initialize the weights g        )ZmeanZstdg      ?N)r   r   ru   rI   r   r3   Znormal_r5   Zinitializer_rangerP   r   Zzero_Zfill_)rW   moduler   r   r   _init_weights  s    
z!BertPreTrainedModel._init_weightsN)ri   rj   rk   rl   r	   Zconfig_class!BERT_PRETRAINED_MODEL_ARCHIVE_MAPZpretrained_model_archive_mapr>   Zload_tf_weightsZbase_model_prefixr   r   r   r   r   r     s   r   am  
    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 (:class:`~transformers.BertConfig`): 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 :meth:`~transformers.PreTrainedModel.from_pretrained` method to load the model weights.
a  
    Args:
        input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary.

            Indices can be obtained using :class:`transformers.BertTokenizer`.
            See :func:`transformers.PreTrainedTokenizer.encode` and
            :func:`transformers.PreTrainedTokenizer.encode_plus` for details.

            `What are input IDs? <../glossary.html#input-ids>`__
        attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):
            Mask to avoid performing attention on padding token indices.
            Mask values selected in ``[0, 1]``:
            ``1`` for tokens that are NOT MASKED, ``0`` for MASKED tokens.

            `What are attention masks? <../glossary.html#attention-mask>`__
        token_type_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):
            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.html#token-type-ids>`_
        position_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):
            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.html#position-ids>`_
        head_mask (:obj:`torch.FloatTensor` of shape :obj:`(num_heads,)` or :obj:`(num_layers, num_heads)`, `optional`, defaults to :obj:`None`):
            Mask to nullify selected heads of the self-attention modules.
            Mask values selected in ``[0, 1]``:
            :obj:`1` indicates the head is **not masked**, :obj:`0` indicates the head is **masked**.
        inputs_embeds (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`, defaults to :obj:`None`):
            Optionally, instead of passing :obj:`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.
        encoder_hidden_states  (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`, defaults to :obj:`None`):
            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 (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):
            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 MASKED tokens.
z^The bare Bert Model transformer outputting raw hidden-states without any specific head on top.c                	       sJ   e Zd ZdZ fddZdd Zdd Zdd	 Zee	dddZ
  ZS )	BertModela  

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

    To behave as an decoder the model needs to be initialized with the
    :obj:`is_decoder` argument of the configuration set to :obj:`True`; an
    :obj:`encoder_hidden_states` is expected as an input to the forward pass.

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

    c                    s<   t  | || _t|| _t|| _t|| _| 	  d S r?   )
rG   rH   r5   rE   rg   r   encoderr   poolerinit_weightsrV   rX   r   r   rH   c  s    


zBertModel.__init__c                 C   s   | j jS r?   rg   rM   rW   r   r   r   get_input_embeddingsm  s    zBertModel.get_input_embeddingsc                 C   s   || j _d S r?   r   )rW   rx   r   r   r   set_input_embeddingsp  s    zBertModel.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   )rW   Zheads_to_pruner   r   r   r   r   _prune_headss  s    zBertModel._prune_headsNc	                 C   sN  |dk	r|dk	rt dn4|dk	r,| }	n"|dk	rF| dd }	nt d|dk	r\|jn|j}
|dkrxtj|	|
d}|dkrtj|	tj|
d}| ||	| j}| jj	r|dk	r| \}}}||f}|dkrtj||
d}| 
|}nd}| || jj}| j||||d}| j|||||d}|d	 }| |}||f|d
d  }|S )a	  
    Return:
        :obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.BertConfig`) and inputs:
        last_hidden_state (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`):
            Sequence of hidden-states at the output of the last layer of the model.
        pooler_output (:obj:`torch.FloatTensor`: of shape :obj:`(batch_size, hidden_size)`):
            Last layer hidden-state of the first token of the sequence (classification token)
            further processed by a Linear layer and a Tanh activation function. The Linear
            layer weights are trained from the next sentence prediction (classification)
            objective during pre-training.

            This output is usually *not* a good summary
            of the semantic content of the input, you're often better with averaging or pooling
            the sequence of hidden-states for the whole input sequence.
        hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_hidden_states=True``):
            Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
            of shape :obj:`(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the initial embedding outputs.
        attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_attentions=True``):
            Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
            :obj:`(batch_size, num_heads, sequence_length, sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.

    Examples::

        from transformers import BertModel, BertTokenizer
        import torch

        tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
        model = BertModel.from_pretrained('bert-base-uncased')

        input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0)  # Batch size 1
        outputs = model(input_ids)

        last_hidden_states = outputs[0]  # The last hidden-state is the first element of the output tuple

        NzDYou cannot specify both input_ids and inputs_embeds at the same timerZ   z5You have to specify either input_ids or inputs_embeds)r\   r[   )rb   rd   rc   re   )r   r   r   r   r   r   )rq   r]   r\   r2   r   ra   r_   Zget_extended_attention_maskr5   r   Zinvert_attention_maskZget_head_maskr   rg   r   r   )rW   rb   r   rc   rd   r   re   r   r   rf   r\   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   rh   {  sX    5

     

zBertModel.forward)NNNNNNNN)ri   rj   rk   rl   rH   r   r   r   r   BERT_INPUTS_DOCSTRINGrh   rm   r   r   rX   r   r   N  s   
        r   zBert Model with two heads on top as done during the pre-training: a `masked language modeling` head and
    a `next sentence prediction (classification)` head. c                	       s6   e Zd Z fddZdd ZeedddZ  ZS )	BertForPreTrainingc                    s,   t  | t|| _t|| _|   d S r?   )rG   rH   r   r   r   clsr   rV   rX   r   r   rH     s    

zBertForPreTraining.__init__c                 C   s
   | j jjS r?   r   r   r   r   r   r   r   get_output_embeddings  s    z(BertForPreTraining.get_output_embeddingsNc	                 C   s   | j ||||||d}	|	dd \}
}| |
|\}}||f|	dd  }	|dk	r|dk	rt }||d| jj|d}||dd|d}|| }|f|	 }	|	S )a   
        masked_lm_labels (``torch.LongTensor`` of shape ``(batch_size, sequence_length)``, `optional`, defaults to :obj:`None`):
            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]``
        next_sentence_label (``torch.LongTensor`` of shape ``(batch_size,)``, `optional`, defaults to :obj:`None`):
            Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair (see :obj:`input_ids` docstring)
            Indices should be in ``[0, 1]``.
            ``0`` indicates sequence B is a continuation of sequence A,
            ``1`` indicates sequence B is a random sequence.

    Returns:
        :obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.BertConfig`) and inputs:
        loss (`optional`, returned when ``masked_lm_labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:
            Total loss as the sum of the masked language modeling loss and the next sequence prediction (classification) loss.
        prediction_scores (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, config.vocab_size)`)
            Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
        seq_relationship_scores (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, 2)`):
            Prediction scores of the next sequence prediction (classification) head (scores of True/False
            continuation before SoftMax).
        hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when :obj:`config.output_hidden_states=True`):
            Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
            of shape :obj:`(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the initial embedding outputs.
        attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_attentions=True``):
            Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
            :obj:`(batch_size, num_heads, sequence_length, sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.


    Examples::

        from transformers import BertTokenizer, BertForPreTraining
        import torch

        tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
        model = BertForPreTraining.from_pretrained('bert-base-uncased')

        input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0)  # Batch size 1
        outputs = model(input_ids)

        prediction_scores, seq_relationship_scores = outputs[:2]

        r   rc   rd   r   re   Nr   rZ   )r   r   r   rz   r5   rJ   )rW   rb   r   rc   rd   r   re   masked_lm_labelsnext_sentence_labelr   r   r   r   r   loss_fctmasked_lm_lossnext_sentence_loss
total_lossr   r   r   rh     s(    =	

zBertForPreTraining.forward)NNNNNNNN)	ri   rj   rk   rH   r   r   r   rh   rm   r   r   rX   r   r     s           r   z3Bert Model with a `language modeling` head on top. c                       s@   e Zd Z fddZdd Zeed
ddZddd	Z  Z	S )BertForMaskedLMc                    s,   t  | t|| _t|| _|   d S r?   )rG   rH   r   r   r   r   r   rV   rX   r   r   rH   U  s    

zBertForMaskedLM.__init__c                 C   s
   | j jjS r?   r   r   r   r   r   r   ]  s    z%BertForMaskedLM.get_output_embeddingsNc              
   C   s   | j ||||||||	d}|d }| |}|f|dd  }|dk	rrt }||d| jj|d}|f| }|
dk	r|ddddddf  }|
ddddf  }
t }||d| jj|
d}|f| }|S )a  
        masked_lm_labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):
            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]``
        lm_labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):
            Labels for computing the left-to-right language modeling loss (next word prediction).
            Indices should be in ``[-100, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring)
            Tokens with indices set to ``-100`` are ignored (masked), the loss is only computed for the tokens with labels
            in ``[0, ..., config.vocab_size]``

    Returns:
        :obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.BertConfig`) and inputs:
        masked_lm_loss (`optional`, returned when ``masked_lm_labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:
            Masked language modeling loss.
        ltr_lm_loss (:obj:`torch.FloatTensor` of shape :obj:`(1,)`, `optional`, returned when :obj:`lm_labels` is provided):
                Next token prediction loss.
        prediction_scores (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, config.vocab_size)`)
            Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
        hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_hidden_states=True``):
            Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
            of shape :obj:`(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the initial embedding outputs.
        attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_attentions=True``):
            Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
            :obj:`(batch_size, num_heads, sequence_length, sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.

        Examples::

            from transformers import BertTokenizer, BertForMaskedLM
            import torch

            tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
            model = BertForMaskedLM.from_pretrained('bert-base-uncased')

            input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0)  # Batch size 1
            outputs = model(input_ids, masked_lm_labels=input_ids)

            loss, prediction_scores = outputs[:2]

        )r   rc   rd   r   re   r   r   r   r   NrZ   r   )r   r   r   rz   r5   rJ   r   )rW   rb   r   rc   rd   r   re   r   r   r   Z	lm_labelsr   r   r   r   r   Zltr_lm_lossr   r   r   rh   `  s0    =


zBertForMaskedLM.forwardc                 K   s   |j }|d }|d kr ||}| jjdkr| 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   Fz.The PAD token should be defined for generationr   rZ   r~   r[   )rb   r   )r/   Znew_onesr5   r   rL   r0   r2   catZ	new_zerosfullr_   r\   )rW   rb   r   Zmodel_kwargsrf   Zeffective_batch_sizeZdummy_tokenr   r   r   prepare_inputs_for_generation  s$    
    z-BertForMaskedLM.prepare_inputs_for_generation)
NNNNNNNNNN)N)
ri   rj   rk   rH   r   r   r   rh   r   rm   r   r   rX   r   r   S  s             ar   zKBert Model with a `next sentence prediction (classification)` head on top. c                       s.   e Zd Z fddZeedddZ  ZS )BertForNextSentencePredictionc                    s,   t  | t|| _t|| _|   d S r?   )rG   rH   r   r   r   r   r   rV   rX   r   r   rH     s    

z&BertForNextSentencePrediction.__init__Nc                 C   sn   | j ||||||d}|d }	| |	}
|
f|dd  }|dk	rjt }||
dd|d}|f| }|S )a&	  
        next_sentence_label (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`, defaults to :obj:`None`):
            Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair (see ``input_ids`` docstring)
            Indices should be in ``[0, 1]``.
            ``0`` indicates sequence B is a continuation of sequence A,
            ``1`` indicates sequence B is a random sequence.

    Returns:
        :obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.BertConfig`) and inputs:
        loss (:obj:`torch.FloatTensor` of shape :obj:`(1,)`, `optional`, returned when :obj:`next_sentence_label` is provided):
            Next sequence prediction (classification) loss.
        seq_relationship_scores (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, 2)`):
            Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation before SoftMax).
        hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_hidden_states=True``):
            Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
            of shape :obj:`(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the initial embedding outputs.
        attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_attentions=True``):
            Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
            :obj:`(batch_size, num_heads, sequence_length, sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.

    Examples::

        from transformers import BertTokenizer, BertForNextSentencePrediction
        import torch

        tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
        model = BertForNextSentencePrediction.from_pretrained('bert-base-uncased')

        input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0)  # Batch size 1
        outputs = model(input_ids)

        seq_relationship_scores = outputs[0]

        r   r   r   NrZ   )r   r   r   rz   )rW   rb   r   rc   rd   r   re   r   r   r   r   r   r   r   r   r   rh     s     3	

z%BertForNextSentencePrediction.forward)NNNNNNNri   rj   rk   rH   r   r   rh   rm   r   r   rX   r   r     s          r   zBert 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ddZ  ZS )BertForSequenceClassificationc                    sJ   t  | |j| _t|| _t|j| _t	|j
|j| _|   d S r?   rG   rH   
num_labelsr   r   r   rS   rT   rU   ru   rK   r   r   rV   rX   r   r   rH   4  s    
z&BertForSequenceClassification.__init__Nc                 C   s   | j ||||||d}|d }	| |	}	| |	}
|
f|dd  }|dk	r| jdkrtt }||
d|d}n t }||
d| j|d}|f| }|S )a@	  
        labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`, defaults to :obj:`None`):
            Labels for computing the sequence classification/regression loss.
            Indices should be in :obj:`[0, ..., config.num_labels - 1]`.
            If :obj:`config.num_labels == 1` a regression loss is computed (Mean-Square loss),
            If :obj:`config.num_labels > 1` a classification loss is computed (Cross-Entropy).

    Returns:
        :obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.BertConfig`) and inputs:
        loss (:obj:`torch.FloatTensor` of shape :obj:`(1,)`, `optional`, returned when :obj:`label` is provided):
            Classification (or regression if config.num_labels==1) loss.
        logits (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, config.num_labels)`):
            Classification (or regression if config.num_labels==1) scores (before SoftMax).
        hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_hidden_states=True``):
            Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
            of shape :obj:`(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the initial embedding outputs.
        attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_attentions=True``):
            Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
            :obj:`(batch_size, num_heads, sequence_length, sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.

    Examples::

        from transformers import BertTokenizer, BertForSequenceClassification
        import torch

        tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
        model = BertForSequenceClassification.from_pretrained('bert-base-uncased')

        input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0)  # Batch size 1
        labels = torch.tensor([1]).unsqueeze(0)  # Batch size 1
        outputs = model(input_ids, labels=labels)

        loss, logits = outputs[:2]

        r   r   r   NrZ   )r   rU   r   r   r   rz   r   )rW   rb   r   rc   rd   r   re   labelsr   r   logitsr   lossr   r   r   rh   >  s(    4	



z%BertForSequenceClassification.forward)NNNNNNNr   r   r   rX   r   r   .  s   
       r   zBert 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ddZ  ZS )BertForMultipleChoicec                    s@   t  | t|| _t|j| _t|j	d| _
|   d S )Nr   )rG   rH   r   r   r   rS   rT   rU   ru   rK   r   r   rV   rX   r   r   rH     s
    
zBertForMultipleChoice.__init__Nc                 C   s   |j d }|d|d}|dk	r6|d|dnd}|dk	rT|d|dnd}|dk	rr|d|dnd}| j||||||d}	|	d }
| |
}
| |
}|d|}|f|	dd  }	|dk	rt }|||}|f|	 }	|	S )aF	  
        labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`, defaults to :obj:`None`):
            Labels for computing the multiple choice classification loss.
            Indices should be in ``[0, ..., num_choices]`` where `num_choices` is the size of the second dimension
            of the input tensors. (see `input_ids` above)

    Returns:
        :obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.BertConfig`) and inputs:
        loss (:obj:`torch.FloatTensor` of shape `(1,)`, `optional`, returned when :obj:`labels` is provided):
            Classification loss.
        classification_scores (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, num_choices)`):
            `num_choices` is the second dimension of the input tensors. (see `input_ids` above).

            Classification scores (before SoftMax).
        hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_hidden_states=True``):
            Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
            of shape :obj:`(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the initial embedding outputs.
        attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_attentions=True``):
            Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
            :obj:`(batch_size, num_heads, sequence_length, sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.

    Examples::

        from transformers import BertTokenizer, BertForMultipleChoice
        import torch

        tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
        model = BertForMultipleChoice.from_pretrained('bert-base-uncased')
        choices = ["Hello, my dog is cute", "Hello, my cat is amazing"]

        input_ids = torch.tensor([tokenizer.encode(s, add_special_tokens=True) for s in choices]).unsqueeze(0)  # Batch size 1, 2 choices
        labels = torch.tensor(1).unsqueeze(0)  # Batch size 1
        outputs = model(input_ids, labels=labels)

        loss, classification_scores = outputs[:2]

        r   rZ   Nr   r   )r/   rz   r]   r   rU   r   r   )rW   rb   r   rc   rd   r   re   r   Znum_choicesr   r   r   Zreshaped_logitsr   r   r   r   r   rh     s.    5
	



zBertForMultipleChoice.forward)NNNNNNNr   r   r   rX   r   r     s   	       r   zBert 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ddZ  ZS )BertForTokenClassificationc                    sJ   t  | |j| _t|| _t|j| _t	|j
|j| _|   d S r?   r   rV   rX   r   r   rH     s    
z#BertForTokenClassification.__init__Nc                 C   s   | j ||||||d}|d }	| |	}	| |	}
|
f|dd  }|dk	rt }|dk	r|ddk}|
d| j}t||dt|j	
|}|||}n||
d| j|d}|f| }|S )aN  
        labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):
            Labels for computing the token classification loss.
            Indices should be in ``[0, ..., config.num_labels - 1]``.

    Returns:
        :obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.BertConfig`) and inputs:
        loss (:obj:`torch.FloatTensor` of shape :obj:`(1,)`, `optional`, returned when ``labels`` is provided) :
            Classification loss.
        scores (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, config.num_labels)`)
            Classification scores (before SoftMax).
        hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_hidden_states=True``):
            Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
            of shape :obj:`(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the initial embedding outputs.
        attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_attentions=True``):
            Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
            :obj:`(batch_size, num_heads, sequence_length, sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.

    Examples::

        from transformers import BertTokenizer, BertForTokenClassification
        import torch

        tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
        model = BertForTokenClassification.from_pretrained('bert-base-uncased')

        input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0)  # Batch size 1
        labels = torch.tensor([1] * input_ids.size(1)).unsqueeze(0)  # Batch size 1
        outputs = model(input_ids, labels=labels)

        loss, scores = outputs[:2]

        r   r   r   NrZ   r   )r   rU   r   r   rz   r   r2   whereZtensorignore_indexZtype_as)rW   rb   r   rc   rd   r   re   r   r   r   r   r   Zactive_lossZactive_logitsZactive_labelsr   r   r   r   rh     s4    2	

  
z"BertForTokenClassification.forward)NNNNNNNr   r   r   rX   r   r     s   
       r   zBert 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ddZ  ZS )BertForQuestionAnsweringc                    s<   t  | |j| _t|| _t|j|j| _| 	  d S r?   )
rG   rH   r   r   r   r   ru   rK   
qa_outputsr   rV   rX   r   r   rH   [  s
    
z!BertForQuestionAnswering.__init__Nc	                 C   s   | j ||||||d}	|	d }
| |
}|jddd\}}|d}|d}||f|	dd  }	|dk	r|dk	rt| dkr|d}t| dkr|d}|d}|d| |d| t|d}|||}|||}|| d }|f|	 }	|	S )	a^  
        start_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`, defaults to :obj:`None`):
            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 (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`, defaults to :obj:`None`):
            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.

    Returns:
        :obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.BertConfig`) and inputs:
        loss (:obj:`torch.FloatTensor` of shape :obj:`(1,)`, `optional`, returned when :obj:`labels` is provided):
            Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.
        start_scores (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length,)`):
            Span-start scores (before SoftMax).
        end_scores (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length,)`):
            Span-end scores (before SoftMax).
        hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_hidden_states=True``):
            Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
            of shape :obj:`(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the initial embedding outputs.
        attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_attentions=True``):
            Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
            :obj:`(batch_size, num_heads, sequence_length, sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.

    Examples::

        from transformers import BertTokenizer, BertForQuestionAnswering
        import torch

        tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
        model = BertForQuestionAnswering.from_pretrained('bert-large-uncased-whole-word-masking-finetuned-squad')

        question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet"
        encoding = tokenizer.encode_plus(question, text)
        input_ids, token_type_ids = encoding["input_ids"], encoding["token_type_ids"]
        start_scores, end_scores = model(torch.tensor([input_ids]), token_type_ids=torch.tensor([token_type_ids]))

        all_tokens = tokenizer.convert_ids_to_tokens(input_ids)
        answer = ' '.join(all_tokens[torch.argmax(start_scores) : torch.argmax(end_scores)+1])

        assert answer == "a nice puppet"

        r   r   r   rZ   r~   r   N)r   )r   r   r&   Zsqueezer,   r]   Zclamp_r   )rW   rb   r   rc   rd   r   re   Zstart_positionsZend_positionsr   r   r   Zstart_logitsZ
end_logitsZignored_indexr   Z
start_lossZend_lossr   r   r   r   rh   d  s8    >	









z BertForQuestionAnswering.forward)NNNNNNNNr   r   r   rX   r   r   U  s   	        r   ):rl   loggingr   r   r2   r   Ztorch.nnr   r   Zactivationsr   r   r   Zconfiguration_bertr	   Z
file_utilsr
   r   Zmodeling_utilsr   r   	getLoggerri   r   r   r>   rC   rA   rD   r   rR   rP   ModulerE   rn   r   r   r   r   r   r   r   r   r   r   r   r   r   ZBERT_START_DOCSTRINGr   r   r   r   r   r   r   r   r   r   r   r   r   <module>   s   
H(N.#)

. c  R\_]