unsloth/studio/backend/utils/transformers_latest.py
Daniel Han 815f242970
Studio: offer the latest transformers release for brand-new architectures (#7056)
* Studio: offer the latest transformers release for brand-new architectures

When a model's config.json model_type is absent from every installed
transformers overlay (base 4.57.x and the .venv_t5_530/550/510 sidecars),
Studio now checks, unauthenticated and cached, whether the newest
transformers ships it:

- utils/transformers_latest.py fetches the latest release version from
  https://pypi.org/pypi/transformers/json and the CONFIG_MAPPING_NAMES
  sources for that tag and for main from raw.githubusercontent.com
  (never api.github.com), parsing them with the same AST extractor the
  static router uses (no code execution, no trust_remote_code). Results
  are cached in memory and in a JSON snapshot under studio_root()/cache
  with a one day ttl; fetches are bounded to 5s with one retry and a
  failure backoff, and offline mode or the new kill switch
  UNSLOTH_STUDIO_NO_LATEST_TRANSFORMERS=1 short-circuits to None.

- POST /api/inference/validate gains requires_transformers_upgrade plus
  a transformers_upgrade payload (model_type, pypi_version,
  supported_in_pypi, supported_in_main) so the frontend can raise the
  install consent dialog before /load, mirroring the existing
  remote-code consent flow. The check fires only when the model_type is
  unknown to all installed overlays and the hardcoded tier tables.

- POST /api/inference/install-latest-transformers provisions a new
  persistent .venv_t5_latest sidecar after user consent, pinned to the
  exact PyPI version (re-verified server-side) with the same
  --target/--no-deps recipe as the fixed sidecars. A JSON pin marker
  inside the dir records the installed package set, so restarts
  revalidate it and routing resolves the new highest-ranked tier
  automatically. A dependency preflight (compat_plan) compares the
  release's requires_dist against the running env: unsatisfied
  tokenizers/safetensors floors are shadow-installed as exact pins into
  the sidecar, anything else unsatisfied blocks the install with a
  clear message.

Routing for every already-supported model_type is unchanged: the
hardcoded lists and the 530/550/510 static resolver run first, the new
tier only participates once its venv exists, and the probe order gains
the latest sidecar only when provisioned. Verified against live PyPI
and GitHub (transformers 5.13.0: 674 model_types, 26 absent from all
installed overlays, e.g. cosmos3_omni; 4 dev-only on main) and with a
real sidecar install plus restart persistence. 64 new tests; the
existing 200-test transformers_version suite passes unchanged.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Latest-transformers check: fetch outside the lock, serialize installs

Release the module lock during the network refresh so a slow fetch cannot
stall other threads in the ASGI pool; concurrent callers during a fetch get
None (the graceful fallthrough) via an in-flight flag instead of stacking
fetches. Serialize install_latest_transformers with an in-progress flag so
concurrent consents cannot race the sidecar delete and recreate; the loser
gets a structured already-in-progress refusal.

* Latest-transformers check: LoRA bases, pin-gated mapping, live reverify

Run the upgrade check over the [adapter, base] target set so a LoRA whose
base model is a brand-new architecture surfaces the prompt (the worker
activates transformers for the base, not the adapter).

Gate the latest overlay's mapping lookup on a valid pin marker, matching
activation and the probe order, so a partial or manual .venv_t5_latest dir
cannot be routed to and then refused at activation.

Re-verify the requested version against a live PyPI snapshot at install
time, falling back to the cached one on fetch failure, so a release
published inside the cache TTL is not silently missed.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Latest-transformers check: nested config types and latest-tier vision probe

Collect every model_type in the config (top level plus each nested
sub-config) and signal on the first one missing from all installed
overlays, so a supported wrapper carrying a brand-new backbone still
surfaces the upgrade prompt; wrappers instantiate sub-configs through
CONFIG_MAPPING and would fail on the nested type.

Route the vision capability subprocess through the pinned latest sidecar
when the model resolves to the latest tier, so latest-only VLMs are not
misclassified as text-only; every other tier keeps the 5.5 sidecar used
today.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Latest tier: nested routing, vision probe after raw miss, safe upgrades

Route by every model_type in the config: a nested sub-config type can raise
the tier (wrappers instantiate sub-configs through CONFIG_MAPPING), so a
supported wrapper with a latest-only backbone routes to latest once
installed instead of staying on default. An unknown nested type never
vetoes; the primary type keeps its previous semantics. The collector is
shared with the upgrade checker.

Vision detection: when the raw heuristics say False for a model that routes
to the latest tier, run the AutoConfig subprocess under the pinned latest
sidecar instead of trusting heuristics built from older transformers.

Provisioning: stage-and-swap. Build the new sidecar in .venv_t5_latest.staging
and swap it in only when the install and pin marker are complete, so a failed
upgrade never destroys a previously working sidecar; restore the old dir if
the final swap fails.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Latest-transformers checker, vision subprocess, and cache fixes

Require the latest release to support every missing model_type (the
primary included) before prompting; a nested-only match cannot make the
model loadable, so no install is offered for it.

The vision-check subprocess now unions the active sidecar's own
registry mappings into the inlined parent-process detection sets, so
architectures only the sidecar knows classify correctly.

A successful sidecar install clears the tier probe cache, the latest
tier's model_type mapping, and the vision-detection cache so the new
venv takes effect without a restart. Tests for all three.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Aggregate upgrade support flags and keep install off /v1

The upgrade signal now reports supported_in_pypi only when the latest
release covers every missing model_type; a mix with a main-only nested
type surfaces as dev-only so no PyPI install is offered that would
still fail at load. The consented install endpoint moves to
studio_router so it is not reachable through the OpenAI-compatible /v1
mount. Tests for both.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Honor the latest-transformers kill switch in routing

With UNSLOTH_STUDIO_NO_LATEST_TRANSFORMERS set after the sidecar was
provisioned, the latest tier still joined mapping and probe routing
because only the pin was checked. Both admission points now also check
the kill switch, so operators can roll back a problematic sidecar
without deleting files.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Repair the latest sidecar through stage-and-swap

The lazy repair path installed into the live .venv_t5_latest, which
_ensure_venv_dir wipes first, so a failed repair deleted the pinned
sidecar and its marker. Both the consented install and the repair now
share one stage-and-swap helper: the incomplete-but-pinned dir survives
any failure and a later attempt can still repair it.

* Tighten comments

* Remove the staging dir when a latest-sidecar install fails

A pip failure inside _ensure_venv_dir returns False without raising, so
the except cleanup never ran and the partial .venv_t5_latest.staging
leaked until a later attempt. Also note on the validate response fields
that frontend consumption ships in the follow-up PR.

* Add the transformers-upgrade consent dialog to the frontend

When /validate reports requires_transformers_upgrade, every explicit load
path (chat runtime and the compare composer) now pauses on a consent
dialog modeled on the remote-code one: it names the model_type and the
latest PyPI transformers version, and on Accept calls
/api/inference/install-latest-transformers itself, shows an installing
state, and resumes the original load automatically on success. Errors
surface in the dialog with a retry; Cancel aborts the load like the
trust dialog's deny path. Architectures shipped only on transformers
main get a dev-only notice with no install button. Background auto-load
skips upgrade-requiring candidates instead of prompting, mirroring the
trust_remote_code rule. The dialog mounts once in the root layout and
runs before the security dialogs, since no load can proceed without the
runtime.

* Route a non-installable new architecture to the custom-code consent as a last resort

When the upgrade dialog has no installable PyPI release (the architecture
is only on transformers main, which Studio never installs), the dialog now
says so explicitly, and when the model also declares custom (auto_map)
code it offers Continue with custom code: resolving the paused load into
the existing trust_remote_code consent gate instead of hard-aborting.
Models with no custom code keep the Cancel-only notice. The backend
returns no upgrade signal at all for architectures unknown to both PyPI
and main, so those still route straight to the unchanged security gate.

* Force a 16-bit load for models on the latest-transformers sidecar

Live validation with Zyphra/ZAYA1-8B (model_type zaya, shipped by
transformers 5.13.1 but unknown to every installed tier) surfaced a
generation crash when the consented sidecar load kept the default bnb
4-bit quantization: transformers' grouped-MoE kernels feed the packed
uint8 expert weights straight into torch._grouped_mm, and generation
dies (plain 16-bit works). New latest_tier_active_for() mirrors the
sidecar activation's tier resolution and never raises; the inference
worker flips load_in_4bit off when it reports true, and the load route
applies the same flip so the pre-load VRAM guard and the worker command
agree. Fixed tiers are untouched. With the guard, ZAYA1-8B loads and
generates correctly in Studio chat.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Offer the custom-code fallback when a latest-sidecar install fails

* Fail remote mapping fetches wholesale and mirror the 16-bit flip in validate

A transient fetch or parse failure of one auto-mapping file no longer caches
a partial latest-release map for the TTL (a real 404 on pre-5.10 tags is
still tolerated), and validate_model now applies the same latest-sidecar
16-bit sizing flip as /load before the training guard so the two agree.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Tighten comments in the latest-transformers changes

* Resolve remote LoRA bases, fold nested tiers, and guard the sidecar swap

latest_tier_active_for now resolves a remote adapter's base model the same
way worker pre-activation does (and returns early without a sidecar pin), a
hardcoded fast-path tier is raised when a nested sub-config's model_type
needs a higher sidecar, and the install route refuses to swap .venv_t5_latest
while training runs on it and unloads a latest-tier chat model first.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Gate the sidecar install on worker liveness and size installable upgrades 16-bit

The install route now refuses while any training or export runs (tier
re-resolution without the load token is unreliable for gated repos), holds
the inference lifecycle gate across the unload and the swap so no load can
interleave, and passes the model name to unload_model. validate_model runs
the upgrade check before the training guard and sizes an installable
upgrade as 16-bit, matching what /load and the worker will force after the
consented install.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Close the sidecar install races and honor the kill switch over cached mappings

Training starts and mutating export routes now refuse while a transformers
install is in progress (shared is_install_in_progress flag), the chat unload
and idle export-worker teardown moved into a before_swap hook that runs only
once the staged install succeeded, and _config_model_types checks the kill
switch before returning a cached latest mapping.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Reserve the sidecar swap before the gate wait and abort it on failed teardown

The install-in-progress flag moved into a shared sidecar swap reservation in
transformers_version, taken by the install route before awaiting the
inference lifecycle gate (so training and export starts see it for the whole
window) and by the lazy .venv_t5_latest repair path. The before_swap hook
now raises when the chat unload or export teardown reports failure, leaving
the previous sidecar untouched.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Back the sidecar swap reservation with a cross-process lock file

The lazy repair runs inside worker subprocesses, where a module-level flag
is invisible to the parent's route checks. The reservation now also creates
a lock file next to .venv_t5_latest (O_EXCL, owner-only removal, stale after
two hours for crashed owners), so is_install_in_progress sees a repair from
any Studio process.

* Hand the swap reservation to the installer thread and harden pre-swap teardown

A cancelled install request no longer releases the reservation while the
installer thread is still staging (the thread owns and releases it, shielded
from cancellation). The route refuses while another inference request is
generating, export teardown runs before the chat unload and is judged by
worker liveness rather than the cleanup return value, and a live inference
worker with no active model (failed load residue) is shut down before the
swap.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Keep the lifecycle gate with the installer and recheck the swap at spawn time

The gate moved into the shielded install task so a cancelled POST cannot
release the guard /load honors while the installer still runs, cached latest
probe results are ignored while the kill switch is set, and the training and
export subprocess spawns recheck the sidecar swap reservation right before
spawning (the route-level guards are one-shot and validation can outlast an
install's start).

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Close the spawn-registration windows against the sidecar install

Training marks the spawn in progress before its reservation recheck and
is_training_active honors the flag, so the install route sees a start that
has passed proc.start() but not yet recorded _proc. Export load-checkpoint
rechecks the reservation after setting _export_active and before tearing
down the old worker, so losing the race keeps the loaded checkpoint instead
of surfacing a 500.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Refine the install-window interleavings around worker teardown

The inference busy count is rechecked under the lifecycle gate (streams
start by taking that gate, so nothing slips past a held gate), the training
handshake moved ahead of the VRAM-freeing before_spawn hook so a lost race
leaves chat/export intact, the export spawn-time check is op-aware (inside
an active op the install is the side that aborts), and the Xet-stall respawn
waits out a transient reservation instead of stranding the run.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Track the install's server-side unload and guard export ops against the swap

The upgrade dialog store records when its install actually ran (the server
unloads the active chat model before swapping), and the load flow then marks
the previous model as unloaded so a later cancelled gate still triggers
rollback; the custom-code fallback leaves the flag unset. _run_export gained
the same reservation handshake as load_checkpoint so an install cannot block
behind an hours-long export op instead of returning 409.

* Tighten comments in the install-guard and upgrade-consent changes

* Surface install-race refusals cleanly and roll back after a failed swap unload

/load refuses while the sidecar swap is reserved so a load cannot succeed
and immediately be unloaded by the pre-swap teardown, worker starts that
lose the install race raise a typed SidecarSwapInProgress mapped to 409
instead of a 500, the install response reports model_unloaded even on a
structured failure so the client can restore its state, and the compare
flow tracks the server-side unload like the primary load path and clears a
stale checkpoint on abort.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Type the export install races, scope the lock release, and keep the unload signal

Export load-checkpoint and export ops raise SidecarSwapInProgress (mapped to
409 in every export route) instead of a 400-shaped failure, the export spawn
check distinguishes repair reservations (always refused) from install ones
(op-aware), the swap lock release only unlinks a lock this process wrote so
a stale-superseded owner cannot drop the new owner's live lock, and the
frontend unload signal survives a superseding consent via read-and-clear
consumption instead of a reset.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Finalize a stalled run when the respawn loses the install race and latch the unload signal

The Xet-stall respawn timeout now finalizes the run as a failure instead of
raising into the pump's broad finalization catch (which stranded it in a
training state with no worker), and a successful install retry ORs the
model_unloaded signal with the latched value so a failed-after-unload first
attempt still triggers rollback.

* Recheck the swap under the load gate and latch the unload before resolver checks

/load rechecks the sidecar reservation after acquiring the lifecycle gate
(an install can reserve while the load queues on it), and the dialog store
latches model_unloaded as soon as the install response arrives, before any
resolver-identity guard, so a superseded consent's unload still reaches
whichever load consumes the signal next.

* Report cleared-state unload failures, guard queued installs, and fold name tiers

A failed chat unload that still cleared the orchestrator's model state now
reports model_unloaded so the client rolls back, the installer aborts with
a 409 when a model load completed while it waited on the lifecycle gate,
and the fixed-tier name fast path consults the config mapping when a latest
sidecar is pinned so an accepted upgrade routes to the sidecar it installed
(no I/O added to the unpinned path).

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Report cleared-state unload failures and harden the spawn handshake flag

The failed-unload branch in before_swap now detects that the orchestrator
cleared its model state and reports model_unloaded before aborting (the
earlier commit claimed this fix but a scripting error dropped the edit),
the installer's queued-load check compares a load generation counter so a
same-model reload is caught, and both training spawn sites wrap everything
after the handshake in a guard that resets _spawn_in_progress on any
exception so a failed start cannot wedge is_training_active.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Bump the load generation when the load is published, not at load start

A start-time bump is already visible when the installer snapshots mid-load,
so a same-model reload completing after the snapshot looked unchanged and
could be unloaded by the swap. The counter now increments alongside the
active_model_name publish.

* Self-heal a broken pinned sidecar, guard lazy repairs, and refresh stale retries

A valid pin whose transformers source dir vanished now triggers the repair
from the routing path (with a five minute backoff after failures) instead of
silently routing latest-only models to older tiers, the lazy repair refuses
while parent-visible chat/training/export workers are active since it has no
teardown of its own, and a version-mismatch install failure carries the
superseding release so the dialog's Retry re-requests a version that can
succeed.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Flip latest-tier loads to 16-bit outside chat and protect export state

Training and export workers now apply the same latest-sidecar 16-bit flip
as the chat worker so a brand-new grouped-MoE architecture cannot reach bnb
4-bit through those paths, the latest-tier vision override returns None on
an inconclusive probe so a transient failure is not cached as not-vision,
and the install route refuses while an idle export checkpoint is loaded
rather than discard it with no rollback signal on a failed swap.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Address parallel-review findings on the sidecar guards and install checks

The training route sizes latest-tier jobs 16-bit before GPU selection, the
inference subprocess spawn rechecks the swap reservation like training and
export (covering the OpenAI auto-switch path) with the typed error mapped
to a retryable 409, compat_plan blocks the install when dependency metadata
cannot be fetched instead of proceeding unverified, snapshot model-type
lists must contain only strings, and pin-marker package specs are validated
against the sidecar's own package set before ever reaching pip.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Parent-only repairs, live-owner locks, remote-base activation, pre-teardown recheck

Lazy sidecar repairs now refuse inside worker children (whose empty backend
singletons cannot see live siblings) and run only in the parent where the
active-worker guard is real, swap-lock staleness requires the owner pid to
be dead so a slow live install is never superseded, both activation entry
points resolve a remote adapter's base model like the inference worker and
latest_tier_active_for already do, and load_model rechecks the reservation
before tearing down the old worker so losing the race keeps the current
model loaded.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Check workers under the repair reservation and keep state on refused swaps

The lazy repair now reserves first and checks workers under the reservation
(worker starts set their active markers before rechecking, so every
interleaving aborts one side), with export ops and in-flight inference loads
counted as active. The inference pre-teardown and spawn guards refuse only
repair reservations since an install shares the load's lifecycle gate and
aborts via its queued-load snapshot, a SidecarSwapInProgress raised before
teardown no longer clears the live model mirrors, and an export spawn abort
after teardown clears current_checkpoint so the page cannot claim a loaded
checkpoint with no worker.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Repair a present-but-incomplete latest sidecar from routing

The routing self-heal only fired when the pinned sidecar's transformers/
dir was missing. A sidecar that kept transformers/ but lost another pinned
package still routed models to the latest tier, and workers refuse
parent-only repairs, so every load failed until a manual reinstall. Routing
now validates the full pin (via _venv_dir_is_valid) and repairs any
incomplete sidecar under the same swap reservation and 5-minute backoff.

* Treat an unrepaired latest sidecar as unavailable in routing

When the pinned sidecar is incomplete and the lazy repair fails (offline,
pip failure, workers active) or is inside the backoff window, routing
returned the source dir anyway, sending models to a tier whose worker
activation is known to fail. Return None instead so models an older tier
supports keep loading there until a repair succeeds, matching the behavior
when the sidecar dir is missing entirely.

* Harden sidecar swap and repair against crash, survivor, and 16-bit paths

Reclaim a swap lock as soon as its recorded owner PID is dead instead of
waiting out the two-hour cutoff, so a crash mid-install no longer wedges
/load, training, export, and repair for hours. A lock whose PID cannot be
read yet still uses the long cutoff so the create-before-write window is
never mistaken for dead.

Probe process liveness with OpenProcess on Windows: os.kill(pid, 0) there
is CTRL_C_EVENT (a real Ctrl+C via GenerateConsoleCtrlEvent), not a
harmless check, and psutil is not always present.

Return whether _shutdown_subprocess actually killed the worker and keep the
live handle when it survives terminate/kill (an uninterruptible CUDA
syscall can outlive SIGKILL). The pre-swap liveness guard now trusts that
result, so the destructive .venv_t5_latest rename cannot proceed while a
live worker still holds sidecar modules.

Recover a sidecar stranded at .old when a swap's activation rename and its
rollback both fail: reading the pin restores it when no swap holds the
reservation, so latest-tier models are not permanently broken.

Resolve the latest tier in the parent for export loads and for explicitly
16-bit training runs, not only 4-bit ones: tier resolution self-heals an
incomplete sidecar, and repairs are parent-only, so those paths could not
recover before. Sidecar integrity and quantization are independent.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Revert the parent-side latest-tier repair probe on training and export loads

The probe ran before the route freed VRAM, so a resident chat or export worker
made _workers_active_for_repair() refuse the parent-only repair; the route then
tore that worker down and spawned a child that also cannot repair, so an
incomplete sidecar still failed to load. Repairing correctly requires running the
repair between the worker teardown and the child spawn, decoupled from VRAM
sizing, which is a larger change tracked separately. Restore the prior behavior
so these paths match the reviewed form and do not partially attempt a repair that
cannot complete while workers are resident.

* Honor failed worker shutdowns on load and revalidate the cached latest mapping

The fresh-load paths spawned a new worker straight after _shutdown_subprocess
without checking its result, so a worker that outlived terminate/kill (a wedged
CUDA syscall) had its handle overwritten by the replacement while it still held
GPU memory, and is_worker_alive/the pre-swap guard could no longer see it. Both
the inference load and the export checkpoint load now abort when the old worker
did not exit, so the load can be retried once it does.

_config_model_types returned a cached latest mapping without re-checking the
sidecar, so a sidecar deleted or broken in-process after its first parse was
never re-validated: routing kept sending latest-only models to the stale latest
tier while activation failed. The cached latest mapping is now dropped and
re-resolved (self-healing) when the sidecar is no longer intact.

* Drop cached latest mapping when the pin is gone; keep 4-bit for custom-code fallback

_latest_sidecar_intact now returns False when the pin marker itself is gone, not
just when a pinned package is missing. Otherwise a cached latest mapping outlived
a deleted pin: _config_model_types kept returning it, so routing sent latest-only
models to a tier whose worker activation then failed (no pinned version) until
restart. It now drops the cache and re-resolves to no latest tier. The
_overlay_transformers_dir caller already gates on a present pin, so it is
unaffected.

validate_model forced 16-bit sizing whenever a PyPI upgrade was merely offered,
even for a model that can fall back to its own auto_map code. /load loads such a
model 4-bit without the install, and the install route refuses while training is
active, so 16-bit sizing here returned a VRAM 409 for the only viable 4-bit path.
The offered-upgrade flip is now gated on the absence of a custom-code fallback;
an already-active latest sidecar still always sizes 16-bit.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2026-07-15 05:25:26 -07:00

607 lines
24 KiB
Python

# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
"""Latest-transformers support check for brand-new model architectures.
When a model's ``model_type`` is absent from every installed transformers overlay
(base 4.57.x plus the .venv_t5_530/550/510 sidecars and, if provisioned, .venv_t5_latest),
Studio cannot load it today. This module answers, without authentication, code execution,
or trust_remote_code:
1. Does the LATEST transformers release on PyPI ship this ``model_type``?
2. Does transformers ``main`` on GitHub ship it (dev-only, not yet installable)?
Sources (all unauthenticated; raw.githubusercontent.com is not API rate-limited and
api.github.com is deliberately never used):
- https://pypi.org/pypi/transformers/json -> latest release version
- https://raw.githubusercontent.com/huggingface/transformers/{ref}/src/transformers/
models/auto/configuration_auto.py + auto_mappings.py -> CONFIG_MAPPING_NAMES
The fetched sources are parsed with the same AST extractor the static router uses
(:func:`utils.transformers_version._model_types_from_source`), so the remote answer is
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
``UNSLOTH_STUDIO_NO_LATEST_TRANSFORMERS=1`` make every check return None (current
behavior preserved).
The consented install path (:func:`install_latest_transformers`) provisions the
persistent ``.venv_t5_latest`` sidecar via
:func:`utils.transformers_version.ensure_latest_transformers_venv`.
"""
import json
import os
import threading
import time
from pathlib import Path
from loggers import get_logger
from utils.paths.storage_roots import studio_root as _studio_root
from utils.transformers_version import (
_env_offline,
_load_config_json,
_model_types_from_source,
_tier_from_config_mapping,
_config_model_types,
_NESTED_CONFIG_KEYS,
_TIER_RANK,
_model_types_from_config,
_TRANSFORMERS_510_MODEL_TYPES,
_TRANSFORMERS_530_MODEL_TYPES,
_TRANSFORMERS_550_MODEL_TYPES,
ensure_latest_transformers_venv,
latest_venv_pinned_version,
)
logger = get_logger(__name__)
_PYPI_JSON_URL = "https://pypi.org/pypi/transformers/json"
_RAW_URL = (
"https://raw.githubusercontent.com/huggingface/transformers/{ref}"
"/src/transformers/models/auto/{name}"
)
_AUTO_FILES = ("configuration_auto.py", "auto_mappings.py")
_FETCH_TIMEOUT_SECONDS = 5.0
_FETCH_RETRIES = 1
_CACHE_TTL_SECONDS = 24 * 60 * 60
_FAILURE_BACKOFF_SECONDS = 300
_CACHE_FILE_NAME = "transformers_latest_check.json"
_SNAPSHOT_SCHEMA = 1
# Snapshot: {"schema", "fetched_at", "pypi_version", "pypi_model_types", "main_model_types"}.
# Install-in-progress state lives in utils.transformers_version (the sidecar swap reservation).
_lock = threading.Lock()
_memory_snapshot: dict | None = None
_last_failure_at: float = 0.0
_is_fetching: bool = False
_TRUE_VALUES = {"1", "true", "yes", "on"}
def _disabled() -> bool:
"""True if the operator disabled the latest-transformers check entirely."""
return (
os.environ.get("UNSLOTH_STUDIO_NO_LATEST_TRANSFORMERS", "").strip().lower() in _TRUE_VALUES
)
def _cache_file() -> Path:
return _studio_root() / "cache" / _CACHE_FILE_NAME
# Sentinel for HTTP 404 (absent at ref), distinct from transient failures.
_FETCH_MISSING = "__unsloth_fetch_missing__"
def _fetch_text(url: str) -> str | None:
"""GET *url* with a bounded timeout and 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".
"""
import urllib.error
import urllib.request
for attempt in range(1 + _FETCH_RETRIES):
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")
except urllib.error.HTTPError as exc:
if exc.code == 404:
return _FETCH_MISSING
logger.debug("Fetch failed (attempt %d) for %s: %s", attempt + 1, url, exc)
except Exception as exc:
logger.debug("Fetch failed (attempt %d) for %s: %s", attempt + 1, url, exc)
return None
def _fetch_latest_pypi_version() -> str | None:
"""Latest transformers release version from PyPI's unauthenticated JSON API."""
body = _fetch_text(_PYPI_JSON_URL)
if body is None or body == _FETCH_MISSING:
return None
try:
version = json.loads(body).get("info", {}).get("version")
except Exception as exc:
logger.debug("Could not parse PyPI JSON: %s", exc)
return None
return version if isinstance(version, str) and version else None
def _fetch_remote_model_types(ref: str) -> frozenset[str] | None:
"""CONFIG_MAPPING_NAMES keys at *ref* (a release tag like ``v5.12.0`` or ``main``).
Fetches configuration_auto.py plus auto_mappings.py (the 5.10+ split) from
raw.githubusercontent.com and parses them with the shared AST extractor. A file
that 404s (auto_mappings.py on pre-5.10 tags) is skipped, but a transient fetch
or parse failure of EITHER file fails the whole lookup: most model types live in
auto_mappings.py on current releases, so a partial map cached for the TTL would
make /validate skip the upgrade prompt for architectures the release does ship.
An empty result is likewise a failure so it is never cached as "supports nothing".
"""
keys: set[str] = set()
fetched_any = False
for name in _AUTO_FILES:
source = _fetch_text(_RAW_URL.format(ref = ref, name = name))
if source is None:
return None
if source == _FETCH_MISSING:
continue
fetched_any = True
try:
keys |= _model_types_from_source(source)
except Exception as exc:
logger.debug("Could not parse %s at %s: %s", name, ref, exc)
return None
if not fetched_any or not keys:
return None
return frozenset(keys)
def _load_snapshot_file() -> dict | None:
"""Persisted snapshot from disk, or None (missing/corrupt/old schema)."""
try:
with open(_cache_file(), encoding = "utf-8") as f:
data = json.load(f)
except Exception:
return None
if not isinstance(data, dict) or data.get("schema") != _SNAPSHOT_SCHEMA:
return None
if not isinstance(data.get("fetched_at"), (int, float)):
return None
if not isinstance(data.get("pypi_version"), str):
return None
for key in ("pypi_model_types", "main_model_types"):
value = data.get(key)
if not isinstance(value, list) or not all(isinstance(v, str) for v in value):
return None
return data
def _save_snapshot_file(snapshot: dict) -> None:
"""Atomic best-effort write (tmp + os.replace, Windows-safe); failures only log."""
path = _cache_file()
tmp = path.with_name(path.name + ".tmp")
try:
path.parent.mkdir(parents = True, exist_ok = True)
tmp.write_text(json.dumps(snapshot), encoding = "utf-8")
os.replace(tmp, path)
except Exception as exc:
logger.debug("Could not persist %s: %s", path, exc)
try:
tmp.unlink(missing_ok = True)
except Exception:
pass
def _snapshot_is_fresh(snapshot: dict | None) -> bool:
return (
snapshot is not None
and (time.time() - float(snapshot.get("fetched_at", 0))) < _CACHE_TTL_SECONDS
)
def _refresh_snapshot() -> dict | None:
"""Fetch a fresh snapshot from PyPI + raw.githubusercontent.com; None on failure.
The PyPI version and its tagged mapping are required; the ``main`` mapping is
best-effort (recorded as an empty list plus ``main_checked=False`` when unavailable,
so a dev-only architecture is reported as "unknown" rather than "unsupported").
"""
version = _fetch_latest_pypi_version()
if version is None:
return None
pypi_types = _fetch_remote_model_types(f"v{version}")
if pypi_types is None:
return None
main_types = _fetch_remote_model_types("main")
return {
"schema": _SNAPSHOT_SCHEMA,
"fetched_at": time.time(),
"pypi_version": version,
"pypi_model_types": sorted(pypi_types),
"main_model_types": sorted(main_types) if main_types is not None else [],
"main_checked": main_types is not None,
}
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).
"""
global _memory_snapshot, _last_failure_at, _is_fetching
with _lock:
if _snapshot_is_fresh(_memory_snapshot):
return _memory_snapshot
disk = _load_snapshot_file()
if _snapshot_is_fresh(disk):
_memory_snapshot = disk
return disk
if _disabled() or _env_offline():
return None
if time.time() - _last_failure_at < _FAILURE_BACKOFF_SECONDS:
return None
if _is_fetching:
return None
_is_fetching = True
fresh = None
try:
fresh = _refresh_snapshot()
finally:
with _lock:
_is_fetching = False
if fresh is None:
_last_failure_at = time.time()
else:
_memory_snapshot = fresh
if fresh is None:
# A stale positive could offer a version PyPI no longer serves; be strict.
return None
_save_snapshot_file(fresh)
return fresh
def clear_caches() -> None:
"""Test helper: drop the in-memory snapshot, failure backoff, and busy flags."""
global _memory_snapshot, _last_failure_at, _is_fetching
with _lock:
_memory_snapshot = None
_last_failure_at = 0.0
_is_fetching = False
from utils.transformers_version import end_sidecar_swap
end_sidecar_swap()
def latest_transformers_supports(model_type: str) -> dict | None:
"""Whether the newest transformers (PyPI release and/or GitHub main) ships *model_type*.
Returns ``{"pypi_version": str, "supported_in_pypi": bool, "supported_in_main": bool}``
or None when the answer is unavailable (offline, kill switch, network failure) — the
caller must then fall through to current behavior. Cached (memory + JSON snapshot on
disk, ttl ~1 day) so repeated tier resolutions never re-fetch.
"""
if not isinstance(model_type, str) or not model_type:
return None
if _disabled() or _env_offline():
return None
snapshot = _get_snapshot()
if snapshot is None:
return None
return {
"pypi_version": snapshot["pypi_version"],
"supported_in_pypi": model_type in set(snapshot["pypi_model_types"]),
"supported_in_main": model_type in set(snapshot["main_model_types"]),
}
# model_types the hardcoded tier tables already route; never remote-check these.
def _hardcoded_model_types() -> frozenset[str]:
return frozenset(
_TRANSFORMERS_530_MODEL_TYPES
| _TRANSFORMERS_550_MODEL_TYPES
| _TRANSFORMERS_510_MODEL_TYPES
)
def check_upgrade_for_model(model_name: str, hf_token: str | None = None) -> dict | None:
"""Upgrade signal for *model_name*, or None when current routing already handles it.
The tier hook for the pre-load ``/validate`` path: fires ONLY when the model's
``model_type`` is absent from every installed overlay (and from the hardcoded tier
tables), i.e. exactly when today's load would fail with an unrecognized-architecture
error. Returns ``{"model_type", "pypi_version", "supported_in_pypi",
"supported_in_main"}`` when the newest transformers knows the type, else None.
Never raises; every network touch is bounded and cached. Offline or with the
``UNSLOTH_STUDIO_NO_LATEST_TRANSFORMERS`` kill switch it returns None immediately.
"""
try:
if _disabled() or _env_offline():
return None
cfg = _load_config_json(model_name, hf_token)
if not isinstance(cfg, dict):
return None
candidates = _model_types_from_config(cfg)
if not candidates:
return None
# Without a readable base mapping every type looks brand new; bail out.
if not _config_model_types("default"):
return None
hardcoded = _hardcoded_model_types()
missing = [
candidate
for candidate in candidates
if candidate not in hardcoded
and not any(candidate in _config_model_types(tier) for tier in _TIER_RANK)
]
if not missing:
return None
# Latest must load EVERY missing type (wrappers build nested sub-configs
# through CONFIG_MAPPING) or the load still fails.
supports = [latest_transformers_supports(candidate) for candidate in missing]
if any(
s is None or not (s["supported_in_pypi"] or s["supported_in_main"]) for s in supports
):
return None
# Offer the PyPI install only if the release ships every missing type; a
# main-only type in the mix surfaces as dev-only.
model_type = missing[0]
supported_in_pypi = all(s["supported_in_pypi"] for s in supports)
supported_in_main = all(s["supported_in_pypi"] or s["supported_in_main"] for s in supports)
logger.info(
"Model %s has model_type=%s unknown to every installed transformers "
"(latest PyPI %s: %s, main: %s)",
model_name,
model_type,
supports[0]["pypi_version"],
"supported" if supported_in_pypi else "unsupported",
"supported" if supported_in_main else "unsupported",
)
return {
"model_type": model_type,
"pypi_version": supports[0]["pypi_version"],
"supported_in_pypi": supported_in_pypi,
"supported_in_main": supported_in_main,
}
except Exception as exc:
logger.debug("Latest-transformers check failed for '%s': %s", model_name, exc)
return None
# --- Dependency compatibility preflight ------------------------------------------------------
# Sidecars install transformers --no-deps atop the base env. Before installing, compare
# requires_dist: unsatisfied shadowable deps become exact --target pins, anything else blocks.
# Safe to shadow inside the sidecar dir (pure wheels, no torch coupling).
_SHADOWABLE_DEPS = frozenset({"tokenizers", "safetensors"})
# Provided by the sidecar recipe; checked against its pin, not the base env.
_SIDECAR_PROVIDED = {"huggingface-hub": "1.8.0", "hf-xet": "1.4.2"}
# CLI-only; never imported at runtime in Studio's workers.
_IGNORED_DEPS = frozenset({"typer"})
def _canonical_dep_name(name: str) -> str:
return name.lower().replace("_", "-")
def _fetch_requires_dist(version: str) -> list[str] | None:
"""Core (marker-free, non-extra) requires_dist of transformers *version* from PyPI."""
body = _fetch_text(f"https://pypi.org/pypi/transformers/{version}/json")
if body is None or body == _FETCH_MISSING:
return None
try:
reqs = json.loads(body).get("info", {}).get("requires_dist")
except Exception:
return None
if not isinstance(reqs, list):
return None
return [r for r in reqs if isinstance(r, str)]
def _resolve_exact_version(name: str, specifier) -> str | None:
"""Newest PyPI release of *name* satisfying *specifier* (exact pin for the shadow)."""
body = _fetch_text(f"https://pypi.org/pypi/{name}/json")
if body is None or body == _FETCH_MISSING:
return None
try:
from packaging.version import InvalidVersion, Version
releases = json.loads(body).get("releases", {})
best = None
for candidate in releases:
try:
parsed = Version(candidate)
except InvalidVersion:
continue
if parsed.is_prerelease or not specifier.contains(candidate):
continue
if best is None or parsed > Version(best):
best = candidate
return best
except Exception as exc:
logger.debug("Could not resolve an exact %s version: %s", name, exc)
return None
def compat_plan(version: str) -> tuple[tuple[str, ...], list[str]]:
"""(extra exact pins to shadow-install, blocking requirement strings) for *version*.
Compares the release's core requires_dist against the running base env (the env the
workers overlay the sidecar onto). A requirement the base env satisfies needs nothing;
an unsatisfied shadowable dep becomes an exact pin inside the sidecar; any other
unsatisfied requirement is a blocker. An unavailable requires_dist BLOCKS the
install: proceeding unverified could pin a sidecar whose imports then crash the
workers, and the caller just reached PyPI for the version check so a retry is cheap.
"""
reqs = _fetch_requires_dist(version)
if reqs is None:
return (), ["dependency metadata for this release (could not be fetched from PyPI; retry)"]
try:
from importlib.metadata import PackageNotFoundError
from importlib.metadata import version as _installed_version
from packaging.requirements import InvalidRequirement, Requirement
except Exception:
return (), []
extras: list[str] = []
blockers: list[str] = []
for raw in reqs:
try:
req = Requirement(raw)
except InvalidRequirement:
continue
if req.extras or (req.marker is not None and not req.marker.evaluate()):
continue
name = _canonical_dep_name(req.name)
if name in _IGNORED_DEPS:
continue
if name in _SIDECAR_PROVIDED:
if not req.specifier.contains(_SIDECAR_PROVIDED[name], prereleases = True):
blockers.append(raw)
continue
try:
installed = _installed_version(req.name)
except PackageNotFoundError:
installed = None
if installed is not None and req.specifier.contains(installed, prereleases = True):
continue
if name in _SHADOWABLE_DEPS:
exact = _resolve_exact_version(name, req.specifier)
if exact is None:
blockers.append(raw)
else:
extras.append(f"{name}=={exact}")
else:
blockers.append(raw)
return tuple(extras), blockers
def is_install_in_progress() -> bool:
"""True while a latest-transformers install or lazy repair holds the sidecar swap
reservation. Training and export starts check this so a fresh worker never
activates the sidecar mid-swap."""
from utils.transformers_version import sidecar_swap_in_progress
return sidecar_swap_in_progress()
def install_latest_transformers(
version: str,
before_swap = None,
reserved: bool = False,
) -> dict:
"""Consented install of the latest transformers sidecar; returns a structured result.
Guards: the requested *version* must match the current PyPI latest from the (cached)
snapshot, so a client cannot pin an arbitrary package version through this endpoint.
On success ``.venv_t5_latest`` is provisioned and pinned; routing then resolves the
new tier automatically on this and every future start. *before_swap* is forwarded
to the stage-and-swap: it runs only after the staged install succeeded, right
before the live sidecar is replaced. *reserved* means the caller already holds the
sidecar swap reservation (the install route takes it before waiting on the
inference lifecycle gate, so worker starts see it for the whole window).
"""
from utils.transformers_version import end_sidecar_swap, try_begin_sidecar_swap
if not reserved and not try_begin_sidecar_swap():
return {
"success": False,
"version": version,
"message": "A transformers installation is already in progress.",
}
try:
return _install_latest_transformers_locked(version, before_swap = before_swap)
finally:
if not reserved:
end_sidecar_swap()
def _install_latest_transformers_locked(version: str, before_swap = None) -> dict:
"""Body of install_latest_transformers; runs with the in-progress flag held."""
if _disabled():
return {
"success": False,
"version": version,
"message": "Latest-transformers installs are disabled "
"(UNSLOTH_STUDIO_NO_LATEST_TRANSFORMERS).",
}
if _env_offline():
return {
"success": False,
"version": version,
"message": "Cannot install: Studio is in offline mode.",
}
# Re-verify against a LIVE snapshot (a release may land inside the cache TTL);
# fall back to the cached one on fetch failure.
global _memory_snapshot
snapshot = _refresh_snapshot()
if snapshot is not None:
with _lock:
_memory_snapshot = snapshot
_save_snapshot_file(snapshot)
else:
snapshot = _get_snapshot()
if snapshot is None:
return {
"success": False,
"version": version,
"message": "Could not verify the latest transformers release on PyPI.",
}
if version != snapshot["pypi_version"]:
return {
"success": False,
"version": version,
"message": f"Requested version {version!r} is not the latest transformers "
f"release ({snapshot['pypi_version']}).",
# Lets the consent dialog retry with the release that superseded the
# one /validate saw, instead of re-sending the stale version forever.
"latest_version": snapshot["pypi_version"],
}
extra_packages, blockers = compat_plan(version)
if blockers:
return {
"success": False,
"version": version,
"message": "Cannot install transformers "
f"{version}: this environment does not satisfy {', '.join(blockers)}. "
"A Studio update is required first.",
}
if not ensure_latest_transformers_venv(version, extra_packages, before_swap = before_swap):
return {
"success": False,
"version": version,
"message": f"Installing transformers {version} failed; see the Studio logs.",
}
_invalidate_capability_caches()
return {
"success": True,
"version": version,
"message": f"Installed transformers {version} into the latest sidecar "
f"(pinned: {latest_venv_pinned_version()}).",
}
def _invalidate_capability_caches():
"""Drop caches computed before the new sidecar existed: tier probes and the
latest tier's model_type mapping (stale on upgrade) plus vision detection
(a raw-heuristic False may now defer to the sidecar AutoConfig probe)."""
try:
from utils import transformers_version as tv
tv._probe_tier_cache.clear()
tv._config_mapping_cache.pop("latest", None)
except Exception:
pass
try:
from utils.models import model_config as mc
mc._vision_detection_cache.clear()
except Exception:
pass