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-tf.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 uncomment the following cell and input your token:
Then you need to install Git-LFS and setup Git if you haven't already. On Linux, uncomment the following instructions and adapt with your name and email. On Windows, please download git-lfs at https://git-lfs.github.com/
Make sure your version of Transformers is at least 4.16.0 since some of the functionality we use 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, its attention computations are masked so that tokens cannot attend to tokens to their right, as this would result in label leakage.
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 your own input 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, tokenize them and concatenate them. Then we will split them into examples of a fixed sequence length. This way the model will receive chunks of contiguous text that may look like:
or
depending on whether they span multiple original texts or not. The labels will be the same as the inputs, shifted to the right.
We will use the gpt2
architecture for this example. You can pick any of the checkpoints listed here instead. For the tokenizer, you can optionally replace the checkpoint with one that you trained yourself.
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 calls 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, and then split the result into chunks of a fixed size, which we will call block_size
. To do this, we will use the map
method again, with the option batched=True
. When we use batched=True
, the function we pass to map()
will be passed multiple inputs at once, allowing us to group them into more or fewer examples than we had in the input. This allows us to create our new fixed-length samples.
We can use any block_size
, but high values might be too big to fit in your GPU RAM, so let's use something a bit smaller: 128.
Then we write the preprocessing function that will group our texts:
Note that we duplicate the inputs for our labels, without shifting them, even though we told you the labels need to be shifted! This is because CausalLM models in the 🤗 Transformers library automatically apply right-shifting to the inputs, 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 several of our original texts.
Now that the data has been cleaned, we're ready to initialize our Model
. First we create the model using the same config as our checkpoint, but initialized with random weights:
Now let's set some hyperparameters like the learning rate and weight decay, as well as the model ID, if we want to upload our model to the Hub afterwards.
Now we initialize our optimizer.
Next, we compile our model. Note that most Transformers models compute loss internally, so we actually don't have to specify anything for that argument! You can of course set your own loss function if you want, but by default our models will choose the 'obvious' loss that matches their task, such as cross-entropy in the case of language modelling. The built-in loss will also correctly handle things like masking the loss on padding tokens, or unlabelled tokens in the case of masked language modelling, so we recommend using it unless you're an advanced user!
We also use the jit_compile
argument to compile the model with XLA. XLA compilation adds a delay at the start of training, but this is quickly repaid by faster training iterations after that. It has one downside, though - if the shape of your input changes at all, then it will need to rerun the compilation again! This isn't a problem for us in this notebook, because all of our examples are exactly the same length. Be careful with it when that isn't true, though - if you have a variable sequence length in your batches, then you might spend more time compiling your model than actually training, especially for small datasets!
If you encounter difficulties when training with XLA, it's a good idea to remove the jit_compile
argument and see if that fixes things. In fact, when debugging, it can be helpful to skip graph compilation entirely with the run_eagerly=True
argument to compile()
. This will let you identify the exact line of code where problems arise, but it will significantly reduce your performance, so make sure to remove it again when you've fixed the problem!
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Input In [1], in <module>
1 import tensorflow as tf
----> 3 model.compile(optimizer=optimizer, jit_compile=True)
NameError: name 'model' is not defined
Next, we convert our datasets to tf.data.Dataset
, which Keras understands natively. There are two ways to do this - we can use the slightly more low-level Dataset.to_tf_dataset()
method, or we can use Model.prepare_tf_dataset()
. The main difference between these two is that the Model
method can inspect the model to determine which column names it can use as input, which means you don't need to specify them yourself. It also supplies a data collator by default which is appropriate for most tasks.
Now we can train our model. We can also add a callback to sync up our model with the Hub - this allows us to resume training from other machines and even test the model's inference quality midway through training! Make sure to change the username
if you do. If you don't want to do this, simply remove the callbacks argument in the call to fit()
.
Once the training is completed, we can evaluate our model and get its loss on the validation set like this:
The quality of language models is often measured in 'perplexity' rather than cross-entropy. To convert to perplexity, we simply raise e to the power of the cross-entropy loss.
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.
If you used the callback above, you can now share this model with all your friends, family or favorite pets: they can all load it with the identifier "your-username/the-name-you-picked"
so for instance:
Inference
Models trained from scratch on small amounts of data will generally not output useful text - you'll need a much bigger dataset and a much longer training time before it starts writing text that you'd want to read! If you want to see an example of inference with causal language models, see the language_modeling-tf
notebook, where we start with a pre-trained model and get higher-quality output much sooner as a result.
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 used before, with two exceptions. First we use a model suitable for masked LM:
We redefine our hyperparameters and choose a new name:
Now we initialize our optimizer.
And as before, we leave the loss
argument blank to use the internal loss, and use jit_compile
to enable XLA.
Finally, we use a special data_collator
. The data_collator
is a function that is responsible for 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 randomly mask tokens. 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. Note that our data collators are designed to work for multiple frameworks, so ensure you set the return_tensors='np'
argument to get NumPy arrays out - you don't want to accidentally get a load of torch.Tensor
objects in the middle of your nice TF code! You could also use return_tensors='tf'
to get TensorFlow tensors, but our TF dataset pipeline actually uses a NumPy loader internally, which is wrapped at the end with a tf.data.Dataset
. As a result, np
is usually more reliable and performant when you're using it!
Now we pass our data collator to the prepare_tf_dataset()
argument.
And now we can train our model:
Like before, we can evaluate our model on the validation set. As training progresses, the perplexity will be much lower for MLM 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.
If you used the callback above, you can now share this model with all your friends, family or favorite pets: they can all load it with the identifier "your-username/the-name-you-picked"
so for instance:
Inference
As with the causal LM above, masked language models trained from scratch on small amounts of data will generally not be very good at their job - you'll need a much bigger dataset and a much longer training time to make a truly useful one! If you want to see an example of inference with masked language models, see the language_modeling-tf
notebook, where we start with a pre-trained model and get higher-quality output much sooner as a result.