Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Ask for the transformers a training model needs, before the run starts (#8721)

Daniel Hand50f49e10504
diff --git a/studio/backend/core/training/provenance.py b/studio/backend/core/training/provenance.py
index 4fbc763d65e..1b6480ef74c 100644
--- a/studio/backend/core/training/provenance.py
+++ b/studio/backend/core/training/provenance.py
@@ -105,6 +105,38 @@ def effective_training_load_in_4bit(
return not latest_tier_active
+def exact_resume_requires_current_4bit(config: dict[str, Any]) -> bool:
+ """Would activating the latest-transformers sidecar strand this stored run?
+
+ ``effective_training_load_in_4bit`` raises ``ExactResumeResourcesUnavailable`` for a
+ 4-bit run with exact-resource provenance the moment ``latest_tier_active_for`` turns
+ true, and that sidecar is a persistent overlay: once installed the checkpoint never
+ resumes in the load mode it was attested with. Callers offering the install ahead of
+ a resume ask this first, rather than trade a working resume for an upgrade the run
+ does not need.
+
+ Takes the run's STORED config (``config_json``), so it recomputes the requirement
+ from the provenance marker: ``require_exact_resume_resources`` and
+ ``require_exact_model_resource`` are stripped before persistence and exist only on
+ the live worker config ``/train/start`` assembles.
+
+ Never raises. A provenance already refusing a resume returns False: nothing the
+ install does makes that checkpoint any less resumable.
+ """
+ if not bool(config.get("load_in_4bit")):
+ return False
+ try:
+ requires_exact_model, _ = exact_resume_resource_requirements(config)
+ except ExactResumeResourcesUnavailable:
+ return False
+ except Exception:
+ return False
+ # The same disjunction effective_training_load_in_4bit tests: routes/training.py
+ # fills require_exact_model_resource from exact_resume_resource_requirements and
+ # require_exact_resume_resources from resource_provenance_is_complete.
+ return bool(requires_exact_model or resource_provenance_is_complete(config))
+
+
def _normalized_repo_id(value: Any) -> Optional[str]:
if not isinstance(value, str):
return None
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 954b451f345..30976eff181 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -444,6 +444,94 @@ class TransformersUpgradeInfo(BaseModel):
)
+class TransformersUpgradeCheckRequest(BaseModel):
+ """Ask whether loading a model needs a newer transformers than any installed overlay."""
+
+ model_name: str = Field(
+ ...,
+ min_length = 1,
+ max_length = 1024,
+ description = "Model identifier, local path or checkpoint directory to check.",
+ )
+ hf_token: Optional[str] = Field(
+ None, description = "HuggingFace token, so gated repos resolve their config.json"
+ )
+ # Cache pin, in the same four fields /models/remote-code-scan takes and resolved by
+ # the same precedence: a cached model loads from its pinned snapshot, whose
+ # config.json can name a different architecture than the repo's current one.
+ prefer_local_cache: bool = Field(
+ False,
+ description = "Inspect the cached snapshot rather than the Hub repo, when one is pinned.",
+ )
+ model_local_path: Optional[str] = Field(
+ None,
+ max_length = 4096,
+ description = "Cache directory the caller selected for this model, if any.",
+ )
+ model_snapshot_path: Optional[str] = Field(
+ None,
+ max_length = 4096,
+ description = "Exact snapshot the load is pinned to; takes precedence over "
+ "model_local_path, as it does for the remote-code scan.",
+ )
+ model_snapshot_repo_id: Optional[str] = Field(
+ None,
+ max_length = 1024,
+ description = "Repository the pinned snapshot belongs to, when it differs from model_name.",
+ )
+ resume_run_id: Optional[str] = Field(
+ None,
+ max_length = 128,
+ description = "Run this check precedes a resume of. Lets the answer say whether "
+ "installing would strand that checkpoint's exact 4-bit resume.",
+ )
+
+
+class TransformersUpgradeCheckResponse(BaseModel):
+ """Upgrade + quantization preflight for a load that does not run /validate.
+
+ /validate answers this for a chat load as part of a much larger check (GGUF
+ placement, VRAM coexistence, security review). Training needs the same two answers
+ on their own, before starting a worker that would die at model load with an
+ unrecognized-architecture error.
+ """
+
+ model_name: str = Field(..., description = "The identifier that was checked")
+ requires_transformers_upgrade: bool = Field(
+ False,
+ description = "True when the architecture is unknown to every installed transformers "
+ "but a newer transformers ships it; the caller should raise the install consent "
+ "dialog before starting the load.",
+ )
+ transformers_upgrade: Optional[TransformersUpgradeInfo] = Field(
+ None,
+ description = "Details for the consent dialog; set only when "
+ "requires_transformers_upgrade is true.",
+ )
+ requires_trust_remote_code: bool = Field(
+ False,
+ description = "Whether the model can load on the CURRENT transformers through its own "
+ "repo code, so a declined (or unavailable) install still has a path forward.",
+ )
+ latest_tier_active: bool = Field(
+ False,
+ description = "Whether the latest-transformers sidecar already routes this model.",
+ )
+ forces_16bit: bool = Field(
+ False,
+ description = "Whether a run started now would load 16-bit rather than bnb 4-bit: true "
+ "when the latest sidecar already routes the model, and when an install-only upgrade "
+ "would put it there. Lets the UI state the real precision before the run starts.",
+ )
+ install_breaks_exact_resume: bool = Field(
+ False,
+ description = "Set only for a resume_run_id: installing the offered release would "
+ "activate the latest sidecar, which permanently refuses that checkpoint's attested "
+ "4-bit model load mode. The caller must not offer the install when the run can "
+ "start without it.",
+ )
+
+
class ValidateModelResponse(BaseModel):
"""Result of model validation.
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 703aca822ee..762bcce189e 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -2206,6 +2206,8 @@ from models.inference import (
ValidateModelRequest,
ValidateModelResponse,
TransformersUpgradeInfo,
+ TransformersUpgradeCheckRequest,
+ TransformersUpgradeCheckResponse,
InstallLatestTransformersRequest,
InstallLatestTransformersResponse,
TextContentPart,
@@ -9111,6 +9113,208 @@ async def validate_model(
)
+def _upgrade_check_config_target(request: TransformersUpgradeCheckRequest) -> str:
+ """The config.json this load will actually read, by the remote-code scan's precedence.
+
+ ``routes/models.py::scan_model_remote_code`` picks its target as: a local identifier
+ stands for itself (resolved); else an exact ``model_snapshot_path`` pin wins; else
+ ``prefer_local_cache`` resolves the selected cache directory to a snapshot; else the
+ repository identifier. ``resolve_training_model_load_target`` agrees, returning
+ ``model_snapshot_path or model_name``, so this check reads the same directory: a
+ repo's current config.json says nothing about the pinned snapshot the run loads.
+
+ The identifier stays the response's ``model_name``, for display; every read, the
+ LoRA base resolve included, goes through this target, as the scan route does.
+
+ Falls back to the identifier on any resolution failure: this route never raises.
+ """
+ from utils.paths import is_local_path, normalize_path
+
+ model_name = request.model_name
+ try:
+ if is_local_path(model_name):
+ normalized = normalize_path(model_name)
+ try:
+ return str(Path(normalized).expanduser().resolve(strict = False))
+ except (OSError, RuntimeError, ValueError):
+ return normalized
+ snapshot_path = (request.model_snapshot_path or "").strip()
+ if snapshot_path:
+ from routes.models import _model_config_inspection_target
+ return _model_config_inspection_target(
+ (request.model_snapshot_repo_id or "").strip() or model_name,
+ True,
+ normalize_path(snapshot_path),
+ )
+ local_path = (request.model_local_path or "").strip()
+ if request.prefer_local_cache:
+ # No path is a legitimate cached selection (an inventory row can carry a null
+ # cachePath) and _resolve_model_snapshot then searches every cache root, as
+ # the scan route and /train/start both do. Taking the pin only when a path
+ # came along would judge those selections on the repo's current architecture
+ # while the worker loads the snapshot.
+ from core.training.training import _resolve_model_snapshot
+ return (
+ _resolve_model_snapshot(
+ model_name, normalize_path(local_path) if local_path else None
+ )
+ or model_name
+ )
+ except Exception as exc:
+ logger.debug("Cache pin resolution failed for '%s': %s", model_name, exc)
+ return model_name
+
+
+def _install_breaks_exact_resume(run_id: str) -> bool:
+ """Would installing the offered release strand the checkpoint of ``run_id``?
+
+ The latest sidecar is a persistent overlay, and a 4-bit run with attested exact
+ resource provenance only resumes in the load mode it was attested with:
+ ``effective_training_load_in_4bit`` raises the moment the sidecar routes it. So an
+ install consented to on the way into a resume is not undoable.
+
+ Answers False for an unknown run: a resume that cannot find its own row is not one
+ this route should be suppressing an install for.
+ """
+ from core.training.provenance import exact_resume_requires_current_4bit
+ from core.training.resume import training_run_config
+ from storage.studio_db import get_run
+
+ try:
+ run = get_run(run_id)
+ if run is None:
+ return False
+ return exact_resume_requires_current_4bit(training_run_config(run))
+ except Exception as exc:
+ logger.debug("Exact-resume check failed for run '%s': %s", run_id, exc)
+ return False
+
+
+# studio_router only: a Studio preflight, kept off the OpenAI-compatible /v1 mount.
+@studio_router.post("/transformers-upgrade-check", response_model = TransformersUpgradeCheckResponse)
+async def check_transformers_upgrade_route(
+ request: TransformersUpgradeCheckRequest, current_subject: str = Depends(get_current_subject)
+):
+ """
+ Does loading this model need a newer transformers than any installed overlay?
+
+ /validate answers this for a chat load, but only as one field of a check that also
+ resolves a ModelConfig, picks a GPU placement and runs the coexistence guard, none of
+ which apply to a training start and several of which refuse while a run is active. So
+ training asks on its own here, before spawning a worker that would otherwise die at
+ model load with an unrecognized-architecture error the user cannot act on.
+
+ Answers the same way /validate does: check_upgrade_for_model across [adapter, base],
+ inside the same forced-offline window, on a worker thread. Also reports whether the
+ run would load 16-bit instead of bnb 4-bit, which is what the latest sidecar means
+ for training. Never raises: an unreadable model reports "no upgrade needed" and the
+ caller proceeds exactly as it did before.
+ """
+ from utils.transformers_version import latest_tier_active_for
+
+ model_name = request.model_name
+ # Inspect what the load will open, not what the identifier resolves to today.
+ load_target = await asyncio.to_thread(_upgrade_check_config_target, request)
+ targets = [load_target]
+ try:
+ from utils.models.model_config import get_base_model_from_lora_identifier
+
+ # The worker activates transformers for the BASE model, so an adapter is judged
+ # by what it is an adapter for. Resolved from the load target rather than the
+ # identifier, as the worker and the scan route both do: a repo that repointed
+ # base_model_name_or_path since the pin was taken would otherwise have this
+ # route judging a base the run never loads.
+ base = await asyncio.to_thread(
+ _offline_guarded,
+ load_target,
+ get_base_model_from_lora_identifier,
+ load_target,
+ request.hf_token,
+ )
+ if base:
+ targets.append(base)
+ except Exception:
+ pass
+ targets = list(dict.fromkeys(targets))
+
+ transformers_upgrade: Optional[TransformersUpgradeInfo] = None
+ try:
+ from utils.transformers_latest import check_upgrade_for_model
+ for target in targets:
+ upgrade = await asyncio.to_thread(
+ _offline_guarded,
+ target,
+ check_upgrade_for_model,
+ target,
+ request.hf_token,
+ )
+ if upgrade is not None:
+ transformers_upgrade = TransformersUpgradeInfo(**upgrade)
+ break
+ except Exception as exc:
+ logger.debug("Transformers upgrade check failed for '%s': %s", model_name, exc)
+
+ requires_trust_remote_code = False
+ try:
+ requires_trust_remote_code = await asyncio.to_thread(
+ _offline_guarded,
+ targets,
+ lambda: any(
+ _requires_trust_remote_code_for_model(target, request.hf_token)
+ for target in targets
+ ),
+ )
+ except Exception as exc:
+ logger.debug("Custom-code check failed for '%s': %s", model_name, exc)
+
+ latest_tier_active = False
+ try:
+ latest_tier_active = await asyncio.to_thread(
+ _offline_guarded,
+ # Every target, not just the load target: latest_tier_active_for resolves a
+ # remote adapter's base itself, so the base is fetched too.
+ tuple(targets),
+ latest_tier_active_for,
+ load_target,
+ request.hf_token,
+ )
+ except Exception as exc:
+ logger.debug("Latest-tier check failed for '%s': %s", model_name, exc)
+
+ # An offered install lands the model on the latest sidecar, which forces 16-bit (bnb
+ # 4-bit feeds quantized experts into unvalidated paths for brand-new architectures).
+ # A dev-only upgrade is never installed, so it changes nothing. Same rule /validate
+ # applies: a model with a custom-code fallback still loads 4-bit on the current
+ # transformers and the dialog offers that way out, so a merely offered upgrade
+ # cannot be claimed as 16-bit. Only an install-only upgrade, or a sidecar already
+ # routing the model, forces it.
+ install_only_upgrade = bool(
+ transformers_upgrade is not None
+ and transformers_upgrade.supported_in_pypi
+ and transformers_upgrade.pypi_version
+ and not requires_trust_remote_code
+ )
+ # Already on the sidecar: the install is not what would strand the checkpoint, and
+ # the resume is refused (or 16-bit) whatever this route answers.
+ install_breaks_exact_resume = False
+ if request.resume_run_id and not latest_tier_active:
+ install_breaks_exact_resume = await asyncio.to_thread(
+ _install_breaks_exact_resume, request.resume_run_id
+ )
+ return TransformersUpgradeCheckResponse(
+ model_name = model_name,
+ requires_transformers_upgrade = transformers_upgrade is not None,
+ transformers_upgrade = transformers_upgrade,
+ # Already booleans: False, or the preflight's own bool result. Re-wrapping the
+ # custom-code one in bool() reads as the raw-YAML pattern the GGUF consistency
+ # guard forbids, and it was never needed here.
+ requires_trust_remote_code = requires_trust_remote_code,
+ latest_tier_active = latest_tier_active,
+ forces_16bit = latest_tier_active or install_only_upgrade,
+ install_breaks_exact_resume = install_breaks_exact_resume,
+ )
+
+
# studio_router only: admin action, kept off the OpenAI-compatible /v1 mount.
@studio_router.post(
"/install-latest-transformers", response_model = InstallLatestTransformersResponse
diff --git a/studio/backend/tests/test_training_provenance.py b/studio/backend/tests/test_training_provenance.py
index 66329dd97cd..016cc571b7c 100644
--- a/studio/backend/tests/test_training_provenance.py
+++ b/studio/backend/tests/test_training_provenance.py
@@ -16,6 +16,8 @@ from core.training.provenance import (
RESOURCE_PROVENANCE_KEY,
attest_loaded_dataset,
build_worker_provenance_event,
+ effective_training_load_in_4bit,
+ exact_resume_requires_current_4bit,
exact_resume_resource_requirements,
exact_dataset_snapshot_path,
exact_model_snapshot_path,
@@ -104,6 +106,49 @@ def test_exact_direct_snapshots_produce_complete_resumable_provenance(tmp_path):
assert resource_provenance_allows_resume(persisted) is True
+def test_a_4bit_run_declares_that_the_latest_sidecar_would_strand_it(tmp_path):
+ """The question the upgrade gate asks before it offers an install ahead of a resume.
+
+ Installing the latest transformers is not undoable: the sidecar is a persistent
+ overlay, and from then on ``effective_training_load_in_4bit`` refuses this
+ checkpoint outright. So the gate has to know beforehand, from the STORED config --
+ which is exactly where ``require_exact_resume_resources`` and
+ ``require_exact_model_resource`` do not exist, because ``_sanitize_db_config``
+ strips both before the row is written.
+ """
+ config, event, model, _dataset = _complete_event(tmp_path, load_in_4bit = True)
+ persisted = {**config, **normalize_worker_provenance_event(event, config)}
+ assert "require_exact_resume_resources" not in persisted
+ assert "require_exact_model_resource" not in persisted
+
+ assert exact_resume_requires_current_4bit(persisted) is True
+ # And the refusal it is predicting, from the flags routes/training.py rebuilds.
+ with patch("utils.transformers_version.latest_tier_active_for", return_value = True):
+ with pytest.raises(ExactResumeResourcesUnavailable):
+ effective_training_load_in_4bit(
+ {**persisted, "require_exact_model_resource": True}, str(model), None
+ )
+
+
+def test_a_16bit_run_has_no_4bit_load_mode_to_lose(tmp_path):
+ config, event, _model, _dataset = _complete_event(tmp_path, load_in_4bit = False)
+ persisted = {**config, **normalize_worker_provenance_event(event, config)}
+ assert exact_resume_requires_current_4bit(persisted) is False
+
+
+def test_an_unresumable_provenance_is_not_made_worse_by_the_install(tmp_path):
+ # Already refused, so there is no working resume for the install to take away.
+ config, event, _model, _dataset = _complete_event(tmp_path, load_in_4bit = True)
+ persisted = {**config, **normalize_worker_provenance_event(event, config)}
+ persisted[RESOURCE_PROVENANCE_KEY] = {
+ **persisted[RESOURCE_PROVENANCE_KEY],
+ "model_status": "incomplete",
+ }
+ with pytest.raises(ExactResumeResourcesUnavailable):
+ exact_resume_resource_requirements(persisted)
+ assert exact_resume_requires_current_4bit(persisted) is False
+
+
@pytest.mark.parametrize(
"repo_id",
["_owner/_repo_", f"{'a' * 96}/{'b' * 96}"],
diff --git a/studio/backend/tests/test_training_transformers_upgrade_gate.py b/studio/backend/tests/test_training_transformers_upgrade_gate.py
new file mode 100644
index 00000000000..3755cc0da3c
--- /dev/null
+++ b/studio/backend/tests/test_training_transformers_upgrade_gate.py
@@ -0,0 +1,456 @@
+# 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 upgrade preflight the Train tab runs before it starts a worker.
+
+A training start on a model whose ``model_type`` no installed transformers ships used
+to be accepted and then killed at model load ("... is not supported yet in
+transformers==5.3.0"). Chat asks first, through /validate; training could not reuse that
+route (it resolves a ModelConfig, picks a GPU placement and runs the chat coexistence
+guard), so it asks here instead.
+"""
+
+import asyncio
+import sys
+from pathlib import Path
+
+import pytest
+
+_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
+if _BACKEND_DIR not in sys.path:
+ sys.path.insert(0, _BACKEND_DIR)
+
+MODEL = "unsloth/Muse-Glimmer-30B-unsloth-bnb-4bit"
+UPGRADE = {
+ "model_type": "muse_glimmer",
+ "pypi_version": "5.15.0",
+ "supported_in_pypi": True,
+ "supported_in_main": True,
+}
+
+
+def _route():
+ pytest.importorskip("fastapi", reason = "inference stack not installed")
+ return pytest.importorskip("routes.inference", reason = "inference stack not installed")
+
+
+def _stub(
+ monkeypatch,
+ *,
+ upgrade = None,
+ latest_tier = False,
+ trust_remote_code = False,
+ inspected = None,
+):
+ """Answer the three preflights the route composes, and nothing else.
+
+ ``inspected`` collects every target the preflights were pointed at, so a test can
+ assert WHICH copy of the model was read.
+ """
+ inf_mod = _route()
+ import utils.transformers_latest as latest_mod
+ import utils.transformers_version as tv
+
+ def _record(target):
+ if inspected is not None:
+ inspected.append(target)
+
+ def _trust_remote_code(target, *args, **kwargs):
+ _record(target)
+ return trust_remote_code
+
+ def _check_upgrade(target, *args, **kwargs):
+ _record(target)
+ return upgrade
+
+ def _latest_tier(target, *args, **kwargs):
+ _record(target)
+ return latest_tier
+
+ monkeypatch.setattr(inf_mod, "_requires_trust_remote_code_for_model", _trust_remote_code)
+ monkeypatch.setattr(
+ inf_mod, "_hf_offline_if_unreachable", lambda: __import__("contextlib").nullcontext()
+ )
+ monkeypatch.setattr(latest_mod, "check_upgrade_for_model", _check_upgrade)
+ monkeypatch.setattr(tv, "latest_tier_active_for", _latest_tier)
+ monkeypatch.setattr(
+ "utils.models.model_config.get_base_model_from_lora_identifier", lambda *a, **k: None
+ )
+ return inf_mod
+
+
+def _call(
+ inf_mod,
+ model = MODEL,
+ hf_token = None,
+ **fields,
+):
+ from models.inference import TransformersUpgradeCheckRequest
+ return asyncio.run(
+ inf_mod.check_transformers_upgrade_route(
+ TransformersUpgradeCheckRequest(model_name = model, hf_token = hf_token, **fields),
+ "tester",
+ )
+ )
+
+
+def test_installable_upgrade_is_reported_with_its_version(monkeypatch):
+ inf_mod = _stub(monkeypatch, upgrade = UPGRADE)
+ response = _call(inf_mod)
+ assert response.requires_transformers_upgrade is True
+ assert response.transformers_upgrade.model_type == "muse_glimmer"
+ assert response.transformers_upgrade.pypi_version == "5.15.0"
+ # The install lands the model on the latest sidecar, and that sidecar trains 16-bit.
+ assert response.forces_16bit is True
+ assert response.latest_tier_active is False
+
+
+def test_dev_only_upgrade_does_not_claim_16bit(monkeypatch):
+ # Unsloth never installs a transformers dev build, so nothing about the run changes.
+ inf_mod = _stub(
+ monkeypatch,
+ upgrade = {**UPGRADE, "supported_in_pypi": False},
+ )
+ response = _call(inf_mod)
+ assert response.requires_transformers_upgrade is True
+ assert response.forces_16bit is False
+
+
+def test_already_routed_model_reports_16bit_without_an_upgrade(monkeypatch):
+ # The second run on a provisioned sidecar: nothing to install, still no 4-bit. The
+ # Configure preview reads "QLoRA - 4-bit" without this, understating the run's VRAM.
+ inf_mod = _stub(monkeypatch, upgrade = None, latest_tier = True)
+ response = _call(inf_mod)
+ assert response.requires_transformers_upgrade is False
+ assert response.transformers_upgrade is None
+ assert response.latest_tier_active is True
+ assert response.forces_16bit is True
+
+
+def test_supported_model_needs_nothing(monkeypatch):
+ inf_mod = _stub(monkeypatch, upgrade = None, latest_tier = False)
+ response = _call(inf_mod)
+ assert response.requires_transformers_upgrade is False
+ assert response.forces_16bit is False
+ assert response.model_name == MODEL
+
+
+def test_custom_code_fallback_is_reported(monkeypatch):
+ # Feeds the dialog's "continue with custom code" way out, exactly as /validate does.
+ inf_mod = _stub(monkeypatch, upgrade = UPGRADE, trust_remote_code = True)
+ assert _call(inf_mod).requires_trust_remote_code is True
+
+
+def test_a_merely_offered_upgrade_keeps_4bit_when_custom_code_can_load_it(monkeypatch):
+ # The dialog offers "continue with custom code" for these, and taking it installs
+ # nothing: the worker runs on the current transformers and loads bnb 4-bit. Claiming
+ # 16-bit would tell the preview 4-bit is unavailable when it is not, oversizing the
+ # run's VRAM. /validate exempts these the same way (_install_only_upgrade is gated
+ # on `not requires_trust_remote_code`).
+ inf_mod = _stub(monkeypatch, upgrade = UPGRADE, trust_remote_code = True)
+ response = _call(inf_mod)
+ assert response.requires_transformers_upgrade is True
+ assert response.forces_16bit is False
+
+
+def test_an_active_sidecar_forces_16bit_even_with_custom_code(monkeypatch):
+ # No install to decline: the sidecar already routes this model, and it trains 16-bit
+ # whatever the repo ships.
+ inf_mod = _stub(monkeypatch, upgrade = UPGRADE, trust_remote_code = True, latest_tier = True)
+ assert _call(inf_mod).forces_16bit is True
+
+
+def test_a_failing_preflight_never_fails_the_start(monkeypatch):
+ # This gate is additive. If it raised, it would block starts that work today.
+ inf_mod = _stub(monkeypatch)
+ import utils.transformers_latest as latest_mod
+ import utils.transformers_version as tv
+
+ def _boom(*args, **kwargs):
+ raise RuntimeError("network exploded")
+
+ monkeypatch.setattr(latest_mod, "check_upgrade_for_model", _boom)
+ monkeypatch.setattr(tv, "latest_tier_active_for", _boom)
+ monkeypatch.setattr(inf_mod, "_requires_trust_remote_code_for_model", _boom)
+
+ response = _call(inf_mod)
+ assert response.requires_transformers_upgrade is False
+ assert response.forces_16bit is False
+
+
+def _cached_snapshot(
+ monkeypatch,
+ root,
+ repo_id = "org/model",
+ commit = "commit-a",
+):
+ """A real HF-layout cache entry: the pin resolvers validate the layout AND the root."""
+ from hub.utils import hf_cache_state
+
+ monkeypatch.setattr(hf_cache_state, "hf_cache_roots", lambda **kwargs: [root])
+ snapshot = root / f"models--{repo_id.replace('/', '--')}" / "snapshots" / commit
+ snapshot.mkdir(parents = True)
+ (snapshot / "config.json").write_text("{}", encoding = "utf-8")
+ (snapshot / "model.safetensors").write_bytes(b"weights")
+ return snapshot
+
+
+def test_a_pinned_snapshot_is_what_gets_inspected(monkeypatch, tmp_path):
+ # The gate used to be handed the Hub identifier for a cached model, while the
+ # remote-code gate and the worker both load the pinned snapshot
+ # (resolve_training_model_load_target returns model_snapshot_path or model_name). A
+ # repo's current config.json says nothing about the snapshot this run opens.
+ inspected: list = []
+ inf_mod = _stub(monkeypatch, upgrade = None, inspected = inspected)
+ snapshot = _cached_snapshot(monkeypatch, tmp_path)
+
+ response = _call(
+ inf_mod,
+ model = "org/model",
+ model_snapshot_path = str(snapshot),
+ model_snapshot_repo_id = "org/model",
+ prefer_local_cache = True,
+ )
+
+ assert inspected, "the route must inspect something"
+ assert all(target == str(snapshot) for target in inspected), inspected
+ # The identifier still names the answer, for display and base-model resolution.
+ assert response.model_name == "org/model"
+
+
+def test_a_selected_cache_directory_resolves_to_its_snapshot(monkeypatch, tmp_path):
+ # prefer_local_cache without an exact pin, the second branch of the scan route's
+ # precedence: the selected cache directory resolves to the snapshot inside it.
+ inspected: list = []
+ inf_mod = _stub(monkeypatch, upgrade = None, inspected = inspected)
+ snapshot = _cached_snapshot(monkeypatch, tmp_path)
+
+ _call(
+ inf_mod,
+ model = "org/model",
+ prefer_local_cache = True,
+ model_local_path = str(snapshot.parent.parent),
+ )
+
+ assert all(target == str(snapshot) for target in inspected), inspected
+
+
+def test_the_lora_base_is_resolved_from_the_pinned_snapshot(monkeypatch, tmp_path):
+ # The worker resolves a LoRA's base from its load target
+ # (core/training/worker.py: get_base_model_from_lora_identifier(load_target)) and the
+ # scan route does the same. Reading the Hub identifier instead asks the current
+ # adapter_config.json which base to judge while the run loads the pinned snapshot's,
+ # so a repo that repointed base_model_name_or_path since the pin was taken gets every
+ # answer for a base the run never opens.
+ resolved_from: list = []
+ inf_mod = _stub(monkeypatch, upgrade = None)
+ snapshot = _cached_snapshot(monkeypatch, tmp_path)
+
+ def _base(identifier, *args, **kwargs):
+ resolved_from.append(identifier)
+ return None
+
+ monkeypatch.setattr("utils.models.model_config.get_base_model_from_lora_identifier", _base)
+
+ _call(
+ inf_mod,
+ model = "org/model",
+ model_snapshot_path = str(snapshot),
+ model_snapshot_repo_id = "org/model",
+ prefer_local_cache = True,
+ )
+
+ assert resolved_from == [str(snapshot)], resolved_from
+
+
+def test_a_known_cached_model_with_no_path_still_resolves_its_snapshot(monkeypatch, tmp_path):
+ # A cached inventory row can carry a null cachePath and the Train tab still sends
+ # prefer_local_cache for it. _resolve_model_snapshot searches every cache root for
+ # exactly that case, as routes/models.py and /train/start both rely on; requiring a
+ # path here judged those selections on the repo's current architecture while the
+ # worker loads the snapshot.
+ inspected: list = []
+ inf_mod = _stub(monkeypatch, upgrade = None, inspected = inspected)
+ snapshot = _cached_snapshot(monkeypatch, tmp_path)
+ from hub.utils import hf_cache_state
+
+ monkeypatch.setattr(
+ hf_cache_state, "iter_repo_cache_dirs", lambda *a, **k: [snapshot.parent.parent]
+ )
+
+ _call(inf_mod, model = "org/model", prefer_local_cache = True)
+
+ assert all(target == str(snapshot) for target in inspected), inspected
+
+
+def test_an_unpinned_model_is_still_checked_by_identifier(monkeypatch):
+ inspected: list = []
+ inf_mod = _stub(monkeypatch, upgrade = None, inspected = inspected)
+ _call(inf_mod)
+ assert all(target == MODEL for target in inspected), inspected
+
+
+def test_an_unresolvable_pin_falls_back_to_the_identifier(monkeypatch, tmp_path):
+ # _model_config_inspection_target 404s for a snapshot that is gone. This preflight is
+ # additive, so it answers about the identifier rather than failing the start.
+ inspected: list = []
+ inf_mod = _stub(monkeypatch, upgrade = None, inspected = inspected)
+
+ _call(
+ inf_mod,
+ model = "org/model",
+ prefer_local_cache = True,
+ model_snapshot_path = str(tmp_path / "models--org--model" / "snapshots" / "gone"),
+ model_snapshot_repo_id = "org/model",
+ )
+
+ assert all(target == "org/model" for target in inspected), inspected
+
+
+def test_an_exact_4bit_resume_is_flagged_before_the_install_is_offered(monkeypatch):
+ # effective_training_load_in_4bit RAISES for this config once the latest sidecar
+ # routes the model, and that sidecar is a persistent overlay: consenting to the
+ # install on the way into a resume strands the checkpoint for good. The caller needs
+ # to know before it shows the dialog.
+ inf_mod = _stub(monkeypatch, upgrade = UPGRADE, trust_remote_code = True)
+ monkeypatch.setattr(
+ "storage.studio_db.get_run",
+ lambda run_id: {"config_json": {"load_in_4bit": True}} if run_id == "run-42" else None,
+ )
+ monkeypatch.setattr(
+ "core.training.provenance.exact_resume_resource_requirements",
+ lambda config: (True, True),
+ )
+
+ assert _call(inf_mod, resume_run_id = "run-42").install_breaks_exact_resume is True
+ # No run named, no claim: a fresh start has no checkpoint to strand.
+ assert _call(inf_mod).install_breaks_exact_resume is False
+ # An unknown run is not one to suppress an install for.
+ assert _call(inf_mod, resume_run_id = "missing").install_breaks_exact_resume is False
+
+
+def test_an_already_active_sidecar_is_not_blamed_on_the_install(monkeypatch):
+ # The overlay is already installed, so the resume is refused (or 16-bit) whatever
+ # this route answers; suppressing the dialog would change nothing for the better.
+ inf_mod = _stub(monkeypatch, upgrade = UPGRADE, latest_tier = True)
+ monkeypatch.setattr(
+ "storage.studio_db.get_run", lambda run_id: {"config_json": {"load_in_4bit": True}}
+ )
+ monkeypatch.setattr(
+ "core.training.provenance.exact_resume_resource_requirements",
+ lambda config: (True, True),
+ )
+
+ assert _call(inf_mod, resume_run_id = "run-42").install_breaks_exact_resume is False
+
+
+def test_route_is_off_the_openai_compatible_mount():
+ # /v1 is the OpenAI-compatible surface; a Studio preflight has no business there.
+ inf_mod = _route()
+ paths = {route.path for route in inf_mod.studio_router.routes}
+ assert "/transformers-upgrade-check" in paths
+ assert "/transformers-upgrade-check" not in {route.path for route in inf_mod.router.routes}
+
+
+# The tests above prove the gate fires. These pin the far more common case where it
+# must not: everything that worked before it existed still behaving as it did.
+
+
+def test_an_old_client_sends_the_identifier_alone():
+ # Every added field has to be optional, or a frontend built before them (an
+ # in-place upgrade mid-restart) fails validation on a payload the route once took.
+ from models.inference import TransformersUpgradeCheckRequest
+
+ request = TransformersUpgradeCheckRequest(model_name = MODEL)
+ assert request.prefer_local_cache is False
+ assert (request.model_local_path, request.model_snapshot_path) == (None, None)
+ assert (request.model_snapshot_repo_id, request.resume_run_id) == (None, None)
+
+
+def test_a_minimal_response_reads_as_the_pre_gate_behaviour():
+ # What an older client sees and a newer one falls back to: no upgrade, no
+ # precision claim, no refusal.
+ from models.inference import TransformersUpgradeCheckResponse
+
+ response = TransformersUpgradeCheckResponse(model_name = MODEL)
+ assert response.requires_transformers_upgrade is False
+ assert response.requires_trust_remote_code is False
+ assert response.latest_tier_active is False
+ assert response.forces_16bit is False
+ assert response.install_breaks_exact_resume is False
+
+
+ "latest_tier,installable,custom_code,expected",
+ [
+ (False, False, False, False), # nothing to do at all
+ (False, False, True, False), # custom code only: loads today, in 4-bit
+ (False, True, False, True), # install-only upgrade: the install forces 16-bit
+ (False, True, True, False), # the fallback keeps 4-bit, so 16-bit is not claimed
+ (True, False, False, True), # already on the sidecar
+ (True, False, True, True),
+ (True, True, False, True),
+ (True, True, True, True),
+ ],
+)
+def test_forces_16bit_over_every_combination(
+ monkeypatch, latest_tier, installable, custom_code, expected
+):
+ # The preview draws its VRAM claim from this field, so a wrong cell is a wrong
+ # number in front of the user. Exhaustive rather than sampled.
+ upgrade = None
+ if installable or custom_code:
+ upgrade = {
+ **UPGRADE,
+ "supported_in_pypi": installable,
+ "pypi_version": "5.15.0" if installable else None,
+ }
+ inf_mod = _stub(
+ monkeypatch, upgrade = upgrade, latest_tier = latest_tier, trust_remote_code = custom_code
+ )
+ assert _call(inf_mod).forces_16bit is expected
+
+
+ "failure",
+ [
+ OSError("network is unreachable"),
+ TimeoutError("timed out"),
+ ValueError("malformed config.json"),
+ KeyError("architectures"),
+ ],
+)
+def test_a_failing_preflight_never_escapes_the_route(monkeypatch, failure):
+ # The additive promise, and the only thing behind it: this route runs in front of
+ # every start, so a raise here fails a start for a model that loads fine.
+ inf_mod = _route()
+ import utils.transformers_latest as latest_mod
+ import utils.transformers_version as tv
+
+ def _boom(*args, **kwargs):
+ raise failure
+
+ monkeypatch.setattr(inf_mod, "_requires_trust_remote_code_for_model", _boom)
+ monkeypatch.setattr(
+ inf_mod, "_hf_offline_if_unreachable", lambda: __import__("contextlib").nullcontext()
+ )
+ monkeypatch.setattr(latest_mod, "check_upgrade_for_model", _boom)
+ monkeypatch.setattr(tv, "latest_tier_active_for", _boom)
+ monkeypatch.setattr(
+ "utils.models.model_config.get_base_model_from_lora_identifier", lambda *a, **k: None
+ )
+
+ response = _call(inf_mod)
+ assert response.requires_transformers_upgrade is False
+ assert response.forces_16bit is False
+
+
+def test_the_route_is_behind_authentication():
+ # Otherwise this is a new way to make the server fetch an arbitrary repo id.
+ import inspect
+
+ inf_mod = _route()
+ subject = inspect.signature(inf_mod.check_transformers_upgrade_route).parameters[
+ "current_subject"
+ ]
+ assert subject.default is not inspect.Parameter.empty
diff --git a/studio/backend/tests/test_transformers_latest.py b/studio/backend/tests/test_transformers_latest.py
index af48d674cc8..9a015b244a2 100644
--- a/studio/backend/tests/test_transformers_latest.py
+++ b/studio/backend/tests/test_transformers_latest.py
@@ -797,8 +797,73 @@ class TestCompatPlan:
assert extras == () and blockers == []
+def test_get_snapshot_waits_for_inflight_fetch(monkeypatch):
+ """A caller arriving mid-fetch gets the running fetch's answer, not "no answer".
+
+ The Configure preview starts a check as soon as the tab renders, so a user who
+ presses Start while it is still running sends a second, concurrent check. Answering
+ that one None reads as "no upgrade needed" all the way up, and the run launches on a
+ model no installed transformers can load -- the exact failure this gate exists to
+ stop. The loser must wait for the snapshot instead.
+ """
+ import threading as _threading
+
+ tl.clear_caches()
+ monkeypatch.setattr(tl, "_load_snapshot_file", lambda: None)
+ monkeypatch.setattr(tl, "_save_snapshot_file", lambda snapshot: None)
+ fetch_started = _threading.Event()
+ release = _threading.Event()
+ calls = {"n": 0}
+
+ def slow_refresh():
+ calls["n"] += 1
+ fetch_started.set()
+ release.wait(10)
+ return {
+ "schema": tl._SNAPSHOT_SCHEMA,
+ "fetched_at": time.time(),
+ "pypi_version": "5.99.0",
+ "pypi_model_types": ["brandnew"],
+ "main_model_types": ["brandnew"],
+ "main_checked": True,
+ }
+
+ monkeypatch.setattr(tl, "_refresh_snapshot", slow_refresh)
+ answers: dict[str, dict | None] = {}
+ winner = _threading.Thread(target = lambda: answers.__setitem__("winner", tl._get_snapshot()))
+ winner.start()
+ assert fetch_started.wait(10)
+ loser = _threading.Thread(target = lambda: answers.__setitem__("loser", tl._get_snapshot()))
+ loser.start()
+ # The loser is parked on the in-flight fetch; nothing can land until it is released.
+ loser.join(0.5)
+ assert loser.is_alive()
+ release.set()
+ winner.join(10)
+ loser.join(10)
+ assert calls["n"] == 1
+ assert answers["winner"] is not None and answers["winner"]["pypi_version"] == "5.99.0"
+ assert answers["loser"] is not None and answers["loser"]["pypi_version"] == "5.99.0"
+ tl.clear_caches()
+
+
+def test_inflight_wait_covers_a_whole_refresh():
+ """The wait a loser makes must outlast the fetch it is waiting for.
+
+ A refresh is five sequential URLs (PyPI, then both auto files at the release tag and
+ at main), each allowed one retry at the fetch timeout, so it can legitimately run for
+ the full product of those three numbers. A wait shorter than that expires while the
+ winner is still working, and the None it then answers is read as "no upgrade needed"
+ by the Start button -- the run launches on the architecture this gate exists to stop.
+ """
+ urls = 1 + 2 * len(tl._AUTO_FILES)
+ assert tl._REFRESH_URL_COUNT == urls
+ worst_case = urls * (1 + tl._FETCH_RETRIES) * tl._FETCH_TIMEOUT_SECONDS
+ assert tl._INFLIGHT_WAIT_SECONDS >= worst_case
+
+
def test_get_snapshot_dedupes_concurrent_fetch(monkeypatch):
- """While one thread is fetching, other callers return None instead of stacking fetches."""
+ """A caller that finds a fetch in flight never starts a second one."""
with tl._lock:
tl._is_fetching = True
calls = {"n": 0}
@@ -1097,3 +1162,224 @@ def test_failed_staging_install_removes_staging_dir(tmp_path, monkeypatch):
monkeypatch.setattr(tv, "_ensure_venv_dir", _fake_ensure)
assert ensure_latest_transformers_venv("5.13.0") is False
assert not Path(str(venv_dir) + ".staging").exists()
+
+
+def _slow_drip_server(chunks: int, gap: float):
+ """A localhost HTTP server that dribbles a body *gap* seconds at a time.
+
+ Every individual socket read completes well inside the fetch timeout, so a
+ socket-level timeout never fires; only a wall-clock budget on the transfer can stop
+ it. Returns the URL; the thread is a daemon and dies with the test session.
+ """
+ import socket as _socket
+ import threading as _threading
+
+ sock = _socket.socket()
+ sock.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, 1)
+ sock.bind(("127.0.0.1", 0))
+ sock.listen(1)
+
+ def serve():
+ try:
+ conn, _ = sock.accept()
+ conn.recv(65536)
+ piece = b"x" * 8
+ conn.sendall(
+ b"HTTP/1.1 200 OK\r\nContent-Length: %d\r\nConnection: close\r\n\r\n"
+ % (len(piece) * chunks)
+ )
+ for _ in range(chunks):
+ time.sleep(gap)
+ conn.sendall(piece)
+ conn.close()
+ except Exception:
+ pass
+
+ _threading.Thread(target = serve, daemon = True).start()
+ return f"http://127.0.0.1:{sock.getsockname()[1]}/"
+
+
+def test_fetch_text_bounds_the_whole_transfer_not_just_socket_operations(monkeypatch):
+ """A response that dribbles bytes must hit the fetch budget, not run indefinitely.
+
+ ``urlopen(timeout=...)`` is a SOCKET timeout: the CPython docs specify it as "a
+ timeout in seconds for blocking operations like the connection attempt", so it bounds
+ each individual read rather than the whole transfer. A mirror that sends a few bytes
+ just inside that timeout therefore keeps ``resp.read()`` alive for as long as it
+ likes, and every wait derived from the timeout stops being a worst case -- the loser
+ it strands answers None, which reads as "no upgrade needed" at the Start button.
+ """
+ monkeypatch.setattr(tl, "_FETCH_RETRIES", 0)
+ monkeypatch.setattr(tl, "_FETCH_TIMEOUT_SECONDS", 1.0)
+ monkeypatch.setattr(tl, "_FETCH_DEADLINE_SECONDS", 0.4)
+ # 30 chunks 0.05s apart: ~1.5s of transfer, every gap far inside the socket timeout.
+ url = _slow_drip_server(chunks = 30, gap = 0.05)
+ started = time.monotonic()
+ body = tl._fetch_text(url)
+ elapsed = time.monotonic() - started
+ assert body is None, "a transfer past its budget must not be accepted as an answer"
+ assert elapsed < 1.2, f"fetch ran {elapsed:.2f}s, past its own budget"
+
+
+def test_fetch_attempt_bound_covers_the_budget_and_one_blocking_read():
+ """The advertised per-attempt worst case must be the budget plus a straddling read.
+
+ The deadline is only checked between reads, so the one socket read already blocking
+ when it expires still runs to the socket timeout. Deriving the attempt bound from
+ both is what keeps the in-flight wait a real ceiling rather than an optimistic one.
+ """
+ assert tl._FETCH_ATTEMPT_SECONDS == tl._FETCH_DEADLINE_SECONDS + tl._FETCH_TIMEOUT_SECONDS
+ urls = 1 + 2 * len(tl._AUTO_FILES)
+ worst_case = urls * (1 + tl._FETCH_RETRIES) * tl._FETCH_ATTEMPT_SECONDS
+ assert tl._INFLIGHT_WAIT_SECONDS >= worst_case
+
+
+def test_waiter_never_answers_no_upgrade_while_the_refresh_is_still_running(monkeypatch):
+ """An expired wait must not be turned into "no upgrade needed".
+
+ The wait is a computed deadline, and the fetch it bounds is only as bounded as its
+ own budget makes it. If the winner is still legitimately working when the clock runs
+ out, the loser used to return None -- and None is read as "no upgrade needed" all the
+ way up to Start, which launches the run on the architecture this gate exists to stop.
+ A loser waits for the refresh's actual completion instead.
+ """
+ import threading as _threading
+
+ tl.clear_caches()
+ monkeypatch.setattr(tl, "_load_snapshot_file", lambda: None)
+ monkeypatch.setattr(tl, "_save_snapshot_file", lambda snapshot: None)
+ # The wait expires long before the refresh finishes: a slow mirror doing exactly
+ # what the socket timeout permits.
+ monkeypatch.setattr(tl, "_INFLIGHT_WAIT_SECONDS", 0.05)
+ fetch_started = _threading.Event()
+
+ def slow_refresh():
+ fetch_started.set()
+ time.sleep(0.6)
+ return {
+ "schema": tl._SNAPSHOT_SCHEMA,
+ "fetched_at": time.time(),
+ "pypi_version": "5.99.0",
+ "pypi_model_types": ["brandnew"],
+ "main_model_types": ["brandnew"],
+ "main_checked": True,
+ }
+
+ monkeypatch.setattr(tl, "_refresh_snapshot", slow_refresh)
+ answers: dict[str, dict | None] = {}
+ winner = _threading.Thread(target = lambda: answers.__setitem__("winner", tl._get_snapshot()))
+ winner.start()
+ assert fetch_started.wait(10)
+ loser = _threading.Thread(target = lambda: answers.__setitem__("loser", tl._get_snapshot()))
+ loser.start()
+ winner.join(10)
+ loser.join(10)
+ assert answers["winner"] is not None
+ assert answers["loser"] is not None, "the loser answered 'no upgrade' mid-refresh"
+ assert answers["loser"]["pypi_version"] == "5.99.0"
+ tl.clear_caches()
+
+
+# The tests near this bound the transfer budget from above. The opposite risk lands on
+# chat as well as training: a budget that also rejects ORDINARY responses would silently
+# stop /validate ever finding an upgrade.
+
+
+class _BodyServer:
+ """Serves one body, either in full or split across chunks."""
+
+ def __init__(
+ self,
+ body: bytes,
+ chunked = False,
+ status = 200,
+ ):
+ import http.server
+ import threading
+
+ outer = self
+ self.body, self.chunked, self.status = body, chunked, status
+
+ class Handler(http.server.BaseHTTPRequestHandler):
+ protocol_version = "HTTP/1.1"
+
+ def do_GET(self): # noqa: N802
+ self.send_response(outer.status)
+ if outer.chunked:
+ self.send_header("Transfer-Encoding", "chunked")
+ self.end_headers()
+ step = max(1, len(outer.body) // 7)
+ for i in range(0, len(outer.body), step):
+ piece = outer.body[i : i + step]
+ self.wfile.write(f"{len(piece):x}\r\n".encode() + piece + b"\r\n")
+ self.wfile.write(b"0\r\n\r\n")
+ else:
+ self.send_header("Content-Length", str(len(outer.body)))
+ self.end_headers()
+ self.wfile.write(outer.body)
+ self.wfile.flush()
+
+ def log_message(self, *args):
+ pass
+
+ self.httpd = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ self.url = f"http://127.0.0.1:{self.httpd.server_port}/x"
+ self.thread = threading.Thread(target = self.httpd.serve_forever, daemon = True)
+
+ def __enter__(self):
+ self.thread.start()
+ return self
+
+ def __exit__(self, *exc):
+ self.httpd.shutdown()
+ self.httpd.server_close()
+
+
+_AUTO_SOURCE = textwrap.dedent(
+ """
+ CONFIG_MAPPING_NAMES = OrderedDict[str, str](
+ [
+ ("albert", "AlbertConfig"),
+ ("llama", "LlamaConfig"),
+ ]
+ )
+ """
+)
+
+
[email protected]("chunked", [False, True])
+def test_an_ordinary_response_comes_back_whole(chunked):
+ with _BodyServer(_AUTO_SOURCE.encode(), chunked = chunked) as server:
+ body = tl._fetch_text(server.url)
+ assert body is not None and body.strip() == _AUTO_SOURCE.strip()
+
+
+def test_a_multi_chunk_body_is_not_truncated_by_the_budget():
+ # configuration_auto.py is ~200 KB against a 64 KB read, so several chunks is the
+ # normal path rather than an edge case.
+ payload = (_AUTO_SOURCE + "# padding\n" * 40_000).encode()
+ with _BodyServer(payload) as server:
+ body = tl._fetch_text(server.url)
+ assert body is not None and len(body) == len(payload.decode())
+
+
+def test_an_empty_body_is_not_a_failure():
+ with _BodyServer(b"") as server:
+ assert tl._fetch_text(server.url) == ""
+
+
+def test_a_missing_file_stays_distinguishable_from_a_failure():
+ # auto_mappings.py does not exist on pre-5.10 tags, so a 404 stays its own answer:
+ # as a failure it breaks every lookup against an older tag, as an empty body it
+ # caches a mapping that supports nothing.
+ with _BodyServer(b"nope", status = 404) as server:
+ assert tl._fetch_text(server.url) == tl._FETCH_MISSING
+
+
+def test_a_truncated_source_fails_the_lookup_instead_of_shrinking_the_map(monkeypatch):
+ # The worst outcome here: a short mapping cached for the TTL as "the architectures
+ # this release ships", offering an upgrade to every model missing from it.
+ truncated = _AUTO_SOURCE[: len(_AUTO_SOURCE) // 2].encode()
+ with _BodyServer(truncated) as server:
+ monkeypatch.setattr(tl, "_RAW_URL", server.url + "?{ref}{name}")
+ assert tl._fetch_remote_model_types("v5.15.0") is None
diff --git a/studio/backend/utils/transformers_latest.py b/studio/backend/utils/transformers_latest.py
index 9f1d11be5bb..e8fa67ff157 100644
--- a/studio/backend/utils/transformers_latest.py
+++ b/studio/backend/utils/transformers_latest.py
@@ -23,8 +23,9 @@ computed exactly like the local overlay answer.
Results are cached in memory and in a small JSON snapshot under ``studio_root()/cache``
(ttl ~1 day) so repeated tier resolutions never re-fetch; failures are backed off in
-memory. Every fetch is bounded (<=5s, one retry), so a hung network cannot block model
-loading. Fully offline-safe: offline env vars or the kill switch
+memory. Every fetch is bounded by an explicit wall-clock budget on the transfer (not just
+the socket timeout, which only bounds one read), so a hung or drip-feeding network cannot
+block model loading. Fully offline-safe: offline env vars or the kill switch
``UNSLOTH_STUDIO_NO_LATEST_TRANSFORMERS=1`` make every check return None (current
behavior preserved).
@@ -68,6 +69,15 @@ _AUTO_FILES = ("configuration_auto.py", "auto_mappings.py")
_FETCH_TIMEOUT_SECONDS = 5.0
_FETCH_RETRIES = 1
+# urlopen's timeout bounds each individual read, never the whole transfer, so a mirror
+# dribbling a few bytes just inside it keeps resp.read() alive indefinitely (measured:
+# 12 chunks 1s apart read in 12.0s under timeout=5.0). The transfer gets its own
+# wall-clock budget instead: one timeout for the connect, one for the body.
+_FETCH_DEADLINE_SECONDS = 2 * _FETCH_TIMEOUT_SECONDS
+# One attempt's true worst case: the budget, plus the single socket read already blocking
+# when it runs out (the deadline is only tested between reads).
+_FETCH_ATTEMPT_SECONDS = _FETCH_DEADLINE_SECONDS + _FETCH_TIMEOUT_SECONDS
+_READ_CHUNK_BYTES = 1 << 16
_CACHE_TTL_SECONDS = 24 * 60 * 60
_FAILURE_BACKOFF_SECONDS = 300
@@ -80,6 +90,19 @@ _lock = threading.Lock()
_memory_snapshot: dict | None = None
_last_failure_at: float = 0.0
_is_fetching: bool = False
+# Set whenever no refresh is in flight; a concurrent caller waits on it for the running
+# fetch's answer instead of reporting "no answer" (see _get_snapshot).
+_fetch_done: threading.Event = threading.Event()
+_fetch_done.set()
+# Backstop for that wait, bounded by the refresh's OWN worst case: the PyPI version plus
+# both auto files at each of the two refs, each allowed its retry at _FETCH_ATTEMPT_SECONDS.
+# Derived rather than a literal, so tuning a timeout, a retry or the transfer budget cannot
+# silently shrink it below what it bounds. Only a backstop: giving up early is not graceful
+# here, since the answer it falls through to reads as "no upgrade needed" all the way to the
+# Start button, launching the run on the architecture this gate exists to stop. So the
+# waiter re-waits while the refresh is genuinely in flight (_get_snapshot).
+_REFRESH_URL_COUNT = 1 + 2 * len(_AUTO_FILES)
+_INFLIGHT_WAIT_SECONDS = _REFRESH_URL_COUNT * (1 + _FETCH_RETRIES) * _FETCH_ATTEMPT_SECONDS + 5.0
_TRUE_VALUES = {"1", "true", "yes", "on"}
@@ -99,8 +122,30 @@ def _cache_file() -> Path:
_FETCH_MISSING = "__unsloth_fetch_missing__"
+def _read_within(resp, deadline: float) -> str | None:
+ """Body of *resp*, or None if the transfer is still running at *deadline*.
+
+ ``resp.read()`` in one call has no bound at all: the socket timeout only fires on a
+ read that stalls longer than itself, so a drip-fed response never trips it. ``read1``
+ returns what has arrived instead of blocking for a full chunk, which is what lets the
+ budget be checked as the body comes in.
+ """
+ read1 = getattr(resp, "read1", None)
+ if read1 is None:
+ # A file-like that hands back the whole body in one go has nothing to dribble.
+ return resp.read().decode("utf-8", "replace")
+ chunks: list[bytes] = []
+ while True:
+ if time.monotonic() >= deadline:
+ return None
+ chunk = read1(_READ_CHUNK_BYTES)
+ if not chunk:
+ return b"".join(chunks).decode("utf-8", "replace")
+ chunks.append(chunk)
+
+
def _fetch_text(url: str) -> str | None:
- """GET *url* with a bounded timeout and one retry; None on any failure.
+ """GET *url* within a bounded wall-clock budget, one retry; None on any failure.
Returns ``_FETCH_MISSING`` (without retrying) on HTTP 404 so callers can tell
"absent at this ref" apart from "network flaked".
@@ -109,10 +154,19 @@ def _fetch_text(url: str) -> str | None:
import urllib.request
for attempt in range(1 + _FETCH_RETRIES):
+ deadline = time.monotonic() + _FETCH_DEADLINE_SECONDS
try:
req = urllib.request.Request(url, headers = {"User-Agent": "unsloth-studio"})
with urllib.request.urlopen(req, timeout = _FETCH_TIMEOUT_SECONDS) as resp:
- return resp.read().decode("utf-8", "replace")
+ body = _read_within(resp, deadline)
+ if body is not None:
+ return body
+ logger.debug(
+ "Fetch (attempt %d) for %s outran its %.1fs budget",
+ attempt + 1,
+ url,
+ _FETCH_DEADLINE_SECONDS,
+ )
except urllib.error.HTTPError as exc:
if exc.code == 404:
return _FETCH_MISSING
@@ -236,10 +290,13 @@ def _get_snapshot() -> dict | None:
"""Current support snapshot: memory -> disk -> network, with TTL and failure backoff.
The network refresh runs outside the lock so a slow fetch cannot stall other
- threads in the ASGI pool; _is_fetching deduplicates concurrent refreshes
- (losers return None, the graceful fallthrough, rather than waiting).
+ threads in the ASGI pool; _is_fetching deduplicates concurrent refreshes, and a
+ loser waits (bounded) for the winner's answer rather than stacking a second fetch.
+ Waiting is what makes this safe to gate on: the Configure preview and the Start
+ button both ask, and a loser that answered "no answer" told the start there was no
+ upgrade, so the run launched on a model no installed transformers can load.
"""
- global _memory_snapshot, _last_failure_at, _is_fetching
+ global _memory_snapshot, _last_failure_at, _is_fetching, _fetch_done
with _lock:
if _snapshot_is_fresh(_memory_snapshot):
return _memory_snapshot
@@ -252,14 +309,31 @@ def _get_snapshot() -> dict | None:
if time.time() - _last_failure_at < _FAILURE_BACKOFF_SECONDS:
return None
if _is_fetching:
- return None
- _is_fetching = True
+ in_flight = _fetch_done
+ else:
+ in_flight = None
+ _is_fetching = True
+ _fetch_done = done = threading.Event()
+ if in_flight is not None:
+ # Wait for the refresh's actual completion, not for a clock. An expiry here is
+ # not "no upgrade needed", it is "the answer is still being fetched", and the
+ # callers above cannot tell those apart. So re-wait while this same refresh is
+ # running; the winner clears _is_fetching and sets the event in one locked
+ # finally, so either condition means it is done.
+ while not in_flight.wait(_INFLIGHT_WAIT_SECONDS):
+ with _lock:
+ if not _is_fetching or _fetch_done is not in_flight:
+ break
+ logger.debug("Still waiting on the in-flight transformers support refresh")
+ with _lock:
+ return _memory_snapshot if _snapshot_is_fresh(_memory_snapshot) else None
fresh = None
try:
fresh = _refresh_snapshot()
finally:
with _lock:
_is_fetching = False
+ done.set()
if fresh is None:
_last_failure_at = time.time()
else:
@@ -278,6 +352,7 @@ def clear_caches() -> None:
_memory_snapshot = None
_last_failure_at = 0.0
_is_fetching = False
+ _fetch_done.set()
from utils.transformers_version import end_sidecar_swap
end_sidecar_swap()
diff --git a/studio/frontend/src/features/studio/wizard/run-preview-card.tsx b/studio/frontend/src/features/studio/wizard/run-preview-card.tsx
index ffee156e52e..1f14df459ae 100644
--- a/studio/frontend/src/features/studio/wizard/run-preview-card.tsx
+++ b/studio/frontend/src/features/studio/wizard/run-preview-card.tsx
@@ -13,6 +13,7 @@ import {
useTrainingConfigStore,
useTrainingReadiness,
useTrainingResourceNotices,
+ useTrainingTransformersUpgradeNotice,
} from "@/features/training";
import { useGpuInfo } from "@/hooks";
import { type TranslationKey, useLocale, useT } from "@/i18n";
@@ -162,6 +163,43 @@ function ResourceNoticeList({
);
}
+/** What the run will really do about transformers and precision.
+ *
+ * The method row above is what the user picked, not what the backend will run: a model
+ * routed to the latest-transformers sidecar always loads 16-bit, so "QLoRA · 4-bit" for
+ * one of those is a VRAM promise the run cannot keep. Stated here, before Start. When
+ * the model also ships its own code the dialog offers both ways in and only one keeps
+ * 4-bit, so the precision line names the action rather than asserting one answer. */
+function TransformersUpgradeNotice(): ReactElement | null {
+ const t = useT();
+ const { installVersion, fourBitUnavailable, installSwitchesTo16Bit } =
+ useTrainingTransformersUpgradeNotice();
+ if (!(installVersion || fourBitUnavailable || installSwitchesTo16Bit)) {
+ return null;
+ }
+ return (
+ <section className="flex flex-col gap-2 rounded-lg border border-amber-500/25 bg-amber-500/[0.06] px-3 py-2.5">
+ {installVersion ? (
+ <p className="text-ui-10p5 leading-relaxed text-foreground/80">
+ {t("studio.preview.noticeTransformersUpgrade", {
+ version: installVersion,
+ })}
+ </p>
+ ) : null}
+ {fourBitUnavailable ? (
+ <p className="text-ui-10p5 leading-relaxed text-foreground/80">
+ {t("studio.preview.noticeSixteenBitOnly")}
+ </p>
+ ) : null}
+ {installSwitchesTo16Bit ? (
+ <p className="text-ui-10p5 leading-relaxed text-foreground/80">
+ {t("studio.preview.noticeInstallSwitchesSixteenBit")}
+ </p>
+ ) : null}
+ </section>
+ );
+}
+
function BatchPreviewValue({
batchSize,
gradientAccumulation,
@@ -488,6 +526,8 @@ export function RunPreviewCard({
<ResourceNoticeList notices={resourceNotices} />
+ <TransformersUpgradeNotice />
+
<div className="-mx-6 h-px bg-foreground/[0.07] dark:bg-white/[0.06]" />
<div className="-mt-2">{startCta}</div>
diff --git a/studio/frontend/src/features/training/api/mappers.ts b/studio/frontend/src/features/training/api/mappers.ts
index 6853acb3309..38e2a0b8e88 100644
--- a/studio/frontend/src/features/training/api/mappers.ts
+++ b/studio/frontend/src/features/training/api/mappers.ts
@@ -33,15 +33,30 @@ function buildS3PayloadConfig(config: TrainingConfigState) {
return s3;
}
+/** Whether this configuration asks the backend for a bnb 4-bit load.
+ *
+ * Exported so the UI can say what the run will do: the backend refuses 4-bit for models
+ * routed to the latest-transformers sidecar, and a preview reading "QLoRA · 4-bit" for a
+ * 16-bit run understates its VRAM by a wide margin. */
+export function trainingLoadsIn4Bit(
+ config: Pick<TrainingConfigState, "trainingMethod" | "selectedModel">,
+): boolean {
+ const isCpt = config.trainingMethod === "cpt";
+ const adapterMethod = config.trainingMethod !== "full";
+ const isQloraMethod = config.trainingMethod === "qlora";
+ const isFourBitModel = (config.selectedModel ?? "")
+ .toLowerCase()
+ .includes("4bit");
+ return (adapterMethod && isQloraMethod) || (isCpt && isFourBitModel);
+}
+
export function buildTrainingStartPayload(
config: TrainingConfigState,
hfToken: string | null,
): TrainingStartRequest {
const isCpt = config.trainingMethod === "cpt";
const adapterMethod = config.trainingMethod !== "full";
- const isQloraMethod = config.trainingMethod === "qlora";
const _selectedModelLower = (config.selectedModel ?? "").toLowerCase();
- const isFourBitModel = _selectedModelLower.includes("4bit");
// DeepSeek OCR ignores user-selected image size; do not send it.
const isDeepseekOcr =
_selectedModelLower.includes("deepseek") &&
@@ -82,7 +97,7 @@ export function buildTrainingStartPayload(
model_known_cached: config.modelKnownCached,
model_local_path: config.modelKnownCached ? config.modelLocalPath : null,
model_format: config.modelFormat,
- load_in_4bit: (adapterMethod && isQloraMethod) || (isCpt && isFourBitModel),
+ load_in_4bit: trainingLoadsIn4Bit(config),
max_seq_length: config.contextLength,
vision_image_size:
config.isVisionModel && config.isDatasetImage === true && !isDeepseekOcr
diff --git a/studio/frontend/src/features/training/hooks/use-training-transformers-upgrade-notice.ts b/studio/frontend/src/features/training/hooks/use-training-transformers-upgrade-notice.ts
new file mode 100644
index 00000000000..3bae3925081
--- /dev/null
+++ b/studio/frontend/src/features/training/hooks/use-training-transformers-upgrade-notice.ts
@@ -0,0 +1,118 @@
+// 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 { useHfTokenStore } from "@/features/hub";
+import {
+ checkTransformersUpgrade,
+ useTransformersUpgradeDialogStore,
+} from "@/features/transformers-upgrade";
+import { useEffect, useState } from "react";
+import { useShallow } from "zustand/react/shallow";
+import { trainingLoadsIn4Bit } from "../api/mappers";
+import {
+ type TrainingTransformersUpgradeNotice,
+ trainingTransformersUpgradeNotice,
+} from "../lib/training-transformers-upgrade";
+import {
+ hasUpgradeNoticeCache,
+ readUpgradeNoticeCache,
+ upgradeNoticeCacheKey,
+ writeUpgradeNoticeCache,
+} from "../lib/training-upgrade-notice-cache";
+import { useTrainingConfigStore } from "../stores/training-config-store";
+
+export type { TrainingTransformersUpgradeNotice };
+
+const EMPTY: TrainingTransformersUpgradeNotice = {
+ installVersion: null,
+ fourBitUnavailable: false,
+ installSwitchesTo16Bit: false,
+};
+
+/** What the Configure preview must disclose about the transformers this model needs.
+ *
+ * Two things it otherwise gets wrong: a model no installed transformers ships (the run
+ * stops on a consent dialog first), and the latest sidecar's 16-bit rule, which makes a
+ * "QLoRA · 4-bit" preview understate the run's VRAM by roughly threefold. */
+export function useTrainingTransformersUpgradeNotice(): TrainingTransformersUpgradeNotice {
+ const { selectedModel, trainingMethod, modelKnownCached, modelLocalPath } =
+ useTrainingConfigStore(
+ useShallow((s) => ({
+ selectedModel: s.selectedModel,
+ trainingMethod: s.trainingMethod,
+ modelKnownCached: s.modelKnownCached,
+ modelLocalPath: s.modelLocalPath,
+ })),
+ );
+ const hfToken = useHfTokenStore((s) => s.token);
+ // Every cached answer is about the sidecar installed when it was taken, and an install
+ // both lands the offered release and flips the run to 16-bit. Reading through the
+ // generation re-asks after one, so Configure does not keep offering an install that
+ // already ran, or keep promising 4-bit for a run the new overlay loads in 16-bit.
+ const sidecarGeneration = useTransformersUpgradeDialogStore(
+ (s) => s.sidecarGeneration,
+ );
+ // The copy the run would load, resolved exactly as freshModelCachePin resolves it for
+ // the start: a cached model loads from its pinned snapshot, so the preview describes
+ // that snapshot rather than whatever the repo publishes today. A known-cached row can
+ // carry a null path and the backend still resolves the pin from the cache roots, so
+ // the flag travels on its own rather than being read off the path.
+ const preferLocalCache = Boolean(modelKnownCached);
+ const localPath = (preferLocalCache && modelLocalPath) || null;
+ // The cache is the state; this counter only re-renders once an answer lands in it,
+ // keeping setState out of the effect body. Reading the map during render already
+ // answers for a model asked about before, and switching models needs no reset because
+ // the key changes with it.
+ const [, markAnswered] = useState(0);
+ const key = selectedModel
+ ? upgradeNoticeCacheKey(
+ sidecarGeneration,
+ selectedModel,
+ preferLocalCache,
+ localPath,
+ hfToken,
+ )
+ : null;
+ const check = key ? readUpgradeNoticeCache(sidecarGeneration, key) : null;
+
+ useEffect(() => {
+ if (
+ !(key && selectedModel) ||
+ hasUpgradeNoticeCache(sidecarGeneration, key)
+ ) {
+ return;
+ }
+ let active = true;
+ checkTransformersUpgrade(selectedModel, hfToken || null, {
+ preferLocalCache,
+ modelLocalPath: localPath,
+ })
+ .then((result) => {
+ writeUpgradeNoticeCache(sidecarGeneration, key, result);
+ if (active) {
+ markAnswered((n) => n + 1);
+ }
+ })
+ // A preview notice is never worth an error surface: an unreachable check leaves
+ // the preview reading as it did before this hook existed.
+ .catch(() => undefined);
+ return () => {
+ active = false;
+ };
+ }, [
+ key,
+ selectedModel,
+ preferLocalCache,
+ localPath,
+ hfToken,
+ sidecarGeneration,
+ ]);
+
+ if (!(selectedModel && check)) {
+ return EMPTY;
+ }
+ return trainingTransformersUpgradeNotice(
+ check,
+ trainingLoadsIn4Bit({ trainingMethod, selectedModel }),
+ );
+}
diff --git a/studio/frontend/src/features/training/index.ts b/studio/frontend/src/features/training/index.ts
index 0a31a57bbc1..2cf896e028b 100644
--- a/studio/frontend/src/features/training/index.ts
+++ b/studio/frontend/src/features/training/index.ts
@@ -86,6 +86,10 @@ export {
} from "./lib/validation";
export { useTrainingReadiness } from "./hooks/use-training-readiness";
export { useTrainingResourceNotices } from "./hooks/use-training-resource-notices";
+export {
+ type TrainingTransformersUpgradeNotice,
+ useTrainingTransformersUpgradeNotice,
+} from "./hooks/use-training-transformers-upgrade-notice";
export {
cacheLocalPathMatchesSelection,
cachedInventoryPathMatchesSelection,
diff --git a/studio/frontend/src/features/training/lib/resume-training-run.ts b/studio/frontend/src/features/training/lib/resume-training-run.ts
index de9ad928452..4c4b820a205 100644
--- a/studio/frontend/src/features/training/lib/resume-training-run.ts
+++ b/studio/frontend/src/features/training/lib/resume-training-run.ts
@@ -27,6 +27,7 @@ import {
settleUnconfirmedTrainingStart,
tryAcquireTrainingStart,
} from "./training-start-runtime";
+import { confirmTrainingTransformersUpgrade } from "./training-transformers-upgrade";
const RESUME_UNAVAILABLE_ERROR =
"studio.training.resumeUnavailable" satisfies TranslationKey;
@@ -55,7 +56,28 @@ export async function resumeTrainingRun(runId: string): Promise<boolean> {
payload.project_name ?? "",
);
- if (!(await confirmResumeRemoteCode(payload, attempt))) {
+ // Upgrade consent first, then the custom-code gate, like a fresh start: a resume
+ // after a reinstall can face the same unknown architecture the first run installed for.
+ // The upgrade check already read this model's config, so carry its custom-code
+ // verdict into the next gate rather than let that gate's fallback re-derive it.
+ const upgradeVerdict = { requiresTrustRemoteCode: false };
+ if (
+ !(await confirmResumeTransformersUpgrade(
+ runId,
+ payload,
+ attempt,
+ upgradeVerdict,
+ ))
+ ) {
+ return false;
+ }
+ if (
+ !(await confirmResumeRemoteCode(
+ payload,
+ attempt,
+ upgradeVerdict.requiresTrustRemoteCode,
+ ))
+ ) {
return false;
}
return await submitResumeTrainingRun(payload, attempt);
@@ -236,28 +258,61 @@ async function prepareResumeHfToken(
return true;
}
-async function confirmResumeRemoteCode(
+async function confirmResumeTransformersUpgrade(
+ runId: string,
payload: TrainingStartRequest,
attempt: ResumeTrainingStartAttempt,
+ verdict: { requiresTrustRemoteCode: boolean },
): Promise<boolean> {
if (!payload.model_name) {
return attempt.isPreflightActive();
}
+ const outcome = await confirmTrainingTransformersUpgrade({
+ modelName: payload.model_name,
+ hfToken: payload.hf_token ?? null,
+ // Same pin the custom-code gate below resolves, so both read one config.json.
+ modelCachePin: resumeModelCachePin(payload),
+ // The stored run decides whether an install is even offerable: this checkpoint may
+ // be attested against a 4-bit load the latest sidecar permanently refuses.
+ resumeRunId: runId,
+ });
+ verdict.requiresTrustRemoteCode = outcome.requiresTrustRemoteCode;
+ if (!attempt.isPreflightActive()) {
+ return false;
+ }
+ return outcome.proceed || attempt.cancel(outcome.error);
+}
- let trustRemoteCode = Boolean(payload.trust_remote_code);
- let approvedRemoteCodeFingerprint =
- payload.approved_remote_code_fingerprint ?? null;
- const remoteCodeCache = resolveResumeRemoteCodeCache({
+/** The copy of the model this resume loads, for every gate that has to inspect it.
+ *
+ * One resolution, so the upgrade check and the custom-code scan can never end up
+ * reading different config.json files for the same start. */
+function resumeModelCachePin(payload: TrainingStartRequest) {
+ return resolveResumeRemoteCodeCache({
actualModelRepoId: payload.actual_model_repo_id,
modelKnownCached: payload.model_known_cached,
modelLocalPath: payload.model_local_path,
modelSnapshotPath: payload.model_snapshot_path,
});
+}
+
+async function confirmResumeRemoteCode(
+ payload: TrainingStartRequest,
+ attempt: ResumeTrainingStartAttempt,
+ upgradeRequiresTrustRemoteCode = false,
+): Promise<boolean> {
+ if (!payload.model_name) {
+ return attempt.isPreflightActive();
+ }
+
+ let trustRemoteCode = Boolean(payload.trust_remote_code);
+ let approvedRemoteCodeFingerprint =
+ payload.approved_remote_code_fingerprint ?? null;
const remoteCodeOk = await confirmRemoteCodeIfNeeded({
modelName: payload.model_name,
hfToken: payload.hf_token ?? null,
- ...remoteCodeCache,
- requiresTrustRemoteCode: trustRemoteCode,
+ ...resumeModelCachePin(payload),
+ requiresTrustRemoteCode: trustRemoteCode || upgradeRequiresTrustRemoteCode,
onApprove: (fingerprint) => {
trustRemoteCode = true;
approvedRemoteCodeFingerprint = fingerprint;
diff --git a/studio/frontend/src/features/training/lib/start-fresh-training-run.ts b/studio/frontend/src/features/training/lib/start-fresh-training-run.ts
index 7bfc6d2814b..099f69a6577 100644
--- a/studio/frontend/src/features/training/lib/start-fresh-training-run.ts
+++ b/studio/frontend/src/features/training/lib/start-fresh-training-run.ts
@@ -43,6 +43,7 @@ import {
settleUnconfirmedTrainingStart,
tryAcquireTrainingStart,
} from "./training-start-runtime";
+import { confirmTrainingTransformersUpgrade } from "./training-transformers-upgrade";
import {
hasIncompatibleTrainingModalities,
validateTrainingConfig,
@@ -277,7 +278,28 @@ export async function startFreshTrainingRun(): Promise<boolean> {
if (useTrainingRuntimeStore.getState().stopRequested) {
return attempt.cancel();
}
- if (!(await confirmSelectedModelRemoteCode(attempt, tokenResult.token))) {
+ // Upgrade consent first, then the custom-code gate: the same order chat loads use,
+ // because installing a newer transformers changes what the load would even run.
+ // The upgrade check already read this model's config, so carry its custom-code
+ // verdict into the next gate rather than let that gate's fallback re-derive it from
+ // the stored flag, which a fresh run leaves false.
+ const upgradeVerdict = { requiresTrustRemoteCode: false };
+ if (
+ !(await confirmSelectedModelTransformersUpgrade(
+ attempt,
+ tokenResult.token,
+ upgradeVerdict,
+ ))
+ ) {
+ return false;
+ }
+ if (
+ !(await confirmSelectedModelRemoteCode(
+ attempt,
+ tokenResult.token,
+ upgradeVerdict.requiresTrustRemoteCode,
+ ))
+ ) {
return false;
}
return await submitFreshTrainingRun(attempt, tokenResult.token);
@@ -428,23 +450,59 @@ function openManualMapping(
return false;
}
-async function confirmSelectedModelRemoteCode(
+async function confirmSelectedModelTransformersUpgrade(
attempt: FreshTrainingStartAttempt,
hfToken: string | null,
+ verdict: { requiresTrustRemoteCode: boolean },
): Promise<boolean> {
const modelName = attempt.config.selectedModel;
if (!modelName) {
return true;
}
+ const outcome = await confirmTrainingTransformersUpgrade({
+ modelName,
+ hfToken,
+ // Same pin the custom-code gate resolves, so both read one config.json: a cached
+ // model loads from its pinned snapshot, whose architecture can differ from the one
+ // the repo publishes today.
+ modelCachePin: freshModelCachePin(attempt),
+ });
+ verdict.requiresTrustRemoteCode = outcome.requiresTrustRemoteCode;
+ if (attempt.abortIfInputsChanged()) {
+ return false;
+ }
+ return outcome.proceed || attempt.cancel(outcome.error);
+}
+/** The copy of the model this start loads, for every gate that has to inspect it. */
+function freshModelCachePin(attempt: FreshTrainingStartAttempt): {
+ preferLocalCache: boolean;
+ modelLocalPath: string | null;
+} {
const preferLocalCache = attempt.config.modelKnownCached;
+ return {
+ preferLocalCache,
+ modelLocalPath: preferLocalCache ? attempt.config.modelLocalPath : null,
+ };
+}
+
+async function confirmSelectedModelRemoteCode(
+ attempt: FreshTrainingStartAttempt,
+ hfToken: string | null,
+ upgradeRequiresTrustRemoteCode = false,
+): Promise<boolean> {
+ const modelName = attempt.config.selectedModel;
+ if (!modelName) {
+ return true;
+ }
+
let approvalApplied = true;
const approved = await confirmRemoteCodeIfNeeded({
modelName,
hfToken,
- preferLocalCache,
- modelLocalPath: preferLocalCache ? attempt.config.modelLocalPath : null,
- requiresTrustRemoteCode: attempt.config.trustRemoteCode,
+ ...freshModelCachePin(attempt),
+ requiresTrustRemoteCode:
+ attempt.config.trustRemoteCode || upgradeRequiresTrustRemoteCode,
onApprove: (fingerprint) => {
approvalApplied = attempt.updateConfig({
trustRemoteCode: true,
diff --git a/studio/frontend/src/features/training/lib/training-transformers-upgrade.ts b/studio/frontend/src/features/training/lib/training-transformers-upgrade.ts
new file mode 100644
index 00000000000..e815bb2e9f2
--- /dev/null
+++ b/studio/frontend/src/features/training/lib/training-transformers-upgrade.ts
@@ -0,0 +1,209 @@
+// 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 {
+ type ModelCachePin,
+ type TransformersUpgradeCheck,
+ checkTransformersUpgrade,
+ confirmTransformersUpgradeIfNeeded,
+ useTransformersUpgradeDialogStore,
+} from "@/features/transformers-upgrade";
+
+/** What the caller must do next once the upgrade gate has run. */
+export interface TrainingTransformersUpgradeOutcome {
+ /** False when the install was declined or none exists: do not start the run. */
+ proceed: boolean;
+ /** Why the start was abandoned; set only when proceed is false. */
+ error: string | null;
+ /** The run will load 16-bit, not bnb 4-bit, because it routes to the latest sidecar. */
+ forces16Bit: boolean;
+ /** The model ships its own modeling code. Hand this to the custom-code gate that runs
+ * next: its fallback otherwise reads the stored config flag, false for a fresh run,
+ * and skips consent for a model that cannot load without it. Chat does the same. */
+ requiresTrustRemoteCode: boolean;
+}
+
+/** What the Configure preview must disclose about transformers and precision. */
+export interface TrainingTransformersUpgradeNotice {
+ /** transformers release the run would offer to install, or null when none is needed. */
+ installVersion: string | null;
+ /** The picked method asks for 4-bit but the run would load 16-bit anyway. */
+ fourBitUnavailable: boolean;
+ /** 4-bit survives only if the user keeps the model's own code: taking Install instead
+ * activates the latest sidecar, which trains 16-bit. */
+ installSwitchesTo16Bit: boolean;
+}
+
+/** Turn one upgrade check into the preview's disclosure.
+ *
+ * A model that both ships its own modeling code and is shipped by the offered release
+ * gets both dialog actions, and they differ in precision: the custom-code fallback loads
+ * 4-bit on the current transformers (so forces_16bit is false), while Install activates
+ * the latest sidecar, which trains 16-bit. Disclose that choice rather than advertise
+ * "QLoRA - 4-bit" for a run the user may well take at triple the VRAM.
+ *
+ * `installable && !forces16Bit` catches exactly that case: forces_16bit is
+ * `latest_tier_active || install_only_upgrade`, and install_only_upgrade is itself
+ * installable-and-no-custom-code. */
+export function trainingTransformersUpgradeNotice(
+ check: TransformersUpgradeCheck,
+ loadsIn4Bit: boolean,
+): TrainingTransformersUpgradeNotice {
+ const installable = Boolean(
+ check.upgrade?.supported_in_pypi && check.upgrade?.pypi_version,
+ );
+ return {
+ installVersion: installable ? (check.upgrade?.pypi_version ?? null) : null,
+ fourBitUnavailable: check.forces16Bit && loadsIn4Bit,
+ installSwitchesTo16Bit: installable && !check.forces16Bit && loadsIn4Bit,
+ };
+}
+
+/** Names the worker's own failure ("... is not supported yet in transformers==x.y.z")
+ * rather than a generic start error, and says what to do about it. */
+export function getTrainingTransformersUpgradeRequiredMessage(
+ modelName: string,
+): string {
+ return `${modelName} is not supported yet by the installed transformers, and the newer release it needs was not installed. Start the run again to install it.`;
+}
+
+/** Dev-only: the architecture is on the transformers development branch and no PyPI
+ * release ships it, so the dialog has no Install action. "Start again to install it"
+ * would be an instruction the app can never carry out. */
+export function getTrainingTransformersUpgradeUnavailableMessage(
+ modelName: string,
+): string {
+ return `${modelName} is not supported yet by the installed transformers, and no released transformers version supports it either: the architecture is only on the transformers development branch, which Unsloth does not install. Wait for the next transformers release, or pick a model the installed transformers supports.`;
+}
+
+/** The resume that installing would strand: the checkpoint is attested against a 4-bit
+ * model load the latest sidecar permanently refuses, so the install cannot rescue it. */
+export function getTrainingResumeUpgradeWouldStrandMessage(
+ modelName: string,
+): string {
+ return `${modelName} is not supported yet by the installed transformers, and installing the release it needs would permanently retire the 4-bit model load this checkpoint was attested with, so the resume would still fail. Start a new run on this model instead.`;
+}
+
+/** Gate a training start on the transformers release the model needs.
+ *
+ * Chat pauses a load on this dialog from `/validate`; training never asked, so a model
+ * no installed transformers ships was accepted, spawned, and killed minutes later at
+ * model load with an error the user could not act on. Same dialog, raised before the
+ * run starts. Additive: a backend that does not serve the check, or fails it, leaves
+ * the start as it was. */
+export async function confirmTrainingTransformersUpgrade({
+ modelName,
+ hfToken,
+ modelCachePin,
+ resumeRunId,
+}: {
+ modelName: string;
+ hfToken?: string | null;
+ /** Which copy the run will load, resolved exactly as the custom-code gate resolves
+ * it: a repo's current config.json often names a different architecture than the
+ * pinned snapshot on disk. */
+ modelCachePin?: ModelCachePin;
+ /** Set on the resume path, so the check can say whether installing would strand
+ * this checkpoint. */
+ resumeRunId?: string | null;
+}): Promise<TrainingTransformersUpgradeOutcome> {
+ let check: TransformersUpgradeCheck;
+ try {
+ check = await checkTransformersUpgrade(modelName, hfToken, {
+ ...modelCachePin,
+ resumeRunId,
+ });
+ } catch {
+ return {
+ proceed: true,
+ error: null,
+ forces16Bit: false,
+ requiresTrustRemoteCode: false,
+ };
+ }
+ const requiresTrustRemoteCode = Boolean(check.requiresTrustRemoteCode);
+ if (!check.upgrade) {
+ return {
+ proceed: true,
+ error: null,
+ forces16Bit: check.forces16Bit,
+ requiresTrustRemoteCode,
+ };
+ }
+ // Only a released version is ever installed, so every branch that talks about
+ // installing checks this first.
+ const installable = Boolean(
+ check.upgrade.supported_in_pypi && check.upgrade.pypi_version,
+ );
+ if (check.installBreaksExactResume) {
+ // The checkpoint is attested against a 4-bit load the latest sidecar refuses, and
+ // that sidecar is a persistent overlay: consenting would strand it for good.
+ if (check.requiresTrustRemoteCode) {
+ // The custom-code gate that runs next loads this on the CURRENT transformers, in
+ // the 4-bit mode the checkpoint needs. Nothing to offer.
+ return {
+ proceed: true,
+ error: null,
+ forces16Bit: false,
+ requiresTrustRemoteCode,
+ };
+ }
+ if (installable) {
+ // No fallback, and the install is not the way out it looks like: it activates the
+ // latest tier, after which effective_training_load_in_4bit raises for this config
+ // (provenance.py gates on the same disjunction). The resume fails either way, so
+ // consent buys only an irreversible overlay. Say so instead of offering it.
+ return {
+ proceed: false,
+ error: getTrainingResumeUpgradeWouldStrandMessage(modelName),
+ forces16Bit: false,
+ requiresTrustRemoteCode,
+ };
+ }
+ // Dev-only: no release to install, so nothing can strand anything, and "start a new
+ // run instead" cannot work either. Fall through to the dev-only path, which says the
+ // true thing: wait for the next release.
+ }
+
+ const upgraded = await confirmTransformersUpgradeIfNeeded({
+ modelName,
+ upgrade: check.upgrade,
+ // With no installable release, a model shipping its own code can still go through
+ // the trust_remote_code gate the caller runs next, exactly as chat does.
+ trustRemoteCodeFallback: requiresTrustRemoteCode,
+ // No forceCancelActive: training raises no "stop N chats" prompt, so it has no such
+ // answer to carry. A chat mid-generation makes the install refuse and the dialog
+ // says so, rather than this tab killing someone else's stream unasked.
+ });
+ // Read before the resolve-time state is reused by any later consent.
+ const installRan = useTransformersUpgradeDialogStore.getState().installRan;
+ if (
+ useTransformersUpgradeDialogStore.getState().consumeServerUnloadedChat()
+ ) {
+ // The install unloads the active chat model. Nothing on this tab owns that
+ // selection, so resync or chat keeps pointing at a model that is gone.
+ void import("@/features/chat")
+ .then((chat) => chat.resyncInferenceStatusAfterServerModelChange())
+ .catch(() => undefined);
+ }
+ if (!upgraded) {
+ // "Start again to install it" only means something when there is something to
+ // install; a dev-only upgrade would send the user round a loop that never ends.
+ return {
+ proceed: false,
+ error: installable
+ ? getTrainingTransformersUpgradeRequiredMessage(modelName)
+ : getTrainingTransformersUpgradeUnavailableMessage(modelName),
+ forces16Bit: false,
+ requiresTrustRemoteCode,
+ };
+ }
+ // Installed: the model now routes to the latest sidecar, which trains 16-bit. The
+ // custom-code fallback resolves true without installing and still loads 4-bit.
+ return {
+ proceed: true,
+ error: null,
+ forces16Bit: installRan,
+ requiresTrustRemoteCode,
+ };
+}
diff --git a/studio/frontend/src/features/training/lib/training-upgrade-notice-cache.ts b/studio/frontend/src/features/training/lib/training-upgrade-notice-cache.ts
new file mode 100644
index 00000000000..02a7c2d14be
--- /dev/null
+++ b/studio/frontend/src/features/training/lib/training-upgrade-notice-cache.ts
@@ -0,0 +1,79 @@
+// 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 type { TransformersUpgradeCheck } from "@/features/transformers-upgrade";
+
+// One answer per (sidecar generation, model, cached copy, token) for the Configure
+// preview. The config.json read behind the check is a network round trip and the notice
+// hook runs on every Configure render, so without this, scrubbing a slider would re-ask.
+//
+// The generation is in the key because an install invalidates every answer here: the
+// release offered is now installed, and the sidecar it activated flips forces16Bit on
+// for models that reported 4-bit before.
+const cache = new Map<string, TransformersUpgradeCheck>();
+
+// Separator no field can contain: a model id, a cache path and a token are all printable.
+const KEY_SEPARATOR = "\u0001";
+
+let cachedGeneration = 0;
+
+/** Key one preview answer. `sidecarGeneration` counts completed installs. */
+export function upgradeNoticeCacheKey(
+ sidecarGeneration: number,
+ modelName: string,
+ preferLocalCache: boolean,
+ localPath: string | null,
+ hfToken: string,
+): string {
+ // preferLocalCache is its own field: a known-cached row with a null path resolves to a
+ // pinned snapshot, a different answer from the same model asked without the preference.
+ return [
+ sidecarGeneration,
+ modelName,
+ preferLocalCache ? "1" : "0",
+ localPath ?? "",
+ hfToken,
+ ].join(KEY_SEPARATOR);
+}
+
+// Entries from a superseded generation can never be read again, so drop them rather than
+// let an install-per-session leak the whole map.
+//
+// The generation only counts up, so an older one is always a straggler: a check fired
+// before an install can still be in flight when it lands, resolving after the
+// post-install check answered. Letting that write rewind the generation would clear the
+// fresh entry and store the stale answer in its place, and since its effect was already
+// cleaned up nothing re-asks, so the preview would show no notice for the rest of the
+// session. Superseded reads and writes are ignored: null, never the whole map.
+function activeCache(sidecarGeneration: number): typeof cache | null {
+ if (sidecarGeneration < cachedGeneration) {
+ return null;
+ }
+ if (sidecarGeneration !== cachedGeneration) {
+ cachedGeneration = sidecarGeneration;
+ cache.clear();
+ }
+ return cache;
+}
+
+export function readUpgradeNoticeCache(
+ sidecarGeneration: number,
+ key: string,
+): TransformersUpgradeCheck | null {
+ return activeCache(sidecarGeneration)?.get(key) ?? null;
+}
+
+export function hasUpgradeNoticeCache(
+ sidecarGeneration: number,
+ key: string,
+): boolean {
+ return activeCache(sidecarGeneration)?.has(key) ?? false;
+}
+
+export function writeUpgradeNoticeCache(
+ sidecarGeneration: number,
+ key: string,
+ check: TransformersUpgradeCheck,
+): void {
+ activeCache(sidecarGeneration)?.set(key, check);
+}
diff --git a/studio/frontend/src/features/transformers-upgrade/api/transformers-upgrade-api.ts b/studio/frontend/src/features/transformers-upgrade/api/transformers-upgrade-api.ts
index 7e1e1b0f5ae..94ee30c64fe 100644
--- a/studio/frontend/src/features/transformers-upgrade/api/transformers-upgrade-api.ts
+++ b/studio/frontend/src/features/transformers-upgrade/api/transformers-upgrade-api.ts
@@ -3,6 +3,69 @@
import { authFetch } from "@/features/auth";
import { readFastApiError } from "@/lib/format-fastapi-error";
+import type {
+ ModelCachePin,
+ TransformersUpgradeCheck,
+ TransformersUpgradeInfo,
+} from "../types";
+
+interface TransformersUpgradeCheckResponse {
+ // biome-ignore lint/style/useNamingConvention: API schema
+ requires_transformers_upgrade?: boolean;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ transformers_upgrade?: TransformersUpgradeInfo | null;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ requires_trust_remote_code?: boolean;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ latest_tier_active?: boolean;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ forces_16bit?: boolean;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ install_breaks_exact_resume?: boolean;
+}
+
+/** Ask whether loading `modelName` needs a newer transformers than any installed sidecar.
+ *
+ * The pre-load half of the consent gate for callers that do not run chat's `/validate`
+ * (the Train tab). The token rides in the POST body, never the URL, like the scan route.
+ * `options` carries the cache pin, so the answer describes the snapshot the load will
+ * open rather than the repo's current config, and for a resume the run it precedes. */
+export async function checkTransformersUpgrade(
+ modelName: string,
+ hfToken?: string | null,
+ options?: ModelCachePin & { resumeRunId?: string | null },
+): Promise<TransformersUpgradeCheck> {
+ const response = await authFetch(
+ "/api/inference/transformers-upgrade-check",
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ model_name: modelName,
+ hf_token: hfToken ?? null,
+ prefer_local_cache: options?.preferLocalCache ?? false,
+ model_local_path: options?.modelLocalPath ?? null,
+ model_snapshot_path: options?.modelSnapshotPath ?? null,
+ model_snapshot_repo_id: options?.modelSnapshotRepoId ?? null,
+ resume_run_id: options?.resumeRunId ?? null,
+ }),
+ },
+ );
+ if (!response.ok) {
+ throw new Error(await readFastApiError(response));
+ }
+ const data = (await response.json()) as TransformersUpgradeCheckResponse;
+ const upgrade = data.requires_transformers_upgrade
+ ? (data.transformers_upgrade ?? null)
+ : null;
+ return {
+ upgrade,
+ requiresTrustRemoteCode: Boolean(data.requires_trust_remote_code),
+ latestTierActive: Boolean(data.latest_tier_active),
+ forces16Bit: Boolean(data.forces_16bit),
+ installBreaksExactResume: Boolean(data.install_breaks_exact_resume),
+ };
+}
interface InstallLatestTransformersResponse {
success: boolean;
@@ -25,11 +88,14 @@ export async function installLatestTransformers(
version: string,
forceCancelActive = false,
): Promise<InstallLatestTransformersResponse> {
- const response = await authFetch("/api/inference/install-latest-transformers", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ version, force_cancel_active: forceCancelActive }),
- });
+ const response = await authFetch(
+ "/api/inference/install-latest-transformers",
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ version, force_cancel_active: forceCancelActive }),
+ },
+ );
if (!response.ok) {
throw new Error(await readFastApiError(response));
}
diff --git a/studio/frontend/src/features/transformers-upgrade/components/transformers-upgrade-dialog.tsx b/studio/frontend/src/features/transformers-upgrade/components/transformers-upgrade-dialog.tsx
index 3e39a8ff1c1..8a6cd3947a9 100644
--- a/studio/frontend/src/features/transformers-upgrade/components/transformers-upgrade-dialog.tsx
+++ b/studio/frontend/src/features/transformers-upgrade/components/transformers-upgrade-dialog.tsx
@@ -15,6 +15,7 @@ import { Spinner } from "@/components/ui/spinner";
import { cn } from "@/lib/utils";
import { PackageIcon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
+import { upgradeDialogActions } from "../lib/upgrade-dialog-actions";
import { useTransformersUpgradeDialogStore } from "../stores/transformers-upgrade-dialog-store";
function modelDisplayName(modelName: string | null): string {
@@ -40,8 +41,11 @@ export function TransformersUpgradeDialog() {
const modelType = upgrade?.model_type ?? "unknown";
const version = upgrade?.pypi_version ?? null;
// Only released PyPI versions are installable; dev (main) builds are never offered.
- const installable = Boolean(upgrade?.supported_in_pypi && version);
- const devOnly = !installable && Boolean(upgrade?.supported_in_main);
+ const { installable, devOnly, customCode } = upgradeDialogActions({
+ upgrade,
+ phase,
+ trustRemoteCodeFallback,
+ });
const installing = phase === "installing";
return (
@@ -75,8 +79,8 @@ export function TransformersUpgradeDialog() {
<span className="font-medium text-foreground">
{version}
</span>{" "}
- from PyPI to load it. The install runs once and can take
- a minute; loading continues automatically afterwards.
+ from PyPI to load it. The install runs once and can take a
+ minute; loading continues automatically afterwards.
</>
) : devOnly ? (
<>
@@ -92,11 +96,12 @@ export function TransformersUpgradeDialog() {
cannot be loaded.
</>
)}
- {!installable && trustRemoteCodeFallback ? (
+ {customCode ? (
<>
{" "}
This model also ships its own modeling code; you can
- continue and review enabling that custom code instead.
+ continue and review enabling that custom code instead,
+ which loads it on the transformers you already have.
</>
) : null}
</AlertDialogDescription>
@@ -122,9 +127,11 @@ export function TransformersUpgradeDialog() {
<AlertDialogCancel disabled={installing}>Cancel</AlertDialogCancel>
{installable ? (
<>
- {phase === "error" && trustRemoteCodeFallback ? (
- // Install failed but the model ships custom code: offer the
- // caller's trust_remote_code gate instead of forcing a retry.
+ {customCode ? (
+ // The model ships custom code, so the caller's trust_remote_code gate
+ // loads it on the installed transformers. Offered next to Install, not
+ // only after one fails: installing activates the 16-bit sidecar, so this
+ // is the only way a 4-bit run on this model can start.
<AlertDialogAction
className="bg-transparent text-foreground hover:bg-accent"
onClick={() => resolve(true)}
@@ -153,7 +160,7 @@ export function TransformersUpgradeDialog() {
)}
</AlertDialogAction>
</>
- ) : trustRemoteCodeFallback ? (
+ ) : customCode ? (
// No installable release but the model ships custom code: continue
// into the caller's trust_remote_code gate as the last resort.
<AlertDialogAction onClick={() => resolve(true)}>
diff --git a/studio/frontend/src/features/transformers-upgrade/index.ts b/studio/frontend/src/features/transformers-upgrade/index.ts
index 4318fd78304..3d079e55927 100644
--- a/studio/frontend/src/features/transformers-upgrade/index.ts
+++ b/studio/frontend/src/features/transformers-upgrade/index.ts
@@ -3,6 +3,13 @@
export { TransformersUpgradeDialog } from "./components/transformers-upgrade-dialog";
export { confirmTransformersUpgradeIfNeeded } from "./hooks/use-transformers-upgrade-consent";
-export { installLatestTransformers } from "./api/transformers-upgrade-api";
+export {
+ checkTransformersUpgrade,
+ installLatestTransformers,
+} from "./api/transformers-upgrade-api";
export { useTransformersUpgradeDialogStore } from "./stores/transformers-upgrade-dialog-store";
-export type { TransformersUpgradeInfo } from "./types";
+export type {
+ ModelCachePin,
+ TransformersUpgradeCheck,
+ TransformersUpgradeInfo,
+} from "./types";
diff --git a/studio/frontend/src/features/transformers-upgrade/lib/upgrade-dialog-actions.ts b/studio/frontend/src/features/transformers-upgrade/lib/upgrade-dialog-actions.ts
new file mode 100644
index 00000000000..aca974d3d01
--- /dev/null
+++ b/studio/frontend/src/features/transformers-upgrade/lib/upgrade-dialog-actions.ts
@@ -0,0 +1,45 @@
+// 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 type {
+ TransformersUpgradeInfo,
+ TransformersUpgradePhase,
+} from "../types";
+
+/** Which ways out the consent dialog offers, besides Cancel. */
+export interface UpgradeDialogActions {
+ /** A released version exists, so the install is a real action. */
+ installable: boolean;
+ /** Only transformers main ships the architecture; nothing to install. */
+ devOnly: boolean;
+ /** Offer "Continue with custom code": the model's own modeling code loads it on the
+ * transformers already installed, so the caller's trust_remote_code gate is a way out. */
+ customCode: boolean;
+}
+
+/** Decide the dialog's actions from the check that raised it.
+ *
+ * The custom-code fallback used to appear only with nothing to install, or after an
+ * install failed. It reads as a courtesy but is a correctness rule: the fallback loads
+ * on the CURRENT transformers, the only path that still loads bnb 4-bit, since
+ * installing activates the 16-bit sidecar. Hiding it behind Install leaves a QLoRA run
+ * no way to start at its own precision. Whenever the fallback exists, it is offered. */
+export function upgradeDialogActions({
+ upgrade,
+ phase,
+ trustRemoteCodeFallback,
+}: {
+ upgrade: TransformersUpgradeInfo | null;
+ phase: TransformersUpgradePhase;
+ trustRemoteCodeFallback: boolean;
+}): UpgradeDialogActions {
+ const installable = Boolean(
+ upgrade?.supported_in_pypi && upgrade?.pypi_version,
+ );
+ return {
+ installable,
+ devOnly: !installable && Boolean(upgrade?.supported_in_main),
+ // Never mid-install: the install is running and this button would abandon it.
+ customCode: trustRemoteCodeFallback && phase !== "installing",
+ };
+}
diff --git a/studio/frontend/src/features/transformers-upgrade/stores/transformers-upgrade-dialog-store.ts b/studio/frontend/src/features/transformers-upgrade/stores/transformers-upgrade-dialog-store.ts
index be37691bc6a..63872dfa9be 100644
--- a/studio/frontend/src/features/transformers-upgrade/stores/transformers-upgrade-dialog-store.ts
+++ b/studio/frontend/src/features/transformers-upgrade/stores/transformers-upgrade-dialog-store.ts
@@ -3,7 +3,10 @@
import { create } from "zustand";
import { installLatestTransformers } from "../api/transformers-upgrade-api";
-import type { TransformersUpgradeInfo, TransformersUpgradePhase } from "../types";
+import type {
+ TransformersUpgradeInfo,
+ TransformersUpgradePhase,
+} from "../types";
type Resolver = (installed: boolean) => void;
@@ -25,6 +28,11 @@ interface TransformersUpgradeDialogStore {
* model before swapping, so the caller must treat it as already unloaded; the
* custom-code fallback resolves true without installing and leaves it loaded. */
installRan: boolean;
+ /** Completed installs this session. The sidecar it provisions is a persistent overlay
+ * that changes every later answer about every model, what is left to install and
+ * whether a run still loads 4-bit, so anything caching those answers keys on this and
+ * re-asks once it moves. Survives `resolve`, unlike the per-consent flags. */
+ sidecarGeneration: number;
/** True when the server unloaded the active chat model during this consent,
* including a swap that failed AFTER the unload: callers must then treat
* their previous model as gone and roll back on any later cancel. */
@@ -37,7 +45,10 @@ interface TransformersUpgradeDialogStore {
requestConsent: (
modelName: string,
upgrade: TransformersUpgradeInfo,
- options?: { trustRemoteCodeFallback?: boolean; forceCancelActive?: boolean },
+ options?: {
+ trustRemoteCodeFallback?: boolean;
+ forceCancelActive?: boolean;
+ },
) => Promise<boolean>;
/** Accept/Retry: run the install; on success resolve(true) and close. */
install: () => Promise<void>;
@@ -54,6 +65,7 @@ export const useTransformersUpgradeDialogStore =
trustRemoteCodeFallback: false,
forceCancelActive: false,
installRan: false,
+ sidecarGeneration: 0,
serverUnloadedChat: false,
requestConsent: (modelName, upgrade, options) =>
new Promise<boolean>((resolve) => {
@@ -108,7 +120,11 @@ export const useTransformersUpgradeDialogStore =
// serverUnloadedChat was latched above (and is never reset here): a
// retry after a failed-after-unload attempt reports false because the
// model is already gone, and a superseded install may have set it too.
- set({ installRan: true });
+ // The overlay is live from here on, for this tab and every model in it.
+ set({
+ installRan: true,
+ sidecarGeneration: get().sidecarGeneration + 1,
+ });
get().resolve(true);
return;
}
diff --git a/studio/frontend/src/features/transformers-upgrade/types.ts b/studio/frontend/src/features/transformers-upgrade/types.ts
index cf6bbe3d2f8..221930366ba 100644
--- a/studio/frontend/src/features/transformers-upgrade/types.ts
+++ b/studio/frontend/src/features/transformers-upgrade/types.ts
@@ -14,3 +14,28 @@ export interface TransformersUpgradeInfo {
}
export type TransformersUpgradePhase = "consent" | "installing" | "error";
+
+/** What `/api/inference/transformers-upgrade-check` says about one model. */
+export interface TransformersUpgradeCheck {
+ /** Set when no installed transformers ships the architecture but a newer one does. */
+ upgrade: TransformersUpgradeInfo | null;
+ /** The model ships its own modeling code, so a declined install still has a path. */
+ requiresTrustRemoteCode: boolean;
+ /** The latest sidecar already routes this model. */
+ latestTierActive: boolean;
+ /** A run started now loads 16-bit, not bnb 4-bit: the latest sidecar forces it. */
+ forces16Bit: boolean;
+ /** Installing would permanently strand the resume this check was asked for: the
+ * checkpoint only resumes in the 4-bit load mode the current runtime still gives it.
+ * Only set when a resume run was named in the request. */
+ installBreaksExactResume: boolean;
+}
+
+/** Which copy of a model to inspect, in the four fields the remote-code scan takes.
+ * Kept identical to that gate's arguments so both read the same config.json. */
+export interface ModelCachePin {
+ preferLocalCache?: boolean;
+ modelLocalPath?: string | null;
+ modelSnapshotPath?: string | null;
+ modelSnapshotRepoId?: string | null;
+}
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 313612d81eb..f0a6b97d157 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -1326,6 +1326,12 @@ export const ar = {
"مجموعة البيانات هذه غير موجودة على الجهاز بعد. سيُنزّلها التدريب تلقائيًا.",
noticeDatasetPartial:
"سيُكمل التدريب التنزيل غير المكتمل لمجموعة البيانات قبل قراءتها.",
+ noticeTransformersUpgrade:
+ "لا يدعم أي إصدار مثبَّت من transformers هذه البنية بعد. عند بدء التشغيل سيُعرض تثبيت transformers {version} أولاً.",
+ noticeSixteenBitOnly:
+ "تتدرَّب هذه البنية بـ LoRA بدقة 16 بت: خيار 4 بت غير متاح لها، لذا يحتاج التشغيل ذاكرة VRAM أكبر بكثير من QLoRA.",
+ noticeInstallSwitchesSixteenBit:
+ "تثبيت ذلك الإصدار بدل الإبقاء على شيفرة النموذج نفسه ينقل هذا التشغيل إلى LoRA بدقة 16 بت، وهو يحتاج ذاكرة VRAM أكبر بكثير من QLoRA.",
advancedSettings: "الإعدادات المتقدمة",
defaultAdvancedSettings: "الإعدادات الافتراضية",
nonDefaultAdvancedSettings: "{count} غير افتراضي",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index e2ab3b1867c..9d9d5e2a787 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -1371,6 +1371,12 @@ export const de = {
"Dieser Datensatz befindet sich noch nicht auf dem Gerät. Beim Start des Trainings wird er automatisch heruntergeladen.",
noticeDatasetPartial:
"Vor dem Einlesen wird der unvollständige Datensatz-Download abgeschlossen.",
+ noticeTransformersUpgrade:
+ "Keine installierte transformers-Version unterstützt diese Architektur bereits. Beim Start wird zuerst die Installation von transformers {version} angeboten.",
+ noticeSixteenBitOnly:
+ "Diese Architektur trainiert als 16-Bit-LoRA: 4 Bit ist dafür nicht verfügbar, der Lauf braucht also deutlich mehr VRAM als QLoRA.",
+ noticeInstallSwitchesSixteenBit:
+ "Wird diese Version installiert, statt den modelleigenen Code zu behalten, wechselt dieser Lauf zu 16-Bit-LoRA und braucht deutlich mehr VRAM als QLoRA.",
advancedSettings: "Erweiterte Einstellungen",
defaultAdvancedSettings: "Standardwerte",
nonDefaultAdvancedSettings: "{count} abweichend",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 728e389dff8..f3765b39218 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -1317,6 +1317,12 @@ export const en = {
"This dataset is not on this device yet. Training will download it automatically.",
noticeDatasetPartial:
"Training will complete the partial dataset download before reading it.",
+ noticeTransformersUpgrade:
+ "No installed transformers supports this architecture yet. Starting the run offers to install transformers {version} first.",
+ noticeSixteenBitOnly:
+ "This architecture trains in 16-bit LoRA: 4-bit is not available for it, so the run needs far more VRAM than QLoRA.",
+ noticeInstallSwitchesSixteenBit:
+ "Installing that release instead of keeping the model's own code switches this run to 16-bit LoRA, which needs far more VRAM than QLoRA.",
advancedSettings: "Advanced settings",
defaultAdvancedSettings: "Defaults",
nonDefaultAdvancedSettings: "{count} non-default",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 4ca9eaed104..868f17301b9 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -1362,6 +1362,12 @@ export const es = {
"Este conjunto de datos aún no está en el dispositivo. Se descargará automáticamente al iniciar el entrenamiento.",
noticeDatasetPartial:
"El entrenamiento completará la descarga parcial del conjunto de datos antes de leerlo.",
+ noticeTransformersUpgrade:
+ "Ninguna versión instalada de transformers admite todavía esta arquitectura. Al iniciar la ejecución se ofrecerá instalar transformers {version} primero.",
+ noticeSixteenBitOnly:
+ "Esta arquitectura se entrena en LoRA de 16 bits: 4 bits no está disponible, así que la ejecución necesita mucha más VRAM que QLoRA.",
+ noticeInstallSwitchesSixteenBit:
+ "Instalar esa versión en lugar de conservar el código propio del modelo cambia esta ejecución a LoRA de 16 bits, que necesita mucha más VRAM que QLoRA.",
advancedSettings: "Ajustes avanzados",
defaultAdvancedSettings: "Valores predeterminados",
nonDefaultAdvancedSettings: "{count} no predeterminados",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index d440340688c..c81d94a4872 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -1371,6 +1371,12 @@ export const fr = {
"Ce jeu de données n'est pas encore sur cet appareil. Il sera téléchargé automatiquement au démarrage de l'entraînement.",
noticeDatasetPartial:
"L'entraînement terminera le téléchargement partiel du jeu de données avant de le lire.",
+ noticeTransformersUpgrade:
+ "Aucune version installée de transformers ne prend encore en charge cette architecture. Au démarrage, l'installation de transformers {version} sera proposée d'abord.",
+ noticeSixteenBitOnly:
+ "Cette architecture s'entraîne en LoRA 16 bits : le 4 bits n'est pas disponible, donc l'exécution demande beaucoup plus de VRAM que QLoRA.",
+ noticeInstallSwitchesSixteenBit:
+ "Installer cette version au lieu de conserver le code propre au modèle fait passer cette exécution en LoRA 16 bits, qui demande beaucoup plus de VRAM que QLoRA.",
advancedSettings: "Paramètres avancés",
defaultAdvancedSettings: "Valeurs par défaut",
nonDefaultAdvancedSettings: "{count} non standard",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index 426bc4daa33..0b60b29a963 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -1333,6 +1333,12 @@ export const hi = {
"यह डेटासेट अभी इस डिवाइस पर नहीं है। ट्रेनिंग इसे अपने आप डाउनलोड करेगी।",
noticeDatasetPartial:
"ट्रेनिंग डेटासेट पढ़ने से पहले उसका अधूरा डाउनलोड पूरा करेगी।",
+ noticeTransformersUpgrade:
+ "इंस्टॉल किया गया कोई भी transformers अभी इस आर्किटेक्चर को सपोर्ट नहीं करता। रन शुरू करने पर पहले transformers {version} इंस्टॉल करने का विकल्प मिलेगा।",
+ noticeSixteenBitOnly:
+ "यह आर्किटेक्चर 16-बिट LoRA में ट्रेन होता है: इसके लिए 4-बिट उपलब्ध नहीं है, इसलिए रन को QLoRA से कहीं अधिक VRAM चाहिए।",
+ noticeInstallSwitchesSixteenBit:
+ "मॉडल के अपने कोड को रखने के बजाय वह रिलीज़ इंस्टॉल करने पर यह रन 16-बिट LoRA में बदल जाता है, जिसे QLoRA से कहीं अधिक VRAM चाहिए।",
advancedSettings: "उन्नत सेटिंग्स",
defaultAdvancedSettings: "डिफ़ॉल्ट",
nonDefaultAdvancedSettings: "{count} गैर-डिफ़ॉल्ट",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 00d19600a88..34feff4e324 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -1370,6 +1370,12 @@ export const it = {
"Questo dataset non è ancora presente sul dispositivo. L'addestramento lo scaricherà automaticamente.",
noticeDatasetPartial:
"L'addestramento completerà il download parziale del dataset prima di leggerlo.",
+ noticeTransformersUpgrade:
+ "Nessuna versione installata di transformers supporta ancora questa architettura. All'avvio verrà proposto di installare prima transformers {version}.",
+ noticeSixteenBitOnly:
+ "Questa architettura si addestra in LoRA a 16 bit: i 4 bit non sono disponibili, quindi l'esecuzione richiede molta più VRAM di QLoRA.",
+ noticeInstallSwitchesSixteenBit:
+ "Installare quella versione invece di mantenere il codice del modello porta questa esecuzione a LoRA a 16 bit, che richiede molta più VRAM di QLoRA.",
advancedSettings: "Impostazioni avanzate",
defaultAdvancedSettings: "Predefinite",
nonDefaultAdvancedSettings: "{count} non predefinite",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index 61d275cc407..4a5d18eb5c6 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -1298,6 +1298,12 @@ export const ja = {
"このデータセットはまだデバイス上にありません。トレーニング時に自動でダウンロードします。",
noticeDatasetPartial:
"トレーニングでは、データセットを読み込む前に未完了のダウンロードを完了します。",
+ noticeTransformersUpgrade:
+ "インストール済みの transformers はこのアーキテクチャに未対応です。実行を開始すると、まず transformers {version} のインストールを確認します。",
+ noticeSixteenBitOnly:
+ "このアーキテクチャは 16 ビット LoRA で学習します。4 ビットは利用できないため、QLoRA より大幅に多い VRAM が必要です。",
+ noticeInstallSwitchesSixteenBit:
+ "モデル独自のコードを使う代わりにそのリリースをインストールすると、この実行は 16 ビット LoRA に切り替わり、QLoRA より大幅に多い VRAM が必要になります。",
advancedSettings: "詳細設定",
defaultAdvancedSettings: "デフォルト",
nonDefaultAdvancedSettings: "デフォルト以外の設定: {count} 件",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 6f12d6c7cca..bb397b3a443 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -1324,6 +1324,12 @@ export const ko = {
"이 데이터셋은 아직 기기에 없습니다. 학습 시 자동으로 다운로드합니다.",
noticeDatasetPartial:
"데이터셋을 읽기 전에 완료되지 않은 다운로드를 마칩니다.",
+ noticeTransformersUpgrade:
+ "설치된 transformers 중 이 아키텍처를 지원하는 버전이 없습니다. 실행을 시작하면 먼저 transformers {version} 설치를 제안합니다.",
+ noticeSixteenBitOnly:
+ "이 아키텍처는 16비트 LoRA로 학습합니다. 4비트를 사용할 수 없어 QLoRA보다 훨씬 많은 VRAM이 필요합니다.",
+ noticeInstallSwitchesSixteenBit:
+ "모델 자체 코드를 유지하는 대신 해당 릴리스를 설치하면 이 실행은 16비트 LoRA로 전환되어 QLoRA보다 훨씬 많은 VRAM이 필요합니다.",
advancedSettings: "고급 설정",
defaultAdvancedSettings: "기본값",
nonDefaultAdvancedSettings: "기본값이 아닌 설정 {count}개",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 9cee3ce8b02..b6ace4a1e0a 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -1344,6 +1344,12 @@ export const ptBR = {
"Este dataset ainda não está no dispositivo. Ele será baixado automaticamente quando o treinamento começar.",
noticeDatasetPartial:
"O download incompleto do dataset será concluído antes da leitura.",
+ noticeTransformersUpgrade:
+ "Nenhuma versão instalada do transformers suporta esta arquitetura ainda. Ao iniciar a execução, será oferecida a instalação do transformers {version} antes.",
+ noticeSixteenBitOnly:
+ "Esta arquitetura treina em LoRA de 16 bits: 4 bits não está disponível, então a execução precisa de muito mais VRAM que QLoRA.",
+ noticeInstallSwitchesSixteenBit:
+ "Instalar essa versão em vez de manter o código do próprio modelo muda esta execução para LoRA de 16 bits, que precisa de muito mais VRAM que QLoRA.",
advancedSettings: "Configurações avançadas",
defaultAdvancedSettings: "Padrões",
nonDefaultAdvancedSettings: "{count} fora do padrão",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index cc8681a40ec..f1dbb07e584 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -1342,6 +1342,12 @@ export const ru = {
"Этого датасета пока нет на устройстве. При запуске обучения он будет загружен автоматически.",
noticeDatasetPartial:
"Перед чтением датасета обучение завершит скачивание недостающих файлов.",
+ noticeTransformersUpgrade:
+ "Ни одна установленная версия transformers пока не поддерживает эту архитектуру. При запуске сначала будет предложено установить transformers {version}.",
+ noticeSixteenBitOnly:
+ "Эта архитектура обучается в 16-битном LoRA: 4-битный режим недоступен, поэтому запуску нужно значительно больше VRAM, чем QLoRA.",
+ noticeInstallSwitchesSixteenBit:
+ "Установка этого выпуска вместо использования собственного кода модели переводит запуск в 16-битный LoRA, которому нужно значительно больше VRAM, чем QLoRA.",
advancedSettings: "Расширенные настройки",
defaultAdvancedSettings: "По умолчанию",
nonDefaultAdvancedSettings: "Нестандартных: {count}",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 2b853b8eca4..eee91772c9d 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -1286,6 +1286,12 @@ export const zhCN = {
"此数据集尚未存储在本设备上。训练时会自动下载。",
noticeDatasetPartial:
"训练会先继续并完成数据集下载,然后再读取数据集。",
+ noticeTransformersUpgrade:
+ "已安装的 transformers 均不支持该架构。启动运行时会先提示安装 transformers {version}。",
+ noticeSixteenBitOnly:
+ "该架构以 16 位 LoRA 训练:无法使用 4 位,因此显存需求远高于 QLoRA。",
+ noticeInstallSwitchesSixteenBit:
+ "安装该版本而非沿用模型自带代码,会将本次运行切换为 16 位 LoRA,显存需求远高于 QLoRA。",
advancedSettings: "高级设置",
defaultAdvancedSettings: "默认值",
nonDefaultAdvancedSettings: "{count} 项非默认设置",
diff --git a/studio/frontend/tests/helpers/transformers-upgrade-resolver.mjs b/studio/frontend/tests/helpers/transformers-upgrade-resolver.mjs
new file mode 100644
index 00000000000..362762f7851
--- /dev/null
+++ b/studio/frontend/tests/helpers/transformers-upgrade-resolver.mjs
@@ -0,0 +1,37 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// bundler-resolver's two rules, plus one redirect: features/transformers-upgrade -> a
+// stub. See transformers-upgrade-stub.mjs for why the redirect is needed.
+import { existsSync } from "node:fs";
+import { fileURLToPath, pathToFileURL } from "node:url";
+
+const SRC = fileURLToPath(new URL("../../src/", import.meta.url));
+const STUB = new URL("./transformers-upgrade-stub.mjs", import.meta.url).href;
+
+function firstExisting(base) {
+ for (const candidate of [`${base}.ts`, `${base}/index.ts`, base]) {
+ if (existsSync(candidate)) return pathToFileURL(candidate).href;
+ }
+ return null;
+}
+
+export function resolve(specifier, context, next) {
+ if (
+ specifier === "@/features/transformers-upgrade" ||
+ /(^|\/)features\/transformers-upgrade$/.test(specifier)
+ ) {
+ return next(STUB, context);
+ }
+ if (specifier.startsWith("@/")) {
+ const resolved = firstExisting(SRC + specifier.slice(2));
+ return next(resolved ?? specifier, context);
+ }
+ if (specifier.startsWith(".") && context.parentURL?.startsWith("file:")) {
+ const resolved = firstExisting(
+ fileURLToPath(new URL(specifier, context.parentURL)),
+ );
+ if (resolved) return next(resolved, context);
+ }
+ return next(specifier, context);
+}
diff --git a/studio/frontend/tests/helpers/transformers-upgrade-stub.d.mts b/studio/frontend/tests/helpers/transformers-upgrade-stub.d.mts
new file mode 100644
index 00000000000..6539d06fcaf
--- /dev/null
+++ b/studio/frontend/tests/helpers/transformers-upgrade-stub.d.mts
@@ -0,0 +1,62 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Types for transformers-upgrade-stub.mjs so a .ts test can drive it without `any`.
+// Same shape as export-api-stub.d.mts next to it.
+
+/** One argument object as the stub records it. Loose on purpose: a test asserts a key
+ * is absent as well as present, so every field is optional and reading an unknown one
+ * is a compile error rather than `any`. */
+export interface RecordedArgs {
+ modelName?: unknown;
+ upgrade?: unknown;
+ trustRemoteCodeFallback?: unknown;
+ forceCancelActive?: unknown;
+ preferLocalCache?: unknown;
+ modelLocalPath?: unknown;
+ modelSnapshotPath?: unknown;
+ modelSnapshotRepoId?: unknown;
+ resumeRunId?: unknown;
+}
+
+export declare const calls: { name: string; args: RecordedArgs[] }[];
+
+export declare const state: {
+ /** What `checkTransformersUpgrade` returns, or an Error it throws instead. */
+ checkResult:
+ | {
+ upgrade: unknown;
+ requiresTrustRemoteCode: boolean;
+ latestTierActive: boolean;
+ forces16Bit: boolean;
+ installBreaksExactResume?: boolean;
+ }
+ | Error;
+ /** What the consent dialog resolves to. */
+ consentResult: boolean;
+ /** Whether the dialog actually ran an install, which is what forces 16-bit. */
+ installRan: boolean;
+ /** Whether the install unloaded the chat model, read once and cleared. */
+ serverUnloadedChat: boolean;
+};
+
+export declare function resetStub(): void;
+
+export declare function checkTransformersUpgrade(
+ modelName: string,
+ hfToken?: string | null,
+ options?: unknown,
+): Promise<unknown>;
+
+export declare function confirmTransformersUpgradeIfNeeded(
+ args: unknown,
+): Promise<boolean>;
+
+export declare function installLatestTransformers(): Promise<never>;
+
+export declare const useTransformersUpgradeDialogStore: {
+ getState(): {
+ installRan: boolean;
+ consumeServerUnloadedChat(): boolean;
+ };
+};
diff --git a/studio/frontend/tests/helpers/transformers-upgrade-stub.mjs b/studio/frontend/tests/helpers/transformers-upgrade-stub.mjs
new file mode 100644
index 00000000000..aeb5cf8a655
--- /dev/null
+++ b/studio/frontend/tests/helpers/transformers-upgrade-stub.mjs
@@ -0,0 +1,72 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Stands in for src/features/transformers-upgrade/index.ts.
+//
+// The real barrel re-exports the consent dialog (.tsx) and node
+// --experimental-strip-types cannot parse JSX, so importing the training-side gate here
+// would pull in the whole React tree. Same cut as export-api-stub.mjs.
+// `checkTransformersUpgrade` answers from `checkResult` (or throws it), the consent
+// answer comes from `consentResult`, and every call is recorded on `calls`.
+
+export const calls = [];
+
+export const state = {
+ checkResult: {
+ upgrade: null,
+ requiresTrustRemoteCode: false,
+ latestTierActive: false,
+ forces16Bit: false,
+ installBreaksExactResume: false,
+ },
+ consentResult: true,
+ installRan: false,
+ serverUnloadedChat: false,
+};
+
+export function resetStub() {
+ calls.length = 0;
+ state.checkResult = {
+ upgrade: null,
+ requiresTrustRemoteCode: false,
+ latestTierActive: false,
+ forces16Bit: false,
+ installBreaksExactResume: false,
+ };
+ state.consentResult = true;
+ state.installRan = false;
+ state.serverUnloadedChat = false;
+}
+
+export async function checkTransformersUpgrade(modelName, hfToken, options) {
+ calls.push({
+ name: "checkTransformersUpgrade",
+ args: [modelName, hfToken, options],
+ });
+ if (state.checkResult instanceof Error) {
+ throw state.checkResult;
+ }
+ return state.checkResult;
+}
+
+export async function confirmTransformersUpgradeIfNeeded(args) {
+ calls.push({ name: "confirmTransformersUpgradeIfNeeded", args: [args] });
+ return state.consentResult;
+}
+
+export async function installLatestTransformers() {
+ throw new Error("installLatestTransformers is not exercised by this stub");
+}
+
+export const useTransformersUpgradeDialogStore = {
+ getState() {
+ return {
+ installRan: state.installRan,
+ consumeServerUnloadedChat() {
+ const value = state.serverUnloadedChat;
+ state.serverUnloadedChat = false;
+ return value;
+ },
+ };
+ },
+};
diff --git a/studio/frontend/tests/training-transformers-upgrade.test.ts b/studio/frontend/tests/training-transformers-upgrade.test.ts
new file mode 100644
index 00000000000..13ce3b3f1f9
--- /dev/null
+++ b/studio/frontend/tests/training-transformers-upgrade.test.ts
@@ -0,0 +1,436 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// A Train-tab run on a model whose architecture no installed transformers ships was
+// accepted, spawned, and killed minutes later at model load:
+// "unsloth/Muse-Glimmer-30B-unsloth-bnb-4bit is not supported yet in transformers==5.3.0"
+// Studio already had the consent dialog that provisions .venv_t5_latest, but it was
+// wired only into chat. These pin the gate: the start path consults the check, pauses
+// on the dialog, and abandons the start when declined.
+
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+
+register("./helpers/transformers-upgrade-resolver.mjs", import.meta.url);
+
+const stub = await import("./helpers/transformers-upgrade-stub.mjs");
+const { confirmTrainingTransformersUpgrade } = await import(
+ "../src/features/training/lib/training-transformers-upgrade.ts"
+);
+
+const MODEL = "unsloth/Muse-Glimmer-30B-unsloth-bnb-4bit";
+const UPGRADE = {
+ // biome-ignore lint/style/useNamingConvention: API schema
+ model_type: "muse_glimmer",
+ // biome-ignore lint/style/useNamingConvention: API schema
+ pypi_version: "5.15.0",
+ // biome-ignore lint/style/useNamingConvention: API schema
+ supported_in_pypi: true,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ supported_in_main: true,
+};
+
+test("a model no installed transformers ships pauses the start on the dialog", async () => {
+ stub.resetStub();
+ stub.state.checkResult = {
+ upgrade: UPGRADE,
+ requiresTrustRemoteCode: false,
+ latestTierActive: false,
+ forces16Bit: true,
+ };
+ stub.state.consentResult = true;
+ stub.state.installRan = true;
+
+ const outcome = await confirmTrainingTransformersUpgrade({
+ modelName: MODEL,
+ hfToken: "hf_token",
+ });
+
+ assert.deepEqual(outcome, {
+ proceed: true,
+ error: null,
+ forces16Bit: true,
+ requiresTrustRemoteCode: false,
+ });
+ assert.equal(stub.calls[0]?.name, "checkTransformersUpgrade");
+ assert.deepEqual(stub.calls[0]?.args.slice(0, 2), [MODEL, "hf_token"]);
+ assert.equal(stub.calls[1]?.name, "confirmTransformersUpgradeIfNeeded");
+ assert.equal(stub.calls[1]?.args[0].modelName, MODEL);
+ assert.equal(stub.calls[1]?.args[0].upgrade, UPGRADE);
+});
+
+test("declining the install abandons the start instead of spawning a doomed run", async () => {
+ stub.resetStub();
+ stub.state.checkResult = {
+ upgrade: UPGRADE,
+ requiresTrustRemoteCode: false,
+ latestTierActive: false,
+ forces16Bit: true,
+ };
+ stub.state.consentResult = false;
+
+ const outcome = await confirmTrainingTransformersUpgrade({
+ modelName: MODEL,
+ hfToken: null,
+ });
+
+ assert.equal(outcome.proceed, false);
+ assert.equal(outcome.forces16Bit, false);
+ // The worker's own wording, so the message names the real cause.
+ assert.match(String(outcome.error), /is not supported yet/);
+ assert.ok(String(outcome.error).includes(MODEL));
+});
+
+test("a model shipping its own code keeps the custom-code way out", async () => {
+ stub.resetStub();
+ stub.state.checkResult = {
+ upgrade: { ...UPGRADE, supported_in_pypi: false },
+ requiresTrustRemoteCode: true,
+ latestTierActive: false,
+ forces16Bit: false,
+ };
+
+ await confirmTrainingTransformersUpgrade({ modelName: MODEL });
+
+ assert.equal(
+ stub.calls[1]?.args[0].trustRemoteCodeFallback,
+ true,
+ "the dialog must offer the trust_remote_code fallback, like chat does",
+ );
+ // Training raises no "stop N chats" prompt, so it carries no answer to one: the
+ // install must never cancel someone else's stream on this tab's behalf.
+ assert.equal(stub.calls[1]?.args[0].forceCancelActive, undefined);
+});
+
+test("a resolved custom-code fallback still loads 4-bit", async () => {
+ stub.resetStub();
+ stub.state.checkResult = {
+ upgrade: { ...UPGRADE, supported_in_pypi: false },
+ requiresTrustRemoteCode: true,
+ latestTierActive: false,
+ forces16Bit: false,
+ };
+ // The fallback resolves true WITHOUT installing, so the sidecar never activates.
+ stub.state.consentResult = true;
+ stub.state.installRan = false;
+
+ const outcome = await confirmTrainingTransformersUpgrade({
+ modelName: MODEL,
+ });
+
+ assert.deepEqual(outcome, {
+ proceed: true,
+ error: null,
+ forces16Bit: false,
+ requiresTrustRemoteCode: true,
+ });
+});
+
+test("an already-routed model reports 16-bit without a dialog", async () => {
+ stub.resetStub();
+ stub.state.checkResult = {
+ upgrade: null,
+ requiresTrustRemoteCode: false,
+ latestTierActive: true,
+ forces16Bit: true,
+ };
+
+ const outcome = await confirmTrainingTransformersUpgrade({
+ modelName: MODEL,
+ });
+
+ assert.deepEqual(outcome, {
+ proceed: true,
+ error: null,
+ forces16Bit: true,
+ requiresTrustRemoteCode: false,
+ });
+ assert.equal(
+ stub.calls.length,
+ 1,
+ "nothing to install, so nothing to consent to",
+ );
+});
+
+test("an exact 4-bit resume is never offered an install that strands it", async () => {
+ // The sidecar is a persistent overlay and this checkpoint is attested against a 4-bit
+ // load it permanently refuses (effective_training_load_in_4bit raises
+ // ExactResumeResourcesUnavailable). The model ships its own code, so the resume works
+ // today: consenting would trade it for an upgrade it does not need, with no way back.
+ stub.resetStub();
+ stub.state.checkResult = {
+ upgrade: UPGRADE,
+ requiresTrustRemoteCode: true,
+ latestTierActive: false,
+ forces16Bit: false,
+ installBreaksExactResume: true,
+ };
+
+ const outcome = await confirmTrainingTransformersUpgrade({
+ modelName: MODEL,
+ resumeRunId: "run-42",
+ });
+
+ assert.deepEqual(outcome, {
+ proceed: true,
+ error: null,
+ forces16Bit: false,
+ requiresTrustRemoteCode: true,
+ });
+ assert.equal(
+ stub.calls.length,
+ 1,
+ "no install may be offered when accepting it would strand the checkpoint",
+ );
+ assert.equal(stub.calls[0]?.args[2]?.resumeRunId, "run-42");
+});
+
+test("a resume with no custom-code way out is not offered a doomed install", async () => {
+ // No fallback, so the install looks like the only way in, but it is not one:
+ // installing activates the latest tier, and effective_training_load_in_4bit then
+ // raises for the very config the backend answered installBreaksExactResume with. The
+ // resume fails either way, and consent buys only a persistent overlay that retires
+ // 4-bit for every later run, so the start is refused with a reason instead.
+ stub.resetStub();
+ stub.state.checkResult = {
+ upgrade: UPGRADE,
+ requiresTrustRemoteCode: false,
+ latestTierActive: false,
+ forces16Bit: true,
+ installBreaksExactResume: true,
+ };
+ stub.state.consentResult = true;
+ stub.state.installRan = true;
+
+ const outcome = await confirmTrainingTransformersUpgrade({
+ modelName: MODEL,
+ resumeRunId: "run-42",
+ });
+
+ assert.equal(outcome.proceed, false);
+ assert.equal(outcome.forces16Bit, false);
+ assert.match(String(outcome.error), /4-bit model load/);
+ assert.match(String(outcome.error), /Start a new run/);
+ assert.equal(
+ stub.calls.length,
+ 1,
+ "an install that cannot rescue the resume must never be offered",
+ );
+});
+
+test("a resume with nothing to install is told the truth about why", async () => {
+ // installBreaksExactResume answers "would the install strand this checkpoint", and the
+ // backend answers it from the run's own provenance, without regard to whether a
+ // release exists to install. For a dev-only architecture there is none, so "installing
+ // would strand it, start a new run instead" is wrong twice over: nothing can be
+ // installed, and a new run on the same architecture cannot load either. The dev-only
+ // explanation is the accurate one.
+ stub.resetStub();
+ stub.state.checkResult = {
+ upgrade: { ...UPGRADE, supported_in_pypi: false },
+ requiresTrustRemoteCode: false,
+ latestTierActive: false,
+ forces16Bit: false,
+ installBreaksExactResume: true,
+ };
+ stub.state.consentResult = false;
+
+ const outcome = await confirmTrainingTransformersUpgrade({
+ modelName: MODEL,
+ resumeRunId: "run-42",
+ });
+
+ assert.equal(outcome.proceed, false);
+ assert.doesNotMatch(String(outcome.error), /Start a new run/);
+ assert.match(String(outcome.error), /development branch/);
+ assert.match(String(outcome.error), /next transformers release/);
+});
+
+test("declining a dev-only upgrade is not told to start again and install it", async () => {
+ // Nothing to install: the architecture is only on transformers main, so the dialog
+ // shows no Install action at all. Reusing the installable wording would send the user
+ // round a loop that can never end.
+ stub.resetStub();
+ stub.state.checkResult = {
+ upgrade: { ...UPGRADE, supported_in_pypi: false },
+ requiresTrustRemoteCode: false,
+ latestTierActive: false,
+ forces16Bit: false,
+ };
+ stub.state.consentResult = false;
+
+ const outcome = await confirmTrainingTransformersUpgrade({
+ modelName: MODEL,
+ });
+
+ assert.equal(outcome.proceed, false);
+ assert.doesNotMatch(String(outcome.error), /Start the run again/);
+ assert.match(String(outcome.error), /development branch/);
+ assert.match(String(outcome.error), /next transformers release/);
+});
+
+test("declining an installable upgrade is still told how to get it", async () => {
+ stub.resetStub();
+ stub.state.checkResult = {
+ upgrade: UPGRADE,
+ requiresTrustRemoteCode: false,
+ latestTierActive: false,
+ forces16Bit: true,
+ };
+ stub.state.consentResult = false;
+
+ const outcome = await confirmTrainingTransformersUpgrade({
+ modelName: MODEL,
+ });
+
+ assert.match(String(outcome.error), /Start the run again to install it/);
+});
+
+test("the check is asked about the copy the run will load", async () => {
+ // A cached model loads from its pinned snapshot; the repo's current config.json can
+ // name a different architecture, and gating on that one gates on the wrong model.
+ stub.resetStub();
+
+ await confirmTrainingTransformersUpgrade({
+ modelName: MODEL,
+ modelCachePin: {
+ preferLocalCache: true,
+ modelLocalPath: "/cache/models--org--model",
+ modelSnapshotPath: "/cache/models--org--model/snapshots/abc",
+ modelSnapshotRepoId: "org/model",
+ },
+ });
+
+ assert.deepEqual(stub.calls[0]?.args[2], {
+ preferLocalCache: true,
+ modelLocalPath: "/cache/models--org--model",
+ modelSnapshotPath: "/cache/models--org--model/snapshots/abc",
+ modelSnapshotRepoId: "org/model",
+ resumeRunId: undefined,
+ });
+});
+
+test("a backend without the check leaves the start exactly as it was", async () => {
+ stub.resetStub();
+ stub.state.checkResult = new Error("404 Not Found");
+
+ const outcome = await confirmTrainingTransformersUpgrade({
+ modelName: MODEL,
+ });
+
+ assert.deepEqual(outcome, {
+ proceed: true,
+ error: null,
+ forces16Bit: false,
+ requiresTrustRemoteCode: false,
+ });
+ assert.equal(stub.calls.length, 1);
+});
+
+test("the custom-code verdict travels to the next gate", async () => {
+ // The gate has just read this model's config, so it knows the model ships its own
+ // modeling code. confirmRemoteCodeIfNeeded falls back to the caller's flag when the
+ // scan request itself fails, and the training callers' stored flag is false on a fresh
+ // run: without carrying this out, that fallback skips consent and starts a worker with
+ // trust_remote_code off, for a model that cannot load without it.
+ stub.resetStub();
+ stub.state.checkResult = {
+ upgrade: { ...UPGRADE, supported_in_pypi: false },
+ requiresTrustRemoteCode: true,
+ latestTierActive: false,
+ forces16Bit: false,
+ };
+ stub.state.consentResult = true;
+ stub.state.installRan = false;
+
+ const outcome = await confirmTrainingTransformersUpgrade({
+ modelName: MODEL,
+ });
+
+ assert.equal(outcome.proceed, true);
+ assert.equal(outcome.requiresTrustRemoteCode, true);
+});
+
+test("a model without custom code reports no verdict to carry", async () => {
+ stub.resetStub();
+ stub.state.checkResult = {
+ upgrade: null,
+ requiresTrustRemoteCode: false,
+ latestTierActive: false,
+ forces16Bit: false,
+ };
+
+ const outcome = await confirmTrainingTransformersUpgrade({
+ modelName: MODEL,
+ });
+
+ assert.equal(outcome.requiresTrustRemoteCode, false);
+});
+
+// Everything that worked before this gate has to keep working. The realistic mismatch
+// is a bundle newer than the backend serving it, which is every in-place upgrade between
+// the assets swapping and the server restarting: the route 404s and the check throws.
+for (const [label, failure] of [
+ ["a 404 from a backend without the route", new Error("404: API endpoint not found")],
+ ["a 405 from a backend without the route", new Error("405: Method Not Allowed")],
+ ["a 500 from a broken backend", new Error("500: Internal Server Error")],
+ ["a network failure", new TypeError("Failed to fetch")],
+] as const) {
+ test(`${label} leaves the start exactly as it was`, async () => {
+ stub.resetStub();
+ stub.state.checkResult = failure;
+ const outcome = await confirmTrainingTransformersUpgrade({ modelName: MODEL });
+ assert.equal(outcome.proceed, true);
+ assert.equal(outcome.error, null);
+ assert.equal(outcome.forces16Bit, false);
+ // false is what the next gate would have used anyway, and the start path ORs it
+ // with the stored flag, so a failed check can never REMOVE a custom-code consent.
+ assert.equal(outcome.requiresTrustRemoteCode, false);
+ assert.equal(
+ stub.calls.filter((c) => c.name === "confirmTransformersUpgradeIfNeeded").length,
+ 0,
+ "a preflight that could not run must raise no dialog",
+ );
+ });
+}
+
+test("an upgrade with no version is never offered as an install", async () => {
+ // A partially populated payload must not produce "Install transformers undefined".
+ stub.resetStub();
+ stub.state.checkResult = {
+ upgrade: {
+ // biome-ignore lint/style/useNamingConvention: API schema
+ model_type: "muse_glimmer",
+ // biome-ignore lint/style/useNamingConvention: API schema
+ pypi_version: null,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ supported_in_pypi: true,
+ },
+ requiresTrustRemoteCode: false,
+ latestTierActive: false,
+ forces16Bit: false,
+ };
+ stub.state.consentResult = false;
+ const outcome = await confirmTrainingTransformersUpgrade({ modelName: MODEL });
+ assert.equal(outcome.proceed, false);
+ assert.match(String(outcome.error), /no released transformers version supports it/);
+});
+
+test("a field from a newer backend is ignored rather than fatal", async () => {
+ stub.resetStub();
+ stub.state.checkResult = {
+ upgrade: null,
+ requiresTrustRemoteCode: false,
+ latestTierActive: false,
+ forces16Bit: false,
+ };
+ // Added through Object.assign because the stub's types are deliberately exact: a key
+ // this build has never heard of is a compile error there, which is the whole point of
+ // typing it that way, and is also exactly what a newer backend would send.
+ Object.assign(stub.state.checkResult, {
+ someVerdictThisBuildHasNeverHeardOf: { nested: true },
+ });
+ const outcome = await confirmTrainingTransformersUpgrade({ modelName: MODEL });
+ assert.equal(outcome.proceed, true);
+});
diff --git a/studio/frontend/tests/training-upgrade-gate-contract.test.ts b/studio/frontend/tests/training-upgrade-gate-contract.test.ts
new file mode 100644
index 00000000000..065a359d051
--- /dev/null
+++ b/studio/frontend/tests/training-upgrade-gate-contract.test.ts
@@ -0,0 +1,153 @@
+// 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 gap this closes: `confirmTransformersUpgradeIfNeeded` had two callers, both in
+// chat, so a Train-tab run on an architecture no installed transformers ships was
+// accepted and then died at model load with
+// "... is not supported yet in transformers==5.3.0"
+// and no prompt. Reading the start paths rather than driving them keeps this a cheap
+// guard against the gate being dropped from either one.
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+const START_PATHS = [
+ "../src/features/training/lib/start-fresh-training-run.ts",
+ "../src/features/training/lib/resume-training-run.ts",
+] as const;
+
+function read(relative: string): string {
+ return readFileSync(new URL(relative, import.meta.url), "utf8");
+}
+
+test("both training start paths consult the transformers-upgrade gate", () => {
+ for (const file of START_PATHS) {
+ assert.ok(
+ read(file).includes("confirmTrainingTransformersUpgrade"),
+ `${file} must consult the transformers-upgrade gate: without it a model whose ` +
+ "architecture no installed transformers ships is accepted and then dies at " +
+ "model load, with no prompt and no way for the user to act on it",
+ );
+ }
+});
+
+test("the upgrade dialog is raised before the custom-code dialog", () => {
+ // Chat's order, and for the same reason: installing a newer transformers changes
+ // what the load would even run, so consenting to the install has to come first.
+ for (const file of START_PATHS) {
+ const source = read(file);
+ const upgradeAt = source.indexOf("confirmTrainingTransformersUpgrade(");
+ const remoteCodeAt = source.indexOf("confirmRemoteCodeIfNeeded(");
+ // Both must be present: a missing call indexes to -1, which would otherwise
+ // satisfy the ordering assertion without either gate existing.
+ assert.ok(
+ upgradeAt >= 0 && remoteCodeAt >= 0,
+ `${file} must run both gates`,
+ );
+ assert.ok(
+ upgradeAt < remoteCodeAt,
+ `${file} must raise the upgrade dialog before the custom-code dialog`,
+ );
+ }
+});
+
+test("both gates on a start path inspect the same copy of the model", () => {
+ // The upgrade check used to be handed the Hub identifier while the custom-code gate
+ // resolved the pinned snapshot, so a cached model could be judged on two different
+ // architectures. One resolver per start path keeps them from drifting apart again.
+ for (const [file, resolver] of [
+ [
+ "../src/features/training/lib/start-fresh-training-run.ts",
+ "freshModelCachePin(",
+ ],
+ [
+ "../src/features/training/lib/resume-training-run.ts",
+ "resumeModelCachePin(",
+ ],
+ ] as const) {
+ const source = read(file);
+ assert.equal(
+ source.split(resolver).length - 1,
+ 3,
+ `${file} must resolve the cache pin once and pass it to both gates`,
+ );
+ }
+});
+
+test("the resume gate names the run it precedes", () => {
+ // Without the run id the check cannot tell that installing would permanently strand
+ // a checkpoint attested against a 4-bit model load the latest sidecar refuses.
+ const source = read("../src/features/training/lib/resume-training-run.ts");
+ assert.ok(source.includes("resumeRunId"));
+});
+
+test("the gate reaches the install through the shared consent dialog", () => {
+ // Not a second implementation of the flow chat already owns.
+ const gate = read(
+ "../src/features/training/lib/training-transformers-upgrade.ts",
+ );
+ assert.ok(gate.includes("confirmTransformersUpgradeIfNeeded"));
+ assert.ok(gate.includes("checkTransformersUpgrade"));
+});
+
+test("the Configure preview re-asks the check after an install", () => {
+ // The hook itself is React, so this guards the wiring the notice cache depends on:
+ // the store counts completed installs and the hook keys its answers on that count.
+ // Break either end and Configure keeps offering an install that already ran, and
+ // 4-bit for a run the new sidecar loads in 16-bit.
+ const store = read(
+ "../src/features/transformers-upgrade/stores/transformers-upgrade-dialog-store.ts",
+ );
+ assert.ok(
+ /sidecarGeneration:\s*get\(\)\.sidecarGeneration \+ 1/.test(store),
+ "a successful install must advance sidecarGeneration",
+ );
+
+ const hook = read(
+ "../src/features/training/hooks/use-training-transformers-upgrade-notice.ts",
+ );
+ assert.ok(hook.includes("s.sidecarGeneration"));
+ assert.ok(
+ /upgradeNoticeCacheKey\(\s*sidecarGeneration/.test(hook),
+ "the preview cache key must carry the generation, or an install cannot retire it",
+ );
+});
+
+test("the consent dialog offers the custom-code way out before an install fails", () => {
+ // Training raises this dialog before a run starts, so what it offers decides what the
+ // run can be. For a model shipping its own code the install is the more expensive way
+ // forward, activating the 16-bit sidecar, so gating the fallback on the error phase
+ // left a QLoRA run with Install or Cancel and no way to the 4-bit run it asked for.
+ const dialog = read(
+ "../src/features/transformers-upgrade/components/transformers-upgrade-dialog.tsx",
+ );
+ assert.ok(
+ dialog.includes("upgradeDialogActions"),
+ "the dialog must take its actions from the shared decision, not re-derive them",
+ );
+ assert.doesNotMatch(
+ dialog,
+ /phase === "error" && trustRemoteCodeFallback/,
+ "the custom-code fallback must not wait for an install to fail first",
+ );
+});
+
+test("both start paths carry the upgrade gate's custom-code verdict forward", () => {
+ // confirmRemoteCodeIfNeeded falls back to the caller's requiresTrustRemoteCode when the
+ // scan request fails, and the stored flag is false on a fresh run. The upgrade check
+ // has already answered the question, so it has to be the one that travels.
+ for (const file of START_PATHS) {
+ const source = read(file);
+ assert.ok(
+ source.includes(
+ "verdict.requiresTrustRemoteCode = outcome.requiresTrustRemoteCode",
+ ),
+ `${file} must record the upgrade gate's custom-code verdict`,
+ );
+ assert.ok(
+ source.includes("upgradeRequiresTrustRemoteCode"),
+ `${file} must pass that verdict into the custom-code gate`,
+ );
+ }
+});
diff --git a/studio/frontend/tests/training-upgrade-notice-cache.test.ts b/studio/frontend/tests/training-upgrade-notice-cache.test.ts
new file mode 100644
index 00000000000..adc9fad927e
--- /dev/null
+++ b/studio/frontend/tests/training-upgrade-notice-cache.test.ts
@@ -0,0 +1,128 @@
+// 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 Configure preview asks the upgrade check once per model and caches the answer,
+// because the hook behind it runs on every render. That cache used to outlive what it
+// describes: consenting to the install provisions a persistent sidecar, and returning to
+// Configure in the same session kept reading the pre-install answer, so the card went on
+// offering a release already installed and promising "QLoRA - 4-bit" for a run the new
+// overlay loads in 16-bit.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ hasUpgradeNoticeCache,
+ readUpgradeNoticeCache,
+ upgradeNoticeCacheKey,
+ writeUpgradeNoticeCache,
+} from "../src/features/training/lib/training-upgrade-notice-cache.ts";
+import type { TransformersUpgradeCheck } from "../src/features/transformers-upgrade/types.ts";
+
+const MODEL = "unsloth/Muse-Glimmer-30B-unsloth-bnb-4bit";
+
+// What the check says before the install: a release to offer, and 4-bit still available
+// because the model's own code can load it on the current transformers.
+const BEFORE_INSTALL: TransformersUpgradeCheck = {
+ upgrade: {
+ // biome-ignore lint/style/useNamingConvention: API schema
+ model_type: "muse_glimmer",
+ // biome-ignore lint/style/useNamingConvention: API schema
+ pypi_version: "5.15.0",
+ // biome-ignore lint/style/useNamingConvention: API schema
+ supported_in_pypi: true,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ supported_in_main: true,
+ },
+ requiresTrustRemoteCode: true,
+ latestTierActive: false,
+ forces16Bit: false,
+ installBreaksExactResume: false,
+};
+
+// What it says once the install has landed: nothing left to offer, and the sidecar that
+// now routes this model trains it in 16-bit.
+const AFTER_INSTALL: TransformersUpgradeCheck = {
+ upgrade: null,
+ requiresTrustRemoteCode: true,
+ latestTierActive: true,
+ forces16Bit: true,
+ installBreaksExactResume: false,
+};
+
+test("an answer is reused for the same model, copy and token", () => {
+ const key = upgradeNoticeCacheKey(0, MODEL, false, null, "");
+ writeUpgradeNoticeCache(0, key, BEFORE_INSTALL);
+
+ assert.equal(upgradeNoticeCacheKey(0, MODEL, false, null, ""), key);
+ assert.equal(hasUpgradeNoticeCache(0, key), true);
+ assert.equal(readUpgradeNoticeCache(0, key), BEFORE_INSTALL);
+});
+
+test("an install retires every answer taken before it", () => {
+ const before = upgradeNoticeCacheKey(1, MODEL, false, null, "");
+ writeUpgradeNoticeCache(1, before, BEFORE_INSTALL);
+ assert.equal(readUpgradeNoticeCache(1, before), BEFORE_INSTALL);
+
+ // The consent flow installed the sidecar, so the store's generation moved on.
+ const after = upgradeNoticeCacheKey(2, MODEL, false, null, "");
+ assert.notEqual(after, before);
+ assert.equal(
+ hasUpgradeNoticeCache(2, after),
+ false,
+ "a post-install render must re-ask, not repeat the pre-install answer",
+ );
+ assert.equal(readUpgradeNoticeCache(2, after), null);
+});
+
+test("a different copy or token is still a different answer", () => {
+ const key = upgradeNoticeCacheKey(3, MODEL, false, null, "");
+ writeUpgradeNoticeCache(3, key, BEFORE_INSTALL);
+
+ assert.equal(
+ hasUpgradeNoticeCache(
+ 3,
+ upgradeNoticeCacheKey(3, MODEL, true, "/cache/x", ""),
+ ),
+ false,
+ );
+ assert.equal(
+ hasUpgradeNoticeCache(
+ 3,
+ upgradeNoticeCacheKey(3, MODEL, false, null, "hf_token"),
+ ),
+ false,
+ );
+ assert.equal(
+ hasUpgradeNoticeCache(
+ 3,
+ upgradeNoticeCacheKey(3, "org/other", false, null, ""),
+ ),
+ false,
+ );
+ // A known-cached row can have a null path, and the backend still resolves the pin from
+ // the cache roots, so the flag alone is a different question about the same model.
+ assert.equal(
+ hasUpgradeNoticeCache(3, upgradeNoticeCacheKey(3, MODEL, true, null, "")),
+ false,
+ );
+ assert.equal(readUpgradeNoticeCache(3, key), BEFORE_INSTALL);
+});
+
+test("a check still in flight across the install cannot rewind the cache", () => {
+ // The pre-install check is a network round trip racing an install that takes a
+ // minute, so it can resolve after the post-install check answered. Its write must be
+ // dropped: rewinding the generation would clear the fresh entry for the stale one, and
+ // with its effect already cleaned up nothing re-asks, so Configure would show no
+ // notice for the rest of the session.
+ const stale = upgradeNoticeCacheKey(4, MODEL, false, null, "");
+ const fresh = upgradeNoticeCacheKey(5, MODEL, false, null, "");
+ writeUpgradeNoticeCache(5, fresh, AFTER_INSTALL);
+
+ writeUpgradeNoticeCache(4, stale, BEFORE_INSTALL);
+
+ assert.equal(hasUpgradeNoticeCache(5, fresh), true);
+ assert.equal(readUpgradeNoticeCache(5, fresh), AFTER_INSTALL);
+ assert.equal(hasUpgradeNoticeCache(4, stale), false);
+ assert.equal(readUpgradeNoticeCache(4, stale), null);
+});
diff --git a/studio/frontend/tests/training-upgrade-notice-precision.test.ts b/studio/frontend/tests/training-upgrade-notice-precision.test.ts
new file mode 100644
index 00000000000..6cc900161fd
--- /dev/null
+++ b/studio/frontend/tests/training-upgrade-notice-precision.test.ts
@@ -0,0 +1,109 @@
+// 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 Configure preview reports one precision for a run whose precision depends on the
+// action taken at Start. A model that ships its own modeling code AND is shipped by the
+// offered release gets both dialog actions: the custom code loads it on the current
+// transformers in 4-bit, Install activates the 16-bit sidecar. The backend collapses
+// that to forces_16bit=false, answering for the fallback, so the card offered the
+// install while promising QLoRA - 4-bit for a run Install turns into roughly triple the
+// VRAM, or an OOM.
+
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+
+import type { TransformersUpgradeCheck } from "../src/features/transformers-upgrade/types.ts";
+
+register("./helpers/transformers-upgrade-resolver.mjs", import.meta.url);
+
+const { trainingTransformersUpgradeNotice } = await import(
+ "../src/features/training/lib/training-transformers-upgrade.ts"
+);
+
+const RELEASE = "5.15.0";
+
+/** Custom code AND an installable release: both dialog actions are selectable. */
+const BOTH_ACTIONS: TransformersUpgradeCheck = {
+ upgrade: {
+ // biome-ignore lint/style/useNamingConvention: API schema
+ model_type: "muse_glimmer",
+ // biome-ignore lint/style/useNamingConvention: API schema
+ pypi_version: RELEASE,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ supported_in_pypi: true,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ supported_in_main: true,
+ },
+ requiresTrustRemoteCode: true,
+ latestTierActive: false,
+ // The backend answers for the custom-code fallback, which keeps 4-bit.
+ forces16Bit: false,
+ installBreaksExactResume: false,
+};
+
+test("an offered install that is not already 16-bit discloses that Install switches to 16-bit", () => {
+ const notice = trainingTransformersUpgradeNotice(BOTH_ACTIONS, true);
+ assert.equal(notice.installVersion, RELEASE);
+ // Not already 16-bit: picking the custom-code fallback really does keep 4-bit.
+ assert.equal(notice.fourBitUnavailable, false);
+ // But Install is selectable and turns this run 16-bit, so the card must say so.
+ assert.equal(notice.installSwitchesTo16Bit, true);
+});
+
+test("a 16-bit run is not told twice that it will be 16-bit", () => {
+ // No custom code: install_only_upgrade makes the backend answer forces_16bit itself,
+ // and the existing warning already covers it.
+ const notice = trainingTransformersUpgradeNotice(
+ { ...BOTH_ACTIONS, requiresTrustRemoteCode: false, forces16Bit: true },
+ true,
+ );
+ assert.equal(notice.fourBitUnavailable, true);
+ assert.equal(notice.installSwitchesTo16Bit, false);
+});
+
+test("a run that never asked for 4-bit has no precision to lose", () => {
+ // LoRA at 16-bit already: switching the overlay changes nothing it was promised.
+ const notice = trainingTransformersUpgradeNotice(BOTH_ACTIONS, false);
+ assert.equal(notice.installVersion, RELEASE);
+ assert.equal(notice.fourBitUnavailable, false);
+ assert.equal(notice.installSwitchesTo16Bit, false);
+});
+
+test("a dev-only upgrade has no Install action to warn about", () => {
+ const notice = trainingTransformersUpgradeNotice(
+ {
+ ...BOTH_ACTIONS,
+ upgrade: {
+ // biome-ignore lint/style/useNamingConvention: API schema
+ model_type: "muse_glimmer",
+ // biome-ignore lint/style/useNamingConvention: API schema
+ pypi_version: RELEASE,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ supported_in_pypi: false,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ supported_in_main: true,
+ },
+ },
+ true,
+ );
+ assert.equal(notice.installVersion, null);
+ assert.equal(notice.installSwitchesTo16Bit, false);
+});
+
+test("the sidecar already routing this model needs no action-dependent wording", () => {
+ // Installed: there is no choice left to disclose, only the 16-bit fact.
+ const notice = trainingTransformersUpgradeNotice(
+ {
+ upgrade: null,
+ requiresTrustRemoteCode: true,
+ latestTierActive: true,
+ forces16Bit: true,
+ installBreaksExactResume: false,
+ },
+ true,
+ );
+ assert.equal(notice.installVersion, null);
+ assert.equal(notice.fourBitUnavailable, true);
+ assert.equal(notice.installSwitchesTo16Bit, false);
+});
diff --git a/studio/frontend/tests/transformers-upgrade-dialog-actions.test.ts b/studio/frontend/tests/transformers-upgrade-dialog-actions.test.ts
new file mode 100644
index 00000000000..9de7310aa7a
--- /dev/null
+++ b/studio/frontend/tests/transformers-upgrade-dialog-actions.test.ts
@@ -0,0 +1,107 @@
+// 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 consent dialog offered "Continue with custom code" only with nothing to install,
+// or after an install failed. Training now raises it before a run starts, and for a
+// model shipping its own modeling code that hid the only path still loading bnb 4-bit,
+// since installing activates the 16-bit sidecar. So the first dialog offers the fallback
+// next to Install.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { upgradeDialogActions } from "../src/features/transformers-upgrade/lib/upgrade-dialog-actions.ts";
+import type { TransformersUpgradeInfo } from "../src/features/transformers-upgrade/types.ts";
+
+const INSTALLABLE: TransformersUpgradeInfo = {
+ // biome-ignore lint/style/useNamingConvention: API schema
+ model_type: "muse_glimmer",
+ // biome-ignore lint/style/useNamingConvention: API schema
+ pypi_version: "5.15.0",
+ // biome-ignore lint/style/useNamingConvention: API schema
+ supported_in_pypi: true,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ supported_in_main: true,
+};
+const DEV_ONLY: TransformersUpgradeInfo = {
+ ...INSTALLABLE,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ supported_in_pypi: false,
+};
+
+test("an installable release offers the custom-code way out alongside Install", () => {
+ const actions = upgradeDialogActions({
+ upgrade: INSTALLABLE,
+ phase: "consent",
+ trustRemoteCodeFallback: true,
+ });
+
+ assert.equal(actions.installable, true);
+ assert.equal(actions.devOnly, false);
+ assert.equal(
+ actions.customCode,
+ true,
+ "installing forces 16-bit, so hiding this leaves a 4-bit run no way to start",
+ );
+});
+
+test("a model without its own code still offers Install alone", () => {
+ const actions = upgradeDialogActions({
+ upgrade: INSTALLABLE,
+ phase: "consent",
+ trustRemoteCodeFallback: false,
+ });
+
+ assert.equal(actions.installable, true);
+ assert.equal(actions.customCode, false);
+});
+
+test("a failed install keeps the fallback offered", () => {
+ const actions = upgradeDialogActions({
+ upgrade: INSTALLABLE,
+ phase: "error",
+ trustRemoteCodeFallback: true,
+ });
+
+ assert.equal(actions.customCode, true);
+});
+
+test("a running install offers nothing that would abandon it", () => {
+ const actions = upgradeDialogActions({
+ upgrade: INSTALLABLE,
+ phase: "installing",
+ trustRemoteCodeFallback: true,
+ });
+
+ assert.equal(actions.customCode, false);
+});
+
+test("a dev-only upgrade has nothing to install and says so", () => {
+ const actions = upgradeDialogActions({
+ upgrade: DEV_ONLY,
+ phase: "consent",
+ trustRemoteCodeFallback: true,
+ });
+
+ assert.equal(actions.installable, false);
+ assert.equal(actions.devOnly, true);
+ assert.equal(actions.customCode, true);
+});
+
+test("an upgrade no transformers ships at all offers only Cancel", () => {
+ const actions = upgradeDialogActions({
+ upgrade: {
+ ...DEV_ONLY,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ supported_in_main: false,
+ },
+ phase: "consent",
+ trustRemoteCodeFallback: false,
+ });
+
+ assert.deepEqual(actions, {
+ installable: false,
+ devOnly: false,
+ customCode: false,
+ });
+});
diff --git a/studio/frontend/tsconfig.test.json b/studio/frontend/tsconfig.test.json
index e25c1acde65..2e6b0e6c23e 100644
--- a/studio/frontend/tsconfig.test.json
+++ b/studio/frontend/tsconfig.test.json
@@ -26,7 +26,10 @@
"@/*": ["./src/*"]
}
},
- // The ambient declarations too: a test that reaches a src module pulling in
- // the dictation adapter needs the SpeechRecognition globals it declares.
- "include": ["tests", "src/speech-recognition.d.ts"]
+ // The ambient globals under src/ are declaration files, so nothing imports them and
+ // "tests" alone never reaches them. A test that (transitively) pulls in a src module
+ // relying on one -- the dictation adapter's SpeechRecognition globals, say -- would
+ // otherwise fail to typecheck here only; the app project sees them because it
+ // includes all of src.
+ "include": ["tests", "src/**/*.d.ts"]
}