U dL@sddlZddlZddlZddlmZmZmZmZmZddl Z ddl m Z m Z m Z m Z ddlmZddlmZddlmZddlmZdd lmZmZmZmZmZmZmZdd lmZe e!Z"zdd lm#Z#Wn&e$k rGd d d e j%Z#YnXee&e&e'ee'dfdddZ(GdddZ)Gddde j%e)eZ*Gddde j%Z+Gddde j%Z,Gddde j%Z-Gddde j%Z.Gddde j%Z/Gd d!d!e j%Z0d,d"d#Z1d-d$d%Z2d.d&d'Z3e&e&ed(e j fe j d)d*d+Z4dS)/N)CallableDictListOptionalTuple)Tensordevicedtypenn)CrossEntropyLoss) functional)get_activation)PretrainedConfig) DUMMY_INPUTSTF2_WEIGHTS_NAMETF_WEIGHTS_NAME WEIGHTS_NAME cached_path hf_bucket_url is_remote_url)GenerationMixin)Identitycs(eZdZdZfddZddZZS)rzFA placeholder identity operator that is argument-insensitive. cstdSN)super__init__)selfargskwargs __class__2/home/yxchng/Downloads/elia/bert/modeling_utils.pyr4szIdentity.__init__cCs|Srr!)rinputr!r!r"forward7szIdentity.forward__name__ __module__ __qualname____doc__rr$ __classcell__r!r!rr"r0s rztorch.LongTensor)headsn_heads head_sizealready_pruned_headsreturncsvt||}t||}|D]&tfdd|Dd|<q|dd}tt|| }||fS)Nc3s|]}|krdndVqdS)r rNr!).0hheadr!r" Bsz3find_pruneable_heads_and_indices..rr ) torchonessetsumview contiguouseqarangelenlong)r+r,r-r.maskindexr!r2r" find_pruneable_heads_and_indices;s   rBc@seZdZdZdeedddZeddZedd Z d d Z d d Z e e dddZ e edddZeedddZeee edddZd eeeedddZddZdS)!ModuleUtilsMixinzF A few utilities for torch.nn.Modules, to be used as a mixin. F)only_trainabler/cCs0|rtdd|n|}tdd|DS)zQ Get number of (optionally, trainable) parameters in the module. cSs|jSr) requires_grad)xr!r!r"Rz1ModuleUtilsMixin.num_parameters..css|]}|VqdSr)numel)r0pr!r!r"r4Ssz2ModuleUtilsMixin.num_parameters..)filter parametersr9)rrDparamsr!r!r"num_parametersNszModuleUtilsMixin.num_parameterscOsLz ddl}Wntk r(tdYnX|t}|}|j|_dS)NrFYou need to install psutil (pip install psutil) to use memory tracing.)psutil ImportErrorProcessosgetpid memory_inforssmem_rss_pre_forward)modulerrrPprocessmemr!r!r"_hook_rss_memory_pre_forwardUs z-ModuleUtilsMixin._hook_rss_memory_pre_forwardcOsrz ddl}Wntk r(tdYnX|t}|}|j|_|j|j}|t |drf|j nd|_ dS)NrrO mem_rss_diff) rPrQrRrSrTrUrVmem_rss_post_forwardrWhasattrr\)rXrrrPrYrZr\r!r!r"_hook_rss_memory_post_forwardas  z.ModuleUtilsMixin._hook_rss_memory_post_forwardcCs2|D]}||j||jq|dS)a Add a memory hook before and after each sub-module forward pass to record increase in memory consumption. Increase in memory consumption is stored in a `mem_rss_diff` attribute for each module and can be reset to zero with `model.reset_memory_hooks_state()` N)modulesregister_forward_pre_hookr[register_forward_hookr_reset_memory_hooks_staterrXr!r!r"add_memory_hooksos  z!ModuleUtilsMixin.add_memory_hookscCs$|D]}d|_d|_d|_qdS)Nr)r`r\r]rWrdr!r!r"rcxs z)ModuleUtilsMixin.reset_memory_hooks_state)r/cCsfzt|jWStk r`tjtttt fddd}|j |d}t|}|djYSXdS)z^ Get torch.device from module, assuming that the whole module has one device. rXr/cSsdd|jD}|S)NcSs"g|]\}}t|r||fqSr!r6 is_tensorr0kvr!r!r" s zKModuleUtilsMixin.device..find_tensor_attributes..__dict__itemsrXZtuplesr!r!r"find_tensor_attributessz7ModuleUtilsMixin.device..find_tensor_attributesget_members_fnr N) nextrLr StopIterationr Modulerrstrr_named_membersrrqgenZ first_tupler!r!r"r~s zModuleUtilsMixin.devicecCsfzt|jWStk r`tjtttt fddd}|j |d}t|}|djYSXdS)z\ Get torch.dtype from module, assuming that the whole module has one dtype. rfcSsdd|jD}|S)NcSs"g|]\}}t|r||fqSr!rgrir!r!r"rls zJModuleUtilsMixin.dtype..find_tensor_attributes..rmrpr!r!r"rqsz6ModuleUtilsMixin.dtype..find_tensor_attributesrrr N) rtrLr rur rvrrrwrrxryr!r!r"r s zModuleUtilsMixin.dtype)encoder_attention_maskr/cCs|dkr(|dddddddf}|dkrL|ddddddf}|j|jd}|jtjkrtd|d}n*|jtjkrd|d}ntd|j|S) z"type: torch.Tensor -> torch.TensorNr ?gezU{} not recognized. `dtype` should be set to either `torch.float32` or `torch.float16`)dimtor r6float16float32 ValueErrorformat)rr{encoder_extended_attention_maskr!r!r"invert_attention_masks    z&ModuleUtilsMixin.invert_attention_mask)attention_mask input_shaperr/c Cs|dkr*|dddddddf}n|dkr|jjr|\}}tj||d}|ddddf||d|ddddfk}||j}|dddddddf|ddddddf}q|ddddddf}ntd ||j |j|jd}d|d }|S) aMakes broadcastable attention mask and causal mask so that future and maked tokens are ignored. Arguments: attention_mask: torch.Tensor with 1 indicating tokens to ATTEND to input_shape: tuple, shape of input_ids device: torch.Device, usually self.device Returns: torch.Tensor with dtype of attention_mask.dtype r|Nr})rr zAWrong shape for input_ids (shape {}) or attention_mask (shape {})r~rr) rconfig is_decoderr6r=repeatrr rrshape) rrrrextended_attention_mask batch_size seq_lengthZseq_idsZ causal_maskr!r!r"get_extended_attention_masks&  . 6  z,ModuleUtilsMixin.get_extended_attention_mask) head_masknum_hidden_layersis_attention_chunkedr/cCs6|dk r(|||}|dkr2|d}n dg|}|S)a # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head attention_probs has shape bsz x n_heads x N x N Arguments: head_mask: torch.Tensor or None: has shape [num_heads] or [num_hidden_layers x num_heads] num_hidden_layers: int Returns: Tensor of shape shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] or list with [None] for each layer NTr5)_convert_head_mask_to_5d unsqueeze)rrrrr!r!r" get_head_masks    zModuleUtilsMixin.get_head_maskcCs|dkr<|dddd}||dddd}n"|dkr^|ddd}|dks|td||j|jd}|S)zD-> [num_hidden_layers x batch x num_heads x seq_length x seq_length]r rr5r}zhead_mask.dim != 5, instead r~)rrexpandAssertionErrorrr )rrrr!r!r"rs  z)ModuleUtilsMixin._convert_head_mask_to_5dN)F)F)r&r'r(r)boolintrN staticmethodr[r_rercpropertyrr rrrrrrr!r!r!r"rCIs    ,rCcseZdZdZdZdZeddZfddZedd Z d d Z e j d d dZ ddZddZddZd&eedddZddZd'ej jeeej jdddZddZedd d!Zd"d#Zed$d%ZZS)(PreTrainedModela Base class for all models. :class:`~transformers.PreTrainedModel` takes care of storing the configuration of the models and handles methods for loading/downloading/saving models as well as a few methods common to all models to (i) resize the input embeddings and (ii) prune heads in the self-attention heads. Class attributes (overridden by derived classes): - ``config_class``: a class derived from :class:`~transformers.PretrainedConfig` to use as configuration class for this model architecture. - ``load_tf_weights``: a python ``method`` for loading a TensorFlow checkpoint in a PyTorch model, taking as arguments: - ``model``: an instance of the relevant subclass of :class:`~transformers.PreTrainedModel`, - ``config``: an instance of the relevant subclass of :class:`~transformers.PretrainedConfig`, - ``path``: a path (string) to the TensorFlow checkpoint. - ``base_model_prefix``: a string indicating the attribute associated to the base model in derived classes of the same architecture adding modules on top of the base model. NcCsdttiS)zx Dummy inputs to do a forward pass in the network. Returns: torch.Tensor with dummy inputs input_ids)r6tensorrrr!r!r" dummy_inputsszPreTrainedModel.dummy_inputscs6tt|ts,td|jj|jj||_dS)NzParameter config in `{}(config)` should be an instance of class `PretrainedConfig`. To create a model from a pretrained model use `model = {}.from_pretrained(PRETRAINED_MODEL_NAME)`) rr isinstancerrrr r&r)rrinputsrrr!r"r%s  zPreTrainedModel.__init__cCst||j|Sr)getattrbase_model_prefixrr!r!r" base_model2szPreTrainedModel.base_modelcCs&t||j|}||k r|StdS)z Returns the model's input embeddings. Returns: :obj:`nn.Module`: A torch module mapping vocabulary to hidden states. N)rrget_input_embeddingsNotImplementedError)rrr!r!r"r6sz$PreTrainedModel.get_input_embeddings)valuecCs*t||j|}||k r"||ntdS)z Set model's input embeddings Args: value (:obj:`nn.Module`): A module mapping vocabulary to hidden states. N)rrset_input_embeddingsr)rrrr!r!r"rDs z$PreTrainedModel.set_input_embeddingscCsdS)z Returns the model's output embeddings. Returns: :obj:`nn.Module`: A torch module mapping hidden states to vocabulary. Nr!rr!r!r"get_output_embeddingsRsz%PreTrainedModel.get_output_embeddingscCs$|}|dk r |||dS)z Tie the weights between the input embeddings and the output embeddings. If the `torchscript` flag is set in the configuration, can't handle parameter sharing so we are cloning the weights instead. N)r_tie_or_clone_weightsr)routput_embeddingsr!r!r" tie_weights\szPreTrainedModel.tie_weightscCs|jjrt|j|_n|j|_t|dddk rhtjj |j j d|jj d|j j dfdd|j _ t |drt |dr|j|_dS)zZ Tie or clone module weights depending of whether we are using TorchScript or not biasNrconstant out_featuresnum_embeddings)r torchscriptr Parameterweightclonerr6r padrdatarr^rr)rrZinput_embeddingsr!r!r"rfsz%PreTrainedModel._tie_or_clone_weights)new_num_tokenscCs>t||j|}||}|dkr$|S||j_||_||S)a Resize input token embeddings matrix of the model if new_num_tokens != config.vocab_size. Take care of tying weights embeddings afterwards if the model class has a `tie_weights()` method. Arguments: new_num_tokens: (`optional`) int: New number of tokens in the embedding matrix. Increasing the size will add newly initialized vectors at the end. Reducing the size will remove vectors from the end. If not provided or None: does nothing and just returns a pointer to the input tokens ``torch.nn.Embeddings`` Module of the model. Return: ``torch.nn.Embeddings`` Pointer to the input tokens Embeddings Module of the model N)rr_resize_token_embeddingsr vocab_sizer)rrrZ model_embedsr!r!r"resize_token_embeddingsxs  z'PreTrainedModel.resize_token_embeddingscCs&|}|||}|||Sr)r_get_resized_embeddingsr)rrold_embeddingsnew_embeddingsr!r!r"rs  z(PreTrainedModel._resize_token_embeddings)rrr/cCs|dkr |S|j\}}||kr&|St||}||jj||t||}|jjd|ddf|jjd|ddf<|S)a5 Build a resized Embedding Module from a provided token Embedding Module. Increasing the size will add newly initialized vectors at the end Reducing the size will remove vectors from the end Args: old_embeddings: ``torch.nn.Embedding`` Old embeddings to be resized. new_num_tokens: (`optional`) int New number of tokens in the embedding matrix. Increasing the size will add newly initialized vectors at the end Reducing the size will remove vectors from the end If not provided or None: return the provided token Embedding Module. Return: ``torch.nn.Embedding`` Pointer to the resized Embedding Module or the old Embedding Module if new_num_tokens is None N) rsizer Embeddingrr _init_weightsminr)rrrZold_num_tokensZold_embedding_dimrZnum_tokens_to_copyr!r!r"rs   ,z'PreTrainedModel._get_resized_embeddingscCs.||j|jjr"||jj|dS)z* Initialize and prunes weights if needed. N)applyrr pruned_heads prune_headsrrr!r!r" init_weightss zPreTrainedModel.init_weights)heads_to_prunecCsN|D]4\}}t|jj|gt|B}t||jj|<q|j|dS)aZ Prunes heads of the base model. Arguments: heads_to_prune: dict with keys being selected layer indices (`int`) and associated values being the list of heads to prune in said layer (list of `int`). E.g. {1: [0, 2], 2: [2, 3]} will prune heads 0 and 2 on layer 1 and heads 2 and 3 on layer 2. N)ror8rrgetlistr _prune_heads)rrlayerr+Z union_headsr!r!r"rs zPreTrainedModel.prune_headscCstj|r td|dStj|ddt|dr>|jn|}|j j g|j _ tj |t}t|j ddrddlmm}|r|j ||||n|j |t||td |dS) a  Save a model and its configuration file to a directory, so that it can be re-loaded using the `:func:`~transformers.PreTrainedModel.from_pretrained`` class method. Arguments: save_directory: directory to which to save. z4Provided path ({}) should be a directory, not a fileNT)exist_okrX xla_deviceFrzModel weights saved in {})rSpathisfileloggererrorrmakedirsr^rXr r&r architecturesjoinrrtorch_xla.core.xla_modelcore xla_modelZis_master_ordinalsave_pretrainedsave state_dictr6info)rsave_directoryZ model_to_saveZoutput_model_filexmr!r!r"rs   zPreTrainedModel.save_pretrainedc s(|dd}|dd|dd}|dd}|dd}|dd}|d d} |d d} |d d} |d d } t|ts|dk r|n|} jj| f||d ||| | d|\}}n|}|dk rtj|r|rtjtj |t drtj |t d}np|r>tjtj |t r>tj |t }nBtjtj |t rftj |t }nt dt t t dg|njtj|st|r|}nLtj|dr|std|d|d}nt||rt nt | d}z&t|||| || d}|dkrt WnHt k rZd|d|d|dt dt dt d }t |YnX||krxtd|ntd||nd}|f||}dkr|sztj|ddWntk rtdYnXggg|r^|dr|||dd}nBzd d!lm}|||d d"}Wn"tk rXtd#YnXnXg}g}D]P}d}d$|kr| d$d%}d&|kr| d&d'}|rn|!||!|qnt"||D]\}}||<qt#d(d$dk r_%dGt&j'd*fd+d, d)}|}t(fd-d.D}t)|j*sh|rhj*d/}t)|j*r|st#|j*}||d0|j+j,|j+j,kr|-}fd1d2|-D}.||t/d kr t0d3|d4|j+j,d5d6|j+j,d7|j+j,d8 ntd9|j+j,d:t/d krht0d;|j+j,d<|d=d>n&td?|j+j,d@|dA|j+j,dBt/d krt1dC|j+j,dD |2|3| rdE}||fSt)|dFr$|j4r$d dl5m6m7}|8||4}|9|4|S)HaInstantiate a pretrained pytorch model from a pre-trained model configuration. The model is set in evaluation mode by default using ``model.eval()`` (Dropout modules are deactivated) To train the model, you should first set it back in training mode with ``model.train()`` The warning ``Weights from XXX not initialized from pretrained model`` means that the weights of XXX do not come pre-trained with the rest of the model. It is up to you to train those weights with a downstream fine-tuning task. The warning ``Weights from XXX not used in YYY`` means that the layer XXX is not used by YYY, therefore those weights are discarded. Parameters: pretrained_model_name_or_path: either: - a string with the `shortcut name` of a pre-trained model to load from cache or download, e.g.: ``bert-base-uncased``. - a string with the `identifier name` of a pre-trained model that was user-uploaded to our S3, e.g.: ``dbmdz/bert-base-german-cased``. - a path to a `directory` containing model weights saved using :func:`~transformers.PreTrainedModel.save_pretrained`, e.g.: ``./my_model_directory/``. - a path or url to a `tensorflow index checkpoint file` (e.g. `./tf_model/model.ckpt.index`). In this case, ``from_tf`` should be set to True and a configuration object should be provided as ``config`` argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards. - None if you are both providing the configuration and state dictionary (resp. with keyword arguments ``config`` and ``state_dict``) model_args: (`optional`) Sequence of positional arguments: All remaning positional arguments will be passed to the underlying model's ``__init__`` method config: (`optional`) one of: - an instance of a class derived from :class:`~transformers.PretrainedConfig`, or - a string valid as input to :func:`~transformers.PretrainedConfig.from_pretrained()` Configuration for the model to use instead of an automatically loaded configuation. Configuration can be automatically loaded when: - the model is a model provided by the library (loaded with the ``shortcut-name`` string of a pretrained model), or - the model was saved using :func:`~transformers.PreTrainedModel.save_pretrained` and is reloaded by suppling the save directory. - the model is loaded by suppling a local directory as ``pretrained_model_name_or_path`` and a configuration JSON file named `config.json` is found in the directory. state_dict: (`optional`) dict: an optional state dictionnary for the model to use instead of a state dictionary loaded from saved weights file. This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using :func:`~transformers.PreTrainedModel.save_pretrained` and :func:`~transformers.PreTrainedModel.from_pretrained` is not a simpler option. cache_dir: (`optional`) string: Path to a directory in which a downloaded pre-trained model configuration should be cached if the standard cache should not be used. force_download: (`optional`) boolean, default False: Force to (re-)download the model weights and configuration files and override the cached versions if they exists. resume_download: (`optional`) boolean, default False: Do not delete incompletely recieved file. Attempt to resume the download if such a file exists. proxies: (`optional`) dict, default None: A dictionary of proxy servers to use by protocol or endpoint, e.g.: {'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}. The proxies are used on each request. output_loading_info: (`optional`) boolean: Set to ``True`` to also return a dictionnary containing missing keys, unexpected keys and error messages. kwargs: (`optional`) Remaining dictionary of keyword arguments: Can be used to update the configuration object (after it being loaded) and initiate the model. (e.g. ``output_attention=True``). Behave differently depending on whether a `config` is provided or automatically loaded: - If a configuration is provided with ``config``, ``**kwargs`` will be directly passed to the underlying model's ``__init__`` method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided, ``kwargs`` will be first passed to the configuration class initialization function (:func:`~transformers.PretrainedConfig.from_pretrained`). Each key of ``kwargs`` that corresponds to a configuration attribute will be used to override said attribute with the supplied ``kwargs`` value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model's ``__init__`` function. Examples:: # For example purposes. Not runnable. model = BertModel.from_pretrained('bert-base-uncased') # Download model and configuration from S3 and cache. model = BertModel.from_pretrained('./test/saved_model/') # E.g. model was saved using `save_pretrained('./test/saved_model/')` model = BertModel.from_pretrained('bert-base-uncased', output_attention=True) # Update configuration during loading assert model.config.output_attention == True # Loading from a TF checkpoint file instead of a PyTorch model (slower) config = BertConfig.from_json_file('./tf_model/my_tf_model_config.json') model = BertModel.from_pretrained('./tf_model/my_tf_checkpoint.ckpt.index', from_tf=True, config=config) rNr cache_dirfrom_tfFforce_downloadresume_downloadproxiesoutput_loading_infolocal_files_onlyuse_cdnT)rreturn_unused_kwargsrrrrz.indexzFError no file named {} found in directory {} or `from_tf` set to Falsez_We found a TensorFlow checkpoint at {}, please set from_tf to True to load from this checkpoint)filenamer)rrrrrzCan't load weights for 'z'. Make sure that: - 'zQ' is a correct model identifier listed on 'https://huggingface.co/models' - or 'zD' is the correct path to a directory containing a file named one of z, z. zloading weights file {}z(loading weights file {} from cache at {}cpu) map_locationzUnable to load weights from pytorch checkpoint file. If you tried to load a PyTorch model from a TF 2.0 checkpoint, please set from_tf=True. ir)$load_tf2_checkpoint_in_pytorch_model)Zallow_missing_keyszLoading a TensorFlow model in PyTorch, requires both PyTorch and TensorFlow to be installed. Please see https://pytorch.org/ and https://www.tensorflow.org/install/ for installation instructions.gammarbetar _metadatar)rXc shdkr in|ddi}|||d|jD]"\}}|dk r@|||dq@dS)Nr5T.)r_load_from_state_dict_modulesro)rXprefixlocal_metadatanamechild) error_msgsloadmetadata missing_keysrunexpected_keysr!r"rs z-PreTrainedModel.from_pretrained..loadc3s|]}|jVqdSr) startswithr)r0sclsr!r"r4sz2PreTrainedModel.from_pretrained..r)rcs g|]}|jddqS)rr5)splitr)r0keyrr!r"rlsz3PreTrainedModel.from_pretrained..z(Some weights of the model checkpoint at z! were not used when initializing z: z, - This IS expected if you are initializing z from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPretraining model). - This IS NOT expected if you are initializing z from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).z9All model checkpoint weights were used when initializing z. zSome weights of z3 were not initialized from the model checkpoint at z and are newly initialized: zo You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.zAll the weights of z/ were initialized from the model checkpoint at zf. If your task is similar to the task the model of the ckeckpoint was trained on, you can already use z* for predictions without further training.z*Error(s) in loading state_dict for {}: {}z )rrrr)r):poprr config_classfrom_pretrainedrSrisdirrrrrrEnvironmentErrorrrrrrrrr6r ExceptionOSErrorendswithload_tf_weightsZ transformersrrQrkeysreplaceappendziprcopyrr rvanyr^rr r&rextendr>warning RuntimeErrorrevalrrrrZsend_cpu_data_to_devicer) rpretrained_model_name_or_pathZ model_argsrrrrrrrrrrZ config_path model_kwargsZ archive_fileZresolved_archive_filemsgmodelrZold_keysZnew_keysrnew_keyZold_keyZ start_prefixZ model_to_loadZhas_prefix_moduleZbase_model_state_dictZ)head_model_state_dict_without_base_prefixZ loading_inforr!)rrrrrrrr"rsBH              "    (                    . zPreTrainedModel.from_pretrained)N)N)r&r'r(r)rrrrrrrr rvrrrrrrrrr6rrrrrr classmethodrr*r!r!rr"r s4      & #rcs$eZdZfddZddZZS)Conv1DcsNt||_t||}tjj|ddt||_ tt ||_ dS)z Conv1D layer as defined by Radford et al. for OpenAI GPT (and also used in GPT-2) Basically works like a Linear layer but the weights are transposed g{Gz?)stdN) rrnfr6emptyr initnormal_rrzerosr)rr nxwrr!r"r0s    zConv1D.__init__c CsF|dd|jf}t|j|d|d|j}|j|}|S)Nr5)rr r6addmmrr:r)rrFZsize_outr!r!r"r$;s  zConv1D.forward)r&r'r(rr$r*r!r!rr"r/s rcs*eZdZdZfddZdddZZS)PoolerStartLogitsz9 Compute SQuAD start_logits from sequence hidden states. cstt|jd|_dS)Nr )rrr Linear hidden_sizedenserrrr!r"rEs zPoolerStartLogits.__init__NcCsZ||d}|dk rVt|jtjkrB|d|d|}n|d|d|}|S)z Args: **p_mask**: (`optional`) ``torch.FloatTensor`` of shape `(batch_size, seq_len)` invalid position mask such as query and special symbols (PAD, SEP, CLS) 1.0 means token should be masked. r5Nr ꌠ9Y>)F)r+squeezertrLr r6r)r hidden_statesp_maskrFr!r!r"r$Is zPoolerStartLogits.forward)Nr%r!r!rr"r(Bs r(cs*eZdZdZfddZdddZZS)PoolerEndLogitszX Compute SQuAD end_logits from sequence hidden states and start token hidden state. csRtt|jd|j|_t|_tj|j|j d|_t|jd|_ dS)Nr})epsr ) rrr r)r*dense_0Tanh activation LayerNormlayer_norm_epsdense_1r,rr!r"r^s   zPoolerEndLogits.__init__NcCs|dk s|dk std|dk rh|jdd\}}|ddddfdd|}|d|}|d|d}|tj||gdd}||}||}| | d}|dk rt | j tjkr|d|d|}n|d|d|}|S) a Args: One of ``start_states``, ``start_positions`` should be not None. If both are set, ``start_positions`` overrides ``start_states``. **start_states**: ``torch.LongTensor`` of shape identical to hidden_states hidden states of the first tokens for the labeled span. **start_positions**: ``torch.LongTensor`` of shape ``(batch_size,)`` position of the first token for the labeled span: **p_mask**: (`optional`) ``torch.FloatTensor`` of shape ``(batch_size, seq_len)`` Mask of invalid position such as query and special symbols (PAD, SEP, CLS) 1.0 means token should be masked. N7One of start_states, start_positions should be not Noner5rr r-r.)rrrgatherr4r6catr6r7r9r/rtrLr r)rr0 start_statesstart_positionsr1slenhszrFr!r!r"r$es(   zPoolerEndLogits.forward)NNNr%r!r!rr"r2Zs r2cs*eZdZdZfddZdddZZS)PoolerAnswerClasszT Compute SQuAD 2.0 answer class from classification and start tokens hidden states. csBtt|jd|j|_t|_tj|jddd|_dS)Nr}r Fr) rrr r)r*r4r5r6r9r,rr!r"rs  zPoolerAnswerClass.__init__NcCs|jd}|dk s"|dk s"td|dk rX|ddddfdd|}|d|d}|dk r|ddddfdd|}|d|d}n|dddddf}|tj||gdd}||}| |d}|S)a Args: One of ``start_states``, ``start_positions`` should be not None. If both are set, ``start_positions`` overrides ``start_states``. **start_states**: ``torch.LongTensor`` of shape identical to ``hidden_states``. hidden states of the first tokens for the labeled span. **start_positions**: ``torch.LongTensor`` of shape ``(batch_size,)`` position of the first token for the labeled span. **cls_index**: torch.LongTensor of shape ``(batch_size,)`` position of the CLS token. If None, take the last token. note(Original repo): no dependency on end_feature so that we can obtain one single `cls_logits` for each sample r5Nr:r;r<) rrrr=r/r4r6r>r6r9)rr0r?r@ cls_indexrBZcls_token_staterFr!r!r"r$s$  zPoolerAnswerClass.forward)NNNr%r!r!rr"rCs rCcs*eZdZdZfddZdddZZS) SQuADHeada A SQuAD head inspired by XLNet. Parameters: config (:class:`~transformers.XLNetConfig`): Model configuration class with all the parameters of the model. Inputs: **hidden_states**: ``torch.FloatTensor`` of shape ``(batch_size, seq_len, hidden_size)`` hidden states of sequence tokens **start_positions**: ``torch.LongTensor`` of shape ``(batch_size,)`` position of the first token for the labeled span. **end_positions**: ``torch.LongTensor`` of shape ``(batch_size,)`` position of the last token for the labeled span. **cls_index**: torch.LongTensor of shape ``(batch_size,)`` position of the CLS token. If None, take the last token. **is_impossible**: ``torch.LongTensor`` of shape ``(batch_size,)`` Whether the question has a possible answer in the paragraph or not. **p_mask**: (`optional`) ``torch.FloatTensor`` of shape ``(batch_size, seq_len)`` Mask of invalid position such as query and special symbols (PAD, SEP, CLS) 1.0 means token should be masked. Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs: **loss**: (`optional`, returned if both ``start_positions`` and ``end_positions`` are provided) ``torch.FloatTensor`` of shape ``(1,)``: Classification loss as the sum of start token, end token (and is_impossible if provided) classification losses. **start_top_log_probs**: (`optional`, returned if ``start_positions`` or ``end_positions`` is not provided) ``torch.FloatTensor`` of shape ``(batch_size, config.start_n_top)`` Log probabilities for the top config.start_n_top start token possibilities (beam-search). **start_top_index**: (`optional`, returned if ``start_positions`` or ``end_positions`` is not provided) ``torch.LongTensor`` of shape ``(batch_size, config.start_n_top)`` Indices for the top config.start_n_top start token possibilities (beam-search). **end_top_log_probs**: (`optional`, returned if ``start_positions`` or ``end_positions`` is not provided) ``torch.FloatTensor`` of shape ``(batch_size, config.start_n_top * config.end_n_top)`` Log probabilities for the top ``config.start_n_top * config.end_n_top`` end token possibilities (beam-search). **end_top_index**: (`optional`, returned if ``start_positions`` or ``end_positions`` is not provided) ``torch.LongTensor`` of shape ``(batch_size, config.start_n_top * config.end_n_top)`` Indices for the top ``config.start_n_top * config.end_n_top`` end token possibilities (beam-search). **cls_logits**: (`optional`, returned if ``start_positions`` or ``end_positions`` is not provided) ``torch.FloatTensor`` of shape ``(batch_size,)`` Log probabilities for the ``is_impossible`` label of the answers. cs<t|j|_|j|_t||_t||_t||_ dSr) rr start_n_top end_n_topr( start_logitsr2 end_logitsrC answer_classr,rr!r"rs    zSQuADHead.__init__NcCsd}|j||d}|dk r|dk r||||fD]"} | dk r.| dkr.| dq.|j|||d} t} | ||} | | |} | | d}|dk r|dk r|j|||d}t}|||}||d7}|f|}n|\}}}t j |dd }t j ||j dd \}}|ddd|}t |d |}|dd|dd}|d|}|dk rb|dnd}|j|||d } t j | dd }t j ||jdd \}}|d|j |j}|d|j |j}t d ||}|j|||d }|||||f|}|S)Nr!)r1r r5)r@r1r})r@rEg?r<r;)r?r1z blh,bl->bh)r?rE)rIrsqueeze_rJr rKr BCEWithLogitsLossrFsoftmaxr6topkrGrrr= expand_asrHr:einsum)rr0r@ end_positionsrEZ is_impossibler1outputsrIrFrJloss_fct start_lossend_loss total_loss cls_logitsZ loss_fct_clsZcls_lossbszrArBZstart_log_probsZstart_top_log_probsZstart_top_indexZstart_top_index_expr?Zhidden_states_expandedZ end_log_probsZend_top_log_probsZ end_top_indexr!r!r"r$sX         zSQuADHead.forward)NNNNNr%r!r!rr"rFs( rFcs0eZdZdZedfdd ZdddZZS) SequenceSummarya- Compute a single vector summary of a sequence hidden states according to various possibilities: Args of the config class: summary_type: - 'last' => [default] take the last token hidden state (like XLNet) - 'first' => take the first token hidden state (like Bert) - 'mean' => take the mean of all tokens hidden states - 'cls_index' => supply a Tensor of classification token position (GPT/GPT-2) - 'attn' => Not implemented now, use multi-head attention summary_use_proj: Add a projection after the vector extraction summary_proj_to_labels: If True, the projection outputs to config.num_labels classes (otherwise to hidden_size). Default: False. summary_activation: 'tanh' or another string => add an activation to the output, Other => no activation. Default summary_first_dropout: Add a dropout before the projection and activation summary_last_dropout: Add a dropout after the projection and activation )rcstt|dd|_|jdkr&tt|_t|drv|jrvt|dr`|j r`|j dkr`|j }n|j }t |j ||_t|dd}|rt|nt|_t|_t|dr|jdkrt |j|_t|_t|d r|jdkrt |j|_dS) N summary_typelastattnsummary_use_projsummary_proj_to_labelsrZsummary_activationsummary_first_dropoutsummary_last_dropout)rrrr\rrsummaryr^r_r` num_labelsr*r r)rr6 first_dropoutraDropout last_dropoutrb)rr num_classesactivation_stringrr!r"r=s$   zSequenceSummary.__init__NcCs|jdkr|dddf}n|jdkr8|dddf}n|jdkrP|jdd}n|jd kr|dkrtj|d ddddf|jd dtjd }n2|dd}|d |d| df}| d | d }n|jdkrt | |}||}||}||}|S)a hidden_states: float Tensor in shape [bsz, ..., seq_len, hidden_size], the hidden-states of the last layer. cls_index: [optional] position of the classification token if summary_type == 'cls_index', shape (bsz,) or more generally (bsz, ...) where ... are optional leading dimensions of hidden_states. if summary_type == 'cls_index' and cls_index is None: we take the last token of the sequence as classification token r]Nr5firstrmeanr r<rE.r;r~)r5r^)r\rkr6 full_likerr?rrrrr=r/rrercr6rg)rr0rEoutputr!r!r"r$Zs&    0"     zSequenceSummary.forward)N)r&r'r(r)rrr$r*r!r!rr"r[-sr[cCs||jj}|j||}|jdk rX|dkrF|j}n|j|}t|j}t |||<t j |d|d|jdk d|jj}d|j_ |j |d|j_ |jdk rd|j_ |j |d|j_ |S)z Prune a linear layer (a model parameters) to keep only entries in index. Return the pruned layer as a new layer with requires_grad=True. Used to remove heads. Nr rrDFT)rrr index_selectrdetachrrrr>r r)rEcopy_r;rrArWbnew_sizeZ new_layerr!r!r"prune_linear_layerzs"  ( rucCs||jj}|j||}|dkr<|j}n|j|}t|j}t |||<t |d|d|jj}d|j_ |j | d|j_ d|j_ |j | d|j_ |S)a  Prune a Conv1D layer (a model parameters) to keep only entries in index. A Conv1D work as a Linear layer (see e.g. BERT) but the weights are transposed. Return the pruned layer as a new layer with requires_grad=True. Used to remove heads. rr FT)rrrrnrrorrrr>rrErpr;rqr!r!r"prune_conv1d_layers rvcCs^t|tjr&t|||dkrdn|dSt|trJt|||dkrBdn|dStd|jdS)z Prune a Conv1D or nn.Linear layer (a model parameters) to keep only entries in index. Return the pruned layer as a new layer with requires_grad=True. Used to remove heads. Nrr<r zCan't prune layer of class {}) rr r)rurrvrrr )rrArr!r!r" prune_layers   rw.) chunk_size chunk_dim forward_fnr/cst|dkstd||djtfdd|DsBtdttj}|t|ksrtd|t||dkr|dj|dkstd|dj||dj|tfdd|D}tfd dt |D}t j |d S|S) a This function chunks the `input_tensors` into smaller input tensor parts of size `chunk_size` over the dimension `chunk_dim`. It then applies a layer `forward_fn` to each chunk independently to save memory. If the `forward_fn` is independent across the `chunk_dim` this function will yield the same result as not applying it. Args: chunk_size: int - the chunk size of a chunked tensor. `num_chunks` = `len(input_tensors[0]) / chunk_size` chunk_dim: int - the dimension over which the input_tensors should be chunked forward_fn: fn - the forward fn of the model input_tensors: tuple(torch.Tensor) - the input tensors of `forward_fn` which are chunked Returns: a Tensor with the same shape the foward_fn would have given if applied Examples:: # rename the usual forward() fn to forward_chunk() def forward_chunk(self, hidden_states): hidden_states = self.decoder(hidden_states) return hidden_states # implement a chunked forward function def forward(self, hidden_states): return apply_chunking_to_forward(self.chunk_size_lm_head, self.seq_len_dim, self.forward_chunk, hidden_states) rz${} has to be a tuple/list of tensorsc3s|]}|jkVqdSr)rr0 input_tensor) tensor_shaper!r"r4sz,apply_chunking_to_forward..z-All input tenors have to be of the same shapezJforward_chunk_fn expects {} arguments, but only {} input tensors are givenzHThe dimension to be chunked {} has to be a multiple of the chunk size {}c3s|]}|jdVqdS)r<N)chunkr{)ry num_chunksr!r"r4sc3s|]}|VqdSrr!)r0Zinput_tensors_chunk)rzr!r"r4sr<) r>rrrallinspect signaturerLtuplerr6r>)rxryrz input_tensorsZnum_args_in_forward_chunk_fnZinput_tensors_chunksZ output_chunksr!)ryrzrr}r"apply_chunking_to_forwards:    r)r)r )N)5rloggingrStypingrrrrrr6rrr r torch.nnr r rN activationsrconfiguration_utilsr file_utilsrrrrrrrZgeneration_utilsr getLoggerr&rrrQrvrr8rBrCrrr(r2rCrFr[rurvrwrr!r!r!r"sV    $    A*//uM