Serve a Local Model and Measure It: TTFT and Tokens per Second on CPU and GPU With llama.cpp
Put a small model behind llama-server, stream one request and stop the clock at the first real text. On a laptop: 150 ms TTFT and 88.4 tokens/s on the CPU, 25 ms and 332.5 tokens/s on the GPU, a 595-token prompt costing wait but not speed, and four users getting 2.3 times the total throughput.
What you will learn
- Move the model out of the worker into a llama.cpp server called by its base URL
- Time TTFT from a streamed response and compute decode tokens per second correctly
- Benchmark fairly: fresh server, a warm-up, five runs, the median
- Read what prompt length, the GPU and four parallel users do to the two numbers
Before you start
- The local Gemma chatbot with a Celery worker
- Streaming responses (Server-Sent Events)
In our chat app, the model lives inside the Celery worker. Every worker that wants an answer loads its own copy. This lecture takes the model out and puts it behind a server, then measures how fast it feels with two numbers: TTFT and tokens per second. The page, the route and the queue stay the same. Only what sits behind the model call changes.
The wait, then the flow
Think of a tap. You open it, and for a moment nothing comes out. That wait before the first drop is time to first token, TTFT. Then the water flows, and what matters is how fast the drops keep coming: tokens per second. A model answers the same way, a wait and then a flow, so we need both numbers.
Take the model out of the worker
A model server runs the model in its own process, loaded once. The worker sends a plain HTTP request to the chat completions address, and tokens stream back a small piece at a time. Now the worker only needs the address: the base URL tells it where to go.
The lecture uses llama.cpp with a small model. The project's README names it: Qwen2.5 0.5B Instruct as a Q4_K_M GGUF file, about 0.5 GB, with no API key. server.py builds the command:
def start(binary, model, layers_on_gpu, slots=1, context=4096, threads=8):
port = free_port()
command = [binary, "-m", model, "--alias", ALIAS,
"--host", "127.0.0.1", "--port", str(port),
"-ngl", str(layers_on_gpu), "-c", str(context),
"-np", str(slots), "-t", str(threads),
"--no-cache-prompt"]
process = subprocess.Popen(
command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
base_url = f"http://127.0.0.1:{port}"
begin = time.perf_counter()
while True:
try:
if urlopen(base_url + "/health", timeout=1).status == 200:
break
except OSError:
time.sleep(0.1)
return process, base_url, time.perf_counter() - begin
-mis the model file, and--aliasgives it a name.-nglis how many layers go on the GPU: 99 means all of them, 0 means the CPU.-cis the room for the prompt,-nphow many requests it takes at once.--no-cache-promptmakes the server read the whole prompt every time, so every TTFT we measure is an honest one.
Then it polls /health until it answers. Running server.py on the GPU, the server was ready in 1.00 s, and GPU memory went from 10 MB to 605 MB. That's the model, sitting on the GPU.
Timing TTFT from the stream
served_engine.py sends one request and reads the stream:
@dataclass
class Measurement:
text: str
prompt_tokens: int
output_tokens: int
ttft_s: float
total_s: float
@property
def decode_tps(self):
return (self.output_tokens - 1) / (self.total_s - self.ttft_s)
def measure(base_url, model, messages, max_tokens=64):
body = {"model": model, "messages": messages, "stream": True, "max_tokens": max_tokens,
"stream_options": {"include_usage": True}, "temperature": 0, "seed": 17}
request = Request(base_url + "/v1/chat/completions", data=json.dumps(body).encode(),
headers={"Content-Type": "application/json"})
pieces, usage, first = [], {}, None
start = perf_counter()
with urlopen(request, timeout=120) as response:
for raw in response:
if not raw.startswith(b"data:") or b"[DONE]" in raw:
continue
event = json.loads(raw[5:])
usage.update(event.get("usage") or {})
for choice in event["choices"]:
piece = choice["delta"].get("content") or ""
if piece.strip() and first is None:
first = perf_counter() - start
pieces.append(piece)
total = perf_counter() - start
return Measurement("".join(pieces), usage["prompt_tokens"],
usage["completion_tokens"], first, total)
The clock starts with perf_counter before sending. The first event carries only the role and no text, so piece.strip() skips it. The clock stops at the first piece with real text, here the word "Hello". In one timed run that was 14.7 ms.
For the speed, decode_tps takes only the tokens after the first. The reply had 64 tokens, so 63 come after the first; divide by the seconds after the first, and that run gave 324.6 tokens per second. Why not 64 divided by the total? Because the total includes the wait, and we want the speed of the flow on its own.
Time it fairly
def trial(label, binary, model, layers):
process, url, boot = start(binary, model, layers)
try:
measure(url, ALIAS, SHORT) # warm-up, never timed
rows = {}
used = gpu_memory_mb()
for name, messages in (("short", SHORT), ("long", LONG)):
got = [measure(url, ALIAS, messages) for _ in range(RUNS)]
# ... store prompt_tokens, ttft_ms, decode_tps ...
A fresh server for the CPU and one for the GPU. One warm-up request that's never timed, because the first request pays for loading things. Then five runs for a short prompt and five for a long one, and we keep the median. The long-prompt CPU TTFTs were 1533.9, 1907.7, 1631.7, 1492.4 and 1469.0 ms: one slow run of 1908 ms, and the median stays at 1534. One slow run can't move it.
CPU and GPU, side by side
The short prompt has 44 tokens, the long one 595. Every reply stopped at 64 tokens, so the runs are comparable. Medians of five:
| Device | Prompt | TTFT (ms) | Decode (tokens/s) |
|---|---|---|---|
| CPU | short, 44 | 150 | 88.4 |
| CPU | long, 595 | 1534 | 81.3 |
| GPU | short, 44 | 25 | 332.5 |
| GPU | long, 595 | 60 | 321.8 |
- Short prompt: 150 / 25 = 6.0, so the first token comes six times sooner on the GPU.
- Long prompt: 1534 / 60 = 25.6. The longer the prompt, the more the GPU helps the wait.
- Speed after that: 332.5 / 88.4 = 3.8 times.
- Memory: the CPU run left the GPU at 10 MB; the GPU run used 605 MB.
A longer prompt costs wait, not speed
595 tokens is 13.5 times more than 44. On the CPU the wait grew 10.2 times (1534 / 150), because the model has to read the whole prompt before it can say the first word. But the speed afterwards barely moved: 81.3 against 88.4, about 0.92 of the short one. Trim the prompt, and the first token comes sooner.
What the user feels
For a 200-token reply, reply time = TTFT + remaining tokens / tokens per second:
- CPU: 0.150 + 199 / 88.4 = 2.40 s.
- GPU: 0.025 + 199 / 332.5 = 0.62 s.
If you stream, the first word shows after 150 ms on the CPU, not after 2.4 s. The reader starts while the rest is still being written. So TTFT tells you when the reply starts, and tokens per second tells you how long it takes. For where else time goes in a request, see where time goes in an LLM request. (Streaming in a web app: SSE and WebSockets.)
Four users at once
parallel.py gives the server four slots (-np 4) and sends the same request from four threads at the same moment.
| Users | Each user (tokens/s) | All together (tokens/s) |
|---|---|---|
| 1 | 315.8 | 299.8 |
| 4 | 192.1 | 692.4 |
Each user gets a bit less, 61% of the solo speed. But together they get 2.3 times as many tokens done. That's what a serving engine is about: everyone a little slower, the machine doing more in total. Continuous batching in depth is in serving open models with vLLM.
Plug it into the app
served_engine.py also has course_generate, with the same signature as the engine the Part 12 registry already calls:
def course_generate(messages, params):
"""Same signature as the engine the Part 12 registry already calls."""
from .schemas import GenerationResult
got = measure(os.environ["LLAMA_BASE_URL"], os.environ["LLAMA_MODEL_ALIAS"], messages, params.max_new_tokens)
return GenerationResult(text=got.text, output_tokens=got.output_tokens, elapsed_seconds=got.total_s)
The registry decides how to run a model by its slug. Gemma keeps its old engine; a four-line patch adds one more slug for the small local model and sends it to course_generate. swap_check.py calls resolve then generate and gets the same kind of generation result as before. The queue, the worker and the page don't change.
llama.cpp or vLLM
vLLM is the other server you'll hear about. It's open source, wants Linux and an NVIDIA GPU (on Windows, WSL 2 or Docker), and is chosen for many users at once. It wasn't run on this PC, so there's no number for it here. The project has the one-line vllm serve command, and served_engine.py stays exactly the same: only the base URL changes.
| llama.cpp | vLLM | |
|---|---|---|
| Runs on | CPU, laptop or GPU | Linux GPU server |
| Model file | one GGUF file | Hugging Face weights |
| Best for | one user or a few | many users at once |
| Measured here | ready in about 1 s, 332.5 tokens/s on the GPU | not run |
Common mistakes
- Dividing all tokens by the total time. That mixes the wait into the speed.
- Timing the first request. Always warm up first.
- Reporting one run, or the mean. One slow run skews it. Use the median of several.
- Leaving prompt caching on. Repeat runs get a fake-fast TTFT.
Try it yourself
Run bench.py on your own machine with your own prompts and keep your numbers. Timings depend on the machine and on what else it's doing.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
When the main model goes down, the backup has to be allowed to take the data, able to read the whole request and tested before the bad day. A simulated four-model chain for an EU customer: a 6,000-token request lands on mid-eu, flagged degraded; a 10,000-token request is served by nobody, on purpose.
Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
A bulk upload buries the chat. In a small simulation, one shared queue grows to 199 waiting and the middle chat answer takes 80.2 s. A bound plus a chat lane brings it to 0.35 s while 178 bulk jobs are told to retry in 10 s, and cancelling abandoned calls saves 21,000 wasted tokens.
Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
Six GPU replicas, two at 95% and four at 30%: round robin counts requests, and requests aren't equal. In a small simulation, least outstanding requests cuts p95 from 6.52 s to 3.05 s, prefix affinity lifts cache hits to 95% but pushes p95 to 11.45 s, a real health check takes errors from 48 to 2, and draining cuts 0 answers instead of 4.
A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
A queue doesn't lose a document, but it can hand one out twice. In a small simulation, a worker crash makes document two go from 3 to 6 chunks and the index holds 11 when the documents hold 8. An idempotent consumer brings it back to 8 with the same two deliveries, and a limit of three tries moves a poison file to a dead letter queue.
