#!/usr/bin/env python # coding: utf-8 # If you're opening this Notebook on colab, you will probably need to install 🤗 Transformers and 🤗 Datasets. Uncomment the following cell and run it. # In[ ]: #! pip install datasets transformers # 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](https://huggingface.co/join) if you haven't already!) then execute the following cell and input your username and password: # In[ ]: from huggingface_hub import notebook_login notebook_login() # Then you need to install Git-LFS. Uncomment the following instructions: # In[ ]: # !apt install git-lfs # Make sure your version of Transformers is at least 4.11.0 since the functionality was introduced in that version: # In[ ]: import transformers print(transformers.__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](https://github.com/huggingface/transformers/tree/master/examples/language-modeling). # 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. # In[ ]: from transformers.utils import send_example_telemetry send_example_telemetry("language_modeling_notebook", framework="pytorch") # # Fine-tuning a language model # In this notebook, we'll see how to fine-tune one of the [🤗 Transformers](https://github.com/huggingface/transformers) model on a language modeling tasks. 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. # # ![Widget inference representing the causal language modeling task](images/causal_language_modeling.png) # # - 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. # # ![Widget inference representing the masked language modeling task](images/masked_language_modeling.png) # # 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 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](https://github.com/huggingface/transformers/tree/master/examples). # ## 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. # In[ ]: from datasets import load_dataset datasets = load_dataset('wikitext', 'wikitext-2-raw-v1') # You can replace the dataset above with any dataset hosted on [the hub](https://huggingface.co/datasets) or use your own files. Just uncomment the following cell and replace the paths with values that will lead to your files: # In[ ]: # datasets = load_dataset("text", data_files={"train": path_to_train.txt, "validation": path_to_validation.txt} # You can also load datasets from a csv or a JSON file, see the [full documentation](https://huggingface.co/docs/datasets/loading_datasets.html#from-local-files) for more information. # To access an actual element, you need to select a split first, then give an index: # In[ ]: datasets["train"][10] # To get a sense of what the data looks like, the following function will show some examples picked randomly in the dataset. # In[ ]: from datasets import ClassLabel import random import pandas as pd from IPython.display import display, HTML def show_random_elements(dataset, num_examples=10): assert num_examples <= len(dataset), "Can't pick more elements than there are in the dataset." picks = [] for _ in range(num_examples): pick = random.randint(0, len(dataset)-1) while pick in picks: pick = random.randint(0, len(dataset)-1) picks.append(pick) df = pd.DataFrame(dataset[picks]) for column, typ in dataset.features.items(): if isinstance(typ, ClassLabel): df[column] = df[column].transform(lambda i: typ.names[i]) display(HTML(df.to_html())) # In[ ]: show_random_elements(datasets["train"]) # 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: # ``` # part of text 1 # ``` # or # ``` # end of text 1 [BOS_TOKEN] beginning of text 2 # ``` # 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 [`distilgpt2`](https://huggingface.co/distilgpt2) model for this example. You can pick any of the checkpoints listed [here](https://huggingface.co/models?filter=causal-lm) instead: # In[ ]: model_checkpoint = "distilgpt2" # 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: # In[ ]: from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained(model_checkpoint, use_fast=True) # We can now call the tokenizer on all our texts. This is very simple, using the [`map`](https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.map) method from the Datasets library. First we define a function that call the tokenizer on our texts: # In[ ]: def tokenize_function(examples): return tokenizer(examples["text"]) # 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. # In[ ]: tokenized_datasets = datasets.map(tokenize_function, batched=True, num_proc=4, remove_columns=["text"]) # 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: # In[ ]: tokenized_datasets["train"][1] # 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. # In[ ]: # block_size = tokenizer.model_max_length block_size = 128 # Then we write the preprocessing function that will group our texts: # In[ ]: def group_texts(examples): # Concatenate all texts. concatenated_examples = {k: sum(examples[k], []) for k in examples.keys()} total_length = len(concatenated_examples[list(examples.keys())[0]]) # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can # customize this part to your needs. total_length = (total_length // block_size) * block_size # Split by chunks of max_len. result = { k: [t[i : i + block_size] for i in range(0, total_length, block_size)] for k, t in concatenated_examples.items() } result["labels"] = result["input_ids"].copy() return result # 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: # In[ ]: lm_datasets = tokenized_datasets.map( group_texts, batched=True, batch_size=1000, num_proc=4, ) # 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. # In[ ]: tokenizer.decode(lm_datasets["train"][1]["input_ids"]) # Now that the data has been cleaned, we're ready to instantiate our `Trainer`. We will a model: # In[ ]: from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained(model_checkpoint) # And some `TrainingArguments`: # In[ ]: from transformers import Trainer, TrainingArguments # In[ ]: model_name = model_checkpoint.split("/")[-1] training_args = TrainingArguments( f"{model_name}-finetuned-wikitext2", evaluation_strategy = "epoch", learning_rate=2e-5, weight_decay=0.01, push_to_hub=True, ) # The last argument to setup everything so we can push the model to the [Hub](https://huggingface.co/models) 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: # In[ ]: trainer = Trainer( model=model, args=training_args, train_dataset=lm_datasets["train"], eval_dataset=lm_datasets["validation"], ) # And we can train our model: # In[ ]: trainer.train() # Once the training is completed, we can evaluate our model and get its perplexity on the validation set like this: # In[ ]: import math eval_results = trainer.evaluate() print(f"Perplexity: {math.exp(eval_results['eval_loss']):.2f}") # You can now upload the result of the training to the Hub, just execute this instruction: # In[ ]: trainer.push_to_hub() # 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: # # ```python # from transformers import AutoModelForCausalLM # # model = AutoModelForCausalLM.from_pretrained("sgugger/my-awesome-model") # ``` # ## 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`](https://huggingface.co/distilroberta-base) model for this example. You can pick any of the checkpoints listed [here](https://huggingface.co/models?filter=masked-lm) instead: # In[ ]: model_checkpoint = "distilroberta-base" # We can apply the same tokenization function as before, we just need to update our tokenizer to use the checkpoint we just picked: # In[ ]: tokenizer = AutoTokenizer.from_pretrained(model_checkpoint, use_fast=True) tokenized_datasets = datasets.map(tokenize_function, batched=True, num_proc=4, remove_columns=["text"]) # 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. # In[ ]: lm_datasets = tokenized_datasets.map( group_texts, batched=True, batch_size=1000, num_proc=4, ) # The rest is very similar to what we had, with two exceptions. First we use a model suitable for masked LM: # In[ ]: from transformers import AutoModelForMaskedLM model = AutoModelForMaskedLM.from_pretrained(model_checkpoint) # We redefine our `TrainingArguments`: # In[ ]: model_name = model_checkpoint.split("/")[-1] training_args = TrainingArguments( f"{model_name}-finetuned-wikitext2", evaluation_strategy = "epoch", learning_rate=2e-5, weight_decay=0.01, push_to_hub=True, ) # Like before, the last argument to setup everything so we can push the model to the [Hub](https://huggingface.co/models) 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/bert-finetuned-wikitext2"` or `"huggingface/bert-finetuned-wikitext2"`). # 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: # In[ ]: from transformers import DataCollatorForLanguageModeling data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm_probability=0.15) # Then we just have to pass everything to `Trainer` and begin training: # In[ ]: trainer = Trainer( model=model, args=training_args, train_dataset=lm_datasets["train"], eval_dataset=lm_datasets["validation"], data_collator=data_collator, ) # In[ ]: trainer.train() # 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. # In[ ]: eval_results = trainer.evaluate() print(f"Perplexity: {math.exp(eval_results['eval_loss']):.2f}") # You can now upload the result of the training to the Hub, just execute this instruction: # In[ ]: trainer.push_to_hub() # 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: # # ```python # from transformers import AutoModelForMaskedLM # # model = AutoModelForMaskedLM.from_pretrained("sgugger/my-awesome-model") # ``` # In[ ]: