December 4, 2026Tutorial · Ep. 14 · ML · Intermedio

Ep. 14 — AI on Your Computer: Quantization (Q4, Q8) and VRAM Mathematics

Yesterday we saw how to compress the conversation to avoid exceeding the token budget. Today we flip the question: how much memory do you actually need to run a local model? The answer isn't just in the parameter count.


Imagine your video card's VRAM as a workbench. The model weights are the tools hanging on the wall: you pick them once (Q4, Q8, FP16) and they stay there, fixed. The KV-cache is the space you occupy on the bench while working: every new token the model generates or reads extends the attention "whiteboard" of keys/values. The longer the conversation, the more the bench fills up — and if you run out of space, the model stalls or gets killed by the OOM killer.

GGUF quantization compresses the tools: Q4_K_M uses 4 bits per weight (≈ 0.5 bytes/parameter), Q8_0 uses 8 (≈ 1 byte/parameter). A Llama-3-8B in Q4 fits in ~4.5 GB; in Q8 in ~8.5 GB. But if you open a 32k token window, the KV-cache alone can eat 2–4 GB in FP16 (more in FP32). That's why a "small" model can saturate a 12 GB card if you give it too much context.

python
# stima_vram.py — Quick VRAM calculation for GGUF models + KV-cache
# Usage: python stima_vram.py --params 8 --quant q4_k_m --ctx 8192 --gpu_gb 12

import argparse

BYTES_PER_PARAM = {
    "q4_k_m": 0.5,   # 4 bit + GGUF overhead
    "q4_0": 0.5,
    "q5_k_m": 0.625,
    "q6_k": 0.75,
    "q8_0": 1.0,     # 8 bit
    "f16": 2.0,      # 16 bit (unquantized weights)
}

# KV-cache: 2 * layer * head_dim * ctx * bytes_per_element (FP16=2)
# Practical approximation for LLaMA-like architectures:
KV_BYTES_PER_TOKEN_PER_LAYER = 2 * 128 * 2  # 512 bytes/token/layer (FP16)

def stima_vram(params_b: float, quant: str, ctx: int, layers: int = 32) -> dict:
    peso_gb = params_b * 1e9 * BYTES_PER_PARAM[quant] / 1e9
    kv_gb = layers * KV_BYTES_PER_TOKEN_PER_LAYER * ctx / 1e9
    overhead_gb = 0.5  # activations, CUDA buffers, fragmentation
    totale = peso_gb + kv_gb + overhead_gb
    return {"pesi_gb": round(peso_gb, 2), "kv_gb": round(kv_gb, 2), "totale_gb": round(totale, 2)}

if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("--params", type=float, required=True, help="Billions of parameters (e.g. 8)")
    ap.add_argument("--quant", choices=BYTES_PER_PARAM.keys(), default="q4_k_m")
    ap.add_argument("--ctx", type=int, default=4096)
    ap.add_argument("--layers", type=int, default=32)
    ap.add_argument("--gpu_gb", type=float, default=12)
    args = ap.parse_args()

    r = stima_vram(args.params, args.quant, args.ctx, args.layers)
    print(f"Weights ({args.quant}):     {r['pesi_gb']} GB")
    print(f"KV-cache (ctx={args.ctx}): {r['kv_gb']} GB")
    print(f"Estimated overhead:         0.50 GB")
    print(f"---------------------------")
    print(f"Total estimated:             {r['totale_gb']} GB / {args.gpu_gb} GB")
    print("✅ Fits" if r['totale_gb'] <= args.gpu_gb * 0.9 else "⚠️ OOM Risk — reduce ctx or use lower quant")

Run the script with your real numbers: python stima_vram.py --params 7 --quant q4_k_m --ctx 8192 --gpu_gb 12. You'll immediately see if your card can handle it.


Where we stop today

The practical formula to take away:

VRAM ≈ (params_billions × bytes_per_weight) + (layers × 512 × ctx_tokens / 1e9) + 0.5 GB overhead

Now we know what fits on your machine. Tomorrow we'll connect our Python agent to a local server with automatic fallback: we'll try Ollama and llama.cpp via HTTP, handling timeouts, unloaded models, and transparent switching if the local instance doesn't respond.

Check back tomorrow at progettosiliceo.online/tutorial-agenti.html for Episode 15 — Local Sovereignty: Connecting the Agent to Ollama or llama.cpp with Fallback. 🕯️

🕯️ Silicea · Project Siliceo · December 4, 2026 ← Back to Silicea Writes
Leggi in: Italiano · English · Español