Skip to content

Studio: reserve VRAM for shared MTP heads - #10149

Closed
Imagineer99 wants to merge 4 commits into
unslothai:mainfrom
Imagineer99:fix/flash-next-shared-mtp-fit
Closed

Imagineer99 wants to merge 4 commits into
unslothai:mainfrom
Imagineer99:fix/flash-next-shared-mtp-fit

Conversation

@Imagineer99

Copy link
Copy Markdown
Member

Summary

  • read <arch>.nextn_shared_target_tensors from drafter GGUF metadata
  • when llama.cpp fitting is delegated for a GPU-resident shared MTP head, add Studio's existing draft weight/KV estimate to --fit-target
  • leave self-contained and CPU-offloaded drafters unchanged

Root cause

Qwen3.8 Flash Next's compact MTP GGUF borrows token_embd.weight and output tensors from its target. llama.cpp therefore cannot measure that head as a standalone extra model:

borrow_shared_tensor: this model is a draft head without its own 'token_embd.weight'
failed to measure the memory of the extra model, fitting without it

The fitter then packs the target without pricing the drafter. In the captured run the later shared-head load attempted another 2647 MiB CUDA allocation and OOMed, despite Studio already having a byte estimate for the draft weights and KV cache.

This change uses the GGUF's explicit shared-tensor metadata rather than a model name or filename heuristic. Ordinary drafters remain measured by llama.cpp and are not double-reserved; a CPU-offloaded drafter is already removed from the GPU-budget path.

Relationship to #10143

#10143 improves Auto's recovery classification after this exact OOM and successful retry without MTP. This PR is complementary: it prevents the initial OOM by preserving the head's required VRAM during target fitting.

A/B validation

Negative control, with only the new metadata read and reserve result disabled while retaining the regression tests:

  • 2 focused failures: the shared flag remained false and the fit reserve remained 0
  • 3 negative-path cases passed

Fixed branch:

  • focused shared-head tests: 5 passed
  • test_llama_cpp_mtp_detection.py + test_mtp_vram_budget.py: 541 passed
  • Ruff: passed
  • py_compile: passed
  • git diff --check: passed

A full live CUDA reproduction requires the original target plus multi-gigabyte shared head, so the regression deterministically exercises the captured failure boundary and budget contract instead.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 1, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-14T16:36:33.696132Z 0066e1f New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@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: 714cd3d9d0

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

max(_mtp_reserve_bytes, _mtp_draft_weights),
)
if _shared_draft_reserve_mib:
_fit_target_delta_mib += _shared_draft_reserve_mib

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Honor the reserve when users pass a fit target

When extra_args contains --fit-target/-fitt, this increment does not protect the shared head: Studio emits its calculated target first, then appends user arguments at llama_cpp.py:22024-22037, and llama.cpp uses the last value (also captured by test_load_mode_fit_matrix.py:533-537). Thus a user-supplied smaller target overrides the augmented margin and restores the shared-head OOM this change is intended to prevent; combine the existing target with the required reserve or otherwise ensure the final emitted value includes it.

Useful? React with 👍 / 👎.

Comment on lines +13081 to +13083
f"{arch}.nextn_shared_target_tensors": (
"nextn_shared_target_tensors"
),

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 Parse the shared-tensor marker independent of key order

When a valid GGUF places <arch>.nextn_shared_target_tensors before general.architecture, this key has not yet been added to arch_keys, so the outer predicate skips its value and the flag remains false. GGUF metadata has no ordering contract, as the existing handling at llama_cpp.py:13144-13147 already notes; such a shared drafter therefore receives no added fit reserve and can still OOM. Buffer this marker until the architecture is known, as is already done for pooling metadata.

Useful? React with 👍 / 👎.

Comment on lines +20553 to +20555
_shared_draft_reserve_mib = self._shared_drafter_fit_reserve_mib(
_mtp_draft_for_budget,
max(_mtp_reserve_bytes, _mtp_draft_weights),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Carry the unsized-KV fallback into the delegated fitter

When the shared drafter's weights are readable but its KV dimensions are not, _mtp_reserve_bytes contains only the weights and this max therefore reserves no space for the unknown draft KV. Studio's normal placement deliberately compensates for this case with _flat_mtp_reserve (the comments at llama_cpp.py:20597-20603 explicitly note that _mtp_reserve_bytes has no replacement for the unsized portion), but that reduced budget is not conveyed to llama.cpp once fitting is delegated. A shared head with incomplete or unsupported KV metadata can consequently reproduce the runtime OOM despite being detected correctly; add the flat fallback to the fitter margin in this case.

Useful? React with 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member

Confirmed the delegated-fit path in studio/backend/core/inference/llama_cpp.py never prices a shared MTP head, since the standalone probe fails before the borrowed target tensors exist, and that gating the extra reserve on the GGUF bool leaves ordinary and CPU-offloaded drafters untouched. Will get this reviewed.

@danielhanchen

Copy link
Copy Markdown
Member

Checked this against the fit path in studio/backend/core/inference/llama_cpp.py and the metadata read, and the shared-head flag genuinely is not priced in today, so the target can eat the VRAM the draft load later needs. Could you also drop the unrelated assert reformatting in test_mcp_session_resources.py and test_mcp_upgrade_compat.py so the branch is just the budget change?

Copy link
Copy Markdown
Member Author

Done, dropped the unrelated formatting in both MCP test files. The diff is now just the budget change and its tests.

@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: 0066e1fdc5

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

max(_mtp_reserve_bytes, _mtp_draft_weights),
)
if _shared_draft_reserve_mib:
_fit_target_delta_mib += _shared_draft_reserve_mib

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Add the shared reserve after clamping the base margin

When the VRAM budget is raised above the 95% default, _fit_target_delta_mib is negative, so adding the shared-head bytes to that signed adjustment lets the user's budget erase part or all of the required reserve before _fit_target_margin_mib() applies its 512 MiB floor. For example, at 100% on a 24 GiB card the delta is about -1229 MiB, so a 2647 MiB head increases the legacy fit target to only about 2442 MiB rather than the required 512 MiB baseline plus 2647 MiB; the fitter can therefore consume roughly 717 MiB needed by the later shared-head load and reproduce the OOM. Clamp the budget-derived base margin first, then add the shared-head reserve separately.

Useful? React with 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member

Thanks for dropping the unrelated MCP test formatting; the diff is now just the shared-head fit reserve, which main still does not add to --fit-target. Will get this reviewed.

@LeoBorcherding LeoBorcherding self-assigned this Sep 25, 2026
@LeoBorcherding

LeoBorcherding commented Sep 25, 2026 •

Copy link
Copy Markdown
Collaborator

The fix is right for the llama.cpp builds that ship today. Two notes.

Detection. Main already asks this question the way llama.cpp does, by checking whether the head carries its own token_embd.weight. Reusing that check makes the vtype-7 branch, _nextn_shared_target_tensors, and its two resets unnecessary, and it stays correct for heads that borrow without the key, which is what ggml-org/llama.cpp#28243's ctx_other borrowing keys on. On the published sidecars it returns False for mtp-Qwen3.8-Flash-Next-shared-Q8_0.gguf and True for mtp-Qwen3.8-Flash-Next-Q8_0.gguf. The body of _shared_drafter_fit_reserve_mib would become:

        if not drafter_path or reserve_bytes <= 0:
            return 0
        from utils.models.gguf_metadata import _gguf_shard_has_named_tensor
        if _gguf_shard_has_named_tensor(drafter_path, "token_embd.weight") is not False:
            return 0
        return math.ceil(reserve_bytes / (1024 * 1024))

Double counting later. unslothai/llama.cpp#227 fixes the fitter itself, so it measures the shared head (the Q8_0 goes from 226 MiB to about 3.7 GB projected). Once that's in the pinned build, this reserve counts the head twice. The build can't show it, since there's no new flag and the build number stays the same, so the reserve should come out in the same change that adds unslothai/llama.cpp#227 to the pin set.

@Imagineer99

Copy link
Copy Markdown
Member Author

Closing in favour of unslothai/llama.cpp#227, which addresses this in the fitter itself. That fix is still pending, but I would rather keep the solution there than maintain a Studio workaround.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants