Repository navigation
avoid Hub metadata probe when loading tokenizers with local_files_only - #7482
danielhanchen merged 18 commits into
Conversation
…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
There was a problem hiding this comment.
💡 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".
| 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( |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| 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"), |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
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.
There was a problem hiding this comment.
💡 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 |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| return _TOKENIZER_MODEL_CACHE[source] | ||
|
|
||
| # Offline: probe the local cache instead of model_info (issue #7481). | ||
| if _env_says_offline(): |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
…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.
|
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 ( What the change actually fixes, and it is worth having
Upstream closed this properly in transformers 5.6.0 (PR #43603 adds a try/except, an lru_cache, and What it does not fixThe None of the symptoms quoted in the issue body appear in the log attached to it. The real cause of Independent confirmation from the same log: Could you drop What I pushed
What I checked that is fineNo 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 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 |
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.
|
Thanks for the detailed review and for pushing Agreed on the scope split:
Updated accordingly:
|
There was a problem hiding this comment.
💡 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]))) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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).
There was a problem hiding this comment.
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.
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.
There was a problem hiding this comment.
💡 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".
| 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") |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
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.
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.
|
@codex review |
|
Codex Review: Didn't find any major issues. Bravo. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
Problem
On transformers 4.57.2 through 5.5.4,
PreTrainedTokenizerFast.from_pretrained(repo_id, local_files_only=True)can still reachmodel_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_fastto resolve a cached snapshot viahf_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_fallbackand the last-resort tokenizer loader.unsloth/save.py: Probe the local HF cache fortokenizer.modelbefore callingHfApi.model_infowhen offline /local_files_only.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 inunsloth_zoo(check_hf_model_exists/check_local_model_existsnot consultingHF_HOME/HF_HUB_CACHEoffline). #7481 stays open for a separate zoo fix.Verification