Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

fix(data): detect format from a bounded prefix, not only the first row (closes #1424) (#1496)

Chaitanya Reddy4d14b3ddc246
diff --git a/changelog.d/0.75.1/1496.fixed.md b/changelog.d/0.75.1/1496.fixed.md
new file mode 100644
index 00000000..d4b23fb6
--- /dev/null
+++ b/changelog.d/0.75.1/1496.fixed.md
@@ -0,0 +1 @@
+- `format: auto` now detects a dataset's format from a bounded prefix of rows instead of the first row alone, so a first row that happens to lack an optional key no longer picks the poorer converter for the whole file and silently drops that key from every row. A mixed file either upgrades to the richer format of the same family when its converter accepts the poorer rows, or is refused with a message naming both shapes and the row where each was first seen. Files that used to load under `format: auto` with a key stripped or rows dropped under a warning now stop at load; set `data.format` to the shape you want to keep. The Web UI data explorer now reports the refusal instead of failing, and the auto-detection behaviour is documented. (#1424 by @chaitanya-y20 in #1496).
diff --git a/docs/data.md b/docs/data.md
index d154ad85..113f7149 100644
--- a/docs/data.md
+++ b/docs/data.md
@@ -159,8 +159,8 @@ soup data canary check --manifest secrets.json --base ./my-model --adapter ./lor
```
`insert` writes the canaries in the dataset's own format, so the loader keeps them:
-`--format auto` (the default) detects it from the first row, as `data.format: auto`
-does. Alpaca, sharegpt and chatml are supported, each with the carrier as the prompt
+`--format auto` (the default) detects it from the first 100 rows, as `data.format: auto`
+does (a file that mixes shapes is refused, see Data Formats). Alpaca, sharegpt and chatml are supported, each with the carrier as the prompt
and the secret as the trained response. Every other format is refused: dpo, kto and
embedding have no single supervised response, plaintext trains on raw text rather
than the chat turn `check` scores, tool-calling puts a tool-schema system turn
@@ -614,6 +614,16 @@ An axolotl `rl:` value with no Soup task (for example `rl: ebft`) stops the migr
Soup supports these formats (auto-detected). Files can be JSONL, JSON, CSV, Parquet, or TXT.
+**Auto-detection.** It reads the first 100 rows, not just the first. Each row resolves
+to the richest format its keys fit. If every row agrees, that format is used. A file
+that mixes `chatml` and `tool-calling` rows loads as `tool-calling` (the plain rows
+convert as ordinary chat turns). Every other mix (`sharegpt` with `llava`, `chatml`
+with `audio`, `plaintext` with `asr`, or two unrelated shapes) is refused with a message
+naming both shapes and the row where each first appears, because converting the file
+with either one would drop the other's keys or rows; set `data.format` to choose. Rows
+after the first 100 are not inspected; `soup data validate` lists every row the chosen
+format drops.
+
**Alpaca:**
```json
{"instruction": "Explain gravity", "input": "", "output": "Gravity is..."}
diff --git a/src/soup_cli/commands/data_canary.py b/src/soup_cli/commands/data_canary.py
index ba5d9f32..4577638a 100644
--- a/src/soup_cli/commands/data_canary.py
+++ b/src/soup_cli/commands/data_canary.py
@@ -116,8 +116,8 @@ def _resolve_format(rows: list, requested: str, path: str) -> str:
)
return requested
if not isinstance(rows[0], dict):
- # detect_format reads the first row's keys; anything else would
- # surface as a bare AttributeError.
+ # The canary carrier is written into row 0, so it must be an object.
+ # (detect_format itself now skips non-dict rows rather than raising.)
_refuse(
f"{path}: the first row is a JSON {_json_type(rows[0])}, not an "
"object; canary insert reads each row as a JSON object"
diff --git a/src/soup_cli/data/formats.py b/src/soup_cli/data/formats.py
index e2ea2c86..0355e7e4 100644
--- a/src/soup_cli/data/formats.py
+++ b/src/soup_cli/data/formats.py
@@ -41,33 +41,66 @@ FORMAT_SIGNATURES = {
"tool-calling": {"messages", "tools"},
}
+# #1424: detection reads a bounded prefix of the file, not just row 0. A first
+# row that happens to lack an optional key (e.g. a text-only LLaVA row) must
+# not pick the converter for the WHOLE file and silently drop that key from
+# every row that has it. The cap keeps detection O(1)-ish on huge files.
+MAX_DETECT_ROWS = 100
+
+# Check more specific formats first (llava/sharegpt4v before sharegpt).
+# tool-calling (messages+tools) is checked BEFORE audio
+# (audio+messages): a row carrying both would otherwise match audio first
+# and silently drop its tools/tool_calls. tool-calling before chatml
+# (signature is a superset of chatml). asr ({audio, text}) is checked
+# BEFORE plaintext ({text}) — its signature is a superset, so plaintext
+# would otherwise win and silently drop the audio path. plaintext last.
+_CHECK_ORDER = [
+ "alpaca", "llava", "sharegpt4v", "kto", "dpo", "embedding",
+ "tool-calling", "audio", "asr", "sharegpt", "chatml", "plaintext",
+]
+
+
+def _richest_format(keys: set[str]) -> Optional[str]:
+ """First format in :data:`_CHECK_ORDER` whose signature fits ``keys``.
+
+ The check order is most-specific-first, so this is the richest format the
+ row's keys could be: a row with ``image`` + ``conversations`` is ``llava``,
+ a row with only ``conversations`` is ``sharegpt``.
+ """
+ for fmt in _CHECK_ORDER:
+ if FORMAT_SIGNATURES[fmt].issubset(keys):
+ return fmt
+ return None
-def detect_format(data: list[dict]) -> str:
- """Auto-detect dataset format from first few rows."""
- if not data:
- raise ValueError("Empty dataset - cannot detect format")
- sample = data[0]
- keys = set(sample.keys())
-
- # Check more specific formats first (llava/sharegpt4v before sharegpt).
- # tool-calling (messages+tools) is checked BEFORE audio
- # (audio+messages): a row carrying both would otherwise match audio first
- # and silently drop its tools/tool_calls. tool-calling before chatml
- # (signature is a superset of chatml). asr ({audio, text}) is checked
- # BEFORE plaintext ({text}) — its signature is a superset, so plaintext
- # would otherwise win and silently drop the audio path. plaintext last.
- check_order = [
- "alpaca", "llava", "sharegpt4v", "kto", "dpo", "embedding",
- "tool-calling", "audio", "asr", "sharegpt", "chatml", "plaintext",
- ]
- for fmt in check_order:
- required_keys = FORMAT_SIGNATURES[fmt]
- if required_keys.issubset(keys):
- return fmt
+def _richer_family_member(a: str, b: str) -> Optional[str]:
+ """Return ``a`` or ``b`` with the strictly larger signature, else ``None``.
- raise ValueError(
- f"Cannot detect format. Keys found: {keys}. "
+ The richer format's signature is a superset of the poorer one's, so a row
+ matching the richer signature also matches the poorer — that is what defines
+ a richer/poorer pair of the same family (llava/sharegpt,
+ tool-calling/chatml, audio/chatml, asr/plaintext). Two unrelated shapes
+ (e.g. alpaca and chatml) share no such relation and must not be merged.
+ """
+ if FORMAT_SIGNATURES[a] > FORMAT_SIGNATURES[b]:
+ return a
+ if FORMAT_SIGNATURES[b] > FORMAT_SIGNATURES[a]:
+ return b
+ return None
+
+
+def _cannot_detect_message(row: object, index: int) -> str:
+ """The existing unrecognised-keys error, naming the offending row.
+
+ ``row`` may be any JSON value, not just an object, so a bare scalar or array
+ is described by its type rather than by keys it does not have.
+ """
+ if isinstance(row, dict):
+ found = f"Keys found: {set(row.keys())}. "
+ else:
+ found = f"Row is a {type(row).__name__}, not an object. "
+ return (
+ f"Cannot detect format at row {index}. {found}"
f"Expected one of: alpaca (instruction, output), "
f"sharegpt (conversations), chatml (messages), "
f"dpo (prompt, chosen, rejected), "
@@ -80,6 +113,111 @@ def detect_format(data: list[dict]) -> str:
)
+def detect_format(data: list[dict]) -> str:
+ """Auto-detect dataset format from a bounded prefix of rows.
+
+ Reads up to :data:`MAX_DETECT_ROWS` rows — not just the first — because a
+ single first row missing an optional key must not force the poorer
+ converter on the whole file and silently drop that key everywhere (#1424).
+
+ Each sampled row resolves to its richest format (the first match in the
+ check order). If every row agrees, that format is returned — a uniform file
+ detects exactly as before. If they disagree the file is *mixed*:
+
+ - a richer/poorer pair of the same family (llava/sharegpt,
+ tool-calling/chatml, audio/chatml, asr/plaintext) upgrades to the richer
+ format, but only when its converter accepts the poorer rows too;
+ - otherwise (an unrelated pair, or a richer converter that rejects the
+ poorer rows) detection raises, naming both shapes and the row where each
+ was first seen and telling the user to set ``data.format`` explicitly.
+
+ Raises:
+ - ``ValueError`` on empty data, or when no row in the prefix matches any
+ format signature. A row that matches no signature is skipped and reported
+ like the converters do (#1217) rather than refusing the whole file. A file
+ that mixes shapes is also refused, naming both shapes and the row where
+ each was first seen.
+ """
+ if not data:
+ raise ValueError("Empty dataset - cannot detect format")
+
+ sampled = data[:MAX_DETECT_ROWS]
+ # First row index at which each richest format was seen, in sample order.
+ first_seen: dict[str, int] = {}
+ # The richest format of every sampled row, aligned with `sampled`.
+ row_formats: list[str] = []
+ ignored: list[int] = []
+ for index, row in enumerate(sampled):
+ # A JSONL line can be any JSON value, not just an object, so a bare
+ # scalar or array is skipped exactly as the converters drop it (#1217)
+ # instead of crashing on .keys().
+ fmt = _richest_format(set(row.keys())) if isinstance(row, dict) else None
+ if fmt is None:
+ # #1217: a row matching no signature is skipped by the converters
+ # rather than fatal, so detection ignores it here too and drops it
+ # from the decision. Refusing on one bad row would restore the
+ # "zero row stop" behaviour #1217 removed; the loader's own drop
+ # warning is what tells the user which row it was.
+ ignored.append(index)
+ row_formats.append("")
+ continue
+ row_formats.append(fmt)
+ first_seen.setdefault(fmt, index)
+
+ if not first_seen:
+ # Nothing in the prefix matched, so there is no format to resolve.
+ first_ignored = ignored[0]
+ raise ValueError(_cannot_detect_message(sampled[first_ignored], first_ignored))
+
+ if len(first_seen) == 1:
+ return next(iter(first_seen))
+
+ # The sampled rows disagree: this file is mixed.
+ ordered = sorted(first_seen.items(), key=lambda item: item[1])
+ if len(ordered) == 2:
+ (fmt_a, idx_a), (fmt_b, idx_b) = ordered
+ richer = _richer_family_member(fmt_a, fmt_b)
+ if richer is not None:
+ if richer == fmt_a:
+ poorer, poorer_idx, richer_idx = fmt_b, idx_b, idx_a
+ else:
+ poorer, poorer_idx, richer_idx = fmt_a, idx_a, idx_b
+ poorer_rows = [
+ row for row, fmt in zip(sampled, row_formats) if fmt == poorer
+ ]
+ # The richer converter must accept EVERY poorer row, and must
+ # convert it to the same messages the poorer one would: the
+ # tool-calling converter rebuilds each message from role, content,
+ # tool_calls and tool_call_id, so a chatml row whose messages carry
+ # name or weight converts "successfully" but loses them. An upgrade
+ # that silently drops a field is the defect this change exists to fix.
+ upgrades = all(
+ format_to_messages(row, richer) is not None
+ and format_to_messages(row, richer) == format_to_messages(row, poorer)
+ for row in poorer_rows
+ )
+ if upgrades:
+ # The richer converter handles the poorer rows too, so upgrading
+ # keeps every row's fields instead of dropping the poorer ones.
+ return richer
+ missing = sorted(FORMAT_SIGNATURES[richer] - FORMAT_SIGNATURES[poorer])
+ missing_text = ", ".join(f"'{key}'" for key in missing)
+ raise ValueError(
+ f"Cannot detect format: this dataset mixes '{poorer}' (row "
+ f"{poorer_idx}) and '{richer}' (row {richer_idx}). They are the "
+ f"same family, but the richer '{richer}' converter rejects the "
+ f"'{poorer}' rows — they have no {missing_text} key — so no "
+ f"single format covers every row. Set data.format explicitly."
+ )
+
+ shapes = " and ".join(f"'{fmt}' (row {idx})" for fmt, idx in ordered)
+ raise ValueError(
+ f"Cannot detect format: this dataset mixes unrelated shapes {shapes}. "
+ f"Converting every row with one of them would silently drop the other's "
+ f"fields. Set data.format explicitly."
+ )
+
+
# Every format format_to_messages can convert. Kept as a module constant so
# the plain and reason-returning entry points share one source of truth.
VALID_FORMATS = (
diff --git a/src/soup_cli/ui/app.py b/src/soup_cli/ui/app.py
index 97f1cfb7..a8af3158 100644
--- a/src/soup_cli/ui/app.py
+++ b/src/soup_cli/ui/app.py
@@ -747,20 +747,29 @@ def create_app(host: str = "127.0.0.1", port: int = 7860):
total = len(raw_data)
sample = raw_data[: req.limit]
- # Detect format
+ # Detect format. detect_format samples a bounded prefix itself (#1424),
+ # and a file that mixes shapes is refused, so a ValueError here is a
+ # reportable outcome for the explorer rather than a 500: this is where
+ # someone lands after soup train refused the same file.
from soup_cli.data.formats import detect_format
- fmt = detect_format(raw_data[:5]) if raw_data else "unknown"
+ format_error = None
+ try:
+ fmt = detect_format(raw_data) if raw_data else "unknown"
+ except ValueError as exc:
+ fmt, format_error = "unknown", str(exc)
# Basic stats
keys = set()
for entry in sample:
- keys.update(entry.keys())
+ if isinstance(entry, dict):
+ keys.update(entry.keys())
return {
"path": str(resolved),
"total": total,
"format": fmt,
+ "format_error": format_error,
"keys": sorted(keys),
"sample": sample,
}
diff --git a/tests/test_issue1424_detect_format_multirow.py b/tests/test_issue1424_detect_format_multirow.py
new file mode 100644
index 00000000..1ef11eed
--- /dev/null
+++ b/tests/test_issue1424_detect_format_multirow.py
@@ -0,0 +1,354 @@
+"""Regression tests for issue #1424: ``format: auto`` read only the first row.
+
+``detect_format`` used ``sample = data[0]`` and returned the first format whose
+required keys were a subset of that single row. A first row missing an optional
+key therefore picked the poorer converter for the WHOLE file and silently
+dropped that key from every row that had it — a 4-row LLaVA file whose first
+row is text-only loaded with 0 of 4 images kept, and a ``messages``/``tools``
+file whose first row had no ``tools`` was converted as ``chatml`` and lost the
+tool schema on every row.
+
+Detection now reads a bounded prefix (``MAX_DETECT_ROWS``). A uniform file
+detects exactly as before (controls below). A mixed file upgrades to the richer
+format when its converter can also read the poorer rows (tool-calling over
+chatml), and otherwise raises a message naming both shapes, the row each was
+first seen at, and the ``data.format`` escape hatch — rather than silently
+converting everything with the poorer format.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from soup_cli.config.schema import DataConfig
+from soup_cli.data.formats import (
+ FORMAT_SIGNATURES,
+ MAX_DETECT_ROWS,
+ detect_format,
+ format_to_messages,
+)
+from soup_cli.data.loader import load_dataset
+
+_CHAT = [{"role": "user", "content": "q"}, {"role": "assistant", "content": "a"}]
+_SHAREGPT = [{"from": "human", "value": "q"}, {"from": "gpt", "value": "a"}]
+_TOOL = {
+ "type": "function",
+ "function": {
+ "name": "get_weather",
+ "description": "Weather for a city",
+ "parameters": {"type": "object", "properties": {"city": {"type": "string"}}},
+ },
+}
+
+# The poorer row of each richer/poorer family, and the richer row that shares
+# the family (same signature plus one key).
+_SHAREGPT_ROW = {"conversations": _SHAREGPT}
+_LLAVA_ROW = {"image": "i.png", "conversations": _SHAREGPT}
+_CHATML_ROW = {"messages": _CHAT}
+_TOOL_ROW = {"messages": _CHAT, "tools": [_TOOL]}
+_AUDIO_ROW = {"audio": "a.wav", "messages": _CHAT}
+_PLAINTEXT_ROW = {"text": "raw text"}
+_ASR_ROW = {"audio": "a.wav", "text": "transcript"}
+
+# One valid row per format `detect_format` can return; the expected detected
+# name is listed separately because sharegpt4v and llava share a signature
+# (llava is checked first, so detection never returns "sharegpt4v").
+_UNIFORM_ROWS = {
+ "alpaca": {"instruction": "q", "output": "a"},
+ "sharegpt": _SHAREGPT_ROW,
+ "chatml": _CHATML_ROW,
+ "dpo": {"prompt": "q", "chosen": "a", "rejected": "b"},
+ "kto": {"prompt": "q", "completion": "a", "label": True},
+ "llava": _LLAVA_ROW,
+ "sharegpt4v": _LLAVA_ROW, # same signature as llava; llava wins the check order
+ "embedding": {"anchor": "q", "positive": "a"},
+ "tool-calling": _TOOL_ROW,
+ "audio": _AUDIO_ROW,
+ "asr": _ASR_ROW,
+ "plaintext": _PLAINTEXT_ROW,
+}
+_UNIFORM_EXPECTED = {fmt: fmt for fmt in _UNIFORM_ROWS}
+_UNIFORM_EXPECTED["sharegpt4v"] = "llava"
+
+
+def _load(path: Path, data_format: str = "auto") -> dict:
+ return load_dataset(DataConfig(train=str(path), format=data_format, val_split=0.0))
+
+
+def _write(path: Path, rows: list[dict]) -> None:
+ path.write_text(
+ "".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8"
+ )
+
+
+# ---------------------------------------------------------------------------
+# Controls — every uniform format detects exactly as before (#1424 step 3)
+# ---------------------------------------------------------------------------
+
+
+def test_fixture_covers_every_format_signature():
+ """A new signature must join the uniform control sweep."""
+ assert set(_UNIFORM_ROWS) == set(FORMAT_SIGNATURES)
+
+
[email protected]("fmt", sorted(_UNIFORM_ROWS))
+def test_uniform_file_detects_exactly_as_before(fmt):
+ # A whole file of one shape keeps detecting to that shape (sharegpt4v's
+ # rows detect as llava, today's behaviour, pinned here as a control).
+ rows = [_UNIFORM_ROWS[fmt]] * 4
+ assert detect_format(rows) == _UNIFORM_EXPECTED[fmt]
+
+
+# ---------------------------------------------------------------------------
+# The four mixed cases from the issue
+# ---------------------------------------------------------------------------
+
+
+def test_mixed_sharegpt_and_llava_refuses_naming_both_shapes():
+ # Row 0 has no `image`; converting the file as sharegpt would drop the
+ # image from row 1. llava's converter refuses a row without an image, so
+ # the fix must raise rather than silently return 'sharegpt'.
+ data = [_SHAREGPT_ROW, _LLAVA_ROW]
+ with pytest.raises(ValueError) as exc:
+ detect_format(data)
+ message = str(exc.value)
+ assert "'sharegpt' (row 0)" in message
+ assert "'llava' (row 1)" in message
+ assert "data.format" in message
+
+
+def test_mixed_messages_and_tools_upgrades_to_tool_calling():
+ # The chatml row converts fine as tool-calling (tools absent -> no schema
+ # turn), so the richer converter covers the whole file.
+ assert detect_format([_CHATML_ROW, _TOOL_ROW]) == "tool-calling"
+ # Order must not matter: the poorer row first, or the richer row first.
+ assert detect_format([_TOOL_ROW, _CHATML_ROW]) == "tool-calling"
+
+
+def test_mixed_chatml_and_audio_refuses_naming_both_shapes():
+ data = [_CHATML_ROW, _AUDIO_ROW]
+ with pytest.raises(ValueError) as exc:
+ detect_format(data)
+ message = str(exc.value)
+ assert "'chatml' (row 0)" in message
+ assert "'audio' (row 1)" in message
+ assert "data.format" in message
+
+
+def test_mixed_plaintext_and_asr_refuses_naming_both_shapes():
+ data = [_PLAINTEXT_ROW, _ASR_ROW]
+ with pytest.raises(ValueError) as exc:
+ detect_format(data)
+ message = str(exc.value)
+ assert "'plaintext' (row 0)" in message
+ assert "'asr' (row 1)" in message
+ assert "data.format" in message
+
+
+def test_unrelated_shapes_refuse_naming_both_rows():
+ # alpaca and chatml share no richer/poorer relation, so neither may win.
+ data = [{"instruction": "q", "output": "a"}, _CHATML_ROW]
+ with pytest.raises(ValueError) as exc:
+ detect_format(data)
+ message = str(exc.value)
+ assert "'alpaca' (row 0)" in message
+ assert "'chatml' (row 1)" in message
+ assert "data.format" in message
+
+
+def test_upgrade_keeps_the_tools_schema_on_the_tools_row():
+ # The whole point of upgrading: the tool schema survives instead of being
+ # dropped by the chatml converter.
+ rows = [_CHATML_ROW, _TOOL_ROW]
+ assert detect_format(rows) == "tool-calling"
+ converted = [format_to_messages(row, "tool-calling") for row in rows]
+ assert all(result is not None for result in converted)
+ schema_blob = json.dumps(converted[1])
+ assert "get_weather" in schema_blob
+ # The chatml-only row still converts (as a plain conversation turn).
+ assert converted[0]["messages"] == _CHAT
+
+
+# ---------------------------------------------------------------------------
+# Bounded prefix + unrecognised keys
+# ---------------------------------------------------------------------------
+
+
+def test_detection_reads_a_bounded_prefix_not_the_whole_file():
+ # A richer row sitting past the cap cannot flip the file: the prefix of
+ # chatml rows decides, exactly as the pre-fix single-row read did for row 0.
+ data = [_CHATML_ROW] * MAX_DETECT_ROWS + [_LLAVA_ROW]
+ assert detect_format(data) == "chatml"
+ # One row inside the cap is enough to trigger mixed detection.
+ inside = [_CHATML_ROW] * (MAX_DETECT_ROWS - 1) + [_LLAVA_ROW]
+ with pytest.raises(ValueError):
+ detect_format(inside)
+
+
+def test_unrecognised_row_is_skipped_not_fatal():
+ # #1217: a row matching no signature is skipped and reported, so one bad row
+ # must not stop the load. The prefix scan resolves from the rows that do
+ # match, and only raises when NOTHING in the prefix matches.
+ data = [_CHATML_ROW, {"unrelated": "keys"}]
+ assert detect_format(data) == "chatml"
+
+
+def test_detection_raises_when_no_row_in_the_prefix_matches():
+ with pytest.raises(ValueError) as exc:
+ detect_format([{"unrelated": "keys"}, {"also": "unrelated"}])
+ assert "Cannot detect format at row 0" in str(exc.value)
+
+
+def test_non_dict_row_in_the_prefix_is_skipped_not_fatal():
+ # A JSONL line may be any JSON value. The old code read only row 0, so a
+ # bare scalar later in the file never reached .keys(); scanning the prefix
+ # must not turn that into an AttributeError that the loader (which catches
+ # only ValueError) would surface as a traceback.
+ for bad in ("a bare json string", 1, 1.5, None, ["a", "list"], True):
+ assert detect_format([_CHATML_ROW, bad]) == "chatml"
+ assert detect_format([bad, _CHATML_ROW]) == "chatml"
+
+
+def test_all_non_dict_rows_raise_valueerror_not_attributeerror():
+ for data in ([1, "x"], ["a string"], [[1, 2], [3, 4]], [None]):
+ with pytest.raises(ValueError) as exc:
+ detect_format(data)
+ assert "not an object" in str(exc.value)
+
+
+def test_empty_dataset_still_raises():
+ with pytest.raises(ValueError, match="Empty"):
+ detect_format([])
+
+
+# ---------------------------------------------------------------------------
+# End-to-end: the acceptance criteria through load_dataset
+# ---------------------------------------------------------------------------
+
+
+def test_mixed_llava_file_refuses_or_keeps_every_image(tmp_path):
+ # The issue's repro: a 4-row LLaVA file whose first row is text-only used
+ # to load with 0 of 4 images kept. Now it refuses.
+ path = tmp_path / "mixed_llava.jsonl"
+ rows = [_SHAREGPT_ROW] + [
+ {"image": f"i{i}.png", "conversations": _SHAREGPT} for i in range(3)
+ ]
+ _write(path, rows)
+ with pytest.raises(ValueError, match="llava"):
+ _load(path)
+
+
+def test_mixed_tools_file_loads_every_row_with_the_schema(tmp_path):
+ path = tmp_path / "mixed_tools.jsonl"
+ _write(path, [_CHATML_ROW, _TOOL_ROW])
+ loaded = _load(path)["train"]
+ assert len(loaded) == 2
+ # The tools row keeps its schema turn; the plain row stays a plain chat.
+ assert "get_weather" in json.dumps(loaded)
+ assert loaded[0]["messages"] == _CHAT
+
+
+def test_mixed_audio_file_refuses(tmp_path):
+ path = tmp_path / "mixed_audio.jsonl"
+ _write(path, [_CHATML_ROW, _AUDIO_ROW])
+ with pytest.raises(ValueError, match="audio"):
+ _load(path)
+
+
+def test_mixed_asr_file_refuses(tmp_path):
+ path = tmp_path / "mixed_asr.jsonl"
+ _write(path, [_PLAINTEXT_ROW, _ASR_ROW])
+ with pytest.raises(ValueError, match="asr"):
+ _load(path)
+
+
+# ---------------------------------------------------------------------------
+# Pinned by review: behaviours the refusal message promises
+# ---------------------------------------------------------------------------
+
+
+def test_upgrade_needs_the_richer_converter_to_accept_every_poorer_row():
+ # Row 0 converts fine as tool-calling, row 1 does not (list content is refused
+ # by the tool-calling converter). One accepted row must not be enough to upgrade.
+ multipart = [
+ {"role": "user", "content": [{"type": "text", "text": "q"}]},
+ {"role": "assistant", "content": "a"},
+ ]
+ data = [
+ {"messages": _CHAT},
+ {"messages": multipart},
+ {"messages": _CHAT, "tools": [_TOOL]},
+ ]
+ with pytest.raises(ValueError) as exc:
+ detect_format(data)
+ message = str(exc.value)
+ assert "'chatml' (row 0)" in message
+ assert "'tool-calling' (row 2)" in message
+ assert "data.format" in message
+
+
+def test_refusal_names_the_first_row_of_each_shape():
+ sharegpt = {"conversations": _SHAREGPT}
+ llava = {"image": "i.png", "conversations": _SHAREGPT}
+ with pytest.raises(ValueError) as exc:
+ detect_format([sharegpt, sharegpt, sharegpt, llava, llava, llava])
+ message = str(exc.value)
+ assert "'sharegpt' (row 0)" in message
+ assert "'llava' (row 3)" in message
+
+
+def test_inspect_endpoint_reports_a_mixed_file_instead_of_a_500(tmp_path):
+ try:
+ from fastapi.testclient import TestClient
+ except ImportError:
+ pytest.skip("FastAPI not installed")
+ from unittest.mock import patch
+
+ from soup_cli.ui.app import create_app, get_auth_token
+
+ path = tmp_path / "mixed.jsonl"
+ rows = [{"conversations": _SHAREGPT}] + [
+ {"image": "i.png", "conversations": _SHAREGPT}
+ ] * 3
+ path.write_text("".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8")
+
+ client = TestClient(create_app(), raise_server_exceptions=False)
+ with patch("soup_cli.ui.app.Path.cwd", return_value=tmp_path):
+ response = client.post(
+ "/api/data/inspect",
+ json={"path": str(path), "limit": 10},
+ headers={"Authorization": f"Bearer {get_auth_token()}"},
+ )
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["total"] == 4
+ assert body["format"] == "unknown"
+ assert "mixes" in body["format_error"]
+
+
+def test_upgrade_refuses_when_the_richer_converter_would_drop_a_field():
+ # A chatml row whose messages carry `name`/`weight` converts through the
+ # chatml converter with those fields and through the tool-calling converter
+ # without them, so the "upgrade" would silently drop them. The converter
+ # accepts the row rather than rejecting it, so acceptance alone is not enough.
+ extras = {
+ "messages": [
+ {"role": "user", "content": "q", "name": "alice", "weight": 0.5},
+ {"role": "assistant", "content": "a"},
+ ]
+ }
+ data = [{"messages": _CHAT}, extras, _TOOL_ROW]
+ with pytest.raises(ValueError) as exc:
+ detect_format(data)
+ message = str(exc.value)
+ assert "'chatml' (row 0)" in message
+ assert "'tool-calling' (row 2)" in message
+ assert "data.format" in message
+
+
+def test_upgrade_still_happens_when_the_converters_agree():
+ # The plain case must still upgrade: no field is lost.
+ assert detect_format([{"messages": _CHAT}, _TOOL_ROW]) == "tool-calling"