← Back to Pull requests

Fix small-angle quaternion gradients #2021

Open
efegokdemir opened this pull request with 56 lines diff across 3 files
View on GitHub
efegokdemir efegokdemir commented on Oct 01, 2026 17:34 UTC
Author

What problem are you trying to solve?

Closes #2020. The adjoint of wp.quat_to_axis_angle() computes Jacobian terms with 1 / |q.xyz|^3. For sufficiently small rotations, that intermediate overflows in float16/float32; multiplying the resulting infinity by zero produces NaN gradients even though the angle gradient is finite.

What does this change?

Compute the same Jacobian using the normalized quaternion vector and 1 / |q.xyz|, avoiding the overflowing cubic inverse while preserving the existing behavior for ordinary rotations. Add a focused small-rotation regression and a changelog fragment.

Existing pull requests

  • I searched open pull requests for duplicate or overlapping work.

  • Related pull requests: None found.
  • Validation

  • Regression validation: The issue reproducer failed on current main with NaN gradients for float16 at 0.03 rad and float32 at 1e-13 rad. After the fix, the existing quaternion gradient suite passes and checks the analytic [2, 0, 0, -angle] gradient for float16, float32, and float64.

  • NVIDIA GPU: Not tested; this checkout is an Apple M2 CPU-only build with CUDA disabled.

  • Other validation: uv run warp/tests/test_quat.py -q (85 passed); uvx pre-commit run --files warp/native/quat.h warp/tests/test_quat.py changelog/2020.fixed.md (passed); git diff --check (passed).
  • Checklist

  • I have read and followed the Contributing Guidelines.

  • This pull request does not bundle unrelated changes unless a maintainer agreed to the broader scope.

  • My branch is up to date with main and contains one commit, unless a maintainer agreed to keep the change as multiple commits.

  • I included the required changelog fragment.
  • <!-- This is an auto-generated comment: release notes by coderabbit.ai -->

    Summary by CodeRabbit

    Bug Fixes
    Improved gradient calculations when converting quaternions to axis-angle for small rotations, preventing NaN gradients and providing more reliable axis and angle gradients across supported numeric types. Small-angle gradient behavior is now covered by additional checks.
    <!-- end of auto-generated comment: release notes by coderabbit.ai -->

    Diff: 56 lines (+43 / -13) across 3 files Reviewer: efegokdemir Review duration: 93039m
    All Vouch review confidence checks passed
    Residual risk 0.09 = Change Risk (0.51) × (1 − Review Confidence (0.83)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.51 · 56 lines diff across 3 files
    0.51
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.94 · 5 substantive comment(s)
    0.94
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    82%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.242
    Self Review self_review
    0.140
    Real PR Conversation Timeline
    6 items
    copy-pr-bot[bot] copy-pr-bot[bot] commented on Oct 01, 2026 17:34 UTC
    Bot

    This pull request requires additional validation before any workflows can run on NVIDIA's runners.

    Pull request vetters can view their responsibilities here.

    Contributors can view more details about this message here.

    coderabbitai[bot] coderabbitai[bot] commented on Oct 01, 2026 17:34 UTC
    Bot

    <!-- This is an auto-generated comment: summarize by coderabbit.ai -->
    <!-- review_stack_entry_start -->

    <a href="https://app.coderabbit.ai/change-stack/NVIDIA/warp/pull/2021?cs_source=review_comment"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=2" alt="Review in Change Stack →" width="220" height="32"></a>

    Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

    <!-- review_stack_entry_end -->
    <details>
    <summary>🧰 Additional context used</summary>

    <details>
    <summary>📚 Code guidelines (1)</summary>

    AGENTS.md — auto-discovered
    

    </details>

    </details>
    <!-- recent_review_start -->

    No actionable comments were generated in the recent review. 🎉

    <details>
    <summary>ℹ️ Recent review info</summary>

    <details>
    <summary>⚙️ Run configuration</summary>

    Configuration used: Repository: NVIDIA/warp/.coderabbit.yml

    Review profile: CHILL

    Plan: Enterprise

    Run ID: 54ba89e6-d085-4e78-b05a-2a8c5c5b4e8c

    </details>

    <details>
    <summary>📥 Commits</summary>

    Reviewing files that changed from the base of the PR and between 2edb7567a6ebed22bc1c7d6b7fe0dfd2ef3f954f and a7926e17a88ec33e2466c81ad85104a3a94652c5.

    </details>

    <details>
    <summary>📒 Files selected for processing (1)</summary>

  • warp/tests/test_quat.py
  • </details>

    Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 9 remain after this review.

    </details>

    ---

    <!-- recent_review_end -->
    <!-- walkthrough_start -->

    <details>
    <summary>📝 Walkthrough</summary>

    Walkthrough

    The quaternion-to-axis-angle adjoint now computes axis-derivative coefficients from normalized imaginary quaternion components, instead of using inverse-cube scaling. A regression test checks small-angle gradients, and the changelog records the fix.

    Changes

    Quaternion Gradient

    |Layer / File(s)|Summary|
    |---|---|
    |Adjoint calculation and regression test <br> warp/native/quat.h, warp/tests/test_quat.py, changelog/2020.fixed.md|The adjoint calculates axis derivatives from normalized imaginary components, using a flip / l scale. The test checks small-angle gradients for float16, float32, and float64. The changelog records the NaN-gradient fix.|

    <!-- change_assessment_start -->
    Priority: ➖ Normal

    Estimated code review effort: 2 (Simple) | ~10 minutes

    <!-- change_assessment_commit:"a7926e17a88ec33e2466c81ad85104a3a94652c5" -->
    Change: Bug fix · Severity of issue fixed: Medium
    <!-- change_assessment_end -->

    Suggested reviewers: shi-eric

    </details>

    <!-- walkthrough_end -->
    <!-- final_review_risk_start -->
    Merge Risk: _⚪ Minimal_ · up to a7926
    <!-- final_review_risk_coverage:{"sourceCommitId":"a7926e17a88ec33e2466c81ad85104a3a94652c5","coveredCommitId":"a7926e17a88ec33e2466c81ad85104a3a94652c5","kind":"reviewed"} -->

    The change addresses the reported small-angle gradient issue, with no newly introduced material problem established. Merge after normal checks.
    <!-- final_review_risk_end -->
    <!-- pre_merge_checks_walkthrough_start -->

    <details>
    <summary>🚥 Pre-merge checks | ✅ 4 | ❌ 1</summary>

    ❌ Failed checks (1 warning)

    | Check name | Status | Explanation | Resolution |
    | :----------------: | :--------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- |
    | Docstring Coverage | ⚠️ Warning | Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 1 functions across 2 files. | Write docstrings for the functions missing them to satisfy the coverage threshold. |

    <details>
    <summary>✅ Passed checks (4 passed)</summary>

    | Check name | Status | Explanation |
    | :------------------------: | :------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
    | Description Check | ✅ Passed | Check skipped - CodeRabbit’s high-level summary is enabled. |
    | Title check | ✅ Passed | The title, "Fix small-angle quaternion gradients," directly and concisely describes the main change to wp.quat_to_axis_angle() gradients. |
    | Linked Issues check | ✅ Passed | Issue #2020 requires finite small-angle gradients for wp.quat_to_axis_angle(). warp/native/quat.h now uses the normalized quaternion vector and flip / l, so it avoids the overflowing 1 / l^3 i… |
    | Out of Scope Changes check | ✅ Passed | The changes are limited to the Issue #2020 implementation, regression tests, and a related changelog entry. No unrelated implementation or test changes are identified. |

    </details>

    </details>

    <!-- pre_merge_checks_walkthrough_end -->

  • <!-- {"checkboxId":"585bb3f6-faf5-4dbf-96d2-74e382adf19a"} --> Fix all pre-merge checks with AI

  • <!-- finishing_touch_checkbox_start -->

    <details>
    <summary>✨ Finishing Touches</summary>

    <details open>
    <summary>🧪 Generate unit tests (beta)</summary>

  • <!-- {"checkboxId": "f47ac10b-58cc-4372-a567-0e02b2c3d479", "radioGroupId": "utg-output-choice-group-unknown_comment_id"} --> Create a new PR
  • </details>

    </details>

    <!-- finishing_touch_checkbox_end -->

    <!-- autopilot:start -->

  • <!-- {"checkboxId":"2708ad07-9f24-4260-9c11-7dc76a49f2e3"} --> <strong title="Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts">Autopilot</strong> · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
  • Autopilot is currently an internal CodeRabbit preview.

    <!-- autopilot:end -->
    <!-- tips_start -->

    ---

    <sub>Comment @coderabbitai help to get the list of available commands.</sub>

    <!-- tips_end -->

    greptile-apps[bot] greptile-apps[bot] commented on Oct 01, 2026 17:38 UTC
    Bot

    <!-- greptile_summary -->

    <h2><a href="https://app.greptile.com/api/retrigger?id=72951426"><picture><source media="(prefers-color-scheme: dark)" srcset="https://greptile-static-assets.s3.amazonaws.com/badges/RetriggerDark.svg?v=2"><source media="(prefers-color-scheme: light)" srcset="https://greptile-static-assets.s3.amazonaws.com/badges/Retrigger.svg?v=2"><img alt="Retrigger" src="https://greptile-static-assets.s3.amazonaws.com/badges/Retrigger.svg?v=2" align="right"></picture></a>Confidence Score: 5/5</h2>

    [Medium risk] Fixes numerical stability in quaternion gradient computation\.

    The PR appears safe to merge; no outstanding finding or new actionable issue was identified.

    <h3>Summary</h3>

    The PR rewrites the quaternion axis-angle adjoint to avoid an overflowing cubic inverse at small angles and adds regression coverage for axis and angle gradients.

    <!-- greptile_confidence_score:5 -->

    <sub>Reviews (2) · Last reviewed commit: "test: cover small-angle quaternion axis ..."</sub>

    greptile-apps[bot] greptile-apps[bot] commented on code on Oct 01, 2026 17:38 UTC
    Code Review
    warp/tests/test_quat.py:1
    @@ -1557,6 +1557,28 @@ def compute_gradients(arr, kernel, dim, index):
         assert_np_equal(edge_gradients_z, edge_gradients_z_auto, tol=tol)
         assert_np_equal(edge_gradients_w, edge_gradients_w_auto, tol=tol)
     
    +    small_angle = {np.float16: 3.0e-2, np.float32: 1.0e-13, np.float64: 1.0e-13}[dtype]
    +    small_quat = wp.array(
    +        [
    +            (
    +                np.sin(0.5 * small_angle),
    +                0.0,
    +                0.0,
    +                np.cos(0.5 * small_angle),
    +            )
    +        ],
    +        dtype=quat_type,
    +        device=device,
    +        requires_grad=True,
    +    )
    +    _, small_gradients = compute_gradients(small_quat, quat_to_axis_angle_kernel, 1, 3)

    <a href="#"><img alt="P2" src="https://greptile-static-assets.s3.amazonaws.com/badges/p2.svg?v=9" align="top"></a> Axis gradients remain unchecked

    This assertion selects coordinate 3, the angle. It catches NaNs that leak from the axis calculations, but it cannot tell whether the rewritten axis derivatives return the correct finite values at small angles. Please also assert an axis-coordinate gradient here; otherwise a finite but incorrect axis Jacobian could pass the regression test.

    Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

    efegokdemir efegokdemir commented on code on Oct 01, 2026 17:41 UTC
    Code Review
    warp/tests/test_quat.py:1
    @@ -1557,6 +1557,28 @@ def compute_gradients(arr, kernel, dim, index):
         assert_np_equal(edge_gradients_z, edge_gradients_z_auto, tol=tol)
         assert_np_equal(edge_gradients_w, edge_gradients_w_auto, tol=tol)
     
    +    small_angle = {np.float16: 3.0e-2, np.float32: 1.0e-13, np.float64: 1.0e-13}[dtype]
    +    small_quat = wp.array(
    +        [
    +            (
    +                np.sin(0.5 * small_angle),
    +                0.0,
    +                0.0,
    +                np.cos(0.5 * small_angle),
    +            )
    +        ],
    +        dtype=quat_type,
    +        device=device,
    +        requires_grad=True,
    +    )
    +    _, small_gradients = compute_gradients(small_quat, quat_to_axis_angle_kernel, 1, 3)

    Added an axis-coordinate regression assertion for the same small-angle quaternion cases. It now checks the Y-axis output gradient against the expected normalized-axis Jacobian, in addition to the existing angle gradient assertion. Focused and full quaternion tests pass on the CPU-only macOS build.

    Reviewers
    Assignees
    efegokdemir efegokdemir
    Labels
    risk: low confidence: 82.9% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 51.1% (MEDIUM) · Higher = larger blast radius
    51.1%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 82.9% · Lower = rushed or shallow review
    82.9%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 8.7% · Safe to merge
    8.7%
    Repository