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: continue LoRA training from a saved adapter checkpoint (#13158)
Indrajit swaina5c7d496aa59
diff --git a/studio/backend/core/training/trainer.py b/studio/backend/core/training/trainer.pyindex cfb33d0289d..45ee91c8bd0 100644--- a/studio/backend/core/training/trainer.py+++ b/studio/backend/core/training/trainer.py@@ -339,6 +339,87 @@ def normalize_gradient_checkpointing(value) -> Union[str, bool]:return "unsloth"+def _ignored_adapter_settings(+ peft_config,+ lora_r,+ lora_alpha,+ modules_to_save,+ target_modules = None,+ lora_dropout = None,+ use_dora = False,+ use_rslora = False,+ use_loftq = False,+) -> list[str]:+ """Requested LoRA settings a continued adapter keeps from its own config instead."""+ adapter = next(iter(peft_config.values()), None) if isinstance(peft_config, dict) else None+ if adapter is None:+ return []++ def leaf(module):+ return str(module).rsplit(".", 1)[-1]++ ignored = []+ saved_r = getattr(adapter, "r", None)+ if saved_r is not None and saved_r != lora_r:+ ignored.append(f"rank {lora_r} (adapter has {saved_r})")+ saved_alpha = getattr(adapter, "lora_alpha", None)+ if saved_alpha is not None and saved_alpha != lora_alpha:+ ignored.append(f"alpha {lora_alpha} (adapter has {saved_alpha})")+ saved_dropout = getattr(adapter, "lora_dropout", None)+ if lora_dropout is not None and saved_dropout is not None and saved_dropout != lora_dropout:+ ignored.append(f"dropout {lora_dropout} (adapter has {saved_dropout})")+ if bool(use_dora) != bool(getattr(adapter, "use_dora", False)):+ ignored.append("DoRA on" if use_dora else "DoRA off")+ if bool(use_rslora) != bool(getattr(adapter, "use_rslora", False)):+ ignored.append("rsLoRA on" if use_rslora else "rsLoRA off")+ if use_loftq:+ # LoftQ only initializes a new adapter; an existing one keeps its weights.+ ignored.append("LoftQ initialization")+ # A string target is a PEFT regex or "all-linear"; only explicit lists compare cleanly.+ saved_targets = getattr(adapter, "target_modules", None)+ requested_list = target_modules if isinstance(target_modules, (list, tuple)) else []+ wants_all_linear = target_modules == "all-linear" or "all-linear" in requested_list+ requested = [m for m in requested_list if m != "all-linear"]+ if isinstance(saved_targets, str) and requested:+ # Saved as "all-linear" or a PEFT regex: an explicit selection cannot narrow it.+ ignored.append(+ f"target modules {', '.join(sorted({leaf(m) for m in requested}))} "+ f"(adapter has {saved_targets})"+ )+ elif isinstance(saved_targets, (list, set, tuple)) and (requested or wants_all_linear):+ saved_names = ", ".join(sorted({leaf(m) for m in saved_targets}))+ if wants_all_linear:+ ignored.append(f"all-linear targets (adapter has {saved_names})")+ elif {leaf(m) for m in requested} != {leaf(m) for m in saved_targets}:+ ignored.append(+ f"target modules {', '.join(sorted({leaf(m) for m in requested}))} "+ f"(adapter has {saved_names})"+ )+ saved_modules = {leaf(m) for m in (getattr(adapter, "modules_to_save", None) or [])}+ missing = [m for m in (modules_to_save or []) if leaf(m) not in saved_modules]+ if missing:+ ignored.append(f"training {', '.join(missing)} (adapter does not train them)")+ return ignored+++def _load_adapter_aware_tokenizer(lookup_name, hf_token, **kwargs):+ """AutoTokenizer for *lookup_name*. A PEFT adapter saved without tokenizer files falls back+ to the base it names, as Unsloth's own adapter loader does (#13140)."""+ from transformers import AutoTokenizer+ try:+ return AutoTokenizer.from_pretrained(lookup_name, token = hf_token, **kwargs)+ except Exception:+ from utils.models.model_config import get_base_model_from_lora_identifier++ base = get_base_model_from_lora_identifier(lookup_name, hf_token)+ if not base:+ raise+ # The adapter's revision and subfolder do not apply to its base repo.+ kwargs.pop("revision", None)+ kwargs.pop("subfolder", None)+ return AutoTokenizer.from_pretrained(base, token = hf_token, **kwargs)++class UnslothTrainer:def __new__(cls, *args, **kwargs):if cls is UnslothTrainer and should_use_mlx_training_backend():@@ -475,11 +556,10 @@ class UnslothTrainer:revision = model_revision,)else:- from transformers import AutoTokenizer- self.tokenizer = AutoTokenizer.from_pretrained(+ self.tokenizer = _load_adapter_aware_tokenizer(lookup_name,+ hf_token,trust_remote_code = trust_remote_code,- token = hf_token,local_files_only = local_files_only,revision = model_revision,# Spark-TTS keeps its tokenizer under LLM/; reading the root finds no vocab and fails blaming a@@ -1496,6 +1576,31 @@ class UnslothTrainer:self._use_gradient_checkpointing = use_gradient_checkpointing+ # Saved LoRA dirs load as PeftModel via from_pretrained; do not stack a second adapter (#13140).+ if getattr(self.model, "peft_config", None):+ ignored = _ignored_adapter_settings(+ self.model.peft_config,+ lora_r,+ lora_alpha,+ modules_to_save,+ target_modules = target_modules,+ lora_dropout = lora_dropout,+ use_dora = use_dora,+ use_rslora = use_rslora,+ use_loftq = use_loftq,+ )+ status = "Continuing from existing LoRA adapters"+ if ignored:+ # The adapter's own shape wins; say so instead of dropping the request silently.+ status += f" (kept the adapter's settings, ignoring {'; '.join(ignored)})"+ logger.warning(f"{status}\n")+ self._update_progress(status_message = status)+ logger.info(+ "Model already has LoRA adapters from the checkpoint; "+ "continuing training without creating a new adapter\n"+ )+ return True+# LoRA/QLoRA. "all-linear" is a PEFT keyword targeting every linear layer.if isinstance(target_modules, list) and "all-linear" in target_modules:if len(target_modules) == 1:diff --git a/studio/backend/core/training/training.py b/studio/backend/core/training/training.pyindex 9afce90d38e..7aca6654f4c 100644--- a/studio/backend/core/training/training.py+++ b/studio/backend/core/training/training.py@@ -325,6 +325,7 @@ def _build_training_worker_config(values: dict[str, Any]) -> dict[str, Any]:"require_exact_model_resource": values.get("require_exact_model_resource", False),"require_exact_dataset_resource": values.get("require_exact_dataset_resource", False),"require_validated_model_snapshot": values.get("require_validated_model_snapshot", False),+ "adapter_base_pin": values.get("adapter_base_pin"),"trust_remote_code": values.get("trust_remote_code", False),"approved_remote_code_fingerprint": values.get("approved_remote_code_fingerprint"),"subject": values.get("subject"),@@ -363,6 +364,7 @@ def _sanitize_db_config(config: dict[str, Any]) -> dict[str, Any]:"require_exact_dataset_resource","require_validated_model_snapshot","resume_model_load_mode",+ "adapter_base_pin",}}s3_config = config.get("s3_config")diff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.pyindex e08dc0d57b6..9c01fed3f93 100644--- a/studio/backend/core/training/worker.py+++ b/studio/backend/core/training/worker.py@@ -146,11 +146,59 @@ def _dataset_local_files_only(config: dict) -> bool:return bool(config.get("dataset_snapshot_path"))+def _uses_mlx_training_backend() -> bool:+ from core.training.training import should_use_mlx_training_backend+ return should_use_mlx_training_backend()+++def _adapter_trains_embeddings(model) -> bool:+ """Whether a loaded adapter already trains embed_tokens or lm_head in full (#13140)."""+ for adapter in (getattr(model, "peft_config", None) or {}).values():+ saved = list(getattr(adapter, "modules_to_save", None) or [])+ saved += list(getattr(adapter, "modules_to_tie", None) or [])+ if any(str(m).rsplit(".", 1)[-1] in ("embed_tokens", "lm_head") for m in saved):+ return True+ return False+++def _adapter_base_changed_error(config: dict) -> str | None:+ """Refuse when the adapter now names a different base than the one checked at start (#13140)."""+ # None: no adapter was admitted. "": an adapter that named no base, which must stay that way.+ pinned = config.get("adapter_base_pin")+ if pinned is None:+ return None+ from utils.models.model_config import get_base_model_from_lora++ if (get_base_model_from_lora(str(config.get("model_name") or "")) or "") != pinned:+ return "The adapter's base model changed after the run was checked. Start the run again."+ return None++def _untrainable_model_format_error(config: dict) -> str | None:model_format = str(config.get("model_format") or "").strip().lower()if model_format == "gguf":return "GGUF models are inference-only and cannot be trained."if model_format == "adapter":+ # LoRA / CPT may continue from a saved adapter; full finetune still cannot (#13140).+ # The embedding, decision and MLX runners wrap a fresh adapter; only the CUDA trainer continues one.+ if config.get("training_type") in ("LoRA/QLoRA", "Continued Pretraining") and not (+ config.get("is_embedding", False)+ or config.get("is_decision", False)+ or _uses_mlx_training_backend()+ ):+ from utils.paths import is_local_path++ if not is_local_path(str(config.get("model_name") or "")):+ return (+ "Continuing from a Hugging Face adapter repository is not supported yet. "+ "Download it to a local folder and select that folder."+ )+ if config.get("is_dataset_image") or config.get("is_dataset_audio"):+ return (+ "Continuing a saved adapter on an image or audio dataset is not supported "+ "yet. Start from its base model instead."+ )+ return Nonereturn "Adapter models are inference-only and cannot be trained as base models."return None@@ -454,7 +502,7 @@ def _verify_config_pins(config: dict, event_queue: Any) -> bool:def _validate_training_worker_config(config: dict, event_queue: Any) -> bool:if not _verify_config_pins(config, event_queue):return False- format_error = _untrainable_model_format_error(config)+ format_error = _untrainable_model_format_error(config) or _adapter_base_changed_error(config)if format_error:event_queue.put({@@ -4564,6 +4612,12 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->_send_status(event_queue, "Loading model...")from utils.hf_xet_fallback import start_watchdog+ # Recheck right before the load: the adapter folder may have been edited since start (#13140).+ base_error = _adapter_base_changed_error(config)+ if base_error:+ event_queue.put({"type": "error", "error": base_error, "stack": "", "ts": time.time()})+ return+event_queue.put({"type": "model_load_started", "ts": time.time()})_load_watchdog_stop = start_watchdog(repo_ids = [model_name],@@ -4793,6 +4847,10 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->)return+ if is_cpt and not cpt_trains_embeddings:+ # A continued adapter keeps its own modules_to_save, so it may train them anyway.+ cpt_trains_embeddings = _adapter_trains_embeddings(getattr(trainer, "model", None))+lr_default = "5e-5" if is_cpt else "2e-4"try:lr_value = float(config.get("learning_rate", lr_default))diff --git a/studio/backend/routes/training.py b/studio/backend/routes/training.pyindex a3094969bb4..48de8e32b1f 100644--- a/studio/backend/routes/training.py+++ b/studio/backend/routes/training.py@@ -228,6 +228,8 @@ class _ModelPreflightResult:model_name: strmodel_local_path: Optional[str]cached_model_pin: Optional[tuple[str, str]]+ # The base an admitted adapter named at preflight; the worker refuses a different one.+ adapter_base_pin: Optional[str] = None# Consecutive 1s polls without a step update that count as a stall (~30 min). Applied only once@@ -472,6 +474,28 @@ def _has_adapter_metadata(path: Path) -> bool:return path.is_dir() and (path / "adapter_config.json").is_file()+def _continue_from_adapter_allowed(request: TrainingStartRequest) -> bool:+ """LoRA / CPT can load a saved adapter as the starting point; full finetune cannot (#13140).++ Only the CUDA trainer keeps an adapter it loaded; the embedding, decision and Apple Silicon+ (MLX) runners always build a fresh one on top, so those still need a base model."""+ if request.training_type not in ("LoRA/QLoRA", "Continued Pretraining"):+ return False+ if getattr(request, "is_embedding", False) or getattr(request, "is_decision", False):+ return False+ from core.training.training import should_use_mlx_training_backend++ return not should_use_mlx_training_backend()+++# The names PEFT and Unsloth's loader open; numbered adapter shards are not loaded.+_ADAPTER_WEIGHT_FILES = ("adapter_model.safetensors", "adapter_model.bin")+++def _has_local_adapter_weights(path: Path) -> bool:+ return path.is_dir() and any((path / name).is_file() for name in _ADAPTER_WEIGHT_FILES)++_HF_MODEL_ACCESS_DENIED = ("Hugging Face denied access to this model. Add a valid Hugging Face ""token with repository access and accept any required access terms, "@@ -644,7 +668,10 @@ def _remote_untrainable_model_format(if normalized.startswith(root) and "/" not in normalized[len(root) :]:root_files.add(normalized[len(root) :])if "adapter_config.json" in root_files:- return "adapter"+ # Same weight files the local check accepts; config-only repos fail later in the loader.+ if any(name in root_files for name in _ADAPTER_WEIGHT_FILES):+ return "adapter"+ return "adapter_without_weights"has_trainable_weights = any(name in root_files for name, _ in _MODEL_WEIGHT_CANDIDATES)if has_gguf and not has_trainable_weights:return "gguf"@@ -919,6 +946,108 @@ def _authorize_cache_fallback(model_name: str, repo_type: str = "model") -> Noneaccount_access.require_model_access(reference, repo_type)+def _refuse_hub_adapter_continuation(request: TrainingStartRequest) -> None:+ # Only saved local adapter folders are continued (#13140). A Hub adapter's tokenizer,+ # base capabilities and revision are resolved differently by the loader; follow-up work.+ if not is_local_path(request.model_name):+ raise _training_start_error(+ 400,+ "training_hub_adapter_unsupported",+ "Continuing from a Hugging Face adapter repository is not supported yet. "+ "Download it to a local folder and select that folder.",+ )+++def _refuse_multimodal_adapter_continuation(request: TrainingStartRequest) -> None:+ # The modality probes read the adapter, not its base, so an image or audio run would be+ # formatted as text. Refuse it until the base is resolved for those probes (#13140).+ if request.is_dataset_image or request.is_dataset_audio:+ raise _training_start_error(+ 400,+ "training_adapter_multimodal_unsupported",+ "Continuing a saved adapter on an image or audio dataset is not supported yet. "+ "Start from its base model instead.",+ )+++def _authorize_adapter_base(adapter: str, hf_token: HfTokenArg) -> Optional[str]:+ """A continued adapter also loads the base it names. Check that base the way the adapter+ was checked, or a public adapter could open a private base from the shared cache (#13140)."""+ from hub.utils.hf_cache_state import (+ cached_repo_ref_for_path,+ repo_cache_has_usable_snapshot,+ )+ from utils.models.model_config import get_base_model_from_lora_identifier++ base = get_base_model_from_lora_identifier(adapter, account_hf_token(hf_token))+ if not base:+ return None+ if is_local_path(base):+ # A managed account may only reach bases in its own workspace or the shared cache.+ account_path(base, shared_cache = True)+ base_path = Path(base).expanduser()+ if not base_path.is_dir():+ raise _training_start_error(+ 400,+ "training_adapter_base_missing",+ "The base model folder this adapter names no longer exists.",+ )+ if not _has_trainable_local_weights(base_path):+ raise _training_start_error(+ 400,+ "training_adapter_base_not_trainable",+ "The base model folder this adapter names has no trainable weights.",+ )+ # A base path inside the Hub cache is still that repository's cached weights.+ cached_ref = cached_repo_ref_for_path(base)+ if cached_ref is None:+ return base+ repo_id, repo_type = cached_ref+ is_cached = lambda: True # noqa: E731 -- the path itself is the evidence+ # Reading the shared cache needs a grant, as for a selected cached model.+ _authorize_cache_fallback(repo_id, repo_type)+ else:+ repo_id, repo_type = canonical_model_repo_id(base), "model"+ is_cached = lambda: repo_cache_has_usable_snapshot("model", repo_id) # noqa: E731+ # Like the selected model: a grant is needed only to read the shared cache, not the Hub.+ if is_cached():+ _authorize_cache_fallback(base)+ if hf_env_offline() and not is_cached():+ raise _hf_preflight_error(+ 409,+ "hf_model_not_cached_offline",+ (+ "Offline mode is enabled, but this adapter's base model is not available "+ "in the local cache. Disable offline mode to download it before starting "+ "training."+ ),+ )+ if not is_cached():+ # The same Hub probe a selected model gets: a private, missing or misspelled base+ # fails here with its access or not-found error, not later in the loader.+ if _remote_untrainable_model_format(base, hf_token) is not None:+ raise _training_start_error(+ 400,+ "training_adapter_base_not_trainable",+ "The base model this adapter names is GGUF-only or adapter-only, "+ "so it cannot be trained.",+ )+ if cached_read_refused(+ hf_token,+ repo_id = repo_id,+ repo_type = repo_type,+ is_cached = is_cached,+ offline = hf_env_offline(),+ ):+ raise _hf_preflight_error(+ 422,+ "hf_model_access_denied",+ "Hugging Face denied access to this adapter's cached base model. "+ "Add a token with repository access.",+ )+ return base++def _is_decision_checkpoint(request: TrainingStartRequest) -> bool:# A Laya or Clef checkpoint, not an LLM that is trained with a new decision head.return bool(request.is_decision) and request.decision_layout != "llm"@@ -936,7 +1065,7 @@ def _reject_untrainable_model_request("training_model_gguf_not_trainable","GGUF models are inference-only and cannot be trained.",)- if model_format == "adapter":+ if model_format == "adapter" and not _continue_from_adapter_allowed(request):raise _training_start_error(400,"training_model_adapter_not_trainable",@@ -1135,11 +1264,22 @@ def _reject_untrainable_model_request("training_remote_model_gguf_only","GGUF-only remote models are inference-only and cannot be trained.",)- raise _training_start_error(- 400,- "training_remote_model_adapter_only",- "Adapter models are inference-only and cannot be trained as base models.",- )+ if not _continue_from_adapter_allowed(request):+ raise _training_start_error(+ 400,+ "training_remote_model_adapter_only",+ "Adapter models are inference-only and cannot be trained as base models.",+ )+ if remote_format == "adapter_without_weights":+ raise _training_start_error(+ 400,+ "training_remote_model_adapter_weights_missing",+ "Adapter repository is missing adapter_model weights.",+ )+ _refuse_hub_adapter_continuation(request)+ _refuse_multimodal_adapter_continuation(request)+ _authorize_adapter_base(request.model_name, hf_token)+ return _ModelPreflightResult(model_name, model_local_path, cached_model_pin)if _is_decision_checkpoint(request):folder = path / request.model_subfolder if request.model_subfolder else pathif not is_decision_model(str(folder)):@@ -1155,11 +1295,33 @@ def _reject_untrainable_model_request(has_trainable_weights = _has_trainable_local_weights(path, request.model_name)if has_trainable_weights:return _ModelPreflightResult(model_name, model_local_path, cached_model_pin)- if _has_adapter_metadata(path):- raise _training_start_error(- 400,- "training_local_model_adapter_only",- "Adapter-only local models are inference-only and cannot be trained as base models.",+ if _has_adapter_metadata(path) or (+ model_format == "adapter" and _has_local_adapter_weights(path)+ ):+ if not _continue_from_adapter_allowed(request):+ raise _training_start_error(+ 400,+ "training_local_model_adapter_only",+ "Adapter-only local models are inference-only and cannot be trained as base models.",+ )+ if not _has_local_adapter_weights(path):+ raise _training_start_error(+ 400,+ "training_local_model_adapter_weights_missing",+ "Adapter directory is missing adapter_model weights.",+ )+ # The loader needs adapter_config.json to find the base model.+ if not _has_adapter_metadata(path):+ raise _training_start_error(+ 400,+ "training_local_model_adapter_config_missing",+ "Adapter directory is missing adapter_config.json.",+ )+ _refuse_hub_adapter_continuation(request)+ _refuse_multimodal_adapter_continuation(request)+ adapter_base = _authorize_adapter_base(str(path), hf_token)+ return _ModelPreflightResult(+ model_name, model_local_path, cached_model_pin, adapter_base_pin = adapter_base or "")try:has_gguf = _detect_local_gguf(path) is not None@@ -2014,6 +2176,7 @@ async def start_training("require_exact_model_resource": resume_requires_exact_model,"require_exact_dataset_resource": resume_requires_exact_dataset,"require_validated_model_snapshot": cached_model_pin is not None,+ "adapter_base_pin": getattr(model_preflight, "adapter_base_pin", None),"trust_remote_code": request.trust_remote_code,"approved_remote_code_fingerprint": request.approved_remote_code_fingerprint,"subject": current_subject,diff --git a/studio/backend/tests/test_continue_adapter_settings.py b/studio/backend/tests/test_continue_adapter_settings.pynew file mode 100644index 00000000000..1b3f3226138--- /dev/null+++ b/studio/backend/tests/test_continue_adapter_settings.py@@ -0,0 +1,174 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Continuing from a saved adapter keeps the adapter's own LoRA shape (#13140).++The run's requested rank, alpha and CPT embedding modules cannot be applied to an+existing adapter, so the trainer must name what it ignored instead of dropping it.+"""++import ast+import os+from types import SimpleNamespace++TRAINER = os.path.join(+ os.path.dirname(os.path.dirname(os.path.abspath(__file__))),+ "core",+ "training",+ "trainer.py",+)+++def _helper():+ # trainer.py imports torch and unsloth; load only the pure helper.+ tree = ast.parse(open(TRAINER, encoding = "utf-8").read())+ fn = next(+ n+ for n in tree.body+ if isinstance(n, ast.FunctionDef) and n.name == "_ignored_adapter_settings"+ )+ namespace = {}+ exec(compile(ast.Module(body = [fn], type_ignores = []), TRAINER, "exec"), namespace)+ return namespace["_ignored_adapter_settings"]+++def _adapter(+ r = 8,+ lora_alpha = 16,+ modules_to_save = None,+ **extra,+):+ fields = {+ "r": r,+ "lora_alpha": lora_alpha,+ "modules_to_save": modules_to_save,+ "lora_dropout": 0.0,+ "use_dora": False,+ "use_rslora": False,+ "target_modules": {"q_proj", "v_proj"},+ }+ fields.update(extra)+ return {"default": SimpleNamespace(**fields)}+++def test_matching_request_ignores_nothing():+ ignored = _helper()+ assert ignored(_adapter(), 8, 16, None) == []+ assert ignored(_adapter(modules_to_save = ["embed_tokens", "lm_head"]), 8, 16, ["lm_head"]) == []+++def test_reports_rank_and_alpha_kept_from_adapter():+ ignored = _helper()(_adapter(r = 8, lora_alpha = 16), 16, 32, None)+ assert ignored == ["rank 16 (adapter has 8)", "alpha 32 (adapter has 16)"]+++def test_reports_cpt_embedding_modules_the_adapter_does_not_train():+ ignored = _helper()(_adapter(), 8, 16, ["embed_tokens", "model.lm_head"])+ assert ignored == ["training embed_tokens, model.lm_head (adapter does not train them)"]+++def test_unknown_peft_config_shape_is_ignored():+ ignored = _helper()+ assert ignored(None, 8, 16, None) == []+ assert ignored({}, 8, 16, None) == []+++def test_reports_targets_dropout_and_variant_kept_from_adapter():+ ignored = _helper()(+ _adapter(),+ 8,+ 16,+ None,+ target_modules = ["q_proj", "k_proj", "v_proj"],+ lora_dropout = 0.1,+ use_dora = True,+ )+ assert ignored == [+ "dropout 0.1 (adapter has 0.0)",+ "DoRA on",+ "target modules k_proj, q_proj, v_proj (adapter has q_proj, v_proj)",+ ]+++def test_matching_targets_and_all_linear_are_not_reported():+ ignored = _helper()+ assert ignored(_adapter(), 8, 16, None, target_modules = ["model.q_proj", "v_proj"]) == []+++def _tokenizer_loader(fake_auto, base):+ import sys+ import types++ tree = ast.parse(open(TRAINER, encoding = "utf-8").read())+ fn = next(+ n+ for n in tree.body+ if isinstance(n, ast.FunctionDef) and n.name == "_load_adapter_aware_tokenizer"+ )+ namespace = {}+ exec(compile(ast.Module(body = [fn], type_ignores = []), TRAINER, "exec"), namespace)+ transformers = types.SimpleNamespace(AutoTokenizer = fake_auto)+ model_config = types.SimpleNamespace(+ get_base_model_from_lora_identifier = lambda name, token: base+ )+ return namespace["_load_adapter_aware_tokenizer"], {+ "transformers": transformers,+ "utils.models.model_config": model_config,+ }+++class _FakeAutoTokenizer:+ calls = []++ @classmethod+ def from_pretrained(cls, name, **kwargs):+ cls.calls.append((name, kwargs))+ if name.endswith("adapter"):+ raise OSError("no tokenizer files")+ return f"tokenizer:{name}"+++def test_adapter_without_tokenizer_loads_the_base_tokenizer(monkeypatch):+ import sys++ _FakeAutoTokenizer.calls = []+ load, modules = _tokenizer_loader(_FakeAutoTokenizer, "org/base")+ for name, module in modules.items():+ monkeypatch.setitem(sys.modules, name, module)++ assert (+ load("/runs/adapter", "tok", revision = "abc", local_files_only = False) == "tokenizer:org/base"+ )+ assert _FakeAutoTokenizer.calls[-1] == ("org/base", {"token": "tok", "local_files_only": False})+++def test_non_adapter_tokenizer_failure_is_not_masked(monkeypatch):+ import sys++ import pytest++ _FakeAutoTokenizer.calls = []+ load, modules = _tokenizer_loader(_FakeAutoTokenizer, None)+ for name, module in modules.items():+ monkeypatch.setitem(sys.modules, name, module)++ with pytest.raises(OSError):+ load("/models/broken-adapter", None)+++def test_reports_loftq_request_on_a_continued_adapter():+ assert _helper()(_adapter(), 8, 16, None, use_loftq = True) == ["LoftQ initialization"]+++def test_reports_all_linear_request_against_explicit_saved_targets():+ ignored = _helper()+ expected = ["all-linear targets (adapter has q_proj, v_proj)"]+ assert ignored(_adapter(), 8, 16, None, target_modules = ["all-linear"]) == expected+ assert ignored(_adapter(), 8, 16, None, target_modules = "all-linear") == expected+++def test_reports_explicit_targets_against_a_saved_all_linear_adapter():+ ignored = _helper()(+ _adapter(target_modules = "all-linear"), 8, 16, None, target_modules = ["q_proj"]+ )+ assert ignored == ["target modules q_proj (adapter has all-linear)"]diff --git a/studio/backend/tests/test_training_cached_start.py b/studio/backend/tests/test_training_cached_start.pyindex a412bbd0a7c..4e5096765fb 100644--- a/studio/backend/tests/test_training_cached_start.py+++ b/studio/backend/tests/test_training_cached_start.py@@ -130,6 +130,13 @@ def _known_cache_root(monkeypatch, tmp_path):monkeypatch.setattr(hf_cache_state, "hf_cache_roots", lambda **kw: [tmp_path])+def _cuda_trainer():+ # Continuation needs the CUDA trainer; an Apple Silicon runner would take the MLX refusal.+ with patch("core.training.training.should_use_mlx_training_backend", return_value = False):+ yield++def _load_route_module(name: str):spec = importlib.util.spec_from_file_location(name, _BACKEND_ROOT / "routes" / "training.py")module = importlib.util.module_from_spec(spec)@@ -438,36 +445,439 @@ def test_hf_dataset_preflight_rejects_before_backend_start():@pytest.mark.parametrize(- ("model_format", "code", "expected"),+ ("model_format", "training_type", "code", "expected"),[- ("gguf", "training_model_gguf_not_trainable", "GGUF models are inference-only"),+ (+ "gguf",+ "LoRA/QLoRA",+ "training_model_gguf_not_trainable",+ "GGUF models are inference-only",+ ),("adapter",+ "Full Finetuning","training_model_adapter_not_trainable","Adapter models are inference-only",),],)-def test_start_rejects_untrainable_model_formats(model_format, code, expected):+def test_start_rejects_untrainable_model_formats(model_format, training_type, code, expected):route = _load_route_module(f"training_route_reject_{model_format}")- request = _request(model_format = model_format)+ request = _request(model_format = model_format, training_type = training_type)exc_info = _shared_setup_5(request, route)assert exc_info.value.detail["code"] == codeassert expected in exc_info.value.detail["message"]-def test_start_rejects_adapter_only_local_dir(tmp_path):- route = _load_route_module("training_route_reject_adapter_dir")+def test_start_rejects_adapter_only_local_dir_for_full_finetuning(tmp_path):+ route = _load_route_module("training_route_reject_adapter_dir_full")(tmp_path / "adapter_config.json").write_text("{}")(tmp_path / "adapter_model.safetensors").write_bytes(b"x")- request = _request(model_name = str(tmp_path))+ request = _request(model_name = str(tmp_path), training_type = "Full Finetuning")exc_info = _shared_setup_5(request, route)assert exc_info.value.detail["code"] == "training_local_model_adapter_only"assert "Adapter-only local models" in exc_info.value.detail["message"][email protected]("_cuda_trainer")+def test_start_allows_adapter_only_local_dir_for_lora(tmp_path):+ route = _load_route_module("training_route_allow_adapter_dir_lora")+ (tmp_path / "adapter_config.json").write_text("{}")+ (tmp_path / "adapter_model.safetensors").write_bytes(b"x")+ request = _request(model_name = str(tmp_path), model_format = "adapter")++ result = route._reject_untrainable_model_request(request)+ assert result.model_name == str(tmp_path.resolve())++[email protected]("_cuda_trainer")+def test_start_rejects_adapter_weights_without_adapter_config_for_lora(tmp_path):+ route = _load_route_module("training_route_reject_adapter_without_config")+ (tmp_path / "adapter_model.safetensors").write_bytes(b"x")+ request = _request(model_name = str(tmp_path), model_format = "adapter")++ exc_info = _shared_setup_2(request, route)+ assert exc_info.value.detail["code"] == "training_local_model_adapter_config_missing"+ assert "adapter_config.json" in exc_info.value.detail["message"]++[email protected]("_cuda_trainer")+def test_untrainable_gate_refuses_cached_hub_adapter_snapshot_for_lora(tmp_path):+ route = _load_route_module("training_route_snapshot_adapter_lora")+ snapshot = tmp_path / "models--unsloth--test" / "snapshots" / "rev"+ snapshot.mkdir(parents = True)+ (snapshot / "adapter_config.json").write_text("{}")+ (snapshot / "adapter_model.safetensors").write_bytes(b"x")+ request = _request(+ model_format = "safetensors",+ model_snapshot_path = str(snapshot),+ resume_from_checkpoint = "/outputs/run",+ )++ exc_info = _shared_setup_2(request, route)+ assert exc_info.value.detail["code"] == "training_hub_adapter_unsupported"++[email protected]("runner", ["embedding", "decision", "mlx"])+def test_start_refuses_adapter_dir_where_runner_builds_a_fresh_adapter(tmp_path, runner):+ route = _load_route_module(f"training_route_adapter_dir_{runner}")+ (tmp_path / "adapter_config.json").write_text("{}")+ (tmp_path / "adapter_model.safetensors").write_bytes(b"x")+ request = _request(+ model_name = str(tmp_path),+ model_format = "adapter",+ is_embedding = runner == "embedding",+ is_decision = runner == "decision",+ )++ with patch(+ "core.training.training.should_use_mlx_training_backend",+ return_value = runner == "mlx",+ ):+ exc_info = _shared_setup_2(request, route)+ assert exc_info.value.detail["code"] == "training_model_adapter_not_trainable"++[email protected]("refused", [True, False])[email protected]("_cuda_trainer")+def test_start_checks_the_cached_base_a_local_adapter_names(tmp_path, refused):+ route = _load_route_module(f"training_route_adapter_base_{refused}")+ (tmp_path / "adapter_config.json").write_text('{"base_model_name_or_path": "org/private-base"}')+ (tmp_path / "adapter_model.safetensors").write_bytes(b"x")+ request = _request(model_name = str(tmp_path), model_format = "adapter")+ asked = []++ def fake_refused(+ hf_token,+ *,+ repo_id,+ is_cached,+ offline = False,+ repo_type = "model",+ ):+ asked.append(repo_id)+ return refused++ with (+ patch.object(route, "cached_read_refused", side_effect = fake_refused),+ patch.object(route, "_remote_untrainable_model_format", return_value = None),+ ):+ if refused:+ with pytest.raises(HTTPException) as exc_info:+ route._reject_untrainable_model_request(request)+ assert exc_info.value.status_code == 422+ assert exc_info.value.detail["code"] == "hf_model_access_denied"+ else:+ route._reject_untrainable_model_request(request)+ assert "org/private-base" in asked++[email protected]("_cuda_trainer")+def test_start_checks_a_cache_path_base_named_by_a_local_adapter(tmp_path):+ route = _load_route_module("training_route_adapter_base_cache_path")+ base = tmp_path / "hub" / "models--org--private" / "snapshots" / "rev"+ base.mkdir(parents = True)+ (base / "config.json").write_text("{}")+ (base / "model.safetensors").write_bytes(b"x")+ (tmp_path / "adapter_config.json").write_text(+ json.dumps({"base_model_name_or_path": str(base)})+ )+ (tmp_path / "adapter_model.safetensors").write_bytes(b"x")+ request = _request(model_name = str(tmp_path), model_format = "adapter")++ with (+ patch(+ "hub.utils.hf_cache_state.cached_repo_ref_for_path",+ side_effect = lambda p: ("org/private", "model") if str(p) == str(base) else None,+ ),+ patch.object(route, "cached_read_refused", return_value = True) as refused,+ ):+ with pytest.raises(HTTPException) as exc_info:+ route._reject_untrainable_model_request(request)++ assert exc_info.value.status_code == 422+ assert refused.call_args.kwargs["repo_id"] == "org/private"++[email protected]("_cuda_trainer")+def test_start_checks_a_local_base_against_the_account_workspace(tmp_path):+ route = _load_route_module("training_route_adapter_base_workspace")+ base = tmp_path / "other-account" / "base"+ base.mkdir(parents = True)+ adapter = tmp_path / "adapter"+ adapter.mkdir()+ (adapter / "adapter_config.json").write_text(json.dumps({"base_model_name_or_path": str(base)}))+ (adapter / "adapter_model.safetensors").write_bytes(b"x")+ request = _request(model_name = str(adapter), model_format = "adapter")++ def guard(value, **kwargs):+ if str(value) == str(base):+ assert kwargs == {"shared_cache": True}+ raise HTTPException(status_code = 403, detail = "Path is outside this account's workspace")+ return value++ with patch.object(route, "account_path", side_effect = guard):+ with pytest.raises(HTTPException) as exc_info:+ route._reject_untrainable_model_request(request)++ assert exc_info.value.status_code == 403++[email protected]("_cuda_trainer")+def test_offline_start_refuses_an_uncached_adapter_base(tmp_path):+ route = _load_route_module("training_route_adapter_base_offline")+ (tmp_path / "adapter_config.json").write_text(+ json.dumps({"base_model_name_or_path": "org/base"})+ )+ (tmp_path / "adapter_model.safetensors").write_bytes(b"x")+ request = _request(model_name = str(tmp_path), model_format = "adapter")++ with (+ patch.object(route, "hf_env_offline", return_value = True),+ patch.object(route, "cached_read_refused", return_value = False),+ patch("hub.utils.hf_cache_state.repo_cache_has_usable_snapshot", return_value = False),+ ):+ with pytest.raises(HTTPException) as exc_info:+ route._reject_untrainable_model_request(request)++ assert exc_info.value.status_code == 409+ assert exc_info.value.detail["code"] == "hf_model_not_cached_offline"++[email protected]("cached", [False, True])[email protected]("_cuda_trainer")+def test_managed_adapter_base_needs_a_grant_only_for_a_cached_read(tmp_path, cached):+ route = _load_route_module(f"training_route_managed_adapter_base_{cached}")+ (tmp_path / "adapter_config.json").write_text(+ json.dumps({"base_model_name_or_path": "me/private-base"})+ )+ (tmp_path / "adapter_model.safetensors").write_bytes(b"x")+ request = _request(model_name = str(tmp_path), model_format = "adapter", hf_token = "hf_own")++ with (+ patch.object(route, "managed_account", return_value = True),+ patch("hub.services.models.account_access.managed_account", return_value = True),+ patch("hub.services.models.account_access.model_grants", return_value = set()),+ patch("hub.services.models.account_access.repo_is_public", return_value = False),+ patch("hub.utils.hf_cache_state.repo_cache_has_usable_snapshot", return_value = cached),+ patch.object(route, "cached_read_refused", return_value = False),+ patch.object(route, "hf_env_offline", return_value = False),+ patch.object(route, "_remote_untrainable_model_format", return_value = None),+ ):+ if cached:+ with pytest.raises(HTTPException):+ route._reject_untrainable_model_request(request, None, "hf_own")+ else:+ route._reject_untrainable_model_request(request, None, "hf_own")++[email protected]("_cuda_trainer")+def test_start_probes_an_uncached_hub_base_named_by_a_local_adapter(tmp_path):+ route = _load_route_module("training_route_adapter_base_probe")+ (tmp_path / "adapter_config.json").write_text(+ json.dumps({"base_model_name_or_path": "org/missing-base"})+ )+ (tmp_path / "adapter_model.safetensors").write_bytes(b"x")+ request = _request(model_name = str(tmp_path), model_format = "adapter")+ not_found = HTTPException(status_code = 404, detail = {"code": "hf_model_verification_failed"})++ with (+ patch("hub.utils.hf_cache_state.repo_cache_has_usable_snapshot", return_value = False),+ patch.object(route, "hf_env_offline", return_value = False),+ patch.object(route, "_remote_untrainable_model_format", side_effect = not_found) as probe,+ ):+ with pytest.raises(HTTPException) as exc_info:+ route._reject_untrainable_model_request(request, None, "hf_tok")++ assert exc_info.value.status_code == 404+ assert probe.call_args.args[0] == "org/missing-base"++[email protected]("_cuda_trainer")+def test_start_pins_the_base_a_local_adapter_was_checked_against(tmp_path):+ route = _load_route_module("training_route_adapter_base_pin")+ (tmp_path / "adapter_config.json").write_text(+ json.dumps({"base_model_name_or_path": "org/base"})+ )+ (tmp_path / "adapter_model.safetensors").write_bytes(b"x")+ request = _request(model_name = str(tmp_path), model_format = "adapter")++ with (+ patch("hub.utils.hf_cache_state.repo_cache_has_usable_snapshot", return_value = True),+ patch.object(route, "cached_read_refused", return_value = False),+ patch.object(route, "hf_env_offline", return_value = False),+ ):+ result = route._reject_untrainable_model_request(request, None, "hf_tok")++ assert result.adapter_base_pin == "org/base"+++def test_worker_refuses_an_adapter_whose_base_changed_after_start(tmp_path):+ from core.training import worker++ (tmp_path / "adapter_config.json").write_text(+ json.dumps({"base_model_name_or_path": "org/base"})+ )+ config = {"model_name": str(tmp_path)}+ assert worker._adapter_base_changed_error(config) is None+ assert worker._adapter_base_changed_error({**config, "adapter_base_pin": "org/base"}) is None+ error = worker._adapter_base_changed_error({**config, "adapter_base_pin": "org/other"})+ assert error is not None and "changed" in error+++def test_worker_rechecks_the_adapter_base_right_before_the_model_load():+ import ast++ from core.training import worker++ source = open(worker.__file__, encoding = "utf-8").read()+ lines = source.splitlines()+ load_line = next(i for i, line in enumerate(lines) if "success = trainer.load_model(" in line)+ window = "\n".join(lines[max(0, load_line - 60) : load_line])+ assert "_adapter_base_changed_error(config)" in window+ ast.parse(source)++[email protected]("_cuda_trainer")+def test_adapter_without_a_base_is_pinned_and_cannot_gain_one(tmp_path):+ from core.training import worker++ route = _load_route_module("training_route_adapter_no_base_pin")+ adapter = tmp_path / "my-adapter"+ adapter.mkdir()+ (adapter / "adapter_config.json").write_text("{}")+ (adapter / "adapter_model.safetensors").write_bytes(b"x")+ request = _request(model_name = str(adapter), model_format = "adapter")++ result = route._reject_untrainable_model_request(request)+ assert result.adapter_base_pin == ""++ config = {"model_name": str(adapter), "adapter_base_pin": result.adapter_base_pin}+ assert worker._adapter_base_changed_error(config) is None+ (adapter / "adapter_config.json").write_text(+ json.dumps({"base_model_name_or_path": "org/private-base"})+ )+ assert worker._adapter_base_changed_error(config) is not None++[email protected]("_cuda_trainer")+def test_start_refuses_an_adapter_whose_local_base_is_gone(tmp_path):+ route = _load_route_module("training_route_adapter_base_gone")+ adapter = tmp_path / "adapter"+ adapter.mkdir()+ (adapter / "adapter_config.json").write_text(+ json.dumps({"base_model_name_or_path": str(tmp_path / "deleted-base")})+ )+ (adapter / "adapter_model.safetensors").write_bytes(b"x")+ request = _request(model_name = str(adapter), model_format = "adapter")++ exc_info = _shared_setup_2(request, route)+ assert exc_info.value.detail["code"] == "training_adapter_base_missing"++[email protected]("base_format", ["gguf", "adapter", "adapter_without_weights"])[email protected]("_cuda_trainer")+def test_start_refuses_an_adapter_whose_hub_base_is_not_trainable(tmp_path, base_format):+ route = _load_route_module(f"training_route_adapter_base_{base_format}")+ (tmp_path / "adapter_config.json").write_text(+ json.dumps({"base_model_name_or_path": "org/base"})+ )+ (tmp_path / "adapter_model.safetensors").write_bytes(b"x")+ request = _request(model_name = str(tmp_path), model_format = "adapter")++ with (+ patch("hub.utils.hf_cache_state.repo_cache_has_usable_snapshot", return_value = False),+ patch.object(route, "hf_env_offline", return_value = False),+ patch.object(route, "_remote_untrainable_model_format", return_value = base_format),+ ):+ exc_info = _shared_setup_2(request, route)++ assert exc_info.value.detail["code"] == "training_adapter_base_not_trainable"++[email protected]("_cuda_trainer")+def test_start_refuses_an_adapter_whose_local_base_has_no_weights(tmp_path):+ route = _load_route_module("training_route_adapter_base_empty")+ base = tmp_path / "empty-base"+ base.mkdir()+ adapter = tmp_path / "adapter"+ adapter.mkdir()+ (adapter / "adapter_config.json").write_text(json.dumps({"base_model_name_or_path": str(base)}))+ (adapter / "adapter_model.safetensors").write_bytes(b"x")+ request = _request(model_name = str(adapter), model_format = "adapter")++ exc_info = _shared_setup_2(request, route)+ assert exc_info.value.detail["code"] == "training_adapter_base_not_trainable"++[email protected]("_cuda_trainer")+def test_cache_path_base_needs_the_account_grant(tmp_path):+ route = _load_route_module("training_route_adapter_cache_base_grant")+ base = tmp_path / "hub" / "models--org--private" / "snapshots" / "rev"+ base.mkdir(parents = True)+ (base / "config.json").write_text("{}")+ (base / "model.safetensors").write_bytes(b"x")+ adapter = tmp_path / "adapter"+ adapter.mkdir()+ (adapter / "adapter_config.json").write_text(json.dumps({"base_model_name_or_path": str(base)}))+ (adapter / "adapter_model.safetensors").write_bytes(b"x")+ request = _request(model_name = str(adapter), model_format = "adapter")+ denied = HTTPException(status_code = 404, detail = "Model not found")++ with (+ patch(+ "hub.utils.hf_cache_state.cached_repo_ref_for_path",+ side_effect = lambda p: ("org/private", "model") if str(p) == str(base) else None,+ ),+ patch.object(route, "_authorize_cache_fallback", side_effect = denied) as grant,+ ):+ with pytest.raises(HTTPException) as exc_info:+ route._reject_untrainable_model_request(request)++ assert exc_info.value.status_code == 404+ assert grant.call_args.args == ("org/private", "model")+++def test_adapter_trains_embeddings_reads_saved_modules():+ from core.training import worker++ def model(**fields):+ return SimpleNamespace(peft_config = {"default": SimpleNamespace(**fields)})++ assert worker._adapter_trains_embeddings(model(modules_to_save = ["lm_head"]))+ assert worker._adapter_trains_embeddings(+ model(modules_to_save = None, modules_to_tie = ["model.embed_tokens"])+ )+ assert not worker._adapter_trains_embeddings(model(modules_to_save = None))+ assert not worker._adapter_trains_embeddings(SimpleNamespace())++[email protected]("dataset_flag", ["is_dataset_image", "is_dataset_audio"])[email protected]("_cuda_trainer")+def test_start_refuses_adapter_continuation_on_multimodal_data(tmp_path, dataset_flag):+ route = _load_route_module(f"training_route_adapter_{dataset_flag}")+ (tmp_path / "adapter_config.json").write_text("{}")+ (tmp_path / "adapter_model.safetensors").write_bytes(b"x")+ request = _request(model_name = str(tmp_path), **{dataset_flag: True})++ exc_info = _shared_setup_2(request, route)+ assert exc_info.value.detail["code"] == "training_adapter_multimodal_unsupported"++ from core.training import worker++ error = worker._untrainable_model_format_error(+ {+ "model_format": "adapter",+ "training_type": "LoRA/QLoRA",+ "model_name": str(tmp_path),+ dataset_flag: True,+ }+ )+ assert error is not None and "image or audio" in error++def test_start_rejects_missing_local_model(tmp_path):route = _load_route_module("training_route_reject_missing_local_model")request = _request(model_name = str(tmp_path / "missing-model"))@@ -516,14 +926,15 @@ def test_uncached_offline_model_fails_without_remote_probe(monkeypatch, offline_remote_probe.assert_not_called()[email protected]("_cuda_trainer")def test_start_rejects_partial_adapter_local_dir(tmp_path):route = _load_route_module("training_route_reject_partial_adapter_dir")(tmp_path / "adapter_config.json").write_text("{}")request = _request(model_name = str(tmp_path), model_format = "safetensors")exc_info = _shared_setup_2(request, route)- assert exc_info.value.detail["code"] == "training_local_model_adapter_only"- assert "Adapter-only local models" in exc_info.value.detail["message"]+ assert exc_info.value.detail["code"] == "training_local_model_adapter_weights_missing"+ assert "missing adapter_model weights" in exc_info.value.detail["message"]def test_start_rejects_gguf_only_local_dir(tmp_path):@@ -660,6 +1071,7 @@ def test_untrainable_gate_inspects_verified_snapshot_path(tmp_path):model_format = "safetensors",model_snapshot_path = str(snapshot),resume_from_checkpoint = "/outputs/run",+ training_type = "Full Finetuning",)exc_info = _shared_setup_2(request, route)@@ -675,6 +1087,7 @@ def test_untrainable_gate_inspects_selected_cache(tmp_path):request = _request(model_known_cached = True,model_format = "safetensors",+ training_type = "Full Finetuning",)exc_info = _shared_setup_2(request, route)@@ -704,7 +1117,7 @@ def test_unavailable_probe_inspects_unadvertised_cache(tmp_path):side_effect = HTTPException(status_code = 503, detail = "unavailable"),):with pytest.raises(HTTPException) as exc_info:- route._reject_untrainable_model_request(_request())+ route._reject_untrainable_model_request(_request(training_type = "Full Finetuning"))assert exc_info.value.status_code == 400assert exc_info.value.detail["code"] == "training_local_model_adapter_only"@@ -1085,9 +1498,9 @@ def test_mlx_pinned_fallback_rejects_cross_repository_bnb_remap():)-def test_untrainable_gate_rejects_remote_adapter():- route = _load_route_module("training_route_remote_adapter")- request = _request()+def test_untrainable_gate_rejects_remote_adapter_for_full_finetuning():+ route = _load_route_module("training_route_remote_adapter_full")+ request = _request(training_type = "Full Finetuning")with patch.object(route, "_remote_untrainable_model_format", return_value = "adapter"):with pytest.raises(HTTPException) as exc_info:@@ -1098,6 +1511,69 @@ def test_untrainable_gate_rejects_remote_adapter():assert "Adapter models are inference-only" in exc_info.value.detail["message"][email protected]("_cuda_trainer")+def test_untrainable_gate_refuses_remote_adapter_continuation_for_lora():+ route = _load_route_module("training_route_remote_adapter_lora")+ request = _request(model_format = "adapter")++ with patch.object(route, "_remote_untrainable_model_format", return_value = "adapter"):+ exc_info = _shared_setup_2(request, route)++ assert exc_info.value.detail["code"] == "training_hub_adapter_unsupported"+++def test_remote_format_probe_flags_adapter_repo_without_weights():+ route = _load_route_module("training_route_remote_adapter_no_weights")+ info = SimpleNamespace(siblings = [SimpleNamespace(rfilename = "adapter_config.json")])++ with _patch_model_info(return_value = info):+ assert (+ route._remote_untrainable_model_format("org/adapter", None) == "adapter_without_weights"+ )++[email protected]("_cuda_trainer")+def test_untrainable_gate_rejects_remote_adapter_without_weights_for_lora():+ route = _load_route_module("training_route_remote_adapter_no_weights_lora")+ request = _request(model_format = "adapter")++ with patch.object(+ route, "_remote_untrainable_model_format", return_value = "adapter_without_weights"+ ):+ with pytest.raises(HTTPException) as exc_info:+ route._reject_untrainable_model_request(request)++ assert exc_info.value.status_code == 400+ assert exc_info.value.detail["code"] == "training_remote_model_adapter_weights_missing"+++def test_remote_format_probe_ignores_numbered_adapter_shards():+ route = _load_route_module("training_route_remote_adapter_shards")+ info = SimpleNamespace(+ siblings = [+ SimpleNamespace(rfilename = "adapter_config.json"),+ SimpleNamespace(rfilename = "adapter_model-00001-of-00002.safetensors"),+ SimpleNamespace(rfilename = "adapter_model-00002-of-00002.safetensors"),+ ]+ )++ with _patch_model_info(return_value = info):+ assert (+ route._remote_untrainable_model_format("org/adapter", None) == "adapter_without_weights"+ )++[email protected]("_cuda_trainer")+def test_start_rejects_local_adapter_with_only_numbered_shards(tmp_path):+ route = _load_route_module("training_route_local_adapter_shards")+ (tmp_path / "adapter_config.json").write_text("{}")+ (tmp_path / "adapter_model-00001-of-00002.safetensors").write_bytes(b"x")+ request = _request(model_name = str(tmp_path))++ exc_info = _shared_setup_2(request, route)+ assert exc_info.value.detail["code"] == "training_local_model_adapter_weights_missing"++def test_untrainable_gate_rejects_remote_gguf_only_repository():route = _load_route_module("training_route_remote_gguf")request = _request()@@ -1113,7 +1589,12 @@ def test_untrainable_gate_rejects_remote_gguf_only_repository():def test_remote_format_probe_preserves_root_level_repo_id():route = _load_route_module("training_route_remote_adapter_metadata")- info = SimpleNamespace(siblings = [SimpleNamespace(rfilename = "adapter_config.json")])+ info = SimpleNamespace(+ siblings = [+ SimpleNamespace(rfilename = "adapter_config.json"),+ SimpleNamespace(rfilename = "adapter_model.safetensors"),+ ]+ )with _patch_model_info(return_value = info) as model_info:assert route._remote_untrainable_model_format("bert-base-uncased", "hf-token") == "adapter"@@ -1144,7 +1625,12 @@ def test_remote_format_probe_resolves_the_bicodec_alias():def test_remote_format_probe_retries_transient_failure():route = _load_route_module("training_route_remote_adapter_metadata_retry")- info = SimpleNamespace(siblings = [SimpleNamespace(rfilename = "adapter_config.json")])+ info = SimpleNamespace(+ siblings = [+ SimpleNamespace(rfilename = "adapter_config.json"),+ SimpleNamespace(rfilename = "adapter_model.safetensors"),+ ]+ )with _patch_model_info(side_effect = [OSError("timed out"), info],@@ -1170,7 +1656,12 @@ def test_remote_format_probe_retries_transient_hub_status(status_code):route = _load_route_module(f"training_route_remote_status_retry_{status_code}")transient_error = RuntimeError("transient Hub failure")transient_error.response = SimpleNamespace(status_code = status_code)- info = SimpleNamespace(siblings = [SimpleNamespace(rfilename = "adapter_config.json")])+ info = SimpleNamespace(+ siblings = [+ SimpleNamespace(rfilename = "adapter_config.json"),+ SimpleNamespace(rfilename = "adapter_model.safetensors"),+ ]+ )with _patch_model_info(side_effect = [transient_error, info],@@ -1292,7 +1783,11 @@ def test_optimizer_checkpoint_does_not_make_adapter_trainable(tmp_path):(tmp_path / "config.json").write_text("{}")(tmp_path / "adapter_config.json").write_text("{}")(tmp_path / "optimizer.pt").write_bytes(b"x")- request = _request(model_name = str(tmp_path), model_format = "safetensors")+ request = _request(+ model_name = str(tmp_path),+ model_format = "safetensors",+ training_type = "Full Finetuning",+ )exc_info = _shared_setup_2(request, route)assert exc_info.value.detail["code"] == "training_local_model_adapter_only"@@ -2382,11 +2877,38 @@ def test_apply_cache_pins_resume_pin_rejects_foreign(tmp_path):assert config["model_snapshot_path"] is None[email protected]("_cuda_trainer")def test_worker_rejects_inference_only_model_formats():from core.training import workerassert "GGUF" in worker._untrainable_model_format_error({"model_format": "gguf"})assert "Adapter" in worker._untrainable_model_format_error({"model_format": "adapter"})+ assert (+ worker._untrainable_model_format_error(+ {"model_format": "adapter", "training_type": "Full Finetuning"}+ )+ is not None+ )+ assert (+ worker._untrainable_model_format_error(+ {"model_format": "adapter", "training_type": "LoRA/QLoRA", "model_name": "/runs/a"}+ )+ is None+ )+ assert "Hugging Face adapter" in worker._untrainable_model_format_error(+ {"model_format": "adapter", "training_type": "LoRA/QLoRA", "model_name": "org/adapter"}+ )+ lora_adapter = {+ "model_format": "adapter",+ "training_type": "LoRA/QLoRA",+ "model_name": "/runs/a",+ }+ for runner_flag in ("is_embedding", "is_decision"):+ assert (+ worker._untrainable_model_format_error({**lora_adapter, runner_flag: True}) is not None+ )+ with patch.object(worker, "_uses_mlx_training_backend", return_value = True):+ assert worker._untrainable_model_format_error(lora_adapter) is not Noneassert worker._untrainable_model_format_error({"model_format": "safetensors"}) is Noneassert worker._untrainable_model_format_error({}) is Nonediff --git a/studio/frontend/src/features/training/lib/freeform-model-validation.ts b/studio/frontend/src/features/training/lib/freeform-model-validation.tsindex a031fa58734..284054b764b 100644--- a/studio/frontend/src/features/training/lib/freeform-model-validation.ts+++ b/studio/frontend/src/features/training/lib/freeform-model-validation.ts@@ -8,19 +8,10 @@ import type {import { classifyUnslothSupport, isGgufLike } from "@/features/hub";import type { TranslationKey } from "@/i18n";+// A single adapter file is not loadable on its own; its folder is.const ADAPTER_ARTIFACT_PATTERN =/(?:^|[/\\])adapter_(?:config\.json|model\.(?:safetensors|bin))$/i;-function hasPeftMetadata({- tags,- libraryName,-}: Pick<TrainingModelValidationCandidate, "tags" | "libraryName">): boolean {- if (libraryName?.trim().toLowerCase() === "peft") {- return true;- }- return tags?.some((tag) => tag.trim().toLowerCase() === "peft") ?? false;-}-export type TrainingModelValidationCandidate = {id: string;modelFormat?: ModelInventoryFormat | null;@@ -46,14 +37,17 @@ export function validateTrainingModelCandidate(if (candidate.modelFormat === "gguf" || isGgufLike(id)) {return { ok: false, reasonKey: "studio.modelPicker.reasonGguf" };}- if (- candidate.modelFormat === "adapter" ||- ADAPTER_ARTIFACT_PATTERN.test(id) ||- hasPeftMetadata(candidate)- ) {+ if (ADAPTER_ARTIFACT_PATTERN.test(id)) {return { ok: false, reasonKey: "studio.modelPicker.reasonAdapter" };}- if (candidate.capabilities && !candidate.capabilities.canTrain) {+ // Adapter / PEFT dirs are allowed here: LoRA and CPT can continue from a saved+ // adapter (#13140). Full finetune is refused later in validateTrainingConfig.+ // The inventory marks adapters canTrain=false (not a base), so skip that check for them.+ if (+ candidate.modelFormat !== "adapter" &&+ candidate.capabilities &&+ !candidate.capabilities.canTrain+ ) {return { ok: false, reasonKey: "studio.modelPicker.reasonNotTrainable" };}const support = classifyUnslothSupport({diff --git a/studio/frontend/src/features/training/lib/validation.ts b/studio/frontend/src/features/training/lib/validation.tsindex c5639ab031b..0856ac9c6d3 100644--- a/studio/frontend/src/features/training/lib/validation.ts+++ b/studio/frontend/src/features/training/lib/validation.ts@@ -3,6 +3,7 @@import { validateHubResourceId } from "@/components/resource-picker/hub-resource-id";import type { TranslationKey } from "@/i18n";+import { isAdapterMethod } from "@/types/training";import type { TrainingConfigState } from "../types/config";import { requiresExplicitCachedDatasetSplit } from "./dataset-split-policy";import {@@ -179,13 +180,25 @@ export function validateTrainingConfig(};}if (isUntrainableModelFormat(config.modelFormat)) {- return {- ok: false,- errorKey:- config.modelFormat === "gguf"- ? "studio.modelPicker.reasonGguf"- : "studio.modelPicker.reasonAdapter",- };+ if (config.modelFormat === "gguf") {+ return { ok: false, errorKey: "studio.modelPicker.reasonGguf" };+ }+ // Adapter format is valid when continuing LoRA / CPT from a saved adapter (#13140).+ // Decision, embedding and Apple Silicon runs build a fresh adapter, so they need a base.+ // Only a saved local adapter folder is continued; a Hub adapter repo is not yet.+ if (+ !isAdapterMethod(config.trainingMethod) ||+ !isLocalTrainingModelSelection({+ model: config.selectedModel,+ knownCached: config.modelKnownCached,+ localPath: config.modelLocalPath,+ }) ||+ config.modelType === "decision" ||+ config.isEmbeddingModel ||+ deviceType === "mac"+ ) {+ return { ok: false, errorKey: "studio.modelPicker.reasonAdapter" };+ }}if (!isTrainingConfigSupportedOnDevice(config, deviceType)) {diff --git a/studio/frontend/src/features/training/stores/training-config-store.ts b/studio/frontend/src/features/training/stores/training-config-store.tsindex c67713c3701..b58ac6d1279 100644--- a/studio/frontend/src/features/training/stores/training-config-store.ts+++ b/studio/frontend/src/features/training/stores/training-config-store.ts@@ -357,8 +357,15 @@ export const useTrainingConfigStore = create<TrainingConfigStore>()(}if (modelDetails.is_lora) {+ // LoRA / CPT can continue from a saved adapter; full finetune and decision+ // adapters cannot (#13140).+ const canContinue =+ isAdapterMethod(get().trainingMethod) &&+ !modelDetails.is_decision;+ // Keep the modality the backend reported even when refusing, so switching the+ // method afterwards still validates the adapter as what it is.set({- ...(shouldApplyTrainingDefaults+ ...(!canContinue && shouldApplyTrainingDefaults? {trainingMethodProvenance: {...get().trainingMethodProvenance,@@ -367,22 +374,31 @@ export const useTrainingConfigStore = create<TrainingConfigStore>()(},}: {}),- modelType: null,+ modelType: resolveTrainingModelType({+ modelType: modelDetails.model_type,+ isEmbedding: !!modelDetails.is_embedding,+ isDecision: !!modelDetails.is_decision,+ isVision: modelDetails.is_vision,+ isAudio: modelDetails.is_audio,+ }),decisionLayout: null,modelFormat: "adapter",- isVisionModel: false,- isEmbeddingModel: false,- isAudioModel: false,- audioCapabilityUnknown: false,+ isVisionModel: modelDetails.is_vision,+ isEmbeddingModel: !!modelDetails.is_embedding,+ isAudioModel: !!modelDetails.is_audio,+ audioCapabilityUnknown: modelDetails.audio_type_known === false,isLoadingModelDefaults: false,isCheckingVision: false,modelDefaultsError: null,modelDefaultsAppliedFor: modelName,- maxPositionEmbeddings: null,- });- toast.error(translate("studio.modelPicker.cantUseModel"), {- description: translate("studio.modelPicker.reasonAdapter"),+ maxPositionEmbeddings:+ modelDetails.max_position_embeddings ?? null,});+ if (!canContinue) {+ toast.error(translate("studio.modelPicker.cantUseModel"), {+ description: translate("studio.modelPicker.reasonAdapter"),+ });+ }return;}diff --git a/studio/frontend/tests/helpers/store-stubs/hub.ts b/studio/frontend/tests/helpers/store-stubs/hub.tsindex 2919e3d4381..d3424faeb20 100644--- a/studio/frontend/tests/helpers/store-stubs/hub.ts+++ b/studio/frontend/tests/helpers/store-stubs/hub.ts@@ -4,6 +4,8 @@// Real logic, re-exported: only the barrel it normally comes from needs stubbing.export { EMBEDDING_TAGS } from "../../../src/features/hub/lib/hf-model-meta.ts";export { normalizeModelIdentity } from "../../../src/features/hub/lib/model-identity.ts";+export { isGgufLike } from "../../../src/features/hub/lib/model-identifiers.ts";+export { classifyUnslothSupport } from "../../../src/features/hub/lib/unsloth-support.ts";/** Minimal HF-token store. */let token = "";diff --git a/studio/frontend/tests/training-adapter-candidate.test.ts b/studio/frontend/tests/training-adapter-candidate.test.tsnew file mode 100644index 00000000000..07ffd20425d--- /dev/null+++ b/studio/frontend/tests/training-adapter-candidate.test.ts@@ -0,0 +1,55 @@+// 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 assert from "node:assert/strict";+import test from "node:test";++import { registerStoreStubResolver } from "./helpers/kit.ts";++registerStoreStubResolver();++const { validateTrainingModelCandidate } = await import(+ "../src/features/training/lib/freeform-model-validation.ts"+);++test("a scanned adapter folder is not refused as untrainable", () => {+ // The inventory marks adapters canTrain=false because they are not bases.+ const capabilities = {+ canChat: true,+ canTrain: false,+ canExport: false,+ } as never;+ assert.deepEqual(+ validateTrainingModelCandidate({+ id: "/outputs/run/checkpoint-30",+ modelFormat: "adapter",+ capabilities,+ }),+ { ok: true },+ );+ assert.deepEqual(+ validateTrainingModelCandidate({+ id: "/models/merged",+ modelFormat: "safetensors",+ capabilities,+ }),+ { ok: false, reasonKey: "studio.modelPicker.reasonNotTrainable" },+ );+});++test("a single adapter file is refused; its folder is the thing to pick", () => {+ for (const id of [+ "/outputs/run/checkpoint-30/adapter_config.json",+ "/outputs/run/adapter_model.safetensors",+ "C:\\outputs\\run\\adapter_model.bin",+ ]) {+ assert.deepEqual(validateTrainingModelCandidate({ id }), {+ ok: false,+ reasonKey: "studio.modelPicker.reasonAdapter",+ });+ }+ assert.deepEqual(+ validateTrainingModelCandidate({ id: "/outputs/run/checkpoint-30" }),+ { ok: true },+ );+});diff --git a/studio/frontend/tests/training-continue-from-adapter.test.ts b/studio/frontend/tests/training-continue-from-adapter.test.tsnew file mode 100644index 00000000000..2808f308dcc--- /dev/null+++ b/studio/frontend/tests/training-continue-from-adapter.test.ts@@ -0,0 +1,105 @@+// 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 assert from "node:assert/strict";+import test, { after } from "node:test";++import {+ installLocalStorageFake,+ registerStoreStubResolver,+} from "./helpers/kit.ts";++registerStoreStubResolver();+installLocalStorageFake();++const { setAuthFetchHandler } = await import("./helpers/store-stubs/auth.ts");+const { useTrainingConfigStore } = await import(+ "../src/features/training/stores/training-config-store.ts"+);++const ADAPTER = "/outputs/qwen-vl-run/checkpoint-30";++async function waitForModelDefaults(model: string): Promise<void> {+ for (let attempt = 0; attempt < 100; attempt += 1) {+ const state = useTrainingConfigStore.getState();+ if (+ !state.isLoadingModelDefaults &&+ state.modelDefaultsAppliedFor === model+ ) {+ return;+ }+ await new Promise((resolve) => setTimeout(resolve, 5));+ }+ throw new Error("model defaults did not settle");+}++function serveAdapterDetails(overrides: Record<string, unknown>): void {+ setAuthFetchHandler(() =>+ Promise.resolve(+ Response.json({+ id: ADAPTER,+ config: {},+ is_vision: false,+ is_embedding: false,+ is_audio: false,+ audio_type_known: true,+ is_lora: true,+ model_type: "text",+ model_size_bytes: null,+ max_position_embeddings: 32768,+ ...overrides,+ }),+ ),+ );+}++after(() => setAuthFetchHandler(null));++test("a vision adapter picked for LoRA keeps its vision capability", async () => {+ useTrainingConfigStore.getState().reset();+ useTrainingConfigStore.setState({ trainingMethod: "lora" });+ serveAdapterDetails({ is_vision: true, model_type: "vision" });++ useTrainingConfigStore.getState().selectTrainingModel(ADAPTER, "vision");+ await waitForModelDefaults(ADAPTER);++ const state = useTrainingConfigStore.getState();+ assert.equal(state.modelFormat, "adapter");+ assert.equal(state.isVisionModel, true);+ assert.equal(state.modelType, "vision");+ assert.equal(state.maxPositionEmbeddings, 32768);+});++test("an adapter picked under full finetuning keeps its modality for a later LoRA switch", async () => {+ useTrainingConfigStore.getState().reset();+ useTrainingConfigStore.setState({ trainingMethod: "full" });+ serveAdapterDetails({ is_vision: true, model_type: "vision" });++ useTrainingConfigStore.getState().selectTrainingModel(ADAPTER, "vision");+ await waitForModelDefaults(ADAPTER);++ const state = useTrainingConfigStore.getState();+ assert.equal(state.modelFormat, "adapter");+ assert.equal(state.isVisionModel, true);+ assert.equal(state.modelType, "vision");+ assert.equal(state.maxPositionEmbeddings, 32768);+});++test("a decision adapter is typed as a decision model, not continued", async () => {+ useTrainingConfigStore.getState().reset();+ useTrainingConfigStore.setState({ trainingMethod: "qlora" });+ serveAdapterDetails({+ is_vision: false,+ is_decision: true,+ decision_layout: "clef",+ model_type: "decision",+ });++ useTrainingConfigStore.getState().selectTrainingModel(ADAPTER, "text");+ await waitForModelDefaults(ADAPTER);++ const state = useTrainingConfigStore.getState();+ assert.equal(state.modelFormat, "adapter");+ assert.equal(state.modelType, "decision");+ assert.equal(state.decisionLayout, null);+});diff --git a/studio/frontend/tests/training-validation.test.ts b/studio/frontend/tests/training-validation.test.tsindex f774484eb04..9c63e49e36d 100644--- a/studio/frontend/tests/training-validation.test.ts+++ b/studio/frontend/tests/training-validation.test.ts@@ -346,3 +346,62 @@ test("a vision model still cannot start from S3", () => {},);});++test("training validation lets LoRA and CPT continue from a saved adapter (#13140)", () => {+ const adapter = {+ ...validConfig,+ selectedModel: "/outputs/run/checkpoint-30",+ modelFormat: "adapter" as const,+ };+ for (const trainingMethod of ["lora", "qlora", "cpt"] as const) {+ assert.deepEqual(+ validateTrainingConfig({ ...adapter, trainingMethod } as never, "linux"),+ { ok: true, errorKey: null },+ );+ }+});++test("training validation refuses an adapter where a fresh adapter would be built", () => {+ const adapter = {+ ...validConfig,+ selectedModel: "/outputs/run/checkpoint-30",+ modelFormat: "adapter" as const,+ };+ const refused = { ok: false, errorKey: "studio.modelPicker.reasonAdapter" };+ assert.deepEqual(+ validateTrainingConfig(+ { ...adapter, trainingMethod: "full" } as never,+ "linux",+ ),+ refused,+ );+ assert.deepEqual(+ validateTrainingConfig(+ { ...adapter, modelType: "decision" } as never,+ "linux",+ ),+ refused,+ );+ assert.deepEqual(+ validateTrainingConfig(+ { ...adapter, isEmbeddingModel: true } as never,+ "linux",+ ),+ refused,+ );+ assert.deepEqual(validateTrainingConfig(adapter as never, "mac"), refused);+});++test("training validation refuses continuing a Hub adapter repo", () => {+ assert.deepEqual(+ validateTrainingConfig(+ {+ ...validConfig,+ selectedModel: "org/adapter",+ modelFormat: "adapter",+ } as never,+ "linux",+ ),+ { ok: false, errorKey: "studio.modelPicker.reasonAdapter" },+ );+});