Skip to content

[rl] Log KV cache occupancy and usage on each completion - #6291

Draft
felipemello1 wants to merge 1 commit into
felipemello1/session-kv-evictorfrom
felipemello1/kv-cache-metrics
Draft

felipemello1 wants to merge 1 commit into
felipemello1/session-kv-evictorfrom
felipemello1/kv-cache-metrics

Conversation

@felipemello1

@felipemello1 felipemello1 commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Agent details

Stacked on the PR that evicts ended rollouts' KV from vLLM's prefix cache; review that first.

TLDR: Two new per-completion metrics, generator/kv_cache_occupancy and generator/kv_cache_usage, show how full the KV cache is. The console shows generator/kv_cache_occupancy/max. vLLM's own usage counts every cached free block as free, so a cache full of waiting rollouts' history reads low. Source +94 / -13.

Example: a pool of 200 blocks. Running requests use 50, and 90 hold live rollouts' cached history. 60 are free.
    usage     = 50 / 200        = 0.25
    occupancy = (50 + 90) / 200 = 0.70

How

  1. occupancy = 1 - (free blocks without a hash) / (usable blocks). The PR below evicts ended rollouts' blocks, so every cached free block is one a live rollout may reuse.
  2. TP rank 0 stamps the reading on each finished request. It re-reads at most once per second, because the read walks the free queue (about 4 ms over 60K free blocks).
  3. Every completion in a one-second window carries the same reading, so /mean weighs readings by completions, not by time. The console shows /max.
  4. Validation completions log them as validation_generator/kv_cache_*.

Results

  • Each occupancy read equals an independent count from vLLM's block list, taken at the same moment: 139 of 139 reads (max gap 0.0). Each completion's logged kv_cache_occupancy equals one of those reads.
  • Same harness run as the PR below: multi-turn Qwen3.5-4B, 358 blocks of 640 tokens, 1 GB300. It ran at an earlier head of this PR, with the same read and throttle. The read costs 21 ms per 263 s cell. The evictor and the reads together take 0.08% of engine step time; about 0.04% of that is the harness's own timers (the main cell, whose evictor methods do nothing, reads 0.04%).

Known issues

  • Hybrid models (Qwen3.5): vLLM caches a Mamba state at every block boundary. A waiting rollout's cached blocks average 1.6-2.1x its next turn's need (the earlier revision's runs), so occupancy reads high (TODO at the read).
  • SGLang engines don't read the KV cache, so SGLang runs have no kv_cache_* keys (noted on RequestMetricsInputs.kv_cache_reading).

Test plan

pytest tests/rl/unit_tests/cpu/test_session_kv_evictor.py -k occupancy   # 1
pytest tests/rl/unit_tests/cpu/test_generator.py -k "stamps or resolves_reply"   # 2
pytest tests/rl/unit_tests/cpu   # 692 passed, 7 skipped (6 need `verifiers`, 1 TODO; the same 7 on main)
# 1 GPU: 27 passed, 1 failed. The failing MXFP8 test needs torchrun's `RANK`; it fails the same way on main.
pytest tests/rl/unit_tests/gpu -m "not multi_gpu"

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 20, 2026
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review. This PR is stacked on #5919: review that one first. It logs generator/kv_cache_occupancy and generator/kv_cache_usage on each finished request.

@claude

claude Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 2m 19s —— View job


Approve (please address the items first): the human-written summary needs filling in, and two small inline suggestions are optional. A maintainer still needs to review, and #5919 first. Review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the items below before merging. This is a small, well-scoped metric whose definition is correct, given that #5919 strips ended rollouts' hashes. This touches RL generator core, so a maintainer still needs to review it (and #5919 first).

What this PR does. On TP rank 0, VLLMEngine.step reads the KV cache at most once a second and stamps the reading on every request that finishes. There are two numbers:

  • usage: vLLM's BlockPool.get_usage().
  • occupancy: 1 - free_uncached / usable.

Both are emitted as per-request generator/kv_cache_* metrics, and occupancy/max is added to the console panel. vLLM's own usage counts cached free blocks as free. Because #5919 evicts ended sessions' hashes, the only cached free blocks left are history that a live rollout can still reuse.

Example. 200 usable blocks. Running requests hold 50, waiting rollouts' cached history holds 90, and 60 are free.

before: generator/* has no KV metric; vLLM usage (OTel only) = 0.25
after:  generator/kv_cache_usage     = 0.25
        generator/kv_cache_occupancy = 0.70   # 140 / 200
session "ended" released -> its 30 blocks lose their hash -> occupancy 0.55, usage 0.25

Must fix

  1. PR description: the "Summary (human-written)" section is empty. The author needs to fill it in before merge (see "AI-assisted contributions" in CONTRIBUTING.md).

Should consider

  • torchtitan/rl/generator/vllm/engine.py:504-515: pass the reading into _finished_request instead of patching it after construction, and consider putting the 1 s cache in the evictor (inline).
  • torchtitan/rl/generator/dispatcher.py:395-399: kv_cache_*/mean is weighted by completions, not by time (inline).

Questions

  • SGLang's engine never sets kv_cache_reading, so these keys (and the console entry) don't exist on SGLang runs. Is that intended until SGLang has an equivalent? If so, a one-line note on RequestMetricsInputs.kv_cache_reading would make it explicit.
Details
  • Gate. The problem is real: with session eviction on, vLLM's get_usage() reads low whenever waiting rollouts hold cached history, which is exactly the state the admission gate needs to see. The only extra symbol is KVCacheReading, and it has two consumers (this metric and the stacked admission-gate PR).
  • Correctness of occupancy.
    • Every request is tracked, because routing_session_id is required on EngineRequest. So a hashed free block always belongs to a live session, or to a request still in vLLM that hasn't been evicted yet.
    • The null block is popped from the free queue at BlockPool init, so it is never counted. Dividing by num_gpu_blocks - 1 matches what get_usage() uses.
    • With prefix caching off, every free block has no hash, so occupancy == usage, which is the right answer.
    • The known overcount for blocks of an untracked "abandoned attempt" (the track TODO) also inflates occupancy until LRU reuse. It is rare and already documented.
  • Cost. Reading the whole free queue is about 4 ms over 60K free blocks, which is why the 1 s throttle exists. Reading only when a step finishes something keeps decode-only steps free of the cost.
  • Private vLLM API. free_block_queue.iter_blocks_after adds another BlockPool internal. The existing TODO (vllm-project/vllm#51428) on VLLMSessionKVEvictor.__init__ already covers this.
  • Tests. The occupancy test in test_session_kv_evictor.py guards the invariant that ended rollouts drop out of occupancy, which could otherwise break silently. The dispatcher change extends an existing test rather than adding one.

Not verified: that FreeKVCacheBlockQueue.iter_blocks_after exists in the pinned vLLM (I couldn't inspect the installed package; the CPU test exercises it), and the GPU timing numbers.

Comment thread torchtitan/rl/generator/vllm/engine.py Outdated
Comment on lines +504 to +515
finished_requests = [
_finished_request(request_output) for request_output in request_outputs
]
if finished_requests and self._is_tp_rank_0:
now = time.monotonic()
if now - self._kv_cache_read_time >= _KV_CACHE_READ_MAX_AGE_S:
self._kv_cache_reading = self._session_kv_evictor.kv_cache_reading()
self._kv_cache_read_time = now
for finished_request in finished_requests:
finished_request.metrics_inputs.kv_cache_reading = (
self._kv_cache_reading
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nit (should consider): this builds each FinishedRequest and then patches metrics_inputs.kv_cache_reading afterwards. It would be simpler to refresh the reading first and pass it in, e.g. _finished_request(request_output, kv_cache_reading=reading) -> _extract_request_metrics_inputs(..., kv_cache_reading=...). Then the field is set where the object is built, and the per-request loop goes away. The same goes for the throttle: the evictor already owns the read, so kv_cache_reading() could own the 1 s cache too. That would take _kv_cache_reading / _kv_cache_read_time off the engine, and the stacked admission-gate PR would get the same throttled value.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: Done in af94054. step reads first and passes the reading in: _finished_request(request_output, kv_cache_reading=...) -> _extract_request_metrics_inputs. The per-request patch loop is gone.

The 1 s cache stays in VLLMEngine.step. The admission-gate PR never reads kv_cache_reading: it admits by a KVCacheBudget read at startup. So the metric is the only user. The evictor's kv_cache_reading() stays a plain read, which the occupancy test calls three times in a row. The body's line that said the gate reads it was wrong, and is gone.

Comment on lines +395 to +399
if inputs.kv_cache_reading is not None:
metric_values[
"generator/kv_cache_occupancy"
] = inputs.kv_cache_reading.occupancy
metric_values["generator/kv_cache_usage"] = inputs.kv_cache_reading.usage

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Should consider: these go through the shared Mean + Max emission below, but they are engine gauges, not per-request values. Every request that finishes within one 1 s read window carries the same reading. So generator/kv_cache_occupancy/mean is weighted by how many requests finished in each window: a burst of 100 short completions at 0.3 outweighs a few long ones at 0.9. /max, which the console shows, is fine. Either emit only Max for the kv_cache_* keys, or say in the docstring above that /mean is completion-weighted, so nobody reads it as a time average.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: Documented in af94054. The docstring now says /mean weighs each reading by its completions, not by time. The body says it too. I kept /mean, so all keys keep the shared Mean + Max loop, and the console shows /max.

@felipemello1
felipemello1 force-pushed the felipemello1/session-kv-evictor branch from 866d659 to 44b74e3 Compare November 20, 2026 16:33
@felipemello1
felipemello1 force-pushed the felipemello1/kv-cache-metrics branch from 8aae2df to af94054 Compare November 20, 2026 16:33
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review af94054.

  • Both inline nits: answered in their threads. The reading is now passed in when each FinishedRequest is built, and /mean is documented as completion-weighted.
  • SGLang: yes, intended. RequestMetricsInputs.kv_cache_reading now says it is None on SGLang and on vLLM TP ranks other than 0. The body's Known issues says so too.
  • Correction: the body said the admission-gate PR reads kv_cache_reading. It doesn't (it admits by KVCacheBudget), so that line is gone.
  • Checks at af94054: RL CPU suite 692 passed, 7 skipped (same 7 as main). 1 GPU: 27 passed, 1 failed (the MXFP8 test that needs torchrun's RANK, same on main).

@claude

claude Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 1m 23s —— View job


Approve (please address the items first): both earlier nits are fixed at af94054. The human-written summary is still empty, and one optional inline nit remains. A maintainer still needs to review it, and #5919 first. Review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the items below before merging. Both earlier inline items are fixed at af94054. The only thing still open from the last review is the empty human-written summary. This touches RL generator core, so a maintainer still needs to review it (and #5919 first).

What changed since the last review. step now reads the KV cache first and passes the reading into _finished_request -> _extract_request_metrics_inputs, so the post-construction patch loop is gone. The 1 s throttle stays on the engine, and the author explained why: the admission-gate PR admits by KVCacheBudget and never reads kv_cache_reading, so the metric is the only consumer and the evictor's read stays a plain read. The _prepare_generation_request_metrics docstring now says /mean is completion-weighted. RequestMetricsInputs.kv_cache_reading documents that it is None on SGLang and on vLLM TP ranks other than 0.

Example. One engine.step() on TP rank 0 finishes r0 and r1 at t=100.0. A step at t=100.5 finishes r2, and one at t=101.1 finishes r3:

r0, r1 -> reading A (read at 100.0)
r2     -> reading A (0.5 s old, not re-read)
r3     -> reading B (1.1 s since last read)
TP rank != 0 -> kv_cache_reading None -> no generator/kv_cache_* keys

Must fix

  1. PR description: "Summary (human-written)" is still empty. The author has to fill it in before merge (see "AI-assisted contributions" in CONTRIBUTING.md). Still open from the previous review.

Should consider

  • torchtitan/rl/generator/vllm/engine.py:602 -- the new kv_cache_reading=None defaults are used only by tests (inline).
Details
  • Earlier findings at HEAD. Patch loop: resolved (engine.py:504-513). /mean weighting: documented (dispatcher.py:370-371). SGLang question: answered on the field docstring (types.py:235-236).
  • New test test_step_stamps_finished_requests_with_a_kv_cache_reading_at_most_a_second_old. It guards the throttle and the TP-rank-0 gate. Both regress silently: you get a stale or missing metric, or a 4 ms read on every step. It uses the existing _vllm_engine helper and adds no fixtures.
  • Throttle placement. Keeping it in step is fine, given that the engine is the only consumer. The evictor stays a pure read, which the occupancy test relies on.
  • Description. It now matches the code: the line saying the gate PR reads kv_cache_reading is gone.

Not verified: GPU timings, and that FreeKVCacheBlockQueue.iter_blocks_after exists in the pinned vLLM. The CPU occupancy test exercises it, and the author reports that suite passing.

Comment thread torchtitan/rl/generator/vllm/engine.py Outdated

def _finished_request(request_output: RequestOutput) -> FinishedRequest:
def _finished_request(
request_output: RequestOutput, *, kv_cache_reading: KVCacheReading | None = None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nit (should consider): kv_cache_reading defaults to None here and on _extract_request_metrics_inputs (line 628). The only production caller, step, always passes it, so the default only saves the tests some typing. If a future caller forgets the argument, the kv_cache_* keys silently disappear. CLAUDE.md says required parameters have no default. Drop both defaults and pass kv_cache_reading=None at the four test call sites that omit it (test_generator.py:286, 306, 691, 705).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: Done in ce52c53. kv_cache_reading is now a required keyword on _finished_request and _extract_request_metrics_inputs. The four test call sites pass kv_cache_reading=None. RL CPU suite: 692 passed, 7 skipped.

Two per-completion metrics, generator/kv_cache_occupancy and
generator/kv_cache_usage. vLLM's usage counts every cached free block as
free, so a cache full of waiting rollouts' history reads low. Occupancy also
counts cached free blocks: once ended rollouts' blocks are evicted, those
belong to live rollouts.

TP rank 0 stamps the reading on each finished request and re-reads at most
once per second, because the read walks the free queue. The console shows
generator/kv_cache_occupancy/max.
@felipemello1
felipemello1 force-pushed the felipemello1/kv-cache-metrics branch from af94054 to ce52c53 Compare November 20, 2026 16:44
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review ce52c53. The only change since af94054 is the nit on engine.py:602: both defaults dropped, the test calls pass the argument.

@claude

claude Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 40s —— View job


Approve (please address the item first): the engine.py:602 nit is fixed at ce52c53. The only open item is the empty human-written summary, and a maintainer still needs to review this PR, after #5919. Review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the items below before merging. The engine.py:602 nit is fixed at ce52c53. The only thing still open is the empty human-written summary. This touches RL generator core, so a maintainer still needs to review it (and #5919 first).

What changed since the last review. kv_cache_reading is now a required keyword-only argument on _finished_request (engine.py:601-603) and _extract_request_metrics_inputs (engine.py:627-629). Every call site passes it: step (engine.py:512) passes the throttled reading, and the five test call sites pass None or an explicit KVCacheReading (test_generator.py:255, 286, 308, 697, 713). If a future caller forgets the argument, it now gets a TypeError instead of silently losing the kv_cache_* keys.

Example.

before: _finished_request(output)                         -> metrics_inputs.kv_cache_reading = None (silent)
after:  _finished_request(output)                         -> TypeError: missing keyword-only argument 'kv_cache_reading'
        _finished_request(output, kv_cache_reading=None)  -> no generator/kv_cache_* keys (explicit)

Must fix

  1. PR description: "Summary (human-written)" is still empty. The author has to fill it in before merge (see "AI-assisted contributions" in CONTRIBUTING.md). This was also open in both earlier reviews.
Details
  • Earlier findings at HEAD. The post-construction patch loop is resolved (engine.py:504-514). The completion-weighted /mean is documented (dispatcher.py:370-372). The SGLang / non-TP-rank-0 None behavior is documented (types.py:110-112). The test-only defaults are removed (engine.py:602, 628).
  • Callsite audit. A repo-wide grep for _finished_request( and _extract_request_metrics_inputs( finds only the engine and test_generator.py, and every call passes the argument. RequestMetricsInputs.kv_cache_reading keeps its = None default. That is consistent with how the class treats its other optional fields, and it is what SGLang relies on.

Not verified: GPU timings, and that FreeKVCacheBlockQueue.iter_blocks_after exists in the pinned vLLM. The CPU occupancy test exercises it.

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

ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant