Repository navigation
Studio: restore cached models hidden by a dangling HF ref, and stop auto-load downloading after a failed load (#7374) - #7375
Conversation
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f367830b30
ℹ️ 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".
| await loadAutoLoadCandidate({ | ||
| id: model.id, | ||
| kind: "model", | ||
| ggufVariant: null, | ||
| maxSeqLength: 4096, |
There was a problem hiding this comment.
Catch failed local auto-loads before trying the next candidate
When a local candidate passes validation but /api/inference/load rejects (for example because a custom folder is stale, unsupported, or OOMs), this await propagates out of tryAutoLoadLocalModels and the outer catch returns loaded: false, so later local models are never tried. The cached GGUF/safetensors loops catch per candidate and continue; the new local loop should do the same or one bad local entry blocks auto-loading any valid model after it.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and fixed in ea012cf. Reproduced by running the real autoLoadSmallestModel from f367830 over an inventory of [/custom/broken-model (whose /api/inference/load rejects), /custom/good-model]: only /custom/broken-model was attempted and the sweep returned loaded=false. loadAutoLoadCandidate awaits loadModel with no guard of its own, so the rejection unwound to the outer catch. The local loop now carries the same per-candidate try/catch the cached loops use, and the same input attempts both and loads /custom/good-model.
| if ( | ||
| await tryAutoLoadLocalModels( | ||
| localModels, |
There was a problem hiding this comment.
Prefer local GGUFs before cached safetensors
Because this new local-model block runs only after the cached safetensors loop above, a user who has both a downloaded HF safetensors repo and a custom-folder/LM Studio GGUF will still auto-load the safetensors model first. The new preference order documented for this auto-load path says local models should be tried before cached safetensors, so this block needs to move ahead of the safetensors fallback to make custom GGUFs win in that common mixed-cache case.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, fixed in bf7d6d7. The docstring this PR added on autoLoadSmallestModel states the order as last-used, then HF-cache GGUF, then custom-folder / LM Studio / models-dir locals, then cached safetensors, and the code ran the local sweep after the safetensors loop instead. Reproduced with one cached safetensors repo plus one custom-folder GGUF: head loaded org/cached-st, it now loads /custom/MyLocal-GGUF. A registered scan folder is a deliberate choice while an HF cache entry is a byproduct of any past download, so the locals win. The HF-cache GGUF tier still runs first, and a local candidate that fails to load still falls through to the safetensors loop.
| lastLoaded | ||
| ? { | ||
| id: lastLoaded.id, | ||
| kind: lastLoaded.kind, | ||
| ggufVariant: lastLoaded.ggufVariant, |
There was a problem hiding this comment.
Honor last-used local models before cached fallbacks
Passing lastLoaded into the local lookup only here makes a remembered custom-folder or LM Studio model lose to every cached HF GGUF and safetensors candidate processed above. After a successful local auto-load records an absolute-path lastLoaded, the next chat still loads some cached repo first if one exists, despite the documented “last-used model” preference; handle local lastLoaded before the cache-size fallbacks or move this preferred lookup to the initial last-used branch.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and fixed in ea012cf. Reproduced against f367830 with lastLoaded = /custom/MyLocal-GGUF (Q4_K_M) plus one cached repo org/tiny-GGUF: the remembered-local lookup only ran after the smallest-first cascade, so org/tiny-GGUF Q2_K won. tryAutoLoadRememberedLocalModel now runs inside the lastLoaded branch, ahead of the cascade, and the same input loads /custom/MyLocal-GGUF Q4_K_M.
Testing noteThis fix was not end-to-end tested in the cloud agent environment — only Requesting retest on Ubuntu (ideally matching #7374):
Expected after this PR:
If retest fails, please share:
@TheAlex25 — would you be able to retest on your Yoga Pro 9 setup when you have a chance? Thanks! |
How do I retry this? Unsloth has not released a new official update version. Not a dev here. By SSD, I meant the internal one on my laptop. The hard drive. I did not mean external, but if you add external drive support, that would be a bonus. |
|
Thanks for clarifying, @TheAlex25 — that's really helpful. On the SSD wording: sorry for the confusion. I didn't mean you need an external drive. "Custom Folders" is just Unsloth's way of pointing at any folder on your machine where GGUFs live — internal laptop storage included. If your Gemma files are on your main drive, that's exactly what this fix is meant to cover. How to retest (no dev setup needed): you're right that you can't test this from a normal Unsloth update yet — this is still an open PR and hasn't shipped in an official release. Once it's merged and included in a new build, retesting is just:
Expected: Studio should load your local Gemma instead of showing "Downloading a small model… No downloaded models found. Fetching Qwen3.5-4B-MTP…". No coding or branch checkout required on your side — just the normal app once the fix lands in a release. I'll ping you here when it's merged so you know when it's worth trying again. One quick question while we're here: in your current setup (v0.1.501-beta), is the Gemma folder already added under Custom Folders, and does Gemma appear in the picker before you hit send? That'll help confirm we're fixing the right path-matching case for your Yoga Pro 9 setup. Thanks again for reporting #7374 and for being willing to retest. |
f367830 to
e4d8398
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ab3736afe4
ℹ️ 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".
| return ( | ||
| model.source === "custom" || | ||
| model.source === "models_dir" || | ||
| model.source === "lmstudio" | ||
| ); |
There was a problem hiding this comment.
Exclude adapters from local auto-load
When a custom scan folder contains a LoRA adapter directory (adapter_config.json plus adapter weights), /api/models/local reports it as a local custom/models_dir row without a GGUF hint, so this source-only filter admits it and the later non-GGUF path calls /api/inference/load as a normal model. The backend auto-detects local LoRAs and can resolve the adapter's base from Hugging Face during FastLanguageModel.from_pretrained(config.path), so a background chat auto-load can still fetch Hub weights even though this change removed the explicit Qwen fallback; filter out adapter/unknown rows or require a complete base model before auto-loading.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, fixed in bf7d6d7. Confirmed both halves: _scan_models_dir admits an adapter_config.json-only directory (its has_config check covers adapter_config.json) and returns it with model_format=null, so the source-only filter takes it; the worker then reads base_model_name_or_path and resolves the base, which a probe on a stub adapter returned as unsloth/Qwen3-4B. /api/inference/validate already reports is_lora from ModelConfig, which auto-detects a local adapter, and canAutoLoad already calls validate for every candidate on this path, so the gate now refuses there before /load. That covers custom, LM Studio, models_dir and a cached adapter repo in one place. It is a skip rather than a failure, so it leaves blockedByTrustRemoteCode and hadNonTrustFailure untouched and the sweep moves to the next candidate; explicit picks still load adapters.
| return loadAutoLoadCandidate({ | ||
| id: model.id, | ||
| kind: "gguf", | ||
| ggufVariant: null, |
There was a problem hiding this comment.
Remember direct GGUF auto-loads
When a standalone .gguf from models_dir, LM Studio, or a custom folder succeeds through this branch, loadAutoLoadCandidate later records it with kind: "gguf" and this null variant; recordLastLocalModelLoad drops GGUF records without a non-empty variant. That means direct-file auto-loads are never remembered, so the next no-model chat falls back to cache/size order instead of the last-used local model; store a direct-file key or allow null variants for direct GGUFs.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and fixed in 9c14d80. Reproduced against ab3736a with a single /custom/qwen3-4b-Q4_K_M.gguf in a custom folder: recordLastLocalModelLoad returned early on the null variant and nothing was stored, so the next chat fell back to size order. Both recordLastLocalModelLoad and readLastLocalModelLoad now allow a null variant when isDirectGgufPath(id), and the same input stores the direct-file key.
09db1dc to
9c14d80
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9c14d8020c
ℹ️ 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".
| const name = (model: LocalModelInfo) => | ||
| model.model_id ?? model.display_name ?? model.id; | ||
| return [...models].sort((a, b) => { | ||
| const updatedDiff = (b.updated_at ?? 0) - (a.updated_at ?? 0); |
There was a problem hiding this comment.
Choose the smallest local GGUF before loading
When a custom folder or LM Studio directory contains several local GGUF models, this mtime sort decides which model is attempted first; tryAutoLoadLocalGgufModel then only picks the smallest variant inside that one folder. A newly copied large model can therefore be loaded before an older small model and hit OOM/the attempt cap, even though this auto-load path advertises selecting the smallest downloaded model. Consider ordering local GGUF candidates by their smallest downloaded variant size before attempting loads.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Leaving this one. The smallest-first contract this path documents is per repo, the smallest downloaded quant inside the chosen folder, and tryAutoLoadLocalGgufModel honors it. Across local folders the order is deliberately mtime-desc so auto-load picks what the picker shows first (collect_local_models sorts the inventory the same way), which is what #7374 asked for: the reporter wanted his 26B Gemma loaded, not the smallest thing on the disk. LocalModelInfo also carries no size, so ordering by size would need a listGgufVariants round trip for every candidate before any load. A candidate that does not load is caught per candidate and the sweep continues, so a large one does not block a valid model behind it.
Thank you. My Gemma-4-26B-A4B is located in the following path. I will use John Doe as my name in the path: /home/john-doe/.cache/huggingface/hub/models--unsloth--gemma-4-26B-A4B-it-qat-GGUF |
Thank you. My Gemma-4-26B-A4B is located in the following path. I will use John Doe as my name in the path. I have no idea why downloaded models are in .cache instead of under /home/john-doe/.unsloth/, but I am not a dev. And I also have no idea why it is dot cache instead of cache. Must be Ubuntu's hidden folder. /home/john-doe/.cache/huggingface/hub/models--unsloth--gemma-4-26B-A4B-it-qat-GGUF |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2a50616457
ℹ️ 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".
| const remembered = findLocalModel( | ||
| models.filter(isAutoLoadLocalModel), | ||
| preferred.id, | ||
| ); |
There was a problem hiding this comment.
Record explicitly loaded local models
When a user explicitly selects a custom-folder, LM Studio, or models_dir model, its modelId is an absolute path, and the successful-load path in use-chat-model-runtime.ts:1083-1099 excludes every isLocalModelPath(modelId) from recordLastLocalModelLoad. Consequently readLastLocalModelLoad() can never supply that manually selected model to this new lookup; after an unload or restart, auto-load chooses a cached or mtime-sorted fallback rather than the user's actual last-used local model. Record trusted inventory-based local selections while continuing to exclude native-token file picks.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Accurate reading of the code, but not a change for this PR. The !isLocalModelPath(modelId) exclusion is pre-existing, added in 86602a5 (#6966), and this PR does not touch that path. The new lookup is not unreachable either: loadAutoLoadCandidate calls recordLastLocalModelLoad with candidate.id and no such exclusion, so an auto-loaded custom-folder or LM Studio model is remembered by absolute path and is picked up on the next chat (verified in the traces for the two items above, where the stored key is /custom/MyLocal-GGUF and /custom/qwen3-4b-Q4_K_M.gguf). Widening what the explicit picker records is a separate behaviour change to the manual load path.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bf7d6d7f6a
ℹ️ 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".
| const updatedDiff = (b.updated_at ?? 0) - (a.updated_at ?? 0); | ||
| if (updatedDiff !== 0) { | ||
| return updatedDiff; | ||
| } | ||
| return name(a).localeCompare(name(b)); |
There was a problem hiding this comment.
Sort local candidates by load size before recency
When several custom-folder, LM Studio, or models-dir entries exist, this comparator tries the most recently modified models rather than the smallest loadable model. If the three newest models fail during loading—for example because they exceed available memory—the MAX_AUTO_LOAD_ATTEMPTS cap is exhausted before an older, smaller model is reached, and chat reports that no model is loaded despite a usable model being present. The backend already exposes size_bytes for local inventory rows (studio/backend/hub/schemas/inventory.py), so the sweep should prioritize the selected variant/model size and use recency only as a fallback.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Leaving this one, same call as on the earlier round. size_bytes does reach the client on the wire, so that correction is fair, but it does not mean what the ordering would need: for a GGUF folder row _classify_local_path sets size_bytes = _sum_file_sizes(gguf_files), the sum of every downloaded quant. A folder holding Q2_K 1.2 GB plus Q8_0 8 GB therefore sorts at 9.2 GB, behind a folder holding a single 4 GB Q4_K_M, even though tryAutoLoadLocalGgufModel would load the 1.2 GB Q2_K out of it. Ordering by the smallest loadable artifact still needs a listGgufVariants round trip per candidate before any load. The ordering is also deliberate rather than incidental: #7374 is a report that auto-load fetched a small Qwen3.5-4B instead of the reporter's 26B Gemma sitting on his SSD, so mtime-desc (the same order collect_local_models returns and the picker shows) is the requested behaviour and smallest-first across folders would reintroduce it. On the attempt cap, a candidate that fails is caught per candidate and per variant as of 7265083 and the sweep continues, so a large model does not block a valid one behind it.
| if (model.id.toLowerCase() === normalized) { | ||
| return true; | ||
| } | ||
| if (model.path.toLowerCase() === normalized) { | ||
| return true; |
There was a problem hiding this comment.
Preserve case when matching local filesystem IDs
On case-sensitive hosts, two local checkpoints can legitimately have paths such as /models/Foo and /models/foo, but lowercasing both id and path makes the remembered-model lookup return whichever row appears first. In that situation auto-load can silently load the wrong weights; local filesystem identifiers should be matched exactly (while repository-style model_id values can remain case-insensitive).
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Leaving this one. The read of the code is right, findLocalModel(inventory, '/models/foo') does return the /models/Foo row when both exist, but it needs two checkpoints in one scan folder whose absolute paths differ only in case, which only exists on a case-sensitive host and is not something a real layout produces. On that host it also cannot mislead in practice: the only writer of a local id is recordLastLocalModelLoad(candidate.id) from loadAutoLoadCandidate, which stores input.id.trim() verbatim from the inventory row, and the next session rebuilds that row from the same scanner, so the stored spelling is byte-identical. The fold is what carries the case-insensitive hosts, where a scan folder re-registered as C:\Models vs c:\models is the same directory and a collision cannot exist, so dropping it there would break the remembered-model lookup this PR just fixed. Kept as is.
| } catch { | ||
| hadNonTrustFailure = true; | ||
| skippedAutoLoadCandidates.add( | ||
| autoLoadCandidateKey("gguf", model.id, preferredVariant), | ||
| ); |
There was a problem hiding this comment.
Continue after a failed local GGUF variant
When loading one downloaded variant throws—for example because the smallest quant is corrupt or unsupported—the catch surrounds the entire variantQueue loop, so the remaining valid variants are never attempted. It also records preferredVariant rather than the variant that actually failed; when there is no preferred variant, the later local sweep does not recognize the failed quant as skipped and can retry it, consuming another slot from the three-attempt budget.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and fixed in 7265083. Reproduced against bf7d6d7 by running the real tryAutoLoadLocalGgufModel over one custom folder holding a downloaded Q2_K and Q4_K_M where /api/inference/load rejects for Q2_K: attempted was [Q2_K] and the call returned loaded=false, because the throw unwound past the whole variantQueue loop to the function-level catch and Q4_K_M was never tried. The second half reproduces too: the recorded key was gguf:/custom/myrepo-gguf: (preferredVariant was undefined) while the per-variant lookup asks for gguf:/custom/myrepo-gguf:q2_k, so a second visit re-attempted Q2_K and spent another of the three attempts. The load call now carries the same per-candidate try/catch tryAutoLoadLocalModels uses and records autoLoadCandidateKey(gguf, model.id, variant.quant), so the same input attempts [Q2_K, Q4_K_M] and loads Q4_K_M, and the second visit skips Q2_K. The outer catch stays for a listGgufVariants failure, where no single variant is at fault. Covered by test_a_failed_local_gguf_variant_does_not_abort_the_rest_of_the_folder, test_a_failed_local_gguf_variant_is_remembered_by_its_own_quant, and test_a_preferred_local_gguf_variant_still_leads_and_falls_back.
| const [ggufRepos, modelRepos, localInventory] = await Promise.all([ | ||
| listCachedGguf().catch(() => []), | ||
| listCachedModels().catch(() => []), | ||
| listLocalModels().catch(() => ({ models: [] as LocalModelInfo[] })), |
There was a problem hiding this comment.
Avoid blocking cached auto-load on the full local scan
When a user has a slow, disconnected, or very large custom-folder drive, this Promise.all waits for /api/models/local to finish scanning every configured source before it even tries an already-known cached GGUF or safetensors model. Because auto-load is on the first-message critical path and the local inventory request has no timeout or cancellation here, an unrelated external folder can make chat appear hung even though a cached model is immediately available; defer or independently await the inventory only when the cached tiers do not succeed.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Leaving this one. All three requests are already concurrent in that Promise.all, so the local scan costs max(t) rather than adding to a sum, and each one carries its own .catch so a failing or absent inventory resolves to an empty list rather than stalling the cascade. Deferring it is not available here either: tryAutoLoadRememberedLocalModel(localModels, ...) runs inside the lastLoaded branch ahead of the cached cascade, which is exactly the ordering fix for the remembered-local item earlier in this review, and tryAutoLoadLocalModels(localModels) runs ahead of the cached safetensors tier per the documented order. Both need the inventory resolved before the first cached attempt, so awaiting it lazily would either restore the bug where any cached repo outranks the user's last local pick or add a second await on the same critical path. A hang with no timeout is not specific to this endpoint either, listCachedGguf and listCachedModels use the same authFetch with no timeout and predate this PR, so a request deadline belongs in authFetch rather than in this call site.
| export function isAutoLoadLocalModel(model: LocalModelInfo): boolean { | ||
| if (model.partial || isGgufCompanionPath(model.path)) { | ||
| return false; |
There was a problem hiding this comment.
Apply companion filtering only to GGUF entries
For a valid non-GGUF checkpoint whose directory is named mtp-*, MTP, or contains mmproj, this unconditional path check classifies it as a GGUF companion and removes it from auto-load entirely. The backend's canonical MTP companion predicate first requires the path to end in .gguf, so ordinary safetensors directories with these names remain valid models; gate this predicate on the entry being GGUF or make the companion matcher itself require a GGUF path.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and fixed in 7265083. Confirmed the mirror divergence: hub/utils/gguf.py is_mtp_drafter_path and core/inference/llama_cpp.py _is_companion_gguf_path both return False before any name test when the path does not end in .gguf, and the frontend helper had no such guard. Reproduced against bf7d6d7 with custom-folder rows /models/mtp-qwen3-next-80b-a3b, /models/mmproj-training-run and /models/MTP at model_format=safetensors: isAutoLoadLocalModel returned false for all three, so a real checkpoint was dropped from auto-load entirely. Gated at the call site on localModelIsGguf rather than loosening isGgufCompanionPath itself, because a companion directory row like /repo-GGUF/MTP has to stay excluded and it is not .gguf. That holds: _scan_custom_folder only emits rows whose model_format is gguf, safetensors or adapter, every companion file row ends in .gguf, and a companion subdir carries model_format=gguf, so all five negative controls (mmproj-F16.gguf, mtp-qwen3-next-Q8_0.gguf, the MTP subdir, a 00002-of-00002 tail shard and the Windows mmproj path) are still refused. Covered by test_companion_filtering_is_scoped_to_gguf_entries.
…ion filtering to GGUF rows for PR unslothai#7375
|
@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". |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bd01857728
ℹ️ 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".
| } catch { | ||
| // Fall through to the cascade. | ||
| hadNonTrustFailure = true; | ||
| return false; |
There was a problem hiding this comment.
Skip failed remembered local candidates on fallback
When the remembered entry is a standalone GGUF or non-GGUF local model and /api/inference/load throws, this catch continues without adding that candidate to skippedAutoLoadCandidates. The later local sweep therefore retries the same broken model and consumes a second slot from the three-attempt budget; with another failed cached candidate, a valid local model later in the inventory is never reached. Record the remembered candidate's key here, as the cached and directory-variant failure paths already do.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in efd8667. The catch in tryAutoLoadRememberedLocalModel set hadNonTrustFailure and returned false without recording anything, so the later sweep walked the same inventory and retried the same entry. It is reachable for a standalone GGUF because that early-return path in tryAutoLoadLocalGgufModel sits outside the inner try, so the throw escapes past the two catches that do record, and for the non-GGUF branch which has no inner catch at all. It now records the key the sweep will actually check: null variant for a standalone GGUF or a plain model, the remembered quant otherwise. Driving the real function under node, all three shapes record exactly one key and reverting the hunk reddens all three.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: efd86672b1
ℹ️ 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".
| await tryAutoLoadRememberedLocalModel(localModels, { | ||
| id: lastLoaded.id, | ||
| kind: lastLoaded.kind, | ||
| ggufVariant: lastLoaded.ggufVariant, |
There was a problem hiding this comment.
Record manual local picks before restoring them
When a user manually selects a custom-folder, LM Studio, or models-dir entry, its ID is an absolute local path, but the only manual-load recorder in use-chat-model-runtime.ts lines 1083-1099 explicitly requires !isLocalModelPath(modelId). Therefore lastLoaded never records that selection, so this new lookup cannot restore it after an unload or restart and instead restores an older cached model or chooses a local model by modification time. Allow inventory-backed local selections to be recorded while continuing to exclude expiring native-path-token selections.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 0d09d44. Evaluating the real guard from use-chat-model-runtime.ts against the real isLocalModelPath / isExternalModelId returned false for every inventory-backed local pick (custom folder, standalone .gguf, Windows path, LM Studio), so tryAutoLoadRememberedLocalModel had nothing to restore and the next start fell back to a stale cached repo. Dropped the path-shape clause only: nativePathToken already excludes the expiring native-file-picker picks, and LoRA and external ids are still excluded. The recorder was already prepared for this by the null-variant standalone-GGUF allowance in last-local-model-load.ts. Covered with a nine-case table that pins the four negative controls.
| return ( | ||
| model.model_format === "gguf" || | ||
| GGUF_REPO_SUFFIX_RE.test(name) || | ||
| GGUF_REPO_SUFFIX_RE.test(model.display_name) || | ||
| model.path.toLowerCase().endsWith(".gguf") | ||
| ); |
There was a problem hiding this comment.
Detect GGUF contents before treating local entries as safetensors
For a custom folder that is itself an HF cache, _scan_hf_cache deliberately leaves model_format unset, so a suffixless GGUF repository fails all of these checks even though its snapshot contains GGUF weights. The new local sweep then sends it through the kind: "model" path without enumerating variants or applying GGUF settings; backend detect_gguf_model selects the largest file in such a directory, while the frontend records safetensors state and a 4096-token limit. This can unexpectedly load a very large quantization and leave the runtime controls inconsistent, so classification needs to inspect the local contents or receive a reliable format hint for cached snapshots.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in d898b73. _scan_hf_cache was the only scanner never setting model_format, and a scan folder that is itself an HF cache goes through it and comes back as a custom row, so a suffixless GGUF repo had no signal left: id and path are the snapshot dir and display_name is the bare repo name. collect_local_models returned model_format=None for such a repo, and the sweep then routed it as kind model, where detect_gguf_model takes the largest .gguf rather than the smallest downloaded variant and the run is recorded as safetensors with a 4096-token cap. Inactive-cache rows are now hinted with the existing _dir_model_format helper, and the active cache is untouched since it is addressed by repo id and excluded from the local sweep. Backend tests in test_cached_gguf_routes.py, with safetensors-only, mixed-weights, and active-cache negative controls, plus a frontend contract test pinning both routing halves.
| } catch { | ||
| hadNonTrustFailure = true; | ||
| } |
There was a problem hiding this comment.
Remember failed local paths during the sweep
When a direct GGUF or non-GGUF local load throws, this catch records only hadNonTrustFailure and not the candidate key. collect_local_models intentionally retains a custom-folder row alongside an LM Studio or models-dir row for the same path, so an overlapping registered folder causes the identical broken or unsupported model to be loaded again and consume another slot in the three-attempt budget; enough duplicate failures can prevent a valid later local or cached model from being tried. Add the failed path's key here, as the directory-GGUF variant path already does.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in e0719b3. Reproduced with the real sweep over a custom row duplicating a models-dir/LM Studio row: the failing entry was loaded twice and the third slot went to the good model, so the budget was gone (attempts [AModel, AModel, ZGood]). Same for a standalone .gguf, whose load sits outside tryAutoLoadLocalGgufModel's own try. The catch now records the key the next visit checks, gguf:: for a standalone file and model:: otherwise, and the classification stays inside the try so a malformed row still cannot unwind the sweep. Guards added in tests/studio/test_autoload_local_model_selection.py, plus negative controls that a failing GGUF folder still records only its own quant and that a clean sweep blacklists nothing.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: cc0d7cd388
ℹ️ 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".
| expected = repo_cache_dir_name("model", repo_id).lower() | ||
| return local if local.parent.parent.name.lower() == expected else None |
There was a problem hiding this comment.
Restrict pinned snapshots to registered cache roots
Fresh evidence after the prior path-validation fix is that this check validates only the directory name: a local_path such as /tmp/models--org--repo/snapshots/rev is accepted for repo_id=org/repo even though /tmp is not a configured HF cache root. _repo_cache_dir_for_request() similarly adopts that directory, so an authenticated caller can still make the variants endpoint scan an arbitrary same-named tree, expose its GGUF metadata, and use it for readiness/context accounting; require the matched repo directory to descend from one of the registered cache roots.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one, and the reason is a concrete regression rather than a disagreement about the observation.
The observation is factually right: _snapshot_scope_for_request matches on the directory name only, so /tmp/models--org--repo/snapshots/rev is accepted for repo_id=org/repo. I confirmed that before deciding.
I then implemented the proposed remedy, requiring the matched directory to descend from a registered cache root, resolving both sides so a symlinked root still matched. It refused the stray tree and kept every symlink and multi-root case working. It also broke 9 tests across three files, which sent me looking for why, and the answer is that "registered cache root" is not the boundary this product actually has.
hf_cache_roots() is only the known hub caches plus the legacy and default ones. Studio additionally scans user-added folders, and it scans them for HF-shaped caches: collect_local_models calls _scan_hf_cache(folder_path, active_cache = False) on every registered scan folder, and _scan_hf_cache sets each row's id to str(snapshot.resolve()). So a user who points Studio at an external drive holding a copied cache gets rows pinned to snapshots outside every registered root. Under the restriction:
scan_folder_row_id /…/my-external-drive/models--Org--Model/snapshots/aaaa
row_is_snapshot_shaped True
pin_accepted_with_restriction None
That row's readiness and native context would silently fall back to the active cache, describing a copy the load never touches. That is a worse and more reachable defect than the one being reported.
On the reported risk itself: the endpoint is authenticated and local, a hand-crafted local_path is not input the product ever issues, and the answer it gives is not wrong, since the directory it reads is the same one a load of that pin would use. It does not meet the bar of a correctness bug reachable on legitimate input, so I have reverted the change rather than ship a real regression to close a theoretical exposure.
If the intent is to bound this, the anchor would have to be the union of the cache roots and the registered scan folders, which is a wider design change than this PR, and I would rather not fold it in here.
A root .safetensors that no shard family groups was counted as a usable payload whatever it was called, so a snapshot holding config.json and only foo.safetensors published a chattable row that transformers cannot load: it probes model.safetensors and pytorch_model.bin, never an arbitrary name. Keep the exemption for the payloads a runtime does discover, a diffusers component weight or a single-file checkpoint, and record anything else as payload nothing reaches.
Status polling clears the pin when the resident changes, but it skips that work entirely while an external provider is selected. Picking the new resident afterwards takes the re-adoption branch, which moved the checkpoint and left the old pin in place, so applying settings sent the previous model's snapshot path and reloaded it. Clear the pin there unless it names the identity being adopted.
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! 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". |
The legacy .incomplete walk asks whether a repo-wide signal describes this snapshot, and that question is per row like the three signals beside it, but this call left the format out and so judged on quants whenever any were offered. A torn quant next to whole safetensors weights therefore charged a leftover blob to the weights row and dropped can_chat from a model that loads. Pass the row's format, as the cancel marker, manifest and recovery checks already do.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: eb63afa4c2
ℹ️ 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".
| payload_snapshots = [ | ||
| snapshot | ||
| for snapshot, flags in revision_flags | ||
| if _classify_non_gguf_model_format(**flags, trusted_hf_cache_repo = False) == model_format | ||
| ] |
There was a problem hiding this comment.
Select the format from a loadable snapshot
When different revisions use different weight formats, the repo-wide flags can select a format that has no complete revision even though another format is ready. For example, an older interrupted safetensors revision plus a refs/main revision containing complete config.json and pytorch_model.bin selects safetensors here; payload_snapshots then contains only the torn safetensors revision, so the inventory pins it and marks the row partial instead of retaining the repo ID that loads the complete checkpoint. Choose the format together with a complete per-revision payload rather than fixing it from flags OR-ed across revisions.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 8d2ac37.
Reproduced with two revisions in one repo: an interrupted safetensors revision (index plus one shard of two) and a complete pytorch_model.bin revision. The repo-wide format flags are OR-ed across revisions, so the repo classified as safetensors, the pinned-snapshot list filtered down to the torn revision alone, and the row came back partial=true, can_chat=false with the load id pinned to the torn revision. The complete checkpoint sitting right beside it was never considered.
Format selection now falls back to a format that actually has a whole revision. Controls held: a repo whose only format is torn still reads torn, and a repo with two whole formats keeps its original selection.
Regression tests: test_a_torn_revision_does_not_choose_the_format_over_a_whole_one and its control test_a_repo_whose_only_format_is_torn_still_reads_as_torn.
| } | ||
| if not family_files <= named: | ||
| return True | ||
| for shard in set(weight_map.values()): |
There was a problem hiding this comment.
Validate index values before deduplicating them
When a corrupt or partially written canonical index contains a non-string, unhashable weight_map value, such as {"weight_map":{"x":[]}}, constructing this set raises TypeError instead of classifying the index as unusable. This is reachable for a root index with no recovered shards because family_files is empty, and the exception propagates through _snapshot_payload() until _scan_cached_models() skips the entire repository, hiding it instead of exposing a partial row that can be repaired or deleted. Check that every value is a nonempty string before deduplicating, or iterate without constructing a set first.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 8d2ac37.
set(weight_map.values()) raises TypeError: unhashable type: 'list' on an index whose map holds a non-string value. The exception escaped _index_cannot_serve_its_shards and propagated to _scan_cached_models, which logged Skipping cached model repo Org/Model: unhashable type: 'list' and dropped the repo entirely: a snapshot with a whole pytorch_model.bin beside the malformed index returned no rows at all.
The map is now read without hashing its values, so the malformed entry is rejected as a bad shard name instead of taking the repo down with it.
Regression test: test_an_index_whose_map_holds_a_non_string_does_not_hide_the_repo, which returns no rows before the fix.
| if not families: | ||
| if kind == "base" and suffix in payload.root_indexes: |
There was a problem hiding this comment.
Judge the canonical index before stray root shards
When a valid canonical root index points to complete shards in a subdirectory but the snapshot also contains a stale numbered shard at the root, families is nonempty and this condition bypasses the root-index result. The grouped root family is then marked unloadable because the index correctly does not name that stale file, and the snapshot is reported partial even though Transformers loads exactly the complete paths from the canonical index and ignores the stray shard. Once the canonical index exists, judge its weight_map regardless of unrelated grouped files discovered beside it.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 8d2ac37.
Reproduced with a valid canonical model.safetensors.index.json naming weights/model-00001-of-00001.safetensors, that shard present, and a stale model-00001-of-00002.safetensors left at the root. The snapshot read partial=true, can_chat=false; the same snapshot without the stale root shard read partial=false. from_pretrained opens the index and its weight_map and nothing else, so the leftover root file is never touched.
The root-index decision now runs ahead of the walk's root families, and coverage is judged only against the family the index actually names.
That alone would have flipped genuinely torn downloads to complete, since the old path caught those through the root family, so _index_cannot_serve_its_shards now also enforces the total a shard name declares: an index listing one of a set has to list the whole set. Three cases in my probe corpus depend on this and are unchanged.
Regression tests: test_a_stale_root_shard_beside_a_whole_index_does_not_tear_the_snapshot and its control test_an_index_naming_half_of_the_family_it_describes_still_reads_as_torn.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 066e565d88
ℹ️ 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".
| complete.add(quant) | ||
| elif isinstance(family, tuple): | ||
| total = family[2] | ||
| if split_groups.get(quant, {}).get(family) == set(range(1, total + 1)): |
There was a problem hiding this comment.
Avoid materializing an unbounded shard range
When a newly recovered dangling-ref snapshot contains a filename such as Model-Q4_K_M-00001-of-999999999.gguf, total comes entirely from that repository-controlled filename and this comparison allocates a set containing every integer through that value. The recovery path now runs this completeness check on repositories that scan_cache_dir previously omitted, so merely listing cached models can exhaust backend memory on a malicious or corrupt cache entry; compare the observed count/min/max against total as _shard_family_is_whole() does instead of constructing the range.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 7891481.
Reproduced against the head with a single Model-Q4_K_M-00001-of-900000000.gguf in a recovered snapshot: under a 6 GB address space cap _completed_gguf_variants raised MemoryError, while the same call on two-shard and unsplit controls returned in under 10 ms with no measurable growth. After the fix the hostile name returns complete=set() and the controls are unchanged.
_shard_family_is_whole already compares count, min and max instead of building the range, and documents this exact reasoning. Line 765 was the one call site that never adopted it, so it now calls that helper.
Regression test: test_a_shard_total_from_a_filename_is_not_materialised, with a declared total of 1000000 so it fails on a peak-allocation assertion rather than by exhausting the runner: 70 MB before the fix against an 8 MB budget. Control: test_a_whole_split_quant_is_still_complete.
# Conflicts: # tests/studio/test_model_picker_contracts.py
An index whose weight_map holds a non-string value raised TypeError out of the scan, which dropped every row for the repo and hid the model entirely. Read the map defensively instead. A canonical root index is selected and loaded for exactly what it names, so judge its contents ahead of the walk's root families: a stale numbered file it names nothing of is never opened. An index that lists one shard of a set is still torn, since a shard names its own total. Format selection now falls back to a format that has a whole revision. The repo-wide flags are OR-ed across revisions, so an interrupted safetensors attempt could hide a complete checkpoint sitting beside it. Adds 5 tests.
A split GGUF filename declares its own total, so a name such as Model-Q4_K_M-00001-of-999999999.gguf made the completeness check allocate one integer per declared shard. Recovery runs that check over repos scan_cache_dir used to drop, so listing cached models could exhaust memory on a corrupt cache entry. _shard_family_is_whole already compares count, min and max for exactly this reason; this was the one call site that never adopted it. Adds 2 tests.
|
@codex review |
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. 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". |
Fixes #7374.
What was actually wrong
The reporter's Gemma-4-26B-A4B GGUF is in the stock Hugging Face cache:
That path has always been scanned, so the earlier theory behind this PR, that the sweep could not see a model in a registered Custom Folder, does not hold. Reproducing his layout shows
/api/hub/localreturning the sameload_idas the cached-GGUF row, so widening the sweep changes nothing for him. Two separate defects produce the reported behaviour instead, and this PR fixes both.1. A dangling ref hides an intact repo from the Hub inventory
huggingface_hub.scan_cache_dirraisesCorruptedCacheExceptionfor a repo whoserefs/<branch>names a commit with nosnapshots/<commit>/directory, and drops that repo from.reposentirely, reporting it only in.warnings._compute_all_hf_cache_scansreads.repos, so the repo silently disappears from/api/hub/cached-ggufwith a 200 and an empty list.The model picker walks directories directly, so it keeps listing the model. That is exactly the contradiction in the issue: the model is present and chattable, while auto-load reports there is nothing downloaded.
Studio can create this state itself. A metadata probe that 404s writes
.no_exist/<HEAD>/andrefs/mainat the live upstream HEAD without materialising that snapshot, so any repo re-uploaded upstream since it was downloaded goes invisible. Measured on one cache:/api/hub/cached-ggufscan_cache_dir/api/models/localcan_chat=True/api/hub/gguf-variantsUD-Q4_K_XL,downloaded=True_prune_dangling_hf_cache_refsremoves only refs whose commit has no snapshot on disk, then rescans once. Removing such a ref is lossless: it already resolves to nothing, andhuggingface_hubrewrites it on the next download. It runs only when the scan actually warned, so a healthy cache is never walked twice and never written to. A repo with in-flight.incompleteblobs is skipped, because a running download legitimately writes its ref before materialising the snapshot. Every filesystem error degrades to the previous behaviour, so a read-only or locked cache is unaffected.2. A failed load silently became a download nobody asked for
Every catch in the auto-load sweep is a parameterless
catch, and the only gate before the Hub-download branch wasloadAttempts >= MAX_AUTO_LOAD_ATTEMPTS, where the cap is 3. With one cached repo a single failure is1 < 3, so the cap never trips and the sweep falls through, downloading Qwen3.5-4B and finishing on a success toast. The real reason was available and discarded.The gate now also stops when a
/api/inference/loadcall actually rejected, and the failure is surfaced naming the model and the backend's reason. A device with nothing cached never records a failure and still downloads the default exactly as before. The attempt cap keeps its existing meaning; the new condition is additional, not a replacement.Only the candidate loader records failures, so variant-listing and validate hiccups keep their current fall-through behaviour, and the default-download call is untouched.
Tests
studio/backend/tests/test_hf_cache_dangling_refs.pycovers the dangling ref, a healthy cache that must not be touched, an in-flight download whose ref must be preserved, a repo with one valid and one dangling ref, and a read-only refs directory.tests/studio/test_chat_autoload_failure_gate.pyslices the realautoLoadSmallestModelout of the adapter and runs it undernode --experimental-strip-types, asserting which/api/inference/loadcalls happen and which toasts fire.With both source changes reverted and the tests kept, five fail on behaviour, including the reported bug itself:
tests/studiogoes from 1826 to 1834 passed with an unchanged failure set, andtsc -bis clean. The empty-device path was checked byte for byte: the whole default-download branch through end of file is identical to before.