{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "X4cRE8IbIrIV" }, "source": [ "If you're opening this Notebook on colab, you will probably need to install 🤗 Transformers and 🤗 Datasets. Uncomment the following cell and run it." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 1000 }, "id": "MOsHUjgdIrIW", "outputId": "f84a093e-147f-470e-aad9-80fb51193c8e" }, "outputs": [], "source": [ "#! pip install transformers\n", "#! pip install datasets\n", "#! pip install huggingface_hub" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you're opening this notebook locally, make sure your environment has an install from the latest version of those libraries.\n", "\n", "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.\n", "\n", "First you have to store your authentication token from the Hugging Face website (sign up [here](https://huggingface.co/join) if you haven't already!) then run the following cell and input your token:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "9dbff25b935149db8796a354c89fdcc3", "version_major": 2, "version_minor": 0 }, "text/plain": [ "VBox(children=(HTML(value='
\\n\n", " \n", " \n", " \n", " text\n", " \n", " \n", " \n", " \n", " 0\n", " Today , Lady Rosebery is a mere footnote in the long history of her husband 's family , rather as Consuelo Vanderbilt is regarded in the Spencer @-@ Churchill family . Her husband , once one of the \" most celebrated figures in Britain , \" is a minor figure in British history . Thus , Hannah , Countess of Rosebery , in her day celebrated in the worlds of politics , philanthropy , and high society , is largely unknown and forgotten . \\n\n", " \n", " \n", " 1\n", " Agujaceratops - ( Texas , USA ) \\n\n", " \n", " \n", " 2\n", " The city of Galveston is situated on Galveston Island , a barrier island off the Texas Gulf coast near the mainland coast . Made up of mostly sand @-@ sized particles and smaller amounts of finer mud sediments and larger gravel @-@ sized sediments , the island is unstable , affected by water and weather , and can shift its boundaries through erosion . \\n\n", " \n", " \n", " 3\n", " Although ceratopsians are generally considered herbivorous , a few paleontologists , such as Darren Naish and Mark Witton , have speculated online that at least some ceratopsians may have been opportunistically omnivorous . \\n\n", " \n", " \n", " 4\n", " \n", " \n", " \n", " 5\n", " \n", " \n", " \n", " 6\n", " = = = Menu , coup and North Vietnamese offensive = = = \\n\n", " \n", " \n", " 7\n", " It was for his leadership and bravery during these actions that Andrew was awarded the Victoria Cross ( VC ) at the age of 20 . The citation read as follows : \\n\n", " \n", " \n", " 8\n", " = = Death of Clement XIII = = \\n\n", " \n", " \n", " 9\n", " = = = In the media = = = \\n\n", " \n", " \n", "" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "show_random_elements(datasets[\"train\"])" ] }, { "cell_type": "markdown", "metadata": { "id": "CKerdF353l-o" }, "source": [ "As we can see, some of the texts are a full paragraph of a Wikipedia article while others are just titles or empty lines." ] }, { "cell_type": "markdown", "metadata": { "id": "JEA1ju653l-p" }, "source": [ "## Causal Language modeling" ] }, { "cell_type": "markdown", "metadata": { "id": "v5GTGKZS3l-q" }, "source": [ "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:\n", "```\n", "part of text 1\n", "```\n", "or \n", "```\n", "end of text 1 [BOS_TOKEN] beginning of text 2\n", "```\n", "depending on whether they span multiple original texts or not. The labels will be the same as the inputs, shifted to the right.\n", "\n", "We will use the [`distilgpt2`](https://huggingface.co/distilgpt2) model for this example. You can pick any of the checkpoints listed [here](https://huggingface.co/models?filter=causal-lm) instead:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "id": "-WGBCO343l-q" }, "outputs": [], "source": [ "model_checkpoint = \"distilgpt2\"\n" ] }, { "cell_type": "markdown", "metadata": { "id": "5io6fY_d3l-u" }, "source": [ "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:" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "id": "iAYlS40Z3l-v" }, "outputs": [], "source": [ "from transformers import AutoTokenizer\n", "\n", "tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)" ] }, { "cell_type": "markdown", "metadata": { "id": "rpOiBrJ13l-y" }, "source": [ "We can now call the tokenizer on all our texts. This is very simple, using the [`map`](https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.map) method from the Datasets library. First we define a function that calls the tokenizer on our texts:" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "id": "lS2m25YM3l-z" }, "outputs": [], "source": [ "def tokenize_function(examples):\n", " return tokenizer(examples[\"text\"])" ] }, { "cell_type": "markdown", "metadata": { "id": "M9xVAa3s3l-2" }, "source": [ "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." ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "id": "NVAO0H8u3l-3", "outputId": "30d88b8a-e353-4e13-f709-8e5e06ef747b" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " " ] }, { "name": "stderr", "output_type": "stream", "text": [ "Loading cached processed dataset at /Users/ArjunPatel/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/a241db52902eaf2c6aa732210bead40c090019a499ceb13bcbfa3f8ab646a126/cache-61391423a2766fc9.arrow\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ " " ] }, { "name": "stderr", "output_type": "stream", "text": [ "Loading cached processed dataset at /Users/ArjunPatel/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/a241db52902eaf2c6aa732210bead40c090019a499ceb13bcbfa3f8ab646a126/cache-5ceac15e651919d2.arrow\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ " " ] }, { "name": "stderr", "output_type": "stream", "text": [ "Loading cached processed dataset at /Users/ArjunPatel/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/a241db52902eaf2c6aa732210bead40c090019a499ceb13bcbfa3f8ab646a126/cache-b81e39451b6b2f7e.arrow\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ " " ] }, { "name": "stderr", "output_type": "stream", "text": [ "Loading cached processed dataset at /Users/ArjunPatel/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/a241db52902eaf2c6aa732210bead40c090019a499ceb13bcbfa3f8ab646a126/cache-1bcda98ae382df67.arrow\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ " " ] }, { "name": "stderr", "output_type": "stream", "text": [ "Loading cached processed dataset at /Users/ArjunPatel/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/a241db52902eaf2c6aa732210bead40c090019a499ceb13bcbfa3f8ab646a126/cache-fa4442bf92b4768b.arrow\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ " " ] }, { "name": "stderr", "output_type": "stream", "text": [ "Loading cached processed dataset at /Users/ArjunPatel/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/a241db52902eaf2c6aa732210bead40c090019a499ceb13bcbfa3f8ab646a126/cache-aa2a4366053b507c.arrow\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ " " ] }, { "name": "stderr", "output_type": "stream", "text": [ "Loading cached processed dataset at /Users/ArjunPatel/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/a241db52902eaf2c6aa732210bead40c090019a499ceb13bcbfa3f8ab646a126/cache-962e11e2efef61ea.arrow\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ " " ] }, { "name": "stderr", "output_type": "stream", "text": [ "Loading cached processed dataset at /Users/ArjunPatel/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/a241db52902eaf2c6aa732210bead40c090019a499ceb13bcbfa3f8ab646a126/cache-9a86568f88be8e85.arrow\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ " " ] }, { "name": "stderr", "output_type": "stream", "text": [ "Loading cached processed dataset at /Users/ArjunPatel/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/a241db52902eaf2c6aa732210bead40c090019a499ceb13bcbfa3f8ab646a126/cache-9f392100036d7e36.arrow\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ " " ] }, { "name": "stderr", "output_type": "stream", "text": [ "Loading cached processed dataset at /Users/ArjunPatel/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/a241db52902eaf2c6aa732210bead40c090019a499ceb13bcbfa3f8ab646a126/cache-bcce0e8f19f73037.arrow\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ " " ] }, { "name": "stderr", "output_type": "stream", "text": [ "Loading cached processed dataset at /Users/ArjunPatel/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/a241db52902eaf2c6aa732210bead40c090019a499ceb13bcbfa3f8ab646a126/cache-9776e9836e6e1ee0.arrow\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ " " ] }, { "name": "stderr", "output_type": "stream", "text": [ "Loading cached processed dataset at /Users/ArjunPatel/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/a241db52902eaf2c6aa732210bead40c090019a499ceb13bcbfa3f8ab646a126/cache-55693ec29a40f3cb.arrow\n" ] } ], "source": [ "tokenized_datasets = datasets.map(\n", " tokenize_function, batched=True, num_proc=4, remove_columns=[\"text\"]\n", ")" ] }, { "cell_type": "markdown", "metadata": { "id": "8qik3J_C3l-7" }, "source": [ "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:" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "id": "nYv_mcKk3l-7", "outputId": "8334734c-0f86-4e18-ec17-4216a2d5dd18" }, "outputs": [ { "data": { "text/plain": [ "{'input_ids': [796, 569, 18354, 7496, 17740, 6711, 796, 220, 198],\n", " 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1]}" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "tokenized_datasets[\"train\"][1]" ] }, { "cell_type": "markdown", "metadata": { "id": "obvgcXda3l--" }, "source": [ "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.\n", "\n", "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." ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "id": "DVHs5aCA3l-_" }, "outputs": [], "source": [ "# block_size = tokenizer.model_max_length\n", "block_size = 128" ] }, { "cell_type": "markdown", "metadata": { "id": "RpNfGiMw3l_A" }, "source": [ "Then we write the preprocessing function that will group our texts:" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "id": "iaAJy5Hu3l_B" }, "outputs": [], "source": [ "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, though you could add padding instead if the model supports it\n", " # In this, as in all things, we advise you to follow your heart\n", " total_length = (total_length // block_size) * block_size\n", " # Split by chunks of max_len.\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": { "id": "LGJWXtNv3l_C" }, "source": [ "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.\n", "\n", "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:" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "id": "gXUSfBrq3l_C", "outputId": "34e55885-3d8f-4f05-cbdb-706ce56a25f8" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " " ] }, { "name": "stderr", "output_type": "stream", "text": [ "Loading cached processed dataset at /Users/ArjunPatel/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/a241db52902eaf2c6aa732210bead40c090019a499ceb13bcbfa3f8ab646a126/cache-7b71dd2271728f79.arrow\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ " " ] }, { "name": "stderr", "output_type": "stream", "text": [ "Loading cached processed dataset at /Users/ArjunPatel/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/a241db52902eaf2c6aa732210bead40c090019a499ceb13bcbfa3f8ab646a126/cache-cee53a8f6793ac14.arrow\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ " " ] }, { "name": "stderr", "output_type": "stream", "text": [ "Loading cached processed dataset at /Users/ArjunPatel/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/a241db52902eaf2c6aa732210bead40c090019a499ceb13bcbfa3f8ab646a126/cache-03de660721d6e90f.arrow\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ " " ] }, { "name": "stderr", "output_type": "stream", "text": [ "Loading cached processed dataset at /Users/ArjunPatel/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/a241db52902eaf2c6aa732210bead40c090019a499ceb13bcbfa3f8ab646a126/cache-1aa9f24edffd33bf.arrow\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ " " ] }, { "name": "stderr", "output_type": "stream", "text": [ "Loading cached processed dataset at /Users/ArjunPatel/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/a241db52902eaf2c6aa732210bead40c090019a499ceb13bcbfa3f8ab646a126/cache-be9266f35a58e0d1.arrow\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ " " ] }, { "name": "stderr", "output_type": "stream", "text": [ "Loading cached processed dataset at /Users/ArjunPatel/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/a241db52902eaf2c6aa732210bead40c090019a499ceb13bcbfa3f8ab646a126/cache-a6201b62855b0506.arrow\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ " " ] }, { "name": "stderr", "output_type": "stream", "text": [ "Loading cached processed dataset at /Users/ArjunPatel/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/a241db52902eaf2c6aa732210bead40c090019a499ceb13bcbfa3f8ab646a126/cache-f208c1a35aa5450a.arrow\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ " " ] }, { "name": "stderr", "output_type": "stream", "text": [ "Loading cached processed dataset at /Users/ArjunPatel/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/a241db52902eaf2c6aa732210bead40c090019a499ceb13bcbfa3f8ab646a126/cache-233fc6217e931151.arrow\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ " " ] }, { "name": "stderr", "output_type": "stream", "text": [ "Loading cached processed dataset at /Users/ArjunPatel/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/a241db52902eaf2c6aa732210bead40c090019a499ceb13bcbfa3f8ab646a126/cache-865d7a7e5760a6af.arrow\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ " " ] }, { "name": "stderr", "output_type": "stream", "text": [ "Loading cached processed dataset at /Users/ArjunPatel/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/a241db52902eaf2c6aa732210bead40c090019a499ceb13bcbfa3f8ab646a126/cache-996d57e28a0c3daa.arrow\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ " " ] }, { "name": "stderr", "output_type": "stream", "text": [ "Loading cached processed dataset at /Users/ArjunPatel/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/a241db52902eaf2c6aa732210bead40c090019a499ceb13bcbfa3f8ab646a126/cache-2b587ab7ed92bd6d.arrow\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ " " ] }, { "name": "stderr", "output_type": "stream", "text": [ "Loading cached processed dataset at /Users/ArjunPatel/.cache/huggingface/datasets/wikitext/wikitext-2-raw-v1/1.0.0/a241db52902eaf2c6aa732210bead40c090019a499ceb13bcbfa3f8ab646a126/cache-81447c56f742f510.arrow\n" ] } ], "source": [ "lm_datasets = tokenized_datasets.map(\n", " group_texts,\n", " batched=True,\n", " batch_size=1000,\n", " num_proc=4,\n", ")" ] }, { "cell_type": "markdown", "metadata": { "id": "6n84V8Gc3l_G" }, "source": [ "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." ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "id": "hTeGCLl_3l_G", "outputId": "ab381a07-f92e-4b14-f7b6-e4af5513d7c4" }, "outputs": [ { "data": { "text/plain": [ "' 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'" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "tokenizer.decode(lm_datasets[\"train\"][1][\"input_ids\"])" ] }, { "cell_type": "markdown", "metadata": { "id": "iEmeQ7Xm3l_H" }, "source": [ "Now that the data has been cleaned, we're ready to initialize our model:" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "id": "sPqQA3TT3l_I" }, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "ff73baa0c0764c60846c0dd310506dfc", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Downloading: 0%| | 0.00/313M [00:00.fetch_function at 0x7fd6e30aa830> and will run it as-is.\n", "Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.\n", "Cause: module 'gast' has no attribute 'Constant'\n", "To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert\n", "WARNING: AutoGraph could not transform .fetch_function at 0x7fd6e30aa830> and will run it as-is.\n", "Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.\n", "Cause: module 'gast' has no attribute 'Constant'\n", "To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert\n", "WARNING:tensorflow:AutoGraph could not transform .ensure_shapes at 0x7fd6f2d50f80> and will run it as-is.\n", "Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.\n", "Cause: module 'gast' has no attribute 'Constant'\n", "To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert\n", "WARNING: AutoGraph could not transform .ensure_shapes at 0x7fd6f2d50f80> and will run it as-is.\n", "Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.\n", "Cause: module 'gast' has no attribute 'Constant'\n", "To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert\n", "WARNING:tensorflow:AutoGraph could not transform .fetch_function at 0x7fd6e30ddd40> and will run it as-is.\n", "Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.\n", "Cause: module 'gast' has no attribute 'Constant'\n", "To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert\n", "WARNING: AutoGraph could not transform .fetch_function at 0x7fd6e30ddd40> and will run it as-is.\n", "Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.\n", "Cause: module 'gast' has no attribute 'Constant'\n", "To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert\n", "WARNING:tensorflow:AutoGraph could not transform .ensure_shapes at 0x7fd6e2b88050> and will run it as-is.\n", "Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.\n", "Cause: module 'gast' has no attribute 'Constant'\n", "To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert\n", "WARNING: AutoGraph could not transform .ensure_shapes at 0x7fd6e2b88050> and will run it as-is.\n", "Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.\n", "Cause: module 'gast' has no attribute 'Constant'\n", "To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert\n" ] } ], "source": [ "from transformers import DefaultDataCollator\n", "\n", "data_collator = DefaultDataCollator(return_tensors=\"tf\")\n", "\n", "train_set = lm_datasets[\"train\"].to_tf_dataset(\n", " columns=[\"attention_mask\", \"input_ids\", \"labels\"],\n", " shuffle=True,\n", " batch_size=16,\n", " collate_fn=data_collator,\n", ")\n", "validation_set = lm_datasets[\"validation\"].to_tf_dataset(\n", " columns=[\"attention_mask\", \"input_ids\", \"labels\"],\n", " shuffle=False,\n", " batch_size=16,\n", " collate_fn=data_collator,\n", ")" ] }, { "cell_type": "markdown", "metadata": { "id": "6Vvz34Td3l_O" }, "source": [ "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()`. " ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "id": "NyZvu_MF3l_P", "outputId": "b69d0931-7f1f-4f2d-fdb8-09d37c7418bb" }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Cloning https://huggingface.co/arjunpatel/distilgpt2-finetuned-wikitext2 into local empty directory.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "WARNING:tensorflow:AutoGraph could not transform .train_function at 0x7fd6e30fb200> and will run it as-is.\n", "Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.\n", "Cause: 'arguments' object has no attribute 'posonlyargs'\n", "To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert\n", "WARNING: AutoGraph could not transform .train_function at 0x7fd6e30fb200> and will run it as-is.\n", "Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.\n", "Cause: 'arguments' object has no attribute 'posonlyargs'\n", "To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert\n", "WARNING:tensorflow:AutoGraph could not transform > and will run it as-is.\n", "Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.\n", "Cause: module 'gast' has no attribute 'Constant'\n", "To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert\n", "WARNING: AutoGraph could not transform > and will run it as-is.\n", "Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.\n", "Cause: module 'gast' has no attribute 'Constant'\n", "To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert\n", "WARNING:tensorflow:AutoGraph could not transform > and will run it as-is.\n", "Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.\n", "Cause: module 'gast' has no attribute 'Constant'\n", "To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert\n", "WARNING: AutoGraph could not transform > and will run it as-is.\n", "Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.\n", "Cause: module 'gast' has no attribute 'Constant'\n", "To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert\n", "WARNING:tensorflow:AutoGraph could not transform > and will run it as-is.\n", "Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.\n", "Cause: 'arguments' object has no attribute 'posonlyargs'\n", "To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert\n", "WARNING: AutoGraph could not transform > and will run it as-is.\n", "Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.\n", "Cause: 'arguments' object has no attribute 'posonlyargs'\n", "To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert\n", "WARNING:tensorflow:AutoGraph could not transform > and will run it as-is.\n", "Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.\n", "Cause: module 'gast' has no attribute 'Constant'\n", "To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert\n", "WARNING: AutoGraph could not transform > and will run it as-is.\n", "Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.\n", "Cause: module 'gast' has no attribute 'Constant'\n", "To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert\n", "WARNING:tensorflow:AutoGraph could not transform > and will run it as-is.\n", "Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.\n", "Cause: module 'gast' has no attribute 'Constant'\n", "To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert\n", "WARNING: AutoGraph could not transform > and will run it as-is.\n", "Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.\n", "Cause: module 'gast' has no attribute 'Constant'\n", "To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert\n", "WARNING:tensorflow:AutoGraph could not transform > and will run it as-is.\n", "Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.\n", "Cause: 'arguments' object has no attribute 'posonlyargs'\n", "To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert\n", "WARNING: AutoGraph could not transform > and will run it as-is.\n", "Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.\n", "Cause: 'arguments' object has no attribute 'posonlyargs'\n", "To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert\n", "WARNING:tensorflow:AutoGraph could not transform > and will run it as-is.\n", "Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.\n", "Cause: 'arguments' object has no attribute 'posonlyargs'\n", "To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert\n", "WARNING: AutoGraph could not transform > and will run it as-is.\n", "Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.\n", "Cause: 'arguments' object has no attribute 'posonlyargs'\n", "To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert\n", "WARNING:tensorflow:AutoGraph could not transform and will run it as-is.\n", "Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.\n", "Cause: 'arguments' object has no attribute 'posonlyargs'\n", "To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert\n", "WARNING: AutoGraph could not transform and will run it as-is.\n", "Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.\n", "Cause: 'arguments' object has no attribute 'posonlyargs'\n", "To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert\n", " 7/1166 [..............................] - ETA: 1:24:49 - loss: 4.5316" ] }, { "ename": "KeyboardInterrupt", "evalue": "", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mKeyboardInterrupt\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/var/folders/vj/m14m1x1j47b8nvnmkfkf20ph0000gn/T/ipykernel_10410/3702115951.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 15\u001b[0m \u001b[0mcallbacks\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0mtensorboard_callback\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mpush_to_hub_callback\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 16\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 17\u001b[0;31m \u001b[0mmodel\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mfit\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mtrain_set\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mvalidation_data\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mvalidation_set\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mepochs\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mcallbacks\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mcallbacks\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;32m~/.local/lib/python3.7/site-packages/keras/utils/traceback_utils.py\u001b[0m in \u001b[0;36merror_handler\u001b[0;34m(*args, **kwargs)\u001b[0m\n\u001b[1;32m 62\u001b[0m \u001b[0mfiltered_tb\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 63\u001b[0m \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 64\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mfn\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 65\u001b[0m \u001b[0;32mexcept\u001b[0m \u001b[0mException\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0me\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0;31m# pylint: disable=broad-except\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 66\u001b[0m \u001b[0mfiltered_tb\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0m_process_traceback_frames\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0me\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m__traceback__\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;32m~/.local/lib/python3.7/site-packages/keras/engine/training.py\u001b[0m in \u001b[0;36mfit\u001b[0;34m(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_batch_size, validation_freq, max_queue_size, workers, use_multiprocessing)\u001b[0m\n\u001b[1;32m 1382\u001b[0m _r=1):\n\u001b[1;32m 1383\u001b[0m \u001b[0mcallbacks\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mon_train_batch_begin\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mstep\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 1384\u001b[0;31m \u001b[0mtmp_logs\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mtrain_function\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0miterator\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 1385\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mdata_handler\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mshould_sync\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1386\u001b[0m \u001b[0mcontext\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0masync_wait\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;32m~/.local/lib/python3.7/site-packages/tensorflow/python/util/traceback_utils.py\u001b[0m in \u001b[0;36merror_handler\u001b[0;34m(*args, **kwargs)\u001b[0m\n\u001b[1;32m 148\u001b[0m \u001b[0mfiltered_tb\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 149\u001b[0m \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 150\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mfn\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 151\u001b[0m \u001b[0;32mexcept\u001b[0m \u001b[0mException\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0me\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 152\u001b[0m \u001b[0mfiltered_tb\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0m_process_traceback_frames\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0me\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m__traceback__\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;32m~/.local/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py\u001b[0m in \u001b[0;36m__call__\u001b[0;34m(self, *args, **kwds)\u001b[0m\n\u001b[1;32m 913\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 914\u001b[0m \u001b[0;32mwith\u001b[0m \u001b[0mOptionalXlaContext\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_jit_compile\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 915\u001b[0;31m \u001b[0mresult\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_call\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwds\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 916\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 917\u001b[0m \u001b[0mnew_tracing_count\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mexperimental_get_tracing_count\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;32m~/.local/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py\u001b[0m in \u001b[0;36m_call\u001b[0;34m(self, *args, **kwds)\u001b[0m\n\u001b[1;32m 945\u001b[0m \u001b[0;31m# In this case we have created variables on the first call, so we run the\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 946\u001b[0m \u001b[0;31m# defunned version which is guaranteed to never create variables.\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 947\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_stateless_fn\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwds\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# pylint: disable=not-callable\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 948\u001b[0m \u001b[0;32melif\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_stateful_fn\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 949\u001b[0m \u001b[0;31m# Release the lock early so that multiple threads can perform the call\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;32m~/.local/lib/python3.7/site-packages/tensorflow/python/eager/function.py\u001b[0m in \u001b[0;36m__call__\u001b[0;34m(self, *args, **kwargs)\u001b[0m\n\u001b[1;32m 2955\u001b[0m filtered_flat_args) = self._maybe_define_function(args, kwargs)\n\u001b[1;32m 2956\u001b[0m return graph_function._call_flat(\n\u001b[0;32m-> 2957\u001b[0;31m filtered_flat_args, captured_inputs=graph_function.captured_inputs) # pylint: disable=protected-access\n\u001b[0m\u001b[1;32m 2958\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2959\u001b[0m \u001b[0;34m@\u001b[0m\u001b[0mproperty\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;32m~/.local/lib/python3.7/site-packages/tensorflow/python/eager/function.py\u001b[0m in \u001b[0;36m_call_flat\u001b[0;34m(self, args, captured_inputs, cancellation_manager)\u001b[0m\n\u001b[1;32m 1852\u001b[0m \u001b[0;31m# No tape is watching; skip to running the function.\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1853\u001b[0m return self._build_call_outputs(self._inference_function.call(\n\u001b[0;32m-> 1854\u001b[0;31m ctx, args, cancellation_manager=cancellation_manager))\n\u001b[0m\u001b[1;32m 1855\u001b[0m forward_backward = self._select_forward_and_backward_functions(\n\u001b[1;32m 1856\u001b[0m \u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;32m~/.local/lib/python3.7/site-packages/tensorflow/python/eager/function.py\u001b[0m in \u001b[0;36mcall\u001b[0;34m(self, ctx, args, cancellation_manager)\u001b[0m\n\u001b[1;32m 502\u001b[0m \u001b[0minputs\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 503\u001b[0m \u001b[0mattrs\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mattrs\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 504\u001b[0;31m ctx=ctx)\n\u001b[0m\u001b[1;32m 505\u001b[0m \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 506\u001b[0m outputs = execute.execute_with_cancellation(\n", "\u001b[0;32m~/.local/lib/python3.7/site-packages/tensorflow/python/eager/execute.py\u001b[0m in \u001b[0;36mquick_execute\u001b[0;34m(op_name, num_outputs, inputs, attrs, ctx, name)\u001b[0m\n\u001b[1;32m 53\u001b[0m \u001b[0mctx\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mensure_initialized\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 54\u001b[0m tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,\n\u001b[0;32m---> 55\u001b[0;31m inputs, attrs, num_outputs)\n\u001b[0m\u001b[1;32m 56\u001b[0m \u001b[0;32mexcept\u001b[0m \u001b[0mcore\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_NotOkStatusException\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0me\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 57\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mname\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mKeyboardInterrupt\u001b[0m: " ] } ], "source": [ "from transformers.keras_callbacks import PushToHubCallback\n", "from tensorflow.keras.callbacks import TensorBoard\n", "\n", "model_name = model_checkpoint.split(\"/\")[-1]\n", "push_to_hub_model_id = f\"{model_name}-finetuned-wikitext2\"\n", "\n", "tensorboard_callback = TensorBoard(log_dir=\"./clm_model_save/logs\")\n", "\n", "push_to_hub_callback = PushToHubCallback(\n", " output_dir=\"./clm_model_save\",\n", " tokenizer=tokenizer,\n", " hub_model_id=push_to_hub_model_id,\n", ")\n", "\n", "callbacks = [tensorboard_callback, push_to_hub_callback]\n", "\n", "model.fit(train_set, validation_data=validation_set, epochs=1, callbacks=callbacks)" ] }, { "cell_type": "markdown", "metadata": { "id": "3APq-vUc3l_R" }, "source": [ "Once the training is completed, we can evaluate our model and get its cross-entropy loss on the validation set like this:" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "id": "diKZnB1I3l_R", "outputId": "9b3ac725-0117-4830-f380-a555ee57c8cf" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "121/121 [==============================] - 4s 33ms/step - loss: 3.6752\n" ] } ], "source": [ "eval_loss = model.evaluate(validation_set)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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." ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Perplexity: 39.46\n" ] } ], "source": [ "import math\n", "\n", "print(f\"Perplexity: {math.exp(eval_loss):.2f}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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:\n", "\n", "```python\n", "from transformers import AutoModelForCausalLM\n", "\n", "model = AutoModelForCausalLM.from_pretrained(\"sgugger/my-awesome-model\")\n", "```" ] }, { "cell_type": "markdown", "metadata": { "id": "q-EIELH43l_T" }, "source": [ "## Masked language modeling" ] }, { "cell_type": "markdown", "metadata": { "id": "LWk97-Ny3l_T" }, "source": [ "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).\n", "\n", "We will use the [`distilroberta-base`](https://huggingface.co/distilroberta-base) model for this example. You can pick any of the checkpoints listed [here](https://huggingface.co/models?filter=masked-lm) instead:" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "id": "QRTpmyCc3l_T" }, "outputs": [], "source": [ "model_checkpoint = \"distilroberta-base\"" ] }, { "cell_type": "markdown", "metadata": { "id": "12F1ulgT3l_V" }, "source": [ "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!" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "id": "h8RCYcvr3l_V", "outputId": "a5ffeb0a-71da-4b27-e57a-c62f1927562e" }, "outputs": [ { "name": "stderr", "output_type": "stream", "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\n", "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\n", "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\n", "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\n", "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\n" ] } ], "source": [ "tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)\n", "tokenized_datasets = datasets.map(\n", " tokenize_function, batched=True, num_proc=4, remove_columns=[\"text\"]\n", ")" ] }, { "cell_type": "markdown", "metadata": { "id": "MTuy8UUs3l_X" }, "source": [ "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." ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "id": "LVYPMwEs3l_X", "outputId": "e71ed7f1-b182-4643-a8fb-3d731c70e40b" }, "outputs": [], "source": [ "lm_datasets = tokenized_datasets.map(\n", " group_texts,\n", " batched=True,\n", " batch_size=1000,\n", " num_proc=4,\n", ")" ] }, { "cell_type": "markdown", "metadata": { "id": "nFJ49iHJ3l_Z" }, "source": [ "The rest is very similar to what we had, with two exceptions. First we use a model suitable for masked LM:" ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "id": "PM10A9Za3l_Z", "outputId": "fff2d5bb-397d-4d5d-9aa9-933090cb6680" }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "All model checkpoint layers were used when initializing TFRobertaForMaskedLM.\n", "\n", "All the layers of TFRobertaForMaskedLM were initialized from the model checkpoint at distilroberta-base.\n", "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.\n" ] } ], "source": [ "from transformers import TFAutoModelForMaskedLM\n", "\n", "model = TFAutoModelForMaskedLM.from_pretrained(model_checkpoint)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We redefine our `optimizer` as we did with the CLM model, and we compile the model. We're using the internal loss again, like we did before." ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/home/matt/miniconda3/envs/tensorflow28/lib/python3.10/site-packages/keras/optimizer_v2/adam.py:105: UserWarning: The `lr` argument is deprecated, use `learning_rate` instead.\n", " super(Adam, self).__init__(name, **kwargs)\n", "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.\n" ] } ], "source": [ "from transformers import create_optimizer, AdamWeightDecay\n", "import tensorflow as tf\n", "\n", "optimizer = AdamWeightDecay(lr=2e-5, weight_decay_rate=0.01)\n", "\n", "model.compile(optimizer=optimizer)" ] }, { "cell_type": "markdown", "metadata": { "id": "z6uuUnvz3l_b" }, "source": [ "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.\n", "\n", "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='tf'` argument to get Tensorflow tensors out - you don't want to accidentally get a load of `torch.Tensor` objects in the middle of your nice TF code!" ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "id": "nRZ-5v_P3l_b" }, "outputs": [], "source": [ "from transformers import DataCollatorForLanguageModeling\n", "\n", "data_collator = DataCollatorForLanguageModeling(\n", " tokenizer=tokenizer, mlm_probability=0.15, return_tensors=\"tf\"\n", ")" ] }, { "cell_type": "markdown", "metadata": { "id": "bqHnWcYC3l_d" }, "source": [ "Now we generate our datasets as before. Remember to pass the `data_collator` you just made to the `collate_fn` argument." ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [], "source": [ "train_set = lm_datasets[\"train\"].to_tf_dataset(\n", " columns=[\"attention_mask\", \"input_ids\", \"labels\"],\n", " shuffle=True,\n", " batch_size=16,\n", " collate_fn=data_collator,\n", ")\n", "\n", "validation_set = lm_datasets[\"validation\"].to_tf_dataset(\n", " columns=[\"attention_mask\", \"input_ids\", \"labels\"],\n", " shuffle=False,\n", " batch_size=16,\n", " collate_fn=data_collator,\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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!" ] }, { "cell_type": "code", "execution_count": 32, "metadata": { "id": "V-Y3gNqV3l_d" }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/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()`.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "1202/1202 [==============================] - ETA: 0s - loss: 1.9043" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Several commits (2) will be pushed upstream.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "1202/1202 [==============================] - 138s 110ms/step - loss: 1.9043 - val_loss: 1.7174\n" ] }, { "data": { "text/plain": [ "" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from transformers.keras_callbacks import PushToHubCallback\n", "\n", "model_name = model_checkpoint.split(\"/\")[-1]\n", "push_to_hub_model_id = f\"{model_name}-finetuned-wikitext2\"\n", "\n", "callback = PushToHubCallback(\n", " output_dir=\"./mlm_model_save\",\n", " tokenizer=tokenizer,\n", " hub_model_id=push_to_hub_model_id,\n", ")\n", "\n", "model.fit(train_set, validation_data=validation_set, epochs=1, callbacks=[callback])" ] }, { "cell_type": "markdown", "metadata": { "id": "KDBi0reX3l_g" }, "source": [ "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." ] }, { "cell_type": "code", "execution_count": 33, "metadata": { "id": "4hSaANqj3l_g", "outputId": "eeeb8727-2e27-4aeb-ac71-c98123214661" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "125/125 [==============================] - 4s 32ms/step - loss: 1.7101\n", "Perplexity: 5.53\n" ] } ], "source": [ "import math\n", "\n", "eval_results = model.evaluate(validation_set)\n", "print(f\"Perplexity: {math.exp(eval_results):.2f}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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:\n", "\n", "```python\n", "from transformers import AutoModelForMaskedLM\n", "\n", "model = AutoModelForMaskedLM.from_pretrained(\"your-username/my-awesome-model\")\n", "```" ] } ], "metadata": { "colab": { "name": "Fine-tune a language model", "provenance": [] }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.13" } }, "nbformat": 4, "nbformat_minor": 4 }