Skip to content

Fix offline Studio training and export preflights - #7065

Closed
Imagineer99 wants to merge 4 commits into
unslothai:mainfrom
Imagineer99:fix/offline-training-export-6817-v2
Closed

Imagineer99 wants to merge 4 commits into
unslothai:mainfrom
Imagineer99:fix/offline-training-export-6817-v2

Conversation

@Imagineer99

@Imagineer99 Imagineer99 commented Jul 10, 2026 •

Copy link
Copy Markdown
Member

Summary

Fixes #6817.

This makes Studio's offline/no-internet paths avoid Hugging Face metadata calls during model selection, RAG warmup, and export:

  • skip embedding/model-size/GGUF metadata calls when HF offline env is set or the HF endpoint is unreachable
  • serve cached GGUF variants directly when metadata is unavailable
  • skip RAG warmup when offline/unreachable and force cached SentenceTransformer loads through an in-process offline window
  • wrap export commands in the same offline window so tokenizer save paths do not trigger hidden Hub metadata calls
  • preserve pre-existing HF_HUB_OFFLINE / TRANSFORMERS_OFFLINE values after offline windows

Attribution

Credit to @InfoSage05 for the original fix direction and affected call-site analysis in #6861. This PR rebuilds that approach on current main with conflict resolution, env preservation, endpoint-unreachable handling, and regression tests.

Validation

  • python3 -m py_compile studio/backend/utils/models/model_config.py studio/backend/routes/models.py studio/backend/main.py studio/backend/core/rag/embeddings.py studio/backend/core/export/worker.py
  • python -m pytest studio/backend/tests/test_offline_gguf_cache_fallback.py -q (78 passed)
  • Focused tests: 12 passed
  • Manual repro with real huggingface_hub, transformers, sentence-transformers, cached models, and HF_ENDPOINT=http://127.0.0.1:9:
    • is_embedding_model() skipped Hub metadata
    • _get_model_size_bytes() skipped HfApi.repo_info()
    • detect_gguf_model_remote() used cached GGUF immediately
    • RAG SentenceTransformer loaded cached unsloth/bge-small-en-v1.5 without HEAD retries
    • export tokenizer hidden Mistral path skipped the Hub model_info() call under the offline window

@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 mechanisms to gracefully handle Hugging Face and Transformers offline modes when the Hugging Face endpoint is unreachable. It adds helper functions and context managers to force offline windows, and integrates these checks across model exporting, RAG embeddings, model routing, and GGUF detection. Additionally, corresponding tests are added to verify offline behavior. The review feedback highlights a potential issue where an exception during context manager entry could bypass the fallback environment variable setup, and suggests wrapping the entry call in a try-except block to ensure robust fallback execution.

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 thread studio/backend/core/export/worker.py Outdated
Comment on lines 258 to 260
force_ctx = _force_hf_offline_window()
force_ctx.__enter__() # sets env + in-process flags + resets sessions
if force_ctx is None:

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.

high

If force_ctx.__enter__() raises an exception, the execution will jump directly to the outer except Exception: pass block of _offline_window_if_unreachable(). This means the fallback block if force_ctx is None: (which sets the HF_HUB_OFFLINE and TRANSFORMERS_OFFLINE environment variables to "1") will be completely skipped. Wrapping the __enter__() call in a try-except block and setting force_ctx = None on failure ensures the fallback mechanism can execute.

Suggested change
force_ctx = _force_hf_offline_window()
force_ctx.__enter__() # sets env + in-process flags + resets sessions
if force_ctx is None:
if "huggingface_hub" in sys.modules or "transformers" in sys.modules:
try:
force_ctx = _force_hf_offline_window()
force_ctx.__enter__() # sets env + in-process flags + resets sessions
except Exception:
force_ctx = None

@Imagineer99
Imagineer99 force-pushed the fix/offline-training-export-6817-v2 branch 2 times, most recently from eb28eed to 70617f0 Compare July 10, 2026 19:10
Imagineer99 added a commit to Imagineer99/unsloth that referenced this pull request Jul 23, 2026
@Imagineer99

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: fe486a10f4

ℹ️ 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 +2098 to +2103
if isinstance(e, (ConnectionError, TimeoutError)) or err_name in (
"ConnectError",
"ConnectTimeout",
"ReadTimeout",
):
break

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 Retry transient Hub connection failures

When the reachability probe succeeds but the subsequent hf_model_info call hits a one-off ConnectionError, ConnectTimeout, or ReadTimeout, this break skips the remaining retry attempts and immediately falls back to cache/None. For an uncached remote GGUF repo, ModelConfig.from_identifier() then treats that transient metadata blip as “not GGUF” and falls through to the wrong loading path, defeating the retry behavior this function still documents for transient Hub failures. Consider only short-circuiting when the pre-probe already determined the endpoint is unavailable, and otherwise keep retrying these transient exceptions.

Useful? React with 👍 / 👎.

Comment on lines +2191 to +2196
if _hf_metadata_unavailable():
logger.debug(
"Offline/unreachable HF Hub -- using cached embedding marker for %s",
model_name,
)
return _embedding_marker_in_hf_cache(model_name)

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 cached embedding metadata when offline

When the endpoint becomes unreachable after an online metadata lookup, this path bypasses _embedding_detection_cache and reclassifies solely from modules.json. Cached transformer-native embedders that are detected only from Hub tags/pipeline metadata (the settings route explicitly calls out gte-modernbert as such) then flip from is_embedding=True to False, so /config reports them as text models and training misses the embedding-model fast path even though the model is already loadable from cache. Please keep using the memoized positive when the repo has a loadable cache, while still rejecting uncached stale positives.

Useful? React with 👍 / 👎.

@Imagineer99

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: 19f2805a62

ℹ️ 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 +2098 to +2103
if isinstance(e, (ConnectionError, TimeoutError)) or err_name in (
"ConnectError",
"ConnectTimeout",
"ReadTimeout",
):
break

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 Keep retrying transient model_info timeouts

When the reachability probe succeeds but the first model_info call raises a transient request timeout such as ReadTimeout or ConnectTimeout, this new break exits the retry loop after one attempt. With no local GGUF cache, the function then falls through to return None, so ModelConfig.from_identifier can treat a GGUF-only repo as non-GGUF instead of retrying as this function's retry contract expects; continue the existing backoff for these transient errors, or only short-circuit errors proven to mean the endpoint is down.

Useful? React with 👍 / 👎.

Comment on lines +2191 to +2196
if _hf_metadata_unavailable():
logger.debug(
"Offline/unreachable HF Hub -- using cached embedding marker for %s",
model_name,
)
return _embedding_marker_in_hf_cache(model_name)

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 verified embedding cache when probe trips

When a remote embedding model was already verified online and memoized, this new unreachable-endpoint branch runs before the memo lookup and only checks for a SentenceTransformers modules.json marker. Cached transformers-native embedders such as gte-modernbert do not need that marker, so a loadable model that was previously accepted in the same session flips to False as soon as the probe reports HF unreachable, causing embedding checks/settings to reject it; use the verified memo when the repo is loadable from cache, or only bypass the memo for uncached repos.

Useful? React with 👍 / 👎.



def test_offline_window_falls_back_when_force_context_enter_fails(monkeypatch):
import transformers # noqa: F401 - ensures the in-process force path is selected

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3 Badge Skip this test when transformers is unavailable

In lightweight test environments where optional ML dependencies are not installed, this test imports transformers unconditionally while the adjacent test uses pytest.importorskip. Running this file without setup now fails with ModuleNotFoundError before exercising the fallback path; guard this import with pytest.importorskip("transformers") or stub the module so the minimal offline tests remain runnable.

Useful? React with 👍 / 👎.

@Imagineer99

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 20424c92d5

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

@Imagineer99
Imagineer99 force-pushed the fix/offline-training-export-6817-v2 branch from 98a19e8 to 04ea345 Compare July 23, 2026 17:15
@Imagineer99

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 04ea34508d

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

@Imagineer99

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: 04ea34508d

ℹ️ 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

Copy link
Copy Markdown
Member

Confirmed the export path in studio/backend/core/export/worker.py still runs _handle_export outside any offline window and _get_model_size_bytes in routes/models.py has no guard, so this direction is right. Could you take a look at Backend CI on Python 3.11, which is green on main, and rebase since the branch is currently conflicting?

@danielhanchen

Copy link
Copy Markdown
Member

Rechecked main and both gaps are still there, so the direction holds, but _hf_metadata_unavailable() adds a 1 second endpoint probe with a 5 second TTL on the normal online model-selection path, and a false negative now makes list_gguf_variants return empty instead of falling through to the Hub. Could you confirm the online cost and that behaviour, and pick up the earlier rebase plus Backend CI on Python 3.11, which is still red here and green on main?

@Imagineer99

Copy link
Copy Markdown
Member Author

Replaced by #11466, which keeps just the export fix. Main already covers the other offline checks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Offline Training and Exporting Is broken

2 participants