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_from_scratch-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 datasets huggingface_hub

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 if you haven't already!) then uncomment 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. On Linux, uncomment the following instructions and adapt with your name and email. On Windows, please download git-lfs at https://git-lfs.github.com/

# !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 introduced in that version:

import transformers print(transformers.__version__)
4.16.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_from_scratch_notebook", framework="tensorflow")

Train a language model

In this notebook, we'll see how to train a 🤗 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 tokens masked 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 the Trainer API to train a model on it.

This notebooks assumes you have trained a tokenizer on the corpus you are using, see the How to train a tokenizer notebook (open in colab).

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 gpt2 architecture for this example. You can pick any of the checkpoints listed here instead. For the tokenizer, you can optionally replace the checkpoint with one that you trained yourself.

model_checkpoint = "gpt2" tokenizer_checkpoint = "sgugger/gpt2-like-tokenizer"
from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained(tokenizer_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"] )

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]
{'attention_mask': [1, 1, 1, 1, 1, 1], 'input_ids': [238, 8576, 9441, 2987, 238, 252]}

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, but high values might be too big to fit in your GPU RAM, 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, 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

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

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"])
' 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 Ozawa. A large'

Now that the data has been cleaned, we're ready to initialize our Model. First we create the model using the same config as our checkpoint, but initialized with random weights:

from transformers import AutoConfig, TFAutoModelForCausalLM config = AutoConfig.from_pretrained(model_checkpoint) model = TFAutoModelForCausalLM.from_config(config)
2022-01-28 14:15:22.987842: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:936] 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-01-28 14:15:22.992329: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:936] 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-01-28 14:15:22.993015: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:936] 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-01-28 14:15:22.994216: I tensorflow/core/platform/cpu_feature_guard.cc:151] 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-01-28 14:15:22.997035: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:936] 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-01-28 14:15:22.997704: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:936] 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-01-28 14:15:22.998354: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:936] 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-01-28 14:15:23.362585: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:936] 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-01-28 14:15:23.363296: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:936] 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-01-28 14:15:23.363929: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:936] 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-01-28 14:15:23.364557: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1525] Created device /job:localhost/replica:0/task:0/device:GPU:0 with 21827 MB memory: -> device: 0, name: GeForce RTX 3090, pci bus id: 0000:21:00.0, compute capability: 8.6 2022-01-28 14:15:23.539334: W tensorflow/python/util/util.cc:368] Sets are not currently considered sequences, but this may change in the future, so consider avoiding using them.

Now let's set some hyperparameters like the learning rate and weight decay, as well as the model ID, if we want to upload our model to the Hub afterwards.

learning_rate = 2e-5 weight_decay = 0.01 push_to_hub_model_id = f"{model_checkpoint}-wikitext2"

Now we initialize our optimizer.

from transformers import AdamWeightDecay optimizer = AdamWeightDecay(learning_rate=learning_rate, weight_decay_rate=weight_decay)

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)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Input In [1], in <module> 1 import tensorflow as tf ----> 3 model.compile(optimizer=optimizer, jit_compile=True) NameError: name 'model' is not defined

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! Make sure to change the username if you do. If you don't want to do this, simply remove the callbacks argument in the call to fit().

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="./clm_from_scratch_model_save", tokenizer=tokenizer, hub_model_id=push_to_hub_model_id, ) model.fit(train_set, validation_data=validation_set, epochs=2, callbacks=[callback])
/home/matt/PycharmProjects/notebooks/examples/clm_from_scratch_model_save is already a clone of https://huggingface.co/Rocketknight1/gpt2-finetuned-wikitext2. Make sure you pull the latest changes with `repo.git_pull()`.
Epoch 1/2 1/1124 [..............................] - ETA: 3:31:23 - loss: 10.9357
2022-01-28 14:15:38.103602: I tensorflow/stream_executor/cuda/cuda_blas.cc:1786] TensorFloat-32 will be used for the matrix multiplication. This will only be logged once.
1124/1124 [==============================] - 207s 174ms/step - loss: 7.3186 - val_loss: 6.7745 Epoch 2/2 1124/1124 [==============================] - 193s 171ms/step - loss: 6.4996 - val_loss: 6.3490
<keras.callbacks.History at 0x7f099c669d50>

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

eval_loss = model.evaluate(validation_set)
121/121 [==============================] - 6s 51ms/step - loss: 6.3490

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

The perplexity is still quite high since for this demo we trained on a small dataset for a small number of epochs. For a real LM training, you would need a larger dataset and more epochs.

If you used the callback above, 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 TFAutoModelForCausalLM model = TFAutoModelForCausalLM.from_pretrained("your-username/my-awesome-model")

Inference

Models trained from scratch on small amounts of data will generally not output useful text - you'll need a much bigger dataset and a much longer training time before it starts writing text that you'd want to read! If you want to see an example of inference with causal language models, see the language_modeling-tf notebook, where we start with a pre-trained model and get higher-quality output much sooner as a result.

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). If you use a tokenizer you trained yourself, make sure the [MASK] token is among the special tokens you passed during training!

We will use the bert-base-cased model for this example. You can pick any of the checkpoints listed here instead. For the tokenizer, replace the checkpoint by the one you trained.

model_checkpoint = "bert-base-cased"

We can apply the same tokenization function as before, we just need to update our tokenizer to use the checkpoint we just picked:

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 (571 > 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 (554 > 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 Token indices sequence length is longer than the specified maximum sequence length for this model (657 > 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 (514 > 512). Running this sequence through the model will result in indexing errors

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.

lm_datasets = tokenized_datasets.map( group_texts, batched=True, batch_size=1000, num_proc=4, )

The rest is very similar to what we used before, with two exceptions. First we use a model suitable for masked LM:

from transformers import AutoConfig, TFAutoModelForMaskedLM config = AutoConfig.from_pretrained(model_checkpoint) model = TFAutoModelForMaskedLM.from_config(config)

We redefine our hyperparameters and choose a new name:

learning_rate = 2e-5 weight_decay = 0.01 push_to_hub_model_id = f"{model_checkpoint}-wikitext2"

Now we initialize our optimizer.

from transformers import AdamWeightDecay optimizer = AdamWeightDecay(learning_rate=learning_rate, weight_decay_rate=weight_decay)

And as before, we leave the loss argument blank to use the internal loss, and use jit_compile to enable XLA.

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! Please ensure your labels are passed as keys in the input dict so that they are accessible to the model during the forward pass. 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 pass our data collator to the prepare_tf_dataset() 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 can train our model:

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="./mlm_from_scratch_model_save/logs") push_to_hub_callback = PushToHubCallback( output_dir="./mlm_from_scratch_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=2, callbacks=callbacks)
/home/matt/PycharmProjects/notebooks/examples/mlm_from_scratch_model_save is already a clone of https://huggingface.co/Rocketknight1/bert-base-cased-finetuned-wikitext2. Make sure you pull the latest changes with `repo.git_pull()`.
Epoch 1/2 6/1172 [..............................] - ETA: 2:36 - loss: 9.9268WARNING:tensorflow:Callback method `on_train_batch_end` is slow compared to the batch time (batch time: 0.0903s vs `on_train_batch_end` time: 0.1139s). Check your callbacks. 1172/1172 [==============================] - 197s 159ms/step - loss: 7.0794 - val_loss: 6.5111 Epoch 2/2 1172/1172 [==============================] - 186s 159ms/step - loss: 6.4127 - val_loss: 6.2672
<keras.callbacks.History at 0x7f099c703e80>

Like before, we can evaluate our model on the validation set. As training progresses, the perplexity will be much lower for MLM 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.

eval_loss = model.evaluate(validation_set) print(f"Perplexity: {math.exp(eval_loss):.2f}")
126/126 [==============================] - 6s 44ms/step - loss: 6.2834 Perplexity: 535.62

The perplexity is still quite high since for this demo we trained on a small dataset for a small number of epochs. For a real LM training, you would need a larger dataset and more epochs.

If you used the callback above, 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 TFAutoModelForMaskedLM model = TFAutoModelForMaskedLM.from_pretrained("your-username/my-awesome-model")

Inference

As with the causal LM above, masked language models trained from scratch on small amounts of data will generally not be very good at their job - you'll need a much bigger dataset and a much longer training time to make a truly useful one! If you want to see an example of inference with masked language models, see the language_modeling-tf notebook, where we start with a pre-trained model and get higher-quality output much sooner as a result.