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
Return no base model, not the bare `unsloth/` org, for a timestamp-less run directory (#9753)
Rajarshi Datta00e265c42728
diff --git a/studio/backend/tests/test_base_model_dir_name_fallback.py b/studio/backend/tests/test_base_model_dir_name_fallback.pynew file mode 100644index 00000000000..c67762ae250--- /dev/null+++ b/studio/backend/tests/test_base_model_dir_name_fallback.py@@ -0,0 +1,264 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The ``unsloth_<model>_<timestamp>`` directory-name fallback for base model detection.++The last resort in ``get_base_model_from_checkpoint`` / ``get_base_model_from_lora`` and in the+two resolvers in ``utils.transformers_version``. It used to slice a two-segment+``unsloth_<model>`` name down to nothing and return the bogus repo id ``unsloth/``.++The round-trip tests are the real specification: a name we write must parse back to the model+it was written from.+"""++import importlib.util+import json+import sys+import types++import pytest++# Keep this runnable where optional logging deps are absent. Probe the installed distribution,+# not sys.modules: structlog is a real dependency, and stubbing it merely because nothing has+# imported it yet would replace the package for every test collected afterwards.+if importlib.util.find_spec("structlog") is None: # pragma: no cover - minimal environments++ class _DummyLogger:+ def __getattr__(self, _name):+ return lambda *args, **kwargs: None++ sys.modules["structlog"] = types.SimpleNamespace(+ BoundLogger = _DummyLogger,+ get_logger = lambda *args, **kwargs: _DummyLogger(),+ )++from utils.models.model_config import ( # noqa: E402+ get_base_model_from_checkpoint,+ get_base_model_from_lora,+)+from utils.training_runs import ( # noqa: E402+ base_model_from_run_dir_name,+ build_default_output_dir_name,+)+++ "dir_name,expected",+ [+ # The shape the heuristic is written for.+ ("unsloth_Qwen3-8B_1771227800", "unsloth/Qwen3-8B"),+ # A hand-made or foreign folder may carry a date-time stamp instead of an epoch.+ ("unsloth_Qwen3-8B_20260101-120000", "unsloth/Qwen3-8B"),+ ("unsloth_Qwen3-8B_20260101", "unsloth/Qwen3-8B"),+ # Underscores inside the model name survive the round trip.+ ("unsloth_llama_3_8b_1771227800", "unsloth/llama_3_8b"),+ # No model segment between the prefix and the timestamp: the originally reported bug.+ ("unsloth_Qwen3-8B", None),+ ("unsloth_", None),+ ("unsloth", None),+ ("unsloth__1771227800", None),+ # A doubled separator means the name really does start with '_', which HF allows.+ # Stripping it would resolve a different, equally valid repo.+ ("unsloth__Qwen3-8B_1771227800", "unsloth/_Qwen3-8B"),+ # The project suffix is not part of the model name.+ ("unsloth_Qwen3-8B__project-demo_1771227800", "unsloth/Qwen3-8B"),+ # ...and a name containing the marker is escaped by the generator.+ ("unsloth_x__project--y_1771227800", "unsloth/x__project-y"),+ # A non-timestamp tail belongs to the model name, so the whole name is unparseable+ # rather than truncated. Truncating gave 'unsloth/llama_3' -- valid, but nonexistent.+ ("unsloth_llama_3_8b", None),+ ("unsloth_gpt_oss_20b", None),+ ("unsloth_Qwen3-8B_final", None),+ ("unsloth_Qwen3-8B_v2", None),+ ("unsloth_Qwen3-8B_checkpoint-500", None),+ # A model name that is itself all digits still round-trips.+ ("unsloth_20260101_1771227800", "unsloth/20260101"),+ # Not ours: leave it to the caller's "could not detect" path.+ ("my-finetune_1771227800", None),+ ("meta-llama_Llama-3.1-8B_1771227800", None),+ ("Unsloth_Qwen3-8B_1771227800", None),+ ("checkpoint-500", None),+ ("", None),+ ],+)+def test_base_model_from_run_dir_name(dir_name, expected):+ assert base_model_from_run_dir_name(dir_name) == expected+++ "repo_id",+ [+ "unsloth/Qwen3-8B",+ "unsloth/llama_3_8b",+ "unsloth/gpt_oss_20b",+ "unsloth/_Qwen3-8B",+ "unsloth/x__project-y",+ "unsloth/20260101",+ "unsloth/Llama-3.2-3B-Instruct",+ ],+)[email protected]("project_name", [None, "Demo Project", "customer support"])+def test_a_generated_run_dir_name_parses_back_to_its_model(repo_id, project_name):+ """The parser is the generator read backwards; this is what stops the two drifting."""+ dir_name = build_default_output_dir_name(repo_id, project_name, timestamp = 1771227800)+ assert base_model_from_run_dir_name(dir_name) == repo_id+++def test_the_bare_org_is_never_returned():+ """``unsloth/`` fails huggingface_hub's validate_repo_id, so it must never escape."""+ candidates = [+ "unsloth_",+ "unsloth__1771227800",+ "unsloth___1771227800",+ "unsloth_1771227800",+ "unsloth__",+ "unsloth____",+ "unsloth_ _1771227800",+ ]+ assert [n for n in candidates if base_model_from_run_dir_name(n) == "unsloth/"] == []+++ "dir_name",+ [+ "unsloth_ _1771227800", # space+ "unsloth_._1771227800", # bare dot+ "unsloth_-_1771227800", # a name may not start or end with '-'+ "unsloth_..._1771227800", # '..' is rejected outright+ "unsloth_--_1771227800", # so is '--'+ "unsloth_.git_1771227800", # a repo id may not end with '.git'+ "unsloth_a\tb_1771227800", # control characters+ "unsloth_\n_1771227800",+ "unsloth_🦥_1771227800", # not a word character+ "unsloth_" + "a" * 97 + "_1771227800", # the Hub caps a name at 96 characters+ ],+)+def test_a_folder_name_that_cannot_be_a_repo_id_is_refused(dir_name):+ """A folder name is user input. Only trust the parse if the Hub would accept the result.++ ``build_default_output_dir_name`` sanitises everything here, so these shapes only arise+ from a hand-made folder -- which is exactly the case the fallback exists to serve.+ """+ assert base_model_from_run_dir_name(dir_name) is None+++def test_the_transcribed_repo_id_rule_is_never_looser_than_the_hubs():+ """The rule is transcribed to keep this module stdlib-only, so pin it to the real one."""+ hub_validate = pytest.importorskip("huggingface_hub.utils").validate_repo_id++ def hub_accepts(name):+ try:+ hub_validate(f"unsloth/{name}")+ return True+ except Exception:+ return False++ names = [+ "Qwen3-8B",+ "llama_3_8b",+ "_Qwen3-8B",+ "x__project-y",+ "20260101",+ "a",+ "a" * 96,+ "a" * 97,+ ".git",+ "a.git",+ "x--y",+ "x..y",+ "-x",+ "x-",+ ".x",+ "x.",+ "x_",+ "🦥",+ "",+ " ",+ "a b",+ "a\tb",+ "Café-8B",+ "a-b.c_d",+ ]+ looser = [+ n+ for n in names+ if base_model_from_run_dir_name(f"unsloth_{n}_1771227800") is not None+ and not hub_accepts(n)+ ]+ assert looser == []+++def _write_adapter(directory):+ directory.mkdir(parents = True)+ # No base_model_name_or_path, so detection has to fall through to the directory name.+ (directory / "adapter_config.json").write_text(json.dumps({}), encoding = "utf-8")+ (directory / "adapter_model.safetensors").write_bytes(b"")+++ "dir_name,expected",+ [+ ("unsloth_Qwen3-8B", None),+ ("unsloth_llama_3_8b", None),+ ("unsloth_Qwen3-8B_1771227800", "unsloth/Qwen3-8B"),+ ("unsloth_Qwen3-8B__project-demo_1771227800", "unsloth/Qwen3-8B"),+ ],+)+def test_lora_detection_end_to_end(tmp_path, dir_name, expected):+ adapter = tmp_path / dir_name+ _write_adapter(adapter)+ assert get_base_model_from_lora(str(adapter)) == expected+++ "dir_name,expected",+ [+ ("unsloth_Qwen3-8B", None),+ ("unsloth_llama_3_8b", None),+ ("unsloth_Qwen3-8B_1771227800", "unsloth/Qwen3-8B"),+ ("unsloth_Qwen3-8B__project-demo_1771227800", "unsloth/Qwen3-8B"),+ ],+)+def test_checkpoint_detection_end_to_end(tmp_path, dir_name, expected):+ checkpoint = tmp_path / dir_name+ checkpoint.mkdir()+ assert get_base_model_from_checkpoint(str(checkpoint)) == expected+++def test_a_named_base_model_still_wins_over_the_directory_name(tmp_path):+ """The fallback must stay a last resort: an explicit config is never second-guessed."""+ adapter = tmp_path / "unsloth_Qwen3-8B_1771227800"+ adapter.mkdir()+ (adapter / "adapter_config.json").write_text(+ json.dumps({"base_model_name_or_path": "meta-llama/Llama-3.1-8B"}), encoding = "utf-8"+ )+ (adapter / "adapter_model.safetensors").write_bytes(b"")+ assert get_base_model_from_lora(str(adapter)) == "meta-llama/Llama-3.1-8B"+++def test_a_trailing_separator_does_not_change_the_answer(tmp_path):+ """Callers pass raw user input; ``Path.name`` must have already normalised it."""+ adapter = tmp_path / "unsloth_Qwen3-8B_1771227800"+ _write_adapter(adapter)+ assert get_base_model_from_lora(str(adapter) + "/") == "unsloth/Qwen3-8B"+++# --- the two resolvers in utils.transformers_version ---------------------------------------+# _resolve_base_model is reached *through* get_base_model_from_lora, so while it kept its own+# copy of the parse it rebuilt the bogus id one branch after the fixed function returned None.+++def test_the_transformers_resolvers_agree_with_the_model_config_one(tmp_path):+ from utils.transformers_version import _resolve_base_model, recorded_local_base+ for dir_name in ("unsloth_Qwen3-8B", "unsloth_llama_3_8b", "unsloth_Qwen3-8B_1771227800"):+ expected = base_model_from_run_dir_name(dir_name)++ weights_only = tmp_path / "weights" / dir_name+ weights_only.mkdir(parents = True)+ (weights_only / "adapter_model.safetensors").write_bytes(b"")+ assert recorded_local_base(str(weights_only)) == (expected, False)+ assert _resolve_base_model(str(weights_only)) == (expected or str(weights_only))++ with_config = tmp_path / "config" / dir_name+ _write_adapter(with_config)+ assert _resolve_base_model(str(with_config)) == (expected or str(with_config))diff --git a/studio/backend/tests/test_offload_planner_seam.py b/studio/backend/tests/test_offload_planner_seam.pyindex 8a08d278c6e..35802a03b5f 100644--- a/studio/backend/tests/test_offload_planner_seam.py+++ b/studio/backend/tests/test_offload_planner_seam.py@@ -1244,6 +1244,8 @@ def test_the_flat_mtp_reserve_reaches_the_spill_budget():reserved = _plan(stub, free_mib = 24 * 1024, usable_mib = 14 * 1024)assert generous is not None and reserved is not Noneassert len(reserved.spilled_blocks) > len(generous.spilled_blocks)++def test_the_seam_computes_a_per_layer_kv_vector():"""The data already existed on the backend (_sliding_window_pattern); it justnever crossed into the planner. Only the RATIOS travel: full attention holdsdiff --git a/studio/backend/utils/models/model_config.py b/studio/backend/utils/models/model_config.pyindex 4fd8b37c1f1..cf84aed14f1 100644--- a/studio/backend/utils/models/model_config.py+++ b/studio/backend/utils/models/model_config.py@@ -17,6 +17,9 @@ from utils.paths import (resolve_export_dir,)from utils.utils import without_hf_auth+from utils.training_runs import (+ base_model_from_run_dir_name as _base_model_from_dir_name,+)from utils.models.gguf_metadata import (is_mmproj_by_metadata,mmproj_accepts_image,@@ -3415,14 +3418,10 @@ def get_base_model_from_checkpoint(checkpoint_path: str) -> Optional[str]:# TODO: reading base_model from training_args.bin is disabled -- torch.load defaults to# weights_only=True (torch >= 2.6), which rejects pickled TrainingArguments.- dir_name = checkpoint_path_obj.name- if dir_name.startswith("unsloth_"):- parts = dir_name.split("_")- if len(parts) >= 2:- model_parts = parts[1:-1]- base_model = "unsloth/" + "_".join(model_parts)- logger.info("Detected base model from directory name: %s", base_model)- return base_model+ base_model = _base_model_from_dir_name(checkpoint_path_obj.name)+ if base_model:+ logger.info("Detected base model from directory name: %s", base_model)+ return base_modellogger.warning(f"Could not detect base model for checkpoint: {checkpoint_path}")return None@@ -3454,14 +3453,10 @@ def get_base_model_from_lora(lora_path: str) -> Optional[str]:# weights_only=True and is a remote-code sink for third-party LoRAs; needs a trust check.# Last resort: parse from dir name (unsloth_<model>_<timestamp>)- dir_name = lora_path_obj.name- if dir_name.startswith("unsloth_"):- parts = dir_name.split("_")- if len(parts) >= 2:- model_parts = parts[1:-1] # Skip "unsloth" and timestamp- base_model = "unsloth/" + "_".join(model_parts)- logger.info(f"Detected base model from directory name: {base_model}")- return base_model+ base_model = _base_model_from_dir_name(lora_path_obj.name)+ if base_model:+ logger.info(f"Detected base model from directory name: {base_model}")+ return base_modellogger.warning(f"Could not detect base model for LoRA: {lora_path}")return Nonediff --git a/studio/backend/utils/training_runs.py b/studio/backend/utils/training_runs.pyindex dcdfa1395de..1d39c58a1f7 100644--- a/studio/backend/utils/training_runs.py+++ b/studio/backend/utils/training_runs.py@@ -13,6 +13,19 @@ _INVALID_SEGMENT_CHARS = re.compile(r"[^A-Za-z0-9._-]+")_MAX_RUN_DIR_NAME_CHARS = 255_PROJECT_MARKER = "__project-"_PROJECT_MARKER_ESCAPE = f"{_PROJECT_MARKER}-"+_UNSLOTH_ORG_PREFIX = "unsloth_"++# We emit a bare epoch; hand-made folders often use a date-time. Anything else+# (``_final``, ``_v2``, ``_8b``) is part of the model name, not a stamp.+_RUN_DIR_TIMESTAMP = re.compile(r"\A\d{6,}(?:[-_]\d{2,})?\Z")++# ``validate_repo_id`` transcribed to keep this module stdlib-only. A folder name is user+# input, so trust the parse only when the Hub would accept what falls out of it.+_REPO_NAME = re.compile(r"\A(?!.*(?:--|\.\.))(?![-.])[\w.-]{1,96}(?<![-.])\Z")+++def _is_valid_repo_name(name: str) -> bool:+ return bool(_REPO_NAME.match(name)) and not name.endswith(".git")def _trim_segment(segment: str, max_chars: int) -> str:@@ -97,6 +110,42 @@ def model_segment_from_default_output_dir_name(output_dir_name: str) -> Optionalreturn model_segment or None+def _model_segment_from_run_dir_name(output_dir_name: str) -> Optional[str]:+ """``model_segment_from_default_output_dir_name`` widened to date-time stamps.++ The strict inverse gates on ``isdigit()`` because it only reads folders we wrote; this+ one also reads folders we did not. Same shape otherwise, project suffix and escape included.+ """+ head, separator, last_segment = str(output_dir_name or "").rpartition("_")+ if not separator or not _RUN_DIR_TIMESTAMP.match(last_segment):+ return None+ marker_index = _appended_project_marker_index(head)+ if marker_index >= 0:+ head = head[:marker_index]+ return _unescape_project_marker(head) or None+++def base_model_from_run_dir_name(dir_name: str) -> Optional[str]:+ """``unsloth_<model>_<timestamp>`` -> ``unsloth/<model>``, else None.++ The last resort when no config names a base model. It sits beside+ ``build_default_output_dir_name`` because it is that function read backwards; keeping the+ pair together is what stops the parse drifting from the names we write.++ None matters as much as a name here. Without a timestamp the folder is not one we wrote,+ and every caller already asks the user instead. Guessing reaches the Hub: ``unsloth/`` is+ rejected outright, and a truncated ``unsloth/llama_3`` for ``unsloth_llama_3_8b`` is worse,+ being a valid id that does not exist.+ """+ model_segment = _model_segment_from_run_dir_name(dir_name)+ if model_segment is None or not model_segment.startswith(_UNSLOTH_ORG_PREFIX):+ return None+ model_name = model_segment[len(_UNSLOTH_ORG_PREFIX) :]+ if not _is_valid_repo_name(model_name):+ return None+ return f"unsloth/{model_name}"++def extract_project_name(config: Any) -> Optional[str]:"""Read and normalize a project name from a stored config dict."""if not isinstance(config, dict):diff --git a/studio/backend/utils/transformers_version.py b/studio/backend/utils/transformers_version.pyindex 768e8b2ebac..9b8e12d40cf 100644--- a/studio/backend/utils/transformers_version.py+++ b/studio/backend/utils/transformers_version.py@@ -53,6 +53,10 @@ from utils.subprocess_compat import (windows_hidden_subprocess_kwargs as _windows_hidden_subprocess_kwargs,)+# Safe at module scope, unlike utils.models below: utils.training_runs is stdlib-only, so it+# cannot pin a transformers version into sys.modules before the sidecar is activated.+from utils.training_runs import base_model_from_run_dir_name+logger = get_logger(__name__)@@ -567,10 +571,9 @@ def recorded_local_base(model_name) -> "tuple[str | None, bool]":return base, False# Only reachable without a Hub call when there is no adapter_config.json; with one,# the resolver tries get_base_model_from_lora first, which needs_hub already covers.- if not adapter_cfg and root.name.startswith("unsloth_") and _has_adapter_weights(root):- parts = root.name.split("_")- if len(parts) >= 2:- return "unsloth/" + "_".join(parts[1:-1]), False+ base = base_model_from_run_dir_name(root.name)+ if base and not adapter_cfg and _has_adapter_weights(root):+ return base, Falsereturn None, adapter_cfgexcept Exception:return None, True@@ -643,16 +646,14 @@ def _resolve_base_model(model_name: str) -> str:)# adapter_model-only LoRA: no config, so parse the unsloth_<model>_<timestamp> dir name.- if local_path.name.startswith("unsloth_") and _has_adapter_weights(local_path):- parts = local_path.name.split("_")- if len(parts) >= 2: # unsloth_<model...>_<timestamp>- base = "unsloth/" + "_".join(parts[1:-1])- logger.info(- "Resolved adapter-only LoRA '%s' → base model '%s' (via directory name)",- model_name,- base,- )- return base+ base = base_model_from_run_dir_name(local_path.name)+ if base and _has_adapter_weights(local_path):+ logger.info(+ "Resolved adapter-only LoRA '%s' → base model '%s' (via directory name)",+ model_name,+ base,+ )+ return basereturn model_namediff --git a/tests/test_fp8_fbgemm_block_shapes.py b/tests/test_fp8_fbgemm_block_shapes.pyindex 8f3a90a514a..ffa1474fd32 100644--- a/tests/test_fp8_fbgemm_block_shapes.py+++ b/tests/test_fp8_fbgemm_block_shapes.py@@ -92,9 +92,7 @@ def _check_grad(X, out, Wq, scale, block):grad_ref = torch.ones(out.shape, device = out.device, dtype = torch.float32) @ _dequant(Wq, scale, block)- torch.testing.assert_close(- X.grad.float(), grad_ref, atol = _bf16_atol(grad_ref), rtol = 5e-2- )+ torch.testing.assert_close(X.grad.float(), grad_ref, atol = _bf16_atol(grad_ref), rtol = 5e-2)def _rel_err(out, ref):