o
    ߥih                    @   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_tensorr    b/home/ubuntu/.local/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_maskattention_mask_b1sattention_mask_bs1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rt|d}n%|d dks|d dkrt|d}n|d dkrt|d}nt||d }t|dkrt|d }|| }qx|dd dkrt|d}n	|dkr||}z
|j|jksJ 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   NzLoading 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 ))adam_v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+)kernelgammaweightoutput_biasbetabiasoutput_weightsr    r   i_embeddingszInitialize PyTorch weight {})renumpy
tensorflowImportErrorprintospathabspathformattrainlist_variablesload_variableappendzipsplitanyjoin	fullmatchgetattrlenint	transposeshapeAssertionErrorargsr   
from_numpydata)modeltf_checkpoint_pathr6   nptftf_path	init_varsnamesarraysnamerL   arraypointerm_namelnumer   r   r   load_tf_weights_in_bert_   sn   


r`   c                 C   s    | d dt | td   S )zImplementation 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    re   c                 C   s   | t |  S N)r   sigmoidrc   r   r   r   swish   s   rh   )re   relurh   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`.
             re   皙?   r    {Gz?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__rJ   
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_filer   r   r   r   r   r   r   r   r   r   r   r   r   r   r   reader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   )rj   r|   r}   )cls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.rr   rs   rt   N)rx   r{   r   ry   rz   )r   	json_filer   textr   r   r   from_json_file   s   
zBertConfig.from_json_filec                 C   s   t |  S rf   )rw   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deepcopyr}   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
)ry   dumpsr   r   r   r   r   r     s   zBertConfig.to_json_stringN)rk   rl   rl   rm   re   rn   rn   ro   r    rp   FFFFrq   )__name__
__module____qualname____doc__r   classmethodr   r   r   r   r   r   r   r   r   rj      s2    
F

rj   )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 )BertLayerNormrq   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   onesr0   zerosr3   variance_epsilon)r   r   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)keepdimr    )r   powr   r   r   r0   r3   )r   rd   usr   r   r   forward$  s   zBertLayerNorm.forward)rq   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   	Embeddingr~   r   word_embeddingsr   position_embeddingsr   token_type_embeddingsr   r   r   r   r   	LayerNormDropoutr   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   arangelongr   r!   	expand_as
zeros_liker   r   r   r   r   r   halftypefloatr   r   )
r   	input_idstoken_type_ids
seq_lengthposition_idswords_embeddingsr   r   
embeddingsprevious_typer   r   r   r   E  sL   












zBertEmbeddings.forwardrf   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   r   r   r   rJ   attention_head_sizeall_head_sizer   Linearqueryr   r   r   r   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   r   r   viewpermute)r   rd   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   matmulrK   r   r   r   r   Softmaxr   r   r   
contiguousr   r   r   )r   hidden_statesr"   mixed_query_layermixed_key_layermixed_value_layerquery_layer	key_layervalue_layerattention_scoresattention_probsr   context_layer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 Nr           )r   r   r   r   Tr3   r   )r   r   r   hasattrr   r   r   r   r   r   r   r   denser   r   r   r   r   r   r   r   r   init_methodr   r   r   r     $   
	zBertSelfOutput.__init__c                 C   P   |  |}| |}|| }| }| jr| }| |}| jr&||}|S rf   r   r   r   r   r   r   r   r   input_tensor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 rf   )r   r	  r   r   r   r   r   r   r   r   r   r     s   
zBertAttention.__init__c                 C   s   |  ||}| ||}|S rf   r   )r   r  r"   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   r   r   r   rv   r   rw   ACT2FNintermediate_act_fnr   r   r   r   r     s   

zBertIntermediate.__init__c                 C   s   |  |}| |}|S rf   )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   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r     r  zBertOutput.__init__c                 C   r  rf   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 rf   )	r   r  r   r	  	attentionr  intermediater  r   r   r   r   r   r   &  s   

zBertLayer.__init__c                 C   s&   |  ||}| |}| ||}|S rf   )r  r  r   )r   r   r"   r  intermediate_output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   
ModuleListranger   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  )inputslayers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   )rI   r  r   
checkpoint	enumeraterB   )r   r   r"   output_all_encoded_layerscheckpoint_activationsall_encoder_layersr$  r]   r   chunk_lengthi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 rf   )	r   r-  r   r   r   r   r   Tanh
activationr   r   r   r   r   o  s   zBertPooler.__init__c                 C   s(   |d d df }|  |}| |}|S )Nr   )r   r/  )r   r   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   r3  r   r   r   r   r   rv   r   rw   r  transform_act_fnr   r   r   r   r   r   r   r   r     s   
z$BertPredictionHeadTransform.__init__c                 C   sH   |  |}| |}| }| jr| }| |}| jr"||}|S rf   )r   r4  r   r   r   r   )r   r   r   r   r   r   r     s   



z#BertPredictionHeadTransform.forwardr   r   r   r   r   r3  }  s    	r3  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 rf   )r   r   r   r   r   r   convert_to_type  s   z6BertLMPredictionHead.__init__.<locals>.convert_to_type)r   r5  r   r3  	transformr   r   r   decoderr   r   type_converter	converted)r   r   bert_model_embedding_weightsr6  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:  r   r7  r   r   r   r   r9  r8  r3   r  r   r   r   r     s   
zBertLMPredictionHead.forwardr   r   r   r   r   r5    s    r5  c                       r   )BertOnlyMLMHeadc                    s   t t|   t||| _d S rf   )r   r<  r   r5  predictionsr   r   r;  r   r   r   r     s   
zBertOnlyMLMHead.__init__c                 C      |  |}|S rf   )r=  )r   sequence_outputprediction_scoresr   r   r   r        
zBertOnlyMLMHead.forwardr   r   r   r   r   r<    r2  r<  c                       r   )BertOnlyNSPHeadc                    s"   t t|   t|jd| _d S Nr    )r   rC  r   r   r   r   seq_relationshipr   r   r   r   r     s   zBertOnlyNSPHead.__init__c                 C   r?  rf   )rE  )r   r1  seq_relationship_scorer   r   r   r     rB  zBertOnlyNSPHead.forwardr   r   r   r   r   rC    s    rC  c                       r   )BertPreTrainingHeadsc                    s.   t t|   t||| _t|jd| _d S rD  )	r   rG  r   r5  r=  r   r   r   rE  r>  r   r   r   r     s
   zBertPreTrainingHeads.__init__c                 C   s@   |  |}| j D ]}|d u rq
||}q
| |}||fS rf   )r=  rE  
parameterstype_as)r   r@  r1  rA  prF  r   r   r   r     s   

zBertPreTrainingHeads.forwardr   r   r   r   r   rG    r  rG  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 )NzParameter 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   rK  r   rv   rj   r   r>   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   ra   N)rv   r   r   r   r0   rP   r   r   r   r   r3   zero_fill_)r   moduler   r   r   init_bert_weights  s   
z%PreTrainedBertModel.init_bert_weightsNFrq   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 rt	j
|t}t|g }g } D ]$}d}d
|v r|d
d}d|v r|dd}|r|| || qt||D ]\}}||< qg 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_dirzModel 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/   r0   r2   r3   	_metadata c              	      sh   d u ri n	 |d d i }| ||d  | j D ]\}}|d ur1||| d  q d S )Nr   T.)get_load_from_state_dict_modulesr|   )rO  prefixlocal_metadatarY   child
error_msgsloadmetadatamissing_keys
state_dictunexpected_keysr   r   r]  l  s   
z1PreTrainedBertModel.from_pretrained.<locals>.loadbertzbert.)rX  r   z7Weights of {} not initialized from pretrained model: {}z0Weights from pretrained model not used in {}: {})rS  ))PRETRAINED_MODEL_ARCHIVE_MAPr   FileNotFoundErrorloggererrorr>   rF   keysinfor;   r<   isdirtempfilemkdtemptarfilerx   
extractallCONFIG_NAMErj   r   r   r   r   r   WEIGHTS_NAMEr   r]  replacerB   rC   poprH   r   rR  r   rI   r:   r   r   shutilrmtree)r   pretrained_model_namer`  rQ  r   r   r   r   r  rL  archive_fileresolved_archive_filetempdirserialization_dirarchiveconfig_filer   rQ   weights_pathold_keysnew_keysr   new_keyold_keyr   r[  r   from_pretrained  s   !

	






z#PreTrainedBertModel.from_pretrained)NNFFrq   F)	r   r   r   r   r   rP  r   r  r   r   r   r   r   rK    s    
rK  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`: controled 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 rf   )r   r  r   r   r   r  encoderr-  poolerapplyrP  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   ra   g     r'  r(  r   )r   	ones_liker   r!   tonextr  rH  r   r   r  rI  )r   r   r   r"   r'  r(  r&   embedding_outputencoded_layersr@  rJ  r1  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 rf   )r   r  r   r  rb  rG  r   r   r0   r   r  rP  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   ignore_indexr    )rb  r   r	   r   r   r~   r   )r   r   r   r"   masked_lm_labelsnext_sentence_labelr(  r@  r1  rA  rF  loss_fctmasked_lm_lossnext_sentence_loss
total_lossr   r   r   r     s.   

zBertForPreTraining.forwardNNNNFr   r   r   r   r   r    s    0	r  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                    r  rf   )r   r  r   r  rb  r<  r   r   r0   r   r  rP  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   r  )rb  r   r	   r   r   r~   )r   r   r   r"   r  r(  r@  r  rA  r  r  r   r   r   r   h  s    


zBertForMaskedLM.forwardNNNFr   r   r   r   r   r  8  s    (	r  c                       r  )	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 rf   )	r   r  r   r  rb  rC  r   r  rP  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 r  )rb  r   r	   r   )r   r   r   r"   r  r(  r  r1  rF  r  r  r   r   r   r     s    



z%BertForNextSentencePrediction.forwardr  r   r   r   r   r   r    s    )r  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 rf   )r   r  r   
num_labelsr  rb  r   r   r   r   r   r   
classifierr  rP  r   r   r  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   )rb  r   r  r	   r   r  )r   r   r   r"   labelsr(  r  r1  logitsr  lossr   r   r   r     s   


z%BertForSequenceClassification.forwardr    r  r   r   r   r   r   r    s    +
r  c                       r  )	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  rb  r   r   r   r   r   r   r  r  rP  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  )rL   reshaper   rb  r   r  r	   )r   r   r   r"   r  r(  
batch_sizenum_choicesflat_input_idsflat_token_type_idsflat_attention_maskr  r1  r  reshaped_logitsr  r  r   r   r   r   E  s.   



zBertForMultipleChoice.forwardr  r   r   r   r   r   r    r  r  c                       r  )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                    r  rf   )r   r  r   r  r  rb  r   r   r   r   r   r   r  r  rP  r  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 r  )	rb  r   get_cuda_rng_trackerforkr   r  r	   r   r  )r   r   r   r"   r  r(  r@  r  r  r  r  r   r   r   r     s    

z"BertForTokenClassification.forwardr  r  r   r   r   r   r   r  c  s    +r  c                       r  )	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 rD  )r   r  r   r  rb  r   r   r   
qa_outputsr  rP  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   r  r    )rb  r  rD   squeezerI   r   clamp_r	   )r   r   r   r"   start_positionsend_positionsr(  r@  r  r  start_logits
end_logitsignored_indexr  
start_lossend_lossr  r   r   r   r     s2   









z BertForQuestionAnswering.forwardr  r   r   r   r   r   r    s    -r  )Ir   
__future__r   r   r   r   r   loggingr   r;   rr  rl  rj  ry   r   torch.nn.functionalr   
functionalFdata_utils.file_utilsr   megatron_utilr   torch.nnr	   r   r   r'   	getLoggerr   re  setLevelINFOrc  rn  ro  TF_WEIGHTS_NAMEr`   re   rh   ri   r  objectrj   #apex.normalization.fused_layer_normr   r   r9   r:   Moduler   r   r   r	  r  r  r  r  r-  r3  r5  r<  rC  rG  rK  r  r  r  r  r  r  r  r  r   r   r   r   <module>   s   

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