← Back to Pull requests

[libcu++] Fix cuda::std::ilogb and logb for subnormal arguments #11799

Open
Arthur031221 opened this pull request with 101 lines diff across 4 files
View on GitHub
Arthur031221 Arthur031221 commented on Oct 01, 2026 16:33 UTC
Author

Description

cuda::std::ilogb and cuda::std::logb return the wrong exponent for subnormal arguments, so code that uses them to rescale or normalise denormals gets wrong results:

#include <cuda/std/cmath>
#include <cstdio>
int main()
{
  float f  = 1.4e-45f; // numeric_limits<float>::denorm_min()
  double d = 4.9e-324; // numeric_limits<double>::denorm_min()
  printf("ilogb(f) = %d, std = %d\n", cuda::std::ilogb(f), std::ilogb(f));
  printf("logb(f)  = %g, std = %g\n", cuda::std::logb(f), std::logb(f));
  printf("ilogb(d) = %d, std = %d\n", cuda::std::ilogb(d), std::ilogb(d));
}

Built with g++ -std=c++20 -Ilibcudacxx/include on the parent commit this prints:

ilogb(f) = -2147483648, std = -149
logb(f)  = -127, std = -149
ilogb(d) = -2147483648, std = -1074

and with this change:

ilogb(f) = -149, std = -149
logb(f)  = -149, std = -149
ilogb(d) = -1074, std = -1074

Both functions read the exponent from the biased exponent field through __fp_get_exp. That field is zero for every subnormal, so the result is the exponent of the smallest normal number minus one, and ilogb then mapped it to INT_MIN through the __exp < __fp_exp_min_v branch. The new helper __fp_get_exp_normalized takes the exponent from the highest set mantissa bit when the biased exponent is zero and the mantissa is not, as exp_min + bit_width(mantissa) - digits. This also covers the x87 long double format, where the integer bit is explicit. __fp_get_exp itself is unchanged, so its existing test is unaffected.

The fallback in logb for compilers without a constexpr bit_cast looped only while |x| >= 2, so it returned 0 for every value below 1, not only for subnormals. It now scales up as well.

Testing

New test logb_subnormal.pass.cpp checks denorm_min, 3 * denorm_min, the largest subnormal and min() for float, double and long double, with both signs, at run time and in a static_assert.

Run locally with gcc 13.3 (host only, -std=c++20 -Ilibcudacxx/include -Ilibcudacxx/test/support): the new test passes, get_exp.pass.cpp passes, and logarithms.pass.cpp passes with its __global__ kernel removed. It also passes with _CCCL_HAS_CONSTEXPR_BIT_CAST() forced to 0, which exercises the fallback. With the headers from the parent commit the new test fails at ilogb(smallest) == min_exp. Not run: nvcc, clang, MSVC, __half, __nv_bfloat16 and the fp8/fp6/fp4 formats (the helper is generic over the format description and does not special-case them).

