Repository navigation
Studio: OpenAI-compatible fine-tuning jobs API (/v1/files, /v1/fine_tuning/jobs) - #14496
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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]
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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".
| 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() |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
Not changing: n_epochs and batch_size are integers in the OpenAI API, so a fractional value is malformed input from the caller.
…, page past a live job [skip ci]
… legacy non-finite configs [skip ci]
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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"), |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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".
| 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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| config.setdefault("enable_wandb", True) | ||
| if wandb.get("project"): | ||
| config.setdefault("wandb_project", wandb["project"]) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
Not changing: same rule, an explicit extra_body value wins over the OpenAI-shaped default.
| @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))) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
…ume with 400 [skip ci]
|
Codex Review: Didn't find any major issues. Nice work! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
pre-commit.ci run |
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
…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.
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:
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/v1next to the existing OpenAI inference routes. It adds no new capability: an API key can already do all of this through/api/train.POST /v1/files(purposefine-tune),GET /v1/files,GET /v1/files/{id}file-<id>is the upload's own id.POST /v1/fine_tuning/jobs/api/train/start, so every guard and refusal applies (one run at a time, busy GPU, gated models, account sandbox).n_epochs,batch_size,seedandsuffixmap directly,validation_filebecomes the eval set (with evaluation on), awandbintegration turns on W&B logging for its project,learning_rate_multiplierscales Studio's default 2e-4, and Studio settings (lora_r,max_steps,load_in_4bit,training_type, ...) go throughextra_body.GET /v1/fine_tuning/jobs,GET /v1/fine_tuning/jobs/{id}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_modelis the run folder name Chat and Export show.GET .../eventsmetricsevent per logged step (loss, learning rate, grad norm, eval loss), framed by start and outcome messages.GET .../checkpointscheckpoint-Nfolders with their step loss.POST .../cancel/api/train/stopfor 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/filesgets the dataset upload's own body cap instead of the small JSON cap.Not supported yet, with a clear 400:
methoddpoandreinforcement, and pause / resume. A second job while one is running is refused with 409 rather than queued, which the SDK raises asConflictError.No change for existing users
Only new routes. The UI, the Train page flow,
/api/trainand the existing/v1inference routes are untouched.Verified end to end
On a Colab T4 with Studio installed from this branch (
studio/setup.sh --local), the stockopenaiSDK pointed athttp://127.0.0.1:8888/v1with ansk-unslothkey:files.create(codes.jsonl, purpose="fine-tune")file-b66b..., 10522 bytes,processedfine_tuning.jobs.create(model="unsloth/Qwen3-0.6B", ..., extra_body={"max_steps": 12, "save_steps": 6})validating_files, thenrunning, thensucceededafter about 100 sjobs.retrievefine_tuned_model="unsloth_Qwen3-0.6B__project-e2e_1792585453",trained_tokens=1000jobs.list_eventsjobs.checkpoints.listcheckpoint-12(loss 1.47) andcheckpoint-6(loss 2.86)jobs.createwhile a job is trainingTraining is already in progress. Stop current training before starting a new one.jobs.cancelmid-runcancelled, and stayscancelledon retrieveOn main the same calls return 404.
After merge, the same flow on the other GPU platforms, Studio built from main at the merge commit:
unsloth/gemma-3-270m-it, 6 stepsrunningthensucceededin about 60 s, loss 9.67 to 6.24,checkpoint-6unsloth/gemma-3-270m-it, 6 stepssucceeded, loss 10.38 to 6.55, 1 checkpoint; the merge commit's parent answersPOST /v1/fileswith 404Tests
studio/backend/tests/test_openai_fine_tuning.pydrives the routes with the realopenaiSDK: 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).