Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio fine-tuning queue: do not start jobs cancelled during the batching probe (#16151)

Daniel Han77e3fa5d3b79
diff --git a/studio/backend/routes/openai_fine_tuning.py b/studio/backend/routes/openai_fine_tuning.py
index 40221237030..0a81d4576a1 100644
--- a/studio/backend/routes/openai_fine_tuning.py
+++ b/studio/backend/routes/openai_fine_tuning.py
@@ -1,16 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""OpenAI-compatible fine-tuning API (``/v1/files`` and ``/v1/fine_tuning/jobs``) over Studio's own training.
-
-A thin translation layer: uploads land where ``/api/hub/datasets/upload`` puts them, jobs start through the
-same ``start_training`` handler as ``/api/train/start`` (every guard and refusal included), and job state is
-read back from the training history, so a job is just a Studio training run under another name. Nothing here
-grants a capability an API key does not already have through ``/api/train``.
-
-A job created while the GPU is busy waits in a first-in-first-out queue and starts, as its own account, once
-training is idle. The queue lives in this process: queued jobs do not survive a Studio restart.
-"""
+"""OpenAI fine-tuning over Studio; queued jobs do not survive a restart."""
from __future__ import annotations
@@ -43,11 +34,11 @@ logger = get_logger(__name__)
router = APIRouter()
FILE_PREFIX = "file-"
-JOB_PREFIX = "ft" # "job_20261021_101500_ab12cd34" -> "ftjob_20261021_101500_ab12cd34"
-# OpenAI scales its own default; Studio's default learning rate is the base the multiplier scales.
+JOB_PREFIX = "ft"
+
BASE_LEARNING_RATE = 2e-4
_UPLOAD_ID = re.compile(r"^[0-9a-f]{32}$")
-# Set by this layer from the OpenAI fields; extra_body may not override them.
+
_MANAGED_FIELDS = frozenset(
{"model_name", "local_datasets", "local_eval_datasets", "start_request_id", "project_name"}
)
@@ -72,7 +63,6 @@ _PHASE_STATUS = {
class FineTuningJobCreate(BaseModel):
- # Unknown keys are Studio training settings sent through the SDK's extra_body.
model_config = ConfigDict(extra = "allow")
model: str
@@ -102,9 +92,6 @@ def _unix(value: Any) -> Optional[int]:
return int(parsed.timestamp())
-# Files
-
-
def _upload_id(name: str) -> Optional[str]:
prefix, sep, _rest = name.partition("_")
return prefix if sep and _UPLOAD_ID.match(prefix) else None
@@ -125,7 +112,6 @@ def _file_object(path: Path) -> dict[str, Any]:
def _uploaded_files() -> list[Path]:
- """This account's dataset uploads, newest first, as the Studio dataset picker lists them."""
items = local_datasets.list_local_datasets_response().datasets
paths = [Path(item.path) for item in items if item.source == "upload"]
return [path for path in paths if _upload_id(path.name)]
@@ -175,9 +161,6 @@ async def retrieve_file(file_id: str, current_subject: str = Depends(get_current
return await asyncio.to_thread(lambda: _file_object(_find_file(file_id)))
-# Jobs
-
-
def _job_id(run_id: str) -> str:
return f"{JOB_PREFIX}{run_id}"
@@ -239,7 +222,6 @@ def _job_object(
def _run_config(run: dict[str, Any]) -> dict[str, Any]:
try:
- # An older install may have stored Infinity / NaN, which the JSON response cannot carry.
config = drop_non_finite(json.loads(run.get("config_json") or "{}"))
except (TypeError, ValueError):
config = {}
@@ -271,18 +253,16 @@ def _job_from_run(run: dict[str, Any]) -> dict[str, Any]:
created_at = _unix(run.get("started_at")),
finished_at = _unix(run.get("ended_at")) if status != "running" else None,
error = (run.get("error_message") or "Training failed") if status == "failed" else None,
- # The run folder: the name Studio's chat, export and checkpoint lists show for this model.
fine_tuned_model = Path(output_dir).name if status == "succeeded" and output_dir else None,
trained_tokens = _trained_tokens(run["id"]),
)
-# Jobs started here, until their history row exists: a retrieve right after create keeps the job's fields.
_STARTED: dict[str, tuple[dict[str, Any], int]] = {}
_STARTED_LIMIT = 16
# Cancelled here while the worker finishes its step: the run row reads "running" until it stops.
_CANCELLING: set[str] = set()
-# Multi-LoRA batches started here: member run id -> batch job id, batch job id -> member run ids.
+
_BATCH_OF: dict[str, str] = {}
_BATCHES: dict[str, list[str]] = {}
@@ -302,7 +282,6 @@ def _remember_batch(batch_id: str, run_ids: list[str]) -> None:
def _for_caller(job: dict[str, Any], via_api_key: bool) -> dict[str, Any]:
- """An API key never sees host paths: a local model becomes its handle, an error loses its paths."""
if host_paths_visible(via_api_key):
return job
model = redact_host_paths({"model_name": job["model"]}, via_api_key = via_api_key)
@@ -313,7 +292,6 @@ def _for_caller(job: dict[str, Any], via_api_key: bool) -> dict[str, Any]:
def _status_field(status: Any, name: str) -> Any:
- # The status route hands back a model, or its redacted dump for an API key.
return status.get(name) if isinstance(status, dict) else getattr(status, name, None)
@@ -331,7 +309,7 @@ async def _job(run_id: str, current_subject: str, via_api_key: bool) -> dict[str
run = await asyncio.to_thread(get_run, run_id)
if run is not None:
return _for_caller(await asyncio.to_thread(_job_from_run, run), via_api_key)
- # A started job has no history row until its worker is up; the live status still knows it.
+
status = await _current_status(current_subject, via_api_key)
if status is not None and _status_field(status, "job_id") == _BATCH_OF.get(run_id, run_id):
phase = _status_field(status, "phase")
@@ -340,8 +318,6 @@ async def _job(run_id: str, current_subject: str, via_api_key: bool) -> dict[str
config, created_at = _STARTED.get(run_id, ({}, None))
state = _PHASE_STATUS.get(phase, "queued")
if run_id in _BATCH_OF and state in ("queued", "running"):
- # A member's row appears with its first step; until then the batch's phase (read from its
- # setup messages) would flip it between running and validating_files.
state = "validating_files"
if failed:
state = "failed"
@@ -396,7 +372,7 @@ def _training_config(body: FineTuningJobCreate) -> dict[str, Any]:
config["local_datasets"] = [str(_find_file(body.training_file))]
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)
if body.suffix:
config["project_name"] = body.suffix
@@ -407,7 +383,7 @@ def _training_config(body: FineTuningJobCreate) -> dict[str, Any]:
f"Integration '{integration.get('type')}' is not supported; use 'wandb'."
)
wandb = _object(integration.get("wandb"), "integrations[].wandb")
- # The W&B key is the server's WANDB_API_KEY, or wandb_token through extra_body.
+
config.setdefault("enable_wandb", True)
if wandb.get("project"):
config.setdefault("wandb_project", wandb["project"])
@@ -431,18 +407,18 @@ def _training_config(body: FineTuningJobCreate) -> dict[str, Any]:
QUEUE_POLL_S = 5.0
-# A 409 with training idle is a conflict that will not clear by waiting (resume, offline state): give up.
+
QUEUE_IDLE_CONFLICTS = 12
_TERMINAL_KEEP = 256
_BUSY_ERRORS = ("Training already active", "Diffusion training already active")
-# 409s that clear by themselves (a chat request in flight, a transformers install): never give up on these.
+
_TRANSIENT_CONFLICTS = (
"inference request is in progress",
"installation is in progress",
"is replacing the latest sidecar",
)
_ALIAS_TABLE = "openai_fine_tuning_aliases"
-# Jobs that may differ only in these train as one multi-LoRA batch; every other training setting must match.
+
_BATCH_MEMBER_FIELDS = frozenset(
{
"local_datasets",
@@ -454,7 +430,6 @@ _BATCH_MEMBER_FIELDS = frozenset(
"random_seed",
"project_name",
"max_steps",
- # Each member has its own optimizer group and scheduler, so these stay per job too.
"weight_decay",
"warmup_steps",
"warmup_ratio",
@@ -473,7 +448,7 @@ class _Queued:
via_api_key: bool
request: TrainingStartRequest
created_at: int
- status: str = "queued" # queued, starting, started, failed, cancelled
+ status: str = "queued"
error: Optional[str] = None
finished_at: Optional[int] = None
idle_conflicts: int = 0
@@ -481,13 +456,13 @@ class _Queued:
_QUEUE: list[_Queued] = []
-# Jobs that have not started (waiting, or ended before starting). A started job's id lives in the database.
+
_ALIASES: dict[str, _Queued] = {}
_ALIAS_RUN: dict[str, tuple[str, Optional[str]]] = {}
_RUN_ALIAS: dict[str, str] = {}
-# A queued job keeps the creation time it was given, not the later time its run started.
+
_ALIAS_CREATED: dict[str, int] = {}
-# Each account has its own database, so its ids load the first time that account asks.
+
_aliases_loaded: set[Optional[str]] = set()
_drainer: Optional[asyncio.Task] = None
_start_locks: "weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, asyncio.Lock]" = (
@@ -500,7 +475,6 @@ def _now() -> int:
def _start_lock() -> asyncio.Lock:
- # One start decision at a time, so two idle creates (or a create and the drainer) never race.
loop = asyncio.get_running_loop()
lock = _start_locks.get(loop)
if lock is None:
@@ -552,7 +526,6 @@ def _save_alias(alias: str, run_id: str, account_id: Optional[str], created_at:
finally:
conn.close()
except Exception: # noqa: BLE001
- # The run is already training: keep it reachable by its id in this process rather than fail it.
logger.exception("Could not persist fine-tuning job id %s", alias)
@@ -593,7 +566,6 @@ _multi_lora: Optional[bool] = None
def _multi_lora_available() -> bool:
- """Whether the installed Unsloth ships the multi-LoRA kernels; looked up on disk, so torch is not imported."""
global _multi_lora
if _multi_lora is None:
try:
@@ -613,7 +585,6 @@ _multi_lora_experts: Optional[bool] = None
def _multi_lora_experts_available() -> bool:
- """Whether the installed multi-LoRA kernels train fused MoE experts (inject_multi_lora_experts)."""
global _multi_lora_experts
if _multi_lora_experts is None:
try:
@@ -633,10 +604,8 @@ def _multi_lora_experts_available() -> bool:
def _batchable(request: TrainingStartRequest) -> bool:
- """Text LoRA/QLoRA on local files with nothing the batched trainer does not run; the rest trains alone."""
from core.training.eval_dataset import evaluation_enabled
from core.training.training import should_use_mlx_training_backend
-
return (
not should_use_mlx_training_backend()
and request.training_type == "LoRA/QLoRA"
@@ -678,7 +647,7 @@ def _batch_key(entry: _Queued) -> Optional[tuple]:
_MOE_COUNT_KEYS = ("num_experts", "n_routed_experts", "num_local_experts")
-# multi_lora_trainer.BATCHED_MOE_MODEL_TYPES.
+
_BATCHED_MOE_TYPES = frozenset({"qwen3_moe", "qwen3_5_moe", "qwen3_5_moe_text"})
# Recurrent / conv state is not checked batched; Gated DeltaNet ("linear_attention") is, and is not matched here.
_SSM_MODEL_TYPES = frozenset(
@@ -757,8 +726,6 @@ def _ssm_config(config: dict) -> bool:
async def _trains_alone(request: TrainingStartRequest) -> bool:
- """Outside what the batched trainer runs: text-diffusion models (own denoising objective), saved LoRA
- adapters (continued in place alone), state-space / conv mixers, and MoE layouts it has no expert LoRA for."""
from utils.models.diffusion_lm import diffusion_lm_profile_for_model
from utils.models.model_config import _read_raw_config_json, get_base_model_from_lora_identifier
@@ -786,7 +753,6 @@ async def _trains_alone(request: TrainingStartRequest) -> bool:
def _batch_for(head: _Queued) -> list[_Queued]:
- """The queue head plus the compatible jobs waiting behind it, in queue order, up to the cap."""
cap = _batch_max()
key = _batch_key(head) if cap > 1 and not head.cancel_requested else None
if key is None:
@@ -820,7 +786,6 @@ def _finish(
async def _start_queued(entry: _Queued) -> bool:
- """Start the queue head as its own account; False while the GPU is still taken."""
from routes import training as training_routes
async with _start_lock():
@@ -831,6 +796,10 @@ async def _start_queued(entry: _Queued) -> bool:
group = _batch_for(entry)
if len(group) > 1 and await arun_as(entry.account, _trains_alone(entry.request)):
group = [entry]
+ # A cancel that landed while the model probe ran has already returned "cancelled": never start it.
+ group = [member for member in group if member.status == "queued"]
+ if entry.status != "queued":
+ return True
if len(group) > 1:
outcome = await _start_batch(group)
if outcome is not None:
@@ -861,7 +830,7 @@ async def _start_queued(entry: _Queued) -> bool:
if entry.cancel_requested:
_finish(entry, "cancelled")
return True
- # Busy, or another start (a UI run) took the GPU while this one was admitted: keep waiting.
+
if started.error in _BUSY_ERRORS or _training_busy():
return False
_finish(entry, "failed", started.message or started.error or "Training did not start")
@@ -882,8 +851,7 @@ async def _start_queued(entry: _Queued) -> bool:
async def _start_batch(group: list[_Queued]) -> Optional[bool]:
- """Start ``group`` as one multi-LoRA run, each job with its own run. None: start the head alone instead,
- which reports any refusal exactly as an unbatched start does; False: training is busy."""
+ """Return None for unavailable batching, False for busy, True after starting."""
from core.training import get_training_backend
from routes import training as training_routes
@@ -981,7 +949,6 @@ def _own_alias(job_id: str) -> Optional[_Queued]:
async def _resolve(job_id: str) -> str:
- """The run behind a job id: a queue id once its job started, else the id itself."""
await asyncio.to_thread(_load_aliases)
record = _ALIAS_RUN.get(job_id)
if record is not None and record[1] == current_account_id():
@@ -997,13 +964,11 @@ async def _stop_run(run_id: str, current_subject: str) -> Any:
current_subject = current_subject,
)
if stopped.status != "idle":
- # The worker stops at its next safe step; the job reads "cancelled" from then on.
_CANCELLING.add(run_id)
return stopped
async def _cancel_run(run_id: str, current_subject: str) -> Any:
- """A job training in a batch beside others still running stops alone; otherwise the whole run stops."""
batch_id = _BATCH_OF.get(run_id)
if batch_id is None:
return await _stop_run(run_id, current_subject)
@@ -1048,7 +1013,6 @@ async def create_fine_tuning_job(
field = ".".join(str(part) for part in first.get("loc", ()))
raise _bad_request(f"Invalid parameter {field}: {first.get('msg')}") from None
async with _start_lock():
- # First come, first served: with jobs already waiting, a new one joins the back of the queue.
if _QUEUE or _training_busy():
return _for_caller(
_queued_job(_enqueue(request, current_subject, via_api_key)), via_api_key
@@ -1093,7 +1057,6 @@ def _paged(rows: list[dict[str, Any]], after: Optional[str], limit: int) -> dict
def _runs_after(after: Optional[str], count: int) -> list[dict[str, Any]]:
- """Up to ``count`` runs older than ``after`` (newest first), paging through the whole history."""
runs: list[dict[str, Any]] = []
found, offset = after is None, 0
while len(runs) < count:
@@ -1128,7 +1091,7 @@ async def list_fine_tuning_jobs(
runs = await asyncio.to_thread(_runs_after, after_run, limit + 1)
status = await _current_status(current_subject, via_api_key)
live_id = _status_field(status, "job_id") if status is not None else None
- # Live jobs without a history row yet (a batch's members while it sets up) are listed first.
+
live = []
if live_id and _status_field(status, "phase") != "idle":
live = [
@@ -1137,14 +1100,13 @@ async def list_fine_tuning_jobs(
if await asyncio.to_thread(get_run, r) is None
]
if after_run in live:
- # The history follows the live jobs, so a cursor on one continues with the rest of them.
live = live[live.index(after_run) + 1 :]
runs = await asyncio.to_thread(_runs_after, None, limit + 1)
elif after_run:
live = []
jobs = [_for_caller(await asyncio.to_thread(_job_from_run, run), via_api_key) for run in runs]
jobs = [await _job(r, current_subject, via_api_key) for r in live] + jobs
- # A job that ended before it started sorts by its creation; once a newer job ran, it is only retrievable.
+
newest = max((job["created_at"] for job in jobs), default = 0)
jobs = [
job
@@ -1167,7 +1129,6 @@ async def retrieve_fine_tuning_job(
def _events(run: dict[str, Any], via_api_key: bool) -> list[dict[str, Any]]:
- """Newest first: one metrics event per logged step, framed by the start and the outcome."""
run_id = run["id"]
started = _unix(run.get("started_at")) or 0
conn = get_connection()
@@ -1270,7 +1231,6 @@ async def list_fine_tuning_events(
run_id = await _resolve(job_id)
run = await asyncio.to_thread(get_run, run_id)
if run is None:
- # Known but not started yet: no events, rather than a 404 a polling client would give up on.
await _job(run_id, current_subject, via_api_key)
return {"object": "list", "data": [], "has_more": False}
return _paged(await asyncio.to_thread(_events, run, via_api_key), after, limit)
@@ -1310,7 +1270,6 @@ def _checkpoints(run: dict[str, Any]) -> list[dict[str, Any]]:
"id": f"ftckpt_{run_id}_{step}",
"object": "fine_tuning.job.checkpoint",
"created_at": int(path.stat().st_mtime) or started,
- # The "<run folder>/<checkpoint>" name Studio loads and exports a checkpoint by.
"fine_tuned_model_checkpoint": f"{Path(output_dir).name}/{path.name}",
"fine_tuning_job_id": _RUN_ALIAS.get(run_id) or _job_id(run_id),
"metrics": {"step": step, "train_loss": loss, "valid_loss": eval_loss},
@@ -1350,7 +1309,6 @@ async def cancel_fine_tuning_job(
_finish(entry, "cancelled")
return _for_caller(_queued_job(entry), via_api_key)
if entry is not None and entry.status == "starting":
- # Its start is in flight: the starter stops the run as soon as it exists.
entry.cancel_requested = True
return _for_caller(_queued_job(entry), via_api_key)
if entry is not None:
diff --git a/studio/backend/tests/test_openai_fine_tuning.py b/studio/backend/tests/test_openai_fine_tuning.py
index 0f4bfb7bbb5..09d900edcd7 100644
--- a/studio/backend/tests/test_openai_fine_tuning.py
+++ b/studio/backend/tests/test_openai_fine_tuning.py
@@ -1,10 +1,6 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""The OpenAI fine-tuning API, driven by the real ``openai`` SDK against the router in-process.
-
-Training itself is stubbed at the ``/api/train`` handlers the router calls; the upload directory and the
-training history are the real ones, in the per-test Studio home."""
import asyncio
import json
@@ -194,7 +190,7 @@ def test_upload_then_create_starts_a_studio_run(studio):
assert job.id == "ftjob_20261021_101500_ab12cd34"
assert job.training_file == uploaded.id
- # No history row until the worker is up: the live training status answers instead.
+
assert retrieved.status == "validating_files"
assert (retrieved.model, retrieved.training_file) == ("unsloth/Qwen3-0.6B", uploaded.id)
@@ -262,7 +258,7 @@ def test_cancel_stops_the_running_job(studio):
async def flow():
cancelled = await client.fine_tuning.jobs.cancel("ftjob_20261021_101500_ab12cd34")
- # The worker is still finishing its step, so the row still reads running.
+
return cancelled, await client.fine_tuning.jobs.retrieve(cancelled.id)
job, retrieved = _run(flow())
@@ -384,7 +380,6 @@ def test_an_overflowed_grad_norm_keeps_events_readable(studio, tmp_path):
@pytest.fixture
def queue(studio, monkeypatch):
- """The queue with the GPU busy and the background drainer replaced by explicit drains."""
client, calls, live = studio
monkeypatch.setattr(openai_fine_tuning, "_QUEUE", [])
monkeypatch.setattr(openai_fine_tuning, "_ALIASES", {})
@@ -393,7 +388,7 @@ def queue(studio, monkeypatch):
monkeypatch.setattr(openai_fine_tuning, "_ALIAS_CREATED", {})
monkeypatch.setattr(openai_fine_tuning, "_aliases_loaded", set())
monkeypatch.setattr(openai_fine_tuning, "_ensure_drainer", lambda: None)
- # Without the multi-LoRA kernels: every queued job starts alone, as before batching existed.
+
monkeypatch.setattr(openai_fine_tuning, "_multi_lora_available", lambda: False)
gpu = {"busy": True}
monkeypatch.setattr(openai_fine_tuning, "_training_busy", lambda: gpu["busy"])
@@ -415,9 +410,9 @@ def test_a_busy_gpu_queues_jobs_and_starts_them_in_order(queue):
second = await _create(client, uploaded.id, suffix = "second")
listed = await client.fine_tuning.jobs.list()
events = await client.fine_tuning.jobs.list_events(second.id)
- await openai_fine_tuning._drain_once() # GPU still busy: nothing starts
+ await openai_fine_tuning._drain_once()
gpu["busy"] = False
- await openai_fine_tuning._drain_once() # the head starts; the GPU is now taken by it
+ await openai_fine_tuning._drain_once()
gpu["busy"] = True
await openai_fine_tuning._drain_once()
after_first = [await client.fine_tuning.jobs.retrieve(j.id) for j in (first, second)]
@@ -430,7 +425,7 @@ def test_a_busy_gpu_queues_jobs_and_starts_them_in_order(queue):
assert [j.id for j in listed.data[:2]] == [second.id, first.id]
assert events.data[0].message == "Waiting for the GPU: position 2 in the queue"
assert [r.project_name for r in calls["start"]] == ["first", "second"]
- # The started job keeps the id the client was given.
+
assert started.id == first.id and started.status == "validating_files"
assert waiting.status == "queued"
@@ -498,7 +493,6 @@ def test_another_account_cannot_see_or_cancel_a_queued_job(queue, monkeypatch):
def _forget_aliases(monkeypatch):
- # What a Studio restart leaves: nothing in memory, the database as it was.
monkeypatch.setattr(openai_fine_tuning, "_RUN_ALIAS", {})
monkeypatch.setattr(openai_fine_tuning, "_ALIAS_RUN", {})
monkeypatch.setattr(openai_fine_tuning, "_ALIAS_CREATED", {})
@@ -516,7 +510,7 @@ def test_a_started_queued_job_keeps_its_id_after_a_restart(queue, monkeypatch):
_forget_aliases(monkeypatch)
retrieved = await client.fine_tuning.jobs.retrieve(job.id)
listed = await client.fine_tuning.jobs.list()
- # The started job as a cursor pages past it rather than ending the list.
+
paged = await client.fine_tuning.jobs.list(after = job.id)
return job, retrieved, listed, paged
@@ -683,7 +677,7 @@ def test_a_job_id_store_failure_keeps_the_started_job(queue, monkeypatch):
async def flow():
uploaded = await client.files.create(file = ("chats.jsonl", CHATS), purpose = "fine-tune")
job = await _create(client, uploaded.id)
- await client.fine_tuning.jobs.list() # load the id table before it locks
+ await client.fine_tuning.jobs.list()
monkeypatch.setattr(openai_fine_tuning, "_alias_db", locked)
gpu["busy"] = False
await openai_fine_tuning._drain_once()
@@ -728,7 +722,7 @@ def test_queue_ids_are_stored_and_loaded_per_account(queue, monkeypatch):
_run(flow())
assert writes == [bob.account_id]
- # Bob's own table is read even though another account loaded its ids first.
+
assert bob.account_id in reads and len(set(reads)) == 2
@@ -768,7 +762,7 @@ def test_a_ui_run_winning_the_gpu_keeps_the_queued_job_waiting(queue, monkeypatc
client, _calls, _live, gpu = queue
async def lost_to_ui(request, current_subject, via_api_key):
- gpu["busy"] = True # the UI run is now training
+ gpu["busy"] = True
return TrainingJobResponse(
job_id = "",
status = "error",
@@ -923,7 +917,7 @@ def test_an_excluded_setting_trains_alone(batching, tmp_path, fields):
other = _entry(tmp_path, "b", **fields)
batching.extend([head, other])
assert openai_fine_tuning._batch_for(head) == [head]
- # A compatible head never pulls the excluded job in either.
+
plain = _entry(tmp_path, "c")
batching.insert(0, plain)
assert openai_fine_tuning._batch_for(plain) == [plain]
@@ -997,7 +991,7 @@ def test_the_kernel_lookup_reads_the_package_on_disk_once(tmp_path, monkeypatch)
monkeypatch.setattr(openai_fine_tuning, "_multi_lora", None)
assert _multi_lora_available() is False
(package / "kernels" / "multi_lora.py").write_text("")
- assert _multi_lora_available() is False # cached
+ assert _multi_lora_available() is False
monkeypatch.setattr(openai_fine_tuning, "_multi_lora", None)
assert _multi_lora_available() is True
# Only the top-level package is looked up: finding a submodule would import unsloth (and torch).
@@ -1022,7 +1016,6 @@ class _BatchBackend:
@pytest.fixture
def batch_queue(queue, monkeypatch):
- """The queue with the multi-LoRA kernels present and a stubbed start_training_batch."""
import core.training
client, calls, live, gpu = queue
@@ -1076,7 +1069,7 @@ def test_compatible_queued_jobs_start_as_one_batch(batch_queue):
assert (subject, via_api_key) == ("unsloth", True)
assert calls["start"] == []
batched = [retrieved[0], retrieved[1], retrieved[3]]
- # Each job keeps the id it was given and its own settings, read from the batch's live status.
+
assert [j.id for j in batched] == [jobs[0].id, jobs[1].id, jobs[3].id]
assert [j.status for j in batched] == ["validating_files"] * 3
assert [j.suffix for j in batched] == ["a", "b", "c"]
@@ -1084,7 +1077,7 @@ def test_compatible_queued_jobs_start_as_one_batch(batch_queue):
assert retrieved[2].status == "queued"
run_ids = [openai_fine_tuning._ALIAS_RUN[j.id][0] for j in batched]
assert run_ids == [f"job_20261021_101500_member0{i}" for i in range(3)]
- # The batch itself is no job: the list shows its members and the job still waiting.
+
listed_ids = [j.id for j in listed.data]
assert sorted(listed_ids) == sorted(j.id for j in jobs)
assert live["status"].job_id not in {openai_fine_tuning._run_id(i) for i in listed_ids}
@@ -1245,7 +1238,7 @@ def test_batch_members_stay_validating_until_their_first_step(batch_queue):
gpu["busy"] = False
await openai_fine_tuning._drain_once()
seen = []
- # The batch's setup messages move its phase through all of these before any member has a row.
+
for phase in ("loading_model", "training", "configuring", "loading_dataset", "training"):
live["status"].phase = phase
seen.append([(await client.fine_tuning.jobs.retrieve(j.id)).status for j in jobs])
@@ -1364,14 +1357,14 @@ def test_cancelling_the_last_running_batched_job_stops_the_run(batch_queue):
jobs = [await _create(client, uploaded.id, suffix = name) for name in ("a", "b")]
gpu["busy"] = False
await openai_fine_tuning._drain_once()
- backend.running = ["job_20261021_101500_member01"] # the other adapter already finished
+ backend.running = ["job_20261021_101500_member01"]
cancelled = await client.fine_tuning.jobs.cancel(jobs[1].id)
return cancelled, await client.fine_tuning.jobs.retrieve(jobs[1].id)
cancelled, retrieved = _run(flow())
assert backend.stopped == []
[stop] = calls["stop"]
- # The whole run is the batch, so the stop names the batch's job.
+
assert stop.expected_job_id == live["status"].job_id == "job_20261021_101500_batch000"
assert cancelled.status == retrieved.status == "cancelled"
@@ -1420,7 +1413,6 @@ def test_start_training_batch_runs_one_start_carrying_every_member(monkeypatch):
)
async def start_training(request, current_subject, via_api_key):
- # Inside start_training, after its own admission of the first member.
members = training_routes._batch_members_for_start({"project_name": request.project_name})
seen.append(("start", request.project_name, members))
return TrainingJobResponse(job_id = "job_batch", status = "queued", message = "queued")
@@ -1504,7 +1496,6 @@ def test_start_training_batch_refuses_resume_and_reports_a_busy_gpu_per_member(m
"model", ["//attacker.example/share/model", "\\\\attacker.example\\share\\model"]
)
def test_batch_probe_never_touches_a_managed_share_path(batch_queue, monkeypatch, model):
- """A managed account's UNC model never reaches the batch probe; the single start refuses it."""
import utils.models.diffusion_lm as diffusion_lm
import utils.models.model_config as model_config
from utils.account_context import AccountContext
@@ -1567,3 +1558,34 @@ def test_batch_probe_unchanged_for_the_owner(batch_queue, monkeypatch):
_run(flow())
assert touched and len(calls["batch"]) == 1
+
+
[email protected]("trains_alone", [False, True])
[email protected]("cancelled", [0, 1])
+def test_a_job_cancelled_during_the_batch_model_probe_never_starts(
+ batch_queue, monkeypatch, cancelled, trains_alone
+):
+ client, calls, _live, gpu, _backend = batch_queue
+ jobs = []
+
+ async def probe_then_cancel(request):
+ cancelled_job = await client.fine_tuning.jobs.cancel(jobs[cancelled].id)
+ assert cancelled_job.status == "cancelled"
+ return trains_alone
+
+ monkeypatch.setattr(openai_fine_tuning, "_trains_alone", probe_then_cancel)
+
+ async def flow():
+ uploaded = await client.files.create(file = ("chats.jsonl", CHATS), purpose = "fine-tune")
+ jobs.extend([await _create(client, uploaded.id, suffix = s) for s in "ab"])
+ gpu["busy"] = False
+ await openai_fine_tuning._drain_once()
+ return [(await client.fine_tuning.jobs.retrieve(j.id)).status for j in jobs]
+
+ statuses = _run(flow())
+ started = [r.project_name for r in calls["start"]] + [
+ r.project_name for requests, *_ in calls["batch"] for r in requests
+ ]
+ assert "ab"[cancelled] not in started
+ assert statuses[cancelled] == "cancelled"
+ assert calls["stop"] == []