KnowML
Hands-onChapter 30

Running Models Locally

Follow one model, Llama 3 8B on an 8 GB graphics card, from "will it fit?" to "how fast will it run?", and learn the arithmetic that answers both before you download anything.

⏱ 16 min readAssumes: KV cache (08), quantization theory (23)
Start reading

Say you've found Llama 3 8B, an open model with about eight billion parameters, and you'd like to chat with it on your own computer. Its graphics card has 8 GB of memory. Will it run? Most people find out the slow way: they download several gigabytes, start the program and watch what happens. It can go wrong in three ways. A load can fail outright, the model can load and then crawl, or it can work fine for an hour and then crash in the middle of a long conversation. All three are predictable in advance with a few lines of arithmetic.

That memory is called VRAM (video RAM), the fast memory attached to the GPU, and three things share it: the model's weights, a temporary store called the KV cache that grows as the conversation gets longer, and a modest amount of overhead from the software itself. At short conversations the weights take most of the room, and at long ones the KV cache takes over, so you have to compute both. The main way to shrink the weights is quantization, which stores each number in fewer bits (chapter 23 covers why that works). Which quantization format you pick is mostly decided by the program you run, so quality doesn't choose it: GGUF for llama.cpp and Ollama, AWQ or GPTQ for vLLM, and bitsandbytes NF4 for QLoRA fine-tuning, and that one isn't a serving format at all.

Names mislead here too. A format called Q4_K_M sounds like 4 bits per weight, and it measures 4.89. Once a model does fit, the next question is speed, and the answer surprises people: memory bandwidth sets how fast tokens come out, and the GPU's arithmetic speed barely matters. A smaller quantization therefore generates tokens faster on identical hardware.

If you need one sentence for an interview, it's this: local inference is a memory-capacity problem first, a memory-bandwidth problem second, and a compute problem almost never. Through the chapter we'll keep one case in front of us, Llama 3 8B at Q4_K_M on an 8 GB card, and watch what each decision does to it. You'll want to know what a KV cache is (chapter 08) and the idea of quantization (chapter 23).

01What fills the card

"Will this run on my machine?" has an answer you can work out before downloading anything. Page 23 explains why quantization works and how PagedAttention manages a KV cache. This page is the practical counterpart, covering what fits, what to install, and what to expect once it's running. We'll start by listing what competes for the card's memory.

First come the model weights, the billions of learned numbers that make up the model. They're fixed once you choose a model and a quantization level, and they're usually the largest single item. Second is the KV cache. When a model generates text it keeps a key and a value vector for every token it has already seen, so it doesn't recompute them for each new token. A token is a word or a piece of a word, and the number of tokens the model can look back over is its context length. It grows linearly with context length and with the number of conversations running at once, so it's small at 2k tokens of context and dominant at 128k. Third is overhead: activations (the temporary results of each layer's calculation), the CUDA context (the bookkeeping the GPU driver keeps for a program) and the framework itself. It's small, a few hundred megabytes to about a gigabyte, and people forget it.

If the sum is more than your VRAM, one of three things happens. The load can fail outright. The runtime can quietly move some layers into ordinary system memory and run an order of magnitude slower. Or you can hit an out-of-memory error partway through a long conversation, which means the KV cache grew past your headroom. That last one catches people because the model had loaded without complaint.

Below, the same 24 GB card in four situations, with every bar at the same scale. Compare the last two rows in particular, because they hold identical weights and differ only in how much context the conversation has reached.

The same 24 GB card, four ways — drawn to scale, 20 px per GB
weights KV cache overhead free 24 GB 70B · FP16 4k context 140 GB of weights — bar runs ~6× off the chart 70B · Q4_K_M 4k context ~40 GB — quantized hard and still 1.7× too big 8B · Q4_K_M 4k context 4.9 GB 17.6 GB free 8B · Q4_K_M 128k context 4.9 GB 16 GB of KV cache Rows 3 and 4 are identical weights on an identical card. Only the context length moved, and it took the card from 27% full to nearly full.
Everything here is drawn at one scale, 20 px per GB, so the bars are comparable and the top two do run off the chart instead of being drawn short. The KV figures assume an 8B model with grouped-query attention (32 layers, 8 KV heads, head dim 128, FP16), which comes to 128 KB per token: 0.5 GB at 4k and 16 GB at 128k. That's why "will model X fit in Y GB" can't be answered without a context length attached, and why an out-of-memory error can arrive an hour into a conversation instead of at load time.

So a question like "does model X fit in Y GB?" is incomplete until someone says how much context, and we can't leave it to guesswork. The next section computes the three terms for our Llama 3 8B.

02Do the arithmetic once

Learn to compute this and you'll never need to trust a compatibility table again. There are two real terms, weights and cache, plus a small allowance for overhead. For the weights, the obvious guess is the number of parameters times the bits each one takes, divided by eight to get bytes. For the bits, the obvious guess is the number in the format's name, so 4-bit would mean half a byte per parameter, or 4.0 GB for our model. In fact the real file is 4.58 GiB (a GiB is 230 bytes, a little more than a GB), and the derivation below shows where the difference goes.

For the cache term we need one fact about the model's architecture. Chapter 08 describes attention heads, the parallel groups of queries, keys and values inside each layer. In grouped-query attention (GQA), several query heads share a single key-value head, so the cache stores only the key-value heads, and Llama 3 8B has 32 attention heads but only 8 key-value heads. That's the number that goes into the formula, and using the wrong one inflates your estimate several-fold. The worked example below puts both terms together for 8 GB of VRAM at 8k context.

Worked example Does Llama 3 8B fit in 8 GB of VRAM at 8k context?

Every number below comes from the model's published config.json and from llama.cpp's own measurements. Your framework overhead will differ, so treat that one term as illustrative. The weight and cache terms are exact.

  1. The naive version, and why it's wrong. People assume 4-bit means half a byte per parameter. Llama 3 8B has 8,030,261,248 parameters, so that predicts 4.0 GB. The real Q4_K_M file is 4.58 GiB. A name isn't a footprint.
  2. Why 4.89 and not 4.00: k-quants store a scale and a minimum per block of weights, and the _M variant deliberately keeps some tensors at higher precision. Both cost bits. llama.cpp publishes a measured 4.8944 bits per weight for this model, and that matches the observed file size exactly.
  3. Why the leading 2: you cache a key and a value for every token, at every layer. The term everybody gets wrong is . With grouped-query attention it's far smaller than the number of attention heads, and picking the wrong one inflates your estimate several-fold.
  4. Where these come from: Llama 3 8B's config gives 32 layers, 8 key-value heads, and a head dimension of 128 (hidden size 4096 over 32 attention heads). The final 2 is bytes per element for an FP16 cache. Note the 32 attention heads against only 8 KV heads.
  5. A clean coincidence worth remembering: this model at 8k context needs exactly one gibibyte of KV cache. Had it used full multi-head attention, with 32 KV heads instead of 8, the same calculation gives 4 GiB. Grouped-query attention is quietly doing a lot of work for local users.
  6. The fudge factor. Activations, the CUDA context and framework allocations are real but modest. Budget several hundred megabytes to roughly a gigabyte. That total leaves usable headroom inside 8 GB, so yes, it fits. Doubling the context to 16k costs exactly one more gibibyte, and that is the term to watch.
The habit worth forming. Compute the weight term and the cache term separately, because they scale differently. Weights are fixed the moment you pick a file. Cache grows with every token of context and every concurrent request. A model that loads comfortably at 2k can run out of memory at 32k on the same card, and that's probably the most common local-inference surprise there is.

Our model fits, with about 1.7 GiB to spare, and we know which term to watch: each doubling of context costs another gibibyte. People also quote a rule of thumb, roughly 0.6 to 0.7 GB per billion parameters at Q4_K_M, and it agrees with the calculation above (4.58 GiB is 4.92 GB, over 8.03B parameters, so 0.61). It's a fine sanity check, though it stays a rule of thumb because it silently assumes a 4-bit k-quant, ignores context length, and says nothing about how many KV heads the architecture has.

That 4.58 GiB came from a particular file format, and formats are the next thing to understand, since the one you can use depends on the program you run.

03Formats you'll meet

A quantization format looks like a quality decision, since it determines how many bits each weight gets. In practice it's a compatibility decision, because each runtime (the program that loads the model and generates text) reads its own format. Pick the runtime first and the format usually follows. Section 4 covers the runtimes, and here are the formats they read.

GGUF is the native format for llama.cpp, and therefore for Ollama and LM Studio, which build on it. It's the only one of these designed for CPU and for hybrid CPU-plus-GPU execution. GPTQ is a post-training weight quantization algorithm aimed at GPU inference, and it's widely supported, vLLM included. AWQ is activation-aware weight quantization: it protects the weights that matter most, the ones whose observed activations are largest, and it's a common choice for GPU serving. bitsandbytes NF4 quantizes the model on load and not ahead of time. It's the standard path for QLoRA fine-tuning and it isn't a serving format (see 29).

Why isn't Q4_K_M 4 bits per weight?

Inside GGUF, the names tell you how a model was quantized, and they're easy to misread. Q4_K_M reads like "4 bits per weight", and it measures 4.8944. Q8_0 reads like 8 bits and measures 8.50. Each piece of the name carries a meaning. Q4 is the base block type. K means k-quants, a block-wise scheme that stores a scale and a minimum for each block of weights, and those extra numbers cost bits. M is the medium mix, which keeps selected tensors at higher precision than the name suggests. So you should budget from measured bits per weight and never from the digit in the filename. Budget Llama 3 8B at a flat 4.0 bits and the real 4.89-bit file comes out 22% bigger than you planned for, and that's plenty to make a model refuse to load.

llama.cpp publishes measured figures for Llama 3.1 8B, and the table below is the real size ladder. Q3_K_M, for instance, measures 4.00 bits, so a "3-bit" name hides a full 4. Each step down the ladder shrinks the file, and each step also takes something from quality.

QuantQ2_KQ3_K_MQ4_K_MQ5_K_MQ6_KQ8_0F16
Bits per weight3.164.004.895.706.568.5016.00
Size (GiB)2.953.744.585.336.147.9514.96

How much quality is lost? Degradation is usually gradual, and how gradual seems to depend on both the model and the task. Q4_K_M is the widely used default because it sits at a good size-to-quality point. Users start reporting noticeable losses below roughly 4 bits per weight, and the very low quants exist for when fitting at all matters more than fidelity. Measure on your own task and don't trust a general claim, this one included.

With a format chosen, the remaining decision is the program that will read it.

04Which tool to pick

Tools split cleanly by what you're doing, and the question to ask is whether you're serving one user or many. For one user on your own machine, Ollama is the shortest path from nothing to a running model, and LM Studio adds a GUI. Use llama.cpp directly when you need control over build flags, quantization and runtime settings. The first two are wrappers around the third, and that's why they all read GGUF.

For many concurrent users, the choice is vLLM, TGI or SGLang. These implement continuous batching (new requests join a batch that's already running) and a paged KV cache, and that's what turns idle GPU time into throughput. Page 23 explains the mechanisms. On Apple Silicon, MLX is built for the hardware, though llama.cpp also runs well on Metal, Apple's GPU programming interface.

A common mistake is reaching for a serving framework to run a single local chat. vLLM's advantages are throughput advantages, and with one user and a batch size of one (a single request at a time), you're paying setup complexity for benefits you can't reach. For our Llama 3 8B on one 8 GB card, Ollama or llama.cpp is the right call. Whether the card is big enough in general is a question about hardware, so that's next.

05Hardware tiers

Everything below follows from the arithmetic in section 2, applied at Q4_K_M with a modest context. Treat the model sizes as what fits comfortably and not as hard ceilings, since context length moves these more than anything else. We'll start at our own 8 GB and work upward.

With 8 GB of VRAM, 7B and 8B models fit at 4-bit with room for a normal context of 4k to 8k, going by the worked example above. That's roughly the entry point where local inference stops being painful. A card with 12 to 16 GB runs 7B to 14B models comfortably, with longer contexts and no need to watch the cache, and the extra headroom mostly buys context and not parameters. At 24 GB you can fit 30B-class models at 4-bit, or a smaller model with a large context, and that's a meaningful step up. From 48 GB upward is 70B-class territory: llama.cpp measures a 70B at 43.1 GB in Q4_K_M, so 48 GB works with care and multi-GPU is more comfortable.

Two kinds of machine don't fit that ladder. Apple Silicon has unified memory, meaning the CPU and GPU share one pool, so a machine with plenty of it can hold models that would otherwise need a very expensive discrete GPU. Bandwidth varies by chip tier, and as the next section shows, bandwidth is what governs speed. A CPU-only machine works too, thanks to GGUF, but generation is slow enough to feel like waiting and not conversing, because you're limited by system RAM bandwidth.

For scale at the top end, llama.cpp's own table puts Llama 3.1 405B at 249.1 GB even in Q4_K_M, against 1,625.1 GB unquantized. Some models aren't a local option at any consumer tier. And once a model does fit, we run into the question the tiers keep pointing at: how fast will it be?

06What makes it slow

Once a model fits, speed becomes the question, and your bottleneck is probably not what you'd guess. It's memory bandwidth, how fast bytes move between memory and the compute units, and arithmetic throughput rarely limits you. To see why, count what happens for one token. Generating a token means reading every weight in the model, so our 4.58 GiB model moves 4.58 GiB for each token, and that cost repeats for every token of every request. At batch size one, each of those bytes does a tiny amount of arithmetic before the next one is needed, so the GPU spends most of its time waiting for memory. Page 23 formalises this as arithmetic intensity.

If that's right, shrinking the weights should speed up generation, and llama.cpp's published benchmarks for Llama 3.1 8B show it. Text generation gets faster as the quantization gets smaller: roughly 72 tokens/sec at Q4_K_M against 51 at Q8_0 and 29 at F16. Prompt processing, the step where the model reads your whole prompt before it starts answering, does the opposite. It stays broadly flat across quantizations, and F16 is the fastest of them. The source table doesn't say which hardware produced these figures, so read the pattern and not the absolute numbers.

Why do prompt processing and generation move in opposite directions?

Prompt processing handles many tokens at once against each weight it loads, so each byte read does a lot of arithmetic so the step is compute-bound and quantization doesn't help it. Generation produces one token at a time, so it's bandwidth-bound, and shrinking the weights shrinks the work directly. Same model, same hardware, two opposite conclusions.

Two practical consequences follow. First, offloading layers to the CPU is expensive. When a model doesn't fit, runtimes put some layers in system RAM, and every token then crosses the PCIe bus, the link between the GPU and the rest of the computer, and that link is far slower than VRAM. A partial offload can therefore cost more speed than dropping to a smaller quantization would have. Second, batch size one is the worst case for bandwidth, and it's also the normal case locally. Batching amortises weight loading across requests, since one read of the weights serves every request in the batch, so serving frameworks help enormously at volume and barely at all in a single chat session.

That leaves a practical question: given all this, when is running locally the right call at all?

07Where you meet this in the wild

Local inference usually isn't about saving money. It's about constraints an API can't satisfy.

Here are five situations where people end up running models themselves, each with the constraint that pushed them there.

Coding assistants
Completion that never leaves the laptop
Proprietary code that can't be sent to a third party, plus latency low enough for inline completion. Small models compete well here, because the task is narrow and the context is already on the machine.
Regulated data
When the data legally can't leave
Health records, legal discovery, defence work. The requirement is that no bytes cross an organisational boundary, and that rules out a hosted API whatever its terms say.
Edge and offline
No network to depend on
Vehicles, field equipment, remote sites, air-gapped networks. The model has to fit a fixed hardware budget nobody's going to upgrade, so quantization stops being an optimisation and becomes a requirement.
Bulk processing
Millions of small, tolerant jobs
Classification, tagging and extraction over a large corpus. Per-token API pricing scales linearly with volume and owned hardware doesn't, so high-volume low-stakes work is where local economics win.
Experimentation
Poking at the actual weights
Interpretability, custom sampling, activation inspection, evaluating your own fine-tune from 29. An API gives you tokens. Local gives you the model.

Reading across the cards, you can turn them into a rule. Left are conditions that point toward running locally, and right are the ones that point back to an API.

Run it locally when
  • Data can't leave. Regulatory or contractual, and no pricing argument overrides it.
  • You need to work below the API surface: logits, activations, custom sampling, your own fine-tuned weights.
  • Volume is high and per-call value is low, so per-token pricing dominates your costs.
  • You need offline operation, or latency a network round trip can't meet.
Use an API when
  • You want frontier quality, and the largest models aren't a local option at consumer scale.
  • Traffic is spiky or low, and idle hardware still costs money while idle API calls don't.
  • You'd be paying an engineer to babysit inference infrastructure that isn't your product.
  • You need elastic concurrency, and one local GPU serving many users behaves like a queue.

08Summary

  1. Three things share your VRAM: the model weights, the KV cache and the framework overhead. Compute all three before you download anything.
  2. Weights are fixed and the cache grows. Weights are set by your choice of file, while the cache grows with context length and concurrent requests, so a model that loads at 2k context can run out of memory at 32k.
  3. Use the right head count. KV cache per token is 2 × layers × KV heads × head dimension × bytes, and with grouped-query attention it's the KV heads that count. Llama 3 8B costs 128 KiB per token, or 1 GiB at 8k context.
  4. The format follows the runtime. GGUF for llama.cpp, Ollama and LM Studio, AWQ or GPTQ for vLLM, and bitsandbytes NF4 for QLoRA fine-tuning, and that one isn't a serving format.
  5. Budget from measured bits per weight. Q4_K_M measures 4.89 and Q8_0 measures 8.50, so the digit in the name understates the real file size.
  6. Q4_K_M is the usual default, at roughly 0.6 to 0.7 GB per billion parameters. Losses tend to show below about 4 bits, so measure on your own task.
  7. Match the tool to the audience. Ollama, LM Studio or llama.cpp for one user, and vLLM, TGI or SGLang when many users share a GPU.
  8. Hardware tiers follow the arithmetic. 8 GB fits 7B and 8B, 12 to 16 GB fits 7B to 14B, 24 GB fits 30B-class, and 48 GB and above reaches 70B.
  9. Generation is bandwidth-bound. Each token reads every weight, so a smaller quantization generates faster, while prompt processing is compute-bound and doesn't speed up.
  10. Offloading to the CPU can cost more than a smaller quant. Layers in system RAM mean every token crosses the PCIe bus.
  11. Run locally for privacy, offline use, low-value bulk work or access to the weights, and use an API for frontier quality, spiky traffic or when you'd rather not run infrastructure.

09Interview questions

BeginnerHow do you estimate whether a model fits on a given GPU?

Add three terms. Weights are parameter count times bits per weight divided by eight, using the measured bits per weight, not the number in the quantization name. KV cache is 2 × layers × KV heads × head dimension × bytes per element, per token, multiplied by your context length and concurrency. Then add several hundred megabytes to about a gigabyte of framework overhead. As a sanity check, Q4_K_M lands near 0.6 to 0.7 GB per billion parameters before cache.

BeginnerWhy is Q4_K_M not 4 bits per weight?

Because k-quants store a scale and a minimum for each block of weights, and the medium mix deliberately keeps some tensors at higher precision. llama.cpp measures Q4_K_M at 4.8944 bits per weight for Llama 3.1 8B, about 22% above the naive assumption. Budget from the filename instead of the measured figure and you'll discover the model doesn't fit only after downloading it.

IntermediateWhy does the KV cache formula use KV heads and not attention heads?

Because grouped-query attention shares each key-value head across several query heads, so only the KV heads are actually stored. Llama 3 8B has 32 attention heads but 8 KV heads, so its cache is four times smaller than the multi-head equivalent: 128 KiB per token instead of 512 KiB. Use attention heads in the formula and you overestimate cache memory by exactly that ratio, which is enough to reject a configuration that would've worked.

IntermediateA model loads fine but runs out of memory after a long conversation. What happened?

Your KV cache grew past the remaining headroom. Weights are a fixed cost paid at load; the cache grows linearly with every token in the context. A model that leaves a gigabyte free after loading will exhaust it once the conversation's cache passes that gigabyte. Fixes: cap context length, drop to a smaller quantization to free capacity, or quantize the cache itself if your runtime supports it.

IntermediateWhy does a smaller quantization generate tokens faster on the same hardware?

Because generation is memory-bandwidth-bound. Producing each token requires reading every weight, so halving the bytes per weight roughly halves the bytes moved per token. llama.cpp's benchmarks show this directly: about 72 tokens/sec at Q4_K_M against 29 at F16 for Llama 3.1 8B. Prompt processing doesn't follow the same pattern and stays roughly flat across quantizations, because prefill processes many tokens per weight load and is compute-bound instead.

DeepYour model needs 26 GB and you have a 24 GB card. Walk through the options.

Take the cheapest quality loss first. Drop one quantization step, since Q5_K_M to Q4_K_M is roughly a 14% size reduction and usually closes a 2 GB gap on its own. Next, reduce maximum context length, which shrinks the cache term without touching weights at all, and check whether your runtime can quantize the KV cache to 8-bit. Offloading layers to CPU comes near-last, because every offloaded layer crosses PCIe on every token and usually costs more throughput than a smaller quantization would have. A second GPU works, but it adds communication between devices, and that's only worth it when quality genuinely can't be compromised.

DeepWhen is running locally genuinely cheaper than an API?

When utilisation is high and quality requirements are modest. Hardware is a fixed cost you pay whether or not it's busy, while API pricing is proportional to use, so local wins on sustained high-volume workloads and loses on spiky or low ones. Include engineering time too, since that's usually the largest hidden cost. Most local deployments are justified by privacy, offline operation or model access, not by cost, and treating cost as the main argument usually means nobody's done the arithmetic.

10Go deeper

●Now write it yourself

Reading the derivation and being able to produce it are different skills. These are Deep-ML problems that exercise what this page covers — each one is checked against real test cases, not multiple choice.

Matched to this page from Deep-ML's catalogue of 1,380 problems. More at deep-ml.com, and Where to practise covers the other platforms and what each one trains.