Skip to content

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

Merged
danielhanchen merged 11 commits into
unslothai:mainfrom
danielhanchen:fix/offline-retry-masks-network-error
Aug 9, 2026
Merged

danielhanchen merged 11 commits into
unslothai:mainfrom
danielhanchen:fix/offline-retry-masks-network-error

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

What happens today

_offline_aware_load retries a failed load once with HF offline mode forced on, so a model that is already cached still loads after the network drops. That is the right behaviour. The problem is what the user sees when the cache is empty.

The retry can only succeed on what is cached, so with an empty cache it fails too. Transformers reports that failure badly: the whole "no weights found" arm in _get_resolved_checkpoint_files sits behind

if not local_files_only and not is_offline_mode():

so under offline mode nothing raises, resolved_archive_file stays None, and from_pretrained falls through to

if is_from_file and not is_sharded and checkpoint_files[0].endswith(".safetensors"):

with checkpoint_files == [None]. What surfaces is:

AttributeError: 'NoneType' object has no attribute 'endswith'

with no mention of the network anywhere in the traceback, and the real cause -- the connection error from the first attempt -- discarded. The only visible clue is that the Unsloth banner printed twice.

Hit on Kaggle loading unsloth/Qwen2.5-VL-7B-Instruct-bnb-4bit on a T4, where a dropped connection mid-download was the entire cause.

The change

The online error is what surfaces, with the offline attempt chained on as its __cause__ so the second attempt stays visible in the traceback. Its type is preserved, so a caller retrying on network errors still sees a network error rather than a new RuntimeError.

One exception. The retry loads the whole model a second time -- which is why the surrounding code collects and empties the CUDA cache first -- and a large VLM can exhaust memory there where the first attempt did not. That is the retry's own news, not a symptom of the network, so an out-of-memory failure reports itself. _out_of_memory_error walks the __cause__ / __context__ chain, since loaders usually re-raise an OOM through their own error type.

Tests

Five in tests/test_offline_loading_helpers.py:

  • the online error surfaces when the retry hits the empty-cache AttributeError, with the AttributeError kept as its cause
  • the tag that stops an enclosing _offline_aware_load from reloading travels on whichever exception actually leaves
  • a plain OOM retry reports itself
  • an OOM wrapped in a RuntimeError is still recognised
  • a successful retry is unchanged, which is the case the whole mechanism exists for

The first fails on main. 213 passed, 4 skipped across every test file that touches loader_utils.

@danielhanchen
danielhanchen requested a review from Datta0 as a code owner August 7, 2026 19:50
@danielhanchen

Copy link
Copy Markdown
Member Author

Two more instances of the error this PR makes readable, from notebooks that had never been executed before.

Running the 21 never-executed base notebooks across Colab, LFM2.5_(1.2B)-Conversational and LFM2.5_(1.2B)-Text_Completion both died with:

AttributeError: 'NoneType' object has no attribute 'endswith'

on torch 2.11.0+cu128, transformers 4.56.2, trl 0.22.2, unsloth 2026.8.8.

That is the exact shape this PR is about: the forced-offline retry runs, finds nothing cached, and Transformers under offline mode skips its own "does not appear to have a file named" raise, leaving resolved_archive_file = None. The user is left with an AttributeError from inside from_pretrained and no mention of the network.

Two things this makes concrete. First, LFM2.5_(1.2B)-Translation, a sibling notebook on the same install and the same GPU pool, passed in the same sweep, which is what a transient fetch failure looks like rather than a model or notebook problem. Second, without this PR there is no way to tell those two cases apart from the traceback alone. I could only classify them by knowing the mechanism.

To be clear about scope, since it matters for how this is reviewed: this PR does not stop the fetch from failing. It makes the failure say what it was. Both notebooks would still fail on a dropped connection, they would just fail legibly.

danielhanchen added 3 commits August 8, 2026 03:20
A dropped connection during a load triggers the forced-offline retry, which
can only succeed on what is already cached. When the cache is empty that
retry fails too, and Transformers reports it badly: under offline mode it
skips its "does not appear to have a file named" raise and falls through
with resolved_archive_file = None, so what reaches the user is

  AttributeError: 'NoneType' object has no attribute 'endswith'

from inside from_pretrained, with no mention of the network at all. Hit on
Kaggle loading unsloth/Qwen2.5-VL-7B-Instruct-bnb-4bit on a T4.

The online error is what surfaces now, with the offline attempt chained on
as its cause. Its type is preserved, so a caller retrying on network errors
still sees one. An out-of-memory retry is left alone: a second load of a
large VLM can exhaust memory where the first did not, and that is the
retry's own news rather than a symptom of the network.
@danielhanchen
danielhanchen force-pushed the fix/offline-retry-masks-network-error branch from 9972bf0 to 91e5c47 Compare August 8, 2026 03:20
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

… the cause

Four things the review found, all reproduced first.

Holding the online exception held its traceback, so the frames of the failed
load stayed reachable and the collect before the retry could not free the
half-built model. Keep the error, drop the traceback.

Selecting the retry's own error only for an OOM meant every other retry failure,
a corrupt checkpoint or a missing dependency, was replaced by the earlier network
error. Inverted: surface the online error only for offline mode's empty-cache
artifact, which is the one retry failure that says nothing. That also covers the
OOM spellings a type list cannot, since accelerate re-raises as a bare
RuntimeError and XPU has its own class.

raise ... from e overwrote the cause of an error classified as network-related
THROUGH its cause, leaving it unclassifiable. Only chain where there is no cause
to lose; the retry still arrives as __context__.
@danielhanchen

Copy link
Copy Markdown
Member Author

All four confirmed, all four fixed in e98c3adb3. Each was reproduced before being agreed with.

P1, the retry pinning the failed load. Correct, and it defeated the stated purpose of the code right above it. online_error = e keeps the exception, the exception keeps its traceback, the traceback keeps the failed loader's frames, and those frames keep the half-built model. Measured with a weakref through the real wrapper:

online_error = e            -> partial model still alive after gc: True
online_error = e.with_traceback(None) -> partial model still alive after gc: False

So the gc.collect() and empty_cache() that follow could not free it, and the second load allocated alongside the first. Fixed by keeping the error and dropping its traceback. The message is unchanged; the raise site supplies a fresh traceback.

Restricting the substitution, and the OOM spellings. Taking these together, because one answer covers both. The selection was surfaced = e if _out_of_memory_error(e) else online_error, so every non-OOM retry failure was replaced: a corrupt checkpoint found offline reported a connection error and sent the user to check their wifi. That is the same masking this PR exists to remove, one layer down.

Rather than extending the OOM list with the XPU class and a message match, I inverted the selection:

surfaced = online_error if _empty_cache_artifact(e) else e

The empty-cache artifact is the one retry failure that says nothing useful, and it has a single stable shape: forced offline, Transformers skips its own "does not appear to have a file named" raise and leaves resolved_archive_file = None, so the user sees AttributeError: 'NoneType' object has no attribute 'endswith'. Everything else is real news and now surfaces itself.

That is strictly stronger than enumerating OOM spellings. It covers the bare RuntimeError from accelerate and torch.xpu.OutOfMemoryError without naming either, and it covers the next spelling nobody has thought of. _out_of_memory_error is gone, since asking the question positively made it unnecessary. _is_oom_error in studio/backend/core/export/export.py stays as it is: it genuinely has to classify OOM, whereas this site only has to recognise one artifact.

Preserving the cause chain. Correct. raise surfaced from e overwrote __cause__, so a RuntimeError that was classifiable only through its cause stopped being classifiable at all. Now the chain is only replaced where there is nothing to lose:

if online_error.__cause__ is None:
    raise surfaced from e
raise surfaced

The retry still reaches the user in the second branch: the raise is inside the except, so implicit chaining sets __context__.

Tests. Four added, and each was proved to fail without its own fix by reverting that fix alone:

sabotage goes red
restore online_error = e test_the_failed_attempt_is_not_pinned_by_the_error_it_raised
select on OOM again test_a_real_retry_failure_is_not_replaced_by_the_network_error + test_an_oom_spelled_as_a_bare_runtimeerror_still_surfaces
always raise ... from e test_a_network_error_wrapped_in_a_runtimeerror_keeps_its_cause

85 passed with the fixes in, and the 81 that existed before are unchanged, including the two that pin the empty-cache path and the retry tag.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: 06a0ce6dd3

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 00db394363

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread unsloth/models/loader_utils.py Outdated
# A wrapper keeps its own cause/context, and those carry tracebacks over the
# SAME failed-attempt frames, so dropping only the top one still pins the
# half-built model. Clear the locals along the chain; file/line is kept.
_chained = online_error.__cause__ or online_error.__context__

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Clear both branches of the exception graph

When a loader raises an exception with an explicit cause while already handling a different exception, Python retains both a distinct __cause__ and __context__. This or traversal clears only the cause branch, while the ignored context traceback can still retain the frame containing the partial model across gc.collect() and make the offline reload OOM. The fresh evidence in the current fix is that it treats the exception graph as a single chain; traverse both branches with a visited set instead.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not reproducible. A distinct __cause__ and __context__ needs raise X from Y executed while handling some other Z; an AST scan for that shape over unsloth/ finds zero sites, and the same scan over the load path we call into (transformers hub/modeling_utils/tokenization_utils_base/configuration_utils/auto, huggingface_hub file_download/_snapshot_download, peft config) also finds zero. The two sites you would expect, loader.py:756 and 1535, raise outside their handlers, so __context__ there is None. The single-chain walk is also the standing convention in this file (_is_offline_related_error) and in the Studio classifier. The loop is a best-effort attempt to unpin the partial model, and the frames that hold it are on the chain that is walked.

danielhanchen and others added 3 commits August 9, 2026 08:54
…r's chain

Surface the online error from outside the retry's except handler, so its own
cause/context survive untouched and the cache miss is reported as a note rather
than as a chain link Python would either hide or overwrite. Also recognise the
tokenizer and processor cache-miss spellings, not just the weights one.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 27c6fa9fa1

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +1237 to +1239
add_note = getattr(error, "add_note", None)
if add_note is None:
return

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve retry details on supported pre-3.11 Python

On Python 3.9 or 3.10, which remain supported by pyproject.toml:10, exceptions have no add_note, so this return leaves an explicitly or implicitly chained online error with no visible indication that the offline retry also failed; _unsloth_offline_retry_error is merely an internal attribute and is not included in the formatted traceback. The fresh evidence after the prior visibility fix is that the new test conditionally skips the rendered-output assertion when add_note is unavailable, leaving both supported versions with the original defect.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not taking this one. What the PR promises on every supported version is that the network error, not the cache-miss artifact, is what reaches the user, and that holds on 3.9 and 3.10 unchanged; the note is extra detail on top. The only ways to make it render on pre-3.11 are to rewrite the chain, which is the thing this PR exists to stop doing, or to mutate a third-party exception's args, which changes str(e) for every caller that matches on the message, including transformers' own handlers. That is a worse trade than a missing note, and the retry error is still reachable programmatically on _unsloth_offline_retry_error. add_note is 3.11+ by PEP 678, which the docstring already states, and the test skips the rendered assertion for exactly that reason rather than to paper over a defect.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 9, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a17d66349b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

artifact in text for artifact in _EMPTY_CACHE_ARTIFACTS
):
return True
exc = exc.__cause__ or exc.__context__

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve terminal fallback failures over artifact contexts

When a meaningful fallback failure is raised while handling a cache artifact, this traversal still finds the older artifact in __context__ and replaces the terminal failure with the original network error. This occurs in vision.py's _last_resort_tokenizer: _load_pretrained_tokenizer_fast(...) runs inside the except for AutoTokenizer, so an OOM or corrupt-tokenizer error from that fallback implicitly carries the AutoTokenizer cache miss as its context; _empty_cache_artifact then returns true and hides the actionable retry failure. The classifier should not let an artifact deeper in the context chain override a meaningful terminal failure.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not taking this one, because the context walk is what makes the common case work rather than what breaks it. In _last_resort_tokenizer the fast fallback runs on the same empty cache that just made AutoTokenizer trip the artifact, and transformers ends that path in a generic OSError("Can't load tokenizer for '<repo>'...") from tokenization_utils_base (checked in 4.57.6: the bare except Exception around cached_file re-raises as that message). That OSError is not an artifact by text, so the only thing that classifies the retry correctly is the artifact sitting in its __context__. Drop the context traversal and the ordinary empty-cache retry stops surfacing the network error, which is the whole point of the PR. The hypothetical it protects against needs a cache that is missing enough for AutoTokenizer to dereference a None yet present enough for the fast loader to fail for an unrelated terminal reason; and even then the terminal error is not discarded, it rides out on _unsloth_offline_retry_error and, on 3.11+, as a note on the surfaced error. Trading the common path for that is the wrong way round.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: a17d66349b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit f0ef75e into unslothai:main Aug 9, 2026
46 of 50 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant