Skip to content

avoid Hub metadata probe when loading tokenizers with local_files_only - #7482

Merged
danielhanchen merged 18 commits into
unslothai:mainfrom
Souravrajvi0:feat/offline-gguf-export-vlm-7481-2214
Jul 27, 2026
Merged

danielhanchen merged 18 commits into
unslothai:mainfrom
Souravrajvi0:feat/offline-gguf-export-vlm-7481-2214

Conversation

@Souravrajvi0

@Souravrajvi0 Souravrajvi0 commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Problem

On transformers 4.57.2 through 5.5.4, PreTrainedTokenizerFast.from_pretrained(repo_id, local_files_only=True) can still reach model_info() when no offline environment variable is set. That window includes 4.57.6 (pinned by Studio's single-env constraints). Loading from a Hub repo id therefore attempts network metadata even though tokenizer files are already in the local HF cache.

Upstream fixed this properly in transformers 5.6.0 (huggingface/transformers#43603). Until the supported floor moves past that, Unsloth needs to load from a resolved snapshot directory instead of the repo id.

Fix

  • unsloth/models/loader_utils.py: Add _resolve_hub_repo_local_dir, _hub_repo_or_local_path, and _load_pretrained_tokenizer_fast to resolve a cached snapshot via hf_hub_download(..., local_files_only=True) and load the tokenizer from that local path (avoids the Hub metadata probe). Defaults stay closed so the helper cannot download with backoff when called without the flag.
  • unsloth/models/vision.py: Use cached snapshot paths in _construct_vlm_processor_fallback and the last-resort tokenizer loader.
  • unsloth/save.py: Probe the local HF cache for tokenizer.model before calling HfApi.model_info when offline / local_files_only.
  • Tests: Unit coverage in tests/saving/test_offline_gguf_vlm_tokenizer_7481.py (wired into Bucket-A CI); optional real-cache integration tests gated on a populated local cache.

Scope note

This PR does not close the reporter's _tmp_model_* does not exist? failure tracked in #7481. That root cause is in unsloth_zoo (check_hf_model_exists / check_local_model_exists not consulting HF_HOME / HF_HUB_CACHE offline). #7481 stays open for a separate zoo fix.

Verification

pytest tests/saving/test_offline_gguf_vlm_tokenizer_7481.py -q

…ai#7481)

Resolve cached snapshot directories before loading PreTrainedTokenizerFast
during VLM processor fallback so transformers does not call is_base_mistral()
-> model_info() when HF_HUB_OFFLINE is set. Also probe the local cache in
_has_tokenizer_model instead of model_info when offline.

Fixes unslothai#7481

@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: 63aa532402

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +1182 to +1185
lfo = bool(local_files_only) or _env_says_offline()
if not lfo and os.path.isdir(repo_id):
return repo_id
local_dir = _resolve_hub_repo_local_dir(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Keep repo IDs for online fallback loads

When local_files_only is false and the cache is empty or partial, this still calls _resolve_hub_repo_local_dir, which downloads only the first matching candidate (usually tokenizer_config.json) and returns that snapshot directory. The vision fallback then passes this incomplete local directory to AutoImageProcessor, AutoConfig, or AutoTokenizer; because it is now a local path, Transformers cannot fetch missing processor/tokenizer files from the Hub, so affected VLMs can fail to load online. Return the repo ID unchanged for online loads and resolve a snapshot only when offline/local-only mode is active.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Already handled on the current head. _hub_repo_or_local_path short-circuits with lfo = bool(local_files_only) or _env_says_offline(); if not lfo: return repo_id, so an online load never gets routed to a partial snapshot dir. Confirmed by execution: local_files_only=False with a populated cache returns the repo id unchanged, which is what test_hub_repo_or_local_path_keeps_repo_id_online pins.

Comment thread unsloth/save.py Outdated
Comment on lines +449 to +455
if _env_says_offline():
local_dir = _resolve_hub_repo_local_dir(
source,
token = token,
local_files_only = True,
filenames = ("tokenizer.model", "tokenizer.json", "tokenizer_config.json"),
cache_dir = os.environ.get("HF_HUB_CACHE"),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Reuse the tokenizer model path resolved offline

When only TRANSFORMERS_OFFLINE=1 is set and a repo-ID tokenizer has a cached tokenizer.model, this branch locates the file but discards its path. _preserve_sentencepiece_tokenizer_assets subsequently calls hf_hub_download at lines 524–528 without local_files_only=True or the resolved cache directory, so it can still issue a Hub request and, after a network failure, silently omit the SentencePiece asset from the GGUF staging directory. Preserve and copy the resolved local file directly, or propagate local-only/cache arguments to the later download.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Addressed on the current head. _preserve_sentencepiece_tokenizer_assets now resolves through _resolve_hub_repo_cached_file(..., local_files_only = True, cache_dir = cache_dir) first, and the hf_hub_download fallback carries both local_files_only = _tokenizer_wants_local_only(tokenizer) and the same cache_dir, so the silent-omission path you describe is closed.

Comment thread unsloth/save.py Outdated
Comment on lines +457 to +460
if local_dir is not None:
has_tokenizer_model = os.path.isfile(os.path.join(local_dir, "tokenizer.model"))
_TOKENIZER_MODEL_CACHE[source] = has_tokenizer_model
return has_tokenizer_model

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 Avoid caching offline cache misses by repo ID

When an offline snapshot contains tokenizer metadata but not tokenizer.model, this stores False globally under only the repo ID. If the file is subsequently populated, or HF_HUB_CACHE is changed to another cache containing it, later saves in the same process return the stale cached result before probing the new local state and omit the SentencePiece asset. Avoid caching negative offline results, or include the resolved snapshot/cache identity in the cache key.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This was accurate against 63aa532 but no longer holds on the current head. The offline branch stopped memoising: it is if _tokenizer_wants_local_only(...): return False with no cache write, and the only entry this PR adds is the positive _TOKENIZER_MODEL_CACHE[source] = True on a hit.

I drove both of your sequences against a real models--org--name/snapshots/<sha> layout, probing with tokenizer.model absent then creating it, and separately repointing HF_HUB_CACHE at a second cache that has it. The second probe returns True in both cases; the same script on 63aa532 returned the stale False.

The one negative still stored is the online model_info result. That line is byte-identical on the merge base d72b58a35, and it memoises the Hub's own authoritative listing rather than an offline cache miss, so I left it.

Souravrajvi0 and others added 2 commits July 27, 2026 03:11
Download unsloth/gemma-3-270m-it-bnb-4bit (~430MB) and verify offline
snapshot resolution and tokenizer load with network blocked. Full unsloth
import tests remain GPU-gated.

@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: 8a0b7bb5b3

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

cache_dir = str(CACHE_ROOT / "hub"),
)
assert tok.vocab_size > 0
assert _has_tokenizer_model(SimpleNamespace(name_or_path = REPO, tokenizer = None)) is True

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 Pass the loaded tokenizer to the integration assertion

When UNSLOTH_INTEGRATION_IMPORT=1 enables this test, the assertion always fails even with a complete cache: _has_tokenizer_model first unwraps any object with a tokenizer attribute, so this SimpleNamespace becomes None and immediately returns False. Pass tok from the load above, or omit the tokenizer=None attribute, so the advertised real-cache integration test actually exercises the offline cache branch.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Correct, and the whole test was weaker than that. With the cache populated it gave 2 passed, 1 skipped on the merge base and on this branch identically, because the two non-skipped tests called hf_hub_download and PreTrainedTokenizerFast directly and imported no unsloth code at all.

Rewrote the file in 5f854f2: all three tests now go through _resolve_hub_repo_local_dir and _load_pretrained_tokenizer_fast, the SimpleNamespace you flagged is gone, and the tokenizer actually loaded is the one asserted on. The import gate moved to module level since all three need it equally.

Comment thread unsloth/save.py Outdated
return _TOKENIZER_MODEL_CACHE[source]

# Offline: probe the local cache instead of model_info (issue #7481).
if _env_says_offline():

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve explicit local-only mode for GGUF saving

When a VLM is loaded with local_files_only=True but neither offline environment variable is set, _offline_aware_load forces the environment only for the load and restores it afterward, while a successfully loaded AutoProcessor can retain the Hub repo ID in name_or_path. A later GGUF save therefore skips this branch and calls HfApi.model_info despite the user's local-only request; on a disconnected host this can delay or fail the export and cause tokenizer.model to be omitted. Persist the load's local-only state for saving or probe the local cache before any metadata request regardless of the environment variables.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed and fixed in e7b7400. I drove the real _offline_aware_load decorator over a real hub-cache snapshot that has tokenizer metadata but no tokenizer.model: the returned processor keeps the Hub repo id in name_or_path, and init_kwargs comes back as ['model_max_length', 'name_or_path', 'vocab_file'], because transformers takes local_files_only as an explicit from_pretrained parameter and never records it.

Before the fix that path made one HfApi.model_info call and then an hf_hub_download(local_files_only=False), so a session the user asked to keep local actually fetched from the Hub. After it, zero model_info calls and cache probes only.

The load now stamps its local-only mode onto both the processor and its inner tokenizer inside the forced-offline window, and _tokenizer_wants_local_only honours it. Only the explicit and env branch stamps; the network-failure retry branch is deliberately left alone. Two tests in tests/saving/test_offline_gguf_vlm_tokenizer_7481.py fail with the hunk reverted.

Worth noting the reach is wider than GGUF: _preserve_sentencepiece_tokenizer_assets is called from the patched unsloth_tokenizer_save_pretrained, so every tokenizer save after a local-only load hit this.

Souravrajvi0 and others added 4 commits July 27, 2026 03:18
…7481)

- Only rewrite Hub repo ids to cached snapshot dirs when offline
- Copy tokenizer.model from cache offline in preserve_sentencepiece
- Do not cache negative offline tokenizer.model probe results
- Add regression tests for all three review items
…othai#7481)

Always resolve tokenizer.model from the local Hub cache before calling
model_info, and skip Hub metadata when the tokenizer was loaded with
local_files_only or offline env vars. Fixes Codex review on PR unslothai#7482.
…thai#7482

Drop the two unused _env_says_offline imports that fail the Source lint
import-hoist check.

test_has_tokenizer_model_offline_skips_model_info and its local_files_only
twin set model_info.side_effect = AssertionError, but _has_tokenizer_model
wraps that call in "except Exception: return False", so the AssertionError
was swallowed and both passed on the merge base with the fix absent. Assert
model_info.call_count == 0 instead; both now fail on the base with
assert 1 == 0.

The real-cache integration tests called hf_hub_download and
PreTrainedTokenizerFast directly, so they exercised plain huggingface_hub and
passed identically on both trees. Route them through the resolver this PR
adds, and gate the file at module level since importing unsloth needs a GPU
host either way.

_resolve_hub_repo_local_dir and _resolve_hub_repo_cached_file defaulted to
local_files_only = False, so a helper named "resolve local dir" would
download with backoff retries when called without the flag. Every caller
already passes it explicitly, so default it closed.

Use tempfile.gettempdir() rather than a hardcoded /tmp, which silently
skipped both files on Windows, the platform in the bug report. Patch
socket.socket connect rather than replacing the class, which broke
isinstance checks.

Wire the unit tests into the Bucket-A CI list; Repo tests (CPU) ignores
tests/saving, so none of these ran anywhere.
@danielhanchen

Copy link
Copy Markdown
Member

Went through this in detail, on both trees, with the network hard-blocked. There is a real bug here and your change does fix it, but it is not the bug in #7481, so I want to separate the two before this lands. I have pushed the fixes described below directly to the branch (5f854f2b5).

What the change actually fixes, and it is worth having

PreTrainedTokenizerFast.from_pretrained(repo_id, local_files_only=True) still reaches model_info() on transformers 4.57.2 through 5.5.4 when no offline environment variable is set. That range includes 4.57.6, which is what studio/backend/requirements/single-env/constraints.txt pins. Driving the real code path on both trees with sockets blocked:

merge base : RAISED ConnectionError    model_info calls: 1   socket attempts: 12
this branch: LOADED OK vocab=262144    model_info calls: 0   socket attempts: 0

Upstream closed this properly in transformers 5.6.0 (PR #43603 adds a try/except, an lru_cache, and local_files_only or is_offline_mode()), so this helper becomes redundant once the supported floor moves past that. A comment naming the version window would help whoever removes it later.

What it does not fix

The is_base_mistral explanation does not hold for the reporter's setup. Their attached log shows the export subprocess running transformers 5.5.0, because Studio routes gemma-4 to the tier-550 venv, and 5.5.0 already has the if is_offline_mode(): _is_local = True guard that short-circuits before is_base_mistral is reached. Grepping the log attached to the issue:

transformers 5.5.0        4
is_base_mistral           0
model_info                0
OfflineModeIsEnabled      0
"fallback returned None"  0
"weirdly not loaded"      0

None of the symptoms quoted in the issue body appear in the log attached to it.

The real cause of _tmp_model_* does not exist? is in unsloth_zoo. check_hf_model_exists (saving_utils.py:4415-4421) has a bare except: return False, and check_local_model_exists never consults HF_HOME or HF_HUB_CACHE. Offline, determine_base_model_source therefore returns (None, ...), and merge_and_overwrite_lora hits warnings.warn(...) + return None at saving_utils.py:2924-2926, before prepare_saving ever creates the output directory. Studio then swallows the warning, since worker.py:521,531 set PYTHONWARNINGS=ignore and warnings.filterwarnings("ignore").

Independent confirmation from the same log: _get_hf_cache_dir() prints Found HuggingFace hub cache directory: ... unconditionally. That line is present in the successful online run at line 111 and absent from the failing offline run at line 211, so execution never reached prepare_saving.

Could you drop Fixes #7481 from the description so the issue stays open, and retitle to what this actually does, something like "avoid the Hub metadata probe when loading tokenizers with local_files_only".

What I pushed

  1. Source lint was red. _env_says_offline was imported at save.py:57 and save.py:3842 and used nowhere, which fails the "Import-hoist / alias-rename safety" step. Removing both lines takes verify_import_hoist.py from 1 blocker to OVERALL: PASS.

  2. Two tests were false greens. test_has_tokenizer_model_offline_skips_model_info and its local_files_only twin set model_info.side_effect = AssertionError(...), but _has_tokenizer_model wraps that call in except Exception: return False. The AssertionError was swallowed, so assert ... is False passed either way, and both passed on the merge base with the fix entirely absent. They now assert model_info.call_count == 0. On the merge base they fail with assert 1 == 0, which is the behaviour you wanted to pin. The file now goes 10 passed on this branch, 10 failed on the base.

  3. The real-cache integration tests proved nothing. With the cache populated they gave 2 passed, 1 skipped on the merge base and on this branch, identically, because the two non-skipped tests called hf_hub_download and PreTrainedTokenizerFast directly and imported no unsloth code. Assertions like assert "/" not in Path(str(snap)).name are unconditionally true. They now go through _resolve_hub_repo_local_dir and _load_pretrained_tokenizer_fast, and the import gate moved to module level since all three need it equally.

  4. _resolve_hub_repo_local_dir and _resolve_hub_repo_cached_file defaulted to local_files_only = False. With no network that is five filenames each retried five times with exponential backoff, roughly two minutes of hangs from a function named "resolve local dir". Every caller already passes the flag explicitly, so I defaulted it closed.

  5. /tmp/hf_offline_test_cache was hardcoded in the integration test and the runner. On Windows that resolves to C:\tmp\..., so both silently skipped on the platform in the bug report. Now tempfile.gettempdir().

  6. _block_network did monkeypatch.setattr(socket, "socket", _guard), replacing the class with a function, which breaks any isinstance(x, socket.socket) in the stack under test. Patches socket.socket.connect now.

  7. None of the three files ran anywhere. Repo tests (CPU) uses --ignore=tests/saving, and the Bucket-A step in consolidated-tests-ci.yml enumerates a fixed list that did not include them. The unit file is now in that list, in both jobs. The integration file stays out, since it needs a populated real cache.

  8. Added the AGPL-3.0 header to the three new files, matching the form used by the other tests/saving files added this month.

What I checked that is fine

No regressions: 232 existing saving and offline tests, outcomes captured per test name and diffed between merge base and branch, identical on both. The online path is preserved by the if not lfo: return repo_id short-circuit. Edge cases fail closed correctly, with a missing snapshot and dangling symlinks over pruned blobs both falling back to the repo id with zero network attempts. The Windows cache layout works, since the code only takes os.path.dirname() of whatever hf_hub_download returns and never assumes symlinks or touches blobs/. Revision selection follows refs/main correctly with two revisions cached. No token leakage to non-Hub hosts.

Two things I could not test: the reporter's exact model, which needs transformers 5.5.0 in a tier venv on a Windows RTX 5090, so I substituted unsloth/gemma-3-270m-it (same 262144 vocab, same > 100000 gate); and a real end-to-end GGUF export, which needs llama.cpp plus merged weights. I validated the tokenizer resolution layer only. I also did not run on Windows itself; the no-symlink cache layout was simulated with real file copies on Linux.

Name the version range where from_pretrained still probes model_info under
local_files_only, and point at the 5.6.0 upstream fix so the helper can be
removed once the supported floor moves past it.
@Souravrajvi0 Souravrajvi0 changed the title fix: keep offline GGUF export off the Hub for VLM tokenizers (#7481) avoid Hub metadata probe when loading tokenizers with local_files_only Jul 27, 2026
@Souravrajvi0

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed review and for pushing 5f854f2b5 — pulled and incorporated.

Agreed on the scope split:

Updated accordingly:

  • Retitled to match what this actually does
  • Dropped Fixes #7481 from the description so the issue stays open
  • Added a short comment naming the transformers version window so the helper can be removed later (f067df239)

@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: f067df239d

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

"tests/saving/test_offline_gguf_real_cache_integration.py",
"-q",
]
raise SystemExit(subprocess.call(cmd, cwd = str(Path(__file__).resolve().parents[2])))

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 Enable real-cache tests in the integration runner

When the documented python tests/saving/run_offline_gguf_integration.py command is run without a preexisting UNSLOTH_INTEGRATION_IMPORT=1, this subprocess inherits no such variable, while test_offline_gguf_real_cache_integration.py marks every test skipped unless it is set. The runner therefore downloads the real model but reports success after executing only the fake-cache suite, so it never performs the integration verification it advertises; pass the gate variable in the subprocess environment.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in the latest commit: run_tests() now copies the env and sets UNSLOTH_INTEGRATION_IMPORT=1 for the pytest subprocess, so the real-cache suite is no longer silently skipped when using the documented runner. Still requires a host that can import unsloth (GPU).

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Right, and I made that worse before fixing it. Moving the gate to module level in 5f854f2 took the file from two useless tests running to all three skipping, so the runner downloaded the model and then verified nothing.

Fixed in e7b7400: run_tests now copies the environment and sets UNSLOTH_INTEGRATION_IMPORT=1 for the subprocess, with a comment saying why.

Souravrajvi0 and others added 4 commits July 27, 2026 08:55
Pass UNSLOTH_INTEGRATION_IMPORT=1 into the pytest subprocess so the
documented runner actually executes the real-cache tests instead of
reporting success after only the fake-cache unit file runs.
Document that the runner sets the gate itself and still needs a host
that can import unsloth.
transformers takes local_files_only as an explicit from_pretrained parameter,
so it never lands in tokenizer.init_kwargs, and _offline_aware_load restores
HF_HUB_OFFLINE / TRANSFORMERS_OFFLINE as soon as the load window closes. A VLM
loaded with local_files_only = True but no offline env var therefore came back
with the Hub repo id in name_or_path and nothing recording the request, so
_tokenizer_wants_local_only returned False on the later save and
_has_tokenizer_model fell through to HfApi.model_info - and then
_preserve_sentencepiece_tokenizer_assets fetched tokenizer.model from the Hub
with local_files_only = False. On a disconnected host that is a network wait
before the export gives up.

Stamp the load's local-only mode onto the returned processor and its tokenizer
inside the forced-offline window, and honour that stamp in
_tokenizer_wants_local_only, so the save path inherits the load's contract.

Verified against a real hub-cache layout whose snapshot has tokenizer metadata
but no tokenizer.model: before, one model_info call plus an hf_hub_download with
local_files_only = False; after, zero model_info calls and cache probes only.

Two tests added to tests/saving/test_offline_gguf_vlm_tokenizer_7481.py; both
fail with the loader_utils hunk reverted and pass with it in place.

@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: e7b7400dee

ℹ️ 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/save.py Outdated
Comment on lines +454 to +458
cache_dir = os.environ.get("HF_HUB_CACHE")
if not cache_dir:
hf_home = os.environ.get("HF_HOME")
if hf_home:
cache_dir = os.path.join(hf_home, "hub")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Retain the custom cache directory for offline saves

When a VLM is loaded with local_files_only=True and a custom cache_dir, but neither HF_HOME nor HF_HUB_CACHE points there, a successful AutoProcessor load can retain the Hub repo ID as name_or_path. The new stamp preserves only the local-only boolean, while this save path probes only environment-derived/default caches; after that miss, _tokenizer_wants_local_only returns true and _has_tokenizer_model returns false, so a cached tokenizer.model in the caller's custom cache is omitted from the GGUF staging directory. Persist the load's cache directory alongside the local-only marker or resolve and retain the actual snapshot path.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Correct, and it is a gap in the stamp I added in e7b7400: I preserved the boolean and not the cache. Fixed in 0d6b540.

FastBaseModel.from_pretrained threads cache_dir all the way down (vision.py:561), so a caller-supplied cache is reachable, and both sites in save.py derived theirs from HF_HUB_CACHE or HF_HOME only. Worse, my stamp made it fail closed: before it, the miss fell through to model_info and the later hf_hub_download could still fetch the asset; after it, _tokenizer_wants_local_only returned true and the file was dropped silently.

The load now stamps its cache_dir next to the local-only marker, and both save sites prefer it. The negative control reverts save.py alone, with _tokenizer_cache_dir still present, so the test reddens on behaviour rather than on a missing symbol: assert False is True. 13 passed with the fix.

danielhanchen and others added 2 commits July 27, 2026 09:43
The local-only stamp added in e7b7400 preserved only the boolean. Saving
still derived its cache from HF_HUB_CACHE or HF_HOME, which does not see a
caller-supplied cache_dir, and FastBaseModel.from_pretrained threads one all
the way down. So a local_files_only load against a custom cache missed on the
probe, and the stamp then stopped the Hub fallback that used to cover it, and
tokenizer.model was silently left out of the GGUF staging directory.

Stamp the cache_dir alongside the local-only marker and prefer it at both
sites in save.py that derive one from the environment. Reverting save.py
alone, with the helper still present, fails the new test on behaviour.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Jul 27, 2026
Brings the branch up to date with main, which clears the stale Source lint
blocker inherited from unslothai#7476 by taking studio/backend/utils/hardware/__init__.py
out of this PR's changed-file set.

pytest was imported in the new test file and never used, which the
import-hoist check flags in its own right.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 8e4857f25b

ℹ️ 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 8b9ee5f into unslothai:main Jul 27, 2026
47 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.

2 participants