FlauBERT

The FlauBERT model was proposed in the paper FlauBERT: Unsupervised Language Model Pre-training for French by Hang Le et al. It’s a transformer pre-trained using a masked language modeling (MLM) objective (BERT-like).

The abstract from the paper is the following:

Language models have become a key step to achieve state-of-the art results in many different Natural Language Processing (NLP) tasks. Leveraging the huge amount of unlabeled texts nowadays available, they provide an efficient way to pre-train continuous word representations that can be fine-tuned for a downstream task, along with their contextualization at the sentence level. This has been widely demonstrated for English using contextualized representations (Dai and Le, 2015; Peters et al., 2018; Howard and Ruder, 2018; Radford et al., 2018; Devlin et al., 2019; Yang et al., 2019b). In this paper, we introduce and share FlauBERT, a model learned on a very large and heterogeneous French corpus. Models of different sizes are trained using the new CNRS (French National Centre for Scientific Research) Jean Zay supercomputer. We apply our French language models to diverse NLP tasks (text classification, paraphrasing, natural language inference, parsing, word sense disambiguation) and show that most of the time they outperform other pre-training approaches. Different versions of FlauBERT as well as a unified evaluation protocol for the downstream tasks, called FLUE (French Language Understanding Evaluation), are shared to the research community for further reproducible experiments in French NLP.

FlaubertConfig

class transformers.FlaubertConfig(layerdrop=0.0, pre_norm=False, pad_token_id=2, bos_token_id=0, **kwargs)[source]

Configuration class to store the configuration of a FlaubertModel. This is the configuration class to store the configuration of a XLMModel. It is used to instantiate an XLM 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 xlm-mlm-en-2048 architecture.

Configuration objects inherit from PretrainedConfig and can be used to control the model outputs. Read the documentation from PretrainedConfig for more information.

