{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Fine-tune a 🤗 Transformers model" ] }, { "cell_type": "markdown", "metadata": { "id": "VaFMt6AIhYbK" }, "source": [ "This notebook is based on [an official 🤗 notebook - \"How to fine-tune a model on text classification\"](https://github.com/huggingface/notebooks/blob/6ca682955173cc9d36ffa431ddda505a048cbe80/examples/text_classification.ipynb). The main aim of this notebook is to show the process of conversion from vanilla 🤗 to [Ray AIR](https://docs.ray.io/en/latest/ray-air/getting-started.html) 🤗 without changing the training logic unless necessary.\n", "\n", "In this notebook, we will:\n", "1. [Set up Ray](#setup)\n", "2. [Load the dataset](#load)\n", "3. [Preprocess the dataset](#preprocess)\n", "4. [Run the training with Ray AIR](#train)\n", "5. [Predict on test data with Ray AIR](#predict)\n", "6. [Optionally, share the model with the community](#share)" ] }, { "cell_type": "markdown", "metadata": { "id": "sQbdfyWQhYbO" }, "source": [ "Uncomment and run the following line in order to install all the necessary dependencies:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "YajFzmkthYbO" }, "outputs": [], "source": [ "#! pip install \"datasets\" \"transformers>=4.19.0\" \"torch>=1.10.0\" \"mlflow\" \"ray[air]>=1.13\"" ] }, { "cell_type": "markdown", "metadata": { "id": "pvSRaEHChYbP" }, "source": [ "## Set up Ray " ] }, { "cell_type": "markdown", "metadata": { "id": "LRdL3kWBhYbQ" }, "source": [ "We will use `ray.init()` to initialize a local cluster. By default, this cluster will be compromised of only the machine you are running this notebook on. You can also run this notebook on an Anyscale cluster.\n", "\n", "This notebook *will not* run in [Ray Client](https://docs.ray.io/en/latest/cluster/ray-client.html) mode." ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "MOsHUjgdIrIW", "outputId": "e527bdbb-2f28-4142-cca0-762e0566cbcd" }, "outputs": [ { "data": { "text/plain": [ "RayContext(dashboard_url='', python_version='3.7.13', ray_version='2.0.0.dev0', ray_commit='e2ee2140f97ca08b70fd0f7561038b7f8d958d63', address_info={'node_ip_address': '172.28.0.2', 'raylet_ip_address': '172.28.0.2', 'redis_address': None, 'object_store_address': '/tmp/ray/session_2022-05-12_18-30-10_467499_75/sockets/plasma_store', 'raylet_socket_name': '/tmp/ray/session_2022-05-12_18-30-10_467499_75/sockets/raylet', 'webui_url': '', 'session_dir': '/tmp/ray/session_2022-05-12_18-30-10_467499_75', 'metrics_export_port': 64840, 'gcs_address': '172.28.0.2:58661', 'address': '172.28.0.2:58661', 'node_id': '65d091b8f504ccd72024fd0b1a8445a8f9ea43e86bcbf67868c22ba7'})" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from pprint import pprint\n", "import ray\n", "\n", "ray.init()" ] }, { "cell_type": "markdown", "metadata": { "id": "oJiSdWy2hYbR" }, "source": [ "We can check the resources our cluster is composed of. If you are running this notebook on your local machine or Google Colab, you should see the number of CPU cores and GPUs available on the said machine." ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "KlMz0dt9hYbS", "outputId": "2d485449-ee69-4334-fcba-47e0ceb63078" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'CPU': 2.0,\n", " 'GPU': 1.0,\n", " 'accelerator_type:T4': 1.0,\n", " 'memory': 7855477556.0,\n", " 'node:172.28.0.2': 1.0,\n", " 'object_store_memory': 3927738777.0}\n" ] } ], "source": [ "pprint(ray.cluster_resources())" ] }, { "cell_type": "markdown", "metadata": { "id": "uS6oeJELhYbS" }, "source": [ "In this notebook, we will see how to fine-tune one of the [🤗 Transformers](https://github.com/huggingface/transformers) model to a text classification task of the [GLUE Benchmark](https://gluebenchmark.com/). We will be running the training using [Ray AIR](https://docs.ray.io/en/latest/ray-air/getting-started.html).\n", "\n", "You can change those two variables to control whether the training (which we will get to later) uses CPUs or GPUs, and how many workers should be spawned. Each worker will claim one CPU or GPU. Make sure not to request more resources than the resources present!\n", "\n", "By default, we will run the training with one GPU worker." ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "id": "gAbhv9OqhYbT" }, "outputs": [], "source": [ "use_gpu = True # set this to False to run on CPUs\n", "num_workers = 1 # set this to number of GPUs/CPUs you want to use" ] }, { "cell_type": "markdown", "metadata": { "id": "rEJBSTyZIrIb" }, "source": [ "## Fine-tuning a model on a text classification task" ] }, { "cell_type": "markdown", "metadata": { "id": "kTCFado4IrIc" }, "source": [ "The GLUE Benchmark is a group of nine classification tasks on sentences or pairs of sentences. If you would like to learn more, refer to the [original notebook](https://github.com/huggingface/notebooks/blob/6ca682955173cc9d36ffa431ddda505a048cbe80/examples/text_classification.ipynb).\n", "\n", "Each task is named by its acronym, with `mnli-mm` standing for the mismatched version of MNLI (so same training set as `mnli` but different validation and test sets):" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "id": "YZbiBDuGIrId" }, "outputs": [], "source": [ "GLUE_TASKS = [\"cola\", \"mnli\", \"mnli-mm\", \"mrpc\", \"qnli\", \"qqp\", \"rte\", \"sst2\", \"stsb\", \"wnli\"]" ] }, { "cell_type": "markdown", "metadata": { "id": "4RRkXuteIrIh" }, "source": [ "This notebook is built to run on any of the tasks in the list above, with any model checkpoint from the [Model Hub](https://huggingface.co/models) as long as that model has a version with a classification head. Depending on you model and the GPU you are using, you might need to adjust the batch size to avoid out-of-memory errors. Set those three parameters, then the rest of the notebook should run smoothly:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "id": "zVvslsfMIrIh" }, "outputs": [], "source": [ "task = \"cola\"\n", "model_checkpoint = \"distilbert-base-uncased\"\n", "batch_size = 16" ] }, { "cell_type": "markdown", "metadata": { "id": "whPRbBNbIrIl" }, "source": [ "### Loading the dataset " ] }, { "cell_type": "markdown", "metadata": { "id": "W7QYTpxXIrIl" }, "source": [ "We will use the [🤗 Datasets](https://github.com/huggingface/datasets) library to download the data and get the metric we need to use for evaluation (to compare our model to the benchmark). This can be easily done with the functions `load_dataset` and `load_metric`.\n", "\n", "Apart from `mnli-mm` being a special code, we can directly pass our task name to those functions.\n", "\n", "As Ray AIR doesn't provide integrations for 🤗 Datasets yet, we will simply run the normal 🤗 Datasets code to load the dataset from the Hub." ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 200 }, "id": "MwhAeEOuhYbV", "outputId": "3aff8c73-d6eb-4784-890a-a419403b5bda" }, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "bf499d18407642489b7f5acb9dc88ca8", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Downloading builder script: 0%| | 0.00/7.78k [00:00" ] }, { "cell_type": "markdown", "metadata": { "id": "YVx71GdAIrJH" }, "source": [ "Before we can feed those texts to our model, we need to preprocess them. This is done by a 🤗 Transformers `Tokenizer` which will (as the name indicates) tokenize the inputs (including converting the tokens to their corresponding IDs in the pretrained vocabulary) and put it in a format the model expects, as well as generate the other inputs that model requires.\n", "\n", "To do all of this, we instantiate our tokenizer with the `AutoTokenizer.from_pretrained` method, which will ensure:\n", "\n", "- we get a tokenizer that corresponds to the model architecture we want to use,\n", "- we download the vocabulary used when pretraining this specific checkpoint." ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 145 }, "id": "eXNLu_-nIrJI", "outputId": "f545a7a5-f341-4315-cd89-9942a657aa31" }, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "8afaa1d7c12a41db8ad9f37c4067bfd4", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Downloading: 0%| | 0.00/28.0 [00:00" ] }, { "cell_type": "markdown", "metadata": { "id": "FBiW8UpKIrJW" }, "source": [ "Now that our data is ready, we can download the pretrained model and fine-tune it.\n", "\n", "Since all our tasks are about sentence classification, we use the `AutoModelForSequenceClassification` class.\n", "\n", "We will not go into details about each specific component of the training (see the [original notebook](https://github.com/huggingface/notebooks/blob/6ca682955173cc9d36ffa431ddda505a048cbe80/examples/text_classification.ipynb) for that). The tokenizer is the same as we have used to encoded the dataset before.\n", "\n", "The main difference when using the Ray AIR is that we need to create our 🤗 Transformers `Trainer` inside a function (`trainer_init_per_worker`) and return it. That function will be passed to the `HuggingFaceTrainer` and ran on every Ray worker. The training will then proceed by the means of PyTorch DDP.\n", "\n", "Make sure that you initialize the model, metric and tokenizer inside that function. Otherwise, you may run into serialization errors.\n", "\n", "Furthermore, `push_to_hub=True` is not yet supported. Ray will however checkpoint the model at every epoch, allowing you to push it to hub manually. We will do that after the training.\n", "\n", "If you wish to use thrid party logging libraries, such as MLFlow or Weights&Biases, do not set them in `TrainingArguments` (they will be automatically disabled) - instead, you should be passing Ray AIR callbacks to `HuggingFaceTrainer`'s `run_config`. In this example, we will use MLFlow." ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "id": "TlqNaB8jIrJW" }, "outputs": [], "source": [ "from transformers import AutoModelForSequenceClassification, TrainingArguments, Trainer\n", "import numpy as np\n", "import torch\n", "\n", "num_labels = 3 if task.startswith(\"mnli\") else 1 if task==\"stsb\" else 2\n", "metric_name = \"pearson\" if task == \"stsb\" else \"matthews_correlation\" if task == \"cola\" else \"accuracy\"\n", "model_name = model_checkpoint.split(\"/\")[-1]\n", "validation_key = \"validation_mismatched\" if task == \"mnli-mm\" else \"validation_matched\" if task == \"mnli\" else \"validation\"\n", "name = f\"{model_name}-finetuned-{task}\"\n", "\n", "def trainer_init_per_worker(train_dataset, eval_dataset = None, **config):\n", " print(f\"Is CUDA available: {torch.cuda.is_available()}\")\n", " metric = load_metric_fn()\n", " tokenizer = AutoTokenizer.from_pretrained(model_checkpoint, use_fast=True)\n", " model = AutoModelForSequenceClassification.from_pretrained(model_checkpoint, num_labels=num_labels)\n", " args = TrainingArguments(\n", " name,\n", " evaluation_strategy=\"epoch\",\n", " save_strategy=\"epoch\",\n", " learning_rate=2e-5,\n", " per_device_train_batch_size=batch_size,\n", " per_device_eval_batch_size=batch_size,\n", " num_train_epochs=5,\n", " weight_decay=0.01,\n", " push_to_hub=False,\n", " disable_tqdm=True, # declutter the output a little\n", " no_cuda=not use_gpu, # you need to explicitly set no_cuda if you want CPUs\n", " )\n", "\n", " def compute_metrics(eval_pred):\n", " predictions, labels = eval_pred\n", " if task != \"stsb\":\n", " predictions = np.argmax(predictions, axis=1)\n", " else:\n", " predictions = predictions[:, 0]\n", " return metric.compute(predictions=predictions, references=labels)\n", "\n", " trainer = Trainer(\n", " model,\n", " args,\n", " train_dataset=train_dataset,\n", " eval_dataset=eval_dataset,\n", " tokenizer=tokenizer,\n", " compute_metrics=compute_metrics\n", " )\n", "\n", " print(\"Starting training\")\n", " return trainer" ] }, { "cell_type": "markdown", "metadata": { "id": "CdzABDVcIrJg" }, "source": [ "With our `trainer_init_per_worker` complete, we can now instantiate the `HuggingFaceTrainer`. Aside from the function, we set the `scaling_config`, controlling the amount of workers and resources used, and the `datasets` we will use for training and evaluation.\n", "\n", "We specify the `MlflowLoggerCallback` inside the `run_config`." ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "id": "RElw7OgLhYba" }, "outputs": [], "source": [ "from ray.train.huggingface import HuggingFaceTrainer\n", "from ray.air.config import RunConfig, ScalingConfig\n", "from ray.air.callbacks.mlflow import MLflowLoggerCallback\n", "\n", "trainer = HuggingFaceTrainer(\n", " trainer_init_per_worker=trainer_init_per_worker,\n", " scaling_config=ScalingConfig(num_workers=num_workers, use_gpu=use_gpu),\n", " datasets={\"train\": ray_datasets[\"train\"], \"evaluation\": ray_datasets[validation_key]},\n", " run_config=RunConfig(callbacks=[MLflowLoggerCallback(experiment_name=name)])\n", ")" ] }, { "cell_type": "markdown", "metadata": { "id": "XvS136zKhYba" }, "source": [ "Finally, we call the `fit` method to being training with Ray AIR. We will save the `Result` object to a variable so we can access metrics and checkpoints." ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 1000 }, "id": "uNx5pyRlIrJh", "outputId": "8496fe4f-f1c3-48ad-a6d3-b16a65716135" }, "outputs": [ { "data": { "text/html": [ "== Status ==
Current time: 2022-05-12 18:35:14 (running for 00:03:48.08)
Memory usage on this node: 5.7/12.7 GiB
Using FIFO scheduling algorithm.
Resources requested: 0/2 CPUs, 0/1 GPUs, 0.0/7.32 GiB heap, 0.0/3.66 GiB objects (0.0/1.0 accelerator_type:T4)
Result logdir: /root/ray_results/HuggingFaceTrainer_2022-05-12_18-31-26
Number of trials: 1/1 (1 TERMINATED)
\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Trial name status loc iter total time (s) loss learning_rate epoch
HuggingFaceTrainer_bb9dd_00000TERMINATED172.28.0.2:419 5 222.3910.1575 1.30841e-06 5


" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stderr", "output_type": "stream", "text": [ "\u001b[2m\u001b[36m(BaseWorkerMixin pid=455)\u001b[0m 2022-05-12 18:31:33,158\tINFO torch.py:347 -- Setting up process group for: env:// [rank=0, world_size=1]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\u001b[2m\u001b[36m(BaseWorkerMixin pid=455)\u001b[0m Is CUDA available: True\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Downloading builder script: 5.76kB [00:00, 6.35MB/s] \n", "Downloading: 0%| | 0.00/256M [00:00, error=None)" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "result" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Predict on test data with Ray AIR " ] }, { "cell_type": "markdown", "metadata": { "id": "Tfoyu1q7hYbb" }, "source": [ "You can now use the checkpoint to run prediction with `HuggingFacePredictor`, which wraps around [🤗 Pipelines](https://huggingface.co/docs/transformers/main_classes/pipelines). In order to distribute prediction, we use `BatchPredictor`. While this is not necessary for the very small example we are using (you could use `HuggingFacePredictor` directly), it will scale well to a large dataset." ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 262 }, "id": "UOUcBkX8IrJi", "outputId": "4dc16812-1400-482d-8c3f-85991ce4b081" }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Map Progress (2 actors 1 pending): 0%| | 0/1 [00:12\n", "
\n", "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
labelscore
0LABEL_10.998539
1LABEL_10.997706
2LABEL_10.998476
3LABEL_10.998498
4LABEL_00.533578
\n", "
\n", " \n", " \n", " \n", "\n", " \n", "
\n", " \n", " " ], "text/plain": [ " label score\n", "0 LABEL_1 0.998539\n", "1 LABEL_1 0.997706\n", "2 LABEL_1 0.998476\n", "3 LABEL_1 0.998498\n", "4 LABEL_0 0.533578" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from ray.train.huggingface import HuggingFacePredictor\n", "from ray.train.batch_predictor import BatchPredictor\n", "import pandas as pd\n", "\n", "sentences = ['Bill whistled past the house.',\n", " 'The car honked its way down the road.',\n", " 'Bill pushed Harry off the sofa.',\n", " 'the kittens yawned awake and played.',\n", " 'I demand that the more John eats, the more he pay.']\n", "predictor = BatchPredictor.from_checkpoint(\n", " checkpoint=result.checkpoint,\n", " predictor_cls=HuggingFacePredictor,\n", " task=\"text-classification\",\n", ")\n", "data = ray.data.from_pandas(pd.DataFrame(sentences, columns=[\"sentence\"]))\n", "prediction = predictor.predict(data)\n", "prediction.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Share the model " ] }, { "cell_type": "markdown", "metadata": { "id": "mS8PId_NhYbb" }, "source": [ "To be able to share your model with the community, there are a few more steps to follow.\n", "\n", "We have conducted the training on the Ray cluster, but share the model from the local enviroment - this will allow us to easily authenticate.\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 execute the following cell and input your username and password:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "2LClXkN8hYbb", "tags": [ "remove-cell-ci" ] }, "outputs": [], "source": [ "from huggingface_hub import notebook_login\n", "\n", "notebook_login()" ] }, { "cell_type": "markdown", "metadata": { "id": "SybKUDryhYbb" }, "source": [ "Then you need to install Git-LFS. Uncomment the following instructions:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "_wF6aT-0hYbb", "tags": [ "remove-cell-ci" ] }, "outputs": [], "source": [ "# !apt install git-lfs" ] }, { "cell_type": "markdown", "metadata": { "id": "5fr6E0e8hYbb" }, "source": [ "Now, load the model and tokenizer locally, and recreate the 🤗 Transformers `Trainer`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "cjH2A8m6hYbc", "tags": [ "remove-cell-ci" ] }, "outputs": [], "source": [ "from ray.train.huggingface import HuggingFaceCheckpoint\n", "\n", "checkpoint = HuggingFaceCheckpoint.from_checkpoint(result.checkpoint)\n", "hf_trainer = checkpoint.get_model(model=AutoModelForSequenceClassification)" ] }, { "cell_type": "markdown", "metadata": { "id": "tgV2xKfFhYbc" }, "source": [ "You can now upload the result of the training to the Hub, just execute this instruction:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "XSkfJe3nhYbc", "tags": [ "remove-cell-ci" ] }, "outputs": [], "source": [ "hf_trainer.push_to_hub()" ] }, { "cell_type": "markdown", "metadata": { "id": "UL-Boc4dhYbc" }, "source": [ "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 AutoModelForSequenceClassification\n", "\n", "model = AutoModelForSequenceClassification.from_pretrained(\"sgugger/my-awesome-model\")\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "ipJBReeWhYbc", "tags": [ "remove-cell-ci" ] }, "outputs": [], "source": [] } ], "metadata": { "accelerator": "GPU", "colab": { "collapsed_sections": [], "name": "huggingface_text_classification.ipynb", "provenance": [] }, "kernelspec": { "display_name": "Python 3.9.12 ('.venv': venv)", "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.9.12" }, "vscode": { "interpreter": { "hash": "a658351b4133f922c5967ed6133cfc05c9f16c53a5161e5843ace3f528fccaf5" } } }, "nbformat": 4, "nbformat_minor": 0 }