Skip to content

[Feature][Worker] Add MRV2 KV Trace - #17833

Open
Tjh-UKN wants to merge 1 commit into
vllm-project:mainfrom
Tjh-UKN:codex/kv-block-trace-design
Open

Tjh-UKN wants to merge 1 commit into
vllm-project:mainfrom
Tjh-UKN:codex/kv-block-trace-design

Conversation

@Tjh-UKN

@Tjh-UKN Tjh-UKN commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

What this PR does / why we need it?

Add opt-in KV Trace address-plan monitoring in Model Runner V2. Consume native SchedulerOutput request/block deltas at runner input and compare them with final per-group slot mappings and block tables. No Scheduler, allocator, BlockPool, or per-attention-layer patch is installed. Model Runner V1 has zero diff against the PR base.

File Responsibility
kv_trace/kv_trace_config.py Read and validate per-engine additional_config.kv_trace.enabled/action.
kv_trace/kv_trace_runner.py Install MRV2 wrappers and collect native request order, final attention metadata, zero/copy boundaries and capture context.
kv_trace/kv_trace_state.py Consume native SchedulerOutput deltas and maintain immutable request-to-group block tables; finished/preempted messages remove local references. No allocator generation/owners/valid-prefix state.
kv_trace/kv_trace_plan.py Freeze step-local binding and metadata snapshots, reuse D2H buffers, compute expected addresses, compare write slots and read block tables, emit write/read or violation records.
kv_trace/kv_trace_runtime.py Connect execution boundaries, finish pending audits at result consumption, emit logs and apply log/raise failure handling.
kv_trace/kv_trace_connector.py Record public connector input metadata and native completion/failure results, without wrapping transport internals.
worker/v2/model_runner.py Minimal integration: install the trace at initialization and configure it after KV-cache setup.

Request bindings are immutable step-local snapshots. Finished/preempted request messages remove local references; this is not a claim of physical block allocation/free visibility. Public connector metadata/results are projected without wrapping transport internals. The existing Mooncake failed-receive result fix is retained.

Does this PR introduce any user-facing change?

Enable per engine:

vllm serve MODEL --additional-config '{"kv_trace":{"enabled":true,"action":"log"}}'

enabled defaults to false. action is log or raise. Normal INFO records include kv_trace.bind, kv_trace.write, kv_trace.read, and boundary records. Only kv_trace.violation latches a raised failure; missing observations are debug-level skipped checks and do not become coverage-gap errors.

The check compares declared execution metadata. It does not prove kernel memory accesses, KV numerical correctness, allocation lifetime, or network transfer integrity, and cannot undo submitted device writes. Existing restrictions on CP, DBO, speculation, encoder/decoder and unadapted cache semantics remain. Connector support is limited to the existing Ascend Mooncake adapter.

How was this patch tested?

Package-only follow-up: 39bd3f159ae39f99ffe28b39c80d33293adb8aa0 moves the feature from vllm_ascend/debug/ to vllm_ascend/kv_trace/, moves its focused tests to tests/ut/kv_trace/, and updates imports and documentation. Configuration remains additional_config.kv_trace. The 60 focused tests and Linux bash format.sh ci pass; Mypy passes for Python 3.10/3.11/3.12. AST comparison confirms unchanged product logic apart from import paths/order. NPU functionality and performance numbers below belong to the explicitly pinned behavior revision; hardware benchmarks were not rerun for this package rename.

NPU-validated behavior revision: 2883638529ac02c9ee1ef29a41a8158da9d0782a. Validated source tree: d3bcee94fc3968c0f29f72dba72dde08774e9fad.

On 179.167.1.2 / Ascend 910B4, Qwen3-0.6B BF16, MRV2, TP1/PP1:

  • 16 fresh engines / 50 requests completed the functional matrix: 46 successful responses and 4 expected raise-mode rejections.
  • Eager/FULL × OFF/ON: 24 healthy requests; paired text outputs match and actual prefix-cache hits were asserted.
  • Eager/FULL pressure: 16 requests, 5 real preemptions per mode, no violations.
  • Two monitoring-OFF native-address fault controls completed normally.
  • Eager/FULL × slot shift/read-block swap × log/raise: eight fault requests. Expected write_target_mismatch / read_target_mismatch logged; log returned output, raise blocked normal output. These are controlled safe-address injections, not production-fault or numerical-correctness proof.
  • 60 focused unit tests passed; product line coverage 90.34% (477/528).
  • bash format.sh ci passed on Linux, all configured hooks, with no formatter changes. Mypy passed for Python 3.10, 3.11 and 3.12.

Performance validation completed on the delivery source: 8 fresh engines, 16 formal windows, 520/520 successful requests and 133,120 output tokens, all windows longer than 60 seconds. Normal INFO trace logging is included. Llama-3.1-8B BF16, MRV2 FULL, input/output 2048/256, concurrency 1/8, prefix caching disabled, same NPU. Order: OFF / ON / ON / OFF / ON / OFF / OFF / ON; four OFF and four ON engines. All valid windows are retained.

Concurrency OFF token/s ON token/s Throughput decrease OFF/ON CV OFF/ON TTFT (ms) TTFT increase OFF/ON ITL (ms) ITL increase
1 24.2183 24.2459 -0.1139% 0.2986% / 0.0651% 218.0061 / 228.3306 +4.7359% 40.5975 / 40.5098 -0.2159%
8 156.7989 155.7702 0.6561% 0.1263% / 0.0609% 771.4675 / 810.8035 +5.0989% 48.1071 / 48.2962 +0.3932%

Throughput is total output tokens divided by total measured time; latency means are weighted by request count. CV is the sample coefficient of variation across four independent engine windows. These measurements do not establish a general 1% bound: throughput and first-token latency are separate outcomes. CPU/RSS sampler windows were invalid due to buffered client markers and are excluded from resource conclusions.

The local HTML report contains the stable functional results and original server logs. It excludes abandoned startup attempts. MLA, multi-rank TP/PP and actual Mooncake network transfer were not exercised in this run.

Checklist

  • Scheduler/allocator patch removed; Model Runner V1 restored to base.

  • Per-engine additional_config.kv_trace and log/raise retained.

  • Exact-source NPU functional validation and focused host checks passed.

  • Repository format checks and Python 3.10/3.11/3.12 typing checks passed.

  • Complete multi-run OFF/ON performance comparison and retain all formal windows.

  • Required online CI passes on the delivery head before merge.

  • vLLM main: vllm-project/vllm@24420b7

@github-actions

Copy link
Copy Markdown
Contributor

👋 Hi! Thank you for contributing to the vLLM Ascend project. The following points will speed up your PR merge:‌‌

  • A PR should do only one thing, smaller PRs enable faster reviews.
  • Every PR should include unit tests and end-to-end tests ‌to ensure it works and is not broken by other future PRs.
  • Write the commit message by fulfilling the PR description to help reviewer and future developers understand.

If CI fails, you can run linting and testing checks locally according Contributing and Testing.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces a diagnostic tracing framework for KV block lifecycles to help identify and debug KV corruption issues. By correlating events across the scheduler, worker, and transfer paths, it allows for detailed inspection of block ownership and access patterns. The feature is opt-in and designed to minimize impact on production performance while providing the necessary evidence for root cause analysis.

Highlights

  • KV Lifecycle Tracing: Implemented an opt-in tracing framework to record KV block lifecycles, including allocation, transfer, and access events, to assist in diagnosing silent KV corruption.
  • Cross-Component Correlation: Integrated tracing across the scheduler, worker, and Mooncake transfer paths to correlate request IDs and block ownership across process boundaries.
  • Offline Analysis Tools: Added a standalone JSONL reader tool to support offline correlation, completeness checks, and querying of trace events.
  • Documentation and Validation: Included comprehensive user guides, design contracts, and performance validation reports to ensure the feature is well-documented and its overhead is understood.
New Features

🧠 You can now enable Memory (public preview) to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize the Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counterproductive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@gemini-code-assist gemini-code-assist 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.

Code Review

Suggested PR Title:

[Ops][Feature] Opt-in KV block lifecycle tracing for Ascend

Suggested PR Summary:

### What this PR does / why we need it?
This PR introduces an opt-in KV block lifecycle tracing feature (`VLLM_ASCEND_KV_TRACE`) for Ascend. It allows recording and querying KV block lifetimes, request mappings, transfers, and selected forward-window byte changes to diagnose silent KV corruption, stale slot mappings, block reuse, and PD request correlation.

Key changes include:
- Core tracing logic and configuration parsing in `vllm_ascend/debug/kv_trace.py` and `kv_trace_manager.py`.
- Integration with Mooncake connector and worker model runner to capture transfer and execution events.
- A CLI tool `tools/kv_block_trace.py` for reading and analyzing trace logs.
- Extensive documentation and design specs.
- Comprehensive unit tests covering the tracing logic.

Feedback:
A critical bug was identified in `vllm_ascend/worker/model_runner_v1.py` where `self._kv_trace_caches` is assigned a list directly instead of a dictionary mapping layer names to cache tensors, which would cause an `AttributeError` when tracing is enabled. A code suggestion has been provided to construct the dictionary properly.

### Does this PR introduce _any_ user-facing change?
Yes, it introduces a new opt-in environment variable `VLLM_ASCEND_KV_TRACE` to enable KV block lifecycle tracing, along with a CLI tool `tools/kv_block_trace.py` for log analysis.

### How was this patch tested?
The patch includes new unit tests in `tests/ut/debug/test_kv_trace.py` and `tests/ut/debug/test_kv_trace_relations.py` which can be run on CPU. Real environment validation was also performed on Ascend 910B4 as documented in the validation reports.

Comment thread vllm_ascend/worker/model_runner_v1.py Outdated
Comment on lines +4766 to +4767
if self._kv_trace is not None:
self._kv_trace_caches = kv_caches

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.

high

In initialize_kv_cache_tensors, kv_caches is returned as a list of cache tensors (or tuples of tensors) from _reshape_kv_cache_tensors. However, kv_trace.py expects runner._kv_trace_caches to be a dictionary mapping layer names to their corresponding cache tensors (calling .get(layer_name) on it). Assigning the list directly to self._kv_trace_caches will cause an AttributeError: 'list' object has no attribute 'get' when tracing is enabled. We should construct a dictionary mapping each layer name to its corresponding cache tensor in order.

Suggested change
if self._kv_trace is not None:
self._kv_trace_caches = kv_caches
if self._kv_trace is not None:
self._kv_trace_caches = {}
layer_idx = 0
for group in kv_cache_config.kv_cache_groups:
for name in group.layer_names:
if layer_idx < len(kv_caches):
self._kv_trace_caches[name] = kv_caches[layer_idx]
layer_idx += 1

@github-actions github-actions Bot added merge-conflicts and removed documentation Improvements or additions to documentation labels Sep 30, 2026
@github-actions

Copy link
Copy Markdown
Contributor

This pull request has conflicts, please resolve those before we can evaluate the pull request.

@Tjh-UKN Tjh-UKN changed the title [Feat][Debug] Add KV block lifecycle tracing and offline correlation [Feat][Debug] Add worker KV cache access legality checks Oct 13, 2026
@Tjh-UKN Tjh-UKN changed the title [Feat][Debug] Add worker KV cache access legality checks [Feature] Add worker KV cache access legality checks Oct 13, 2026
@Tjh-UKN
Tjh-UKN force-pushed the codex/kv-block-trace-design branch from 6e71cfb to 7db943c Compare October 13, 2026 13:01
@github-actions

Copy link
Copy Markdown
Contributor

This pull request has conflicts, please resolve those before we can evaluate the pull request.

@Tjh-UKN Tjh-UKN changed the title [Feature] Add worker KV cache access legality checks [Feature][Worker] Add KV cache address legality checks Oct 16, 2026
@Tjh-UKN
Tjh-UKN force-pushed the codex/kv-block-trace-design branch from cb7f26d to b4d38b1 Compare October 16, 2026 08:55
@Tjh-UKN Tjh-UKN changed the title [Feature][Worker] Add KV cache address legality checks [Feature][Worker] Add KV cache address legality checks for V1 and V2 Oct 16, 2026
@github-actions

Copy link
Copy Markdown
Contributor

This pull request has conflicts, please resolve those before we can evaluate the pull request.

@github-actions github-actions Bot added documentation Improvements or additions to documentation and removed merge-conflicts labels Oct 20, 2026
@Tjh-UKN
Tjh-UKN force-pushed the codex/kv-block-trace-design branch from 1a6906e to 55b60a9 Compare October 20, 2026 06:40
@github-actions

Copy link
Copy Markdown
Contributor

This pull request has conflicts, please resolve those before we can evaluate the pull request.

Comment thread vllm_ascend/worker/v1/model_runner.py Outdated
)
from vllm_ascend.compilation.breakable_aclgraph import BreakableACLGraphWrapper
from vllm_ascend.core.kv_cache_interface import is_circular_kv_cache_spec
from vllm_ascend.debug.kv_guard_runtime import install_guard

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

MRV1 is deprecated. You don't need to change MRV1

Comment thread vllm_ascend/attention/attention_v1.py Outdated
key, value, block_size, block_table, actual_seq_lengths_kv = self._get_fia_params(
key, value, attn_metadata, kv_cache
)
guard = getattr(self, "_kv_guard", None)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Lets check whether it's necessary to add guards in attention forward.

@@ -0,0 +1,182 @@
# SPDX-License-Identifier: Apache-2.0

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

What's your future plan to remove this patch? Do you have any upstream vLLM RFCs or PRs?

@Tjh-UKN Tjh-UKN changed the title [Feature][Worker] Add KV cache address legality checks for V1 and V2 [Feature][Worker] Add KV Trace monitoring with per-group address checks Nov 11, 2026
@Tjh-UKN Tjh-UKN changed the title [Feature][Worker] Add KV Trace monitoring with per-group address checks [Feature][Worker] Add MRV2 KV Trace without Scheduler patches Nov 13, 2026
@@ -0,0 +1,3 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Opt-in diagnostics. Importing this package does not enable instrumentation."""

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I suggest that change the directory name to kv_trace

@freyfwt freyfwt added the ready-precise run selected e2e test for pr label Nov 13, 2026
@Tjh-UKN Tjh-UKN changed the title [Feature][Worker] Add MRV2 KV Trace without Scheduler patches [Feature][Worker] Add MRV2 KV Trace Nov 13, 2026
Consolidate the final KV Trace changes onto current main so CI can rebase without replaying obsolete KV guard commits.

Signed-off-by: TAJh <taojiaheng1@huawei.com>
@Tjh-UKN
Tjh-UKN force-pushed the codex/kv-block-trace-design branch from 3fdd8f6 to b44bdef Compare November 14, 2026 00:58

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

documentation Improvements or additions to documentation module:core module:tests ready-precise run selected e2e test for pr

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants