{ "cells": [ { "cell_type": "markdown", "id": "7bcdad0e-b67c-4927-b00e-3a4d950cd8ce", "metadata": {}, "source": [ "# How to fine-tune chat models\n", "\n", "This notebook provides a step-by-step guide for our new `gpt-3.5-turbo` fine-tuning. We'll perform entity extraction using the [RecipeNLG dataset](https://github.com/Glorf/recipenlg), which provides various recipes and a list of extracted generic ingredients for each. This is a common dataset for named entity recognition (NER) tasks.\n", "\n", "We will go through the following steps:\n", "\n", "1. **Setup:** Loading our dataset and filtering down to one domain to fine-tune on.\n", "2. **Data preparation:** Preparing your data for fine-tuning by creating training and validation examples, and uploading them to the `Files` endpoint.\n", "3. **Create the fine-tune:** Creating your fine-tuned model.\n", "4. **Use model for inference:** Using your fine-tuned model for inference on new inputs.\n", "\n", "By the end of this you should be able to train, evaluate and deploy a fine-tuned `gpt-3.5-turbo` model.\n" ] }, { "cell_type": "markdown", "id": "6f49cb10-f895-41f4-aa97-da606d0084d4", "metadata": {}, "source": [ "## Setup\n", "\n", "First we will import any required libraries and prepare our data.\n", "\n", "Fine tuning works best when focused on a particular domain. It's important to make sure your dataset is both focused enough for the model to learn, but general enough that unseen examples won't be missed. Having this in mind, we have already extracted a subset from the RecipesNLG dataset to only contain documents from www.cookbooks.com.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "32036e70", "metadata": {}, "outputs": [], "source": [ "# make sure to use the latest version of the openai python package\n", "!pip install --upgrade openai " ] }, { "cell_type": "code", "execution_count": 76, "id": "6e1f4403-37e1-4115-a215-12fd7daa1eb6", "metadata": {}, "outputs": [], "source": [ "import json\n", "import openai\n", "import os\n", "import pandas as pd\n", "import requests\n", "from pprint import pprint\n", "\n", "OPENAI_API_KEY = os.getenv(\"OPENAI_API_KEY\", \"\")" ] }, { "cell_type": "code", "execution_count": 2, "id": "f57ebc23-14b7-47f9-90b8-1d791ccfc9bc", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\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", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
titleingredientsdirectionslinksourceNER
0No-Bake Nut Cookies[\"1 c. firmly packed brown sugar\", \"1/2 c. eva...[\"In a heavy 2-quart saucepan, mix brown sugar...www.cookbooks.com/Recipe-Details.aspx?id=44874www.cookbooks.com[\"brown sugar\", \"milk\", \"vanilla\", \"nuts\", \"bu...
1Jewell Ball'S Chicken[\"1 small jar chipped beef, cut up\", \"4 boned ...[\"Place chipped beef on bottom of baking dish....www.cookbooks.com/Recipe-Details.aspx?id=699419www.cookbooks.com[\"beef\", \"chicken breasts\", \"cream of mushroom...
2Creamy Corn[\"2 (16 oz.) pkg. frozen corn\", \"1 (8 oz.) pkg...[\"In a slow cooker, combine all ingredients. C...www.cookbooks.com/Recipe-Details.aspx?id=10570www.cookbooks.com[\"frozen corn\", \"cream cheese\", \"butter\", \"gar...
3Chicken Funny[\"1 large whole chicken\", \"2 (10 1/2 oz.) cans...[\"Boil and debone chicken.\", \"Put bite size pi...www.cookbooks.com/Recipe-Details.aspx?id=897570www.cookbooks.com[\"chicken\", \"chicken gravy\", \"cream of mushroo...
4Reeses Cups(Candy)[\"1 c. peanut butter\", \"3/4 c. graham cracker ...[\"Combine first four ingredients and press in ...www.cookbooks.com/Recipe-Details.aspx?id=659239www.cookbooks.com[\"peanut butter\", \"graham cracker crumbs\", \"bu...
\n", "
" ], "text/plain": [ " title ingredients \\\n", "0 No-Bake Nut Cookies [\"1 c. firmly packed brown sugar\", \"1/2 c. eva... \n", "1 Jewell Ball'S Chicken [\"1 small jar chipped beef, cut up\", \"4 boned ... \n", "2 Creamy Corn [\"2 (16 oz.) pkg. frozen corn\", \"1 (8 oz.) pkg... \n", "3 Chicken Funny [\"1 large whole chicken\", \"2 (10 1/2 oz.) cans... \n", "4 Reeses Cups(Candy) [\"1 c. peanut butter\", \"3/4 c. graham cracker ... \n", "\n", " directions \\\n", "0 [\"In a heavy 2-quart saucepan, mix brown sugar... \n", "1 [\"Place chipped beef on bottom of baking dish.... \n", "2 [\"In a slow cooker, combine all ingredients. C... \n", "3 [\"Boil and debone chicken.\", \"Put bite size pi... \n", "4 [\"Combine first four ingredients and press in ... \n", "\n", " link source \\\n", "0 www.cookbooks.com/Recipe-Details.aspx?id=44874 www.cookbooks.com \n", "1 www.cookbooks.com/Recipe-Details.aspx?id=699419 www.cookbooks.com \n", "2 www.cookbooks.com/Recipe-Details.aspx?id=10570 www.cookbooks.com \n", "3 www.cookbooks.com/Recipe-Details.aspx?id=897570 www.cookbooks.com \n", "4 www.cookbooks.com/Recipe-Details.aspx?id=659239 www.cookbooks.com \n", "\n", " NER \n", "0 [\"brown sugar\", \"milk\", \"vanilla\", \"nuts\", \"bu... \n", "1 [\"beef\", \"chicken breasts\", \"cream of mushroom... \n", "2 [\"frozen corn\", \"cream cheese\", \"butter\", \"gar... \n", "3 [\"chicken\", \"chicken gravy\", \"cream of mushroo... \n", "4 [\"peanut butter\", \"graham cracker crumbs\", \"bu... " ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Read in the dataset we'll use for this task.\n", "# This will be the RecipesNLG dataset, which we've cleaned to only contain documents from www.cookbooks.com\n", "recipe_df = pd.read_csv(\"data/cookbook_recipes_nlg_10k.csv\")\n", "\n", "recipe_df.head()" ] }, { "cell_type": "markdown", "id": "2b3151e9-8715-47bd-a153-195d6a0d0a70", "metadata": {}, "source": [ "## Data preparation\n", "\n", "We'll begin by preparing our data. When fine-tuning with the `ChatCompletion` format, each training example is a simple list of `messages`. For example, an entry could look like:\n", "\n", "```\n", "[{'role': 'system',\n", " 'content': 'You are a helpful recipe assistant. You are to extract the generic ingredients from each of the recipes provided.'},\n", "\n", " {'role': 'user',\n", " 'content': 'Title: No-Bake Nut Cookies\\n\\nIngredients: [\"1 c. firmly packed brown sugar\", \"1/2 c. evaporated milk\", \"1/2 tsp. vanilla\", \"1/2 c. broken nuts (pecans)\", \"2 Tbsp. butter or margarine\", \"3 1/2 c. bite size shredded rice biscuits\"]\\n\\nGeneric ingredients: '},\n", "\n", " {'role': 'assistant',\n", " 'content': '[\"brown sugar\", \"milk\", \"vanilla\", \"nuts\", \"butter\", \"bite size shredded rice biscuits\"]'}]\n", "```\n", "\n", "During the training process this conversation will be split, with the final entry being the `completion` that the model will produce, and the remainder of the `messages` acting as the prompt. Consider this when building your training examples - if your model will act on multi-turn conversations, then please provide representative examples so it doesn't perform poorly when the conversation starts to expand.\n", "\n", "For fine-tuning with `ChatCompletion` you can begin with even 30-50 well-pruned examples. You should see performance continue to scale linearly as you increase the size of the training set, but your jobs will also take longer.\n", "\n", "Please note that currently there is a 4096 token limit for each training example. Anything longer than this will be truncated at 4096 tokens.\n" ] }, { "cell_type": "code", "execution_count": 17, "id": "9a8216b0-d1dc-472d-b07d-1be03acd70a5", "metadata": {}, "outputs": [], "source": [ "training_data = []\n", "\n", "system_message = \"You are a helpful recipe assistant. You are to extract the generic ingredients from each of the recipes provided.\"\n", "\n", "\n", "def create_user_message(row):\n", " return f\"\"\"Title: {row['title']}\\n\\nIngredients: {row['ingredients']}\\n\\nGeneric ingredients: \"\"\"\n", "\n", "\n", "# Take first 100 records for training\n", "for x, y in recipe_df.head(100).iterrows():\n", " training_message = []\n", " training_message.append({\"role\": \"system\", \"content\": system_message})\n", "\n", " user_message = create_user_message(y)\n", " training_message.append({\"role\": \"user\", \"content\": user_message})\n", "\n", " training_message.append({\"role\": \"assistant\", \"content\": y[\"NER\"]})\n", " training_message_dict = {\"messages\": training_message}\n", " training_data.append(training_message_dict)" ] }, { "cell_type": "code", "execution_count": 18, "id": "5b853efa-dfea-4770-ab88-9b7e17794421", "metadata": {}, "outputs": [], "source": [ "validation_data = []\n", "\n", "# We'll pick a test set from further on in the dataset\n", "test_df = recipe_df.loc[100:200]\n", "\n", "for x, y in test_df.iterrows():\n", " validation_message = []\n", " validation_message.append({\"role\": \"system\", \"content\": system_message})\n", "\n", " user_message = create_user_message(y)\n", " validation_message.append({\"role\": \"user\", \"content\": user_message})\n", "\n", " validation_message.append({\"role\": \"assistant\", \"content\": y[\"NER\"]})\n", " validation_message_dict = {\"messages\": validation_message}\n", " validation_data.append(validation_message_dict)" ] }, { "cell_type": "markdown", "id": "1d5e7bfe-f6c8-4a23-a951-3df3f3791d7f", "metadata": {}, "source": [ "We then need to export these as `.jsonl` files, with each row being one training example.\n" ] }, { "cell_type": "code", "execution_count": 19, "id": "8d2eb207-2c2b-43f6-a613-64a7e92d494d", "metadata": {}, "outputs": [], "source": [ "def dicts_to_jsonl(data_list: list, filename: str) -> None:\n", " \"\"\"\n", " Method saves list of dicts into jsonl file.\n", " :param data: (list) list of dicts to be stored,\n", " :param filename: (str) path to the output file. If suffix .jsonl is not given then methods appends\n", " .jsonl suffix into the file.\n", " \"\"\"\n", " sjsonl = \".jsonl\"\n", "\n", " # Check filename\n", " if not filename.endswith(sjsonl):\n", " filename = filename + \".jsonl\"\n", "\n", " # Save data\n", " with open(filename, \"w\") as out:\n", " for ddict in data_list:\n", " jout = json.dumps(ddict) + \"\\n\"\n", " out.write(jout)" ] }, { "cell_type": "code", "execution_count": 20, "id": "8b53e7a2-1cac-4c5f-8ba4-3292ba2a0770", "metadata": {}, "outputs": [], "source": [ "# Save training_data to JSONL\n", "training_file_name = \"tmp_recipe_finetune_training\"\n", "dicts_to_jsonl(training_data, training_file_name)\n", "\n", "# Save validation_data to JSONL\n", "validation_file_name = \"tmp_recipe_finetune_validation\"\n", "dicts_to_jsonl(validation_data, validation_file_name)" ] }, { "cell_type": "markdown", "id": "0d149e2e-50dd-45c1-bd8d-1291975670b4", "metadata": {}, "source": [ "### Upload files\n", "\n", "You can then upload the files to our `Files` endpoint to be used by the fine-tuned model.\n" ] }, { "cell_type": "code", "execution_count": 21, "id": "69462d9e-e6bd-49b9-a064-9eae4ea5b7a8", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Training file id: file-XMhftmLXyyTvvmiLpMRMIAcL\n", "Validation file id: file-kZz433aerpPIMADZF7xC5NKd\n" ] } ], "source": [ "training_response = openai.File.create(\n", " file=open(training_file_name + \".jsonl\", \"rb\"), purpose=\"fine-tune\"\n", ")\n", "training_file_id = training_response[\"id\"]\n", "\n", "validation_response = openai.File.create(\n", " file=open(validation_file_name + \".jsonl\", \"rb\"), purpose=\"fine-tune\"\n", ")\n", "validation_file_id = validation_response[\"id\"]\n", "\n", "print(\"Training file id:\", training_file_id)\n", "print(\"Validation file id:\", validation_file_id)" ] }, { "cell_type": "markdown", "id": "d61cd381-63ad-4ed9-b0be-47a438891028", "metadata": {}, "source": [ "### Create fine-tune job\n", "\n", "Now we can create our fine-tuning job with the generated files and an optional suffix to identify the model. The response will contain an `id` which you can use to retrieve updates on the job.\n", "\n", "Note: The files have to first be processed by our system, so you might get a `File is not ready` error. In that case, simply retry a few minutes later.\n" ] }, { "cell_type": "code", "execution_count": 24, "id": "05541ceb-5628-447e-962d-7e57c112439c", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{\n", " \"object\": \"fine_tuning.job\",\n", " \"id\": \"ftjob-ksOzx7zjpsrADZfhB5eyfB0Z\",\n", " \"model\": \"gpt-3.5-turbo-0613\",\n", " \"created_at\": 1692734343,\n", " \"finished_at\": null,\n", " \"fine_tuned_model\": null,\n", " \"organization_id\": \"org-l89177bnhkme4a44292n5r3j\",\n", " \"result_files\": [],\n", " \"status\": \"created\",\n", " \"validation_file\": \"file-kZz433aerpPIMADZF7xC5NKd\",\n", " \"training_file\": \"file-XMhftmLXyyTvvmiLpMRMIAcL\",\n", " \"hyperparameters\": {\n", " \"n_epochs\": 3\n", " },\n", " \"trained_tokens\": null\n", "}\n" ] } ], "source": [ "suffix_name = \"recipe-ner\"\n", "\n", "\n", "response = openai.FineTuningJob.create(\n", " training_file=training_file_id,\n", " validation_file=validation_file_id,\n", " model=\"gpt-3.5-turbo\",\n", " suffix=suffix_name,\n", ")\n", "\n", "job_id = response[\"id\"]\n", "\n", "print(response)" ] }, { "cell_type": "markdown", "id": "1de3ed71-f2d4-4138-95a3-70da187a007e", "metadata": {}, "source": [ "#### Check job status\n", "\n", "You can make a `GET` request to the `https://api.openai.com/v1/alpha/fine-tunes` endpoint to list your alpha fine-tune jobs. In this instance you'll want to check that the ID you got from the previous step ends up as `status: succeeded`.\n", "\n", "Once it is completed, you can use the `result_files` to sample the results from the validation set (if you uploaded one), and use the ID from the `fine_tuned_model` parameter to invoke your trained model.\n" ] }, { "cell_type": "code", "execution_count": 59, "id": "d7392f48", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{\n", " \"object\": \"fine_tuning.job\",\n", " \"id\": \"ftjob-ksOzx7zjpsrADZfhB5eyfB0Z\",\n", " \"model\": \"gpt-3.5-turbo-0613\",\n", " \"created_at\": 1692734343,\n", " \"finished_at\": 1692735182,\n", " \"fine_tuned_model\": \"ft:gpt-3.5-turbo-0613:openai:recipe-ner:7qS2GFaX\",\n", " \"organization_id\": \"org-l89177bnhkme4a44292n5r3j\",\n", " \"result_files\": [\n", " \"file-Tjt0E6BvQ846m75gYxtWiRzb\"\n", " ],\n", " \"status\": \"succeeded\",\n", " \"validation_file\": \"file-kZz433aerpPIMADZF7xC5NKd\",\n", " \"training_file\": \"file-XMhftmLXyyTvvmiLpMRMIAcL\",\n", " \"hyperparameters\": {\n", " \"n_epochs\": 3\n", " },\n", " \"trained_tokens\": 39687\n", "}\n" ] } ], "source": [ "response = openai.FineTuningJob.retrieve(job_id)\n", "print(response)" ] }, { "cell_type": "markdown", "id": "30a57fbb", "metadata": {}, "source": [ "We can track the progress of the fine-tune with the events endpoint. You can rerun the cell below a few times until the fine-tune is ready. \n" ] }, { "cell_type": "code", "execution_count": 69, "id": "08cace28", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Created fine-tune: ftjob-ksOzx7zjpsrADZfhB5eyfB0Z\n", "Fine tuning job started\n", "Step 10: training loss=0.16\n", "Step 20: training loss=0.14\n", "Step 30: training loss=0.30\n", "Step 40: training loss=0.17\n", "Step 50: training loss=0.03\n", "Step 60: training loss=0.55\n", "Step 70: training loss=0.09\n", "Step 80: training loss=0.00\n", "Step 90: training loss=0.15\n", "Step 100: training loss=0.06\n", "Step 110: training loss=0.03\n", "Step 120: training loss=0.04\n", "Step 130: training loss=0.21\n", "Step 140: training loss=0.00\n", "Step 150: training loss=0.02\n", "Step 160: training loss=0.00\n", "Step 170: training loss=0.00\n", "Step 180: training loss=0.19\n", "Step 190: training loss=0.55\n", "Step 200: training loss=0.01\n", "Step 210: training loss=0.00\n", "Step 220: training loss=0.00\n", "Step 230: training loss=0.00\n", "Step 240: training loss=0.00\n", "Step 250: training loss=0.00\n", "Step 260: training loss=0.36\n", "Step 270: training loss=0.16\n", "Step 280: training loss=0.01\n", "Step 290: training loss=0.04\n", "Step 300: training loss=0.53\n", "New fine-tuned model created: ft:gpt-3.5-turbo-0613:openai:recipe-ner:7qS2GFaX\n", "Fine-tuning job successfully completed\n" ] } ], "source": [ "response = openai.FineTuningJob.list_events(id=job_id, limit=50)\n", "\n", "events = response[\"data\"]\n", "events.reverse()\n", "\n", "for event in events:\n", " print(event[\"message\"])" ] }, { "cell_type": "markdown", "id": "d0da4e32", "metadata": {}, "source": [ "Now that it's done, we can get a fine-tuned model ID from the job\n" ] }, { "cell_type": "code", "execution_count": 81, "id": "40b28c26", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{\n", " \"object\": \"fine_tuning.job\",\n", " \"id\": \"ftjob-ksOzx7zjpsrADZfhB5eyfB0Z\",\n", " \"model\": \"gpt-3.5-turbo-0613\",\n", " \"created_at\": 1692734343,\n", " \"finished_at\": 1692735182,\n", " \"fine_tuned_model\": \"ft:gpt-3.5-turbo-0613:openai:recipe-ner:7qS2GFaX\",\n", " \"organization_id\": \"org-l89177bnhkme4a44292n5r3j\",\n", " \"result_files\": [\n", " \"file-Tjt0E6BvQ846m75gYxtWiRzb\"\n", " ],\n", " \"status\": \"succeeded\",\n", " \"validation_file\": \"file-kZz433aerpPIMADZF7xC5NKd\",\n", " \"training_file\": \"file-XMhftmLXyyTvvmiLpMRMIAcL\",\n", " \"hyperparameters\": {\n", " \"n_epochs\": 3\n", " },\n", " \"trained_tokens\": 39687\n", "}\n", "\n", "Fine-tuned model id: ft:gpt-3.5-turbo-0613:openai:recipe-ner:7qS2GFaX\n" ] } ], "source": [ "response = openai.FineTuningJob.retrieve(job_id)\n", "fine_tuned_model_id = response[\"fine_tuned_model\"]\n", "\n", "print(response)\n", "print(\"\\nFine-tuned model id:\", fine_tuned_model_id)" ] }, { "cell_type": "markdown", "id": "0025e392-84cd-4566-a384-ea31ca43e567", "metadata": {}, "source": [ "## Generate with the fine-tuned model" ] }, { "cell_type": "markdown", "id": "0ab9ac11", "metadata": {}, "source": [ "The last step is to use your fine-tuned model for inference. Similar to the classic `FineTuning`, you simply call `ChatCompletions` with your new fine-tuned model name filling the `model` parameter." ] }, { "cell_type": "code", "execution_count": 87, "id": "1c7de631-b68f-4eff-9ae7-051641579c2b", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[{'content': 'You are a helpful recipe assistant. You are to extract the '\n", " 'generic ingredients from each of the recipes provided.',\n", " 'role': 'system'},\n", " {'content': 'Title: Pancakes\\n'\n", " '\\n'\n", " 'Ingredients: [\"1 c. flour\", \"1 tsp. soda\", \"1 tsp. salt\", \"1 '\n", " 'Tbsp. sugar\", \"1 egg\", \"3 Tbsp. margarine, melted\", \"1 c. '\n", " 'buttermilk\"]\\n'\n", " '\\n'\n", " 'Generic ingredients: ',\n", " 'role': 'user'}]\n" ] } ], "source": [ "test_row = test_df.iloc[0]\n", "test_messages = []\n", "test_messages.append({\"role\": \"system\", \"content\": system_message})\n", "user_message = create_user_message(test_row)\n", "test_messages.append({\"role\": \"user\", \"content\": create_user_message(test_row)})\n", "\n", "pprint(test_messages)" ] }, { "cell_type": "code", "execution_count": 88, "id": "1a1d2589", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[\"flour\", \"soda\", \"salt\", \"sugar\", \"egg\", \"margarine\", \"buttermilk\"]\n" ] } ], "source": [ "response = openai.ChatCompletion.create(\n", " model=fine_tuned_model_id, messages=test_messages, temperature=0, max_tokens=500\n", ")\n", "print(response[\"choices\"][0][\"message\"][\"content\"])" ] }, { "cell_type": "markdown", "id": "07799909-3f2a-4274-b81e-dabc048be28f", "metadata": {}, "source": [ "## Conclusion\n", "\n", "Congratulations, you are now ready to fine-tune your own models using the `ChatCompletion` format! We look forward to seeing what you build\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "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.13" } }, "nbformat": 4, "nbformat_minor": 5 }