Skip to content

fix(studio): keep MTP-flavor GGUF siblings as separate variants (#7460) - #7463

Closed
Souravrajvi0 wants to merge 29 commits into
unslothai:mainfrom
Souravrajvi0:feat/gguf-mtp-variant-keys-4af7
Closed

Souravrajvi0 wants to merge 29 commits into
unslothai:mainfrom
Souravrajvi0:feat/gguf-mtp-variant-keys-4af7

Conversation

@Souravrajvi0

@Souravrajvi0 Souravrajvi0 commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #7460

Two main-weight GGUF files in the same folder with similar names were treated as one variant. Studio showed a single Q6_K entry at ~68 GB (sizes summed), and there was no way to tell which file would load.

Reporter filenames:

  • Qwen3.6-40B-Deck-Opus-NEO-CODE-Q6_K-MTP.gguf
  • Qwen3.6-40B-Deck-Opus-NEO-CODE-Q6_K-PT-MTP.gguf

What happens

list_local_gguf_variants() groups files by quant label and sums shard sizes. Both files above extracted as Q6_K, so they collapsed into one variant with combined size.

These are main-weight MTP graft variants, not separate MTP/mtp-*.gguf drafter companions (those are already skipped via is_mtp_drafter_path()).

file before (quant key) after (quant key)
...-Q6_K-MTP.gguf Q6_K Q6_K-MTP
...-Q6_K-PT-MTP.gguf Q6_K Q6_K-PT-MTP

Fix

Extend quant label extraction to preserve post-quant disambiguating suffixes (-MTP, -PT-MTP, and -bpw in the hub path for parity with model_config):

  • studio/backend/hub/utils/gguf.py — extract_quant_token()
  • studio/backend/utils/models/model_config.py — _extract_quant_label()

No frontend changes: the picker already renders whatever quant strings the backend returns.

Reproduction (before)

  1. Place both MTP-flavor GGUFs in the same local folder.
  2. Open the model picker → On Device → expand the folder.
  3. One Q6_K row at ~68 GB; loading does not make the choice obvious.

After this fix, two rows appear with per-file sizes; _find_local_gguf_by_variant() resolves each label to the correct file.

Testing

Ran in this environment (no reporter hardware / no Windows ROCm box):

test result
TestExtractQuantToken::test_post_quant_mtp_suffixes_do_not_collapse pass
test_list_local_gguf_variants_keeps_mtp_flavor_siblings_separate pass
TestExtractQuantLabelSubdir::test_mtp_flavor_suffixes_are_distinct pass
test_list_local_gguf_variants_skips_big_endian_sibling (regression) pass
Full TestExtractQuantLabelSubdir + related hub quant tests 12 passed

Manual smoke with the reporter filenames under /tmp/gguf7460-test:

hub variants:  Q6_K-MTP (100 B), Q6_K-PT-MTP (200 B)  — separate rows, correct sizes
find Q6_K-MTP    → ...-Q6_K-MTP.gguf
find Q6_K-PT-MTP → ...-Q6_K-PT-MTP.gguf

Not run here: full Studio UI picker on Windows/ROCm with the reporter’s 40B weights (no GGUF on this VM).

Notes

Vision / mmproj (unchanged, likely separate follow-up): reporter logs show detect_mmproj_file: dropped mmproj-*.gguf (metadata mismatch) for all three projectors in the folder. That pairing path is strict about weight/projector metadata; this PR does not relax it. If vision still fails after variant selection works, we should track the specific mmproj + weight metadata in a follow-up.

…othai#7460)

Similar main-weight files like ...-Q6_K-MTP.gguf and ...-Q6_K-PT-MTP.gguf
were collapsing into one Q6_K variant with summed size. Extend quant label
extraction to preserve post-quant -MTP / -PT-MTP (and bpw in hub) suffixes
so the picker shows distinct selectable variants with correct per-file sizes.

@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: 31df38aa48

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

Comment thread studio/backend/hub/utils/gguf.py Outdated
if match:
prefix = match.group(1) or ""
return f"{prefix}{match.group(2)}"
return _quant_with_disambiguating_suffix(stem, match)

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 suffixes found in quant directories

When the basename has no quant and the match comes from a parent directory, match indexes that directory segment but _quant_with_disambiguating_suffix receives the basename stem. Consequently supported subdirectory layouts such as Q6_K-MTP/model.gguf and Q6_K-PT-MTP/model.gguf both resolve to Q6_K and are merged, while some basenames can spuriously contribute a suffix at the same offset. Pass the matched parent segment alongside its match so the suffix is extracted from the text that was actually searched.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Correct, and reproduced on the commit this was posted against (31df38a), where the suffix was read from the basename stem at the parent segment's offset:

Q6_K-MTP/model.gguf -> Q6_K (should be Q6_K-MTP)
Q6_K-PT-MTP/model.gguf -> Q6_K (should be Q6_K-PT-MTP)
IQ4_XS-3.53bpw/m.gguf -> IQ4_XS (should be IQ4_XS-3.53bpw)

and the spurious direction you called out also reproduced, since the basename can supply a suffix at the same offset:

Q6_K/abcd-MTP.gguf -> Q6_K-MTP (should be Q6_K)
IQ4_XS/abcdef-4.25bpw.gguf -> IQ4_XS-4.25bpw (should be IQ4_XS)

Fixed in 41341b1 by carrying matched_text alongside the match, so _quant_with_disambiguating_suffix extracts from the segment that was actually searched. All five now return the expected label at head.

tail = stem[match.end() :]
suffix_match = _POST_QUANT_VARIANT_SUFFIX_RE.match(tail)
if suffix_match:
quant += suffix_match.group(0)

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 suffixed variants eligible for preferred defaults

Once this appends -MTP, -PT-MTP, or -<n>bpw, pick_best_gguf() no longer finds the variant in its exact by_quant lookup against GGUF_QUANT_PREFERENCE. For example, with model-Q6_K-MTP.gguf and model-Q8_0.gguf, the Hub variants endpoint now recommends Q8_0 even though Q6_K precedes it in the preference table; similarly, an IQ4_XS-3.53bpw candidate loses to an exact lower-ranked quant. The preference selection should compare the base quant while still returning the full disambiguated label.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Correct, and reproduced on 31df38a with both of your examples:

pick_best_gguf(['model-Q6_K-MTP.gguf', 'model-Q8_0.gguf']) -> model-Q8_0.gguf
pick_best_gguf(['m-IQ4_XS-3.53bpw.gguf', 'm-IQ3_M.gguf']) -> m-IQ3_M.gguf

Both lost because the disambiguated label missed the exact by_quant lookup against GGUF_QUANT_PREFERENCE.

Fixed in 41341b1: pick_best_gguf now tries the exact label first and then falls back to comparing _base_quant_for_preference(label) against the preference entry, returning the full disambiguated filename. At head the two cases above return model-Q6_K-MTP.gguf and m-IQ4_XS-3.53bpw.gguf. Exact still wins over suffixed at the same base, so ['m-Q6_K.gguf', 'm-Q6_K-MTP.gguf'] returns m-Q6_K.gguf, and a genuinely higher-ranked exact quant still wins: ['m-IQ4_XS-3.53bpw.gguf', 'm-Q2_K.gguf'] returns m-Q2_K.gguf.

Souravrajvi0 and others added 2 commits July 26, 2026 08:44
…hai#7460)

- Extract post-quant suffixes from the matched parent directory segment, not
  the basename stem (Q6_K-MTP/model.gguf layouts)
- Rank suffixed labels in pick_best_gguf by base quant for GGUF_QUANT_PREFERENCE
- Mirror parent-segment suffix handling in model_config._extract_quant_label
@Etherll

Etherll commented Jul 26, 2026

Copy link
Copy Markdown
Collaborator

@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: 07901cd568

ℹ️ 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 +1588 to +1590
for name in gguf_files:
label = _extract_quant_label(name)
by_label.setdefault(label.upper(), 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 real quant ranking after precision infixes

When a filename contains a precision token before its actual quant, such as Foo-BF16-Q4_K_M.gguf, _extract_quant_label() returns the first match (BF16). Making _pick_best_gguf() rely exclusively on that label regresses the previous filename-based ranking: given this file alongside Foo-Q8_0.gguf, it now selects Q8_0 instead of the preferred Q4_K_M. The hub parser already handles this case by preferring non-precision matches, so this mirrored selector needs equivalent extraction behavior.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Correct, and reproduced on the commit this was posted against (07901cd):

_extract_quant_label('Foo-BF16-Q4_K_M.gguf') -> BF16
_pick_best_gguf(['Foo-BF16-Q4_K_M.gguf', 'Foo-Q8_0.gguf']) -> Foo-Q8_0.gguf

Fixed in eefb972 by adding _select_quant_label_match, the mirror of the hub parser's _select_quant_match: BF16/F16/F32 are held as a fallback and a real quant later in the stem wins. At head the label is Q4_K_M and the pick is Foo-BF16-Q4_K_M.gguf.

Since this selector has to stay in lockstep with the hub one, I checked the pair over a generated corpus of 249851 well-formed filenames (quants x MTP/bpw suffixes x split shards x subdir and Windows layouts): hub extract_quant_label vs model_config _extract_quant_label disagree on 0 of them, down from 72982 on main. Over the real sibling lists of 21 GGUF repos (1264 files) the two agree on every file, every per-repo label set is unchanged, and the one pick that moved is ubergarm/DeepSeek-V3-0324-GGUF, where main's hub and model_config disagreed (IQ1_S_R4 vs IQ2_K_R4) and now both return IQ1_S_R4.

Souravrajvi0 and others added 2 commits July 26, 2026 09:13
unslothai#7460)

Align _extract_quant_label with hub gguf parsing so Foo-BF16-Q4_K_M.gguf
labels as Q4_K_M, not BF16. Restores _pick_best_gguf ranking when precision
tokens appear as filename infixes (Codex review).
@Etherll

Etherll commented Jul 26, 2026

Copy link
Copy Markdown
Collaborator

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: d1a13d2dbf

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

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: acbf5b5e60

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

@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: 2f32f31173

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


# Mirror of hub/utils/gguf.py. Anchored, so ``-MTPX`` / ``-MTP-v2`` are not MTP flavors.
_POST_QUANT_VARIANT_SUFFIX_RE = re.compile(
r"-(?:(?:PT-)?MTP|[0-9]+(?:\.[0-9]+)?bpw)$",

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 Recognize suffixed quant directories when locating companions

When a direct GGUF path uses the newly supported layout snapshot/Q6_K-MTP/model.gguf (likewise Q6_K-PT-MTP), _local_gguf_companion_search_root() still full-matches the parent against a base-quant-only quant_dir_re. It therefore returns the quant directory rather than snapshot, so detect_mmproj_file() and detect_mtp_file() never scan root-level companions and the model loads without its projector or separate drafter. Extend that quant-directory matcher with these suffixes or share this suffix definition with it.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed and fixed in 76c895b. _local_gguf_companion_search_root full-matched a base-quant-only pattern, so snap/Q6_K-MTP/model.gguf returned snap/Q6_K-MTP while snap/Q6_K/model.gguf correctly returned snap, and the mmproj/drafter scan never reached the root. The dir matcher now shares _POST_QUANT_VARIANT_SUFFIX with the filename matcher, so the two definitions cannot drift again. Covered by TestCompanionSearchRootSuffixedQuantDir: 5 suffixed dirs climb, 8 plain dirs still climb, and 6 near misses (Q6_K-MTPX, Q6_K-MTP-v2, Q6_K-junk, Q6_K-bpw, MTP, my-model) still do not. Reverting the regex reddens exactly the 5 suffixed cases.

@danielhanchen

Copy link
Copy Markdown
Member

@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: 71302157e2

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

Comment on lines +1680 to +1682
suffix_match = _POST_QUANT_VARIANT_SUFFIX_RE.match(matched_text[match.end() :])
suffix = suffix_match.group(0) if suffix_match else ""
return f"{prefix}{match.group(2)}{suffix}"

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 pre-upgrade local variant keys loadable

For a saved local recipe that selected Q6_K before this change and whose directory contains a single model-Q6_K-MTP.gguf, the new extraction result becomes Q6_K-MTP. ModelConfig.from_identifier() passes the persisted Q6_K to _find_local_gguf_by_variant(), whose exact quant != variant comparison now rejects the file, so the previously working local model no longer loads. Preserve a backward-compatible base-quant match when it resolves to exactly one file, while retaining the new labels when multiple MTP flavors make the old key ambiguous.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed and fixed in 71588d0. Reproduced: a directory holding only model-Q6_K-MTP.gguf returned None for the persisted key Q6_K, so a model that loaded before this branch stopped loading. _find_local_gguf_by_variant now falls back to a base-quant match when the exact match finds nothing, and only when it is unambiguous: with Q6_K-MTP and Q6_K-PT-MTP both present it still returns None, and when a plain Q6_K file exists the exact match still wins. Shards of the one surviving flavor resolve to the first shard. Reverting just this hunk reddens exactly test_lone_flavor_resolves_from_the_old_key and test_sharded_lone_flavor_returns_the_first_shard, while the ambiguity and cross-quant guards stay green either way.

_GGUF_SPLIT_SUFFIX_RE = re.compile(r"-\d{3,}-of-\d{3,}", re.IGNORECASE)
# Suffixes that keep files sharing a base quant distinct (-Q6_K-MTP vs -Q6_K-PT-MTP).
_POST_QUANT_VARIANT_SUFFIX_RE = re.compile(
r"-(?:(?:PT-)?MTP|[0-9]+(?:\.[0-9]+)?bpw)$",

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 chained bpw and MTP suffixes

When a filename combines the two supported modifiers, such as m-IQ4_XS-3.53bpw-MTP.gguf, this anchored alternation matches neither because it accepts only one suffix. Consequently 3.53bpw-MTP and 3.97bpw-MTP files both extract as IQ4_XS, so variant listing merges their sizes and selection can load either file arbitrarily. Accept the supported bpw and MTP components in combination as well as individually.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The mechanism is right but I could not find the input. Scanned the 180 most-downloaded GGUF repos on the Hub (8,108 .gguf filenames): 47 carry an MTP suffix, zero carry a bpw suffix at all, and zero combine the two. So m-IQ4_XS-3.53bpw-MTP.gguf is a constructed name, not a layout anyone ships, and widening the anchored alternation to accept chained modifiers is a speculative change to a regex that also decides every ordinary quant label. Leaving it. If a repo does start shipping both modifiers on one file the symptom is a merged entry in the variant list, which is visible and cheap to fix then.

Comment thread studio/backend/hub/utils/gguf.py Outdated
match = _select_quant_match(stem)
if not match and "/" in filename:
parents = filename.rsplit("/", 1)[0]
if not match and "/" in normalized:

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 Honor flavor suffixes when basenames repeat the base quant

The fresh unhandled case after the parent-segment fix is a layout such as Q6_K-MTP/model-Q6_K.gguf: because the basename already matches, the parent is never inspected. As a result that path and Q6_K-PT-MTP/model-Q6_K.gguf both extract as Q6_K, so list_local_gguf_variants() merges them and variant selection is ambiguous. When the basename quant equals the base quant of a suffixed parent directory, preserve the parent's flavor suffix.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed and fixed in 71588d0 on both mirrors. Reproduced: Q6_K-MTP/model-Q6_K.gguf and Q6_K-PT-MTP/model-Q6_K.gguf both extracted Q6_K, and list_local_gguf_variants collapsed them into a single entry. Both extractors now consult the nearest quant-named parent when the basename label carries no flavor, and adopt its suffix only when the base quants agree. Q4_K_M-MTP/model-Q6_K.gguf still gives Q6_K, and Q6_K-MTPX / Q6_K-MTP-v2 parents are still ignored. Mirror parity re-checked over the 249,851-name corpus: 78 natural mismatches, unchanged from before this commit, all in the pre-existing no-quant fallback class.

@danielhanchen

Copy link
Copy Markdown
Member

@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: ac00be4116

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

Comment on lines +257 to +260
label = _quant_with_disambiguating_suffix(stem, match)
if not _POST_QUANT_VARIANT_SUFFIX_RE.search(label):
label += _parent_flavor_suffix(normalized, match)
return label

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 legacy base keys in cached path resolution

When an existing HF-backed recipe still stores the pre-upgrade key Q6_K and its cache contains a lone model-Q6_K-MTP.gguf, this relabels the cached variant to Q6_K-MTP, but resolve_local_gguf_path() still requires exact equality at line 476 and therefore returns None. The fresh remaining path beyond the previously fixed _find_local_gguf_by_variant() case is used by validation and diffusion classification, so an otherwise loadable cached model loses staged context/chat-template metadata and may be treated as an unknown diffusion model by the active-training guard. Apply the same unambiguous base-quant compatibility fallback in cached path resolution.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Correct, my previous commit only closed half of it. Fixed in eb5169b. resolve_local_gguf_path compared variant.quant == gguf_variant exactly, so a cache holding a lone model-Q6_K-MTP.gguf returned None for the stored key Q6_K even after _find_local_gguf_by_variant learned the fallback. It now applies the same unambiguous base-quant match, per snapshot and only after the exact pass fails. Verified: legacy key resolves for model-Q6_K-MTP.gguf and for the Q6_K-MTP/model.gguf dir layout; a cache with both Q6_K-MTP and Q6_K-PT-MTP still returns None; Q4_K_M-MTP is not offered for Q6_K; and a cached plain Q6_K still wins over the flavor. Reverting the hunk reddens exactly the two legacy-key cases.

@danielhanchen

Copy link
Copy Markdown
Member

@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: 7f9e49a088

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

if match:
label = _quant_with_disambiguating_suffix(stem, match)
if not _POST_QUANT_VARIANT_SUFFIX_RE.search(label):
label += _parent_flavor_suffix(normalized, match)

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 big-endian detection after inheriting suffixes

For a supported layout such as Q6_K-MTP/model-Q6_K-be.gguf, this changes the extracted label to Q6_K-MTP, which no longer occurs in the basename. is_big_endian_gguf_path() consequently treats the quant as parent-only and returns false for the trailing -be, so local listing and default selection can expose a big-endian weight on little-endian systems. The mirrored extractor in model_config.py has the same interaction; big-endian detection needs to compare against the base quant present in the basename.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed and fixed in 1643d89. Q6_K-MTP/model-Q6_K-be.gguf returned False from the endian check while Q6_K/model-Q6_K-be.gguf returned True, because the inherited label no longer occurs in the basename so quant_index went negative and the file read as quant-in-parent-only. All three copies of the detector (model_config, hub, llama_cpp) now strip the flavor suffix before searching the basename, which restores exactly the pre-branch comparison. Covered across all three for five paths.

Comment on lines +1685 to +1687
suffix_match = _POST_QUANT_VARIANT_SUFFIX_RE.match(segment[m.end() :])
if suffix_match:
label += suffix_match.group(0)

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 Delete inherited-suffix variants by relative path

When an exported model uses Q6_K-MTP/model-Q6_K.gguf, local variant listing now exposes Q6_K-MTP because of this inherited suffix. However, _delete_gguf_variant_files() in routes/models.py re-extracts from path.name only, obtains Q6_K, and therefore deletes nothing and returns a 404 for the displayed variant. That deletion scan needs to extract the label from the path relative to the export root, matching the listing behavior.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed and fixed in 1643d89. Worth noting the scan was already broken for plain subdir layouts before this branch: Q6_K/model.gguf with variant Q6_K also deleted nothing, since path.name has no quant at all. It now extracts from the path relative to the export root, so both that pre-existing case and the new Q6_K-MTP one delete correctly, and a sibling Q6_K/ or Q4_K_M file is left untouched.

Comment thread studio/backend/hub/utils/gguf.py Outdated
Comment on lines +245 to +248
if parent_match.group(2).upper() != match.group(2).upper():
return ""
suffix_match = _POST_QUANT_VARIANT_SUFFIX_RE.match(segment[parent_match.end() :])
return suffix_match.group(0) if suffix_match else ""

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 Compare the UD prefix before inheriting a parent flavor

The parent agreement check compares only group(2) and ignores the optional UD- prefix, even though that prefix is part of the quant identity. Thus UD-Q4_K_XL-MTP/model-Q4_K_XL.gguf is labeled Q4_K_XL-MTP, and the inverse layout Q4_K_XL-MTP/model-UD-Q4_K_XL.gguf is labeled UD-Q4_K_XL-MTP; in both cases a flavor is inherited from a different base quant, which can merge or mis-rank directory-based variants. Compare the complete base label, including group(1), in this helper and the mirrored model_config.py implementation.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Right, that was my bug. _parent_flavor_suffix compared only group(2), so UD-Q4_K_XL-MTP/model-Q4_K_XL.gguf gave Q4_K_XL-MTP and the inverse layout gave UD-Q4_K_XL-MTP, both inheriting across quant identities. Fixed in 1643d89: a shared _full_base_label compares prefix plus quant in both mirrors, so those two now give Q4_K_XL and UD-Q4_K_XL, while the matched pairs still inherit.

Comment on lines +223 to +225
suffix_match = _POST_QUANT_VARIANT_SUFFIX_RE.match(tail)
if suffix_match:
quant += suffix_match.group(0)

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 legacy base keys in chat-template lookup

For a pre-upgrade recipe that stores Q6_K while the local directory or cache contains only model-Q6_K-MTP.gguf, this relabeling makes the embedded chat template unreachable. The fresh remaining path is picker/service.py::_variant_matches(): both extractors now return q6_k-mtp, but its compatibility branch accepts only numeric bpw suffixes, so _find_gguf_in_dir() returns None and read_default_chat_template() loses the GGUF template when no tokenizer sidecar exists. Apply the same unambiguous base-quant compatibility used by the updated local and cached path resolvers.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed and fixed in 1643d89, the third mirror of the same gap. _variant_matches hard-coded a numeric-bpw test, so the legacy needle q6_k refused model-Q6_K-MTP.gguf and the template was lost. It now accepts any suffix the extractors keep, reusing _POST_QUANT_VARIANT_SUFFIX_RE rather than a second spelling of the rule. A different base quant still does not match either way.

@danielhanchen

Copy link
Copy Markdown
Member

@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: 8806a3f24a

ℹ️ 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 +265 to +266
if not _POST_QUANT_VARIANT_SUFFIX_RE.search(label):
label += _parent_flavor_suffix(normalized, match)

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 parent path when deleting suffixed variants

When an HF snapshot uses a layout such as Q6_K-MTP/model-Q6_K.gguf, this inheritance makes the listed variant Q6_K-MTP, but _delete_gguf_variant_from_repos() and the stale-file reclaimer pass only CachedFileInfo.file_name through extract_quant_label() (hub/services/models/deletion.py:81-86,199-203,421-425). With the pinned Hugging Face cache scanner that field is the basename, so those paths are read as Q6_K; deleting the displayed Q6_K-MTP variant therefore matches nothing. Derive the snapshot-relative name from file_path, as _cached_repo_file_name() already does, before applying the deletion predicates.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed and fixed in 425e919, the cache-scanner sibling of the export-root case. _repo_file_matches now derives the snapshot-relative name via cache_inventory._cached_repo_file_name, the helper the listing side already uses, so one change covers both the variant deletion and the stale-file reclaimer. Q6_K-MTP/model-Q6_K.gguf and IQ4_XS-3.53bpw/m.gguf now match their displayed variants, the pre-existing Q6_K/model.gguf case matches too, and in a repo holding Q6_K-MTP/, Q6_K/ and a root Q4_K_M file only the MTP one is selected. It also feeds the relative path to _is_mtp_drafter_path, which is what that predicate wants for the MTP/ subdir copies. Reverting the hunk reddens both new tests.

@danielhanchen

Copy link
Copy Markdown
Member

@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: ad9386816b

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

Comment on lines +225 to +227
suffix_match = _POST_QUANT_VARIANT_SUFFIX_RE.match(tail)
if suffix_match:
quant += suffix_match.group(0)

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 pre-upgrade partial downloads resumable

When an interrupted download was created before this upgrade, its manifest and cancel marker store the base key (for example, Q6_K for model-Q6_K-MTP.gguf). The new extraction makes build_gguf_variant_plans() expose only q6_k-mtp, while hf_download.py::_gguf_variant_target_plan() still performs an exact lookup; if Hub metadata is available, _download_gguf_variant() therefore exits with “No GGUF shards matching variant” instead of using the existing manifest. Preserve an unambiguous base-key fallback or resume from the stored manifest so these pre-upgrade partial downloads remain resumable.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed and fixed in 329a60f, the fourth reader of the relabelled key. Reproduced: with Hub metadata reachable and only model-Q6_K-MTP.gguf in the repo, _gguf_variant_target_plan(..., 'Q6_K') returned None and _download_gguf_variant exited 1 with "No GGUF shards matching variant", stranding the partial blobs the manifest still described. The exact lookup now falls back to an unambiguous base-key match: Q6_K resumes the lone MTP plan, two flavors still give None, a different base quant never matches, and a real Q6_K sibling still wins the exact lookup. Reverting the hunk reddens exactly the legacy-key case.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 329a60fc21

ℹ️ 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 added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Jul 26, 2026

@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: c488030f6b

ℹ️ 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 +550 to +551
by_base = [k for k in plans if k != key and _base_quant_for_preference(k).lower() == key]
return plans[by_base[0]] if len(by_base) == 1 else 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 Apply the legacy fallback when rebuilding offline plans

When a pre-upgrade Q6_K manifest records model-Q6_K-MTP.gguf and Hub metadata is unavailable, this fallback is never reached: the offline branch rebuilds the plan with plan_from_expected_files(variant, ...), whose exact variant predicate no longer recognizes the relabeled main file. The resulting main_hashes is empty, so any interrupted download with active .incomplete blobs exits before snapshot_download instead of resuming. Fresh evidence in the final tree is the metadata-unavailable path at hf_download.py:585-625; apply the same unambiguous base-quant compatibility while reconstructing that manifest plan.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Correct, and it reproduces. Fixed in 7460cd1.

Reproduction on c488030: a pre-upgrade manifest for variant Q6_K recording model-Q6_K-MTP.gguf, _gguf_variant_target_plan raising (metadata unavailable), and an active .incomplete blob. The offline branch rebuilds via plan_from_expected_files("Q6_K", ...), whose is_main_gguf_variant_path predicate compares extract_quant_label("model-Q6_K-MTP.gguf") == "Q6_K-MTP" against Q6_K, so main_filenames and main_hashes come back empty and the has_active_incomplete_blobs guard exits 1 before snapshot_download ever runs. Same scenario against the merge base resumes normally (one snapshot_download call), so it is a regression from the relabeling, not pre-existing.

Fix: the offline branch now falls back to the same unambiguous base-quant compatibility as the metadata path. _gguf_variant_target_plan had that logic inline, so it is factored into compatible_base_quant_label(variant, labels) in hub/utils/gguf.py and both call sites use it, with main_gguf_variant_labels() in gguf_plan.py supplying the manifest-side candidate labels. Exactly one flavor may share the base quant, otherwise the plan stays unresolved and the abort is preserved.

Two more readers had the same gap, found while tracing the resume path, both reproduced against the same manifest:

  • gguf_variants.gguf_variant_requirements is the service-side twin of _gguf_variant_target_plan and does the same build_gguf_variant_plans(...).get(variant.lower()) lookup, but never got the fallback, so Q6_K resolved to None while the worker resolved it.
  • _manifest_variant_blob_hashes(include_companions=False) runs the same exact predicate over the manifest.

Together those two make user-driven deletion of a partial pre-upgrade download a no-op while a sibling variant is active: delete_variant_incomplete_blobs_result(companions=False) got an empty hash set from both, returned deleted=0, unresolved=True, and left q6-main.incomplete on disk. The merge base deletes it. Both now go through the same helper.

Coverage in hub/tests/test_model_services.py: offline resume matches the relabeled main file and scopes the purge to its hash, the manifest hash reader and the requirements lookup resolve the base quant, and two ambiguity guards keep Q6_K-MTP plus Q6_K-PT-MTP unresolved so nothing is resumed or purged on a guess. Reverting the four source hunks reddens the three positive tests and leaves the ambiguity guards green; restoring them greens all five.

Suites, each in its own process: test_offline_gguf_cache_fallback.py 143, test_resolve_quant_gguf.py 8, test_mtp_drafter_companion.py 44, hub/tests/test_model_services.py 133 -> 138. 328 before, 333 after.

@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: 2b2e148e7f

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

parents = filename.rsplit("/", 1)[0]
for segment in reversed(parents.split("/")):
if match:
label = _quant_with_disambiguating_suffix(stem, match)

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 Use the legacy base fallback when sizing flavored GGUFs

When a pre-upgrade remote recipe still stores Q6_K and the repo contains only a newly relabeled Q6_K-MTP file, routes/inference.py::_estimate_gguf_required_gb() still searches list_gguf_variants() using exact quant equality, so it returns None instead of the flavored file's size. During active training, a GGUF-only repo that the generic model estimator cannot size is consequently rejected with estimate_unavailable even though the new compatibility paths can load it. Apply compatible_base_quant_label() to this sizing lookup as well.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Correct, and already landed in d9df520 (that commit is on head a93c9d2, which post-dates the round this comment was written against, 2b2e148). _estimate_gguf_required_gb now falls back to compatible_base_quant_label over [v.quant for v in variants] before giving up.

Negative control, reverting just that hunk on head:

$ python3 -m pytest tests/test_chat_load_during_training.py -q -k TestEstimateGgufRequiredGb
E       TypeError: unsupported operand type(s) for -: 'NoneType' and 'float'
FAILED tests/test_chat_load_during_training.py::TestEstimateGgufRequiredGb::test_remote_matches_pre_7460_base_quant
1 failed, 8 passed, 50 deselected

restored:

9 passed, 50 deselected

Coverage is test_remote_matches_pre_7460_base_quant, plus test_remote_rejects_ambiguous_base_quant and test_remote_exact_variant_wins_over_flavored_sibling for the two guard rails.

prefix = m.group(1) or ""
# Keep a trailing bpw / MTP flavor so same-base-quant files stay distinct (#7460).
suffix_match = _POST_QUANT_VARIANT_SUFFIX_RE.match(text[m.end() :])
return f"{prefix}{m.group(2)}{suffix_match.group(0) if suffix_match else ''}"

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 Accept legacy base keys when checking data-recipe models

For a pre-upgrade local recipe that stores Q6_K and a directory containing only model-Q6_K-MTP.gguf, _find_local_gguf_by_variant() now deliberately allows the model to load, but the local load records llama_backend.hf_variant from this extractor as Q6_K-MTP. routes/data_recipe/jobs.py::_ensure_selected_local_model_loaded() still compares that value exactly with the recipe's Q6_K, so running the recipe fails with “Selected local model is not loaded” immediately after successfully loading the selected model. Apply the same unambiguous base-quant compatibility to that identity check.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Correct, and also already landed in d9df520. _ensure_selected_local_model_loaded now accepts the recipe key when compatible_base_quant_label(gguf_variant, (active_variant,)) resolves, so the exact compare is no longer the only path.

Negative control, reverting just that hunk on head:

$ python3 -m pytest tests/test_data_recipe_local_model_selection.py -q
E   ValueError: Selected local model is not loaded. Selected /models/Gemma (Q6_K); active /models/Gemma (Q6_K-MTP). Load the selected model again, then run the recipe.
FAILED tests/test_data_recipe_local_model_selection.py::test_selection_accepts_pre_7460_base_quant
1 failed, 3 passed

restored:

4 passed

The ambiguous case still refuses: with the recipe on Q6_K-MTP and a loaded Q6_K-PT-MTP the run is blocked rather than served by the wrong quant.

One follow-up worth noting: the frontend has the same comparison unpatched at use-recipe-executions.ts:213 (activeVariant === ggufVariant), so Recipe Studio can still ask for a reload the backend would now accept. Tracking that separately since it is outside this PR.

for f in getattr(rev, "files", ()):
name = str(getattr(f, "file_name", ""))
# Snapshot-relative like the listing; ``file_name`` drops subdir quants.
name = cache_inventory._cached_repo_file_name(f)

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 Avoid truncating repo paths with a nested snapshots directory

For a valid Hub path such as assets/snapshots/Q6_K-MTP/model.gguf, this now calls _cached_repo_file_name(), which chooses the last path component named snapshots and therefore returns only model.gguf instead of the snapshot-relative repo path. The online variant listing still derives Q6_K-MTP from the sibling's full rfilename, but the cache deletion predicate derives an unknown model label and matches nothing, so deleting the displayed variant returns no deletion and leaves its cached files behind. Identify the cache's own snapshots/<revision> component rather than blindly choosing the last occurrence.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Correct, fixed in df1f999, with one correction to the framing.

The remedy you name is the right one and I took it: CachedRevisionInfo.snapshot_path is already on the object _repo_file_matches iterates, so _cached_repo_file_name now takes it and returns path.relative_to(snapshot_path). The last-occurrence scan stays only as the fallback for callers that have no revision.

Reproduced on head:

file_path=/hub/models--Org--Repo-GGUF/snapshots/rev1/assets/snapshots/Q6_K-MTP/model.gguf
  _cached_repo_file_name -> 'model.gguf'    extract_quant_label -> 'model'
  label from the full rfilename       -> 'Q6_K-MTP'
  delete_cached_model_blocking(..., 'Q6_K-MTP') -> HTTP 404
  snapshot file still present: True    blob still present: True

The correction: "this now calls _cached_repo_file_name()" reads as a regression, and it is not one. Before this PR the site read f.file_name, which huggingface_hub sets to file_path.name, i.e. the same bare model.gguf. Verified against the merge base d819029: the nested case 404s identically there. The flaw is latent in a pre-existing helper this PR reuses, and it was already reachable through cache_inventory._repo_gguf_blob_map, whose keys feed the update check and bucket by quant the same way. Both call sites now pass snapshot_path.

Reachability is real, not theoretical. _validate_path_in_repo only forbids ., .., .git and .cache, so snapshots is a legal repo path component, and public repos ship it: nm-testing/qwen3-8b-peagle-speculators, and GGUF-tagged MonsterMMORPG/Wan_GGUF, tda45/TdAI, aka7774/comfyui-models.

Negative control, reverting the fix hunk and keeping the tests:

FAILED test_cached_repo_file_name_keeps_repo_path_holding_a_snapshots_dir
FAILED test_delete_variant_reclaims_repo_path_holding_a_snapshots_dir
FAILED test_repo_gguf_blob_map_keys_repo_path_holding_a_snapshots_dir
3 failed, 145 deselected

restored: 3 passed, 145 deselected, module 149 passed.

_build_variant_cache_repo also had to stop being more generous than reality: it now reports file_name as the basename and carries the revision snapshot_path, matching what the real cache scan produces.

…F variant readers for PR unslothai#7463

A variant key stored before unslothai#7460 holds the base quant (Q6_K) where the file
now labels itself Q6_K-MTP, so every reader that looks a stored key up against
freshly derived labels needs compatible_base_quant_label. Seven more sites were
still comparing exactly:

- Cached-variant delete matched no completed main GGUF, so the delete returned
  404 and left the file on disk (or reported "deleted" off a purged manifest
  while the file survived).
- The post-update stale reclaim matched nothing, so the superseded revision's
  blobs were never unlinked.
- The empty <quant>/ folder reclaim left an interrupted split download's folder
  behind, which the listing then kept showing as a phantom cleanable row.
- The loaded-model delete guard compared the loaded key against the listing's
  label, so it stopped blocking and unlinked weights out from under a running
  llama-server. Blocks on either spelling now, since either can name that file.
- The OpenAI auto-switch resolver dropped a client pin of repo:Q6_K, so the
  request was silently answered by whatever model was resident.
- The recipe runner's model identity check compared the recipe's stored variant
  against the loaded label, permanently blocking a run that was in fact against
  the right file, since the stored key never changes.
- The training-time chat load guard could not size a stored variant, and an
  unsized variant default-denies, so the load was refused with a memory reason.

main_gguf_variant_labels now delegates to main_gguf_variant_labels_for_paths so
the manifest side and the cache-scan side share one spelling of "main GGUF
labels". Every new fallback keeps the ambiguity guard: with both Q6_K-MTP and
Q6_K-PT-MTP present a stored Q6_K stays unresolved rather than picking one, and
an exact label still wins over a flavored sibling.
@danielhanchen

Copy link
Copy Markdown
Member

Systematic audit of every stored-variant-key reader

Finding these one reviewer round at a time was not converging, so I swept the whole call graph in studio/backend for sites that resolve a stored or user-supplied variant key against labels derived from extract_quant_label / _extract_quant_label / directory names / manifest expected_files, and settled all of them in one pass.

Every "does it resolve" verdict below is a run, not a reading: I extracted the merge base (git merge-base origin/main HEAD = d819029be) with git archive and ran the identical scenario against both trees. Confirming the framing, the three #7460 commits (31df38aa4, 41341b18f, eefb972f2) sit on this branch above that merge base, so base-vs-head is the right regression test.

Site table

Scenario throughout: stored key Q6_K, on-disk file model-Q6_K-MTP.gguf (or a Q6_K-MTP/ dir).

Site Base Head before Resolves? Verdict
hub/services/models/deletion.py:203 cached-variant delete deleted 404, file on disk NO fixed
hub/services/models/deletion.py:425 stale reclaim 1 blob freed deleted_blobs=0, blob on disk NO fixed
hub/services/models/deletion.py:117/140 empty <quant>/ reclaim removed=1 removed=0, dir on disk NO fixed
hub/services/models/deletion.py:542 loaded-model delete guard blocks does not block NO fixed
core/inference/local_model_resolver.py:272 OpenAI repo:VARIANT pin resolved None NO fixed
routes/data_recipe/jobs.py:161 recipe model identity matches mismatch NO fixed
routes/inference.py:3886 training-time chat load sizing sized None NO fixed
core/inference/llama_cpp.py:1458 _gguf_files_for_variant resolved resolved YES no change, see below
hub/services/models/gguf_variants.py:190 n/a n/a exact by design confirmed, unchanged
hub/utils/gguf_plan.py:76 is_main_gguf_variant_path n/a n/a exact by design confirmed, unchanged
routes/models.py:2257 exported-GGUF delete deleted 404 NO reported, not fixed
routes/models.py:2379/2396 exported delete load guard blocks does not block NO reported, not fixed
routes/models.py:3196 /cached-model-path, /reveal-cached-model resolved 404 NO reported, not fixed
routes/models.py:2671 /kv-cache-estimate sized null NO reported, not fixed
routes/inference.py:3664 _already_serving matches mismatch NO reported, not fixed
routes/inference.py:4374 /load idempotency matches mismatch NO reported, not fixed
hub/utils/download_registry.py:1301 has_active_variant matches mismatch NO reported, not fixed
picker/service.py, model_config.py _find_local_gguf_by_variant, gguf.py resolve_local_gguf_path, hf_download.py, gguf_variants.py requirements + manifest hashes resolved resolved YES already covered by this PR
common.py:514, inventory_scan.py:335, gguf_plan.py:112/163, gguf.py:559/613, model_config.py:1503/1521/1905/1983/2051/2084/2901, picker/service.py:240 n/a n/a n/a key derived fresh in the same call, mismatch impossible

llama_cpp.py:1458 is worth calling out: the exact-label branch does miss, but the boundary regex below it is (?<![a-zA-Z0-9])q6_k(?![a-zA-Z0-9]), and both - and _ sit outside that class, so it matches inside model-q6_k-mtp.gguf. Verified by execution against base and head, identical results including the split-dir layout. Adding the helper there would be redundant, so I left it. gguf_variants.py:190 and gguf_plan.py:76 are confirmed to be the exact lookups the helper falls back from; giving them their own fallback would double up and would strip the ambiguity guard, since neither can see the full label set.

Base vs head evidence for the fixed sites

delete completed Q6_K-MTP as "Q6_K"    base: deleted, no files left
                                       head: HTTP 404, model-Q6_K-MTP.gguf left on disk
reclaim stale Q6_K-MTP as "Q6_K"       base: removed_snapshots=1 deleted_blobs=1
                                       head: removed_snapshots=0 deleted_blobs=0, blob left
empty Q6_K-MTP/ dir as "Q6_K"          base: removed=1, dir gone
                                       head: removed=0, dir left
OpenAI pin "repo:Q6_K"                 base: resolved Q6_K
                                       head: resolved None

Consequences, in the shape the earlier round established:

  • Cached-variant delete is the same silent no-op as the .incomplete case already fixed here, on the completed-file half. The offline/state listing hands back the key the manifest was filed under (gguf.py:395, "Each variant's quant is the stored variant key"), so a delete legitimately arrives as Q6_K. Worse than a plain 404 in the mixed case: purge_state still finds the pre-[Bug] Unsloth Studio thinks that 2 models in the same folder with similar names = the same model to be loaded together #7460 manifest, so the route returns 200 {"status": "deleted"} while the multi-GB GGUF stays on disk.
  • Stale reclaim is downstream of this PR's own _gguf_variant_target_plan fallback: that fallback lets a pre-[Bug] Unsloth Studio thinks that 2 models in the same folder with similar names = the same model to be loaded together #7460 job resume and re-download, and then the reclaim matches nothing, so the superseded revision leaks permanently.
  • Empty-dir reclaim left the folder, and _mark_empty_dir_cleanables runs on the offline branch too, so the user saw the real Q6_K row plus a phantom 0-byte Q6_K-MTP cleanable and one delete could not clear both.
  • Delete guard is the one that is unsafe rather than annoying. This PR deliberately makes a stored Q6_K loadable, so backend.hf_variant is Q6_K while the listing says Q6_K-MTP; the guard then compared q6_k == q6_k-mtp, failed open, and unlinked weights out from under a running llama-server. It now blocks on either spelling, since either can name that file.
  • OpenAI pin: resolve_local_gguf returning None makes auto-switch a no-op, so the request is silently answered by whatever model is resident, with no error.
  • Recipe identity check was the only permanent one. The recipe's gguf_variant is durable state, the active side is derived fresh, and reloading never converges because the stored key never changes: the run is blocked forever with "Selected local model is not loaded".
  • Training-time sizing: an unsized variant default-denies, so a stored key turned every chat load during a training run into a 409 worded as a memory problem.

Negative controls

Each hunk reverted, its tests run, restored, run again:

1. deletion.py _delete_gguf_variant_from_repos
   REVERTED  FAILED test_delete_variant_matches_pre_7460_base_quant / 1 failed, 2 passed
   RESTORED  3 passed
2. deletion.py reclaim_replaced_gguf_variant
   REVERTED  FAILED test_reclaim_replaced_gguf_variant_matches_pre_7460_base_quant / 1 failed, 2 passed
   RESTORED  3 passed
3. deletion.py _remove_empty_variant_dirs
   REVERTED  FAILED test_remove_empty_variant_dirs_matches_pre_7460_base_quant / 1 failed, 2 passed
   RESTORED  3 passed
4. deletion.py _loaded_repo_variant_blocks_delete
   REVERTED  FAILED test_loaded_variant_guard_blocks_pre_7460_base_quant[Q6_K-Q6_K-MTP]
             FAILED test_loaded_variant_guard_blocks_pre_7460_base_quant[Q6_K-MTP-Q6_K] / 2 failed, 2 passed
   RESTORED  4 passed
5. local_model_resolver.py resolve_local_gguf
   REVERTED  FAILED test_resolver_matches_pre_7460_base_quant / 1 failed, 2 passed
   RESTORED  3 passed
6. data_recipe/jobs.py _ensure_selected_local_model_loaded
   REVERTED  FAILED test_selection_accepts_pre_7460_base_quant / 1 failed, 3 passed
   RESTORED  4 passed
7. routes/inference.py _estimate_gguf_required_gb
   REVERTED  FAILED test_remote_matches_pre_7460_base_quant / 1 failed, 2 passed
   RESTORED  3 passed

The ambiguity-guard and exact-wins cases pass in both states by design: reverting also yields "unresolved", so they cannot redden. They are there to stop a future over-broad fallback, and every fix carries both. With Q6_K-MTP and Q6_K-PT-MTP both present a stored Q6_K stays unresolved rather than picking one, and an exact label still beats a flavored sibling.

Deliberately left alone

  • routes/models.py exported-GGUF paths (2257, 2379/2396, 3196, 2671). Divergence is real and reproduces, but exports are written as <name>-<quantization_method>.gguf and never carry an -MTP or -bpw flavor, and each reader is paired with a listing that derives its label from the same relative path, so the two agree. Only a script holding a pre-upgrade key can reach them. /kv-cache-estimate additionally has no callers anywhere in the repo.
  • routes/inference.py:3664 _already_serving and :4374 /load idempotency. These skip work rather than gate it. Only a single loaded label is available at each, so compatible_base_quant_label cannot run its ambiguity guard, and a false match would serve a flavor the caller did not ask for. The cost of leaving them is a redundant reload of the identical file, never a wrong answer. Fixing them properly needs the loaded variant normalised at the source, which is a larger change than this PR should carry.
  • The mirror direction, fresh label to stored state slug. Every per-variant artefact is filed under an exact-key slug, so a post-upgrade Q6_K-MTP misses a pre-upgrade q6_k file. Reproduced for download_registry.py:443/571 (transport marker missed, partial purged, download restarts from zero), and it also affects deletion.py:284 purge_state, hf_download.py:590, inventory_scan.py:589. This is a genuinely different resolution shape (scan stored keys, base-quant match, ambiguity guard in reverse), not the helper applied in another direction, so I did not invent a second fallback here. Worth its own change.

Test results

Baseline suites, before and after, each module in its own process:

Module Before After
tests/test_offline_gguf_cache_fallback.py 143 143
tests/test_resolve_quant_gguf.py 8 8
tests/test_mtp_drafter_companion.py 44 44
hub/tests/test_model_services.py 138 145
tests/test_model_update_robustness.py 22 25
tests/test_cached_gguf_routes.py 36 36
tests/test_gguf_load_cache_reuse.py 33 33
tests/test_gguf_routing.py 8 8
tests/test_gguf_xet_fallback_integration.py 3 3
hub/tests/test_empty_variant_folder.py 11 14
tests/test_openai_auto_switch.py 178 181
tests/test_openai_catalog.py 6 6
tests/test_chat_load_during_training.py 56 59
tests/test_data_recipe_local_model_selection.py new 4
Total 686 709

All passing, no failures either side.

One refactor came with this: main_gguf_variant_labels now delegates to main_gguf_variant_labels_for_paths, so the manifest side and the cache-scan side share a single spelling of "main GGUF labels" rather than growing a second one.

@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: a93c9d2d6e

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

Comment on lines +193 to +196
# Pre-#7460 keys stored the base quant. Same fallback the worker's
# _gguf_variant_target_plan applies to these very plans.
compatible = compatible_base_quant_label(variant, requirements)
return requirements[compatible] if compatible is not None else 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 Cache the compatible requirement under the requested key

When a pre-upgrade caller requests Q6_K and the remote repo has a lone Q6_K-MTP plan, this returns the compatible requirement but _fetch_gguf_variant_requirements() caches it only under q6_k-mtp. The next Q6_K lookup therefore misses again and calls HfApi.model_info() on every download-status poll; snapshot_progress.compute_snapshot_progress() invokes this resolver unconditionally, so normal polling can repeatedly hit Hub metadata and trigger unnecessary latency or rate limits. Store the resolved requirement under the original cache key as well.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Correct on the mechanism, fixed in df1f999. One attribution correction.

Measured on head with HfApi.model_info counted, five lookups of a stored Q6_K against a repo whose only main GGUF is model-Q6_K-MTP.gguf:

[stored key Q6_K]   resolved: 5/5    model_info calls: 5
                    positive cache keys: [('org/gemma', 'q6_k-mtp', '')]
                    negative cache size: 0
[exact Q6_K-MTP]    resolved: 5/5    model_info calls: 1

The negative cache is per repo and only set on an exception, and a successful fetch clears it, so nothing suppressed the refetch. Confirmed the poll path too: compute_snapshot_progress calls the resolver before any cache walk (snapshot_progress.py:140), and the frontend drives it at PROGRESS_POLL_INTERVAL_MS = 1_000 for the first 60s, then 2s.

The correction: this is not something the PR introduced. Against the pre-PR file the same input also made 5 calls, it just returned None each time, and an unresolvable key such as Q3_K_S still does. So the cost was already there; what the PR changed is the return value, and what was missing was extending the memoization that the exact path already had. After the fix it is 1 call.

On shadowing, since it is the obvious objection: the alias is only ever written when no exact plan exists, compatible_base_quant_label returns None on two flavors sharing a base, the token fingerprint is part of the key, and if the repo later publishes a plain model-Q6_K.gguf the alias serves the flavored plan for at most _VARIANT_REQUIREMENT_POS_TTL (60s) before _variant_requirement_cache_set_many overwrites it. Same staleness window every other entry already accepts.

Negative control, reverting the fix hunk:

>       assert len(fetches) == 1
E       assert 2 == 1
FAILED test_gguf_variant_requirements_cache_pre_7460_base_quant_key

restored: 1 passed, 148 deselected, module 149 passed.

I deliberately left the unknown-key refetch (Q3_K_S) alone. A per-variant negative entry is a larger behavior change than this item warrants.

Comment on lines +2034 to +2037
# Pre-#7460 recipes stored the base quant, so resolve a lone flavored sibling.
if len(by_base) == 1:
only = sorted(next(iter(by_base.values())))
return str(_local_gguf_load_path(only[0]))

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 Propagate the flavored label after legacy local resolution

When a saved local selection requests Q6_K and the directory contains only model-Q6_K-MTP.gguf, this fallback finds the file but the returned ModelConfig still has no resolved gguf_variant; the backend consequently infers Q6_K-MTP from the path. A subsequent identical /load request still carries Q6_K, and the exact comparison in routes/inference.py::_load_model_impl() no longer recognizes the resident model, causing an unnecessary llama-server teardown and reload instead of returning already_loaded. Preserve the resolved flavored label in the config or apply the same compatibility check to the loaded-state comparison.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Declining this one. Steps 1 to 4 of the chain reproduce exactly as described, but the consequence does not follow, and both remedies are wrong.

The chain, on head:

_find_local_gguf_by_variant(dir, 'Q6_K')          -> model-Q6_K-MTP.gguf
config.gguf_variant                              -> None
backend hf_variant (derived from the path)       -> 'Q6_K-MTP'
route gate inference.py:4380 already_loaded      -> False        <- as you say
load_model guard llama_cpp.py:6456               -> True
=> llama-server actually torn down and reloaded? -> False

_load_model_impl performs no teardown between the missed gate and load_model. The teardown lives inside load_model, behind _already_in_target_state, which runs first under the serial load lock, and whose local-load branch compares resolved gguf_paths rather than variants:

# Direct-file loads pass hf_variant=None while the backend stores an
# extracted filename label; compare paths to keep the guard symmetric.
if gguf_path is not None and self._gguf_path:

So the outcome is the slower of two dedupe paths, not a reload. The already_loaded status string has no consumers in studio/frontend/src.

Remedy (a), preserving the resolved label on the config, is inert: the gate compares llama_backend.hf_variant against request.gguf_variant, and hf_variant is Q6_K-MTP whether it arrives via config.gguf_variant or via the _extract_quant_label fallback. Same string, same False.

Remedy (b), applying the compatibility check at the loaded-state comparison, is worse than the problem. That gate sits ~120 lines before from_identifier resolves anything, so the only label available is the resident one, and with a single-element list the helper can never see the ambiguity it exists to detect:

dir contents: ['model-Q6_K-MTP.gguf', 'model-Q6_K.gguf']
user asks Q6_K; resolver would load : model-Q6_K.gguf
resident file is                    : model-Q6_K-MTP.gguf
compatible_base_quant_label('Q6_K', ['Q6_K-MTP']) -> q6_k-mtp
remedy (b) returns already_loaded, serving model-Q6_K-MTP.gguf  (WRONG FILE)
current gate returns already_loaded  -> False

_find_local_gguf_by_variant avoids that by checking exact matches first and only then falling back, which needs disk knowledge the gate does not have. A safe version would have to be gated on "no exactly-labelled file exists", which requires the resolved config, by which point _already_in_target_state already dedupes on path. There is no minimal correct fix at the anchored site.

Net at this site, the PR is a strict improvement: pre-#7460 the gate returned True, post-#7460 pre-#7463 the load failed outright (is_gguf=False), and now it succeeds and takes the second dedupe path.

danielhanchen and others added 2 commits July 27, 2026 04:05
… the resolved variant key for PR unslothai#7463

Two GGUF variant readers were resolving a key correctly and then losing it.

_cached_repo_file_name reconstructed the snapshot-relative path by scanning for
the LAST path component named "snapshots". That is a guess, and the revision dir
it is guessing at is already on the object being iterated. A repo that ships its
own snapshots/ dir (assets/snapshots/Q6_K-MTP/model.gguf is a legal Hub path)
makes the scan cut at the repo's component and return the bare basename, so the
quant is gone. The variant listing still reads Q6_K-MTP off the sibling's full
rfilename, so the two sides disagree: the deletion predicate derives "model",
matches nothing, and deleting the displayed variant 404s with its bytes still on
disk. The same key feeds _repo_gguf_blob_map, where the truncation buckets the
file under an unknown quant and shows an update that no download clears. Both
call sites now pass the revision's snapshot_path and the scan stays only as the
fallback for callers that do not have one.

gguf_variant_requirements resolved a pre-unslothai#7460 key to the lone flavored plan but
_fetch_gguf_variant_requirements files plans under the labels the repo
publishes, so the stored key missed on every later lookup.
compute_snapshot_progress resolves this on every download-status poll, which the
frontend drives at 1 Hz for the first minute of a job, so a pre-upgrade key cost
one HfApi.model_info round trip per poll. Measured 5 fetches over 5 lookups
against 1 for an exact key. The resolved requirement is now stored under the
requested key too, bounded by the same 60s positive TTL as every other entry and
only ever written when no exact plan exists.

Test helper note: _build_variant_cache_repo now reports file_name as the
basename and carries the revision's snapshot_path, matching what
huggingface_hub's scan actually produces.
@danielhanchen

Copy link
Copy Markdown
Member

Stepping back from the individual items, because the shape of this PR now matters more than the next fix.

Relabeling a quant key has surfaced sixteen downstream readers, found in waves, with several of the later ones existing because an earlier fallback made a pre-upgrade key loadable again. That is a design smell rather than bad luck, so I inventoried the rest instead of continuing reader by reader. Roughly nineteen more mixed comparisons remain on the backend and thirteen on the frontend, including the startup auto-load restore and Recipe Studio's client-side twin of a check already fixed server-side. Reader-by-reader will not converge.

I looked at whether the keys could just be normalised once at a boundary so downstream readers could go back to exact comparison. Short answer: not as a pure normalisation. Q6_K to Q6_K-MTP is not derivable from the key alone, only against a specific label universe, and every reader has a different universe (Hub siblings, a cache scan, a directory walk, a manifest, or a single resident label). The coherent version is "resolve once against the right universe, then pass the canonical label around", and that boundary does exist and is finite: the route layer, where 21 handlers accept a quant key and each already has the universe it would need.

Three things make it a follow-up rather than something to bolt on here:

  1. The key is a filename on disk, not only a value. Manifests and cancel markers are named models--owner--name--variant--q6_k.json, so migration means renaming files and rewriting bodies in one pass. HF-cache snapshots/<rev>/<QUANT>/ directories also carry the label and must NOT be renamed, since that breaks blob symlinks.
  2. There is a live re-infection path. list_partial_gguf_variants_from_state deliberately publishes the stored manifest key so a resume passes the right --variant back, so the API hands pre-upgrade keys to the client, which persists them into localStorage stores, two of which use the variant as a map key. A disk-only migration gets re-infected within one round trip.
  3. Some keys arrive from software we do not control. External OpenAI clients pin repo:Q6_K in the model field, so at least one fallback survives regardless.

Suggested order, and what I would do here:

  • Finish this PR as-is: fallbacks only on readers with user-visible damage (data loss, wrong model served, blocked run). Not the latency or cosmetic ones.
  • Follow-up A: fix the re-infection path first, publishing the derived label as quant and carrying the stored key separately for the resume. Nothing else stabilises while that leaks. Worth pairing with a branded TS type for the stored-key-versus-derived-label distinction, which the existing frontend type check would enforce across all thirteen sites for free.
  • Follow-up B: one-time migration of the manifest and cancel-marker filenames and bodies. Bounded and testable, and it drains the actual stale population.
  • Follow-up C: only after B has shipped and aged, delete the per-reader fallbacks. Deleting them earlier breaks un-migrated installs.

The fallbacks in this PR are compensation, not a fix. They are the right call right now because the regression is live and the migration is not, but I would not keep adding them indefinitely.

@danielhanchen

Copy link
Copy Markdown
Member

Similarly we won't be fixing this, as this should be best to rename the files

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.

[Bug] Unsloth Studio thinks that 2 models in the same folder with similar names = the same model to be loaded together

3 participants