Skip to content

Show the MoE cache hit rate in perf output and llama-server /metrics - #259

Open
LeoBorcherding wants to merge 15 commits into
unslothai:base/pin268-38c731590from
LeoBorcherding:moe-cache-stats
Open

LeoBorcherding wants to merge 15 commits into
unslothai:base/pin268-38c731590from
LeoBorcherding:moe-cache-stats

Conversation

@LeoBorcherding

@LeoBorcherding LeoBorcherding commented Oct 10, 2026 •

Copy link
Copy Markdown

--moe-cache-mib only reports its hits and misses from its destructor, at INFO level. llama-cli shows them only with -lv 4 and a clean exit. llama-server never shows them: Ctrl-C skips the line, and there is no metric. Once Unsloth Studio passes --moe-cache-mib auto, there is no way to tell whether the cache is helping on a given machine.

MoE cache hit rate vs decode speed

The hit rate is the number that decides that. On an R9700 32 GB (gfx1201, Windows 11, HIP 7.1), with Qwen3.8-Flash-Next IQ1_M and -cmoe, at 74db68e:

cache (warm, llama-server -np 1) experts cached hit rate decode t/s
none 0% - 11.8
8000 MiB 33% 85.3% 11.9
16000 MiB 67% 94.4% 23.2

At 85% hits the cache uploaded 41.9 GB over 300 tokens and gained nothing. At 94% it doubled decode. From the outside, both runs look the same.

What this adds

  • Hits, misses and bytes uploaded in llama_perf_context_data, and the hit rate in the perf output and on llama-cli's timings line.
  • moe_cache_hits / moe_cache_misses in each server response's timings.
  • llamacpp:moe_cache_hits_total, moe_cache_misses_total and moe_cache_uploaded_bytes_total on /metrics.

Pin model and base

The prebuilt is an aged upstream b#### tag plus the pins in scripts/unsloth/pr-set.json, merged in order; each pin is upstream plus one change. This PR reads the counters of the MoE cache pin (#268), so it is stacked on it: the base branch base/pin268-38c731590 is #268's current head, and the diff here is only this PR's 14 files. In pr-set.json it has to come right after #268. If #268 is repinned with changes in these files, this branch needs another merge of #268's head (git merge --no-ff, #268's lines kept verbatim), as done for 38c731590.

Fixes on top of the original patch

  • GPU lookups were not counted. Host-weight prefetch in the scheduler, faster MoE cache prompt and decode, cache seeding under llama-server #268 does the lookups of small batches on the GPU and keeps those counts in a device tensor. The original patch only summed the host-side stats, so on CUDA and HIP /metrics and the perf data showed 0 for decode while -lv 4 showed the real hit rate. The stats now add the device counters, read after the device has finished its work.
  • Server: /metrics reads the counters only when --metrics is on; the totals survive --sleep-idle-seconds; TTS and realtime decodes refresh them too; prompt progress updates leave the counts out, so they never wait for the device.
  • Shutdown and Ctrl-C: the exit log reads the counters without synchronizing, since the backends are already freed when the cache is destroyed. While encode / decode runs, a perf read (the SIGINT handler's, for example) serves the device counts of the last read and makes no device call, so it can never synchronize a stream that is capturing a CUDA graph.
  • A new request no longer snapshots the counters when another slot is already active (the counts are shared then anyway), so it does not wait for the device either.
  • Host-weight prefetch in the scheduler, faster MoE cache prompt and decode, cache seeding under llama-server #268's exit log line is kept exactly as it is in the pin.

Evidence

Tiny MoE model (stories15M_MOE, F16), -ngl 99 -cmoe --moe-cache-mib 64, three greedy completions, then /metrics.

ROCm, gfx1151 (Radeon 8060S, Linux, HIP build from source), this branch at 3a56bdda7:

lookups /metrics hits / misses / bytes per request hits exit log, device lookups exit
on the GPU (6 layers) 2331 / 10 / 13.27 MB 768, 776, 777 hits = 2331, misses = 24 0
on the host (LLAMA_MOE_CACHE_DEVICE=0) 2331 / 10 / 13.27 MB 768, 776, 777 - 0

Same generated text both ways. The exit log counts more misses than /metrics because it also covers the warmup before the perf counters are reset.

CUDA, Colab L4, this branch at d6e67f4e2: the same numbers as on ROCm with GPU lookups on and off (2331 / 10 / 13.27 MB, same text), hits across two sleep / wake cycles 778, 778, 1557, 1557, the llama-completion perf line MoE cache hits = 98.29 % (574 / 584 experts, 12.66 MiB uploaded), and 12 Ctrl-C interrupts of llama-completion mid generation all exiting with 130 and no CUDA error.

CUDA, Colab T4, the original patch against these fixes (on the earlier #268 pin):

original patch with the fixes
/metrics with GPU lookups (hits / misses / bytes) 0 / 0 / 0 3484 / 10 / 7.05 MB
same, GPU lookups off (control) 3484 / 10 / 7.05 MB 3484 / 10 / 7.05 MB
hits across two sleep / wake cycles 0 every time 778, 778, 1556, 1556

CPU: builds; the server tests for metrics, sleep and prompt progress pass (23 tests). Pin set simulation on b13004 with this PR right after #268: merges cleanly and adds no failures (the same pins fail with and without it).

Not tested: -np > 1, multi-GPU, Metal, Windows; speed of the per-decode counter read (it only runs with --metrics).

AI disclosure from the original author: an AI assistant was used to write the patch, run the benchmarks and draft this PR; the numbers were checked against the logs.

- add MoE cache hits, misses and uploaded bytes to llama_perf_context_data, reset by llama_perf_context_reset
- print the hit rate in llama_perf_context_print and common_perf_print
- server: add llamacpp:moe_cache_* counters to /metrics and moe_cache_hits/misses to the request timings
- cli: show the hit rate next to the prompt and generation speed
…red a decode

The cache counters belong to the context, so with concurrent slots each request's delta included the other slots' lookups. /metrics keeps the totals.
…each decode

/metrics can run on the queue worker during llama_process(), which raced with the cache updating its counters.
@LeoBorcherding

Copy link
Copy Markdown
Author

Pushed 049eee313 and 66ba7fd2c.

The per-request moe_cache_hits / moe_cache_misses were deltas of counters that belong to the context, so with concurrent slots each request also counted the other slots' lookups. On a 2-slot server, two concurrent requests both reported 538 hits / 20470 misses, which was the shared total. A request now leaves the counts out of its timings if another slot decoded while it ran. A request that ran alone still reports them, and /metrics keeps the totals.

/metrics also read those counters on the queue worker while llama_process() was updating them on the main thread. The main thread now takes a snapshot after each decode and /metrics serves that.

Checked on an Apple M5 (Metal, granite-3.1-1b-a400m, --cpu-moe -nr --moe-cache-mib 200 -np 2). The solo request's counts were the same before and after the fix. The concurrent requests went from the shared total to omitted. The /metrics totals rise during a decode and agree with the per-request counts afterwards.

Codex review on the mirror is clean at 66ba7fd2c. CI is next.

@LeoBorcherding

Copy link
Copy Markdown
Author
image

…ts device lookup counters

Conflicts resolved by keeping both sides: llama_perf_context_data keeps upstream's n_reallocs_same / n_reallocs_diff and adds the MoE cache fields after them; llama-moe-cache.h keeps unslothai#268's declarations and adds llama_moe_cache_stats.
On the pinned unslothai#268 cache, ubatches of up to 32 tokens look up their experts on the device and count hits and misses in each group's state tensor, so the host-only stats reported 0 for decode. get_stats now adds them (the exit log reads the same counters). The misses help text also covers misses computed on the CPU.
…abled

The snapshot now reads the MoE cache device counters, so skip it after each decode when nothing serves it.
@danielhanchen
danielhanchen changed the base branch from base/upstream-8a1a9b512 to base/pin268-1d1e4f549 December 5, 2026 13:40
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 5, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-05T21:07:27.800019Z d6e67f4 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…ives sleep

During sleep /metrics renders the cached server_metrics only, so the separate perf snapshot read 0, and a wake creates a new context whose counters restart. The totals now live in server_metrics, with the counts of the contexts destroyed by sleep carried over.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Those slots decode on the target context outside the shared batch, so /metrics stayed stale while they ran.
…as it is

pin_contract checks that a later pin keeps every line an earlier pin adds.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…ice is done

The CUDA getter copies on another stream, so get_stats now synchronizes each device first. The server refreshes /metrics only after a synced decode, and catches up an unsynced one (a prompt chunk without outputs, e.g. before a cancel) when the slots go idle.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: a5afd7c45c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

The cache is destroyed after the context backends, so synchronizing there crashed llama-server at shutdown with device lookups on (CUDA). The context already synchronizes before it is destroyed; only get_stats waits for the devices.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: 3929fa7cd0

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Dec 5, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Dec 5, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Dec 5, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@shimmyshimmer
shimmyshimmer changed the base branch from base/pin268-1d1e4f549 to base/pin268-38c731590 December 5, 2026 17:51
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Dec 5, 2026
@unslothai unslothai deleted a comment from shimmyshimmer Dec 5, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Dec 5, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 73bda9bf39

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/llama-moe-cache.cpp Outdated
llama_moe_cache_stats llama_moe_cache::get_stats() const {
const auto & s = pimpl->stats_small;
const auto & l = pimpl->stats_large;
const auto d = pimpl->device_stats(true);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep device synchronization out of the SIGINT perf path

On Unix CUDA runs with device-side MoE cache lookups enabled, SIGINT during CUDA graph capture now reaches this synchronized read: sigint_handler() in tools/completion/completion.cpp:63-77 calls common_perf_print(), which calls llama_perf_context(). device_stats(true) then synchronizes the cache backend through ggml_backend_cuda_synchronize(). Synchronizing a capturing stream is invalid and the operation is wrapped in CUDA_CHECK, so Ctrl-C can now trigger a CUDA abort instead of reaching the handler's _exit(130) path. Collect device counters at normal synchronization points and let the signal-handler performance path read a host snapshot.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in d6e67f4: while encode / decode runs, the perf read serves the device counts of the last read and makes no device call, so a SIGINT that lands mid graph (capture included) prints from the host copy. Reads outside a decode, the server's and the final perf print, still read the device.

…runs, so a SIGINT perf print never touches the device
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: d6e67f4e2b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants