Skip to content

Studio: respect offline mode for RAG embedding-model checks - #7296

Closed
danielhanchen wants to merge 13 commits into
unslothai:mainfrom
danielhanchen:fix/studio-offline-embedding-minimal
Closed

danielhanchen wants to merge 13 commits into
unslothai:mainfrom
danielhanchen:fix/studio-offline-embedding-minimal

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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() called huggingface_hub.model_info() with no timeout.
  • The RAG embedder loaded SentenceTransformer without local_files_only.
  • The /settings embedding-model gate probed the Hub for module subdirs before scanning.

What this changes

  • New utils.utils.hf_env_offline() treats HF_HUB_OFFLINE or TRANSFORMERS_OFFLINE as
    offline (huggingface_hub honors only the former); 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 local cache marker on a transient error, so a dead network degrades
    gracefully instead of hanging.
  • evaluate_file_security() gains a local_only_load flag. Offline the Hub malware scan is
    unreachable, so instead of failing open it inspects the local cache and fails closed on an
    unscanned pickle weight (pytorch_model.bin and friends, plain or sharded) that has no
    inert safetensors alternative. A safetensors/gguf-only cache loads normally; nothing
    cached means nothing to load, so it is allowed.
  • The embedder (core/rag/embeddings.py) and the /settings route capture the offline state
    once, skip the network subdir probes offline, and thread local_files_only into 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

  • New studio/backend/tests/test_offline_embedding_minimal.py (41 tests): offline
    classification 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.
  • Existing suites test_file_security.py, test_embedding_model_security_gate.py,
    test_embedding_model_settings.py, test_rag_embeddings.py still pass (101 total green
    with the new file).

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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Comment on lines +330 to +342
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}",
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

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.

Suggested change
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}",
)

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.

Done in 01f0e86: blocked pickles are now reported as snapshot-relative posix paths via relative_to(snapshot).as_posix().

@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: 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".

Comment thread studio/backend/core/rag/embeddings.py Outdated
Comment on lines +193 to +196
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

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 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 👍 / 👎.

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.

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.

Comment on lines +44 to +46
_PICKLE_WEIGHT_RE = re.compile(
r"^(model|pytorch_model)(-\d+-of-\d+)?\.(bin|pt|pth|ckpt|pkl|pickle)$",
re.IGNORECASE,

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 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 👍 / 👎.

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.

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.

Comment on lines +291 to +295
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]

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 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 👍 / 👎.

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.

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.

@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: 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".

Comment on lines +291 to +295
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]

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 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 👍 / 👎.

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.

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.

Comment thread studio/backend/core/rag/embeddings.py Outdated
Comment on lines +193 to +197
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)

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 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 👍 / 👎.

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.

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.

shimmyshimmer and others added 3 commits July 21, 2026 13:50
…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.
@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: 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".

Comment thread studio/backend/core/rag/embeddings.py Outdated
Comment on lines +172 to +173
prior = os.environ.get("HF_HUB_OFFLINE")
os.environ["HF_HUB_OFFLINE"] = "1"

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 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 👍 / 👎.

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.

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.

Comment thread studio/backend/utils/utils.py Outdated
Comment on lines +55 to +57
root = os.environ.get("HF_HUB_CACHE") or os.environ.get("HUGGINGFACE_HUB_CACHE")
if root:
return Path(root)

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 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 👍 / 👎.

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.

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.

Comment thread studio/backend/utils/utils.py Outdated
Comment on lines +52 to +63
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"

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 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 👍 / 👎.

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.

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.

shimmyshimmer and others added 2 commits July 21, 2026 14:09
…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.
@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

cache_key = (model_name, hf_token)
if cache_key in _embedding_detection_cache:
return _embedding_detection_cache[cache_key]

P2 Badge Include offline state in the embedding detection cache key

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".

Comment on lines +304 to +316
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)

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 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 👍 / 👎.

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.

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.

shimmyshimmer and others added 2 commits July 21, 2026 14:21
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.
@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: 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".

Comment on lines +2130 to +2133
if hf_env_offline():
is_emb = _embedding_marker_in_hf_cache(model_name)
_embedding_detection_cache[cache_key] = is_emb
return is_emb

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 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 👍 / 👎.

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.

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.

Comment thread studio/backend/utils/utils.py Outdated
Comment on lines +65 to +74
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")

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 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 👍 / 👎.

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.

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.

shimmyshimmer and others added 2 commits July 21, 2026 14:34
…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.
@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: 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".

Comment on lines +421 to +423
# 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()

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 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 👍 / 👎.

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.

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.

Comment thread studio/backend/core/rag/embeddings.py Outdated
Comment on lines +193 to +198
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

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 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 👍 / 👎.

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.

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.

Comment thread studio/backend/routes/settings.py Outdated
Comment on lines +497 to +498
from utils.utils import hf_cache_snapshot_dir
offline_cached = local_only_load and hf_cache_snapshot_dir(model) is not None

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 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 👍 / 👎.

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.

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.

shimmyshimmer and others added 2 commits July 21, 2026 14:45
…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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 36b6881c45

ℹ️ 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 deleted the fix/studio-offline-embedding-minimal branch July 22, 2026 11:06
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