* 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>
539 lines
19 KiB
Python
539 lines
19 KiB
Python
"""Unit tests for the offline-loading helpers in unsloth/models/loader_utils.py:
|
|
error classification, _force_hf_offline flip/restore, and the retry orchestrator.
|
|
Pure CPU, no network, no GPU."""
|
|
|
|
import os
|
|
import socket
|
|
|
|
import pytest
|
|
|
|
from unsloth.models import loader_utils as L
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# _env_says_offline / _get_effective_local_files_only
|
|
# ---------------------------------------------------------------------------
|
|
|
|
_OFFLINE_TRUE = ("1", "true", "yes", "on", "ON", " 1 ", "\tyes\n")
|
|
_OFFLINE_FALSE = ("0", "no", "false", "off", "", " ", "maybe")
|
|
|
|
|
|
@pytest.mark.parametrize("value", _OFFLINE_TRUE)
|
|
def test_env_says_offline_truthy(monkeypatch, value):
|
|
monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)
|
|
monkeypatch.setenv("HF_HUB_OFFLINE", value)
|
|
assert L._env_says_offline() is True
|
|
|
|
|
|
@pytest.mark.parametrize("value", _OFFLINE_FALSE)
|
|
def test_env_says_offline_falsy(monkeypatch, value):
|
|
monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)
|
|
monkeypatch.setenv("HF_HUB_OFFLINE", value)
|
|
assert L._env_says_offline() is False
|
|
|
|
|
|
def test_env_says_offline_absent(monkeypatch):
|
|
monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
|
|
monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)
|
|
assert L._env_says_offline() is False
|
|
|
|
|
|
def test_env_says_offline_transformers_var(monkeypatch):
|
|
monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
|
|
monkeypatch.setenv("TRANSFORMERS_OFFLINE", "1")
|
|
assert L._env_says_offline() is True
|
|
|
|
|
|
def test_effective_lfo_kwarg_wins(monkeypatch):
|
|
monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
|
|
monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)
|
|
assert L._get_effective_local_files_only({"local_files_only": True}) is True
|
|
|
|
|
|
def test_effective_lfo_env_only(monkeypatch):
|
|
monkeypatch.setenv("HF_HUB_OFFLINE", "1")
|
|
assert L._get_effective_local_files_only({}) is True
|
|
|
|
|
|
def test_effective_lfo_neither(monkeypatch):
|
|
monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
|
|
monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)
|
|
assert L._get_effective_local_files_only({"local_files_only": False}) is False
|
|
|
|
|
|
def test_effective_lfo_is_read_only():
|
|
# Must not pop local_files_only: the weight load reuses the same kwarg.
|
|
kwargs = {"local_files_only": True}
|
|
L._get_effective_local_files_only(kwargs)
|
|
assert kwargs == {"local_files_only": True}
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# _is_offline_related_error
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def _http_error(status):
|
|
import requests
|
|
|
|
resp = requests.Response()
|
|
resp.status_code = status
|
|
return requests.exceptions.HTTPError("http %s" % status, response = resp)
|
|
|
|
|
|
def test_none_is_not_offline():
|
|
assert L._is_offline_related_error(None) is False
|
|
|
|
|
|
def test_plain_connection_error_is_offline():
|
|
assert L._is_offline_related_error(ConnectionError("down")) is True
|
|
|
|
|
|
def test_timeout_error_is_offline():
|
|
assert L._is_offline_related_error(TimeoutError("slow")) is True
|
|
|
|
|
|
def test_plain_file_not_found_propagates():
|
|
assert L._is_offline_related_error(FileNotFoundError("config.json")) is False
|
|
|
|
|
|
def test_unrelated_error_is_not_offline():
|
|
assert L._is_offline_related_error(ValueError("bad arg")) is False
|
|
|
|
|
|
def test_requests_connection_error_is_offline():
|
|
import requests
|
|
assert L._is_offline_related_error(requests.exceptions.ConnectionError("x")) is True
|
|
|
|
|
|
@pytest.mark.parametrize("status", (500, 502, 503, 504))
|
|
def test_http_5xx_is_offline(status):
|
|
assert L._is_offline_related_error(_http_error(status)) is True
|
|
|
|
|
|
@pytest.mark.parametrize("status", (400, 401, 403, 404))
|
|
def test_http_4xx_propagates(status):
|
|
assert L._is_offline_related_error(_http_error(status)) is False
|
|
|
|
|
|
def test_status_less_http_with_network_wording_is_offline():
|
|
import requests
|
|
err = requests.exceptions.HTTPError("Couldn't connect to the server")
|
|
assert L._is_offline_related_error(err) is True
|
|
|
|
|
|
def test_status_less_http_without_network_wording_propagates():
|
|
import requests
|
|
err = requests.exceptions.HTTPError("I'm a teapot")
|
|
assert L._is_offline_related_error(err) is False
|
|
|
|
|
|
def test_gaierror_dns_failure_is_offline():
|
|
assert L._is_offline_related_error(socket.gaierror(-2, "Name or service not known")) is True
|
|
|
|
|
|
def test_gaierror_without_wording_is_offline_by_type():
|
|
# Matched by type, so a locale-specific / empty message still classifies offline.
|
|
assert L._is_offline_related_error(socket.gaierror(-2, "")) is True
|
|
|
|
|
|
def test_urllib_urlerror_is_offline():
|
|
import urllib.error
|
|
assert L._is_offline_related_error(urllib.error.URLError("connection failed")) is True
|
|
|
|
|
|
def test_urllib_httperror_404_propagates():
|
|
import urllib.error
|
|
err = urllib.error.HTTPError("http://x", 404, "Not Found", {}, None)
|
|
assert L._is_offline_related_error(err) is False
|
|
|
|
|
|
def test_urllib_httperror_503_is_offline():
|
|
import urllib.error
|
|
err = urllib.error.HTTPError("http://x", 503, "Service Unavailable", {}, None)
|
|
assert L._is_offline_related_error(err) is True
|
|
|
|
|
|
def test_ssl_error_is_not_offline():
|
|
# TLS/cert failure must surface, not silently fall back to cached files.
|
|
import ssl
|
|
assert L._is_offline_related_error(ssl.SSLError("certificate verify failed")) is False
|
|
|
|
|
|
def test_requests_ssl_error_is_not_offline():
|
|
# requests.SSLError subclasses ConnectionError, but is still a TLS failure -> not offline.
|
|
requests = pytest.importorskip("requests")
|
|
assert L._is_offline_related_error(requests.exceptions.SSLError("bad cert")) is False
|
|
|
|
|
|
def test_urlerror_wrapping_ssl_is_not_offline():
|
|
import ssl
|
|
import urllib.error
|
|
|
|
err = urllib.error.URLError(ssl.SSLCertVerificationError("self-signed certificate"))
|
|
assert L._is_offline_related_error(err) is False
|
|
|
|
|
|
def test_ssl_node_does_not_hide_deeper_connection_cause():
|
|
# Skipping a TLS node must not abort the walk: a genuine outage deeper still counts.
|
|
import ssl
|
|
|
|
outer = RuntimeError("load failed")
|
|
mid = ssl.SSLError("cert")
|
|
mid.__context__ = ConnectionError("down")
|
|
outer.__cause__ = mid
|
|
assert L._is_offline_related_error(outer) is True
|
|
|
|
|
|
def test_oserror_network_unreachable_is_offline():
|
|
assert L._is_offline_related_error(OSError("Network is unreachable")) is True
|
|
|
|
|
|
def test_offline_mode_is_enabled_is_offline():
|
|
errors = pytest.importorskip("huggingface_hub.errors")
|
|
assert L._is_offline_related_error(errors.OfflineModeIsEnabled("offline")) is True
|
|
|
|
|
|
def test_local_entry_not_found_is_offline():
|
|
# Both a FileNotFoundError and an HfHubHTTPError, but means "not cached + Hub down" -> offline.
|
|
errors = pytest.importorskip("huggingface_hub.errors")
|
|
assert L._is_offline_related_error(errors.LocalEntryNotFoundError("missing")) is True
|
|
|
|
|
|
def test_chained_cause_connection_error_is_offline():
|
|
err = RuntimeError("combined load failure")
|
|
err.__cause__ = ConnectionError("down")
|
|
assert L._is_offline_related_error(err) is True
|
|
|
|
|
|
def test_chained_context_connection_error_is_offline():
|
|
try:
|
|
try:
|
|
raise ConnectionError("down")
|
|
except ConnectionError:
|
|
raise RuntimeError("wrap")
|
|
except RuntimeError as e:
|
|
err = e
|
|
assert L._is_offline_related_error(err) is True
|
|
|
|
|
|
def test_chained_cause_404_still_propagates():
|
|
err = RuntimeError("combined load failure")
|
|
err.__cause__ = _http_error(404)
|
|
assert L._is_offline_related_error(err) is False
|
|
|
|
|
|
def test_cause_context_cycle_terminates():
|
|
a = RuntimeError("a")
|
|
b = RuntimeError("b")
|
|
a.__context__ = b
|
|
b.__context__ = a
|
|
# Must not hang; neither is network-related.
|
|
assert L._is_offline_related_error(a) is False
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# _force_hf_offline
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def _inprocess_offline_flags():
|
|
flags = []
|
|
try:
|
|
import huggingface_hub.constants as hfc
|
|
if hasattr(hfc, "HF_HUB_OFFLINE"):
|
|
flags.append(hfc.HF_HUB_OFFLINE)
|
|
except Exception:
|
|
pass
|
|
try:
|
|
import transformers.utils.hub as tuh
|
|
for attr in ("_is_offline_mode", "OFFLINE"):
|
|
if hasattr(tuh, attr):
|
|
flags.append(getattr(tuh, attr))
|
|
except Exception:
|
|
pass
|
|
return flags
|
|
|
|
|
|
def test_force_offline_sets_and_restores_absent_env(monkeypatch):
|
|
monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
|
|
monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)
|
|
with L._force_hf_offline():
|
|
assert os.environ.get("HF_HUB_OFFLINE") == "1"
|
|
assert os.environ.get("TRANSFORMERS_OFFLINE") == "1"
|
|
# Absent before -> absent after (not left as "1").
|
|
assert os.environ.get("HF_HUB_OFFLINE") is None
|
|
assert os.environ.get("TRANSFORMERS_OFFLINE") is None
|
|
|
|
|
|
def test_force_offline_preserves_prior_env_value(monkeypatch):
|
|
monkeypatch.setenv("HF_HUB_OFFLINE", "0")
|
|
with L._force_hf_offline():
|
|
assert os.environ.get("HF_HUB_OFFLINE") == "1"
|
|
assert os.environ.get("HF_HUB_OFFLINE") == "0"
|
|
|
|
|
|
def test_force_offline_flips_inprocess_constants():
|
|
before = _inprocess_offline_flags()
|
|
with L._force_hf_offline():
|
|
during = _inprocess_offline_flags()
|
|
assert during, "expected at least one in-process offline flag to inspect"
|
|
assert all(flag is True for flag in during)
|
|
assert _inprocess_offline_flags() == before
|
|
|
|
|
|
def test_force_offline_nesting_shares_one_flip(monkeypatch):
|
|
monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
|
|
monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)
|
|
with L._force_hf_offline():
|
|
with L._force_hf_offline():
|
|
assert os.environ.get("HF_HUB_OFFLINE") == "1"
|
|
# Inner exit must NOT restore while the outer window is still open.
|
|
assert os.environ.get("HF_HUB_OFFLINE") == "1"
|
|
assert os.environ.get("HF_HUB_OFFLINE") is None
|
|
|
|
|
|
def test_force_offline_restores_on_exception(monkeypatch):
|
|
monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
|
|
monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)
|
|
with pytest.raises(RuntimeError):
|
|
with L._force_hf_offline():
|
|
assert os.environ.get("HF_HUB_OFFLINE") == "1"
|
|
raise RuntimeError("boom")
|
|
assert os.environ.get("HF_HUB_OFFLINE") is None
|
|
assert os.environ.get("TRANSFORMERS_OFFLINE") is None
|
|
|
|
|
|
def test_force_offline_depth_returns_to_zero():
|
|
assert L._force_offline_depth == 0
|
|
with L._force_hf_offline():
|
|
assert L._force_offline_depth == 1
|
|
assert L._force_offline_depth == 0
|
|
|
|
|
|
def test_reset_hf_sessions_is_safe():
|
|
# Best-effort no-op when the hub helper is missing; must never raise.
|
|
L._reset_hf_sessions()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# _has_local_tokenizer_files / _resolve_checkpoint_tokenizer_name
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def _touch(path, name):
|
|
open(os.path.join(path, name), "w").close()
|
|
|
|
|
|
def test_has_local_tokenizer_json(tmp_path):
|
|
_touch(tmp_path, "tokenizer.json")
|
|
assert L._has_local_tokenizer_files(str(tmp_path)) is True
|
|
|
|
|
|
def test_has_local_tokenizer_model(tmp_path):
|
|
_touch(tmp_path, "tokenizer.model")
|
|
assert L._has_local_tokenizer_files(str(tmp_path)) is True
|
|
|
|
|
|
def test_has_local_tokenizer_bpe_needs_merges(tmp_path):
|
|
# vocab.json alone is not loadable BPE; it needs merges.txt.
|
|
_touch(tmp_path, "vocab.json")
|
|
assert L._has_local_tokenizer_files(str(tmp_path)) is False
|
|
_touch(tmp_path, "merges.txt")
|
|
assert L._has_local_tokenizer_files(str(tmp_path)) is True
|
|
|
|
|
|
def test_has_local_tokenizer_empty_dir(tmp_path):
|
|
assert L._has_local_tokenizer_files(str(tmp_path)) is False
|
|
|
|
|
|
def test_resolve_tokenizer_explicit_override_wins(tmp_path):
|
|
kwargs = {"tokenizer_name": "base/repo"}
|
|
assert L._resolve_checkpoint_tokenizer_name(str(tmp_path), kwargs) == "base/repo"
|
|
# tokenizer_name is always popped (it is passed explicitly downstream too).
|
|
assert "tokenizer_name" not in kwargs
|
|
|
|
|
|
def test_resolve_tokenizer_self_sufficient_dir(tmp_path):
|
|
_touch(tmp_path, "tokenizer_config.json")
|
|
_touch(tmp_path, "tokenizer.json")
|
|
kwargs = {}
|
|
assert L._resolve_checkpoint_tokenizer_name(str(tmp_path), kwargs) == str(tmp_path)
|
|
|
|
|
|
def test_resolve_tokenizer_config_without_files_falls_back(tmp_path):
|
|
# Has tokenizer_config.json but no loadable tokenizer file -> base repo.
|
|
_touch(tmp_path, "tokenizer_config.json")
|
|
assert L._resolve_checkpoint_tokenizer_name(str(tmp_path), {}) is None
|
|
|
|
|
|
def test_resolve_tokenizer_nonexistent_dir_falls_back():
|
|
assert L._resolve_checkpoint_tokenizer_name("/no/such/dir", {}) is None
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# _offline_aware_load (the retry orchestrator)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_retry_once_on_offline_error_then_succeed(monkeypatch):
|
|
monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
|
|
monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)
|
|
calls = []
|
|
|
|
@L._offline_aware_load
|
|
def fake(*args, **kwargs):
|
|
calls.append(dict(kwargs))
|
|
if len(calls) == 1:
|
|
raise ConnectionError("network down")
|
|
return "ok"
|
|
|
|
assert fake("model") == "ok"
|
|
assert len(calls) == 2
|
|
assert not calls[0].get("local_files_only")
|
|
assert calls[1].get("local_files_only") is True
|
|
assert L._force_offline_depth == 0
|
|
|
|
|
|
def test_no_retry_on_non_offline_error(monkeypatch):
|
|
monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
|
|
monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)
|
|
calls = []
|
|
|
|
@L._offline_aware_load
|
|
def fake(*args, **kwargs):
|
|
calls.append(1)
|
|
raise ValueError("genuine bug, not a network issue")
|
|
|
|
with pytest.raises(ValueError):
|
|
fake("model")
|
|
assert len(calls) == 1
|
|
|
|
|
|
def test_no_retry_when_already_offline_via_kwarg(monkeypatch):
|
|
monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
|
|
monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)
|
|
calls = []
|
|
|
|
@L._offline_aware_load
|
|
def fake(*args, **kwargs):
|
|
calls.append(dict(kwargs))
|
|
# Offline window is active for the single attempt.
|
|
assert os.environ.get("HF_HUB_OFFLINE") == "1"
|
|
return "ok"
|
|
|
|
assert fake("model", local_files_only = True) == "ok"
|
|
assert len(calls) == 1
|
|
assert L._force_offline_depth == 0
|
|
|
|
|
|
def test_offline_error_when_already_offline_propagates(monkeypatch):
|
|
# Already offline -> no online attempt to retry, so the error propagates once.
|
|
monkeypatch.setenv("HF_HUB_OFFLINE", "1")
|
|
calls = []
|
|
|
|
@L._offline_aware_load
|
|
def fake(*args, **kwargs):
|
|
calls.append(1)
|
|
raise ConnectionError("still down")
|
|
|
|
with pytest.raises(ConnectionError):
|
|
fake("model")
|
|
assert len(calls) == 1
|
|
assert L._force_offline_depth == 0
|
|
|
|
|
|
def test_kwargs_preserved_across_retry(monkeypatch):
|
|
# Callee popping config/tokenizer_name must not change what the retry sees:
|
|
# fn(*args, **kwargs) re-packs a fresh **kwargs per call.
|
|
monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
|
|
monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)
|
|
seen = []
|
|
|
|
@L._offline_aware_load
|
|
def fake(model_name, **kwargs):
|
|
cfg = kwargs.pop("config", None)
|
|
tok = kwargs.pop("tokenizer_name", None)
|
|
seen.append((cfg, tok))
|
|
if len(seen) == 1:
|
|
raise ConnectionError("down")
|
|
return cfg, tok
|
|
|
|
assert fake("m", config = "CFG", tokenizer_name = "TOK") == ("CFG", "TOK")
|
|
assert seen == [("CFG", "TOK"), ("CFG", "TOK")]
|
|
|
|
|
|
def test_retry_runs_gc_collect_between_attempts(monkeypatch):
|
|
# The retry lives OUTSIDE the except so the failed attempt's traceback (a
|
|
# partial model) is freed by gc.collect() before the second load reallocates.
|
|
monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
|
|
monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)
|
|
gc_calls = []
|
|
monkeypatch.setattr(L.gc, "collect", lambda *a, **k: gc_calls.append(1))
|
|
calls = []
|
|
|
|
@L._offline_aware_load
|
|
def fake(*args, **kwargs):
|
|
calls.append(1)
|
|
if len(calls) == 1:
|
|
raise ConnectionError("down")
|
|
# By the retry attempt, gc.collect() must already have fired.
|
|
assert gc_calls, "gc.collect must run before the offline retry"
|
|
return "ok"
|
|
|
|
gc_calls.clear()
|
|
assert fake("model") == "ok"
|
|
assert len(calls) == 2
|
|
assert len(gc_calls) == 1
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# _force_hf_offline — constant restore (no stale offline pin)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_force_offline_restores_freshly_imported_constant(monkeypatch):
|
|
# If huggingface_hub.constants is first imported inside the window, the saved value must
|
|
# be the pre-window state, not the just-forced "1"; otherwise the process pins offline.
|
|
import sys
|
|
|
|
monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
|
|
monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)
|
|
saved_mod = sys.modules.get("huggingface_hub.constants")
|
|
saved_val = getattr(saved_mod, "HF_HUB_OFFLINE", None) if saved_mod else None
|
|
try:
|
|
sys.modules.pop("huggingface_hub.constants", None) # simulate "not imported yet"
|
|
with L._force_hf_offline():
|
|
import huggingface_hub.constants as hfc_in
|
|
assert hfc_in.HF_HUB_OFFLINE is True # forced offline inside the window
|
|
import huggingface_hub.constants as hfc_after
|
|
|
|
assert hfc_after.HF_HUB_OFFLINE is False # restored, not pinned True
|
|
assert os.environ.get("HF_HUB_OFFLINE") is None
|
|
finally:
|
|
if saved_mod is not None:
|
|
sys.modules["huggingface_hub.constants"] = saved_mod
|
|
if saved_val is not None:
|
|
saved_mod.HF_HUB_OFFLINE = saved_val
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# _resolve_checkpoint_tokenizer_name — VLM needs local processor files
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_resolve_tokenizer_vlm_without_processor_falls_back(tmp_path):
|
|
# VLM checkpoint with tokenizer files but no processor config -> base repo (None), so its
|
|
# cached processor still loads instead of AutoProcessor failing on the local dir.
|
|
_touch(tmp_path, "tokenizer_config.json")
|
|
_touch(tmp_path, "tokenizer.json")
|
|
assert L._resolve_checkpoint_tokenizer_name(str(tmp_path), {}, require_processor = True) is None
|
|
|
|
|
|
def test_resolve_tokenizer_vlm_with_processor_uses_local_dir(tmp_path):
|
|
_touch(tmp_path, "tokenizer_config.json")
|
|
_touch(tmp_path, "tokenizer.json")
|
|
_touch(tmp_path, "preprocessor_config.json")
|
|
assert L._resolve_checkpoint_tokenizer_name(str(tmp_path), {}, require_processor = True) == str(
|
|
tmp_path
|
|
)
|