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-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 latest 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 run the following cell and input your token:
Then you need to install Git-LFS and setup Git if you haven't already. Uncomment the following instructions and adapt with your name and email:
Make sure your version of Transformers is at least 4.16.0 since some of the functionality we use was only 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.
Fine-tuning a language model
In this notebook, we'll see how to fine-tune one of the 🤗 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 masked tokens 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 Keras to fine-tune a model on it.
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 distilgpt2
model for this example. You can pick any of the checkpoints listed here instead:
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 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
up to the the maximum length our model was pretrained with, which for models in the gpt2
family is usually something in the range 512-1024. This might be a bit too big to fit in your GPU RAM, though, 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:
Once we've done that, it's time for our optimizer! We can initialize our AdamWeightDecay
optimizer directly, or we can use the create_optimizer
function to generate an AdamWeightDecay
optimizer with a learning rate schedule. In this case, we'll just stick with a constant learning rate for simplicity, so let's just use AdamWeightDecay
.
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!
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! If you don't want to do this, simply remove the callbacks argument in the call to fit()
.
1/1166 [..............................] - ETA: 5:26:28 - loss: 4.5466
1166/1166 [==============================] - 120s 89ms/step - loss: 3.8582 - val_loss: 3.6744
Once the training is completed, we can evaluate our model and get its cross-entropy 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.
If you saved the model with the callback, 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:
Inference
Now we've trained our model, let's see how we could load it and use it to generate text in future! First, let's load it from the hub. This means we can resume the code from here without needing to rerun everything above every time.
Now, let's make up a sentence and see if the model can continue it for us!
We'll need to tokenize our input(s) and then use the generate()
method.
Those are definitely tokens! We should probably turn them back into text so that we can read them:
This combination of quick, fluent responses with a complete incomprehension of the actual underlying facts will be familiar to anyone who's ever scrolled through their Twitter timeline. distilgpt2
is a very small LM compared to some others, and as you scale them up and train them for longer on larger datasets to get lower losses they often stop making errors as obvious as this one, but their tendency to confidently hallucinate their own "alternative facts" rather than admit ignorance never fully goes away, so bear this in mind before you deploy a generative language model in production!
Pipeline API
An alternative way to quickly perform inference with any model on the hub is to use the Pipeline API, which abstracts away all the steps we did manually above. It will perform the preprocessing, forward pass and postprocessing all in a single object.
Let's showcase this for our trained model:
Note that we got a different (and equally historically, uh, interesting) response this time! Because generate()
samples from the model's probability outputs each time, it can return multiple different outputs from the same starting text. If consistency is important to you, you can use parameters like temperature
to control how variable the outputs should be.
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).
We will use the distilroberta-base
model for this example. You can pick any of the checkpoints listed here instead:
We can apply the same tokenization function as before, we just need to update our tokenizer to use the checkpoint we just picked. Don't panic about the warnings about inputs being too long for the model - remember that we'll be breaking them into shorter chunks right afterwards!
And now, we group texts together and chunk them into samples of length block_size
. You can skip this 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 optimizer
as we did with the CLM model, and we compile the model. We're using the internal loss and jit_compile
again, like we did before.
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 generate our datasets as before. Remember to pass the data_collator
you just made to the collate_fn
argument.
And now we fit our model! As before, we can use a callback to sync with the hub during training. You can remove this if you don't want to!
1202/1202 [==============================] - 136s 99ms/step - loss: 1.8983 - val_loss: 1.6968
Like before, we can evaluate our model on the validation set and compute perplexity. 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.
If you used the callback, 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
Masked language models are not generally used directly for inference - the task they were trained on was to "fill in the blank", to identify missing words in sentences, and while this is an interesting demo, it has limited uses in production! However, masked language models work great as a base to be fine-tuned further on new tasks, like text or token classification. They are generally preferable to causal language models as a base for tasks that do not involve generating new text, and you'll see them being used as a base model in several other notebooks in this folder.
Still, if you're curious, you can do inference to see what your model learned! Let's use the fill-mask
pipeline and give the model some test sentences. Note that the mask token may not be "<mask>" in some other models - you can use tokenizer.mask_token
to find out what it is for your specific model if you're not using distilroberta
.
Nice! Let's see how it does on history:
Masked language models are often more accurate than causal language models because they can use information that comes after the masked position to help them, whereas causal models can only look back. This answer is definitely better than the answers from the causal LM above!