Skip to content

Studio: reserve the duplicated MTP target KV context for MLA models (GLM-5.2 OOM) - #6447

Merged
danielhanchen merged 4 commits into
mainfrom
mtp-mla-target-ctx-reserve
Jun 18, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
mtp-mla-target-ctx-reserve

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Loading unsloth/GLM-5.2-GGUF:UD-IQ1_S in Studio advertised the model's native 1,048,576-token context, loaded successfully, then crashed on the first generation:

CUDA error: the resource allocation failed
  cublasCreate_v2(&cublas_handles[device])   (device 1)

The weights fit; the decode OOMed. This makes the GGUF auto-fit reserve account for a cost it was missing on MLA models, so the chosen -c actually holds at runtime.

Cause

When MTP speculative decoding is engaged, llama.cpp keeps a second full copy of the target model's KV context for draft verification (ctx_tgt=yes in the spec log), allocated at f16 regardless of the main cache type. On an MLA model (compressed latent KV) that copy is ~the main KV again. The spec log sized it directly:

load_model: [spec] estimated memory usage of MTP context is 99804.05 MiB   (~97.5 GiB)

But the auto-fit MTP reserve (#6312) only counted the embedded draft head — for GLM-5.2 at 1M ctx that is ~2 GiB, 46x too low. So the budget math looked like it fit on 2x B200:

@ 1M ctx reserved (before) actual
weights ~202 GiB ~202 GiB
main KV (MLA, f16) ~83 GiB ~83 GiB
MTP context ~2 GiB ~97 GiB
total ~287 GiB (fits 2x182) ~382 GiB (overruns)

Disabling speculative decoding removes the copy, and the same 1M context runs fine — which confirmed MTP as the culprit.

#6312 made the MTP reserve byte-accurate, but it was measured on Qwen3.6 MTP (non-MLA, embedded head, ~512 MiB), which keeps no such target copy. The duplicate context only shows up on MLA models.

Fix

_estimate_mtp_overhead_bytes now adds the duplicated target context — the main KV re-estimated at f16 — when the model is MLA. Auto-fit then backs the context off (or selects more GPUs) instead of advertising one that OOMs.

  • Gated strictly on MLA (kv_lora_rank present): exactly the family that keeps the extra copy (GLM-5.x, DeepSeek, Kimi-K2). Non-MLA MTP (Qwen, Gemma) is byte-for-byte unchanged.
  • Stays deterministic from GGUF dims (no magic constant), matching studio: deterministic VRAM auto-fit for GGUF (MTP reserve, compute buffer, total-based budget) #6312's approach. The target copy is f16 (llama.cpp's MTP cache type), not the main cache type.
  • GLM-5.2 @ 1M: MTP reserve goes 2.1 GiB -> 91.0 GiB (vs llama.cpp's ~97.5 GiB; the small remainder rides in the 0.95 budget headroom).

Tests

studio/backend/tests/test_mtp_mla_target_ctx.py:

  • MLA reserve includes the f16 target copy and it dominates the draft head.
  • The copy is f16 regardless of the main cache type, and scales linearly with context.
  • Non-MLA embedded heads keep overhead == draft KV (no copy).
  • _fit_context_to_vram on the GLM-5.2 / 2x B200 budget returns a context below the requested 1M, where the old draft-only reserve kept the full 1M.

All 563 existing MTP/KV/context-fit tests still pass (test_mtp_vram_budget, test_kv_cache_estimation, test_llama_cpp_context_fit, test_llama_cpp_max_context_threshold, test_mtp_drafter_companion, test_llama_cpp_mtp_detection).

danielhanchen and others added 2 commits June 18, 2026 16:56
GLM-5.2 UD-IQ1_S advertised its native 1,048,576-token context, loaded, then
crashed cublasCreate on the first generation with "CUDA error: the resource
allocation failed" on a 2x B200 box. The model loaded fine; the decode OOMed.

Cause: when MTP speculative decoding is engaged, llama.cpp keeps a second full
copy of the target model's KV context for draft verification (ctx_tgt=yes in the
spec log), at f16. On an MLA model that copy is ~the main KV again -- for GLM-5.2
at 1M ctx llama.cpp sized it at ~97.5 GiB -- but the auto-fit reserve only
counted the tiny embedded draft head (~2 GiB), 46x too low. So weights (~202 GiB)
+ main KV (~83 GiB) + a 2 GiB reserve looked like it fit in 2x182 GiB, when the
real footprint with the ~97 GiB MTP copy is ~382 GiB and overruns the cards.
Disabling speculative decoding removed the copy and the same context ran fine.

_estimate_mtp_overhead_bytes now adds the duplicated target context (the main KV
re-estimated at f16) for MLA models, so auto-fit backs the context off (or selects
more GPUs) instead of advertising one that OOMs. It is gated strictly on MLA
(kv_lora_rank present), which is exactly the family that keeps the extra copy
(GLM-5.x, DeepSeek, Kimi-K2); non-MLA MTP (Qwen, Gemma) is byte-for-byte
unchanged. The reserve stays deterministic from GGUF dims, matching #6312.

test_mtp_mla_target_ctx.py covers it: the MLA reserve includes the f16 target
copy and dominates the draft head, the copy is f16 regardless of the main cache
type and scales with context, non-MLA embedded heads keep overhead == draft KV,
and _fit_context_to_vram on the GLM-5.2 / 2x B200 budget now returns a context
below the requested 1M where the old draft-only reserve kept the full 1M.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request updates the MTP draft reserve estimation for MLA models (such as GLM-5.x, DeepSeek, and Kimi-K2) in llama_cpp.py to include a duplicated target KV context copy at f16, preventing out-of-memory (OOM) errors during draft verification. It also introduces comprehensive unit tests in test_mtp_mla_target_ctx.py to validate this overhead calculation and ensure non-MLA models remain unaffected. There are no review comments, so I have no feedback to provide.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

@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: 21dae29241

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


sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))

from core.inference.llama_cpp import ( # noqa: E402

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 Stub app deps before importing llama_cpp

When this new pure unit test is collected before test_mtp_vram_budget.py (or run directly) in the lightweight test environment, this import goes through core.inference.__init__ and reaches orchestrator.py, which imports structlog; because this file does not install the same structlog/loggers stubs used by the neighboring MTP budget tests, collection aborts with ModuleNotFoundError: No module named 'structlog' before any tests run. Add the local stubs before this import or move them into shared test setup so the file is order-independent.

Useful? React with 👍 / 👎.

…independent

The new test imports core.inference.llama_cpp, which pulls in orchestrator ->
structlog. In the lightweight test env structlog is absent, so when this file is
collected before test_mtp_vram_budget.py (it sorts first) or run directly,
collection aborted with ModuleNotFoundError. Install the same loggers/structlog
(+ conditional httpx) stubs the sibling MTP tests use before the import, matching
the established per-file convention.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 787be38205

ℹ️ 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 +2848 to +2849
if self._kv_lora_rank is not None:
target_ctx_copy = self._estimate_kv_cache_bytes(n_ctx, "f16", n_parallel = n_parallel)

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 Gate the target-KV copy to MTP spec mode

When extras select --spec-type draft-simple or draft-eagle3 with a separate drafter, _user_draft_via_extras still routes that load through this overhead function, but upstream --spec-type help separates draft-simple (simple draft model) from draft-mtp (MTP heads). This MLA-only addition therefore charges a full f16 target-KV copy for non-MTP draft modes, which can cut the advertised context by tens of GiB even though those modes only need the separate drafter's reserve; pass the effective spec type here and add the copy only for draft-mtp/MTP.

Useful? React with 👍 / 👎.

@danielhanchen
danielhanchen merged commit 1390e72 into main Jun 18, 2026
25 of 32 checks passed
@danielhanchen
danielhanchen deleted the mtp-mla-target-ctx-reserve branch June 18, 2026 17:24
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.

1 participant