#!/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 transformers #! pip install datasets #! pip install huggingface_hub # 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](https://huggingface.co/join) if you haven't already!) then run the following cell and input your token: # In[ ]: from huggingface_hub import notebook_login notebook_login() # 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: # In[ ]: # !apt install git-lfs # !git config --global user.email "you@example.com" # !git config --global user.name "Your Name" # 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. # In[1]: 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="tensorflow") # # 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 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. # # ![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 masked tokens 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 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](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[2]: 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 your own input files: # In[3]: # 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[4]: 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[5]: 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[6]: 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, 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: # ``` # part of text 1 # ``` # or # ``` # end of text 1 [BOS_TOKEN] beginning of text 2 # ``` # 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`](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[7]: 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[8]: from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained(model_checkpoint) # 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 calls the tokenizer on our texts: # In[9]: 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[10]: 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[11]: tokenized_datasets["train"][1] # 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. # In[12]: # block_size = tokenizer.model_max_length block_size = 128 # Then we write the preprocessing function that will group our texts: # In[13]: 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, though you could add padding instead if the model supports it # In this, as in all things, we advise you to follow your heart 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 # 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: # In[14]: 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 several of our original texts. # In[15]: tokenizer.decode(lm_datasets["train"][1]["input_ids"]) # Now that the data has been cleaned, we're ready to initialize our model: # In[16]: from transformers import TFAutoModelForCausalLM model = TFAutoModelForCausalLM.from_pretrained(model_checkpoint) # 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`](https://huggingface.co/docs/transformers/main_classes/optimizer_schedules#transformers.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`. # In[17]: from transformers import create_optimizer, AdamWeightDecay # In[18]: optimizer = AdamWeightDecay(lr=2e-5, weight_decay_rate=0.01) # 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](https://www.tensorflow.org/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()`](https://www.tensorflow.org/api_docs/python/tf/keras/Model#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! # In[19]: import tensorflow as tf model.compile(optimizer=optimizer, jit_compile=True) # 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()`](https://huggingface.co/docs/datasets/package_reference/main_classes#datasets.Dataset.to_tf_dataset) method, or we can use [`Model.prepare_tf_dataset()`](https://huggingface.co/docs/transformers/main_classes/model#transformers.TFPreTrainedModel.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. # In[20]: train_set = model.prepare_tf_dataset( lm_datasets["train"], shuffle=True, batch_size=16, ) validation_set = model.prepare_tf_dataset( lm_datasets["validation"], shuffle=False, batch_size=16, ) # 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()`. # In[21]: from transformers.keras_callbacks import PushToHubCallback from tensorflow.keras.callbacks import TensorBoard model_name = model_checkpoint.split("/")[-1] push_to_hub_model_id = f"{model_name}-finetuned-wikitext2" tensorboard_callback = TensorBoard(log_dir="./clm_model_save/logs") push_to_hub_callback = PushToHubCallback( output_dir="./clm_model_save", tokenizer=tokenizer, hub_model_id=push_to_hub_model_id, ) callbacks = [tensorboard_callback, push_to_hub_callback] model.fit(train_set, validation_data=validation_set, epochs=1, callbacks=callbacks) # Once the training is completed, we can evaluate our model and get its cross-entropy loss on the validation set like this: # In[22]: eval_loss = model.evaluate(validation_set) # 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. # In[23]: import math print(f"Perplexity: {math.exp(eval_loss):.2f}") # 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: # # ```python # from transformers import AutoModelForCausalLM # # model = AutoModelForCausalLM.from_pretrained("sgugger/my-awesome-model") # ``` # ## 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. # In[26]: from transformers import AutoTokenizer, TFAutoModelForCausalLM # You can, of course, use your own username and model name here # once you've pushed your model using the code above! checkpoint = "Rocketknight1/distilgpt2-finetuned-wikitext2" model = TFAutoModelForCausalLM.from_pretrained(checkpoint) tokenizer = AutoTokenizer.from_pretrained(checkpoint) # Now, let's make up a sentence and see if the model can continue it for us! # In[62]: test_sentence = "The Gulf War was a conflict between" # We'll need to tokenize our input(s) and then use the `generate()` method. # In[63]: tokenized = tokenizer(test_sentence, return_tensors="np") outputs = model.generate(**tokenized, max_length=24) print(outputs) # Those are definitely tokens! We should probably turn them back into text so that we can read them: # In[64]: tokenizer.decode(outputs[0]) # 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](https://huggingface.co/docs/transformers/main_classes/pipelines), 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: # In[66]: from transformers import pipeline text_generator = pipeline( "text-generation", "Rocketknight1/distilgpt2-finetuned-wikitext2", framework="tf", ) # In[75]: text_generator(test_sentence) # Note that we got a different (and equally historically, uh, interesting) response this time! Because [`generate()`](https://huggingface.co/docs/transformers/v4.20.1/en/main_classes/text_generation#transformers.generation_tf_utils.TFGenerationMixin.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`](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[76]: 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. 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! # In[77]: tokenizer = AutoTokenizer.from_pretrained(model_checkpoint) tokenized_datasets = datasets.map( tokenize_function, batched=True, num_proc=4, remove_columns=["text"] ) # 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. # In[78]: 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[79]: from transformers import TFAutoModelForMaskedLM model = TFAutoModelForMaskedLM.from_pretrained(model_checkpoint) # 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. # In[80]: from transformers import create_optimizer, AdamWeightDecay import tensorflow as tf optimizer = AdamWeightDecay(lr=2e-5, weight_decay_rate=0.01) model.compile(optimizer=optimizer, jit_compile=True) # 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! # In[81]: from transformers import DataCollatorForLanguageModeling data_collator = DataCollatorForLanguageModeling( tokenizer=tokenizer, mlm_probability=0.15, return_tensors="np" ) # Now we generate our datasets as before. Remember to pass the `data_collator` you just made to the `collate_fn` argument. # In[82]: train_set = model.prepare_tf_dataset( lm_datasets["train"], shuffle=True, batch_size=16, collate_fn=data_collator, ) validation_set = model.prepare_tf_dataset( lm_datasets["validation"], shuffle=False, batch_size=16, collate_fn=data_collator, ) # 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! # In[83]: from transformers.keras_callbacks import PushToHubCallback model_name = model_checkpoint.split("/")[-1] push_to_hub_model_id = f"{model_name}-finetuned-wikitext2" callback = PushToHubCallback( output_dir="./mlm_model_save", tokenizer=tokenizer, hub_model_id=push_to_hub_model_id, ) model.fit(train_set, validation_data=validation_set, epochs=1, callbacks=[callback]) # 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. # In[84]: import math eval_results = model.evaluate(validation_set) print(f"Perplexity: {math.exp(eval_results):.2f}") # 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: # # ```python # from transformers import AutoModelForMaskedLM # # model = AutoModelForMaskedLM.from_pretrained("your-username/my-awesome-model") # ``` # ## 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 "\" 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`. # In[86]: from transformers import pipeline # You can of course use your own model checkpoint here instead of mine mask_filler = pipeline( "fill-mask", "Rocketknight1/distilroberta-base-finetuned-wikitext2", framework="tf", ) # In[90]: mask_filler("The most common household pets are and dogs.", top_k=1) # Nice! Let's see how it does on history: # In[98]: mask_filler("The Gulf War was a conflict that took place in in 1990-1991.", top_k=3) # 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! # In[ ]: