Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/main/examples/language_modeling_from_scratch.ipynb
Views: 2535
If you're opening this Notebook on colab, you will probably need to install 🤗 Transformers and 🤗 Datasets. Uncomment the following cell and run it.
If you're opening this notebook locally, make sure your environment has an install from the last version of those libraries.
To be able to share your model with the community and generate results like the one shown in the picture below via the inference API, there are a few more steps to follow.
First you have to store your authentication token from the Hugging Face website (sign up here if you haven't already!) then execute the following cell and input your username and password:
Then you need to install Git-LFS. Uncomment the following instructions:
Make sure your version of Transformers is at least 4.11.0 since the functionality was introduced in that version:
You can find a script version of this notebook to fine-tune your model in a distributed fashion using multiple GPUs or TPUs here.
We also quickly upload some telemetry - this tells us which examples and software versions are getting used so we know where to prioritize our maintenance efforts. We don't collect (or care about) any personally identifiable information, but if you'd prefer not to be counted, feel free to skip this step or delete this cell entirely.
Train a language model
In this notebook, we'll see how to train a 🤗 Transformers model on a language modeling task. We will cover two types of language modeling tasks which are:
Causal language modeling: the model has to predict the next token in the sentence (so the labels are the same as the inputs shifted to the right). To make sure the model does not cheat, it gets an attention mask that will prevent it to access the tokens after token i when trying to predict the token i+1 in the sentence.
Masked language modeling: the model has to predict some tokens that are masked in the input. It still has access to the whole sentence, so it can use the tokens before and after the tokens masked to predict their value.
We will see how to easily load and preprocess the dataset for each one of those tasks, and how to use the Trainer
API to train a model on it.
This notebooks assumes you have trained a tokenizer on the corpus you are using, see the How to train a tokenizer notebook (open in colab).
A script version of this notebook you can directly run on a distributed environment or on TPU is available in our examples folder.
Preparing the dataset
For each of those tasks, we will use the Wikitext 2 dataset as an example. You can load it very easily with the 🤗 Datasets library.
You can replace the dataset above with any dataset hosted on the hub or use your own files. Just uncomment the following cell and replace the paths with values that will lead to your files:
You can also load datasets from a csv or a JSON file, see the full documentation for more information.
To access an actual element, you need to select a split first, then give an index:
To get a sense of what the data looks like, the following function will show some examples picked randomly in the dataset.
As we can see, some of the texts are a full paragraph of a Wikipedia article while others are just titles or empty lines.
Causal Language modeling
For causal language modeling (CLM) we are going to take all the texts in our dataset and concatenate them after they are tokenized. Then we will split them in examples of a certain sequence length. This way the model will receive chunks of contiguous text that may look like:
or
depending on whether they span over several of the original texts in the dataset or not. The labels will be the same as the inputs, shifted to the left.
We will use the gpt2
architecture for this example. You can pick any of the checkpoints listed here instead. For the tokenizer, you can replace the checkpoint by the one you trained yourself.
To tokenize all our texts with the same vocabulary that was used when training the model, we have to download a pretrained tokenizer. This is all done by the AutoTokenizer
class:
We can now call the tokenizer on all our texts. This is very simple, using the map
method from the Datasets library. First we define a function that call the tokenizer on our texts:
Then we apply it to all the splits in our datasets
object, using batched=True
and 4 processes to speed up the preprocessing. We won't need the text
column afterward, so we discard it.
If we now look at an element of our datasets, we will see the text have been replaced by the input_ids
the model will need:
Now for the harder part: we need to concatenate all our texts together then split the result in small chunks of a certain block_size
. To do this, we will use the map
method again, with the option batched=True
. This option actually lets us change the number of examples in the datasets by returning a different number of examples than we got. This way, we can create our new samples from a batch of examples.
First, we grab the maximum length our model was pretrained with. This might be a big too big to fit in your GPU RAM, so here we take a bit less at just 128.
Then we write the preprocessing function that will group our texts:
First note that we duplicate the inputs for our labels. This is because the model of the 🤗 Transformers library apply the shifting to the right, so we don't need to do it manually.
Also note that by default, the map
method will send a batch of 1,000 examples to be treated by the preprocessing function. So here, we will drop the remainder to make the concatenated tokenized texts a multiple of block_size
every 1,000 examples. You can adjust this behavior by passing a higher batch size (which will also be processed slower). You can also speed-up the preprocessing by using multiprocessing:
And we can check our datasets have changed: now the samples contain chunks of block_size
contiguous tokens, potentially spanning over several of our original texts.
Now that the data has been cleaned, we're ready to instantiate our Trainer
. First we create the model using the same config as our checkpoint, but initialized with random weights:
And we will needsome TrainingArguments
:
The last argument to setup everything so we can push the model to the Hub regularly during training. Remove it if you didn't follow the installation steps at the top of the notebook. If you want to save your model locally in a name that is different than the name of the repository it will be pushed, or if you want to push your model under an organization and not your name space, use the hub_model_id
argument to set the repo name (it needs to be the full name, including your namespace: for instance "sgugger/gpt-finetuned-wikitext2"
or "huggingface/gpt-finetuned-wikitext2"
).
We pass along all of those to the Trainer
class:
And we can train our model:
Once the training is completed, we can evaluate our model and get its perplexity on the validation set like this:
The perplexity is still quite high since for this demo we trained on a small dataset for a small number of epochs. For a real LM training, you would need a larger dataset and more epochs.
You can now upload the result of the training to the Hub, just execute this instruction:
You can now share this model with all your friends, family, favorite pets: they can all load it with the identifier "your-username/the-name-you-picked"
so for instance:
Masked language modeling
For masked language modeling (MLM) we are going to use the same preprocessing as before for our dataset with one additional step: we will randomly mask some tokens (by replacing them by [MASK]
) and the labels will be adjusted to only include the masked tokens (we don't have to predict the non-masked tokens). If you use a tokenizer you trained yourself, make sure the [MASK]
token is among the special tokens you passed during training!
We will use the bert-base-cased
model for this example. You can pick any of the checkpoints listed here instead. For the tokenizer, replace the checkpoint by the one you trained.
We can apply the same tokenization function as before, we just need to update our tokenizer to use the checkpoint we just picked:
And like before, we group texts together and chunk them in samples of length block_size
. You can skip that step if your dataset is composed of individual sentences.
The rest is very similar to what we had, with two exceptions. First we use a model suitable for masked LM:
We redefine our TrainingArguments
:
Like before, the last two arguments are to setup everything so we can push the model to the Hub at the end of training. Remove the two of them if you didn't follow the installation steps at the top of the notebook, otherwise you can change the value of push_to_hub_model_id
to something you would prefer.
Finally, we use a special data_collator
. The data_collator
is a function that is responsible of taking the samples and batching them in tensors. In the previous example, we had nothing special to do, so we just used the default for this argument. Here we want to do the random-masking. We could do it as a pre-processing step (like the tokenization) but then the tokens would always be masked the same way at each epoch. By doing this step inside the data_collator
, we ensure this random masking is done in a new way each time we go over the data.
To do this masking for us, the library provides a DataCollatorForLanguageModeling
. We can adjust the probability of the masking:
Then we just have to pass everything to Trainer
and begin training:
Like before, we can evaluate our model on the validation set. The perplexity is much lower than for the CLM objective because for the MLM objective, we only have to make predictions for the masked tokens (which represent 15% of the total here) while having access to the rest of the tokens. It's thus an easier task for the model.
The perplexity is still quite high since for this demo we trained on a small dataset for a small number of epochs. For a real LM training, you would need a larger dataset and more epochs.
You can now upload the result of the training to the Hub, just execute this instruction:
You can now share this model with all your friends, family, favorite pets: they can all load it with the identifier "your-username/the-name-you-picked"
so for instance: