Skip to content

fix(llm): count a local call's tokens from its own usage, not /stats - #4005

Merged
kovtcharov-amd merged 1 commit into
amd:mainfrom
kovtcharov:claude/local-token-usage
Sep 19, 2026
Merged

kovtcharov-amd merged 1 commit into
amd:mainfrom
kovtcharov:claude/local-token-usage

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

Token counts for local models under-reported input by up to 16x, so local runs looked far cheaper than cloud runs doing the same work. Any token budget applied to a local run would measure the wrong thing. GAIA now counts each local call from that call's own usage, the same way it already counts cloud calls. Fixes #4003.

🔍 Technical details
  • LemonadeProvider.get_performance_stats returned the server-global /stats for local models. There, input_tokens is the uncached remainder of the last request the server handled, which can be a side call.
  • The provider already stores the call's own usage in _last_usage (feat(email): optimize the context footprint #1891) and resets it at the start of every chat(). It now returns that when present. Streaming calls leave it None and keep reading /stats, so the UI's streaming path is unchanged.

Test plan

  • pytest tests/unit/test_lemonade_cloud_models.py tests/unit/test_agent_token_usage.py tests/unit/test_turn_metrics_wire.py: 122 pass, including the new test_local_provider_prefers_the_calls_own_usage.
  • Live, flagship on Gemma-4-E4B through embedded Lemonade, one non-streaming task, compared against a log of every request. GAIA recorded 18,600 input and 821 output tokens; llama.cpp processed exactly 18,600 and 821. Before the fix, the same task recorded 11,778 input against 23,185 sent.

Local-model runs under-reported input tokens by up to 16x. For a local model
the provider read Lemonade's server-wide /stats, which counts only the
uncached part of whichever request the server served last, often a
background call rather than the agent's. The provider already captured each
non-streaming call's own usage and reset it per call; it now reports that.
Streaming calls carry no usage and still read /stats.

Fixes amd#4003.
@github-actions github-actions Bot added llm LLM backend changes tests Test changes performance Performance-critical changes labels Sep 18, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Request changes

The token-counting fix is right and the live evidence backs it up — but it takes the whole stats payload with it. The old path returned the server's full performance record; the new one returns only the four token/rate fields from the call's own usage, so time-to-first-token and cold-start model-load time silently disappear from every local, non-streaming turn.

Those are user-visible: the agent prints TTFT alongside the final answer and feeds it into per-turn metrics, and the cold-load attribution added a few releases back (a 44.5s cold query that used to report 7.6s) rides on the same field. After this change a local turn reports no TTFT at all, and the prefill-rate figure stops being computed.

The fix is small — take the accurate token counts from the call's own usage, but keep the timing fields the server reports. Details and a concrete patch are below. Worth adding a test that covers the provider→turn-metrics link too: the three test files in the test plan all feed stats dicts in directly, so none of them can see this.

Real-world evidence

N/A — no evidence bundle was produced for this run. The PR description does carry a live check on the surface that matters most here: a flagship run on Gemma-4-E4B through embedded Lemonade recorded 18,600 input / 821 output tokens against a request log showing llama.cpp processed exactly 18,600 and 821, versus 11,778 recorded against 23,185 sent before the fix. That is convincing for the token counts, and it is why the fix's core idea isn't in question.

It does not cover the timing fields the same change removes — no turn output showing TTFT before and after. The TTFT finding rests on static review, and re-running that same live task with the turn's TTFT/tok-s line captured would settle it either way.

🔍 Technical details

🔴 Timing fields dropped from local non-streaming stats (src/gaia/llm/providers/lemonade.py:532-535)

_last_usage holds only prompt_tokens, completion_tokens, total_tokens, tokens_per_second (lemonade.py:455). Returning it verbatim drops everything else /stats carried — notably time_to_first_token and model_load_seconds. Neither is reconstructible elsewhere: time_to_first_token exists only in the /stats HTTP body, and model_load_seconds is merged in client-side by LemonadeClient.get_stats (lemonade_client.py:4117).

Downstream, for a local non-streaming call:

  • _query_ttft_seconds (agent.py:545) returns None → print_final_answer(ttft_seconds=None) (agent.py:7365), so the turn prints no TTFT.
  • The fix(tui): ttft excludes cold model-load latency — a 44.5s cold query reports ttft 7.6s #2924 cold-load attribution is dead — model_load_seconds is never seen.
  • TurnMetrics.end_llm_call (turn_metrics.py:232) records ttft_s=None and skips prefill_tok_per_s.
  • AgentConsole.display_stats (console.py:1734-1745) loses its Time-to-First-Token, Input Tokens and Output Tokens rows for anything handed the raw provider stats — it keys on input_tokens/output_tokens, which _last_usage doesn't use.

Token summation itself survives: _sum_conversation_tokens (agent.py:485) and turn_metrics.py:235 already accept both spellings.

Merging is the smallest fix that keeps both properties — note it restores the /stats round-trip the PR description cites as a benefit, and the aliases are required so _sum_conversation_tokens, which prefers input_tokens, doesn't pick the stale server-global value back up:

        # A non-streaming local call carries its own usage. /stats counts only
        # the uncached part of whichever request the server served last, but it
        # is the only source of ttft and model-load timing.
        stats = dict(self._backend.get_stats() or {})
        if self._last_usage:
            stats.update(self._last_usage)
            stats["input_tokens"] = self._last_usage["prompt_tokens"]
            stats["output_tokens"] = self._last_usage["completion_tokens"]
        return stats

If avoiding the round-trip matters, the alternative is to read TTFT off the same response body — timings.prompt_ms / 1000 sits right next to the predicted_per_second already consumed at lemonade.py:459 — and pull model_load_seconds from the backend attribute directly. Either way test_local_provider_prefers_the_calls_own_usage needs its get_stats.assert_not_called() updated.

🟡 No test covers the provider→turn-metrics link

test_turn_metrics_wire.py and test_agent_token_usage.py construct stats dicts inline, so they pass regardless of what the provider actually returns — which is why this regression is invisible to the test plan. A test asserting that a local non-streaming call's stats still carry time_to_first_token (and that a cold call carries model_load_seconds) would pin both halves of the contract.

🟢 Nit — assert against a literal (tests/unit/test_lemonade_cloud_models.py:39)

assert adapter.get_performance_stats() == adapter._last_usage compares the result to the same dict the test just assigned, so it can't distinguish a copy from the live object and restates the implementation. A literal expected dict reads better and would catch an accidental key rename.

Strengths

  • The diagnosis is exact and well-evidenced: /stats reporting the uncached remainder of whichever request the server last handled is a genuinely subtle trap, and the log-vs-recorded comparison proves it rather than asserting it.
  • Reusing the _last_usage already captured for feat(email): optimize the context footprint #1891 means no new state and no extra request for the token counts.
  • The cloud branch is left untouched and the streaming path deliberately falls through, keeping the change narrow.

@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 19, 2026
Merged via the queue into amd:main with commit b46327f Sep 19, 2026
34 checks passed
kovtcharov pushed a commit to kovtcharov/gaia that referenced this pull request Sep 19, 2026
Addresses review on amd#4005: reporting only the call's own token usage had
dropped the timing fields a local turn shows and records. Both now come from
the request itself rather than from /stats, which describes whichever request
the server served last: time to first token is the response's own prefill
time (timings.prompt_ms), and a cold call carries the load time the client
measured. input_tokens/output_tokens aliases keep the console rows. A test now
covers the path from the provider to the turn's metrics and ttft.
@kovtcharov

Copy link
Copy Markdown
Contributor Author

Local turns keep their time-to-first-token and cold-start load time again, and the token counts stay correct. I took the timing from the request's own response rather than merging /stats back in. /stats describes whichever request the server served last, which is the same race this PR removes for token counts.

🔍 Technical details
  • 🔴 Timing dropped (d19eeb6):
    • time_to_first_token now comes from this response's timings.prompt_ms / 1000, llama.cpp's prefill time for the request, next to the predicted_per_second already read.
    • model_load_seconds comes from a new LemonadeClient.last_model_load_seconds property, which exposes the value the client measures around /load and resets on every call (fix(tui): ttft excludes cold model-load latency — a 44.5s cold query reports ttft 7.6s #2924).
    • input_tokens / output_tokens aliases keep display_stats and _sum_conversation_tokens reading the per-call counts.
    • Streaming calls still read /stats (no usage there).
  • 🟡 Provider-to-metrics test. test_local_timing_reaches_the_turn_metrics_and_the_turns_ttft drives a real LemonadeProvider.chat() with a llama.cpp-shaped response and checks three things:
    • the stats it returns give TurnRecorder its ttft_s, input_tokens and prefill_tok_per_s;
    • _query_ttft_seconds returns prefill plus load time for a cold call;
    • test_a_cold_local_call_carries_its_model_load_time covers the cold path on its own.
  • 🟢 Literal assertion. The provider test now asserts against a literal dict.
  • Tests:
    • pytest tests/unit/test_lemonade_cloud_models.py tests/unit/test_agent_token_usage.py tests/unit/test_turn_metrics_wire.py: 126 pass.
    • tests/test_lemonade_client.py has the same 31 failures on the merge-base: its integration tests need a Lemonade server on the default port.
  • Not re-run live: the before/after TTFT line from a live turn. This machine can't hold a local model at full context. The provider-to-metrics test covers the same path.

kovtcharov added a commit to kovtcharov/gaia that referenced this pull request Sep 19, 2026
…#4007)

CI never ran the flagship GaiaAgent, and never checked whether its code
changes work. The only agent eval is ChatAgent answering questions about
documents, scored by an LLM's opinion. This adds a CI job that gives the
flagship four real tasks: explain a file, fix a bug with a regression
test, build a weekly CSV report, and add an env-var config option.
Coding tasks are scored by what the finished project does; question
tasks are decided by the judge against the points a correct answer must
establish. Claude grades quality in one call, and the job fails on a
missed expectation for passes, quality, honesty, tokens, steps or
runtime. Every report puts main's committed results beside the current
run. It runs on GAIA's embedded Lemonade, in the same report-by-default
/ `enforce` policy as the existing categories.

The first run on current main already finds real problems. Kimi K2
passed all 4 tasks, but quality was 3.4/5: pytest was refused before it
ran, stray `.bak` files were left behind, and one answer claimed "all
tests pass" while admitting pytest never ran.

<details>
<summary>🔍 Technical details</summary>

- **`gaia eval tasks run | judge | gate`** in
`src/gaia/eval/flagship_tasks.py`. Tasks and the `core` (4) and `full`
(8) suites live in `eval/tasks/tasks.json`; the fixture project is
`eval/tasks/toybox`.
- **Isolation.** Each task gets a fresh copy of the project in a temp
dir, and the agent's `allowed_paths` is exactly that copy. `run` pops
`CLAUDE_CODE_OAUTH_TOKEN` and `ANTHROPIC_API_KEY` from its own
environment before the agent starts. In CI those credentials exist only
in the judge step.
- **Judge.** `claude -p --tools ""` in an empty temp directory, given
the original project, the answer and the diff. A task with no usable
grade is recorded as unjudged, and the gate fails its quality checks
rather than skipping them.
- **Gate.** Expectations live in
`eval/tasks/expectations/<model>.<suite>.json`, tied to model, suite and
judge model. The file holds main's measured results (overall and per
task, with commit and runner) plus the limits. The report reads `Main |
This run | Limit`. `--propose` writes that file from a run with
headroom: one task may flip, quality may drop 0.5, tokens and steps may
grow 35%, and runtime may grow 50%. Limits move only through a reviewed
commit. No file is committed yet: the first runner run's artifact
carries the proposal.
- **Excluded tasks.** Six of the bench's 14 tasks are left out. Five
need a GitHub token inside the agent's environment, and the
shell-injection task relies on Unix shell behaviour that the Windows
runner lacks.
- **Workflow.** A new `flagship-tasks` job sits before `agent-eval`, so
it doesn't overlap amd#4001's hunks. It adds a `task_suite` dispatch input
and triggers on `eval/tasks/**`. The artifact is the scorecard plus
proposed expectations, scanned for credentials, kept 14 days. Every
`run:` body is pure ASCII.
- **Local token counts.** Gemma under-reports tokens until amd#4005 lands.
Capture expectations after it, or the token limits will be about 2-16x
too low.
</details>

## Test plan

- [x] `pytest tests/unit/eval/test_flagship_tasks.py`: 67 pass (plus the
opt-in live judge check, which passes: 10/10 verdicts in one call). Each
coding task fails on the untouched project and passes a reference
solution. Credentials never reach the agent. The judge gets no tools.
Every gate metric can fail on its own. Report vs. enforce exit codes are
covered.
- [x] `pytest tests/unit/eval tests/unit/test_cli*.py
tests/unit/test_eval*.py`: 725 pass. The 1 failure is the macOS
`python`-not-on-PATH case (amd#3981), identical on main.
- [x] End to end on Kimi K2 via Lemonade: `run` passed 4/4 in 190 s,
`judge` graded all 4, `gate` without expectations reported and exited 0,
and `--propose` followed by `gate --enforce` against that proposal
exited 0.
- [x] `pylint`, `black`, `isort`, `flake8` on the new code;
`util/check_doc_links.py` passes; the workflow YAML parses and every
`run:` body is ASCII.
- [ ] First run on the Strix Halo runner (needs a same-repo branch,
since fork PRs skip it). Check that the embedded Lemonade starts with
`llamacpp:vulkan`, all 4 tasks run, and the artifact holds
`scorecard.json` and `proposed-expectations.json`.
- [ ] Commit that proposal as
`eval/tasks/expectations/Gemma-4-E4B-it-GGUF.core.json` (after amd#4005) to
switch the gate on.

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

llm LLM backend changes performance Performance-critical changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Local-model token counts leave out cache-reused tokens, so input reads ~16x low

2 participants