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 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 if you haven't already!) then execute the following cell and input your username and password:
from huggingface_hub import notebook_login
notebook_login()
Then you need to install Git-LFS. Uncomment the following instructions:
# !apt install git-lfs
Make sure your version of Transformers is at least 4.11.0 since the functionality was introduced in that version:
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.
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="pytorch")
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:
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.
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/sgugger/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/aa5e094000ec7afeb74c3be92c88313cd6f132d564c7effd961c10fd47c76f20)
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 values that will lead to your 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"])
text | |
---|---|
0 | = 7 / 2 ) suppresses the superconductivity , which is induced by eliminating this local moment ( J = \n |
1 | On his Chelsea debut away at Manchester United , McNichol found himself playing at right back after ten minutes when Sid Tickridge sustained an injury . Once restored to the forward line , his goals helped Chelsea avoid relegation to the Second Division at the end of his first season . A " dramatic last @-@ minute goal ... enabled Chelsea to snatch a lucky victory at West Bromwich " with three games left , and he scored the third goal of Chelsea 's 3 – 1 defeat of Manchester City in their last fixture of the season which confirmed their escape from the relegation positions . \n |
2 | = = = Manpower = = = \n |
3 | |
4 | The ironic interpretations of " Ulysses " may be the result of the modern tendency to consider the narrator of a dramatic monologue as necessarily " unreliable " . According to critic Dwight Culler , the poem has been a victim of revisionist readings in which the reader expects to reconstruct the truth from a misleading narrator 's accidental revelations . ( Compare the more obvious use of this approach in Robert Browning 's " My Last Duchess " . ) Culler himself views " Ulysses " as a dialectic in which the speaker weighs the virtues of a contemplative and an active approach to life ; Ulysses moves through four emotional stages that are self @-@ revelatory , not ironic : beginning with his rejection of the barren life to which he has returned in Ithaca , he then fondly recalls his heroic past , recognizes the validity of Telemachus ' method of governing , and with these thoughts plans another journey . \n |
5 | |
6 | = = Legacy = = \n |
7 | |
8 | |
9 | = = Exit list = = \n |
As we can see, some of the texts are a full paragraph of a Wikipedia article while others are just titles or empty lines.
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 gpt2
architecture for this example. You can pick any of the checkpoints listed here instead. For the tokenizer, you can replace the checkpoint by the one you trained yourself.
model_checkpoint = "gpt2"
tokenizer_checkpoint = "sgugger/gpt2-like-tokenizer"
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(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 call 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 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.
# 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
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:
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.
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 instantiate our Trainer
. First we create the model using the same config as our checkpoint, but initialized with random weights:
from transformers import AutoConfig, AutoModelForCausalLM
config = AutoConfig.from_pretrained(model_checkpoint)
model = AutoModelForCausalLM.from_config(config)
And we will needsome TrainingArguments
:
from transformers import Trainer, TrainingArguments
training_args = TrainingArguments(
f"{model_checkpoint}-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 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:
trainer = Trainer(
model=model,
args=training_args,
train_dataset=lm_datasets["train"],
eval_dataset=lm_datasets["validation"],
)
And we can train our model:
trainer.train()
***** Running training ***** Num examples = 17991 Num Epochs = 3 Instantaneous batch size per device = 8 Total train batch size (w. parallel, distributed & accumulation) = 8 Gradient Accumulation steps = 1 Total optimization steps = 6747
Epoch | Training Loss | Validation Loss |
---|---|---|
1 | 6.748400 | 6.652853 |
2 | 6.404400 | 6.388820 |
3 | 6.244400 | 6.314827 |
Saving model checkpoint to test-clm/checkpoint-500 Configuration saved in test-clm/checkpoint-500/config.json Model weights saved in test-clm/checkpoint-500/pytorch_model.bin Saving model checkpoint to test-clm/checkpoint-1000 Configuration saved in test-clm/checkpoint-1000/config.json Model weights saved in test-clm/checkpoint-1000/pytorch_model.bin Saving model checkpoint to test-clm/checkpoint-1500 Configuration saved in test-clm/checkpoint-1500/config.json Model weights saved in test-clm/checkpoint-1500/pytorch_model.bin Saving model checkpoint to test-clm/checkpoint-2000 Configuration saved in test-clm/checkpoint-2000/config.json Model weights saved in test-clm/checkpoint-2000/pytorch_model.bin ***** Running Evaluation ***** Num examples = 1934 Batch size = 8 Saving model checkpoint to test-clm/checkpoint-2500 Configuration saved in test-clm/checkpoint-2500/config.json Model weights saved in test-clm/checkpoint-2500/pytorch_model.bin Saving model checkpoint to test-clm/checkpoint-3000 Configuration saved in test-clm/checkpoint-3000/config.json Model weights saved in test-clm/checkpoint-3000/pytorch_model.bin Saving model checkpoint to test-clm/checkpoint-3500 Configuration saved in test-clm/checkpoint-3500/config.json Model weights saved in test-clm/checkpoint-3500/pytorch_model.bin Saving model checkpoint to test-clm/checkpoint-4000 Configuration saved in test-clm/checkpoint-4000/config.json Model weights saved in test-clm/checkpoint-4000/pytorch_model.bin ***** Running Evaluation ***** Num examples = 1934 Batch size = 8 Saving model checkpoint to test-clm/checkpoint-4500 Configuration saved in test-clm/checkpoint-4500/config.json Model weights saved in test-clm/checkpoint-4500/pytorch_model.bin Saving model checkpoint to test-clm/checkpoint-5000 Configuration saved in test-clm/checkpoint-5000/config.json Model weights saved in test-clm/checkpoint-5000/pytorch_model.bin Saving model checkpoint to test-clm/checkpoint-5500 Configuration saved in test-clm/checkpoint-5500/config.json Model weights saved in test-clm/checkpoint-5500/pytorch_model.bin Saving model checkpoint to test-clm/checkpoint-6000 Configuration saved in test-clm/checkpoint-6000/config.json Model weights saved in test-clm/checkpoint-6000/pytorch_model.bin Saving model checkpoint to test-clm/checkpoint-6500 Configuration saved in test-clm/checkpoint-6500/config.json Model weights saved in test-clm/checkpoint-6500/pytorch_model.bin ***** Running Evaluation ***** Num examples = 1934 Batch size = 8 Training completed. Do not forget to share your model on huggingface.co/models =)
TrainOutput(global_step=6747, training_loss=6.595932285008615, metrics={'train_runtime': 827.616, 'train_samples_per_second': 65.215, 'train_steps_per_second': 8.152, 'total_flos': 5158187333517312.0, 'train_loss': 6.595932285008615, 'epoch': 3.0})
Once the training is completed, we can evaluate our model and get its perplexity on the validation set like this:
import math
eval_results = trainer.evaluate()
print(f"Perplexity: {math.exp(eval_results['eval_loss']):.2f}")
***** Running Evaluation ***** Num examples = 1934 Batch size = 8
Perplexity: 552.71
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.
You can now upload the result of the training to the Hub, just execute this instruction:
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:
from transformers import AutoModelForCausalLM
model = AutoModelForCausalLM.from_pretrained("sgugger/my-awesome-model")
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"
tokenizer_checkpoint = "sgugger/bert-like-tokenizer"
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(tokenizer_checkpoint)
tokenized_datasets = datasets.map(tokenize_function, batched=True, num_proc=4, remove_columns=["text"])
https://huggingface.co/sgugger/bert-like-tokenizer/resolve/main/tokenizer_config.json not found in cache or force_download set to True, downloading to /home/sgugger/.cache/huggingface/transformers/tmpj0hlre6a
HBox(children=(FloatProgress(value=0.0, description='Downloading', max=320.0, style=ProgressStyle(description_…
storing https://huggingface.co/sgugger/bert-like-tokenizer/resolve/main/tokenizer_config.json in cache at /home/sgugger/.cache/huggingface/transformers/8e2bf16fe90bdd2f922f692d28792f71927c19b3ec57cf1457567cd848515842.0bbe47aa0e39b09ed05a95f7d42a27299232ce8e9ef28608e8f8a1cb57a74c0a creating metadata file for /home/sgugger/.cache/huggingface/transformers/8e2bf16fe90bdd2f922f692d28792f71927c19b3ec57cf1457567cd848515842.0bbe47aa0e39b09ed05a95f7d42a27299232ce8e9ef28608e8f8a1cb57a74c0a https://huggingface.co/sgugger/bert-like-tokenizer/resolve/main/vocab.txt not found in cache or force_download set to True, downloading to /home/sgugger/.cache/huggingface/transformers/tmpceo1r0j0
HBox(children=(FloatProgress(value=0.0, description='Downloading', max=174528.0, style=ProgressStyle(descripti…
storing https://huggingface.co/sgugger/bert-like-tokenizer/resolve/main/vocab.txt in cache at /home/sgugger/.cache/huggingface/transformers/d2c888a76d867b3c110720b637a5958d9748e157d245806d646a7c015a393b95.7b1a250944f9d3669d4f57ab97b1f6a21a494a84cff113694cf15d673e7bb6d5 creating metadata file for /home/sgugger/.cache/huggingface/transformers/d2c888a76d867b3c110720b637a5958d9748e157d245806d646a7c015a393b95.7b1a250944f9d3669d4f57ab97b1f6a21a494a84cff113694cf15d673e7bb6d5
https://huggingface.co/sgugger/bert-like-tokenizer/resolve/main/tokenizer.json not found in cache or force_download set to True, downloading to /home/sgugger/.cache/huggingface/transformers/tmp9i7md8wn
HBox(children=(FloatProgress(value=0.0, description='Downloading', max=364912.0, style=ProgressStyle(descripti…
storing https://huggingface.co/sgugger/bert-like-tokenizer/resolve/main/tokenizer.json in cache at /home/sgugger/.cache/huggingface/transformers/f385664afe38b7f081454cb8d1aa1ff0c4e16507dfbafe1fad8fc85538262261.159bf1d23803f236f036667eafea5ec2d6b22bcaf4b88d1dafeb8e6c7c35d6f9 creating metadata file for /home/sgugger/.cache/huggingface/transformers/f385664afe38b7f081454cb8d1aa1ff0c4e16507dfbafe1fad8fc85538262261.159bf1d23803f236f036667eafea5ec2d6b22bcaf4b88d1dafeb8e6c7c35d6f9
https://huggingface.co/sgugger/bert-like-tokenizer/resolve/main/special_tokens_map.json not found in cache or force_download set to True, downloading to /home/sgugger/.cache/huggingface/transformers/tmp58nljjm6
HBox(children=(FloatProgress(value=0.0, description='Downloading', max=112.0, style=ProgressStyle(description_…
storing https://huggingface.co/sgugger/bert-like-tokenizer/resolve/main/special_tokens_map.json in cache at /home/sgugger/.cache/huggingface/transformers/c90d08712ec5954e9bf3853df3bab5a6549e408225f4e9b6dd90f3bc3d3c0461.dd8bd9bfd3664b530ea4e645105f557769387b3da9f79bdb55ed556bdd80611d creating metadata file for /home/sgugger/.cache/huggingface/transformers/c90d08712ec5954e9bf3853df3bab5a6549e408225f4e9b6dd90f3bc3d3c0461.dd8bd9bfd3664b530ea4e645105f557769387b3da9f79bdb55ed556bdd80611d loading file https://huggingface.co/sgugger/bert-like-tokenizer/resolve/main/vocab.txt from cache at /home/sgugger/.cache/huggingface/transformers/d2c888a76d867b3c110720b637a5958d9748e157d245806d646a7c015a393b95.7b1a250944f9d3669d4f57ab97b1f6a21a494a84cff113694cf15d673e7bb6d5 loading file https://huggingface.co/sgugger/bert-like-tokenizer/resolve/main/tokenizer.json from cache at /home/sgugger/.cache/huggingface/transformers/f385664afe38b7f081454cb8d1aa1ff0c4e16507dfbafe1fad8fc85538262261.159bf1d23803f236f036667eafea5ec2d6b22bcaf4b88d1dafeb8e6c7c35d6f9 loading file https://huggingface.co/sgugger/bert-like-tokenizer/resolve/main/added_tokens.json from cache at None loading file https://huggingface.co/sgugger/bert-like-tokenizer/resolve/main/special_tokens_map.json from cache at /home/sgugger/.cache/huggingface/transformers/c90d08712ec5954e9bf3853df3bab5a6549e408225f4e9b6dd90f3bc3d3c0461.dd8bd9bfd3664b530ea4e645105f557769387b3da9f79bdb55ed556bdd80611d loading file https://huggingface.co/sgugger/bert-like-tokenizer/resolve/main/tokenizer_config.json from cache at /home/sgugger/.cache/huggingface/transformers/8e2bf16fe90bdd2f922f692d28792f71927c19b3ec57cf1457567cd848515842.0bbe47aa0e39b09ed05a95f7d42a27299232ce8e9ef28608e8f8a1cb57a74c0a
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 had, with two exceptions. First we use a model suitable for masked LM:
from transformers import AutoConfig, AutoModelForMaskedLM
config = AutoConfig.from_pretrained(model_checkpoint)
model = AutoModelForMaskedLM.from_config(config)
loading configuration file https://huggingface.co/bert-base-cased/resolve/main/config.json from cache at /home/sgugger/.cache/huggingface/transformers/a803e0468a8fe090683bdc453f4fac622804f49de86d7cecaee92365d4a0f829.a64a22196690e0e82ead56f388a3ef3a50de93335926ccfa20610217db589307 Model config BertConfig { "architectures": [ "BertForMaskedLM" ], "attention_probs_dropout_prob": 0.1, "gradient_checkpointing": false, "hidden_act": "gelu", "hidden_dropout_prob": 0.1, "hidden_size": 768, "initializer_range": 0.02, "intermediate_size": 3072, "layer_norm_eps": 1e-12, "max_position_embeddings": 512, "model_type": "bert", "num_attention_heads": 12, "num_hidden_layers": 12, "pad_token_id": 0, "position_embedding_type": "absolute", "transformers_version": "4.9.0.dev0", "type_vocab_size": 2, "use_cache": true, "vocab_size": 28996 }
We redefine our TrainingArguments
:
training_args = TrainingArguments(
"test-clm",
evaluation_strategy = "epoch",
learning_rate=2e-5,
weight_decay=0.01,
push_to_hub=True,
push_to_hub_model_id=f"{model_checkpoint}-wikitext2",
)
Like before, the last two arguments are to setup everything so we can push the model to the Hub at the end of training. Remove the two of them if you didn't follow the installation steps at the top of the notebook, otherwise you can change the value of push_to_hub_model_id
to something you would prefer.
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:
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:
trainer = Trainer(
model=model,
args=training_args,
train_dataset=lm_datasets["train"],
eval_dataset=lm_datasets["validation"],
data_collator=data_collator,
)
trainer.train()
***** Running training ***** Num examples = 18761 Num Epochs = 3 Instantaneous batch size per device = 8 Total train batch size (w. parallel, distributed & accumulation) = 8 Gradient Accumulation steps = 1 Total optimization steps = 7038
Epoch | Training Loss | Validation Loss |
---|---|---|
1 | 7.091100 | 7.049844 |
2 | 6.905400 | 6.870386 |
3 | 6.856900 | 6.888713 |
Saving model checkpoint to test-clm/checkpoint-500 Configuration saved in test-clm/checkpoint-500/config.json Model weights saved in test-clm/checkpoint-500/pytorch_model.bin Saving model checkpoint to test-clm/checkpoint-1000 Configuration saved in test-clm/checkpoint-1000/config.json Model weights saved in test-clm/checkpoint-1000/pytorch_model.bin Saving model checkpoint to test-clm/checkpoint-1500 Configuration saved in test-clm/checkpoint-1500/config.json Model weights saved in test-clm/checkpoint-1500/pytorch_model.bin Saving model checkpoint to test-clm/checkpoint-2000 Configuration saved in test-clm/checkpoint-2000/config.json Model weights saved in test-clm/checkpoint-2000/pytorch_model.bin ***** Running Evaluation ***** Num examples = 2009 Batch size = 8 Saving model checkpoint to test-clm/checkpoint-2500 Configuration saved in test-clm/checkpoint-2500/config.json Model weights saved in test-clm/checkpoint-2500/pytorch_model.bin Saving model checkpoint to test-clm/checkpoint-3000 Configuration saved in test-clm/checkpoint-3000/config.json Model weights saved in test-clm/checkpoint-3000/pytorch_model.bin Saving model checkpoint to test-clm/checkpoint-3500 Configuration saved in test-clm/checkpoint-3500/config.json Model weights saved in test-clm/checkpoint-3500/pytorch_model.bin Saving model checkpoint to test-clm/checkpoint-4000 Configuration saved in test-clm/checkpoint-4000/config.json Model weights saved in test-clm/checkpoint-4000/pytorch_model.bin Saving model checkpoint to test-clm/checkpoint-4500 Configuration saved in test-clm/checkpoint-4500/config.json Model weights saved in test-clm/checkpoint-4500/pytorch_model.bin ***** Running Evaluation ***** Num examples = 2009 Batch size = 8 Saving model checkpoint to test-clm/checkpoint-5000 Configuration saved in test-clm/checkpoint-5000/config.json Model weights saved in test-clm/checkpoint-5000/pytorch_model.bin Saving model checkpoint to test-clm/checkpoint-5500 Configuration saved in test-clm/checkpoint-5500/config.json Model weights saved in test-clm/checkpoint-5500/pytorch_model.bin Saving model checkpoint to test-clm/checkpoint-6000 Configuration saved in test-clm/checkpoint-6000/config.json Model weights saved in test-clm/checkpoint-6000/pytorch_model.bin Saving model checkpoint to test-clm/checkpoint-6500 Configuration saved in test-clm/checkpoint-6500/config.json Model weights saved in test-clm/checkpoint-6500/pytorch_model.bin Saving model checkpoint to test-clm/checkpoint-7000 Configuration saved in test-clm/checkpoint-7000/config.json Model weights saved in test-clm/checkpoint-7000/pytorch_model.bin ***** Running Evaluation ***** Num examples = 2009 Batch size = 8 Training completed. Do not forget to share your model on huggingface.co/models =)
TrainOutput(global_step=7038, training_loss=7.04967836345858, metrics={'train_runtime': 790.1373, 'train_samples_per_second': 71.232, 'train_steps_per_second': 8.907, 'total_flos': 4683068522136576.0, 'train_loss': 7.04967836345858, 'epoch': 3.0})
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.
eval_results = trainer.evaluate()
print(f"Perplexity: {math.exp(eval_results['eval_loss']):.2f}")
***** Running Evaluation ***** Num examples = 2009 Batch size = 8
Perplexity: 947.45
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.
You can now upload the result of the training to the Hub, just execute this instruction:
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:
from transformers import AutoModelForMaskedLM
model = AutoModelForMaskedLM.from_pretrained("sgugger/my-awesome-model")