Skip to content

Studio: OpenAI-compatible fine-tuning jobs API (/v1/files, /v1/fine_tuning/jobs) - #14496

Merged
danielhanchen merged 8 commits into
mainfrom
studio-openai-fine-tuning-api
Oct 22, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
studio-openai-fine-tuning-api

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 21, 2026 •

Copy link
Copy Markdown
Member

Fixes #13603

Existing code that uses OpenAI's fine-tuning API can now train on Unsloth Studio by changing only the base URL and the key:

from openai import OpenAI

client = OpenAI(base_url="http://localhost:8888/v1", api_key="sk-unsloth-...")

f = client.files.create(file=open("train.jsonl", "rb"), purpose="fine-tune")
job = client.fine_tuning.jobs.create(
    model="unsloth/Qwen3-4B-Instruct-2507",
    training_file=f.id,
    method={"type": "supervised", "supervised": {"hyperparameters": {"n_epochs": 2}}},
    suffix="support-bot",
    extra_body={"lora_r": 16, "max_seq_length": 4096},  # any Studio training setting
)
client.fine_tuning.jobs.retrieve(job.id)          # status, trained_tokens, fine_tuned_model
client.fine_tuning.jobs.list_events(job.id)       # loss per step
client.fine_tuning.jobs.checkpoints.list(job.id)
client.fine_tuning.jobs.cancel(job.id)

OpenAI is winding down its own fine-tuning platform (new jobs only until January 6, 2027), and none of the popular open-source trainers serve this API today, so this gives people moving off it a local drop-in.

How it works

A thin translation layer in studio/backend/routes/openai_fine_tuning.py, mounted on /v1 next to the existing OpenAI inference routes. It adds no new capability: an API key can already do all of this through /api/train.

OpenAI route Studio
POST /v1/files (purpose fine-tune), GET /v1/files, GET /v1/files/{id} The same dataset upload as the Train page, so the file also shows up in the dataset picker. file-<id> is the upload's own id.
POST /v1/fine_tuning/jobs Builds a normal training request and calls the same handler as /api/train/start, so every guard and refusal applies (one run at a time, busy GPU, gated models, account sandbox). n_epochs, batch_size, seed and suffix map directly, validation_file becomes the eval set (with evaluation on), a wandb integration turns on W&B logging for its project, learning_rate_multiplier scales Studio's default 2e-4, and Studio settings (lora_r, max_steps, load_in_4bit, training_type, ...) go through extra_body.
GET /v1/fine_tuning/jobs, GET /v1/fine_tuning/jobs/{id} Read from the training history; a job is a Studio run (ftjob_<run id>), so runs started from the UI are listed too. Status: running, succeeded, cancelled, failed, plus validating_files / queued before the worker is up. fine_tuned_model is the run folder name Chat and Export show.
GET .../events One metrics event per logged step (loss, learning rate, grad norm, eval loss), framed by start and outcome messages.
GET .../checkpoints The run's checkpoint-N folders with their step loss.
POST .../cancel /api/train/stop for that job (saves at the next safe step).

API keys never see host paths: a local model path comes back as its handle and error messages are path-redacted, as on the other routes. /v1/files gets the dataset upload's own body cap instead of the small JSON cap.

Not supported yet, with a clear 400: method dpo and reinforcement, and pause / resume. A second job while one is running is refused with 409 rather than queued, which the SDK raises as ConflictError.

No change for existing users

Only new routes. The UI, the Train page flow, /api/train and the existing /v1 inference routes are untouched.

Verified end to end

On a Colab T4 with Studio installed from this branch (studio/setup.sh --local), the stock openai SDK pointed at http://127.0.0.1:8888/v1 with an sk-unsloth key:

Call Result
files.create(codes.jsonl, purpose="fine-tune") file-b66b..., 10522 bytes, processed
fine_tuning.jobs.create(model="unsloth/Qwen3-0.6B", ..., extra_body={"max_steps": 12, "save_steps": 6}) validating_files, then running, then succeeded after about 100 s
jobs.retrieve fine_tuned_model="unsloth_Qwen3-0.6B__project-e2e_1792585453", trained_tokens=1000
jobs.list_events one event per step, loss 4.40 at step 1 down to 1.47 at step 12
jobs.checkpoints.list checkpoint-12 (loss 1.47) and checkpoint-6 (loss 2.86)
jobs.create while a job is training 409 Training is already in progress. Stop current training before starting a new one.
jobs.cancel mid-run cancelled, and stays cancelled on retrieve

On main the same calls return 404.

After merge, the same flow on the other GPU platforms, Studio built from main at the merge commit:

Platform Model Result
Apple Silicon, macOS 15 arm64 (MLX), GitHub runner unsloth/gemma-3-270m-it, 6 steps running then succeeded in about 60 s, loss 9.67 to 6.24, checkpoint-6
AMD Radeon 8060S (gfx1151, ROCm 7.13), Linux unsloth/gemma-3-270m-it, 6 steps succeeded, loss 10.38 to 6.55, 1 checkpoint; the merge commit's parent answers POST /v1/files with 404

Tests

studio/backend/tests/test_openai_fine_tuning.py drives the routes with the real openai SDK: upload then create (checks the exact training request built), a finished run read back as a succeeded job with events and checkpoints, a failed run with its host paths redacted for an API key, cancel, the refusals, and paging through the whole history. The multi-account route matrix now covers the new object routes (another account and the owner get 404).

@danielhanchen danielhanchen self-assigned this Oct 21, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-22T07:20:24.186735Z 6bbe268 Manual request
🔒 Security Review ⚠️ Failed 2026-10-21T11:23:58.219189Z
We couldn’t complete this review. Comment @codex security review to try again.
c68a9e9 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

…history, keep fields before the run row, isolation matrix

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1f30cd8a00

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +471 to +475
rows = conn.execute(
"SELECT step, loss, learning_rate, grad_norm, eval_loss, epoch, elapsed_seconds "
"FROM training_metrics WHERE run_id = ? AND step > 0 ORDER BY step",
(run_id,),
).fetchall()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Bound event queries to the requested page

For long runs, every events request fetches and materializes the entire metrics history before _paged applies after and limit. A run near the supported one-million-step maximum can therefore allocate a very large list and scan every metric on each polling request even when the client asks for only 20 events; apply cursor ordering and LIMIT limit + 1 in SQL instead.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing: metrics are one row per logged step, so even a long run is a few thousand rows per read, and million-step LoRA runs are not a realistic Studio workload.

"validation_file": _file_id_for(eval_datasets[0]) if eval_datasets else None,
"method": {"type": "supervised", "supervised": {"hyperparameters": hyperparameters}},
"suffix": config.get("project_name"),
"metadata": None,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve accepted job metadata

When a client supplies the declared metadata field, job creation succeeds, but _training_config never persists it and every create, retrieve, and list response hard-codes it to None. This silently discards experiment labels that callers expect to recover from the job; persist and return the value, or reject the field explicitly rather than accepting and losing it.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing: metadata is accepted so OpenAI clients that send it keep working; Studio has no place to store it on a run, and nothing in the job lifecycle depends on it.

Comment on lines +361 to +366
n_epochs = hyperparameters.get("n_epochs", "auto")
if n_epochs != "auto":
config["num_epochs"] = int(n_epochs)
batch_size = hyperparameters.get("batch_size", "auto")
if batch_size != "auto":
config["batch_size"] = int(batch_size)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject fractional integer hyperparameters

If a client sends a JSON number such as n_epochs: 2.9 or batch_size: 3.5, int() silently truncates it and starts a materially different training run instead of producing the promised integer-or-auto validation error. Validate that these values are integral before conversion so malformed experiment settings cannot be silently changed.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing: n_epochs and batch_size are integers in the OpenAI API, so a fractional value is malformed input from the caller.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: eb87c90d0c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

"seed": config.get("random_seed"),
"status": status,
"trained_tokens": trained_tokens,
"training_file": _file_id_for(datasets[0]) if datasets else config.get("hf_dataset"),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Exclude runs that cannot supply a training-file ID

Because the jobs API deliberately projects every Studio run, UI runs backed by recipe-generated local datasets, S3 data, or other non-upload sources can reach this branch with a local path whose basename lacks the 32-character upload ID. _file_id_for then returns None, so list and retrieve emit training_file: null even though FineTuningJob.training_file is a required file-ID string and there is no corresponding /v1/files object for clients to inspect. Either expose a stable File object for these sources or omit incompatible runs from this API.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing: the SDK parses a null training_file without error, and hiding runs started from the Train page would make real jobs disappear from the list.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1e759e7a5f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +369 to +372
if body.validation_file:
config["local_eval_datasets"] = [str(_find_file(body.validation_file))]
# Studio evaluates only when eval_steps > 0; OpenAI always validates a given validation_file.
config.setdefault("eval_steps", 0.1)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Force evaluation when a validation file is supplied

When a client supplies validation_file together with extra_body={"eval_steps": 0}, the earlier config.update(extra) preserves zero here, so Studio records the evaluation dataset but never runs evaluation. This contradicts the route's stated OpenAI behavior and silently removes validation metrics from the experiment; assign a positive cadence when validation_file is present rather than using setdefault.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing: extra_body is the caller's explicit Studio override, so an explicit eval_steps of 0 is honoured on purpose; without it a validation_file turns evaluation on.

Comment on lines +383 to +385
config.setdefault("enable_wandb", True)
if wandb.get("project"):
config.setdefault("wandb_project", wandb["project"])

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Let the requested W&B integration override extra defaults

When callers include a standard W&B integration but their Studio extra_body also contains a default such as enable_wandb=false or a different wandb_project, these setdefault calls retain the extra-body values, disabling logging or sending it to the wrong project despite the explicit integration request. Fresh evidence beyond the earlier fixed finding is that integrations are now parsed but can still be silently overridden; set the integration fields directly or reject conflicting values.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing: same rule, an explicit extra_body value wins over the OpenAI-shaped default.

Comment on lines +163 to +165
@router.get("/files/{file_id}")
async def retrieve_file(file_id: str, current_subject: str = Depends(get_current_subject)):
return await asyncio.to_thread(lambda: _file_object(_find_file(file_id)))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Add the Files API deletion operation

Clients that clean up a training upload with files.delete(file_id) receive a method-not-allowed response and the dataset remains on disk indefinitely, because a repo-wide route search finds only this GET handler for /files/{file_id} and no DELETE counterpart. This breaks the normal Files API lifecycle and makes automated fine-tuning workflows accumulate potentially large uploads; add an account-scoped delete handler for these upload IDs.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not adding here: Studio has no route that deletes a dataset upload today, and an upload can back an existing run's resume, so deletion is a separate change rather than part of this compatibility layer.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 21, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: e7b22d9a0f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 21, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

pre-commit.ci run

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 6bbe268aeb

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

danielhanchen added a commit to Etherll/unsloth that referenced this pull request Oct 27, 2026
…i#14645)

Follow-up to unslothai#14496 for unslothai#13603.

Until now a second `POST /v1/fine_tuning/jobs` while another training
run held the GPU was refused with a 400 ("Training already active").
OpenAI's API instead accepts the job and reports it as `queued`, and
clients written against it poll until it runs. This makes Studio do the
same.

## What changes
- A job created while training (or a diffusion LoRA run) is active, or
while other jobs are already waiting, is accepted with `status:
"queued"` and an `ftjob_q...` id.
- Jobs start first in, first out once training is idle. Each one starts
through the same `start_training` handler as before, as the account that
created it, so every existing guard and refusal still applies.
- `retrieve`, `list`, `events` (queue position), `checkpoints` and
`cancel` all accept the queued id, both before and after the job starts.
After it starts, the id resolves to the real training run.
- Cancelling a queued job removes it from the queue; it never starts.
- A queued job whose start is refused (bad model, resume mismatch, a 409
that keeps happening while the GPU is idle) is marked `failed` with the
reason instead of retrying forever.
- Queued jobs are visible only to their own account, like runs.

## What does not change
- The Studio UI and `/api/train/*` are untouched. A training run started
from the UI still starts immediately when the GPU is free; the queue
only waits for it.
- With the GPU idle and nothing queued, `create` starts the job right
away, exactly as before.

The queue lives in the server process, so queued (not yet started) jobs
do not survive a Studio restart. That is stated in the module docstring.

## Tests
- `tests/test_openai_fine_tuning.py`: 14 passed (4 new: FIFO start
order, cancel before start, refused start fails the job, another account
cannot see or cancel a queued job). Module state is now reset per test.
- `tests/multi_account/test_alice_bob_matrix.py -k "openai or fine_tun
or training"`: 144 passed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] OpenAI-compatible Fine-tuning Jobs API for Unsloth Studio

1 participant