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.

Improve empty text dataset validation (#6646)

Lee Jacksona4a2404c1108
diff --git a/studio/backend/core/training/trainer.py b/studio/backend/core/training/trainer.py
index 9cd40626542..ec24f7ba5e7 100644
--- a/studio/backend/core/training/trainer.py
+++ b/studio/backend/core/training/trainer.py
@@ -308,6 +308,16 @@ def _dataset_has_audio_column(dataset) -> Optional[bool]:
return False if saw_a_usable_value else None
+def _raise_if_empty_train_split(dataset, stage: str) -> None:
+ # Format detection and SFTTrainer die with a bare StopIteration on an empty split.
+ if hasattr(dataset, "__len__") and len(dataset) == 0:
+ where = f" {stage}" if stage else ""
+ raise ValueError(
+ f"The training dataset has no rows{where}. "
+ "Add at least one example before starting training."
+ )
+
+
# Marks an omitted mode, which keeps the loaded one; a literal default would overwrite it.
_UNSET = object()
@@ -3296,6 +3306,8 @@ class UnslothTrainer:
self._format_audio_vlm_eval_split(eval_dataset, custom_format_mapping),
)
+ _raise_if_empty_train_split(dataset, "")
+
# ========== FORMAT FIRST ==========
logger.info(f"Formatting dataset with format_type='{format_type}'...\n")
@@ -3363,6 +3375,8 @@ class UnslothTrainer:
train_portion, eval_dataset = split_result
dataset_info["dataset"] = train_portion
+ _raise_if_empty_train_split(dataset_info["dataset"], "after formatting")
+
return (dataset_info, eval_dataset)
except S3DownloadCancelled:
diff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.py
index 469c3bb1afa..1366efd469d 100644
--- a/studio/backend/core/training/worker.py
+++ b/studio/backend/core/training/worker.py
@@ -2853,9 +2853,18 @@ def _run_mlx_training(event_queue, stop_queue, config):
format_type = format_type,
dataset_name = hf_dataset or "local",
custom_format_mapping = custom_format_mapping,
+ split_name = "eval",
)
if ev.get("success", True):
eval_dataset = ev.get("dataset", eval_dataset)
+ if hasattr(eval_dataset, "__len__") and len(eval_dataset) == 0:
+ _send(
+ "warning",
+ message = "The eval dataset is empty after preprocessing, so this run has no evaluation.",
+ )
+ eval_dataset = None
+ # A user-supplied split that filters to nothing must not carve one out of train.
+ eval_enabled = False
else:
eval_errors = ev.get("errors", [])
raise ValueError(
diff --git a/studio/backend/tests/test_mlx_dataset_format_failure.py b/studio/backend/tests/test_mlx_dataset_format_failure.py
index 7dd94d27baf..232ed839e6a 100644
--- a/studio/backend/tests/test_mlx_dataset_format_failure.py
+++ b/studio/backend/tests/test_mlx_dataset_format_failure.py
@@ -34,6 +34,7 @@ def _run(
train_warning = None,
eval_success = True,
eval_warning = None,
+ formatted_eval = "FORMATTED_EVAL",
):
"""Execute the real block from _run_mlx_training and report what it did.
@@ -49,7 +50,7 @@ def _run(
first = calls["n"] == 1
return {
"success": train_success if first else eval_success,
- "dataset": "FORMATTED_TRAIN" if first else "FORMATTED_EVAL",
+ "dataset": "FORMATTED_TRAIN" if first else formatted_eval,
"final_format": "chatml_messages",
"dropped_rows_warning": train_warning if first else eval_warning,
}
@@ -64,6 +65,7 @@ def _run(
"tokenizer": object(),
"hf_dataset": "local",
"custom_format_mapping": None,
+ "eval_enabled": True,
"_fmt_progress": lambda **_kw: None,
"_send": lambda kind, **kw: events.append((kind, kw)),
"format_and_template_dataset": _fake_format,
@@ -77,6 +79,7 @@ def _run(
error = str(exc)
return {
+ "eval_enabled": namespace.get("eval_enabled"),
"dataset": namespace.get("dataset"),
"eval_dataset": namespace.get("eval_dataset"),
"warnings": [kw["message"] for kind, kw in events if kind == "warning"],
@@ -120,3 +123,14 @@ def test_a_clean_run_is_unchanged():
assert result["dataset"] == "FORMATTED_TRAIN"
assert result["eval_dataset"] == "FORMATTED_EVAL"
assert result["warnings"] == []
+
+
+def test_an_eval_split_formatted_to_nothing_disables_evaluation():
+ result = _run(formatted_eval = [])
+
+ assert result["error"] is None
+ assert result["eval_dataset"] is None
+ assert result["eval_enabled"] is False, "must not carve an eval split out of train"
+ assert result["warnings"] == [
+ "The eval dataset is empty after preprocessing, so this run has no evaluation."
+ ]
diff --git a/studio/backend/tests/test_raw_text_blank_rows.py b/studio/backend/tests/test_raw_text_blank_rows.py
new file mode 100644
index 00000000000..f42c3a4b6d1
--- /dev/null
+++ b/studio/backend/tests/test_raw_text_blank_rows.py
@@ -0,0 +1,76 @@
+# 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 datasets import Dataset, IterableDataset
+
+from utils.datasets.raw_text import prepare_raw_text_dataset
+
+
+def test_streaming_raw_text_drops_invalid_prefix_lazily_then_appends_eos():
+ visited: list[int] = []
+
+ def rows():
+ for index, text in enumerate([None, " ", "valid"]):
+ visited.append(index)
+ yield {"text": text}
+
+ result = prepare_raw_text_dataset(
+ IterableDataset.from_generator(rows),
+ mode_label = "CPT",
+ split_name = "train",
+ eos_token = "<eos>",
+ append_eos = True,
+ )
+
+ # Column discovery reads one row; the filter must not scan further until training.
+ assert visited == [0]
+ assert next(iter(result.dataset))["text"] == "valid<eos>"
+
+
[email protected]("streaming", [False, True])
+def test_raw_blanks_are_dropped_before_eos_append(streaming):
+ texts = ["", " ", None, "hello", "\n", "world"]
+ dataset = (
+ IterableDataset.from_generator(lambda: ({"text": text} for text in texts))
+ if streaming
+ else Dataset.from_dict({"text": texts})
+ )
+ result = prepare_raw_text_dataset(
+ dataset,
+ mode_label = "CPT",
+ split_name = "train",
+ eos_token = "<eos>",
+ append_eos = True,
+ )
+ assert [row["text"] for row in result.dataset] == ["hello<eos>", "world<eos>"]
+ assert any("blank" in notice.message for notice in result.notices)
+
+
+def test_all_blank_raw_eval_split_is_left_for_the_trainer_to_skip():
+ result = prepare_raw_text_dataset(
+ Dataset.from_dict({"text": ["", " "]}),
+ mode_label = "CPT",
+ split_name = "eval",
+ eos_token = "<eos>",
+ append_eos = True,
+ )
+ assert len(result.dataset) == 0
+ assert any("blank" in notice.message for notice in result.notices)
+
+
+def test_all_blank_raw_train_split_still_fails():
+ with pytest.raises(ValueError, match = "at least one non-blank string"):
+ prepare_raw_text_dataset(Dataset.from_dict({"text": ["", " "]}), split_name = "train")
+
+
+def test_shared_formatter_passes_the_eval_split_to_raw_prep():
+ from utils.datasets import format_and_template_dataset
+
+ blank = Dataset.from_dict({"text": ["", " "]})
+ kwargs = dict(model_name = "m", tokenizer = None, format_type = "raw")
+ ev = format_and_template_dataset(blank, split_name = "eval", **kwargs)
+ assert ev["success"] and len(ev["dataset"]) == 0
+
+ with pytest.raises(ValueError, match = "at least one non-blank string"):
+ format_and_template_dataset(blank, **kwargs)
diff --git a/studio/backend/tests/test_training_raw_support.py b/studio/backend/tests/test_training_raw_support.py
index 7e817f33aaa..c708eb6295d 100644
--- a/studio/backend/tests/test_training_raw_support.py
+++ b/studio/backend/tests/test_training_raw_support.py
@@ -527,9 +527,24 @@ class TestTrainingRawSupport(unittest.TestCase):
self.assertEqual(result.dataset[0]["text"], "hello<eos>")
self.assertEqual(result.dataset[1]["text"], "world<eos>")
self.assertTrue(
- any("null or non-string 'text' values" in notice.message for notice in result.notices)
+ any(
+ "null, non-string or blank 'text' values" in notice.message
+ for notice in result.notices
+ )
)
+ def test_prepare_raw_text_dataset_rejects_all_blank_rows_before_appending_eos(self):
+ dataset = Dataset.from_dict({"text": ["", " "]})
+
+ with self.assertRaisesRegex(ValueError, "at least one non-blank string"):
+ prepare_raw_text_dataset(
+ dataset,
+ mode_label = "CPT",
+ split_name = "train",
+ eos_token = "<eos>",
+ append_eos = True,
+ )
+
if __name__ == "__main__":
unittest.main()
diff --git a/studio/backend/tests/test_training_token_forwarding.py b/studio/backend/tests/test_training_token_forwarding.py
index 2b43e2d902d..20b2c3c310f 100644
--- a/studio/backend/tests/test_training_token_forwarding.py
+++ b/studio/backend/tests/test_training_token_forwarding.py
@@ -17,6 +17,7 @@ from types import SimpleNamespace
from unittest.mock import MagicMock
import pytest
+from datasets import Dataset
torch = pytest.importorskip("torch")
@@ -208,3 +209,52 @@ def test_token_stays_absent_when_not_provided(monkeypatch):
assert len(load_calls) == 1
assert "token" not in load_calls[0]
assert probe_calls == []
+
+
+def _load_texts(
+ monkeypatch,
+ train_texts,
+ formatted = None,
+):
+ errors: list[str] = []
+ monkeypatch.setattr(
+ trainer_mod,
+ "load_dataset",
+ lambda **kwargs: Dataset.from_dict({"text": list(train_texts)}),
+ )
+ if formatted is not None:
+ monkeypatch.setattr(
+ trainer_mod,
+ "format_and_template_dataset",
+ lambda dataset, **kwargs: {
+ "dataset": formatted(dataset),
+ "detected_format": "test",
+ "success": True,
+ },
+ )
+ monkeypatch.setattr(
+ sys.modules["datasets"], "get_dataset_split_names", lambda **kwargs: ["train"]
+ )
+ trainer = _trainer()
+ trainer._update_progress = lambda **kwargs: errors.append(kwargs.get("error"))
+ return trainer.load_and_format_dataset("org/data", dataset_streaming = False), errors
+
+
+def test_empty_loaded_split_fails_before_format_detection(monkeypatch):
+ result, errors = _load_texts(monkeypatch, [])
+ assert result is None
+ assert "The training dataset has no rows. Add at least one example" in errors[-1]
+
+
+def test_formatting_that_drops_every_row_fails_clearly(monkeypatch):
+ result, errors = _load_texts(monkeypatch, ["a"], formatted = lambda ds: ds.select([]))
+ assert result is None
+ assert "has no rows after formatting" in errors[-1]
+
+
[email protected]("texts", [["hello"], ["", "hello"], [" ", "\n"]])
+def test_non_empty_train_split_is_left_to_the_trainer(monkeypatch, texts):
+ result, errors = _load_texts(monkeypatch, texts, formatted = lambda ds: ds)
+ assert result is not None
+ assert result[0]["dataset"]["text"] == texts
+ assert not any(errors)
diff --git a/studio/backend/utils/datasets/dataset_utils.py b/studio/backend/utils/datasets/dataset_utils.py
index 3612c63e78f..90a844b7b3e 100644
--- a/studio/backend/utils/datasets/dataset_utils.py
+++ b/studio/backend/utils/datasets/dataset_utils.py
@@ -363,13 +363,14 @@ def format_dataset(
num_proc = None,
auto_detect_custom = True,
custom_format_mapping = None,
+ split_name = None,
):
"""Formats dataset and returns {dataset, detected_format, final_format, chat_column, is_standardized, requires_manual_mapping, warnings}."""
multimodal_info = detect_multimodal_dataset(dataset)
if format_type == "raw":
- raw_result = prepare_raw_text_dataset(dataset)
+ raw_result = prepare_raw_text_dataset(dataset, split_name = split_name)
return {
"dataset": raw_result.dataset,
"detected_format": "raw_text",
@@ -795,6 +796,7 @@ def format_and_template_dataset(
batch_size = 1000,
num_proc = None,
progress_callback = None,
+ split_name = 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}."""
@@ -1036,6 +1038,7 @@ def format_and_template_dataset(
aliases_for_assistant = aliases_for_assistant,
batch_size = batch_size,
num_proc = num_proc,
+ split_name = split_name,
)
if dataset_info["final_format"] == "raw_text":
diff --git a/studio/backend/utils/datasets/raw_text.py b/studio/backend/utils/datasets/raw_text.py
index a30eed953e6..ce06eee7d8d 100644
--- a/studio/backend/utils/datasets/raw_text.py
+++ b/studio/backend/utils/datasets/raw_text.py
@@ -69,11 +69,17 @@ def _split_scope(split_name: str | None) -> str:
def _drop_invalid_text_rows(
- dataset: Dataset, *, mode_title: str, split_scope: str
+ dataset: Dataset,
+ *,
+ mode_title: str,
+ split_scope: str,
+ allow_empty: bool = False,
) -> tuple[Dataset, list[RawTextNotice]]:
- # Lazy filter — drops rows whose 'text' is null/non-string before they reach
+ # Lazy filter — drops rows whose 'text' is null/non-string/blank before they reach
# the tokenizer. Works on both Dataset and streaming IterableDataset.
- filtered_dataset = dataset.filter(lambda ex: isinstance(ex["text"], str))
+ filtered_dataset = dataset.filter(
+ lambda ex: isinstance(ex["text"], str) and bool(ex["text"].strip())
+ )
# Streaming datasets (IterableDataset) have no __len__, so we can't count the
# dropped rows or verify the result is non-empty without consuming the whole
@@ -82,8 +88,8 @@ def _drop_invalid_text_rows(
return filtered_dataset, [
RawTextNotice(
message = (
- f"{mode_title}: streaming dataset — rows with null or "
- f"non-string 'text' in {split_scope} are dropped on the fly."
+ f"{mode_title}: streaming dataset — rows with null, non-string "
+ f"or blank 'text' in {split_scope} are dropped on the fly."
),
level = "info",
)
@@ -93,17 +99,18 @@ def _drop_invalid_text_rows(
if not dropped_rows:
return filtered_dataset, []
- if len(filtered_dataset) == 0:
+ # An empty eval split falls through to the trainer, which warns and skips evaluation.
+ if len(filtered_dataset) == 0 and not allow_empty:
raise ValueError(
- f"{mode_title} training requires at least one string 'text' value "
- f"in {split_scope}; all {dropped_rows} rows were null or non-string."
+ f"{mode_title} training requires at least one non-blank string 'text' value "
+ f"in {split_scope}; all {dropped_rows} rows were null, non-string or blank."
)
return filtered_dataset, [
RawTextNotice(
message = (
- f"{mode_title}: dropped {dropped_rows:,} row(s) with null or "
- f"non-string 'text' values from {split_scope}"
+ f"{mode_title}: dropped {dropped_rows:,} row(s) with null, non-string "
+ f"or blank 'text' values from {split_scope}"
),
level = "warning",
update_status = True,
@@ -160,6 +167,7 @@ def prepare_raw_text_dataset(
dataset,
mode_title = mode_title,
split_scope = split_scope,
+ allow_empty = split_name == "eval",
)
notices.extend(invalid_row_notices)