Skip to content

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

Report the network error when the offline retry finds nothing cached (#8121)

Daniel Hanf0ef75ec91e2
diff --git a/tests/test_offline_loading_helpers.py b/tests/test_offline_loading_helpers.py
index b7176dbff4d..d0573a32a3e 100644
--- a/tests/test_offline_loading_helpers.py
+++ b/tests/test_offline_loading_helpers.py
@@ -4,6 +4,7 @@ Pure CPU, no network, no GPU."""
import os
import socket
+import traceback
import pytest
@@ -537,3 +538,494 @@ def test_resolve_tokenizer_vlm_with_processor_uses_local_dir(tmp_path):
assert L._resolve_checkpoint_tokenizer_name(str(tmp_path), {}, require_processor = True) == str(
tmp_path
)
+
+
+# ---------------------------------------------------------------------------
+# what the retry reports when it fails too
+# ---------------------------------------------------------------------------
+
+
+def test_the_online_error_is_what_surfaces_when_the_cache_is_empty(monkeypatch):
+ """The retry only succeeds on what is cached, so its own failure names an empty
+ cache badly: offline mode skips Transformers' "does not appear to have a file
+ named" raise, so the user saw `AttributeError: 'NoneType' ... 'endswith'`."""
+ 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("connection reset while downloading model.safetensors")
+ raise AttributeError("'NoneType' object has no attribute 'endswith'")
+
+ with pytest.raises(ConnectionError) as caught:
+ fake("model")
+ assert len(calls) == 2
+ assert "connection reset" in str(caught.value)
+ # The offline attempt is kept as the cause rather than thrown away.
+ assert isinstance(caught.value.__cause__, AttributeError)
+
+
+def test_the_surfaced_error_is_tagged_so_an_outer_wrapper_does_not_retry(monkeypatch):
+ """Stacked loaders must not reload twice more, so the tag has to travel on
+ whichever exception actually leaves."""
+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
+ monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)
+ calls = []
+
+ @L._offline_aware_load
+ def inner(*args, **kwargs):
+ calls.append(1)
+ raise ConnectionError("network down")
+
+ @L._offline_aware_load
+ def outer(*args, **kwargs):
+ return inner(*args, **kwargs)
+
+ with pytest.raises(ConnectionError) as caught:
+ outer("model")
+ assert getattr(caught.value, "_unsloth_offline_retried", False)
+ assert len(calls) == 2, "the outer wrapper retried an already-retried load"
+
+
+def test_an_out_of_memory_retry_reports_itself(monkeypatch):
+ """A large VLM can exhaust memory on the retry's second load. That says nothing
+ about the network, so it must not be replaced by the network error."""
+ 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)
+ if len(calls) == 1:
+ raise ConnectionError("network down")
+ raise MemoryError("CUDA out of memory")
+
+ with pytest.raises(MemoryError):
+ fake("model")
+
+
+def test_a_wrapped_out_of_memory_retry_is_recognised(monkeypatch):
+ """Loaders re-raise through their own error types, so the OOM is usually a
+ cause rather than the exception itself."""
+ 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)
+ if len(calls) == 1:
+ raise ConnectionError("network down")
+ try:
+ raise MemoryError("CUDA out of memory")
+ except MemoryError as oom:
+ raise RuntimeError("failed to place weights") from oom
+
+ with pytest.raises(RuntimeError) as caught:
+ fake("model")
+ assert isinstance(caught.value.__cause__, MemoryError)
+
+
+def test_a_successful_retry_is_unchanged(monkeypatch):
+ """The point of the retry: a cached model still loads after the network drops."""
+ 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)
+ if len(calls) == 1:
+ raise ConnectionError("network down")
+ return "loaded from cache"
+
+ assert fake("model") == "loaded from cache"
+ assert L._force_offline_depth == 0
+
+
+# ---------------------------------------------------------------------------
+# what the retry must not hold, hide, or overwrite
+# ---------------------------------------------------------------------------
+
+
+def test_the_failed_attempt_is_not_pinned_by_the_error_it_raised(monkeypatch):
+ """Holding the online error holds its frames, and its frames hold the partial
+ model. The retry then reallocates alongside it and a large VLM runs out of
+ memory doing exactly what the retry exists to do."""
+ import gc
+ import weakref
+
+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
+ monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)
+
+ class _PartialModel:
+ pass
+
+ witness = {}
+ calls = []
+
+ @L._offline_aware_load
+ def fake(*args, **kwargs):
+ calls.append(1)
+ if len(calls) == 1:
+ partial = _PartialModel() # what the failed load already built
+ witness["ref"] = weakref.ref(partial)
+ raise ConnectionError("connection reset while downloading model.safetensors")
+ witness["alive_during_retry"] = witness["ref"]() is not None
+ return "loaded"
+
+ monkeypatch.setattr(gc, "collect", lambda *a, **k: 0) # only refcounts, no cycles
+ assert fake("model") == "loaded"
+ assert (
+ witness["alive_during_retry"] is False
+ ), "the first attempt's model was still reachable while the retry reloaded"
+
+
+def test_a_real_retry_failure_is_not_replaced_by_the_network_error(monkeypatch):
+ """A corrupt checkpoint found offline is actionable and must reach the user.
+ Reporting the earlier connection error instead sends them to fix their wifi."""
+ 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)
+ if len(calls) == 1:
+ raise ConnectionError("network down")
+ raise ValueError("checkpoint header is corrupt")
+
+ with pytest.raises(ValueError) as caught:
+ fake("model")
+ assert "corrupt" in str(caught.value)
+
+
+def test_an_oom_spelled_as_a_bare_runtimeerror_still_surfaces(monkeypatch):
+ """accelerate re-raises an accelerator OOM as a plain RuntimeError, and XPU has
+ its own class. Selecting on the empty-cache artifact rather than on a list of
+ OOM spellings covers both without naming either."""
+ 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)
+ if len(calls) == 1:
+ raise ConnectionError("network down")
+ raise RuntimeError("CUDA out of memory. Tried to allocate 2.00 GiB")
+
+ with pytest.raises(RuntimeError) as caught:
+ fake("model")
+ assert "out of memory" in str(caught.value)
+
+
+def test_a_network_error_wrapped_in_a_runtimeerror_keeps_its_cause(monkeypatch):
+ """`FastModel.from_pretrained` raises a RuntimeError FROM the connection error,
+ so the chain is the only thing that makes it classifiable. Overwriting the cause
+ with the retry's failure loses that."""
+ 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)
+ if len(calls) == 1:
+ try:
+ raise ConnectionError("connection reset")
+ except ConnectionError as connection_error:
+ raise RuntimeError("could not load model") from connection_error
+ raise AttributeError("'NoneType' object has no attribute 'endswith'")
+
+ with pytest.raises(RuntimeError) as caught:
+ fake("model")
+ assert isinstance(
+ caught.value.__cause__, ConnectionError
+ ), "the retry replaced the connection error that made this classifiable"
+ assert L._is_offline_related_error(
+ caught.value
+ ), "the surfaced error is no longer recognisable as network-related"
+
+
+def test_a_wrapped_online_error_does_not_pin_the_failed_attempt(monkeypatch):
+ """Same pinning as above, but through the wrapper path the retry already supports:
+ the loader re-raises the connection error as its own type, so the partial model is
+ held by the CAUSE's traceback, not the top-level one."""
+ import gc
+ import weakref
+
+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
+ monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)
+
+ class _PartialModel:
+ pass
+
+ def _download():
+ raise ConnectionError("connection reset while downloading model.safetensors")
+
+ witness = {}
+ calls = []
+
+ @L._offline_aware_load
+ def fake(*args, **kwargs):
+ calls.append(1)
+ if len(calls) == 1:
+ partial = _PartialModel() # what the failed load already built
+ witness["ref"] = weakref.ref(partial)
+ try:
+ _download()
+ except ConnectionError as connection_error:
+ raise RuntimeError("could not load model") from connection_error
+ witness["alive_during_retry"] = witness["ref"]() is not None
+ return "loaded"
+
+ monkeypatch.setattr(gc, "collect", lambda *a, **k: 0) # only refcounts, no cycles
+ assert fake("model") == "loaded"
+ assert (
+ witness["alive_during_retry"] is False
+ ), "the wrapper's cause still held the first attempt's model while the retry reloaded"
+
+
+def test_an_implicitly_chained_network_error_stays_recognisable(monkeypatch):
+ """Loaders also chain implicitly (`raise RuntimeError(...)` inside an except, no
+ `from`), so the network error is in `__context__`. A raise inside the retry's
+ except block overwrites `__context__`, so the surfacing raise has to happen
+ outside it."""
+ 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)
+ if len(calls) == 1:
+ try:
+ raise ConnectionError("connection reset")
+ except ConnectionError:
+ raise RuntimeError("could not load model") # implicit chaining
+ raise AttributeError("'NoneType' object has no attribute 'endswith'")
+
+ with pytest.raises(RuntimeError) as caught:
+ fake("model")
+ assert L._is_offline_related_error(
+ caught.value
+ ), "the retry replaced the implicitly chained connection error that made this classifiable"
+ # The connection error keeps the slot the traceback prints, and the retry is
+ # reported alongside it rather than in place of it.
+ assert isinstance(caught.value.__context__, ConnectionError)
+ assert isinstance(caught.value._unsloth_offline_retry_error, AttributeError)
+
+
+def test_the_retry_is_reported_even_when_the_online_error_has_an_explicit_cause(monkeypatch):
+ """`FastModel.from_pretrained` raises `RuntimeError(...) from _cause` for a failed
+ config probe (loader.py:756). Python prints a cause INSTEAD of a context, so hanging
+ the retry off `__context__` there shows the user nothing about the cache attempt."""
+ 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)
+ if len(calls) == 1:
+ raise RuntimeError("could not load model") from ConnectionError("connection reset")
+ raise AttributeError("'NoneType' object has no attribute 'endswith'")
+
+ with pytest.raises(RuntimeError) as caught:
+ fake("model")
+ assert isinstance(caught.value.__cause__, ConnectionError)
+ assert isinstance(caught.value._unsloth_offline_retry_error, AttributeError)
+ if hasattr(caught.value, "add_note"): # notes are 3.11+
+ rendered = "".join(
+ traceback.format_exception(type(caught.value), caught.value, caught.value.__traceback__)
+ )
+ assert "retrying from the local cache also failed" in rendered
+ assert "'NoneType' object has no attribute 'endswith'" in rendered
+
+
+def test_a_context_the_loader_suppressed_is_not_promoted_to_a_cause(monkeypatch):
+ """`raise ... from None` keeps `__context__` but sets `__suppress_context__` to keep
+ it out of the traceback. Copying it into `__cause__` publishes what the loader chose
+ to hide."""
+ 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)
+ if len(calls) == 1:
+ try:
+ raise ConnectionError("connection reset from 10.0.0.1 with token hf_xxx")
+ except ConnectionError:
+ raise RuntimeError("could not load model") from None
+ raise AttributeError("'NoneType' object has no attribute 'endswith'")
+
+ with pytest.raises(RuntimeError) as caught:
+ fake("model")
+ assert caught.value.__cause__ is None, "the suppressed context was promoted to a cause"
+ assert caught.value.__suppress_context__ is True
+ rendered = "".join(
+ traceback.format_exception(type(caught.value), caught.value, caught.value.__traceback__)
+ )
+ assert "10.0.0.1" not in rendered
+
+
+ "artifact",
+ [
+ # A missing vocabulary resolves to None and is then dereferenced, opened or
+ # stat'd, so the family spans four exception types (#7845).
+ AttributeError("'NoneType' object has no attribute 'readlines'"),
+ TypeError(
+ "argument should be a str or an os.PathLike object where __fspath__ "
+ "returns a str, not 'NoneType'"
+ ),
+ TypeError("expected str, bytes or os.PathLike object, not NoneType"),
+ TypeError("stat: path should be string, bytes, os.PathLike or integer, not NoneType"),
+ ValueError("Can't find a vocabulary file at path 'None'."),
+ ],
+)
+def test_a_tokenizer_cache_miss_also_surfaces_the_network_error(monkeypatch, artifact):
+ """The retry loads the tokenizer and processor too, and an empty cache there is just
+ as opaque as it is for the weights."""
+ 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)
+ if len(calls) == 1:
+ raise ConnectionError("connection reset while downloading tokenizer.json")
+ raise artifact
+
+ with pytest.raises(ConnectionError) as caught:
+ fake("model")
+ assert "connection reset" in str(caught.value)
+ assert caught.value.__cause__ is artifact
+
+
+def test_the_same_wording_about_a_real_path_is_not_a_cache_miss():
+ """The TypeError spellings are generic, so they must stay gated on the None: a real
+ path in that message is a caller bug and has to reach the user unchanged."""
+ assert (
+ L._empty_cache_artifact(
+ TypeError("stat: path should be string, bytes, os.PathLike or integer, not int")
+ )
+ is False
+ )
+
+
+def test_the_vlm_tokenizer_fallback_does_not_pin_the_built_model(monkeypatch):
+ """The real path this matters on (vision.py:1683-1708): the model is already built,
+ `patch_tokenizer` fails, the AutoTokenizer fallback then hits the network, and the
+ network error is re-raised with the patch failure implicitly chained onto it. The
+ patch failure's traceback is the frame holding the model, so clearing only the
+ network error's own traceback leaves the whole model allocated for the retry."""
+ import gc
+ import weakref
+
+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
+ monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)
+
+ class _BuiltModel:
+ pass
+
+ def _patch_tokenizer(model, tok):
+ raise TypeError("Unsloth: this VLM processor cannot be patched")
+
+ def _fallback_auto_tokenizer():
+ raise ConnectionError("Max retries exceeded with url: /api/models")
+
+ witness = {}
+ calls = []
+
+ @L._offline_aware_load
+ def fake(*args, **kwargs):
+ calls.append(1)
+ if len(calls) == 1:
+ model = _BuiltModel() # already allocated by the weight load
+ witness["ref"] = weakref.ref(model)
+ try:
+ model, tokenizer = _patch_tokenizer(model, object())
+ except Exception as patch_error:
+ try:
+ _fallback_auto_tokenizer()
+ except Exception as fallback_error:
+ if L._is_offline_related_error(fallback_error):
+ raise
+ raise patch_error
+ witness["alive_during_retry"] = witness["ref"]() is not None
+ return "loaded"
+
+ monkeypatch.setattr(gc, "collect", lambda *a, **k: 0) # only refcounts, no cycles
+ assert fake("model") == "loaded"
+ assert (
+ witness["alive_during_retry"] is False
+ ), "the implicitly chained patch failure still held the built model during the retry"
+
+
+def test_the_surfaced_online_error_still_names_where_it_failed(monkeypatch):
+ """Freeing the failed attempt's memory must not cost the user the origin of the
+ network failure: with the traceback detached, the report says only that the
+ decorator re-raised something, which is useless for a failure raised deep inside
+ `trust_remote_code`."""
+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
+ monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)
+ calls = []
+
+ def _resolve_config_from_the_hub():
+ raise ConnectionError("Max retries exceeded with url: /api/models")
+
+ @L._offline_aware_load
+ def fake(*args, **kwargs):
+ calls.append(1)
+ if len(calls) == 1:
+ _resolve_config_from_the_hub()
+ raise AttributeError("'NoneType' object has no attribute 'endswith'")
+
+ with pytest.raises(ConnectionError) as caught:
+ fake("model")
+ rendered = "".join(
+ traceback.format_exception(type(caught.value), caught.value, caught.value.__traceback__)
+ )
+ assert "_resolve_config_from_the_hub" in rendered, rendered
+
+
+def test_the_retrys_own_frames_do_not_pin_the_cached_model(monkeypatch):
+ """The retry can load the whole model from the cache and only then trip over a
+ missing tokenizer file. That error is kept on the surfaced one, so its frames hold
+ the cached model for as long as the caller holds the error, and nothing collects
+ after this point."""
+ import gc
+ import weakref
+
+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
+ monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)
+
+ class _CachedModel:
+ pass
+
+ witness = {}
+ calls = []
+
+ @L._offline_aware_load
+ def fake(*args, **kwargs):
+ calls.append(1)
+ if len(calls) == 1:
+ raise ConnectionError("connection reset while downloading tokenizer.json")
+ model = _CachedModel() # the retry got the weights, then found no tokenizer
+ witness["ref"] = weakref.ref(model)
+ raise AttributeError("'NoneType' object has no attribute 'endswith'")
+
+ monkeypatch.setattr(gc, "collect", lambda *a, **k: 0) # only refcounts, no cycles
+ with pytest.raises(ConnectionError) as caught:
+ fake("model")
+ assert caught.value.__cause__ is not None
+ assert witness["ref"]() is None, "the retry error's traceback still held the cached model"
diff --git a/unsloth/models/loader_utils.py b/unsloth/models/loader_utils.py
index 767321f2ebe..269ceda220c 100644
--- a/unsloth/models/loader_utils.py
+++ b/unsloth/models/loader_utils.py
@@ -36,6 +36,7 @@ from transformers import __version__ as transformers_version
from unsloth.models._utils import TorchAOConfig
from unsloth_zoo.utils import Version, get_quant_type
import gc
+import traceback as _traceback
transformers_version = Version(transformers_version)
SUPPORTS_FOURBIT = transformers_version >= Version("4.37")
@@ -1180,6 +1181,85 @@ def _restore_progress_bars(were_disabled):
pass
+# Every way a cache miss reaches the caller once offline mode has skipped Transformers'
+# own "does not appear to have a file named" raise: the resolved path stays None and the
+# next line dereferences it, so the message names the None and never the cache. Same set
+# the Studio training worker matches (studio/backend/core/training/worker.py, #7845):
+# weights come out as `endswith`, tokenizers/processors as any of the other four.
+_EMPTY_CACHE_ARTIFACTS = (
+ "'nonetype' object has no attribute 'endswith'",
+ "'nonetype' object has no attribute 'readlines'",
+ "argument should be a str or an os.pathlike object",
+ "expected str, bytes or os.pathlike object",
+ "stat: path should be string, bytes, os.pathlike or integer",
+ "can't find a vocabulary file at path 'none'",
+)
+
+
+def _empty_cache_artifact(exc):
+ """True if exc, or something it wraps, is offline mode's empty-cache artifact.
+
+ The one family of retry failure that says nothing useful.
+
+ Named positively, rather than asking "is this an OOM": every other retry
+ failure is real news and must reach the user, and enumerating the ways an
+ accelerator spells OOM cannot be complete (accelerate re-raises it as a bare
+ RuntimeError, XPU has its own class). Asking for the artifact instead is
+ complete by construction.
+ """
+ seen = set()
+ while exc is not None and id(exc) not in seen:
+ seen.add(id(exc))
+ text = str(exc).lower()
+ # Gate on the None: the same TypeError wording about a real path (`not 'int'`)
+ # is a caller bug, not an empty cache.
+ if ("nonetype" in text or "path 'none'" in text) and any(
+ artifact in text for artifact in _EMPTY_CACHE_ARTIFACTS
+ ):
+ return True
+ exc = exc.__cause__ or exc.__context__
+ return False
+
+
+def _release_traceback_locals(error):
+ """Drop the frame locals along an exception chain, keeping file and line.
+
+ An exception we keep past its handler keeps its frames alive, and a failed load's
+ frames still own whatever the attempt had already built, so a retained error can pin
+ a model's GPU tensors for as long as the caller holds it. Clearing the locals beats
+ dropping the traceback: the memory goes either way, but the origin stays printable,
+ which for a network failure inside `trust_remote_code` is the only clue there is.
+ """
+ seen = set()
+ while error is not None and id(error) not in seen:
+ seen.add(id(error))
+ # The frame we are running in cannot be cleared; clear_frames skips it for us.
+ _traceback.clear_frames(error.__traceback__)
+ error = error.__cause__ or error.__context__
+
+
+def _note_offline_retry(error, retry_error):
+ """Record the failed cache retry on the online error we are about to surface.
+
+ A note is the only place it can go that survives: the online error usually
+ already has a cause, and Python prints a cause INSTEAD of a context, so
+ chaining the retry on would hide it (and would cost the chain that makes the
+ online error classifiable). Notes are 3.11+; below that this is a no-op and
+ the attribute is all there is."""
+ text = f"Unsloth: retrying from the local cache also failed: {type(retry_error).__name__}: {retry_error}"
+ try:
+ error._unsloth_offline_retry_error = retry_error
+ except Exception:
+ pass
+ add_note = getattr(error, "add_note", None)
+ if add_note is None:
+ return
+ try:
+ add_note(text)
+ except Exception:
+ pass
+
+
def _offline_aware_load(fn):
"""Decide offline ONCE (local_files_only kwarg or env) and force it around the
whole load. If we started online and hit a network error, retry once forced-offline.
@@ -1201,6 +1281,12 @@ def _offline_aware_load(fn):
# (else outer layers reload the whole model again).
if not _is_offline_related_error(e) or getattr(e, "_unsloth_offline_retried", False):
raise
+ # Holding `e` holds its frames, and those frames hold the half-built model,
+ # so the collect below could not free it and a large VLM OOMed on the reload
+ # the retry exists to make. A wrapper's cause/context carries tracebacks over
+ # the SAME frames, so the whole chain has to be released, not just the top.
+ online_error = e
+ _release_traceback_locals(online_error)
# Retry OUTSIDE the except so the failed attempt's traceback (a partial model)
# is freed before reallocating, else a large VLM can OOM on the second load.
try:
@@ -1218,12 +1304,36 @@ def _offline_aware_load(fn):
with _force_hf_offline():
return fn(*args, **kwargs)
except Exception as e:
- # Tag so an enclosing _offline_aware_load skips its own redundant retry.
- try:
- e._unsloth_offline_retried = True
- except Exception:
- pass
- raise
+ # A real retry failure (corrupt checkpoint, OOM) is news and goes out as
+ # itself; only the empty-cache artifact is worth replacing.
+ if not _empty_cache_artifact(e):
+ # Tag so an enclosing _offline_aware_load skips its own redundant retry.
+ try:
+ e._unsloth_offline_retried = True
+ except Exception:
+ pass
+ raise
+ # The retry can load a whole cached model and only then trip over a missing
+ # tokenizer file, and this error outlives the call on the online one, so its
+ # frames would keep that model resident for as long as the caller holds it.
+ _release_traceback_locals(e)
+ retry_error = e
+ # Report the ONLINE error: this retry only runs because of it, and its own
+ # failure names an empty cache badly (offline mode skips Transformers'
+ # "does not appear to have a file named" raise, so the user saw
+ # `AttributeError: 'NoneType' ... 'endswith'`).
+ try:
+ online_error._unsloth_offline_retried = True
+ except Exception:
+ pass
+ # Raise OUTSIDE the handler above: inside it, Python would overwrite
+ # `__context__` with the cache miss, and that chain is often the only thing
+ # that still makes the online error classifiable as network-related.
+ if online_error.__cause__ is None and online_error.__context__ is None:
+ # No chain to lose, so chain the retry on where it also prints.
+ raise online_error from retry_error
+ _note_offline_retry(online_error, retry_error)
+ raise online_error
return _wrapper