GPT Finetuning With Wandb
Fine-tune ChatGPT-3.5 and GPT-4 with Weights & Biases
Note: you will need an OpenAI API key to run this colab.
If you use OpenAI's API to fine-tune ChatGPT-3.5, you can now use the W&B integration to track experiments, models, and datasets in your central dashboard.
All it takes is one line: openai wandb sync
See the OpenAI section in the Weights & Biases documentation for full details of the integration
Optional: Fine-tune ChatGPT-3.5
It's always more fun to experiment with your own projects so if you have already used the openai API to fine-tune an OpenAI model, just skip this section.
Otherwise let's fine-tune ChatGPT-3.5 on a legal dataset!
Imports and initial set-up
Start your Weigths & Biases run. If you don't have an account you can sign up for one for free at www.wandb.ai
Set up your API key
Dataset Preparation
We download a dataset from LegalBench, a project to curate tasks for evaluating legal reasoning, specifically the Contract NLI Explicit Identification task.
This comprises of a total of 117 examples, from which we will create our own train and test datasets
Let's look at a few samples.
(117,
, [{'answer': 'No',
, 'index': '94',
, 'text': 'Recipient shall use the Confidential Information exclusively for HySafe purposes, especially to advice the Governing Board of HySafe. ',
, 'document_name': 'NDA_V3.pdf',
, 'new_index': 0},
, {'answer': 'No',
, 'index': '53',
, 'text': '3. In consideration of each and every disclosure of CONFIDENTIAL INFORMATION, the Parties agree to: (c) make no disclosures of any CONFIDENTIAL INFORMATION to any party other than officers and employees of a Party to this IRA; (d) limit access to CONFIDENTIAL INFORMATION to those officers and employees having a reasonable need for such INFORMATION and being boUnd by a written obligation to maintain the confidentiality of such INFORMATION; and ',
, 'document_name': '1084000_0001144204-06-046785_v056501_ex10-16.txt',
, 'new_index': 1}]) Format our Data for Chat Completion Models
We modify the base_prompt from the LegalBench task to make it a zero-shot prompt, as we are training the model instead of using few-shot prompting
We now split it into training/validation dataset, lets train on 30 samples and test on the remainder
(30,
, 87,
, 87,
, {'messages': [{'role': 'system',
, 'content': 'Identify if the clause provides that all Confidential Information shall be expressly identified by the Disclosing Party. Answer with only `Yes` or `No`'},
, {'role': 'user',
, 'content': '2. The Contractor shall not, without the State’s prior written consent, copy, disclose, publish, release, transfer, disseminate, use, or allow access for any purpose or in any form, any Confidential Information except for the sole and exclusive purpose of performing under the Contract. '},
, {'role': 'assistant', 'content': 'No'}]}) Save the data to Weigths & Biases
Save the data in a train and test file first
Next, we validate that our training data is in the correct format using a script from the OpenAI fine-tuning documentation
Validate train data
Num examples: 30
First example:
{'role': 'system', 'content': 'Identify if the clause provides that all Confidential Information shall be expressly identified by the Disclosing Party. Answer with only `Yes` or `No`'}
{'role': 'user', 'content': 'Recipient shall use the Confidential Information exclusively for HySafe purposes, especially to advice the Governing Board of HySafe. '}
{'role': 'assistant', 'content': 'No'}
No errors found
Num examples missing system message: 0
Num examples missing user message: 0
#### Distribution of num_messages_per_example:
min / max: 3, 3
mean / median: 3.0, 3.0
p5 / p95: 3.0, 3.0
#### Distribution of num_total_tokens_per_example:
min / max: 69, 319
mean / median: 143.46666666666667, 122.0
p5 / p95: 82.10000000000001, 235.10000000000002
#### Distribution of num_assistant_tokens_per_example:
min / max: 1, 1
mean / median: 1.0, 1.0
p5 / p95: 1.0, 1.0
0 examples may be over the 4096 token limit, they will be truncated during fine-tuning
Dataset has ~4304 tokens that will be charged for during training
By default, you'll train for 3 epochs on this dataset
By default, you'll be charged for ~12912 tokens
See pricing page to estimate total costs
Log our data to Weigths & Biases Artifacts for storage and versioning
Failed to detect the name of this notebook, you can set it manually with the WANDB_NOTEBOOK_NAME environment variable to enable code saving. wandb: Currently logged in as: capecape. Use `wandb login --relogin` to force relogin
wandb: WARNING Source type is set to 'repo' but some required information is missing from the environment. A job will not be created from this run. See https://docs.wandb.ai/guides/launch/create-job
Create a fine-tuned model
We'll now use OpenAI API to fine-tune ChatGPT-3.5
Let's first download our training & validation files and save them to a folder called my_data. We will retrieve the latest version of the artifact, but it could also be v0, v1 or any alias we associated with it
VBox(children=(Label(value='Waiting for wandb.init()...\r'), FloatProgress(value=0.016751802766035932, max=1.0…
'my_data/encoded_train_data.jsonl'
Then we upload the training data to OpenAI. OpenAi has to process the data, so this will take a few minutes depending on the size of your dataset.
<File file id=file-spPASR6VWco54SqfN2yo7T8v> JSON: {
, "object": "file",
, "id": "file-spPASR6VWco54SqfN2yo7T8v",
, "purpose": "fine-tune",
, "filename": "file",
, "bytes": 24059,
, "created_at": 1693388388,
, "status": "uploaded",
, "status_details": null
,} Time to train the model!
Let's define our ChatGPT-3.5 fine-tuning hyper-parameters.
<FineTuningJob fine_tuning.job id=ftjob-x4tl83IlSGolkUF3fCFyZNGs> JSON: {
, "object": "fine_tuning.job",
, "id": "ftjob-x4tl83IlSGolkUF3fCFyZNGs",
, "model": "gpt-3.5-turbo-0613",
, "created_at": 1693388447,
, "finished_at": null,
, "fine_tuned_model": null,
, "organization_id": "org-WnF2wEqNkV1Nj65CzDxr6iUm",
, "result_files": [],
, "status": "created",
, "validation_file": null,
, "training_file": "file-spPASR6VWco54SqfN2yo7T8v",
, "hyperparameters": {
, "n_epochs": 3
, },
, "trained_tokens": null
,} this takes around 5 minutes to train, and you get an email from OpenAI when finished.
Thats it!
Now your model is training on OpenAI's machines. To get the current state of your fine-tuning job, run:
('succeeded',
, 12732,
, 1693389024,
, 'ft:gpt-3.5-turbo-0613:weights-biases::7tC85HcX') Show recent events for our fine-tuning job
<OpenAIObject list> JSON: {
, "object": "list",
, "data": [
, {
, "object": "fine_tuning.job.event",
, "id": "ftevent-5x9Y6Payk6fIdyJyMRY5um1v",
, "created_at": 1693389024,
, "level": "info",
, "message": "Fine-tuning job successfully completed",
, "data": null,
, "type": "message"
, },
, {
, "object": "fine_tuning.job.event",
, "id": "ftevent-i16NTGNakv9P0RkOtJ7vvvoG",
, "created_at": 1693389022,
, "level": "info",
, "message": "New fine-tuned model created: ft:gpt-3.5-turbo-0613:weights-biases::7tC85HcX",
, "data": null,
, "type": "message"
, },
, {
, "object": "fine_tuning.job.event",
, "id": "ftevent-MkLrJQ8sDgaC67CdmFMwsIjV",
, "created_at": 1693389017,
, "level": "info",
, "message": "Step 90/90: training loss=0.00",
, "data": {
, "step": 90,
, "train_loss": 2.5828578600339824e-06,
, "train_mean_token_accuracy": 1.0
, },
, "type": "metrics"
, },
, {
, "object": "fine_tuning.job.event",
, "id": "ftevent-3sRpTRSjK3TfFRZY88HEASpX",
, "created_at": 1693389015,
, "level": "info",
, "message": "Step 89/90: training loss=0.00",
, "data": {
, "step": 89,
, "train_loss": 2.5828578600339824e-06,
, "train_mean_token_accuracy": 1.0
, },
, "type": "metrics"
, },
, {
, "object": "fine_tuning.job.event",
, "id": "ftevent-HtS6tJMVPOmazquZ82a1iCdV",
, "created_at": 1693389015,
, "level": "info",
, "message": "Step 88/90: training loss=0.00",
, "data": {
, "step": 88,
, "train_loss": 2.5828578600339824e-06,
, "train_mean_token_accuracy": 1.0
, },
, "type": "metrics"
, }
, ],
, "has_more": true
,} We can run a few different fine-tunes with different parameters or even with different datasets.
Log OpenAI fine-tune jobs to Weights & Biases
We can log our fine-tunes with a simple command.
usage: openai wandb sync [-h] [-i ID] [-n N_FINE_TUNES] [--project PROJECT]
[--entity ENTITY] [--force] [--legacy]
options:
-h, --help show this help message and exit
-i ID, --id ID The id of the fine-tune job (optional)
-n N_FINE_TUNES, --n_fine_tunes N_FINE_TUNES
Number of most recent fine-tunes to log when an id is
not provided. By default, every fine-tune is synced.
--project PROJECT Name of the Weights & Biases project where you're
sending runs. By default, it is "OpenAI-Fine-Tune".
--entity ENTITY Weights & Biases username or team name where you're
sending runs. By default, your default entity is used,
which is usually your username.
--force Forces logging and overwrite existing wandb run of the
same fine-tune.
--legacy Log results from legacy OpenAI /v1/fine-tunes api
Calling openai wandb sync will log all un-synced fine-tuned jobs to W&B
Below we are just logging 1 job, passing:
- our OpenAI key as an environment variable
- the id of the fine-tune job we'd like to log
- the W&B project of where to log it to
See the OpenAI section in the Weights & Biases documentation for full details of the integration
Retrieving fine-tune job... wandb: Currently logged in as: capecape. Use `wandb login --relogin` to force relogin wandb: Tracking run with wandb version 0.15.9 wandb: Run data is saved locally in /Users/tcapelle/work/examples/colabs/openai/wandb/run-20230830_115915-ftjob-x4tl83IlSGolkUF3fCFyZNGs wandb: Run `wandb offline` to turn off syncing. wandb: Syncing run ftjob-x4tl83IlSGolkUF3fCFyZNGs wandb: ⭐️ View project at https://wandb.ai/capecape/OpenAI-Fine-Tune wandb: 🚀 View run at https://wandb.ai/capecape/OpenAI-Fine-Tune/runs/ftjob-x4tl83IlSGolkUF3fCFyZNGs wandb: Waiting for W&B process to finish... (success). wandb: wandb: Run history: wandb: train_accuracy ▁▁▁▁▁█▁█▁██▁████████████████████████████ wandb: train_loss █▇▆▂▂▁▂▁▅▁▁▇▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁ wandb: wandb: Run summary: wandb: fine_tuned_model ft:gpt-3.5-turbo-061... wandb: status succeeded wandb: train_accuracy 1.0 wandb: train_loss 0.0 wandb: wandb: 🚀 View run ftjob-x4tl83IlSGolkUF3fCFyZNGs at: https://wandb.ai/capecape/OpenAI-Fine-Tune/runs/ftjob-x4tl83IlSGolkUF3fCFyZNGs wandb: Synced 6 W&B file(s), 0 media file(s), 1 artifact file(s) and 0 other file(s) wandb: Find logs at: ./wandb/run-20230830_115915-ftjob-x4tl83IlSGolkUF3fCFyZNGs/logs 🎉 wandb sync completed successfully
VBox(children=(Label(value='0.050 MB of 0.050 MB uploaded (0.000 MB deduped)\r'), FloatProgress(value=1.0, max…
wandb: WARNING Source type is set to 'repo' but some required information is missing from the environment. A job will not be created from this run. See https://docs.wandb.ai/guides/launch/create-job
upload_file exception https://storage.googleapis.com/wandb-production.appspot.com/capecape/OpenAI-Fine-Tune/1ili9l51/requirements.txt?Expires=1693475972&GoogleAccessId=gorilla-files-url-signer-man%40wandb-production.iam.gserviceaccount.com&Signature=NzF9wj2gS8rMEwRT9wlft2lNubemw67f2qrz9Zy90Bjxg5xCL9pIu%2FRbBGjRwLA2v64PuiP23Au5Dho26Tnw3UjUS1apqTkaOgjWDTlCCiDLzvMUsqHf0lhhWIgGMZcsA4gPpOi%2Bc%2ByJm4z6JE7D6RJ7r8y4fI0Jg6fX9KSWpzh8INiM6fQZiQjUChLVdtNJQZ2gfu7xRc%2BZIUEjgDuUqmS705pIUOgJXA9MS3%2Fhewkc7CxWay4ReMJixBZgaqLIRqHQnyzb38I5nPrRS3JrwrigQyX6tOsK05LDLA0o%2Bs0K11664%2F1ZxO6mSTfOaw7tXUmbUUWFOp33Qq8KXNz9Zg%3D%3D: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))
upload_file request headers: {'User-Agent': 'python-requests/2.28.2', 'Accept-Encoding': 'gzip, deflate, br', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Length': '4902'}
upload_file response body:
upload_file exception https://storage.googleapis.com/wandb-production.appspot.com/capecape/OpenAI-Fine-Tune/1ili9l51/conda-environment.yaml?Expires=1693475972&GoogleAccessId=gorilla-files-url-signer-man%40wandb-production.iam.gserviceaccount.com&Signature=wKnFdg7z7CiJOMn4WSvt6GSj2hPnMr0Xc4KuwAXa8akLucmw700x%2FWF87jmWaqnp%2FK4%2BF6JTRghQAokXF9jxCcXBSYhgFhCVACrOVyN%2BSTZ4u8tDgD6Dm%2FEFwWObiH%2BALSS1N0FmG7i6kL9Evyng3yPc4noEz%2FkLNIDIascAPgUe9UkPaBCRc9j7OxzYJx07bpeL4HaGe4yaCvk2mSVr4l%2FUfsICBI6E4KKrLDvtZvFFFUB4MgqXp0Sxc0k0pOxaw9zZhiNQQELDnhnuNY4wi78EPiXN1BpU6bTgIYaHe5mkS%2B7M5HiFs83ML98JI2OeRiAjAGtIIETT4xDjTYWVpA%3D%3D: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))
upload_file request headers: {'User-Agent': 'python-requests/2.28.2', 'Accept-Encoding': 'gzip, deflate, br', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Length': '8450'}
upload_file response body:
Our fine-tunes are now successfully synced to Weights & Biases.
Anytime we have new fine-tunes, we can just call openai wandb sync to add them to our dashboard.
Run evalution and log the results
The best way to evaluate a generative model is to explore sample predictions from your evaluation set.
Let's generate a few inference samples and log them to W&B and see how the performance compares to a baseline ChatGPT-3.5 model
There are 87 test examples
Run evaluation on the Fine-Tuned Model
Set up OpenAI call with retries
Let's get our trained model id
'ft:gpt-3.5-turbo-0613:weights-biases::7tC85HcX'
Run evaluation and log results to W&B
0%| | 0/87 [00:00<?, ?it/s]
Calculate the accuracy of the fine-tuned model and log to W&B
Accuracy is 0.8390804597701149
Run evaluation on a Baseline model for comparison
Lets compare our model to the baseline model, gpt-3.5-turbo
0%| | 0/87 [00:00<?, ?it/s]
Calculate the accuracy of the fine-tuned model and log to W&B
Baseline Accurcy is: 0.7931034482758621
VBox(children=(Label(value='0.248 MB of 0.248 MB uploaded (0.000 MB deduped)\r'), FloatProgress(value=1.0, max…
wandb: WARNING Source type is set to 'repo' but some required information is missing from the environment. A job will not be created from this run. See https://docs.wandb.ai/guides/launch/create-job
And thats it! In this example we have prepared our data, logged it to Weights & Biases, fine-tuned an OpenAI model using that data, logged the results to Weights & Biases and then run evaluation on the fine-tuned model.
From here you can start to train on larger or more complex tasks, or else explore other ways to modify ChatGPT-3.5 such as giving it a different tone and style or response.