PyTorch XLM
This commit is contained in:
@@ -1,75 +1,88 @@
|
|||||||
XLM
|
XLM
|
||||||
----------------------------------------------------
|
----------------------------------------------------
|
||||||
|
|
||||||
``XLMConfig``
|
The XLM model was proposed in `Cross-lingual Language Model Pretraining`_
|
||||||
|
by Guillaume Lample*, Alexis Conneau*. It's a transformer pre-trained using one of the following objectives:
|
||||||
|
|
||||||
|
- a causal language modeling (CLM) objective (next token prediction),
|
||||||
|
- a masked language modeling (MLM) objective (Bert-like), or
|
||||||
|
- a Translation Language Modeling (TLM) object (extension of Bert's MLM to multiple language inputs)
|
||||||
|
|
||||||
|
Original code can be found `here <https://github.com/facebookresearch/XLM>`_.
|
||||||
|
|
||||||
|
This model is a PyTorch `torch.nn.Module`_ sub-class. Use it as a regular PyTorch Module and
|
||||||
|
refer to the PyTorch documentation for all matter related to general usage and behavior.
|
||||||
|
|
||||||
|
|
||||||
|
XLMConfig
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
.. autoclass:: transformers.XLMConfig
|
.. autoclass:: transformers.XLMConfig
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
``XLMTokenizer``
|
XLMTokenizer
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
.. autoclass:: transformers.XLMTokenizer
|
.. autoclass:: transformers.XLMTokenizer
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
``XLMModel``
|
XLMModel
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
.. autoclass:: transformers.XLMModel
|
.. autoclass:: transformers.XLMModel
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
|
|
||||||
``XLMWithLMHeadModel``
|
XLMWithLMHeadModel
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
.. autoclass:: transformers.XLMWithLMHeadModel
|
.. autoclass:: transformers.XLMWithLMHeadModel
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
|
|
||||||
``XLMForSequenceClassification``
|
XLMForSequenceClassification
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
.. autoclass:: transformers.XLMForSequenceClassification
|
.. autoclass:: transformers.XLMForSequenceClassification
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
|
|
||||||
``XLMForQuestionAnsweringSimple``
|
XLMForQuestionAnsweringSimple
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
.. autoclass:: transformers.XLMForQuestionAnsweringSimple
|
.. autoclass:: transformers.XLMForQuestionAnsweringSimple
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
|
|
||||||
``XLMForQuestionAnswering``
|
XLMForQuestionAnswering
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
.. autoclass:: transformers.XLMForQuestionAnswering
|
.. autoclass:: transformers.XLMForQuestionAnswering
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
|
|
||||||
``TFXLMModel``
|
TFXLMModel
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
.. autoclass:: transformers.TFXLMModel
|
.. autoclass:: transformers.TFXLMModel
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
|
|
||||||
``TFXLMWithLMHeadModel``
|
TFXLMWithLMHeadModel
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
.. autoclass:: transformers.TFXLMWithLMHeadModel
|
.. autoclass:: transformers.TFXLMWithLMHeadModel
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
|
|
||||||
``TFXLMForSequenceClassification``
|
TFXLMForSequenceClassification
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
.. autoclass:: transformers.TFXLMForSequenceClassification
|
.. autoclass:: transformers.TFXLMForSequenceClassification
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
|
|
||||||
``TFXLMForQuestionAnsweringSimple``
|
TFXLMForQuestionAnsweringSimple
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
.. autoclass:: transformers.TFXLMForQuestionAnsweringSimple
|
.. autoclass:: transformers.TFXLMForQuestionAnsweringSimple
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ from torch.nn import CrossEntropyLoss, MSELoss
|
|||||||
from torch.nn import functional as F
|
from torch.nn import functional as F
|
||||||
|
|
||||||
from .configuration_xlm import XLMConfig
|
from .configuration_xlm import XLMConfig
|
||||||
from .file_utils import add_start_docstrings
|
from .file_utils import add_start_docstrings, add_start_docstrings_to_callable
|
||||||
from .modeling_utils import PreTrainedModel, SequenceSummary, SQuADHead, prune_linear_layer
|
from .modeling_utils import PreTrainedModel, SequenceSummary, SQuADHead, prune_linear_layer
|
||||||
|
|
||||||
|
|
||||||
@@ -249,27 +249,7 @@ class XLMPreTrainedModel(PreTrainedModel):
|
|||||||
module.weight.data.fill_(1.0)
|
module.weight.data.fill_(1.0)
|
||||||
|
|
||||||
|
|
||||||
XLM_START_DOCSTRING = r""" The XLM model was proposed in
|
XLM_START_DOCSTRING = r"""
|
||||||
`Cross-lingual Language Model Pretraining`_
|
|
||||||
by Guillaume Lample*, Alexis Conneau*. It's a transformer pre-trained using one of the following objectives:
|
|
||||||
|
|
||||||
- a causal language modeling (CLM) objective (next token prediction),
|
|
||||||
- a masked language modeling (MLM) objective (Bert-like), or
|
|
||||||
- a Translation Language Modeling (TLM) object (extension of Bert's MLM to multiple language inputs)
|
|
||||||
|
|
||||||
Original code can be found `here`_.
|
|
||||||
|
|
||||||
This model is a PyTorch `torch.nn.Module`_ sub-class. Use it as a regular PyTorch Module and
|
|
||||||
refer to the PyTorch documentation for all matter related to general usage and behavior.
|
|
||||||
|
|
||||||
.. _`Cross-lingual Language Model Pretraining`:
|
|
||||||
https://arxiv.org/abs/1901.07291
|
|
||||||
|
|
||||||
.. _`torch.nn.Module`:
|
|
||||||
https://pytorch.org/docs/stable/nn.html#module
|
|
||||||
|
|
||||||
.. _`here`:
|
|
||||||
https://github.com/facebookresearch/XLM
|
|
||||||
|
|
||||||
Parameters:
|
Parameters:
|
||||||
config (:class:`~transformers.XLMConfig`): Model configuration class with all the parameters of the model.
|
config (:class:`~transformers.XLMConfig`): Model configuration class with all the parameters of the model.
|
||||||
@@ -278,48 +258,55 @@ XLM_START_DOCSTRING = r""" The XLM model was proposed in
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
XLM_INPUTS_DOCSTRING = r"""
|
XLM_INPUTS_DOCSTRING = r"""
|
||||||
Inputs:
|
Args:
|
||||||
**input_ids**: ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:
|
input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`):
|
||||||
Indices of input sequence tokens in the vocabulary.
|
Indices of input sequence tokens in the vocabulary.
|
||||||
|
|
||||||
XLM is a model with absolute position embeddings so it's usually advised to pad the inputs on
|
Indices can be obtained using :class:`transformers.BertTokenizer`.
|
||||||
the right rather than the left.
|
|
||||||
|
|
||||||
Indices can be obtained using :class:`transformers.XLMTokenizer`.
|
|
||||||
See :func:`transformers.PreTrainedTokenizer.encode` and
|
See :func:`transformers.PreTrainedTokenizer.encode` and
|
||||||
:func:`transformers.PreTrainedTokenizer.convert_tokens_to_ids` for details.
|
:func:`transformers.PreTrainedTokenizer.encode_plus` for details.
|
||||||
**attention_mask**: (`optional`) ``torch.FloatTensor`` of shape ``(batch_size, sequence_length)``:
|
|
||||||
|
`What are input IDs? <../glossary.html#input-ids>`__
|
||||||
|
attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):
|
||||||
Mask to avoid performing attention on padding token indices.
|
Mask to avoid performing attention on padding token indices.
|
||||||
Mask values selected in ``[0, 1]``:
|
Mask values selected in ``[0, 1]``:
|
||||||
``1`` for tokens that are NOT MASKED, ``0`` for MASKED tokens.
|
``1`` for tokens that are NOT MASKED, ``0`` for MASKED tokens.
|
||||||
**langs**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:
|
|
||||||
|
`What are attention masks? <../glossary.html#attention-mask>`__
|
||||||
|
langs (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):
|
||||||
A parallel sequence of tokens to be used to indicate the language of each token in the input.
|
A parallel sequence of tokens to be used to indicate the language of each token in the input.
|
||||||
Indices are languages ids which can be obtained from the language names by using two conversion mappings
|
Indices are languages ids which can be obtained from the language names by using two conversion mappings
|
||||||
provided in the configuration of the model (only provided for multilingual models).
|
provided in the configuration of the model (only provided for multilingual models).
|
||||||
More precisely, the `language name -> language id` mapping is in `model.config.lang2id` (dict str -> int) and
|
More precisely, the `language name -> language id` mapping is in `model.config.lang2id` (dict str -> int) and
|
||||||
the `language id -> language name` mapping is `model.config.id2lang` (dict int -> str).
|
the `language id -> language name` mapping is `model.config.id2lang` (dict int -> str).
|
||||||
**token_type_ids**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:
|
|
||||||
A parallel sequence of tokens (can be used to indicate various portions of the inputs).
|
See usage examples detailed in the `multilingual documentation <https://huggingface.co/transformers/multilingual.html>`__.
|
||||||
The embeddings from these tokens will be summed with the respective token embeddings.
|
token_type_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):
|
||||||
Indices are selected in the vocabulary (unlike BERT which has a specific vocabulary for segment indices).
|
Segment token indices to indicate first and second portions of the inputs.
|
||||||
**position_ids**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:
|
Indices are selected in ``[0, 1]``: ``0`` corresponds to a `sentence A` token, ``1``
|
||||||
|
corresponds to a `sentence B` token
|
||||||
|
|
||||||
|
`What are token type IDs? <../glossary.html#token-type-ids>`_
|
||||||
|
position_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):
|
||||||
Indices of positions of each input sequence tokens in the position embeddings.
|
Indices of positions of each input sequence tokens in the position embeddings.
|
||||||
Selected in the range ``[0, config.max_position_embeddings - 1]``.
|
Selected in the range ``[0, config.max_position_embeddings - 1]``.
|
||||||
**lengths**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size,)``:
|
|
||||||
|
`What are position IDs? <../glossary.html#position-ids>`_
|
||||||
|
lengths (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`, defaults to :obj:`None`):
|
||||||
Length of each sentence that can be used to avoid performing attention on padding token indices.
|
Length of each sentence that can be used to avoid performing attention on padding token indices.
|
||||||
You can also use `attention_mask` for the same result (see above), kept here for compatbility.
|
You can also use `attention_mask` for the same result (see above), kept here for compatbility.
|
||||||
Indices selected in ``[0, ..., input_ids.size(-1)]``:
|
Indices selected in ``[0, ..., input_ids.size(-1)]``:
|
||||||
**cache**:
|
cache (:obj:`Dict[str, torch.FloatTensor]`, `optional`, defaults to :obj:`None`):
|
||||||
dictionary with ``torch.FloatTensor`` that contains pre-computed
|
dictionary with ``torch.FloatTensor`` that contains pre-computed
|
||||||
hidden-states (key and values in the attention blocks) as computed by the model
|
hidden-states (key and values in the attention blocks) as computed by the model
|
||||||
(see `cache` output below). Can be used to speed up sequential decoding.
|
(see `cache` output below). Can be used to speed up sequential decoding.
|
||||||
The dictionary object will be modified in-place during the forward pass to add newly computed hidden-states.
|
The dictionary object will be modified in-place during the forward pass to add newly computed hidden-states.
|
||||||
**head_mask**: (`optional`) ``torch.FloatTensor`` of shape ``(num_heads,)`` or ``(num_layers, num_heads)``:
|
head_mask (:obj:`torch.FloatTensor` of shape :obj:`(num_heads,)` or :obj:`(num_layers, num_heads)`, `optional`, defaults to :obj:`None`):
|
||||||
Mask to nullify selected heads of the self-attention modules.
|
Mask to nullify selected heads of the self-attention modules.
|
||||||
Mask values selected in ``[0, 1]``:
|
Mask values selected in ``[0, 1]``:
|
||||||
``1`` indicates the head is **not masked**, ``0`` indicates the head is **masked**.
|
:obj:`1` indicates the head is **not masked**, :obj:`0` indicates the head is **masked**.
|
||||||
**inputs_embeds**: (`optional`) ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, embedding_dim)``:
|
input_embeds (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`, defaults to :obj:`None`):
|
||||||
Optionally, instead of passing ``input_ids`` you can choose to directly pass an embedded representation.
|
Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded representation.
|
||||||
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
||||||
than the model's internal embedding lookup matrix.
|
than the model's internal embedding lookup matrix.
|
||||||
"""
|
"""
|
||||||
@@ -328,30 +315,8 @@ XLM_INPUTS_DOCSTRING = r"""
|
|||||||
@add_start_docstrings(
|
@add_start_docstrings(
|
||||||
"The bare XLM Model transformer outputting raw hidden-states without any specific head on top.",
|
"The bare XLM Model transformer outputting raw hidden-states without any specific head on top.",
|
||||||
XLM_START_DOCSTRING,
|
XLM_START_DOCSTRING,
|
||||||
XLM_INPUTS_DOCSTRING,
|
|
||||||
)
|
)
|
||||||
class XLMModel(XLMPreTrainedModel):
|
class XLMModel(XLMPreTrainedModel):
|
||||||
r"""
|
|
||||||
Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:
|
|
||||||
**last_hidden_state**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, hidden_size)``
|
|
||||||
Sequence of hidden-states at the last layer of the model.
|
|
||||||
**hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)
|
|
||||||
list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)
|
|
||||||
of shape ``(batch_size, sequence_length, hidden_size)``:
|
|
||||||
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
|
||||||
**attentions**: (`optional`, returned when ``config.output_attentions=True``)
|
|
||||||
list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:
|
|
||||||
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
|
|
||||||
|
|
||||||
Examples::
|
|
||||||
|
|
||||||
tokenizer = XLMTokenizer.from_pretrained('xlm-mlm-en-2048')
|
|
||||||
model = XLMModel.from_pretrained('xlm-mlm-en-2048')
|
|
||||||
input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0) # Batch size 1
|
|
||||||
outputs = model(input_ids)
|
|
||||||
last_hidden_states = outputs[0] # The last hidden-state is the first element of the output tuple
|
|
||||||
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, config): # , dico, is_encoder, with_output):
|
def __init__(self, config): # , dico, is_encoder, with_output):
|
||||||
super().__init__(config)
|
super().__init__(config)
|
||||||
@@ -437,6 +402,7 @@ class XLMModel(XLMPreTrainedModel):
|
|||||||
for layer, heads in heads_to_prune.items():
|
for layer, heads in heads_to_prune.items():
|
||||||
self.attentions[layer].prune_heads(heads)
|
self.attentions[layer].prune_heads(heads)
|
||||||
|
|
||||||
|
@add_start_docstrings_to_callable(XLM_INPUTS_DOCSTRING)
|
||||||
def forward(
|
def forward(
|
||||||
self,
|
self,
|
||||||
input_ids=None,
|
input_ids=None,
|
||||||
@@ -448,7 +414,33 @@ class XLMModel(XLMPreTrainedModel):
|
|||||||
cache=None,
|
cache=None,
|
||||||
head_mask=None,
|
head_mask=None,
|
||||||
inputs_embeds=None,
|
inputs_embeds=None,
|
||||||
): # removed: src_enc=None, src_len=None
|
):
|
||||||
|
r"""
|
||||||
|
Return:
|
||||||
|
:obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:obj:`~transformers.GPT2Config`) and inputs:
|
||||||
|
last_hidden_state (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`):
|
||||||
|
Sequence of hidden-states at the output of the last layer of the model.
|
||||||
|
hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_hidden_states=True``):
|
||||||
|
Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
|
||||||
|
of shape :obj:`(batch_size, sequence_length, hidden_size)`.
|
||||||
|
|
||||||
|
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
||||||
|
attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_attentions=True``):
|
||||||
|
Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
|
||||||
|
:obj:`(batch_size, num_heads, sequence_length, sequence_length)`.
|
||||||
|
|
||||||
|
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
||||||
|
heads.
|
||||||
|
|
||||||
|
Examples::
|
||||||
|
|
||||||
|
tokenizer = XLMTokenizer.from_pretrained('xlm-mlm-en-2048')
|
||||||
|
model = XLMModel.from_pretrained('xlm-mlm-en-2048')
|
||||||
|
input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0) # Batch size 1
|
||||||
|
outputs = model(input_ids)
|
||||||
|
last_hidden_states = outputs[0] # The last hidden-state is the first element of the output tuple
|
||||||
|
|
||||||
|
"""
|
||||||
if input_ids is not None:
|
if input_ids is not None:
|
||||||
bs, slen = input_ids.size()
|
bs, slen = input_ids.size()
|
||||||
else:
|
else:
|
||||||
@@ -626,39 +618,8 @@ class XLMPredLayer(nn.Module):
|
|||||||
"""The XLM Model transformer with a language modeling head on top
|
"""The XLM Model transformer with a language modeling head on top
|
||||||
(linear layer with weights tied to the input embeddings). """,
|
(linear layer with weights tied to the input embeddings). """,
|
||||||
XLM_START_DOCSTRING,
|
XLM_START_DOCSTRING,
|
||||||
XLM_INPUTS_DOCSTRING,
|
|
||||||
)
|
)
|
||||||
class XLMWithLMHeadModel(XLMPreTrainedModel):
|
class XLMWithLMHeadModel(XLMPreTrainedModel):
|
||||||
r"""
|
|
||||||
**labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:
|
|
||||||
Labels for language modeling.
|
|
||||||
Note that the labels **are shifted** inside the model, i.e. you can set ``lm_labels = input_ids``
|
|
||||||
Indices are selected in ``[-1, 0, ..., config.vocab_size]``
|
|
||||||
All labels set to ``-100`` are ignored (masked), the loss is only
|
|
||||||
computed for labels in ``[0, ..., config.vocab_size]``
|
|
||||||
|
|
||||||
Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:
|
|
||||||
**loss**: (`optional`, returned when ``labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:
|
|
||||||
Language modeling loss.
|
|
||||||
**prediction_scores**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, config.vocab_size)``
|
|
||||||
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
|
||||||
**hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)
|
|
||||||
list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)
|
|
||||||
of shape ``(batch_size, sequence_length, hidden_size)``:
|
|
||||||
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
|
||||||
**attentions**: (`optional`, returned when ``config.output_attentions=True``)
|
|
||||||
list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:
|
|
||||||
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
|
|
||||||
|
|
||||||
Examples::
|
|
||||||
|
|
||||||
tokenizer = XLMTokenizer.from_pretrained('xlm-mlm-en-2048')
|
|
||||||
model = XLMWithLMHeadModel.from_pretrained('xlm-mlm-en-2048')
|
|
||||||
input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0) # Batch size 1
|
|
||||||
outputs = model(input_ids)
|
|
||||||
last_hidden_states = outputs[0] # The last hidden-state is the first element of the output tuple
|
|
||||||
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, config):
|
def __init__(self, config):
|
||||||
super().__init__(config)
|
super().__init__(config)
|
||||||
@@ -683,6 +644,7 @@ class XLMWithLMHeadModel(XLMPreTrainedModel):
|
|||||||
langs = None
|
langs = None
|
||||||
return {"input_ids": input_ids, "langs": langs}
|
return {"input_ids": input_ids, "langs": langs}
|
||||||
|
|
||||||
|
@add_start_docstrings_to_callable(XLM_INPUTS_DOCSTRING)
|
||||||
def forward(
|
def forward(
|
||||||
self,
|
self,
|
||||||
input_ids=None,
|
input_ids=None,
|
||||||
@@ -696,6 +658,41 @@ class XLMWithLMHeadModel(XLMPreTrainedModel):
|
|||||||
inputs_embeds=None,
|
inputs_embeds=None,
|
||||||
labels=None,
|
labels=None,
|
||||||
):
|
):
|
||||||
|
r"""
|
||||||
|
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):
|
||||||
|
Labels for language modeling.
|
||||||
|
Note that the labels **are shifted** inside the model, i.e. you can set ``lm_labels = input_ids``
|
||||||
|
Indices are selected in ``[-100, 0, ..., config.vocab_size]``
|
||||||
|
All labels set to ``-100`` are ignored (masked), the loss is only
|
||||||
|
computed for labels in ``[0, ..., config.vocab_size]``
|
||||||
|
|
||||||
|
Return:
|
||||||
|
:obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:obj:`~transformers.GPT2Config`) and inputs:
|
||||||
|
loss (:obj:`torch.FloatTensor` of shape `(1,)`, `optional`, returned when ``labels`` is provided)
|
||||||
|
Language modeling loss.
|
||||||
|
prediction_scores (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, config.vocab_size)`):
|
||||||
|
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
||||||
|
hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_hidden_states=True``):
|
||||||
|
Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
|
||||||
|
of shape :obj:`(batch_size, sequence_length, hidden_size)`.
|
||||||
|
|
||||||
|
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
||||||
|
attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_attentions=True``):
|
||||||
|
Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
|
||||||
|
:obj:`(batch_size, num_heads, sequence_length, sequence_length)`.
|
||||||
|
|
||||||
|
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
||||||
|
heads.
|
||||||
|
|
||||||
|
Examples::
|
||||||
|
|
||||||
|
tokenizer = XLMTokenizer.from_pretrained('xlm-mlm-en-2048')
|
||||||
|
model = XLMWithLMHeadModel.from_pretrained('xlm-mlm-en-2048')
|
||||||
|
input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0) # Batch size 1
|
||||||
|
outputs = model(input_ids)
|
||||||
|
last_hidden_states = outputs[0] # The last hidden-state is the first element of the output tuple
|
||||||
|
|
||||||
|
"""
|
||||||
transformer_outputs = self.transformer(
|
transformer_outputs = self.transformer(
|
||||||
input_ids,
|
input_ids,
|
||||||
attention_mask=attention_mask,
|
attention_mask=attention_mask,
|
||||||
@@ -719,39 +716,8 @@ class XLMWithLMHeadModel(XLMPreTrainedModel):
|
|||||||
"""XLM Model with a sequence classification/regression head on top (a linear layer on top of
|
"""XLM Model with a sequence classification/regression head on top (a linear layer on top of
|
||||||
the pooled output) e.g. for GLUE tasks. """,
|
the pooled output) e.g. for GLUE tasks. """,
|
||||||
XLM_START_DOCSTRING,
|
XLM_START_DOCSTRING,
|
||||||
XLM_INPUTS_DOCSTRING,
|
|
||||||
)
|
)
|
||||||
class XLMForSequenceClassification(XLMPreTrainedModel):
|
class XLMForSequenceClassification(XLMPreTrainedModel):
|
||||||
r"""
|
|
||||||
**labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size,)``:
|
|
||||||
Labels for computing the sequence classification/regression loss.
|
|
||||||
Indices should be in ``[0, ..., config.num_labels - 1]``.
|
|
||||||
If ``config.num_labels == 1`` a regression loss is computed (Mean-Square loss),
|
|
||||||
If ``config.num_labels > 1`` a classification loss is computed (Cross-Entropy).
|
|
||||||
|
|
||||||
Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:
|
|
||||||
**loss**: (`optional`, returned when ``labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:
|
|
||||||
Classification (or regression if config.num_labels==1) loss.
|
|
||||||
**logits**: ``torch.FloatTensor`` of shape ``(batch_size, config.num_labels)``
|
|
||||||
Classification (or regression if config.num_labels==1) scores (before SoftMax).
|
|
||||||
**hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)
|
|
||||||
list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)
|
|
||||||
of shape ``(batch_size, sequence_length, hidden_size)``:
|
|
||||||
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
|
||||||
**attentions**: (`optional`, returned when ``config.output_attentions=True``)
|
|
||||||
list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:
|
|
||||||
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
|
|
||||||
|
|
||||||
Examples::
|
|
||||||
|
|
||||||
tokenizer = XLMTokenizer.from_pretrained('xlm-mlm-en-2048')
|
|
||||||
model = XLMForSequenceClassification.from_pretrained('xlm-mlm-en-2048')
|
|
||||||
input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0) # Batch size 1
|
|
||||||
labels = torch.tensor([1]).unsqueeze(0) # Batch size 1
|
|
||||||
outputs = model(input_ids, labels=labels)
|
|
||||||
loss, logits = outputs[:2]
|
|
||||||
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, config):
|
def __init__(self, config):
|
||||||
super().__init__(config)
|
super().__init__(config)
|
||||||
@@ -762,6 +728,7 @@ class XLMForSequenceClassification(XLMPreTrainedModel):
|
|||||||
|
|
||||||
self.init_weights()
|
self.init_weights()
|
||||||
|
|
||||||
|
@add_start_docstrings_to_callable(XLM_INPUTS_DOCSTRING)
|
||||||
def forward(
|
def forward(
|
||||||
self,
|
self,
|
||||||
input_ids=None,
|
input_ids=None,
|
||||||
@@ -775,6 +742,41 @@ class XLMForSequenceClassification(XLMPreTrainedModel):
|
|||||||
inputs_embeds=None,
|
inputs_embeds=None,
|
||||||
labels=None,
|
labels=None,
|
||||||
):
|
):
|
||||||
|
r"""
|
||||||
|
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`, defaults to :obj:`None`):
|
||||||
|
Labels for computing the sequence classification/regression loss.
|
||||||
|
Indices should be in :obj:`[0, ..., config.num_labels - 1]`.
|
||||||
|
If :obj:`config.num_labels == 1` a regression loss is computed (Mean-Square loss),
|
||||||
|
If :obj:`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
:obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.BertConfig`) and inputs:
|
||||||
|
loss (:obj:`torch.FloatTensor` of shape :obj:`(1,)`, `optional`, returned when :obj:`label` is provided):
|
||||||
|
Classification (or regression if config.num_labels==1) loss.
|
||||||
|
logits (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, config.num_labels)`):
|
||||||
|
Classification (or regression if config.num_labels==1) scores (before SoftMax).
|
||||||
|
hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_hidden_states=True``):
|
||||||
|
Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
|
||||||
|
of shape :obj:`(batch_size, sequence_length, hidden_size)`.
|
||||||
|
|
||||||
|
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
||||||
|
attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_attentions=True``):
|
||||||
|
Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
|
||||||
|
:obj:`(batch_size, num_heads, sequence_length, sequence_length)`.
|
||||||
|
|
||||||
|
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
||||||
|
heads.
|
||||||
|
|
||||||
|
Examples::
|
||||||
|
|
||||||
|
tokenizer = XLMTokenizer.from_pretrained('xlm-mlm-en-2048')
|
||||||
|
model = XLMForSequenceClassification.from_pretrained('xlm-mlm-en-2048')
|
||||||
|
input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0) # Batch size 1
|
||||||
|
labels = torch.tensor([1]).unsqueeze(0) # Batch size 1
|
||||||
|
outputs = model(input_ids, labels=labels)
|
||||||
|
loss, logits = outputs[:2]
|
||||||
|
|
||||||
|
"""
|
||||||
transformer_outputs = self.transformer(
|
transformer_outputs = self.transformer(
|
||||||
input_ids,
|
input_ids,
|
||||||
attention_mask=attention_mask,
|
attention_mask=attention_mask,
|
||||||
@@ -809,51 +811,8 @@ class XLMForSequenceClassification(XLMPreTrainedModel):
|
|||||||
"""XLM Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear layers on top of
|
"""XLM Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear layers on top of
|
||||||
the hidden-states output to compute `span start logits` and `span end logits`). """,
|
the hidden-states output to compute `span start logits` and `span end logits`). """,
|
||||||
XLM_START_DOCSTRING,
|
XLM_START_DOCSTRING,
|
||||||
XLM_INPUTS_DOCSTRING,
|
|
||||||
)
|
)
|
||||||
class XLMForQuestionAnsweringSimple(XLMPreTrainedModel):
|
class XLMForQuestionAnsweringSimple(XLMPreTrainedModel):
|
||||||
r"""
|
|
||||||
**start_positions**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size,)``:
|
|
||||||
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
|
||||||
Positions are clamped to the length of the sequence (`sequence_length`).
|
|
||||||
Position outside of the sequence are not taken into account for computing the loss.
|
|
||||||
**end_positions**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size,)``:
|
|
||||||
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
|
||||||
Positions are clamped to the length of the sequence (`sequence_length`).
|
|
||||||
Position outside of the sequence are not taken into account for computing the loss.
|
|
||||||
**is_impossible**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size,)``:
|
|
||||||
Labels whether a question has an answer or no answer (SQuAD 2.0)
|
|
||||||
**cls_index**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size,)``:
|
|
||||||
Labels for position (index) of the classification token to use as input for computing plausibility of the answer.
|
|
||||||
**p_mask**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:
|
|
||||||
Optional mask of tokens which can't be in answers (e.g. [CLS], [PAD], ...)
|
|
||||||
|
|
||||||
Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:
|
|
||||||
**loss**: (`optional`, returned when ``labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:
|
|
||||||
Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.
|
|
||||||
**start_scores**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length,)``
|
|
||||||
Span-start scores (before SoftMax).
|
|
||||||
**end_scores**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length,)``
|
|
||||||
Span-end scores (before SoftMax).
|
|
||||||
**hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)
|
|
||||||
list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)
|
|
||||||
of shape ``(batch_size, sequence_length, hidden_size)``:
|
|
||||||
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
|
||||||
**attentions**: (`optional`, returned when ``config.output_attentions=True``)
|
|
||||||
list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:
|
|
||||||
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
|
|
||||||
|
|
||||||
Examples::
|
|
||||||
|
|
||||||
tokenizer = XLMTokenizer.from_pretrained('xlm-mlm-en-2048')
|
|
||||||
model = XLMForQuestionAnsweringSimple.from_pretrained('xlm-mlm-en-2048')
|
|
||||||
input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0) # Batch size 1
|
|
||||||
start_positions = torch.tensor([1])
|
|
||||||
end_positions = torch.tensor([3])
|
|
||||||
outputs = model(input_ids, start_positions=start_positions, end_positions=end_positions)
|
|
||||||
loss, start_scores, end_scores = outputs[:2]
|
|
||||||
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, config):
|
def __init__(self, config):
|
||||||
super().__init__(config)
|
super().__init__(config)
|
||||||
@@ -863,6 +822,7 @@ class XLMForQuestionAnsweringSimple(XLMPreTrainedModel):
|
|||||||
|
|
||||||
self.init_weights()
|
self.init_weights()
|
||||||
|
|
||||||
|
@add_start_docstrings_to_callable(XLM_INPUTS_DOCSTRING)
|
||||||
def forward(
|
def forward(
|
||||||
self,
|
self,
|
||||||
input_ids=None,
|
input_ids=None,
|
||||||
@@ -877,6 +837,47 @@ class XLMForQuestionAnsweringSimple(XLMPreTrainedModel):
|
|||||||
start_positions=None,
|
start_positions=None,
|
||||||
end_positions=None,
|
end_positions=None,
|
||||||
):
|
):
|
||||||
|
r"""
|
||||||
|
start_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`, defaults to :obj:`None`):
|
||||||
|
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
||||||
|
Positions are clamped to the length of the sequence (`sequence_length`).
|
||||||
|
Position outside of the sequence are not taken into account for computing the loss.
|
||||||
|
end_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`, defaults to :obj:`None`):
|
||||||
|
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
||||||
|
Positions are clamped to the length of the sequence (`sequence_length`).
|
||||||
|
Position outside of the sequence are not taken into account for computing the loss.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
:obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (config) and inputs:
|
||||||
|
loss (:obj:`torch.FloatTensor` of shape :obj:`(1,)`, `optional`, returned when :obj:`labels` is provided):
|
||||||
|
Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.
|
||||||
|
start_scores (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length,)`):
|
||||||
|
Span-start scores (before SoftMax).
|
||||||
|
end_scores (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length,)`):
|
||||||
|
Span-end scores (before SoftMax).
|
||||||
|
hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_hidden_states=True``):
|
||||||
|
Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
|
||||||
|
of shape :obj:`(batch_size, sequence_length, hidden_size)`.
|
||||||
|
|
||||||
|
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
||||||
|
attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_attentions=True``):
|
||||||
|
Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
|
||||||
|
:obj:`(batch_size, num_heads, sequence_length, sequence_length)`.
|
||||||
|
|
||||||
|
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
||||||
|
heads.
|
||||||
|
|
||||||
|
Examples::
|
||||||
|
|
||||||
|
tokenizer = XLMTokenizer.from_pretrained('xlm-mlm-en-2048')
|
||||||
|
model = XLMForQuestionAnsweringSimple.from_pretrained('xlm-mlm-en-2048')
|
||||||
|
input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0) # Batch size 1
|
||||||
|
start_positions = torch.tensor([1])
|
||||||
|
end_positions = torch.tensor([3])
|
||||||
|
outputs = model(input_ids, start_positions=start_positions, end_positions=end_positions)
|
||||||
|
loss, start_scores, end_scores = outputs[:2]
|
||||||
|
|
||||||
|
"""
|
||||||
transformer_outputs = self.transformer(
|
transformer_outputs = self.transformer(
|
||||||
input_ids,
|
input_ids,
|
||||||
attention_mask=attention_mask,
|
attention_mask=attention_mask,
|
||||||
@@ -926,51 +927,8 @@ class XLMForQuestionAnsweringSimple(XLMPreTrainedModel):
|
|||||||
"""XLM Model with a beam-search span classification head on top for extractive question-answering tasks like SQuAD (a linear layers on top of
|
"""XLM Model with a beam-search span classification head on top for extractive question-answering tasks like SQuAD (a linear layers on top of
|
||||||
the hidden-states output to compute `span start logits` and `span end logits`). """,
|
the hidden-states output to compute `span start logits` and `span end logits`). """,
|
||||||
XLM_START_DOCSTRING,
|
XLM_START_DOCSTRING,
|
||||||
XLM_INPUTS_DOCSTRING,
|
|
||||||
)
|
)
|
||||||
class XLMForQuestionAnswering(XLMPreTrainedModel):
|
class XLMForQuestionAnswering(XLMPreTrainedModel):
|
||||||
r"""
|
|
||||||
**start_positions**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size,)``:
|
|
||||||
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
|
||||||
Positions are clamped to the length of the sequence (`sequence_length`).
|
|
||||||
Position outside of the sequence are not taken into account for computing the loss.
|
|
||||||
**end_positions**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size,)``:
|
|
||||||
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
|
||||||
Positions are clamped to the length of the sequence (`sequence_length`).
|
|
||||||
Position outside of the sequence are not taken into account for computing the loss.
|
|
||||||
**is_impossible**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size,)``:
|
|
||||||
Labels whether a question has an answer or no answer (SQuAD 2.0)
|
|
||||||
**cls_index**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size,)``:
|
|
||||||
Labels for position (index) of the classification token to use as input for computing plausibility of the answer.
|
|
||||||
**p_mask**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:
|
|
||||||
Optional mask of tokens which can't be in answers (e.g. [CLS], [PAD], ...)
|
|
||||||
|
|
||||||
Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:
|
|
||||||
**loss**: (`optional`, returned when ``labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:
|
|
||||||
Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.
|
|
||||||
**start_scores**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length,)``
|
|
||||||
Span-start scores (before SoftMax).
|
|
||||||
**end_scores**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length,)``
|
|
||||||
Span-end scores (before SoftMax).
|
|
||||||
**hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)
|
|
||||||
list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)
|
|
||||||
of shape ``(batch_size, sequence_length, hidden_size)``:
|
|
||||||
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
|
||||||
**attentions**: (`optional`, returned when ``config.output_attentions=True``)
|
|
||||||
list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:
|
|
||||||
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
|
|
||||||
|
|
||||||
Examples::
|
|
||||||
|
|
||||||
tokenizer = XLMTokenizer.from_pretrained('xlm-mlm-en-2048')
|
|
||||||
model = XLMForQuestionAnswering.from_pretrained('xlm-mlm-en-2048')
|
|
||||||
input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0) # Batch size 1
|
|
||||||
start_positions = torch.tensor([1])
|
|
||||||
end_positions = torch.tensor([3])
|
|
||||||
outputs = model(input_ids, start_positions=start_positions, end_positions=end_positions)
|
|
||||||
loss, start_scores, end_scores = outputs[:2]
|
|
||||||
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, config):
|
def __init__(self, config):
|
||||||
super().__init__(config)
|
super().__init__(config)
|
||||||
@@ -980,6 +938,7 @@ class XLMForQuestionAnswering(XLMPreTrainedModel):
|
|||||||
|
|
||||||
self.init_weights()
|
self.init_weights()
|
||||||
|
|
||||||
|
@add_start_docstrings_to_callable(XLM_INPUTS_DOCSTRING)
|
||||||
def forward(
|
def forward(
|
||||||
self,
|
self,
|
||||||
input_ids=None,
|
input_ids=None,
|
||||||
@@ -997,6 +956,60 @@ class XLMForQuestionAnswering(XLMPreTrainedModel):
|
|||||||
cls_index=None,
|
cls_index=None,
|
||||||
p_mask=None,
|
p_mask=None,
|
||||||
):
|
):
|
||||||
|
r"""
|
||||||
|
start_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`, defaults to :obj:`None`):
|
||||||
|
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
||||||
|
Positions are clamped to the length of the sequence (`sequence_length`).
|
||||||
|
Position outside of the sequence are not taken into account for computing the loss.
|
||||||
|
end_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`, defaults to :obj:`None`):
|
||||||
|
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
||||||
|
Positions are clamped to the length of the sequence (`sequence_length`).
|
||||||
|
Position outside of the sequence are not taken into account for computing the loss.
|
||||||
|
is_impossible (``torch.LongTensor`` of shape ``(batch_size,)``, `optional`, defaults to :obj:`None`):
|
||||||
|
Labels whether a question has an answer or no answer (SQuAD 2.0)
|
||||||
|
cls_index (``torch.LongTensor`` of shape ``(batch_size,)``, `optional`, defaults to :obj:`None`):
|
||||||
|
Labels for position (index) of the classification token to use as input for computing plausibility of the answer.
|
||||||
|
p_mask (``torch.FloatTensor`` of shape ``(batch_size, sequence_length)``, `optional`, defaults to :obj:`None`):
|
||||||
|
Optional mask of tokens which can't be in answers (e.g. [CLS], [PAD], ...).
|
||||||
|
1.0 means token should be masked. 0.0 mean token is not masked.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
:obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (config) and inputs:
|
||||||
|
loss (:obj:`torch.FloatTensor` of shape :obj:`(1,)`, `optional`, returned if both :obj:`start_positions` and :obj:`end_positions` are provided):
|
||||||
|
Classification loss as the sum of start token, end token (and is_impossible if provided) classification losses.
|
||||||
|
start_top_log_probs (``torch.FloatTensor`` of shape ``(batch_size, config.start_n_top)``, `optional`, returned if ``start_positions`` or ``end_positions`` is not provided):
|
||||||
|
Log probabilities for the top config.start_n_top start token possibilities (beam-search).
|
||||||
|
start_top_index (``torch.LongTensor`` of shape ``(batch_size, config.start_n_top)``, `optional`, returned if ``start_positions`` or ``end_positions`` is not provided):
|
||||||
|
Indices for the top config.start_n_top start token possibilities (beam-search).
|
||||||
|
end_top_log_probs (``torch.FloatTensor`` of shape ``(batch_size, config.start_n_top * config.end_n_top)``, `optional`, returned if ``start_positions`` or ``end_positions`` is not provided):
|
||||||
|
Log probabilities for the top ``config.start_n_top * config.end_n_top`` end token possibilities (beam-search).
|
||||||
|
end_top_index (``torch.LongTensor`` of shape ``(batch_size, config.start_n_top * config.end_n_top)``, `optional`, returned if ``start_positions`` or ``end_positions`` is not provided):
|
||||||
|
Indices for the top ``config.start_n_top * config.end_n_top`` end token possibilities (beam-search).
|
||||||
|
cls_logits (``torch.FloatTensor`` of shape ``(batch_size,)``, `optional`, returned if ``start_positions`` or ``end_positions`` is not provided):
|
||||||
|
Log probabilities for the ``is_impossible`` label of the answers.
|
||||||
|
hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_hidden_states=True``):
|
||||||
|
Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
|
||||||
|
of shape :obj:`(batch_size, sequence_length, hidden_size)`.
|
||||||
|
|
||||||
|
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
||||||
|
attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_attentions=True``):
|
||||||
|
Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
|
||||||
|
:obj:`(batch_size, num_heads, sequence_length, sequence_length)`.
|
||||||
|
|
||||||
|
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
||||||
|
heads.
|
||||||
|
|
||||||
|
Examples::
|
||||||
|
|
||||||
|
tokenizer = XLMTokenizer.from_pretrained('xlm-mlm-en-2048')
|
||||||
|
model = XLMForQuestionAnswering.from_pretrained('xlm-mlm-en-2048')
|
||||||
|
input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0) # Batch size 1
|
||||||
|
start_positions = torch.tensor([1])
|
||||||
|
end_positions = torch.tensor([3])
|
||||||
|
outputs = model(input_ids, start_positions=start_positions, end_positions=end_positions)
|
||||||
|
loss, start_scores, end_scores = outputs[:2]
|
||||||
|
|
||||||
|
"""
|
||||||
transformer_outputs = self.transformer(
|
transformer_outputs = self.transformer(
|
||||||
input_ids,
|
input_ids,
|
||||||
attention_mask=attention_mask,
|
attention_mask=attention_mask,
|
||||||
|
|||||||
Reference in New Issue
Block a user