CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
huggingface

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

GitHub Repository: huggingface/notebooks
Path: blob/main/examples/language_modeling-tf.ipynb
Views: 2535
Kernel: Python 3 (ipykernel)

If you're opening this Notebook on colab, you will probably need to install 🤗 Transformers and 🤗 Datasets. Uncomment the following cell and run it.

#! 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 if you haven't already!) then run the following cell and input your token:

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:

# !apt install git-lfs # !git config --global user.email "[email protected]" # !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.

import transformers print(transformers.__version__)
4.21.0.dev0

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.

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 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

  • 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

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.

from datasets import load_dataset datasets = load_dataset("wikitext", "wikitext-2-raw-v1")
Reusing dataset wikitext (/home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/a241db52902eaf2c6aa732210bead40c090019a499ceb13bcbfa3f8ab646a126)

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:

# 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 for more information.

To access an actual element, you need to select a split first, then give an index:

datasets["train"][10]
{'text': ' The game \'s battle system , the BliTZ system , is carried over directly from Valkyira Chronicles . During missions , players select each unit using a top @-@ down perspective of the battlefield map : once a character is selected , the player moves the character around the battlefield in third @-@ person . A character can only act once per @-@ turn , but characters can be granted multiple turns at the expense of other characters \' turns . Each character has a field and distance of movement limited by their Action Gauge . Up to nine characters can be assigned to a single mission . During gameplay , characters will call out if something happens to them , such as their health points ( HP ) getting low or being knocked out by enemy attacks . Each character has specific " Potentials " , skills unique to each character . They are divided into " Personal Potential " , which are innate skills that remain unaltered unless otherwise dictated by the story and can either help or impede a character , and " Battle Potentials " , which are grown throughout the game and always grant boons to a character . To learn Battle Potentials , each character has a unique " Masters Table " , a grid @-@ based skill table that can be used to acquire and link different skills . Characters also have Special Abilities that grant them temporary boosts on the battlefield : Kurt can activate " Direct Command " and move around the battlefield without depleting his Action Point gauge , the character Reila can shift into her " Valkyria Form " and become invincible , while Imca can target multiple enemy units with her heavy weapon . \n'}

To get a sense of what the data looks like, the following function will show some examples picked randomly in the dataset.

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()))
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 model for this example. You can pick any of the checkpoints listed here instead:

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:

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 method from the Datasets library. First we define a function that calls the tokenizer on our texts:

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.

tokenized_datasets = datasets.map( tokenize_function, batched=True, num_proc=4, remove_columns=["text"] )
Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/a241db52902eaf2c6aa732210bead40c090019a499ceb13bcbfa3f8ab646a126/cache-92135046227bc72f.arrow
Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/a241db52902eaf2c6aa732210bead40c090019a499ceb13bcbfa3f8ab646a126/cache-c163bdd33bd446e0.arrow
Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/a241db52902eaf2c6aa732210bead40c090019a499ceb13bcbfa3f8ab646a126/cache-dd75e1e0708c3673.arrow
Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/a241db52902eaf2c6aa732210bead40c090019a499ceb13bcbfa3f8ab646a126/cache-982dabf6f315acbb.arrow

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:

