Skip to content

[WS2] Add CP-aware Attention contract and dispatch metadata #236

Open
Bsgg1 wants to merge 5 commits into
RL-Align:mainfrom
Bsgg1:feat/issue-235-attention-cp-contract
Open

[WS2] Add CP-aware Attention contract and dispatch metadata #236
Bsgg1 wants to merge 5 commits into
RL-Align:mainfrom
Bsgg1:feat/issue-235-attention-cp-contract

Conversation

@Bsgg1

@Bsgg1 Bsgg1 commented Jul 19, 2026

Copy link
Copy Markdown
Contributor

Summary

Implements PR 1 of #235 by introducing the explicit WS2 contract and dispatch metadata for CP-aware deterministic standard softmax Attention.

This PR defines how TP/CP sharding, deterministic (out, lse) reduction, packed sequences, and decode KV-cache identity must be described and
validated before a backend can be selected.

Changes

  • Add typed Attention contract objects:
    • AttentionContract
    • ShardingSpec
    • ReductionSpec
    • KVCacheSpec
    • AttentionBackendCapability
  • Validate Qwen3-style TP-local GQA head ownership.
  • Support contiguous and non-contiguous CP block metadata with stable global block ordering.
  • Require FP32 online-softmax/LSE merge semantics and final-write downcasting.
  • Validate packed sequence count, causal offsets, and logical batch size.
  • Validate decode KV-cache identity:
    • cache positions and sequence lengths
    • strictly increasing global token positions
    • page size and active page count
    • trailing block-table padding
    • duplicate page ownership
    • explicit read-only shared prefix pages
    • exclusive writable suffix pages
  • Add contract-aware KernelRegistry.get_attention_op() dispatch.
  • Reject undeclared or incompatible backends instead of silently falling back.
  • Record requested/actual backend and complete contract provenance.
  • Add WS2 Attention contract and dispatch documentation.

Behavior

A valid Qwen3-8B TP=4, CP=4, BF16 contract can now be represented and validated.

Existing WS1 Attention backends are intentionally rejected for strict WS2 requests because they do not yet export attention-domain LSE or implement
deterministic CP (out, lse) merge.

Legacy KernelRegistry.get_op() behavior is unchanged.

Validation

432 passed, 256 skipped

Also passed:

- Black
- isort
- flake8
- Ruff
- mkdocs build --strict

## Out of Scope

This PR does not implement:

- CP communication or collective execution
- deterministic CP (out, lse) merge
- fused CUDA/Triton/FlashAttention alignment
- distributed drift benchmarks
- Qwen3 TP=4/CP=4 runtime integration

Those are covered by later PRs in #235.

## Related

- Part of #235
- #83
- #108
- #111
- #207

<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
## Summary by CodeRabbit

- **New Features**
- Added contract-aware WS2 attention dispatch with strict tensor/context-parallel validation and deterministic semantics.
- Introduced a WS2 CP-aware attention contract model and capability-based backend selection with explicit rejection (no silent fallback) and recorded dispatch provenance.
- **Documentation**
- Documented WS2 CP-aware attention contract and updated attention dispatch behavior accordingly.
- **Tests**
- Added comprehensive unit tests for contract validation, backend compatibility, and packed-varlen/layout and KV-cache identity rules.
- **Chores**
- Extended CI to run the new attention contract test suite.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

@coderabbitai

coderabbitai Bot commented Jul 19, 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: beb3fcd3-5d6d-4e5c-946a-c7143eebeb75

📥 Commits

Reviewing files that changed from the base of the PR and between 0f1fd76 and 6d826df.

📒 Files selected for processing (3)
  • docs/design/ws2-cp-attention-contract.md
  • rl_engine/kernels/attention_contract.py
  • tests/test_attention_contract.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • docs/design/ws2-cp-attention-contract.md
  • rl_engine/kernels/attention_contract.py

📝 Walkthrough

Walkthrough

This PR introduces a typed WS2 CP-aware attention contract, validates sharding, reduction, causal, packed-varlen, and KV-cache metadata, adds capability-aware registry dispatch with provenance, and documents and tests strict backend rejection behavior.

Changes

WS2 attention contract and dispatch

Layer / File(s) Summary
Contract model and sharding semantics
docs/design/ws2-cp-attention-contract.md, rl_engine/kernels/attention_contract.py, tests/test_attention_contract.py
Defines typed TP/CP sharding and deterministic FP32 reduction contracts with validation, serialization, and tests for ownership, block ordering, offsets, and causal metadata.
KV-cache and backend capability validation
rl_engine/kernels/attention_contract.py, tests/test_attention_contract.py
Validates decode KV-cache identity, page mappings, prefix sharing, packed layouts, and backend capability compatibility.
Strict capability-aware registry dispatch
rl_engine/kernels/registry.py, tests/test_attention_contract.py
Adds get_attention_op(contract), registers capability descriptors, rejects incompatible or undeclared backends, enforces requested backend IDs, and records dispatch provenance.
Dispatch documentation and coverage
docs/design/runtime-dispatch.md, docs/operators/attention.md, docs/design/ws2-cp-attention-contract.md, .github/workflows/ci.yml
Documents contract-aware WS2 dispatch, deterministic reduction requirements, provenance, explicit rejection, unchanged legacy dispatch behavior, and CI execution of the new tests.

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

Possibly related issues

  • RL-Align/RL-Kernel#235 — The PR implements the issue’s WS2 CP-aware attention contract, validation, deterministic reduction metadata, and contract-aware dispatch.

Suggested reviewers: inaniloquentee, kjldefeated, bitborne, 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 clearly matches the main change: adding WS2 CP-aware attention contract and dispatch metadata.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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

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

🤖 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 `@rl_engine/kernels/attention_contract.py`:
- Around line 403-420: Rename the loop-bound active_blocks variables in the
sequence consistency loop and the exclusive_page_owners loop to distinct names,
updating their references within each loop. Preserve the existing list-based
active_blocks binding and all validation and ownership logic.
🪄 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: bb3bdb48-0e1e-4f2b-9707-bebdb8e47072

📥 Commits

Reviewing files that changed from the base of the PR and between 6df029a and b7ba64b.

📒 Files selected for processing (6)
  • docs/design/runtime-dispatch.md
  • docs/design/ws2-cp-attention-contract.md
  • docs/operators/attention.md
  • rl_engine/kernels/attention_contract.py
  • rl_engine/kernels/registry.py
  • tests/test_attention_contract.py

Comment thread rl_engine/kernels/attention_contract.py Outdated
@Bsgg1
Bsgg1 requested a review from bitborne as a code owner July 19, 2026 15:59
Comment thread rl_engine/kernels/attention_contract.py Outdated
object.__setattr__(self, "mode", _enum_value(AttentionMode, self.mode, "mode"))
object.__setattr__(self, "dtype", _enum_value(AttentionDType, self.dtype, "dtype"))
batch_size = _positive_int(self.batch_size, "batch_size")
_positive_int(self.query_sequence_length, "query_sequence_length")

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.

Small contract gap: for prefill, should we reject cases where query_sequence_length doesn’t match sharding.local_sequence_length? Right now an inconsistent contract like query_sequence_length=2048 with local_sequence_length=1024 can still be constructed.

global_token_positions = _integer_tuple(
self.global_token_positions, "global_token_positions"
)
if not cache_positions or any(position < 0 for position in cache_positions):

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.

Another small gap: cache_positions is only checked for shape/non-negativity, but not against global_token_positions. For decode identity, we probably want to reject cases like cache_positions=(999,) when the declared tokens are only 0..16.

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