Repository navigation
Studio: respect offline mode for RAG embedding-model checks - #7296
danielhanchen wants to merge 13 commits into
Conversation
Fixes the RAG embedding path of issue unslothai#6817. Offline, the studio's embedding preflight called huggingface_hub model_info without a timeout and loaded the SentenceTransformer without local_files_only, so a DNS-dead session hung on download retries instead of using the already-cached model. - utils.utils.hf_env_offline() treats HF_HUB_OFFLINE or TRANSFORMERS_OFFLINE as offline; hf_cache_snapshot_dir() resolves the active cached snapshot from refs/main without touching the network. - is_embedding_model() classifies offline from the cached modules.json (mirroring the existing local-path check), bounds the online model_info call with a 15s timeout, and falls back to the cache marker on a transient error. - evaluate_file_security() gains local_only_load: offline it inspects the local cache and fails closed on an unscanned pickle weight that has no safetensors alternative, instead of hanging or failing open. - The embedder and the /settings route capture the offline state once, skip the network subdir probes, and thread local_files_only into the load. Adds tests/test_offline_embedding_minimal.py covering the offline classification, the fail-closed gate matrix, and the loader wiring with no network calls.
|
@codex review |
There was a problem hiding this comment.
Code Review
This pull request introduces robust offline handling for RAG embedding models to prevent network hangs when Hugging Face is unreachable. It implements offline detection of embedding models using cached metadata, bounds online metadata lookups with a 15-second timeout, and adds an offline security gate that fails closed on unscanned pickle weights unless a safe alternative (like safetensors or GGUF) is present. The feedback suggests improving the offline security gate's error reporting by using repo-relative paths instead of just base filenames to avoid ambiguity when reporting unsafe files in subdirectories.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| names = ", ".join(sorted(p.name for p in pickles)) | ||
| logger.warning( | ||
| "Blocking offline load of '%s': cached pickle weight(s) cannot be malware-scanned " | ||
| "offline and have no safetensors alternative (%s).", | ||
| model_name, | ||
| names, | ||
| ) | ||
| return FileSecurityDecision( | ||
| model_name, | ||
| True, | ||
| unsafe_files = [{"path": p.name, "level": "unscanned"} for p in pickles], | ||
| reason = f"offline; unscanned pickle weights with no safetensors alternative: {names}", | ||
| ) |
There was a problem hiding this comment.
In offline mode, reporting only the base filename (p.name) for unsafe files can be ambiguous if there are multiple files with the same name in different subdirectories (e.g., pytorch_model.bin in different module folders).
We can improve this by using the repo-relative path via p.relative_to(snapshot).as_posix(). This matches the online behavior where full repo-relative paths are returned, and adheres to the repository's preference for using .as_posix() for path string conversions.
| names = ", ".join(sorted(p.name for p in pickles)) | |
| logger.warning( | |
| "Blocking offline load of '%s': cached pickle weight(s) cannot be malware-scanned " | |
| "offline and have no safetensors alternative (%s).", | |
| model_name, | |
| names, | |
| ) | |
| return FileSecurityDecision( | |
| model_name, | |
| True, | |
| unsafe_files = [{"path": p.name, "level": "unscanned"} for p in pickles], | |
| reason = f"offline; unscanned pickle weights with no safetensors alternative: {names}", | |
| ) | |
| relative_paths = sorted(p.relative_to(snapshot).as_posix() for p in pickles) | |
| names = ", ".join(relative_paths) | |
| logger.warning( | |
| "Blocking offline load of '%s': cached pickle weight(s) cannot be malware-scanned " | |
| "offline and have no safetensors alternative (%s).", | |
| model_name, | |
| names, | |
| ) | |
| return FileSecurityDecision( | |
| model_name, | |
| True, | |
| unsafe_files = [{"path": rel_path, "level": "unscanned"} for rel_path in relative_paths], | |
| reason = f"offline; unscanned pickle weights with no safetensors alternative: {names}", | |
| ) |
There was a problem hiding this comment.
Done in 01f0e86: blocked pickles are now reported as snapshot-relative posix paths via relative_to(snapshot).as_posix().
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d696fc443b
ℹ️ 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".
| if local_only and _st_accepts_local_files_only(SentenceTransformer): | ||
| # Keep the load fully local so a TRANSFORMERS_OFFLINE-only session (which | ||
| # huggingface_hub ignores) still never reaches the network. | ||
| st_kwargs["local_files_only"] = True |
There was a problem hiding this comment.
Preserve offline mode for older SentenceTransformer releases
When only TRANSFORMERS_OFFLINE=1 is set and the installed sentence-transformers version predates its local_files_only constructor parameter, this condition is false and the subsequent constructor call has no offline flag. sentence-transformers is unpinned in pyproject.toml, so such installations are supported; its Hub download path will then ignore TRANSFORMERS_OFFLINE (as the adjacent comment notes) and can retry network/DNS requests for an uncached model. Set/propagate an offline mechanism that works for the fallback version as well, rather than silently omitting the flag.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Good catch. Fixed in 01f0e86: the offline branch now forces HF_HUB_OFFLINE around the SentenceTransformer construction (and restores it afterward), so a TRANSFORMERS_OFFLINE-only session or an older sentence-transformers without local_files_only still loads fully local.
| _PICKLE_WEIGHT_RE = re.compile( | ||
| r"^(model|pytorch_model)(-\d+-of-\d+)?\.(bin|pt|pth|ckpt|pkl|pickle)$", | ||
| re.IGNORECASE, |
There was a problem hiding this comment.
Include adapter weights in the offline pickle gate
For a cached embedding model whose Transformer module uses a PEFT adapter with adapter_model.bin and no adapter_model.safetensors, this regex finds no candidate and the offline gate permits the unscanned pickle. adapter_model.bin is a standard loadable weight name in this repository (see studio/backend/routes/models.py:271), and the online gate would block it when Hub flags it because it is a root-level .bin; offline therefore creates a security bypass precisely when the scan is unavailable. Include adapter weight names (and their shards) in the local scan.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 01f0e86: the offline pickle regex now also matches adapter_model and consolidated weights, so an adapter_model.bin with no adapter_model.safetensors is blocked offline instead of slipping through.
| if path.name.lower().endswith(".safetensors"): | ||
| dirs_with_safetensors.add(path.parent) | ||
| elif _PICKLE_WEIGHT_RE.match(path.name): | ||
| candidates.append(path) | ||
| return [p for p in candidates if p.parent not in dirs_with_safetensors] |
There was a problem hiding this comment.
Require a loadable safetensors alternative before allowing pickle
A cached pytorch_model.bin is allowed whenever any .safetensors file shares its directory, even if that file is unrelated to the base model (for example adapter_model.safetensors). The normal base-model loader does not use an adapter safetensors file as a replacement for pytorch_model.bin, so it still deserializes the unscanned pickle while this gate reports the directory as safe. Restrict the alternative check to the safetensors filenames/index that the same load root can actually select.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 01f0e86: a pickle is now suppressed only by a safetensors of its own weight family (base model.safetensors for a base pickle, adapter_model.safetensors for an adapter pickle). An unrelated safetensors in the same directory no longer masks it.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d696fc443b
ℹ️ 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".
| if path.name.lower().endswith(".safetensors"): | ||
| dirs_with_safetensors.add(path.parent) | ||
| elif _PICKLE_WEIGHT_RE.match(path.name): | ||
| candidates.append(path) | ||
| return [p for p in candidates if p.parent not in dirs_with_safetensors] |
There was a problem hiding this comment.
Require a matching safetensors alternative
When an offline snapshot contains a pickled base weight plus any unrelated *.safetensors file in the same directory, this marks the directory safe and permits the load. The actual loader can still select and deserialize pytorch_model.bin—for example, adapter_model.safetensors (or an arbitrary extra safetensors file) is not the base-model model.safetensors alternative—so a malicious cached embedding repo bypasses the new offline security gate. Restrict the exemption to the specific safe weight filename/index corresponding to the pickle weights, rather than every safetensors sibling.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Already addressed in 95419b0 (same fix as the earlier thread on this file): a pickle is now suppressed only by a safetensors of its own weight family (base model.safetensors for a base pickle, adapter_model.safetensors for an adapter pickle), so an unrelated or decoy safetensors no longer marks the directory safe.
| if local_only and _st_accepts_local_files_only(SentenceTransformer): | ||
| # Keep the load fully local so a TRANSFORMERS_OFFLINE-only session (which | ||
| # huggingface_hub ignores) still never reaches the network. | ||
| st_kwargs["local_files_only"] = True | ||
| _model = SentenceTransformer(name, **st_kwargs) |
There was a problem hiding this comment.
Preserve offline behavior for older SentenceTransformers
For supported installs with an older sentence-transformers release whose constructor lacks local_files_only, this condition silently omits the only local-only control. In a TRANSFORMERS_OFFLINE=1-only deployment (which this change explicitly says huggingface_hub ignores), an incomplete cached model can therefore still enter SentenceTransformer's Hub download path and hang on network retries—the behavior this change is intended to prevent. Enforce the equivalent Hub offline setting for this compatibility path, or require a SentenceTransformers version that supports the argument.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Already addressed in 95419b0: the offline path now forces HF_HUB_OFFLINE around the SentenceTransformer construction (restored afterward), so a TRANSFORMERS_OFFLINE-only or older sentence-transformers install stays fully local instead of entering the Hub download path.
…line load Addresses review of the offline RAG embedding path: - Force HF_HUB_OFFLINE around the SentenceTransformer load when offline, so a TRANSFORMERS_OFFLINE-only session (or an ST version predating local_files_only) still stays fully local instead of retrying the network for an uncached file. - Include adapter_model / consolidated pickles in the offline scan, and suppress a pickle only when its OWN safetensors family is present in the same directory (base model.safetensors for a base pickle, adapter_model.safetensors for an adapter pickle); an unrelated decoy safetensors no longer masks a pickle. - Report snapshot-relative posix paths for the blocked pickles.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 95419b0140
ℹ️ 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".
| prior = os.environ.get("HF_HUB_OFFLINE") | ||
| os.environ["HF_HUB_OFFLINE"] = "1" |
There was a problem hiding this comment.
Force Hub offline before importing it
When only TRANSFORMERS_OFFLINE is set, _guard_model_security() calls hf_cache_snapshot_dir() before this context, which imports huggingface_hub while HF_HUB_OFFLINE is absent. Hub versions that cache the offline setting at import time will therefore retain False; changing os.environ here is too late, and a cache miss during SentenceTransformer construction can still perform retrying network requests. Set the flag before the cache/security imports or pass local_files_only=True on supported SentenceTransformer versions.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in fe9d3ca. Confirmed HF_HUB_OFFLINE is import-frozen (constants.py folds HF_HUB_OFFLINE and TRANSFORMERS_OFFLINE at import), so the late os.environ change was ineffective. The offline load now passes per-call local_files_only=True, which snapshot_download honors independent of the frozen constant. An older ST without the arg relies on a launch-time offline env, which huggingface_hub folds into its offline mode at import.
| root = os.environ.get("HF_HUB_CACHE") or os.environ.get("HUGGINGFACE_HUB_CACHE") | ||
| if root: | ||
| return Path(root) |
There was a problem hiding this comment.
Expand Hugging Face cache environment paths
When HF_HUB_CACHE is configured with ~ or $HOME (both forms are expanded by huggingface_hub), this returns a literal, unexpanded Path, so the offline cache lookup misses the snapshot actually used by the loader. In that case _evaluate_local_only() treats the model as uncached and allows it, while SentenceTransformer resolves the real cache and may deserialize an unscanned pickle. Apply expanduser() and expandvars() before returning the cache root.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in fe9d3ca: the cache resolver now applies expanduser() and expandvars() (matching huggingface_hub), so a ~ or $VAR in HF_HUB_CACHE / HF_HOME resolves to the same directory the loader uses.
| def _hf_cache_root() -> Path: | ||
| """Local HF hub cache root, honoring ``HF_HUB_CACHE`` / ``HF_HOME`` at call time | ||
| (mirrors huggingface_hub's own resolution so it tracks a test's env override).""" | ||
| root = os.environ.get("HF_HUB_CACHE") or os.environ.get("HUGGINGFACE_HUB_CACHE") | ||
| if root: | ||
| return Path(root) | ||
| hf_home = os.environ.get("HF_HOME") | ||
| if hf_home: | ||
| return Path(hf_home) / "hub" | ||
| xdg = os.environ.get("XDG_CACHE_HOME") | ||
| base = Path(xdg) if xdg else Path.home() / ".cache" | ||
| return base / "huggingface" / "hub" |
There was a problem hiding this comment.
Inspect the SentenceTransformers cache override
When SENTENCE_TRANSFORMERS_HOME is set, SentenceTransformer(name, ...) uses that directory as its cache_folder, but this resolver only examines the Hugging Face Hub cache. The offline gate then reports “nothing cached” and allows the model, even though the loader can find and deserialize a pickle from SENTENCE_TRANSFORMERS_HOME. Check that override before the Hub cache so the security check and offline embedding classification inspect the same files as the loader.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in fe9d3ca: the resolver now also inspects SENTENCE_TRANSFORMERS_HOME (SentenceTransformer's cache_folder), first in precedence, so the gate and the offline classification see the same files the loader resolves.
…d offline force Addresses the second review round on the offline RAG embedding path: - Resolve the cache the way the loader does: expand ~ and $VARS in HF_HUB_CACHE / HF_HOME, and also inspect SENTENCE_TRANSFORMERS_HOME (SentenceTransformer's cache_folder), so the offline gate and classification see the same files the load will, instead of missing them and failing open. - Force the offline load with per-call local_files_only (honored by snapshot_download regardless of the import-frozen HF_HUB_OFFLINE), rather than a late os.environ change the frozen constant ignores. An older ST without the arg relies on a launch-time offline env, which huggingface_hub folds into its offline mode at import.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
unsloth/studio/backend/utils/models/model_config.py
Lines 2114 to 2116 in 6938853
When offline mode changes during a long-lived Studio process, this cache returns a result computed under the prior connectivity mode before reaching the new offline branch. For example, an online True for a remote-only embedding model lets /settings accept it after HF_HUB_OFFLINE=1 is set even though no cached snapshot exists and the subsequent cache-only SentenceTransformer load fails; the inverse transition similarly preserves an offline negative and skips the fresh Hub check. The neighboring audio/vision detection caches already key on effective offline mode for this reason.
ℹ️ 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".
| for path in snapshot.rglob("*"): | ||
| try: | ||
| if not path.is_file(): | ||
| continue | ||
| except OSError: | ||
| continue | ||
| name = path.name | ||
| if _BASE_SAFETENSORS_RE.match(name): | ||
| base_safetensors_dirs.add(path.parent) | ||
| elif _ADAPTER_SAFETENSORS_RE.match(name): | ||
| adapter_safetensors_dirs.add(path.parent) | ||
| elif _PICKLE_WEIGHT_RE.match(name): | ||
| pickles.append(path) |
There was a problem hiding this comment.
Scope offline pickle checks to actual ST load roots
When an otherwise valid cached SentenceTransformer repo contains an auxiliary nested pickle (for example nemo/pytorch_model.bin or an example artifact) that is not referenced by modules.json or a weight index, this full-snapshot walk adds it to pickles and the offline settings/load gate returns 403. SentenceTransformer does not deserialize arbitrary files in the snapshot, and the existing online gate deliberately excludes unreferenced subdirectory pickles, so this introduces false security blocks for offline users; restrict the local scan to the module/load roots (and indexed shards) instead of every nested file.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 76a671c: the offline scan is now scoped to the actual ST load roots (the snapshot root plus each modules.json module path, read locally), so an unreferenced nested pickle such as nemo/pytorch_model.bin no longer blocks. This matches the online gate, which excludes unreferenced subdirectory pickles.
Addresses a false-positive over-block: the offline gate walked the whole snapshot and blocked any pickle anywhere, including an unreferenced nested one (e.g. nemo/pytorch_model.bin or an example artifact) that SentenceTransformer never deserializes. Scope the scan to the actual load roots (the snapshot root plus each modules.json module path, read locally), matching the online gate which ignores unreferenced nested pickles.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1c1e28f9b9
ℹ️ 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".
| if hf_env_offline(): | ||
| is_emb = _embedding_marker_in_hf_cache(model_name) | ||
| _embedding_detection_cache[cache_key] = is_emb | ||
| return is_emb |
There was a problem hiding this comment.
Preserve offline validation for non-ST embedding models
When offline, this replaces the established metadata-based checks (which explicitly support feature-extraction models such as gte-modernbert) with a modules.json-only test. A cached transformer-native embedding model that SentenceTransformer can load but that does not ship Sentence-Transformers layout metadata will now be rejected by /settings with a 409 unless the user manually forces the save, despite having been accepted online. Retain a cache-only signal for these supported non-ST embedding repositories or avoid treating the missing marker as a definitive non-embedding result offline.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in cf507db: offline, is_embedding_model can only confirm the Sentence-Transformers layout (modules.json), and a transformers-native embedder (feature-extraction) is unverifiable without Hub metadata. The /settings save now accepts such a repo when it is already cached and loadable (SentenceTransformer can load any cached encoder) instead of the 409 that online would not raise; an uncached repo still gets the forceable 409.
| st_home = os.environ.get("SENTENCE_TRANSFORMERS_HOME") | ||
| if st_home: | ||
| roots.append(_expand_path(st_home)) | ||
| hub = os.environ.get("HF_HUB_CACHE") or os.environ.get("HUGGINGFACE_HUB_CACHE") | ||
| if hub: | ||
| roots.append(_expand_path(hub)) | ||
| hf_home = os.environ.get("HF_HOME") | ||
| if hf_home: | ||
| roots.append(_expand_path(hf_home) / "hub") | ||
| xdg = os.environ.get("XDG_CACHE_HOME") |
There was a problem hiding this comment.
Inspect only the cache root the embedder will load from
These roots are searched as fallbacks even though SENTENCE_TRANSFORMERS_HOME (or an explicit HF_HUB_CACHE) selects the single cache_folder passed to SentenceTransformer; it does not fall through to the next cache root. For example, with an empty SENTENCE_TRANSFORMERS_HOME and a valid old model under HF_HUB_CACHE, this helper marks the model available and allows it through /settings, but the offline SentenceTransformer load searches only SENTENCE_TRANSFORMERS_HOME and fails. Stop after the configured highest-precedence root instead of treating lower-priority caches as loadable fallbacks.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in cf507db: the resolver now returns the single cache root the loader actually uses (SENTENCE_TRANSFORMERS_HOME exclusively when set, else HF_HUB_CACHE, else HF_HOME/hub, else the default hub cache), rather than searching lower-precedence caches it would never fall through to.
…ached non-ST embedders Addresses the fourth review round: - Resolve the single cache root the loader actually uses (SENTENCE_TRANSFORMERS_HOME exclusively when set, else HF_HUB_CACHE then HF_HOME/hub then the default HF hub cache), instead of searching lower-precedence caches the loader would never fall through to. - Offline, is_embedding_model can only confirm the Sentence-Transformers layout (modules.json); a transformers-native embedder (feature-extraction, e.g. gte-modernbert) is unverifiable without Hub metadata. The /settings save now accepts such a repo when it is already cached and loadable rather than raising a 409 that online would not; an uncached repo still gets the forceable 409.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a92d0f6b00
ℹ️ 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".
| # Capture the offline state once: offline, both the Hub malware scan and the is-embedding | ||
| # metadata check are unreachable, so both degrade to the local cache below. | ||
| local_only_load = hf_env_offline() |
There was a problem hiding this comment.
Skip GGUF repository probing while offline
When HF_HUB_OFFLINE or TRANSFORMERS_OFFLINE is enabled and the llama-server backend is active, this flag is captured but never used to suppress the later _hf_gguf_backend_error call (settings.py:508), which invokes huggingface_hub.list_repo_files for each remote candidate. Thus saving a non-default GGUF embedding model can still perform the DNS/network operation that this change is intended to avoid, and can hang in the offline/dead-DNS scenario.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in e1771bc: the remote GGUF probe (_hf_gguf_backend_error -> list_repo_files) is now skipped when offline, so saving a non-default GGUF embedder on the llama backend cannot hang on a dead DNS. The local GGUF check still runs.
| if local_only and _st_accepts_local_files_only(SentenceTransformer): | ||
| # local_files_only forces snapshot_download to cache-only for this call, | ||
| # independent of the process-wide HF_HUB_OFFLINE (frozen at import). An older ST | ||
| # without this arg relies on a launch-time HF_HUB_OFFLINE / TRANSFORMERS_OFFLINE, | ||
| # which huggingface_hub folds into its offline mode when first imported. | ||
| st_kwargs["local_files_only"] = True |
There was a problem hiding this comment.
Enforce local-only loading for supported legacy ST versions
For installations with an older sentence-transformers release, _st_accepts_local_files_only returns false and this leaves the constructor without any cache-only argument. The project leaves sentence-transformers unpinned, so such installations are supported; with only TRANSFORMERS_OFFLINE=1 (not HF_HUB_OFFLINE), older SentenceTransformer paths call huggingface_hub directly and may still attempt network access. The fallback should explicitly enforce Hub offline mode or otherwise prevent the load from reaching the network rather than relying on TRANSFORMERS_OFFLINE being honored by the Hub client.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in e1771bc via a cleaner route: offline, a cached model is loaded from its resolved local snapshot directory (a local path never touches the Hub), so the load is offline-safe on any sentence-transformers version, including ones predating local_files_only. Uncached falls back to a cache-only repo load that fails fast.
| from utils.utils import hf_cache_snapshot_dir | ||
| offline_cached = local_only_load and hf_cache_snapshot_dir(model) is not None |
There was a problem hiding this comment.
Verify cached weights before accepting offline models
In offline mode this accepts any existing snapshot directory after metadata verification fails, but hf_cache_snapshot_dir only establishes that refs/main points to a directory; it does not establish that the snapshot has config.json, tokenizer files, or model weights. A partial cache (for example one populated only by downloading metadata) therefore returns 200 and persists the model selection, yet the subsequent cache-only SentenceTransformer load fails when RAG is used. Require the cached files needed by the selected backend before treating the model as an offline-valid override.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in e1771bc: /settings now accepts an offline model only when its cache is genuinely loadable (config plus a weight file) via hf_cache_snapshot_is_loadable, not merely a resolved refs/main; a metadata-only partial cache still gets the forceable 409.
…e before accept Addresses the fifth review round: - Skip the remote GGUF availability probe (_hf_gguf_backend_error -> list_repo_files) when offline, so saving a non-default GGUF embedding model on the llama backend cannot hang on a dead DNS. The local GGUF check still runs. - Load a cached embedder from its resolved local snapshot directory when offline, a local path that never touches the Hub, so the load is offline-safe on any sentence-transformers version (including ones predating local_files_only). Uncached falls back to a cache-only repo load that fails fast. - Accept an offline model in /settings only when its cache is genuinely loadable (config plus a weight file), not merely a resolved refs/main; a metadata-only partial cache still gets the forceable 409.
|
@codex review |
|
Codex Review: Didn't find any major issues. 👍 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". |
Summary
This addresses the RAG embedding path of #6817. When Unsloth Studio runs offline, the
embedding-model preflight made Hugging Face network calls that ignore the local cache and
the offline env flags, so a machine with no network hangs on download retries instead of
using the already-cached model:
is_embedding_model()calledhuggingface_hub.model_info()with no timeout.SentenceTransformerwithoutlocal_files_only./settingsembedding-model gate probed the Hub for module subdirs before scanning.What this changes
utils.utils.hf_env_offline()treatsHF_HUB_OFFLINEorTRANSFORMERS_OFFLINEasoffline (huggingface_hub honors only the former);
hf_cache_snapshot_dir()resolves theactive cached snapshot from
refs/mainwithout touching the network.is_embedding_model()classifies offline from the cachedmodules.json(mirroring theexisting local-path check), bounds the online
model_infocall with a 15s timeout, andfalls back to the local cache marker on a transient error, so a dead network degrades
gracefully instead of hanging.
evaluate_file_security()gains alocal_only_loadflag. Offline the Hub malware scan isunreachable, so instead of failing open it inspects the local cache and fails closed on an
unscanned pickle weight (
pytorch_model.binand friends, plain or sharded) that has noinert
safetensorsalternative. A safetensors/gguf-only cache loads normally; nothingcached means nothing to load, so it is allowed.
core/rag/embeddings.py) and the/settingsroute capture the offline stateonce, skip the network subdir probes offline, and thread
local_files_onlyinto the load(gated on the SentenceTransformer version that accepts it).
Scope
Intentionally minimal and limited to the RAG embedding path, matching the title of #7218.
This is a smaller alternative to that PR, which I am keeping open for comparison. The other
offline symptoms in #6817 (the GGUF/model-size preflight and the transformers export-tokenizer
lookup) are separate call sites and out of scope here.
Testing
studio/backend/tests/test_offline_embedding_minimal.py(41 tests): offlineclassification with no network calls, the fail-closed gate matrix (safetensors allowed,
pickle-without-safetensors blocked, pickle-with-safetensors sibling allowed, sharded pickle
blocked, gguf allowed, nothing-cached allowed, subdir cases), the online bounded-timeout and
cache-fallback paths, and the loader wiring.
test_file_security.py,test_embedding_model_security_gate.py,test_embedding_model_settings.py,test_rag_embeddings.pystill pass (101 total greenwith the new file).