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(trainer): accept PIL images and image structs in vision SFT (#1597) (#1601)
Nariman Abdikarimb4afe5d625ae
diff --git a/changelog.d/0.75.1/1601.fixed.md b/changelog.d/0.75.1/1601.fixed.mdnew file mode 100644index 00000000..edc708cc--- /dev/null+++ b/changelog.d/0.75.1/1601.fixed.md@@ -0,0 +1 @@+- Vision SFT accepts decoded PIL images from Hugging Face Hub datasets and Parquet image structs ({"bytes", "path"}) without crashing. Path structs follow the same directory resolution and path containment rules as file path strings (#1597 by @Nari-Ab in #1601).diff --git a/docs/training.md b/docs/training.mdindex 61a30e9d..d7174c13 100644--- a/docs/training.md+++ b/docs/training.md@@ -1069,6 +1069,9 @@ A relative `image` path resolves against `data.image_dir`, or against the data fdirectory when it is unset. A Hub dataset or a remote URI has no data file directory, so set`data.image_dir` when its rows hold image paths; see[Data Pipeline Pro](data.md#data-pipeline-pro).+Decoded in-memory PIL images (such as from a Hugging Face Hub `Image()` column) and Parquet+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.diff --git a/src/soup_cli/data/loader.py b/src/soup_cli/data/loader.pyindex 6a08df0d..8bb3f4b0 100644--- a/src/soup_cli/data/loader.py+++ b/src/soup_cli/data/loader.py@@ -1019,7 +1019,8 @@ def _load_interleaved_streaming_datasets(def _validate_vision_images(data: list[dict], image_dir: Path) -> list[dict]:"""Validate and resolve image paths in vision dataset rows.- Each row must have an 'image' key with a filename or path. Resolves+ Each row must have an 'image' key with a filename or path, a decoded PIL+ image, or a datasets Image struct ({'bytes': ..., 'path': ...}). Resolvesrelative paths against image_dir and rejects path traversal — a craftedllava/sharegpt4v row like ``{"image": "/etc/passwd"}`` must not be handedto ``PIL.Image.open``. Mirrors :func:`_validate_audio_files` (the sibling@@ -1125,6 +1126,36 @@ def _resolve_media_entries(entries.append(None)continueif not isinstance(value, str):+ if isinstance(value, dict):+ # Struct with embedded bytes passes through unchanged+ if value.get("bytes"):+ entries.append(row)+ continue+ path_val = value.get("path")+ if path_val:+ if isinstance(path_val, (bytes, os.PathLike)):+ outside += 1+ entries.append(None)+ continue+ if not isinstance(path_val, str):+ missing += 1+ entries.append(None)+ continue+ if media_dir is None:+ raise _media_dir_required(source, key, plural=plural)+ if "\x00" in path_val or is_network_or_device_path(path_val):+ outside += 1+ entries.append(None)+ continue+ media_path = Path(path_val)+ if not media_path.is_absolute():+ media_path = media_dir / media_path+ if not is_under(media_path, media_dir):+ outside += 1+ entries.append(None)+ continue+ entries.append({**row, key: {**value, "path": str(media_path.resolve())}})+ continueentries.append(row)continueif media_dir is None:diff --git a/src/soup_cli/trainer/sft.py b/src/soup_cli/trainer/sft.pyindex 6b41a5b1..c28667bc 100644--- a/src/soup_cli/trainer/sft.py+++ b/src/soup_cli/trainer/sft.py@@ -2019,27 +2019,60 @@ class SFTTrainerWrapper(StreamingSetupMixin):def _prepare_vision_dataset(self, dataset: dict):"""Keep messages + PIL images raw for processor-aware collation."""+ import io+ import os+from datasets import Dataset+ from PIL import Image as PILImage++ def _to_rgb_image(image_raw):+ if image_raw is None or image_raw == "":+ return None+ if isinstance(image_raw, PILImage.Image):+ try:+ return image_raw.convert("RGB")+ except (OSError, ValueError):+ return None+ if isinstance(image_raw, dict):+ img_bytes = image_raw.get("bytes")+ if img_bytes:+ try:+ return PILImage.open(io.BytesIO(img_bytes)).convert("RGB")+ except (OSError, ValueError):+ return None+ img_path = image_raw.get("path")+ if img_path:+ try:+ if isinstance(img_path, (str, bytes, os.PathLike)):+ require_regular_file(os.fsdecode(img_path))+ return PILImage.open(img_path).convert("RGB")+ except (FileNotFoundError, OSError, ValueError):+ return None+ return None+ if isinstance(image_raw, (str, bytes, os.PathLike)):+ try:+ require_regular_file(os.fsdecode(image_raw))+ return PILImage.open(image_raw).convert("RGB")+ except (FileNotFoundError, OSError, ValueError):+ return None+ return Nonefrom soup_cli.utils.paths import require_regular_filedef load_and_format_vision(example):- from PIL import Image as PILImage-- image_path = example.get("image", "")- image = None- if image_path:- try:- # Open a file name only when it is a regular file: a FIFO- # or a device would stall the reader.- if isinstance(image_path, (str, bytes, os.PathLike)):- require_regular_file(os.fsdecode(image_path))- image = PILImage.open(image_path).convert("RGB")- except (FileNotFoundError, OSError):- console.print(- "[yellow]Warning: cannot open image: "- f"{for_terminal(image_path)}[/]"- )+ image_raw = example.get("image")+ image = _to_rgb_image(image_raw)+ if image is None and image_raw:+ if isinstance(image_raw, (str, bytes, os.PathLike)):+ err_label = str(image_raw)+ elif isinstance(image_raw, dict) and image_raw.get("path"):+ err_label = str(image_raw["path"])+ else:+ err_label = type(image_raw).__name__+ console.print(+ "[yellow]Warning: cannot open image: "+ f"{for_terminal(err_label)}[/]"+ )result = {"images": []}if image is not None:diff --git a/tests/test_issue1597_vision_image_objects.py b/tests/test_issue1597_vision_image_objects.pynew file mode 100644index 00000000..927c4af4--- /dev/null+++ b/tests/test_issue1597_vision_image_objects.py@@ -0,0 +1,216 @@+"""Tests for Issue #1597: Vision SFT on Hub/Parquet datasets with decoded Image or struct."""++import io+import tempfile+from pathlib import Path++import pytest+from PIL import Image+from rich.console import Console++from soup_cli.config.schema import DataConfig+from soup_cli.data.loader import (+ _resolve_media_entries,+ _validate_vision_images,+ load_dataset,+)+from soup_cli.trainer.sft import SFTTrainerWrapper+++def test_prepare_vision_dataset_with_pil_images():+ """Hub datasets return in-memory PIL Images, which should be accepted and converted to RGB."""+ img1 = Image.new("RGBA", (16, 16), (255, 0, 0, 128))+ img2 = Image.new("RGB", (16, 16), "blue")+ dataset = {+ "train": [+ {"image": img1, "messages": [{"role": "user", "content": "hi"}]},+ {"image": img2, "messages": [{"role": "user", "content": "hello"}]},+ ],+ "val": [+ {"image": img1, "messages": [{"role": "user", "content": "val"}]},+ ],+ }++ wrapper = SFTTrainerWrapper.__new__(SFTTrainerWrapper)+ train_ds, val_ds = wrapper._prepare_vision_dataset(dataset)++ assert len(train_ds) == 2+ assert len(train_ds[0]["images"]) == 1+ assert train_ds[0]["images"][0].mode == "RGB"+ assert len(train_ds[1]["images"]) == 1+ assert train_ds[1]["images"][0].mode == "RGB"++ assert len(val_ds) == 1+ assert len(val_ds[0]["images"]) == 1+ assert val_ds[0]["images"][0].mode == "RGB"+++def test_prepare_vision_dataset_with_image_bytes_struct():+ """Parquet datasets can store images as dicts with raw bytes."""+ buf = io.BytesIO()+ Image.new("RGB", (10, 10), "green").save(buf, format="PNG")+ png_bytes = buf.getvalue()++ dataset = {+ "train": [+ {+ "image": {"bytes": png_bytes, "path": "test.png"},+ "messages": [{"role": "user", "content": "hi"}],+ },+ ]+ }++ wrapper = SFTTrainerWrapper.__new__(SFTTrainerWrapper)+ train_ds, val_ds = wrapper._prepare_vision_dataset(dataset)++ assert len(train_ds) == 1+ assert len(train_ds[0]["images"]) == 1+ assert train_ds[0]["images"][0].size == (10, 10)+ assert train_ds[0]["images"][0].mode == "RGB"+ assert val_ds is None+++def test_validate_vision_images_with_pil_and_structs():+ """Validate that _validate_vision_images accepts in-memory images and enforces traversal."""+ with tempfile.TemporaryDirectory() as tmpdir:+ base_dir = Path(tmpdir)+ local_img = base_dir / "valid.png"+ Image.new("RGB", (8, 8), "white").save(local_img)++ pil_img = Image.new("RGB", (8, 8), "red")+ data = [+ {"image": pil_img, "id": "1"},+ {"image": {"bytes": b"fakebytes", "path": None}, "id": "2"},+ {"image": {"bytes": None, "path": "valid.png"}, "id": "3"},+ {"image": {"bytes": None, "path": "../outside.png"}, "id": "4"},+ {"image": str(local_img), "id": "5"},+ {"image": "/etc/passwd", "id": "6"},+ ]++ validated = _validate_vision_images(data, base_dir)+ ids = [row["id"] for row in validated]+ # Rows 1 (PIL), 2 (bytes), 3 (valid struct path), 5 (valid path str) kept+ # Rows 4 (traversal struct) and 6 (traversal str) rejected+ assert ids == ["1", "2", "3", "5"]+++def test_load_parquet_with_image_features():+ """Loading a parquet dataset containing datasets.Image column should work end-to-end."""+ import datasets++ with tempfile.TemporaryDirectory() as tmpdir:+ parquet_path = Path(tmpdir) / "train.parquet"+ img = Image.new("RGB", (8, 8), "red")+ turns = [{"from": "human", "value": "<image>\nColour?"}, {"from": "gpt", "value": "Red."}]++ ds = datasets.Dataset.from_dict(+ {"image": [img], "conversations": [turns]},+ features=datasets.Features({+ "image": datasets.Image(),+ "conversations": [+ {"from": datasets.Value("string"), "value": datasets.Value("string")}+ ],+ }),+ )+ ds.to_parquet(str(parquet_path))++ loaded = load_dataset(DataConfig(train=str(parquet_path), format="llava", val_split=0.0))+ assert len(loaded["train"]) == 1+ assert "image" in loaded["train"][0]++ # And feeding to _prepare_vision_dataset should produce images+ wrapper = SFTTrainerWrapper.__new__(SFTTrainerWrapper)+ train_ds, _ = wrapper._prepare_vision_dataset(loaded)+ assert len(train_ds) == 1+ assert len(train_ds[0]["images"]) == 1+++def test_validate_vision_images_resolves_struct_path(tmp_path):+ Image.new("RGB", (8, 8), "white").save(tmp_path / "valid.png")+ rows = [{"image": {"bytes": None, "path": "valid.png"}}]+ validated = _validate_vision_images(rows, tmp_path)+ assert validated[0]["image"]["path"] == str((tmp_path / "valid.png").resolve())+++def test_prepare_vision_dataset_opens_path_only_struct(tmp_path):+ img = tmp_path / "pic.png"+ Image.new("RGB", (6, 4), "blue").save(img)+ dataset = {"train": [{"image": {"bytes": None, "path": str(img)},+ "messages": [{"role": "user", "content": "hi"}]}]}+ wrapper = SFTTrainerWrapper.__new__(SFTTrainerWrapper)+ train_ds, _ = wrapper._prepare_vision_dataset(dataset)+ assert [im.size for im in train_ds[0]["images"]] == [(6, 4)]+++def test_struct_path_refusals_count_as_outside(tmp_path):+ rows = [+ {"image": {"bytes": None, "path": "bad\x00name.png"}},+ {"image": {"bytes": None, "path": tmp_path / "valid.png"}},+ ]+ entries, missing, outside = _resolve_media_entries(rows, "image", tmp_path)+ assert entries == [None, None]+ assert (missing, outside) == (0, 2)+++def test_struct_path_without_image_dir_names_the_setting():+ rows = [{"image": {"bytes": None, "path": "pic.png"}}]+ with pytest.raises(ValueError, match="data.image_dir"):+ _resolve_media_entries(rows, "image", None, source="Hub dataset 'org/x'")+++def test_struct_with_bytes_is_kept_whatever_its_path(tmp_path):+ elsewhere = str(tmp_path.parent / "elsewhere" / "pic.png")+ rows = [{"image": {"bytes": b"\x89PNG", "path": elsewhere}}]+ entries, missing, outside = _resolve_media_entries(rows, "image", tmp_path)+ assert entries == rows+ assert (missing, outside) == (0, 0)+++def test_prepare_vision_dataset_never_opens_a_non_regular_struct_path(tmp_path, monkeypatch):+ from soup_cli.trainer import sft++ monkeypatch.setattr(sft, "console", Console(file=io.StringIO(), width=400))+ opened = []+ real_open = Image.open++ def spy(fp, *args, **kwargs):+ opened.append(fp)+ return real_open(fp, *args, **kwargs)++ rows = [+ {+ "image": {"bytes": None, "path": str(tmp_path)},+ "messages": [{"role": "user", "content": "hi"}],+ }+ ]+ wrapper = SFTTrainerWrapper.__new__(SFTTrainerWrapper)+ with monkeypatch.context() as patched:+ patched.setattr(Image, "open", spy)+ train_ds, _ = wrapper._prepare_vision_dataset({"train": rows})+ assert opened == []+ assert [len(images) for images in train_ds["images"]] == [0]+++def test_struct_with_undecodable_bytes_never_opens_its_path(tmp_path, monkeypatch):+ from soup_cli.trainer import sft++ monkeypatch.setattr(sft, "console", Console(file=io.StringIO(), width=400))+ media_dir = tmp_path / "media"+ media_dir.mkdir()+ outside = tmp_path / "outside.png"+ Image.new("RGB", (3, 9), "red").save(outside)+ rows = [+ {+ "image": {"bytes": b"not an image", "path": str(outside)},+ "messages": [{"role": "user", "content": "hi"}],+ }+ ]++ kept = _validate_vision_images(rows, media_dir)+ assert len(kept) == 1 # kept for its bytes; its path is never checked+ wrapper = SFTTrainerWrapper.__new__(SFTTrainerWrapper)+ train_ds, _ = wrapper._prepare_vision_dataset({"train": kept})+ # The path is outside data.image_dir: it must not be read instead.+ assert [len(images) for images in train_ds["images"]] == [0]++diff --git a/tests/test_loader_media_paths_parity.py b/tests/test_loader_media_paths_parity.pyindex b54db939..83932cbd 100644--- a/tests/test_loader_media_paths_parity.py+++ b/tests/test_loader_media_paths_parity.py@@ -1393,18 +1393,19 @@ def test_vision_trainer_checks_a_bytes_path_too(tmp_path, monkeypatch):assert _plain(out.getvalue()).count("Warning: cannot open image:") == len(refused)-def test_vision_trainer_hands_a_decoded_image_to_the_reader(tmp_path, monkeypatch):+def test_vision_trainer_converts_a_decoded_image_without_the_reader(tmp_path, monkeypatch):pil_image = pytest.importorskip("PIL.Image")wrapper, _ = _vision_wrapper(monkeypatch)- rows = [{"messages": _VISION_MESSAGES, "image": pil_image.new("RGB", (4, 4), "blue")}]+ rows = [{"messages": _VISION_MESSAGES, "image": pil_image.new("RGBA", (4, 4), "blue")}]opened: list = []with monkeypatch.context() as patched:patched.setattr(pil_image, "open", _open_spy(pil_image, opened))train_ds, _ = wrapper._prepare_vision_dataset({"train": rows})- assert [isinstance(value, pil_image.Image) for value in opened] == [True]- assert [len(images) for images in train_ds["images"]] == [1]+ # A decoded image is already an image: PIL.Image.open cannot read one (#1597).+ assert opened == []+ assert [[image.mode for image in images] for images in train_ds["images"]] == [["RGB"]]_AUDIO_MESSAGES = [