Turning Three Known VRAM Traps Into a Working Estimator
Turning Three Known VRAM Traps Into a Working Estimator
Search
Ask the AI

Turning Three Known VRAM Traps Into a Working Estimator

“Will this model fit on this card?” has two kinds of answer. One is a lookup table — record measured values for common combinations and consult it. The other is an estimator that computes an answer for any combination.

Variant, quantisation format, context length, and card count form hundreds of combinations. Measurements alone cannot cover them all, so a calculator needs a model of VRAM consumption.

This records that modelling exercise: what the formula looks like, how to measure the one quantity you cannot look up, and two constraints that VRAM alone will not reveal. The estimator that came out of it is the site’s VRAM calculator, which lists the weights, KV cache and overhead terms separately, so each section below can be checked against it.

Three known mechanisms, briefly

Three traps have to be cleared before modelling. I wrote up their symptoms and causes in detail in a separate piece on choosing between variants, so here are just the conclusions — each corresponds to a term in the formula:

One: parameter count does not give you size. Vendors define parameter counts inconsistently (total / activated / effective), while the byte count on disk is unambiguous. So the estimator’s input must be a looked-up file size, not a parameter count.

Two: quantisation coverage is not uniform. Common quantisation configs compress only linear layers, leaving embeddings at full precision. On architectures using per-layer embeddings, that uncompressed lookup table can exceed the trunk — so “few parameters” can mean “large file”. The formula must account for the uncompressed portion at its original precision.

Three: file size is not VRAM usage. Some inference engines keep the sparsely-accessed embedding table in system memory. The same file loads a different amount onto the card depending on the engine. So what you estimate is “what the engine actually loads”, not the file size.

Those three determine what the formula’s inputs should be. The rest is the formula itself.

Three terms

Fitted to within 0.15 GiB across four measured configurations. Three terms summed:

Weights, minus the portion resident in system memory. Deducted only for architectures with per-layer embeddings, and only for formats where the engine makes that choice:

CPU-resident = (vocab × layers × perLayerDim + vocab × hidden) × bytesPerParam
VRAM weights = file size - CPU-resident

KV cache. When the runtime allocates sliding-window caches at the window size and capacity exceeds that window, global cached layers contribute the context-dependent term. Windowed layers still contribute a nonzero constant. Check cache sharing, KV head counts and head dimensions in the model configuration and pinned source; retaining only global layers omits window-cache storage.

Runtime overhead. Purely empirical, covering CUDA context, activations, and fragmentation:

overhead = max(0.7 × cards, weights × 0.10) + context/131072 × 0.35

The max is an empirical choice in the old fit, whose residuals are below 0.15 GiB on four E4B configurations. Fixed backend costs and activation memory can coexist. Those measurements do not show that the terms cannot add, and they do not validate the multi-GPU branch. The original formula is retained as a calibration model.

The quantity you can’t look up: measuring the global share

The proportion of global attention layers may not be in vendor documentation, and may not be in the config file either. But it can be measured, and the method generalises.

If only KV allocation changes with context, and sliding windows have saturated, memory increments can estimate an effective global-cache slope. Total VRAM also changes with compute buffers, allocation granularity and backend policies. The old max overhead formula itself has a context-linear term, so the total derivative cannot be assigned directly to global KV.

Hold everything else fixed, vary only context length, and record steady-state VRAM at each step:

for ctx in 8192 16384 32768 65536; do
  start engine --ctx-size $ctx --parallel 1
  wait for loading to finish and run one inference
  nvidia-smi --query-gpu=memory.used --format=csv,noheader
  stop engine
done

The original method divides adjacent VRAM differences by context increments, then by 2 × kvHeads × headDim × bytesPerElement for an equivalent layer count. It assumes equal K/V types and dimensions, no extra quantization-block overhead, and subtraction of other context-dependent allocations. Gemma 4 E4B has local head_dim=256, global_head_dim=512 and cross-layer KV sharing. Its config supplies layer_types, so calculate each class directly. The old 3/8 of non-shared layers is a fitted coefficient; these four total-memory points do not identify it as an architectural ratio.

Correction, 2026-11-07: this section previously treated the global-layer share as a quantity that cannot be looked up and reported a measured value of roughly 3/8 of the non-shared layers. Gemma 4 E4B’s config.json lists layer_types directly (7 of its 42 layers use full attention), so the global layers can be counted; 3/8 is a coefficient fitted to the memory readings.

Hold these three conditions fixed; each caused a problem in my measurements:

Fix concurrency and the KV mode. Engines may use a shared token pool, independent slots or dynamic paging. Concurrency 1 reduces variables, but effective capacity and allocation strategy still need recording. Slot count is not necessarily a multiplier for independent cache allocations.

Wait for loading to finish and one inference to run before reading. Reading mid-load captures a partial allocation, and how far along you are differs per step, so the noise swamps the signal.

Take at least three points and check linearity. Two points always form a line and reveal nothing. If three points aren’t collinear, something else is active — a step that triggers a different allocation strategy, say — and the slope itself is untrustworthy until you understand the inflection.

A single-variable experiment measures the system’s response to that parameter. Attributing its slope to one internal mechanism still requires allocation logs or independent observations that exclude other changing terms. Monotonicity alone does not make an internal parameter identifiable.

Concurrency and context per request

The estimator takes the target context per request. To accommodate four simultaneous requests of 16K each, budget KV cache for 65536 tokens in total:

fully occupied KV budget = KV cache per request × simultaneous full requests

In llama.cpp, --ctx-size sets the total context. With --ctx-size 16384 --parallel 4 --no-kv-unified, four independent slots each get 4096. The current automatic parallel mode uses unified KV. Each slot can access the total pool, while all active requests together remain constrained by its capacity. Four slots do not automatically multiply 16384 into 65536; see the server parameter documentation.

Correction, 2026-11-07: this section previously said an engine allocates one KV cache per concurrent slot, so --ctx-size 16384 with a default of 4 slots allocates 16384 × 4 = 65536 tokens. In llama.cpp b10216 and b12184, --ctx-size is the total for all slots: independent slots split it, and the server’s automatic mode (4 slots, unified KV) shares it as one pool.

The original deployment recorded prompt processing at 1.3 tokens per second with some layers on the CPU. To investigate such a result, record n_ctx, n_ctx_seq, the KV mode, and GPU offload layers together. These distinguish allocation changes from changes in execution speed.

Write the parallel count and KV mode explicitly in generated commands. The slope experiment above fixes concurrency at 1 so that context length is the only variable that changes.

Constraint VRAM won’t show you, part one: divisibility

Beyond memory, check tensor-parallel constraints in the actual model implementation. In vLLM v0.19.0 QKVParallelLinear, KV heads are sharded when their count is at least the TP rank count. With fewer KV heads, the implementation can replicate them, provided the rank count is divisible by the KV head count. Query heads, MLP dimensions and quantization kernels retain their own constraints.

KV head counts vary widely within a model family, anywhere from 1 to 16. Two consequences follow:

A single KV head does not by itself prohibit tensor parallelism. An implementation with replication can retain that head on several ranks; the corresponding KV memory does not divide equally across the cards. Check the complete versioned Gemma 4 implementation for support.

Check card counts against the full model structure. Neither 3, 5, 6 nor 4, 8 establishes feasibility on its own. Query heads, KV sharding or replication, hidden dimensions, kernels and interconnect determine the supported configuration. Powers of two still need those checks.

Correction, 2026-11-07: this section previously said tensor parallelism requires the KV head count to be divisible by the card count, so a variant with a single KV head can never use it. In vLLM v0.19.0, QKVParallelLinear replicates KV heads when the TP size is at least the KV head count; that path needs the TP size to be divisible by the KV head count, which a single head always satisfies.

Layer splitting avoids some constraints on sharding individual tensors and helps fit larger models. A request still traverses layers sequentially, but multiple requests can gain throughput through pipeline parallelism. It does not follow that multiple cards can never be faster; scheduling, microbatches and the interconnect determine the gain.

So the calculator must answer two questions: does it fit, and can it parallelise at this card count. Both must pass.

Constraint VRAM won’t show you, part two: ranking

When several combinations fit, the estimator also needs a recommendation order.

The lazy implementation sorts by weight size descending — bigger means stronger. Measurement says this misfires: at one VRAM tier it recommended a small variant at high precision (16.8 GB) over a clearly stronger large variant in a quantised format (16.3 GB). Near-identical size, meaningfully different capability.

The correct ordering is two-level: among the candidates that fit, pick the most capable variant, then within it pick the highest-precision format. Variant strength comes from architecture and evaluations, not from size.

File size does not directly measure task quality. This picker first applies its task-specific variant order, then its format preference. Higher precision usually preserves the original weights more closely, but task scores also depend on quantization, calibration and sampling variation; they are not guaranteed to improve monotonically.

The pattern recurs elsewhere: file size as a proxy for content quality, line count as a proxy for complexity, response time as a proxy for system health. Each holds inside some range and breaks across ranges.

When the formula stops applying

State the domain of a fitted formula so users can establish whether it covers their case.

Changing engine requires re-measurement. Which tensors stay in system memory is entirely an engine implementation choice, not a model property. The same weights on a different engine may make that deduction vanish. The term should be gated on the engine, not applied unconditionally.

Changing architecture family requires re-measurement. The global-layer share is a constant inferred for one architecture. A family with different attention design makes that 3/8 meaningless — and worse, it will produce a plausible-looking number. No error, just wrong.

A new quantisation scheme means re-reading the config. Vendors may start quantising embeddings at any point. Once they do, mechanism two inverts entirely — the “small is bigger than large” anomaly disappears, and the old formula overestimates.

The overhead coefficients are empirical. 0.7 × cards and × 0.10 have no theoretical basis; they were fitted against specific driver and engine versions. A major driver update is worth re-measuring after — the fixed cost of a CUDA context genuinely shifts between versions.

Write each term’s applicability and provenance into the code comments and keep the measured configurations as a regression baseline. After any change, run the same inputs; an error beyond 0.15 GiB indicates that the change affected the existing estimate.

What’s worth keeping

An estimator’s error usually comes from a missing mechanism, not a wrong coefficient. None of the three corrections was a mistyped formula; each time the model lacked something that genuinely exists. So when estimates are off, tuning constants rarely helps — look for what you haven’t modelled.

Check configuration and source, then measure allocations. Gemma 4 exposes layer_types, head dimensions and sharing parameters directly. Measurements test the runtime implementation and budget. Interpret increments when the slope and allocation logs agree.

Feasibility has several conditions. Check memory, model support, and tensor sharding or replication constraints together. Then rank feasible candidates by task quality, latency and throughput.

Related: two different GPUs reporting the same name — under WSL2 device_kind gives one model for two cards, the same class of “do not trust what a device says about itself” problem.

Leave a Reply

Scroll down