Checklist


  • New or existing tests cover these changes.

  • The documentation is up to date with these changes.
  • Diff: 101 lines (+91 / -10) across 4 files Reviewer: fbusato Review duration: 19692m
    All Vouch review confidence checks passed
    Residual risk 0.03 = Change Risk (0.35) × (1 − Review Confidence (0.90)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.35 · 101 lines diff across 4 files
    0.35
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.88 · 5 substantive comment(s)
    0.88
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    90%
    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.277
    Real PR Conversation Timeline
    14 items
    copy-pr-bot[bot] copy-pr-bot[bot] commented on Oct 01, 2026 16:33 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 16:35 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/cccl/pull/11799?scope=ghh_OusAJGA4HG8ljoOV0wJvVx8NmnZIjc2DdjmxOu0xZWA&amp;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>

    <!-- review_stack_entry_end -->
    <!-- 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/cccl/.coderabbit.yaml

  • Review profile: CHILL

  • Plan: Enterprise

  • Run ID: af30f5a1-dc51-45ff-94d9-f3dc889e506e
  • <hr>

    </details>

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

    Reviewing files that changed from the base of the PR and between 0577044fc3b0b475eabcb80645fb2320e7017b29 and 4fcdfdde2e950bc01ce1745a1f1015296a303ac3.

    <hr>

    </details>

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

    libcudacxx/include/cuda/std/__cmath/logarithms.h
    libcudacxx/include/cuda/std/__floating_point/decompose.h
    libcudacxx/test/libcudacxx/libcxx/numerics/floating.point/decompose/get_exp.pass.cpp

    <hr>

    </details>

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

    <hr>

    </details>

    ---

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

    <details>
    <summary>📝 Summary</summary>

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

    Summary by CodeRabbit

    Bug Fixes
    Corrected ilogb and logb results for subnormal floating-point values, including the smallest positive and negative values and values near the normal range. Smallest normal values retain their expected exponents.
    Corrected exponent results for subnormal values in floating-point decomposition.

    <!-- end of auto-generated comment: release notes by coderabbit.ai -->

    Walkthrough

    ilogb and logb now calculate exponents for subnormal values. Tests cover selected positive and negative subnormals and the smallest normal across supported floating-point types.

    Changes

    Subnormal exponent handling

    |Layer / File(s)|Summary|
    |:---|:---|
    |Normalize subnormal exponents <br> libcudacxx/include/cuda/std/__floating_point/decompose.h, libcudacxx/test/libcudacxx/libcxx/numerics/floating.point/decompose/get_exp.pass.cpp|__fp_get_exp derives a subnormal’s exponent from its highest set mantissa bit. The denormal exponent test now expects that value.|
    |Handle subnormal logarithm inputs <br> libcudacxx/include/cuda/std/__cmath/logarithms.h, libcudacxx/test/libcudacxx/std/numerics/c.math/logb_subnormal.pass.cpp|ilogb returns extracted exponents below the format’s minimum exponent. The native logb fallback uses a signed exponent counter and scales values below 1. Tests check selected subnormal values and the smallest normal at runtime, and at compile time when constexpr bit-cast support is available.|

    Suggested reviewers: miscco

    <hr>

    </details>

    <!-- walkthrough_end -->
    <!-- change_assessment_start -->
    Priority: ⬇️ Low

    <!-- change_assessment_commit:"4fcdfdde2e950bc01ce1745a1f1015296a303ac3" -->
    Change: Bug fix
    <!-- change_assessment_end -->
    <!-- final_review_risk_start -->
    Merge Risk: ⚪ Minimal · up to 4fcdf
    <!-- final_review_risk_coverage:{"sourceCommitId":"4fcdfdde2e950bc01ce1745a1f1015296a303ac3","coveredCommitId":"4fcdfdde2e950bc01ce1745a1f1015296a303ac3","kind":"reviewed"} -->

    No unresolved defect is established by the reviewed changes; the PR is mergeable after normal checks.
    <!-- final_review_risk_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 -->

    fbusato fbusato commented on code on Oct 01, 2026 16:40 UTC
    Code Review
    libcudacxx/include/cuda/std/__cmath/logarithms.h:1
    @@ -228,6 +229,24 @@ template <class _Integer, enable_if_t<is_integral_v<_Integer>, int> = 0>
     
     // ilogb
     
    +//! @brief Returns the unbiased exponent of a nonzero finite value, normalising subnormals

    no need for doxygen comments on internal functions

    fbusato fbusato commented on code on Oct 01, 2026 16:41 UTC
    Code Review
    libcudacxx/include/cuda/std/__cmath/logarithms.h:1
    @@ -228,6 +229,24 @@ template <class _Integer, enable_if_t<is_integral_v<_Integer>, int> = 0>
     
     // ilogb
     
    +//! @brief Returns the unbiased exponent of a nonzero finite value, normalising subnormals
    +template <class _Tp>
    +[[nodiscard]] _CCCL_API inline constexpr int __fp_get_exp_normalized(_Tp __x) noexcept

    inline is redundant here

    fbusato fbusato commented on code on Oct 01, 2026 16:41 UTC
    Code Review
    libcudacxx/include/cuda/std/__cmath/logarithms.h:1
    @@ -228,6 +229,24 @@ template <class _Integer, enable_if_t<is_integral_v<_Integer>, int> = 0>
     
     // ilogb
     
    +//! @brief Returns the unbiased exponent of a nonzero finite value, normalising subnormals
    +template <class _Tp>
    +[[nodiscard]] _CCCL_API inline constexpr int __fp_get_exp_normalized(_Tp __x) noexcept

    [[nodiscard]] _CCCL_API constexpr int __fp_get_exp_normalized(const _Tp __x) noexcept
    

    fbusato fbusato commented on code on Oct 01, 2026 16:43 UTC
    Code Review
    libcudacxx/include/cuda/std/__cmath/logarithms.h:1
    @@ -484,23 +499,28 @@ template <class _Tp>
       }
     
     #if _CCCL_HAS_CONSTEXPR_BIT_CAST()
    -  return static_cast<_Tp>(::cuda::std::__fp_get_exp(__x));
    +  return static_cast<_Tp>(::cuda::std::__fp_get_exp_normalized(__x));
     #else // ^^^ _CCCL_HAS_CONSTEXPR_BIT_CAST() ^^^ / vvv !_CCCL_HAS_CONSTEXPR_BIT_CAST() vvv
       // We need to go through the slow emulation for old GCC
       if constexpr (__fp_is_native_type_v<_Tp>)
       {
    -    __x                      = ::cuda::std::fabs(__x);
    -    unsigned long long __exp = 0;
    +    __x             = ::cuda::std::fabs(__x);
    +    long long __exp = 0;

        int64_t __exp = 0;
    

    fbusato fbusato commented on code on Oct 01, 2026 16:45 UTC
    Code Review
    libcudacxx/include/cuda/std/__cmath/logarithms.h:1
    @@ -228,6 +229,24 @@ template <class _Integer, enable_if_t<is_integral_v<_Integer>, int> = 0>
     
     // ilogb
     
    +//! @brief Returns the unbiased exponent of a nonzero finite value, normalising subnormals
    +template <class _Tp>

    @davebayer would make sense to move this utility in the __fp functionalities?

    miscco miscco commented on code on Oct 01, 2026 16:51 UTC
    Code Review
    libcudacxx/include/cuda/std/__cmath/logarithms.h:1
    @@ -228,6 +229,24 @@ template <class _Integer, enable_if_t<is_integral_v<_Integer>, int> = 0>
     
     // ilogb
     
    +//! @brief Returns the unbiased exponent of a nonzero finite value, normalising subnormals

    Does not hurt, especially for nontrivial math things

    miscco miscco commented on code on Oct 01, 2026 16:51 UTC
    Code Review
    libcudacxx/include/cuda/std/__cmath/logarithms.h:1
    @@ -228,6 +229,24 @@ template <class _Integer, enable_if_t<is_integral_v<_Integer>, int> = 0>
     
     // ilogb
     
    +//! @brief Returns the unbiased exponent of a nonzero finite value, normalising subnormals
    +template <class _Tp>

    Definitely

    miscco miscco requested changes on Oct 01, 2026 16:56 UTC
    Changes Requested Reviewer

    Thanks a lot, this is a great PR.

    I would like this to be close to __fp_get_exp, and would like to think hard whether we need to just fix __fp_get_exp

    miscco miscco commented on Oct 01, 2026 16:58 UTC
    Contributor

    I would like this to be close to __fp_get_exp, and would like to think hard whether we need to just fix __fp_get_exp

    Actually there are no other uses of __fp_get_exp so we should just fix it

    fbusato fbusato commented on code on Oct 01, 2026 17:48 UTC
    Code Review
    libcudacxx/include/cuda/std/__cmath/logarithms.h:1
    @@ -228,6 +229,24 @@ template <class _Integer, enable_if_t<is_integral_v<_Integer>, int> = 0>
     
     // ilogb
     
    +//! @brief Returns the unbiased exponent of a nonzero finite value, normalising subnormals

    I meant do not use doxygen comment, a standard comment is fine :)

    Arthur031221 Arthur031221 commented on Oct 09, 2026 17:13 UTC
    Author

    Fixed __fp_get_exp itself as suggested. A subnormal now gets its true exponent from the highest set mantissa bit, and zero, infinity and NaN still return the raw exponent field minus the bias. ilogb and logb call it directly and __fp_get_exp_normalized is gone, which settles the remarks on its doxygen comment, inline and signature. The int64_t suggestion is applied in the logb fallback.

    The description is out of date, since __fp_get_exp isn't unchanged anymore and there's no new helper. get_exp.pass.cpp now expects denorm_min() to report exp_min - digits + 1, logb_subnormal.pass.cpp is as before, and the conflict with main in logarithms.h is gone. CI needs a /ok to test for the new commit.

    ilogb and logb of denorm_min() give -149, -1074, -24 and -133 for float, double, __half and __nv_bfloat16 on the host and on an RTX 5090, and the 63 tests under libcxx/numerics/floating.point and std/numerics/c.math pass with nvcc 13.2 for sm_120.

    Reviewers
    Assignees
    Arthur031221 Arthur031221
    Labels
    risk: low confidence: 90.1% 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: 35.1% (MEDIUM) · Higher = larger blast radius
    35.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: 90.1% · Lower = rushed or shallow review
    90.1%
    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: 3.5% · Safe to merge
    3.5%
    Repository