Budget inference RAM and VRAM by separating static weights, activation working sets and attention caches, then validate residency before you scale concurrency.
Who this is for
ML engineers, systems developers and homelab operators sizing local inference hosts.
Learning objectives
- Separate weight memory, activation scratch and KV or feature caches in a written capacity plan.
- Estimate transformer KV-cache growth with context length and precision.
- Explain why CUDA and similar device allocators need headroom beyond the weight file size.
- Detect host swapping and device OOM as distinct failure modes with different fixes.
- Produce a memory worksheet for one model artifact before changing hardware.
Three buckets: weights, activations and caches
Inference memory is not “model file size plus a little extra.” A working service consumes at least three budgets: static parameters (weights), transient activations for the current forward pass, and persistent caches that grow with context or streaming state. Confusing these buckets produces hosts that boot a model once and collapse on the second concurrent request.
Weight memory is largely deterministic for a pinned artifact and precision. An 8B-parameter model at 4-bit weight quantization occupies on the order of 4–5 GB for parameters alone, but the runtime still needs allocator metadata, workspace and alignment padding. Treat the GGUF or safetensors byte size as a lower bound, not a capacity plan.
Activation scratch depends on batch size, sequence length and operator fusion. Vision backbones may spike during high-resolution convolutions; decoder-only transformers spike during prefill when the full prompt is processed at once. If you only measure decode tokens per second, you will under-budget the prefill spike that actually OOMs the box.
Label monitors by bucket—weights, activations, KV—so context-length incidents are visible before users feel stalls.
When offloading layers across devices, draw the residency map and expected PCIe traffic per token before calling the setup interactive-ready.
Operational addendum 1 for inference-memory: keep manifests, measurements, power envelopes and rejection reasons written beside the model hash; unspoken tribal knowledge is not a deployment strategy for SER-002 chapter 2. Rehearse the acceptance checks after every runtime or BSP bump, and refuse silent EP fallbacks on the hot path.
KV cache mathematics for autoregressive models
For transformer decode, the key-value attention cache often dominates growth after weights are loaded. Roughly, cache bytes scale with layers × KV heads × head dimension × sequence length × bytes per element × 2 (keys and values). Long contexts are therefore a memory feature, not a free software toggle.
Example intuition: moving from a 2K to a 32K context can multiply cache residency by roughly 16× if every other factor is fixed. That growth lands in RAM or VRAM depending on the backend. A Mini PC that “fits” an 8B Q4 model at short context can still thrash when a retrieval pipeline quietly raises max context.
Write the cache policy into the service manifest: maximum context, eviction or truncation behavior, and whether multiple sessions share a process. Unbounded chat history is a capacity defect. Pair the policy with a load test that grows prompt length until the allocator fails, then set the production limit below that cliff with margin.
For non-transformers, budget the analogous persistent state (RNN hidden state, tracker history, embedding cache) with the same discipline.
Cap sessions in the API with clear 429 responses before the allocator or OOM killer decides for you.
Operational addendum 2 for inference-memory: keep manifests, measurements, power envelopes and rejection reasons written beside the model hash; unspoken tribal knowledge is not a deployment strategy for SER-002 chapter 2. Rehearse the acceptance checks after every runtime or BSP bump, and refuse silent EP fallbacks on the hot path.
Device allocators and why brochure VRAM lies by omission
NVIDIA’s CUDA memory documentation describes how device memory is allocated and managed for kernels and applications. Frameworks build additional caches and workspaces on top of that device heap. A card advertised with 12 GB does not offer 12 GB of contiguous model capacity after driver reservations, fragmentation and runtime pools.
Always leave headroom. A practical local-serving rule is to keep steady-state usage under roughly 80–90% of visible device memory after warmup, and to reject jobs that would push past the limit instead of letting the process die mid-response. On unified-memory APUs the same discipline applies to system RAM: the GPU block and the OS still compete.
Profile with the vendor tools that match your stack—nvidia-smi or equivalent, plus runtime allocator stats—while reproducing the production batch and context. Single short prompts hide fragmentation that appears only after hours of mixed traffic.
Run a fragmentation soak with varied context lengths and define process-recycle policy if free memory becomes unusable.
Pin allocator environment variables (CUDA pools, ORT arenas) in the service unit beside image digests.
Operational addendum 3 for inference-memory: keep manifests, measurements, power envelopes and rejection reasons written beside the model hash; unspoken tribal knowledge is not a deployment strategy for SER-002 chapter 2. Rehearse the acceptance checks after every runtime or BSP bump, and refuse silent EP fallbacks on the hot path.
Host RAM, mmap and swap failure modes
CPU and many GGUF-style runners memory-map weight files. That makes the kernel page cache part of your performance surface: under host pressure, clean file-backed pages can be reclaimed and faulted back from NVMe, collapsing tokens per second without a clean OOM message. Watch major fault rates and disk I/O while load testing, not only RSS.
Hugging Face documentation on memory and model loading repeatedly emphasizes dtype, device placement and the difference between loading for training versus inference. Those knobs change host versus device residency. Document which framework call path you use (low memory loaders, device_map, accelerate offload) because offload that “works” can silently turn a GPU job into a PCIe paging job.
Swap is not overflow capacity for active tensors. If weights or KV pages hit disk, latency becomes storage latency. Prefer hard cgroup limits and failed requests over a machine that appears alive while generating 0.2 tokens per second.
If using mlock on mmap weights, pair it with cgroup headroom so administrative SSH survives pressure.
File incidents with anonymous versus file-backed growth distinguished in memory reports.
Operational addendum 4 for inference-memory: keep manifests, measurements, power envelopes and rejection reasons written beside the model hash; unspoken tribal knowledge is not a deployment strategy for SER-002 chapter 2. Rehearse the acceptance checks after every runtime or BSP bump, and refuse silent EP fallbacks on the hot path.
Concurrency multiplies the wrong terms
Horizontal request concurrency multiplies activation and cache footprints unless the runtime explicitly shares weights and caps parallel sequences. Two simultaneous 8K contexts are not “the same model twice on disk”; they are two live caches plus two working sets. Measure concurrency with fixed prompt lengths before advertising multi-user capacity.
Separate read-only weight sharing from per-request state. Good local servers load weights once and isolate session state. Bad demos launch a new process per request and double-count weights until the host OOMs. Your runbook should state process model, max parallel sequences and the observed memory delta per additional session.
Feed the worksheet into the next chapter: once capacity is known, precision and quantization become the levers that trade accuracy for residency—not random flags flipped after an outage.
Gate horizontal scale-out on free RAM/VRAM probes that subtract per-session deltas from the worksheet.
Attach worksheets to upgrade requests so finance sees GB and GB/s instead of vague “faster AI PC” language.
Operational addendum 5 for inference-memory: keep manifests, measurements, power envelopes and rejection reasons written beside the model hash; unspoken tribal knowledge is not a deployment strategy for SER-002 chapter 2. Rehearse the acceptance checks after every runtime or BSP bump, and refuse silent EP fallbacks on the hot path.
Worksheet: one artifact, one host, one pass/fail
Create a single worksheet row per model artifact: parameter count, weight dtype/quant, weight bytes on disk, measured resident weights after load, max context, measured cache at max context, peak activation during prefill, allocator headroom target, and pass/fail on a scripted soak test.
Run the soak test three ways: short prompt single stream, max-context single stream, and N concurrent mid-context streams. Record host RAM, device memory and whether swap or major faults appeared. Promote only configurations that pass all three with margin.
If the worksheet fails, change one lever at a time: lower context, lower concurrency, increase quant compression, or move to a host with more bandwidth/capacity. Changing three levers at once produces folklore instead of capacity knowledge.
Archive worksheets with model cards and fail CI when max context rises without a revised estimate.
Technical Glossary
- SODIMM
- Small Outline Dual In-Line Memory Module — compact modular RAM form factor used in laptops and most socketed Mini PCs.
- NPU
- Neural Processing Unit — dedicated silicon block optimized for low-power, fixed-precision AI inference.
- UCFF
- Ultra-Compact Form Factor — roughly 4x4 inch (10x10 cm) Mini PC motherboard and chassis class (typically 0.5–1.5 L).
- PCIe lane
- A point-to-point serial data link (Tx/Rx pair) connecting the CPU to NVMe SSDs, NICs, or expansion cards.
- ECC
- Error-Correcting Code memory — detects and corrects single-bit memory errors for unattended server stability.
- UEFI
- Unified Extensible Firmware Interface — modern system firmware controlling boot, power limits, fan curves, and auto power-on.
- NAND
- Non-volatile flash memory cells used inside SSDs; endurance and sustained write behavior depend on controller and cache.
Sources
- CUDA Memory Management Documentation
Device memory allocation, management and hierarchy overview
- Hugging Face Transformers Memory and Loading Guidance
Inference performance and memory considerations on a single GPU
Claim-to-source map
- NVIDIA CUDA documentation describes how applications allocate and manage device memory for kernels and data on the GPU.
Direct sources: CUDA Memory Management Documentation (citation) - Hugging Face Transformers documentation covers GPU inference performance and memory considerations for model loading and serving.
Direct sources: Hugging Face Transformers Memory and Loading Guidance (citation)
