From f7c4931ef52a815032e6f8de72eda0fcc6afd2f7 Mon Sep 17 00:00:00 2001 From: Max Buckley Date: Tue, 1 Sep 2026 16:31:45 +0200 Subject: [PATCH 1/6] Avoid unintended FP64 promotion in float kernels Three device-code sites forced double-precision arithmetic into kernels instantiated with float (or with integer output types). FP64 runs at 1/64 the FP32 rate on consumer GPUs, so these dominated the kernels they appeared in. 1. reduce_rows_by_key: the accumulate ternaries used a `0.0` alternative, so the common type of `(cond) ? SumsT(val) : 0.0` was double. Every iteration of the innermost loop of a bandwidth-bound reduction paid four double adds plus float/double conversions. Use `SumsT(0)` / `DataType(0)`. The float path was measurably *slower* than the double path before this change (195 GB/s vs 611 GB/s on the same shape). 2. multi_variable_gaussian: `pow(W[Wi], 0.5)` binds to `double pow(double, double)` regardless of T, which nvcc inlines as a software routine (41 DFMA + MUFU.RCP64H in SASS). `raft::sqrt` is equivalent for the non-negative inputs guarded above it, and is both faster and correctly rounded. The double instantiation benefits too. 3. normalInt: the Box-Muller transform was hardcoded to double no matter how wide the integer output was, so generating int8/int32 normals ran FP64 sqrt/log/sincos. Select the compute type from the output width, keeping double only where float's 24-bit mantissa is insufficient (64-bit integer outputs). Measured on an RTX 5090 (sm_120, CUDA 13.2), 20-50 timed iterations after warmup: reduce_rows_by_key 4.2M x 32, nkeys=4 2.834 -> 1.397 ms 2.03x reduce_rows_by_key 1.0M x 128, nkeys=4 2.522 -> 1.366 ms 1.85x reduce_rows_by_key 16.8M x 8, nkeys=4 3.269 -> 1.022 ms 3.20x reduce_rows_by_key 4.2M x 32, nkeys=4 1.784 -> 1.783 ms 1.00x combined_dot_product dim=1024 0.133 -> 0.010 ms 12.9x combined_dot_product dim=4096 2.058 -> 0.135 ms 15.2x combined_dot_product dim=4096 2.068 -> 0.240 ms 8.6x normalInt n=67.1M 3.563 -> 0.100 ms 35.6x normalInt n=67.1M 3.566 -> 0.183 ms 19.5x normalInt n=67.1M 3.572 -> 3.571 ms 1.00x Verified in SASS (cuobjdump) that no FP64 instructions remain in the float-instantiated kernels, and that the double instantiations are unchanged where they should be. Note: change 3 alters the normalInt random stream for integer types of 32 bits or fewer, since a float draw consumes 32 bits of generator state instead of 64. The distributions are unaffected. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01Vj4qbCmCuATAoLSP9XzY31 --- .../raft/linalg/detail/reduce_rows_by_key.cuh | 10 +++++----- .../raft/random/detail/multi_variable_gaussian.cuh | 4 ++-- cpp/include/raft/random/detail/rng_device.cuh | 13 ++++++++----- 3 files changed, 15 insertions(+), 12 deletions(-) diff --git a/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh b/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh index 347a6a7382..dbe3f59b69 100644 --- a/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh +++ b/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh @@ -115,17 +115,17 @@ __launch_bounds__(SUM_ROWS_SMALL_K_DIMX, 4) block_offset_irow < nrows; // we will syncthreads() inside the loop, no CTA divergence block_offset_irow += blockDim.x * gridDim.x) { IdxT irow = block_offset_irow + threadIdx.x; - DataType val = (irow < nrows) ? d_A[irow * lda + idim] : 0.0; + DataType val = (irow < nrows) ? d_A[irow * lda + idim] : DataType(0); if (d_weights && irow < nrows) { val = val * d_weights[irow]; } // we are not reusing the keys - after profiling // d_keys is mainly loaded from L2, and this kernel is DRAM BW bounded // (experimentation gave a 10% speed up - not worth the many code lines added) IdxT row_key = (irow < nrows) ? d_keys[irow] : std::numeric_limits::max(); - thread_sums.x += (row_key == 0) ? static_cast(val) : 0.0; - thread_sums.y += (row_key == 1) ? static_cast(val) : 0.0; - thread_sums.z += (row_key == 2) ? static_cast(val) : 0.0; - thread_sums.w += (row_key == 3) ? static_cast(val) : 0.0; + thread_sums.x += (row_key == 0) ? static_cast(val) : SumsT(0); + thread_sums.y += (row_key == 1) ? static_cast(val) : SumsT(0); + thread_sums.z += (row_key == 2) ? static_cast(val) : SumsT(0); + thread_sums.w += (row_key == 3) ? static_cast(val) : SumsT(0); } // End of column diff --git a/cpp/include/raft/random/detail/multi_variable_gaussian.cuh b/cpp/include/raft/random/detail/multi_variable_gaussian.cuh index bf9df1eaee..0208f3d630 100644 --- a/cpp/include/raft/random/detail/multi_variable_gaussian.cuh +++ b/cpp/include/raft/random/detail/multi_variable_gaussian.cuh @@ -95,8 +95,8 @@ RAFT_KERNEL combined_dot_product(int rows, int cols, const T* W, T* matrix, int* int m_i = threadIdx.x + blockDim.x * blockIdx.x; int Wi = m_i / cols; if (m_i < cols * rows) { - if (W[Wi] >= 0.0) - matrix[m_i] = pow(W[Wi], 0.5) * (matrix[m_i]); + if (W[Wi] >= T(0)) + matrix[m_i] = raft::sqrt(W[Wi]) * (matrix[m_i]); else check[0] = Wi; // reports Wi'th eigen values is negative. } diff --git a/cpp/include/raft/random/detail/rng_device.cuh b/cpp/include/raft/random/detail/rng_device.cuh index 8720d65769..3eb7dad8a6 100644 --- a/cpp/include/raft/random/detail/rng_device.cuh +++ b/cpp/include/raft/random/detail/rng_device.cuh @@ -243,15 +243,18 @@ HDI void custom_next(GenType& gen, LenType idx = 0, LenType stride = 0) { - double res1, res2; + // float has enough mantissa for any int type up to 32 bits; only 64-bit outputs need double, + // which is 1/64 rate on consumer GPUs. + using compute_t = std::conditional_t<(sizeof(IntType) > 4), double, float>; + compute_t res1, res2; do { gen.next(res1); - } while (res1 == double(0.0)); + } while (res1 == compute_t(0.0)); gen.next(res2); - double mu = static_cast(params.mu); - double sigma = static_cast(params.sigma); - box_muller_transform(res1, res2, sigma, mu); + compute_t mu = static_cast(params.mu); + compute_t sigma = static_cast(params.sigma); + box_muller_transform(res1, res2, sigma, mu); *val = static_cast(res1); *(val + 1) = static_cast(res2); } From 4f1cebb56b5509c294191e4769ca6c05aeb50f3d Mon Sep 17 00:00:00 2001 From: Max Buckley Date: Tue, 1 Sep 2026 17:08:24 +0200 Subject: [PATCH 2/6] Apply mu in the output type in normalInt Review feedback: with the deviate computed in float for 32-bit outputs, folding mu into the Box-Muller transform rounds mu itself once it exceeds float's mantissa. The damage is larger than just mu, because the deviate is added to mu inside the transform and then rounded to the spacing at that magnitude. For int32_t with mu = 2e9 the float spacing is 128, so a sigma of 10 disappears completely and every sample comes back as exactly mu: mu=2e9 sigma=10, 64K draws, distinct values / observed range main: 81 [1999999962, 2000000045] previous commit: 1 [2000000000, 2000000000] this commit: 81 [1999999959, 2000000040] Draw a zero-mean deviate instead and shift by mu in the output type. mu is then exact for every value of IntType, and the deviate keeps the full resolution the output type can represent. Reverting 32-bit outputs to double would also fix mu, but gives up the speedup and still rounds the deviate at 2^53 for 64-bit outputs; this fixes both widths. The int64_t path is improved for the same reason: mu was previously rounded to double, which collapses the deviate above 2^53. This also removes a truncation bias. Casting mu + deviate to an integer truncates towards zero, biasing the sample away from mu by up to one unit; casting the deviate alone is symmetric about mu. Sample mean error over 64K draws at mu = 1e8, sigma = 10: -0.48 before, +0.01 now. Costs nothing: the generated kernels are unchanged in size (328 instructions for PCGenerator, 480 for PhiloxGenerator) and normalInt still runs at 0.183 ms / 67.1M int32 samples, versus 3.566 ms on main. Adds RngNormalIntLargeMu, which pins the invariant that makes this work: the deviate does not depend on mu, so drawing with mu and with 0 from the same seed must give identical deviates. That is exact and needs no statistical tolerance. Verified to fail against the previous commit for every mu tested, and against main for the 64-bit cases. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01Vj4qbCmCuATAoLSP9XzY31 --- cpp/include/raft/random/detail/rng_device.cuh | 16 +++-- cpp/tests/random/rng_int.cu | 62 +++++++++++++++++++ 2 files changed, 72 insertions(+), 6 deletions(-) diff --git a/cpp/include/raft/random/detail/rng_device.cuh b/cpp/include/raft/random/detail/rng_device.cuh index 3eb7dad8a6..3754cf6d1a 100644 --- a/cpp/include/raft/random/detail/rng_device.cuh +++ b/cpp/include/raft/random/detail/rng_device.cuh @@ -243,8 +243,13 @@ HDI void custom_next(GenType& gen, LenType idx = 0, LenType stride = 0) { - // float has enough mantissa for any int type up to 32 bits; only 64-bit outputs need double, - // which is 1/64 rate on consumer GPUs. + // Draw a zero-mean deviate in the narrowest type that can carry it, then shift by mu in the + // output type. Folding mu into the transform would round mu itself and, worse, quantize the + // deviate away entirely once |mu| exceeds the mantissa of the compute type (2^24 for float, + // 2^53 for double): at mu = 2e9 the float spacing is 128, so a sigma of 10 vanishes. + // With mu applied separately, float carries any deviate an integer output can represent, and + // double is only needed for the wider deviates of 64-bit outputs. Double is 1/64 rate on + // consumer GPUs, so this matters. using compute_t = std::conditional_t<(sizeof(IntType) > 4), double, float>; compute_t res1, res2; do { @@ -252,11 +257,10 @@ HDI void custom_next(GenType& gen, } while (res1 == compute_t(0.0)); gen.next(res2); - compute_t mu = static_cast(params.mu); compute_t sigma = static_cast(params.sigma); - box_muller_transform(res1, res2, sigma, mu); - *val = static_cast(res1); - *(val + 1) = static_cast(res2); + box_muller_transform(res1, res2, sigma, compute_t(0)); + *val = static_cast(res1) + params.mu; + *(val + 1) = static_cast(res2) + params.mu; } template diff --git a/cpp/tests/random/rng_int.cu b/cpp/tests/random/rng_int.cu index 96d531dea2..0bd68a1011 100644 --- a/cpp/tests/random/rng_int.cu +++ b/cpp/tests/random/rng_int.cu @@ -16,6 +16,8 @@ #include +#include + namespace raft { namespace random { @@ -287,5 +289,65 @@ TEST_P(RngMdspanTestS64, Result) } INSTANTIATE_TEST_SUITE_P(RngMdspanTests, RngMdspanTestS64, ::testing::ValuesIn(inputs_s64)); +/** + * normalInt draws the deviate in a narrower type than the output when it can, so the shift by mu + * has to be applied in the output type. If mu is folded into the Box-Muller transform instead, + * everything below the mantissa of the compute type is lost: at mu = 2e9 the float spacing is 128, + * which quantizes a sigma of 10 away completely and collapses the sample to a single value. + * + * The deviate does not depend on mu, so drawing with mu and with 0 from the same seed must give + * the same deviates. That is exact, so it needs no statistical tolerance. + */ +template +void testNormalIntLargeMu(T mu, T sigma, GeneratorType gtype) +{ + raft::resources handle; + auto stream = resource::get_cuda_stream(handle); + constexpr int len = 32 * 1024; + + rmm::device_uvector shifted(len, stream); + rmm::device_uvector centered(len, stream); + + RngState r_shifted(1234ULL, gtype); + normalInt(handle, r_shifted, shifted.data(), len, mu, sigma); + RngState r_centered(1234ULL, gtype); + normalInt(handle, r_centered, centered.data(), len, T(0), sigma); + + std::vector h_shifted(len); + std::vector h_centered(len); + update_host(h_shifted.data(), shifted.data(), len, stream); + update_host(h_centered.data(), centered.data(), len, stream); + resource::sync_stream(handle, stream); + + bool all_zero = true; + for (int i = 0; i < len; ++i) { + // Subtract in the integer type: converting values of this magnitude to a floating point type + // would lose the very precision being tested for. + ASSERT_EQ(static_cast(h_shifted[i] - mu), h_centered[i]) + << "deviate " << i << " differs once shifted by mu=" << mu; + all_zero = all_zero && (h_centered[i] == T(0)); + } + ASSERT_FALSE(all_zero) << "every deviate was zero for sigma=" << sigma; +} + +TEST(RngNormalIntLargeMu, S32) +{ + for (auto gtype : {GenPhilox, GenPC}) { + testNormalIntLargeMu(16777217, 10, gtype); // 2^24 + 1, past float's mantissa + testNormalIntLargeMu(100000000, 10, gtype); + testNormalIntLargeMu(2000000000, 10, gtype); // near the int32_t limit + testNormalIntLargeMu(-2000000000, 10, gtype); + } +} + +TEST(RngNormalIntLargeMu, S64) +{ + for (auto gtype : {GenPhilox, GenPC}) { + // 2^53 + 1, past double's mantissa + testNormalIntLargeMu(9007199254740993LL, 10, gtype); + testNormalIntLargeMu(4000000000000000000LL, 10, gtype); + } +} + } // namespace random } // namespace raft From e4e21881729e699eacd92d93d0205c2a8d7c1699 Mon Sep 17 00:00:00 2001 From: Max Buckley Date: Thu, 3 Sep 2026 10:10:08 +0200 Subject: [PATCH 3/6] Use the canonical NVIDIA copyright notice in rng_device.cuh Applied by `pre-commit run --all-files`; the verify-copyright hook requires the "& AFFILIATES. All rights reserved." form. This was the only check-style failure on the PR. Co-Authored-By: Claude Opus 5 (1M context) --- cpp/include/raft/random/detail/rng_device.cuh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cpp/include/raft/random/detail/rng_device.cuh b/cpp/include/raft/random/detail/rng_device.cuh index 3754cf6d1a..6a80ea3120 100644 --- a/cpp/include/raft/random/detail/rng_device.cuh +++ b/cpp/include/raft/random/detail/rng_device.cuh @@ -1,5 +1,5 @@ /* - * SPDX-FileCopyrightText: Copyright (c) 2022-2026, NVIDIA CORPORATION. + * SPDX-FileCopyrightText: Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. * SPDX-License-Identifier: Apache-2.0 */ From 62b4af3eac4426b6632f129c1a22d8c32f37ad15 Mon Sep 17 00:00:00 2001 From: Max Buckley Date: Thu, 24 Sep 2026 11:12:02 +0200 Subject: [PATCH 4/6] Fix normalInt for unsigned outputs Applying mu in the output type means the zero-mean deviate is converted to IntType before the shift. For unsigned IntType a negative deviate makes that conversion undefined, and the device saturates it to 0, so every sample below mu collapsed onto mu. The host wraps instead, which is what Rng/TestW/NormalIntT (host_api_test) caught in CI. Convert through the signed type of the same width so the shift wraps modulo 2^n. Signed outputs are unchanged. Add RngNormalIntUnsigned tests that check samples fall on both sides of mu; the shifted-vs-centered check cannot see this bug because both draws collapse identically. Co-Authored-By: Claude Opus 5.5 (1M context) --- cpp/include/raft/random/detail/rng_device.cuh | 8 +++- cpp/tests/random/rng_int.cu | 45 +++++++++++++++++++ 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/cpp/include/raft/random/detail/rng_device.cuh b/cpp/include/raft/random/detail/rng_device.cuh index 6a80ea3120..e886cec437 100644 --- a/cpp/include/raft/random/detail/rng_device.cuh +++ b/cpp/include/raft/random/detail/rng_device.cuh @@ -17,6 +17,7 @@ #include #include +#include namespace raft { namespace random { @@ -259,8 +260,11 @@ HDI void custom_next(GenType& gen, gen.next(res2); compute_t sigma = static_cast(params.sigma); box_muller_transform(res1, res2, sigma, compute_t(0)); - *val = static_cast(res1) + params.mu; - *(val + 1) = static_cast(res2) + params.mu; + // A negative deviate must not be converted straight to an unsigned IntType: that is undefined, + // and the device saturates it to 0. Going through the signed type wraps it modulo 2^n instead. + using signed_t = std::make_signed_t; + *val = static_cast(params.mu + static_cast(static_cast(res1))); + *(val + 1) = static_cast(params.mu + static_cast(static_cast(res2))); } template diff --git a/cpp/tests/random/rng_int.cu b/cpp/tests/random/rng_int.cu index 0bd68a1011..b2df1789ab 100644 --- a/cpp/tests/random/rng_int.cu +++ b/cpp/tests/random/rng_int.cu @@ -349,5 +349,50 @@ TEST(RngNormalIntLargeMu, S64) } } +/** + * With an unsigned output, a negative deviate converted straight to the output type saturates to + * 0 on the device, collapsing every sample below mu onto mu. The shifted/centered comparison above + * cannot see that, since both draws collapse identically, so check both sides of mu directly. + */ +template +void testNormalIntUnsignedBothSides(T mu, T sigma, GeneratorType gtype) +{ + raft::resources handle; + auto stream = resource::get_cuda_stream(handle); + constexpr int len = 32 * 1024; + + rmm::device_uvector out(len, stream); + RngState r(1234ULL, gtype); + normalInt(handle, r, out.data(), len, mu, sigma); + + std::vector h_out(len); + update_host(h_out.data(), out.data(), len, stream); + resource::sync_stream(handle, stream); + + int below = 0; + int above = 0; + for (int i = 0; i < len; ++i) { + below += h_out[i] < mu; + above += h_out[i] > mu; + } + ASSERT_GT(below, len / 3) << "mu=" << mu << " sigma=" << sigma; + ASSERT_GT(above, len / 3) << "mu=" << mu << " sigma=" << sigma; +} + +TEST(RngNormalIntUnsigned, U32) +{ + for (auto gtype : {GenPhilox, GenPC}) { + testNormalIntUnsignedBothSides(10000000, 10000, gtype); + testNormalIntUnsignedBothSides(4000000000U, 10, gtype); // above INT32_MAX + } +} + +TEST(RngNormalIntUnsigned, U64) +{ + for (auto gtype : {GenPhilox, GenPC}) { + testNormalIntUnsignedBothSides(10000000, 10000, gtype); + } +} + } // namespace random } // namespace raft From 38ab815a1ea033055cc8c0935b7152559edb9625 Mon Sep 17 00:00:00 2001 From: Max Buckley Date: Thu, 24 Sep 2026 13:59:39 +0200 Subject: [PATCH 5/6] Handle normalInt deviates by magnitude instead of via make_signed make_signed_t is ill-formed, so normalInt stopped compiling, and a uint32_t deviate above INT32_MAX overflowed the int32_t step and was clamped on the device. Branch on the sign and convert only the deviate's magnitude to IntType, which handles both. In-range results are unchanged since truncation toward zero is symmetric. Add tests for a uint32_t deviate above INT32_MAX and for normalInt. Co-Authored-By: Claude Opus 5.5 (1M context) --- cpp/include/raft/random/detail/rng_device.cuh | 11 +++--- cpp/tests/random/rng_int.cu | 38 +++++++++++++++++++ 2 files changed, 44 insertions(+), 5 deletions(-) diff --git a/cpp/include/raft/random/detail/rng_device.cuh b/cpp/include/raft/random/detail/rng_device.cuh index e886cec437..e935d17ef2 100644 --- a/cpp/include/raft/random/detail/rng_device.cuh +++ b/cpp/include/raft/random/detail/rng_device.cuh @@ -260,11 +260,12 @@ HDI void custom_next(GenType& gen, gen.next(res2); compute_t sigma = static_cast(params.sigma); box_muller_transform(res1, res2, sigma, compute_t(0)); - // A negative deviate must not be converted straight to an unsigned IntType: that is undefined, - // and the device saturates it to 0. Going through the signed type wraps it modulo 2^n instead. - using signed_t = std::make_signed_t; - *val = static_cast(params.mu + static_cast(static_cast(res1))); - *(val + 1) = static_cast(params.mu + static_cast(static_cast(res2))); + // Only convert the deviate's magnitude to IntType: a negative value converted to an unsigned + // IntType is undefined, and the device saturates it to 0. + *val = res1 < 0 ? static_cast(params.mu - static_cast(-res1)) + : static_cast(params.mu + static_cast(res1)); + *(val + 1) = res2 < 0 ? static_cast(params.mu - static_cast(-res2)) + : static_cast(params.mu + static_cast(res2)); } template diff --git a/cpp/tests/random/rng_int.cu b/cpp/tests/random/rng_int.cu index b2df1789ab..1b132c7355 100644 --- a/cpp/tests/random/rng_int.cu +++ b/cpp/tests/random/rng_int.cu @@ -387,6 +387,44 @@ TEST(RngNormalIntUnsigned, U32) } } +/** + * A positive deviate above INT32_MAX still fits a uint32_t output, so it must not pass through + * int32_t on the way: the device would saturate it to INT32_MAX (or INT32_MIN for negatives). + * sigma is kept below 2^32 / 6 so every deviate fits uint32_t, since beyond that is out of range. + */ +TEST(RngNormalIntUnsigned, U32DeviateAboveInt32Max) +{ + for (auto gtype : {GenPhilox, GenPC}) { + raft::resources handle; + auto stream = resource::get_cuda_stream(handle); + constexpr int len = 32 * 1024; + + rmm::device_uvector out(len, stream); + RngState r(1234ULL, gtype); + normalInt(handle, r, out.data(), len, uint32_t(0), uint32_t(700000000)); + + std::vector h_out(len); + update_host(h_out.data(), out.data(), len, stream); + resource::sync_stream(handle, stream); + + int saturated = 0; + for (int i = 0; i < len; ++i) { + saturated += h_out[i] == 2147483647U || h_out[i] == 2147483648U; + } + ASSERT_LT(saturated, 3) << "deviates beyond INT32_MAX were clamped"; + } +} + +TEST(RngNormalIntBool, Compiles) +{ + raft::resources handle; + auto stream = resource::get_cuda_stream(handle); + rmm::device_uvector out(1024, stream); + RngState r(1234ULL, GenPC); + normalInt(handle, r, out.data(), 1024, true, true); + resource::sync_stream(handle, stream); +} + TEST(RngNormalIntUnsigned, U64) { for (auto gtype : {GenPhilox, GenPC}) { From 3ed101856d6778ec294aaa1d93be7937bff013d7 Mon Sep 17 00:00:00 2001 From: Max Buckley Date: Thu, 24 Sep 2026 22:19:41 +0200 Subject: [PATCH 6/6] Saturate out-of-range normalInt samples instead of wrapping When the deviate carries mu + deviate outside IntType, the magnitude path wrapped modulo 2^n for unsigned outputs (mu = 0 with a negative deviate gave values near UINT32_MAX). Saturate to lowest()/max() instead, which is what main produces on the device: it converts the double sum mu + deviate to IntType, and device conversions saturate. shift_by_deviate checks the headroom in the unsigned type of the same width, so nothing overflows and a negative deviate is never converted to an unsigned type. Checked against an exact 128-bit reference on host and device for every integer width and bool (4M cases each, including bound-adjacent mu, deviates beyond the type range and |deviate| < 1): no mismatches. Tests: U32DeviateAboveInt32Max now checks that negative deviates saturate to 0 rather than relying on wraparound, and RngNormalIntSaturates covers mu next to each bound for 32- and 64-bit, signed and unsigned. All five fail on the previous commit. Co-Authored-By: Claude Opus 5.5 (1M context) --- cpp/include/raft/random/detail/rng_device.cuh | 40 ++++++-- cpp/tests/random/rng_int.cu | 97 +++++++++++++++---- 2 files changed, 114 insertions(+), 23 deletions(-) diff --git a/cpp/include/raft/random/detail/rng_device.cuh b/cpp/include/raft/random/detail/rng_device.cuh index e935d17ef2..89d648a083 100644 --- a/cpp/include/raft/random/detail/rng_device.cuh +++ b/cpp/include/raft/random/detail/rng_device.cuh @@ -16,6 +16,7 @@ #include +#include #include #include @@ -237,6 +238,37 @@ HDI void custom_next( *(val + 1) = res2; } +template +struct shift_unsigned { + using type = std::make_unsigned_t; +}; +template <> +struct shift_unsigned { + using type = unsigned char; +}; + +/** + * mu + trunc(dev), saturated to the range of IntType, which is what converting the exact sum + * would give on the device. The bounds are checked in the unsigned type of the same width, so + * nothing overflows and a negative deviate is never converted to an unsigned type. + */ +template +HDI IntType shift_by_deviate(IntType mu, T dev) +{ + using U = typename shift_unsigned::type; + constexpr auto lo = std::numeric_limits::lowest(); + constexpr auto hi = std::numeric_limits::max(); + + const bool neg = dev < T(0); + const T mag = neg ? -dev : dev; + const U room = neg ? U(U(mu) - U(lo)) : U(U(hi) - U(mu)); + // T(max) + 1 rounds to exactly 2^digits, so below it the conversion to U is in range. + if (mag >= T(std::numeric_limits::max()) + T(1)) { return neg ? lo : hi; } + const U m = static_cast(mag); + if (m > room) { return neg ? lo : hi; } + return static_cast(neg ? U(U(mu) - m) : U(U(mu) + m)); +} + template HDI void custom_next(GenType& gen, IntType* val, @@ -260,12 +292,8 @@ HDI void custom_next(GenType& gen, gen.next(res2); compute_t sigma = static_cast(params.sigma); box_muller_transform(res1, res2, sigma, compute_t(0)); - // Only convert the deviate's magnitude to IntType: a negative value converted to an unsigned - // IntType is undefined, and the device saturates it to 0. - *val = res1 < 0 ? static_cast(params.mu - static_cast(-res1)) - : static_cast(params.mu + static_cast(res1)); - *(val + 1) = res2 < 0 ? static_cast(params.mu - static_cast(-res2)) - : static_cast(params.mu + static_cast(res2)); + *val = shift_by_deviate(params.mu, res1); + *(val + 1) = shift_by_deviate(params.mu, res2); } template diff --git a/cpp/tests/random/rng_int.cu b/cpp/tests/random/rng_int.cu index 400406b39f..4312586ee3 100644 --- a/cpp/tests/random/rng_int.cu +++ b/cpp/tests/random/rng_int.cu @@ -16,6 +16,7 @@ #include +#include #include namespace raft { @@ -387,34 +388,96 @@ TEST(RngNormalIntUnsigned, U32) } } +template +std::vector drawNormalInt(T mu, T sigma, GeneratorType gtype, int len) +{ + raft::resources handle; + auto stream = resource::get_cuda_stream(handle); + rmm::device_uvector out(len, stream); + RngState r(1234ULL, gtype); + normalInt(handle, r, out.data(), len, mu, sigma); + std::vector h_out(len); + update_host(h_out.data(), out.data(), len, stream); + resource::sync_stream(handle, stream); + return h_out; +} + /** - * A positive deviate above INT32_MAX still fits a uint32_t output, so it must not pass through - * int32_t on the way: the device would saturate it to INT32_MAX (or INT32_MIN for negatives). - * sigma is kept below 2^32 / 6 so every deviate fits uint32_t, since beyond that is out of range. + * A positive deviate above INT32_MAX still fits a uint32_t output, so it must come through intact + * rather than being clamped at INT32_MAX or INT32_MIN on the way. With mu = 0, every negative + * deviate is out of range and must saturate to 0; wrapping would put it near UINT32_MAX instead. */ TEST(RngNormalIntUnsigned, U32DeviateAboveInt32Max) { + constexpr int len = 32 * 1024; for (auto gtype : {GenPhilox, GenPC}) { - raft::resources handle; - auto stream = resource::get_cuda_stream(handle); - constexpr int len = 32 * 1024; - - rmm::device_uvector out(len, stream); - RngState r(1234ULL, gtype); - normalInt(handle, r, out.data(), len, uint32_t(0), uint32_t(700000000)); + auto h_out = drawNormalInt(0, 700000000, gtype, len); - std::vector h_out(len); - update_host(h_out.data(), out.data(), len, stream); - resource::sync_stream(handle, stream); + int zero = 0, above_int32 = 0, at_int32_edge = 0; + for (auto v : h_out) { + zero += v == 0; + above_int32 += v > 2147483648U; + at_int32_edge += v == 2147483647U || v == 2147483648U; + } + ASSERT_GT(zero, len * 45 / 100) << "negative deviates must saturate to 0"; + ASSERT_LT(zero, len * 55 / 100); + ASSERT_GT(above_int32, 0) << "deviates above INT32_MAX were lost"; + ASSERT_LT(at_int32_edge, 3) << "deviates beyond INT32_MAX were clamped"; + } +} - int saturated = 0; - for (int i = 0; i < len; ++i) { - saturated += h_out[i] == 2147483647U || h_out[i] == 2147483648U; +/** + * Samples that fall outside the output type saturate to its bounds, as converting the exact sum + * mu + deviate would on the device. With mu a few units from a bound, about half the samples + * saturate there and none may wrap around to the far end of the range. + */ +template +void testNormalIntSaturates(T mu, T sigma, bool at_low_end) +{ + constexpr int len = 32 * 1024; + const T bound = at_low_end ? std::numeric_limits::lowest() : std::numeric_limits::max(); + for (auto gtype : {GenPhilox, GenPC}) { + auto h_out = drawNormalInt(mu, sigma, gtype, len); + + int saturated = 0, wrapped = 0; + for (auto v : h_out) { + saturated += v == bound; + // Every in-range sample is within 6 sigma of mu, since the deviate is at most ~5.8 sigma. + // Measure the distance in the unsigned type so a wrapped value cannot overflow it. + using U = std::make_unsigned_t; + const U dist = v < mu ? U(U(mu) - U(v)) : U(U(v) - U(mu)); + wrapped += dist > U(6) * U(sigma) && v != bound; } - ASSERT_LT(saturated, 3) << "deviates beyond INT32_MAX were clamped"; + ASSERT_GT(saturated, len * 45 / 100) << "mu=" << mu << " sigma=" << sigma; + ASSERT_LT(saturated, len * 55 / 100) << "mu=" << mu << " sigma=" << sigma; + ASSERT_EQ(wrapped, 0) << "mu=" << mu << " sigma=" << sigma; } } +TEST(RngNormalIntSaturates, U32) +{ + testNormalIntSaturates(5, 1000, true); + testNormalIntSaturates(std::numeric_limits::max() - 5, 1000, false); +} + +TEST(RngNormalIntSaturates, S32) +{ + testNormalIntSaturates(std::numeric_limits::lowest() + 5, 1000, true); + testNormalIntSaturates(std::numeric_limits::max() - 5, 1000, false); +} + +TEST(RngNormalIntSaturates, U64) +{ + testNormalIntSaturates(5, 1000, true); + testNormalIntSaturates(std::numeric_limits::max() - 5, 1000, false); +} + +TEST(RngNormalIntSaturates, S64) +{ + testNormalIntSaturates(std::numeric_limits::lowest() + 5, 1000, true); + testNormalIntSaturates(std::numeric_limits::max() - 5, 1000, false); +} + TEST(RngNormalIntBool, Compiles) { raft::resources handle;