transformers_doc/en/pytorch/language_modeling.ipynb (658 lines of code) (raw):
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Transformers installation\n",
"! pip install transformers datasets evaluate accelerate\n",
"# To install from source instead of the last release, comment the command above and uncomment the following one.\n",
"# ! pip install git+https://github.com/huggingface/transformers.git"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Causal language modeling"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There are two types of language modeling, causal and masked. This guide illustrates causal language modeling.\n",
"Causal language models are frequently used for text generation. You can use these models for creative applications like\n",
"choosing your own text adventure or an intelligent coding assistant like Copilot or CodeParrot."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"cellView": "form",
"hide_input": true
},
"outputs": [
{
"data": {
"text/html": [
"<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/Vpjb1lu0MDk?rel=0&controls=0&showinfo=0\" frameborder=\"0\" allowfullscreen></iframe>"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"execution_count": null,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"#@title\n",
"from IPython.display import HTML\n",
"\n",
"HTML('<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/Vpjb1lu0MDk?rel=0&controls=0&showinfo=0\" frameborder=\"0\" allowfullscreen></iframe>')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Causal language modeling predicts the next token in a sequence of tokens, and the model can only attend to tokens on\n",
"the left. This means the model cannot see future tokens. GPT-2 is an example of a causal language model.\n",
"\n",
"This guide will show you how to:\n",
"\n",
"1. Finetune [DistilGPT2](https://huggingface.co/distilbert/distilgpt2) on the [r/askscience](https://www.reddit.com/r/askscience/) subset of the [ELI5](https://huggingface.co/datasets/eli5) dataset.\n",
"2. Use your finetuned model for inference.\n",
"\n",
"<Tip>\n",
"\n",
"To see all architectures and checkpoints compatible with this task, we recommend checking the [task-page](https://huggingface.co/tasks/text-generation)\n",
"\n",
"</Tip>\n",
"\n",
"Before you begin, make sure you have all the necessary libraries installed:\n",
"\n",
"```bash\n",
"pip install transformers datasets evaluate\n",
"```\n",
"\n",
"We encourage you to log in to your Hugging Face account so you can upload and share your model with the community. When prompted, enter your token to log in:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from huggingface_hub import notebook_login\n",
"\n",
"notebook_login()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Load ELI5 dataset"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Start by loading the first 5000 examples from the [ELI5-Category](https://huggingface.co/datasets/eli5_category) dataset with the 🤗 Datasets library. This'll give you a chance to experiment and make sure everything works before spending more time training on the full dataset."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from datasets import load_dataset\n",
"\n",
"eli5 = load_dataset(\"eli5_category\", split=\"train[:5000]\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Split the dataset's `train` split into a train and test set with the [train_test_split](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset.train_test_split) method:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"eli5 = eli5.train_test_split(test_size=0.2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Then take a look at an example:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'q_id': '7h191n',\n",
" 'title': 'What does the tax bill that was passed today mean? How will it affect Americans in each tax bracket?',\n",
" 'selftext': '',\n",
" 'category': 'Economics',\n",
" 'subreddit': 'explainlikeimfive',\n",
" 'answers': {'a_id': ['dqnds8l', 'dqnd1jl', 'dqng3i1', 'dqnku5x'],\n",
" 'text': [\"The tax bill is 500 pages long and there were a lot of changes still going on right to the end. It's not just an adjustment to the income tax brackets, it's a whole bunch of changes. As such there is no good answer to your question. The big take aways are: - Big reduction in corporate income tax rate will make large companies very happy. - Pass through rate change will make certain styles of business (law firms, hedge funds) extremely happy - Income tax changes are moderate, and are set to expire (though it's the kind of thing that might just always get re-applied without being made permanent) - People in high tax states (California, New York) lose out, and many of them will end up with their taxes raised.\",\n",
" 'None yet. It has to be reconciled with a vastly different house bill and then passed again.',\n",
" 'Also: does this apply to 2017 taxes? Or does it start with 2018 taxes?',\n",
" 'This article explains both the House and senate bills, including the proposed changes to your income taxes based on your income level. URL_0'],\n",
" 'score': [21, 19, 5, 3],\n",
" 'text_urls': [[],\n",
" [],\n",
" [],\n",
" ['https://www.investopedia.com/news/trumps-tax-reform-what-can-be-done/']]},\n",
" 'title_urls': ['url'],\n",
" 'selftext_urls': ['url']}"
]
},
"execution_count": null,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"eli5[\"train\"][0]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"While this may look like a lot, you're only really interested in the `text` field. What's cool about language modeling\n",
"tasks is you don't need labels (also known as an unsupervised task) because the next word *is* the label."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Preprocess"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"cellView": "form",
"hide_input": true
},
"outputs": [
{
"data": {
"text/html": [
"<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/ma1TrR7gE7I?rel=0&controls=0&showinfo=0\" frameborder=\"0\" allowfullscreen></iframe>"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"execution_count": null,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"#@title\n",
"from IPython.display import HTML\n",
"\n",
"HTML('<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/ma1TrR7gE7I?rel=0&controls=0&showinfo=0\" frameborder=\"0\" allowfullscreen></iframe>')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The next step is to load a DistilGPT2 tokenizer to process the `text` subfield:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from transformers import AutoTokenizer\n",
"\n",
"tokenizer = AutoTokenizer.from_pretrained(\"distilbert/distilgpt2\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You'll notice from the example above, the `text` field is actually nested inside `answers`. This means you'll need to\n",
"extract the `text` subfield from its nested structure with the [`flatten`](https://huggingface.co/docs/datasets/process#flatten) method:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'q_id': '7h191n',\n",
" 'title': 'What does the tax bill that was passed today mean? How will it affect Americans in each tax bracket?',\n",
" 'selftext': '',\n",
" 'category': 'Economics',\n",
" 'subreddit': 'explainlikeimfive',\n",
" 'answers.a_id': ['dqnds8l', 'dqnd1jl', 'dqng3i1', 'dqnku5x'],\n",
" 'answers.text': [\"The tax bill is 500 pages long and there were a lot of changes still going on right to the end. It's not just an adjustment to the income tax brackets, it's a whole bunch of changes. As such there is no good answer to your question. The big take aways are: - Big reduction in corporate income tax rate will make large companies very happy. - Pass through rate change will make certain styles of business (law firms, hedge funds) extremely happy - Income tax changes are moderate, and are set to expire (though it's the kind of thing that might just always get re-applied without being made permanent) - People in high tax states (California, New York) lose out, and many of them will end up with their taxes raised.\",\n",
" 'None yet. It has to be reconciled with a vastly different house bill and then passed again.',\n",
" 'Also: does this apply to 2017 taxes? Or does it start with 2018 taxes?',\n",
" 'This article explains both the House and senate bills, including the proposed changes to your income taxes based on your income level. URL_0'],\n",
" 'answers.score': [21, 19, 5, 3],\n",
" 'answers.text_urls': [[],\n",
" [],\n",
" [],\n",
" ['https://www.investopedia.com/news/trumps-tax-reform-what-can-be-done/']],\n",
" 'title_urls': ['url'],\n",
" 'selftext_urls': ['url']}"
]
},
"execution_count": null,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"eli5 = eli5.flatten()\n",
"eli5[\"train\"][0]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Each subfield is now a separate column as indicated by the `answers` prefix, and the `text` field is a list now. Instead\n",
"of tokenizing each sentence separately, convert the list to a string so you can jointly tokenize them.\n",
"\n",
"Here is a first preprocessing function to join the list of strings for each example and tokenize the result:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def preprocess_function(examples):\n",
" return tokenizer([\" \".join(x) for x in examples[\"answers.text\"]])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To apply this preprocessing function over the entire dataset, use the 🤗 Datasets [map](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset.map) method. You can speed up the `map` function by setting `batched=True` to process multiple elements of the dataset at once, and increasing the number of processes with `num_proc`. Remove any columns you don't need:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"tokenized_eli5 = eli5.map(\n",
" preprocess_function,\n",
" batched=True,\n",
" num_proc=4,\n",
" remove_columns=eli5[\"train\"].column_names,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This dataset contains the token sequences, but some of these are longer than the maximum input length for the model.\n",
"\n",
"You can now use a second preprocessing function to\n",
"\n",
"- concatenate all the sequences\n",
"- split the concatenated sequences into shorter chunks defined by `block_size`, which should be both shorter than the maximum input length and short enough for your GPU RAM."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"block_size = 128\n",
"\n",
"\n",
"def group_texts(examples):\n",
" # Concatenate all texts.\n",
" concatenated_examples = {k: sum(examples[k], []) for k in examples.keys()}\n",
" total_length = len(concatenated_examples[list(examples.keys())[0]])\n",
" # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can\n",
" # customize this part to your needs.\n",
" if total_length >= block_size:\n",
" total_length = (total_length // block_size) * block_size\n",
" # Split by chunks of block_size.\n",
" result = {\n",
" k: [t[i : i + block_size] for i in range(0, total_length, block_size)]\n",
" for k, t in concatenated_examples.items()\n",
" }\n",
" result[\"labels\"] = result[\"input_ids\"].copy()\n",
" return result"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Apply the `group_texts` function over the entire dataset:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"lm_dataset = tokenized_eli5.map(group_texts, batched=True, num_proc=4)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now create a batch of examples using [DataCollatorForLanguageModeling](https://huggingface.co/docs/transformers/main/en/main_classes/data_collator#transformers.DataCollatorForLanguageModeling). It's more efficient to *dynamically pad* the\n",
"sentences to the longest length in a batch during collation, instead of padding the whole dataset to the maximum length.\n",
"\n",
"Use the end-of-sequence token as the padding token and set `mlm=False`. This will use the inputs as labels shifted to the right by one element:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from transformers import DataCollatorForLanguageModeling\n",
"\n",
"tokenizer.pad_token = tokenizer.eos_token\n",
"data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Train"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<Tip>\n",
"\n",
"If you aren't familiar with finetuning a model with the [Trainer](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer), take a look at the [basic tutorial](https://huggingface.co/docs/transformers/main/en/tasks/../training#train-with-pytorch-trainer)!\n",
"\n",
"</Tip>\n",
"\n",
"You're ready to start training your model now! Load DistilGPT2 with [AutoModelForCausalLM](https://huggingface.co/docs/transformers/main/en/model_doc/auto#transformers.AutoModelForCausalLM):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from transformers import AutoModelForCausalLM, TrainingArguments, Trainer\n",
"\n",
"model = AutoModelForCausalLM.from_pretrained(\"distilbert/distilgpt2\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"At this point, only three steps remain:\n",
"\n",
"1. Define your training hyperparameters in [TrainingArguments](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.TrainingArguments). The only required parameter is `output_dir` which specifies where to save your model. You'll push this model to the Hub by setting `push_to_hub=True` (you need to be signed in to Hugging Face to upload your model).\n",
"2. Pass the training arguments to [Trainer](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer) along with the model, datasets, and data collator.\n",
"3. Call [train()](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer.train) to finetune your model."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"training_args = TrainingArguments(\n",
" output_dir=\"my_awesome_eli5_clm-model\",\n",
" eval_strategy=\"epoch\",\n",
" learning_rate=2e-5,\n",
" weight_decay=0.01,\n",
" push_to_hub=True,\n",
")\n",
"\n",
"trainer = Trainer(\n",
" model=model,\n",
" args=training_args,\n",
" train_dataset=lm_dataset[\"train\"],\n",
" eval_dataset=lm_dataset[\"test\"],\n",
" data_collator=data_collator,\n",
" tokenizer=tokenizer,\n",
")\n",
"\n",
"trainer.train()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Once training is completed, use the [evaluate()](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer.evaluate) method to evaluate your model and get its perplexity:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Perplexity: 49.61"
]
},
"execution_count": null,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import math\n",
"\n",
"eval_results = trainer.evaluate()\n",
"print(f\"Perplexity: {math.exp(eval_results['eval_loss']):.2f}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Then share your model to the Hub with the [push_to_hub()](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer.push_to_hub) method so everyone can use your model:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"trainer.push_to_hub()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<Tip>\n",
"\n",
"For a more in-depth example of how to finetune a model for causal language modeling, take a look at the corresponding\n",
"[PyTorch notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling.ipynb)\n",
"or [TensorFlow notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling-tf.ipynb).\n",
"\n",
"</Tip>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Inference"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Great, now that you've finetuned a model, you can use it for inference!\n",
"\n",
"Come up with a prompt you'd like to generate text from:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"prompt = \"Somatic hypermutation allows the immune system to\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The simplest way to try out your finetuned model for inference is to use it in a [pipeline()](https://huggingface.co/docs/transformers/main/en/main_classes/pipelines#transformers.pipeline). Instantiate a `pipeline` for text generation with your model, and pass your text to it:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[{'generated_text': \"Somatic hypermutation allows the immune system to be able to effectively reverse the damage caused by an infection.\\n\\n\\nThe damage caused by an infection is caused by the immune system's ability to perform its own self-correcting tasks.\"}]"
]
},
"execution_count": null,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from transformers import pipeline\n",
"\n",
"generator = pipeline(\"text-generation\", model=\"username/my_awesome_eli5_clm-model\")\n",
"generator(prompt)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Tokenize the text and return the `input_ids` as PyTorch tensors:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from transformers import AutoTokenizer\n",
"\n",
"tokenizer = AutoTokenizer.from_pretrained(\"username/my_awesome_eli5_clm-model\")\n",
"inputs = tokenizer(prompt, return_tensors=\"pt\").input_ids"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Use the [generate()](https://huggingface.co/docs/transformers/main/en/main_classes/text_generation#transformers.GenerationMixin.generate) method to generate text.\n",
"For more details about the different text generation strategies and parameters for controlling generation, check out the [Text generation strategies](https://huggingface.co/docs/transformers/main/en/tasks/../generation_strategies) page."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from transformers import AutoModelForCausalLM\n",
"\n",
"model = AutoModelForCausalLM.from_pretrained(\"username/my_awesome_eli5_clm-model\")\n",
"outputs = model.generate(inputs, max_new_tokens=100, do_sample=True, top_k=50, top_p=0.95)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Decode the generated token ids back into text:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[\"Somatic hypermutation allows the immune system to react to drugs with the ability to adapt to a different environmental situation. In other words, a system of 'hypermutation' can help the immune system to adapt to a different environmental situation or in some cases even a single life. In contrast, researchers at the University of Massachusetts-Boston have found that 'hypermutation' is much stronger in mice than in humans but can be found in humans, and that it's not completely unknown to the immune system. A study on how the immune system\"]"
]
},
"execution_count": null,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"tokenizer.batch_decode(outputs, skip_special_tokens=True)"
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 4
}