Parameters
  • pre_norm (bool, optional, defaults to False) – Whether to apply the layer normalization before or after the feed forward layer following the attention in each layer (Vaswani et al., Tensor2Tensor for Neural Machine Translation. 2018)

  • layerdrop (float, optional, defaults to 0.0) – Probability to drop layers during training (Fan et al., Reducing Transformer Depth on Demand with Structured Dropout. ICLR 2020)

  • vocab_size (int, optional, defaults to 30145) – Vocabulary size of the Flaubert model. Defines the different tokens that can be represented by the inputs_ids passed to the forward method of FlaubertModel.

  • emb_dim (int, optional, defaults to 2048) – Dimensionality of the encoder layers and the pooler layer.

  • n_layer (int, optional, defaults to 12) – Number of hidden layers in the Transformer encoder.

  • n_head (int, optional, defaults to 16) – Number of attention heads for each attention 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 probability for the attention mechanism

  • gelu_activation (boolean, optional, defaults to True) – The non-linear activation function (function or string) in the encoder and pooler. If set to True, “gelu” will be used instead of “relu”.

  • sinusoidal_embeddings (boolean, optional, defaults to False) – Whether to use sinusoidal positional embeddings instead of absolute positional embeddings.

  • causal (boolean, optional, defaults to False) – Set this to True for the model to behave in a causal manner. Causal models use a triangular attention mask in order to only attend to the left-side context instead if a bidirectional context.

  • asm (boolean, optional, defaults to False) – Whether to use an adaptive log softmax projection layer instead of a linear layer for the prediction layer.

  • n_langs (int, optional, defaults to 1) – The number of languages the model handles. Set to 1 for monolingual models.

  • use_lang_emb (boolean, optional, defaults to True) – Whether to use language embeddings. Some models use additional language embeddings, see the multilingual models page for information on how to use them.

  • 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).

  • embed_init_std (float, optional, defaults to 2048^-0.5) – The standard deviation of the truncated_normal_initializer for initializing the embedding matrices.

  • init_std (int, optional, defaults to 50257) – The standard deviation of the truncated_normal_initializer for initializing all weight matrices except the embedding matrices.

  • layer_norm_eps (float, optional, defaults to 1e-12) – The epsilon used by the layer normalization layers.

  • bos_index (int, optional, defaults to 0) – The index of the beginning of sentence token in the vocabulary.

  • eos_index (int, optional, defaults to 1) – The index of the end of sentence token in the vocabulary.

  • pad_index (int, optional, defaults to 2) – The index of the padding token in the vocabulary.

  • unk_index (int, optional, defaults to 3) – The index of the unknown token in the vocabulary.

  • mask_index (int, optional, defaults to 5) – The index of the masking token in the vocabulary.

  • is_encoder (boolean, optional, defaults to True) – Whether the initialized model should be a transformer encoder or decoder as seen in Vaswani et al.

  • summary_type (string, optional, defaults to “first”) –

    Argument used when doing sequence summary. Used in for the multiple choice head in XLMForSequenceClassification. Is one of the following options:

    • ’last’ => take the last token hidden state (like XLNet)

    • ’first’ => take the first token hidden state (like Bert)

    • ’mean’ => take the mean of all tokens hidden states

    • ’cls_index’ => supply a Tensor of classification token position (GPT/GPT-2)

    • ’attn’ => Not implemented now, use multi-head attention

  • summary_use_proj (boolean, optional, defaults to True) – Argument used when doing sequence summary. Used in for the multiple choice head in XLMForSequenceClassification. Add a projection after the vector extraction

  • summary_activation (string or None, optional, defaults to None) – Argument used when doing sequence summary. Used in for the multiple choice head in XLMForSequenceClassification. ‘tanh’ => add a tanh activation to the output, Other => no activation.

  • summary_proj_to_labels (boolean, optional, defaults to True) – Argument used when doing sequence summary. Used in for the multiple choice head in XLMForSequenceClassification. If True, the projection outputs to config.num_labels classes (otherwise to hidden_size). Default: False.

  • summary_first_dropout (float, optional, defaults to 0.1) – Argument used when doing sequence summary. Used in for the multiple choice head in XLMForSequenceClassification. Add a dropout before the projection and activation

  • start_n_top (int, optional, defaults to 5) – Used in the SQuAD evaluation script for XLM and XLNet.

  • end_n_top (int, optional, defaults to 5) – Used in the SQuAD evaluation script for XLM and XLNet.

  • mask_token_id (int, optional, defaults to 0) – Model agnostic parameter to identify masked tokens when generating text in an MLM context.

  • lang_id (int, optional, defaults to 1) – The ID of the language used by the model. This parameter is used when generating text in a given language.

FlaubertTokenizer

class transformers.FlaubertTokenizer(do_lowercase=False, **kwargs)[source]

BPE tokenizer for Flaubert

  • Moses preprocessing & tokenization

  • Normalize all inputs text

  • argument special_tokens and function set_special_tokens, can be used to add additional symbols (ex: “__classify__”) to a vocabulary

  • do_lowercase controle lower casing (automatically set for pretrained vocabularies)

This tokenizer inherits from XLMTokenizer. Please check the superclass for usage examples and documentation regarding arguments.

FlaubertModel

class transformers.FlaubertModel(config)[source]

The bare Flaubert Model transformer outputting raw hidden-states without any specific head on top.

This model is a PyTorch torch.nn.Module sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

Parameters

config (FlaubertConfig) – 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 the from_pretrained() method to load the model weights.

config_class

alias of transformers.configuration_flaubert.FlaubertConfig

forward(input_ids=None, attention_mask=None, langs=None, token_type_ids=None, position_ids=None, lengths=None, cache=None, head_mask=None, inputs_embeds=None)[source]

The FlaubertModel forward method, overrides the __call__() special method.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

Parameters
  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) –

    Indices of input sequence tokens in the vocabulary.

    Indices can be obtained using transformers.BertTokenizer. See transformers.PreTrainedTokenizer.encode() and transformers.PreTrainedTokenizer.encode_plus() for details.

    What are input IDs?

  • attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional, defaults to None) –

    Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]: 1 for tokens that are NOT MASKED, 0 for MASKED tokens.

    What are attention masks?

  • token_type_ids (torch.LongTensor of shape (batch_size, sequence_length), optional, defaults to None) –

    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

    What are token type IDs?

  • position_ids (torch.LongTensor of shape (batch_size, sequence_length), optional, defaults to None) –

    Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.max_position_embeddings - 1].

    What are position IDs?

  • lengths (torch.LongTensor of shape (batch_size,), optional, defaults to None) – Length of each sentence that can be used to avoid performing attention on padding token indices. You can also use attention_mask for the same result (see above), kept here for compatbility. Indices selected in [0, ..., input_ids.size(-1)]:

  • cache (Dict[str, torch.FloatTensor], optional, defaults to None) – dictionary with torch.FloatTensor that contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model (see cache output below). Can be used to speed up sequential decoding. The dictionary object will be modified in-place during the forward pass to add newly computed hidden-states.

  • head_mask (torch.FloatTensor of shape (num_heads,) or (num_layers, num_heads), optional, defaults to None) – 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.

  • input_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional, defaults to None) – Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.

Returns

last_hidden_state (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size)):

Sequence of hidden-states at the output of the last layer of the model.

hidden_states (tuple(torch.FloatTensor), optional, returned when config.output_hidden_states=True):

Tuple of torch.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 when config.output_attentions=True):

Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.

Return type

tuple(torch.FloatTensor) comprising various elements depending on the configuration (XLMConfig) and inputs

Examples:

from transformers import FlaubertTokenizer, FlaubertModel
import torch

tokenizer = FlaubertTokenizer.from_pretrained('flaubert-base-cased')
model = FlaubertModel.from_pretrained('flaubert-base-cased')
input_ids = torch.tensor(tokenizer.encode("Le chat mange une pomme.", add_special_tokens=True)).unsqueeze(0)  # Batch size 1
outputs = model(input_ids)
last_hidden_states = outputs[0]  # The last hidden-state is the first element of the output tuple

FlaubertWithLMHeadModel

class transformers.FlaubertWithLMHeadModel(config)[source]

The Flaubert Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).

This model is a PyTorch torch.nn.Module sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

Parameters

config (FlaubertConfig) – 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 the from_pretrained() method to load the model weights.

This class overrides XLMWithLMHeadModel. Please check the superclass for the appropriate documentation alongside usage examples.

config_class

alias of transformers.configuration_flaubert.FlaubertConfig

FlaubertForSequenceClassification

class transformers.FlaubertForSequenceClassification(config)[source]

Flaubert Model with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks.

This model is a PyTorch torch.nn.Module sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

Parameters

config (FlaubertConfig) – 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 the from_pretrained() method to load the model weights.

This class overrides XLMForSequenceClassification. Please check the superclass for the appropriate documentation alongside usage examples.

config_class

alias of transformers.configuration_flaubert.FlaubertConfig

FlaubertForQuestionAnsweringSimple

class transformers.FlaubertForQuestionAnsweringSimple(config)[source]

Flaubert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear layers on top of the hidden-states output to compute span start logits and span end logits).

This model is a PyTorch torch.nn.Module sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

Parameters

config (FlaubertConfig) – 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 the from_pretrained() method to load the model weights.

This class overrides XLMForQuestionAnsweringSimple. Please check the superclass for the appropriate documentation alongside usage examples.

config_class

alias of transformers.configuration_flaubert.FlaubertConfig

FlaubertForQuestionAnswering

class transformers.FlaubertForQuestionAnswering(config)[source]

Flaubert Model with a beam-search span classification head on top for extractive question-answering tasks like SQuAD (a linear layers on top of the hidden-states output to compute span start logits and span end logits).

This model is a PyTorch torch.nn.Module sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

Parameters

config (FlaubertConfig) – 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 the from_pretrained() method to load the model weights.

This class overrides XLMForQuestionAnswering. Please check the superclass for the appropriate documentation alongside usage examples.

config_class

alias of transformers.configuration_flaubert.FlaubertConfig