tokenized_datasets["train"][1]
{'input_ids': [796, 569, 18354, 7496, 17740, 6711, 796, 220, 198], 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 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.

# block_size = tokenizer.model_max_length block_size = 128

Then we write the preprocessing function that will group our texts:

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:

lm_datasets = tokenized_datasets.map( group_texts, batched=True, batch_size=1000, num_proc=4, )
Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/a241db52902eaf2c6aa732210bead40c090019a499ceb13bcbfa3f8ab646a126/cache-9e50d524675c31d0.arrow
Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/a241db52902eaf2c6aa732210bead40c090019a499ceb13bcbfa3f8ab646a126/cache-2961c7eed0e1c293.arrow Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/a241db52902eaf2c6aa732210bead40c090019a499ceb13bcbfa3f8ab646a126/cache-1e0fca7b3861aea7.arrow
Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/a241db52902eaf2c6aa732210bead40c090019a499ceb13bcbfa3f8ab646a126/cache-5ac1197b188b71c5.arrow

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.

tokenizer.decode(lm_datasets["train"][1]["input_ids"])
' game and follows the " Nameless ", a penal military unit serving the nation of Gallia during the Second Europan War who perform secret black operations and are pitted against the Imperial unit " Calamaty Raven ". \n The game began development in 2010, carrying over a large portion of the work done on Valkyria Chronicles II. While it retained the standard features of the series, it also underwent multiple adjustments, such as making the game more forgiving for series newcomers. Character designer Raita Honjou and composer Hitoshi Sakimoto both returned from previous entries, along with Valkyria Chronicles II director Takeshi Oz'

Now that the data has been cleaned, we're ready to initialize our model:

from transformers import TFAutoModelForCausalLM model = TFAutoModelForCausalLM.from_pretrained(model_checkpoint)
2022-07-20 14:42:37.104406: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:975] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2022-07-20 14:42:37.141555: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:975] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2022-07-20 14:42:37.142578: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:975] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2022-07-20 14:42:37.144764: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX2 FMA To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags. 2022-07-20 14:42:37.147975: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:975] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2022-07-20 14:42:37.148652: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:975] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2022-07-20 14:42:37.149307: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:975] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2022-07-20 14:42:37.869776: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:975] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2022-07-20 14:42:37.870775: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:975] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2022-07-20 14:42:37.871753: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:975] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2022-07-20 14:42:37.872779: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1532] Created device /job:localhost/replica:0/task:0/device:GPU:0 with 21705 MB memory: -> device: 0, name: NVIDIA GeForce RTX 3090, pci bus id: 0000:21:00.0, compute capability: 8.6 2022-07-20 14:42:38.925211: I tensorflow/stream_executor/cuda/cuda_blas.cc:1786] TensorFloat-32 will be used for the matrix multiplication. This will only be logged once. All model checkpoint layers were used when initializing TFGPT2LMHeadModel. All the layers of TFGPT2LMHeadModel were initialized from the model checkpoint at distilgpt2. If your task is similar to the task the model of the checkpoint was trained on, you can already use TFGPT2LMHeadModel for predictions without further training.

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.

from transformers import create_optimizer, AdamWeightDecay
optimizer = AdamWeightDecay(lr=2e-5, weight_decay_rate=0.01)
/home/matt/miniconda3/envs/tensorflow28/lib/python3.10/site-packages/keras/optimizers/optimizer_v2/adam.py:110: UserWarning: The `lr` argument is deprecated, use `learning_rate` instead. super(Adam, self).__init__(name, **kwargs)

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!

import tensorflow as tf model.compile(optimizer=optimizer, jit_compile=True)
No loss specified in compile() - the model's internal loss computation will be used as the loss. Don't panic - this is a common way to train TensorFlow models in Transformers! To disable this behaviour please pass a loss argument, or explicitly pass `loss=None` if you do not want your model to compute a loss.

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.

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().

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)
/home/matt/PycharmProjects/notebooks/examples/clm_model_save is already a clone of https://huggingface.co/Rocketknight1/distilgpt2-finetuned-wikitext2. Make sure you pull the latest changes with `repo.git_pull()`. 2022-07-20 14:43:40.621522: I tensorflow/compiler/xla/service/service.cc:170] XLA service 0x55b0e1d74cd0 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices: 2022-07-20 14:43:40.621560: I tensorflow/compiler/xla/service/service.cc:178] StreamExecutor device (0): NVIDIA GeForce RTX 3090, Compute Capability 8.6 2022-07-20 14:43:40.793088: I tensorflow/compiler/mlir/tensorflow/utils/dump_mlir_util.cc:263] disabling MLIR crash reproducer, set env var `MLIR_CRASH_REPRODUCER_DIRECTORY` to enable. 2022-07-20 14:43:40.845975: W tensorflow/compiler/tf2xla/kernels/random_ops.cc:57] Warning: Using tf.random.uniform with XLA compilation will ignore seeds; consider using tf.random.stateless_uniform instead if reproducible behavior is desired. tfgpt2lm_head_model/transformer/dropout/dropout/random_uniform/RandomUniform
1/1166 [..............................] - ETA: 5:26:28 - loss: 4.5466
2022-07-20 14:43:51.668910: I tensorflow/compiler/jit/xla_compilation_cache.cc:478] Compiled cluster using XLA! This line is logged at most once for the lifetime of the process.
6/1166 [..............................] - ETA: 1:19 - loss: 4.4934WARNING:tensorflow:Callback method `on_train_batch_end` is slow compared to the batch time (batch time: 0.0153s vs `on_train_batch_end` time: 0.0725s). Check your callbacks. 1166/1166 [==============================] - ETA: 0s - loss: 3.8582
2022-07-20 14:45:14.179805: W tensorflow/compiler/tf2xla/kernels/assert_op.cc:38] Ignoring Assert operator tfgpt2lm_head_model/sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/assert_equal_1/Assert/Assert 2022-07-20 14:45:18.452953: W tensorflow/compiler/tf2xla/kernels/assert_op.cc:38] Ignoring Assert operator tfgpt2lm_head_model/sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/assert_equal_1/Assert/Assert Several commits (5) will be pushed upstream.
1166/1166 [==============================] - 120s 89ms/step - loss: 3.8582 - val_loss: 3.6744
<keras.callbacks.History at 0x7f377ca19a80>

