o
    *Îji ã                   @   sþ  d Z ddlmZmZmZmZ ddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddlZddlZddlm  mZ ddlmZ ddlmZ ddlmZ ddlmZ dd	„ Zd
d„ Zdd„ Ze e¡Ze ej ¡ ddddddddœZ!dZ"dZ#dZ$dd„ Z%dd„ Z&dd„ Z'e&ejjj(e'dœZ)G d d!„ d!e*ƒZ+zdd"l,m-Z. W n e/yµ   e0d#ƒ G d$d%„ d%ej1ƒZ.Y nw G d&d'„ d'ej1ƒZ2G d(d)„ d)ej1ƒZ3G d*d+„ d+ej1ƒZ4G d,d-„ d-ej1ƒZ5G d.d/„ d/ej1ƒZ6G d0d1„ d1ej1ƒZ7G d2d3„ d3ej1ƒZ8G d4d5„ d5ej1ƒZ9G d6d7„ d7ej1ƒZ:G d8d9„ d9ej1ƒZ;G d:d;„ d;ej1ƒZ<G d<d=„ d=ej1ƒZ=G d>d?„ d?ej1ƒZ>G d@dA„ dAej1ƒZ?G dBdC„ dCej1ƒZ@G dDdE„ dEe@ƒZAG dFdG„ dGe@ƒZBG dHdI„ dIe@ƒZCG dJdK„ dKe@ƒZDG dLdM„ dMe@ƒZEG dNdO„ dOe@ƒZFG dPdQ„ dQe@ƒZGG dRdS„ dSe@ƒZHdS )TzPyTorch BERT model.é    )Úabsolute_importÚdivisionÚprint_functionÚunicode_literalsN)Úcached_path)Úmpu)Únn)ÚCrossEntropyLossc                    s   ‡ ‡fdd„}|S )Nc                    ó   t jjj| ˆ ˆdS ©N©ÚmeanÚstd©Útorchr   ÚinitÚnormal_©Ztensorr   © úo/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/modelscope/models/nlp/mglm/model/modeling_bert.pyÚinit_)   ó   z!normal_init_method.<locals>.init_r   )r   r   r   r   r   r   Únormal_init_method'   s   r   c                    s$   ˆt  d| ¡ ‰‡ ‡fdd„}|S )z3Init method based on N(0, sigma/sqrt(2*num_layers).ç       @c                    r
   r   r   r   r   r   r   r   3   r   z!scaled_init_method.<locals>.init_)ÚmathÚsqrt)r   r   Ú
num_layersr   r   r   r   Úscaled_init_method/   s   r   c                 C   s*   |   d¡}|   d¡}|| }|  d¡}|S )Né   é   )Ú	unsqueeze)Úattention_maskZattention_mask_b1sZattention_mask_bs1Zattention_mask_bssÚextended_attention_maskr   r   r   Úbert_extended_attention_mask9   s
   


r#   z#/root/data/bert-base-uncased.tar.gzzMhttps://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased.tar.gzzJhttps://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased.tar.gzzKhttps://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased.tar.gzzYhttps://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-uncased.tar.gzzWhttps://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-cased.tar.gzzLhttps://s3.amazonaws.com/models.huggingface.co/bert/bert-base-chinese.tar.gz)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_config.jsonzpytorch_model.binz
model.ckptc                 C   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d |	|
¡ƒ |j	 ||	¡}| |	¡ | |¡ q4t||ƒD ]Ã\}	}|	 d¡}	tdd„ |	D ƒƒrttd	 d |	¡¡ƒ qW| }|	D ]Y}| d
|¡r‡| d|¡}n|g}|d dks–|d dkrœt|dƒ}n%|d dks¨|d dkr®t|dƒ}n|d dkrºt|dƒ}nt||d ƒ}t|ƒdkrÑt|d ƒ}|| }qx|dd… dkràt|dƒ}n	|dkré| |¡}z
|j|jksòJ ‚W n ty } z| j|j|jf7  _‚ d}~ww td |	¡ƒ t |¡|_qW| S )z, Load tf checkpoints in a pytorch model
    r   NzšLoading a TensorFlow models 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 v V  qdS ))Zadam_vZadam_mNr   )Ú.0Únr   r   r   Ú	<genexpr>|   s   € z*load_tf_weights_in_bert.<locals>.<genexpr>zSkipping {}z[A-Za-z]+_\d+z_(\d+)ZkernelÚgammaÚweightZoutput_biasÚbetaÚbiasZoutput_weightsr   r   iõÿÿÿZ_embeddingszInitialize PyTorch weight {})ÚreÚnumpyZ
tensorflowÚImportErrorÚprintÚosÚpathÚabspathÚformatÚtrainZlist_variablesZload_variableÚappendÚzipÚsplitÚanyÚjoinÚ	fullmatchÚgetattrÚlenÚintÚ	transposeÚshapeÚAssertionErrorÚargsr   Z
from_numpyÚdata)ÚmodelZtf_checkpoint_pathr,   ÚnpÚtfZtf_pathZ	init_varsÚnamesZarraysÚnamer?   ÚarrayÚpointerZm_nameÚlÚnumÚer   r   r   Úload_tf_weights_in_bert_   sn   ÿû

€
€þrM   c                 C   s    | d dt  | t d¡ ¡  S )zûImplementation of the gelu activation function.
        For information: OpenAI GPT's gelu is slightly different (and gives slightly different results):
        0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))
    g      à?ç      ð?r   )r   Úerfr   r   ©Úxr   r   r   Úgeluž   s    rR   c                 C   s   | t  | ¡ S ©N)r   ZsigmoidrP   r   r   r   Úswish¦   s   rT   )rR   ÚrelurT   c                   @   sh   e Zd ZdZ												
	
	
	
	ddd„Zedd„ ƒZedd„ ƒZdd„ Zdd„ Z	dd„ Z
dS )Ú
BertConfigzEConfiguration class to store the configuration of a `BertModel`.
    é   é   é   rR   çš™™™™™¹?é   r   ç{®Gáz”?Fçê-™—q=c                 C   sÜ   t |tƒr3t|ddd}t | ¡ ¡}W d  ƒ n1 sw   Y  | ¡ D ]	\}}|| j|< q'dS t |tƒrj|| _	|| _
|| _|| _|| _|| _|| _|| _|	| _|
| _|| _|| _|| _|| _|| _|| _dS tdƒ‚)a¨  Constructs BertConfig.

        Args:
            vocab_size_or_config_json_file: Vocabulary size of `inputs_ids` in `BertModel`.
            hidden_size: Size of the encoder layers and the pooler layer.
            num_hidden_layers: Number of hidden layers in the Transformer encoder.
            num_attention_heads: Number of attention heads for each attention layer in
                the Transformer encoder.
            intermediate_size: The size of the "intermediate" (i.e., feed-forward)
                layer in the Transformer encoder.
            hidden_act: The non-linear activation function (function or string) in the
                encoder and pooler. If string, "gelu", "relu" and "swish" are supported.
            hidden_dropout_prob: The dropout probability for all fully connected
                layers in the embeddings, encoder, and pooler.
            attention_probs_dropout_prob: The dropout ratio for the attention
                probabilities.
            max_position_embeddings: The maximum sequence length that this model might
                ever be used with. Typically set this to something large just in case
                (e.g., 512 or 1024 or 2048).
            type_vocab_size: The vocabulary size of the `token_type_ids` passed into
                `BertModel`.
            initializer_range: The stdev of the truncated_normal_initializer for
                initializing all weight matrices.
        Úrúutf-8©ÚencodingNzhFirst argument must be either a vocabulary size (int)or the path to a pretrained model config file (str))Ú
isinstanceÚstrÚopenÚjsonÚloadsÚreadÚitemsÚ__dict__r=   Ú
vocab_sizeÚhidden_sizeÚnum_hidden_layersÚnum_attention_headsÚ
hidden_actÚintermediate_sizeÚhidden_dropout_probÚattention_probs_dropout_probÚmax_position_embeddingsÚtype_vocab_sizeÚinitializer_rangeÚ	deep_initÚfp32_layernormÚfp32_embeddingÚlayernorm_epsilonÚfp32_tokentypesÚ
ValueError)ÚselfÚvocab_size_or_config_json_filerk   rl   rm   ro   rn   rp   rq   rr   rs   rt   ru   rv   rw   ry   rx   ÚreaderZjson_configÚkeyÚvaluer   r   r   Ú__init__±   s>   
)þýÿ

ÿzBertConfig.__init__c                 C   s*   t dd}| ¡ D ]	\}}||j|< q	|S )zAConstructs a `BertConfig` from a Python dictionary of parameters.éÿÿÿÿ)r|   )rV   rh   ri   )ÚclsZjson_objectÚconfigr~   r   r   r   r   Ú	from_dict÷   s   
zBertConfig.from_dictc                 C   sF   t |ddd}| ¡ }W d  ƒ n1 sw   Y  |  t |¡¡S )z9Constructs a `BertConfig` from a json file of parameters.r^   r_   r`   N)rd   rg   r„   re   rf   )r‚   Z	json_filer}   Útextr   r   r   Úfrom_json_fileÿ   s   
ÿzBertConfig.from_json_filec                 C   s   t |  ¡ ƒS rS   )rc   Úto_json_string©r{   r   r   r   Ú__repr__  s   zBertConfig.__repr__c                 C   s   t  | j¡}|S )z0Serializes this instance to a Python dictionary.)ÚcopyÚdeepcopyri   ©r{   Úoutputr   r   r   Úto_dict	  s   zBertConfig.to_dictc                 C   s   t j|  ¡ dddd S )z*Serializes this instance to a JSON string.r   T)ÚindentÚ	sort_keysÚ
)re   ÚdumpsrŽ   rˆ   r   r   r   r‡     s   zBertConfig.to_json_stringN)rW   rX   rX   rY   rR   rZ   rZ   r[   r   r\   FFFFr]   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r€   Úclassmethodr„   r†   r‰   rŽ   r‡   r   r   r   r   rV   ­   s2    
ðF

rV   )ÚFusedLayerNormzYBetter speed can be achieved with apex installed from https://www.github.com/nvidia/apex.c                       s&   e Zd Zd‡ fdd„	Zdd„ Z‡  ZS )ÚBertLayerNormr]   c                    s<   t t| ƒ ¡  t t |¡¡| _t t |¡¡| _	|| _
dS )z[Construct a layernorm module in the TF style (epsilon inside the square root).
            N)Úsuperr™   r€   r   Ú	Parameterr   Zonesr)   Zzerosr+   Úvariance_epsilon)r{   rk   Úeps©Ú	__class__r   r   r€     s   
zBertLayerNorm.__init__c                 C   sN   |j ddd}||  d¡j ddd}|| t || j ¡ }| j| | j S )Nr   T)Zkeepdimr   )r   Úpowr   r   rœ   r)   r+   )r{   rQ   ÚuÚsr   r   r   Úforward$  s   zBertLayerNorm.forward)r]   ©r“   r”   r•   r€   r£   Ú__classcell__r   r   rž   r   r™     s    r™   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                    s€   t t| ƒ ¡  t |j|j¡| _t |j|j¡| _	t |j
|j¡| _|j| _|j| _|j| _t|j|jd| _t |j¡| _d S ©N©r   )rš   r¦   r€   r   Ú	Embeddingrj   rk   Úword_embeddingsrr   Úposition_embeddingsrs   Útoken_type_embeddingsrv   rw   ry   r™   rx   Ú	LayerNormÚDropoutrp   Údropout©r{   rƒ   rž   r   r   r€   /  s"   ÿÿÿÿzBertEmbeddings.__init__Nc           
      C   s@  |  d¡}tj|tj|jd}| d¡ |¡}|d u r t |¡}|  |¡}|  	|¡}|  
|¡}| jsc|| | }| jrB| jsB| ¡ }| ¡ }	| jrM| ¡ }|  |¡}| jrb| jr]| ¡ }n<| |	¡}n6| ¡ | ¡  | ¡  }| jry| jsy| ¡ }| ¡ }	| jr„| ¡ }|  |¡}| jr™| jr”| ¡ }n| |	¡}|  |¡}|S )Nr   )ÚdtypeÚdevicer   )Úsizer   ZarangeÚlongr²   r    Z	expand_asÚ
zeros_likerª   r«   r¬   ry   rw   rv   ÚhalfÚtypeÚfloatr­   r¯   )
r{   Ú	input_idsÚtoken_type_idsZ
seq_lengthZposition_idsZwords_embeddingsr«   r¬   Ú
embeddingsÚprevious_typer   r   r   r£   E  sL   

ÿ






€ÿ



zBertEmbeddings.forwardrS   ©r“   r”   r•   r–   r€   r£   r¥   r   r   rž   r   r¦   +  s    r¦   c                       s,   e Zd Z‡ fdd„Zdd„ Zdd„ Z‡  ZS )ÚBertSelfAttentionc                    s¢   t t| ƒ ¡  |j|j dkrtd|j|jf ƒ‚|j| _t|j|j ƒ| _| j| j | _t	 
|j| j¡| _t	 
|j| j¡| _t	 
|j| j¡| _t	 |j¡| _d S )Nr   zLThe hidden size (%d) is not a multiple of the number of attention heads (%d))rš   r¾   r€   rk   rm   rz   r=   Úattention_head_sizeÚall_head_sizer   ÚLinearÚqueryr~   r   r®   rq   r¯   r°   rž   r   r   r€   r  s    
þÿÿzBertSelfAttention.__init__c                 C   s6   |  ¡ d d… | j| jf }|j|Ž }| dddd¡S )Nr   r   r   r   é   )r³   rm   r¿   ÚviewÚpermute)r{   rQ   Znew_x_shaper   r   r   Útranspose_for_scores„  s
   ÿ
z&BertSelfAttention.transpose_for_scoresc                 C   sÐ   |   |¡}|  |¡}|  |¡}|  |¡}|  |¡}|  |¡}t || dd¡¡}	|	t | j	¡ }	|	| }	t
jdd|	ƒ}
|  |
¡}
|
 ¡ }t |
|¡}| dddd¡ ¡ }| ¡ d d… | jf }|j|Ž }|S )Nr   éþÿÿÿ©Údimr   r   r   rÃ   )rÂ   r~   r   rÆ   r   Úmatmulr>   r   r   r¿   r   ZSoftmaxr¯   r·   rÅ   Ú
contiguousr³   rÀ   rÄ   )r{   Úhidden_statesr!   Zmixed_query_layerZmixed_key_layerZmixed_value_layerZquery_layerZ	key_layerZvalue_layerZattention_scoresZattention_probsr¼   Zcontext_layerZnew_context_layer_shaper   r   r   r£   Š  s.   






ÿÿ
ÿ
zBertSelfAttention.forward)r“   r”   r•   r€   rÆ   r£   r¥   r   r   rž   r   r¾   p  s    r¾   c                       ó$   e Zd Z‡ fdd„Zdd„ Z‡  ZS )ÚBertSelfOutputc                    s‚   t t| ƒ ¡  t|dƒr|jrtd|j|jd}ntd|jd}t	j
|j|jdd| _|j| _t|j|jd| _t	 |j¡| _d S ©Nru   ç        )r   r   r   r   T©r+   r¨   )rš   rÎ   r€   Úhasattrru   r   rt   rl   r   r   rÁ   rk   Údenserv   r™   rx   r­   r®   rp   r¯   ©r{   rƒ   Zinit_methodrž   r   r   r€   ­  ó$   ýÿ
ÿ	ÿzBertSelfOutput.__init__c                 C   óP   |   |¡}|  |¡}|| }| ¡ }| jr| ¡ }|  |¡}| jr&| |¡}|S rS   ©rÓ   r¯   r·   rv   r¸   r­   ©r{   rÌ   Úinput_tensorZln_inputr¼   r   r   r   r£   Å  ó   



zBertSelfOutput.forwardr¤   r   r   rž   r   rÎ   «  ó    rÎ   c                       rÍ   )ÚBertAttentionc                    s&   t t| ƒ ¡  t|ƒ| _t|ƒ| _d S rS   )rš   rÜ   r€   r¾   r{   rÎ   r   r°   rž   r   r   r€   Ô  s   
zBertAttention.__init__c                 C   s   |   ||¡}|  ||¡}|S rS   rŒ   )r{   rÙ   r!   Zself_outputÚattention_outputr   r   r   r£   à  s   zBertAttention.forwardr¤   r   r   rž   r   rÜ   Ò  s    rÜ   c                       rÍ   )ÚBertIntermediatec                    sL   t t| ƒ ¡  tj|j|jdd| _t|j	t
ƒr t|j	 | _d S |j	| _d S )NTrÑ   )rš   rÞ   r€   r   rÁ   rk   ro   rÓ   rb   rn   rc   ÚACT2FNÚintermediate_act_fnr°   rž   r   r   r€   è  s   
ÿ
ÿÿzBertIntermediate.__init__c                 C   s   |   |¡}|  |¡}|S rS   )rÓ   rà   ©r{   rÌ   r   r   r   r£   ÷  s   

zBertIntermediate.forwardr¤   r   r   rž   r   rÞ   æ  s    rÞ   c                       rÍ   )Ú
BertOutputc                    s‚   t t| ƒ ¡  t|dƒr|jrtd|j|jd}ntd|jd}t	j
|j|jdd| _|j| _t|j|jd| _t	 |j¡| _d S rÏ   )rš   râ   r€   rÒ   ru   r   rt   rl   r   r   rÁ   ro   rk   rÓ   rv   r™   rx   r­   r®   rp   r¯   rÔ   rž   r   r   r€   ÿ  rÕ   zBertOutput.__init__c                 C   rÖ   rS   r×   rØ   r   r   r   r£     rÚ   zBertOutput.forwardr¤   r   r   rž   r   râ   ý  rÛ   râ   c                       rÍ   )Ú	BertLayerc                    s0   t t| ƒ ¡  t|ƒ| _t|ƒ| _t|ƒ| _d S rS   )	rš   rã   r€   rÜ   Ú	attentionrÞ   Úintermediaterâ   r   r°   rž   r   r   r€   &  s   

zBertLayer.__init__c                 C   s&   |   ||¡}|  |¡}|  ||¡}|S rS   )rä   rå   r   )r{   rÌ   r!   rÝ   Zintermediate_outputZlayer_outputr   r   r   r£   ,  s   
zBertLayer.forwardr¤   r   r   rž   r   rã   $  ó    rã   c                       s*   e Zd Z‡ fdd„Z		ddd„Z‡  ZS )ÚBertEncoderc                    s2   t t| ƒ ¡  t ‡ fdd„tˆ jƒD ƒ¡| _d S )Nc                    s   g | ]}t ˆ ƒ‘qS r   )rã   )r%   Ú_©rƒ   r   r   Ú
<listcomp>:  s    z(BertEncoder.__init__.<locals>.<listcomp>)rš   rç   r€   r   Z
ModuleListÚrangerl   Úlayerr°   rž   ré   r   r€   5  s   
ÿzBertEncoder.__init__TFc                    sž   g }‡ fdd„}|r.d}t ˆ jƒ}d}	||k r-t ||||	 ƒ||d ¡}||	7 }||k sntˆ jƒD ]\}
}|||ƒ}|rC| |¡ q3|rH|rM| |¡ |S )Nc                    s   ‡ ‡‡fdd„}|S )Nc                     s2   ˆj ˆˆ … }| d }|D ]	}||| d ƒ}q|S )Nr   r   )rì   )ÚinputsZlayersZx_rì   )Úendr{   Ústartr   r   Úcustom_forwardN  s
   z;BertEncoder.forward.<locals>.custom.<locals>.custom_forwardr   )rï   rî   rð   rˆ   )rî   rï   r   ÚcustomL  s   z#BertEncoder.forward.<locals>.customr   r   )r<   rì   r   Ú
checkpointÚ	enumerater5   )r{   rÌ   r!   Úoutput_all_encoded_layersÚcheckpoint_activationsZall_encoder_layersrñ   rJ   r   Úchunk_lengthÚiZlayer_moduler   rˆ   r   r£   E  s,   
þü€

€
zBertEncoder.forward)TFr¤   r   r   rž   r   rç   3  s
    ürç   c                       rÍ   )Ú
BertPoolerc                    s.   t t| ƒ ¡  t |j|j¡| _t ¡ | _d S rS   )	rš   rø   r€   r   rÁ   rk   rÓ   ZTanhÚ
activationr°   rž   r   r   r€   o  s   zBertPooler.__init__c                 C   s(   |d d …df }|   |¡}|  |¡}|S )Nr   )rÓ   rù   )r{   rÌ   Zfirst_token_tensorÚpooled_outputr   r   r   r£   t  s   

zBertPooler.forwardr¤   r   r   rž   r   rø   m  ó    rø   c                       rÍ   )ÚBertPredictionHeadTransformc                    s\   t t| ƒ ¡  t |j|j¡| _t|jt	ƒrt
|j n|j| _t|j|jd| _|j| _d S r§   )rš   rü   r€   r   rÁ   rk   rÓ   rb   rn   rc   rß   Útransform_act_fnr™   rx   r­   rv   r°   rž   r   r   r€     s   
ÿÿÿz$BertPredictionHeadTransform.__init__c                 C   sH   |   |¡}|  |¡}| ¡ }| jr| ¡ }|  |¡}| jr"| |¡}|S rS   )rÓ   rý   r·   rv   r¸   r­   )r{   rÌ   r¼   r   r   r   r£   ˆ  s   



z#BertPredictionHeadTransform.forwardr¤   r   r   rž   r   rü   }  s    	rü   c                       rÍ   )ÚBertLMPredictionHeadc                    sb   t tˆ ƒ ¡  t|ƒˆ _tj| d¡| d¡ddˆ _|j	ˆ _	|j
ˆ _
‡ fdd„}|ˆ _dˆ _d S )Nr   r   FrÑ   c                    s   ˆ j r|  ¡ S | S rS   )rw   r¶   r   rˆ   r   r   Úconvert_to_type¦  s   z6BertLMPredictionHead.__init__.<locals>.convert_to_type)rš   rþ   r€   rü   Ú	transformr   rÁ   r³   Údecoderrw   rv   Útype_converterÚ	converted)r{   rƒ   Úbert_model_embedding_weightsrÿ   rž   rˆ   r   r€   –  s   
ý
zBertLMPredictionHead.__init__c                 C   sR   | j sd| _ | jr| j ¡  | jr| jj ¡  |  |  |¡¡}|  |¡| j	 }|S )NT)
r  rw   r   r¶   rv   r­   r¸   r  r  r+   rá   r   r   r   r£   ¯  s   
zBertLMPredictionHead.forwardr¤   r   r   rž   r   rþ   ”  s    rþ   c                       rÍ   )ÚBertOnlyMLMHeadc                    s   t t| ƒ ¡  t||ƒ| _d S rS   )rš   r  r€   rþ   Úpredictions©r{   rƒ   r  rž   r   r   r€   Á  s   
ÿzBertOnlyMLMHead.__init__c                 C   ó   |   |¡}|S rS   )r  )r{   Úsequence_outputÚprediction_scoresr   r   r   r£   Æ  ó   
zBertOnlyMLMHead.forwardr¤   r   r   rž   r   r  ¿  rû   r  c                       rÍ   )ÚBertOnlyNSPHeadc                    s"   t t| ƒ ¡  t |jd¡| _d S ©Nr   )rš   r  r€   r   rÁ   rk   Úseq_relationshipr°   rž   r   r   r€   Í  s   zBertOnlyNSPHead.__init__c                 C   r  rS   )r  )r{   rú   Úseq_relationship_scorer   r   r   r£   Ñ  r  zBertOnlyNSPHead.forwardr¤   r   r   rž   r   r  Ë  s    r  c                       rÍ   )ÚBertPreTrainingHeadsc                    s.   t t| ƒ ¡  t||ƒ| _t |jd¡| _d S r  )	rš   r  r€   rþ   r  r   rÁ   rk   r  r  rž   r   r   r€   Ø  s
   ÿzBertPreTrainingHeads.__init__c                 C   s@   |   |¡}| j ¡ D ]}|d u rq
| |¡}q
|  |¡}||fS rS   )r  r  Ú
parametersÚtype_as)r{   r	  rú   r
  Úpr  r   r   r   r£   Þ  s   

zBertPreTrainingHeads.forwardr¤   r   r   rž   r   r  Ö  ræ   r  c                       sB   e Zd ZdZ‡ fdd„Zdd„ Ze						dd	d
„ƒZ‡  ZS )ÚPreTrainedBertModelz† An abstract class to handle weights initialization and
        a simple interface for downloading and loading pretrained models.
    c                    s:   t t| ƒ ¡  t|tƒstd | jj| jj¡ƒ‚|| _	d S )Nz¶Parameter config in `{}(config)` should be an instance of class `BertConfig`. To create a model from a Google pretrained model use `model = {}.from_pretrained(PRETRAINED_MODEL_NAME)`)
rš   r  r€   rb   rV   rz   r3   rŸ   r“   rƒ   )r{   rƒ   rí   Úkwargsrž   r   r   r€   í  s   
ÿý
zPreTrainedBertModel.__init__c                 C   s|   t |tjtjfƒr|jjjd| jjd nt |t	ƒr'|j
j ¡  |jj d¡ t |tjƒr:|j
dur<|j
j ¡  dS dS dS )z! Initialize the weights.
        rÐ   r   rN   N)rb   r   rÁ   r©   r)   rB   r   rƒ   rt   r™   r+   Zzero_Zfill_)r{   Úmoduler   r   r   Úinit_bert_weights÷  s   ÿ
ÿz%PreTrainedBertModel.init_bert_weightsNFr]   c                    sž  |t v r	t | }
n|}
zt|
|d}W n ty,   t d |d t  ¡ ¡|
¡¡ Y dS w ||
kr:t d |
¡¡ n	t d |
|¡¡ d}t	j
 |¡rN|}n*t ¡ }t d ||¡¡ t |d¡}| |¡ W d  ƒ n1 sqw   Y  |}t	j
 |t¡}t |¡}||_||_||_||_t d	 |¡¡ | |g|¢R i |	¤Ž}ˆdu r³t	j
 |t¡}t |¡‰g }g }ˆ ¡ D ]$}d}d
|v rÉ| d
d¡}d|v rÓ| dd¡}|rß| |¡ | |¡ q»t||ƒD ]\}}ˆ |¡ˆ|< qåg ‰g ‰g ‰ tˆddƒ‰ˆ  ¡ ‰ˆdur	ˆˆ_!d‡ ‡‡‡‡‡fdd„	‰ˆ|t"|dƒrdndd t#ˆƒdkr4t$d |j%j&ˆ¡ƒ t#ˆƒdkrEt$d |j%j&ˆ¡ƒ |rMt' (|¡ |S )aæ  
        Instantiate a PreTrainedBertModel from a pre-trained model file or a pytorch state dict.
        Download and cache the pre-trained model file if needed.

        Params:
            pretrained_model_name: either:
                - a str with the name of a pre-trained model to load selected in the list of:
                    . `bert-base-uncased`
                    . `bert-large-uncased`
                    . `bert-base-cased`
                    . `bert-large-cased`
                    . `bert-base-multilingual-uncased`
                    . `bert-base-multilingual-cased`
                    . `bert-base-chinese`
                - a path or url to a pretrained model archive containing:
                    . `bert_config.json` a configuration file for the model
                    . `pytorch_model.bin` a PyTorch dump of a BertForPreTraining instance
            cache_dir: an optional path to a folder in which the pre-trained models will be cached.
            state_dict: an optional state dictionary (collections.OrderedDict object) to use instead of Google pre-trained models
            *inputs, **kwargs: additional input for the specific Bert class
                (ex: num_labels for BertForSequenceClassification)
        )Ú	cache_dirz“Model name '{}' was not found in model name list ({}). We assumed '{}' was a path or url but couldn't find any file associated to this path or url.z, Nzloading archive file {}z(loading archive file {} from cache at {}z)extracting archive file {} to temp dir {}zr:gzzModel config {}r(   r)   r*   r+   Ú	_metadataÚ c              	      sh   ˆd u ri n	ˆ  |d d… i ¡}|  ˆ||dˆˆˆ ¡ | j ¡ D ]\}}|d ur1ˆ||| d ƒ q d S )Nr   TÚ.)ÚgetZ_load_from_state_dictZ_modulesrh   )r  ÚprefixZlocal_metadatarG   Úchild©Ú
error_msgsÚloadÚmetadataZmissing_keysÚ
state_dictZunexpected_keysr   r   r!  l  s   ÿ
þ€þz1PreTrainedBertModel.from_pretrained.<locals>.loadÚbertzbert.)r  r   z7Weights of {} not initialized from pretrained model: {}z0Weights from pretrained model not used in {}: {})r  ))ÚPRETRAINED_MODEL_ARCHIVE_MAPr   ÚFileNotFoundErrorÚloggerÚerrorr3   r9   ÚkeysÚinfor0   r1   ÚisdirÚtempfileÚmkdtempÚtarfilerd   Ú
extractallÚCONFIG_NAMErV   r†   rv   rw   rx   ry   ÚWEIGHTS_NAMEr   r!  Úreplacer5   r6   Úpopr;   rŠ   r  rÒ   r<   r/   rŸ   r“   ÚshutilÚrmtree)r‚   Zpretrained_model_namer#  r  rv   rw   rx   ry   rí   r  Zarchive_fileZresolved_archive_fileÚtempdirZserialization_dirÚarchiveÚconfig_filerƒ   rC   Zweights_pathZold_keysZnew_keysr~   Znew_keyÚold_keyr   r  r   Úfrom_pretrained  sž   !

ÿýýø	ÿÿÿ



€

ÿÿ
z#PreTrainedBertModel.from_pretrained)NNFFr]   F)	r“   r”   r•   r–   r€   r  r—   r:  r¥   r   r   rž   r   r  è  s    
ùr  c                       s2   e Zd ZdZ‡ fdd„Z				d	dd„Z‡  ZS )
Ú	BertModela  BERT model ("Bidirectional Embedding Representations from a Transformer").

    Params:
        config: a BertConfig class instance with the configuration to build a new model

    Inputs:
        `input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]
            with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts
            `extract_features.py`, `run_classifier.py` and `run_squad.py`)
        `token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token
            types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to
            a `sentence B` token (see BERT paper for more details).
        `attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices
            selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max
            input sequence length in the current batch. It's the mask that we typically use for attention when
            a batch has varying length sentences.
        `output_all_encoded_layers`: boolean which controls the content of the `encoded_layers` output as described below. Default: `True`.

    Outputs: Tuple of (encoded_layers, pooled_output)
        `encoded_layers`: controlled by `output_all_encoded_layers` argument:
            - `output_all_encoded_layers=True`: outputs a list of the full sequences of encoded-hidden-states at the end
                of each attention block (i.e. 12 full sequences for BERT-base, 24 for BERT-large), each
                encoded-hidden-state is a torch.FloatTensor of size [batch_size, sequence_length, hidden_size],
            - `output_all_encoded_layers=False`: outputs only the full sequence of hidden-states corresponding
                to the last attention block of shape [batch_size, sequence_length, hidden_size],
        `pooled_output`: a torch.FloatTensor of size [batch_size, hidden_size] which is the output of a
            classifier pretrained on top of the hidden state associated to the first character of the
            input (`CLF`) to train on the Next-Sentence task (see BERT's paper).

    Examples:
        >>> # Already been converted into WordPiece token ids
        >>> input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])
        >>> input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])
        >>> token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])

        >>> config = modeling.BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,
        >>>     num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)

        >>> model = modeling.BertModel(config=config)
        >>> all_encoder_layers, pooled_output = model(input_ids, token_type_ids, input_mask)
    c                    s>   t t| ƒ |¡ t|ƒ| _t|ƒ| _t|ƒ| _|  	| j
