Local LLM Deployment Guide: Memory Budgeting and Quantization Choices

    A practical guide to deploying large language models locally, covering how to estimate memory requirements, choose quantization levels, weigh unified vs. discrete GPU memory, and handle long contexts, audio input, and model versioning.

    1. Memory Capacity Is Usually the Bottleneck

    When running a large language model locally, the hardware must hold three kinds of data at once: model weights, the KV cache generated during inference, and activation values plus runtime overhead. Whether a machine can load a given model is determined by the sum of all three.

    For models with tens of billions of parameters or more, memory capacity tends to become the bottleneck before compute speed does. If the model cannot be loaded, faster hardware is meaningless. So budget memory first, then discuss throughput and latency.

    Note that memory capacity and generation speed are two different metrics. Capacity determines whether the model can run at all; memory bandwidth determines how many tokens per second it can generate. Evaluate these separately when choosing hardware.

    2. Estimating Memory Requirements

    2.1 Weights

    Weight memory is straightforward to estimate:

    Weight memory ≈ parameter count × bits per parameter ÷ 8

    For a 120B-parameter model:

    • 16-bit (half precision): ~240 GB
    • 8-bit: ~120 GB
    • 4-bit: ~60 GB

    Actual usage varies slightly depending on the quantization format, grouping parameters, and embedding precision, so leave some headroom in your estimates.

    2.2 KV Cache

    KV cache grows linearly with context length:

    KV cache ≈ 2 × layers × KV heads × head dimension × context length × bytes per element

    The factor of 2 accounts for the Key and Value tensors. Models using Grouped-Query Attention (GQA) have far fewer KV heads than query heads, which significantly reduces cache size.

    The following function combines both parts into a single estimate. The overhead ratio of 0.15 is an assumption—adjust it based on measurements from your inference framework.

    1. def estimate_memory_gb(params_b, weight_bits, layers, kv_heads,
    2. head_dim, context_len, kv_bytes=2,
    3. overhead_ratio=0.15):
    4. weights = params_b * 1e9 * weight_bits / 8
    5. kv_cache = 2 * layers * kv_heads * head_dim * context_len * kv_bytes
    6. total = (weights + kv_cache) * (1 + overhead_ratio)
    7. return weights / 1e9, kv_cache / 1e9, total / 1e9
    8. # Example: 120B params, 4-bit weights, 64 layers, 8 KV heads,
    9. # head dim 128, 128K context
    10. w, kv, total = estimate_memory_gb(120, 4, 64, 8, 128, 131072)
    11. print(f"Weights {w:.1f} GB, KV cache {kv:.1f} GB, total {total:.1f} GB")

    The result is roughly: 60.0 GB of weights, 34.4 GB of KV cache, and 108.6 GB total. At 128K context, the cache alone is nearly half the weight footprint. This shows that long-context scenarios must be budgeted separately—you cannot just look at model size.

    3. Choosing a Quantization Level

    Quantization compresses weights from high-precision values into lower-bit representations. It is the most common technique in local deployment, and the core trade-off is quality loss versus memory savings.

    General industry rules of thumb:

    • 8-bit quantization is usually very close to the original precision and works well when memory is plentiful.
    • 4-bit quantization offers a good balance between size and quality, and is the default choice for many local deployments.
    • 2- to 3-bit quantization saves more space, but quality degradation is often noticeable on reasoning, math, and coding tasks.

    Keep in mind that “4-bit is good enough” is a rule of thumb, not a conclusion. Always validate a quantized model against your own task set:

    1. Compare perplexity before and after quantization as a quick screening metric.
    2. Compare accuracy on task sets relevant to your business.
    3. Manually spot-check scenarios prone to errors, such as long-form generation, structured output, and tool calling.

    If your hardware can only run lower precision, consider a mixed-precision approach: keep higher precision for sensitive parts such as the output layer and critical attention layers, and use lower precision elsewhere.

    4. Unified Memory vs. Discrete GPU Memory

    Local deployments typically involve two hardware architectures, each with trade-offs.

    Unified memory architecture lets the CPU and GPU share one large pool of memory. Its advantage is capacity—it can hold models that discrete GPUs cannot. Its downside is that memory bandwidth is usually lower than high-end discrete GPUs, limiting tokens per second.

    Discrete GPU architecture offers high memory bandwidth, suited to high-throughput inference and batch serving. But VRAM capacity is limited, so a single card holds a smaller model, and multi-GPU setups add cost and complexity.

    Ask these questions when choosing:

    • Can a 4-bit (or higher precision) version of your target model fit entirely in memory?
    • Does your use case value single-user availability or concurrent throughput?
    • What are your requirements for time-to-first-token and tokens per second?

    For personal developers or small teams doing offline work, unified memory is often easier to get running. For online services, prioritize bandwidth and concurrency.

    5. Resource Characteristics of Mixture-of-Experts Models

    Mixture of Experts (MoE) is a common design in recent large models. The model contains multiple expert subnetworks, and each token activates only a subset of them.

    This creates a distinctive resource profile:

    • Capacity scales with total parameters: all expert weights typically need to stay in memory, unless you use extra mechanisms like expert offloading. Memory usage is therefore close to the quantized size of the total parameter count.
    • Speed scales with active parameters: each generated token involves far fewer weights than the total, so per-step compute is small. In bandwidth-limited scenarios, speed correlates with how much data is read per step, so MoE models are usually faster than dense models of comparable total size.

    This makes MoE models a good fit for environments with plenty of memory but limited compute or bandwidth. When choosing one, don’t rely on the headline parameter count alone—check total parameters, active parameters, and how well your deployment framework supports MoE.

    6. The Engineering Cost of Long Context

    Long-context support is an important capability, but its costs need to be fully understood.

    1. Memory cost: KV cache grows linearly with context length; the estimation method above applies directly.
    2. Compute cost: attention cost rises with sequence length, and time-to-first-token for long inputs grows noticeably.
    3. Effectiveness cost: the fact that a context window supports a given length doesn’t mean the model reliably uses all information within it. When key information sits in the middle of a long document, recall may drop.

    Practical strategies:

    • Set a context limit based on business needs rather than defaulting to the maximum.
    • Summarize long documents in segments first, then feed the summaries and key excerpts to the model.
    • Use Retrieval-Augmented Generation (RAG) to place only relevant passages in context, reducing wasted capacity.

    Test long-context capability with your own data—for example, insert key facts at different positions and observe how well the model retrieves and answers them.

    7. Integrating Audio and Other Multimodal Inputs

    Some models accept audio input. Common engineering issues when integrating it include sample-rate normalization, audio chunking, and input format conventions.

    Models usually impose fixed input requirements, such as mono audio at 16 kHz. Collected audio must be resampled and channel-converted first. Longer recordings should be split into segments with a small overlap between them, so words aren’t cut off at boundaries.

    1. def split_audio(samples, sr=16000, chunk_seconds=30, overlap_seconds=1):
    2. """Split mono audio into fixed-length chunks with overlap between adjacent chunks."""
    3. chunk = sr * chunk_seconds
    4. step = chunk - sr * overlap_seconds
    5. chunks = []
    6. start = 0
    7. while start < len(samples):
    8. chunks.append(samples[start:start + chunk])
    9. start += step
    10. return chunks

    There are two common patterns for audio input; choose based on your scenario:

    • Native audio understanding: send audio directly to the model, which handles understanding or Q&A. Best when tone, sound events, and similar information matter.
    • Transcribe first, then process: use a speech recognition module to convert audio to text before passing it to the language model. The pipeline is easier to debug and makes transcripts auditable.

    Either way, check input quality—silence ratio, noise level, volume range—and log abnormal samples for later optimization.

    8. Model Version Lifecycle Management

    Version management matters when a team maintains multiple models. Model files are large, and keeping unused ones on fast storage consumes valuable memory or disk resources.

    A sound practice is to maintain a manifest for each model, recording its source, version, quantization method, checksum, evaluation results, and storage location. Models no longer in active use can be moved to low-cost cold storage, such as the infrequent-access tier of object storage, with the manifest retained for easy restoration.

    1. model_id: model-a-v2.5
    2. source: internal registry
    3. quantization: 4bit-grouped
    4. size_gb: 62
    5. sha256: "<checksum>"
    6. eval:
    7. task_set: internal-v3
    8. accuracy: 0.87
    9. first_token_latency_ms: 850
    10. status: archived
    11. storage: cold-object-storage/models/
    12. restore_command_ref: docs/restore.md

    Before archiving, complete three steps: verify the checksum, confirm the manifest is complete, and save representative evaluation results. When restoring, re-verify the files to avoid corrupted files causing anomalies in production.

    9. Building Your Own Evaluation Benchmark

    Public leaderboards reflect a model’s general ability but cannot replace testing on your business scenarios. A self-built evaluation set typically includes three categories:

    • Typical questions from real business usage, covering common and high-frequency scenarios.
    • Edge cases prone to errors, such as long-text reasoning, format constraints, and multi-step calculations.
    • Safety and compliance samples, to check refusals and handling of sensitive content.

    Evaluate both quality and performance metrics: accuracy, time-to-first-token, tokens per second, and peak memory. Here is a simple benchmark framework:

    1. import time
    2. def run_benchmark(generate, cases):
    3. """cases is a list of (prompt, checker) tuples; checker takes the output and returns pass/fail."""
    4. results = []
    5. for prompt, checker in cases:
    6. t0 = time.perf_counter()
    7. output = generate(prompt)
    8. latency = time.perf_counter() - t0
    9. results.append({"ok": checker(output), "latency_s": latency})
    10. accuracy = sum(r["ok"] for r in results) / len(results)
    11. avg_latency = sum(r["latency_s"] for r in results) / len(results)
    12. return accuracy, avg_latency