Running a 27B LLM Locally: Inference Speed Benchmarks and an Optimization Guide
When you run a 27B-class dense model on a single flagship consumer GPU with 4-bit weights, an FP8 KV cache, multi-token prediction, and a context window stretched to around 180K, single-request decode speed lands in the 120–150 tokens/s range. But that number is only meaningful once you understand what produces it. This article clarifies why "tokens/s" is not a single metric, explains the memory-bandwidth ceiling that governs decode speed, walks through the trade-offs of 4-bit quantization, breaks down the memory, compute, and quality costs of long context, examines the often-underestimated prefill cost of multimodal input, and provides a reproducible measurement script plus a prioritized optimization checklist. By fixing variables, recording data, and aligning tests with real workloads, you can turn "it feels fast" into reliable, business-relevant performance numbers.
In the local LLM community, “how many tokens/s does your such-and-such model run?” is an evergreen question. Even with similar hardware and model versions, reported speeds can differ several-fold. The reason isn’t voodoo: inference performance has clear, quantifiable drivers.
Consider a configuration common in the community: a 27B-class dense model, a single flagship consumer GPU, 4-bit weight quantization, a context window opened to around 180K, with multi-token prediction (MTP) and visual input enabled. Measured decode speed for this setup falls in the 120–150 tokens/s range, roughly in line with the reference figures published by inference-engine authors. This article isn’t trying to crown any single number as the answer. It wants to address three more useful questions:
- How is that speed actually calculated?
- What makes it move up or down?
- How do you decide whether it fits your workload?
1. Aligning definitions first: tokens/s is not one metric
Before discussing speed, you have to agree on how it’s measured. On the same model and the same machine, reported numbers can differ by more than 2x, usually because the following metrics get conflated:
| Metric | Meaning | Main determinants | Impact on experience |
|---|---|---|---|
| Time to first token (TTFT) | Time from sending a request to receiving the first token | Input length, number and resolution of images, prefill compute | Determines “how long you wait after hitting Enter” |
| Decode speed | Tokens generated per second after the first token | Memory bandwidth for reading weights and KV cache, decoding strategy | Determines “how fast the text streams out” |
| End-to-end speed | Total output tokens ÷ total elapsed time | A combination of the two above | Determines when the full reply finishes |
| Aggregate concurrent throughput | Total tokens processed per second at a given concurrency | Batch scheduling, VRAM capacity | Determines “how many users one machine can serve” |
Take a 2,000-word answer, assuming 4,000 output tokens:
- If the first token takes 1 second and decode then runs at 130 tokens/s, total time is about 31.8 seconds, and end-to-end speed is about 126 tokens/s.
- If the first token takes 8 seconds, end-to-end speed drops to about 111 tokens/s.
The longer the input and the more images involved, the wider the gap between the two. So when you see “this model runs at X tokens/s,” the first things to ask are “how many input and output tokens, and is this a single request or multiple concurrent requests?” This article assumes single-request decode speed by default.
2. The physical ceiling on decode speed: start with memory bandwidth
2.1 Decoding is about moving data, not computing
When a Transformer generates tokens one at a time, every token requires a full forward pass. The operators here are dominated by matrix-vector multiplication: the compute is small, but you must read nearly all of the model weights. If single-GPU memory bandwidth is B (bytes/s) and each step must read M bytes, then the ideal decode-speed ceiling is:
Decode speed ceiling ≈ B / MM ≈ weight bytes + current-context KV cache bytes + other overhead
On common consumer GPUs (memory bandwidth around 1–2 TB/s), the decode phase is generally memory-bandwidth-bound, not compute-bound. One intuitive corollary: as long as capacity allows, increasing a GPU’s memory bandwidth usually improves decode speed more than increasing its floating-point compute.
2.2 A rough-grained VRAM “bill”
The estimates below are illustrative, meant only to convey the order of magnitude; actual values depend on the specific model architecture and engine implementation:
| Item | Estimate | Notes |
|---|---|---|
| Weights (4-bit, including scale factors and other metadata) | ~0.50–0.60 bytes/parameter, ~14–16 GB for 27B | A major cost |
| KV cache (bf16) | ~2 × layers × KV heads × head dim × 2 bytes, ~0.5 KB per layer per token | Grows linearly with context |
| KV cache (FP8) | ~0.25 KB | Especially important with very long context |
| Multimodal vision encoder | Several GB | A secondary cost compared to the text LLM |
Using the bandwidth-ceiling formula above, consider two cases:
- Short context, bf16 KV cache: M is about 15 GB, giving a theoretical ceiling of about 120 tokens/s (assuming 1.8 TB/s bandwidth).
- 180K context, FP8 KV cache: M is about 20 GB, giving a theoretical ceiling of about 90 tokens/s.
Real throughput is usually only 70%–90% of the peak, so single-request 120–150 tokens/s is closer to what you see with shorter contexts; long-context scenarios that approach the ceiling typically reach only about half that. This matches intuition: the longer the context, the more KV cache each step must read, and the slower it goes.
2.3 Why multi-token prediction can break the “normal” ceiling
The formula describes the ceiling for decoding one token at a time in sequence. MTP lets the model predict several upcoming tokens in a single forward pass, then has the main model verify them and accept the parts it deems valid. One forward pass reads the weights once but can emit multiple tokens, so effective speed can exceed the one-token-at-a-time ceiling.
There are three main costs:
- Compute per decode step increases;
- Rejected draft tokens are wasted computation;
- When requests vary widely in length, batching is more prone to imbalance and idle waiting.
The speedup can be roughly estimated as:
Speedup ≈ average acceptance length / (1 + draft overhead ratio)
Average acceptance length is the mean number of tokens accepted per verification round. With an acceptance rate of α and up to k draft tokens per round, average acceptance length = (1 - α^(k+1)) / (1 - α).
You can back this figure out directly from throughput data: with MTP off, short context runs at about 120 tokens/s; with it on, it reaches 145 tokens/s. Under the 1.8 TB/s bandwidth assumption, the average acceptance length is about 145/120 × (1 + 15/120) ≈ 1.36 tokens. With that number in hand, you’re in a position to compare MTP configurations across different draft lengths and tasks.
2.4 Judging the credibility of a single measurement
Running a 27B-class 4-bit model with an 180K context at 120–150 tokens/s on a single GPU with limited compute and no way to shard across devices falls within the range of commonly published reference data. Hitting this level on a single card usually means a few things are already being done right:
- Weights are read at close to the theoretical peak bandwidth utilization;
- The KV cache isn’t constantly shuttling between VRAM and system memory;
- VRAM isn’t near exhaustion, avoiding fragmentation-driven allocation failures and retries.
From a cost-benefit standpoint, this is also a sensible sweet spot for a consumer single GPU: adding more VRAM mainly buys longer context and higher concurrency, not a noticeable single-request speedup.
3. Quantization: the capability and the cost of 4-bit
3.1 Quantization changes more than “size”
| Scheme | Weight read per step (27B-class) | Decode speed impact | Quality risk | Typical issues |
|---|---|---|---|---|
| bf16 (16-bit) | ~54 GB | Doesn’t fit on one GPU; needs multiple GPUs or machines | Lowest | VRAM cost, cross-device communication |
| 8-bit | ~27 GB | Barely fits on one GPU; KV cache space is squeezed | Very low | Limited long context |
| 4-bit | ~14–16 GB | Comfortable on one GPU | Low–medium, depends on calibration | Repetition or degradation on long outputs |
Note that the KV cache also consumes bandwidth. If weights are 4-bit but the KV cache stays bf16, the KV cache becomes the main bottleneck at long context, and the speedup from low-bit weights is largely cancelled out. So for long-context scenarios, plan weights and KV cache together.
3.2 Compute precision and storage precision are not the same thing
If you compute in 16-bit but store in 4-bit (that is, “low-bit storage, higher-precision compute”), inference has to dequantize the weights on-chip. The extra reads and computation from dequantization erode 4-bit’s theoretical gains. As a result:
- 4-bit’s speed advantage is most pronounced at low batch sizes during the long decode phase;
- In the high-concurrency prefill phase, where compute is the main bottleneck, the benefit shrinks.
Choosing a quantization scheme is essentially a trade-off among VRAM capacity, speed, and quality:
- First fix the target context length and concurrency scale, then work backward to a VRAM budget;
- Within that budget, prioritize KV cache precision, and only consider more aggressive quantization if necessary;
- For fine-tuned models, the calibration dataset should stay as close as possible to the real task distribution.
3.3 Quality validation for long chain-of-thought scenarios
In the output of these reasoning-oriented models, the reasoning process often takes up a large portion of the text. 4-bit quantization may show almost no difference on short answers, but across thousands of tokens in a long output, errors accumulate step by step. Occasional repetition, loops, or logical jumps come from here.
Judging whether it’s usable can’t rely on “feel” alone. It’s worth building a small but discriminating test set:
- Multi-step math and logic problems;
- Long-document information extraction;
- Code generation and repair;
- Visual question answering.
Compare the quantized and full-precision versions under identical decoding parameters, focusing on three things: answer accuracy, the proportion of degenerate repetition, and average output length. Among these, a sudden jump in average output length is often an early warning of quality degradation. The differences between quantization schemes are often larger than the difference between “quantized and full precision.” Community versions built by further fine-tuning open-weight models are often entirely adequate once quantized, and satisfying in many scenarios, but only after the validation above.
4. An 180K context: the three bills of long context
4.1 The VRAM bill: KV cache grows linearly with length
Suppose a 27B-class model uses grouped-query attention (GQA) with 40 layers, 4 KV heads, and a head dimension of 128. The KV cache per layer per token is:
2 (K and V) × 4 (KV heads) × 128 (head dim) × 2 bytes (bf16) = 2048 bytes = 2 KB
Across the whole model, that’s 80 KB per token, which maps to the following context lengths:
| Context length | bf16 | FP8 | 4-bit |
|---|---|---|---|
| 8K | 0.65 GB | 0.33 GB | 0.16 GB |
| 32K | 2.6 GB | 1.3 GB | 0.65 GB |
| 128K | 10.5 GB | 5.2 GB | 2.6 GB |
| 180K | 14.4 GB | 7.2 GB | 3.6 GB |
(Using 1 GB = 10⁹ bytes.)
These numbers make two things clear:
- Without optimizing KV cache precision, an 180K context needs more than 14 GB just for the KV cache. Add 4-bit weights and a 32 GB GPU has almost no headroom left, before stacking on the vision encoder and the inference engine’s own overhead.
- Switching to an FP8 KV cache frees up about 7 GB, but that saving comes at the cost of some long-context precision loss. Whether it’s worth it depends on your workload’s requirements for long-document retrieval and reasoning accuracy.
In addition, inference engines reserve VRAM as a KV cache pool; when capacity runs short, they can only truncate or reject requests. So “context opened to 180K” and “stable service at an 180K context” are two different things.
4.2 The compute bill: attention cost and prefill latency
The KV cache brings two kinds of overhead:
- Decode phase: every new token must attend over all historical KV, and the cost grows linearly with context length. In the estimate above, speed at 180K drops about 30% versus short context, mostly because of this.
- Prefill phase: attention computation grows quadratically with sequence length. When a document of tens of thousands of tokens is first submitted, TTFT can jump from sub-second to several seconds or even tens of seconds, which feels like “the model is stuck.”
Mitigations include:
- Chunked prefill: split a long prefill into small chunks and interleave them with requests that are already decoding, so a long input doesn’t “block” other users’ output;
- Prefix caching: keep the KV cache of repeated prefixes such as system prompts and long documents, and reuse it directly for later requests. TTFT for requests sharing a prefix can drop significantly.
- Reasonably control image resolution and the number of tiles, to avoid uncontrolled growth of visual tokens.
4.3 The quality bill: nominal length is not effective length
A context window rated at 180K doesn’t mean the model reliably uses information across the entire 180K range. The industry widely observes the “lost in the middle” phenomenon: when key information sits in the middle of a long context, recall is markedly lower than at the beginning or end.
A low-cost way to verify this is a “needle in a haystack” test:
- Build a filler text of tens of thousands to over a hundred thousand tokens;
- Insert one distinctive fact at a random position, for example “the passphrase is blue-whale-7342”;
- Ask questions targeting the beginning, middle, and end positions, and measure recall;
- Layer on multi-hop questions, such as “what is the population of the city the passphrase refers to,” to test whether the model can reason by combining information from multiple places.
It’s also worth limiting the actual input length through parameter caps or application-layer validation, to minimize the risk of uncontrolled truncation.
5. Multimodal: the underestimated prefill burden
Once you enable vision, a single input image is usually encoded into a large number of visual tokens that enter the context alongside text tokens. The larger the image and the more tiles, the more visual tokens, which directly affects:
- TTFT: multiple images or high-resolution input can make prefill substantially longer;
- Context budget: visual tokens share the same context window as text, and a few large images can consume tens of thousands of tokens;
- VRAM usage: the vision encoder stays resident in VRAM, competing with the main model for space.
Practical advice:
- For document images, compress them first to the “smallest readable resolution” to avoid pointless detail bloat;
- For batch image processing, prefer reusing a shared prefix cache and control concurrency;
- For video and long-document scenarios, extract text first via OCR or layout analysis before feeding it to the model; this is often faster and cheaper than sending the raw images.
6. Turning “it feels fast” into reproducible data
6.1 Measurement principles
- Fix variables: keep model version, quantization scheme, context length, decoding parameters, batch size, and KV cache precision constant, and change only one factor at a time.
- Warm up first: the first request often includes one-time costs like graph construction and kernel loading, so discard warm-up samples.
- Take the median over multiple samples: repeat at least 3–5 times, and report both the median and the range of variation.
- Record separately: TTFT, decode speed, and end-to-end speed; don’t substitute an end-to-end number for decode speed.
6.2 A ready-to-use benchmarking script
The script below depends only on the Python standard library and issues a streaming request to an OpenAI-protocol-compatible local inference service. On connect, it disables buffering and enables TCP_NODELAY to reduce timing bias from chunked transfer:
import jsonimport socketimport timeimport urllib.request# Local inference service endpoint; fill in according to your deploymentURL = "http://127.0.0.1:8000/v1/chat/completions"def _connect_without_buffering(url):"""Open a connection with buffering disabled and TCP_NODELAY enabled,to reduce timing bias caused by chunked transfer"""host, port = url.netloc.split(":")sock = socket.create_connection((host, int(port)))sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)return http.client.HTTPConnection(host, int(port), timeout=600), sockdef stream_generate(prompt, max_tokens=512):"""Stream text generation; yields each incremental content chunk"""body = {"messages": [{"role": "user", "content": prompt}],"max_tokens": max_tokens,"stream": True,}conn, sock = _connect_without_buffering(urlparse(URL))try:conn.request("POST", urlparse(URL).path or "/",body=json.dumps(body),headers={"Content-Type": "application/json"})resp = conn.getresponse()buf = b""while True:chunk = resp.read(64) # small reads, to stay close to real arrival timesif not chunk:breakbuf += chunkwhile b"\n" in buf:line, buf = buf.split(b"\n", 1)line = line.strip()if not line.startswith(b"data:"):continuedata = line[5:].strip()if data == b"[DONE]":returntry:obj = json.loads(data)delta = obj["choices"][0]["delta"].get("content", "")if delta:yield deltaexcept (KeyError, IndexError, json.JSONDecodeError):continue # ignore heartbeat, comment, and other non-data linesfinally:conn.close()sock.close()def measure(prompt, max_tokens=512):t0 = time.perf_counter()ttft, count, chars = None, 0, 0for piece in stream_generate(prompt, max_tokens):if ttft is None:ttft = time.perf_counter() - t0count += 1chars += len(piece)total = time.perf_counter() - t0return {"ttft_s": round(ttft, 3),"chunks": count,"chars": chars,"decode_chunks_per_s": round((count - 1) / (total - ttft), 1),"e2e_chunks_per_s": round(count / total, 1),"note": "Some streaming interfaces slice by character; token counts must be rechecked with the real tokenizer",}if __name__ == "__main__":print(measure("Please explain step by step: why does LLM decoding slow down under long context?", 512))
This script reports both TTFT and decode-phase throughput, and it makes one thing explicit: the chunking of a streaming interface doesn’t necessarily match real tokenization, so when you need strict token counts, re-count the complete output with the model’s own tokenizer.
6.3 A performance log
It’s worth keeping a table like this for each configuration:
| Scenario | Input/output tokens | TTFT | Decode speed | End-to-end speed | Notes |
|---|---|---|---|---|---|
| Short Q&A | ~100 / ~500 | TBD | TBD | TBD | Baseline scenario |
| Long-document summarization | ~60000 / ~1000 | TBD | TBD | TBD | Prefix cache on/off comparison |
| Multi-image VQA | ~30000 / ~800 | TBD | TBD | TBD | Different-resolution comparison |
| High concurrency (e.g., 16-way) | ~500 / ~500 | TBD | TBD | TBD | Observe throughput and tail latency |
With this table, every adjustment to the quantization scheme, KV cache precision, or MTP parameters has a concrete basis for comparison.
7. Optimization checklist: from “it runs” to “it runs well”
Ordered by return on investment:
First priority (low cost, high payoff)
- Quantization: 4-bit weights are the prerequisite for running a 27B-class model on a single GPU; pair them with an FP8 KV cache to free up long-context space.
- Context configured on demand: set the engine’s KV cache pool to your actual workload length, and avoid reserving VRAM for an 180K context you’ll never use.
- Decoding parameters: set temperature and repetition penalty sensibly. Too strong a repetition penalty breaks normal reasoning; too weak, and long outputs tend to loop.
Second priority (needs engine feature support)
- Prefix caching: keep fixed system prompts, long documents, and knowledge-base snippets at the front and keep them consistent, to maximize reuse.
- Chunked prefill: under mixed workloads, prevent long inputs from slowing down every request that’s currently decoding.
- Streaming output: start displaying as soon as the first token arrives; perceived latency drops sharply.
Third priority (needs trade-offs and tuning)
- Multi-token prediction: tune draft length to the acceptance rate of your actual tasks. Structured output usually has a higher acceptance rate; creative writing fluctuates more, and the payoff may be limited.
- Concurrency and batch size: faster single requests don’t automatically mean a better overall system. Raising concurrency lifts aggregate throughput but lowers single-request decode speed, so cap it according to your latency requirements.
- Precision trade-offs: dropping the KV cache to 4-bit allows longer context, but you’ll need to re-run long-context quality tests.
8. A few common misconceptions
- Treating “high throughput” as “good experience”: chat scenarios care more about TTFT and streaming fluency; batch offline processing cares more about aggregate throughput. The two optimization directions aren’t the same.
- Treating the “context window” as “usable context”: the larger the window, the more it tests KV cache precision, VRAM, and quality degradation. Rather than piling on length, invest in good retrieval and chunking.
- Treating “subjective feeling” as “a conclusion”: it’s common, and genuinely felt, to think “this feels smarter than some general-purpose cloud models,” but that’s heavily influenced by task type, prompt, and decoding parameters, and different models each have their strengths. To reach a reliable conclusion, run blind comparisons on your own workload data instead of relying on a single experience.
- Ignoring stability: under sustained high load, watch for VRAM fragmentation, request timeouts, and tail latency. A service with a great average throughput but individual requests that take minutes to respond is hard to put into production.
9. Local deployment versus cloud calls
The core value of local deployment lies in keeping data inside your network, controlling long-term cost, and allowing deep customization per workload. The limitations are equally clear:
- VRAM capacity determines the ceiling on context and concurrency;
- Quantization and tuning require ongoing engineering investment;
- You have to track model iterations yourself.
Managed cloud services spare you operations and hardware investment and offer better elasticity, making them well suited to spiky workloads or rapid validation. The two aren’t mutually exclusive: routing sensitive core data through local deployment and peak traffic and complex tasks through the cloud is a common combination for many teams.
If you want a near-local experience in a compliance-controlled cloud environment, Baidu AI Cloud’s Qianfan platform offers end-to-end capabilities for model development, training, deployment, and invocation, and can be evaluated as one of the cloud options.
Closing
Back to the original question: “how many tokens/s can a 27B-class model run?”
The answer: on a single 32 GB-class GPU with 4-bit quantization, an FP8 KV cache, and multi-token prediction enabled, single-request decode speed at short context usually reaches around 120 tokens/s, close to the physical ceiling set by memory bandwidth; at an 180K context, it declines somewhat because of the KV cache read overhead. More important than the number is understanding what determines it:
- Memory bandwidth sets the ceiling;
- Quantization determines whether you can even get in the door;
- The KV cache and context length determine where you actually land;
- Multi-token prediction determines whether you can break the normal ceiling;
- And the measurement methodology determines whether the number you’re looking at is real or not.
Fix the variables, record the data, and aim your tests at your actual workload, and local LLMs can genuinely move from “it runs” to “it works well.”
