Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: train audio VLMs on the images in a mixed audio + image dataset (#16124)

Leo Borcherding50f09c8e378b
diff --git a/studio/backend/core/training/trainer.py b/studio/backend/core/training/trainer.py
index ae16e00aeab..bda6658aaee 100644
--- a/studio/backend/core/training/trainer.py
+++ b/studio/backend/core/training/trainer.py
@@ -2342,14 +2342,101 @@ class UnslothTrainer:
)
return result_dataset
+ @staticmethod
+ def _resolve_audio_vlm_image_column(
+ dataset,
+ custom_format_mapping,
+ audio_col,
+ text_col = None,
+ speaker_col = None,
+ ):
+ cols = dataset.column_names
+ reserved = {audio_col, text_col}
+ reserved.update(
+ col for col, role in (custom_format_mapping or {}).items() if role and role != "image"
+ )
+ for col, role in (custom_format_mapping or {}).items():
+ if role == "image" and col in cols and col not in reserved:
+ return col
+ from hub.utils.dataset_format import (
+ _first_row,
+ _is_image_list_item,
+ _is_image_value,
+ detect_multimodal_dataset,
+ )
+
+ from datasets import Image
+
+ def image_typed(col):
+ feature = (getattr(dataset, "features", None) or {}).get(col)
+ inner = feature[0] if isinstance(feature, list) and feature else feature
+ return isinstance(getattr(inner, "feature", inner), Image)
+
+ if speaker_col and not image_typed(speaker_col):
+ reserved.add(speaker_col)
+
+ def image_list(value):
+ if not isinstance(value, list):
+ return False
+ items = [
+ item
+ for item in value
+ if item is not None and not (isinstance(item, str) and not item)
+ ]
+ return bool(items) and all(map(_is_image_list_item, items))
+
+ sample = _first_row(dataset) or {}
+
+ def empty(value):
+ # Not `in (None, "", [])`: that compares a pixel ndarray elementwise and raises.
+ return (
+ value is None
+ or (isinstance(value, str) and not value)
+ or (
+ isinstance(value, list)
+ and all(item is None or (isinstance(item, str) and not item) for item in value)
+ )
+ )
+
+ ordered = list(
+ dict.fromkeys(detect_multimodal_dataset(dataset)["multimodal_columns"] + cols)
+ )
+ ordered = [col for col in ordered if col not in reserved]
+ typed = {col: image_typed(col) for col in ordered}
+ values = {col: sample.get(col) for col in ordered}
+ first_candidate = next(
+ (
+ i
+ for i, col in enumerate(ordered)
+ if typed[col] or _is_image_value(values[col]) or image_list(values[col])
+ ),
+ len(ordered),
+ )
+ unresolved = {
+ col for col in ordered[:first_candidate] if not typed[col] and empty(values[col])
+ }
+ if unresolved:
+ for i, row in enumerate(dataset):
+ if i >= 100 or not unresolved:
+ break
+ for col in tuple(unresolved):
+ if not empty(row.get(col)):
+ values[col] = row[col]
+ unresolved.remove(col)
+ return next(
+ (
+ col
+ for col in ordered
+ if typed[col] or _is_image_value(values[col]) or image_list(values[col])
+ ),
+ None,
+ )
+
def _format_audio_vlm_dataset(
self,
dataset,
custom_format_mapping = None,
):
- """Format dataset as audio chat messages for multimodal models (e.g. Gemma 3N). Expects
- columns audio (Audio), text (str). Produces a messages column with system/user/assistant
- chat format."""
from datasets import Audio
resolved = self._resolve_audio_columns(dataset, custom_format_mapping)
@@ -2361,14 +2448,82 @@ class UnslothTrainer:
)
self._audio_vlm_audio_col = audio_col
+ image_col = self._resolve_audio_vlm_image_column(
+ dataset, custom_format_mapping, audio_col, text_col, resolved["speaker_col"]
+ )
+ self._audio_vlm_image_col = image_col
dataset = dataset.cast_column(audio_col, Audio(sampling_rate = 16000))
+ if image_col:
+ from datasets import Image, Sequence
+
+ feature = dataset.features.get(image_col)
+ inner = feature[0] if isinstance(feature, list) else getattr(feature, "feature", None)
+
+ pixel_feature, dimensions = feature, 0
+ while getattr(pixel_feature, "feature", None) is not None:
+ pixel_feature = pixel_feature.feature
+ dimensions += 1
+ if dimensions <= 1 and getattr(pixel_feature, "dtype", "") in (
+ "string",
+ "large_string",
+ ):
+
+ def normalize_paths(values):
+ return {
+ image_col: [
+ [None if item == "" else item for item in value]
+ if isinstance(value, list)
+ else None
+ if value == ""
+ else value
+ for value in values
+ ]
+ }
+
+ dataset = dataset.map(normalize_paths, batched = True, input_columns = image_col)
+ if dimensions in (2, 3) and getattr(pixel_feature, "dtype", "").startswith(
+ ("int", "uint", "float")
+ ):
+ from itertools import islice
+
+ import numpy as np
+
+ value = next(
+ (row[image_col] for row in islice(dataset, 100) if row[image_col] is not None),
+ None,
+ )
+ shape = np.asarray(value).shape if value is not None else ()
+ if value is None or len(shape) == 2 or (len(shape) == 3 and shape[-1] in (1, 3, 4)):
+ inner = None
+
+ # Image(decode = False) yields {"path", "bytes"} dicts the processor rejects.
+ def decodes(f):
+ return isinstance(f, Image) and f.decode
+
+ if inner is not None:
+ if not decodes(inner):
+ dataset = dataset.cast_column(image_col, Sequence(Image()))
+ elif not decodes(feature):
+ dataset = dataset.cast_column(image_col, Image())
+ logger.info(f"Audio VLM dataset also has images in '{image_col}'; training on both\n")
def format_messages(samples):
formatted = {"messages": []}
for idx in range(len(samples[audio_col])):
audio = samples[audio_col][idx]["array"]
label = str(samples[text_col][idx])
+ user_content = [
+ {"type": "audio", "audio": audio},
+ {"type": "text", "text": "Please transcribe this audio."},
+ ]
+ if image_col:
+ row_images = samples[image_col][idx]
+ if isinstance(row_images, list):
+ n_images = sum(1 for i in row_images if i is not None)
+ else:
+ n_images = 0 if row_images is None else 1
+ user_content[:0] = [{"type": "image"} for _ in range(n_images)]
message = [
{
"role": "system",
@@ -2379,13 +2534,7 @@ class UnslothTrainer:
}
],
},
- {
- "role": "user",
- "content": [
- {"type": "audio", "audio": audio},
- {"type": "text", "text": "Please transcribe this audio."},
- ],
- },
+ {"role": "user", "content": user_content},
{"role": "assistant", "content": [{"type": "text", "text": label}]},
]
formatted["messages"].append(message)
@@ -2970,15 +3119,21 @@ class UnslothTrainer:
return None
def _format_audio_vlm_eval_split(self, eval_dataset, custom_format_mapping):
- """Format the audio VLM eval split, dropping it if it resolves a different audio
- column: audio_vlm_collate_fn reads the one recorded name for BOTH splits."""
if eval_dataset is None:
return None
train_audio_col = getattr(self, "_audio_vlm_audio_col", None)
+ train_image_col = getattr(self, "_audio_vlm_image_col", None)
+ eval_mapping = custom_format_mapping
+ image_feature = eval_dataset.features.get(train_image_col)
+ while getattr(image_feature, "feature", None) is not None:
+ image_feature = image_feature.feature
+ if train_image_col and getattr(image_feature, "dtype", None) == "null":
+ eval_mapping = {train_image_col: "image", **(custom_format_mapping or {})}
formatted = self._preprocess_audio_eval_split(
- eval_dataset, self._format_audio_vlm_dataset, custom_format_mapping
+ eval_dataset, self._format_audio_vlm_dataset, eval_mapping
)
eval_audio_col = getattr(self, "_audio_vlm_audio_col", None)
+ eval_image_col = getattr(self, "_audio_vlm_image_col", None)
if formatted is not None and eval_audio_col != train_audio_col:
self._record_warning(
f"The eval dataset stores audio in '{eval_audio_col}' but the training dataset "
@@ -2986,7 +3141,15 @@ class UnslothTrainer:
"same audio column name."
)
formatted = None
+ elif formatted is not None and eval_image_col != train_image_col:
+ self._record_warning(
+ f"The eval dataset's image column ('{eval_image_col}') does not match the training "
+ f"dataset's ('{train_image_col}'), so this run has no evaluation. Give both splits "
+ "the same image column."
+ )
+ formatted = None
self._audio_vlm_audio_col = train_audio_col
+ self._audio_vlm_image_col = train_image_col
return formatted
def _audio_eval_config(self, training_args):
@@ -4584,6 +4747,7 @@ class UnslothTrainer:
processor = self.tokenizer
audio_col_name = getattr(self, "_audio_vlm_audio_col", "audio")
+ image_col_name = getattr(self, "_audio_vlm_image_col", None)
if training_args.get("train_on_completions", False) and not training_args.get(
"is_cpt", False
):
@@ -4614,6 +4778,7 @@ class UnslothTrainer:
def audio_vlm_collate_fn(examples):
texts = []
audios = []
+ images = []
for example in examples:
text = processor.apply_chat_template(
example["messages"],
@@ -4622,8 +4787,25 @@ class UnslothTrainer:
).strip()
texts.append(text)
audios.append(example[audio_col_name]["array"])
+ if image_col_name:
+ row = example[image_col_name]
+ row = row if isinstance(row, list) else [row]
+ images.append(
+ [
+ i.convert("RGB") if hasattr(i, "convert") else i
+ for i in row
+ if i is not None
+ ]
+ )
- batch = processor(text = texts, audio = audios, return_tensors = "pt", padding = True)
+ image_kwargs = {"images": images} if any(images) else {}
+ batch = processor(
+ text = texts,
+ audio = audios,
+ return_tensors = "pt",
+ padding = True,
+ **image_kwargs,
+ )
labels = batch["input_ids"].clone()
labels[labels == processor.tokenizer.pad_token_id] = -100
diff --git a/studio/backend/tests/test_audio_vlm_nullable_eval_images.py b/studio/backend/tests/test_audio_vlm_nullable_eval_images.py
new file mode 100644
index 00000000000..c50cbbeaa98
--- /dev/null
+++ b/studio/backend/tests/test_audio_vlm_nullable_eval_images.py
@@ -0,0 +1,75 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import pytest
+
+from .test_trainer_audio_vlm_image_and_audio import (
+ _NoAudioCast,
+ _dataset,
+ audio_vlm_trainer, # noqa: F401
+ datasets,
+)
+
+
[email protected]("image_col", ["image", "photo"])
[email protected]("empty_value", [None, []], ids = ["null", "empty_list"])
+def test_all_null_eval_images_keep_the_shared_image_column(
+ audio_vlm_trainer, image_col, empty_value
+):
+ mapping = (
+ {"audio": "audio", "text": "text", image_col: "image"} if image_col == "photo" else None
+ )
+ audio_vlm_trainer._format_audio_vlm_dataset(_dataset([image_col]), mapping)
+ evaluation = _NoAudioCast(
+ datasets.Dataset.from_dict(
+ {
+ "audio": [{"array": [0.0] * 160, "sampling_rate": 16000}] * 2,
+ "text": ["one", "two"],
+ image_col: [empty_value, empty_value],
+ }
+ )
+ )
+
+ formatted = audio_vlm_trainer._format_audio_vlm_eval_split(evaluation, mapping)
+
+ assert formatted is not None
+ assert audio_vlm_trainer._audio_vlm_image_col == image_col
+ assert audio_vlm_trainer._audio_vlm_audio_col == "audio"
+ assert list(formatted[image_col]) == [empty_value, empty_value]
+ for row in formatted:
+ user = next(message for message in row["messages"] if message["role"] == "user")
+ assert [part["type"] for part in user["content"]] == ["audio", "text"]
+ if mapping is not None:
+ assert mapping == {"audio": "audio", "text": "text", image_col: "image"}
+
+
+def test_a_different_eval_image_column_still_disables_evaluation(audio_vlm_trainer, monkeypatch):
+ audio_vlm_trainer._format_audio_vlm_dataset(_dataset(["image"]))
+ warnings = []
+ monkeypatch.setattr(audio_vlm_trainer, "_record_warning", warnings.append)
+
+ formatted = audio_vlm_trainer._format_audio_vlm_eval_split(_dataset(["photo"]), None)
+
+ assert formatted is None
+ assert audio_vlm_trainer._audio_vlm_image_col == "image"
+ assert audio_vlm_trainer._audio_vlm_audio_col == "audio"
+ assert any("image column" in warning for warning in warnings)
+
+
+def test_non_image_eval_values_do_not_gain_an_image_mapping(audio_vlm_trainer, monkeypatch):
+ audio_vlm_trainer._format_audio_vlm_dataset(_dataset(["image"]))
+ evaluation = _NoAudioCast(
+ datasets.Dataset.from_dict(
+ {
+ "audio": [{"array": [0.0] * 160, "sampling_rate": 16000}] * 2,
+ "text": ["one", "two"],
+ "image": ["metadata", "metadata"],
+ }
+ )
+ )
+ warnings = []
+ monkeypatch.setattr(audio_vlm_trainer, "_record_warning", warnings.append)
+
+ assert audio_vlm_trainer._format_audio_vlm_eval_split(evaluation, None) is None
+ assert any("image column" in warning for warning in warnings)
+ assert not any("could not be prepared" in warning for warning in warnings)
diff --git a/studio/backend/tests/test_trainer_audio_vlm_image_and_audio.py b/studio/backend/tests/test_trainer_audio_vlm_image_and_audio.py
new file mode 100644
index 00000000000..0dba918e954
--- /dev/null
+++ b/studio/backend/tests/test_trainer_audio_vlm_image_and_audio.py
@@ -0,0 +1,504 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from __future__ import annotations
+
+import logging
+import sys
+import textwrap
+import types
+from pathlib import Path
+
+_BACKEND = Path(__file__).resolve().parent.parent
+if str(_BACKEND) not in sys.path:
+ sys.path.insert(0, str(_BACKEND))
+
+import importlib # noqa: E402
+from unittest.mock import MagicMock # noqa: E402
+
+import pytest # noqa: E402
+
+datasets = pytest.importorskip("datasets")
+PIL_Image = pytest.importorskip("PIL.Image")
+
+_STUBBED: list[str] = []
+
+
+def _stub_if_missing(name, attrs):
+ if name in sys.modules:
+ return
+ try:
+ importlib.import_module(name)
+ return
+ except Exception: # noqa: BLE001 - stub unusable imports
+ pass
+ _STUBBED.append(name)
+ mod = types.ModuleType(name)
+ mod.__spec__ = None
+ for attr in attrs:
+ setattr(mod, attr, MagicMock())
+ sys.modules[name] = mod
+ parent, _, child = name.rpartition(".")
+ if parent and parent in sys.modules:
+ setattr(sys.modules[parent], child, mod)
+
+
+_stub_if_missing("unsloth", ("FastLanguageModel", "FastVisionModel", "is_bfloat16_supported"))
+_stub_if_missing("unsloth.chat_templates", ("get_chat_template",))
+_stub_if_missing("trl", ("SFTTrainer", "SFTConfig"))
+
+from core.training import trainer as tmod # noqa: E402
+
+for _name in reversed(_STUBBED):
+ sys.modules.pop(_name, None)
+
+
+class _NoAudioCast:
+ """A real Dataset whose Audio cast is a no-op: decoding needs torchcodec, absent on CPU runners."""
+
+ def __init__(self, ds):
+ self._ds = ds
+
+ def cast_column(self, column, feature):
+ if isinstance(feature, datasets.Audio):
+ return self
+ return _NoAudioCast(self._ds.cast_column(column, feature))
+
+ def map(self, fn, **kwargs):
+ kwargs.pop("num_proc", None)
+ return _NoAudioCast(self._ds.map(fn, **kwargs))
+
+ def __getattr__(self, name):
+ return getattr(self._ds, name)
+
+ def __iter__(self):
+ return iter(self._ds)
+
+ def __len__(self):
+ return len(self._ds)
+
+ def __getitem__(self, idx):
+ return self._ds[idx]
+
+
+def _dataset(columns, per_row = None):
+ image = PIL_Image.new("RGB", (8, 8), "red")
+ rows = {
+ "audio": [{"array": [0.0] * 160, "sampling_rate": 16000}] * 2,
+ "text": ["a red square", "still red"],
+ }
+ for name in columns:
+ rows[name] = [[image] * n for n in per_row] if per_row else [image, image]
+ return _NoAudioCast(datasets.Dataset.from_dict(rows))
+
+
+def audio_vlm_trainer(monkeypatch):
+ monkeypatch.setattr(tmod, "should_use_mlx_training_backend", lambda *a, **k: False)
+ t = tmod.UnslothTrainer()
+ t.model_name = "unsloth/gemma-3n-E2B-it"
+ t.is_audio_vlm = True
+ return t
+
+
+def _user_part_types(dataset):
+ user = next(m for m in dataset[0]["messages"] if m["role"] == "user")
+ return [part["type"] for part in user["content"]]
+
+
+def test_mixed_dataset_keeps_the_image_in_the_user_turn(audio_vlm_trainer):
+ formatted = audio_vlm_trainer._format_audio_vlm_dataset(_dataset(["image"]))
+
+ assert _user_part_types(formatted) == ["image", "audio", "text"]
+ assert audio_vlm_trainer._audio_vlm_image_col == "image"
+
+
+def test_audio_only_dataset_is_unchanged(audio_vlm_trainer):
+ formatted = audio_vlm_trainer._format_audio_vlm_dataset(_dataset([]))
+
+ assert getattr(audio_vlm_trainer, "_audio_vlm_image_col", None) is None
+ assert _user_part_types(formatted) == ["audio", "text"]
+
+
+def test_an_image_filename_transcript_stays_text(audio_vlm_trainer):
+ ds = _dataset([])
+ ds = _NoAudioCast(
+ ds._ds.remove_columns("text").add_column("text", ["diagram.png", "photo.jpg"])
+ )
+ formatted = audio_vlm_trainer._format_audio_vlm_dataset(ds)
+
+ assert audio_vlm_trainer._audio_vlm_image_col is None
+ assert _user_part_types(formatted) == ["audio", "text"]
+ assert formatted[0]["messages"][-1]["content"][0]["text"] == "diagram.png"
+
+
+ "column, mapping",
+ [
+ ("speaker_id", None),
+ ("speaker_tag", {"audio": "audio", "text": "text", "speaker_tag": "speaker_id"}),
+ ],
+)
+def test_an_image_filename_speaker_id_stays_text(audio_vlm_trainer, column, mapping):
+ ds = _dataset([])
+ ds = _NoAudioCast(ds._ds.add_column(column, ["voice.png", "speaker.jpg"]))
+ formatted = audio_vlm_trainer._format_audio_vlm_dataset(ds, mapping)
+
+ assert audio_vlm_trainer._audio_vlm_image_col is None
+ assert _user_part_types(formatted) == ["audio", "text"]
+ assert formatted[0][column] == "voice.png"
+
+
+def test_an_image_typed_source_column_remains_an_image(audio_vlm_trainer):
+ formatted = audio_vlm_trainer._format_audio_vlm_dataset(_dataset(["source"]))
+
+ assert audio_vlm_trainer._audio_vlm_image_col == "source"
+ assert _user_part_types(formatted) == ["image", "audio", "text"]
+
+
[email protected]("shape", [(8, 8), (8, 8, 3)])
+def test_a_mapped_pixel_array_is_one_image(audio_vlm_trainer, shape):
+ np = pytest.importorskip("numpy")
+ pixels = np.arange(np.prod(shape), dtype = np.uint8).reshape(shape)
+ rows = {
+ "audio": [{"array": [0.0] * 160, "sampling_rate": 16000}] * 2,
+ "text": ["one", "two"],
+ "photo": [pixels] * 2,
+ }
+ formatted = audio_vlm_trainer._format_audio_vlm_dataset(
+ _NoAudioCast(datasets.Dataset.from_dict(rows)), {"photo": "image"}
+ )
+
+ assert isinstance(formatted[0]["photo"], PIL_Image.Image)
+ assert formatted[0]["photo"].size == (8, 8)
+ assert np.array_equal(np.asarray(formatted[0]["photo"]), pixels)
+ assert _user_part_types(formatted) == ["image", "audio", "text"]
+
+
+def test_a_list_of_grayscale_pixel_images_stays_a_list(audio_vlm_trainer):
+ np = pytest.importorskip("numpy")
+ rows = {
+ "audio": [{"array": [0.0] * 160, "sampling_rate": 16000}] * 2,
+ "text": ["one", "two"],
+ "photo": [[np.zeros((8, 8), dtype = np.uint8)] * 2] * 2,
+ }
+ formatted = audio_vlm_trainer._format_audio_vlm_dataset(
+ _NoAudioCast(datasets.Dataset.from_dict(rows)), {"photo": "image"}
+ )
+
+ assert [image.size for image in formatted[0]["photo"]] == [(8, 8), (8, 8)]
+ assert _user_part_types(formatted) == ["image", "image", "audio", "text"]
+
+
+ "column, cells",
+ [
+ ("images", [[], ["image"]]),
+ ("attachments", [None, "image"]),
+ ("photo", [[None, "image"], ["image"]]),
+ ("photo", [[None], [None, "image"]]),
+ ],
+)
+def test_untyped_nullable_images_are_found(audio_vlm_trainer, tmp_path, column, cells):
+ path = tmp_path / "image.png"
+ PIL_Image.new("RGB", (8, 8)).save(path)
+ values = [
+ [str(path) if value == "image" else value for value in cell]
+ if isinstance(cell, list)
+ else str(path)
+ if cell == "image"
+ else cell
+ for cell in cells
+ ]
+ rows = {
+ "audio": [{"array": [0.0] * 160, "sampling_rate": 16000}] * 2,
+ "text": ["one", "two"],
+ column: values,
+ }
+ formatted = audio_vlm_trainer._format_audio_vlm_dataset(
+ _NoAudioCast(datasets.Dataset.from_dict(rows))
+ )
+
+ assert audio_vlm_trainer._audio_vlm_image_col == column
+ for row, value in zip(formatted, values):
+ user = next(message for message in row["messages"] if message["role"] == "user")
+ count = (
+ sum(item is not None for item in value)
+ if isinstance(value, list)
+ else int(value is not None)
+ )
+ assert sum(part["type"] == "image" for part in user["content"]) == count
+
+
+ "cells, counts",
+ [
+ (["", "image"], [0, 1]),
+ ([["", "image"], ["image"]], [1, 1]),
+ ([["", None], ["", "image"]], [0, 1]),
+ ],
+)
+def test_blank_optional_image_paths_are_missing(audio_vlm_trainer, tmp_path, cells, counts):
+ path = tmp_path / "image.png"
+ PIL_Image.new("RGB", (8, 8)).save(path)
+ values = [
+ [str(path) if value == "image" else value for value in cell]
+ if isinstance(cell, list)
+ else str(path)
+ if cell == "image"
+ else cell
+ for cell in cells
+ ]
+ rows = {
+ "audio": [{"array": [0.0] * 160, "sampling_rate": 16000}] * 2,
+ "text": ["one", "two"],
+ "image": values,
+ }
+ formatted = audio_vlm_trainer._format_audio_vlm_dataset(
+ _NoAudioCast(datasets.Dataset.from_dict(rows))
+ )
+
+ assert audio_vlm_trainer._audio_vlm_image_col == "image"
+ for row, expected in zip(formatted, counts):
+ user = next(message for message in row["messages"] if message["role"] == "user")
+ assert sum(part["type"] == "image" for part in user["content"]) == expected
+ images = row["image"] if isinstance(row["image"], list) else [row["image"]]
+ assert sum(isinstance(image, PIL_Image.Image) for image in images) == expected
+ assert all(image is None or isinstance(image, PIL_Image.Image) for image in images)
+
+
+def test_a_mapped_image_column_is_used(audio_vlm_trainer):
+ mapping = {"audio": "audio", "text": "text", "photo": "image"}
+ formatted = audio_vlm_trainer._format_audio_vlm_dataset(_dataset(["photo"]), mapping)
+
+ assert _user_part_types(formatted)[0] == "image"
+ assert audio_vlm_trainer._audio_vlm_image_col == "photo"
+
+
+def test_a_list_of_images_per_row_gets_one_slot_per_image(audio_vlm_trainer):
+ formatted = audio_vlm_trainer._format_audio_vlm_dataset(_dataset(["images"], per_row = [1, 2]))
+
+ assert audio_vlm_trainer._audio_vlm_image_col == "images"
+ users = [next(m for m in row["messages"] if m["role"] == "user") for row in formatted]
+ assert [[p["type"] for p in u["content"]].count("image") for u in users] == [1, 2]
+
+
+def test_a_file_name_column_of_audio_paths_is_not_taken_for_images(audio_vlm_trainer):
+ rows = {
+ "audio": [{"array": [0.0] * 160, "sampling_rate": 16000}] * 2,
+ "text": ["one", "two"],
+ "file_name": ["clips/a.wav", "clips/b.wav"],
+ }
+ formatted = audio_vlm_trainer._format_audio_vlm_dataset(
+ _NoAudioCast(datasets.Dataset.from_dict(rows))
+ )
+
+ assert getattr(audio_vlm_trainer, "_audio_vlm_image_col", None) is None
+ assert _user_part_types(formatted) == ["audio", "text"]
+
+
[email protected]("feature", ["image", "images"])
+def test_an_image_typed_column_counts_even_when_row_zero_is_empty(audio_vlm_trainer, feature):
+ image = PIL_Image.new("RGB", (8, 8), "red")
+ many = feature == "images"
+ rows = {
+ "audio": [{"array": [0.0] * 160, "sampling_rate": 16000}] * 2,
+ "text": ["one", "two"],
+ feature: [[] if many else None, [image] if many else image],
+ }
+ schema = datasets.Features(
+ {
+ "audio": {
+ "array": datasets.Sequence(datasets.Value("float32")),
+ "sampling_rate": datasets.Value("int64"),
+ },
+ "text": datasets.Value("string"),
+ feature: datasets.Sequence(datasets.Image()) if many else datasets.Image(),
+ }
+ )
+ ds = _NoAudioCast(datasets.Dataset.from_dict(rows, features = schema))
+
+ assert audio_vlm_trainer._resolve_audio_vlm_image_column(ds, None, "audio") == feature
+
+
+def _collator_block():
+ lines = (_BACKEND / "core" / "training" / "trainer.py").read_text(encoding = "utf-8").splitlines()
+ start = next(
+ i
+ for i, line in enumerate(lines)
+ if line.strip() == 'audio_col_name = getattr(self, "_audio_vlm_audio_col", "audio")'
+ )
+ end = next(
+ i
+ for i in range(start, len(lines))
+ if lines[i].strip() == "data_collator = audio_vlm_collate_fn"
+ )
+ return textwrap.dedent("\n".join(lines[start:end]))
+
+
+class _RecordingProcessor:
+ def __init__(self):
+ self.tokenizer = types.SimpleNamespace(pad_token_id = 0)
+ self.calls = []
+
+ def apply_chat_template(self, messages, tokenize, add_generation_prompt):
+ return "x"
+
+ def __call__(self, text, audio, return_tensors, padding, **kwargs):
+ import torch
+ self.calls.append(kwargs)
+ return {"input_ids": torch.ones((len(text), 2), dtype = torch.long)}
+
+
+def _collate(
+ image_col,
+ row_image = None,
+ rows = None,
+):
+ pytest.importorskip("torch")
+ processor = _RecordingProcessor()
+ namespace = {
+ "processor": processor,
+ "training_args": {},
+ "self": types.SimpleNamespace(_audio_vlm_audio_col = "audio", _audio_vlm_image_col = image_col),
+ "logger": logging.getLogger(__name__),
+ "types": types,
+ "apply_completion_masking": None,
+ "audio_response_masker": None,
+ }
+ exec(_collator_block(), namespace)
+ image = PIL_Image.new("L", (4, 4))
+ row_image = image if row_image is None else row_image
+ examples = [
+ {"messages": [], "audio": {"array": [0.0]}, "image": r}
+ for r in (rows if rows is not None else [row_image, row_image])
+ ]
+ namespace["audio_vlm_collate_fn"](examples)
+ return processor.calls[0]
+
+
+def test_collator_passes_one_rgb_image_per_example():
+ kwargs = _collate("image")
+
+ images = kwargs.get("images")
+ assert images is not None, "images never reached the processor"
+ assert [len(per_example) for per_example in images] == [1, 1]
+ assert all(per_example[0].mode == "RGB" for per_example in images)
+
+
+def test_collator_passes_every_image_of_a_list_row():
+ image = PIL_Image.new("L", (4, 4))
+ images = _collate("image", row_image = [image, image])["images"]
+
+ assert [len(per_example) for per_example in images] == [2, 2]
+ assert all(i.mode == "RGB" for per_example in images for i in per_example)
+
+
+def test_collator_without_images_does_not_pass_the_kwarg():
+ assert "images" not in _collate(None)
+
+
+def test_a_none_image_row_gets_no_slot_and_no_image(audio_vlm_trainer):
+ image = PIL_Image.new("RGB", (8, 8), "red")
+ rows = {
+ "audio": [{"array": [0.0] * 160, "sampling_rate": 16000}] * 2,
+ "text": ["one", "two"],
+ "image": [None, image],
+ }
+ schema = datasets.Features(
+ {
+ "audio": {
+ "array": datasets.Sequence(datasets.Value("float32")),
+ "sampling_rate": datasets.Value("int64"),
+ },
+ "text": datasets.Value("string"),
+ "image": datasets.Image(),
+ }
+ )
+ formatted = audio_vlm_trainer._format_audio_vlm_dataset(
+ _NoAudioCast(datasets.Dataset.from_dict(rows, features = schema))
+ )
+ users = [next(m for m in row["messages"] if m["role"] == "user") for row in formatted]
+ assert [[p["type"] for p in u["content"]].count("image") for u in users] == [0, 1]
+
+ image = PIL_Image.new("L", (4, 4))
+ assert [len(x) for x in _collate("image", rows = [None, image])["images"]] == [0, 1]
+ assert "images" not in _collate("image", rows = [None, None])
+
+
[email protected]("many", [False, True])
+def test_a_non_decoding_image_feature_is_decoded(audio_vlm_trainer, many):
+ image = PIL_Image.new("RGB", (8, 8), "red")
+ inner = datasets.Image(decode = False)
+ schema = datasets.Features(
+ {
+ "audio": {
+ "array": datasets.Sequence(datasets.Value("float32")),
+ "sampling_rate": datasets.Value("int64"),
+ },
+ "text": datasets.Value("string"),
+ "image": datasets.Sequence(inner) if many else inner,
+ }
+ )
+ rows = {
+ "audio": [{"array": [0.0] * 160, "sampling_rate": 16000}] * 2,
+ "text": ["one", "two"],
+ "image": [[image], [image, image]] if many else [image, image],
+ }
+ formatted = audio_vlm_trainer._format_audio_vlm_dataset(
+ _NoAudioCast(datasets.Dataset.from_dict(rows, features = schema))
+ )
+
+ cell = formatted[1]["image"]
+ cells = cell if many else [cell]
+ assert len(cells) == (2 if many else 1)
+ assert all(isinstance(x, PIL_Image.Image) for x in cells)
+
+
+def test_a_messages_column_with_image_parts_is_not_taken_for_images(audio_vlm_trainer):
+ image = PIL_Image.new("RGB", (8, 8), "red")
+ turn = [{"role": "user", "content": [{"type": "image", "image": image}]}]
+ ds = _NoAudioCast(
+ datasets.Dataset.from_dict(
+ {
+ "audio": [{"array": [0.0] * 160, "sampling_rate": 16000}] * 2,
+ "text": ["one", "two"],
+ "messages": [turn, turn],
+ }
+ )
+ )
+
+ assert audio_vlm_trainer._resolve_audio_vlm_image_column(ds, None, "audio") is None
+
+
+def test_an_untyped_path_column_counts_when_row_zero_is_empty(audio_vlm_trainer):
+ ds = _NoAudioCast(
+ datasets.Dataset.from_dict(
+ {
+ "audio": [{"array": [0.0] * 160, "sampling_rate": 16000}] * 3,
+ "text": ["one", "two", "three"],
+ "image": [None, None, "pics/a.png"],
+ }
+ )
+ )
+
+ assert audio_vlm_trainer._resolve_audio_vlm_image_column(ds, None, "audio") == "image"
+
+
+def test_a_pixel_array_column_does_not_break_column_resolution(audio_vlm_trainer):
+ np = pytest.importorskip("numpy")
+ rows = [
+ {"audio": {"array": np.zeros(160), "sampling_rate": 16000}, "text": t, "image": v}
+ for t, v in (("one", None), ("two", np.zeros((2, 2, 3))))
+ ]
+
+ class Rows:
+ column_names = ["audio", "text", "image"]
+ features = {}
+
+ def __iter__(self):
+ return iter(rows)
+
+ ds = Rows()
+
+ audio_vlm_trainer._resolve_audio_vlm_image_column(ds, None, "audio")