DistilBERT¶
Overview¶
The DistilBERT model was proposed in the blog post Smaller, faster, cheaper, lighter: Introducing DistilBERT, a distilled version of BERT, and the paper DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter. DistilBERT is a small, fast, cheap and light Transformer model trained by distilling Bert base. It has 40% less parameters than bert-base-uncased, runs 60% faster while preserving over 95% of Bert’s performances as measured on the GLUE language understanding benchmark.
The abstract from the paper is the following:
As Transfer Learning from large-scale pre-trained models becomes more prevalent in Natural Language Processing (NLP), operating these large models in on-the-edge and/or under constrained computational training or inference budgets remains challenging. In this work, we propose a method to pre-train a smaller general-purpose language representation model, called DistilBERT, which can then be fine-tuned with good performances on a wide range of tasks like its larger counterparts. While most prior work investigated the use of distillation for building task-specific models, we leverage knowledge distillation during the pre-training phase and show that it is possible to reduce the size of a BERT model by 40%, while retaining 97% of its language understanding capabilities and being 60% faster. To leverage the inductive biases learned by larger models during pre-training, we introduce a triple loss combining language modeling, distillation and cosine-distance losses. Our smaller, faster and lighter model is cheaper to pre-train and we demonstrate its capabilities for on-device computations in a proof-of-concept experiment and a comparative on-device study.
Tips:
DistilBert doesn’t have token_type_ids, you don’t need to indicate which token belongs to which segment. Just separate your segments with the separation token tokenizer.sep_token (or [SEP])
DistilBert doesn’t have options to select the input positions (position_ids input). This could be added if necessary though, just let’s us know if you need this option.
The original code can be found here.
DistilBertConfig¶
-
class
transformers.
DistilBertConfig
(vocab_size=30522, max_position_embeddings=512, sinusoidal_pos_embds=False, n_layers=6, n_heads=12, dim=768, hidden_dim=3072, dropout=0.1, attention_dropout=0.1, activation='gelu', initializer_range=0.02, qa_dropout=0.1, seq_classif_dropout=0.2, pad_token_id=0, **kwargs)[source]¶ This is the configuration class to store the configuration of a
DistilBertModel
. It is used to instantiate a DistilBERT model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the DistilBERT distilbert-base-uncased architecture.Configuration objects inherit from
PretrainedConfig
and can be used to control the model outputs. Read the documentation fromPretrainedConfig
for more information.- Parameters
vocab_size (
int
, optional, defaults to 30522) – Vocabulary size of the DistilBERT model. Defines the different tokens that can be represented by the inputs_ids passed to the forward method ofBertModel
.max_position_embeddings (
int
, optional, defaults to 512) – 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).sinusoidal_pos_embds (
boolean
, optional, defaults toFalse
) – Whether to use sinusoidal positional embeddings.n_layers (
int
, optional, defaults to 6) – Number of hidden layers in the Transformer encoder.n_heads (
int
, optional, defaults to 12) – Number of attention heads for each attention layer in the Transformer encoder.dim (
int
, optional, defaults to 768) – Dimensionality of the encoder layers and the pooler layer.hidden_dim (
int
, optional, defaults to 3072) – The size of the “intermediate” (i.e., feed-forward) layer in the Transformer encoder.dropout (
float
, optional, defaults to 0.1) – The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.attention_dropout (
float
, optional, defaults to 0.1) – The dropout ratio for the attention probabilities.activation (
str
orfunction
, optional, defaults to “gelu”) – The non-linear activation function (function or string) in the encoder and pooler. If string, “gelu”, “relu”, “swish” and “gelu_new” are supported.initializer_range (
float
, optional, defaults to 0.02) – The standard deviation of the truncated_normal_initializer for initializing all weight matrices.qa_dropout (
float
, optional, defaults to 0.1) – The dropout probabilities used in the question answering modelDistilBertForQuestionAnswering
.seq_classif_dropout (
float
, optional, defaults to 0.2) – The dropout probabilities used in the sequence classification and the multiple choice modelDistilBertForSequenceClassification
.
Example:
>>> from transformers import DistilBertModel, DistilBertConfig >>> # Initializing a DistilBERT configuration >>> configuration = DistilBertConfig() >>> # Initializing a model from the configuration >>> model = DistilBertModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config
DistilBertTokenizer¶
-
class
transformers.
DistilBertTokenizer
(vocab_file, do_lower_case=True, do_basic_tokenize=True, never_split=None, unk_token='[UNK]', sep_token='[SEP]', pad_token='[PAD]', cls_token='[CLS]', mask_token='[MASK]', tokenize_chinese_chars=True, strip_accents=None, **kwargs)[source]¶ Constructs a DistilBertTokenizer.
BertTokenizer
and runs end-to-end tokenization: punctuation splitting + wordpiece.Refer to superclass
BertTokenizer
for usage examples and documentation concerning parameters.
DistilBertTokenizerFast¶
-
class
transformers.
DistilBertTokenizerFast
(vocab_file, do_lower_case=True, unk_token='[UNK]', sep_token='[SEP]', pad_token='[PAD]', cls_token='[CLS]', mask_token='[MASK]', clean_text=True, tokenize_chinese_chars=True, strip_accents=None, wordpieces_prefix='##', **kwargs)[source]¶ Constructs a “Fast” DistilBertTokenizer (backed by HuggingFace’s tokenizers library).
DistilBertTokenizerFast
is identical toBertTokenizerFast
and runs end-to-end tokenization: punctuation splitting + wordpiece.Refer to superclass
BertTokenizerFast
for usage examples and documentation concerning parameters.
DistilBertModel¶
-
class
transformers.
DistilBertModel
(config)[source]¶ The bare DistilBERT encoder/transformer outputting raw hidden-states without any specific head on top.
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.
- Parameters
config (
DistilBertConfig
) – Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()
method to load the model weights.
-
forward
(input_ids=None, attention_mask=None, head_mask=None, inputs_embeds=None, output_attentions=None, output_hidden_states=None, return_dict=None)[source]¶ The
DistilBertModel
forward method, overrides the__call__()
special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.- Parameters
input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) –Indices of input sequence tokens in the vocabulary.
Indices can be obtained using
transformers.DistilBertTokenizer
. Seetransformers.PreTrainedTokenizer.encode()
andtransformers.PreTrainedTokenizer.__call__()
for details.attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
, optional, defaults toNone
) –Mask to avoid performing attention on padding token indices. Mask values selected in
[0, 1]
:1
for tokens that are NOT MASKED,0
for MASKED tokens.head_mask (
torch.FloatTensor
of shape(num_heads,)
or(num_layers, num_heads)
, optional, defaults toNone
) – Mask to nullify selected heads of the self-attention modules. Mask values selected in[0, 1]
:1
indicates the head is not masked,0
indicates the head is masked.inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional, defaults toNone
) – Optionally, instead of passinginput_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.output_attentions (
bool
, optional, defaults toNone
) – If set toTrue
, the attentions tensors of all attention layers are returned. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional, defaults toNone
) – If set toTrue
, the hidden states of all layers are returned. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional, defaults toNone
) – If set toTrue
, the model will return aModelOutput
instead of a plain tuple.
Example:
>>> from transformers import DistilBertTokenizer, DistilBertModel >>> import torch >>> tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased') >>> model = DistilBertModel.from_pretrained('distilbert-base-uncased', return_dict=True) >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") >>> outputs = model(**inputs) >>> last_hidden_states = outputs.last_hidden_state
- Returns
A
BaseModelOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftorch.FloatTensor
comprising various elements depending on the configuration (DistilBertConfig
) and inputs.last_hidden_state (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
) – Sequence of hidden-states at the output of the last layer of the model.hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) – Tuple oftorch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) 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 (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) – Tuple oftorch.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.
- Return type
BaseModelOutput
ortuple(torch.FloatTensor)
Example:
>>> from transformers import DistilBertTokenizer, DistilBertModel >>> import torch >>> tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased') >>> model = DistilBertModel.from_pretrained('distilbert-base-uncased', return_dict=True) >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") >>> outputs = model(**inputs) >>> last_hidden_states = outputs.last_hidden_state
DistilBertForMaskedLM¶
-
class
transformers.
DistilBertForMaskedLM
(config)[source]¶ DistilBert Model with a masked language modeling head on top.
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.
- Parameters
config (
DistilBertConfig
) – Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()
method to load the model weights.
-
forward
(input_ids=None, attention_mask=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None, **kwargs)[source]¶ The
DistilBertForMaskedLM
forward method, overrides the__call__()
special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.- Parameters
input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) –Indices of input sequence tokens in the vocabulary.
Indices can be obtained using
transformers.DistilBertTokenizer
. Seetransformers.PreTrainedTokenizer.encode()
andtransformers.PreTrainedTokenizer.__call__()
for details.attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
, optional, defaults toNone
) –Mask to avoid performing attention on padding token indices. Mask values selected in
[0, 1]
:1
for tokens that are NOT MASKED,0
for MASKED tokens.head_mask (
torch.FloatTensor
of shape(num_heads,)
or(num_layers, num_heads)
, optional, defaults toNone
) – Mask to nullify selected heads of the self-attention modules. Mask values selected in[0, 1]
:1
indicates the head is not masked,0
indicates the head is masked.inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional, defaults toNone
) – Optionally, instead of passinginput_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.output_attentions (
bool
, optional, defaults toNone
) – If set toTrue
, the attentions tensors of all attention layers are returned. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional, defaults toNone
) – If set toTrue
, the hidden states of all layers are returned. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional, defaults toNone
) – If set toTrue
, the model will return aModelOutput
instead of a plain tuple.labels (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional, defaults toNone
) – Labels for computing the masked language modeling loss. Indices should be in[-100, 0, ..., config.vocab_size]
(seeinput_ids
docstring) Tokens with indices set to-100
are ignored (masked), the loss is only computed for the tokens with labels in[0, ..., config.vocab_size]
kwargs (
Dict[str, any]
, optional, defaults to {}) – Used to hide legacy arguments that have been deprecated.
- Returns
A
MaskedLMOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftorch.FloatTensor
comprising various elements depending on the configuration (DistilBertConfig
) and inputs.loss (
torch.FloatTensor
of shape(1,)
, optional, returned whenlabels
is provided) – Masked languaged modeling (MLM) loss.logits (
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 (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) – Tuple oftorch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) 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 (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) – Tuple oftorch.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.
- Return type
MaskedLMOutput
ortuple(torch.FloatTensor)
Example:
>>> from transformers import DistilBertTokenizer, DistilBertForMaskedLM >>> import torch >>> tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased') >>> model = DistilBertForMaskedLM.from_pretrained('distilbert-base-uncased', return_dict=True) >>> input_ids = tokenizer("Hello, my dog is cute", return_tensors="pt")["input_ids"] >>> outputs = model(input_ids, labels=input_ids) >>> loss = outputs.loss >>> prediction_logits = outputs.logits
DistilBertForSequenceClassification¶
-
class
transformers.
DistilBertForSequenceClassification
(config)[source]¶ DistilBert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks.
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.
- Parameters
config (
DistilBertConfig
) – Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()
method to load the model weights.
-
forward
(input_ids=None, attention_mask=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None)[source]¶ The
DistilBertForSequenceClassification
forward method, overrides the__call__()
special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.- Parameters
input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) –Indices of input sequence tokens in the vocabulary.
Indices can be obtained using
transformers.DistilBertTokenizer
. Seetransformers.PreTrainedTokenizer.encode()
andtransformers.PreTrainedTokenizer.__call__()
for details.attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
, optional, defaults toNone
) –Mask to avoid performing attention on padding token indices. Mask values selected in
[0, 1]
:1
for tokens that are NOT MASKED,0
for MASKED tokens.head_mask (
torch.FloatTensor
of shape(num_heads,)
or(num_layers, num_heads)
, optional, defaults toNone
) – Mask to nullify selected heads of the self-attention modules. Mask values selected in[0, 1]
:1
indicates the head is not masked,0
indicates the head is masked.inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional, defaults toNone
) – Optionally, instead of passinginput_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.output_attentions (
bool
, optional, defaults toNone
) – If set toTrue
, the attentions tensors of all attention layers are returned. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional, defaults toNone
) – If set toTrue
, the hidden states of all layers are returned. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional, defaults toNone
) – If set toTrue
, the model will return aModelOutput
instead of a plain tuple.labels (
torch.LongTensor
of shape(batch_size,)
, optional, defaults toNone
) – Labels for computing the sequence classification/regression loss. Indices should be in[0, ..., config.num_labels - 1]
. Ifconfig.num_labels == 1
a regression loss is computed (Mean-Square loss), Ifconfig.num_labels > 1
a classification loss is computed (Cross-Entropy).
- Returns
A
SequenceClassifierOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftorch.FloatTensor
comprising various elements depending on the configuration (DistilBertConfig
) and inputs.loss (
torch.FloatTensor
of shape(1,)
, optional, returned whenlabels
is provided) – 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 (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) – Tuple oftorch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) 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 (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) – Tuple oftorch.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.
- Return type
SequenceClassifierOutput
ortuple(torch.FloatTensor)
Example:
>>> from transformers import DistilBertTokenizer, DistilBertForSequenceClassification >>> import torch >>> tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased') >>> model = DistilBertForSequenceClassification.from_pretrained('distilbert-base-uncased', return_dict=True) >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") >>> labels = torch.tensor([1]).unsqueeze(0) # Batch size 1 >>> outputs = model(**inputs, labels=labels) >>> loss = outputs.loss >>> logits = outputs.logits
DistilBertForMultipleChoice¶
-
class
transformers.
DistilBertForMultipleChoice
(config)[source]¶ DistilBert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a softmax) e.g. for RocStories/SWAG tasks.
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.
- Parameters
config (
DistilBertConfig
) – Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()
method to load the model weights.
-
forward
(input_ids=None, attention_mask=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None)[source]¶ The
DistilBertForMultipleChoice
forward method, overrides the__call__()
special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.- Parameters
input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) –Indices of input sequence tokens in the vocabulary.
Indices can be obtained using
transformers.DistilBertTokenizer
. Seetransformers.PreTrainedTokenizer.encode()
andtransformers.PreTrainedTokenizer.__call__()
for details.attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
, optional, defaults toNone
) –Mask to avoid performing attention on padding token indices. Mask values selected in
[0, 1]
:1
for tokens that are NOT MASKED,0
for MASKED tokens.head_mask (
torch.FloatTensor
of shape(num_heads,)
or(num_layers, num_heads)
, optional, defaults toNone
) – Mask to nullify selected heads of the self-attention modules. Mask values selected in[0, 1]
:1
indicates the head is not masked,0
indicates the head is masked.inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional, defaults toNone
) – Optionally, instead of passinginput_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.output_attentions (
bool
, optional, defaults toNone
) – If set toTrue
, the attentions tensors of all attention layers are returned. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional, defaults toNone
) – If set toTrue
, the hidden states of all layers are returned. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional, defaults toNone
) –If set to
True
, the model will return aModelOutput
instead of a plain tuple.- labels (
torch.LongTensor
of shape(batch_size,)
, optional, defaults toNone
): Labels for computing the multiple choice classification loss. Indices should be in
[0, ..., num_choices-1]
where num_choices is the size of the second dimension of the input tensors. (see input_ids above)
- labels (
- Returns
A
MultipleChoiceModelOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftorch.FloatTensor
comprising various elements depending on the configuration (DistilBertConfig
) and inputs.loss (
torch.FloatTensor
of shape (1,), optional, returned whenlabels
is provided) – Classification loss.logits (
torch.FloatTensor
of shape(batch_size, num_choices)
) – num_choices is the second dimension of the input tensors. (see input_ids above).Classification scores (before SoftMax).
hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) – Tuple oftorch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) 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 (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) – Tuple oftorch.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:
>>> from transformers import DistilBertTokenizer, DistilBertForMultipleChoice >>> import torch >>> tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-cased') >>> model = DistilBertForMultipleChoice.from_pretrained('distilbert-base-cased', return_dict=True) >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced." >>> choice0 = "It is eaten with a fork and a knife." >>> choice1 = "It is eaten while held in the hand." >>> labels = torch.tensor(0).unsqueeze(0) # choice0 is correct (according to Wikipedia ;)), batch size 1 >>> encoding = tokenizer([[prompt, choice0], [prompt, choice1]], return_tensors='pt', padding=True) >>> outputs = model(**{k: v.unsqueeze(0) for k,v in encoding.items()}, labels=labels) # batch size is 1 >>> # the linear classifier still needs to be trained >>> loss = outputs.loss >>> logits = outputs.logits
- Return type
MultipleChoiceModelOutput
ortuple(torch.FloatTensor)
DistilBertForTokenClassification¶
-
class
transformers.
DistilBertForTokenClassification
(config)[source]¶ DistilBert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks.
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.
- Parameters
config (
DistilBertConfig
) – Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()
method to load the model weights.
-
forward
(input_ids=None, attention_mask=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None)[source]¶ The
DistilBertForTokenClassification
forward method, overrides the__call__()
special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.- Parameters
input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) –Indices of input sequence tokens in the vocabulary.
Indices can be obtained using
transformers.DistilBertTokenizer
. Seetransformers.PreTrainedTokenizer.encode()
andtransformers.PreTrainedTokenizer.__call__()
for details.attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
, optional, defaults toNone
) –Mask to avoid performing attention on padding token indices. Mask values selected in
[0, 1]
:1
for tokens that are NOT MASKED,0
for MASKED tokens.head_mask (
torch.FloatTensor
of shape(num_heads,)
or(num_layers, num_heads)
, optional, defaults toNone
) – Mask to nullify selected heads of the self-attention modules. Mask values selected in[0, 1]
:1
indicates the head is not masked,0
indicates the head is masked.inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional, defaults toNone
) – Optionally, instead of passinginput_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.output_attentions (
bool
, optional, defaults toNone
) – If set toTrue
, the attentions tensors of all attention layers are returned. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional, defaults toNone
) – If set toTrue
, the hidden states of all layers are returned. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional, defaults toNone
) – If set toTrue
, the model will return aModelOutput
instead of a plain tuple.labels (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional, defaults toNone
) – Labels for computing the token classification loss. Indices should be in[0, ..., config.num_labels - 1]
.
- Returns
A
TokenClassifierOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftorch.FloatTensor
comprising various elements depending on the configuration (DistilBertConfig
) and inputs.loss (
torch.FloatTensor
of shape(1,)
, optional, returned whenlabels
is provided) – Classification loss.logits (
torch.FloatTensor
of shape(batch_size, sequence_length, config.num_labels)
) – Classification scores (before SoftMax).hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) – Tuple oftorch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) 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 (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) – Tuple oftorch.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.
- Return type
TokenClassifierOutput
ortuple(torch.FloatTensor)
Example:
>>> from transformers import DistilBertTokenizer, DistilBertForTokenClassification >>> import torch >>> tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased') >>> model = DistilBertForTokenClassification.from_pretrained('distilbert-base-uncased', return_dict=True) >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") >>> labels = torch.tensor([1] * inputs["input_ids"].size(1)).unsqueeze(0) # Batch size 1 >>> outputs = model(**inputs, labels=labels) >>> loss = outputs.loss >>> logits = outputs.logits
DistilBertForQuestionAnswering¶
-
class
transformers.
DistilBertForQuestionAnswering
(config)[source]¶ DistilBert 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).
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.
- Parameters
config (
DistilBertConfig
) – Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()
method to load the model weights.
-
forward
(input_ids=None, attention_mask=None, head_mask=None, inputs_embeds=None, start_positions=None, end_positions=None, output_attentions=None, output_hidden_states=None, return_dict=None)[source]¶ The
DistilBertForQuestionAnswering
forward method, overrides the__call__()
special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.- Parameters
input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) –Indices of input sequence tokens in the vocabulary.
Indices can be obtained using
transformers.DistilBertTokenizer
. Seetransformers.PreTrainedTokenizer.encode()
andtransformers.PreTrainedTokenizer.__call__()
for details.attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
, optional, defaults toNone
) –Mask to avoid performing attention on padding token indices. Mask values selected in
[0, 1]
:1
for tokens that are NOT MASKED,0
for MASKED tokens.head_mask (
torch.FloatTensor
of shape(num_heads,)
or(num_layers, num_heads)
, optional, defaults toNone
) – Mask to nullify selected heads of the self-attention modules. Mask values selected in[0, 1]
:1
indicates the head is not masked,0
indicates the head is masked.inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional, defaults toNone
) – Optionally, instead of passinginput_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.output_attentions (
bool
, optional, defaults toNone
) – If set toTrue
, the attentions tensors of all attention layers are returned. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional, defaults toNone
) – If set toTrue
, the hidden states of all layers are returned. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional, defaults toNone
) – If set toTrue
, the model will return aModelOutput
instead of a plain tuple.start_positions (
torch.LongTensor
of shape(batch_size,)
, optional, defaults toNone
) – 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 (
torch.LongTensor
of shape(batch_size,)
, optional, defaults toNone
) – 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
A
QuestionAnsweringModelOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftorch.FloatTensor
comprising various elements depending on the configuration (DistilBertConfig
) and inputs.loss (
torch.FloatTensor
of shape(1,)
, optional, returned whenlabels
is provided) – Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.start_logits (
torch.FloatTensor
of shape(batch_size, sequence_length,)
) – Span-start scores (before SoftMax).end_logits (
torch.FloatTensor
of shape(batch_size, sequence_length,)
) – Span-end scores (before SoftMax).hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) – Tuple oftorch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) 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 (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) – Tuple oftorch.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.
- Return type
QuestionAnsweringModelOutput
ortuple(torch.FloatTensor)
Example:
>>> from transformers import DistilBertTokenizer, DistilBertForQuestionAnswering >>> import torch >>> tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased') >>> model = DistilBertForQuestionAnswering.from_pretrained('distilbert-base-uncased', return_dict=True) >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") >>> start_positions = torch.tensor([1]) >>> end_positions = torch.tensor([3]) >>> outputs = model(**inputs, start_positions=start_positions, end_positions=end_positions) >>> loss = outputs.loss >>> start_scores = outputs.start_scores >>> end_scores = outputs.end_scores
TFDistilBertModel¶
-
class
transformers.
TFDistilBertModel
(*args, **kwargs)[source]¶ The bare DistilBERT encoder/transformer outputing raw hidden-states without any specific head on top. This model is a tf.keras.Model sub-class. Use it as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and behavior.
Note
TF 2.0 models accepts two formats as inputs:
having all inputs as keyword arguments (like PyTorch models), or
having all inputs as a list, tuple or dict in the first positional arguments.
This second option is useful when using
tf.keras.Model.fit()
method which currently requires having all the tensors in the first argument of the model call function:model(inputs)
.If you choose this second option, there are three possibilities you can use to gather all the input Tensors in the first positional argument :
a single Tensor with input_ids only and nothing else:
model(inputs_ids)
a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
model([input_ids, attention_mask])
a dictionary with one or several input Tensors associated to the input names given in the docstring:
model({'input_ids': input_ids})
- Parameters
config (
DistilBertConfig
) – Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()
method to load the model weights.
-
call
(inputs, **kwargs)[source]¶ The
TFDistilBertModel
forward method, overrides the__call__()
special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.- Parameters
input_ids (
Numpy array
ortf.Tensor
of shape(batch_size, sequence_length)
) –Indices of input sequence tokens in the vocabulary.
Indices can be obtained using
transformers.BertTokenizer
. Seetransformers.PreTrainedTokenizer.encode()
andtransformers.PreTrainedTokenizer.__call__()
for details.attention_mask (
Numpy array
ortf.Tensor
of shape(batch_size, sequence_length)
, optional, defaults toNone
) –Mask to avoid performing attention on padding token indices. Mask values selected in
[0, 1]
:1
for tokens that are NOT MASKED,0
for MASKED tokens.head_mask (
Numpy array
ortf.Tensor
of shape(num_heads,)
or(num_layers, num_heads)
, optional, defaults toNone
) – Mask to nullify selected heads of the self-attention modules. Mask values selected in[0, 1]
:1
indicates the head is not masked,0
indicates the head is masked.inputs_embeds (
Numpy array
ortf.Tensor
of shape(batch_size, sequence_length, embedding_dim)
, optional, defaults toNone
) – Optionally, instead of passinginput_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.training (
boolean
, optional, defaults toFalse
) – Whether to activate dropout modules (if set toTrue
) during training or to de-activate them (if set toFalse
) for evaluation.output_attentions (
bool
, optional, defaults toNone
) – If set toTrue
, the attentions tensors of all attention layers are returned. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional, defaults toNone
) – If set toTrue
, the hidden states of all layers are returned. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional, defaults toNone
) – If set toTrue
, the model will return aModelOutput
instead of a plain tuple.
- Returns
A
TFBaseModelOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftf.Tensor
comprising various elements depending on the configuration (DistilBertConfig
) and inputs.last_hidden_state (
tf.Tensor
of shape(batch_size, sequence_length, hidden_size)
) – Sequence of hidden-states at the output of the last layer of the model.hidden_states (
tuple(tf.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) – Tuple oftf.Tensor
(one for the output of the embeddings + one for the output of each layer) 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 (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) – Tuple oftf.Tensor
(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.
- Return type
TFBaseModelOutput
ortuple(tf.Tensor)
Example:
>>> from transformers import DistilBertTokenizer, TFDistilBertModel >>> import tensorflow as tf >>> tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased') >>> model = TFDistilBertModel.from_pretrained('distilbert-base-uncased') >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf") >>> outputs = model(inputs) >>> last_hidden_states = outputs[0] # The last hidden-state is the first element of the output tuple
TFDistilBertForMaskedLM¶
-
class
transformers.
TFDistilBertForMaskedLM
(*args, **kwargs)[source]¶ DistilBert Model with a masked language modeling head on top. This model is a tf.keras.Model sub-class. Use it as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and behavior.
Note
TF 2.0 models accepts two formats as inputs:
having all inputs as keyword arguments (like PyTorch models), or
having all inputs as a list, tuple or dict in the first positional arguments.
This second option is useful when using
tf.keras.Model.fit()
method which currently requires having all the tensors in the first argument of the model call function:model(inputs)
.If you choose this second option, there are three possibilities you can use to gather all the input Tensors in the first positional argument :
a single Tensor with input_ids only and nothing else:
model(inputs_ids)
a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
model([input_ids, attention_mask])
a dictionary with one or several input Tensors associated to the input names given in the docstring:
model({'input_ids': input_ids})
- Parameters
config (
DistilBertConfig
) – Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()
method to load the model weights.
-
call
(inputs=None, attention_mask=None, head_mask=None, inputs_embeds=None, output_attentions=None, output_hidden_states=None, return_dict=None, labels=None, training=False)[source]¶ The
TFDistilBertForMaskedLM
forward method, overrides the__call__()
special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.- Parameters
input_ids (
Numpy array
ortf.Tensor
of shape(batch_size, sequence_length)
) –Indices of input sequence tokens in the vocabulary.
Indices can be obtained using
transformers.BertTokenizer
. Seetransformers.PreTrainedTokenizer.encode()
andtransformers.PreTrainedTokenizer.__call__()
for details.attention_mask (
Numpy array
ortf.Tensor
of shape(batch_size, sequence_length)
, optional, defaults toNone
) –Mask to avoid performing attention on padding token indices. Mask values selected in
[0, 1]
:1
for tokens that are NOT MASKED,0
for MASKED tokens.head_mask (
Numpy array
ortf.Tensor
of shape(num_heads,)
or(num_layers, num_heads)
, optional, defaults toNone
) – Mask to nullify selected heads of the self-attention modules. Mask values selected in[0, 1]
:1
indicates the head is not masked,0
indicates the head is masked.inputs_embeds (
Numpy array
ortf.Tensor
of shape(batch_size, sequence_length, embedding_dim)
, optional, defaults toNone
) – Optionally, instead of passinginput_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.training (
boolean
, optional, defaults toFalse
) – Whether to activate dropout modules (if set toTrue
) during training or to de-activate them (if set toFalse
) for evaluation.output_attentions (
bool
, optional, defaults toNone
) – If set toTrue
, the attentions tensors of all attention layers are returned. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional, defaults toNone
) – If set toTrue
, the hidden states of all layers are returned. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional, defaults toNone
) – If set toTrue
, the model will return aModelOutput
instead of a plain tuple.labels (
tf.Tensor
of shape(batch_size, sequence_length)
, optional, defaults toNone
) – Labels for computing the masked language modeling loss. Indices should be in[-100, 0, ..., config.vocab_size]
(seeinput_ids
docstring) Tokens with indices set to-100
are ignored (masked), the loss is only computed for the tokens with labels in[0, ..., config.vocab_size]
- Returns
A
TFMaskedLMOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftf.Tensor
comprising various elements depending on the configuration (DistilBertConfig
) and inputs.loss (
tf.Tensor
of shape(1,)
, optional, returned whenlabels
is provided) – Masked languaged modeling (MLM) loss.logits (
tf.Tensor
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 (
tuple(tf.Tensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) – Tuple oftf.Tensor
(one for the output of the embeddings + one for the output of each layer) 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 (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) – Tuple oftf.Tensor
(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.
- Return type
TFMaskedLMOutput
ortuple(tf.Tensor)
- Example::
>>> from transformers import DistilBertTokenizer, TFDistilBertForMaskedLM >>> import tensorflow as tf
>>> tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased') >>> model = TFDistilBertForMaskedLM.from_pretrained('distilbert-base-uncased')
>>> input_ids = tf.constant(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True))[None, :] # Batch size 1
>>> outputs = model(input_ids) >>> prediction_scores = outputs[0]
TFDistilBertForSequenceClassification¶
-
class
transformers.
TFDistilBertForSequenceClassification
(*args, **kwargs)[source]¶ DistilBert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks. This model is a tf.keras.Model sub-class. Use it as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and behavior.
Note
TF 2.0 models accepts two formats as inputs:
having all inputs as keyword arguments (like PyTorch models), or
having all inputs as a list, tuple or dict in the first positional arguments.
This second option is useful when using
tf.keras.Model.fit()
method which currently requires having all the tensors in the first argument of the model call function:model(inputs)
.If you choose this second option, there are three possibilities you can use to gather all the input Tensors in the first positional argument :
a single Tensor with input_ids only and nothing else:
model(inputs_ids)
a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
model([input_ids, attention_mask])
a dictionary with one or several input Tensors associated to the input names given in the docstring:
model({'input_ids': input_ids})
- Parameters
config (
DistilBertConfig
) – Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()
method to load the model weights.
-
call
(inputs=None, attention_mask=None, head_mask=None, inputs_embeds=None, output_attentions=None, output_hidden_states=None, return_dict=None, labels=None, training=False)[source]¶ The
TFDistilBertForSequenceClassification
forward method, overrides the__call__()
special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.- Parameters
input_ids (
Numpy array
ortf.Tensor
of shape(batch_size, sequence_length)
) –Indices of input sequence tokens in the vocabulary.
Indices can be obtained using
transformers.BertTokenizer
. Seetransformers.PreTrainedTokenizer.encode()
andtransformers.PreTrainedTokenizer.__call__()
for details.attention_mask (
Numpy array
ortf.Tensor
of shape(batch_size, sequence_length)
, optional, defaults toNone
) –Mask to avoid performing attention on padding token indices. Mask values selected in
[0, 1]
:1
for tokens that are NOT MASKED,0
for MASKED tokens.head_mask (
Numpy array
ortf.Tensor
of shape(num_heads,)
or(num_layers, num_heads)
, optional, defaults toNone
) – Mask to nullify selected heads of the self-attention modules. Mask values selected in[0, 1]
:1
indicates the head is not masked,0
indicates the head is masked.inputs_embeds (
Numpy array
ortf.Tensor
of shape(batch_size, sequence_length, embedding_dim)
, optional, defaults toNone
) – Optionally, instead of passinginput_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.training (
boolean
, optional, defaults toFalse
) – Whether to activate dropout modules (if set toTrue
) during training or to de-activate them (if set toFalse
) for evaluation.output_attentions (
bool
, optional, defaults toNone
) – If set toTrue
, the attentions tensors of all attention layers are returned. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional, defaults toNone
) – If set toTrue
, the hidden states of all layers are returned. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional, defaults toNone
) – If set toTrue
, the model will return aModelOutput
instead of a plain tuple.labels (
tf.Tensor
of shape(batch_size,)
, optional, defaults toNone
) – Labels for computing the sequence classification/regression loss. Indices should be in[0, ..., config.num_labels - 1]
. Ifconfig.num_labels == 1
a regression loss is computed (Mean-Square loss), Ifconfig.num_labels > 1
a classification loss is computed (Cross-Entropy).
- Returns
A
TFSequenceClassifierOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftf.Tensor
comprising various elements depending on the configuration (DistilBertConfig
) and inputs.loss (
tf.Tensor
of shape(1,)
, optional, returned whenlabels
is provided) – Classification (or regression if config.num_labels==1) loss.logits (
tf.Tensor
of shape(batch_size, config.num_labels)
) – Classification (or regression if config.num_labels==1) scores (before SoftMax).hidden_states (
tuple(tf.Tensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) – Tuple oftf.Tensor
(one for the output of the embeddings + one for the output of each layer) 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 (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) – Tuple oftf.Tensor
(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.
- Return type
TFSequenceClassifierOutput
ortuple(tf.Tensor)
Example:
>>> from transformers import DistilBertTokenizer, TFDistilBertForSequenceClassification >>> import tensorflow as tf >>> tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased') >>> model = TFDistilBertForSequenceClassification.from_pretrained('distilbert-base-uncased') >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf") >>> inputs["labels"] = tf.reshape(tf.constant(1), (-1, 1)) # Batch size 1 >>> outputs = model(inputs) >>> loss, logits = outputs[:2]
TFDistilBertForMultipleChoice¶
-
class
transformers.
TFDistilBertForMultipleChoice
(*args, **kwargs)[source]¶ DistilBert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a softmax) e.g. for RocStories/SWAG tasks. This model is a tf.keras.Model sub-class. Use it as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and behavior.
Note
TF 2.0 models accepts two formats as inputs:
having all inputs as keyword arguments (like PyTorch models), or
having all inputs as a list, tuple or dict in the first positional arguments.
This second option is useful when using
tf.keras.Model.fit()
method which currently requires having all the tensors in the first argument of the model call function:model(inputs)
.If you choose this second option, there are three possibilities you can use to gather all the input Tensors in the first positional argument :
a single Tensor with input_ids only and nothing else:
model(inputs_ids)
a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
model([input_ids, attention_mask])
a dictionary with one or several input Tensors associated to the input names given in the docstring:
model({'input_ids': input_ids})
- Parameters
config (
DistilBertConfig
) – Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()
method to load the model weights.
-
call
(inputs, attention_mask=None, head_mask=None, inputs_embeds=None, output_attentions=None, output_hidden_states=None, return_dict=None, labels=None, training=False)[source]¶ The
TFDistilBertForMultipleChoice
forward method, overrides the__call__()
special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.- Parameters
input_ids (
Numpy array
ortf.Tensor
of shape(batch_size, sequence_length)
) –Indices of input sequence tokens in the vocabulary.
Indices can be obtained using
transformers.BertTokenizer
. Seetransformers.PreTrainedTokenizer.encode()
andtransformers.PreTrainedTokenizer.__call__()
for details.attention_mask (
Numpy array
ortf.Tensor
of shape(batch_size, sequence_length)
, optional, defaults toNone
) –Mask to avoid performing attention on padding token indices. Mask values selected in
[0, 1]
:1
for tokens that are NOT MASKED,0
for MASKED tokens.head_mask (
Numpy array
ortf.Tensor
of shape(num_heads,)
or(num_layers, num_heads)
, optional, defaults toNone
) – Mask to nullify selected heads of the self-attention modules. Mask values selected in[0, 1]
:1
indicates the head is not masked,0
indicates the head is masked.inputs_embeds (
Numpy array
ortf.Tensor
of shape(batch_size, sequence_length, embedding_dim)
, optional, defaults toNone
) – Optionally, instead of passinginput_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.training (
boolean
, optional, defaults toFalse
) – Whether to activate dropout modules (if set toTrue
) during training or to de-activate them (if set toFalse
) for evaluation.output_attentions (
bool
, optional, defaults toNone
) – If set toTrue
, the attentions tensors of all attention layers are returned. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional, defaults toNone
) – If set toTrue
, the hidden states of all layers are returned. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional, defaults toNone
) – If set toTrue
, the model will return aModelOutput
instead of a plain tuple.labels (
tf.Tensor
of shape(batch_size,)
, optional, defaults toNone
) – Labels for computing the multiple choice classification loss. Indices should be in[0, ..., num_choices]
where num_choices is the size of the second dimension of the input tensors. (see input_ids above)
- Returns
A
TFMultipleChoiceModelOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftf.Tensor
comprising various elements depending on the configuration (DistilBertConfig
) and inputs.loss (
tf.Tensor
of shape (1,), optional, returned whenlabels
is provided) – Classification loss.logits (
tf.Tensor
of shape(batch_size, num_choices)
) – num_choices is the second dimension of the input tensors. (see input_ids above).Classification scores (before SoftMax).
hidden_states (
tuple(tf.Tensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) – Tuple oftf.Tensor
(one for the output of the embeddings + one for the output of each layer) 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 (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) – Tuple oftf.Tensor
(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.
- Return type
TFMultipleChoiceModelOutput
ortuple(tf.Tensor)
Example:
>>> from transformers import DistilBertTokenizer, TFDistilBertForMultipleChoice >>> import tensorflow as tf >>> tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased') >>> model = TFDistilBertForMultipleChoice.from_pretrained('distilbert-base-uncased') >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced." >>> choice0 = "It is eaten with a fork and a knife." >>> choice1 = "It is eaten while held in the hand." >>> encoding = tokenizer([[prompt, prompt], [choice0, choice1]], return_tensors='tf', padding=True) >>> inputs = {k: tf.expand_dims(v, 0) for k, v in encoding.items()} >>> outputs = model(inputs) # batch size is 1 >>> # the linear classifier still needs to be trained >>> logits = outputs[0]
-
property
dummy_inputs
¶ Dummy inputs to build the network.
- Returns
tf.Tensor with dummy inputs
TFDistilBertForTokenClassification¶
-
class
transformers.
TFDistilBertForTokenClassification
(*args, **kwargs)[source]¶ DistilBert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks. This model is a tf.keras.Model sub-class. Use it as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and behavior.
Note
TF 2.0 models accepts two formats as inputs:
having all inputs as keyword arguments (like PyTorch models), or
having all inputs as a list, tuple or dict in the first positional arguments.
This second option is useful when using
tf.keras.Model.fit()
method which currently requires having all the tensors in the first argument of the model call function:model(inputs)
.If you choose this second option, there are three possibilities you can use to gather all the input Tensors in the first positional argument :
a single Tensor with input_ids only and nothing else:
model(inputs_ids)
a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
model([input_ids, attention_mask])
a dictionary with one or several input Tensors associated to the input names given in the docstring:
model({'input_ids': input_ids})
- Parameters
config (
DistilBertConfig
) – Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()
method to load the model weights.
-
call
(inputs=None, attention_mask=None, head_mask=None, inputs_embeds=None, output_attentions=None, output_hidden_states=None, return_dict=None, labels=None, training=False)[source]¶ The
TFDistilBertForTokenClassification
forward method, overrides the__call__()
special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.- Parameters
input_ids (
Numpy array
ortf.Tensor
of shape(batch_size, sequence_length)
) –Indices of input sequence tokens in the vocabulary.
Indices can be obtained using
transformers.BertTokenizer
. Seetransformers.PreTrainedTokenizer.encode()
andtransformers.PreTrainedTokenizer.__call__()
for details.attention_mask (
Numpy array
ortf.Tensor
of shape(batch_size, sequence_length)
, optional, defaults toNone
) –Mask to avoid performing attention on padding token indices. Mask values selected in
[0, 1]
:1
for tokens that are NOT MASKED,0
for MASKED tokens.head_mask (
Numpy array
ortf.Tensor
of shape(num_heads,)
or(num_layers, num_heads)
, optional, defaults toNone
) – Mask to nullify selected heads of the self-attention modules. Mask values selected in[0, 1]
:1
indicates the head is not masked,0
indicates the head is masked.inputs_embeds (
Numpy array
ortf.Tensor
of shape(batch_size, sequence_length, embedding_dim)
, optional, defaults toNone
) – Optionally, instead of passinginput_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.training (
boolean
, optional, defaults toFalse
) – Whether to activate dropout modules (if set toTrue
) during training or to de-activate them (if set toFalse
) for evaluation.output_attentions (
bool
, optional, defaults toNone
) – If set toTrue
, the attentions tensors of all attention layers are returned. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional, defaults toNone
) – If set toTrue
, the hidden states of all layers are returned. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional, defaults toNone
) – If set toTrue
, the model will return aModelOutput
instead of a plain tuple.labels (
tf.Tensor
of shape(batch_size, sequence_length)
, optional, defaults toNone
) – Labels for computing the token classification loss. Indices should be in[0, ..., config.num_labels - 1]
.
- Returns
A
TFTokenClassifierOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftf.Tensor
comprising various elements depending on the configuration (DistilBertConfig
) and inputs.loss (
tf.Tensor
of shape(1,)
, optional, returned whenlabels
is provided) – Classification loss.logits (
tf.Tensor
of shape(batch_size, sequence_length, config.num_labels)
) – Classification scores (before SoftMax).hidden_states (
tuple(tf.Tensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) – Tuple oftf.Tensor
(one for the output of the embeddings + one for the output of each layer) 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 (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) – Tuple oftf.Tensor
(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.
- Return type
TFTokenClassifierOutput
ortuple(tf.Tensor)
Example:
>>> from transformers import DistilBertTokenizer, TFDistilBertForTokenClassification >>> import tensorflow as tf >>> tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased') >>> model = TFDistilBertForTokenClassification.from_pretrained('distilbert-base-uncased') >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf") >>> input_ids = inputs["input_ids"] >>> inputs["labels"] = tf.reshape(tf.constant([1] * tf.size(input_ids).numpy()), (-1, tf.size(input_ids))) # Batch size 1 >>> outputs = model(inputs) >>> loss, scores = outputs[:2]
TFDistilBertForQuestionAnswering¶
-
class
transformers.
TFDistilBertForQuestionAnswering
(*args, **kwargs)[source]¶ DistilBert 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). This model is a tf.keras.Model sub-class. Use it as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and behavior.
Note
TF 2.0 models accepts two formats as inputs:
having all inputs as keyword arguments (like PyTorch models), or
having all inputs as a list, tuple or dict in the first positional arguments.
This second option is useful when using
tf.keras.Model.fit()
method which currently requires having all the tensors in the first argument of the model call function:model(inputs)
.If you choose this second option, there are three possibilities you can use to gather all the input Tensors in the first positional argument :
a single Tensor with input_ids only and nothing else:
model(inputs_ids)
a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
model([input_ids, attention_mask])
a dictionary with one or several input Tensors associated to the input names given in the docstring:
model({'input_ids': input_ids})
- Parameters
config (
DistilBertConfig
) – Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()
method to load the model weights.
-
call
(inputs=None, attention_mask=None, head_mask=None, inputs_embeds=None, output_attentions=None, output_hidden_states=None, return_dict=None, start_positions=None, end_positions=None, training=False)[source]¶ The
TFDistilBertForQuestionAnswering
forward method, overrides the__call__()
special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.- Parameters
input_ids (
Numpy array
ortf.Tensor
of shape(batch_size, sequence_length)
) –Indices of input sequence tokens in the vocabulary.
Indices can be obtained using
transformers.BertTokenizer
. Seetransformers.PreTrainedTokenizer.encode()
andtransformers.PreTrainedTokenizer.__call__()
for details.attention_mask (
Numpy array
ortf.Tensor
of shape(batch_size, sequence_length)
, optional, defaults toNone
) –Mask to avoid performing attention on padding token indices. Mask values selected in
[0, 1]
:1
for tokens that are NOT MASKED,0
for MASKED tokens.head_mask (
Numpy array
ortf.Tensor
of shape(num_heads,)
or(num_layers, num_heads)
, optional, defaults toNone
) – Mask to nullify selected heads of the self-attention modules. Mask values selected in[0, 1]
:1
indicates the head is not masked,0
indicates the head is masked.inputs_embeds (
Numpy array
ortf.Tensor
of shape(batch_size, sequence_length, embedding_dim)
, optional, defaults toNone
) – Optionally, instead of passinginput_ids
you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.training (
boolean
, optional, defaults toFalse
) – Whether to activate dropout modules (if set toTrue
) during training or to de-activate them (if set toFalse
) for evaluation.output_attentions (
bool
, optional, defaults toNone
) – If set toTrue
, the attentions tensors of all attention layers are returned. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional, defaults toNone
) – If set toTrue
, the hidden states of all layers are returned. Seehidden_states
under returned tensors for more detail.return_dict (
bool
, optional, defaults toNone
) – If set toTrue
, the model will return aModelOutput
instead of a plain tuple.start_positions (
tf.Tensor
of shape(batch_size,)
, optional, defaults toNone
) – 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 (
tf.Tensor
of shape(batch_size,)
, optional, defaults toNone
) – 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
A
TFQuestionAnsweringModelOutput
(ifreturn_dict=True
is passed or whenconfig.return_dict=True
) or a tuple oftf.Tensor
comprising various elements depending on the configuration (DistilBertConfig
) and inputs.loss (
tf.Tensor
of shape(1,)
, optional, returned whenlabels
is provided) – Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.start_logits (
tf.Tensor
of shape(batch_size, sequence_length,)
) – Span-start scores (before SoftMax).end_logits (
tf.Tensor
of shape(batch_size, sequence_length,)
) – Span-end scores (before SoftMax).hidden_states (
tuple(tf.Tensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) – Tuple oftf.Tensor
(one for the output of the embeddings + one for the output of each layer) 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 (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) – Tuple oftf.Tensor
(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.
- Return type
TFQuestionAnsweringModelOutput
ortuple(tf.Tensor)
Example:
>>> from transformers import DistilBertTokenizer, TFDistilBertForQuestionAnswering >>> import tensorflow as tf >>> tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased') >>> model = TFDistilBertForQuestionAnswering.from_pretrained('distilbert-base-uncased') >>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet" >>> input_dict = tokenizer(question, text, return_tensors='tf') >>> start_scores, end_scores = model(input_dict) >>> all_tokens = tokenizer.convert_ids_to_tokens(input_dict["input_ids"].numpy()[0]) >>> answer = ' '.join(all_tokens[tf.math.argmax(start_scores, 1)[0] : tf.math.argmax(end_scores, 1)[0]+1])