¡ d S rS   )rš   r;  r€   r¦   r»   rç   Úencoderrø   ÚpoolerÚapplyr  r°   rž   r   r   r€   ®  s
   


zBertModel.__init__NTFc                 C   sÄ   |d u r	t  |¡}|d u rt  |¡}| d¡ d¡}|jt| j ¡ ƒjd}d| d }|  	||¡}| j||||d}|d }	| j
 ¡ D ]}
|
d u rKqD|	 |
¡}	 |  
|	¡}|rZ|r^|d }||fS )Nr   r   )r±   rN   g     ˆÃÀ©rô   rõ   r   )r   Z	ones_likerµ   r    ÚtoÚnextr<  r  r±   r»   r=  r  )r{   r¹   rº   r!   rô   rõ   r"   Zembedding_outputZencoded_layersr	  r  rú   r   r   r   r£   µ  s4   

ÿü

zBertModel.forward)NNTFr½   r   r   rž   r   r;  ƒ  ó    *	ûr;  c                       ó4   e Zd ZdZ‡ fdd„Z					ddd„Z‡  ZS )	ÚBertForPreTrainingaz  BERT model with pre-training heads.
    This module comprises the BERT model followed by the two pre-training heads:
        - the masked language modeling head, and
        - the next sentence classification head.

    Params:
        config: a BertConfig class instance with the configuration to build a new model.

    Inputs:
        `input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]
            with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts
            `extract_features.py`, `run_classifier.py` and `run_squad.py`)
        `token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token
            types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to
            a `sentence B` token (see BERT paper for more details).
        `attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices
            selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max
            input sequence length in the current batch. It's the mask that we typically use for attention when
            a batch has varying length sentences.
        `masked_lm_labels`: masked language modeling labels: torch.LongTensor of shape [batch_size, sequence_length]
            with indices selected in [-1, 0, ..., vocab_size]. All labels set to -1 are ignored (masked), the loss
            is only computed for the labels set in [0, ..., vocab_size]
        `next_sentence_label`: next sentence classification loss: torch.LongTensor of shape [batch_size]
            with indices selected in [0, 1].
            0 => next sentence is the continuation, 1 => next sentence is a random sentence.

    Outputs:
        if `masked_lm_labels` and `next_sentence_label` are not `None`:
            Outputs the total_loss which is the sum of the masked language modeling loss and the next
            sentence classification loss.
        if `masked_lm_labels` or `next_sentence_label` is `None`:
            Outputs a tuple comprising
            - the masked language modeling logits of shape [batch_size, sequence_length, vocab_size], and
            - the next sentence classification logits of shape [batch_size, 2].

    Examples:
        >>> # Already been converted into WordPiece token ids
        >>> input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])
        >>> input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])
        >>> token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])

        >>> config = BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,
        >>>     num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)

        >>> model = BertForPreTraining(config)
        >>> masked_lm_logits_scores, seq_relationship_logits = model(input_ids, token_type_ids, input_mask)
    c                    ó>   t t| ƒ |¡ t|ƒ| _t|| jjjjƒ| _	|  
| j¡ d S rS   )rš   rD  r€   r;  r$  r  r»   rª   r)   r‚   r>  r  r°   rž   r   r   r€     s   
ÿzBertForPreTraining.__init__NFc                 C   s’   | j |||d|d\}}|  ||¡\}	}
|d urE|d urEtdd}||	 d| jj¡ ¡ | d¡ƒ}||
 dd¡ ¡ | d¡ƒ}|| }|S |	|
fS ©NFr?  r   ©Zignore_indexr   )r$  r‚   r	   rÄ   rƒ   rj   r¸   )r{   r¹   rº   r!   Úmasked_lm_labelsÚnext_sentence_labelrõ   r	  rú   r
  r  Úloss_fctÚmasked_lm_lossÚnext_sentence_lossÚ
total_lossr   r   r   r£     s.   
ûÿ
þþzBertForPreTraining.forward©NNNNFr½   r   r   rž   r   rD  â  s    0	úrD  c                       ó2   e Zd ZdZ‡ fdd„Z				ddd„Z‡  ZS )	ÚBertForMaskedLMa	  BERT model with the masked language modeling head.
    This module comprises the BERT model followed by the masked language modeling head.

    Params:
        config: a BertConfig class instance with the configuration to build a new model.

    Inputs:
        `input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]
            with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts
            `extract_features.py`, `run_classifier.py` and `run_squad.py`)
        `token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token
            types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to
            a `sentence B` token (see BERT paper for more details).
        `attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices
            selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max
            input sequence length in the current batch. It's the mask that we typically use for attention when
            a batch has varying length sentences.
        `masked_lm_labels`: masked language modeling labels: torch.LongTensor of shape [batch_size, sequence_length]
            with indices selected in [-1, 0, ..., vocab_size]. All labels set to -1 are ignored (masked), the loss
            is only computed for the labels set in [0, ..., vocab_size]

    Outputs:
        if `masked_lm_labels` is  not `None`:
            Outputs the masked language modeling loss.
        if `masked_lm_labels` is `None`:
            Outputs the masked language modeling logits of shape [batch_size, sequence_length, vocab_size].

    Examples:
        >>> # Already been converted into WordPiece token ids
        >>> input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])
        >>> input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])
        >>> token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])

        >>> config = BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,
        >>>     num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)

        >>> model = BertForMaskedLM(config)
        >>> masked_lm_logits_scores = model(input_ids, token_type_ids, input_mask)
    c                    rE  rS   )rš   rP  r€   r;  r$  r  r»   rª   r)   r‚   r>  r  r°   rž   r   r   r€   a  s   

ÿzBertForMaskedLM.__init__NFc                 C   sX   | j |||d|d\}}|  |¡}|d ur*tdd}	|	| d| jj¡| d¡ƒ}
|
S |S )NFr?  r   rG  )r$  r‚   r	   rÄ   rƒ   rj   )r{   r¹   rº   r!   rH  rõ   r	  rè   r
  rJ  rK  r   r   r   r£   h  s    
û

þzBertForMaskedLM.forward©NNNFr½   r   r   rž   r   rP  8  s    (	ûrP  c                       rO  )	ÚBertForNextSentencePredictiona7	  BERT model with next sentence prediction head.
    This module comprises the BERT model followed by the next sentence classification head.

    Params:
        config: a BertConfig class instance with the configuration to build a new model.

    Inputs:
        `input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]
            with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts
            `extract_features.py`, `run_classifier.py` and `run_squad.py`)
        `token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token
            types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to
            a `sentence B` token (see BERT paper for more details).
        `attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices
            selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max
            input sequence length in the current batch. It's the mask that we typically use for attention when
            a batch has varying length sentences.
        `next_sentence_label`: next sentence classification loss: torch.LongTensor of shape [batch_size]
            with indices selected in [0, 1].
            0 => next sentence is the continuation, 1 => next sentence is a random sentence.

    Outputs:
        if `next_sentence_label` is not `None`:
            Outputs the total_loss which is the sum of the masked language modeling loss and the next
            sentence classification loss.
        if `next_sentence_label` is `None`:
            Outputs the next sentence classification logits of shape [batch_size, 2].

    Examples:
        >>> # Already been converted into WordPiece token ids
        >>> input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])
        >>> input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])
        >>> token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])

        >>> config = BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,
        >>>     num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)

        >>> model = BertForNextSentencePrediction(config)
        >>> seq_relationship_logits = model(input_ids, token_type_ids, input_mask)
    c                    s4   t t| ƒ |¡ t|ƒ| _t|ƒ| _|  | j¡ d S rS   )	rš   rR  r€   r;  r$  r  r‚   r>  r  r°   rž   r   r   r€   ª  s   

z&BertForNextSentencePrediction.__init__NFc                 C   sT   | j |||d|d\}}|  |¡}|d ur(tdd}	|	| dd¡| d¡ƒ}
|
S |S rF  )r$  r‚   r	   rÄ   )r{   r¹   rº   r!   rI  rõ   rè   rú   r  rJ  rL  r   r   r   r£   °  s    
û


þz%BertForNextSentencePrediction.forwardrQ  r½   r   r   rž   r   rR  €  s    )ûrR  c                       ó4   e Zd ZdZd	‡ fdd„	Z				d
dd„Z‡  ZS )ÚBertForSequenceClassificationaä  BERT model for classification.
    This module is composed of the BERT model with a linear layer on top of
    the pooled output.

    Params:
        `config`: a BertConfig class instance with the configuration to build a new model.
        `num_labels`: the number of classes for the classifier. Default = 2.

    Inputs:
        `input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]
            with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts
            `extract_features.py`, `run_classifier.py` and `run_squad.py`)
        `token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token
            types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to
            a `sentence B` token (see BERT paper for more details).
        `attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices
            selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max
            input sequence length in the current batch. It's the mask that we typically use for attention when
            a batch has varying length sentences.
        `labels`: labels for the classification output: torch.LongTensor of shape [batch_size]
            with indices selected in [0, ..., num_labels].

    Outputs:
        if `labels` is not `None`:
            Outputs the CrossEntropy classification loss of the output with the labels.
        if `labels` is `None`:
            Outputs the classification logits of shape [batch_size, num_labels].

    Examples:
        >>> # Already been converted into WordPiece token ids
        >>> input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])
        >>> input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])
        >>> token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])

        >>> config = BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,
        >>>     num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)

        >>> num_labels = 2

        >>> model = BertForSequenceClassification(config, num_labels)
        >>> logits = model(input_ids, token_type_ids, input_mask)
    r   c                    óN   t t| ƒ |¡ || _t|ƒ| _t |j¡| _	t 
