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 OpenAI API: refuse unsupported weights in selected JSONL chats (#16153)

Daniel Han45657738adc4
diff --git a/studio/backend/routes/openai_fine_tuning.py b/studio/backend/routes/openai_fine_tuning.py
index 0a81d4576a1..51a491276b2 100644
--- a/studio/backend/routes/openai_fine_tuning.py
+++ b/studio/backend/routes/openai_fine_tuning.py
@@ -126,6 +126,57 @@ def _find_file(file_id: str) -> Path:
raise _bad_request(f"No such File object: {file_id}", 404)
+def _refuse_message_weights(
+ path: Path,
+ param: str,
+ config: Optional[dict[str, Any]] = None,
+) -> None:
+ from utils.datasets.format_detection import detect_dataset_format
+
+ config = config or {}
+ if (
+ path.suffix.lower() != ".jsonl"
+ or config.get("format_type") == "raw"
+ or config.get("training_type") == "Continued Pretraining"
+ ):
+ return
+ mapping = config.get("custom_format_mapping")
+ if mapping:
+ from utils.datasets.dataset_utils import _TO_CHATML
+ if mapping.get("messages") not in _TO_CHATML:
+ return
+ with open(path, "rb") as handle:
+ for number, line in enumerate(handle, start = 1):
+ # Unicode escapes can hide a weight key from the byte prefilter.
+ if b'"weight"' not in line and b"\\u" not in line:
+ continue
+ try:
+ row = json.loads(line)
+ except ValueError:
+ continue
+ if not isinstance(row, dict):
+ continue
+ messages = row.get("messages")
+ for message in messages if isinstance(messages, list) else ():
+ if (
+ isinstance(message, dict)
+ and message.get("weight") is not None
+ and message["weight"] != 1
+ ):
+ if not mapping:
+ from utils.datasets.cache_safe import load_dataset_cache_safe
+ dataset = load_dataset_cache_safe(
+ "json", data_files = str(path), split = "train"
+ )
+ if detect_dataset_format(dataset)["chat_column"] != "messages":
+ return
+ raise _bad_request(
+ f"{param} line {number}: per-message 'weight' {message.get('weight')!r} is not "
+ "supported; Unsloth Studio trains every assistant message. Remove the message "
+ "or its weight."
+ )
+
+
def _file_id_for(path: Any) -> Optional[str]:
upload_id = _upload_id(Path(str(path)).name) if path else None
return f"{FILE_PREFIX}{upload_id}" if upload_id else None
@@ -369,9 +420,13 @@ def _training_config(body: FineTuningJobCreate) -> dict[str, Any]:
config.update(extra)
config["model_name"] = body.model
- config["local_datasets"] = [str(_find_file(body.training_file))]
+ training_path = _find_file(body.training_file)
+ _refuse_message_weights(training_path, "training_file", config)
+ config["local_datasets"] = [str(training_path)]
if body.validation_file:
- config["local_eval_datasets"] = [str(_find_file(body.validation_file))]
+ validation_path = _find_file(body.validation_file)
+ _refuse_message_weights(validation_path, "validation_file", config)
+ config["local_eval_datasets"] = [str(validation_path)]
config.setdefault("eval_steps", 0.1)
if body.suffix:
diff --git a/studio/backend/tests/test_openai_fine_tuning.py b/studio/backend/tests/test_openai_fine_tuning.py
index 09d900edcd7..b9ba1d3b20a 100644
--- a/studio/backend/tests/test_openai_fine_tuning.py
+++ b/studio/backend/tests/test_openai_fine_tuning.py
@@ -135,6 +135,175 @@ def _finished_run(
return run_id
[email protected]("mode", ["mapped", "alpaca", "raw"])
+def test_unused_weighted_messages_do_not_block_other_training_data(studio, mode):
+ client, calls, _live = studio
+ row = {
+ "messages": [{"role": "assistant", "content": "CONTEXT_ONLY", "weight": 0}],
+ "question": "Question",
+ "answer": "TARGET",
+ }
+ extra = {}
+ if mode == "mapped":
+ extra["custom_format_mapping"] = {"question": "user", "answer": "assistant"}
+ elif mode == "alpaca":
+ row.update(instruction = "Question", output = "TARGET")
+ else:
+ row["text"] = "TARGET"
+ extra["format_type"] = "raw"
+
+ async def flow():
+ uploaded = await client.files.create(
+ file = ("rows.jsonl", (json.dumps(row) + "\n").encode()), purpose = "fine-tune"
+ )
+ return await _create(client, uploaded.id, extra_body = extra)
+
+ job = _run(flow())
+ assert job.status == "validating_files"
+ assert len(calls["start"]) == 1
+
+
[email protected]("mode", ["cpt", "sparse_alpaca"])
[email protected]("file_param", ["training_file", "validation_file"])
+def test_dataset_selection_ignores_unused_message_weights(studio, tmp_path, mode, file_param):
+ from datasets import load_dataset
+ from utils.datasets.dataset_utils import format_dataset
+
+ client, calls, _live = studio
+ weighted = [{"role": "assistant", "content": "CONTEXT_ONLY", "weight": 0}]
+ if mode == "cpt":
+ rows = [{"text": "TARGET", "messages": weighted}]
+ extra = {"training_type": "Continued Pretraining"}
+ else:
+ rows = [
+ {"instruction": "Question", "output": "TARGET", "messages": weighted},
+ {"output": "TARGET", "messages": weighted},
+ ]
+ extra = {}
+ content = "".join(json.dumps(row) + "\n" for row in rows).encode()
+ source = tmp_path / "selected.jsonl"
+ source.write_bytes(content)
+ dataset = load_dataset(
+ "json", data_files = str(source), split = "train", cache_dir = str(tmp_path / "cache")
+ )
+ formatted = format_dataset(dataset, format_type = "raw" if mode == "cpt" else "auto")
+ assert formatted["final_format"] == ("raw_text" if mode == "cpt" else "alpaca")
+
+ async def flow():
+ uploaded = await client.files.create(file = ("selected.jsonl", content), purpose = "fine-tune")
+ plain = await client.files.create(file = ("plain.jsonl", CHATS), purpose = "fine-tune")
+ kwargs = {"training_file": plain.id, file_param: uploaded.id}
+ return await client.fine_tuning.jobs.create(
+ model = "unsloth/Qwen3-0.6B", extra_body = extra, **kwargs
+ )
+
+ job = _run(flow())
+ assert job.status == "validating_files"
+ assert len(calls["start"]) == 1
+
+
+def test_a_mapping_that_selects_weighted_messages_is_still_refused(studio):
+ client, calls, _live = studio
+ rows = b'{"messages":[{"role":"assistant","content":"CONTEXT_ONLY","weight":0}]}\n'
+
+ async def flow():
+ uploaded = await client.files.create(file = ("rows.jsonl", rows), purpose = "fine-tune")
+ with pytest.raises(openai.BadRequestError):
+ await _create(
+ client, uploaded.id, extra_body = {"custom_format_mapping": {"messages": "assistant"}}
+ )
+
+ _run(flow())
+ assert calls["start"] == []
+
+
+def test_exported_unit_weight_messages_still_train(studio, tmp_path):
+ from datasets import Dataset
+
+ client, calls, _live = studio
+ exported = tmp_path / "export.jsonl"
+ Dataset.from_list(
+ [
+ {
+ "messages": [
+ {"role": "user", "content": "Hi"},
+ {"role": "assistant", "content": "Hello"},
+ {"role": "user", "content": "Bye"},
+ {"role": "assistant", "content": "Goodbye", "weight": 1},
+ ]
+ }
+ ]
+ ).to_json(exported)
+ rows = exported.read_bytes()
+ assert json.loads(rows)["messages"][1]["weight"] is None
+
+ async def flow():
+ uploaded = await client.files.create(file = ("export.jsonl", rows), purpose = "fine-tune")
+ return await _create(client, uploaded.id)
+
+ job = _run(flow())
+ assert job.status == "validating_files"
+ assert len(calls["start"]) == 1
+
+
[email protected]("weight, escaped", [(0, False), (0.5, False), (0, True)])
+def test_a_file_excluding_an_assistant_message_by_weight_is_refused(studio, weight, escaped):
+ client, calls, _live = studio
+ rows = (
+ json.dumps(
+ {
+ "messages": [
+ {"role": "user", "content": "Question"},
+ {"role": "assistant", "content": "CONTEXT_ONLY", "weight": weight},
+ {"role": "user", "content": "Question"},
+ {"role": "assistant", "content": "TARGET", "weight": 1},
+ ]
+ }
+ ).encode()
+ + b"\n"
+ )
+ if escaped:
+ rows = rows.replace(b'"weight"', b'"weigh\\u0074"')
+ assert b'"weight"' not in rows and json.loads(rows)["messages"][1]["weight"] == 0
+
+ async def flow():
+ weighted = await client.files.create(
+ file = ("weighted.jsonl", CHATS + rows), purpose = "fine-tune"
+ )
+ plain = await client.files.create(file = ("plain.jsonl", CHATS), purpose = "fine-tune")
+ errors = []
+ for kwargs in (
+ {"training_file": weighted.id},
+ {"training_file": plain.id, "validation_file": weighted.id},
+ ):
+ try:
+ await client.fine_tuning.jobs.create(model = "unsloth/Qwen3-0.6B", **kwargs)
+ except openai.BadRequestError as exc:
+ errors.append(exc.response.text)
+ return errors
+
+ errors = _run(flow())
+ assert len(errors) == 2
+ assert "training_file line 3" in errors[0] and "validation_file line 3" in errors[1]
+ assert calls["start"] == []
+
+
+def test_a_file_with_only_weight_one_messages_still_trains(studio):
+ client, calls, _live = studio
+ rows = (
+ b'{"messages": [{"role": "user", "content": "Hi"}, '
+ b'{"role": "assistant", "content": "Hello!", "weight": 1}]}\n'
+ )
+
+ async def flow():
+ uploaded = await client.files.create(file = ("chats.jsonl", rows), purpose = "fine-tune")
+ return await _create(client, uploaded.id)
+
+ job = _run(flow())
+ assert job.status == "validating_files"
+ assert len(calls["start"]) == 1
+
+
def test_upload_then_create_starts_a_studio_run(studio):
client, calls, _live = studio
diff --git a/studio/backend/tests/test_training_api_snippet_contract.py b/studio/backend/tests/test_training_api_snippet_contract.py
index d61782d468b..dc27b5c8470 100644
--- a/studio/backend/tests/test_training_api_snippet_contract.py
+++ b/studio/backend/tests/test_training_api_snippet_contract.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 Train page's API examples create jobs the fine-tuning route accepts, with the form's settings.
-
-The bodies are the ones the frontend generator sends (``tests/training-api-snippets.test.ts`` keeps the
-fixture in step with it)."""
import json
from pathlib import Path
@@ -21,13 +17,18 @@ BODIES = json.loads(
)
)
FILE_ID = "file-0123456789abcdef0123456789abcdef"
-UPLOADED = Path(f"/uploads/{FILE_ID}.jsonl")
OPENAI_FIELDS = {"model", "hyperparameters", "seed", "suffix"}
@pytest.fixture(autouse = True)
-def uploaded_file(monkeypatch):
- monkeypatch.setattr(openai_fine_tuning, "_find_file", lambda file_id: UPLOADED)
+def uploaded_file(monkeypatch, tmp_path):
+ uploaded = tmp_path / f"{FILE_ID}.jsonl"
+ uploaded.write_text(
+ '{"messages": [{"role": "user", "content": "Hi"}, {"role": "assistant", "content": "Hello"}]}\n',
+ encoding = "utf-8",
+ )
+ monkeypatch.setattr(openai_fine_tuning, "_find_file", lambda file_id: uploaded)
+ return uploaded
def _request(body: dict) -> TrainingStartRequest:
@@ -38,16 +39,16 @@ def _request(body: dict) -> TrainingStartRequest:
@pytest.mark.parametrize("name", sorted(BODIES))
-def test_generated_body_is_accepted_with_its_settings(name):
+def test_generated_body_is_accepted_with_its_settings(name, uploaded_file):
body = BODIES[name]
request = _request(body)
assert request.model_name == body["model"]
- assert request.local_datasets == [str(UPLOADED)]
+ assert request.local_datasets == [str(uploaded_file)]
assert request.num_epochs == body["hyperparameters"]["n_epochs"]
assert request.batch_size == body["hyperparameters"]["batch_size"]
assert request.random_seed == body["seed"]
assert request.project_name == body.get("suffix")
- # The route normalises the string ("2e-4" -> "0.0002"); the rate itself must not change.
+
assert float(request.learning_rate) == float(body["learning_rate"])
extras = {
key: value