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 tokentokenizer.sep_token(or[SEP]).DistilBERT doesn’t have options to select the input positions (
position_idsinput). This could be added if necessary though, just let 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
DistilBertModelor aTFDistilBertModel. 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
PretrainedConfigand can be used to control the model outputs. Read the documentation fromPretrainedConfigfor more information.- Parameters
vocab_size (
int, optional, defaults to 30522) – Vocabulary size of the DistilBERT model. Defines the number of different tokens that can be represented by theinputs_idspassed when callingDistilBertModelorTFDistilBertModel.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” (often named feed-forward) layer in the Transformer encoder.dropout (
float, optional, defaults to 0.1) – The dropout probability 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 (
strorCallable, optional, defaults to"gelu") – The non-linear activation function (function or string) in the encoder and pooler. If string,"gelu","relu","silu"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.
Examples:
>>> 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]¶ Construct a DistilBERT tokenizer.
DistilBertTokenizeris identical toBertTokenizerand runs end-to-end tokenization: punctuation splitting and wordpiece.Refer to superclass
BertTokenizerfor usage examples and documentation concerning parameters.
DistilBertTokenizerFast¶
-
class
transformers.DistilBertTokenizerFast(vocab_file, tokenizer_file=None, do_lower_case=True, unk_token='[UNK]', sep_token='[SEP]', pad_token='[PAD]', cls_token='[CLS]', mask_token='[MASK]', tokenize_chinese_chars=True, strip_accents=None, **kwargs)[source]¶ Construct a “fast” DistilBERT tokenizer (backed by HuggingFace’s tokenizers library).
DistilBertTokenizerFastis identical toBertTokenizerFastand runs end-to-end tokenization: punctuation splitting and wordpiece.Refer to superclass
BertTokenizerFastfor usage examples and documentation concerning parameters.-
slow_tokenizer_class¶ alias of
transformers.tokenization_distilbert.DistilBertTokenizer
-
DistilBertModel¶
-
class
transformers.DistilBertModel(config)[source]¶ The bare DistilBERT encoder/transformer outputting raw hidden-states without any specific head on top.
This model inherits from
PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)This model is also a PyTorch torch.nn.Module subclass. 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
DistilBertModelforward method, overrides the__call__()special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance 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.LongTensorof shape(batch_size, num_choices)) –Indices of input sequence tokens in the vocabulary.
Indices can be obtained using
DistilBertTokenizer. Seetransformers.PreTrainedTokenizer.encode()andtransformers.PreTrainedTokenizer.__call__()for details.attention_mask (
torch.FloatTensorof shape(batch_size, num_choices), optional) –Mask to avoid performing attention on padding token indices. Mask values selected in
[0, 1]:1 for tokens that are not masked,
0 for tokens that are masked.
head_mask (
torch.FloatTensorof shape(num_heads,)or(num_layers, num_heads), optional) –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.FloatTensorof shape(batch_size, num_choices, hidden_size), optional) – Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix.output_attentions (
bool, optional) – Whether or not to return the attentions tensors of all attention layers. Seeattentionsunder returned tensors for more detail.output_hidden_states (
bool, optional) – Whether or not to return the hidden states of all layers. Seehidden_statesunder returned tensors for more detail.return_dict (
bool, optional) – Whether or not to return aModelOutputinstead 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=Trueis passed or whenconfig.return_dict=True) or a tuple oftorch.FloatTensorcomprising various elements depending on the configuration (DistilBertConfig) and inputs.last_hidden_state (
torch.FloatTensorof 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=Trueis 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=Trueis 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
BaseModelOutputortuple(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 inherits from
PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)This model is also a PyTorch torch.nn.Module subclass. 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
DistilBertForMaskedLMforward method, overrides the__call__()special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance 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.LongTensorof shape(batch_size, num_choices)) –Indices of input sequence tokens in the vocabulary.
Indices can be obtained using
DistilBertTokenizer. Seetransformers.PreTrainedTokenizer.encode()andtransformers.PreTrainedTokenizer.__call__()for details.attention_mask (
torch.FloatTensorof shape(batch_size, num_choices), optional) –Mask to avoid performing attention on padding token indices. Mask values selected in
[0, 1]:1 for tokens that are not masked,
0 for tokens that are masked.
head_mask (
torch.FloatTensorof shape(num_heads,)or(num_layers, num_heads), optional) –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.FloatTensorof shape(batch_size, num_choices, hidden_size), optional) – Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix.output_attentions (
bool, optional) – Whether or not to return the attentions tensors of all attention layers. Seeattentionsunder returned tensors for more detail.output_hidden_states (
bool, optional) – Whether or not to return the hidden states of all layers. Seehidden_statesunder returned tensors for more detail.return_dict (
bool, optional) – Whether or not to return aModelOutputinstead of a plain tuple.labels (
torch.LongTensorof shape(batch_size, sequence_length), optional) – Labels for computing the masked language modeling loss. Indices should be in[-100, 0, ..., config.vocab_size](seeinput_idsdocstring) Tokens with indices set to-100are 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=Trueis passed or whenconfig.return_dict=True) or a tuple oftorch.FloatTensorcomprising various elements depending on the configuration (DistilBertConfig) and inputs.loss (
torch.FloatTensorof shape(1,), optional, returned whenlabelsis provided) – Masked language modeling (MLM) loss.logits (
torch.FloatTensorof 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=Trueis 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=Trueis 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
MaskedLMOutputortuple(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) >>> inputs = tokenizer("The capital of France is [MASK].", return_tensors="pt") >>> labels = tokenizer("The capital of France is Paris.", return_tensors="pt")["input_ids"] >>> outputs = model(**inputs, labels=labels) >>> loss = outputs.loss >>> 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 inherits from
PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)This model is also a PyTorch torch.nn.Module subclass. 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
DistilBertForSequenceClassificationforward method, overrides the__call__()special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance 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.LongTensorof shape(batch_size, num_choices)) –Indices of input sequence tokens in the vocabulary.
Indices can be obtained using
DistilBertTokenizer. Seetransformers.PreTrainedTokenizer.encode()andtransformers.PreTrainedTokenizer.__call__()for details.attention_mask (
torch.FloatTensorof shape(batch_size, num_choices), optional) –Mask to avoid performing attention on padding token indices. Mask values selected in
[0, 1]:1 for tokens that are not masked,
0 for tokens that are masked.
head_mask (
torch.FloatTensorof shape(num_heads,)or(num_layers, num_heads), optional) –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.FloatTensorof shape(batch_size, num_choices, hidden_size), optional) – Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix.output_attentions (
bool, optional) – Whether or not to return the attentions tensors of all attention layers. Seeattentionsunder returned tensors for more detail.output_hidden_states (
bool, optional) – Whether or not to return the hidden states of all layers. Seehidden_statesunder returned tensors for more detail.return_dict (
bool, optional) – Whether or not to return aModelOutputinstead of a plain tuple.labels (
torch.LongTensorof shape(batch_size,), optional) – Labels for computing the sequence classification/regression loss. Indices should be in[0, ..., config.num_labels - 1]. Ifconfig.num_labels == 1a regression loss is computed (Mean-Square loss), Ifconfig.num_labels > 1a classification loss is computed (Cross-Entropy).
- Returns
A
SequenceClassifierOutput(ifreturn_dict=Trueis passed or whenconfig.return_dict=True) or a tuple oftorch.FloatTensorcomprising various elements depending on the configuration (DistilBertConfig) and inputs.loss (
torch.FloatTensorof shape(1,), optional, returned whenlabelsis provided) – Classification (or regression if config.num_labels==1) loss.logits (
torch.FloatTensorof 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=Trueis 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=Trueis 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
SequenceClassifierOutputortuple(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 inherits from
PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)This model is also a PyTorch torch.nn.Module subclass. 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
DistilBertForMultipleChoiceforward method, overrides the__call__()special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance 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.LongTensorof shape(batch_size, num_choices, sequence_length)) –Indices of input sequence tokens in the vocabulary.
Indices can be obtained using
DistilBertTokenizer. Seetransformers.PreTrainedTokenizer.encode()andtransformers.PreTrainedTokenizer.__call__()for details.attention_mask (
torch.FloatTensorof shape(batch_size, num_choices, sequence_length), optional) –Mask to avoid performing attention on padding token indices. Mask values selected in
[0, 1]:1 for tokens that are not masked,
0 for tokens that are masked.
head_mask (
torch.FloatTensorof shape(num_heads,)or(num_layers, num_heads), optional) –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.FloatTensorof shape(batch_size, num_choices, sequence_length, hidden_size), optional) – Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix.output_attentions (
bool, optional) – Whether or not to return the attentions tensors of all attention layers. Seeattentionsunder returned tensors for more detail.output_hidden_states (
bool, optional) – Whether or not to return the hidden states of all layers. Seehidden_statesunder returned tensors for more detail.return_dict (
bool, optional) – Whether or not to return aModelOutputinstead of a plain tuple.labels (
torch.LongTensorof shape(batch_size,), optional) – Labels for computing the multiple choice classification loss. Indices should be in[0, ..., num_choices-1]wherenum_choicesis the size of the second dimension of the input tensors. (Seeinput_idsabove)
- Returns
A
MultipleChoiceModelOutput(ifreturn_dict=Trueis passed or whenconfig.return_dict=True) or a tuple oftorch.FloatTensorcomprising various elements depending on the configuration (DistilBertConfig) and inputs.loss (
torch.FloatTensorof shape (1,), optional, returned whenlabelsis provided) – Classification loss.logits (
torch.FloatTensorof 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=Trueis 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=Trueis 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
MultipleChoiceModelOutputortuple(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 inherits from
PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)This model is also a PyTorch torch.nn.Module subclass. 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
DistilBertForTokenClassificationforward method, overrides the__call__()special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance 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.LongTensorof shape({0})) –Indices of input sequence tokens in the vocabulary.
Indices can be obtained using
DistilBertTokenizer. Seetransformers.PreTrainedTokenizer.encode()andtransformers.PreTrainedTokenizer.__call__()for details.attention_mask (
torch.FloatTensorof shape({0}), optional) –Mask to avoid performing attention on padding token indices. Mask values selected in
[0, 1]:1 for tokens that are not masked,
0 for tokens that are masked.
head_mask (
torch.FloatTensorof shape(num_heads,)or(num_layers, num_heads), optional) –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.FloatTensorof shape({0}, hidden_size), optional) – Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix.output_attentions (
bool, optional) – Whether or not to return the attentions tensors of all attention layers. Seeattentionsunder returned tensors for more detail.output_hidden_states (
bool, optional) – Whether or not to return the hidden states of all layers. Seehidden_statesunder returned tensors for more detail.return_dict (
bool, optional) – Whether or not to return aModelOutputinstead of a plain tuple.labels (
torch.LongTensorof shape(batch_size, sequence_length), optional) – Labels for computing the token classification loss. Indices should be in[0, ..., config.num_labels - 1].
- Returns
A
TokenClassifierOutput(ifreturn_dict=Trueis passed or whenconfig.return_dict=True) or a tuple oftorch.FloatTensorcomprising various elements depending on the configuration (DistilBertConfig) and inputs.loss (
torch.FloatTensorof shape(1,), optional, returned whenlabelsis provided) – Classification loss.logits (
torch.FloatTensorof shape(batch_size, sequence_length, config.num_labels)) – Classification scores (before SoftMax).hidden_states (
tuple(torch.FloatTensor), optional, returned whenoutput_hidden_states=Trueis 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=Trueis 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
TokenClassifierOutputortuple(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 inherits from
PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)This model is also a PyTorch torch.nn.Module subclass. 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
DistilBertForQuestionAnsweringforward method, overrides the__call__()special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance 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.LongTensorof shape(batch_size, num_choices)) –Indices of input sequence tokens in the vocabulary.
Indices can be obtained using
DistilBertTokenizer. Seetransformers.PreTrainedTokenizer.encode()andtransformers.PreTrainedTokenizer.__call__()for details.attention_mask (
torch.FloatTensorof shape(batch_size, num_choices), optional) –Mask to avoid performing attention on padding token indices. Mask values selected in
[0, 1]:1 for tokens that are not masked,
0 for tokens that are masked.
head_mask (
torch.FloatTensorof shape(num_heads,)or(num_layers, num_heads), optional) –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.FloatTensorof shape(batch_size, num_choices, hidden_size), optional) – Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix.output_attentions (
bool, optional) – Whether or not to return the attentions tensors of all attention layers. Seeattentionsunder returned tensors for more detail.output_hidden_states (
bool, optional) – Whether or not to return the hidden states of all layers. Seehidden_statesunder returned tensors for more detail.return_dict (
bool, optional) – Whether or not to return aModelOutputinstead of a plain tuple.start_positions (
torch.LongTensorof shape(batch_size,), optional) – 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.LongTensorof shape(batch_size,), optional) – 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=Trueis passed or whenconfig.return_dict=True) or a tuple oftorch.FloatTensorcomprising various elements depending on the configuration (DistilBertConfig) and inputs.loss (
torch.FloatTensorof shape(1,), optional, returned whenlabelsis provided) – Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.start_logits (
torch.FloatTensorof shape(batch_size, sequence_length)) – Span-start scores (before SoftMax).end_logits (
torch.FloatTensorof shape(batch_size, sequence_length)) – Span-end scores (before SoftMax).hidden_states (
tuple(torch.FloatTensor), optional, returned whenoutput_hidden_states=Trueis 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=Trueis 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
QuestionAnsweringModelOutputortuple(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) >>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet" >>> inputs = tokenizer(question, text, 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_logits >>> end_scores = outputs.end_logits
TFDistilBertModel¶
-
class
transformers.TFDistilBertModel(*args, **kwargs)[source]¶ The bare DistilBERT encoder/transformer outputting raw hidden-states without any specific head on top.
This model inherits from
TFPreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)This model is also a tf.keras.Model subclass. 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_idsonly 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
TFDistilBertModelforward method, overrides the__call__()special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance 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 arrayortf.Tensorof shape(batch_size, sequence_length)) –Indices of input sequence tokens in the vocabulary.
Indices can be obtained using
DistilBertTokenizer. Seetransformers.PreTrainedTokenizer.__call__()andtransformers.PreTrainedTokenizer.encode()for details.attention_mask (
Numpy arrayortf.Tensorof shape(batch_size, sequence_length), optional) –Mask to avoid performing attention on padding token indices. Mask values selected in
[0, 1]:1 for tokens that are not masked,
0 for tokens that are masked.
head_mask (
Numpy arrayortf.Tensorof shape(num_heads,)or(num_layers, num_heads), optional) –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 (
tf.Tensorof shape(batch_size, sequence_length, hidden_size), optional) – Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix.output_attentions (
bool, optional) – Whether or not to return the attentions tensors of all attention layers. Seeattentionsunder returned tensors for more detail.output_hidden_states (
bool, optional) – Whether or not to return the hidden states of all layers. Seehidden_statesunder returned tensors for more detail.return_dict (
bool, optional) – Whether or not to return aModelOutputinstead of a plain tuple.training (
bool, optional, defaults toFalse) – Whether or not to use the model in training mode (some modules like dropout modules have different behaviors between training and evaluation).
- Returns
A
TFBaseModelOutput(ifreturn_dict=Trueis passed or whenconfig.return_dict=True) or a tuple oftf.Tensorcomprising various elements depending on the configuration (DistilBertConfig) and inputs.last_hidden_state (
tf.Tensorof 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=Trueis 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=Trueis 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
TFBaseModelOutputortuple(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', return_dict=True) >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf") >>> outputs = model(inputs) >>> last_hidden_states = outputs.last_hidden_states
TFDistilBertForMaskedLM¶
-
class
transformers.TFDistilBertForMaskedLM(*args, **kwargs)[source]¶ DistilBert Model with a masked language modeling head on top.
This model inherits from
TFPreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)This model is also a tf.keras.Model subclass. 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_idsonly 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
TFDistilBertForMaskedLMforward method, overrides the__call__()special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance 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 arrayortf.Tensorof shape(batch_size, sequence_length)) –Indices of input sequence tokens in the vocabulary.
Indices can be obtained using
DistilBertTokenizer. Seetransformers.PreTrainedTokenizer.__call__()andtransformers.PreTrainedTokenizer.encode()for details.attention_mask (
Numpy arrayortf.Tensorof shape(batch_size, sequence_length), optional) –Mask to avoid performing attention on padding token indices. Mask values selected in
[0, 1]:1 for tokens that are not masked,
0 for tokens that are masked.
head_mask (
Numpy arrayortf.Tensorof shape(num_heads,)or(num_layers, num_heads), optional) –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 (
tf.Tensorof shape(batch_size, sequence_length, hidden_size), optional) – Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix.output_attentions (
bool, optional) – Whether or not to return the attentions tensors of all attention layers. Seeattentionsunder returned tensors for more detail.output_hidden_states (
bool, optional) – Whether or not to return the hidden states of all layers. Seehidden_statesunder returned tensors for more detail.return_dict (
bool, optional) – Whether or not to return aModelOutputinstead of a plain tuple.training (
bool, optional, defaults toFalse) – Whether or not to use the model in training mode (some modules like dropout modules have different behaviors between training and evaluation).labels (
tf.Tensorof shape(batch_size, sequence_length), optional) – Labels for computing the masked language modeling loss. Indices should be in[-100, 0, ..., config.vocab_size](seeinput_idsdocstring) Tokens with indices set to-100are ignored (masked), the loss is only computed for the tokens with labels in[0, ..., config.vocab_size]
- Returns
A
TFMaskedLMOutput(ifreturn_dict=Trueis passed or whenconfig.return_dict=True) or a tuple oftf.Tensorcomprising various elements depending on the configuration (DistilBertConfig) and inputs.loss (
tf.Tensorof shape(1,), optional, returned whenlabelsis provided) – Masked language modeling (MLM) loss.logits (
tf.Tensorof 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=Trueis 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=Trueis 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
TFMaskedLMOutputortuple(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', return_dict=True) >>> inputs = tokenizer("The capital of France is [MASK].", return_tensors="tf") >>> inputs["labels"] = tokenizer("The capital of France is Paris.", return_tensors="tf")["input_ids"] >>> outputs = model(inputs) >>> loss = outputs.loss >>> logits = outputs.logits
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 inherits from
TFPreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)This model is also a tf.keras.Model subclass. 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_idsonly 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
TFDistilBertForSequenceClassificationforward method, overrides the__call__()special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance 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 arrayortf.Tensorof shape(batch_size, sequence_length)) –Indices of input sequence tokens in the vocabulary.
Indices can be obtained using
DistilBertTokenizer. Seetransformers.PreTrainedTokenizer.__call__()andtransformers.PreTrainedTokenizer.encode()for details.attention_mask (
Numpy arrayortf.Tensorof shape(batch_size, sequence_length), optional) –Mask to avoid performing attention on padding token indices. Mask values selected in
[0, 1]:1 for tokens that are not masked,
0 for tokens that are masked.
head_mask (
Numpy arrayortf.Tensorof shape(num_heads,)or(num_layers, num_heads), optional) –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 (
tf.Tensorof shape(batch_size, sequence_length, hidden_size), optional) – Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix.output_attentions (
bool, optional) – Whether or not to return the attentions tensors of all attention layers. Seeattentionsunder returned tensors for more detail.output_hidden_states (
bool, optional) – Whether or not to return the hidden states of all layers. Seehidden_statesunder returned tensors for more detail.return_dict (
bool, optional) – Whether or not to return aModelOutputinstead of a plain tuple.training (
bool, optional, defaults toFalse) – Whether or not to use the model in training mode (some modules like dropout modules have different behaviors between training and evaluation).labels (
tf.Tensorof shape(batch_size,), optional) – Labels for computing the sequence classification/regression loss. Indices should be in[0, ..., config.num_labels - 1]. Ifconfig.num_labels == 1a regression loss is computed (Mean-Square loss), Ifconfig.num_labels > 1a classification loss is computed (Cross-Entropy).
- Returns
A
TFSequenceClassifierOutput(ifreturn_dict=Trueis passed or whenconfig.return_dict=True) or a tuple oftf.Tensorcomprising various elements depending on the configuration (DistilBertConfig) and inputs.loss (
tf.Tensorof shape(1,), optional, returned whenlabelsis provided) – Classification (or regression if config.num_labels==1) loss.logits (
tf.Tensorof 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=Trueis 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=Trueis 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
TFSequenceClassifierOutputortuple(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', return_dict=True) >>> 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 = outputs.loss >>> logits = outputs.logits
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 inherits from
TFPreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)This model is also a tf.keras.Model subclass. 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_idsonly 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
TFDistilBertForMultipleChoiceforward method, overrides the__call__()special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance 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 arrayortf.Tensorof shape(batch_size, num_choices, sequence_length)) –Indices of input sequence tokens in the vocabulary.
Indices can be obtained using
DistilBertTokenizer. Seetransformers.PreTrainedTokenizer.__call__()andtransformers.PreTrainedTokenizer.encode()for details.attention_mask (
Numpy arrayortf.Tensorof shape(batch_size, num_choices, sequence_length), optional) –Mask to avoid performing attention on padding token indices. Mask values selected in
[0, 1]:1 for tokens that are not masked,
0 for tokens that are masked.
head_mask (
Numpy arrayortf.Tensorof shape(num_heads,)or(num_layers, num_heads), optional) –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 (
tf.Tensorof shape(batch_size, num_choices, sequence_length, hidden_size), optional) – Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix.output_attentions (
bool, optional) – Whether or not to return the attentions tensors of all attention layers. Seeattentionsunder returned tensors for more detail.output_hidden_states (
bool, optional) – Whether or not to return the hidden states of all layers. Seehidden_statesunder returned tensors for more detail.return_dict (
bool, optional) – Whether or not to return aModelOutputinstead of a plain tuple.training (
bool, optional, defaults toFalse) – Whether or not to use the model in training mode (some modules like dropout modules have different behaviors between training and evaluation).labels (
tf.Tensorof shape(batch_size,), optional) – Labels for computing the multiple choice classification loss. Indices should be in[0, ..., num_choices]wherenum_choicesis the size of the second dimension of the input tensors. (Seeinput_idsabove)
- Returns
A
TFMultipleChoiceModelOutput(ifreturn_dict=Trueis passed or whenconfig.return_dict=True) or a tuple oftf.Tensorcomprising various elements depending on the configuration (DistilBertConfig) and inputs.loss (
tf.Tensorof shape (1,), optional, returned whenlabelsis provided) – Classification loss.logits (
tf.Tensorof 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=Trueis 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=Trueis 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
TFMultipleChoiceModelOutputortuple(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', 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." >>> 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.logits
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 inherits from
TFPreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)This model is also a tf.keras.Model subclass. 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_idsonly 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
TFDistilBertForTokenClassificationforward method, overrides the__call__()special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance 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 arrayortf.Tensorof shape(batch_size, sequence_length)) –Indices of input sequence tokens in the vocabulary.
Indices can be obtained using
DistilBertTokenizer. Seetransformers.PreTrainedTokenizer.__call__()andtransformers.PreTrainedTokenizer.encode()for details.attention_mask (
Numpy arrayortf.Tensorof shape(batch_size, sequence_length), optional) –Mask to avoid performing attention on padding token indices. Mask values selected in
[0, 1]:1 for tokens that are not masked,
0 for tokens that are masked.
head_mask (
Numpy arrayortf.Tensorof shape(num_heads,)or(num_layers, num_heads), optional) –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 (
tf.Tensorof shape(batch_size, sequence_length, hidden_size), optional) – Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix.output_attentions (
bool, optional) – Whether or not to return the attentions tensors of all attention layers. Seeattentionsunder returned tensors for more detail.output_hidden_states (
bool, optional) – Whether or not to return the hidden states of all layers. Seehidden_statesunder returned tensors for more detail.return_dict (
bool, optional) – Whether or not to return aModelOutputinstead of a plain tuple.training (
bool, optional, defaults toFalse) – Whether or not to use the model in training mode (some modules like dropout modules have different behaviors between training and evaluation).labels (
tf.Tensorof shape(batch_size, sequence_length), optional) – Labels for computing the token classification loss. Indices should be in[0, ..., config.num_labels - 1].
- Returns
A
TFTokenClassifierOutput(ifreturn_dict=Trueis passed or whenconfig.return_dict=True) or a tuple oftf.Tensorcomprising various elements depending on the configuration (DistilBertConfig) and inputs.loss (
tf.Tensorof shape(1,), optional, returned whenlabelsis provided) – Classification loss.logits (
tf.Tensorof shape(batch_size, sequence_length, config.num_labels)) – Classification scores (before SoftMax).hidden_states (
tuple(tf.Tensor), optional, returned whenoutput_hidden_states=Trueis 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=Trueis 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
TFTokenClassifierOutputortuple(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', return_dict=True) >>> 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 = outputs.loss >>> logits = outputs.logits
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 layer on top of the hidden-states output to compute span start logits and span end logits).
This model inherits from
TFPreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)This model is also a tf.keras.Model subclass. 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_idsonly 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
TFDistilBertForQuestionAnsweringforward method, overrides the__call__()special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance 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 arrayortf.Tensorof shape(batch_size, sequence_length)) –Indices of input sequence tokens in the vocabulary.
Indices can be obtained using
DistilBertTokenizer. Seetransformers.PreTrainedTokenizer.__call__()andtransformers.PreTrainedTokenizer.encode()for details.attention_mask (
Numpy arrayortf.Tensorof shape(batch_size, sequence_length), optional) –Mask to avoid performing attention on padding token indices. Mask values selected in
[0, 1]:1 for tokens that are not masked,
0 for tokens that are masked.
head_mask (
Numpy arrayortf.Tensorof shape(num_heads,)or(num_layers, num_heads), optional) –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 (
tf.Tensorof shape(batch_size, sequence_length, hidden_size), optional) – Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix.output_attentions (
bool, optional) – Whether or not to return the attentions tensors of all attention layers. Seeattentionsunder returned tensors for more detail.output_hidden_states (
bool, optional) – Whether or not to return the hidden states of all layers. Seehidden_statesunder returned tensors for more detail.return_dict (
bool, optional) – Whether or not to return aModelOutputinstead of a plain tuple.training (
bool, optional, defaults toFalse) – Whether or not to use the model in training mode (some modules like dropout modules have different behaviors between training and evaluation).start_positions (
tf.Tensorof shape(batch_size,), optional) – 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.Tensorof shape(batch_size,), optional) – 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=Trueis passed or whenconfig.return_dict=True) or a tuple oftf.Tensorcomprising various elements depending on the configuration (DistilBertConfig) and inputs.loss (
tf.Tensorof shape(1,), optional, returned whenlabelsis provided) – Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.start_logits (
tf.Tensorof shape(batch_size, sequence_length)) – Span-start scores (before SoftMax).end_logits (
tf.Tensorof shape(batch_size, sequence_length)) – Span-end scores (before SoftMax).hidden_states (
tuple(tf.Tensor), optional, returned whenoutput_hidden_states=Trueis 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=Trueis 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
TFQuestionAnsweringModelOutputortuple(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', return_dict=True) >>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet" >>> input_dict = tokenizer(question, text, return_tensors='tf') >>> outputs = model(input_dict) >>> start_logits = outputs.start_logits >>> end_logits = outputs.end_logits >>> all_tokens = tokenizer.convert_ids_to_tokens(input_dict["input_ids"].numpy()[0]) >>> answer = ' '.join(all_tokens[tf.math.argmax(start_logits, 1)[0] : tf.math.argmax(end_logits, 1)[0]+1])