Skip to content

feat(ws1): add NativeKVCacheAttnOp pure-PyTorch KV-cache attention reference - #195

Merged
Flink-ddd merged 4 commits into
RL-Align:mainfrom
maxiaosong1124:feat/ws1-kv-cache-attention-pytorch-op
Jul 6, 2026
Merged

Flink-ddd merged 4 commits into
RL-Align:mainfrom
maxiaosong1124:feat/ws1-kv-cache-attention-pytorch-op

Conversation

@maxiaosong1124

@maxiaosong1124 maxiaosong1124 commented Jun 27, 2026 •

Copy link
Copy Markdown
Collaborator

⚠️ Depends on #188 (attention) — do not merge first

NativeKVCacheAttnOp delegates to the same NativeAttentionOp reduction added in #188,
so prefill and decode share one numerical path. This branch is stacked on top of #188's
feat/ws1-attention-pytorch-op.

Because #188 is not merged yet, the diff below currently also contains #188's attention
files.
For this review, please look only at the kv_cache-specific changes:

  • rl_engine/kernels/ops/pytorch/attention/kv_cache.py
  • tests/test_kv_cache_attention.py
  • the kv_cache_attention entries in rl_engine/kernels/registry.py
  • the kv_cache CI step in .github/workflows/ci.yml

Once #188 merges to main, I'll rebase onto main and the diff becomes lean (attention-free).
Please do not merge this before #188.

Summary

Pure-PyTorch fp32 ground-truth reference for KV-cache (incremental/decode) attention
(WS1 / ISSUE #108). It concatenates cached and new K/V along the sequence axis and then calls
the exact same NativeAttentionOp
used for full-sequence prefill — re-implementing softmax
here would defeat the purpose. This guarantees decode (rollout) and prefill (training) take an
identical reduction, which is what keeps rollout↔training numerically consistent.

Shapes follow Qwen3-8B (synthetic tensors, no weights downloaded): 32 Q / 8 KV heads
(GQA g=4) / head_dim=128, scale = 1/√128.

What this adds

  • NativeKVCacheAttnOp (pytorch/attention/kv_cache.py):
    forward / forward_fp32(q, k_cache, v_cache, k_new, v_new, *, causal=True, scale=None, key_padding_mask=None) per the frozen contract (INTERFACES §9). cat([cache, new], dim=2)
    → delegates to NativeAttentionOp. Returns attention output only; cache update is out of
    scope for the numerical contract.
  • Registry: PYTORCH_NATIVE_KV_CACHE_ATTN enum + kv_cache_attention priority-map entries
    (cpu / cuda / rocm).
  • tests/test_kv_cache_attention.py — 14 CPU-safe tests (+ GPU/large markers).
  • CI: pytest tests/test_kv_cache_attention.py -k "not large and not gpu".

Test coverage

  • Delegation correctness — forward / forward_fp32 equal NativeAttentionOp on the
    concatenated K/V.
  • Prefill↔decode consistency — stepwise decode matches a single full-sequence prefill.
  • Cache split-point invariance — same total KV split at different cache/new boundaries
    gives the same result.
  • Axis-A — batch slice invariance (torch.equal).
  • key_padding_mask — padded keys get zero weight; near-equality atol=2e-6 (differing
    softmax reduction widths, same rationale as :feat(ws1): add NativeAttentionOp pure-PyTorch standard-softmax reference #188's padding test, with headroom over the
    ~1.3e-6 platform-sensitive drift).
  • Axis-B — bf16 / fp16 forward tracks fp32 within per-dtype peak-relative tolerance.
  • Empty-cache == plain attention, closed-form uniform-attention decode, output shape follows
    q, GQA divisibility guard, input purity (no mutation), registry dispatch.

Local run

```
python -m pytest tests/test_kv_cache_attention.py -v -k "not large and not gpu"

14 passed

```

Notes

  • Pure function: no randomness, no in-place, no device moves; dtype/device follow inputs.
  • Mask convention: True = valid / keep, False = padding (consistent with the rest of the repo).

Summary by CodeRabbit

  • New Features

    • Added support for KV-cache attention with a native PyTorch implementation and registry routing.
    • Expanded CI to run additional CPU-safe attention validation checks.
  • Bug Fixes

    • Enforced stricter input alignment for decode-time attention.
    • Improved handling for cached, masked, and incremental attention cases.
  • Tests

    • Added comprehensive coverage for KV-cache attention correctness, precision, and error handling.

@coderabbitai

coderabbitai Bot commented Jun 27, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: a8dfa582-17ea-4342-8a83-1551ae5fa544

📥 Commits

Reviewing files that changed from the base of the PR and between 4e6df2c and 5e6b778.

📒 Files selected for processing (3)
  • rl_engine/kernels/ops/pytorch/attention/kv_cache.py
  • rl_engine/kernels/registry.py
  • tests/test_kv_cache_attention.py

📝 Walkthrough

Walkthrough

Adds NativeKVCacheAttnOp, a pure-PyTorch KV-cache/decode attention operator that validates query-length alignment, concatenates cached and new key/value tensors, and delegates to NativeAttentionOp. Registers it in the kernel registry under "kv_cache_attention" for CUDA, ROCm, and CPU. Adds a corresponding test suite and CI steps.

Changes

KV-cache attention operator

Layer / File(s) Summary
Operator implementation
rl_engine/kernels/ops/pytorch/attention/kv_cache.py
NativeKVCacheAttnOp validates decode alignment, concatenates cache+new K/V along the sequence axis, and delegates forward/forward_fp32 to NativeAttentionOp.
Registry backend and routing
rl_engine/kernels/registry.py
Adds OpBackend.PYTORCH_NATIVE_KV_CACHE_ATTN and routes "kv_cache_attention" to it in CUDA, ROCm, and CPU priority maps.
Validation suite and CI
tests/test_kv_cache_attention.py, .github/workflows/ci.yml
Tests cover delegation equivalence, split-point/stepwise decode invariance, batch invariance, empty-cache, uniform-attention, masking, dtype accuracy, shape, error handling, immutability, and registry dispatch; CI runs CPU-safe attention and KV-cache attention tests.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Possibly related PRs

  • RL-Align/RL-Kernel#188: NativeKVCacheAttnOp delegates to and is validated against NativeAttentionOp from this PR.

Suggested reviewers: bitborne, KJLdefeated, inaniloquentee, Flink-ddd

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: adding a pure-PyTorch NativeKVCacheAttnOp KV-cache attention reference.
Docstring Coverage ✅ Passed Docstring coverage is 92.31% which is sufficient. The required threshold is 80.00%.
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.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

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

Actionable comments posted: 5

🤖 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 `@docs/operators/attention.md`:
- Around line 72-73: The operator contract text is out of sync with the
implementation and should be corrected in the attention docs. Update the
`forward_fp32()` contract wording so it no longer claims the original dtype is
preserved, and change the padding tolerance statement to match the shipped
`2e-6` value. Keep the wording aligned with the operator contract section and
the relevant `forward_fp32()` behavior so downstream users get the correct
guarantees.

In `@rl_engine/kernels/ops/pytorch/attention/kv_cache.py`:
- Around line 78-118: Add an explicit sequence-length validation in
`KVCacheAttention.forward` and `KVCacheAttention.forward_fp32` to reject cases
where `q` does not match the newly appended token length (`Sq != S_new`). Use
the existing `_concat_kv` flow as the location to enforce this check before
calling `_attn.forward` or `_attn.forward_fp32`, and raise an error with clear
context when the `q`/`k_new`/`v_new` shapes are misaligned.

In `@rl_engine/kernels/ops/pytorch/attention/standard_attn.py`:
- Around line 183-191: The _strict_fp32_math helper currently mutates the
process-wide torch.backends.cuda.matmul.allow_tf32 flag, which can affect
unrelated CUDA work and concurrent calls. Update the forward_fp32 path to avoid
toggling shared backend state in standard_attn.py, and instead use a safer
isolation approach within _strict_fp32_math (or an equivalent local-only
mechanism) while still disabling autocast for the true fp32 reference path.

In `@tests/test_attention.py`:
- Around line 281-285: Reformat the assert block in test_attention.py so it
matches Black’s preferred wrapping, especially the multi-line assert with the
trailing message string. Update the padding-mask check around the
masked/valid_only comparison to use Black-compatible line breaks and
parentheses, keeping the same logic but adjusting the formatting so CI no longer
rewrites it.

In `@tests/test_kv_cache_attention.py`:
- Around line 145-157: The split-point KV-cache test is using a full-length
query tensor for every split, which hides whether the suffix-only path is
correct. Update the test in the split loop so the query tensor is the suffix of
q that corresponds to each non-zero split, and keep the existing forward_fp32
comparison against the all-cache/all-new cases. Use the symbols q, k_full,
v_full, split, and op.forward_fp32 to align the test with the documented
KV-cache contract.
🪄 Autofix (Beta)

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: defaults

Review profile: CHILL

Plan: Pro

Run ID: 527d2fb3-1020-4591-be59-ecf3322d1308

📥 Commits

Reviewing files that changed from the base of the PR and between ea196da and efdcce2.

📒 Files selected for processing (9)
  • .github/workflows/ci.yml
  • docs/.nav.yml
  • docs/operators/README.md
  • docs/operators/attention.md
  • rl_engine/kernels/ops/pytorch/attention/kv_cache.py
  • rl_engine/kernels/ops/pytorch/attention/standard_attn.py
  • rl_engine/kernels/registry.py
  • tests/test_attention.py
  • tests/test_kv_cache_attention.py

Comment thread docs/operators/attention.md Resolved
Comment thread tests/test_attention.py Resolved
Comment thread tests/test_kv_cache_attention.py Resolved
@maxiaosong1124
maxiaosong1124 force-pushed the feat/ws1-kv-cache-attention-pytorch-op branch from efdcce2 to 3d466fe Compare June 28, 2026 08:46
maxiaosong1124 added a commit to maxiaosong1124/RL-Kernel that referenced this pull request Jun 28, 2026
…eview

forward_fp32 returns fp32 (not the input dtype), and the shipped padding
tolerance is atol=2e-6, not 1e-6. Aligns the operator contract doc with the
code (CodeRabbit).
…ference

Concat cache+new K/V then delegate to NativeAttentionOp so prefill and decode
share one reduction path. Register kv_cache_attention in the registry (cpu/cuda/
rocm) and add a standalone CPU-safe test suite + CI step.
@maxiaosong1124
maxiaosong1124 force-pushed the feat/ws1-kv-cache-attention-pytorch-op branch from 3d466fe to 4e6df2c Compare June 28, 2026 08:55

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

🧹 Nitpick comments (1)
tests/test_kv_cache_attention.py (1)

351-353: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Resolve Ruff B905 on the snapshot loop.

If the repo targets Python 3.10+, make this zip(..., strict=True) so mismatched tensor lists cannot truncate silently and the Ruff warning goes away.

Suggested change
-    for orig, snap in zip((q, k_cache, v_cache, k_new, v_new), snapshots):
+    for orig, snap in zip((q, k_cache, v_cache, k_new, v_new), snapshots, strict=True):
🤖 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 `@tests/test_kv_cache_attention.py` around lines 351 - 353, The snapshot
verification loop in test_kv_cache_attention.py uses zip without strict
checking, which triggers Ruff B905. Update the loop that iterates over q,
k_cache, v_cache, k_new, and v_new to use zip(..., strict=True) so the tensor
snapshot comparison cannot silently truncate and the warning is resolved.

Source: Linters/SAST tools

🤖 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 `@tests/test_kv_cache_attention.py`:
- Around line 351-353: The snapshot verification loop in
test_kv_cache_attention.py uses zip without strict checking, which triggers Ruff
B905. Update the loop that iterates over q, k_cache, v_cache, k_new, and v_new
to use zip(..., strict=True) so the tensor snapshot comparison cannot silently
truncate and the warning is resolved.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 8e271f6f-2062-47ad-bec9-0183469d462d

📥 Commits

Reviewing files that changed from the base of the PR and between 3d466fe and 4e6df2c.

📒 Files selected for processing (5)
  • .github/workflows/ci.yml
  • docs/operators/attention.md
  • rl_engine/kernels/ops/pytorch/attention/kv_cache.py
  • rl_engine/kernels/registry.py
  • tests/test_kv_cache_attention.py
✅ Files skipped from review due to trivial changes (1)
  • docs/operators/attention.md
🚧 Files skipped from review as they are similar to previous changes (3)
  • rl_engine/kernels/ops/pytorch/attention/kv_cache.py
  • .github/workflows/ci.yml
  • rl_engine/kernels/registry.py

…tract-aligned split-point test

- kv_cache.py: validate q holds exactly the new positions (Sq == S_new) in
  forward/forward_fp32; a mismatch would silently use the wrong causal offset.
- test: split-point test now decodes the suffix queries and compares to the
  matching slice of full prefill (near-equal, atol=2e-6, not bitwise -- the
  score matmul's M dim differs across splits); add a misaligned-q raises test.
@Flink-ddd

Copy link
Copy Markdown
Collaborator

@maxiaosong1124 please resolve the code conflicts first, Thank. cc @KJLdefeated PTAL

@maxiaosong1124

Copy link
Copy Markdown
Collaborator Author

@maxiaosong1124 please resolve the code conflicts first, Thank. cc @KJLdefeated PTAL

@Flink-ddd Resolved!

@Flink-ddd Flink-ddd left a comment

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.

LGTM, Thanks. also cc @KJLdefeated PTAL.

@KJLdefeated KJLdefeated left a comment

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.

LGTM. Thx!

@Flink-ddd
Flink-ddd merged commit 135940b into RL-Align:main Jul 6, 2026
5 checks passed
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