Causal language modeling
There are two types of language modeling, causal and masked. This guide illustrates causal language modeling. Causal language models are frequently used for text generation. You can use these models for creative applications like choosing your own text adventure or an intelligent coding assistant like Copilot or CodeParrot.
Causal language modeling predicts the next token in a sequence of tokens, and the model can only attend to tokens on the left. This means the model cannot see future tokens. GPT-2 is an example of a causal language model.
This guide will show you how to:
Finetune DistilGPT2 on the r/askscience subset of the ELI5 dataset.
Use your finetuned model for inference.
You can finetune other architectures for causal language modeling following the same steps in this guide. Choose one of the following architectures:
BART, BERT, Bert Generation, BigBird, BigBird-Pegasus, BioGpt, Blenderbot, BlenderbotSmall, BLOOM, CamemBERT, CodeLlama, CodeGen, CPM-Ant, CTRL, Data2VecText, ELECTRA, ERNIE, Falcon, GIT, GPT-Sw3, OpenAI GPT-2, GPTBigCode, GPT Neo, GPT NeoX, GPT NeoX Japanese, GPT-J, LLaMA, Marian, mBART, MEGA, Megatron-BERT, Mistral, MPT, MusicGen, MVP, OpenLlama, OpenAI GPT, OPT, Pegasus, Persimmon, PLBart, ProphetNet, QDQBert, Reformer, RemBERT, RoBERTa, RoBERTa-PreLayerNorm, RoCBert, RoFormer, RWKV, Speech2Text2, Transformer-XL, TrOCR, XGLM, XLM, XLM-ProphetNet, XLM-RoBERTa, XLM-RoBERTa-XL, XLNet, X-MOD
Before you begin, make sure you have all the necessary libraries installed:
Copied
pip install transformers datasets evaluateWe encourage you to log in to your BOINC AI account so you can upload and share your model with the community. When prompted, enter your token to log in:
Copied
>>> from boincai_hub import notebook_login
>>> notebook_login()Load ELI5 dataset
Start by loading a smaller subset of the r/askscience subset of the ELI5 dataset from the π Datasets library. Thisβll give you a chance to experiment and make sure everything works before spending more time training on the full dataset.
Copied
Split the datasetβs train_asks split into a train and test set with the train_test_split method:
Copied
Then take a look at an example:
Copied
While this may look like a lot, youβre only really interested in the text field. Whatβs cool about language modeling tasks is you donβt need labels (also known as an unsupervised task) because the next word is the label.
Preprocess
The next step is to load a DistilGPT2 tokenizer to process the text subfield:
Copied
Youβll notice from the example above, the text field is actually nested inside answers. This means youβll need to extract the text subfield from its nested structure with the flatten method:
Copied
Each subfield is now a separate column as indicated by the answers prefix, and the text field is a list now. Instead of tokenizing each sentence separately, convert the list to a string so you can jointly tokenize them.
Here is a first preprocessing function to join the list of strings for each example and tokenize the result:
Copied
To apply this preprocessing function over the entire dataset, use the π Datasets map method. You can speed up the map function by setting batched=True to process multiple elements of the dataset at once, and increasing the number of processes with num_proc. Remove any columns you donβt need:
Copied
This dataset contains the token sequences, but some of these are longer than the maximum input length for the model.
You can now use a second preprocessing function to
concatenate all the sequences
split the concatenated sequences into shorter chunks defined by
block_size, which should be both shorter than the maximum input length and short enough for your GPU RAM.
Copied
Apply the group_texts function over the entire dataset:
Copied
Now create a batch of examples using DataCollatorForLanguageModeling. Itβs more efficient to dynamically pad the sentences to the longest length in a batch during collation, instead of padding the whole dataset to the maximum length.
PytorchHide Pytorch content
Use the end-of-sequence token as the padding token and set mlm=False. This will use the inputs as labels shifted to the right by one element:
Copied
TensorFlowHide TensorFlow content
Use the end-of-sequence token as the padding token and set mlm=False. This will use the inputs as labels shifted to the right by one element:
Copied
Train
PytorchHide Pytorch content
If you arenβt familiar with finetuning a model with the Trainer, take a look at the basic tutorial!
Youβre ready to start training your model now! Load DistilGPT2 with AutoModelForCausalLM:
Copied
At this point, only three steps remain:
Define your training hyperparameters in TrainingArguments. The only required parameter is
output_dirwhich specifies where to save your model. Youβll push this model to the Hub by settingpush_to_hub=True(you need to be signed in to BOINC AI to upload your model).Pass the training arguments to Trainer along with the model, datasets, and data collator.
Call train() to finetune your model.
Copied
Once training is completed, use the evaluate() method to evaluate your model and get its perplexity:
Copied
Then share your model to the Hub with the push_to_hub() method so everyone can use your model:
Copied
TensorFlowHide TensorFlow content
If you arenβt familiar with finetuning a model with Keras, take a look at the basic tutorial!
To finetune a model in TensorFlow, start by setting up an optimizer function, learning rate schedule, and some training hyperparameters:Copied
Then you can load DistilGPT2 with TFAutoModelForCausalLM:
Copied
Convert your datasets to the tf.data.Dataset format with prepare_tf_dataset():
Copied
Configure the model for training with compile. Note that Transformers models all have a default task-relevant loss function, so you donβt need to specify one unless you want to:
Copied
This can be done by specifying where to push your model and tokenizer in the PushToHubCallback:
Copied
Finally, youβre ready to start training your model! Call fit with your training and validation datasets, the number of epochs, and your callback to finetune the model:
Copied
Once training is completed, your model is automatically uploaded to the Hub so everyone can use it!
For a more in-depth example of how to finetune a model for causal language modeling, take a look at the corresponding PyTorch notebook or TensorFlow notebook.
Inference
Great, now that youβve finetuned a model, you can use it for inference!
Come up with a prompt youβd like to generate text from:
Copied
The simplest way to try out your finetuned model for inference is to use it in a pipeline(). Instantiate a pipeline for text generation with your model, and pass your text to it:
Copied
PytorchHide Pytorch content
Tokenize the text and return the input_ids as PyTorch tensors:
Copied
Use the generate() method to generate text. For more details about the different text generation strategies and parameters for controlling generation, check out the Text generation strategies page.
Copied
Decode the generated token ids back into text:
Copied
TensorFlowHide TensorFlow content
Tokenize the text and return the input_ids as TensorFlow tensors:
Copied
Use the generate() method to create the summarization. For more details about the different text generation strategies and parameters for controlling generation, check out the Text generation strategies page.
Copied
Decode the generated token ids back into text:
Copied
Last updated