Skip to content

[None][fix] Fix window vector layer indexing - #17466

Open
yuxianq wants to merge 1 commit into
NVIDIA:mainfrom
yuxianq:fix/window-vec-layer-idx
Open

[None][fix] Fix window vector layer indexing#17466
yuxianq wants to merge 1 commit into
NVIDIA:mainfrom
yuxianq:fix/window-vec-layer-idx

Conversation

@yuxianq

@yuxianq yuxianq commented Aug 10, 2026

Copy link
Copy Markdown
Collaborator

Description

KvCacheConfig.max_attention_window is a model-global repeating pattern, while KV-cache pools and attention metadata are pipeline-stage local. The previous mixed contract left V1 partially sharded, kept V2 global, and required consumers to guess which layer index to use.

Resolve the configured pattern once into an exact per-local-layer max_attention_window_vec for both managers. Cache, sizing, and FMHA consumers now consistently use the local layer index, including nonzero and uneven pipeline-parallel stages. The projection preserves the compact enabled-layer convention used by masked hybrid caches and leaves the public configuration unchanged.

The change also:

  • keeps model-wide VSWA feature gates separate from rank-local pool state;
  • synchronizes V1 sizing with one rank-consistent collective, validates the windows actually hosted by each stage, and preserves distinct recurrent-state units;
  • uses local cache geometry for speculative KV relocation and selects the corresponding local pool;
  • fixes V2 static/runtime cache-cost window phasing across PP stages.

There are no public API, configuration-schema, dependency, or test-list changes.

Test Coverage

  • Added CPU regressions for V1/V2 short patterns, full vectors, masks, dummy ranks, uneven PP window phasing, distributed pool sizing, and global-vs-local VSWA gates.
  • Added focused FMHA propagation and speculative relocation tests using nonzero PP-local layer/pool layouts.
  • pre-commit run --files <all changed files>
  • python3 -m py_compile <all changed Python files>
  • Targeted pytest collection was attempted, but this worktree does not contain the compiled tensorrt_llm.bindings module; collection stops in tests/unittest/conftest.py with ModuleNotFoundError.

PR Checklist

  • PR description clearly explains what and why.
  • Follows the TRT-LLM coding guidelines.
  • Test cases are provided for new code paths.
  • No public API change or new dependency.
  • No CODEOWNERS, documentation, or architecture-diagram update is required.

Dev Engineer Review

  • Fixed attention-window indexing for KV-cache V2 across pipeline-parallel stages.
  • Preserved cache-local indexing for V1.
  • Added window projection, validation, sizing, and local-pool handling for KV-cache V2 and EAGLE3 relocation.
  • Added compatibility handling for configured VSWA state.
  • Updated calculate_max_num_blocks with an optional synchronization parameter.
  • Added cleanup for partially allocated dummy requests.
  • No configuration or test-list changes.
  • Python compilation and pre-commit checks passed.
  • Targeted CPU tests were blocked by an unrelated PyTorch/TensorRT-LLM ABI mismatch.

QA Engineer Review

  • Added tests for:
    • V2 attention-window indexing in test_trtllm_attention_window.py.
    • Pipeline-parallel cache sizing in test_kv_cache_estimation.py.
    • V2 window resolution and draft-token relocation in test_kv_cache_manager_v2.py.
    • Configured VSWA detection in test_py_executor.py.
    • Window projection and cache sizing in test_resource_manager.py.
    • EAGLE3 local-cache relocation in test_eagle3.py.
  • No test-db/, qa/, or tests/integration/test_lists/ coverage changes were reported.
  • Verdict: needs follow-up because targeted test execution was blocked and test-list coverage is unavailable.

@yuxianq
yuxianq requested a review from a team as a code owner August 10, 2026 07:53
@coderabbitai

coderabbitai Bot commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

The change resolves attention windows in pipeline-local layer order. It updates KV-cache sizing, configuration, relocation, attention integration, VSWA detection, distributed capacity reduction, and regression coverage.

Changes

Pipeline-local KV cache windows

Layer / File(s) Summary
Window projection and distributed cache sizing
tensorrt_llm/_torch/pyexecutor/resource_manager.py
Attention-window vectors are clamped, projected to local layers, validated, and used for distributed cache-capacity reduction.
KVCacheManagerV2 local-window lifecycle
tensorrt_llm/_torch/pyexecutor/kv_cache_manager_v2.py
KVCacheManagerV2 stores resolved local-layer windows and uses them for sizing, configuration, and draft-token relocation.
Attention and VSWA integration
tensorrt_llm/_torch/attention_backend/trtllm.py, tensorrt_llm/_torch/pyexecutor/py_executor.py
Attention-window selection uses the cached local layer index. VSWA checks prefer configured state and retain legacy fallback behavior.
EAGLE3 local-pool relocation
tensorrt_llm/_torch/speculative/eagle3_dynamic_tree.py
EAGLE3 relocation validates uniform local windows and passes local pool metadata to the relocation operator.
Local-window and relocation validation
tests/unittest/_torch/attention/*, tests/unittest/_torch/executor/*, tests/unittest/_torch/speculative/*
Tests cover pipeline-local ordering, projected patterns, distributed sizing, VSWA detection, and relocation arguments.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant KVCacheManagerV2
  participant ResourceManager
  participant AttentionBackend
  participant RelocationKernel
  KVCacheManagerV2->>ResourceManager: Resolve configured windows for local layers
  ResourceManager-->>KVCacheManagerV2: Return local window vector and cache sizing
  KVCacheManagerV2->>AttentionBackend: Provide local-layer cache metadata
  AttentionBackend->>RelocationKernel: Use local window and pool metadata
Loading

Possibly related PRs

Suggested reviewers: schetlur-nv

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 3.45% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description check ✅ Passed The description explains the problem, solution, test coverage, test limitations, and checklist items with sufficient detail.
Title check ✅ Passed The title is concise, follows the required format, and clearly identifies the window-vector layer-indexing fix.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai 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.

🧹 Nitpick comments (1)
tensorrt_llm/_torch/attention_backend/trtllm.py (1)

1802-1807: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Add regression coverage for both layer-index contracts.

Use distinct window values and a nonzero pipeline-parallel stage. Assert that V2 uses self.layer_idx and V1 uses get_local_layer_idx(metadata). This protects the corrected behavior from a future simplification.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tensorrt_llm/_torch/attention_backend/trtllm.py` around lines 1802 - 1807,
Add regression tests covering the window selection logic around the V2/V1 branch
in the attention backend, using distinct window values and a nonzero
pipeline-parallel stage. Assert that KVCacheManagerV2 selects via
self.layer_idx, while the V1 path selects via get_local_layer_idx(metadata),
preserving both layer-index contracts.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@tensorrt_llm/_torch/attention_backend/trtllm.py`:
- Around line 1802-1807: Add regression tests covering the window selection
logic around the V2/V1 branch in the attention backend, using distinct window
values and a nonzero pipeline-parallel stage. Assert that KVCacheManagerV2
selects via self.layer_idx, while the V1 path selects via
get_local_layer_idx(metadata), preserving both layer-index contracts.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 84a563a0-4010-4672-b735-4807b796ca5c

📥 Commits

Reviewing files that changed from the base of the PR and between 07a5591 and e590ab0.

📒 Files selected for processing (1)
  • tensorrt_llm/_torch/attention_backend/trtllm.py

@yuxianq
yuxianq force-pushed the fix/window-vec-layer-idx branch from e590ab0 to b018ef5 Compare August 10, 2026 08:00
@yuxianq
yuxianq requested a review from ziyixiong-nv August 10, 2026 08:23
window = window_vec[self.local_layer_idx % len(window_vec)]
# V2 retains the global window pattern, while V1 may shard a
# full per-layer vector into cache-local order.
window_layer_idx = self.layer_idx if isinstance(

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.

If window_vec is using repeating pattern, looks like the vector will not use cache-local order for V1, should self.layer_idx be used in this case?

Signed-off-by: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com>
@yuxianq
yuxianq force-pushed the fix/window-vec-layer-idx branch from b018ef5 to 7dcd4fb Compare August 10, 2026 10:52
@yuxianq
yuxianq requested review from a team as code owners August 10, 2026 10:52

@coderabbitai coderabbitai 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.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
tensorrt_llm/_torch/pyexecutor/kv_cache_manager_v2.py (1)

693-733: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Reject speculative decoding with enable_swa_scratch_reuse. The target manager still invokes _update_kv_cache_draft_token_location(), while scratch reuse maps each local layer to a distinct pool. The local_pool_ids assertion therefore fails when accepted draft tokens exist. Add configuration-time validation or support relocation across per-layer pools.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tensorrt_llm/_torch/pyexecutor/kv_cache_manager_v2.py` around lines 693 -
733, Reject the incompatible configuration during cache-manager setup when
speculative decoding is enabled together with enable_swa_scratch_reuse, before
_update_kv_cache_draft_token_location can run. Add validation at the relevant
initialization/configuration symbol and provide a clear assertion or error; do
not rely on the local_pool_ids single-pool assertion in the relocation path.
🧹 Nitpick comments (1)
tensorrt_llm/_torch/attention_backend/trtllm.py (1)

1379-1393: 🗄️ Data Integrity & Integration | 🔵 Trivial | 💤 Low value

Use the cache-local layer index.

V1 and V2 resolve max_attention_window_vec into local-layer order. self.local_layer_idx is correct for both managers. Update the PR description to say “cache-local layer index,” not “model-global layer index.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tensorrt_llm/_torch/attention_backend/trtllm.py` around lines 1379 - 1393,
The implementation already uses self.local_layer_idx correctly in
_set_cache_attention_window; update the PR description wording to refer to the
“cache-local layer index” instead of the “model-global layer index,” without
changing the code.

Source: Learnings

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tensorrt_llm/_torch/pyexecutor/kv_cache_manager_v2.py`:
- Around line 306-323: Update _resolve_v2_max_attention_window_vec so configured
windows less than or equal to zero are normalized to None, matching
normalize_window_size in _get_static_cache_size_layer_components; retain the
existing max_seq_len-to-None normalization and projection behavior for positive
windows.

---

Outside diff comments:
In `@tensorrt_llm/_torch/pyexecutor/kv_cache_manager_v2.py`:
- Around line 693-733: Reject the incompatible configuration during
cache-manager setup when speculative decoding is enabled together with
enable_swa_scratch_reuse, before _update_kv_cache_draft_token_location can run.
Add validation at the relevant initialization/configuration symbol and provide a
clear assertion or error; do not rely on the local_pool_ids single-pool
assertion in the relocation path.

---

Nitpick comments:
In `@tensorrt_llm/_torch/attention_backend/trtllm.py`:
- Around line 1379-1393: The implementation already uses self.local_layer_idx
correctly in _set_cache_attention_window; update the PR description wording to
refer to the “cache-local layer index” instead of the “model-global layer
index,” without changing the code.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 1eb33bf8-32f0-4c94-a48b-b34b3663e2fc

📥 Commits

Reviewing files that changed from the base of the PR and between b018ef5 and 7dcd4fb.

📒 Files selected for processing (11)
  • tensorrt_llm/_torch/attention_backend/trtllm.py
  • tensorrt_llm/_torch/pyexecutor/kv_cache_manager_v2.py
  • tensorrt_llm/_torch/pyexecutor/py_executor.py
  • tensorrt_llm/_torch/pyexecutor/resource_manager.py
  • tensorrt_llm/_torch/speculative/eagle3_dynamic_tree.py
  • tests/unittest/_torch/attention/test_trtllm_attention_window.py
  • tests/unittest/_torch/executor/test_kv_cache_estimation.py
  • tests/unittest/_torch/executor/test_kv_cache_manager_v2.py
  • tests/unittest/_torch/executor/test_py_executor.py
  • tests/unittest/_torch/executor/test_resource_manager.py
  • tests/unittest/_torch/speculative/test_eagle3.py

Comment on lines +306 to +323
def _resolve_v2_max_attention_window_vec(
max_attention_window_vec: Optional[Sequence[int]],
max_seq_len: int,
pp_layers: Sequence[int],
num_layers: int,
layer_mask: Optional[Sequence[bool]] = None,
) -> List[Optional[int]]:
"""Resolve a V2 window pattern into exact cache-local layer order."""
configured_windows = _clamp_max_attention_window_vec(max_attention_window_vec, max_seq_len)
normalized_windows = [
None if window == max_seq_len else window for window in configured_windows
]
return _project_max_attention_window_vec(
normalized_windows,
pp_layers,
num_layers,
layer_mask,
)

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Normalize non-positive windows to None, as the static path does.

_resolve_v2_max_attention_window_vec maps only window == max_seq_len to None. A configured window of 0 or a negative value survives clamping and reaches AttentionLayerConfig.sliding_window_size at line 1898.

_get_static_cache_size_layer_components treats the same input differently: its normalize_window_size maps window_size <= 0 to None (line 375-376). The static estimator and the runtime layer configuration therefore disagree for the same kv_cache_config.max_attention_window.

KvCacheConfig.max_attention_window declares only min_length=1, so a non-positive entry is accepted by validation.

🔧 Proposed fix to align normalization
     configured_windows = _clamp_max_attention_window_vec(max_attention_window_vec, max_seq_len)
     normalized_windows = [
-        None if window == max_seq_len else window for window in configured_windows
+        None if window is None or window <= 0 or window == max_seq_len else window
+        for window in configured_windows
     ]
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def _resolve_v2_max_attention_window_vec(
max_attention_window_vec: Optional[Sequence[int]],
max_seq_len: int,
pp_layers: Sequence[int],
num_layers: int,
layer_mask: Optional[Sequence[bool]] = None,
) -> List[Optional[int]]:
"""Resolve a V2 window pattern into exact cache-local layer order."""
configured_windows = _clamp_max_attention_window_vec(max_attention_window_vec, max_seq_len)
normalized_windows = [
None if window == max_seq_len else window for window in configured_windows
]
return _project_max_attention_window_vec(
normalized_windows,
pp_layers,
num_layers,
layer_mask,
)
def _resolve_v2_max_attention_window_vec(
max_attention_window_vec: Optional[Sequence[int]],
max_seq_len: int,
pp_layers: Sequence[int],
num_layers: int,
layer_mask: Optional[Sequence[bool]] = None,
) -> List[Optional[int]]:
"""Resolve a V2 window pattern into exact cache-local layer order."""
configured_windows = _clamp_max_attention_window_vec(max_attention_window_vec, max_seq_len)
normalized_windows = [
None if window is None or window <= 0 or window == max_seq_len else window
for window in configured_windows
]
return _project_max_attention_window_vec(
normalized_windows,
pp_layers,
num_layers,
layer_mask,
)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tensorrt_llm/_torch/pyexecutor/kv_cache_manager_v2.py` around lines 306 -
323, Update _resolve_v2_max_attention_window_vec so configured windows less than
or equal to zero are normalized to None, matching normalize_window_size in
_get_static_cache_size_layer_components; retain the existing max_seq_len-to-None
normalization and projection behavior for positive windows.

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.

2 participants