I-BERTΒΆ
OverviewΒΆ
The I-BERT model was proposed in I-BERT: Integer-only BERT Quantization by Sehoon Kim, Amir Gholami, Zhewei Yao, Michael W. Mahoney and Kurt Keutzer. Itβs a quantized version of RoBERTa running inference up to four times faster.
The abstract from the paper is the following:
Transformer based models, like BERT and RoBERTa, have achieved state-of-the-art results in many Natural Language Processing tasks. However, their memory footprint, inference latency, and power consumption are prohibitive for efficient inference at the edge, and even at the data center. While quantization can be a viable solution for this, previous work on quantizing Transformer based models use floating-point arithmetic during inference, which cannot efficiently utilize integer-only logical units such as the recent Turing Tensor Cores, or traditional integer-only ARM processors. In this work, we propose I-BERT, a novel quantization scheme for Transformer based models that quantizes the entire inference with integer-only arithmetic. Based on lightweight integer-only approximation methods for nonlinear operations, e.g., GELU, Softmax, and Layer Normalization, I-BERT performs an end-to-end integer-only BERT inference without any floating point calculation. We evaluate our approach on GLUE downstream tasks using RoBERTa-Base/Large. We show that for both cases, I-BERT achieves similar (and slightly higher) accuracy as compared to the full-precision baseline. Furthermore, our preliminary implementation of I-BERT shows a speedup of 2.4 - 4.0x for INT8 inference on a T4 GPU system as compared to FP32 inference. The framework has been developed in PyTorch and has been open-sourced.
This model was contributed by kssteven. The original code can be found here.
IBertConfigΒΆ
-
class
transformers.IBertConfig(vocab_size=30522, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size=2, initializer_range=0.02, layer_norm_eps=1e-12, pad_token_id=1, bos_token_id=0, eos_token_id=2, position_embedding_type='absolute', quant_mode=False, force_dequant='none', **kwargs)[source]ΒΆ This is the configuration class to store the configuration of a
IBertModel. It is used to instantiate a I-BERT model according to the specified arguments,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 I-BERT model. Defines the number of different tokens that can be represented by theinputs_idspassed when callingIBertModelhidden_size (
int, optional, defaults to 768) β Dimensionality of the encoder layers and the pooler layer.num_hidden_layers (
int, optional, defaults to 12) β Number of hidden layers in the Transformer encoder.num_attention_heads (
int, optional, defaults to 12) β Number of attention heads for each attention layer in the Transformer encoder.intermediate_size (
int, optional, defaults to 3072) β Dimensionality of the βintermediateβ (often named feed-forward) layer in the Transformer encoder.hidden_act (
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.hidden_dropout_prob (
float, optional, defaults to 0.1) β The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.attention_probs_dropout_prob (
float, optional, defaults to 0.1) β The dropout ratio for the attention probabilities.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).type_vocab_size (
int, optional, defaults to 2) β The vocabulary size of thetoken_type_idspassed when callingIBertModelinitializer_range (
float, optional, defaults to 0.02) β The standard deviation of the truncated_normal_initializer for initializing all weight matrices.layer_norm_eps (
float, optional, defaults to 1e-12) β The epsilon used by the layer normalization layers.position_embedding_type (
str, optional, defaults to"absolute") β Type of position embedding. Choose one of"absolute","relative_key","relative_key_query". For positional embeddings use"absolute". For more information on"relative_key", please refer to Self-Attention with Relative Position Representations (Shaw et al.). For more information on"relative_key_query", please refer to Method 4 in Improve Transformer Models with Better Relative Position Embeddings (Huang et al.).quant_mode (
bool, optional, defaults toFalse) β Whether to quantize the model or not.force_dequant (
str, optional, defaults to"none") β Force dequantize specific nonlinear layer. Dequatized layers are then executed with full precision."none","gelu","softmax","layernorm"and"nonlinear"are supported. As deafult, it is set as"none", which does not dequantize any layers. Please specify"gelu","softmax", or"layernorm"to dequantize GELU, Softmax, or LayerNorm, respectively."nonlinear"will dequantize all nonlinear layers, i.e., GELU, Softmax, and LayerNorm.
IBertModelΒΆ
-
class
transformers.IBertModel(config, add_pooling_layer=True)[source]ΒΆ The bare I-BERT Model 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 (
IBertConfig) β 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.
The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of cross-attention is added between the self-attention layers, following the architecture described in Attention is all you need by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
-
forward(input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, output_attentions=None, output_hidden_states=None, return_dict=None)[source]ΒΆ The
IBertModelforward 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, sequence_length))) βIndices of input sequence tokens in the vocabulary.
Indices can be obtained using
RobertaTokenizer. Seetransformers.PreTrainedTokenizer.encode()andtransformers.PreTrainedTokenizer.__call__()for details.attention_mask (
torch.FloatTensorof 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.
token_type_ids (
torch.LongTensorof shape((batch_size, sequence_length)), optional) βSegment token indices to indicate first and second portions of the inputs. Indices are selected in
[0, 1]:0 corresponds to a sentence A token,
1 corresponds to a sentence B token.
position_ids (
torch.LongTensorof shape((batch_size, sequence_length)), optional) βIndices of positions of each input sequence tokens in the position embeddings. Selected in the range
[0, config.max_position_embeddings - 1].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, 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.
- Returns
A
BaseModelOutputWithPoolingAndCrossAttentionsor a tuple oftorch.FloatTensor(ifreturn_dict=Falseis passed or whenconfig.return_dict=False) comprising various elements depending on the configuration (IBertConfig) 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.pooler_output (
torch.FloatTensorof shape(batch_size, hidden_size)) β Last layer hidden-state of the first token of the sequence (classification token) further processed by a Linear layer and a Tanh activation function. The Linear layer weights are trained from the next sentence prediction (classification) objective during pretraining.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.
cross_attentions (
tuple(torch.FloatTensor), optional, returned whenoutput_attentions=Trueandconfig.add_cross_attention=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 of the decoderβs cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads.
past_key_values (
tuple(tuple(torch.FloatTensor)), optional, returned whenuse_cache=Trueis passed or whenconfig.use_cache=True) β Tuple oftuple(torch.FloatTensor)of lengthconfig.n_layers, with each tuple having 2 tensors of shape(batch_size, num_heads, sequence_length, embed_size_per_head)) and optionally ifconfig.is_encoder_decoder=True2 additional tensors of shape(batch_size, num_heads, encoder_sequence_length, embed_size_per_head).Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if
config.is_encoder_decoder=Truein the cross-attention blocks) that can be used (seepast_key_valuesinput) to speed up sequential decoding.
- Return type
BaseModelOutputWithPoolingAndCrossAttentionsortuple(torch.FloatTensor)
Example:
>>> from transformers import RobertaTokenizer, IBertModel >>> import torch >>> tokenizer = RobertaTokenizer.from_pretrained('kssteven/ibert-roberta-base') >>> model = IBertModel.from_pretrained('kssteven/ibert-roberta-base') >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") >>> outputs = model(**inputs) >>> last_hidden_states = outputs.last_hidden_state
IBertForMaskedLMΒΆ
-
class
transformers.IBertForMaskedLM(config)[source]ΒΆ I-BERT Model with a 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 (
IBertConfig) β 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, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None)[source]ΒΆ The
IBertForMaskedLMforward 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, sequence_length)) βIndices of input sequence tokens in the vocabulary.
Indices can be obtained using
RobertaTokenizer. Seetransformers.PreTrainedTokenizer.encode()andtransformers.PreTrainedTokenizer.__call__()for details.attention_mask (
torch.FloatTensorof 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.
token_type_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) βSegment token indices to indicate first and second portions of the inputs. Indices are selected in
[0, 1]:0 corresponds to a sentence A token,
1 corresponds to a sentence B token.
position_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) βIndices of positions of each input sequence tokens in the position embeddings. Selected in the range
[0, config.max_position_embeddings - 1].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, 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, 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
MaskedLMOutputor a tuple oftorch.FloatTensor(ifreturn_dict=Falseis passed or whenconfig.return_dict=False) comprising various elements depending on the configuration (IBertConfig) 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 RobertaTokenizer, IBertForMaskedLM >>> import torch >>> tokenizer = RobertaTokenizer.from_pretrained('kssteven/ibert-roberta-base') >>> model = IBertForMaskedLM.from_pretrained('kssteven/ibert-roberta-base') >>> 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
IBertForSequenceClassificationΒΆ
-
class
transformers.IBertForSequenceClassification(config)[source]ΒΆ I-BERT 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 (
IBertConfig) β 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, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None)[source]ΒΆ The
IBertForSequenceClassificationforward 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, sequence_length)) βIndices of input sequence tokens in the vocabulary.
Indices can be obtained using
RobertaTokenizer. Seetransformers.PreTrainedTokenizer.encode()andtransformers.PreTrainedTokenizer.__call__()for details.attention_mask (
torch.FloatTensorof 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.
token_type_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) βSegment token indices to indicate first and second portions of the inputs. Indices are selected in
[0, 1]:0 corresponds to a sentence A token,
1 corresponds to a sentence B token.
position_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) βIndices of positions of each input sequence tokens in the position embeddings. Selected in the range
[0, config.max_position_embeddings - 1].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, 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 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
SequenceClassifierOutputor a tuple oftorch.FloatTensor(ifreturn_dict=Falseis passed or whenconfig.return_dict=False) comprising various elements depending on the configuration (IBertConfig) 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 RobertaTokenizer, IBertForSequenceClassification >>> import torch >>> tokenizer = RobertaTokenizer.from_pretrained('kssteven/ibert-roberta-base') >>> model = IBertForSequenceClassification.from_pretrained('kssteven/ibert-roberta-base') >>> 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
IBertForMultipleChoiceΒΆ
-
class
transformers.IBertForMultipleChoice(config)[source]ΒΆ I-BERT 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 (
IBertConfig) β 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, token_type_ids=None, attention_mask=None, labels=None, position_ids=None, head_mask=None, inputs_embeds=None, output_attentions=None, output_hidden_states=None, return_dict=None)[source]ΒΆ The
IBertForMultipleChoiceforward 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
RobertaTokenizer. 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.
token_type_ids (
torch.LongTensorof shape(batch_size, num_choices, sequence_length), optional) βSegment token indices to indicate first and second portions of the inputs. Indices are selected in
[0, 1]:0 corresponds to a sentence A token,
1 corresponds to a sentence B token.
position_ids (
torch.LongTensorof shape(batch_size, num_choices, sequence_length), optional) βIndices of positions of each input sequence tokens in the position embeddings. Selected in the range
[0, config.max_position_embeddings - 1].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
MultipleChoiceModelOutputor a tuple oftorch.FloatTensor(ifreturn_dict=Falseis passed or whenconfig.return_dict=False) comprising various elements depending on the configuration (IBertConfig) 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.
- Return type
MultipleChoiceModelOutputortuple(torch.FloatTensor)
Example:
>>> from transformers import RobertaTokenizer, IBertForMultipleChoice >>> import torch >>> tokenizer = RobertaTokenizer.from_pretrained('kssteven/ibert-roberta-base') >>> model = IBertForMultipleChoice.from_pretrained('kssteven/ibert-roberta-base') >>> 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, prompt], [choice0, 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
IBertForTokenClassificationΒΆ
-
class
transformers.IBertForTokenClassification(config)[source]ΒΆ I-BERT 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 (
IBertConfig) β 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, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None)[source]ΒΆ The
IBertForTokenClassificationforward 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, sequence_length)) βIndices of input sequence tokens in the vocabulary.
Indices can be obtained using
RobertaTokenizer. Seetransformers.PreTrainedTokenizer.encode()andtransformers.PreTrainedTokenizer.__call__()for details.attention_mask (
torch.FloatTensorof 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.
token_type_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) βSegment token indices to indicate first and second portions of the inputs. Indices are selected in
[0, 1]:0 corresponds to a sentence A token,
1 corresponds to a sentence B token.
position_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) βIndices of positions of each input sequence tokens in the position embeddings. Selected in the range
[0, config.max_position_embeddings - 1].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, 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, sequence_length), optional) β Labels for computing the token classification loss. Indices should be in[0, ..., config.num_labels - 1].
- Returns
A
TokenClassifierOutputor a tuple oftorch.FloatTensor(ifreturn_dict=Falseis passed or whenconfig.return_dict=False) comprising various elements depending on the configuration (IBertConfig) 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 RobertaTokenizer, IBertForTokenClassification >>> import torch >>> tokenizer = RobertaTokenizer.from_pretrained('kssteven/ibert-roberta-base') >>> model = IBertForTokenClassification.from_pretrained('kssteven/ibert-roberta-base') >>> 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
IBertForQuestionAnsweringΒΆ
-
class
transformers.IBertForQuestionAnswering(config)[source]ΒΆ I-BERT 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 (
IBertConfig) β 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, token_type_ids=None, position_ids=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
IBertForQuestionAnsweringforward 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, sequence_length)) βIndices of input sequence tokens in the vocabulary.
Indices can be obtained using
RobertaTokenizer. Seetransformers.PreTrainedTokenizer.encode()andtransformers.PreTrainedTokenizer.__call__()for details.attention_mask (
torch.FloatTensorof 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.
token_type_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) βSegment token indices to indicate first and second portions of the inputs. Indices are selected in
[0, 1]:0 corresponds to a sentence A token,
1 corresponds to a sentence B token.
position_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) βIndices of positions of each input sequence tokens in the position embeddings. Selected in the range
[0, config.max_position_embeddings - 1].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, 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.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
QuestionAnsweringModelOutputor a tuple oftorch.FloatTensor(ifreturn_dict=Falseis passed or whenconfig.return_dict=False) comprising various elements depending on the configuration (IBertConfig) 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 RobertaTokenizer, IBertForQuestionAnswering >>> import torch >>> tokenizer = RobertaTokenizer.from_pretrained('kssteven/ibert-roberta-base') >>> model = IBertForQuestionAnswering.from_pretrained('kssteven/ibert-roberta-base') >>> 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