unsloth/studio/backend/tests/test_vision_cache.py
Daniel Han 1396c01253
Fix offline checkpoint load/export: "tokenizer is weirdly not loaded" (#6554)
* Fix offline checkpoint load/export failing with "tokenizer is weirdly not loaded"

Loading a fine-tuned checkpoint with no internet (e.g. a Studio export) crashed
with "Unsloth: The tokenizer is weirdly not loaded? Please check if there is one."

For a LoRA adapter the loader reassigns model_name to the base model repo id and
only keeps the local checkpoint dir as tokenizer_name when it contains
tokenizer_config.json, tokenizer.json AND special_tokens_map.json. Modern
tokenizers (e.g. Gemma) store special tokens inside tokenizer_config.json and
omit special_tokens_map.json, so tokenizer_name fell back to the base repo id.
The tokenizer/processor loads in vision.py then hit the Hub with no
local_files_only, so with no network they failed (AutoProcessor) or hung for
minutes (AutoTokenizer) even though every file was already cached.

loader.py: keep the local checkpoint dir as tokenizer_name when it has a
tokenizer config plus the actual tokenizer files (tokenizer.json / tokenizer.model
/ vocab files); special_tokens_map.json is no longer required.

vision.py: compute an effective local_files_only (explicit kwarg plus the
HF_HUB_OFFLINE / TRANSFORMERS_OFFLINE env vars, mirroring loader.py and
diffusion.py) and thread it through every AutoConfig, AutoProcessor,
AutoTokenizer and the manual VLM processor fallback, including the
hf_hub_download in that fallback (which now prefers a local file). When a load
fails and no offline env var is set, retry against the local cache. The retry
forces HF offline mode because local_files_only alone does not stop
AutoProcessor / AutoTokenizer from issuing a /api/models request during class
resolution. The final error now explains the offline/cache cause instead of the
misleading "weirdly not loaded" message.

studio export: probe Hub reachability once per checkpoint load and pass
local_files_only when offline so exports use the local checkpoint dir / cache
instead of hanging or crashing with no internet.

Online behavior is unchanged: the new flags default to off and the retry only
runs after a network related failure.

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

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

* Address review: safer offline forcing, cached fallback config, proxy-aware probe

Follow-up to the offline checkpoint load fix, addressing review feedback:

- vision.py: only flip the process-wide HF offline flag when offline is actually
  requested (local_files_only / env) or after a real network failure, never
  pre-emptively while we might be online. The flip is now guarded by a lock +
  depth counter so nested or concurrent windows restore the flag correctly
  (no stale value).
- vision.py: guard the get_auto_processor fallback so a network error there
  returns None and the local-cache retry still runs instead of escaping.
- vision.py: in the manual VLM processor fallback, read tokenizer_config.json
  via hf_hub_download(..., local_files_only=...) so a cached repo-id config is
  still resolved offline and the model-specific image/video tokens are restored.
- studio export: make the reachability probe proxy aware (probe the configured
  HTTP(S) proxy egress, honour NO_PROXY, use the endpoint port) so a proxy-only
  setup is not wrongly marked offline; allow UNSLOTH_OFFLINE_PROBE=0 to disable.
- studio export: run the audio/vision type-detection probes inside the
  forced-offline window when offline, so their config/tokenizer reads hit the
  local cache instead of waiting out connection timeouts.

Online behavior remains unchanged.

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

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

* Address review: gate offline retry, safer tokenizer_name pop, skip audio net probe offline

- vision.py: only force the process-wide HF offline flag on the tokenizer
  retry when offline was requested or the captured primary error is actually
  network related, so a permanent tokenizer error no longer toggles global
  offline mode for other concurrent loads.
- loader.py: always pop tokenizer_name out of kwargs and let a caller-supplied
  value win, avoiding a "multiple values for keyword argument 'tokenizer_name'"
  TypeError when it is also passed explicitly downstream.
- model_config.py / export.py: add local_files_only to detect_audio_type so the
  raw requests.get tokenizer_config fetch is skipped offline (it ignores the HF
  offline flag), and pass it from the export probe.

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

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

* Address review: classify LocalEntryNotFoundError as offline-related

huggingface_hub's LocalEntryNotFoundError subclasses FileNotFoundError, so the
"not isinstance(cur, FileNotFoundError)" guard in _is_offline_related_error was
swallowing it and it could never be recognised as offline, despite being listed
in the network error types. It means "not in cache and the Hub is unreachable",
which is genuinely offline. Capture the class into an isinstance-checkable tuple
(empty, hence a no-op, if the import is unavailable) and exclude it from the
FileNotFoundError guard, so a real offline failure now triggers the local-cache
retry while a plain missing-file error still propagates.

* Address review: require merges.txt for BPE, status-gate HTTP errors, isolate local-only audio cache

- loader.py: a local dir with vocab.json but no merges.txt (and no tokenizer.json)
  is not a loadable BPE tokenizer, so do not treat it as self-sufficient; require
  merges.txt alongside vocab.json in both gate blocks, otherwise fall back to the
  base model tokenizer as before.
- vision.py: _is_offline_related_error no longer buckets every HfHubHTTPError /
  requests HTTPError as offline. HTTP errors are judged by status code: only a
  transient 5xx triggers the forced local-cache retry, while 401/403 (auth/gated)
  and 404 (missing) propagate as the real error instead of being masked. Hard
  signals (connection/timeout/OfflineModeIsEnabled/LocalEntryNotFoundError) still
  classify as offline.
- model_config.py: include local_files_only in the audio-detection cache key so a
  local-only (offline) negative result cannot be reused by a later online probe,
  which would otherwise route an audio model through the text loader until restart.

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

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

* Address re-review: fix studio test stubs, force offline env in probe window, drop redundant retry

- studio/backend/tests/test_vision_cache.py: the three _detect_audio_from_tokenizer
  stubs were called with the new local_files_only kwarg and raised TypeError, failing
  Backend CI. Add local_files_only to the stub signatures and add a test that a
  local-only negative does not poison a later online audio probe.
- export.py: the type-detection probe window now also sets HF_HUB_OFFLINE /
  TRANSFORMERS_OFFLINE env vars (saved/restored), not just the in-process flag.
  transformers_version._load_config_json / _check_tokenizer_config_needs_v5 gate
  their urllib fetches on the env vars, and is_vision_model may spawn a subprocess
  that inherits os.environ but not the in-process flag; without the env vars a
  probe-detected offline export could still block on a network timeout.
- vision.py: only retry the processor load when the first attempt was online and
  failed with a network error. When local_files_only was already requested the first
  attempt was forced offline, so the previous retry just repeated identical failing
  work before the last-resort path.
- model_config.py: correct the _audio_detection_cache type annotation to the 3-tuple
  key (name, token_fingerprint, local_files_only).

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

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

* Address review: thread-safe probe-offline env window, clear error for local dir without config

- export.py: guard the HF_HUB_OFFLINE / TRANSFORMERS_OFFLINE mutation in
  _force_offline_probe_window with a lock + depth counter (mirrors _force_hf_offline),
  so concurrent / nested export probes only flip on first entry and restore on last
  exit. This prevents overlapping export requests from permanently poisoning those
  env vars or restoring a stale value.
- vision.py: in the VLM processor fallback, when tokenizer_name is a local directory,
  read its tokenizer_config.json directly and raise a clear FileNotFoundError if it is
  absent, instead of handing the local path to hf_hub_download (which would treat it as
  a repo id and raise a confusing HFValidationError / RepositoryNotFoundError).
  hf_hub_download is now only used for actual repo ids.

* Address review: classify raw socket.gaierror DNS failures as offline

Add the platform-specific getaddrinfo / DNS-resolution wording to the offline
detection list in _is_offline_related_error so a bare socket.gaierror (an OSError
subclass) is recovered from the local cache: "Name or service not known" and
"Temporary failure in name resolution" (Linux) and "nodename nor servname
provided" (macOS). Genuine non-network OSErrors (disk full, permission denied)
and plain FileNotFoundError still propagate.

* Address review: retry degraded VLM offline, force offline for text export + patch-tokenizer fallback

- vision.py: a degraded VLM processor (text-only, no image_processor) whose manual
  fallback fails offline used to be kept, so image inputs broke even with cached
  files. _construct_vlm_processor_fallback now returns its failure error;
  _acquire_processor surfaces it, and the caller retries forced-offline when the
  result is None OR a degraded VLM and the failure was network related, keeping the
  original result if the retry is not strictly better (never regress). The retry is
  still gated on an online first attempt + offline-related error so a permanent
  error never flips the global offline flag.
- vision.py: wrap the patch_tokenizer except-branch AutoTokenizer.from_pretrained in
  the same forced-offline-on-network-error pattern as the primary / last-resort
  loads, so an offline export where patch_tokenizer raises does not hang or fail.
- export.py: force HF offline around the two FastLanguageModel loads (text and SNAC)
  when the probe detected offline. Their text tokenizer path (load_correct_tokenizer
  -> AutoTokenizer) does not forward local_files_only, so without this a text export
  could still contact the Hub. Added a small _offline_window_if helper reused by the
  probe and load windows.

* Consolidate offline loading into one entry-point decision

Decide offline once per entry point instead of at every HF call site. The
prior approach threaded local_files_only into ~15 scattered config / tokenizer
/ processor / weight loads, each wrapped in its own try-online, classify-error,
retry-forced-offline dance, which is what kept surfacing "another call site you
missed", "another error shape misclassified", and global-flag thread-safety in
review.

FastLanguageModel / FastModel / FastBaseModel.from_pretrained now share an
@_offline_aware_load decorator: when offline (explicit local_files_only kwarg or
HF_HUB_OFFLINE / TRANSFORMERS_OFFLINE env) it sets local_files_only and runs the
whole load inside one _force_hf_offline() window so every nested HF call inherits
it; when online it runs normally and, only if the load fails with a genuinely
network-related error, retries once forced-offline. The online path is unchanged
(no probe added) and 401 / 403 / 404 / permanent errors still propagate.

Centralise the offline helpers in loader_utils.py as the single source of truth
(shared by loader.py, re-exported from vision.py, and reused by the Studio
exporter):
- _force_hf_offline now sets the HF_HUB_OFFLINE / TRANSFORMERS_OFFLINE env vars
  AND the in-process huggingface_hub / transformers flags, refcounted under one
  lock so nested / concurrent windows restore correctly. Setting the env vars
  covers env-gated urllib probes and spawned subprocesses too.
- _get_effective_local_files_only, _is_offline_related_error (unchanged
  classifier, retains the 5xx-vs-4xx, LocalEntryNotFound and gaierror handling),
  _offline_aware_load, and _resolve_checkpoint_tokenizer_name.

loader.py: wrap both entry points; drop the two duplicated env-var fallback
blocks and the two byte-identical local-tokenizer-gate blocks (now
_resolve_checkpoint_tokenizer_name).

vision.py: drop the per-site force_offline params and the three retry gates
(processor, patch_tokenizer fallback, last-resort). They now just surface the
underlying error so the single entry-point safety net retries forced-offline. A
network fallback error now takes precedence over a permanent primary error so the
offline retry still fires when the manual VLM fallback needs cached repo files.

studio/backend export.py: reuse the unified core _force_hf_offline (env + flags)
and drop the duplicate probe-window primitive; the snac / text branches no longer
need their own window. model_config.py: also gate the raw requests.get audio
fallback on the HF offline env vars so it is covered even without the kwarg.

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

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

* Address 10-reviewer P1 findings: vision cache split, PEFT offline, retry OOM

Split the Studio vision-detection cache by local_files_only, mirroring the audio
cache fix. is_vision_model / _is_vision_model_uncached / _raw_config_has_vision_config
/ load_model_config now thread local_files_only, the cache key includes it, and the
exporter passes it. Offline detection also skips the transformers-5 network
subprocess and stays on the local cache, so an offline negative can no longer be
keyed under the online entry and poison a later online probe. Adds a regression
test mirroring the audio poison test.

Forward local_files_only to both PeftModel.from_pretrained adapter-attach sites in
loader.py so a cached remote LoRA adapter resolves from the local cache under
explicit local-only / offline loads (defence-in-depth alongside the forced-offline
window).

_offline_aware_load: run the forced-offline retry OUTSIDE the except block and
collect + empty the device cache first. An except-scoped exception keeps its
__traceback__, which pins the failed attempt's frame locals (a partially loaded
model) until the block exits; loading the model again while that copy is still
alive could OOM a large VLM. Letting the except block close drops the traceback so
the partial load is freed before the retry reallocates.

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

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

