Skip to content

studio: deterministic VRAM auto-fit for GGUF (MTP reserve, compute buffer, total-based budget) - #6312

Merged
danielhanchen merged 54 commits into
mainfrom
studio-mtp-vram-autofit
Jun 17, 2026
Merged

danielhanchen merged 54 commits into
mainfrom
studio-mtp-vram-autofit

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Jun 14, 2026 •

Copy link
Copy Markdown
Member

Summary

Studio's GGUF auto-fit could advertise a context (for example ~110k for the Qwen3.6-27B MTP GGUF) that fit on paper but then OOMed mid-generation, or it left a lot of context on the table on a partly-used or multi-GPU box. This makes the auto-fit budget deterministic from GGUF dims and the launch flags, so the chosen -c actually holds at runtime and uses the card fully.

Three changes, each replacing a magic constant with a value derived from the model and the hardware:

  1. Byte-accurate MTP draft reserve (replaces the flat 5% fraction).
  2. Total-based VRAM budget at 0.95 (replaces 0.90 of free VRAM).
  3. Deterministic compute-graph buffer in both multi-GPU paths (replaces the flat 5 GB tensor reserve).

1. Byte-accurate MTP draft reserve

The MTP draft reserve was a flat 5% of total VRAM. That tracks neither real cost: the MTP head keeps its own attention KV cache that grows with context (and on the hybrid Mamba/attention Qwen3.6 models the main KV is small, so auto-fit kept a near-native context while the draft KV scaled), and a separate drafter (Gemma) keeps its own weights on GPU.

The reserve is now sized from GGUF dims and evaluated per candidate context inside the fit binary search:

draft_kv = nextn_predict_layers * n_kv * (k_len + v_len) * bytes_per_elem(draft_cache_type) * n_ctx   # embedded head (Qwen)
draft_kv = drafter._estimate_kv_cache_bytes(n_ctx, draft_cache_type)                                   # separate drafter (Gemma)
reserve  = draft_kv + drafter_weights
  • Both MTP shapes are handled: Qwen's last-layer embedded head (sized from nextn_predict_layers) and Gemma's separate drafter GGUF (sized from the drafter's own dims and weights).
  • Draft KV defaults to f16 (llama.cpp's MTP draft context is f16 regardless of the main --cache-type-k/v). An explicit --cache-type-k-draft/--spec-draft-type-k recomputes it, but the embedded single-layer head floors a quantized draft type at f16: llama.cpp cannot amortize quantized-KV overhead over one layer, so a quantized draft KV fits less context than f16 there, not more (Qwen3.6 + MTP: Calculated context size is smaller when I use `--spec-draft-type-* q4_0`. is this normal? ggml-org/llama.cpp#24102). A full separate drafter still uses its real type.
  • The speculative verify buffer is context-independent and small, so it rides in the budget headroom rather than as a tuned constant.
  • The flat fraction is kept only as a fallback when GGUF dims are unavailable; non-MTP loads are unchanged.

Measured draft KV (27B MTP, nextn=1) is 64 / 256 / 512 MiB at 16k / 65k / 131k; the deterministic estimate matches within 2 MiB.

2. Total-based VRAM budget (0.95)

Cap GPU occupancy at a fraction of TOTAL VRAM rather than a fraction of FREE VRAM, and raise the fraction from 0.90 to 0.95:

budget = free - (1 - 0.95) * total       (per GPU; summed across a pool)

free already excludes other processes, so this is exactly 0.95 * total - used. The reserve is now absolute (a fixed slice of the card) instead of shrinking as the GPU fills, so a partly-used GPU keeps a constant cushion for compute/CUDA/verify buffers instead of over-promising context and offloading to CPU at runtime. _get_gpu_memory() reads memory.total alongside memory.free; _fit_context_to_vram, _select_gpus, and the load_model pool loops thread the totals through.

Multi-GPU is handled on both axes. Layer split (the default, pipeline parallel) prefers the fewest GPUs that fit and pools sum(free_i - 0.05 * total_i). Tensor parallel (--split-mode tensor, opt-in) reserves the compute buffer per device and weights --tensor-split by free - buffer.

3. Deterministic compute-graph buffer

The tensor path reserved a flat 5 GB/device (_TENSOR_PARALLEL_BUFFER_RESERVE_MIB), which over-reserved about 8x on a 27B model; the layer-split path reserved nothing. Both now use a deterministic estimate from GGUF dims and the launch flags:

out = n_vocab * n_ubatch * 4            # vocab-width output buffer
act = 4 * n_embd * n_ubatch * 4         # activation scratch
pipeline_per_device = act + out * (n_parallel - 1)
tensor_per_device   = 2*act + out * n_parallel

The buffer is context-independent and scales with --parallel (concurrent serving slots), a separate axis from how the model is split across GPUs. --kv-unified is memory-neutral (it changes window semantics, not total VRAM) and is emitted only when slots > 1, matching how the budget is computed. Vocab size (tokenizer tokens array length) and feed_forward_length are now parsed from the GGUF for this. The flat 5 GB stays only as a fallback when dims are unavailable.

Measured compute buffer (27B MTP, vocab 248320): single-GPU serving slots 1/2/4/8 give 36 / 492 / 1388 / 3220 MiB; tensor mode about 600 MiB/device. The estimate is a small upper bound over each point.

A layer split also pays a fixed per-device overhead (CUDA context + per-device scratch) on every participating GPU, separate from that slot-scaling buffer. Measured on the 27B GGUF, layer-split total VRAM grows about 0.9 GB per extra GPU (≈ +894 MiB at --parallel 8, +946 MiB at --parallel 1; ~linear to +2.6 GB at 4 GPUs), independent of --parallel. The fit reserves (GPUs - 1) * _PIPELINE_PER_DEVICE_OVERHEAD_MIB so a tight multi-GPU layer split can't pin a context that fits the pool on paper but OOMs a device; a single GPU adds nothing, so single-GPU sizing is unchanged. The slot-scaling buffer above is conserved across the split, so it is still folded once.

Root cause confirmed by an A/B bisect

A user reported the unsloth/Qwen3.6-27B-MTP GGUF fitting 110k context on an older build but OOMing on a later build, single GPU. Installing both versions fresh into isolated UNSLOTH_STUDIO_HOMEs and measuring on one GPU showed the Studio backend (auto-fit + MTP code) is byte-identical between the two, and so is the torch stack. The difference is that the bundled llama.cpp gained MTP support across the update: MTP went from inert (the GGUF behaved like a plain model, so 110k fit) to actually running --spec-type draft-mtp, and its draft KV now consumes the extra VRAM. The old flat-5% reserve did not track the context-scaling draft KV, so auto-fit still advertised ~110k and the load OOMed. This change reserves the right amount once MTP engages, and (via a binary-capability gate) reserves nothing when the bundled llama.cpp cannot run MTP.

Effect on advertised / achievable context

Qwen3.6-27B MTP Q6_K, MTP on, before this PR vs after:

scenario KV before after
1x 32GB pipeline (~31 GB free) f16 23,040 64,000
q8_0 43,520 114,944
q4_0 82,432 199,680
2x 32GB pipeline any 262,144 262,144
2x 24GB tensor (~23 GB free) f16 134,049 262,144
q8_0 252,329 262,144

A single card roughly triples the supported f16 context (recovering the user's old ~60k while keeping it on-GPU); tight tensor setups recover the full native window.

Validated on hardware

Measured per-PID VRAM on B200s capped to the target free VRAM, b9625 llama-server, MTP on:

  • 1x 32GB, f16: manually loading -c 64768 uses 29.3 GB at 120 t/s, estimate within 0.1% (auto-fit advertises a slightly more conservative 64000 once the compute buffer is folded in, so the advertised context loads with headroom to spare).
  • 2x ~23GB, tensor, f16 @ 262144 (full native window): loads at 22.2 GB/device, 98 t/s, no OOM. Estimate within 0.4%.

Capped runs also confirm the old behavior at low free VRAM advertised the full window and silently offloaded to CPU (the 100 to 20 t/s drop users reported); the new code returns a real on-GPU context.

Test plan

  • New studio/backend/tests/test_compute_buffer.py (19 tests): the estimate is a safe upper bound on every measured allocation, scales with serving slots / vocab / ubatch, tensor exceeds pipeline, and falls back to the flat reserve when dims are missing.
  • studio/backend/tests/test_mtp_vram_budget.py rewritten for the deterministic design (embedded vs separate drafter, draft-KV-type recompute, overhead = draft KV + drafter weights, no tuned constants).
  • KV / context-fit / max-context-threshold tests updated for the 0.95 constant and the total-based budget.
  • Targeted suite green: test_compute_buffer, test_tensor_parallel, test_mtp_vram_budget, test_llama_cpp_context_fit, test_kv_cache_estimation, test_llama_cpp_max_context_threshold, test_llama_cpp_wait_for_vram_settle (310 passed).

danielhanchen and others added 2 commits June 14, 2026 06:38
Auto-fit advertised a context (for example ~110k for the Qwen3.6-27B MTP
GGUF) that fit on paper but OOMed mid-generation or during tool calls once
MTP speculative decoding was active. The MTP draft path's VRAM was reserved
as a flat 5% of total VRAM, which tracks neither of the two real costs: the
MTP head keeps its own attention KV cache that grows with context, and the
speculative verification buffer grows with --spec-draft-n-max. On the
hybrid Mamba/attention Qwen3.6 models the main KV is small, so auto-fit
happily kept a near-native context while the draft path pushed the load
over budget at runtime.

Replace the flat fraction with a byte-accurate, context- and n_max-aware
reserve sized from GGUF dims: draft KV from nextn_predict_layers and the
attention dims at f16 (llama.cpp's MTP draft context uses f16 KV regardless
of the main cache type), plus a verify buffer per embedding-unit per draft
token. The reserve is evaluated per candidate context inside the fit binary
search and added to every pin/fit check, including the tensor-parallel
planner and its even-split decision. Coefficients were calibrated against
llama-server VRAM measurements on the Qwen3.6-27B MTP GGUF (RMS 14 MiB).

The flat fraction remains as a fallback when GGUF dims are unavailable, so
non-MTP loads are unchanged. The budget now also engages when the user wires
MTP through extra args (--spec-type draft-mtp, including chains), reads the
effective draft depth from --spec-draft-n-max or the legacy --draft-max with
extras taking precedence over the first-class field, reserves a separate
drafter's weights when supplied via --model-draft/--spec-draft-model/-md,
and mirrors _build_speculative_flags so it never reserves for MTP the launch
resolver will not emit (needs a head/drafter and a binary that supports
--spec-type mtp).

Adds tests/test_mtp_vram_budget.py.

@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 replaces the flat 5% VRAM reservation fallback for Multi-Token Prediction (MTP) with a byte-accurate, context-aware overhead estimation. It introduces calculations for the MTP head's draft KV cache (which scales with context length) and speculative verification buffers (which scale with draft depth), falling back to the flat fraction only when GGUF dimensions are unavailable. The context auto-fitting, tensor parallel planning, and GPU selection logic are updated to evaluate this dynamic overhead per candidate context. Additionally, a comprehensive suite of unit tests is added to verify these calculations and prevent out-of-memory (OOM) regressions. There are no review comments, so no feedback is provided.

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.

danielhanchen and others added 2 commits June 15, 2026 08:24
Build on the byte-accurate MTP reserve with three changes that make the
GGUF auto-fit budget deterministic across architectures and recover usable
context, especially for MTP models on a single tight card.

1. Total-based budget. Cap GPU occupancy at a fraction of TOTAL VRAM rather
   than a fraction of FREE VRAM, and raise the fraction from 0.90 to 0.95:

       budget = free - (1 - 0.95) * total      (per GPU, summed for a pool)

   The reserve is now absolute (a fixed slice of the card) instead of
   shrinking as the GPU fills, so a partly-used GPU keeps a constant cushion
   for compute/CUDA/verify buffers instead of over-promising context and
   spilling to CPU at runtime. _get_gpu_memory() reads memory.total alongside
   memory.free; _fit_context_to_vram, _select_gpus and the load_model pool
   loops thread the totals through. Multi-GPU layer-split pools
   sum(free_i - 0.05*total_i); tensor mode reserves per device.

2. Deterministic compute-graph buffer. Replace the flat 5 GB/device tensor
   reserve (a magic constant that over-reserved about 8x on a 27B model) with
   _estimate_compute_buffer_bytes, sized from GGUF dims and the launch flags:

       out = n_vocab * n_ubatch * 4            # vocab-width output buffer
       act = 4 * n_embd * n_ubatch * 4         # activation scratch
       pipeline_per_device = act + out * (n_parallel - 1)
       tensor_per_device   = 2*act + out * n_parallel

   The buffer is context-independent and scales with --parallel (serving
   slots), not with how the model is split across GPUs. It is now reserved in
   BOTH multi-GPU paths (layer split folds one buffer into the pooled
   footprint; tensor mode reserves it per device). The flat 5 GB stays only as
   a fallback when vocab/embedding dims are unavailable. Calibrated against
   llama-server measurements (parallel 1/2/4/8 give 36/492/1388/3220 MiB on a
   single GPU; about 600 MiB/device tensor); the estimate is a small upper
   bound.

3. GGUF parsing. Read vocab size (tokenizer tokens array length) and
   feed_forward_length for the compute-buffer estimate.

Effect on the Qwen3.6-27B MTP Q6_K case (MTP on): a single 32 GB card at
about 31 GB free advertises f16 23k to 64k, q8_0 44k to 115k, q4_0 82k to
200k; 2x 24 GB tensor mode recovers the full 262k window for f16 (was about
134k). Validated on hardware: 1x 32 GB f16 at 64768 loads at 29.3 GB / 120
t/s; 2x 23 GB tensor f16 at 262144 loads at 22.2 GB/device / 98 t/s; both
within 0.4% of the estimate. Adds test_compute_buffer.py and updates the
KV/context-fit/MTP-budget tests for the 0.95 constant and the new budget.
@danielhanchen danielhanchen changed the title studio: reserve MTP draft VRAM in GGUF auto-fit studio: deterministic VRAM auto-fit for GGUF (MTP reserve, compute buffer, total-based budget) Jun 15, 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: 253231b0cf

ℹ️ 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 draft_kv is None:
return None
return draft_kv + max(0, draft_weights_bytes)

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 Account for draft depth in MTP reserve

When a load sets a larger spec_draft_n_max via the API or --spec-draft-n-max, the verifier buffer grows with that draft depth, but this return value is only draft KV plus drafter weights, so every n_max gets the same fit/pin budget. That can still advertise and pin a context that fits at the default draft depth but OOMs as soon as speculative decoding allocates the larger verifier buffer.

Useful? React with 👍 / 👎.

db = self._draft_backend_for(drafter_path)
if db is None or not db._can_estimate_kv():
return None
kv = db._estimate_kv_cache_bytes(n_ctx, draft_cache_type)

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 Pass serving slot count to drafter KV estimate

For a separate drafter with sliding-window layers (for example Gemma-style drafters) and n_parallel > 1, this call uses _estimate_kv_cache_bytes with its default n_parallel=1. The main KV estimator explicitly scales SWA cache by the serving slot count, so the drafter reserve undercounts the extra per-slot SWA KV and auto-fit/tensor planning can choose a context that does not leave enough VRAM for the actual drafter cache.

Useful? React with 👍 / 👎.

Comment on lines +1957 to 1958
if _usable(ranked[0][0], ranked[0][1]) >= model_size_mib:
return [ranked[0][0]], False

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 Try the largest usable GPU before expanding

With total_by_idx set, _usable() subtracts headroom based on total VRAM, so the GPU with the most free MiB is not necessarily the GPU with the most usable MiB. On mixed or partly occupied cards, this only tests the free-ranked first GPU for a single-GPU fit and can return a multi-GPU/--fit plan even when a slightly lower-free GPU would fit alone, unnecessarily slowing or offloading the load.

Useful? React with 👍 / 👎.

Comment on lines +702 to +704
"--cache-type-v-draft",
"--spec-draft-type-v",
"-ctvd",

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 draft K and V cache types separate

llama.cpp exposes separate draft-cache flags for K and V, both defaulting to f16. Including the V-only aliases in this single found value means an extra arg like --cache-type-v-draft q4_0 makes the reserve price both K and V as q4_0 even though K remains f16, under-reserving roughly the K half of the draft KV cache at long context.

Useful? React with 👍 / 👎.

Comment on lines +4172 to +4174
_compute_buffer_pipeline = self._estimate_compute_buffer_bytes(
n_parallel = n_parallel, per_device_tensor = False
)

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 user ubatch overrides before sizing buffers

-ub/--ubatch-size is an allowed llama-server pass-through arg and is appended after Studio's flags, but this estimate always uses the default 512 micro-batch. If a user raises --ubatch-size for faster prompt processing, llama-server allocates a much larger compute graph than the fit/pin budget reserved here (and in the tensor reserve below), so Studio can still pick a context/GPU set that OOMs at startup.

Useful? React with 👍 / 👎.

Condense the docstrings and inline comments added by this PR (internal backend
helpers): drop restated-signature docstrings, fold multi-line block comments to
one or two lines, and remove notes that just repeat the code. No behavior change
(AST-verified comment/docstring-only via comment_tools.py); the backend test
suite is unchanged and green.

@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: 39845ad69a

ℹ️ 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 +3432 to +3435
reserve_mib = (
_reserve_bytes // (1024 * 1024)
if _reserve_bytes > 0
else self._TENSOR_PARALLEL_BUFFER_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.

P2 Badge Reserve total-VRAM headroom in tensor planning

In the tensor-parallel path, when GGUF dims are available this replaces the old 5 GiB per-device reserve with only the estimated compute buffer (the new tests anchor this at ~600 MiB/device for Qwen), but _plan_tensor_parallel then budgets the entire remaining pool for weights+KV. Unlike the non-tensor branches, this leaves no 5% total-VRAM headroom for CUDA context/allocator slack, so a tensor load whose model+KV fits only in the last few percent of VRAM can still be selected with use_fit=False even though llama.cpp cannot shrink tensor-mode loads and may OOM at startup.

Useful? React with 👍 / 👎.

_mtp_eff_n_max = 2 if gpus else 3
# Separate-drafter weights live on GPU too (an embedded head is
# already in model_size).
_mtp_draft_for_budget = mtp_draft_path or _extra_args_mtp_draft_path(extra_args)

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 Budget the drafter that will actually be launched

When Studio auto-resolves mtp_draft_path and the user also passes a custom --model-draft/-md in extra_args, the custom flag is appended last and overrides the auto drafter at launch, but this or budgets the auto path instead. If the user-selected drafter is larger or has a larger KV cache (for example an F16 copy under MTP/), auto-fit can pin a context/GPU set that only fits the smaller auto drafter and then OOM when llama-server loads the overridden drafter.

Useful? React with 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member Author

/gemini review

@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 replaces flat, conservative VRAM reserves for Multi-Token Prediction (MTP) and tensor-parallel compute buffers with dynamic, byte-accurate estimates derived from GGUF metadata dimensions (such as vocabulary size, embedding length, and draft layers). It also updates GPU memory queries to retrieve total VRAM, enabling absolute headroom capping, and adds comprehensive unit tests to validate these calculations. The review feedback suggests a valuable performance optimization during GGUF metadata parsing: instead of reading the entire large tokenizer.ggml.tokens array into memory via _gguf_read_array_value just to get its length, the code should fast-skip the string array directly in the file stream to avoid significant overhead.

Important

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

Comment on lines +2589 to 2592
# Vocab size = token count; keep the length, not the strings.
if key == "tokenizer.ggml.tokens":
self._vocab_size = int(alen)
val_a = self._gguf_read_array_value(f, atype, alen)

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.

medium

Since tokenizer.ggml.tokens is a very large array of strings (often containing 256,000+ tokens), calling _gguf_read_array_value will loop through all elements and call _gguf_skip_value for each one. This introduces significant Python-level function call and dictionary lookup overhead, which can slow down metadata parsing by several hundred milliseconds on every model load.

Since we only need the array length (alen) to determine the vocabulary size, we can fast-skip the string array directly inside _read_gguf_metadata and continue the loop, avoiding the overhead of _gguf_read_array_value entirely.

                                # Vocab size = token count; keep the length, not the strings.
                                if key == 'tokenizer.ggml.tokens':
                                    self._vocab_size = int(alen)
                                    for _ in range(alen):
                                        slen = struct.unpack('<Q', f.read(8))[0]
                                        f.seek(slen, 1)
                                    continue
                                val_a = self._gguf_read_array_value(f, atype, alen)

danielhanchen and others added 6 commits June 15, 2026 09:58
Five fixes from a parallel-reviewer pass on this PR; all confirmed against the
real functions and covered by new tests.

- Tensor mode now honors the total-based VRAM cap. _plan_tensor_parallel took
  total_by_idx and budgets each GPU at free - (1-frac)*total, mirroring the
  layer-split paths; previously it fit against raw free and could spend the 5%
  safety cushion on a partly-used multi-GPU box (reproduced ~3.3 GB over).

- Draft K and V cache types are parsed and accounted independently. A one-sided
  override (e.g. --cache-type-k-draft q4_0, V left f16) no longer applies the
  small quant to both axes and under-reserves the f16 axis. The embedded-head
  formula sizes per axis; the separate-drafter path uses the heavier type so it
  never under-reserves.

- The compute-graph buffer honors a user --ubatch / --ubatch-size / -ub override
  (parsed and threaded into every _estimate_compute_buffer_bytes call and the
  tensor planner); it previously always assumed the 512 default, under-reserving
  up to ~8x at --ubatch 4096.

- GPU ranking uses the usable budget (free - (1-frac)*total) instead of raw free
  in _select_gpus and both auto-context subset loops, so a more-used large card
  no longer outranks a less-used small card that has more usable room.

Adds regression tests for each (tensor total cap, ubatch reserve scaling, split
K/V no-under-reserve, --ubatch parser, usable-ranking GPU selection). Full
targeted backend suite green (321 passed).
The tensor-parallel GPU admission filters still used raw free VRAM after
the total-based budget landed, an asymmetric fix: a partly-used large card
can clear the per-device compute-buffer reserve on raw free while its usable
budget (free - (1-frac)*total) does not, so the planner admitted it and the
even split could emit a near-zero weight slice for a GPU that should have
been excluded.

- _plan_tensor_parallel: admit GPUs by usable budget, not raw free (move the
  _usable helper above the filter).
- load_model: admit the tensor set by _gpu_usable, and downgrade to layer
  split when the pooled usable budget cannot hold weights plus per-device
  compute buffers (the planner can only floor the context, not stop an
  overcommitted launch).

Adds regression tests: planner drops a GPU whose usable budget is below the
reserve, and a source-level check that load_model admits on the usable
budget and carries the pooled-weight downgrade.
A user --model-draft passed in extra_args is appended last and wins at the
llama-server launch, but the VRAM budget preferred Studio's auto-detected
drafter (mtp_draft_path or extras), so a larger custom drafter was
under-reserved. Flip the precedence to extras-first, matching the draft-depth
(n_max) resolution two lines above. Adds a source-level regression test.
@danielhanchen

Copy link
Copy Markdown
Member Author

VRAM auto-fit: before vs after (measured)

Test model: Qwen3.6-27B-MTP UD-Q6_K_XL (24.2 GiB weights, native ctx 262144, embedded MTP head). Binary: Unsloth llama-server b9625. This is the model/setup from the reports of context dropping after an update.

The change replaces the old free-VRAM fraction (free * (0.90 - 0.05), with a flat MTP reserve folded into the fraction and a footprint re-check against free * 0.85) with a total-based budget (free - (1 - 0.95) * total), a byte-accurate per-context MTP draft reserve, and a deterministic compute-graph buffer reserve.

1. Advertised context recovered (single GPU)

UI context ceiling chosen by the auto-fit for the model above on a 32 GB card, by free VRAM and main KV type. Numbers are the actual _fit_context_to_vram output before (pre-PR main) and after (this PR):

free VRAM main KV before after delta
32000 MiB f16 35840 78848 +120%
32000 MiB q8_0 67584 141824 +110%
32000 MiB q4_0 127744 246016 +93%
31000 MiB f16 23040 64768 +181%
30000 MiB f16 10240 50432 +392%
28000 MiB f16 4096 22016 +438%

The gain grows as free VRAM tightens: the old fraction wasted more of the cushion exactly where weights already dominate.

2. Validated on real hardware (B200, capped to the stated budget)

Each row is a real llama-server load plus a 256-token generation; VRAM is per-PID.

cap ctx main KV GPU used t/s result
32 GB 98k f16 31312 103 fits fully on GPU
32 GB 131k f16 30632 50 KV spills to CPU (too big)
32 GB 154k q8_0 30564 75 quantized KV recovers 154k on GPU
28 GB 98k f16 26766 46 4 GB less free, same ctx now spills
28 GB 37k f16 26454 73 must drop to ~37k for full speed

The after-PR f16 ceiling at ~32 GB free (78848) sits safely under the measured on-GPU max (98k loads at 31312 MiB), and the empirical points match the estimator within 0.1% at 64768 (predicted vs 29348 MiB measured). The 28 GB rows reproduce the reported symptom: losing ~4 GB of free VRAM turns a 98k load from 103 to 46 t/s as KV offloads to CPU. The cause was free-VRAM pressure, not the Studio or llama.cpp version (verified: Studio launch code is byte-identical across the reported versions, and b9496/b9510/b9518/b9585/b9625 all engage MTP identically).

3. The MTP reserve is now byte-accurate

Draft-KV reserve sized from the model's nextn dims, per context:

ctx 16k 65k 131k 262k
reserve (MiB) 64 256 512 1024

vs the old flat 5% of free, which under low free VRAM let the advertised full context silently offload to CPU. The reserve also splits draft K and V cache types independently and honors a user --ubatch override in the compute buffer.

4. Multi-GPU

Both split paths now budget against the same total-based usable VRAM (free - 0.05 * total) per device:

  • Pipeline / layer split (default): pools usable budget across the fewest GPUs that fit.
  • Tensor parallel (opt-in): reserves the deterministic per-device compute-graph buffer (measured ~600 MiB/device at --parallel 1, scaling with serving slots), weights --tensor-split by usable budget, admits GPUs by usable budget (not raw free), and downgrades to layer split when the pooled budget cannot hold weights plus buffers. Validated: 2x24 GB f16 at 262144 used 22190 MiB/device at 98 t/s (within 0.4% of estimate).

Recommendation surfaced by the study

Keep MTP on (~1 GB, ~1.6x speed). The largest single lever for context on a fixed card is quantizing the main KV cache: q8_0 reaches ~154k at ~105 t/s with negligible quality loss; q4_0 reaches ~242k. Exposing main KV cache type in Studio is the highest-value follow-up.

@oobabooga

Copy link
Copy Markdown
Member

I believe this issue is likely to be resolved by this: https://www.reddit.com/r/unsloth/comments/1u59lcz/running_into_issues_with_latest_update/

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

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

_tp_weight_budget_mib = (
sum(_gpu_usable(g) for g in tp_gpus) - len(tp_gpus) * reserve_mib
)
if _tp_weight_budget_mib <= model_size / (1024 * 1024):

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 Include MTP reserve in tensor fallback check

When tensor parallelism is requested for an MTP load with a separate drafter or other byte-accurate MTP reserve, this guard only checks that the main model weights fit after the per-device compute buffers. _plan_tensor_parallel can only shrink context to a floor and the caller then sets use_fit=False, so a pool where the main weights barely fit but drafter weights plus minimum draft KV do not will still launch --split-mode tensor and OOM instead of taking the intended layer-split fallback.

Useful? React with 👍 / 👎.

danielhanchen and others added 2 commits June 15, 2026 11:17
Two issues found by re-review of the prior fix:

- The tensor-parallel capacity gate only checked the model weights against the
  pooled budget, not the MTP reserve. A separate-drafter MTP load whose weights
  fit but weights + drafter do not could still launch overcommitted in tensor
  mode. Add the non-shrinkable MTP reserve (drafter weights + floor draft KV, or
  the flat 2 GiB fallback when dims are unavailable) to the gate.

- The nvidia-smi probe was switched to a three-column query (index,free,total)
  for the total-based budget but required exactly three columns, so a driver or
  mock returning the legacy two-column "index,free" was dropped and the probe
  fell through to the real GPUs. Accept two columns (total 0) and treat an
  unknown total as the legacy free*fraction in _select_gpus.

Tests: tensor gate asserts the MTP term is included; _get_gpu_memory parses both
two- and three-column output; the existing two-column GPU-detection mocks pass
again.
danielhanchen added a commit that referenced this pull request Jun 15, 2026
On a restart the constructor reaps the previous run's orphaned llama-server, but the driver does not reclaim that VRAM synchronously. _kill_orphaned_servers now returns the number of processes it killed, and __init__ arms _last_kill_monotonic when that count is positive, so the first load_model waits for VRAM to settle before ranking GPUs by free memory instead of pinning the model onto the smaller card. The compute-graph / auto-fit reserve is handled separately in #6312.
…unknown

_plan_tensor_parallel fell back to raw free VRAM when a GPU's total was
unavailable (a two-column nvidia-smi probe reporting total 0), while
_select_gpus and the load_model ranking both fall back to free*fraction. That
let tensor planning spend the 5% cushion the rest of the fit preserves and
over-advertise context in exactly that path. Align the fallback to
free*_CTX_FIT_VRAM_FRACTION. Updates the no-totals planner test expectations
(now free*frac) and adds a regression test that total 0 keeps the cushion.

@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: 8ee8fb68c8

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

)
else:
_tp_mtp_floor = 2 * 1024**3 # flat reserve when dims unavailable
_tp_required_mib = (model_size + _tp_mtp_floor) / (1024 * 1024)

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 Include floor KV in tensor fallback gate

When --split-mode tensor is requested on a pool that has room for the weights (and _tp_mtp_floor) but not for the mandatory 2048-token main KV floor, this guard passes because _tp_required_mib excludes the main model KV. _plan_tensor_parallel then clamps the context to 2048 and the caller launches with use_fit=False, so llama.cpp still has to allocate that KV in tensor mode and can OOM instead of taking the layer-split fallback.

Useful? React with 👍 / 👎.

@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: 144f9939a0

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

found: Optional[str] = None
for i, raw in enumerate(args):
flag, eq, inline = raw.partition("=")
if flag not in ("--model-draft", "--spec-draft-model", "-md"):

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 Budget HF draft model overrides

When users pass a draft model via extra args using the HF draft flags, this parser returns None because it only recognizes local --model-draft aliases. I checked llama-server help, which lists --spec-draft-hf, -hfd, -hfrd, and --hf-repo-draft as the draft-model repository flags (https://manpages.debian.org/unstable/llama.cpp-tools/llama-server.1.en.html), and these extra args are appended last at launch; for --spec-type draft-mtp --spec-draft-hf big/repo:Q8_0, the fit budget sizes the embedded/auto drafter instead of the actual HF draft weights/KV, so Studio can pin a context/GPU set that OOMs when llama-server downloads and loads the overridden drafter.

Useful? React with 👍 / 👎.


# Effective micro-batch (a user --ubatch override scales the
# compute buffer); None -> the 512 default in the estimate.
_effective_ubatch = _extra_args_n_ubatch(extra_args)

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 LLAMA_ARG_UBATCH in buffer sizing

When Studio is launched with LLAMA_ARG_UBATCH in its environment, child_env_without_native_path_secret() preserves that env for llama-server and llama-server documents it as the env override for -ub, --ubatch-size (https://manpages.debian.org/unstable/llama.cpp-tools/llama-server.1.en.html). This only reads extra_args, so a service-level LLAMA_ARG_UBATCH=4096 still sizes the compute buffer at the 512 default while the child allocates the larger graph, allowing auto-fit to pin a context/GPU set that can OOM at startup.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

danielhanchen and others added 2 commits June 17, 2026 01:45
A second review pass found the env-aware tensor/MTP handling was applied
asymmetrically: some paths inherited LLAMA_ARG_* env, others didn't. Three real
follow-ups, plus a small consolidation so the env semantics live in one place.

1. Tensor fallback ignored the inherited tensor env. load_with_tensor_fallback
   computed its retry gate with the env-blind resolve_tensor_parallel, so an
   env-only tensor load (toggle off, no --split-mode extra) that crashed on a
   tensor-incompatible GGUF re-raised instead of retrying layer split. It now
   uses the env-aware decision; and since the inherited env would otherwise
   re-engage tensor on the retry (CLI args persist, the env does too), the retry
   forces --split-mode layer (CLI wins over env) so it can't re-crash.

2. Duplicate-load matchers looped reloads after a tensor->layer downgrade. Both
   matchers compared the env-expanded tensor decision against the loaded server,
   but load_model may downgrade tensor to layer (capacity/buffer) and scrub the
   child env. The still-set parent env then made every identical request look
   like a mismatch, killing and reloading a healthy layer server. Add
   _tensor_parallel_matches_loaded, which only lets an inherited tensor env raise
   a match against a server that actually launched tensor; a downgraded server
   matches the same request (an identical load would downgrade the same way).

3. MTP binary-capability fallback leaked an inherited LLAMA_ARG_SPEC_TYPE. When
   the binary lacks MTP, _emit_mtp degraded but emitted no spec flag, so an
   inherited LLAMA_ARG_SPEC_TYPE=draft-mtp still reached the child and attempted
   MTP the gate had budgeted off. It now emits --spec-default (CLI wins over env)
   like the sibling no-head / non-MTP fallbacks.

Consolidation: moved _env_split_mode_is_tensor / _effective_tensor_parallel into
llama_server_args.py (with the new _tensor_parallel_matches_loaded) so the
lightweight tensor_fallback module can share them without importing llama_cpp;
llama_cpp re-exports them for back-compat.

All gated on inherited env the documented benchmarks don't set; the single-GPU,
tensor and pipeline reconfirm numbers are byte-identical, and the full backend
suite passes (883) with regression tests for each fix.
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

A review pass found the explicit-extras counterpart of the env cache-type fix.
load_model adopts the heavier inherited LLAMA_ARG_CACHE_TYPE_K/_V env for the
reserve, but the explicit-extras path used resolve_cache_type_kv, which collapses
both axes to one last-wins value. So extras such as
--cache-type-k f32 --cache-type-v f16 (lighter axis last) budgeted f16 for both
axes while the child allocates f32 on K, over-advertising context and
re-opening the OOM path this PR closes.

Add parse_cache_override_per_axis (keeps the K/V last-wins values apart) and
_extra_args_main_cache_type_for_budget (the heavier of the two by bytes/elem),
and budget from it. The user's extras are appended last and win per axis at the
child, so this only raises the reserve; the emitted command and the asymmetric
child cache are unchanged, and the common single-axis / symmetric cases resolve
to the same type as before.

Reconfirm numbers (single-GPU table, tensor, pipeline) are byte-identical, and
the full backend suite passes (892) with per-axis parser and heavier-axis budget
regression tests.
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

…ctors

A review pass found two more env/extras edge cases on the speculative and tensor
cache paths.

Tensor-safety could miss a quantized axis. The previous change budgets the
heavier-by-bytes cache type, but that masks a quantized axis paired with a
heavier one: --cache-type-k f16 --cache-type-v q4_0 resolves to f16, so the
tensor-safety block did not fire and the q4_0 axis survived into tensor mode,
which aborts on quantized KV. Test each explicit --cache-type-k/-v axis (not just
the budget type) so any quantized axis drops the cache for the tensor attempt.

Inherited HF drafter selectors were not stripped. _extra_args_mtp_draft_path
treats --spec-draft-hf / -hfd / -hfrd / --hf-repo-draft as drafter selectors, but
_SPEC_FLAGS only stripped the local --model-draft selectors, so on an inherited-
extras Apply a stale HF drafter survived and last-wins-overrode Studio's
re-derived spec choice. Add the HF aliases to _SPEC_FLAGS. The per-drafter tuning
knobs (--spec-draft-type-*, -ngld, --spec-draft-device) are intentionally left in
place: the VRAM budget reads them via the same parsers the child honors, so they
stay consistent on inherit, and stripping them would silently move a CPU-offloaded
drafter back onto the GPU.

A third flagged item -- that the HF draft env var should be LLAMA_ARG_HFD_REPO --
was a false positive from a stale manpage; the bundled binary's common/arg.cpp
sets LLAMA_ARG_SPEC_DRAFT_HF_REPO for --spec-draft-hf, which the code already
uses, so it is left unchanged.

Reconfirm numbers (single-GPU table, tensor, pipeline) are byte-identical, and
the full backend suite passes (899) with regression tests for both fixes.
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

…after reserve

A review pass found two more tensor-path edges, one a regression from the
per-axis cache change.

Tensor-to-layer downgrade collapsed asymmetric cache extras. The per-axis
tensor-safety check strips an asymmetric --cache-type-k/-v (tensor rejects
quantized KV), but the downgrade restored only the scalar heavier type, so a
layer fallback silently rewrote --cache-type-k q4_0 --cache-type-v f16 to
symmetric f16/f16 even though layer split supports the original. Save the
original extras before the tensor strip and restore them verbatim (minus the
user --split-mode) on both downgrade points; the budget still uses the heavier
scalar, the child gets the real asymmetric cache. Before the per-axis change this
case happened to survive (last-wins was f16, untouched), so this restores that.

Tensor mode reserved GPU VRAM for a CPU-offloaded drafter. The layer path drops
the flat MTP reserve when the only drafter is a separate CPU one with no embedded
head, but the tensor capacity gate and planner still charged it, under-advertising
context. Gate the tensor reserve on the same condition via _mtp_reserves_gpu.

Reconfirm numbers (single-GPU table, tensor, pipeline) are byte-identical (both
fixes are gated on conditions the benchmarks don't hit), and the full backend
suite passes (901) with regression tests for each.
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

The refactor re-pointed load_model and the matchers off resolve_tensor_parallel /
resolve_cache_type_kv and moved the env split-mode helper into llama_server_args,
leaving those three names imported but unused in llama_cpp. The repo's import-hoist
safety-net lint blocks that, so drop them; the env split-mode test now imports
_env_split_mode_is_tensor from its real home (llama_server_args).
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

Bring the branch up to date with main so the import-hoist lint diffs against a
current base (clears the stale-base false-positive on main's scan_packages.py
urllib import, which this branch never touched).
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@danielhanchen
danielhanchen merged commit 0e69614 into main Jun 17, 2026
33 checks passed
@danielhanchen
danielhanchen deleted the studio-mtp-vram-autofit branch June 17, 2026 10:10
danielhanchen added a commit that referenced this pull request Jun 18, 2026
…GLM-5.2 OOM) (#6447)

* Studio: reserve the duplicated MTP target KV context for MLA models

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.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: stub structlog/loggers in MTP-MLA test so it is import-order-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.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen added a commit that referenced this pull request Jun 19, 2026
…#6449)

_estimate_mtp_overhead_bytes is also reached for the separate-drafter spec modes
(draft-simple / draft-eagle3) through _user_draft_via_extras. Those modes load a
small distinct drafter with its own KV -- already counted in the draft KV +
weights -- and keep no duplicated full target context; only MTP runs a second
context over the target model's own KV geometry (llama.cpp ctx_tgt). Charging the
~main-KV-sized f16 copy there over-reserved by tens of GiB on an MLA model and
needlessly shrank the advertised context, the same under-advertising #6312 set
out to fix.

Thread mtp_keeps_target_ctx through _estimate_mtp_overhead_bytes (True for MTP,
False for separate-drafter modes) and derive _engaged_is_mtp at the fit call site
so the target copy is added only when the engaged mode is actually MTP. MLA + MTP
(GLM-5.2 / DeepSeek / Kimi) is unchanged, so the GLM-5.2 OOM fix is preserved;
non-MLA and the draft-simple / draft-eagle3 paths no longer pay the copy.

test_mtp_mla_target_ctx.py adds a case asserting the separate-drafter reserve
collapses to the draft KV (no target copy) while the default MTP path keeps it.
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.

2 participants