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 Continued Pretraining on the body text column (#12790)

Nilay001fc665074d
diff --git a/studio/backend/core/training/trainer.py b/studio/backend/core/training/trainer.py
index 61d87006184..6bec5077ca6 100644
--- a/studio/backend/core/training/trainer.py
+++ b/studio/backend/core/training/trainer.py
@@ -2761,6 +2761,8 @@ class UnslothTrainer:
def _raw_mode_label() -> str:
return "CPT" if is_cpt else "raw text"
+ raw_text_column = {}
+
def _apply_raw_text_prep(ds: Dataset, split_name: str) -> Dataset:
try:
result = prepare_raw_text_dataset(
@@ -2769,6 +2771,7 @@ class UnslothTrainer:
split_name = split_name,
eos_token = getattr(self.tokenizer, "eos_token", None),
append_eos = True,
+ text_column = raw_text_column.get("train"),
)
except ValueError as exc:
error_msg = str(exc)
@@ -2778,12 +2781,14 @@ class UnslothTrainer:
for notice in result.notices:
if notice.level == "warning":
- logger.warning(notice.message)
if notice.update_status:
- self._update_progress(status_message = notice.message)
+ self._record_warning(notice.message)
+ else:
+ logger.warning(notice.message)
else:
logger.info(f"{notice.message}\n")
+ raw_text_column.setdefault(split_name, result.source_column)
return result.dataset
# S3 datasets download to a local temp dir, then use the local-file path below.
diff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.py
index 7fe970e72be..5c1fce92634 100644
--- a/studio/backend/core/training/worker.py
+++ b/studio/backend/core/training/worker.py
@@ -3089,6 +3089,8 @@ def _run_mlx_training(event_queue, stop_queue, config):
raise ValueError(f"Dataset format conversion failed: {'; '.join(errors)}")
if info.get("dropped_rows_warning"):
_send("warning", message = info["dropped_rows_warning"])
+ for message in info.get("run_warnings", []):
+ _send("warning", message = message)
dataset_final_format = str(info.get("final_format", "") or "").lower()
if eval_dataset is not None:
ev = format_and_template_dataset(
@@ -3100,6 +3102,7 @@ def _run_mlx_training(event_queue, stop_queue, config):
dataset_name = hf_dataset or "local",
custom_format_mapping = custom_format_mapping,
split_name = "eval",
+ raw_text_column = info.get("raw_text_column"),
)
if ev.get("success", True):
eval_dataset = ev.get("dataset", eval_dataset)
@@ -3118,6 +3121,8 @@ def _run_mlx_training(event_queue, stop_queue, config):
)
if ev.get("dropped_rows_warning"):
_send("warning", message = f"Eval dataset: {ev['dropped_rows_warning']}")
+ for message in ev.get("run_warnings", []):
+ _send("warning", message = message)
except ImportError:
_send("status", status_message = "Format helper unavailable, using raw dataset")
diff --git a/studio/backend/tests/test_csv_cells_as_written.py b/studio/backend/tests/test_csv_cells_as_written.py
index f800602cba0..acd8b6d5d89 100644
--- a/studio/backend/tests/test_csv_cells_as_written.py
+++ b/studio/backend/tests/test_csv_cells_as_written.py
@@ -147,6 +147,58 @@ def test_cpt_csv_still_trains_the_text_column_not_the_id(trainer, tmp_path):
assert list(dataset_info["dataset"]["text"]) == ["101</s>", "102</s>"]
+def test_cpt_csv_trains_the_body_column_and_keeps_the_warning(trainer, tmp_path):
+ path = tmp_path / "posts.csv"
+ path.write_text(
+ "title,body\nFirst post,The first post has a long body of text.\n"
+ "Second post,The second post has an even longer body of text.\n"
+ )
+
+ dataset_info, _ = trainer.load_and_format_dataset(None, local_datasets = [str(path)], is_cpt = True)
+
+ assert list(dataset_info["dataset"]["text"]) == [
+ "The first post has a long body of text.</s>",
+ "The second post has an even longer body of text.</s>",
+ ]
+ assert any(
+ w.startswith("CPT:") and "auto-selecting 'body'" in w
+ for w in trainer.training_progress.warnings
+ )
+
+
+def test_cpt_eval_csv_uses_the_column_the_train_csv_chose(trainer, tmp_path):
+ train = tmp_path / "train.csv"
+ train.write_text(
+ "title,body\nA,The first post has a long body.\nB,The second post has a body.\n"
+ )
+ eval_ = tmp_path / "eval.csv"
+ eval_.write_text("title,body\nA much longer title than the body,Short.\n")
+
+ dataset_info, eval_dataset = trainer.load_and_format_dataset(
+ None,
+ local_datasets = [str(train)],
+ local_eval_datasets = [str(eval_)],
+ eval_steps = 10,
+ is_cpt = True,
+ )
+
+ assert list(dataset_info["dataset"]["text"])[0] == "The first post has a long body.</s>"
+ assert list(eval_dataset["text"]) == ["Short.</s>"]
+
+
+def test_cpt_csv_with_an_id_column_trains_the_text_without_a_column_warning(trainer, tmp_path):
+ path = tmp_path / "docs.csv"
+ path.write_text("id,passage\n1,The first document.\n2,The second document.\n")
+
+ dataset_info, _ = trainer.load_and_format_dataset(None, local_datasets = [str(path)], is_cpt = True)
+
+ assert list(dataset_info["dataset"]["text"]) == [
+ "The first document.</s>",
+ "The second document.</s>",
+ ]
+ assert not any("auto-selecting" in w for w in trainer.training_progress.warnings)
+
+
def test_csv_files_missing_a_column_still_load_together(trainer, tmp_path):
wide = tmp_path / "a.csv"
wide.write_text("instruction,input,output\nZip code?,Holtsville,00501\n")
diff --git a/studio/backend/tests/test_raw_text_column_choice.py b/studio/backend/tests/test_raw_text_column_choice.py
new file mode 100644
index 00000000000..94ec7cea649
--- /dev/null
+++ b/studio/backend/tests/test_raw_text_column_choice.py
@@ -0,0 +1,74 @@
+# 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
+
+from utils.datasets.raw_text import prepare_raw_text_dataset
+
+CODE = "def f():\n return 1\n" * 20
+ROWS = {
+ "repo_name": ["pansapiens/mytardis", "a/b"],
+ "path": ["tardis/models.py", "x.py"],
+ "content": [CODE, CODE + "print(f())\n"],
+}
+
+
[email protected]("streaming", [False, True])
+def test_raw_text_trains_the_body_column_not_the_first_string_column(streaming):
+ dataset = Dataset.from_dict(ROWS)
+ if streaming:
+ dataset = dataset.to_iterable_dataset()
+
+ result = prepare_raw_text_dataset(dataset, mode_label = "CPT", split_name = "train")
+
+ assert [row["text"] for row in result.dataset] == ROWS["content"]
+ assert any("auto-selecting 'content'" in notice.message for notice in result.notices)
+
+
+def test_raw_text_keeps_the_first_column_when_no_column_is_longer():
+ result = prepare_raw_text_dataset(
+ Dataset.from_dict({"content": ["101", "102"], "source": ["corpus", "corpus"]})
+ )
+ assert list(result.dataset["text"]) == ["101", "102"]
+
+
+def test_raw_text_uses_the_requested_column_without_the_choice_warning():
+ result = prepare_raw_text_dataset(
+ Dataset.from_dict({"title": ["A much longer title"], "body": ["Short."]}),
+ text_column = "body",
+ )
+ assert list(result.dataset["text"]) == ["Short."]
+ assert result.source_column == "body"
+ assert not any("auto-selecting" in notice.message for notice in result.notices)
+
+
+def test_raw_text_scores_unspaced_scripts_by_length_not_by_spaces():
+ doc = "自然语言处理是计算机科学领域与人工智能领域中的一个重要方向。"
+ result = prepare_raw_text_dataset(
+ Dataset.from_dict({"content": [doc, doc], "source": ["news article", "news article"]})
+ )
+ assert list(result.dataset["text"]) == [doc, doc]
+
+
+def test_raw_format_eval_split_reuses_the_train_column():
+ from utils.datasets.dataset_utils import format_and_template_dataset
+
+ train = format_and_template_dataset(
+ Dataset.from_dict({"title": ["A"], "body": ["The body has the most words."]}),
+ model_name = "test",
+ tokenizer = None,
+ format_type = "raw",
+ )
+ eval_ = format_and_template_dataset(
+ Dataset.from_dict({"title": ["A much longer title"], "body": ["Short."]}),
+ model_name = "test",
+ tokenizer = None,
+ format_type = "raw",
+ split_name = "eval",
+ raw_text_column = train["raw_text_column"],
+ )
+ assert train["raw_text_column"] == "body"
+ assert any("auto-selecting 'body'" in w for w in train["run_warnings"])
+ assert not any("auto-selecting" in w for w in eval_["run_warnings"])
+ assert list(eval_["dataset"]["text"]) == ["Short."]
diff --git a/studio/backend/utils/datasets/dataset_utils.py b/studio/backend/utils/datasets/dataset_utils.py
index 90a844b7b3e..f12986d124b 100644
--- a/studio/backend/utils/datasets/dataset_utils.py
+++ b/studio/backend/utils/datasets/dataset_utils.py
@@ -364,13 +364,16 @@ def format_dataset(
auto_detect_custom = True,
custom_format_mapping = None,
split_name = None,
+ raw_text_column = 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, split_name = split_name)
+ raw_result = prepare_raw_text_dataset(
+ dataset, split_name = split_name, text_column = raw_text_column
+ )
return {
"dataset": raw_result.dataset,
"detected_format": "raw_text",
@@ -381,6 +384,12 @@ def format_dataset(
"is_image": multimodal_info["is_image"],
"multimodal_info": multimodal_info,
"warnings": [notice.message for notice in raw_result.notices],
+ "raw_text_column": raw_result.source_column,
+ "run_warnings": [
+ notice.message
+ for notice in raw_result.notices
+ if notice.level == "warning" and notice.update_status
+ ],
}
if custom_format_mapping:
@@ -797,6 +806,7 @@ def format_and_template_dataset(
num_proc = None,
progress_callback = None,
split_name = None,
+ raw_text_column = 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}."""
@@ -1039,6 +1049,7 @@ def format_and_template_dataset(
batch_size = batch_size,
num_proc = num_proc,
split_name = split_name,
+ raw_text_column = raw_text_column,
)
if dataset_info["final_format"] == "raw_text":
@@ -1054,6 +1065,8 @@ def format_and_template_dataset(
"warnings": dataset_info.get("warnings", []),
"errors": [],
"summary": summary,
+ "raw_text_column": dataset_info.get("raw_text_column"),
+ "run_warnings": dataset_info.get("run_warnings", []),
}
detected = dataset_info.get("detected_format", "unknown")
diff --git a/studio/backend/utils/datasets/raw_text.py b/studio/backend/utils/datasets/raw_text.py
index df534e03da3..93f57c39f7e 100644
--- a/studio/backend/utils/datasets/raw_text.py
+++ b/studio/backend/utils/datasets/raw_text.py
@@ -8,6 +8,8 @@
from __future__ import annotations
from dataclasses import dataclass
+import re
+from itertools import islice
from typing import Literal, TYPE_CHECKING
from .cells import typed_csv_columns
@@ -27,6 +29,7 @@ class RawTextNotice:
class RawTextPreparationResult:
dataset: Dataset
notices: list[RawTextNotice]
+ source_column: str = "text"
def resolve_column_names(dataset) -> list[str]:
@@ -66,10 +69,28 @@ def _string_columns(dataset: Dataset) -> list[str]:
return string_cols
-def _pick_text_column(dataset: Dataset, string_cols: list[str]) -> str:
+def _text_columns(dataset: Dataset, string_cols: list[str]) -> list[str]:
# Every column of an uploaded CSV is text; skip one pandas would have typed, like an id.
typed = typed_csv_columns(dataset)
- return next((col for col in string_cols if col not in typed), string_cols[0])
+ return [col for col in string_cols if col not in typed] or string_cols
+
+
+# One unit per CJK / kana / Thai character (scripts written without spaces), else per word, with
+# unspaced runs cut every 16 characters: minified code counts by length, an id or hash stays short.
+_UNSPACED = "\u0e00-\u0e7f\u3040-\u30ff\u3400-\u9fff\uf900-\ufaff"
+_TEXT_UNIT = re.compile(f"[{_UNSPACED}]|[^\\s{_UNSPACED}]{{1,16}}")
+
+
+def _pick_text_column(dataset: Dataset, text_cols: list[str]) -> str:
+ if len(text_cols) == 1:
+ return text_cols[0]
+ rows = list(islice(dataset.select_columns(text_cols), 100))
+ return max(
+ text_cols,
+ key = lambda col: sum(
+ len(_TEXT_UNIT.findall(row[col])) for row in rows if isinstance(row[col], str)
+ ),
+ )
def _split_scope(split_name: str | None) -> str:
@@ -133,10 +154,12 @@ def prepare_raw_text_dataset(
split_name: str | None = None,
eos_token: str | None = None,
append_eos: bool = False,
+ text_column: str | None = None,
) -> RawTextPreparationResult:
notices: list[RawTextNotice] = []
- mode_title = mode_label.capitalize()
+ mode_title = mode_label[:1].upper() + mode_label[1:]
split_scope = _split_scope(split_name)
+ renamed_col = "text"
col_names = resolve_column_names(dataset)
if "text" not in col_names:
@@ -147,13 +170,18 @@ def prepare_raw_text_dataset(
f"was found in {split_scope} (columns: {col_names})."
)
- renamed_col = _pick_text_column(dataset, string_cols)
- if len(string_cols) > 1:
+ text_cols = _text_columns(dataset, string_cols)
+ # An eval split reuses the train split's column: per-split word counts can disagree.
+ if text_column in string_cols:
+ renamed_col = text_column
+ else:
+ renamed_col = _pick_text_column(dataset, text_cols)
+ if len(text_cols) > 1 and renamed_col != text_column:
notices.append(
RawTextNotice(
message = (
- f"{mode_title}: dataset has {len(string_cols)} string "
- f"columns ({string_cols}); auto-selecting '{renamed_col}' "
+ f"{mode_title}: dataset has {len(text_cols)} string "
+ f"columns ({text_cols}); auto-selecting '{renamed_col}' "
"as the training text. Rename the intended column to "
"'text' to override."
),
@@ -198,4 +226,4 @@ def prepare_raw_text_dataset(
dataset = dataset.map(_append_eos)
- return RawTextPreparationResult(dataset = dataset, notices = notices)
+ return RawTextPreparationResult(dataset = dataset, notices = notices, source_column = renamed_col)