* Address Codex review: env-offline cache key + rebuild HF sessions in offline window

Key the Studio audio and vision detection caches on the EFFECTIVE offline state
(local_files_only OR the HF offline env vars), not just the kwarg. detect_audio_type
and is_vision_model both skip the remote fetch / network subprocess when
HF_HUB_OFFLINE / TRANSFORMERS_OFFLINE is set even with the default
local_files_only=False, so the result reflects offline; storing it under the online
(False) key let an env-offline negative poison a later online lookup once the env var
was cleared. Both now compute effective_offline once and use it for the cache key and
the downstream call. Adds a regression test for the env-offline dimension.

_force_hf_offline now rebuilds huggingface_hub's cached sessions on enter and exit
(best-effort _reset_hf_sessions). On hub 0.x the offline adapter is baked into the
per-thread requests.Session at creation, so flipping the constant alone leaves an
already-cached online session able to hit the network inside the window (and an
offline one stuck offline after restore); resetting forces the next get_session() to
match the current flag. On hub 1.x offline is checked dynamically per request, so
reset_sessions does not exist and the helper is a safe no-op.

The third review point (release the failed load before retrying) was already fixed in
af0f58a: the forced-offline retry now runs outside the except block and frees the
device cache first, so the failed attempt's traceback-pinned partial model is
released before the retry reallocates.

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

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

* Align Studio _env_offline parsing with the canonical offline helper

model_config._env_offline gates the raw requests.get tokenizer-config fallback in
detect_audio_type and the audio/vision detection cache keys, but it only accepted
unstripped "1"/"true"/"yes". unsloth's offline helpers (loader_utils._env_says_offline
and the from_pretrained env fallback) accept the canonical set {1,true,yes,on} after
strip + lowercase, so HF_HUB_OFFLINE=on or HF_HUB_OFFLINE=" 1 " was treated as offline
by the loaders but online here, leaving the raw network fetch reachable while
"offline". Use the same strip + lowercase {1,true,yes,on} set. Adds parsing tests.

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

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

* Fix lint: drop dead offline-helper re-exports from vision.py

The import-hoist verifier (scripts/verify_import_hoist.py) flagged vision.py's
re-export block as HOISTED-IMPORT-UNUSED blockers: it imported eight offline
helpers from loader_utils but only used three internally
(_get_effective_local_files_only, _is_offline_related_error, _offline_aware_load).
The other five were imported purely to preserve `from unsloth.models.vision import
X`, but nothing imports four of them from vision, and loader.py already imports
_resolve_checkpoint_tokenizer_name straight from loader_utils.

Import only the three names vision.py actually uses, and point the Studio exporter
at the canonical source (from unsloth.models.loader_utils import _force_hf_offline)
instead of re-exporting it through vision. loader_utils stays the single source of
truth; no behaviour change.

* Address Opus review: chain probe errors, unify env-offline, status-less HTTP

Chain the original AutoConfig/PeftConfig probe exception into the combined
RuntimeError in both FastLanguageModel.from_pretrained and FastModel.from_pretrained
(`raise RuntimeError(combined_error) from (autoconfig_exc or peft_exc)`). The probes
caught every Exception and stringified it, so the re-raised RuntimeError had no
__cause__/__context__ and _is_offline_related_error could not classify it -- the
network-down-but-cached auto-retry never fired for these entry points. With the
cause chained, the decorator sees a ConnectionError/LocalEntryNotFoundError/5xx and
retries forced-offline from cache; a permanent cause (404 / bad config) is still not
offline-classified and propagates without a wasted retry.

Unify the third offline-env parser: studio/backend/utils/transformers_version._env_offline
now uses the canonical {1,true,yes,on} + strip + lowercase set (matching
loader_utils._env_says_offline and model_config._env_offline), so HF_HUB_OFFLINE=on
or " 1 " no longer leaks the direct urllib metadata fetches to the network.

_is_offline_related_error: a status-less HTTP error (no response / unparseable code)
now falls back to the network-wording check instead of being dropped, so a transient
HTTP failure with clear "couldn't connect" wording is treated as offline. HTTP errors
with a real status code still decide by code (4xx propagates, 5xx is offline).

* Condense offline-loading code comments, drop dead helper, dedupe import for PR #6554

* Add unit tests for offline-loading helpers for PR #6554

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

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

* Guard load cleanup with try/finally and add retry-contract tests for PR #6554

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

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

* Add gc.collect retry-step test for PR #6554

* Tighten offline-loading comments and docstrings for PR #6554

* Raise the both-config-failed error before model-type lookup so offline retry fires for PR #6554

* Prefer offline cause for retry and bound export reachability probe for PR #6554

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

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

* Skip remote mapper while offline, harden text-load cleanup, and stop stacked offline retries for PR #6554

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

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

* Surface VLM fallback offline errors, probe offline before export version activation, and restore progress bars across retries for PR #6554

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

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

* Restore offline env after export version activation so the persistent worker re-decides per load for PR #6554

* Classify socket.gaierror and urllib URLError as offline by type for PR #6554

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

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

* Probe offline around export load preflights and never offline-retry TLS failures for PR #6554

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

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

* Force in-process offline for export preflights, verify proxy egress in probe, and skip caching offline version negatives for PR #6554