Once the training is completed, we can evaluate our model and get its cross-entropy loss on the validation set like this:

eval_loss = model.evaluate(validation_set)
121/121 [==============================] - 3s 22ms/step - loss: 3.6744

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.

import math print(f"Perplexity: {math.exp(eval_loss):.2f}")
Perplexity: 39.43

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:

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.

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)
All model checkpoint layers were used when initializing TFGPT2LMHeadModel. All the layers of TFGPT2LMHeadModel were initialized from the model checkpoint at Rocketknight1/distilgpt2-finetuned-wikitext2. If your task is similar to the task the model of the checkpoint was trained on, you can already use TFGPT2LMHeadModel for predictions without further training.

Now, let's make up a sentence and see if the model can continue it for us!

test_sentence = "The Gulf War was a conflict between"

We'll need to tokenize our input(s) and then use the generate() method.

tokenized = tokenizer(test_sentence, return_tensors="np") outputs = model.generate(**tokenized, max_length=24) print(outputs)
Setting `pad_token_id` to 50256 (first `eos_token_id`) to generate sequence
tf.Tensor( [[ 464 12108 1810 373 257 5358 1022 262 1578 1829 290 262 7570 4479 326 15436 1566 262 886 286 2159 1810 2873 764]], shape=(1, 24), dtype=int32)

Those are definitely tokens! We should probably turn them back into text so that we can read them:

tokenizer.decode(outputs[0])
'The Gulf War was a conflict between the United States and the Soviet Union that lasted until the end of World War II.'

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:

from transformers import pipeline text_generator = pipeline( "text-generation", "Rocketknight1/distilgpt2-finetuned-wikitext2", framework="tf", )
All model checkpoint layers were used when initializing TFGPT2LMHeadModel. All the layers of TFGPT2LMHeadModel were initialized from the model checkpoint at Rocketknight1/distilgpt2-finetuned-wikitext2. If your task is similar to the task the model of the checkpoint was trained on, you can already use TFGPT2LMHeadModel for predictions without further training.
text_generator(test_sentence)
Setting `pad_token_id` to 50256 (first `eos_token_id`) to generate sequence
[{'generated_text': 'The Gulf War was a conflict between the U.S. and Turkey, which started in 1858. An Ottoman army entered the area and the British Army was overwhelmed, and reinforcements arrived. The Battle of Haga was fought between Ottoman forces and Turkish'}]

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:

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!

tokenizer = AutoTokenizer.from_pretrained(model_checkpoint) tokenized_datasets = datasets.map( tokenize_function, batched=True, num_proc=4, remove_columns=["text"] )
Token indices sequence length is longer than the specified maximum sequence length for this model (544 > 512). Running this sequence through the model will result in indexing errors
Token indices sequence length is longer than the specified maximum sequence length for this model (560 > 512). Running this sequence through the model will result in indexing errors Token indices sequence length is longer than the specified maximum sequence length for this model (528 > 512). Running this sequence through the model will result in indexing errors Token indices sequence length is longer than the specified maximum sequence length for this model (638 > 512). Running this sequence through the model will result in indexing errors Token indices sequence length is longer than the specified maximum sequence length for this model (522 > 512). Running this sequence through the model will result in indexing errors

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.

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:

from transformers import TFAutoModelForMaskedLM model = TFAutoModelForMaskedLM.from_pretrained(model_checkpoint)
All model checkpoint layers were used when initializing TFRobertaForMaskedLM. All the layers of TFRobertaForMaskedLM were initialized from the model checkpoint at distilroberta-base. If your task is similar to the task the model of the checkpoint was trained on, you can already use TFRobertaForMaskedLM for predictions without further training.

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.

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)
/home/matt/miniconda3/envs/tensorflow28/lib/python3.10/site-packages/keras/optimizers/optimizer_v2/adam.py:110: UserWarning: The `lr` argument is deprecated, use `learning_rate` instead. super(Adam, self).__init__(name, **kwargs) No loss specified in compile() - the model's internal loss computation will be used as the loss. Don't panic - this is a common way to train TensorFlow models in Transformers! To disable this behaviour please pass a loss argument, or explicitly pass `loss=None` if you do not want your model to compute a loss.

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!

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.

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!

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])
/home/matt/PycharmProjects/notebooks/examples/mlm_model_save is already a clone of https://huggingface.co/Rocketknight1/distilroberta-base-finetuned-wikitext2. Make sure you pull the latest changes with `repo.git_pull()`.
1202/1202 [==============================] - ETA: 0s - loss: 1.8983
2022-07-20 15:41:11.208542: W tensorflow/compiler/tf2xla/kernels/assert_op.cc:38] Ignoring Assert operator tf_roberta_for_masked_lm/sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/assert_equal_1/Assert/Assert 2022-07-20 15:41:15.777750: W tensorflow/compiler/tf2xla/kernels/assert_op.cc:38] Ignoring Assert operator tf_roberta_for_masked_lm/sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/assert_equal_1/Assert/Assert Several commits (4) will be pushed upstream.
1202/1202 [==============================] - 136s 99ms/step - loss: 1.8983 - val_loss: 1.6968
<keras.callbacks.History at 0x7f377d28f760>

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.

import math eval_results = model.evaluate(validation_set) print(f"Perplexity: {math.exp(eval_results):.2f}")
125/125 [==============================] - 3s 24ms/step - loss: 1.7174 Perplexity: 5.57

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:

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 "<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.

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", )
All model checkpoint layers were used when initializing TFRobertaForMaskedLM. All the layers of TFRobertaForMaskedLM were initialized from the model checkpoint at Rocketknight1/distilroberta-base-finetuned-wikitext2. If your task is similar to the task the model of the checkpoint was trained on, you can already use TFRobertaForMaskedLM for predictions without further training.
mask_filler("The most common household pets are <mask> and dogs.", top_k=1)
[{'score': 0.9744477868080139, 'token': 10017, 'token_str': ' cats', 'sequence': 'The most common household pets are cats and dogs.'}]

Nice! Let's see how it does on history:

mask_filler("The Gulf War was a conflict that took place in <mask> in 1990-1991.", top_k=3)
[{'score': 0.6171202659606934, 'token': 13857, 'token_str': ' Kuwait', 'sequence': 'The Gulf War was a conflict that took place in Kuwait in 1990-1991.'}, {'score': 0.07419946044683456, 'token': 3345, 'token_str': ' Iraq', 'sequence': 'The Gulf War was a conflict that took place in Iraq in 1990-1991.'}, {'score': 0.04156286269426346, 'token': 1854, 'token_str': ' Syria', 'sequence': 'The Gulf War was a conflict that took place in Syria in 1990-1991.'}]

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!