Where Did My Tokens Go?

Where Did My Tokens Go?

Table of Contents

TL;DR

I run local models on a 2017 Radeon RX 580 with llama.cpp behind llama-swap. Scraping each llama-server’s /metrics lost data: llama-swap kills the process when it swaps models, and the counters die with it.

The fix was reading llama-swap’s per-request activity log and pushing OpenTelemetry GenAI semconv histograms instead. Now I’m working on making that native in llama-swap (issue #1320, PR #1321).

I sent four requests to my local LLM, and Dash0 said it had served zero tokens.

The model had answered all four, but the metrics just weren’t there. And the problem wasn’t my dashboard, my query or the collector: it was the way I was collecting them.

Info

This is the second post of a three-part series. The first one covers how the rest of my homelab is observed, and the next one uses everything here to tune the LLM. Full disclosure: I work at Dash0, and this lab is where I play with it outside of work.

A GPU from 2017 in a Kubernetes cluster

Remember the GPU I bought pretending I was going to play games? It’s a Sapphire Radeon RX 580 with 8 GB of VRAM, and it’s now passed through to one of the k3s VMs. Polaris cards don’t get ROCm, so llama.cpp runs on its Vulkan backend, which works surprisingly well.

In front of it sits llama-swap, which I love for its simplicity. It exposes one OpenAI-compatible endpoint and starts the right llama-server process for whichever model a request asks for. Two small models stay loaded together, and asking for the bigger one swaps them out. That swapping is the whole story of this post.

First try: scraping /metrics

llama-server exposes Prometheus metrics (tokens processed, tokens generated, requests in flight), so the first version was the obvious one: an OpenTelemetry Collector sidecar in the same pod scraped each llama-server every 15 seconds and renamed things toward OpenTelemetry conventions on the way out.

It looked great. I sent a request to the bigger model, the counter went up by exactly the number of tokens I expected, and I moved on. Then I sent four quick requests, in about 15 seconds, to a model that was about to be swapped out, and Dash0 showed zero.

Dash0 chart of scraped output-token counters: qwen3-4b appears as one point at zero, qwen3-8b resets to zero and jumps to 181
qwen3-4b shows up for a single scrape, at zero, and is gone

Look at the chart closely and it tells the whole story: the qwen3-4b series exists for exactly one sample, reading zero, and then it’s gone, while qwen3-8b’s counter drops to zero too, because swapping it back in started a brand new process.

Counters die with their process

Once you see it, it’s obvious: a Prometheus counter lives inside the process that exposes it. When llama-swap swaps models, it stops that llama-server process, and every increment since the last scrape goes with it. Scraping is sampling: if the process doesn’t survive until the next sample, those requests never happened, as far as your metrics know.

A shorter scrape interval only makes that window smaller, but it doesn’t close it.

There was also a second, quieter problem. Counters are cumulative totals, while the OpenTelemetry GenAI semantic conventions define per-request histograms: tokens per request, request duration, time per output token. You can’t rebuild a distribution of individual requests from a running total.

So I needed a source that knows about every request and outlives the processes that serve them.


Reading llama-swap’s activity log

llama-swap already had it. It keeps one record per request, with the model, the token counts, the timings llama-server reports and the duration, and that record lives in llama-swap itself, which runs as long as the pod does. It’s available over HTTP at /api/metrics/activity.

My first instinct was to read it with the collector, because I use the collector wherever I can, but I couldn’t. There’s no generic “poll a JSON URL” receiver, and although llama-swap can also write the records to SQLite, sqlqueryreceiver has no SQLite driver. Parsing llama-server’s free-text log lines would be fragile too, since the lines don’t even name the model. I wrote that reasoning down as a decision record in the repo, including what would make me revisit it.

So it’s a small, stdlib-only Python sidecar that runs from the llama-swap image itself, reads the activity log every 10 seconds and pushes histograms over OTLP/HTTP to the cluster’s collector. Here’s the core of it:

def _record(self, row: dict[str, Any]) -> None:
    attrs = {
        "gen_ai.operation.name": row.get("task") or "chat",
        "gen_ai.provider.name": "llama.cpp",
        "gen_ai.request.model": row["model"],
    }
    status = row.get("resp_status_code", 0)
    duration_attrs = attrs | ({"error.type": str(status)} if status >= 400 else {})
    self._observe("gen_ai.server.request.duration", duration_attrs, row["duration_ms"] / 1000)

    tokens = row.get("tokens") or {}
    for kind in ("input", "output"):
        count = tokens.get(f"{kind}_tokens", -1)
        if count >= 0:  # -1 means llama-swap didn't know
            self._observe("gen_ai.client.token.usage", attrs | {"gen_ai.token.type": kind}, count)
    if tokens.get("tokens_per_second", 0) > 0:
        self._observe("gen_ai.server.time_per_output_token", attrs, 1 / tokens["tokens_per_second"])

Let’s break down this code. Every activity record becomes one observation in each histogram, labeled with the model and the attributes the conventions define, and errors get error.type, the way the semconv expects. The histograms are cumulative, so if a push fails nothing is lost, because the next one carries the totals, and a cursor makes sure a record is never counted twice, even across restarts.

That tokens_per_second is the generation rate llama-server itself reports, so time per output token measures generation only, without mixing in the prompt. And yes, gen_ai.client.token.usage is a client metric in the conventions, but llama-swap is the closest thing to a client I can observe, and I’d rather bend that a little than invent a new name.

The GPU, alerts and logs

With the hard part solved, the rest was much easier.

The GPU

The same sidecar reads amdgpu’s sysfs and sends hw.gpu.utilization, hw.gpu.memory.usage, hw.power and hw.temperature, from the hardware semantic conventions, and having the GPU next to the requests paid off quickly. After one reboot, the time per output token in Dash0 went from 19 ms to over 340 ms, averaged over two hours, which means going from around 53 tokens per second to a fraction of it.

Dash0 chart of gen_ai.server.time_per_output_token rising from about 20 ms to over 340 ms on November 9 and falling back
Time per output token as a 2-hour rolling mean, so it lags: the fix went in around 11:00

The cause was amdgpu’s runtime power management suspending the card while llama-server held it open. It’s fixed now, and right after fixing it I added alerts.

Alerts

Like everything else in the lab, they’re Prometheus Operator PrometheusRule resources in git: generation slower than a threshold per token, 5xx responses, the GPU above 80 or 88 °C, and GPU metrics going missing. The query for the first one is plain PromQL over the semconv histogram:

histogram_quantile(0.5, sum by (gen_ai_request_model) (rate({otel_metric_name="gen_ai.server.time_per_output_token"}[10m])))

Logs

llama-server can log JSON lines with --log-jsonl. llama-swap has no JSON option, so a tiny Python filter wraps its stdout and turns lines like [INFO] <model> msg into JSON, with gen_ai.request.model when the line names one. It’s not glamorous, but every log line in that pod is now structured.

Making it native

A sidecar that polls an API and hand-builds OTLP JSON works, but it’s a workaround. The right place for this is llama-swap itself: it knows about every request the moment it finishes, so it can record GenAI metrics with no polling and no cursor.

So I opened issue #1320 proposing native OpenTelemetry metrics and traces using the GenAI conventions, and PR #1321, which exports the GenAI semconv metrics over OTLP. Both are still open as I write this, and when they land, my decision record already says what happens: the GenAI part of the sidecar gets deleted.

Conclusion

Counters die with their process, and it’s one of those things everyone knows and nobody thinks about until the process is the thing being swapped in and out. For workloads like llama-swap, where processes are disposable by design, the source of truth has to be something that outlives them, and per-request records mapped onto the GenAI semantic conventions turned out to be a much better fit than scraping ever was.

In my view, this is also a good argument for semantic conventions. Because the metrics use standard names, I could write the dashboards and alerts against them, and propose the same names upstream without inventing anything new. In the next post I’ll use these exact metrics to tune this GPU, before and after. If you’re running local models and want to compare notes, reach out on LinkedIn. 🚀

Share:

Related Posts

Observability strategies to not overload engineering teams – eBPF.

Observability strategies to not overload engineering teams – eBPF.

eBPF is a powerful technology since it allows you to inject custom user-definition programs in the kernel without having to install additional kernel modules or recompile the kernel itself.

Read More
Balancing Act: Cutting Kubernetes Event Storage Costs Without Losing Visibility with OpenTelemetry

Balancing Act: Cutting Kubernetes Event Storage Costs Without Losing Visibility with OpenTelemetry

A few weeks ago I wrote a blog post about efficient Kubernetes event tracking. In that blog post I explained how you can collect Kubernetes events using OpenTelemetry, and I also explained why I think OpenTelemetry is a great solution for Kubernetes event collection.

Read More
Observing My Homelab Like It's Production

Observing My Homelab Like It's Production

Like any good nerd engineer, I have a homelab 🤓 It’s a 2017 machine, a Ryzen 5 2600 with 48 GB of RAM and a Radeon RX 580, that I bought pretending I was going to play games on it. Silly boy. Spoiler: it barely saw a game. Today it runs a three-node Kubernetes cluster, and that GPU spends its days running an LLM instead of rendering frames.

Read More