* Snapshot offline constants before forcing env and require local processor files for VLM checkpoints for PR #6554

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

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

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2026-06-25 23:16:53 -07:00

767 lines
32 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
"""Tests for is_vision_model() caching behaviour.
``_vision_detection_cache`` mirrors the ``_audio_detection_cache``
pattern used by ``detect_audio_type()``. These tests verify:
* Repeated calls for the same model hit the cache.
* Different models each trigger their own detection.
* Both True and False results are cached.
* The subprocess path (transformers 5.x models) is cached.
* Exceptions that fall back to False are cached.
"""
import sys
import types as _types
from pathlib import Path
from unittest.mock import patch, MagicMock
import pytest
# sys.path + logger stub — same pattern as the rest of the test suite
_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
if _BACKEND_DIR not in sys.path:
sys.path.insert(0, _BACKEND_DIR)
_loggers_stub = _types.ModuleType("loggers")
_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)
sys.modules.setdefault("loggers", _loggers_stub)
from utils.models.model_config import (
ModelConfig,
is_vision_model,
_is_vision_model_uncached,
_vision_detection_cache,
)
# Helpers
@pytest.fixture(autouse = True)
def _clear_vision_cache(tmp_path, monkeypatch):
"""Ensure every test starts with a fresh cache, from an empty working dir.
``is_vision_model`` calls ``is_local_path`` first: any relative model id that
happens to exist on disk (``Path(name).exists()``) is treated as a local
model, short-circuiting before the mocked detection internals run. The CI cwd
(``studio/backend``) and the HF cache can contain dirs whose names collide
with the synthetic remote ids used here (``org/my-vlm``, ``model-a``,
``broken/model`` ...), which made these tests fail with "called 0 times".
Running each test from a fresh empty ``tmp_path`` removes that collision
while leaving the real ``is_local_path`` logic intact (the local-GGUF tests
pass absolute ``tmp_path`` paths, unaffected by cwd).
"""
monkeypatch.chdir(tmp_path)
_vision_detection_cache.clear()
yield
_vision_detection_cache.clear()
# Cache hit / miss tests
class TestVisionCacheHitMiss:
"""Verify the cache prevents redundant detection calls."""
@patch("utils.models.model_config._is_vision_model_uncached", return_value = True)
def test_second_call_uses_cache(self, mock_uncached):
"""Two calls for the same model invoke the uncached fn once."""
assert is_vision_model("org/my-vlm") is True
assert is_vision_model("org/my-vlm") is True
mock_uncached.assert_called_once_with("org/my-vlm", None, local_files_only = False)
@patch("utils.models.model_config._is_vision_model_uncached", return_value = False)
def test_different_models_each_detected(self, mock_uncached):
"""Different model names should each trigger detection."""
is_vision_model("model-a")
is_vision_model("model-b")
assert mock_uncached.call_count == 2
@patch("utils.models.model_config._is_vision_model_uncached", return_value = True)
def test_cache_returns_correct_value(self, mock_uncached):
"""The cached value must match what _is_vision_model_uncached returned."""
first = is_vision_model("org/vlm")
second = is_vision_model("org/vlm")
assert first is True
assert second is True
class TestVisionCacheStoresFalse:
"""Non-VLM results (False) must also be cached to avoid re-detection."""
@patch("utils.models.model_config._is_vision_model_uncached", return_value = False)
def test_false_result_cached(self, mock_uncached):
assert is_vision_model("org/text-only") is False
assert is_vision_model("org/text-only") is False
mock_uncached.assert_called_once()
assert _vision_detection_cache[("org/text-only", None, False)] is False
# Subprocess path (transformers 5.x) caching
class TestVisionCacheSubprocessPath:
"""transformers 5.x models go through _is_vision_model_subprocess.
The cache should spawn the subprocess at most once per model per
process."""
@patch("utils.models.model_config._raw_config_has_vision_config", return_value = None)
@patch("utils.models.model_config._is_vision_model_subprocess", return_value = True)
@patch("utils.transformers_version.needs_transformers_5", return_value = True)
def test_subprocess_called_once_with_cache(self, mock_needs_t5, mock_subprocess, mock_raw):
"""When the raw-config reader is inconclusive (None), the transformers
5.x subprocess fires only on the first call; the second is cached."""
# First call: raw None -> subprocess
assert is_vision_model("unsloth/Qwen3.5-2B") is True
# Second call: cache hit, no subprocess
assert is_vision_model("unsloth/Qwen3.5-2B") is True
mock_subprocess.assert_called_once()
assert _vision_detection_cache[("unsloth/Qwen3.5-2B", None, False)] is True
@patch("utils.models.model_config._raw_config_has_vision_config", return_value = True)
@patch("utils.models.model_config._is_vision_model_subprocess", return_value = None)
@patch("utils.transformers_version.needs_transformers_5", return_value = True)
def test_raw_config_primary_skips_subprocess(
self, mock_needs_t5, mock_subprocess, mock_raw_config
):
# The raw config.json read is the primary path; a definitive answer there never
# reaches the transformers-5.x subprocess or needs_transformers_5 routing.
assert is_vision_model("unsloth/gemma-4-E4B-it") is True
assert is_vision_model("unsloth/gemma-4-E4B-it") is True
mock_raw_config.assert_called_once_with(
"unsloth/gemma-4-E4B-it", hf_token = None, local_files_only = False
)
mock_subprocess.assert_not_called()
# ---------------------------------------------------------------------------
# Local GGUF capability path
# ---------------------------------------------------------------------------
class TestLocalGgufVisionDetection:
@patch(
"utils.models.model_config._is_vision_model_subprocess",
side_effect = AssertionError("GGUF must not use Transformers vision detection"),
)
def test_qwen36_gguf_with_mmproj_skips_transformers(self, mock_subprocess, tmp_path):
model = tmp_path / "Qwen3.6-27B-UD-Q4_K_XL-MTP.gguf"
model.write_bytes(b"")
(tmp_path / "mmproj-F32.gguf").write_bytes(b"")
assert is_vision_model(str(model)) is True
mock_subprocess.assert_not_called()
@patch(
"utils.models.model_config._is_vision_model_subprocess",
side_effect = AssertionError("GGUF must not use Transformers vision detection"),
)
def test_direct_gguf_in_variant_subdir_finds_snapshot_mmproj(self, mock_subprocess, tmp_path):
variant_dir = tmp_path / "BF16"
variant_dir.mkdir()
model = variant_dir / "Qwen3.6-27B-UD-Q4_K_XL-MTP.gguf"
model.write_bytes(b"")
(tmp_path / "mmproj-F32.gguf").write_bytes(b"")
assert is_vision_model(str(model)) is True
mock_subprocess.assert_not_called()
@patch(
"utils.models.model_config._is_vision_model_subprocess",
side_effect = AssertionError("GGUF must not use Transformers vision detection"),
)
def test_qwen36_gguf_without_mmproj_skips_transformers(self, mock_subprocess, tmp_path):
model = tmp_path / "Qwen3.6-27B-UD-Q4_K_XL-MTP.gguf"
model.write_bytes(b"")
assert is_vision_model(str(model)) is False
mock_subprocess.assert_not_called()
def test_local_gguf_check_observes_mmproj_added_later(self, tmp_path):
model = tmp_path / "Qwen3.6-27B-UD-Q4_K_XL-MTP.gguf"
model.write_bytes(b"")
assert is_vision_model(str(model)) is False
(tmp_path / "mmproj-F32.gguf").write_bytes(b"")
assert is_vision_model(str(model)) is True
@patch(
"utils.models.model_config._is_vision_model_subprocess",
side_effect = AssertionError("GGUF must not use Transformers vision detection"),
)
def test_ui_selection_returns_local_gguf_config(self, mock_subprocess, tmp_path):
model = tmp_path / "Qwen3.6-27B-UD-Q4_K_XL-MTP.gguf"
model.write_bytes(b"")
mmproj = tmp_path / "mmproj-F32.gguf"
mmproj.write_bytes(b"")
config = ModelConfig.from_ui_selection(str(model), None)
assert config is not None
assert config.is_gguf is True
assert config.is_vision is True
assert config.gguf_mmproj_file == str(mmproj.resolve())
mock_subprocess.assert_not_called()
@patch(
"utils.models.model_config._is_vision_model_subprocess",
side_effect = AssertionError("GGUF must not use Transformers vision detection"),
)
def test_ui_selection_direct_gguf_in_variant_subdir_keeps_mmproj(
self, mock_subprocess, tmp_path
):
variant_dir = tmp_path / "BF16"
variant_dir.mkdir()
model = variant_dir / "Qwen3.6-27B-UD-Q4_K_XL-MTP.gguf"
model.write_bytes(b"")
mmproj = tmp_path / "mmproj-F32.gguf"
mmproj.write_bytes(b"")
config = ModelConfig.from_ui_selection(str(model), None)
assert config is not None
assert config.is_gguf is True
assert config.is_vision is True
assert config.gguf_mmproj_file == str(mmproj.resolve())
mock_subprocess.assert_not_called()
# ---------------------------------------------------------------------------
# Exception handling — cache the False fallback
class TestVisionCacheOnException:
"""On exception, _is_vision_model_uncached distinguishes permanent
failures (cached as False) from transient ones (returned as None,
not cached, so the next call retries). Verify both contracts."""
@patch(
"utils.models.model_config.load_model_config",
side_effect = ValueError("bad config"),
)
@patch("utils.transformers_version.needs_transformers_5", return_value = False)
def test_permanent_exception_result_cached(self, mock_needs_t5, mock_load_config):
"""A permanent failure (ValueError / RepositoryNotFoundError /
GatedRepoError / JSONDecodeError) is caught, returns False, and
that False is cached so subsequent calls don't retry. ValueError
stands in as the simplest cacheable exception type."""
# First call raises -> False; second is a cache hit.
assert is_vision_model("broken/model") is False
assert is_vision_model("broken/model") is False
mock_load_config.assert_called_once()
@patch(
"utils.models.model_config.load_model_config",
side_effect = OSError("network down"),
)
@patch("utils.transformers_version.needs_transformers_5", return_value = False)
def test_transient_exception_not_cached(self, mock_needs_t5, mock_load_config):
"""A transient failure (OSError, timeouts) returns None from
_is_vision_model_uncached, surfaces as False, and is NOT cached
so the next call retries."""
# First call: OSError -> False, not cached; second call retries.
assert is_vision_model("broken/model") is False
assert is_vision_model("broken/model") is False
assert mock_load_config.call_count == 2
# Direct detection path (non-transformers-5 models) caching
class TestVisionCacheDirectPath:
"""Models that do NOT need transformers 5.x detect via
load_model_config directly. The cache must work the same way."""
@patch("utils.models.model_config._raw_config_has_vision_config", return_value = None)
@patch("utils.transformers_version.needs_transformers_5", return_value = False)
@patch("utils.models.model_config.load_model_config")
def test_direct_vlm_detection_cached(self, mock_load_config, mock_needs_t5, mock_raw):
"""A standard VLM detected via architecture suffix should be cached."""
cfg = MagicMock(spec = []) # strict: only explicitly set attrs exist
cfg.model_type = "gemma3"
cfg.architectures = ["Gemma3ForConditionalGeneration"]
mock_load_config.return_value = cfg
assert is_vision_model("google/gemma-3-4b-it") is True
assert is_vision_model("google/gemma-3-4b-it") is True
# load_model_config should only be called once
mock_load_config.assert_called_once()
@patch("utils.models.model_config._raw_config_has_vision_config", return_value = None)
@patch("utils.transformers_version.needs_transformers_5", return_value = False)
@patch("utils.models.model_config.load_model_config")
def test_direct_non_vlm_detection_cached(self, mock_load_config, mock_needs_t5, mock_raw):
"""A standard text model (no VLM indicators) should cache False."""
cfg = MagicMock(spec = []) # spec=[] means no attributes at all
cfg.model_type = "llama"
cfg.architectures = ["LlamaForCausalLM"]
mock_load_config.return_value = cfg
# No VLM suffix, no vision_config, etc.
assert is_vision_model("meta-llama/Llama-3-8B") is False
assert is_vision_model("meta-llama/Llama-3-8B") is False
mock_load_config.assert_called_once()
@patch("utils.models.model_config._raw_config_has_vision_config", return_value = None)
@patch("utils.transformers_version.needs_transformers_5", return_value = False)
@patch("utils.models.model_config.load_model_config")
def test_vision_config_attr_detected_and_cached(
self, mock_load_config, mock_needs_t5, mock_raw
):
"""Models with vision_config (LLaVA, Qwen2-VL, etc.) should be cached as True."""
cfg = MagicMock(spec = []) # strict: only explicitly set attrs exist
cfg.model_type = "qwen2_vl"
cfg.architectures = ["Qwen2VLForCausalLM"] # Doesn't match VLM suffixes
cfg.vision_config = {"hidden_size": 1024}
mock_load_config.return_value = cfg
assert is_vision_model("Qwen/Qwen2-VL-7B") is True
assert is_vision_model("Qwen/Qwen2-VL-7B") is True
mock_load_config.assert_called_once()
@patch("utils.models.model_config._raw_config_has_vision_config", return_value = None)
@patch("utils.transformers_version.needs_transformers_5", return_value = False)
@patch("utils.models.model_config.load_model_config")
def test_gemma4_model_type_detected_and_cached(self, mock_load_config, mock_needs_t5, mock_raw):
cfg = MagicMock(spec = [])
cfg.model_type = "gemma4"
cfg.architectures = ["Gemma4ForConditionalGeneration"]
mock_load_config.return_value = cfg
assert is_vision_model("google/gemma-4-E4B-it") is True
assert is_vision_model("google/gemma-4-E4B-it") is True
mock_load_config.assert_called_once()
@patch("utils.models.model_config._raw_config_has_vision_config", return_value = None)
@patch("utils.transformers_version.needs_transformers_5", return_value = False)
@patch("utils.models.model_config.load_model_config")
def test_gemma4_audio_subconfig_not_detected_as_vision(
self, mock_load_config, mock_needs_t5, mock_raw
):
cfg = MagicMock(spec = [])
cfg.model_type = "gemma4_audio"
cfg.architectures = ["Gemma4AudioModel"]
mock_load_config.return_value = cfg
assert is_vision_model("local/gemma4-audio-encoder") is False
assert is_vision_model("local/gemma4-audio-encoder") is False
mock_load_config.assert_called_once()
@patch("utils.models.model_config._raw_config_has_vision_config", return_value = None)
@patch("utils.transformers_version.needs_transformers_5", return_value = False)
@patch("utils.models.model_config.load_model_config")
def test_gemma4_text_subconfig_not_detected_as_vision(
self, mock_load_config, mock_needs_t5, mock_raw
):
cfg = MagicMock(spec = [])
cfg.model_type = "gemma4_text"
cfg.architectures = ["Gemma4ForCausalLM"]
mock_load_config.return_value = cfg
assert is_vision_model("local/gemma-4-text") is False
assert is_vision_model("local/gemma-4-text") is False
mock_load_config.assert_called_once()
@patch("utils.models.model_config._raw_config_has_vision_config", return_value = None)
@patch("utils.transformers_version.needs_transformers_5", return_value = False)
@patch("utils.models.model_config.load_model_config")
def test_audio_model_excluded_and_cached(self, mock_load_config, mock_needs_t5, mock_raw):
"""Audio-only models (csm, whisper) with ForConditionalGeneration
should be excluded from VLM detection and cached as False."""
cfg = MagicMock(spec = []) # strict: only explicitly set attrs exist
cfg.model_type = "whisper"
cfg.architectures = ["WhisperForConditionalGeneration"]
mock_load_config.return_value = cfg
assert is_vision_model("openai/whisper-large-v3") is False
assert is_vision_model("openai/whisper-large-v3") is False
mock_load_config.assert_called_once()
# hf_token handling
class TestVisionCacheTokenHandling:
"""The cache is keyed on (model_name, hf_token). Different tokens
for the same model trigger separate detections for gated models."""
@patch("utils.models.model_config._is_vision_model_uncached", return_value = True)
def test_different_tokens_trigger_new_detection(self, mock_uncached):
"""Different tokens trigger separate detections for gated models
(e.g. unauthenticated probe → False, then authenticated
re-check)."""
assert is_vision_model("gated/model", hf_token = "token-a") is True
assert is_vision_model("gated/model", hf_token = "token-b") is True
assert mock_uncached.call_count == 2
@patch("utils.models.model_config._is_vision_model_uncached", return_value = True)
def test_same_token_uses_cache(self, mock_uncached):
"""Repeated calls with identical model + token should hit cache."""
assert is_vision_model("gated/model", hf_token = "token-a") is True
assert is_vision_model("gated/model", hf_token = "token-a") is True
mock_uncached.assert_called_once()
class TestVisionCacheLocalOnly:
"""local_files_only is in the cache key: an offline negative must not be reused by a
later online probe (else a VLM is routed through the text loader until restart)."""
def test_local_only_negative_does_not_poison_online(self, monkeypatch):
import utils.models.model_config as mc
mc._vision_detection_cache.clear()
monkeypatch.setattr(mc, "is_local_path", lambda *_a, **_k: False)
monkeypatch.setattr(mc, "resolve_cached_repo_id_case", lambda n, *_a, **_k: n)
# Pin env-offline off so the key tracks the kwarg.
monkeypatch.setattr(mc, "_env_offline", lambda: False)
seen = []
def _probe(
name,
hf_token = None,
local_files_only = False,
):
seen.append(local_files_only)
# Offline can't fetch -> not a VLM; online reveals the VLM.
return False if local_files_only else True
monkeypatch.setattr(mc, "_is_vision_model_uncached", _probe)
# Offline probe caches False under a local-only key.
assert mc.is_vision_model("some/vlm", local_files_only = True) is False
# A later online probe must re-run (different key) and detect the VLM.
assert mc.is_vision_model("some/vlm", local_files_only = False) is True
assert seen == [True, False]
# The online positive is then cached for subsequent online callers.
assert mc.is_vision_model("some/vlm", local_files_only = False) is True
assert seen == [True, False]
mc._vision_detection_cache.clear()
# ---------------------------------------------------------------------------
# Direct unit tests for _raw_config_has_vision_config
# ---------------------------------------------------------------------------
import json as _json
from utils.models.model_config import (
_AUDIO_ONLY_MODEL_TYPES,
_VISION_CHECK_INLINE_HELPERS,
_VISION_CHECK_SCRIPT,
_is_vlm,
_raw_config_has_vision_config,
)
def _write_config(tmp_path, config):
(tmp_path / "config.json").write_text(_json.dumps(config))
return tmp_path
class TestRawConfigVlmDetection:
"""Direct coverage of _raw_config_has_vision_config across the same
indicator set used by _is_vlm. The cache integration tests above mock
this function; these exercise its real implementation."""
def test_truthy_vision_config(self, tmp_path):
p = _write_config(tmp_path, {"vision_config": {"hidden_size": 1024}})
assert _raw_config_has_vision_config(str(p)) is True
def test_empty_vision_config_key(self, tmp_path):
p = _write_config(tmp_path, {"vision_config": {}})
assert _raw_config_has_vision_config(str(p)) is True
def test_arch_suffix_detection(self, tmp_path):
p = _write_config(
tmp_path,
{
"architectures": ["Gemma4ForConditionalGeneration"],
"model_type": "gemma4",
},
)
assert _raw_config_has_vision_config(str(p)) is True
def test_img_processor_key(self, tmp_path):
p = _write_config(tmp_path, {"img_processor": {"image_size": 336}})
assert _raw_config_has_vision_config(str(p)) is True
def test_image_token_index_key(self, tmp_path):
p = _write_config(tmp_path, {"image_token_index": 32000})
assert _raw_config_has_vision_config(str(p)) is True
def test_known_vlm_model_type(self, tmp_path):
p = _write_config(tmp_path, {"model_type": "gemma4"})
assert _raw_config_has_vision_config(str(p)) is True
def test_plain_text_model_returns_false(self, tmp_path):
p = _write_config(
tmp_path,
{"model_type": "llama", "architectures": ["LlamaForCausalLM"]},
)
assert _raw_config_has_vision_config(str(p)) is False
def test_missing_config_returns_none(self, tmp_path):
assert _raw_config_has_vision_config(str(tmp_path)) is None
# ---------------------------------------------------------------------------
# Self-contained subprocess script (no parent backend imports)
# ---------------------------------------------------------------------------
class TestSubprocessScript:
def test_does_not_import_parent_module(self):
assert "from utils.models.model_config" not in _VISION_CHECK_SCRIPT
def test_inline_is_vlm_executes_correctly(self):
ns: dict = {}
exec(_VISION_CHECK_INLINE_HELPERS, ns)
inline_is_vlm = ns["_is_vlm"]
class _C:
def __init__(self, **kw):
for k, v in kw.items():
setattr(self, k, v)
assert (
inline_is_vlm(
_C(
model_type = "gemma4",
architectures = ["Gemma4ForConditionalGeneration"],
)
)
is True
)
assert (
inline_is_vlm(_C(model_type = "gemma4_text", architectures = ["Gemma4ForCausalLM"]))
is False
)
assert inline_is_vlm(_C(model_type = "llama", architectures = ["LlamaForCausalLM"])) is False
# ---------------------------------------------------------------------------
# Audio-only model exclusion must apply across every detection path
# ---------------------------------------------------------------------------
class TestVlmAudioExclusion:
"""The {csm, whisper} guard previously lived only in the direct caller
branch. These tests assert it now applies inside _is_vlm, the raw
fallback, and the inlined subprocess helper too."""
def test_audio_only_set_canonical(self):
# Derived from the transformers audio registry, so a superset of {csm, whisper}.
assert {"csm", "whisper"} <= _AUDIO_ONLY_MODEL_TYPES
def test_is_vlm_excludes_whisper(self):
cfg = MagicMock(spec = [])
cfg.model_type = "whisper"
cfg.architectures = ["WhisperForConditionalGeneration"]
assert _is_vlm(cfg) is False
def test_raw_fallback_excludes_whisper(self, tmp_path):
p = _write_config(
tmp_path,
{
"architectures": ["WhisperForConditionalGeneration"],
"model_type": "whisper",
},
)
assert _raw_config_has_vision_config(str(p)) is False
def test_inline_subprocess_helper_excludes_whisper(self):
ns: dict = {}
exec(_VISION_CHECK_INLINE_HELPERS, ns)
cfg = MagicMock(spec = [])
cfg.model_type = "whisper"
cfg.architectures = ["WhisperForConditionalGeneration"]
assert ns["_is_vlm"](cfg) is False
@patch("utils.models.model_config._is_vision_model_subprocess", return_value = None)
@patch("utils.transformers_version.needs_transformers_5", return_value = True)
def test_t5_subprocess_none_falls_back_through_raw_for_whisper(
self, mock_needs_t5, mock_subprocess, tmp_path
):
_write_config(
tmp_path,
{
"architectures": ["WhisperForConditionalGeneration"],
"model_type": "whisper",
},
)
assert is_vision_model(str(tmp_path)) is False
class TestAudioDetectionCacheTokenAware:
"""The audio cache mirrors the vision cache: keyed by (model, token_fingerprint)
so an unauthenticated miss cannot poison a later authenticated lookup."""
def test_audio_cache_is_token_aware(self, monkeypatch):
import utils.models.model_config as mc
mc._audio_detection_cache.clear()
calls = []
def _fake(
name,
hf_token = None,
local_files_only = False,
):
calls.append(hf_token)
# Gated repo: only an authenticated probe can read the tokenizer.
return ("bicodec", True) if hf_token else (None, True)
monkeypatch.setattr(mc, "_detect_audio_from_tokenizer", _fake)
monkeypatch.setattr(mc, "is_local_path", lambda *_a, **_k: False)
monkeypatch.setattr(mc, "resolve_cached_repo_id_case", lambda n, *_a, **_k: n)
# Unauthenticated miss caches None under (name, None)...
assert mc.detect_audio_type("private/spark") is None
# ...but the authenticated call uses a different key and is NOT poisoned.
assert mc.detect_audio_type("private/spark", hf_token = "hf_x") == "bicodec"
assert calls == [None, "hf_x"]
# Same (model, token) is served from cache (no third probe).
assert mc.detect_audio_type("private/spark", hf_token = "hf_x") == "bicodec"
assert calls == [None, "hf_x"]
mc._audio_detection_cache.clear()
def test_transient_none_is_not_cached_but_definitive_none_is(self, monkeypatch):
"""A transient probe failure (definitive=False) must retry; a clean
'not audio' read (definitive=True) caches so we don't re-probe."""
import utils.models.model_config as mc
mc._audio_detection_cache.clear()
monkeypatch.setattr(mc, "is_local_path", lambda *_a, **_k: False)
monkeypatch.setattr(mc, "resolve_cached_repo_id_case", lambda n, *_a, **_k: n)
transient_calls = []
def _transient(
name,
hf_token = None,
local_files_only = False,
):
transient_calls.append(hf_token)
return (None, False) # network/5xx -- not cacheable
monkeypatch.setattr(mc, "_detect_audio_from_tokenizer", _transient)
assert mc.detect_audio_type("flaky/model") is None
assert mc.detect_audio_type("flaky/model") is None
# Re-probed both times: the transient None was never cached.
assert transient_calls == [None, None]
definitive_calls = []
def _definitive(
name,
hf_token = None,
local_files_only = False,
):
definitive_calls.append(hf_token)
return (None, True) # read the config, no audio tokens
monkeypatch.setattr(mc, "_detect_audio_from_tokenizer", _definitive)
assert mc.detect_audio_type("plain/text-model") is None
assert mc.detect_audio_type("plain/text-model") is None
# Probed once: the definitive None was cached.
assert definitive_calls == [None]
mc._audio_detection_cache.clear()
def test_local_only_negative_does_not_poison_online(self, monkeypatch):
"""An offline negative must not be reused by a later online probe (else an audio
model is routed through the text loader until restart)."""
import utils.models.model_config as mc
mc._audio_detection_cache.clear()
monkeypatch.setattr(mc, "is_local_path", lambda *_a, **_k: False)
monkeypatch.setattr(mc, "resolve_cached_repo_id_case", lambda n, *_a, **_k: n)
# Pin env-offline off so the key tracks the kwarg.
monkeypatch.setattr(mc, "_env_offline", lambda: False)
seen = []
def _probe(
name,
hf_token = None,
local_files_only = False,
):
seen.append(local_files_only)
# Offline: nothing on disk -> not audio; online reveals the audio model.
return (None, True) if local_files_only else ("snac", True)
monkeypatch.setattr(mc, "_detect_audio_from_tokenizer", _probe)
# Offline probe caches None under a local-only key.
assert mc.detect_audio_type("some/audio-model", local_files_only = True) is None
# A later online probe must re-run (different key) and detect the audio model.
assert mc.detect_audio_type("some/audio-model", local_files_only = False) == "snac"
assert seen == [True, False]
# The online positive is then cached for subsequent online callers.
assert mc.detect_audio_type("some/audio-model", local_files_only = False) == "snac"
assert seen == [True, False]
mc._audio_detection_cache.clear()
def test_env_offline_negative_does_not_poison_online(self, monkeypatch):
"""An env-offline probe (default local_files_only=False) must cache under the
effective-offline key, so clearing the env var later doesn't leak a stale negative."""
import utils.models.model_config as mc
mc._audio_detection_cache.clear()
monkeypatch.setattr(mc, "is_local_path", lambda *_a, **_k: False)
monkeypatch.setattr(mc, "resolve_cached_repo_id_case", lambda n, *_a, **_k: n)
env_offline = {"v": True}
monkeypatch.setattr(mc, "_env_offline", lambda: env_offline["v"])
seen = []
def _probe(
name,
hf_token = None,
local_files_only = False,
):
seen.append(local_files_only)
return (None, True) if local_files_only else ("snac", True)
monkeypatch.setattr(mc, "_detect_audio_from_tokenizer", _probe)
# Env offline + default kwarg -> probe runs offline; None cached under the offline key.
assert mc.detect_audio_type("some/audio-model") is None
assert seen == [True]
# Env var cleared: a fresh online probe must re-run (different key) and detect.
env_offline["v"] = False
assert mc.detect_audio_type("some/audio-model") == "snac"
assert seen == [True, False]
mc._audio_detection_cache.clear()
class TestEnvOfflineParsing:
"""_env_offline accepts the canonical truthy set (strip+lower, on/true/yes/1); it gates
the requests.get fallback and the cache keys, so 'on' or ' 1 ' must still count as offline."""
def test_truthy_values_recognized(self, monkeypatch):
import utils.models.model_config as mc
for var in ("HF_HUB_OFFLINE", "TRANSFORMERS_OFFLINE"):
for val in ("1", "true", "TRUE", "yes", "Yes", "on", "ON", " 1 ", " on ", "\ttrue\n"):
monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)
monkeypatch.setenv(var, val)
assert mc._env_offline() is True, f"{var}={val!r} should be offline"
def test_falsy_values_not_offline(self, monkeypatch):
import utils.models.model_config as mc
monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)
assert mc._env_offline() is False
for val in ("", "0", "false", "no", "off", "2", "onn"):
monkeypatch.setenv("HF_HUB_OFFLINE", val)
assert mc._env_offline() is False, f"HF_HUB_OFFLINE={val!r} should not be offline"