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): cap per-row skip warnings in the dataset loader (#1888) (#1930)

George Tonmoy Roy1ad921356e1b
diff --git a/changelog.d/0.76.0/1930.fixed.md b/changelog.d/0.76.0/1930.fixed.md
new file mode 100644
index 00000000..aac21a08
--- /dev/null
+++ b/changelog.d/0.76.0/1930.fixed.md
@@ -0,0 +1 @@
+- **Dataset loading no longer prints one warning per skipped row.** The JSON/JSONL loader and `soup data review` print the first three warnings per kind (non-object rows, invalid-JSON lines), then one `... and N more` line; `soup data validate` still reports the exact skipped count. (#1888 by @george07-t in #1930)
diff --git a/docs/data.md b/docs/data.md
index 001f7690..1fdd18c5 100644
--- a/docs/data.md
+++ b/docs/data.md
@@ -679,11 +679,11 @@ where a key is absent (#1807):
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` lists these warnings as issues (the
-first three, then `... and N more`), and every skipped row, whether not an object
+first three of each kind, then `... and N more`), and every skipped row, whether not an object
or not valid JSON, counts as an invalid row in its `N/M rows valid` line, in
`--min-valid-fraction` and in the exit code; its other 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.
+same object check before displaying a pair. Rejected row contents are not printed. The loader likewise prints only the first three warnings per kind (non-object rows, invalid-JSON lines), then one `... and N more` line. `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.
diff --git a/src/soup_cli/commands/data.py b/src/soup_cli/commands/data.py
index 4508cdb3..385871df 100644
--- a/src/soup_cli/commands/data.py
+++ b/src/soup_cli/commands/data.py
@@ -13,8 +13,14 @@ import typer
from rich.console import Console
from rich.table import Table
-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_stats
+from soup_cli.data.loader import (
+ SkippedRows,
+ SkipTally,
+ _resolve_media_entries,
+ load_raw_data,
+ non_object_row_issue,
+)
+from soup_cli.data.validator import validate_and_stats
from soup_cli.utils.embed import DEFAULT_EMBED_MODEL, embed_texts
from soup_cli.utils.exit_codes import EXIT_GATE_FAILED, EXIT_USAGE_ERROR, GateCommand
from soup_cli.utils.paths import is_under_cwd
@@ -109,12 +115,12 @@ def validate(
)
raise typer.Exit(EXIT_USAGE_ERROR)
- load_issues: list[str] = []
+ load_issues = SkippedRows()
data = load_raw_data(file_path, issues=load_issues)
# #1887: every row the loader skipped (not an object, or not JSON) is an
# invalid row for the N/M line, for --min-valid-fraction and for the exit
# code. The statistics below still describe the retained objects.
- skipped = len(load_issues)
+ skipped = load_issues.total
none_remain = f"no object rows remain: {skipped} row(s) skipped (listed above)"
# Auto-detect format if not specified
@@ -135,9 +141,11 @@ def validate(
if not data and skipped:
result["issues"] = [none_remain if i == "Dataset is empty" else i
for i in result["issues"]]
- 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")
+ # The loader keeps up to _MAX_REASON_SAMPLES messages per kind, so list them all
+ # and report the exact remainder.
+ load_issue_samples = list(load_issues)
+ if load_issues.total > len(load_issue_samples):
+ load_issue_samples.append(f"... and {load_issues.total - len(load_issue_samples)} more")
result["issues"] = load_issue_samples + result["issues"]
if result["issues"]:
@@ -2281,6 +2289,7 @@ def review_cmd(
raise typer.Exit(1)
shown = 0
+ non_objects = SkipTally("lines skipped (JSON values that are not objects)")
with path.open("r", encoding="utf-8") as fh:
for line_number, line in enumerate(fh, start=1):
if shown >= sample:
@@ -2293,8 +2302,7 @@ def review_cmd(
except _json.JSONDecodeError:
continue
if not isinstance(entry, dict):
- issue = non_object_row_issue(entry, line_number)
- console.print(f"[yellow]Warning: {issue}[/]")
+ non_objects.add(non_object_row_issue(entry, line_number))
continue
prompt = str(entry.get("prompt", ""))
chosen = str(entry.get("chosen", ""))
@@ -2308,6 +2316,7 @@ def review_cmd(
))
shown += 1
+ non_objects.finish()
if shown == 0:
console.print("[yellow]No pairs found in file.[/]")
diff --git a/src/soup_cli/data/loader.py b/src/soup_cli/data/loader.py
index f189b983..6f55efe8 100644
--- a/src/soup_cli/data/loader.py
+++ b/src/soup_cli/data/loader.py
@@ -20,6 +20,7 @@ from soup_cli.data.formats import (
is_vision_format,
unify_preference_layout,
)
+from soup_cli.data.validator import _MAX_REASON_SAMPLES
from soup_cli.utils.paths import is_under_cwd
console = Console()
@@ -73,7 +74,11 @@ MAX_REMOTE_ROWS = 1_000_000
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."""
+ """Load file rows, skipping non-objects unless a caller needs the original JSON rows.
+
+ ``issues`` receives at most ``_MAX_REASON_SAMPLES`` messages per kind of skipped row.
+ Pass a ``SkippedRows`` to also get the exact number of skipped rows in ``.total``.
+ """
if not path.exists():
raise FileNotFoundError(f"Data file not found: {path}")
@@ -104,10 +109,54 @@ def non_object_row_issue(value: object, position: int, unit: str = "line") -> st
return f"{unit} {position} is a JSON {kind}, not an object"
+class SkippedRows(list):
+ """``issues`` list for ``load_raw_data``: keeps a bounded sample plus an exact total."""
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.total = 0
+
+
+class SkipTally:
+ """Counts rows skipped for one reason; prints only the first few warnings.
+
+ The exact ``count`` is always kept. Warnings, and the messages recorded in
+ ``issues``, stop after ``_MAX_REASON_SAMPLES``; ``finish()`` prints one line
+ for the rest.
+ """
+
+ def __init__(
+ self, summary: str, *, issues: list[str] | None = None, record: bool = False,
+ ) -> None:
+ self.summary = summary
+ self.count = 0
+ self.issues = issues
+ self.record = record
+
+ def add(self, message: str) -> None:
+ self.count += 1
+ if self.record and isinstance(self.issues, SkippedRows):
+ self.issues.total += 1
+ if self.count > _MAX_REASON_SAMPLES:
+ return
+ console.print(f"[yellow]Warning: {message}[/]")
+ if self.record and self.issues is not None:
+ self.issues.append(message)
+
+ def finish(self) -> None:
+ extra = self.count - _MAX_REASON_SAMPLES
+ if extra > 0:
+ console.print(f"[yellow]Warning: ... and {extra} more {self.summary}[/]")
+
+
def _load_jsonl(
path: Path, *, issues: list[str] | None = None, skip_non_object: bool = True,
) -> list[dict]:
data = []
+ non_objects = SkipTally(
+ "lines skipped (JSON values that are not objects)", issues=issues, record=True,
+ )
+ bad_json = SkipTally("lines skipped (invalid JSON)", issues=issues, record=True)
# v0.40.1 Part E — auto-strip UTF-8 BOM (Windows users overwhelmingly
# write JSONL via PowerShell `Out-File -Encoding utf8` which adds BOM).
# The ``utf-8-sig`` codec consumes the BOM transparently if present.
@@ -119,19 +168,13 @@ def _load_jsonl(
try:
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)
+ non_objects.add(non_object_row_issue(row, i + 1))
continue
data.append(row)
except json.JSONDecodeError as e:
- issue = f"invalid JSON on line {i + 1}: {e}"
- console.print(f"[yellow]Warning: {issue}[/]")
- if issues is not None:
- # #1887: a line that is not JSON is a skipped row too, and
- # `soup data validate` counts it like a non-object row.
- issues.append(issue)
+ bad_json.add(f"invalid JSON on line {i + 1}: {e}")
+ non_objects.finish()
+ bad_json.finish()
return data
@@ -144,14 +187,15 @@ def _load_json(
if not skip_non_object:
return raw
rows = []
+ non_objects = SkipTally(
+ "rows skipped (JSON values that are not objects)", issues=issues, record=True,
+ )
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)
+ non_objects.add(non_object_row_issue(row, position, "row"))
continue
rows.append(row)
+ non_objects.finish()
return rows
raise ValueError("JSON file must contain a list of objects")
diff --git a/tests/test_data_loader_skip_warning_cap.py b/tests/test_data_loader_skip_warning_cap.py
new file mode 100644
index 00000000..e19629ee
--- /dev/null
+++ b/tests/test_data_loader_skip_warning_cap.py
@@ -0,0 +1,188 @@
+"""Skipped-row warnings are capped per kind, with an exact count kept."""
+
+import json
+import re
+
+import pytest
+from typer.testing import CliRunner
+
+from soup_cli.commands.data import app
+from soup_cli.data.loader import SkippedRows, load_raw_data
+from soup_cli.data.validator import _MAX_REASON_SAMPLES as N
+from tests.conftest import strip_ansi
+
+GOOD = {"instruction": "A sufficiently long question", "output": "A useful answer"}
+PAIR = {"prompt": "A sufficiently long prompt", "chosen": "Good", "rejected": "Bad"}
+
+
+def _plain(text):
+ return " ".join(strip_ansi(text).split())
+
+
+def _write_jsonl(path, lines):
+ path.write_text("\n".join(lines) + "\n", encoding="utf-8")
+
+
+def _non_object_warnings(text, unit="line"):
+ return re.findall(rf"Warning: {unit} \d+ is a JSON \w+, not an object", _plain(text))
+
+
+def _bad_json_warnings(text):
+ return re.findall(r"Warning: invalid JSON on line \d+", _plain(text))
+
+
+def test_jsonl_non_objects_are_capped_with_one_summary(tmp_path, capsys):
+ path = tmp_path / "junk.jsonl"
+ _write_jsonl(path, [json.dumps(GOOD)] + [str(i) for i in range(N + 5)])
+ issues = SkippedRows()
+ assert load_raw_data(path, issues=issues) == [GOOD]
+ out = capsys.readouterr().out
+ assert len(_non_object_warnings(out)) == N
+ assert _plain(out).count("... and 5 more lines skipped") == 1
+ assert issues.total == N + 5
+ assert len(issues) == N
+
+
+def test_json_array_non_objects_are_capped_with_one_summary(tmp_path, capsys):
+ path = tmp_path / "junk.json"
+ path.write_text(json.dumps([GOOD] + list(range(N + 5))), encoding="utf-8")
+ issues = SkippedRows()
+ assert load_raw_data(path, issues=issues) == [GOOD]
+ out = capsys.readouterr().out
+ assert len(_non_object_warnings(out, "row")) == N
+ assert _plain(out).count("... and 5 more rows skipped") == 1
+ assert issues.total == N + 5
+ assert len(issues) == N
+
+
+def test_invalid_json_lines_are_capped_with_one_summary(tmp_path, capsys):
+ path = tmp_path / "junk.jsonl"
+ _write_jsonl(path, [json.dumps(GOOD)] + [f"{{not json {i}" for i in range(N + 5)])
+ assert load_raw_data(path) == [GOOD]
+ out = capsys.readouterr().out
+ assert len(_bad_json_warnings(out)) == N
+ assert _plain(out).count("... and 5 more lines skipped (invalid JSON)") == 1
+
+
+def test_each_kind_gets_its_own_cap_and_summary(tmp_path, capsys):
+ path = tmp_path / "mixed.jsonl"
+ lines = [json.dumps(GOOD)]
+ lines += [str(i) for i in range(N + 2)]
+ lines += [f"{{not json {i}" for i in range(N + 2)]
+ _write_jsonl(path, lines)
+ issues = SkippedRows()
+ assert load_raw_data(path, issues=issues) == [GOOD]
+ out = capsys.readouterr().out
+ assert len(_non_object_warnings(out)) == N
+ assert len(_bad_json_warnings(out)) == N
+ assert _plain(out).count("... and 2 more lines skipped (JSON values") == 1
+ assert _plain(out).count("... and 2 more lines skipped (invalid JSON)") == 1
+ # every skipped row, of either kind, is counted (#1887) and 2 * N samples are kept
+ assert issues.total == 2 * (N + 2)
+ assert len(issues) == 2 * N
+
+
[email protected]("junk", [N - 1, N])
+def test_up_to_the_cap_prints_every_warning_and_no_summary(tmp_path, capsys, junk):
+ path = tmp_path / "few.jsonl"
+ _write_jsonl(path, [json.dumps(GOOD)] + [str(i) for i in range(junk)])
+ issues = SkippedRows()
+ load_raw_data(path, issues=issues)
+ out = capsys.readouterr().out
+ assert len(_non_object_warnings(out)) == junk
+ assert "more" not in _plain(out)
+ assert issues.total == junk
+ assert len(issues) == junk
+
+
+def test_plain_list_issues_still_works_and_is_bounded(tmp_path):
+ path = tmp_path / "junk.jsonl"
+ _write_jsonl(path, [json.dumps(GOOD)] + [str(i) for i in range(N + 5)])
+ issues = []
+ load_raw_data(path, issues=issues)
+ assert len(issues) == N
+
+
+def test_validate_reports_capped_listing_with_exact_remainder(tmp_path, monkeypatch):
+ monkeypatch.chdir(tmp_path)
+ path = tmp_path / "junk.jsonl"
+ _write_jsonl(path, [json.dumps(GOOD)] + [str(i) for i in range(N + 5)])
+ result = CliRunner().invoke(app, ["validate", str(path), "--format", "alpaca"])
+ assert result.exit_code == 0, (result.output, result.exception)
+ out = _plain(result.output)
+ assert len(_non_object_warnings(out)) == N # loader warnings
+ assert len(re.findall(r"! line \d+ is a JSON number", out)) == N # issue listing
+ assert out.count("... and 5 more lines skipped") == 1 # loader summary
+ assert out.count("! ... and 5 more") == 1 # listing remainder
+
+
+def test_review_caps_warnings_and_still_shows_pairs(tmp_path, monkeypatch):
+ monkeypatch.chdir(tmp_path)
+ path = tmp_path / "pairs.jsonl"
+ _write_jsonl(path, [str(i) for i in range(N + 5)] + [json.dumps(PAIR)])
+ result = CliRunner().invoke(app, ["review", str(path)])
+ assert result.exit_code == 0, (result.output, result.exception)
+ out = _plain(result.output)
+ assert len(_non_object_warnings(out)) == N
+ assert out.count("... and 5 more lines skipped") == 1
+ assert "Pair 1" in out
+
+
+def test_large_junk_file_is_bounded(tmp_path, capsys):
+ path = tmp_path / "junk20k.jsonl"
+ _write_jsonl(path, [json.dumps(GOOD)] + [str(i) for i in range(20000)])
+ issues = SkippedRows()
+ assert load_raw_data(path, issues=issues) == [GOOD]
+ out = capsys.readouterr().out
+ assert len(_non_object_warnings(out)) == N
+ assert issues.total == 20000
+ assert len(issues) == N
+
+
[email protected]("extension", ["jsonl", "json"])
+def test_validate_counts_every_skipped_row_not_just_the_sampled_ones(tmp_path, extension):
+ # #1887 counts skipped rows as invalid rows; with the warnings capped, the count
+ # must come from the exact total, not from the few retained samples.
+ junk = N + 17
+ path = tmp_path / f"data.{extension}"
+ rows = [GOOD, {**GOOD, "instruction": "Another sufficiently long question"}]
+ if extension == "jsonl":
+ _write_jsonl(path, [json.dumps(r) for r in rows] + [str(i) for i in range(junk)])
+ else:
+ path.write_text(json.dumps(rows + list(range(junk))), encoding="utf-8")
+ total = 2 + junk
+
+ result = CliRunner().invoke(app, ["validate", str(path), "--format", "alpaca"])
+ out = _plain(result.output)
+ assert f"2/{total} rows valid" in out, out
+
+ gated = CliRunner().invoke(
+ app, ["validate", str(path), "--format", "alpaca", "--min-valid-fraction", "0.5"],
+ )
+ assert gated.exit_code == 2, _plain(gated.output)
+
+
+def test_validate_counts_non_object_and_invalid_json_lines_together(tmp_path):
+ path = tmp_path / "mixed.jsonl"
+ _write_jsonl(
+ path,
+ [json.dumps(GOOD)] + [str(i) for i in range(N + 4)] + ["{bad"] * (N + 6),
+ )
+ skipped = (N + 4) + (N + 6)
+ result = CliRunner().invoke(app, ["validate", str(path), "--format", "alpaca"])
+ assert f"1/{1 + skipped} rows valid" in _plain(result.output), _plain(result.output)
+
+
+def test_validate_listing_shows_samples_of_both_kinds(tmp_path):
+ path = tmp_path / "both.jsonl"
+ _write_jsonl(
+ path,
+ [json.dumps(GOOD)] + [str(i) for i in range(N)] + ["{bad"] * (N + 2),
+ )
+ result = CliRunner().invoke(app, ["validate", str(path), "--format", "alpaca"])
+ out = _plain(result.output)
+ # the issue listing under "Issues found" keeps samples of both kinds
+ listing = out.split("Issues found", 1)[1]
+ assert listing.count("invalid JSON on line") == N, out
+ assert listing.count("not an object") == N, out
+ assert "... and 2 more" in listing, out