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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: read streamed dataset slices in batches instead of row by row (#16083)
Daniel Han6a87eb76391c
diff --git a/studio/backend/core/training/trainer.py b/studio/backend/core/training/trainer.pyindex 4769ade5130..ae16e00aeab 100644--- a/studio/backend/core/training/trainer.py+++ b/studio/backend/core/training/trainer.py@@ -84,6 +84,7 @@ from utils.datasets.completion_masking import (truncated_drop_cause,)from utils.datasets.iterable import is_streaming_dataset as detect_streaming_dataset+from utils.datasets.iterable import take_rowsfrom utils.datasets.pretokenized import (PRETOKENIZED_FORMAT,has_custom_labels,@@ -3462,7 +3463,7 @@ class UnslothTrainer:)stream = load_dataset(**load_kwargs, streaming = True)dataset_attestation_source = stream- dataset = Dataset.from_list(list(stream.take(rows_to_stream)))+ dataset = Dataset.from_list(take_rows(stream, rows_to_stream))logger.info(f"[dataset-slice] Downloaded {len(dataset)} rows "f"(requested {rows_to_stream})\n"diff --git a/studio/backend/hub/utils/dataset_cache.py b/studio/backend/hub/utils/dataset_cache.pyindex 80dbb3886d2..25d763cf9a8 100644--- a/studio/backend/hub/utils/dataset_cache.py+++ b/studio/backend/hub/utils/dataset_cache.py@@ -521,6 +521,8 @@ def load_cached_hf_dataset(if token:kwargs["token"] = tokenif stream_limited_snapshot:+ from utils.datasets.iterable import take_rows+kwargs["streaming"] = Truewith tempfile.TemporaryDirectory(prefix = "unsloth-dataset-slice-") as cache_dir:kwargs["cache_dir"] = cache_dir@@ -542,7 +544,7 @@ def load_cached_hf_dataset({name: SplitInfo(name = name) for name in available_splits})split_identity = getattr(stream, "split", None)- rows = list(stream.take(row_limit))+ rows = take_rows(stream, row_limit)del stream, streamsfrom datasets import Datasetdiff --git a/studio/backend/tests/test_take_rows_batched.py b/studio/backend/tests/test_take_rows_batched.pynew file mode 100644index 00000000000..53537d8c850--- /dev/null+++ b/studio/backend/tests/test_take_rows_batched.py@@ -0,0 +1,200 @@+# 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 io+import json+import sys+from pathlib import Path++import pytest++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++datasets = pytest.importorskip("datasets")+pa = pytest.importorskip("pyarrow")+from datasets import ClassLabel, Dataset, Features, IterableDataset, Value, load_dataset++from utils.datasets.iterable import take_rows++_ALPACA = [+ {"instruction": f"i{i}", "input": "" if i % 3 else f"x{i}", "output": "o" * (i % 7)}+ for i in range(2500)+]+_ALPACA_FEATURES = Features(+ {"instruction": Value("string"), "input": Value("string"), "output": Value("string")}+)+++def _jsonl(tmp_path, name, rows):+ path = tmp_path / name+ path.write_text("".join(json.dumps(row) + "\n" for row in rows), encoding = "utf-8")+ return str(path)+++def _hetero():+ for i in range(1500):+ yield {"a": i} if i % 2 else {"a": i, "extra": str(i)}+++def _streams(tmp_path):+ alpaca = _jsonl(tmp_path, "alpaca.jsonl", _ALPACA)+ first = _jsonl(tmp_path, "d1.jsonl", [{"a": i, "b": None} for i in range(700)])+ second = _jsonl(tmp_path, "d2.jsonl", [{"a": i, "b": f"s{i}"} for i in range(700)])+ nested = tmp_path / "nested.parquet"+ Dataset.from_list(+ [+ {+ "messages": [+ {"role": "user", "content": f"q{i}"},+ {"role": "assistant", "content": f"a{i}"},+ ],+ "meta": {"k": i, "t": [1, 2] if i % 2 else []},+ "label": i % 3,+ }+ for i in range(1300)+ ]+ ).cast_column("label", ClassLabel(names = ["x", "y", "z"])).to_parquet(str(nested))+ return {+ "json_untyped": lambda: load_dataset(+ "json", data_files = alpaca, split = "train", streaming = True+ ),+ "json_typed": lambda: load_dataset(+ "json", data_files = alpaca, split = "train", streaming = True, features = _ALPACA_FEATURES+ ),+ "json_two_files_typed": lambda: load_dataset(+ "json",+ data_files = [first, second],+ split = "train",+ streaming = True,+ features = Features({"a": Value("int64"), "b": Value("string")}),+ ),+ "parquet_nested_classlabel": lambda: load_dataset(+ "parquet", data_files = str(nested), split = "train", streaming = True+ ),+ "generator_untyped_mixed_keys": lambda: IterableDataset.from_generator(_hetero),+ "generator_typed": lambda: IterableDataset.from_generator(+ _hetero, features = Features({"a": Value("int32"), "extra": Value("string")})+ ),+ "sharded_iterable": lambda: Dataset.from_list(_ALPACA).to_iterable_dataset(num_shards = 4),+ "formatted_numpy": lambda: load_dataset(+ "json", data_files = alpaca, split = "train", streaming = True, features = _ALPACA_FEATURES+ ).with_format("numpy"),+ }++[email protected]("count", [0, 1, 999, 1000, 1001, 2345, 10**6])+def test_take_rows_matches_row_iteration(tmp_path, count):+ for name, make in _streams(tmp_path).items():+ expected = list(make().take(count))+ got = take_rows(make(), count)+ if name == "formatted_numpy":+ assert repr(got) == repr(expected), name+ continue+ assert got == expected, name+ assert [list(row) for row in got] == [list(row) for row in expected], name+ if expected:+ base, head = Dataset.from_list(expected), Dataset.from_list(got)+ assert head.features == base.features, name+ assert head._fingerprint == base._fingerprint, name+++def test_take_rows_matches_images(tmp_path):+ pil = pytest.importorskip("PIL.Image")+ from datasets import Image++ rows = []+ for i in range(40):+ buffer = io.BytesIO()+ pil.new("RGB", (4 + i % 5, 3), (i, 0, 0)).save(buffer, format = "PNG")+ rows.append({"image": {"bytes": buffer.getvalue(), "path": None}, "text": f"t{i}"})+ path = tmp_path / "images.parquet"+ Dataset.from_list(rows).cast_column("image", Image()).to_parquet(str(path))++ def make():+ return load_dataset("parquet", data_files = str(path), split = "train", streaming = True)++ expected = list(make().take(25))+ got = take_rows(make(), 25)+ assert [row["text"] for row in got] == [row["text"] for row in expected]+ assert [row["image"].tobytes() for row in got] == [row["image"].tobytes() for row in expected]+ assert [row["image"].size for row in got] == [row["image"].size for row in expected]+++def test_take_rows_builds_the_schema_per_batch_not_per_row(tmp_path, monkeypatch):+ path = _jsonl(tmp_path, "alpaca.jsonl", _ALPACA)+ calls = []+ original = Features.arrow_schema++ def counting(self):+ calls.append(1)+ return original.fget(self)++ monkeypatch.setattr(Features, "arrow_schema", property(counting))++ def make():+ return load_dataset(+ "json", data_files = path, split = "train", streaming = True, features = _ALPACA_FEATURES+ )++ expected = list(make().take(2345))+ row_by_row = len(calls)+ calls.clear()+ assert take_rows(make(), 2345) == expected+ # datasets 3.4 builds the schema once per stream on both paths; later releases build it per row.+ assert len(calls) <= min(10, row_by_row)+++def test_take_rows_matches_when_files_drift_from_declared_features(tmp_path):+ # README features vs differing per-file schemas: datasets 4.3 raises ArrowInvalid batched, so take_rows falls back.+ (tmp_path / "data").mkdir()+ (tmp_path / "README.md").write_text(+ "---\ndataset_info:\n features:\n - name: a\n dtype: int64\n - name: b\n"+ " dtype: string\n - name: c\n dtype: float64\nconfigs:\n- config_name: default\n"+ " data_files:\n - split: train\n path: data/*.jsonl\n---\n",+ encoding = "utf-8",+ )+ _jsonl(tmp_path / "data", "1.jsonl", [{"a": i, "b": None, "c": i} for i in range(600)])+ _jsonl(tmp_path / "data", "2.jsonl", [{"b": f"s{i}", "a": i, "c": i + 0.5} for i in range(600)])++ def make():+ return load_dataset(str(tmp_path), split = "train", streaming = True)++ assert make().features+ for count in (599, 1100, 5000):+ expected = list(make().take(count))+ got = take_rows(make(), count)+ assert got == expected+ assert [list(row) for row in got] == [list(row) for row in expected]+++def test_take_rows_reads_row_by_row_when_batches_disagree():+ rows = [{"a": 1}, {"a": 2}, {"a": 3}]++ class Taken:+ def __init__(self, count):+ self.count = count++ def iter(self, batch_size):+ yield {"a": [1]}+ raise pa.ArrowInvalid("Schema at index 1 was different")++ def __iter__(self):+ return iter(rows[: self.count])++ class Stream:+ features = {"a": object()}++ def take(self, count):+ return Taken(count)++ assert take_rows(Stream(), 2) == [{"a": 1}, {"a": 2}]+++def test_streamed_slices_read_through_take_rows():+ backend = Path(_BACKEND_DIR)+ for relative in ("core/training/trainer.py", "hub/utils/dataset_cache.py"):+ source = (backend / relative).read_text(encoding = "utf-8")+ assert "list(stream.take(" not in source, relative+ assert "take_rows(stream, " in source, relativediff --git a/studio/backend/utils/datasets/iterable.py b/studio/backend/utils/datasets/iterable.pyindex 8408ef75f30..95db21ba982 100644--- a/studio/backend/utils/datasets/iterable.py+++ b/studio/backend/utils/datasets/iterable.py@@ -18,3 +18,30 @@ def is_streaming_dataset(dataset) -> bool:return isinstance(dataset, TorchIterableDataset)except ImportError:return False+++def take_rows(+ stream,+ count: int,+ batch_size: int = 1000,+) -> list:+ """``list(stream.take(count))``, batched for typed streams: per-row reads rebuild the Arrow schema each row.++ Untyped, formatted (stacked-array batches) or schema-mismatched (ArrowException) streams read row by row.+ """+ taken = stream.take(count)+ if (+ not getattr(stream, "features", None)+ or getattr(taken, "_formatting", "unknown") is not None+ ):+ return list(taken)+ import pyarrow as pa++ rows = []+ try:+ for batch in taken.iter(batch_size = batch_size):+ columns = list(batch)+ rows.extend(dict(zip(columns, row)) for row in zip(*batch.values()))+ except pa.ArrowException:+ return list(stream.take(count))+ return rows