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: resolve vision image paths relative to dataset (#1604)

Suyog Vermab4b108483796
diff --git a/changelog.d/0.75.1/1604.fixed.md b/changelog.d/0.75.1/1604.fixed.md
new file mode 100644
index 00000000..943db9e3
--- /dev/null
+++ b/changelog.d/0.75.1/1604.fixed.md
@@ -0,0 +1 @@
+- `soup data inspect` resolves relative vision image paths against the data file's directory (or `--image-dir`), the same way training does, and reports an image training would refuse as outside the image directory instead of counting it as found (#1598 by @commit-msuyog in #1604).
\ No newline at end of file
diff --git a/docs/commands.md b/docs/commands.md
index 0b0ae509..6454acee 100644
--- a/docs/commands.md
+++ b/docs/commands.md
@@ -99,7 +99,7 @@ POST /v1/adapters/activate/<name> Hot-swap active LoRA adapter
soup sweep --config soup.yaml --param lr=... Hyperparameter search
soup sweep --config soup.yaml --sweep-config sweep.yaml Sweep from a standalone strategy/n_runs/seed/params file
soup diff --model-a ./a --model-b ./b Compare two models
-soup data inspect <path> View dataset stats
+soup data inspect <path> [--image-dir <dir>] View dataset stats; optionally override vision image directory
soup data validate <path> Check format (auto-detect)
soup data doctor <path> --model <id> Chat-template compat report: 8 checks, OK/MINOR/MAJOR
soup data doctor <path> --model <id> --show-mask N Per-token trained/masked colouring via the real collator
diff --git a/docs/training.md b/docs/training.md
index 67d48c66..8371d83c 100644
--- a/docs/training.md
+++ b/docs/training.md
@@ -1073,7 +1073,7 @@ Decoded in-memory PIL images (such as from a Hugging Face Hub `Image()` column)
image structs (`{"bytes": ..., "path": ...}`) written by `datasets` are also accepted; a struct's
`path` follows the same directory resolution and path containment rules as a plain path string.
-`soup data inspect` automatically shows image statistics (count, formats, missing files) for vision datasets.
+`soup data inspect` resolves image paths the same way, or uses `--image-dir` when provided, and automatically shows image statistics (count, formats, missing files) for vision datasets.
## Audio / Speech Fine-tuning
diff --git a/src/soup_cli/commands/data.py b/src/soup_cli/commands/data.py
index b7c58303..d6eb2af0 100644
--- a/src/soup_cli/commands/data.py
+++ b/src/soup_cli/commands/data.py
@@ -13,11 +13,11 @@ import typer
from rich.console import Console
from rich.table import Table
-from soup_cli.data.loader import load_raw_data
+from soup_cli.data.loader import _resolve_media_entries, load_raw_data
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_network_or_device_path, is_under_cwd
+from soup_cli.utils.paths import is_under_cwd
from soup_cli.utils.semdedup import DedupReport, greedy_semdedup
from soup_cli.utils.terminal import for_terminal
@@ -30,6 +30,9 @@ app = typer.Typer(no_args_is_help=True)
def inspect(
path: str = typer.Argument(..., help="Path to dataset file (jsonl, csv, parquet)"),
rows: int = typer.Option(5, "--rows", "-r", help="Number of sample rows to show"),
+ image_dir: Optional[str] = typer.Option(
+ None, "--image-dir", help="Directory containing referenced images"
+ ),
):
"""Inspect a dataset: show stats and sample rows."""
file_path = Path(path)
@@ -55,7 +58,8 @@ def inspect(
console.print(stats_table)
# Vision stats (if dataset contains images)
- _show_vision_stats(data)
+ image_root = Path(image_dir) if image_dir else file_path.parent
+ _show_vision_stats(data, image_root)
# Print sample rows
if rows > 0 and len(data) > 0:
@@ -674,11 +678,14 @@ def stats(
)
-def _show_vision_stats(data: list[dict]) -> None:
+def _show_vision_stats(data: list[dict], image_dir: Path | None = None) -> None:
"""Show image statistics if dataset contains image fields."""
if not data:
return
+ if image_dir is None:
+ image_dir = Path.cwd()
+
# Check if this is a vision dataset
sample = data[0]
if "image" not in sample:
@@ -690,16 +697,22 @@ def _show_vision_stats(data: list[dict]) -> None:
# Collect image file info
extensions: dict[str, int] = {}
+ entries, _, outside = _resolve_media_entries(
+ data, "image", image_dir, source="data.inspect"
+ )
+
existing = 0
- for row in data:
- img_path = row.get("image", "")
- if not img_path or not isinstance(img_path, str):
+ for row in entries:
+ if row is None:
+ continue
+
+ img_path = row.get("image")
+ if not isinstance(img_path, str):
continue
+
ext = Path(img_path).suffix.lower()
extensions[ext] = extensions.get(ext, 0) + 1
- # A network share or a device path is never looked up, nor counted as found.
- if is_network_or_device_path(img_path):
- continue
+
if Path(img_path).exists():
existing += 1
@@ -709,9 +722,14 @@ def _show_vision_stats(data: list[dict]) -> None:
vision_table.add_row("Images referenced", str(has_image))
vision_table.add_row("Missing image field", str(missing_image))
vision_table.add_row("Images found on disk", str(existing))
+ vision_table.add_row("Images outside image directory", str(outside))
+
if extensions:
- ext_str = ", ".join(f"{ext} ({count})" for ext, count in sorted(extensions.items()))
+ ext_str = ", ".join(
+ f"{ext} ({count})" for ext, count in sorted(extensions.items())
+ )
vision_table.add_row("Image formats", ext_str)
+
console.print(vision_table)
diff --git a/tests/test_vision.py b/tests/test_vision.py
index 7d880f43..ae038a79 100644
--- a/tests/test_vision.py
+++ b/tests/test_vision.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import json
+import re
import tempfile
from pathlib import Path
from unittest.mock import MagicMock, patch
@@ -533,6 +534,62 @@ class TestInitVisionTemplate:
class TestDataInspectVision:
"""Test data inspect command with vision datasets."""
+ @staticmethod
+ def _images_found(output: str) -> int:
+ """Extract the Images found on disk value from Rich output."""
+ ansi_re = re.compile(r"\x1b\[[0-9;]*m")
+ plain = " ".join(ansi_re.sub("", output).split())
+ match = re.search(r"Images found on disk\W+(\d+)", plain)
+ assert match, plain
+ return int(match.group(1))
+
+ @staticmethod
+ def _inspect(*args) -> str:
+ """Run data inspect and return its output."""
+ from typer.testing import CliRunner
+
+ from soup_cli.cli import app
+
+ result = CliRunner().invoke(
+ app, ["data", "inspect", *args, "--rows", "0"]
+ )
+ assert result.exit_code == 0, (
+ result.output,
+ repr(result.exception),
+ )
+ return result.output
+
+ @staticmethod
+ def _vision_layout(
+ root: Path,
+ images=("imgs/a.png", "imgs/b.png"),
+ ) -> tuple[Path, Path]:
+ """Create a vision dataset and its referenced images."""
+ data_dir = root / "proj" / "data"
+ (data_dir / "imgs").mkdir(parents=True)
+
+ for name in ("a.png", "b.png"):
+ (data_dir / "imgs" / name).touch()
+
+ rows = [
+ {
+ "image": img,
+ "conversations": [
+ {"from": "human", "value": "<image> hi"},
+ {"from": "gpt", "value": "a picture"},
+ ],
+ }
+ for img in images
+ ]
+
+ dataset = data_dir / "train.jsonl"
+ dataset.write_text(
+ "".join(json.dumps(row) + "\n" for row in rows),
+ encoding="utf-8",
+ )
+
+ return data_dir, dataset
+
def test_show_vision_stats_with_images(self):
"""_show_vision_stats should detect image fields and show stats."""
from io import StringIO
@@ -549,11 +606,12 @@ class TestDataInspectVision:
output = StringIO()
with patch("soup_cli.commands.data.console", Console(file=output)):
- _show_vision_stats(data)
+ _show_vision_stats(data, Path("."))
text = output.getvalue()
assert "Vision Stats" in text
- assert "2" in text # 2 images referenced
+ assert "Images referenced" in text
+ assert "2" in text
def test_show_vision_stats_no_images(self):
"""_show_vision_stats should not print anything for non-vision datasets."""
@@ -567,7 +625,7 @@ class TestDataInspectVision:
output = StringIO()
with patch("soup_cli.commands.data.console", Console(file=output)):
- _show_vision_stats(data)
+ _show_vision_stats(data, Path("."))
text = output.getvalue()
assert "Vision" not in text
@@ -576,8 +634,7 @@ class TestDataInspectVision:
"""_show_vision_stats should handle empty data gracefully."""
from soup_cli.commands.data import _show_vision_stats
- # Should not raise
- _show_vision_stats([])
+ _show_vision_stats([], Path("."))
def test_show_vision_stats_image_extensions(self):
"""_show_vision_stats should report image file extensions."""
@@ -595,12 +652,73 @@ class TestDataInspectVision:
output = StringIO()
with patch("soup_cli.commands.data.console", Console(file=output)):
- _show_vision_stats(data)
+ _show_vision_stats(data, Path("."))
text = output.getvalue()
assert ".jpg" in text
assert ".png" in text
+ def test_inspect_counts_images_next_to_the_data_from_any_cwd(
+ self, tmp_path, monkeypatch
+ ):
+ """Inspect should resolve images relative to the dataset directory."""
+ data_dir, _ = self._vision_layout(tmp_path)
+
+ monkeypatch.chdir(tmp_path / "proj")
+ assert self._images_found(self._inspect("data/train.jsonl")) == 2
+
+ # Reverse case from #1598: the files exist under the cwd,
+ # not next to the data.
+ for name in ("a.png", "b.png"):
+ (data_dir / "imgs" / name).unlink()
+
+ elsewhere = tmp_path / "proj" / "elsewhere"
+ (elsewhere / "imgs").mkdir(parents=True)
+
+ for name in ("a.png", "b.png"):
+ (elsewhere / "imgs" / name).touch()
+
+ monkeypatch.chdir(elsewhere)
+ assert self._images_found(self._inspect("../data/train.jsonl")) == 0
+
+ def test_inspect_image_dir_option(self, tmp_path, monkeypatch):
+ """Inspect should use --image-dir when it is provided."""
+ data_dir, dataset = self._vision_layout(tmp_path)
+
+ pics = tmp_path / "pics"
+ (pics / "imgs").mkdir(parents=True)
+
+ for name in ("a.png", "b.png"):
+ (data_dir / "imgs" / name).replace(pics / "imgs" / name)
+
+ monkeypatch.chdir(tmp_path)
+
+ assert self._images_found(self._inspect(str(dataset))) == 0
+ assert (
+ self._images_found(
+ self._inspect(str(dataset), "--image-dir", str(pics))
+ )
+ == 2
+ )
+
+ def test_inspect_does_not_count_a_path_training_refuses(
+ self, tmp_path, monkeypatch
+ ):
+ """Inspect should reject image paths outside the image directory."""
+ self._vision_layout(
+ tmp_path,
+ images=("imgs/a.png", "../outside.png"),
+ )
+
+ (tmp_path / "proj" / "outside.png").touch()
+
+ monkeypatch.chdir(tmp_path)
+
+ output = self._inspect(str(tmp_path / "proj" / "data" / "train.jsonl"))
+
+ assert self._images_found(output) == 1
+ plain = " ".join(re.sub(r"\x1b\[[0-9;]*m", "", output).split())
+ assert re.search(r"Images outside image directory\W+1\b", plain), plain
# ─── Doctor Tests ──────────────────────────────────────────────────────────