* studio: reserve MTP draft VRAM in GGUF auto-fit 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. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: total-based VRAM budget + deterministic compute-graph buffer 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. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: tighten comments in the VRAM auto-fit changes 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. * studio: address review findings in the VRAM auto-fit budget 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). * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: gate tensor-parallel admission on usable VRAM budget 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. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: size the MTP reserve for the user's overriding drafter 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. * studio: account for MTP reserve in tensor gate, restore 2-col GPU probe 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. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: keep the VRAM cushion in tensor planning when GPU totals are 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. * studio: honor LLAMA_ARG_* env overrides and HF draft flags in the VRAM budget The budget parsed llama-server flags only from the request's extra_args, but the child process inherits Studio's full environment (child_env_without_native_path_secret copies os.environ), and llama-server honors LLAMA_ARG_* env vars for the same options. So a service-level override the child acts on was invisible to the fit, which could then advertise a context/GPU set that OOMs at load. - _extra_args_n_ubatch: fall back to LLAMA_ARG_UBATCH (drives the compute buffer; an unseen 4096 vs the 512 default under-reserves ~8x). - _extra_args_mtp_draft_path: also recognize the HF draft-repo flags (--spec-draft-hf/-hfd/-hfrd/--hf-repo-draft) and fall back to LLAMA_ARG_SPEC_DRAFT_MODEL / LLAMA_ARG_SPEC_DRAFT_HF_REPO. An HF repo isn't a local file so it can't be sized, but recognizing it routes to the flat reserve instead of mis-sizing Studio's auto/embedded drafter. - _extra_args_draft_cache_types: fall back to LLAMA_ARG_SPEC_DRAFT_CACHE_TYPE_K/_V per axis. CLI extra_args win over env (they are appended last at launch). Each parser takes an injectable env for deterministic tests. Adds env-fallback and HF-flag tests. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: review polish - drop non-flag --ubatch, harden GPU probe, document buffer Non-blocking items from a second review pass; no behavior change in the common path: - _extra_args_n_ubatch: drop --ubatch; the binary only accepts --ubatch-size/-ub, so parsing --ubatch implied support it does not have (it would over-reserve for a launch that fails on the unknown flag). - _get_gpu_memory: skip a malformed nvidia-smi line instead of letting one bad line raise and drop the whole NVIDIA probe to the torch fallback. - _estimate_compute_buffer_bytes: document that the per-slot output-buffer model assumes a small n_outputs_max (chat decode); it would under-count for embeddings / --logits-all / reranking, which Studio does not run on this path. * studio: honor LLAMA_ARG_SPEC_TYPE when deciding the MTP reserve _extra_args_requests_mtp only checked extra_args, but the child inherits Studio's env and llama-server honors LLAMA_ARG_SPEC_TYPE. So a service-level LLAMA_ARG_SPEC_TYPE=draft-mtp would run MTP while the fit skipped the draft reserve and could advertise a context/GPU set that OOMs at load. Recognize the env value (CLI still wins). Completes the env-override coverage alongside ubatch, draft model, and draft cache types. Adds an env regression test. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: reserve VRAM for non-MTP model-based draft modes too The draft reserve only engaged for MTP. A user passing a non-MTP model-based draft mode (--spec-type draft-simple / draft-eagle3) with a --model-draft loads a separate draft model whose weights + KV consume GPU memory, but the fit reserved nothing and could OOM at load. Engage the existing drafter reserve for those modes when extras (or LLAMA_ARG_SPEC_TYPE) name a drafter; ngram-* load no model and are unaffected. Purely additive (reserves where there was none). Adds parser + gate tests. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: floor quantized embedded MTP draft KV at f16; fix two test issues Address PR review feedback (three findings): 1. Quantized embedded MTP draft KV was underpriced. The embedded head is a single draft layer, so llama.cpp cannot amortize quantized-KV overhead over many layers the way the main model does: a quantized draft KV (e.g. --spec-draft-type-k q4_0) actually fits LESS context than f16, not more (ggml-org/llama.cpp#24102, where a collaborator recommends f16 for the draft KV). Pricing q4_0 at 0.5625 of an element (~28% of f16) under-reserved, so a quantized override could advertise a context that shrinks or OOMs at load. Floor the embedded draft KV bytes-per-element at f16 (quantized types priced as f16, f32 still its full 4 bytes). The separate multi-layer drafter, where quantization does amortize, keeps the user's real type. 2. test_load_model_reserves_for_non_mtp_draft_modes asserted an exact one-line source substring that pre-commit black wrapped across lines, breaking CI. Strip whitespace before matching so the check survives any line-wrapping. 3. test_compute_buffer.py installed a partial httpx stub via setdefault that, if collected before test_kv_cache_estimation.py, leaked into sys.modules without HTTPError/Response and could break the transformers introspection tier by collection order. Adopt the sister file's pattern: only stub when real httpx is absent, and include the full symbol set. Updates the affected draft-KV tests to assert the f16 floor. * studio: guard httpx stub in test_mtp_vram_budget too test_mtp_vram_budget.py installed a partial httpx stub via setdefault that, like test_compute_buffer.py before it, lacked HTTPError/Response and could leak into sys.modules ahead of tests that need huggingface_hub/transformers, breaking the introspection tier by collection order. Apply the same guard used by test_kv_cache_estimation.py: only stub when real httpx is absent, with the full symbol set. * studio: per-device layer-split reserve, effective spec-type, drafter weights, KV restore Address PR review feedback (four findings in the auto-fit budget): A. Reserve the per-device layer-split overhead. A layer (pipeline) split allocates a fixed per-device overhead (CUDA context + per-device compute scratch) on every participating GPU, beyond the slot-scaling compute buffer that is conserved across the split. Measured ~0.9 GB/device on the Qwen3.6-27B GGUF (b9625), independent of --parallel: layer-split TOTAL VRAM grew +894 MiB (parallel=8) / +946 MiB (parallel=1) per extra GPU, ~linear to +2.6 GB at 4 GPUs. The fit folded a single compute buffer for all subset sizes, so a k-GPU layer split was short by ~(k-1)*0.9 GB and could pin a context that fits the pool on paper but OOMs a device. Reserve (k-1) * _PIPELINE_PER_DEVICE_OVERHEAD_MIB per subset in the layer-split fit; k=1 adds nothing, so single-GPU sizing (and the validated benchmark rows) is unchanged. B. Track the effective --spec-type. _extra_args_requests_mtp returned true on the first MTP-ish --spec-type and consulted LLAMA_ARG_SPEC_TYPE even when a CLI --spec-type was present, contrary to llama.cpp (last CLI value wins; a CLI flag overrides the env). So `--spec-type draft-mtp --spec-type ngram-mod` or a non-MTP CLI value with a stale MTP env over-reserved a drafter the launch won't load (shrinking context / selecting extra GPUs). Route both detectors through a new _effective_spec_type helper. C. Keep known drafter weights in the fallback reserve. When a separate drafter's KV metadata can't be sized, _estimate_mtp_overhead_bytes returned None and discarded the drafter's known weight bytes, falling back to the flat 5% reserve; a drafter larger than that cushion could launch over budget and OOM. Reserve the known weights even when KV sizing fails (None only when nothing is known). D. Restore quantized KV on tensor->layer-split downgrade. The tensor attempt drops a quantized KV cache (tensor mode aborts on it). When the GPU-count or capacity gate then downgrades to layer split -- which supports quantized KV -- the dropped type was lost and the launch used f16, using more VRAM and shrinking context. Remember the dropped type and restore it on downgrade (the launch re-emits it from the var). Adds regression tests for each. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: per-device overhead in GPU pin, skip CPU draft, gate env spec-type Address PR review feedback (three follow-up findings): F1. Reserve the per-device layer-split overhead in the pin path too. The earlier per-device reserve was added to the auto-context fit loops but not to _select_gpus, which the explicit-ctx and file-size-only paths use to PIN GPUs with -ngl -1 (no --fit fallback). A 2+ GPU pin within ~1 GiB/extra-GPU of the budget could OOM a device at load. Add a per_device_overhead_bytes arg to _select_gpus so a k-GPU pin must hold model + (k-1)*overhead; pass the pipeline overhead at both pin call sites. Single-GPU pins are unchanged. F2. Don't charge a CPU-offloaded drafter against the GPU budget. A user passing --spec-draft-ngl 0 or --spec-draft-device none/cpu keeps the separate draft model's weights + KV on CPU, but the budget still charged the full drafter GGUF size, auto-reducing context or downgrading GPU selection. Detect the CPU-offload flags and drop the separate drafter (and its flat fallback) from the budget; an embedded head follows the main -ngl and is unaffected. F3. Consult LLAMA_ARG_SPEC_TYPE only when it can reach the child. llama-server's CLI args override env, and _build_speculative_flags emits a --spec-type/--spec-default for every UI mode except "off". So a stale MTP env on a non-MTP model (auto mode) made the fit reserve MTP that the emitted --spec-default disables, shrinking context / picking extra GPUs. Gate the env consult on "no user --spec-type and UI mode off"; the MTP-model auto path still engages via Studio's own detection. Adds regression tests for each. * studio: drafter budget precedence and --spec-default in effective spec-type Two spec-precedence fixes surfaced by an independent multi-reviewer pass: R3. Size the drafter the launch actually loads. _mtp_draft_for_budget consulted LLAMA_ARG_SPEC_DRAFT_MODEL (via _extra_args_mtp_draft_path's env fallback) before Studio's resolved mtp_draft_path, but _build_speculative_flags emits --model-draft mtp_draft_path, which overrides the env at launch. With a stale (smaller) env drafter, the budget under-reserved and could OOM. Order the budget by what actually launches: CLI extras --model-draft (appended last, wins), then Studio's emitted mtp_draft_path (when MTP engages and the user doesn't own --spec-type), then the env drafter. R4. Treat --spec-default as a CLI spec override in _effective_spec_type. It only recognized --spec-type, so extras=["--spec-default"] with LLAMA_ARG_SPEC_TYPE= draft-mtp fell through to the env and over-reserved MTP, even though the CLI --spec-default overrides the env to a non-MTP default. Recognize it as a CLI spec flag (resolves to "default", non-MTP) that suppresses the env fallback. Adds regression tests for each. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: refine MTP draft reserve (parallel slots, last-wins, KV cushion, ranking) Address PR review feedback (five follow-up findings, all edges of this session's earlier MTP/auto-fit changes): G1. Price the separate drafter's KV per --parallel slot. _mtp_draft_kv_bytes called the drafter's _estimate_kv_cache_bytes with the default n_parallel=1, but the drafter is served under the main model's slot count; a sliding-window drafter (Gemma) grows KV per slot and was under-reserved. Thread n_parallel through the draft KV / overhead estimate and the fit closure. G2. Honor last-wins for the draft-offload flags. _extra_args_draft_offloaded_to_cpu returned True on the first CPU value, so --spec-draft-ngl 0 --spec-draft-ngl -1 (final = GPU) wrongly dropped the drafter reserve while the server kept it on GPU -> OOM. Decide on the final value of each flag only. G3. Keep the flat cushion when only the drafter weights could be sized. The weights fallback installs mtp_overhead_fn, which made callers drop the flat MTP reserve, leaving the still-unsized draft KV with no cushion. Keep the flat fraction on in that weights-only case, on top of the byte-accurate weights. G4. Rank auto/cap GPU subsets by the active budget fraction. The ranking used a hard-coded 0.95 while the fit tests _pin_fraction (lowered by the flat MTP reserve); on mixed-total GPUs that could order subsets differently and pick a worse plan. Rank with the same fraction the fit uses. G5. Keep the embedded-head flat reserve under a draft CPU-offload flag. F2's not-_draft_on_cpu guard also dropped the reserve for an embedded MTP head, which is part of the main model and stays on GPU regardless of --spec-draft-ngl. Only suppress the flat reserve for a CPU-offloaded separate drafter (no embedded head). Adds regression tests for each. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: keep GPU on non-integer total, keep tensor flat reserve for weights-only Two review findings: - _get_gpu_memory dropped a whole GPU when nvidia-smi reported a non-integer memory.total ("N/A" on some drivers / MIG / vGPU): index, free and total were parsed in one try/except that skipped the line on any ValueError, so the GPU vanished from the probe and the load could silently spill to CPU. Parse index and free (required) first, then total separately, defaulting to 0 (the fit then uses the free*frac path for that GPU). Adds N/A and bad-free test cases. - Tensor planning skipped the flat MTP reserve for a weights-only drafter (file size known, KV unsizable): the capacity gate used the byte floor whenever mtp_overhead_fn was set, so it reserved only the drafter weights and no draft KV. Tensor mode has no --fit valve, so that could overcommit and OOM. Keep the flat reserve (never below the byte floor) in the weights-only case too, mirroring the layer-split _mtp_kv_unsized handling. Adds a regression test. (A third suggestion -- fold --batch-size into the compute-buffer reserve -- was checked on hardware and declined: -b 8192 -ub 512 used identical VRAM to the default at -c 64000, so the logical batch does not size the graph buffer; the estimate correctly uses the physical micro-batch.) * studio: budget the main KV from LLAMA_ARG_CACHE_TYPE env when Studio emits none The child inherits LLAMA_ARG_CACHE_TYPE_K / LLAMA_ARG_CACHE_TYPE_V, but Studio emits --cache-type-k/-v only when the param or extras set the type. When neither does, a heavier env type (f32) reaches the child while the auto-fit budget assumed the f16 default, under-reserving the main KV and risking OOM at the advertised context. This is the one main-KV axis that lacked the env-aware handling the other axes already have (spec-type, draft model, draft cache type, ubatch). load_model now adopts the heavier of the two env types when it exceeds f16 (only f32 does), and the launch re-emits it so child and budget stay byte-consistent. Quantized env types are <= f16 and remain safely over-reserved by the default, so they are left untouched (no change). A single value is used because the budget's KV estimate has one cache_type_kv knob, matching parse_cache_override's existing key/value collapse. Adds _env_main_cache_type_for_budget plus regression tests covering f32 adoption, the K/V heavier-of collapse, quantized/unknown no-ops, and the load_model source precedence. * studio: budget tensor parallel when LLAMA_ARG_SPLIT_MODE env selects it Studio emits --split-mode tensor only on its tensor branch; the default layer-split path emits nothing and resolve_tensor_parallel consults only extras. The child inherits LLAMA_ARG_SPLIT_MODE, so a tensor env on a layer-split plan silently runs the child tensor-parallel (heavier per-device compute buffer) while the budget reserved only the layer-split per-device overhead, under- reserving on multi-GPU. load_model now flips the plan to tensor when extras do not set a split mode and the env selects tensor, so Studio plans, reserves, and emits tensor consistently. The flip is one-directional (guarded on not tensor_parallel and no extras split-mode) so an existing tensor plan is never downgraded and extras keep precedence. Other env modes (layer/row/none) are not a runtime-heavier surprise and are left untouched. Adds _env_split_mode_is_tensor plus unit and load_model source-level tests. * studio: reconcile inherited llama.cpp env with the budgeted launch decision Addresses a review pass over the VRAM auto-fit work. The budget now sizes the right amount, but the child process inherits LLAMA_ARG_* env (see child_env_without_native_path_secret), and a few axes could still run the child in a mode Studio neither chose nor budgeted. Mixed known/unknown GPU totals over-advertised the pooled layer-split budget. _pool_budget_mib pooled free and total separately, so an unknown-total GPU (MIG/vGPU/N/A) contributed its full free with no cushion when mixed with known-total GPUs (~(1-frac)*free over-advertise, about 500 MiB in a two-GPU case). It now sums each GPU's own usable budget, and the layer-split fit calls take that as an absolute budget (budget_frac=1.0, total_mib=None) so the fit and the footprint check agree. All-known-total pools are unchanged. LLAMA_ARG_SPLIT_MODE=tensor survived a tensor-to-layer downgrade. The downgrade only stripped CLI extras, so the inherited env still ran the child tensor while Studio budgeted layer split. When the final decision is layer split, a non-layer inherited split mode (and any paired LLAMA_ARG_TENSOR_SPLIT) is now cleared from the child env. Inherited quantized LLAMA_ARG_CACHE_TYPE_K/_V crashed tensor mode. Tensor mode aborts on a quantized KV cache; Studio drops a quantized cache_type_kv for the tensor attempt but the inherited env reached the child anyway. When the final decision is tensor split, a quantized cache-type env is now cleared so the child uses the tensor-safe default that was budgeted. Env-derived cache budget no longer mutates the emitted launch flags. An env-only main KV type now informs the budget only; it is not re-emitted, so an asymmetric K=f32,V=f16 env reaches the child as set instead of being rewritten to symmetric --cache-type-k/-v f32. Adds source-level regression tests for all four and confirms the documented single-GPU/tensor/pipeline numbers are byte-identical before and after. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: tighten comments in the VRAM auto-fit code Compress the verbose docstrings and inline comments added by this work to succinct 2-4 line versions, drop restated/obvious ones, and cut duplicated rationale across the two tensor-downgrade branches. Keeps the non-obvious intent (env-inheritance precedence, the #24102 embedded-draft floor, the per-device overhead and pool-budget rationale) while removing roughly 120 lines of comment text from llama_cpp.py. Also trims the few longest test-comment blocks; concise per-test scenario notes are left intact. No logic change: verified with comment_tools.py check --strip-docstrings (code- only signature unchanged vs the prior commit) and the full backend suite still passes (824). * studio: lock in env-drafter engagement for the separate-draft reserve A review suggested an env-provided LLAMA_ARG_SPEC_DRAFT_MODEL would skip the draft reserve and OOM. It does not: the gate's _extra_args_mtp_draft_path(extra_args) call defaults env=None, which consults os.environ, so an env-only drafter still sets _user_draft_via_extras and is sized via _env_draft_for_budget. Add a source guard that the gate keeps the env-inclusive form (not extras-only env={}) and a behavioral test mirroring the reviewed scenario, so a future cleanup can't regress it. No production change. * studio: carry the unsized MTP reserve and env split/offload into tensor planning Addresses a review pass over the multi-GPU and env-inheritance paths. Tensor planner dropped the unsized draft-KV cushion. When a separate drafter has known weights but unreadable KV metadata, _plan_tensor_parallel receives a non-None weights-only mtp_overhead_fn and applied the flat 2 GiB reserve only for the no-fn case, so its binary search spent the unsized-KV cushion on context and over-advertised. Add mtp_flat_reserve_bytes (subtracted from the pooled budget and the even-split check), and pass it from load_model whenever _mtp_kv_unsized. The layer path and the tensor pre-gate already kept this cushion. Stale LLAMA_ARG_TENSOR_SPLIT survived in tensor mode. When the planner picks an even split it emits no --tensor-split, so an inherited tensor-split env reached the child and overrode the budgeted split. The layer downgrade branch cleared it; the tensor branch now does too. Env-only draft CPU offload was ignored. _extra_args_draft_offloaded_to_cpu checked extras but not LLAMA_ARG_N_GPU_LAYERS_DRAFT, so an env-offloaded drafter was still charged GPU budget and under-advertised context. It now consults that env (the device flag has no env), called with env=os.environ. Layer-split compute buffer had no fallback when GGUF dims are missing. The estimate returns 0 then, so the layer path folded no buffer while the tensor path falls back to the flat reserve. Use the flat reserve for the layer path too (a safe upper bound, since the tensor buffer >= the layer one). All four are gated on conditions the documented benchmarks don't hit; the single-GPU/tensor/pipeline reconfirm numbers are byte-identical, and the full backend suite passes (830) with regression tests for each fix. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: share the env-aware tensor decision across load and dedup matchers A review pass found the inherited-LLAMA_ARG_SPLIT_MODE=tensor flip lived only in load_model, so the two duplicate-load matchers disagreed with it. Consolidate the decision into _effective_tensor_parallel (extras + toggle, then flip on when extras set no split mode and the child inherits a tensor split env). load_model, the backend matcher (_already_in_target_state) and the route matcher (_request_matches_loaded_settings) now all call it. Before, an env-driven tensor server compared against resolve_tensor_parallel (env-blind) in both matchers, so a follow-up load that should dedup was seen as a mismatch and the healthy server was needlessly killed and reloaded. Also finish the tensor cache-type handling: when the tensor attempt drops a quantized KV it now re-adopts a heavier inherited env cache type (f32) for the budget, mirroring the initial adoption; and the two layer-split downgrades clear _cache_type_from_env so the restored quantized type is actually re-emitted rather than left to a stale inherited env. 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 (832) with unit + source regression tests for the shared helper and the route matcher. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: complete the env-aware tensor/spec handling across all paths 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. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: budget the heavier axis of asymmetric --cache-type-k/-v extras 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. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: fix tensor-safety masking and strip inherited HF drafter selectors 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. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: preserve asymmetric cache on tensor downgrade and skip CPU-drafter 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. * studio: drop now-unused llama_server_args imports from llama_cpp 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). --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1002 lines
49 KiB
Python
1002 lines
49 KiB
Python
# SPDX-License-Identifier: AGPL-3.0-only
|
|
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
|
|
|
|
"""Tests for the deterministic MTP VRAM reserve used by load-time auto-fit.
|
|
|
|
reserve(ctx) = draft_KV(ctx, draft_cache_type) + separate_drafter_weights, sized
|
|
from GGUF dims (embedded head from the main model's dims; separate drafter from
|
|
its own KV). Anchors checked against real llama-server measurements. Pure: no
|
|
GPU, network, subprocess, or GGUF I/O."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import inspect
|
|
import os
|
|
import sys
|
|
import types as _types
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Stub heavy/unavailable deps before importing the module under test.
|
|
# ---------------------------------------------------------------------------
|
|
|
|
_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
|
|
if _BACKEND_DIR not in sys.path:
|
|
sys.path.insert(0, _BACKEND_DIR)
|
|
|
|
_loggers_stub = _types.ModuleType("loggers")
|
|
_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)
|
|
sys.modules.setdefault("loggers", _loggers_stub)
|
|
|
|
sys.modules.setdefault("structlog", _types.ModuleType("structlog"))
|
|
|
|
# httpx -- only stub when the real library is missing. Unconditional stubbing
|
|
# shadows HTTPError/Response that huggingface_hub.errors imports at load time,
|
|
# silently breaking the transformers introspection tier in tests collected after
|
|
# this one (the stub leaks via sys.modules for the whole session).
|
|
try:
|
|
import httpx as _httpx_real # noqa: F401
|
|
except ImportError:
|
|
_httpx_stub = _types.ModuleType("httpx")
|
|
for _exc_name in (
|
|
"ConnectError",
|
|
"TimeoutException",
|
|
"ReadTimeout",
|
|
"ReadError",
|
|
"RemoteProtocolError",
|
|
"CloseError",
|
|
"HTTPError",
|
|
"RequestError",
|
|
):
|
|
setattr(_httpx_stub, _exc_name, type(_exc_name, (Exception,), {}))
|
|
_httpx_stub.Timeout = type("Timeout", (), {"__init__": lambda self, *a, **kw: None})
|
|
_httpx_stub.Response = type("Response", (), {})
|
|
_httpx_stub.Client = type(
|
|
"Client",
|
|
(),
|
|
{
|
|
"__init__": lambda self, **kw: None,
|
|
"__enter__": lambda self: self,
|
|
"__exit__": lambda self, *a: None,
|
|
},
|
|
)
|
|
sys.modules["httpx"] = _httpx_stub
|
|
|
|
from core.inference.llama_cpp import ( # noqa: E402
|
|
_CTX_FIT_VRAM_FRACTION,
|
|
LlamaCppBackend,
|
|
_extra_args_draft_cache_types,
|
|
_extra_args_draft_offloaded_to_cpu,
|
|
_extra_args_mtp_draft_path,
|
|
_extra_args_n_ubatch,
|
|
_extra_args_requests_mtp,
|
|
_extra_args_requests_separate_draft,
|
|
_extra_args_spec_draft_n_max,
|
|
_effective_tensor_parallel,
|
|
_env_main_cache_type_for_budget,
|
|
_extra_args_main_cache_type_for_budget,
|
|
_kv_bytes_per_elem,
|
|
_tensor_parallel_matches_loaded,
|
|
)
|
|
from core.inference.llama_server_args import _env_split_mode_is_tensor # noqa: E402
|
|
|
|
MIB = 1024 * 1024
|
|
GIB = 1024**3
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Helpers
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def _make_backend(
|
|
*,
|
|
nextn = 1,
|
|
n_kv_heads = 4,
|
|
n_heads = 24,
|
|
kv_key_length = 256,
|
|
kv_value_length = 256,
|
|
embedding_length = 5120,
|
|
n_layers = 65,
|
|
native_ctx = 262144,
|
|
):
|
|
"""Qwen3.6-27B-MTP-class backend (embedded head) with the MTP-math dims."""
|
|
b = LlamaCppBackend.__new__(LlamaCppBackend)
|
|
b._nextn_predict_layers = nextn
|
|
b._n_kv_heads = n_kv_heads
|
|
b._n_heads = n_heads
|
|
b._kv_key_length = kv_key_length
|
|
b._kv_value_length = kv_value_length
|
|
b._embedding_length = embedding_length
|
|
b._n_layers = n_layers
|
|
b._context_length = native_ctx
|
|
# Hybrid attention/Mamba (qwen35 path) + remaining KV-estimator fields.
|
|
b._shared_kv_layers = 0
|
|
b._kv_lora_rank = None
|
|
b._sliding_window = None
|
|
b._sliding_window_pattern = None
|
|
b._ssm_inner_size = 6144
|
|
b._full_attention_interval = 4
|
|
b._key_length_mla = None
|
|
b._n_kv_heads_by_layer = None
|
|
b._kv_key_length_swa = None
|
|
b._kv_value_length_swa = None
|
|
b._draft_backend_cache = None
|
|
return b
|
|
|
|
|
|
class _StubDrafter:
|
|
"""Stand-in for a separate drafter backend (no GGUF I/O)."""
|
|
|
|
def __init__(self, kv_per_token):
|
|
self._kv_per_token = kv_per_token
|
|
|
|
def _can_estimate_kv(self):
|
|
return True
|
|
|
|
def _estimate_kv_cache_bytes(
|
|
self,
|
|
n_ctx,
|
|
cache_type = None,
|
|
n_parallel = 1,
|
|
**_k,
|
|
):
|
|
bpe = _kv_bytes_per_elem(cache_type)
|
|
# n_parallel scales like a sliding-window drafter's per-slot KV.
|
|
return 0 if n_ctx <= 0 else int(n_ctx * self._kv_per_token * bpe / 2.0 * n_parallel)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Embedded draft KV: deterministic from nextn dims, scales with ctx + draft type
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestEmbeddedDraftKv:
|
|
def test_scales_linearly_with_context(self):
|
|
b = _make_backend()
|
|
kv_8k = b._mtp_draft_kv_bytes(8192)
|
|
kv_16k = b._mtp_draft_kv_bytes(16384)
|
|
kv_64k = b._mtp_draft_kv_bytes(65536)
|
|
assert kv_8k and kv_16k and kv_64k
|
|
assert kv_16k == pytest.approx(2 * kv_8k)
|
|
assert kv_64k == pytest.approx(8 * kv_8k)
|
|
|
|
def test_value_matches_dim_formula_f16(self):
|
|
# nextn(1) * n_kv(4) * (256+256) * 2(f16) * ctx -- no magic safety factor.
|
|
b = _make_backend()
|
|
ctx = 131072
|
|
expected = int(1 * 4 * 512 * 2.0 * ctx)
|
|
assert b._mtp_draft_kv_bytes(ctx) == expected
|
|
# And that is 512 MiB, matching the measured 27B draft-KV slope (~4 MiB/1k).
|
|
assert b._mtp_draft_kv_bytes(ctx) / MIB == pytest.approx(512, abs = 1)
|
|
|
|
def test_scales_with_nextn_predict_layers(self):
|
|
one = _make_backend(nextn = 1)._mtp_draft_kv_bytes(65536)
|
|
two = _make_backend(nextn = 2)._mtp_draft_kv_bytes(65536)
|
|
assert two == pytest.approx(2 * one)
|
|
|
|
def test_embedded_draft_kv_floored_at_f16(self):
|
|
# The embedded MTP head is one layer, so llama.cpp's quantized-KV
|
|
# overhead is not amortized: a quantized draft KV fits LESS context than
|
|
# f16, not more (ggml-org/llama.cpp#24102). The embedded reserve floors a
|
|
# quantized draft type at f16 (never under-reserved); f32 still costs more.
|
|
b = _make_backend()
|
|
f16 = b._mtp_draft_kv_bytes(65536, draft_cache_type_k = "f16", draft_cache_type_v = "f16")
|
|
q8 = b._mtp_draft_kv_bytes(65536, draft_cache_type_k = "q8_0", draft_cache_type_v = "q8_0")
|
|
q4 = b._mtp_draft_kv_bytes(65536, draft_cache_type_k = "q4_0", draft_cache_type_v = "q4_0")
|
|
f32 = b._mtp_draft_kv_bytes(65536, draft_cache_type_k = "f32", draft_cache_type_v = "f32")
|
|
assert q8 == f16 and q4 == f16 # quantized draft KV priced as f16, not less
|
|
assert f32 == pytest.approx(f16 * 2.0) # f32 genuinely larger, not floored
|
|
|
|
def test_draft_kv_split_axes_no_under_reserve(self):
|
|
# A quantized draft type on either or both axes never reserves below the
|
|
# all-f16 value for the single-layer embedded head (the f16 floor; #24102).
|
|
b = _make_backend()
|
|
both_q4 = b._mtp_draft_kv_bytes(
|
|
131072, draft_cache_type_k = "q4_0", draft_cache_type_v = "q4_0"
|
|
)
|
|
k_only = b._mtp_draft_kv_bytes(131072, draft_cache_type_k = "q4_0") # V defaults f16
|
|
both_f16 = b._mtp_draft_kv_bytes(131072, draft_cache_type_k = "f16", draft_cache_type_v = "f16")
|
|
assert both_q4 == k_only == both_f16 # floored at f16, never under-reserved
|
|
|
|
def test_none_when_dims_missing(self):
|
|
assert _make_backend(nextn = 0)._mtp_draft_kv_bytes(65536) is None
|
|
assert _make_backend(kv_key_length = None)._mtp_draft_kv_bytes(65536) is None
|
|
assert _make_backend()._mtp_draft_kv_bytes(0) is None
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Separate drafter (Gemma): sized from the drafter GGUF's own dims + weights
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestSeparateDrafter:
|
|
def test_uses_drafter_kv_and_weights(self, monkeypatch):
|
|
b = _make_backend(nextn = None) # main has no embedded head
|
|
stub = _StubDrafter(kv_per_token = 2000)
|
|
monkeypatch.setattr(b, "_draft_backend_for", lambda path: stub)
|
|
ctx = 65536
|
|
kv = b._mtp_draft_kv_bytes(ctx, drafter_path = "/m/draft.gguf")
|
|
assert kv == stub._estimate_kv_cache_bytes(ctx)
|
|
total = b._estimate_mtp_overhead_bytes(
|
|
ctx, drafter_path = "/m/draft.gguf", draft_weights_bytes = GIB
|
|
)
|
|
assert total == kv + GIB
|
|
|
|
def test_drafter_kv_scales_with_context(self, monkeypatch):
|
|
b = _make_backend(nextn = None)
|
|
monkeypatch.setattr(b, "_draft_backend_for", lambda path: _StubDrafter(2000))
|
|
a = b._mtp_draft_kv_bytes(16384, drafter_path = "/m/d.gguf")
|
|
c = b._mtp_draft_kv_bytes(65536, drafter_path = "/m/d.gguf")
|
|
assert c == pytest.approx(4 * a)
|
|
|
|
def test_drafter_kv_scales_with_parallel_slots(self, monkeypatch):
|
|
# The drafter is served under the same --parallel slots as the main model,
|
|
# so a sliding-window drafter's KV grows per slot; the reserve must thread
|
|
# n_parallel or it under-reserves (Finding G1).
|
|
b = _make_backend(nextn = None)
|
|
monkeypatch.setattr(b, "_draft_backend_for", lambda path: _StubDrafter(2000))
|
|
one = b._mtp_draft_kv_bytes(65536, drafter_path = "/m/d.gguf", n_parallel = 1)
|
|
four = b._mtp_draft_kv_bytes(65536, drafter_path = "/m/d.gguf", n_parallel = 4)
|
|
assert four == pytest.approx(4 * one)
|
|
# And it threads through the overhead estimate too.
|
|
ov1 = b._estimate_mtp_overhead_bytes(
|
|
65536, drafter_path = "/m/d.gguf", draft_weights_bytes = GIB, n_parallel = 1
|
|
)
|
|
ov4 = b._estimate_mtp_overhead_bytes(
|
|
65536, drafter_path = "/m/d.gguf", draft_weights_bytes = GIB, n_parallel = 4
|
|
)
|
|
assert (ov4 - GIB) == pytest.approx(4 * (ov1 - GIB)) # KV scales, weights flat
|
|
|
|
def test_none_when_drafter_unreadable(self, monkeypatch):
|
|
b = _make_backend(nextn = None)
|
|
monkeypatch.setattr(b, "_draft_backend_for", lambda path: None)
|
|
assert b._mtp_draft_kv_bytes(65536, drafter_path = "/m/d.gguf") is None
|
|
assert b._estimate_mtp_overhead_bytes(65536, drafter_path = "/m/d.gguf") is None
|
|
|
|
def test_keeps_weights_when_drafter_kv_unsizable(self, monkeypatch):
|
|
# KV can't be sized (exotic/remote drafter), but the local weights are
|
|
# known: reserve the weights so a drafter larger than the flat fallback
|
|
# cushion can't slip through and OOM (Finding C). Nothing known -> None.
|
|
b = _make_backend(nextn = None)
|
|
monkeypatch.setattr(b, "_draft_backend_for", lambda path: None)
|
|
assert b._mtp_draft_kv_bytes(65536, drafter_path = "/m/d.gguf") is None
|
|
assert (
|
|
b._estimate_mtp_overhead_bytes(
|
|
65536, drafter_path = "/m/d.gguf", draft_weights_bytes = 3 * GIB
|
|
)
|
|
== 3 * GIB
|
|
)
|
|
assert b._estimate_mtp_overhead_bytes(65536, drafter_path = "/m/d.gguf") is None
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Total overhead = draft KV (+ separate drafter weights); no verify constant
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestOverheadTotal:
|
|
def test_equals_draft_kv_for_embedded(self):
|
|
b = _make_backend()
|
|
for ctx in (16384, 65536, 131072):
|
|
assert b._estimate_mtp_overhead_bytes(ctx) == b._mtp_draft_kv_bytes(ctx)
|
|
|
|
def test_does_not_depend_on_n_max(self):
|
|
# The verify buffer (the only n_max-dependent term) rides in headroom now.
|
|
b = _make_backend()
|
|
assert b._estimate_mtp_overhead_bytes(
|
|
65536, spec_draft_n_max = 2
|
|
) == b._estimate_mtp_overhead_bytes(65536, spec_draft_n_max = 6)
|
|
|
|
def test_none_when_draft_kv_unsizable(self):
|
|
assert _make_backend(nextn = 0)._estimate_mtp_overhead_bytes(65536) is None
|
|
|
|
def test_includes_separate_drafter_weights(self):
|
|
b = _make_backend()
|
|
base = b._estimate_mtp_overhead_bytes(65536)
|
|
with_w = b._estimate_mtp_overhead_bytes(65536, draft_weights_bytes = GIB)
|
|
assert with_w - base == GIB
|
|
|
|
@pytest.mark.parametrize(
|
|
"ctx,measured_draft_kv_mib",
|
|
# Measured 27B MTP delta minus the (headroom-covered) ~500 MiB verify
|
|
# buffer leaves the draft KV; the deterministic estimate must match it.
|
|
[(16384, 64), (65536, 256), (131072, 512)],
|
|
)
|
|
def test_draft_kv_matches_measured(self, ctx, measured_draft_kv_mib):
|
|
b = _make_backend()
|
|
pred = b._estimate_mtp_overhead_bytes(ctx) / MIB
|
|
assert pred == pytest.approx(measured_draft_kv_mib, abs = 2)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# _fit_context_to_vram: MTP reserve lowers the chosen context
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestFitContextWithMtp:
|
|
def _fit_backend(self, kv_per_token = 325_000):
|
|
b = _make_backend()
|
|
b._can_estimate_kv = lambda: True
|
|
b._estimate_kv_cache_bytes = lambda n, _t = None, **_k: (0 if n <= 0 else n * kv_per_token)
|
|
return b
|
|
|
|
def test_overhead_fn_lowers_context(self):
|
|
b = self._fit_backend()
|
|
avail_mib = 24_000
|
|
model = 8 * GIB
|
|
without = b._fit_context_to_vram(131072, avail_mib, model)
|
|
with_mtp = b._fit_context_to_vram(
|
|
131072,
|
|
avail_mib,
|
|
model,
|
|
mtp_overhead_fn = lambda c: b._estimate_mtp_overhead_bytes(c) or 0,
|
|
)
|
|
assert 0 < with_mtp < without
|
|
|
|
def test_quantized_embedded_draft_kv_does_not_inflate_context(self):
|
|
# For the single-layer embedded head, quantizing the draft KV does NOT
|
|
# buy more context (it fits less in practice; ggml-org/llama.cpp#24102),
|
|
# so the f16-floored reserve advertises the same context as f16 -- never
|
|
# a larger one off a smaller (unsafe) reserve.
|
|
b = self._fit_backend()
|
|
avail_mib, model = 24_000, 8 * GIB
|
|
f16 = b._fit_context_to_vram(
|
|
131072,
|
|
avail_mib,
|
|
model,
|
|
mtp_overhead_fn = lambda c: b._estimate_mtp_overhead_bytes(
|
|
c, draft_cache_type_k = "f16", draft_cache_type_v = "f16"
|
|
)
|
|
or 0,
|
|
)
|
|
q4 = b._fit_context_to_vram(
|
|
131072,
|
|
avail_mib,
|
|
model,
|
|
mtp_overhead_fn = lambda c: b._estimate_mtp_overhead_bytes(
|
|
c, draft_cache_type_k = "q4_0", draft_cache_type_v = "q4_0"
|
|
)
|
|
or 0,
|
|
)
|
|
assert 0 < q4 == f16
|
|
|
|
def test_no_mtp_unchanged(self):
|
|
b = self._fit_backend()
|
|
avail_mib, model = 24_000, 8 * GIB
|
|
a = b._fit_context_to_vram(131072, avail_mib, model)
|
|
bb = b._fit_context_to_vram(
|
|
131072, avail_mib, model, mtp_engaged = False, mtp_overhead_fn = None
|
|
)
|
|
assert a == bb
|
|
|
|
def test_chosen_context_actually_fits_budget(self):
|
|
b = self._fit_backend()
|
|
avail_mib, model = 24_000, 8 * GIB
|
|
fn = lambda c: b._estimate_mtp_overhead_bytes(c) or 0 # noqa: E731
|
|
ctx = b._fit_context_to_vram(131072, avail_mib, model, mtp_overhead_fn = fn)
|
|
budget = avail_mib * MIB * _CTX_FIT_VRAM_FRACTION
|
|
assert model + b._estimate_kv_cache_bytes(ctx) + fn(ctx) <= budget
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# extra_args parsing: detect user-enabled MTP + draft depth + draft KV type
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestExtraArgsMtpDetection:
|
|
@pytest.mark.parametrize(
|
|
"args,expected",
|
|
[
|
|
(["--spec-type", "draft-mtp"], True),
|
|
(["--spec-type", "mtp"], True),
|
|
(["--spec-type", "ngram-mod,draft-mtp"], True),
|
|
(["--spec-type=draft-mtp"], True),
|
|
(["--spec-type", "ngram-mod"], False),
|
|
(["--spec-default"], False),
|
|
(["-c", "131072"], False),
|
|
(None, False),
|
|
([], False),
|
|
],
|
|
)
|
|
def test_requests_mtp(self, args, expected):
|
|
assert _extra_args_requests_mtp(args, env = {}) is expected
|
|
|
|
def test_requests_mtp_env(self):
|
|
# The child honors LLAMA_ARG_SPEC_TYPE; env-requested MTP must reserve too.
|
|
assert _extra_args_requests_mtp([], env = {"LLAMA_ARG_SPEC_TYPE": "draft-mtp"}) is True
|
|
assert _extra_args_requests_mtp([], env = {"LLAMA_ARG_SPEC_TYPE": "ngram-mod,mtp"}) is True
|
|
assert _extra_args_requests_mtp([], env = {"LLAMA_ARG_SPEC_TYPE": "draft-simple"}) is False
|
|
assert _extra_args_requests_mtp([], env = {"LLAMA_ARG_SPEC_TYPE": "none"}) is False
|
|
|
|
def test_requests_mtp_effective_spec_type(self):
|
|
# llama.cpp uses the LAST CLI --spec-type and ignores the env when any CLI
|
|
# --spec-type is present. The reserve must track that effective value, not
|
|
# any earlier/MTP-ish one, or it over-reserves a drafter the launch won't
|
|
# load (Finding B).
|
|
env_mtp = {"LLAMA_ARG_SPEC_TYPE": "draft-mtp"}
|
|
# Later CLI value overrides an earlier MTP one (last-wins).
|
|
assert (
|
|
_extra_args_requests_mtp(
|
|
["--spec-type", "draft-mtp", "--spec-type", "ngram-mod"], env = {}
|
|
)
|
|
is False
|
|
)
|
|
# A non-MTP CLI flag overrides a stale MTP env.
|
|
assert _extra_args_requests_mtp(["--spec-type", "ngram-mod"], env = env_mtp) is False
|
|
assert _extra_args_requests_mtp(["--spec-type", "none"], env = env_mtp) is False
|
|
# A later MTP CLI value still engages.
|
|
assert (
|
|
_extra_args_requests_mtp(
|
|
["--spec-type", "ngram-mod", "--spec-type", "draft-mtp"], env = {}
|
|
)
|
|
is True
|
|
)
|
|
# Same precedence for separate (draft-simple/eagle3) detection.
|
|
assert (
|
|
_extra_args_requests_separate_draft(
|
|
["--spec-type", "draft-simple", "--spec-type", "ngram-mod"], env = {}
|
|
)
|
|
is False
|
|
)
|
|
assert (
|
|
_extra_args_requests_separate_draft(
|
|
["--spec-type", "ngram-mod"], env = {"LLAMA_ARG_SPEC_TYPE": "draft-simple"}
|
|
)
|
|
is False
|
|
)
|
|
|
|
@pytest.mark.parametrize(
|
|
"args,expected",
|
|
[
|
|
(["--spec-type", "draft-simple"], True),
|
|
(["--spec-type", "draft-eagle3"], True),
|
|
(["--spec-type=draft-eagle3"], True),
|
|
(["--spec-type", "draft-mtp"], False), # MTP path handles this one
|
|
(["--spec-type", "ngram-mod"], False), # loads no draft model
|
|
(["-c", "4096"], False),
|
|
(None, False),
|
|
],
|
|
)
|
|
def test_requests_separate_draft(self, args, expected):
|
|
assert _extra_args_requests_separate_draft(args, env = {}) is expected
|
|
|
|
def test_requests_separate_draft_env(self):
|
|
assert (
|
|
_extra_args_requests_separate_draft([], env = {"LLAMA_ARG_SPEC_TYPE": "draft-simple"})
|
|
is True
|
|
)
|
|
assert (
|
|
_extra_args_requests_separate_draft([], env = {"LLAMA_ARG_SPEC_TYPE": "draft-mtp"})
|
|
is False
|
|
)
|
|
|
|
def test_load_model_reserves_for_non_mtp_draft_modes(self):
|
|
# load_model engages the draft reserve for a non-MTP model-based draft mode
|
|
# only when extras also name a drafter (else nothing is loaded to reserve).
|
|
# Strip all whitespace so the check survives any line-wrapping the
|
|
# formatter applies to the call (pre-commit black wraps long lines).
|
|
compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
|
|
assert "_user_draft_via_extras" in compact
|
|
# called with extra_args (an env kwarg may follow); prefix match stays
|
|
# robust to that and to any formatter line-wrapping.
|
|
assert "_extra_args_requests_separate_draft(extra_args" in compact
|
|
assert "or_user_draft_via_extras" in compact # OR'd into the reserve gate
|
|
# The drafter check must NOT force extras-only (env={}); the default
|
|
# env=None lets it see an env LLAMA_ARG_SPEC_DRAFT_MODEL, so an env-only
|
|
# drafter still engages the reserve (codex review 4507014299).
|
|
assert "bool(_extra_args_mtp_draft_path(extra_args))" in compact
|
|
|
|
def test_env_only_drafter_engages_separate_draft_reserve(self, monkeypatch):
|
|
# An env-provided drafter (no --model-draft in extras) must still engage
|
|
# the draft reserve, or auto-fit spends the drafter's VRAM and OOMs. Mirror
|
|
# load_model's _user_draft_via_extras gate (codex review 4507014299).
|
|
monkeypatch.setenv("LLAMA_ARG_SPEC_DRAFT_MODEL", "/large.gguf")
|
|
monkeypatch.delenv("LLAMA_ARG_SPEC_DRAFT_HF_REPO", raising = False)
|
|
ea = ["--spec-type", "draft-simple"] # _spec_env is {} (extras set spec-type)
|
|
assert _extra_args_requests_separate_draft(ea, env = {}) is True
|
|
assert _extra_args_mtp_draft_path(ea) == "/large.gguf" # env=None -> os.environ
|
|
# -> _user_draft_via_extras True; _env_draft_for_budget sizes the drafter.
|
|
assert _extra_args_mtp_draft_path([], env = dict(os.environ)) == "/large.gguf"
|
|
|
|
def test_load_model_gates_env_spec_type_on_off_mode(self):
|
|
# LLAMA_ARG_SPEC_TYPE only reaches the child when Studio emits no spec
|
|
# flag (UI mode "off", no user --spec-type); otherwise the emitted
|
|
# --spec-type/--spec-default overrides the env, so the reserve must not
|
|
# consult it or a stale MTP env over-reserves (Finding F3). Whitespace-
|
|
# stripped so the check survives formatter line-wrapping.
|
|
compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
|
|
assert '_mtp_canonical=="off"' in compact # the env-reaches-child gate
|
|
assert "_extra_args_requests_mtp(extra_args,env=_spec_env)" in compact
|
|
|
|
def test_spec_default_overrides_env_mtp(self):
|
|
# --spec-default is a CLI spec flag (resolves to the model default,
|
|
# non-MTP) that overrides a stale LLAMA_ARG_SPEC_TYPE env, so the reserve
|
|
# must not treat it as MTP (reviewer.py R4).
|
|
env_mtp = {"LLAMA_ARG_SPEC_TYPE": "draft-mtp"}
|
|
assert _extra_args_requests_mtp(["--spec-default"], env = env_mtp) is False
|
|
assert (
|
|
_extra_args_requests_separate_draft(
|
|
["--spec-default"], env = {"LLAMA_ARG_SPEC_TYPE": "draft-simple"}
|
|
)
|
|
is False
|
|
)
|
|
# A later --spec-type still wins over an earlier --spec-default.
|
|
assert (
|
|
_extra_args_requests_mtp(["--spec-default", "--spec-type", "draft-mtp"], env = {}) is True
|
|
)
|
|
|
|
def test_load_model_drafter_budget_precedence(self):
|
|
# The budget sizes the drafter the launch actually loads: CLI extras win,
|
|
# then Studio's emitted mtp_draft_path (overrides LLAMA_ARG_SPEC_DRAFT_MODEL),
|
|
# then the env drafter -- not the env before Studio's (reviewer.py R3).
|
|
compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
|
|
assert "_cli_draft_for_budget=_extra_args_mtp_draft_path(extra_args,env={})" in compact
|
|
assert "_env_draft_for_budget=_extra_args_mtp_draft_path([],env=os.environ)" in compact
|
|
assert "_cli_draft_for_budgetor_studio_draft_for_budgetor_env_draft_for_budget" in compact
|
|
|
|
def test_load_model_drops_cpu_offloaded_drafter_from_budget(self):
|
|
# A SEPARATE drafter offloaded to CPU (--spec-draft-ngl 0 /
|
|
# --spec-draft-device none) consumes no GPU, so it must be dropped from the
|
|
# budget and get no flat reserve (Finding F2). But an embedded head is on
|
|
# GPU regardless of those draft-only flags, so the flat reserve is only
|
|
# suppressed when there is no embedded head (Finding G5).
|
|
compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
|
|
# env-aware: also honors the inherited LLAMA_ARG_N_GPU_LAYERS_DRAFT.
|
|
assert (
|
|
"_draft_on_cpu=_extra_args_draft_offloaded_to_cpu(extra_args,env=os.environ)" in compact
|
|
)
|
|
assert "if_draft_on_cpu:_mtp_draft_for_budget=None" in compact
|
|
# flat reserve suppressed only for a CPU drafter with no embedded head
|
|
assert "_draft_cpu_no_embedded=_draft_on_cpuandnotself._nextn_predict_layers" in compact
|
|
assert "not_draft_cpu_no_embedded" in compact
|
|
|
|
def test_load_model_keeps_flat_reserve_for_unsized_draft_kv(self):
|
|
# When only the drafter weights could be sized (KV unsizable), the flat
|
|
# fraction stays on as the cushion for the still-unsized draft KV, on top
|
|
# of the byte-accurate weights reserve (Finding G3).
|
|
compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
|
|
assert "_mtp_kv_unsized" in compact
|
|
assert "mtp_overhead_fnisNoneor_mtp_kv_unsized" in compact
|
|
|
|
def test_load_model_ranks_subsets_by_active_pin_fraction(self):
|
|
# Auto/cap subset ranking uses the active budget fraction (lowered by the
|
|
# flat MTP reserve), not a hard-coded 0.95, so the ranking order matches
|
|
# the fit budget that is then tested (Finding G4).
|
|
compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
|
|
assert "_gpu_usable(g,pin_fraction)" in compact
|
|
assert "_gpu_usable(g,_CTX_FIT_VRAM_FRACTION-_flat_mtp_reserve)" in compact
|
|
|
|
@pytest.mark.parametrize(
|
|
"args,expected",
|
|
[
|
|
(["--spec-draft-ngl", "0"], True),
|
|
(["-ngld", "0"], True),
|
|
(["--spec-draft-ngl=0"], True),
|
|
(["--n-gpu-layers-draft", "0"], True),
|
|
(["--spec-draft-ngl", "20"], False),
|
|
(["--spec-draft-device", "none"], True),
|
|
(["--spec-draft-device", "CPU"], True),
|
|
(["-devd", "cpu,none"], True),
|
|
(["--spec-draft-device", "CUDA0"], False),
|
|
(["--spec-draft-device", "CUDA0,CPU"], False), # any GPU -> on GPU
|
|
(["-c", "4096"], False),
|
|
(None, False),
|
|
# last-wins: only the final value of each flag counts (Finding G2)
|
|
(["--spec-draft-ngl", "0", "--spec-draft-ngl", "-1"], False), # last = GPU
|
|
(["--spec-draft-ngl", "-1", "--spec-draft-ngl", "0"], True), # last = CPU
|
|
(["--spec-draft-device", "CUDA0", "--spec-draft-device", "none"], True),
|
|
(["--spec-draft-device", "none", "--spec-draft-device", "CUDA0"], False),
|
|
],
|
|
)
|
|
def test_draft_offloaded_to_cpu(self, args, expected):
|
|
assert _extra_args_draft_offloaded_to_cpu(args, env = {}) is expected
|
|
|
|
def test_draft_offloaded_to_cpu_env(self):
|
|
# The child honors LLAMA_ARG_N_GPU_LAYERS_DRAFT; an env-only CPU offload
|
|
# must drop the drafter from the budget too (review run3 #3). CLI wins.
|
|
assert (
|
|
_extra_args_draft_offloaded_to_cpu([], env = {"LLAMA_ARG_N_GPU_LAYERS_DRAFT": "0"})
|
|
is True
|
|
)
|
|
assert (
|
|
_extra_args_draft_offloaded_to_cpu([], env = {"LLAMA_ARG_N_GPU_LAYERS_DRAFT": "-1"})
|
|
is False
|
|
)
|
|
# CLI --spec-draft-ngl wins over the env (last-wins is CLI-only).
|
|
assert (
|
|
_extra_args_draft_offloaded_to_cpu(
|
|
["--spec-draft-ngl", "-1"], env = {"LLAMA_ARG_N_GPU_LAYERS_DRAFT": "0"}
|
|
)
|
|
is False
|
|
)
|
|
assert _extra_args_draft_offloaded_to_cpu([], env = {}) is False
|
|
|
|
@pytest.mark.parametrize(
|
|
"args,expected",
|
|
[
|
|
(["--spec-draft-n-max", "4"], 4),
|
|
(["--spec-draft-n-max=6"], 6),
|
|
(["--spec-type", "draft-mtp", "--spec-draft-n-max", "3"], 3),
|
|
(["--spec-draft-n-max", "2", "--spec-draft-n-max", "5"], 5), # last wins
|
|
(["--spec-draft-n-max", "notanint"], None),
|
|
(["-c", "4096"], None),
|
|
(None, None),
|
|
(["--draft-max", "6"], 6),
|
|
(["--draft-max=4"], 4),
|
|
(["--spec-type", "draft-mtp", "--draft-max", "6"], 6),
|
|
(["--spec-draft-n-max", "2", "--draft-max", "5"], 5),
|
|
],
|
|
)
|
|
def test_spec_draft_n_max(self, args, expected):
|
|
assert _extra_args_spec_draft_n_max(args) == expected
|
|
|
|
@pytest.mark.parametrize(
|
|
"args,expected",
|
|
[
|
|
(["--model-draft", "/m/draft.gguf"], "/m/draft.gguf"),
|
|
(["--spec-draft-model", "/m/draft.gguf"], "/m/draft.gguf"),
|
|
(["-md", "/m/draft.gguf"], "/m/draft.gguf"),
|
|
(["--model-draft=/m/draft.gguf"], "/m/draft.gguf"),
|
|
(["--model-draft", "--spec-type"], None),
|
|
(["-c", "4096"], None),
|
|
(None, None),
|
|
],
|
|
)
|
|
def test_mtp_draft_path(self, args, expected):
|
|
# env={} isolates pure-CLI behavior from a polluted test environment.
|
|
assert _extra_args_mtp_draft_path(args, env = {}) == expected
|
|
|
|
@pytest.mark.parametrize(
|
|
"args,expected",
|
|
[
|
|
# HF draft repo flags are real llama-server flags; the budget must see them.
|
|
(["--spec-draft-hf", "big/repo:Q8_0"], "big/repo:Q8_0"),
|
|
(["-hfd", "big/repo"], "big/repo"),
|
|
(["-hfrd", "big/repo"], "big/repo"),
|
|
(["--hf-repo-draft=big/repo"], "big/repo"),
|
|
],
|
|
)
|
|
def test_mtp_draft_path_hf_flags(self, args, expected):
|
|
assert _extra_args_mtp_draft_path(args, env = {}) == expected
|
|
|
|
def test_mtp_draft_path_env_fallback(self):
|
|
# The child honors LLAMA_ARG_SPEC_DRAFT_MODEL / _HF_REPO; CLI wins over env.
|
|
assert (
|
|
_extra_args_mtp_draft_path([], env = {"LLAMA_ARG_SPEC_DRAFT_MODEL": "/m/e.gguf"})
|
|
== "/m/e.gguf"
|
|
)
|
|
assert _extra_args_mtp_draft_path([], env = {"LLAMA_ARG_SPEC_DRAFT_HF_REPO": "x/y"}) == "x/y"
|
|
assert (
|
|
_extra_args_mtp_draft_path(
|
|
["-md", "/m/cli.gguf"], env = {"LLAMA_ARG_SPEC_DRAFT_HF_REPO": "x/y"}
|
|
)
|
|
== "/m/cli.gguf"
|
|
)
|
|
|
|
@pytest.mark.parametrize(
|
|
"args,expected",
|
|
[
|
|
(["--cache-type-k-draft", "q8_0"], ("q8_0", None)),
|
|
(["--spec-draft-type-k", "q4_0"], ("q4_0", None)),
|
|
(["-ctkd", "q8_0"], ("q8_0", None)),
|
|
(["--cache-type-v-draft", "q4_0"], (None, "q4_0")), # K stays f16, V only
|
|
(["--cache-type-k-draft", "q4_0", "--cache-type-v-draft", "q8_0"], ("q4_0", "q8_0")),
|
|
(["--cache-type-k-draft=q8_0"], ("q8_0", None)),
|
|
(["--cache-type-k", "q8_0"], (None, None)), # main type, not draft
|
|
(["-c", "4096"], (None, None)),
|
|
(None, (None, None)),
|
|
],
|
|
)
|
|
def test_draft_cache_types(self, args, expected):
|
|
assert _extra_args_draft_cache_types(args, env = {}) == expected
|
|
|
|
def test_draft_cache_types_env_fallback(self):
|
|
# The child honors LLAMA_ARG_SPEC_DRAFT_CACHE_TYPE_K/_V per axis; CLI wins.
|
|
assert _extra_args_draft_cache_types(
|
|
[], env = {"LLAMA_ARG_SPEC_DRAFT_CACHE_TYPE_K": "q8_0"}
|
|
) == ("q8_0", None)
|
|
assert _extra_args_draft_cache_types(
|
|
[],
|
|
env = {
|
|
"LLAMA_ARG_SPEC_DRAFT_CACHE_TYPE_K": "q8_0",
|
|
"LLAMA_ARG_SPEC_DRAFT_CACHE_TYPE_V": "q4_0",
|
|
},
|
|
) == ("q8_0", "q4_0")
|
|
assert _extra_args_draft_cache_types(
|
|
["-ctkd", "q4_0"], env = {"LLAMA_ARG_SPEC_DRAFT_CACHE_TYPE_K": "q8_0"}
|
|
) == ("q4_0", None)
|
|
|
|
@pytest.mark.parametrize(
|
|
"args,expected",
|
|
[
|
|
(["--ubatch-size", "1024"], 1024),
|
|
(["-ub", "4096"], 4096),
|
|
(["--ubatch-size=512"], 512),
|
|
(["--ubatch", "2048"], None), # not a real llama-server flag; ignore it
|
|
(["-c", "4096"], None),
|
|
(None, None),
|
|
],
|
|
)
|
|
def test_n_ubatch(self, args, expected):
|
|
assert _extra_args_n_ubatch(args, env = {}) == expected
|
|
|
|
def test_n_ubatch_env_fallback(self):
|
|
# The child honors LLAMA_ARG_UBATCH; it must reach the compute-buffer reserve.
|
|
assert _extra_args_n_ubatch([], env = {"LLAMA_ARG_UBATCH": "4096"}) == 4096
|
|
assert (
|
|
_extra_args_n_ubatch(["-ub", "1024"], env = {"LLAMA_ARG_UBATCH": "4096"}) == 1024
|
|
) # CLI wins
|
|
assert _extra_args_n_ubatch([], env = {"LLAMA_ARG_UBATCH": "notint"}) is None
|
|
|
|
def test_env_main_cache_type_for_budget(self):
|
|
# The child inherits LLAMA_ARG_CACHE_TYPE_K/_V, but Studio emits no
|
|
# --cache-type when neither param nor extras set it -> a heavier env
|
|
# main KV (f32) must be adopted so the reserve matches the child.
|
|
assert _env_main_cache_type_for_budget(env = {}) is None
|
|
# f32 exceeds the f16 default -> adopt it (lower-cased so the launch
|
|
# re-emits it via _valid_cache_types).
|
|
assert _env_main_cache_type_for_budget(env = {"LLAMA_ARG_CACHE_TYPE_K": "f32"}) == "f32"
|
|
assert _env_main_cache_type_for_budget(env = {"LLAMA_ARG_CACHE_TYPE_V": "F32"}) == "f32"
|
|
# Heavier of K/V (single knob; over-reserves the lighter axis).
|
|
assert (
|
|
_env_main_cache_type_for_budget(
|
|
env = {"LLAMA_ARG_CACHE_TYPE_K": "f32", "LLAMA_ARG_CACHE_TYPE_V": "f16"}
|
|
)
|
|
== "f32"
|
|
)
|
|
# Quantized env types are <= f16 -> already over-reserved by the default.
|
|
assert _env_main_cache_type_for_budget(env = {"LLAMA_ARG_CACHE_TYPE_K": "q4_0"}) is None
|
|
assert _env_main_cache_type_for_budget(env = {"LLAMA_ARG_CACHE_TYPE_V": "q8_0"}) is None
|
|
assert _env_main_cache_type_for_budget(env = {"LLAMA_ARG_CACHE_TYPE_K": "f16"}) is None
|
|
# Unknown env type self-neutralizes (treated as f16 by _kv_bytes_per_elem).
|
|
assert _env_main_cache_type_for_budget(env = {"LLAMA_ARG_CACHE_TYPE_K": "wat"}) is None
|
|
|
|
def test_load_model_adopts_env_main_cache_type(self):
|
|
# Source-level: load_model budgets the heavier of asymmetric --cache-type
|
|
# extras, then (only when neither param nor extras set it) adopts the env
|
|
# main KV type, so the reserve covers a child that inherits a heavier
|
|
# LLAMA_ARG_CACHE_TYPE_*. Whitespace-stripped to survive formatter wraps.
|
|
compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
|
|
assert "_extra_args_main_cache_type_for_budget(extra_args)" in compact
|
|
assert "ifcache_type_kvisNone:" in compact
|
|
assert "cache_type_kv=_env_main_cache_type_for_budget()" in compact
|
|
|
|
def test_env_split_mode_is_tensor(self):
|
|
# The child inherits LLAMA_ARG_SPLIT_MODE, but Studio emits --split-mode
|
|
# only on its tensor branch -> a tensor env must flip the budget so the
|
|
# heavier per-device compute buffer is reserved (not layer overhead).
|
|
assert _env_split_mode_is_tensor(env = {}) is False
|
|
assert _env_split_mode_is_tensor(env = {"LLAMA_ARG_SPLIT_MODE": "tensor"}) is True
|
|
assert _env_split_mode_is_tensor(env = {"LLAMA_ARG_SPLIT_MODE": "Tensor"}) is True
|
|
# Other modes are not a runtime-heavier surprise -> not acted on.
|
|
assert _env_split_mode_is_tensor(env = {"LLAMA_ARG_SPLIT_MODE": "layer"}) is False
|
|
assert _env_split_mode_is_tensor(env = {"LLAMA_ARG_SPLIT_MODE": "row"}) is False
|
|
assert _env_split_mode_is_tensor(env = {"LLAMA_ARG_SPLIT_MODE": "none"}) is False
|
|
|
|
def test_effective_tensor_parallel_env_flip(self):
|
|
# Shared by load_model and both duplicate-load matchers, so they agree.
|
|
tensor_env = {"LLAMA_ARG_SPLIT_MODE": "tensor"}
|
|
# No extras, toggle off, tensor env -> flips on.
|
|
assert _effective_tensor_parallel(None, False, env = tensor_env) is True
|
|
# Extras override (any --split-mode) beats the env, even if non-tensor.
|
|
assert _effective_tensor_parallel(["--split-mode", "layer"], False, env = tensor_env) is False
|
|
# Explicit extras/toggle tensor stays on regardless of env.
|
|
assert _effective_tensor_parallel(["--split-mode", "tensor"], False, env = {}) is True
|
|
assert _effective_tensor_parallel(None, True, env = {}) is True
|
|
# One-directional: a non-tensor env never downgrades, and no env -> no flip.
|
|
assert _effective_tensor_parallel(None, False, env = {}) is False
|
|
assert (
|
|
_effective_tensor_parallel(None, False, env = {"LLAMA_ARG_SPLIT_MODE": "layer"}) is False
|
|
)
|
|
|
|
def test_tensor_parallel_matches_loaded_env_downgrade(self):
|
|
# Env-only tensor matches a server that actually launched tensor, but a
|
|
# server load_model downgraded to layer (env scrubbed) must still match
|
|
# an identical request -- not reload forever (#6312).
|
|
tensor_env = {"LLAMA_ARG_SPLIT_MODE": "tensor"}
|
|
# Launched tensor: env-only request matches.
|
|
assert _tensor_parallel_matches_loaded(None, False, True, env = tensor_env) is True
|
|
# Downgraded to layer: same env-only request still matches (no reload loop).
|
|
assert _tensor_parallel_matches_loaded(None, False, False, env = tensor_env) is True
|
|
# No env: a plain request matches a layer server and mismatches a tensor one.
|
|
assert _tensor_parallel_matches_loaded(None, False, False, env = {}) is True
|
|
assert _tensor_parallel_matches_loaded(None, False, True, env = {}) is False
|
|
# Explicit tensor request stays strict: must have a tensor server.
|
|
assert _tensor_parallel_matches_loaded(None, True, False, env = {}) is False
|
|
assert _tensor_parallel_matches_loaded(None, True, True, env = {}) is True
|
|
# An explicit non-tensor --split-mode beats the env (no flip).
|
|
assert (
|
|
_tensor_parallel_matches_loaded(["--split-mode", "layer"], False, True, env = tensor_env)
|
|
is False
|
|
)
|
|
|
|
def test_route_matcher_uses_tensor_parallel_matches_loaded(self):
|
|
# Fix: the route duplicate-load matcher must use the downgrade-aware
|
|
# helper, or an env-driven tensor server (or its layer downgrade) is
|
|
# needlessly reloaded (#6312). Read from disk (importing routes.inference
|
|
# drags in heavy deps).
|
|
routes_src = (
|
|
Path(__file__).resolve().parent.parent / "routes" / "inference.py"
|
|
).read_text()
|
|
start = routes_src.index("def _request_matches_loaded_settings")
|
|
end = routes_src.index("\ndef ", start + 1)
|
|
body = "".join(routes_src[start:end].split())
|
|
assert (
|
|
"_tensor_parallel_matches_loaded(effective_extra,"
|
|
"request.tensor_parallel,llama_backend.tensor_parallel)" in body
|
|
)
|
|
|
|
def test_extra_args_main_cache_type_heavier_axis(self):
|
|
# Asymmetric --cache-type-k/-v must budget the heavier axis (extras win
|
|
# per axis at launch), not the last-wins single type that under-reserves.
|
|
H = _extra_args_main_cache_type_for_budget
|
|
assert H(["--cache-type-k", "f32", "--cache-type-v", "f16"]) == "f32"
|
|
assert H(["--cache-type-v", "f16", "--cache-type-k", "f32"]) == "f32" # order-free
|
|
assert H(["--cache-type-k=f32", "--cache-type-v=f16"]) == "f32" # = form
|
|
assert H(["-ctk", "q4_0", "-ctv", "q8_0"]) == "q8_0" # heavier quant
|
|
assert H(["--cache-type-k", "q8_0"]) == "q8_0" # single axis honored as-is
|
|
assert H(["-c", "4096"]) is None # no cache flags
|
|
assert H(None) is None
|
|
|
|
def test_load_model_budgets_heavier_asymmetric_cache_axis(self):
|
|
# load_model must reserve from the heavier of asymmetric cache extras, or
|
|
# an f32 K against an f16 budget over-advertises context and can OOM.
|
|
load = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
|
|
assert "_extra_args_main_cache_type_for_budget(extra_args)" in load
|
|
|
|
def test_load_model_tensor_drops_any_quantized_cache_axis(self):
|
|
# The heavier-by-bytes budget type can mask a quantized axis (an f16
|
|
# budget hides a paired q4_0), so the tensor-safety drop must test each
|
|
# --cache-type-k/-v extra, not just cache_type_kv -- else the quantized
|
|
# axis survives into tensor mode and crashes the load (#6312).
|
|
load = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
|
|
assert "_ck_extra,_cv_extra=parse_cache_override_per_axis(extra_args)" in load
|
|
assert "forcin(cache_type_kv,_ck_extra,_cv_extra)" in load
|
|
assert "iftensor_paralleland_cache_non_tensor_safe:" in load
|
|
|
|
def test_load_model_layer_downgrade_restores_original_cache_extras(self):
|
|
# Tensor mode strips asymmetric --cache-type-k/-v (it rejects quantized),
|
|
# but layer split supports them, so a downgrade must restore the ORIGINAL
|
|
# extras, not just the scalar heavier type (else q4_0/f16 silently becomes
|
|
# f16/f16 on the layer fallback) (#6312).
|
|
load = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
|
|
assert "_tensor_dropped_extra_args=list(extra_args)" in load
|
|
# Both tensor->layer downgrade points restore the saved originals.
|
|
assert load.count("strip_split_mode_only(_tensor_dropped_extra_argsif") == 2
|
|
|
|
def test_load_model_tensor_skips_reserve_for_cpu_drafter(self):
|
|
# A separate CPU-offloaded drafter (no embedded head) uses no GPU, so the
|
|
# tensor reserve must be suppressed like the layer path -- else tensor mode
|
|
# subtracts a phantom flat MTP reserve and under-advertises context (#6312).
|
|
load = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
|
|
assert "_mtp_will_engageandnot_draft_cpu_no_embedded" in load
|
|
assert "ifnot_mtp_reserves_gpu:" in load
|
|
assert "mtp_engaged=_mtp_reserves_gpu" in load
|
|
|
|
def test_load_model_adopts_env_tensor_split_mode(self):
|
|
# load_model delegates the tensor decision to _effective_tensor_parallel,
|
|
# which flips to tensor only one-directionally: extras set no split mode,
|
|
# none is overridden, and the env selects tensor (an existing tensor plan
|
|
# is never downgraded). Whitespace-stripped to survive formatter wrapping.
|
|
load = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
|
|
assert "tensor_parallel=_effective_tensor_parallel(extra_args,tensor_parallel)" in load
|
|
helper = "".join(inspect.getsource(_effective_tensor_parallel).split())
|
|
assert "notresolved" in helper
|
|
assert "parse_split_mode_override(extra_args)isNone" in helper
|
|
assert "_env_split_mode_is_tensor(env)" in helper
|
|
|
|
def test_load_model_does_not_emit_env_only_cache_type(self):
|
|
# Cluster C: an env-only (budget) cache type must not be re-emitted as
|
|
# --cache-type flags (that would rewrite an asymmetric K/V env). Emission
|
|
# is guarded by `not _cache_type_from_env`, set when the value came from
|
|
# _env_main_cache_type_for_budget(). Whitespace-stripped for formatter.
|
|
compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
|
|
assert "cache_type_kv=_env_main_cache_type_for_budget()" in compact
|
|
assert "_cache_type_from_env=cache_type_kvisnotNone" in compact
|
|
assert "andnot_cache_type_from_env" in compact
|
|
|
|
def test_load_model_clears_inherited_split_mode_on_layer(self):
|
|
# Cluster A: when the final decision is layer split, an inherited
|
|
# non-layer LLAMA_ARG_SPLIT_MODE (and paired LLAMA_ARG_TENSOR_SPLIT) must
|
|
# be popped from the child env so the child cannot run tensor/row/none
|
|
# against Studio's layer budget. Whitespace-stripped for formatter.
|
|
compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
|
|
assert 'env.get("LLAMA_ARG_SPLIT_MODE")' in compact
|
|
assert '_inherited_sm!="layer"' in compact
|
|
assert 'env.pop("LLAMA_ARG_SPLIT_MODE",None)' in compact
|
|
assert 'env.pop("LLAMA_ARG_TENSOR_SPLIT",None)' in compact
|
|
|
|
def test_load_model_clears_quantized_kv_env_for_tensor(self):
|
|
# Cluster B: tensor mode aborts on quantized KV. An inherited quantized
|
|
# LLAMA_ARG_CACHE_TYPE_K/_V must be popped from the child env so it cannot
|
|
# crash the tensor child (and matches the tensor-safe budget).
|
|
# Whitespace-stripped for formatter.
|
|
compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
|
|
assert '("LLAMA_ARG_CACHE_TYPE_K","LLAMA_ARG_CACHE_TYPE_V")' in compact
|
|
assert "_ct_rawnotinself._TENSOR_PARALLEL_KV_TYPES" in compact
|
|
assert "env.pop(_ct_var,None)" in compact
|
|
|
|
def test_load_model_clears_tensor_split_env_in_tensor_mode(self):
|
|
# review run3 #2: Studio owns the tensor split. When it emits no
|
|
# --tensor-split (even split), a stale inherited LLAMA_ARG_TENSOR_SPLIT must
|
|
# be cleared in the TENSOR branch too (not just the layer downgrade), or the
|
|
# child runs a split Studio didn't budget. The else (tensor) branch pops it.
|
|
src = inspect.getsource(LlamaCppBackend.load_model)
|
|
compact = "".join(src.split())
|
|
# appears in both the layer branch and the tensor branch.
|
|
assert compact.count('env.pop("LLAMA_ARG_TENSOR_SPLIT",None)') >= 2
|
|
|
|
def test_load_model_layer_compute_buffer_fallback(self):
|
|
# review run3 #4: when GGUF dims are missing the compute-buffer estimate is
|
|
# 0; the layer path must still reserve the flat fallback (tensor buffer >=
|
|
# layer buffer), not fold 0, or it under-reserves at high --parallel.
|
|
compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
|
|
assert "if_compute_buffer_pipeline<=0:" in compact
|
|
# The RHS expression only (no `_compute_buffer_pipeline=` prefix) so the
|
|
# match survives the formatter wrapping it in parens. It's unique within
|
|
# load_model (the other use of this constant is in MiB, no *1024*1024).
|
|
assert "self._TENSOR_PARALLEL_BUFFER_RESERVE_MIB*1024*1024" in compact
|
|
|
|
def test_load_model_passes_unsized_mtp_reserve_to_tensor_planner(self):
|
|
# review run3 #1/#5: a weights-only (KV-unsized) MTP reserve must flow into
|
|
# _plan_tensor_parallel as a flat cushion, else its binary search spends the
|
|
# unsized draft KV on context and OOMs.
|
|
compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
|
|
assert "_tp_unsized_mtp_reserve=" in compact
|
|
# Gated on _mtp_reserves_gpu so a CPU-offloaded drafter reserves nothing.
|
|
assert "(_mtp_reserves_gpuand_mtp_kv_unsized)" in compact
|
|
assert "mtp_flat_reserve_bytes=_tp_unsized_mtp_reserve" in compact
|
|
|
|
def test_pool_budget_sums_per_gpu_usable(self):
|
|
# Finding #1: the multi-GPU pooled budget must sum each GPU's own usable
|
|
# budget (so an unknown-total GPU gets the free*frac cushion) rather than
|
|
# pooling free and total separately. The fit calls pass the precomputed
|
|
# budget as an absolute (budget_frac=1.0, total_mib=None) so fit and check
|
|
# agree. Whitespace-stripped for formatter.
|
|
compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
|
|
assert "def_pool_budget_mib(subset,frac):" in compact
|
|
assert "sum(max(0.0,_gpu_usable(g,frac))forginsubset)" in compact
|
|
# No revert to the pooled free/total form.
|
|
assert "def_pool_total(" not in compact
|
|
assert "budget_frac=1.0" in compact
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Regression: the reported Qwen3.6-27B MTP / 24 GB scenario
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_qwen36_class_regression_picks_lower_ctx_with_mtp():
|
|
"""A 24 GB card that auto-picks a high context without MTP must pick a
|
|
strictly lower one once the MTP draft reserve is accounted for."""
|
|
b = _make_backend()
|
|
b._can_estimate_kv = lambda: True
|
|
b._estimate_kv_cache_bytes = lambda n, _t = None, **_k: (0 if n <= 0 else int(n * 66_000))
|
|
avail_mib = 24_000
|
|
model = int(17.9 * GIB) # UD-Q4_K_XL weights
|
|
no_mtp = b._fit_context_to_vram(262144, avail_mib, model)
|
|
with_mtp = b._fit_context_to_vram(
|
|
262144,
|
|
avail_mib,
|
|
model,
|
|
mtp_overhead_fn = lambda c: b._estimate_mtp_overhead_bytes(c) or 0,
|
|
)
|
|
assert 0 < with_mtp < no_mtp
|
|
|
|
|
|
def test_mtp_draft_budget_prefers_user_extras_drafter():
|
|
# A user --model-draft in extras is appended last and wins at launch, so the
|
|
# VRAM budget must size it first; then Studio's emitted mtp_draft_path (which
|
|
# overrides LLAMA_ARG_SPEC_DRAFT_MODEL), then the env drafter (load_model is too
|
|
# entangled to drive end-to-end; assert the precedence at the source level).
|
|
# Whitespace-stripped so the check survives any formatter line-wrapping.
|
|
compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
|
|
# CLI extras sized first (env={} so the env doesn't pre-empt Studio's drafter).
|
|
assert "_cli_draft_for_budget=_extra_args_mtp_draft_path(extra_args,env={})" in compact
|
|
# Order: CLI extras, then Studio's mtp_draft_path, then the env drafter.
|
|
assert "_cli_draft_for_budgetor_studio_draft_for_budgetor_env_draft_for_budget" in compact
|
|
# The env must not be consulted before Studio's resolved drafter.
|
|
assert "_extra_args_mtp_draft_path(extra_args)ormtp_draft_path" not in compact
|