Local LLM Deployment: VRAM, Throughput, and Chat Template Tuning for Small Models
A practical guide to running 4B–10B parameter models locally. It shows how to estimate VRAM up front (weights, multimodal components, KV cache, runtime overhead), how quantization tiers trade quality against file size, why decode speed tracks memory bandwidth rather than prompt content, how to benchmark TTFT and tokens/s through a streaming API, how to get chat template rendering right, and how to choose between lightweight inference engines and high-throughput serving frameworks. It closes with an operations view and a tuning checklist.
1. Background: Why “Small Model + Local Deployment” Deserves a Serious Evaluation
A single-GPU workstation, or a PC with a discrete GPU, can already carry models in the 4B–10B parameter range. That opens up new options for local deployment:
- Data stays local: contracts, source code, and internal documents — sensitive material never has to leave your network;
- Controllable latency: no round trips over the public internet;
- Predictable long-term cost: one hardware purchase, no usage-based billing.
The hard part in practice is the gap between “it runs” and “it runs stably, fast, and accurately”. Not enough VRAM means load failures or constant paging. A chat template rendered the wrong way produces answers that miss the question. Once concurrency climbs, throughput drops sharply and wait times become unpredictable.
The evaluation framework fits in one sentence: whether a local inference service is adequate comes down to four metrics.
- Does it fit? VRAM and system memory usage, including model weights, multimodal components, and the KV cache;
- Is it fast? Time to first token and per-request output speed;
- Does it hold up under concurrency? Throughput and tail latency when several users share it;
- Are the answers right? Actual performance on your business tasks.
Each point is expanded below.
2. A Calculable Model of VRAM Usage
Judgments about “how much memory this model needs” usually stay at the level of intuition, yet VRAM usage can be estimated fairly accurately before deployment.
2.1 Where the Memory Goes: Four Components Added Together
Total VRAM ≈ model weights + multimodal component weights + KV cache + runtime overhead
| Component | Depends on | Typical magnitude (small/medium models) |
|---|---|---|
| Model weights | parameter count × bytes per parameter | roughly 2–5 GB (4-bit quantization) |
| Multimodal component weights | vision encoder and projection layer | usually a few hundred MB |
| KV cache | number of layers, KV head dimension, sequence length, concurrency | a few hundred MB up to several GB |
| Runtime overhead | framework, memory pool, compute graph, temporary buffers | a fixed portion plus a variable portion |
Three additions:
- Multi-GPU deployment: every card keeps its own copy of the runtime overhead, so you cannot simply divide “total VRAM” evenly;
- Context amplification: expanding the context from a few thousand to well over a hundred thousand tokens multiplies the KV cache, which can end up larger than the weights themselves;
- Process sharing: the same weights loaded in several processes get copied each time, so whether a single instance is economical depends on your concurrency needs.
2.2 Estimating Weight Size: One Table Does It
| Weight precision | Bytes per parameter (incl. small alignment overhead) | 4B-class model | 9B-class model |
|---|---|---|---|
| FP16 / BF16 | ~2.0 | ~8 GB | ~18 GB |
| 8-bit group quantization | ~1.1 | ~4.4 GB | ~9.9 GB |
| 4-bit group quantization | ~0.6 | ~2.4 GB | ~5.4 GB |
The numbers are theoretical estimates using a generic method. Real files differ slightly depending on the quantization algorithm, the alignment scheme, and which layers stay at higher precision, so the actual size of the weight files is authoritative.
This gives a rule of thumb: parameter count determines weight size, and weight size in turn determines the baseline cost per token during decoding (see Section 4). When VRAM capacity is limited, quantization is usually the most direct and most effective lever.
2.3 More Aggressive Quantization Is Not Always Better
The common approach is to push most tensors down to 4 bits, keep some layers at higher precision, and share a scale factor per small block. The costs are twofold:
- Quality loss: code, math, and long-form reasoning are more sensitive to quantization;
- Extra compute: dequantization and table lookups add work, and individual layers or operations may fall back to higher-precision arithmetic.
On selection, the 4-bit tier that keeps inference quality reasonably intact while cutting file size well below 8-bit is usually the cost/benefit sweet spot, but always validate it with business samples. INT8 offers high compute efficiency and small accuracy loss on most hardware, which suits cases with large weights or compute-heavy workloads. Below that bit width, returns diminish and quality risk rises.
2.4 A Small but Crucial Concept: “Effective Parameter Count”
Some newer architectures reduce the compute and storage actually needed at inference time through sharing, low-rank decomposition, or conditional computation, so vendors may label a model with an “effective parameter count”. A model advertised as 4B whose real parameter count is closer to 8B is not unusual.
That also explains the observation that a model’s “footprint is about the same as a 4B-class model”: if the reference point is a full-precision checkpoint, the two sizes may genuinely be close; if the reference is a quantized checkpoint, check whether different quantization tiers were used. Parameter count is only the starting point — the actual size of the weight files is the cost baseline.
3. The Extra Overhead Introduced by Multimodal Inputs
In the original author’s comparison, the vision component was counted toward the footprint together with the language model weights, and that is correct. A multimodal model’s memory usage splits into two parts:
- Static overhead: the vision encoder and projection layer stay resident in VRAM, loaded once, independent of the number of images;
- Dynamic overhead: each image first goes through the vision encoder to extract features, then through the projection layer, which maps them into vision tokens the language model can process; those tokens are inserted into the context sequence and take part in all subsequent computation.
So the higher the image resolution and the more images per request, the more vision tokens there are, and both prefill compute and KV cache usage rise.
Two practical takeaways:
- For recognition tasks, downscale images to a size where text is still legible first; for multi-image cases, assess whether every image really needs to be passed in full;
- Multimodal component weights are usually only a few hundred MB — if they dominate your VRAM budget, re-check weight precision and the loading method first.
4. Why Decoding Is Determined by Memory Bandwidth: A Speed Intuition
Before reasoning about speed, separate the two compute phases:
- Prefill: the model processes the entire input in one pass — large matrix multiplications, so it is compute-bound;
- Decode: tokens are generated autoregressively, one at a time; every step reads all the weights from VRAM into the compute units while the actual arithmetic is small, so it is memory-bandwidth-bound.
That leads to a generalizable conclusion:
For a single request, generation speed (tokens/s) is roughly proportional to memory bandwidth and roughly inversely proportional to the number of weight bytes read per token.
Three inferences follow:
- Halving weight precision without changing the architecture should roughly double theoretical generation speed, though implementation details take a cut;
- Smaller models are “fast” essentially because their weights are smaller and fewer bytes are read per token;
- Decode speed is largely determined by model size and hardware bandwidth, and has little to do with prompt content; prompt length shows up mainly in time to first token.
The rule has practical value too: if two small models have similar footprints and similar measured speeds, it usually means they read a similar volume of weights per token, not that one of them is “especially efficient”.
5. Deep-Thinking Models “Feel Faster”: How to Measure It
Reasoning models generate a fairly long chain of thought before giving the answer. Their time budget does not match intuition:
| Time component | Determined by | Note |
|---|---|---|
| Length of the thinking chain | how the model was trained, output length settings | largest impact on total time |
| Time to first token | input length (prefill), whether VRAM is paging | most strongly perceived by users |
| Output speed during thinking | memory bandwidth, weight precision and size | thinking content is usually not shown in the UI, creating the impression that things are “stuck” |
| Answer generation speed | same as above | output is visible and countable |
“Thinking felt faster” may be a genuine speed improvement or just a per-task difference, so do not draw conclusions from feel. Record three numbers:
- Time to first token (TTFT)
- Token count and elapsed time for the thinking portion
- Total output tokens and total elapsed time
Results are only comparable once conditions such as average input/output length and concurrency are included.
5.1 Separating Visual Smoothness from Actual Speed
Streaming output in a UI often creates an impression of speed, but visual smoothness depends on refresh rate and network conditions. If output is emitted in batches to save compute, or requests are relayed through a server, subjective feel and actual throughput can diverge noticeably. Trust only the real data returned by the server.
5.2 Measure Through the Streaming API
If the server offers a streaming endpoint and reports usage in fields such as completion_tokens, the script below measures accurate numbers:
import jsonimport timeimport urllib.requestdef measure(base_url: str, payload: dict) -> dict:"""Send one streaming request to the server and report:ttft_ms time to first token (milliseconds)total_ms total time from request start to end of stream (milliseconds)tokens output token count reported by the servertps average generation speed across the thinking and output phases"""req = urllib.request.Request(f"{base_url}/v1/chat/completions",data=json.dumps(payload, ensure_ascii=False).encode("utf-8"),headers={"Content-Type": "application/json"},)start = time.perf_counter()first_token_at = Noneusage = Nonewith urllib.request.urlopen(req) as resp:for raw in resp:line = raw.decode("utf-8").strip()if not line or not line.startswith("data:"):continuedata = line[len("data:"):].strip()if data == "[DONE]":continuechunk = json.loads(data)if chunk.get("usage"):usage = chunk["usage"]delta = chunk["choices"][0]["delta"].get("content")if delta and first_token_at is None:first_token_at = time.perf_counter()tokens = usage["completion_tokens"] if usage else 0tps = tokens / (time.perf_counter() - first_token_at) if first_token_at and tokens else 0return {"ttft_ms": round((first_token_at - start) * 1000, 1) if first_token_at else None,"total_ms": round((time.perf_counter() - start) * 1000, 1),"tokens": tokens,"tps": round(tps, 1),}if __name__ == "__main__":payload = {"model": "local-model","messages": [{"role": "user", "content": "Explain what a KV cache is in about 200 words."}],"stream": True,"stream_options": {"include_usage": True}, # return token usage at the end of the stream}print(json.dumps(measure("http://127.0.0.1:8080", payload), ensure_ascii=False))
Notes:
- Sample repeatedly: fix the random seed, run at least 5 times, and look at P50 and P95;
- Remove interference: avoid running other GPU workloads during the test;
- Control variables: keep input length, output length, concurrency, and quantization tier identical.
If the server does not return usage fields, encode and count the output text on the client with the same rules and treat the result as an approximation.
6. Chat Template Rendering: The Most Overlooked Hidden Cost
The question “do I need to enable chat template rendering at startup?” comes up often. The short answer:
- The flag itself has no fixed meaning. Many local inference engines offer a startup option that makes the engine read the model’s own chat template; the exact name depends on the engine and version, so follow the documentation for the version you are running.
- What enabling it actually means is keeping the rendering scheme consistent with what the model was trained on.
6.1 What It Actually Does
The model never sees plain text — it sees a structured sequence containing special tokens. The engine either:
- Uses the model’s own template (usually embedded in the tokenizer configuration or the model card): rendering the message list into the format the model expects, in the order “system prompt → multi-turn dialogue → generation start marker”;
- Skips template rendering: the caller must assemble the prompt itself and pass stop conditions explicitly.
Both paths start from the same text, yet the results can be completely different:
# Illustrative code: relies on engine-internal APIs; exact APIs vary by enginefrom chat_template_renderer import render # engine-side template rendererfrom tokenizer_utils import load_tokenizertokenizer = load_tokenizer("path/to/model")messages = [{"role": "system", "content": "You are a rigorous technical assistant."},{"role": "user", "content": "What is a KV cache?"},]# Correct: let the engine render with the model's own template and append the# "assistant starts here" prompt markerprompt = render(tokenizer, messages, add_generation_prompt=True)# Wrong: manual concatenation with missing special tokens or incorrect role markers# prompt = "System: You are a rigorous technical assistant.\nUser: What is a KV cache?\nAssistant:"
6.2 Typical Symptoms of a Template Mismatch
- The model treats the question as body text and goes on rewriting or translating it;
- It answers off-topic, ignores the system prompt, or cannot tell where “user” ends and “assistant” begins;
- It continues the dialogue on its own, asking and answering its own questions;
- Formatting breaks and tool calls fail to parse.
These problems are easily misdiagnosed as “the model just isn’t smart enough”.
6.3 Troubleshooting Checklist
- Compare the token sequence the engine actually feeds the model against the rendering produced by the model’s official template;
- Confirm stop conditions are set correctly instead of relying on the model to stop “on its own”;
- Check that the tokenizer files are complete (for example the added special-token table); missing pieces can shift tokens;
- Recommended order: rule out rendering and configuration problems first, then compare model capability.
7. “Which One Is Smarter”: How to Compare Model Capabilities
Public leaderboards are a useful reference but should not be the only basis for a decision:
- Different leaderboards use different eval sets, prompt formats, and scoring scripts, so scores cannot be compared directly across them;
- Eval sets may already be part of the training data;
- Local quantization and template rendering differences significantly affect real-world scores.
Build a private test set that covers your business scenarios:
- Task types: knowledge Q&A, summarization, information extraction, code generation and explanation, multi-turn dialogue, multilingual understanding;
- Scoring method: for tasks with reference answers, score automatically by accuracy or key-field hit rate; for open-ended tasks, use multiple blind human raters or model-assisted review with a fixed review prompt;
- Experimental design: compare under the same hardware, the same quantization tier, and the same template rendering path, and record average generation speed, P95 latency, peak VRAM, and cost per question.
One caveat: quantized weights should not be compared directly against the official scores of full-precision models — they are not on the same baseline.
8. Deployment Options: Lightweight Inference Engines vs. High-Throughput Serving Frameworks
Mainstream local deployment options fall into two categories:
| Dimension | Lightweight quantized inference engine | High-throughput serving framework |
|---|---|---|
| Typical form | single-process or multi-process local service, can also be embedded in an application | standalone inference service cluster exposing an HTTP API |
| Quantization formats | broad support, covering 2-bit to 8-bit tiers | mainly GPU quantization formats; confirm they match your hardware |
| Hardware coverage | often GPU, CPU, and unified-memory devices | mainly GPU, focused on multi-GPU parallelism |
| Core optimizations | memory-mapped loading, quantized kernels | continuous batching, paged KV cache, prefix reuse, speculative decoding |
| Multimodal | usually supported | check whether the deployed version supports it |
| Best fit | individual development, offline environments, low concurrency | multiple users, higher throughput and stability requirements |
Key point: the two categories do not compete — they fit different workload profiles.
- Interactive workloads: sparse requests, low concurrency, long generation per request; the bottleneck is decode speed and VRAM capacity, so a lightweight engine is enough.
- Throughput workloads: large numbers of short requests arriving concurrently; the bottleneck is scheduling and resource utilization.
Continuous batching illustrates the difference. Traditional static batching must wait for the entire batch to complete before releasing resources, so short requests are dragged down by long ones. Continuous batching schedules dynamically at token granularity: as soon as one request finishes, a new one fills the slot, which raises both GPU utilization and overall throughput.
The pseudocode below shows the difference:
def run_static_batch(requests, model, max_new_tokens=512):"""Static batching: the whole batch can only return once the slowest request finishes."""# Say request 1 emits 20 tokens and then hits the end marker, while the others need 500.# Even though request 1 finished long ago, its KV cache and VRAM stay allocated until# the entire batch ends.outputs = model.generate_all(requests, max_new_tokens=max_new_tokens)return outputsdef run_continuous_batching(scheduler, model):"""Continuous batching: finished requests leave immediately and the waiting queue refills slots."""wait_queue = []while not wait_queue or scheduler.has_running_requests():while scheduler.can_add_request() and wait_queue:scheduler.add_request(wait_queue.pop(0)) # fill idle slotsfor req in scheduler.step(model): # advance every active request by one stepif req.is_finished():yield req.id, req.outputelse:wait_queue.append(req) # not done, wait for the next scheduling round
Selection guidelines:
- Validation phase: get the functionality working and confirm the template renders correctly; a lightweight engine is the fastest way to start;
- Multiple users or a stable QPS requirement: choose a high-throughput serving framework and give more of the VRAM budget to the KV cache and concurrent batching;
- Switching options: first check whether the model architecture, quantization format, and hardware are supported, then load-test with real business traffic and decide on P95 latency and throughput rather than the performance numbers a framework advertises;
- Hybrid mode: run the local deployment as a low-latency entry point or offline fallback, with peak traffic served from the cloud — commonly by putting a unified gateway in front of local and cloud model services.
9. Enterprise Operations: From “It Runs” to “It’s Maintainable”
Operational complexity often exceeds expectations once local inference goes live:
- Capacity planning: VRAM is not the only bottleneck — long inputs and concurrency consume KV cache space quickly;
- Observability: collect GPU utilization, VRAM usage, queue latency, throughput, and error rate;
- Log retention: requests and responses should be masked and retained in tiers, which helps both troubleshooting and auditing.
When the service is hosted in the cloud, containerize the inference service and run it on a container platform, backed by general-purpose cloud capabilities:
- Object storage: holds model weights and versions so multiple instances can pull them quickly;
- Log service: collects access and runtime logs in one place;
- Monitoring and alerting: thresholds on VRAM, latency, and error rate with automatic notification.
Cloud vendors, Baidu AI Cloud among them, offer products in these general categories. Managed model services can also serve as a reference for quality benchmarking and as elastic overflow capacity for local deployments.
10. Tuning Checklist
| Area | Check | Common issues and recommendations |
|---|---|---|
| VRAM budget | weights + multimodal components + KV cache + runtime overhead | leave 15%–20% headroom; for long contexts, compress the input rather than blindly adding VRAM |
| Quantization | whether the tier matches the hardware | prefer a 4-bit tier that balances quality and size; validate math and code tasks with business samples |
| Multimodal | resolution and image count | downscale before recognition; confirm whether multi-image cases really need every image |
| Chat template | whether the model’s own template rendering is used | verify rendering output and stop conditions at startup |
| Speed measurement | TTFT, output token count, generation speed, P95 latency | fix the seed, run 5+ times, control variables |
| Concurrency scheduling | concurrency level and batching strategy | prioritize latency for interactive workloads, throughput for throughput workloads; decide on load-test data |
| Operations | logs, monitoring, alerting | mask requests and responses; set alert thresholds on latency and error rate |
11. Conclusion
Back to the questions we started with:
- Footprint: model it as weights + multimodal components + KV cache + runtime overhead, and the answer turns from a feeling into numbers;
- Speed: decode speed is determined by weight size and memory bandwidth — measure it with TTFT and tokens/s;
- Smarter: evaluate under a unified template rendering path and a business test set;
- Options: decide between a lightweight engine and a high-throughput serving framework based on whether the workload is interactive or throughput-oriented.
Benchmark parameters and implementations keep evolving, but the methodology is stable: estimate VRAM, verify template rendering, measure speed, and evaluate quality against business samples. Get those four steps right before optimizing, and a local model goes from “it runs” to “it’s genuinely useful”.
