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: pass the request hf_token to the training dataset load (#8924)
Krish Patel789b25a5fa59
diff --git a/studio/backend/core/training/trainer.py b/studio/backend/core/training/trainer.pyindex be63f934464..7a1e5ec777b 100644--- a/studio/backend/core/training/trainer.py+++ b/studio/backend/core/training/trainer.py@@ -2504,6 +2504,7 @@ class UnslothTrainer:dataset_local_path: Optional[str] = None,dataset_revision: Optional[str] = None,require_exact_resume_resources: bool = False,+ hf_token: Optional[str] = None,max_train_rows: Optional[int] = None,max_train_rows_seed: int = 3407,) -> Optional[tuple]:@@ -2518,6 +2519,9 @@ class UnslothTrainer:Returns (dataset_info, eval_dataset) or None on error; eval_datasetmay be None if no eval split is available.++ hf_token must reach every load_dataset and get_dataset_split_names call below,+ or a gated dataset is read under the ambient HF_TOKEN instead of the request."""from core.training.s3_dataset import S3DownloadCancelled@@ -2644,6 +2648,8 @@ class UnslothTrainer:load_kwargs["name"] = subsetif dataset_revision:load_kwargs["revision"] = dataset_revision+ if hf_token:+ load_kwargs["token"] = hf_tokenif dataset_streaming:self._update_progress(status_message = f"Streaming dataset: {dataset_source}...")@@ -2787,6 +2793,8 @@ class UnslothTrainer:eval_load_kwargs["name"] = subsetif dataset_revision:eval_load_kwargs["revision"] = dataset_revision+ if hf_token:+ eval_load_kwargs["token"] = hf_tokenif dataset_streaming:# load_dataset(streaming=True) returns an IterableDataset without validating the@@ -2799,6 +2807,8 @@ class UnslothTrainer:probe_kwargs["config_name"] = subsetif dataset_revision:probe_kwargs["revision"] = dataset_revision+ if hf_token:+ probe_kwargs["token"] = hf_tokentry:available_splits = get_dataset_split_names(**probe_kwargs)except Exception as probe_err:@@ -2898,6 +2908,7 @@ class UnslothTrainer:train_split or "train"),revision = dataset_revision,+ token = hf_token,strict_split_loading = (require_exact_resume_resources and dataset_loaded_from_cache),@@ -3161,6 +3172,7 @@ class UnslothTrainer:split_loader: Optional[Callable[[str], Dataset]] = None,excluded_split: Any = None,revision: Optional[str] = None,+ token: Optional[str] = None,strict_split_loading: bool = False,) -> Optional[Dataset]:"""Auto-detect an eval split from an HF dataset (named split only)."""@@ -3173,6 +3185,8 @@ class UnslothTrainer:load_kwargs["config_name"] = subsetif revision:load_kwargs["revision"] = revision+ if token:+ load_kwargs["token"] = tokenavailable_splits = get_dataset_split_names(**load_kwargs)elif available_splits is None or split_loader is None:raise ValueError("Cached split names and loader must be provided together")@@ -3193,6 +3207,8 @@ class UnslothTrainer:eval_load_kwargs["name"] = subsetif revision:eval_load_kwargs["revision"] = revision+ if token:+ eval_load_kwargs["token"] = tokencandidate_ds = load_dataset(**eval_load_kwargs)if len(candidate_ds) >= MIN_EVAL_ROWS:logger.info(diff --git a/studio/backend/core/training/training.py b/studio/backend/core/training/training.pyindex 601f03b82eb..24e6d4e939b 100644--- a/studio/backend/core/training/training.py+++ b/studio/backend/core/training/training.py@@ -795,11 +795,12 @@ class _MLXTrainerAdapter:dataset_local_path: Optional[str] = None,dataset_revision: Optional[str] = None,require_exact_resume_resources: bool = False,+ hf_token: Optional[str] = None,max_train_rows: Optional[int] = None,max_train_rows_seed: int = 3407,) -> Optional[tuple]:- # Signature must match UnslothTrainer: the MLX worker loads its own data and derives the row bound- # from its config, so the two bound arguments are accepted and deliberately not forwarded.+ # Signature must match UnslothTrainer. The MLX worker gets the token from _model_config, loads its+ # own data, and derives the row bound, so these arguments are accepted and not forwarded here.self._dataset_config = {"hf_dataset": dataset_source or "","local_datasets": local_datasets,diff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.pyindex 9431d49a12d..76ab16964bd 100644--- a/studio/backend/core/training/worker.py+++ b/studio/backend/core/training/worker.py@@ -4337,6 +4337,7 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->config.get("require_exact_resume_resources")or config.get("require_exact_dataset_resource")),+ hf_token = hf_token,max_train_rows = max_train_rows,max_train_rows_seed = max_train_rows_seed,)diff --git a/studio/backend/tests/test_training_cached_start.py b/studio/backend/tests/test_training_cached_start.pyindex 583cf433b8f..6deb615e14b 100644--- a/studio/backend/tests/test_training_cached_start.py+++ b/studio/backend/tests/test_training_cached_start.py@@ -3168,6 +3168,19 @@ def test_mlx_adapter_accepts_and_preserves_dataset_cache_pins():assert adapter._dataset_config["require_exact_dataset_resource"] is True+def test_mlx_adapter_accepts_dataset_hf_token():+ from core.training.training import _MLXTrainerAdapter++ adapter = _MLXTrainerAdapter()++ result = adapter.load_and_format_dataset(+ "org/dataset",+ hf_token = "hf_explicit",+ )++ assert result is not None++def test_strict_resume_cached_dataset_none_never_loads_remote():from core.training import workerconfig = {diff --git a/studio/backend/tests/test_training_token_forwarding.py b/studio/backend/tests/test_training_token_forwarding.pynew file mode 100644index 00000000000..2b43e2d902d--- /dev/null+++ b/studio/backend/tests/test_training_token_forwarding.py@@ -0,0 +1,210 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""load_and_format_dataset must forward an explicit hf_token to every remote call.++Without it, load_dataset and get_dataset_split_names resolve None through+huggingface_hub.get_token() and read a gated dataset under the ambient HF_TOKEN+instead of the request identity. The no-token case is pinned too: that env fallback+is the only credential a caller without a token has."""++from __future__ import annotations++import importlib+import sys+import types+from types import SimpleNamespace+from unittest.mock import MagicMock++import pytest++torch = pytest.importorskip("torch")+++_STUBBED: list[str] = []+++def _stub_if_missing(name, attrs):+ """Stub a dep the backend pytest job does not install, as test_audio_type_inconclusive.py does.++ core.training.trainer imports unsloth and trl at module scope; that job installs studio.txt+ plus torch and transformers and stops. __spec__ = None keeps the trainer's own+ _ensure_real_packages namespace-shadow guard a no-op on the stub.+ """+ if name in sys.modules:+ return+ try:+ importlib.import_module(name)+ return+ except Exception: # noqa: BLE001 - unusable here either way, so stub it+ 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"))++import core.training.trainer as trainer_mod # noqa: E402++# Trainer holds its own references now; leaving the stubs would run the whole suite on them.+for _name in reversed(_STUBBED):+ sys.modules.pop(_name, None)+++_load_and_format_dataset = trainer_mod.UnslothTrainer.load_and_format_dataset+_auto_detect_eval = trainer_mod.UnslothTrainer._auto_detect_eval_split_from_hf+++class _Dataset:+ """The minimum a loaded dataset must look like on the paths under test."""++ column_names = ["text"]++ def __len__(self):+ # >= MIN_EVAL_ROWS (16) so an auto-detected candidate split is accepted.+ return 16+++def _trainer():+ """A stand-in carrying only what load_and_format_dataset reads."""+ trainer = SimpleNamespace(+ should_stop = False,+ _audio_type = None,+ is_audio_vlm = False,+ is_vlm = False,+ model_name = "org/model",+ tokenizer = None,+ _update_progress = lambda **kwargs: None,+ _resolve_eval_split_from_dataset = lambda dataset: None,+ )+ trainer._auto_detect_eval_split_from_hf = _auto_detect_eval.__get__(trainer)+ trainer.load_and_format_dataset = _load_and_format_dataset.__get__(trainer)+ return trainer+++def _patch_dataset_loading(monkeypatch, load_calls, probe_calls):+ def fake_load_dataset(**kwargs):+ load_calls.append(kwargs)+ return _Dataset()++ def fake_split_names(**kwargs):+ probe_calls.append(kwargs)+ return ["train", "validation"]++ monkeypatch.setattr(trainer_mod, "load_dataset", fake_load_dataset)+ monkeypatch.setattr(+ trainer_mod,+ "format_and_template_dataset",+ lambda dataset, **kwargs: {"dataset": dataset, "detected_format": "test", "success": True},+ )+ monkeypatch.setattr(sys.modules["datasets"], "get_dataset_split_names", fake_split_names)+++def test_streaming_path_forwards_explicit_token(monkeypatch):+ load_calls: list[dict] = []+ probe_calls: list[dict] = []+ _patch_dataset_loading(monkeypatch, load_calls, probe_calls)++ result = _trainer().load_and_format_dataset(+ "org/gated",+ subset = "en",+ train_split = "train",+ eval_split = "validation",+ dataset_streaming = True,+ eval_steps = 1,+ dataset_revision = "dataset-commit",+ hf_token = "hf_0123456789abcdef",+ )++ assert result is not None+ assert probe_calls == [+ {+ "path": "org/gated",+ "config_name": "en",+ "revision": "dataset-commit",+ "token": "hf_0123456789abcdef",+ }+ ]+ assert [call.get("split") for call in load_calls] == ["train", "validation"]+ for call in load_calls:+ assert call["path"] == "org/gated"+ assert call["name"] == "en"+ assert call["revision"] == "dataset-commit"+ assert call["token"] == "hf_0123456789abcdef"+ assert call["streaming"] is True+++def test_eager_path_forwards_explicit_token(monkeypatch):+ load_calls: list[dict] = []+ probe_calls: list[dict] = []+ _patch_dataset_loading(monkeypatch, load_calls, probe_calls)++ result = _trainer().load_and_format_dataset(+ "org/gated",+ dataset_streaming = False,+ hf_token = "hf_0123456789abcdef",+ )++ assert result is not None+ assert len(load_calls) == 1+ assert load_calls[0]["token"] == "hf_0123456789abcdef"+ assert "streaming" not in load_calls[0]+ assert probe_calls == []+++def test_auto_detect_eval_forwards_explicit_token(monkeypatch):+ load_calls: list[dict] = []+ probe_calls: list[dict] = []+ _patch_dataset_loading(monkeypatch, load_calls, probe_calls)++ result = _trainer().load_and_format_dataset(+ "org/gated",+ subset = "en",+ dataset_streaming = False,+ eval_steps = 1,+ dataset_revision = "dataset-commit",+ hf_token = "hf_0123456789abcdef",+ )++ assert result is not None+ # Auto-detect (no explicit eval_split) probes the splits, then loads a candidate.+ assert probe_calls == [+ {+ "path": "org/gated",+ "config_name": "en",+ "revision": "dataset-commit",+ "token": "hf_0123456789abcdef",+ }+ ]+ assert [call.get("split") for call in load_calls] == ["train", "validation"]+ for call in load_calls:+ assert call["path"] == "org/gated"+ assert call["name"] == "en"+ assert call["revision"] == "dataset-commit"+ assert call["token"] == "hf_0123456789abcdef"+ assert "streaming" not in call+++def test_token_stays_absent_when_not_provided(monkeypatch):+ load_calls: list[dict] = []+ probe_calls: list[dict] = []+ _patch_dataset_loading(monkeypatch, load_calls, probe_calls)++ result = _trainer().load_and_format_dataset(+ "org/dataset",+ dataset_streaming = True,+ )++ assert result is not None+ assert len(load_calls) == 1+ assert "token" not in load_calls[0]+ assert probe_calls == []diff --git a/unsloth_cli/commands/train.py b/unsloth_cli/commands/train.pyindex 4925b30e41a..8b6aac4f21f 100644--- a/unsloth_cli/commands/train.py+++ b/unsloth_cli/commands/train.py@@ -139,6 +139,7 @@ def train(dataset_source = cfg.data.dataset or "",format_type = cfg.data.format_type,local_datasets = cfg.data.local_dataset,+ hf_token = hf_token,)if result is None:typer.echo("Dataset load failed", err = True)