Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
fix(data): report and skip non-object JSON dataset rows (#1873)
Aditya Pratap Singh3cc1463ff140
diff --git a/changelog.d/0.76.0/1873.fixed.md b/changelog.d/0.76.0/1873.fixed.mdnew file mode 100644index 00000000..b414c382--- /dev/null+++ b/changelog.d/0.76.0/1873.fixed.md@@ -0,0 +1 @@+- **Dataset commands warn and skip non-object JSON rows instead of crashing.** JSONL warnings identify the physical line and JSON-array warnings identify the row; validation lists these as issues, and review checks objects before accessing pair fields. Rejected contents are not printed. Canary insertion still refuses a non-object first row and preserves later rows. (#1860 by @akkupratap323 in #1873)diff --git a/docs/data.md b/docs/data.mdindex cb98ce57..1ef97ba2 100644--- a/docs/data.md+++ b/docs/data.md@@ -640,6 +640,12 @@ reports "Could not read the final trainer's args statically" and uses Soup defau## Data Formats+JSONL dataset rows must be objects; JSON dataset files must contain an array of+objects. Non-object rows are skipped with a warning naming the physical JSONL+line or JSON array row. `soup data validate` also lists these warnings as issues;+its row statistics describe the retained objects. `soup data review` applies the+same object check before displaying a pair. Rejected row contents are not printed. `soup data canary insert` retains its first-row refusal and preserves later rows when rewriting the file.+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 resolvesdiff --git a/src/soup_cli/commands/data.py b/src/soup_cli/commands/data.pyindex a2a8b723..3d116190 100644--- a/src/soup_cli/commands/data.py+++ b/src/soup_cli/commands/data.py@@ -13,8 +13,8 @@ import typerfrom rich.console import Consolefrom rich.table import Table-from soup_cli.data.loader import _resolve_media_entries, load_raw_data-from soup_cli.data.validator import validate_and_stats+from soup_cli.data.loader import _resolve_media_entries, load_raw_data, non_object_row_issue+from soup_cli.data.validator import _MAX_REASON_SAMPLES, validate_and_statsfrom soup_cli.utils.embed import DEFAULT_EMBED_MODEL, embed_textsfrom soup_cli.utils.exit_codes import EXIT_GATE_FAILED, EXIT_USAGE_ERROR, GateCommandfrom soup_cli.utils.paths import is_under_cwd@@ -109,7 +109,8 @@ def validate()raise typer.Exit(EXIT_USAGE_ERROR)- data = load_raw_data(file_path)+ load_issues: list[str] = []+ data = load_raw_data(file_path, issues=load_issues)# Auto-detect format if not specifiedif fmt == "auto":@@ -123,6 +124,10 @@ def validate(raise typer.Exit(EXIT_USAGE_ERROR)result = validate_and_stats(data, expected_format=fmt)+ load_issue_samples = load_issues[:_MAX_REASON_SAMPLES]+ if len(load_issues) > _MAX_REASON_SAMPLES:+ load_issue_samples.append(f"... and {len(load_issues) - _MAX_REASON_SAMPLES} more")+ result["issues"] = load_issue_samples + result["issues"]if result["issues"]:console.print("[yellow]Issues found:[/]")@@ -2266,7 +2271,7 @@ def review_cmd(shown = 0with path.open("r", encoding="utf-8") as fh:- for line in fh:+ for line_number, line in enumerate(fh, start=1):if shown >= sample:breakline = line.strip()@@ -2276,6 +2281,10 @@ def review_cmd(entry = _json.loads(line)except _json.JSONDecodeError:continue+ if not isinstance(entry, dict):+ issue = non_object_row_issue(entry, line_number)+ console.print(f"[yellow]Warning: {issue}[/]")+ continueprompt = str(entry.get("prompt", ""))chosen = str(entry.get("chosen", ""))rejected = str(entry.get("rejected", ""))diff --git a/src/soup_cli/commands/data_canary.py b/src/soup_cli/commands/data_canary.pyindex 4577638a..b44d0dd9 100644--- a/src/soup_cli/commands/data_canary.py+++ b/src/soup_cli/commands/data_canary.py@@ -175,7 +175,8 @@ def insert(f"got {output!r}")- rows = load_raw_data(file_path)+ # _resolve_format needs the raw first row; insert writes later rows back as read.+ rows = load_raw_data(file_path, skip_non_object=False)fmt = _resolve_format(rows, data_format, path)try:canaries = generate_canaries(count=count, seed=seed)diff --git a/src/soup_cli/data/loader.py b/src/soup_cli/data/loader.pyindex c17f91dc..0dac7163 100644--- a/src/soup_cli/data/loader.py+++ b/src/soup_cli/data/loader.py@@ -70,8 +70,10 @@ def _streaming_builder_for(entry: str) -> str:MAX_REMOTE_ROWS = 1_000_000-def load_raw_data(path: Path) -> list[dict]:- """Load raw data from a file into list of dicts."""+def load_raw_data(+ path: Path, *, issues: list[str] | None = None, skip_non_object: bool = True,+) -> list[dict]:+ """Load file rows, skipping non-objects unless a caller needs the original JSON rows."""if not path.exists():raise FileNotFoundError(f"Data file not found: {path}")@@ -80,9 +82,9 @@ def load_raw_data(path: Path) -> list[dict]:raise ValueError(f"Unsupported file format: {ext}. Supported: {SUPPORTED_EXTENSIONS}")if ext == ".jsonl":- return _load_jsonl(path)+ return _load_jsonl(path, issues=issues, skip_non_object=skip_non_object)elif ext == ".json":- return _load_json(path)+ return _load_json(path, issues=issues, skip_non_object=skip_non_object)elif ext == ".csv":return _load_csv(path)elif ext == ".parquet":@@ -93,7 +95,18 @@ def load_raw_data(path: Path) -> list[dict]:raise ValueError(f"Unsupported format: {ext}")-def _load_jsonl(path: Path) -> list[dict]:+def non_object_row_issue(value: object, position: int, unit: str = "line") -> str:+ """Describe a rejected JSON value without printing its possibly sensitive contents."""+ kind = {+ str: "string", list: "array", int: "number", float: "number",+ bool: "boolean", type(None): "null",+ }[type(value)]+ return f"{unit} {position} is a JSON {kind}, not an object"+++def _load_jsonl(+ path: Path, *, issues: list[str] | None = None, skip_non_object: bool = True,+) -> list[dict]:data = []# v0.40.1 Part E — auto-strip UTF-8 BOM (Windows users overwhelmingly# write JSONL via PowerShell `Out-File -Encoding utf8` which adds BOM).@@ -104,17 +117,37 @@ def _load_jsonl(path: Path) -> list[dict]:if not line:continuetry:- data.append(json.loads(line))+ row = json.loads(line)+ if skip_non_object and not isinstance(row, dict):+ issue = non_object_row_issue(row, i + 1)+ console.print(f"[yellow]Warning: {issue}[/]")+ if issues is not None:+ issues.append(issue)+ continue+ data.append(row)except json.JSONDecodeError as e:console.print(f"[yellow]Warning: invalid JSON on line {i + 1}: {e}[/]")return data-def _load_json(path: Path) -> list[dict]:+def _load_json(+ path: Path, *, issues: list[str] | None = None, skip_non_object: bool = True,+) -> list[dict]:with open(path, encoding="utf-8") as f:raw = json.load(f)if isinstance(raw, list):- return raw+ if not skip_non_object:+ return raw+ rows = []+ for position, row in enumerate(raw, start=1):+ if not isinstance(row, dict):+ issue = non_object_row_issue(row, position, "row")+ console.print(f"[yellow]Warning: {issue}[/]")+ if issues is not None:+ issues.append(issue)+ continue+ rows.append(row)+ return rowsraise ValueError("JSON file must contain a list of objects")diff --git a/tests/test_data_non_object_rows.py b/tests/test_data_non_object_rows.pynew file mode 100644index 00000000..f6688137--- /dev/null+++ b/tests/test_data_non_object_rows.py@@ -0,0 +1,135 @@+"""Non-object dataset rows are named and skipped, with a canary first-row exception."""++import json++import pytest+from typer.testing import CliRunner++from soup_cli.commands.data import app+from soup_cli.commands.data_canary import app as canary_app+from soup_cli.config.schema import DataConfig+from soup_cli.data.loader import load_dataset, load_raw_data+from tests.conftest import strip_ansi++GOOD = {"instruction": "A sufficiently long question", "output": "A useful answer"}+GOOD2 = {**GOOD, "instruction": "Another sufficiently long question"}+BAD_KINDS = [("abc", "string"), ([1, 2], "array"), (42, "number"),+ (None, "null"), (True, "boolean"), (1.5, "number")]+++def _plain(text):+ return " ".join(strip_ansi(text).split())+++def _write(path, rows):+ content = ("\n".join(json.dumps(row) for row in rows)+ if path.suffix == ".jsonl" else json.dumps(rows))+ path.write_text(content, encoding="utf-8")+ return content++[email protected]("bad,kind", BAD_KINDS)[email protected]("extension", ["jsonl", "json"])+def test_raw_loader_skips_non_objects_and_names_their_kind(tmp_path, capsys, bad, kind, extension):+ path = tmp_path / f"mixed.{extension}"+ _write(path, [GOOD, bad, GOOD2])+ issues = []+ assert load_raw_data(path, issues=issues) == [GOOD, GOOD2]+ unit = "line" if extension == "jsonl" else "row"+ assert issues == [f"{unit} 2 is a JSON {kind}, not an object"]+ assert issues[0] in _plain(capsys.readouterr().out)++[email protected]("bad,kind", BAD_KINDS)[email protected]("command", ["review", "inspect", "validate", "stats", "dedup"])[email protected]("position", [1, 2])+def test_commands_skip_junk_at_first_or_middle_line_and_continue(+ tmp_path, monkeypatch, bad, kind, command, position,+):+ monkeypatch.chdir(tmp_path)+ path = tmp_path / "mixed.jsonl"+ rows = [GOOD, GOOD2]+ rows.insert(position - 1, bad)+ _write(path, rows)+ args = [command, str(path)]+ if command == "validate":+ args += ["--format", "alpaca"]+ if command == "dedup":+ args += ["--output", "deduped.jsonl"]+ result = CliRunner().invoke(app, args)+ assert result.exit_code == 0, (result.output, result.exception)+ output = _plain(result.output)+ assert f"line {position} is a JSON {kind}, not an object" in output+ if command == "review":+ assert "Pair 2" in output+ if command == "validate":+ assert "Issues found:" in output+ assert "Dataset is valid!" not in output+++def test_blank_lines_keep_the_physical_line_and_hide_contents(tmp_path, capsys):+ path = tmp_path / "blank.jsonl"+ path.write_text('\n\n"private content"\n' + json.dumps(GOOD), encoding="utf-8")+ assert load_raw_data(path) == [GOOD]+ output = _plain(capsys.readouterr().out)+ assert "line 3 is a JSON string, not an object" in output+ assert "private content" not in output++[email protected]("bad,kind", BAD_KINDS)[email protected]("extension", ["jsonl", "json"])[email protected]("explicit_format", [False, True])+def test_canary_insert_refuses_non_object_first_row_without_writing(+ tmp_path, monkeypatch, bad, kind, extension, explicit_format,+):+ monkeypatch.chdir(tmp_path)+ path = tmp_path / f"mixed.{extension}"+ content = _write(path, [bad, GOOD])+ args = ["insert", str(path), "--manifest", "manifest.json", "-o", "canaried.jsonl"]+ if explicit_format:+ args += ["--format", "alpaca"]+ result = CliRunner().invoke(canary_app, args)+ assert result.exit_code == 1+ assert f"the first row is a JSON {kind}, not an object" in _plain(result.output)+ assert not (tmp_path / "canaried.jsonl").exists()+ assert not (tmp_path / "manifest.json").exists()+ assert path.read_text(encoding="utf-8") == content++[email protected]("extension", ["jsonl", "json"])+def test_canary_insert_preserves_later_non_object_rows(tmp_path, monkeypatch, extension):+ monkeypatch.chdir(tmp_path)+ path = tmp_path / f"mixed.{extension}"+ _write(path, [GOOD, 42, GOOD2])+ issues = []+ assert load_raw_data(path, issues=issues, skip_non_object=False) == [GOOD, 42, GOOD2]+ assert issues == []+ result = CliRunner().invoke(canary_app, [+ "insert", str(path), "--manifest", "manifest.json", "-o", "canaried.jsonl", "--count", "2",+ ])+ assert result.exit_code == 0, (result.output, result.exception)+ written = [json.loads(line) for line in (tmp_path / "canaried.jsonl").read_text().splitlines()]+ assert len(written) == 5+ assert [row for row in written if row in [GOOD, 42, GOOD2]] == [GOOD, 42, GOOD2]+++def test_training_loader_warns_before_conversion_instead_of_old_drop_error(tmp_path, capsys):+ path = tmp_path / "train.jsonl"+ _write(path, [GOOD, "abc", GOOD2])+ dataset = load_dataset(DataConfig(train=str(path), format="alpaca", val_split=0.0))+ assert len(dataset["train"]) == 2+ output = _plain(capsys.readouterr().out)+ assert "line 2 is a JSON string, not an object" in output+ assert "string indices must be integers" not in output+++def test_validate_caps_the_repeated_issue_listing(tmp_path):+ path = tmp_path / "many.jsonl"+ _write(path, [GOOD] + [42] * 6)+ result = CliRunner().invoke(app, ["validate", str(path), "--format", "alpaca"])+ assert result.exit_code == 0, (result.output, result.exception)+ listing = _plain(result.output).split("Issues found:", 1)[1]+ for line in (2, 3, 4):+ assert f"line {line} is a JSON number, not an object" in listing+ assert "line 5 is a JSON" not in listing+ assert "... and 3 more" in listing