Skip to content

test(ws1): add elementwise and RoPE invariance audit - #164

Closed
haoruilee wants to merge 1 commit into
RL-Align:mainfrom
haoruilee:feat/ws1-elementwise-rope-audit
Closed

haoruilee wants to merge 1 commit into
RL-Align:mainfrom
haoruilee:feat/ws1-elementwise-rope-audit

Conversation

@haoruilee

@haoruilee haoruilee commented Jun 21, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • add a reusable WS1 batch-invariance sweep helper in rl_engine.testing.forward_invariance
  • add a pure-PyTorch RoPE reference helper with deterministic table lookup, strict position-id validation, and explicit dtype/device checks
  • validate RoPE cache construction rejects non-floating dtypes before trig tables can be silently quantized
  • add batch-invariance tests for audited Transformer pointwise ops: SiLU, GELU, residual add, scalar scaling, bias add, mask fill, and dtype casts
  • use a tight GELU tolerance (atol=1e-6, rtol=1e-6) for CPU libm/vector paths while keeping the other pass-through ops and RoPE bitwise by default
  • add RoPE bitwise invariance coverage for fixed positions, target batch position changes, unrelated noise rows, padding, and packed-sequence position reset
  • document the elementwise/RoPE audit verdicts, standard sweep, and verification commands
  • wire tests/test_forward_invariance.py into the normal CI unit-test job as its own narrow step

Closes #149

Notes

No audited op showed reduction-style drift. This PR does not add a production RoPE kernel or change runtime dispatch; it adds the reference contract, audit, CI coverage, and tests required to close the pass-through audit.

Validation

  • python3 -m pytest rl_engine/tests/test_dispatch.py -v && python3 -m pytest tests/test_forward_invariance.py -v -> 3 passed; 44 passed, 14 skipped
  • /tmp/rl-kernel-cpu-ci-venv/bin/python -m pytest tests/test_forward_invariance.py -q with torch-2.12.1+cpu -> 17 passed, 15 skipped
  • python3 -m pytest tests/test_forward_invariance.py tests/test_reference_ops.py -q -> 51 passed, 14 skipped
  • python3 -m pytest rl_engine/tests/test_dispatch.py tests/test_op_accuracy.py tests/test_grpo_single_gpu_example.py tests/test_vllm_rollout_sampler.py -q -> 35 passed
  • /tmp/rl-kernel-test-venv/bin/python -m pytest tests/ rl_engine/tests/ -q -> 205 passed, 15 skipped
  • uvx mypy --ignore-missing-imports rl_engine/ -> passed
  • uvx pre-commit run --files .github/workflows/ci.yml docs/design/batch-invariant-elementwise-rope.md rl_engine/testing/__init__.py rl_engine/testing/forward_invariance.py tests/test_forward_invariance.py -> passed
  • uvx ruff check rl_engine/testing/forward_invariance.py rl_engine/testing/__init__.py tests/test_forward_invariance.py -> passed
  • python3 -m compileall rl_engine/testing tests/test_forward_invariance.py -> passed
  • git diff --check -> passed
  • /tmp/rl-kernel-docs-venv/bin/mkdocs build --strict -f mkdocs.yaml -> passed

Summary by CodeRabbit

  • Tests
    • Added a new forward-invariance test suite covering elementwise operations and RoPE, checking bitwise-identical results when a target sample is embedded in larger batches across CPU/CUDA and float32/float16/bfloat16, plus negative-case validation.
  • Documentation
    • Added the “Batch-Invariant Elementwise and RoPE Audit” guide, detailing the invariance contracts, RoPE scenarios, and how to run the focused and expanded checks.
  • Chores
    • Updated CI to run the new forward-invariance tests as part of unit testing.

@coderabbitai

coderabbitai Bot commented Jun 21, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@haoruilee, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 7 minutes and 26 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more credits in the billing tab to continue.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based credits.

🚦 How do rate limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan refill rate.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, the refill rate gradually slows as usage increases. The highest same-day bursts are limited more strictly.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 486d06fc-fae7-4f32-b70e-26af6c76d91a

📥 Commits

Reviewing files that changed from the base of the PR and between 075a37f and a5d5d5b.

📒 Files selected for processing (5)
  • .github/workflows/ci.yml
  • docs/design/batch-invariant-elementwise-rope.md
  • rl_engine/testing/__init__.py
  • rl_engine/testing/forward_invariance.py
  • tests/test_forward_invariance.py
📝 Walkthrough

Walkthrough

Adds a batch-invariance testing framework (rl_engine/testing/forward_invariance.py) with a BatchInvariantConfig dataclass, assert_batch_invariant_across_configs, and RoPE reference utilities (rotate_half, build_rope_cache, apply_rope_reference). A comprehensive test suite (tests/test_forward_invariance.py) covers elementwise ops, dtype casts, and RoPE scenarios. The package exports are extended, CI is updated to run the new tests, and a design doc is added.

Changes

Batch-Invariant Elementwise & RoPE Audit

Layer / File(s) Summary
BatchInvariantConfig and assertion framework
rl_engine/testing/forward_invariance.py
BatchInvariantConfig dataclass with field validation, default sweep configs, BatchInvariantOp and BatchInputFactory type aliases, and assert_batch_invariant_across_configs with internal _select_batch_output, _assert_outputs_match, _tensor_matches, and _first_tensor helpers.
RoPE reference implementation
rl_engine/testing/forward_invariance.py
rotate_half (half-dimension swap-and-negate), build_rope_cache (deterministic cos/sin lookup tables with parameter validation), apply_rope_reference (position-id-indexed application), and _validate_rope_inputs (shape/dtype/device/bounds enforcement).
Elementwise test infrastructure and utilities
tests/test_forward_invariance.py
Frozen _ElementwiseCase dataclass and _ELEMENTWISE_CASES tuple enumerating six pointwise operations. Device/dtype gating utilities for CPU/CUDA with precision-support rules, and batch-embedding helpers to construct batched inputs with targets embedded at specified indices.
Elementwise op and dtype cast batch-invariance tests
tests/test_forward_invariance.py
test_forward_path_elementwise_ops_are_batch_invariant parameterized over device, dtype, and each elementwise case to assert batch invariance via assert_batch_invariant_across_configs. Also tests dtype-cast batch invariance from float32 to mixed-precision targets.
RoPE behavioral tests
tests/test_forward_invariance.py
Tests for fixed-position batch invariance, padding position-id isolation, and packed-sequence position reset. Confirms rotated Q/K remain bitwise-identical when embedding a target into larger batches with unrelated noise.
RoPE and helper validation tests
tests/test_forward_invariance.py
Validates rejection of invalid build_rope_cache parameters, invalid apply_rope_reference inputs, rotate_half odd-dimension rejection, and CUDA device-mismatch detection with expected error-message patterns.
Package exports and CI integration
rl_engine/testing/__init__.py, .github/workflows/ci.yml
__init__.py imports and re-exports all six new forward_invariance symbols via __all__; CI unit-test job adds a second pytest command for tests/test_forward_invariance.py.
Audit design documentation
docs/design/batch-invariant-elementwise-rope.md
Design doc covering audit scope, excluded ops, the tested bitwise contract, elementwise and RoPE scenario matrix, verification commands, and explicitly stated known boundaries.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related issues

  • #150 — This PR builds the foundational batch-invariance assertion helpers and RoPE reference implementation that issue #150's chain integration tests depend on.

Poem

🐇 A bunny checked each tensor's row,
Through batches large and batches small,
Did RoPE twist the same below?
torch.equal confirmed them all!
No drift, no shift — bit-perfect so,
The audit doc seals the deal with a bow. 🎉

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 13.33% 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
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed Title accurately describes the main change: adding batch-invariance audit tests for elementwise operations and RoPE.
Linked Issues check ✅ Passed PR comprehensively implements all coding requirements from #149: reusable batch-invariance infrastructure, RoPE reference with validation, elementwise tests, RoPE invariance tests including position handling, CI integration, and comprehensive documentation.
Out of Scope Changes check ✅ Passed All changes directly support the batch-invariance audit scope: test infrastructure, RoPE reference, elementwise/RoPE tests, documentation, and CI wiring. No unrelated changes detected.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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 and usage tips.

@haoruilee
haoruilee force-pushed the feat/ws1-elementwise-rope-audit branch from dc1434f to b641e2f Compare June 21, 2026 11:37
@haoruilee
haoruilee marked this pull request as ready for review June 21, 2026 11:38

@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

Caution

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

⚠️ Outside diff range comments (1)
.github/workflows/ci.yml (1)

34-66: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add explicit least-privilege permissions to the workflow/job.

This workflow relies on default token permissions; that’s broader than necessary for test-only execution and weakens CI hardening.

Suggested fix
 name: CI
+permissions:
+  contents: read
@@
 jobs:
   unit-tests:
+    permissions:
+      contents: read
     needs: linting
     runs-on: ubuntu-latest
🤖 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 @.github/workflows/ci.yml around lines 34 - 66, The unit-tests job currently
relies on default token permissions which are overly broad for a test-only CI
execution. Add an explicit permissions block to the unit-tests job that grants
only the minimal required permissions. For this test-only workflow that checks
out code and runs tests, add a permissions configuration that specifies
contents: read to allow repository checkout, and explicitly deny or omit any
other permissions that are not required for the job's functionality.

Source: Linters/SAST tools

🧹 Nitpick comments (1)
docs/design/batch-invariant-elementwise-rope.md (1)

3-3: 💤 Low value

Minor style improvement: rephrase wordy preposition.

The phrase "with respect to" on line 3 can be simplified. Consider "relative to", "across", or "per" instead to improve clarity.

💬 Suggested rephrase
-Issue `#149` audits the forward-path operations that should be pass-through with respect to batch configuration.
+Issue `#149` audits the forward-path operations that should be pass-through across batch configuration.
🤖 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 `@docs/design/batch-invariant-elementwise-rope.md` at line 3, The phrase "with
respect to" in the document is wordy and impacts clarity. Find and replace this
phrase with a more concise alternative such as "relative to", "across", or "per"
depending on the context of the sentence to improve readability.

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.

Inline comments:
In `@rl_engine/testing/forward_invariance.py`:
- Around line 121-139: The build_rope_cache function lacks validation for the
dtype parameter, which can lead to silent corruption of trigonometric values if
non-floating types like torch.int* or torch.bool are passed. Add a dtype
validation check in the function alongside the existing parameter validations
(similar to the checks for max_position, head_dim, and base) to ensure dtype is
a floating-point type. Raise a ValueError with an appropriate message if a
non-float dtype is provided, preventing the function from returning incorrectly
quantized cosine and sine values that would corrupt apply_rope_reference
results.

---

Outside diff comments:
In @.github/workflows/ci.yml:
- Around line 34-66: The unit-tests job currently relies on default token
permissions which are overly broad for a test-only CI execution. Add an explicit
permissions block to the unit-tests job that grants only the minimal required
permissions. For this test-only workflow that checks out code and runs tests,
add a permissions configuration that specifies contents: read to allow
repository checkout, and explicitly deny or omit any other permissions that are
not required for the job's functionality.

---

Nitpick comments:
In `@docs/design/batch-invariant-elementwise-rope.md`:
- Line 3: The phrase "with respect to" in the document is wordy and impacts
clarity. Find and replace this phrase with a more concise alternative such as
"relative to", "across", or "per" depending on the context of the sentence to
improve readability.
🪄 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: 3e31b468-85fc-4d3a-9900-05c2e927ee6b

📥 Commits

Reviewing files that changed from the base of the PR and between d6db6bf and b641e2f.

📒 Files selected for processing (5)
  • .github/workflows/ci.yml
  • docs/design/batch-invariant-elementwise-rope.md
  • rl_engine/testing/__init__.py
  • rl_engine/testing/forward_invariance.py
  • tests/test_forward_invariance.py

Comment thread rl_engine/testing/forward_invariance.py
@haoruilee
haoruilee force-pushed the feat/ws1-elementwise-rope-audit branch from b641e2f to 0466ac1 Compare June 21, 2026 11:53

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

Caution

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

⚠️ Outside diff range comments (1)
.github/workflows/ci.yml (1)

34-66: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Scope the job token explicitly.

This job does not declare any permissions: block, so it inherits the workflow default scope. Add a read-only contents permission (or tighter) to keep the test job from running with broader token access than it needs.

🤖 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 @.github/workflows/ci.yml around lines 34 - 66, The unit-tests job lacks an
explicit permissions block, which causes it to inherit the workflow default
scope and run with broader token access than necessary. Add a permissions block
to the unit-tests job definition that explicitly grants read-only access to the
contents permission scope, ensuring the job has the minimum required token
access for its operations.

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.

Outside diff comments:
In @.github/workflows/ci.yml:
- Around line 34-66: The unit-tests job lacks an explicit permissions block,
which causes it to inherit the workflow default scope and run with broader token
access than necessary. Add a permissions block to the unit-tests job definition
that explicitly grants read-only access to the contents permission scope,
ensuring the job has the minimum required token access for its operations.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 8ac135da-448f-4907-b5a0-215a9e1b95e1

📥 Commits

Reviewing files that changed from the base of the PR and between b641e2f and 0466ac1.

📒 Files selected for processing (5)
  • .github/workflows/ci.yml
  • docs/design/batch-invariant-elementwise-rope.md
  • rl_engine/testing/__init__.py
  • rl_engine/testing/forward_invariance.py
  • tests/test_forward_invariance.py
🚧 Files skipped from review as they are similar to previous changes (3)
  • rl_engine/testing/init.py
  • tests/test_forward_invariance.py
  • rl_engine/testing/forward_invariance.py

@haoruilee
haoruilee force-pushed the feat/ws1-elementwise-rope-audit branch 2 times, most recently from 195d23e to 075a37f Compare June 21, 2026 12:17

@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)
docs/design/batch-invariant-elementwise-rope.md (1)

3-4: 💤 Low value

Minor wording: Simplify "with respect to".

The phrase "with respect to batch configuration" is correct but can be tightened. Consider alternatives like "for batch configuration", "given batch configuration", or restructuring to "batch-configuration-dependent" for brevity.

🤖 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 `@docs/design/batch-invariant-elementwise-rope.md` around lines 3 - 4, The
phrase "with respect to batch configuration" in the opening paragraph of the
document is wordy and can be simplified. Replace "with respect to batch
configuration" with a more concise alternative such as "for batch
configuration", "given batch configuration", or restructure the sentence to use
"batch-configuration-dependent" to improve clarity and brevity while maintaining
the intended meaning about operations being pass-through for different batch
configurations.

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 `@docs/design/batch-invariant-elementwise-rope.md`:
- Around line 3-4: The phrase "with respect to batch configuration" in the
opening paragraph of the document is wordy and can be simplified. Replace "with
respect to batch configuration" with a more concise alternative such as "for
batch configuration", "given batch configuration", or restructure the sentence
to use "batch-configuration-dependent" to improve clarity and brevity while
maintaining the intended meaning about operations being pass-through for
different batch configurations.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 8fb1da7a-992c-479e-b6fb-f4a6dcfb777e

📥 Commits

Reviewing files that changed from the base of the PR and between 0466ac1 and 075a37f.

📒 Files selected for processing (5)
  • .github/workflows/ci.yml
  • docs/design/batch-invariant-elementwise-rope.md
  • rl_engine/testing/__init__.py
  • rl_engine/testing/forward_invariance.py
  • tests/test_forward_invariance.py
✅ Files skipped from review due to trivial changes (1)
  • rl_engine/testing/init.py
🚧 Files skipped from review as they are similar to previous changes (3)
  • .github/workflows/ci.yml
  • tests/test_forward_invariance.py
  • rl_engine/testing/forward_invariance.py

@haoruilee
haoruilee force-pushed the feat/ws1-elementwise-rope-audit branch from 075a37f to a5d5d5b Compare June 21, 2026 12:30
@Flink-ddd
Flink-ddd requested a review from frank-2077 June 21, 2026 12:44
@Flink-ddd

Copy link
Copy Markdown
Collaborator

cc @a-kaa PTAL

@frank-2077

Copy link
Copy Markdown
Collaborator

Hi, the WS1 be assigned to me @maxiaosong1124. I am gladed to your contribution but we have some contact for the code. We want the interfaces are aligned. PLS contact with wechat(yye6964434), we haved finished some ops(actually include rope). It is best to avoid doing repetitive work.
ISSUE_108_INTERFACES(1).md

@haoruilee

Copy link
Copy Markdown
Contributor Author

Hi @a-kaa

Sorry for the mix up. The issue actually still shows as unassigned on my end, so I didn't realize you were already working on WS1.

I agree we should align interfaces to avoid duplicate work. However, I keep my WeChat mostly for personal use, so I'd much prefer we discuss things here on GitHub. But if you think it's better to discuses it in person I'd like to do so.

@frank-2077

Copy link
Copy Markdown
Collaborator

@haoruilee I apologize for causing any unnecessary misunderstanding. Actually, staring with WS issues have already been taken. You ca take on other tasks expect the five workstreams of the P0.3+ roadmap.

@haoruilee

Copy link
Copy Markdown
Contributor Author

Hi @a-kaa,

I got it and feel free to close this PR if it's no longer needed. Sorry for my misunderstanding.

@frank-2077

Copy link
Copy Markdown
Collaborator

@haoruilee We will have some issues(not WS issue) in next few days and welcome to contribute.

@frank-2077 frank-2077 closed this Jun 22, 2026
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.

[WS1] Batch-invariant elementwise / RoPE pass-through audit

3 participants