|j|¡| _|  | j¡ d S rS   )rš   rT  r€   Ú
num_labelsr;  r$  r   r®   rp   r¯   rÁ   rk   Ú
classifierr>  r  ©r{   rƒ   rV  rž   r   r   r€   ô  s   
z&BertForSequenceClassification.__init__NFc                 C   s\   | j |||d|d\}}|  |¡}|  |¡}|d ur,tƒ }	|	| d| j¡| d¡ƒ}
|
S |S ©NFr?  r   )r$  r¯   rW  r	   rÄ   rV  )r{   r¹   rº   r!   Úlabelsrõ   rè   rú   ÚlogitsrJ  Úlossr   r   r   r£   ü  s   
û

z%BertForSequenceClassification.forward©r   rQ  r½   r   r   rž   r   rT  È  s    +
ûrT  c                       rO  )	ÚBertForMultipleChoicea]	  BERT model for multiple choice tasks.
    This module is composed of the BERT model with a linear layer on top of
    the pooled output.

    Params:
        `config`: a BertConfig class instance with the configuration to build a new model.
        `num_choices`: the number of classes for the classifier. Default = 2.

    Inputs:
        `input_ids`: a torch.LongTensor of shape [batch_size, num_choices, sequence_length]
            with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts
            `extract_features.py`, `run_classifier.py` and `run_squad.py`)
        `token_type_ids`: an optional torch.LongTensor of shape [batch_size, num_choices, sequence_length]
            with the token types indices selected in [0, 1]. Type 0 corresponds to a `sentence A`
            and type 1 corresponds to a `sentence B` token (see BERT paper for more details).
        `attention_mask`: an optional torch.LongTensor of shape [batch_size, num_choices, sequence_length] with indices
            selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max
            input sequence length in the current batch. It's the mask that we typically use for attention when
            a batch has varying length sentences.
        `labels`: labels for the classification output: torch.LongTensor of shape [batch_size]
            with indices selected in [0, ..., num_choices].

    Outputs:
        if `labels` is not `None`:
            Outputs the CrossEntropy classification loss of the output with the labels.
        if `labels` is `None`:
            Outputs the classification logits of shape [batch_size, num_labels].

    Examples:
        >>> # Already been converted into WordPiece token ids
        >>> input_ids = torch.LongTensor([[[31, 51, 99], [15, 5, 0]], [[12, 16, 42], [14, 28, 57]]])
        >>> input_mask = torch.LongTensor([[[1, 1, 1], [1, 1, 0]],[[1,1,0], [1, 0, 0]]])
        >>> token_type_ids = torch.LongTensor([[[0, 0, 1], [0, 1, 0]],[[0, 1, 1], [0, 0, 1]]])
        >>> config = BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,
        >>>     num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)

        >>> num_choices = 2

        >>> model = BertForMultipleChoice(config, num_choices)
        >>> logits = model(input_ids, token_type_ids, input_mask)
    c                    sH   t t| ƒ |¡ t|ƒ| _t |j¡| _t 	|j
d¡| _|  | j¡ d S )Nr   )rš   r^  r€   r;  r$  r   r®   rp   r¯   rÁ   rk   rW  r>  r  r°   rž   r   r   r€   >  s
   
zBertForMultipleChoice.__init__NFc                 C   s    |j d d… \}}| d| d¡¡}| d| d¡¡}	| d| d¡¡}
| j||	|
d|d\}}|  |¡}|  |¡}| d|¡}|d urNtƒ }|||ƒ}|S |S )Nr   r   Fr?  )r?   Zreshaper³   r$  r¯   rW  r	   )r{   r¹   rº   r!   rZ  rõ   Z
batch_sizeZnum_choicesZflat_input_idsZflat_token_type_idsZflat_attention_maskrè   rú   r[  Zreshaped_logitsrJ  r\  r   r   r   r£   E  s.   ÿÿ
û


zBertForMultipleChoice.forwardrQ  r½   r   r   rž   r   r^    rB  r^  c                       rS  )ÚBertForTokenClassificationa	  BERT model for token-level classification.
    This module is composed of the BERT model with a linear layer on top of
    the full hidden state of the last layer.

    Params:
        `config`: a BertConfig class instance with the configuration to build a new model.
        `num_labels`: the number of classes for the classifier. Default = 2.

    Inputs:
        `input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]
            with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts
            `extract_features.py`, `run_classifier.py` and `run_squad.py`)
        `token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token
            types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to
            a `sentence B` token (see BERT paper for more details).
        `attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices
            selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max
            input sequence length in the current batch. It's the mask that we typically use for attention when
            a batch has varying length sentences.
        `labels`: labels for the classification output: torch.LongTensor of shape [batch_size]
            with indices selected in [0, ..., num_labels].

    Outputs:
        if `labels` is not `None`:
            Outputs the CrossEntropy classification loss of the output with the labels.
        if `labels` is `None`:
            Outputs the classification logits of shape [batch_size, sequence_length, num_labels].

    Examples:
        >>> # Already been converted into WordPiece token ids
        >>> input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])
        >>> input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])
        >>> token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])

        >>> config = BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,
        >>>     num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)

        >>> num_labels = 2

        >>> model = BertForTokenClassification(config, num_labels)
        >>> logits = model(input_ids, token_type_ids, input_mask)
    r   c                    rU  rS   )rš   r_  r€   rV  r;  r$  r   r®   rp   r¯   rÁ   rk   rW  r>  r  rX  rž   r   r   r€     s   
	z#BertForTokenClassification.__init__NFc                 C   sˆ   | j |||d|d\}}t ¡  ¡  |  |¡}W d   ƒ n1 s"w   Y  |  |¡}|d urBtƒ }	|	| d| j¡| d¡ƒ}
|
S |S rY  )	r$  r   Zget_cuda_rng_trackerÚforkr¯   rW  r	   rÄ   rV  )r{   r¹   rº   r!   rZ  rõ   r	  rè   r[  rJ  r\  r   r   r   r£   Ÿ  s    
ûÿ
z"BertForTokenClassification.forwardr]  rQ  r½   r   r   rž   r   r_  c  s    +ûr_  c                       rC  )	ÚBertForQuestionAnsweringa  BERT model for Question Answering (span extraction).
    This module is composed of the BERT model with a linear layer on top of
    the sequence output that computes start_logits and end_logits

    Params:
        `config`: a BertConfig class instance with the configuration to build a new model.

    Inputs:
        `input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]
            with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts
            `extract_features.py`, `run_classifier.py` and `run_squad.py`)
        `token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token
            types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to
            a `sentence B` token (see BERT paper for more details).
        `attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices
            selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max
            input sequence length in the current batch. It's the mask that we typically use for attention when
            a batch has varying length sentences.
        `start_positions`: position of the first token for the labeled span: torch.LongTensor of shape [batch_size].
            Positions are clamped to the length of the sequence and position outside of the sequence are not taken
            into account for computing the loss.
        `end_positions`: position of the last token for the labeled span: torch.LongTensor of shape [batch_size].
            Positions are clamped to the length of the sequence and position outside of the sequence are not taken
            into account for computing the loss.

    Outputs:
        if `start_positions` and `end_positions` are not `None`:
            Outputs the total_loss which is the sum of the CrossEntropy loss for the start and end token positions.
        if `start_positions` or `end_positions` is `None`:
            Outputs a tuple of start_logits, end_logits which are the logits respectively for the start and end
            position tokens of shape [batch_size, sequence_length].

    Examples:
        >>> # Already been converted into WordPiece token ids
        >>> input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])
        >>> input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])
        >>> token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])

        >>> config = BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,
        >>>     num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)

        >>> model = BertForQuestionAnswering(config)
        >>> start_logits, end_logits = model(input_ids, token_type_ids, input_mask)
    c                    s:   t t| ƒ |¡ t|ƒ| _t |jd¡| _|  	| j
