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.

Unsloth Studio: train video-capable VLMs on a dataset's video instead of dropping it (#16965)

Leo Borcherding9882ccb2611b
diff --git a/studio/backend/core/training/trainer.py b/studio/backend/core/training/trainer.py
index da0b0dd01be..b67e5a461a4 100644
--- a/studio/backend/core/training/trainer.py
+++ b/studio/backend/core/training/trainer.py
@@ -3805,6 +3805,7 @@ class UnslothTrainer:
is_vlm = self.is_vlm,
format_type = format_type,
dataset_name = dataset_source,
+ dataset_revision = dataset_revision,
custom_format_mapping = custom_format_mapping,
progress_callback = self._update_progress,
)
@@ -3843,6 +3844,7 @@ class UnslothTrainer:
is_vlm = self.is_vlm,
format_type = format_type,
dataset_name = dataset_source,
+ dataset_revision = dataset_revision,
custom_format_mapping = custom_format_mapping,
)
if not eval_info.get("success", True):
diff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.py
index 93b501df1e1..5b7edabebf7 100644
--- a/studio/backend/core/training/worker.py
+++ b/studio/backend/core/training/worker.py
@@ -2554,6 +2554,12 @@ def _resize_mlx_vlm_images(
return _resize_mlx_vlm_image(value, resize, image_layout = image_layout)
+_MLX_VIDEO_UNSUPPORTED = (
+ "Training on video is not supported on Apple Silicon (MLX) yet. "
+ "Train this dataset on an NVIDIA or AMD GPU, or drop the video column."
+)
+
+
_RESOLVE_IMAGE_COLUMN = object()
@@ -2629,6 +2635,8 @@ def _adapt_for_mlx_vlm(
if isinstance(content, list):
new_content = []
for part in content:
+ if isinstance(part, dict) and part.get("type") == "video":
+ raise ValueError(_MLX_VIDEO_UNSUPPORTED)
if isinstance(part, dict) and part.get("type") == "image":
img = part.get("image")
if img is not None:
@@ -3567,6 +3575,14 @@ def _run_mlx_training(event_queue, stop_queue, config):
eval_dataset, resize = vision_image_size, image_layout = image_layout
)
elif is_vlm:
+ from utils.datasets.format_detection import detect_video_columns, video_sample
+
+ # Before formatting: conversion would fetch every Hub clip only to be refused.
+ first_row = next(iter(dataset), None)
+ if isinstance(first_row, dict) and detect_video_columns(
+ video_sample(dataset, first_row)
+ ):
+ raise ValueError(_MLX_VIDEO_UNSUPPORTED)
_send("status", status_message = "Formatting VLM dataset...")
vlm_info = format_and_template_dataset(
dataset,
@@ -3574,6 +3590,7 @@ def _run_mlx_training(event_queue, stop_queue, config):
tokenizer = tokenizer,
is_vlm = True,
dataset_name = hf_dataset or "local",
+ dataset_revision = config.get("dataset_revision"),
custom_format_mapping = custom_format_mapping,
progress_callback = _fmt_progress,
)
@@ -3598,6 +3615,7 @@ def _run_mlx_training(event_queue, stop_queue, config):
tokenizer = tokenizer,
is_vlm = True,
dataset_name = hf_dataset or "local",
+ dataset_revision = config.get("dataset_revision"),
custom_format_mapping = custom_format_mapping,
)
if ev_info.get("success"):
diff --git a/studio/backend/hub/utils/dataset_format.py b/studio/backend/hub/utils/dataset_format.py
index 1dfc1e39127..594109a75eb 100644
--- a/studio/backend/hub/utils/dataset_format.py
+++ b/studio/backend/hub/utils/dataset_format.py
@@ -9,7 +9,10 @@ from typing import Any, Optional
from utils.datasets.cells import text_cell_check, unwrap_message_column
from utils.datasets.format_detection import (
detect_dataset_format,
+ detect_video_columns,
+ detect_video_structure,
has_message_prompt_completion,
+ video_sample,
is_plain_text_dataset,
)
from utils.datasets.pretokenized import PRETOKENIZED_FORMAT, is_pretokenized_dataset
@@ -457,6 +460,7 @@ def detect_multimodal_dataset(dataset):
if sample is None:
return {
"is_image": False,
+ "is_video": False,
"multimodal_columns": [],
"modality_types": [],
"is_audio": False,
@@ -508,6 +512,12 @@ def detect_multimodal_dataset(dataset):
modality_types.add("audio")
if audio_columns:
multimodal_columns = [col for col in multimodal_columns if col not in set(audio_columns)]
+ video_columns = detect_video_columns(video_sample(dataset, sample))
+ audio_columns = [col for col in audio_columns if col not in video_columns]
+ if video_columns:
+ multimodal_columns = [col for col in multimodal_columns if col not in video_columns]
+ multimodal_columns += video_columns
+ modality_types.add("video")
detected_text_col = None
if audio_columns:
@@ -530,6 +540,7 @@ def detect_multimodal_dataset(dataset):
break
return {
"is_image": len(multimodal_columns) > 0,
+ "is_video": bool(video_columns),
"multimodal_columns": multimodal_columns,
"modality_types": list(modality_types),
"is_audio": len(audio_columns) > 0,
@@ -550,6 +561,9 @@ def detect_vlm_dataset_structure(dataset):
"text_column": None,
"messages_column": None,
}
+ video_structure = detect_video_structure(video_sample(dataset, sample))
+ if video_structure is not None:
+ return video_structure
column_names = set(sample.keys())
is_text = text_cell_check(dataset)
if "messages" in column_names:
@@ -761,7 +775,7 @@ def check_dataset_format(dataset, is_vlm: bool = False) -> dict:
warning = None
if requires_mapping:
missing = []
- if not vlm_structure.get("image_column"):
+ if not (vlm_structure.get("image_column") or vlm_structure.get("video_column")):
missing.append("image")
if not vlm_structure.get("text_column"):
missing.append("text")
diff --git a/studio/backend/tests/test_video_dataset_training.py b/studio/backend/tests/test_video_dataset_training.py
new file mode 100644
index 00000000000..9638ae5512c
--- /dev/null
+++ b/studio/backend/tests/test_video_dataset_training.py
@@ -0,0 +1,620 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""A video column must reach the vision collator, not train as text with the clip dropped."""
+
+import pytest
+from datasets import Dataset
+
+from hub.utils.dataset_format import check_dataset_format
+from utils.datasets import format_and_template_dataset
+
+QUESTION = "What colour is the ball and which way does it move?"
+ANSWERS = ["red moves left", "blue moves right"]
+CLIPS = ["clips/clip00.mp4", "clips/clip01.mp4"]
+
+
+def _messages_rows():
+ return Dataset.from_list(
+ [
+ {
+ "messages": [
+ {
+ "role": "user",
+ "content": [
+ {"type": "video", "video": clip},
+ {"type": "text", "text": QUESTION},
+ ],
+ },
+ {"role": "assistant", "content": [{"type": "text", "text": answer}]},
+ ]
+ }
+ for clip, answer in zip(CLIPS, ANSWERS)
+ ]
+ )
+
+
+def _flat_rows():
+ return Dataset.from_dict({"video": CLIPS, "question": [QUESTION] * 2, "answer": ANSWERS})
+
+
+def _format(ds):
+ info = format_and_template_dataset(
+ ds,
+ model_name = "unsloth/Qwen2.5-VL-3B-Instruct",
+ tokenizer = None,
+ is_vlm = True,
+ dataset_name = "local",
+ )
+ assert info["success"], info["errors"]
+ assert info["final_format"] == "vlm_messages"
+ return list(info["dataset"])
+
+
+def _video_parts(row):
+ return [
+ part
+ for message in row["messages"]
+ for part in message["content"]
+ if part.get("type") == "video"
+ ]
+
+
[email protected]("rows", [_messages_rows, _flat_rows], ids = ["messages", "flat"])
+def test_check_format_routes_video_to_the_vision_path(rows):
+ result = check_dataset_format(rows(), is_vlm = True)
+ # is_image is what the UI sends back as is_dataset_image, which selects the VLM trainer.
+ assert result["is_image"] is True
+ assert result["requires_manual_mapping"] is False
+ assert result["detected_format"] in ("vlm_messages", "video_text")
+
+
+def test_messages_rows_keep_their_video_parts():
+ out = _format(_messages_rows())
+ assert [_video_parts(row) for row in out] == [
+ [{"type": "video", "video": clip}] for clip in CLIPS
+ ]
+
+
+def test_flat_video_rows_become_video_messages():
+ out = _format(_flat_rows())
+ for row, clip, answer in zip(out, CLIPS, ANSWERS):
+ user, assistant = row["messages"]
+ assert user["content"] == [
+ {"type": "video", "video": clip},
+ {"type": "text", "text": QUESTION},
+ ]
+ assert assistant["content"] == [{"type": "text", "text": answer}]
+
+
+ "clip", ["clips/a.webm", {"bytes": None, "path": "clips/a.webm"}], ids = ["str", "dict"]
+)
+def test_webm_in_a_video_column_is_video_not_audio(clip):
+ ds = Dataset.from_list([{"video": clip, "answer": "red moves left"}] * 2)
+ result = check_dataset_format(ds, is_vlm = True)
+ assert result["is_image"] is True
+ assert result["is_audio"] is False
+ assert result["detected_format"] == "video_text"
+
+
+def test_audio_in_a_column_named_video_stays_audio():
+ ds = Dataset.from_list([{"video": {"bytes": None, "path": "a.wav"}, "text": "hello"}] * 2)
+ result = check_dataset_format(ds, is_vlm = True)
+ assert result["is_audio"] is True
+ assert "video" not in (result["multimodal_columns"] or [])
+
+
+def test_text_columns_named_like_video_stay_text():
+ ds = Dataset.from_dict(
+ {"video_id": ["abc", "def"], "video title": ["Cooking", "Hiking"], "text": ["a", "b"]}
+ )
+ result = check_dataset_format(ds, is_vlm = True)
+ assert result["is_image"] is False
+
+
+def _mlx_adapter():
+ # worker.py pulls the whole CUDA/MLX import chain; the adapter itself is self-contained.
+ import ast
+ from pathlib import Path
+
+ source = (Path(__file__).parents[1] / "core" / "training" / "worker.py").read_text(
+ encoding = "utf-8"
+ )
+ nodes = [
+ n
+ for n in ast.parse(source).body
+ if (isinstance(n, ast.FunctionDef) and n.name == "_adapt_for_mlx_vlm")
+ or (isinstance(n, ast.Assign) and ast.unparse(n.targets[0]) == "_MLX_VIDEO_UNSUPPORTED")
+ ]
+ namespace = {"_resize_mlx_vlm_image": lambda image, *a, **k: image}
+ exec(compile(ast.Module(nodes, []), "worker.py", "exec"), namespace)
+ return namespace["_adapt_for_mlx_vlm"]
+
+
+def test_mlx_refuses_video_rather_than_dropping_it():
+ with pytest.raises(ValueError, match = "video"):
+ _mlx_adapter()(_format(_messages_rows()))
+
+
[email protected]("url", ["https://example.com/clip.mp4", "HTTP://example.com/clip.mov?x=1"])
[email protected]("shape", ["flat", "messages"])
+def test_remote_video_urls_are_refused_with_a_clear_message(url, shape):
+ # Never handed to the collator to fetch unguarded, nor read as a local path for a managed account.
+ if shape == "flat":
+ ds = Dataset.from_dict({"video": [url] * 2, "answer": ANSWERS})
+ else:
+ ds = Dataset.from_list(
+ [
+ {
+ "messages": [
+ {"role": "user", "content": [{"type": "video", "video": url}]},
+ {"role": "assistant", "content": [{"type": "text", "text": a}]},
+ ]
+ }
+ for a in ANSWERS
+ ]
+ )
+ info = format_and_template_dataset(
+ ds,
+ model_name = "unsloth/Qwen2.5-VL-3B-Instruct",
+ tokenizer = None,
+ is_vlm = True,
+ dataset_name = "local",
+ )
+ assert not info["success"]
+ assert "Remote video URLs are not fetched" in " ".join(map(str, info["errors"]))
+
+
+def test_completion_is_a_video_answer_column():
+ ds = Dataset.from_dict({"video": CLIPS, "completion": ANSWERS})
+ assert check_dataset_format(ds, is_vlm = True)["detected_format"] == "video_text"
+ for row, answer in zip(_format(ds), ANSWERS):
+ assert row["messages"][1]["content"] == [{"type": "text", "text": answer}]
+
+
+def test_a_video_column_with_no_answer_column_is_not_reported_as_formatted():
+ ds = Dataset.from_dict({"video": CLIPS, "notes_id": ["1", "2"]})
+ info = format_and_template_dataset(
+ ds,
+ model_name = "unsloth/Qwen2.5-VL-3B-Instruct",
+ tokenizer = None,
+ is_vlm = True,
+ dataset_name = "local",
+ )
+ assert not info["success"]
+ assert info["requires_manual_mapping"] is True
+ assert "video" in " ".join(map(str, info["errors"]))
+
+
+def test_a_null_first_video_row_still_reads_as_video():
+ ds = Dataset.from_dict({"video": [None, *CLIPS], "answer": [None, *ANSWERS]})
+ result = check_dataset_format(ds, is_vlm = True)
+ assert result["is_image"] is True
+ assert result["detected_format"] == "video_text"
+ out = _format(ds)
+ assert [_video_parts(row) for row in out] == [[{"type": "video", "video": c}] for c in CLIPS]
+
+
+def test_a_blank_first_answer_still_finds_the_answer_column():
+ ds = Dataset.from_dict({"video": CLIPS, "answer": [" ", ANSWERS[1]]})
+ assert check_dataset_format(ds, is_vlm = True)["detected_format"] == "video_text"
+ out = _format(ds)
+ assert len(out) == 1 and out[0]["messages"][1]["content"] == [
+ {"type": "text", "text": ANSWERS[1]}
+ ]
+
+
+def test_every_video_column_reaches_the_message():
+ ds = Dataset.from_dict(
+ {"video_front": CLIPS, "video_side": ["clips/side0.mp4", None], "answer": ANSWERS}
+ )
+ out = _format(ds)
+ assert _video_parts(out[0]) == [
+ {"type": "video", "video": CLIPS[0]},
+ {"type": "video", "video": "clips/side0.mp4"},
+ ]
+ assert _video_parts(out[1]) == [{"type": "video", "video": CLIPS[1]}]
+
+
+class _DecodedVideo:
+ """What a datasets `Video` feature yields with decoding on: a decoder carrying its source."""
+
+ def __init__(self, path):
+ self._hf_encoded = {"path": path, "bytes": None}
+
+
+def test_decoded_hf_video_cells_are_video():
+ from utils.datasets.format_conversion import convert_video_to_vlm_format
+ from utils.datasets.format_detection import detect_video_structure
+
+ rows = [{"clip": _DecodedVideo(c), "answer": a} for c, a in zip(CLIPS, ANSWERS)]
+ structure = detect_video_structure(rows[0])
+ assert structure["format"] == "video_text" and structure["video_column"] == "clip"
+ out = convert_video_to_vlm_format(
+ rows, "clip", "answer", video_columns = structure["video_columns"]
+ )
+ assert [_video_parts(row) for row in out] == [[{"type": "video", "video": c}] for c in CLIPS]
+
+
+def test_a_numeric_answer_column_is_an_answer():
+ ds = Dataset.from_dict({"video": CLIPS, "label": [0, 1]})
+ assert check_dataset_format(ds, is_vlm = True)["detected_format"] == "video_text"
+ out = _format(ds)
+ assert [row["messages"][1]["content"][0]["text"] for row in out] == ["0", "1"]
+
+
+def test_rows_mixing_video_and_image_columns_are_refused():
+ from PIL import Image
+
+ image = Image.new("RGB", (4, 4))
+ ds = Dataset.from_dict({"video": CLIPS, "image": [image, image], "answer": ANSWERS})
+ info = format_and_template_dataset(
+ ds,
+ model_name = "unsloth/Qwen2.5-VL-3B-Instruct",
+ tokenizer = None,
+ is_vlm = True,
+ dataset_name = "local",
+ )
+ assert not info["success"]
+ assert "image" in " ".join(map(str, info["errors"]))
+
+
+def test_a_text_column_named_image_is_not_an_image():
+ ds = Dataset.from_dict({"video": CLIPS, "image_caption": ["a", "b"], "answer": ANSWERS})
+ assert len(_format(ds)) == 2
+
+
+def test_byte_backed_hf_video_is_refused_with_a_clear_message():
+ from utils.datasets.format_conversion import convert_video_to_vlm_format
+ from utils.datasets.format_detection import detect_video_structure
+
+ clip = _DecodedVideo(None)
+ clip._hf_encoded["bytes"] = b"\x00\x00\x00\x18ftypmp42"
+ row = {"clip": clip, "answer": "red"}
+ structure = detect_video_structure(row)
+ assert structure["video_column"] == "clip"
+ with pytest.raises(ValueError, match = "embedded bytes"):
+ convert_video_to_vlm_format([row], "clip", "answer")
+
+
+def test_a_blank_optional_clip_is_skipped_not_fatal():
+ from utils.datasets.format_conversion import convert_video_to_vlm_format
+
+ rows = [{"front": CLIPS[0], "side": " ", "answer": "red"}]
+ out = convert_video_to_vlm_format(rows, "front", "answer", video_columns = ["front", "side"])
+ assert _video_parts(out[0]) == [{"type": "video", "video": CLIPS[0]}]
+
+
+def test_embedded_bytes_with_a_filename_only_path_are_refused():
+ from utils.datasets.format_conversion import convert_video_to_vlm_format
+
+ clip = _DecodedVideo("clip.mp4")
+ clip._hf_encoded["bytes"] = b"\x00\x00\x00\x18ftypmp42"
+ with pytest.raises(ValueError, match = "embedded bytes"):
+ convert_video_to_vlm_format([{"clip": clip, "answer": "red"}], "clip", "answer")
+
+
+def test_cached_hub_clips_resolve_when_the_repo_cannot_be_listed(monkeypatch, tmp_path):
+ import huggingface_hub
+
+ from utils.datasets.format_conversion import convert_video_to_vlm_format
+
+ class Api:
+ def list_repo_files(self, *a, **kw):
+ raise OSError("offline")
+
+ def download(
+ repo_id,
+ filename,
+ local_files_only = False,
+ **kw,
+ ):
+ assert local_files_only
+ return str(tmp_path / filename)
+
+ monkeypatch.setattr(huggingface_hub, "HfApi", Api)
+ monkeypatch.setattr(huggingface_hub, "hf_hub_download", download)
+ rows = [{"video": "videos/clip00.mp4", "answer": "red"}]
+ out = convert_video_to_vlm_format(rows, "video", "answer", dataset_name = "someone/clips")
+ assert _video_parts(out[0])[0]["video"] == str(tmp_path / "videos/clip00.mp4")
+
+
+def test_an_image_past_the_detection_probe_is_still_refused():
+ from PIL import Image
+
+ from utils.datasets.format_conversion import convert_video_to_vlm_format
+
+ rows = [{"video": CLIPS[0], "image": None, "answer": "a"}] * 40
+ rows = rows + [{"video": CLIPS[1], "image": Image.new("RGB", (4, 4)), "answer": "b"}]
+ with pytest.raises(ValueError, match = "image"):
+ convert_video_to_vlm_format(rows, "video", "answer")
+
+
+def test_hub_relative_clips_resolve_from_the_dataset_repo(monkeypatch, tmp_path):
+ import huggingface_hub
+
+ from utils.datasets.format_conversion import convert_video_to_vlm_format, own_message_videos
+
+ calls, revisions = [], []
+
+ class Api:
+ def list_repo_files(
+ self,
+ repo_id,
+ repo_type = None,
+ revision = None,
+ ):
+ assert (repo_id, repo_type) == ("someone/clips", "dataset")
+ revisions.append(("list", revision))
+ return ["videos/clip00.mp4", "videos/clip01.mp4", "README.md"]
+
+ def download(
+ repo_id,
+ filename,
+ repo_type = None,
+ revision = None,
+ cache_dir = None,
+ **kw,
+ ):
+ calls.append(filename)
+ revisions.append(("download", revision))
+ return str(tmp_path / filename)
+
+ monkeypatch.setattr(huggingface_hub, "HfApi", Api)
+ monkeypatch.setattr(huggingface_hub, "hf_hub_download", download)
+ rows = [{"video": f"videos/clip0{i}.mp4", "answer": a} for i, a in enumerate(ANSWERS)]
+ out = convert_video_to_vlm_format(rows, "video", "answer", dataset_name = "someone/clips")
+ assert [_video_parts(r)[0]["video"] for r in out] == [
+ str(tmp_path / f"videos/clip0{i}.mp4") for i in range(2)
+ ]
+ assert {revision for _, revision in revisions} == {None}
+ messages = [
+ {"messages": [{"role": "user", "content": [{"type": "video", "video": "clip01.mp4"}]}]}
+ ]
+ out = own_message_videos(messages, dataset_name = "someone/clips")
+ assert _video_parts(out[0])[0]["video"] == str(tmp_path / "videos/clip01.mp4")
+
+ # A pinned dataset revision lists and downloads clips from that revision, not main.
+ revisions.clear()
+ convert_video_to_vlm_format(
+ rows, "video", "answer", dataset_name = "someone/clips", dataset_revision = "abc123"
+ )
+ own_message_videos(messages, dataset_name = "someone/clips", dataset_revision = "abc123")
+ assert revisions and {revision for _, revision in revisions} == {"abc123"}
+ assert {kind for kind, _ in revisions} == {"list", "download"}
+
+
+def test_the_dataset_revision_reaches_the_clip_resolver_from_every_trainer():
+ import ast
+ from pathlib import Path
+
+ backend = Path(__file__).parents[1]
+ for path in ("core/training/trainer.py", "core/training/worker.py"):
+ tree = ast.parse((backend / path).read_text(encoding = "utf-8"))
+ calls = [
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Call)
+ and getattr(node.func, "id", None) == "format_and_template_dataset"
+ # Clips are resolved only on the VLM path; a text-only call never reaches them.
+ and any(
+ kw.arg == "is_vlm"
+ and not (isinstance(kw.value, ast.Constant) and kw.value.value is False)
+ for kw in node.keywords
+ )
+ ]
+ assert calls, path
+ missing = [
+ c.lineno for c in calls if not any(kw.arg == "dataset_revision" for kw in c.keywords)
+ ]
+ assert (
+ not missing
+ ), f"{path}: format_and_template_dataset without dataset_revision at {missing}"
+
+
+def test_a_lone_column_of_clip_paths_is_not_raw_text():
+ from utils.datasets.format_detection import is_plain_text_dataset
+ assert not is_plain_text_dataset(Dataset.from_dict({"clip": CLIPS}))
+ assert is_plain_text_dataset(Dataset.from_dict({"text": ["a story", "another"]}))
+
+
+def test_an_ambiguous_bare_clip_name_is_refused(monkeypatch, tmp_path):
+ import huggingface_hub
+
+ from utils.datasets.format_conversion import convert_video_to_vlm_format
+
+ class Api:
+ def list_repo_files(
+ self,
+ repo_id,
+ repo_type = None,
+ revision = None,
+ ):
+ return ["train/clip.mp4", "test/clip.mp4"]
+
+ monkeypatch.setattr(huggingface_hub, "HfApi", Api)
+ monkeypatch.setattr(huggingface_hub, "hf_hub_download", lambda *a, **k: str(tmp_path / "x.mp4"))
+ with pytest.raises(ValueError, match = "train/clip.mp4"):
+ convert_video_to_vlm_format(
+ [{"video": "clip.mp4", "answer": "a"}], "video", "answer", dataset_name = "someone/clips"
+ )
+ out = convert_video_to_vlm_format(
+ [{"video": "test/clip.mp4", "answer": "a"}], "video", "answer", dataset_name = "someone/clips"
+ )
+ assert _video_parts(out[0])[0]["video"] == str(tmp_path / "x.mp4")
+
+
[email protected]("repo_files", [["clip.mp4", "sub/clip.mp4"], ["sub/clip.mp4", "clip.mp4"]])
+def test_a_root_level_clip_is_its_own_repo_path(monkeypatch, tmp_path, repo_files):
+ import huggingface_hub
+
+ from utils.datasets.format_conversion import convert_video_to_vlm_format
+
+ class Api:
+ def list_repo_files(
+ self,
+ repo_id,
+ repo_type = None,
+ revision = None,
+ ):
+ return repo_files
+
+ monkeypatch.setattr(huggingface_hub, "HfApi", Api)
+ monkeypatch.setattr(
+ huggingface_hub, "hf_hub_download", lambda repo, filename, **k: str(tmp_path / filename)
+ )
+ # "clip.mp4" is the root file's repo-relative path, so it is exact whatever the listing order.
+ for name in ("clip.mp4", "sub/clip.mp4"):
+ out = convert_video_to_vlm_format(
+ [{"video": name, "answer": "a"}], "video", "answer", dataset_name = "someone/clips"
+ )
+ assert _video_parts(out[0])[0]["video"] == str(tmp_path / name)
+
+
+def test_a_classlabel_answer_trains_on_the_class_name():
+ from datasets import ClassLabel, Features, Value
+
+ features = Features({"video": Value("string"), "label": ClassLabel(names = ["cat", "dog"])})
+ ds = Dataset.from_dict({"video": CLIPS, "label": [1, 0]}, features = features)
+ out = _format(ds)
+ assert [row["messages"][1]["content"][0]["text"] for row in out] == ["dog", "cat"]
+
+
+def test_a_manual_video_mapping_uses_the_video_converter():
+ ds = Dataset.from_dict({"video": CLIPS, "ask": [QUESTION] * 2, "target": ANSWERS})
+ info = format_and_template_dataset(
+ ds,
+ model_name = "unsloth/Qwen2.5-VL-3B-Instruct",
+ tokenizer = None,
+ is_vlm = True,
+ dataset_name = "local",
+ custom_format_mapping = {"video": "image", "target": "assistant", "ask": "user"},
+ )
+ assert info["success"], info["errors"]
+ for row, clip, answer in zip(info["dataset"], CLIPS, ANSWERS):
+ user, assistant = row["messages"]
+ assert user["content"] == [
+ {"type": "video", "video": clip},
+ {"type": "text", "text": QUESTION},
+ ]
+ assert assistant["content"] == [{"type": "text", "text": answer}]
+
+
+def test_a_ui_video_mapping_keeps_the_detected_question():
+ ds = Dataset.from_dict({"video": CLIPS, "question": [QUESTION] * 2, "target": ANSWERS})
+ info = format_and_template_dataset(
+ ds,
+ model_name = "unsloth/Qwen2.5-VL-3B-Instruct",
+ tokenizer = None,
+ is_vlm = True,
+ dataset_name = "local",
+ custom_format_mapping = {"video": "image", "target": "text"},
+ )
+ assert info["success"], info["errors"]
+ for row in info["dataset"]:
+ assert row["messages"][0]["content"][-1] == {"type": "text", "text": QUESTION}
+
+
+class AudioDecoder:
+ def __init__(self, path):
+ self._hf_encoded = {"path": path, "bytes": None}
+
+
[email protected]("path", ["a.wav", "a.mp4"])
+def test_decoded_hf_audio_cells_are_not_video(path):
+ from utils.datasets.format_detection import detect_video_columns
+ assert detect_video_columns({"audio": AudioDecoder(path), "text": "hi"}) == []
+
+
+def test_an_input_column_is_the_video_question():
+ ds = Dataset.from_dict({"video": CLIPS, "input": [QUESTION] * 2, "output": ANSWERS})
+ for row in _format(ds):
+ assert row["messages"][0]["content"][-1] == {"type": "text", "text": QUESTION}
+
+
+def test_text_only_message_rows_lose_the_arrow_video_key():
+ text_row = {
+ "messages": [
+ {"role": "user", "content": [{"type": "text", "text": "hi"}]},
+ {"role": "assistant", "content": [{"type": "text", "text": "yo"}]},
+ ]
+ }
+ ds = Dataset.from_list([_messages_rows()[0], text_row])
+ for row in _format(ds):
+ for message in row["messages"]:
+ for part in message["content"]:
+ assert None not in part.values(), part
+
+
+def test_a_text_only_first_message_row_still_finds_later_video():
+ text_row = {
+ "messages": [
+ {"role": "user", "content": [{"type": "text", "text": "hi"}]},
+ {"role": "assistant", "content": [{"type": "text", "text": "yo"}]},
+ ]
+ }
+ ds = Dataset.from_list([text_row, _messages_rows()[0]])
+ result = check_dataset_format(ds, is_vlm = True)
+ assert result["is_image"] is True
+ assert not result["requires_manual_mapping"]
+
+
+def test_a_decoded_audio_dict_with_an_mp4_path_is_not_video():
+ from utils.datasets.format_detection import detect_video_columns
+ cell = {"path": "clip.mp4", "array": [0.0], "sampling_rate": 16000}
+ assert detect_video_columns({"audio": cell, "text": "hi"}) == []
+
+
+def test_mlx_refuses_video_before_formatting_fetches_clips():
+ import ast
+ from pathlib import Path
+
+ source = (Path(__file__).parents[1] / "core" / "training" / "worker.py").read_text(
+ encoding = "utf-8"
+ )
+ run = next(
+ n
+ for n in ast.parse(source).body
+ if isinstance(n, ast.FunctionDef) and n.name == "_run_mlx_training"
+ )
+ calls = [
+ node.func.id
+ for node in ast.walk(run)
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name)
+ ]
+ lines = {
+ name: min(
+ n.lineno
+ for n in ast.walk(run)
+ if isinstance(n, ast.Call) and isinstance(n.func, ast.Name) and n.func.id == name
+ )
+ for name in ("detect_video_columns", "format_and_template_dataset")
+ if name in calls
+ }
+ assert lines["detect_video_columns"] < lines["format_and_template_dataset"]
+
+
[email protected]("name", ["user_prompt", "problem", "inputs"])
+def test_vlm_question_aliases_are_video_questions(name):
+ ds = Dataset.from_dict({"video": CLIPS, name: [QUESTION] * 2, "answer": ANSWERS})
+ for row in _format(ds):
+ assert row["messages"][0]["content"][-1] == {"type": "text", "text": QUESTION}
+
+
[email protected]("embedded", [False, True])
+def test_network_share_clips_are_refused_before_any_stat(monkeypatch, embedded):
+ import os
+
+ import utils.datasets.format_conversion as fc
+
+ stats = []
+ monkeypatch.setattr(fc, "is_network_share", lambda p: p.startswith("\\\\"))
+ monkeypatch.setattr(fc, "private_sources_allowed", lambda: False)
+ monkeypatch.setattr(os.path, "exists", lambda p: stats.append(p) or False)
+ monkeypatch.setattr(os.path, "isfile", lambda p: stats.append(p) or False)
+ clip = "\\\\host\\share\\clip.mp4"
+ cell = {"path": clip, "bytes": b"x"} if embedded else clip
+ with pytest.raises(OSError, match = "network share"):
+ fc._own_video_part(cell, None, fc._HubClips("someone/clips"))
+ assert clip not in stats
diff --git a/studio/backend/utils/datasets/__init__.py b/studio/backend/utils/datasets/__init__.py
index caa471bde5d..0141ef786b3 100644
--- a/studio/backend/utils/datasets/__init__.py
+++ b/studio/backend/utils/datasets/__init__.py
@@ -17,6 +17,8 @@ from .format_conversion import (
convert_to_vlm_format,
convert_llava_to_vlm_format,
convert_sharegpt_with_images_to_vlm_format,
+ convert_video_to_vlm_format,
+ own_message_videos,
)
from .chat_templates import (
@@ -63,6 +65,8 @@ __all__ = [
"convert_to_vlm_format",
"convert_llava_to_vlm_format",
"convert_sharegpt_with_images_to_vlm_format",
+ "convert_video_to_vlm_format",
+ "own_message_videos",
# Templates
"apply_chat_template_to_dataset",
"get_dataset_info_summary",
diff --git a/studio/backend/utils/datasets/dataset_utils.py b/studio/backend/utils/datasets/dataset_utils.py
index eef0f6e24b0..a037cb43aa0 100644
--- a/studio/backend/utils/datasets/dataset_utils.py
+++ b/studio/backend/utils/datasets/dataset_utils.py
@@ -11,6 +11,10 @@ from .format_detection import (
detect_vlm_dataset_structure,
detect_custom_format_heuristic,
is_plain_text_dataset,
+ detect_video_columns,
+ detect_video_structure,
+ video_sample,
+ _VIDEO_TEXT_KEYWORDS,
)
from .format_conversion import (
standardize_chat_format,
@@ -19,6 +23,8 @@ from .format_conversion import (
convert_to_vlm_format,
convert_llava_to_vlm_format,
convert_sharegpt_with_images_to_vlm_format,
+ convert_video_to_vlm_format,
+ own_message_videos,
normalize_chatml_roles,
)
from .chat_templates import (
@@ -890,6 +896,7 @@ def format_and_template_dataset(
progress_callback = None,
split_name = None,
raw_text_column = None,
+ dataset_revision = None,
):
"""Combines format_dataset and apply_chat_template_to_dataset, for UI workflows where one call does everything. custom_prompt_template is retained for signature compatibility; non-None values are rejected because Studio cannot persist a matching inference template. Returns {dataset (with a 'text' column), detected_format, final_format, success, requires_manual_mapping, warnings, errors, summary}."""
from .tokenizer_fingerprint import install_tokenizer_fingerprint
@@ -927,6 +934,76 @@ def format_and_template_dataset(
elif role in ["text", "user", "caption", "assistant"]:
user_vlm_text_column = col
+ # The text-role loop above keeps the last one; a clip needs the answer and question kept apart.
+ video_answer_column = next(
+ (
+ c
+ for c, r in custom_format_mapping.items()
+ if r in ("assistant", "text", "caption")
+ ),
+ user_vlm_text_column,
+ )
+ video_question_column = next(
+ (
+ c
+ for c, r in custom_format_mapping.items()
+ if r == "user" and c != video_answer_column
+ ),
+ None,
+ )
+ first = next(iter(dataset), None)
+ probe = video_sample(dataset, first) if isinstance(first, dict) else {}
+ mapped_video = (
+ user_vlm_image_column
+ and user_vlm_text_column
+ and user_vlm_image_column in detect_video_columns(probe)
+ )
+ if mapped_video and video_question_column is None:
+ # The VLM mapping UI offers only image and text roles, so take the question from detection.
+ detected_question = (detect_video_structure(probe) or {}).get("question_column")
+ if detected_question not in (None, video_answer_column, user_vlm_image_column):
+ video_question_column = detected_question
+ if mapped_video:
+ # The image role on a clip column: the image converter would try to open the clip.
+ try:
+ dataset = convert_video_to_vlm_format(
+ dataset,
+ video_column = user_vlm_image_column,
+ text_column = video_answer_column,
+ question_column = video_question_column,
+ instruction = vlm_instruction,
+ dataset_name = dataset_name,
+ dataset_revision = dataset_revision,
+ )
+ except Exception as e:
+ errors.append(f"Failed to convert the mapped video + text columns: {e}")
+ return {
+ "dataset": dataset,
+ "detected_format": "user_mapped",
+ "final_format": "vlm_conversion_failed",
+ "is_vlm": True,
+ "success": False,
+ "requires_manual_mapping": True,
+ "warnings": warnings,
+ "errors": errors,
+ }
+ warnings.append(
+ f"Applied user VLM mapping: video='{user_vlm_image_column}', text='{video_answer_column}'"
+ )
+ return {
+ "dataset": dataset,
+ "detected_format": "user_mapped",
+ "final_format": "vlm_messages",
+ "chat_column": "messages",
+ "is_vlm": True,
+ "is_image": True,
+ "multimodal_info": multimodal_info,
+ "success": True,
+ "requires_manual_mapping": False,
+ "warnings": warnings,
+ "errors": [],
+ }
+
if user_vlm_image_column and user_vlm_text_column:
try:
dataset = convert_to_vlm_format(
@@ -1030,6 +1107,64 @@ def format_and_template_dataset(
"errors": errors,
}
+ elif vlm_structure["format"] == "video_text" and vlm_structure.get("image_columns"):
+ errors.append(
+ f"Rows mix video ('{vlm_structure['video_column']}') with image columns "
+ f"{vlm_structure['image_columns']}; video conversion would drop the images, so remove "
+ "those columns or split the dataset."
+ )
+ return {
+ "dataset": dataset,
+ "detected_format": "video_text",
+ "final_format": "vlm_conversion_failed",
+ "is_vlm": True,
+ "success": False,
+ "requires_manual_mapping": True,
+ "warnings": warnings,
+ "errors": errors,
+ }
+
+ elif vlm_structure["format"] == "video_text":
+ try:
+ dataset = convert_video_to_vlm_format(
+ dataset,
+ video_column = vlm_structure["video_column"],
+ text_column = vlm_structure["text_column"],
+ question_column = vlm_structure.get("question_column"),
+ instruction = vlm_instruction,
+ video_columns = vlm_structure.get("video_columns"),
+ dataset_name = dataset_name,
+ dataset_revision = dataset_revision,
+ )
+ except Exception as e:
+ errors.append(f"Failed to convert video + text rows to VLM format: {e}")
+ return {
+ "dataset": dataset,
+ "detected_format": "video_text",
+ "final_format": "vlm_conversion_failed",
+ "is_vlm": True,
+ "success": False,
+ "requires_manual_mapping": True,
+ "warnings": warnings,
+ "errors": errors,
+ }
+
+ elif vlm_structure["format"] == "unknown" and vlm_structure.get("video_column"):
+ errors.append(
+ f"Found videos in '{vlm_structure['video_column']}' but no answer column; name the answer column with one of these words: "
+ + ", ".join(_VIDEO_TEXT_KEYWORDS)
+ )
+ return {
+ "dataset": dataset,
+ "detected_format": "unknown",
+ "final_format": "vlm_unknown",
+ "is_vlm": True,
+ "success": False,
+ "requires_manual_mapping": True,
+ "warnings": warnings,
+ "errors": errors,
+ }
+
elif vlm_structure["needs_conversion"]:
if vlm_text_column is None:
vlm_text_column = vlm_structure["text_column"]
@@ -1101,7 +1236,22 @@ def format_and_template_dataset(
}
elif vlm_structure["format"] == "vlm_messages":
- dataset = [sample for sample in dataset]
+ try:
+ dataset = own_message_videos(
+ dataset, dataset_name = dataset_name, dataset_revision = dataset_revision
+ )
+ except Exception as e:
+ errors.append(f"Failed to read the video parts of VLM messages rows: {e}")
+ return {
+ "dataset": dataset,
+ "detected_format": "vlm_messages",
+ "final_format": "vlm_conversion_failed",
+ "is_vlm": True,
+ "success": False,
+ "requires_manual_mapping": True,
+ "warnings": warnings,
+ "errors": errors,
+ }
warnings.append("Dataset already in standard VLM messages format")
return {
diff --git a/studio/backend/utils/datasets/format_conversion.py b/studio/backend/utils/datasets/format_conversion.py
index 804bc461dd2..65785916adc 100644
--- a/studio/backend/utils/datasets/format_conversion.py
+++ b/studio/backend/utils/datasets/format_conversion.py
@@ -843,6 +843,227 @@ def convert_to_vlm_format(
return converted_list
+class _HubClips:
+ """Repo-relative clip names of a Hub dataset, resolved by download the way bare image filenames are."""
+
+ def __init__(
+ self,
+ dataset_name,
+ revision = None,
+ ):
+ self.repo, self.revision, self.files, self.listed = dataset_name, revision, None, False
+ if (
+ not isinstance(dataset_name, str)
+ or dataset_name.count("/") != 1
+ or os.path.exists(dataset_name)
+ ):
+ self.repo = None
+
+ def resolve(self, path):
+ if self.repo is None or os.path.exists(path) or "://" in path or os.path.isabs(path):
+ return None
+ if self.files is None:
+ from huggingface_hub import HfApi
+
+ from .format_detection import _VIDEO_EXTENSIONS
+
+ self.files, ambiguous = {}, {}
+ try:
+ repo_files = HfApi().list_repo_files(
+ self.repo, repo_type = "dataset", revision = self.revision
+ )
+ self.listed = True
+ except Exception as e: # noqa: BLE001 -- not a Hub repo or offline: paths stay local
+ logger.info(f"Could not list {self.repo} to resolve video filenames: {e}")
+ repo_files = []
+ for f in repo_files:
+ if f.lower().endswith(_VIDEO_EXTENSIONS + (".webm",)):
+ ambiguous.setdefault(os.path.basename(f), []).append(f)
+ for f in repo_files:
+ if f.lower().endswith(_VIDEO_EXTENSIONS + (".webm",)):
+ name = os.path.basename(f)
+ # A name in several folders resolves to its list, refused below: one copy is a guess.
+ self.files.setdefault(name, f if len(ambiguous[name]) == 1 else ambiguous[name])
+ self.files[f] = f
+ from huggingface_hub import hf_hub_download
+
+ from utils.hf_cache_settings import active_hf_hub_cache
+
+ if path not in self.files:
+ if self.listed:
+ return None
+ # Offline: an exact repo path may still be in the cache.
+ try:
+ return hf_hub_download(
+ self.repo,
+ path,
+ repo_type = "dataset",
+ revision = self.revision,
+ cache_dir = active_hf_hub_cache(),
+ local_files_only = True,
+ )
+ except Exception: # noqa: BLE001 -- not cached: the path stays local
+ return None
+ if isinstance(self.files[path], list):
+ raise ValueError(
+ f"Video '{path}' matches several files in {self.repo} ({', '.join(self.files[path])}); "
+ "use the repo-relative path."
+ )
+ return hf_hub_download(
+ self.repo,
+ self.files[path],
+ repo_type = "dataset",
+ revision = self.revision,
+ cache_dir = active_hf_hub_cache(),
+ )
+
+
+def _own_video_part(
+ video,
+ account,
+ hub = None,
+):
+ from .format_detection import encoded_video
+
+ video = encoded_video(video)
+ embedded = isinstance(video, dict) and bool(video.get("bytes"))
+ if isinstance(video, dict):
+ video = video.get("path")
+ # Before any stat: probing a UNC path can already contact the share.
+ if isinstance(video, str) and is_network_share(video) and not private_sources_allowed():
+ raise OSError(
+ f"Refusing a video path on a network share: {video}. "
+ "Set UNSLOTH_ALLOW_PRIVATE_URL_FETCH=1 to load videos from shares you trust."
+ )
+ # An embedded clip's path is often just its original filename, with no file behind it.
+ if embedded and not (isinstance(video, str) and os.path.isfile(video)):
+ resolved = (
+ hub.resolve(video)
+ if hub is not None and isinstance(video, str) and video.strip()
+ else None
+ )
+ if resolved is not None:
+ return resolved
+ raise ValueError(
+ "A video is stored as embedded bytes with no readable file path; training reads clips from "
+ "files, so save the clips to files and point the column at their paths."
+ )
+ if not isinstance(video, str) or not video.strip():
+ raise ValueError("Row has no video")
+ if video.strip().lower().startswith(("http://", "https://")):
+ # The collator would fetch it unguarded; the image fetchers' 64 MB cap does not fit clips.
+ raise ValueError(
+ f"Remote video URLs are not fetched for training: {video}. "
+ "Download the clips and point the column at local files or a Hub dataset."
+ )
+ resolved = hub.resolve(video) if hub is not None else None
+ if resolved is not None:
+ return resolved
+ return _own_image_path(video, account)
+
+
+def own_message_videos(
+ rows,
+ dataset_name = None,
+ dataset_revision = None,
+):
+ """VLM messages rows as a list, every video path checked like an image path."""
+ from utils.account_context import current_account
+ from .format_detection import video_parts
+
+ account = current_account()
+ hub = _HubClips(dataset_name, dataset_revision)
+ rows = [row for row in rows]
+ for row in rows:
+ if not isinstance(row.get("messages"), list):
+ continue
+ for message in row["messages"]:
+ content = message.get("content") if isinstance(message, dict) else None
+ if not isinstance(content, list):
+ continue
+ # Arrow fills absent keys with None; templates and the collator read key presence.
+ content[:] = [
+ {k: v for k, v in part.items() if v is not None} if isinstance(part, dict) else part
+ for part in content
+ ]
+ for part in video_parts(row["messages"]):
+ part["video"] = _own_video_part(part["video"], account, hub)
+ return rows
+
+
+def convert_video_to_vlm_format(
+ dataset,
+ video_column,
+ text_column,
+ question_column = None,
+ instruction = None,
+ video_columns = None,
+ dataset_name = None,
+ dataset_revision = None,
+):
+ """Flat video + text rows to VLM messages; clips stay paths for the collator to decode."""
+ from utils.account_context import current_account
+
+ from .format_detection import _holds_images, _is_image_value
+
+ account = current_account()
+ hub = _HubClips(dataset_name, dataset_revision)
+ answer_feature = (getattr(dataset, "features", None) or {}).get(text_column)
+ as_label = getattr(answer_feature, "int2str", None)
+ default_instruction = instruction or "Describe this video."
+ converted = []
+ for row in dataset:
+ answer = row.get(text_column)
+ clip_columns = video_columns or [video_column]
+ # Detection probes a few rows; an image further down would otherwise be dropped silently.
+ images = [
+ c
+ for c, v in row.items()
+ if c not in clip_columns and (_is_image_value(v) or _holds_images(v))
+ ]
+ if images:
+ raise ValueError(
+ f"Rows mix video with image columns {images}; video conversion would drop the images, "
+ "so remove those columns or split the dataset."
+ )
+ clips = [
+ row[c]
+ for c in clip_columns
+ if row.get(c) is not None and not (isinstance(row[c], str) and not row[c].strip())
+ ]
+ if not clips or answer is None or not str(answer).strip():
+ continue
+ answer = as_label(answer) if as_label and isinstance(answer, int) else str(answer)
+ question = row.get(question_column) if question_column else None
+ if not isinstance(question, str) or not question.strip():
+ question = default_instruction
+ converted.append(
+ {
+ "messages": [
+ {
+ "role": "user",
+ "content": [
+ *(
+ {"type": "video", "video": _own_video_part(clip, account, hub)}
+ for clip in clips
+ ),
+ {"type": "text", "text": question},
+ ],
+ },
+ {"role": "assistant", "content": [{"type": "text", "text": answer}]},
+ ]
+ }
+ )
+ if not converted:
+ raise ValueError(
+ f"No rows have both a video in '{video_column}' and text in '{text_column}'"
+ )
+ skipped = len(dataset) - len(converted) if hasattr(dataset, "__len__") else 0
+ if skipped:
+ logger.info(f"Skipping {skipped} rows without a video or text")
+ return converted
+
+
def convert_sharegpt_with_images_to_vlm_format(
dataset,
image_column = "image",
diff --git a/studio/backend/utils/datasets/format_detection.py b/studio/backend/utils/datasets/format_detection.py
index 30fd5ebd345..616dc214fc5 100644
--- a/studio/backend/utils/datasets/format_detection.py
+++ b/studio/backend/utils/datasets/format_detection.py
@@ -178,7 +178,7 @@ def _is_single_string_row(row) -> bool:
if not isinstance(value, str) or not value.strip() or _is_image_value(value):
return False
# A column of media paths still needs its other roles mapped.
- return not value.strip().lower().endswith(_AUDIO_EXTENSIONS)
+ return not value.strip().lower().endswith(_AUDIO_EXTENSIONS) and not _is_video_value(value)
def detect_dataset_format(dataset):
@@ -665,6 +665,14 @@ def detect_multimodal_dataset(dataset):
audio_set = set(audio_columns)
multimodal_columns = [c for c in multimodal_columns if c not in audio_set]
+ # A {"bytes","path"} video cell would otherwise read as an image, a .webm one as audio.
+ video_columns = detect_video_columns(video_sample(dataset, sample))
+ audio_columns = [c for c in audio_columns if c not in video_columns]
+ if video_columns:
+ multimodal_columns = [c for c in multimodal_columns if c not in video_columns]
+ multimodal_columns += video_columns
+ modality_types.add("video")
+
detected_text_col = None
if audio_columns:
text_keywords = ["text", "sentence", "transcript", "transcription", "label"]
@@ -686,6 +694,7 @@ def detect_multimodal_dataset(dataset):
return {
"is_image": len(multimodal_columns) > 0,
+ "is_video": bool(video_columns),
"multimodal_columns": multimodal_columns,
"modality_types": list(modality_types),
"is_audio": is_audio,
@@ -780,6 +789,157 @@ _AUDIO_EXTENSIONS = (
)
+# .webm is also an audio container, so it counts as video only in a column named video.
+_VIDEO_EXTENSIONS = (".mp4", ".mov", ".mkv", ".avi", ".m4v", ".mpeg", ".mpg")
+_VIDEO_TEXT_KEYWORDS = (
+ "answer",
+ "completion",
+ "text",
+ "caption",
+ "description",
+ "output",
+ "response",
+ "label",
+)
+# Same aliases as generate_smart_vlm_instruction.
+_VIDEO_QUESTION_KEYWORDS = (
+ "question",
+ "query",
+ "prompt",
+ "instruction",
+ "user_prompt",
+ "problem",
+ "input",
+ "inputs",
+)
+
+
+def encoded_video(value):
+ """A decoded datasets ``Video`` cell as its source {"path", "bytes"} (datasets keeps it on the decoder)."""
+ encoded = getattr(value, "_hf_encoded", None)
+ return encoded if isinstance(encoded, dict) else value
+
+
+def _is_hf_video(value) -> bool:
+ # datasets' Audio cells are torchcodec AudioDecoders carrying the same _hf_encoded source.
+ return (
+ isinstance(getattr(value, "_hf_encoded", None), dict)
+ and "video" in type(value).__name__.lower()
+ )
+
+
+def _is_video_value(value, extensions = _VIDEO_EXTENSIONS) -> bool:
+ if hasattr(value, "_hf_encoded") and not _is_hf_video(value):
+ return False
+ # A decoded audio dict (soundfile / PyAV fallback) can keep an .mp4 path.
+ if isinstance(value, dict) and ("array" in value or "sampling_rate" in value):
+ return False
+ value = encoded_video(value)
+ if isinstance(value, dict):
+ value = value.get("path")
+ if not isinstance(value, str) or len(value) >= 1000:
+ return False
+ return value.strip().lower().split("?")[0].endswith(extensions)
+
+
+def video_sample(
+ dataset,
+ sample: dict,
+ rows: int = 32,
+) -> dict:
+ """``sample`` with each null or blank cell taken from the next rows, so a sparse first row still shows its columns."""
+ import itertools
+
+ def _missing(key, value):
+ # A text-only messages row says nothing about whether later rows carry video.
+ if key == "messages" and isinstance(value, list):
+ return not video_parts(value)
+ return value is None or (isinstance(value, str) and not value.strip())
+
+ if not any(_missing(k, v) for k, v in sample.items()):
+ return sample
+ filled = dict(sample)
+ try:
+ for row in itertools.islice(iter(dataset), 1, rows):
+ for key, value in row.items():
+ if _missing(key, filled.get(key)) and not _missing(key, value):
+ filled[key] = value
+ if not any(_missing(k, v) for k, v in filled.items()):
+ break
+ except Exception: # noqa: BLE001 -- unreadable rows: detect from the first one
+ return sample
+ return filled
+
+
+def video_parts(messages) -> list:
+ if not isinstance(messages, list):
+ return []
+ return [
+ part
+ for message in messages
+ if isinstance(message, dict) and isinstance(message.get("content"), list)
+ for part in message["content"]
+ if isinstance(part, dict) and part.get("type") == "video" and part.get("video") is not None
+ ]
+
+
+def detect_video_columns(sample: dict) -> list:
+ columns = []
+ for col_name, value in sample.items():
+ if _is_video_value(value) or video_parts(value) or _is_hf_video(value):
+ columns.append(col_name)
+ elif _keyword_in_column("video", col_name) and _is_video_value(
+ value, _VIDEO_EXTENSIONS + (".webm",)
+ ):
+ columns.append(col_name)
+ return columns
+
+
+def detect_video_structure(sample: dict):
+ if video_parts(sample.get("messages")):
+ return {
+ "format": "vlm_messages",
+ "needs_conversion": False,
+ "messages_column": "messages",
+ "image_column": None,
+ "video_column": None,
+ "text_column": None,
+ }
+ flat = [col for col in detect_video_columns(sample) if not isinstance(sample[col], list)]
+ if not flat:
+ return None
+
+ def _pick(keywords, scalars = False):
+ for keyword in keywords:
+ for col_name, value in sample.items():
+ usable = (isinstance(value, str) and value.strip()) or (
+ scalars and isinstance(value, (int, float)) and not isinstance(value, bool)
+ )
+ if col_name in flat or not usable:
+ continue
+ if _keyword_in_column(keyword, col_name):
+ return col_name
+ return None
+
+ text_col = _pick(_VIDEO_TEXT_KEYWORDS, scalars = True)
+ question_col = _pick(_VIDEO_QUESTION_KEYWORDS)
+ return {
+ "format": "video_text" if text_col else "unknown",
+ "needs_conversion": True if text_col else None,
+ "messages_column": None,
+ "image_column": None,
+ "video_column": flat[0],
+ "video_columns": flat,
+ "image_columns": [
+ col
+ for col, value in sample.items()
+ if col not in flat and (_is_image_value(value) or _holds_images(value))
+ ],
+ "text_column": text_col,
+ "question_column": question_col if question_col != text_col else None,
+ }
+
+
def _is_audio_value(value) -> bool:
"""Check if a single sample value looks like audio data."""
if value is None:
@@ -832,6 +992,10 @@ def detect_vlm_dataset_structure(dataset):
"messages_column": None,
}
+ video_structure = detect_video_structure(video_sample(dataset, sample))
+ if video_structure is not None:
+ return video_structure
+
column_names = set(sample.keys())
is_text = text_cell_check(dataset)