¡ d S r  )rš   ra  r€   r;  r$  r   rÁ   rk   Ú
qa_outputsr>  r  r°   rž   r   r   r€   å  s   
	z!BertForQuestionAnswering.__init__NFc                 C   sä   | j |||d|d\}}|  |¡}	|	jddd\}
}|
 d¡}
| d¡}|d urn|d urnt| ¡ ƒdkr9| d¡}t| ¡ ƒdkrF| d¡}|
 d¡}| d|¡ | d|¡ t|d}||
|ƒ}|||ƒ}|| d }|S |
|fS )	NFr?  r   r   rÈ   r   rG  r   )r$  rb  r7   Zsqueezer<   r³   Zclamp_r	   )r{   r¹   rº   r!   Zstart_positionsZend_positionsrõ   r	  rè   r[  Zstart_logitsZ
end_logitsZignored_indexrJ  Z
start_lossZend_lossrM  r   r   r   r£   õ  s2   
û








z BertForQuestionAnswering.forwardrN  r½   r   r   rž   r   ra  ·  s    -úra  )Ir–   Ú
__future__r   r   r   r   rŠ   Úloggingr   r0   r4  r.  r,  re   r   Ztorch.nn.functionalr   Z
functionalÚFZdata_utils.file_utilsr   Zmegatron_utilr   Ztorch.nnr	   r   r   r#   Ú	getLoggerr“   r'  ÚsetLevelÚINFOr%  r0  r1  ZTF_WEIGHTS_NAMErM   rR   rT   rU   rß   ÚobjectrV   Z#apex.normalization.fused_layer_normr˜   r™   r.   r/   ÚModuler¦   r¾   rÎ   rÜ   rÞ   râ   rã   rç   rø   rü   rþ   r  r  r  r  r;  rD  rP  rR  rT  r^  r_  ra  r   r   r   r   Ú<module>   sŠ   

ò?fÿûE;'':+ _VHHKPT