From cccaaec44a89036cb403d8b62a9d37aade97b7a9 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Wed, 4 Nov 2026 11:46:55 -0800 Subject: [PATCH 01/33] Add the continuous distributions to dpnp.random.Generator Port NumPy's continuous samplers to device kernels: exponential, gamma, beta, chisquare, standard_t, f, lognormal, standard_cauchy, wald, pareto, weibull, power, rayleigh, laplace, gumbel, logistic, triangular and vonmises. The rejection samplers return NaN for device parameters that would make them loop forever. --- CHANGELOG.md | 1 + doc/reference/random.rst | 30 +- dpnp/libtensor/AGENTS.md | 2 +- dpnp/libtensor/extensions/rng/CMakeLists.txt | 2 + .../extensions/rng/distributions.hpp | 2 + dpnp/libtensor/extensions/rng/exponential.cpp | 65 +++ dpnp/libtensor/extensions/rng/gamma.cpp | 69 +++ .../extensions/rng/kernels/distributions.hpp | 297 +++++++++++ .../extensions/rng/kernels/sample.hpp | 3 +- .../extensions/rng/kernels/samplers.hpp | 384 ++++++++++++++ dpnp/libtensor/extensions/rng/normal.cpp | 18 + dpnp/libtensor/extensions/rng/rng_py.cpp | 2 + dpnp/libtensor/extensions/rng/uniform.cpp | 35 ++ dpnp/random/_bit_generator.py | 3 +- dpnp/random/_generator.py | 496 +++++++++++++++++- dpnp/tests/test_random_generator.py | 250 +++++++++ dpnp/tests/test_sycl_queue.py | 22 + dpnp/tests/test_usm_type.py | 2 + .../cupy/random_tests/test_generator_api.py | 15 +- 19 files changed, 1679 insertions(+), 19 deletions(-) create mode 100644 dpnp/libtensor/extensions/rng/exponential.cpp create mode 100644 dpnp/libtensor/extensions/rng/gamma.cpp diff --git a/CHANGELOG.md b/CHANGELOG.md index 7ceb1d52d8e0..6c74a154e846 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ This release drops support for Python 3.10, making Python 3.11 the minimum requi * Added implementation of `dpnp.scipy.linalg.cho_factor` and `dpnp.scipy.linalg.cho_solve` (SciPy-compatible) [#3116](https://github.com/IntelPython/dpnp/pull/3116) * Added the `dpnp.random.Generator` API with `default_rng`, `BitGenerator`, `SeedSequence` and the `Philox4x3210` bit generator, sampling on the device with the device RNG API of oneMKL or oneMath [#3157](https://github.com/IntelPython/dpnp/pull/3157) * Added `dpnp.argpartition` and `dpnp.ndarray.argpartition` to return the indices that would partition an array [#3138](https://github.com/IntelPython/dpnp/pull/3138) +* Added the continuous distributions of `numpy.random.Generator`, such as `gamma`, `beta` and `vonmises`, to `dpnp.random.Generator` [#3158](https://github.com/IntelPython/dpnp/pull/3158) ### Changed diff --git a/doc/reference/random.rst b/doc/reference/random.rst index c7ba5109bfdc..e31a51250af3 100644 --- a/doc/reference/random.rst +++ b/doc/reference/random.rst @@ -29,8 +29,10 @@ Differences from NumPy ---------------------- * The streams differ from NumPy's. For a given seed, output size and data - type, the raw bits and the uniform floats are the same on every device, - while the normal samples agree to a few ULP. + type, the raw bits and the uniform floats are the same on every device. + The other distributions use transcendental functions, which may round + differently on another device: their samples agree to a few ULP, or + differ when a rejection sampler then takes another candidate. * The values depend on the output size: a draw is not a prefix of a larger one, and two draws of ``n`` values differ from one draw of ``2 * n``. Code splitting its draws into chunks gets other values. @@ -44,7 +46,9 @@ Differences from NumPy * Parameters on the host (Python scalars, lists and NumPy arrays) are checked as in NumPy. Parameters in :class:`dpnp.ndarray` are not, since that would wait for the device. - Invalid ones give undefined values, such as NaN. + Invalid ones give undefined values, such as NaN or the smallest ``int64``, + but the kernels handle them safely: they never loop without end or access + memory out of bounds. * Parameters given as lists or NumPy arrays are copied to the device first, which waits for the work already submitted to the queue. Scalars and :class:`dpnp.ndarray` parameters don't wait. @@ -89,9 +93,29 @@ Distributions :toctree: generated/ :nosignatures: + Generator.beta + Generator.chisquare + Generator.exponential + Generator.f + Generator.gamma + Generator.gumbel + Generator.laplace + Generator.logistic + Generator.lognormal Generator.normal + Generator.pareto + Generator.power + Generator.rayleigh + Generator.standard_cauchy + Generator.standard_exponential + Generator.standard_gamma Generator.standard_normal + Generator.standard_t + Generator.triangular Generator.uniform + Generator.vonmises + Generator.wald + Generator.weibull Bit generators -------------- diff --git a/dpnp/libtensor/AGENTS.md b/dpnp/libtensor/AGENTS.md index 1c81104d5747..788569c68007 100644 --- a/dpnp/libtensor/AGENTS.md +++ b/dpnp/libtensor/AGENTS.md @@ -23,7 +23,7 @@ A new extension's `CMakeLists.txt` lists its sources and calls `build_dpnp_pybin - Guard double, complex and half with `dpnp::tensor::type_utils::validate_type_for_device(q)`; don't use double literals or casts in kernels that must run without fp64. - `blas`, `fft`, `lapack` and `sparse` build against either oneMKL or oneMath (`USE_ONEMATH`); `vm` has kernels only with oneMKL: with oneMath it builds empty and `_is_available()` returns `False`; `rng` uses the header-only device RNG API of oneMKL, or of oneMath with `USE_ONEMATH`, and links neither library. - Release the GIL around blocking oneMKL calls (`py::gil_scoped_release`). -- `rng` draws depend only on the engine state and the number of elements, never on the device or the layout chosen for it (`extensions/rng/kernels/sample.hpp`): raw bits and uniform floats are bit-identical across devices, samplers using transcendental functions agree to a few ULP. Each engine's `items_per_work_item` (`kernels/engines.hpp`) is part of its stream definition. +- `rng` draws depend only on the engine state and the number of elements, never on the device or the layout chosen for it (`extensions/rng/kernels/sample.hpp`): raw bits and uniform floats are bit-identical across devices, samplers using transcendental functions agree to a few ULP, or differ where a rejection sampler then takes another candidate. Each engine's `items_per_work_item` (`kernels/engines.hpp`) is part of its stream definition. Parameters on the device are unchecked, so a rejection sampler returns NaN for the inputs that would make it loop forever, including values that are valid but round badly in fp32. - An extension whose kernels may be launched over more than `INT_MAX` work-items passes `LARGE_RANGES` to `build_dpnp_pybind11_ext`, which adds `-fno-sycl-id-queries-fit-in-int` at compile and link time (DPC++ 2026.2 and later need it at link time). `source/CMakeLists.txt` and `dpnp_backend_c` pass it to both `target_compile_options` and `target_link_options`. - clang-format 23 formats C++ (`.clang-format`: LLVM base, 4-space indent, 80 columns); gersemi formats CMake at 88 columns, except `dpnp/backend/cmake/Modules/`. diff --git a/dpnp/libtensor/extensions/rng/CMakeLists.txt b/dpnp/libtensor/extensions/rng/CMakeLists.txt index 88050a0039fd..82138e03b3b2 100644 --- a/dpnp/libtensor/extensions/rng/CMakeLists.txt +++ b/dpnp/libtensor/extensions/rng/CMakeLists.txt @@ -29,6 +29,8 @@ set(python_module_name _rng_impl) set(_module_src + ${CMAKE_CURRENT_SOURCE_DIR}/exponential.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/gamma.cpp ${CMAKE_CURRENT_SOURCE_DIR}/normal.cpp ${CMAKE_CURRENT_SOURCE_DIR}/rng_py.cpp ${CMAKE_CURRENT_SOURCE_DIR}/sample.cpp diff --git a/dpnp/libtensor/extensions/rng/distributions.hpp b/dpnp/libtensor/extensions/rng/distributions.hpp index 381534f6fe44..6d41e71b39d1 100644 --- a/dpnp/libtensor/extensions/rng/distributions.hpp +++ b/dpnp/libtensor/extensions/rng/distributions.hpp @@ -36,4 +36,6 @@ namespace py = pybind11; void init_uniform(py::module_ m); void init_normal(py::module_ m); +void init_exponential(py::module_ m); +void init_gamma(py::module_ m); } // namespace dpnp::extensions::rng diff --git a/dpnp/libtensor/extensions/rng/exponential.cpp b/dpnp/libtensor/extensions/rng/exponential.cpp new file mode 100644 index 000000000000..5e36e15e2295 --- /dev/null +++ b/dpnp/libtensor/extensions/rng/exponential.cpp @@ -0,0 +1,65 @@ +//***************************************************************************** +// Copyright (c) 2026, Intel Corporation +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// - Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// - Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// - Neither the name of the copyright holder nor the names of its contributors +// may be used to endorse or promote products derived from this software +// without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF +// THE POSSIBILITY OF SUCH DAMAGE. +//***************************************************************************** +#include + +#include "common.hpp" +#include "distributions.hpp" + +namespace dpnp::extensions::rng +{ +static sample_dispatch_table_t exponential_dispatch_table; +static sample_dispatch_table_t pareto_dispatch_table; +static sample_dispatch_table_t weibull_dispatch_table; +static sample_dispatch_table_t power_dispatch_table; +static sample_dispatch_table_t rayleigh_dispatch_table; + +void init_exponential(py::module_ m) +{ + def_sampler( + m, "_exponential", + "Fill the result with exponential samples of scale scale", + exponential_dispatch_table); + + def_sampler( + m, "_pareto", "Fill the result with Pareto II samples of shape a", + pareto_dispatch_table); + + def_sampler( + m, "_weibull", "Fill the result with Weibull samples of shape a", + weibull_dispatch_table); + + def_sampler( + m, "_power", + "Fill the result with power distribution samples of exponent a - 1", + power_dispatch_table); + + def_sampler( + m, "_rayleigh", "Fill the result with Rayleigh samples of mode scale", + rayleigh_dispatch_table); +} +} // namespace dpnp::extensions::rng diff --git a/dpnp/libtensor/extensions/rng/gamma.cpp b/dpnp/libtensor/extensions/rng/gamma.cpp new file mode 100644 index 000000000000..b683f78bdc28 --- /dev/null +++ b/dpnp/libtensor/extensions/rng/gamma.cpp @@ -0,0 +1,69 @@ +//***************************************************************************** +// Copyright (c) 2026, Intel Corporation +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// - Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// - Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// - Neither the name of the copyright holder nor the names of its contributors +// may be used to endorse or promote products derived from this software +// without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF +// THE POSSIBILITY OF SUCH DAMAGE. +//***************************************************************************** +#include + +#include "common.hpp" +#include "distributions.hpp" + +namespace dpnp::extensions::rng +{ +static sample_dispatch_table_t gamma_dispatch_table; +static sample_dispatch_table_t beta_dispatch_table; +static sample_dispatch_table_t chisquare_dispatch_table; +static sample_dispatch_table_t standard_t_dispatch_table; +static sample_dispatch_table_t f_dispatch_table; + +void init_gamma(py::module_ m) +{ + def_sampler( + m, "_gamma", + "Fill the result with gamma samples of shape shape and scale scale", + gamma_dispatch_table); + + def_sampler( + m, "_beta", + "Fill the result with beta samples of shape parameters a and b", + beta_dispatch_table); + + def_sampler( + m, "_chisquare", + "Fill the result with chi-square samples of df degrees of freedom", + chisquare_dispatch_table); + + def_sampler( + m, "_standard_t", + "Fill the result with Student's t samples of df degrees of freedom", + standard_t_dispatch_table); + + def_sampler( + m, "_f", + "Fill the result with F samples of dfnum and dfden degrees of " + "freedom", + f_dispatch_table); +} +} // namespace dpnp::extensions::rng diff --git a/dpnp/libtensor/extensions/rng/kernels/distributions.hpp b/dpnp/libtensor/extensions/rng/kernels/distributions.hpp index 6aea1987355a..3f1a0af62e87 100644 --- a/dpnp/libtensor/extensions/rng/kernels/distributions.hpp +++ b/dpnp/libtensor/extensions/rng/kernels/distributions.hpp @@ -29,6 +29,7 @@ #pragma once #include +#include #include #include @@ -112,4 +113,300 @@ class StandardNormal return r * sycl::sinpi(phi); } }; + +// NumPy's "inv" method; 1 - u is on (0, 1], so the result is finite +template +T standard_exponential(BitGenT &bg) +{ + return -sycl::log1p(-bg.template next_uniform()); +} + +// Marsaglia and Tsang for shape > 1, and a rejection method built on the +// exponential distribution for shape < 1, as in NumPy's +// random_standard_gamma() +template +T standard_gamma(BitGenT &bg, StandardNormal &normal, const T shape) +{ + if (shape == T(1)) { + return standard_exponential(bg); + } + else if (shape == T(0)) { + return T(0); + } + else if (!(shape > T(0))) { + // invalid, and for a shape just below zero every draw would be + // rejected + return std::numeric_limits::quiet_NaN(); + } + else if (shape < T(1)) { + for (;;) { + const T U = bg.template next_uniform(); + const T V = standard_exponential(bg); + if (U <= T(1) - shape) { + const T X = sycl::pow(U, T(1) / shape); + if (X <= V) { + return X; + } + } + else { + const T Y = -sycl::log((T(1) - U) / shape); + const T X = sycl::pow(T(1) - shape + shape * Y, T(1) / shape); + if (X <= (V + Y)) { + return X; + } + } + } + } + + const T b = shape - T(1) / T(3); + const T c = T(1) / sycl::sqrt(T(9) * b); + for (;;) { + T X, V; + do { + X = normal(bg); + V = T(1) + c * X; + } while (V <= T(0)); + + V = V * V * V; + const T U = bg.template next_uniform(); + if (U < T(1) - T(0.0331) * (X * X) * (X * X)) { + return b * V; + } + // log(0) is fine here + if (sycl::log(U) < T(0.5) * X * X + b * (T(1) - V + sycl::log(V))) { + return b * V; + } + } +} + +// Johnk's algorithm when both parameters are at most one, and a ratio of +// gamma variates otherwise, as in NumPy's random_beta() +template +T beta(BitGenT &bg, StandardNormal &normal, const T a, const T b) +{ + if (!(a > T(0)) || !(b > T(0))) { + // invalid input, which Johnk's algorithm would reject forever + return std::numeric_limits::quiet_NaN(); + } + if ((a <= T(1)) && (b <= T(1))) { + // Below this threshold the result is 0 or 1 with overwhelming + // probability, so a single uniform draw decides which. The + // threshold underflows to zero, disabling the shortcut, in float. + constexpr T tiny_threshold = static_cast(3e-103); + if (a < tiny_threshold && b < tiny_threshold) { + const T U = bg.template next_uniform(); + return static_cast((a + b) * U < a); + } + + for (;;) { + const T U = bg.template next_uniform(); + const T V = bg.template next_uniform(); + const T X = sycl::pow(U, T(1) / a); + const T Y = sycl::pow(V, T(1) / b); + const T XpY = X + Y; + // reject if both U and V are 0 + if ((XpY <= T(1)) && (U + V > T(0))) { + T res; + + // NumPy tests X > 0 and Y > 0 here. Devices that flush + // subnormals to zero can see a subnormal X as positive + // while X + Y flushes to zero, so require normal values. + constexpr T min_normal = std::numeric_limits::min(); + if ((X >= min_normal) && (Y >= min_normal)) { + res = X / XpY; + } + else { + // X or Y underflowed, so work with logarithms + const T logX = sycl::log(U) / a; + const T logY = sycl::log(V) / b; + const T delta = logX - logY; + if (delta > T(0)) { + res = sycl::exp(-sycl::log1p(sycl::exp(-delta))); + } + else { + res = sycl::exp(delta - sycl::log1p(sycl::exp(delta))); + } + } + + // Division and exp need not be correctly rounded on the + // device, and can land an ulp above 1; NaN is kept + return (res > T(1)) ? T(1) : res; + } + } + } + + const T Ga = standard_gamma(bg, normal, a); + const T Gb = standard_gamma(bg, normal, b); + // as above; this is Ga / Ga when Gb underflows + const T res = Ga / (Ga + Gb); + return (res > T(1)) ? T(1) : res; +} + +template +T chisquare(BitGenT &bg, StandardNormal &normal, const T df) +{ + return T(2) * standard_gamma(bg, normal, df / T(2)); +} + +template +T standard_cauchy(BitGenT &bg, StandardNormal &normal) +{ + const T num = normal(bg); + return num / normal(bg); +} + +template +T standard_t(BitGenT &bg, StandardNormal &normal, const T df) +{ + const T num = normal(bg); + const T denom = standard_gamma(bg, normal, df / T(2)); + return sycl::sqrt(df / T(2)) * num / sycl::sqrt(denom); +} + +template +T f(BitGenT &bg, StandardNormal &normal, const T dfnum, const T dfden) +{ + const T num = chisquare(bg, normal, dfnum) * dfden; + return num / (chisquare(bg, normal, dfden) * dfnum); +} + +template +T laplace(BitGenT &bg, const T loc, const T scale) +{ + for (;;) { + const T U = bg.template next_uniform(); + if (U >= T(0.5)) { + return loc - scale * sycl::log(T(2) - U - U); + } + else if (U > T(0)) { + return loc + scale * sycl::log(U + U); + } + // reject U == 0 + } +} + +template +T gumbel(BitGenT &bg, const T loc, const T scale) +{ + for (;;) { + const T U = T(1) - bg.template next_uniform(); + if (U < T(1)) { + return loc - scale * sycl::log(-sycl::log(U)); + } + // reject U == 1 + } +} + +template +T logistic(BitGenT &bg, const T loc, const T scale) +{ + for (;;) { + const T U = bg.template next_uniform(); + if (U > T(0)) { + return loc + scale * sycl::log(U / (T(1) - U)); + } + // reject U == 0 + } +} + +// NumPy's random_wald() takes X = mean + mean/(2*scale)*(Y - sqrt(4*scale*Y + +// Y*Y)), which cancels, and overflows in float, for large Y. This is the same +// value as mean*4*scale/(sqrt(Y) + sqrt(Y + 4*scale))**2. +template +T wald(BitGenT &bg, StandardNormal &normal, const T mean, const T scale) +{ + const T n = normal(bg); + const T Y = mean * n * n; + const T s = sycl::sqrt(Y) + sycl::sqrt(Y + T(4) * scale); + const T X = mean * (T(4) * scale / (s * s)); + const T U = bg.template next_uniform(); + if (U <= mean / (mean + X)) { + return X; + } + return mean * (mean / X); +} + +template +T triangular(BitGenT &bg, const T left, const T mode, const T right) +{ + const T base = right - left; + const T leftbase = mode - left; + const T ratio = leftbase / base; + const T leftprod = leftbase * base; + const T rightprod = (right - mode) * base; + + const T U = bg.template next_uniform(); + if (U <= ratio) { + return left + sycl::sqrt(U * leftprod); + } + return right - sycl::sqrt((T(1) - U) * rightprod); +} + +// Best and Fisher's algorithm, with the fallbacks of NumPy's +// random_vonmises() for very small and very large kappa +template +T vonmises(BitGenT &bg, StandardNormal &normal, const T mu, const T kappa) +{ + constexpr T pi = T(3.141592653589793238462643383279502884L); + + if (sycl::isnan(kappa)) { + return std::numeric_limits::quiet_NaN(); + } + if (kappa < T(1e-8)) { + // the distribution is uniform on the circle + return pi * (T(2) * bg.template next_uniform() - T(1)); + } + + T s; + if (kappa < T(1e-5)) { + // as in NumPy, whose form of rho is zero in double precision until + // 1.4e-8 + s = T(1) / kappa + kappa; + } + else if (kappa <= T(1e6)) { + // rho = (r - sqrt(2 r)) / (2 kappa), without the cancellation which + // makes it zero in single precision for kappa below about 4e-4, + // where every draw would be rejected + const T r = T(1) + sycl::sqrt(T(1) + T(4) * kappa * kappa); + const T rho = T(2) * kappa / (r + sycl::sqrt(T(2) * r)); + s = (T(1) + rho * rho) / (T(2) * rho); + } + else { + // a wrapped normal approximates the distribution for large kappa + T result = mu + sycl::sqrt(T(1) / kappa) * normal(bg); + if (result < -pi) { + result += T(2) * pi; + } + if (result > pi) { + result -= T(2) * pi; + } + return result; + } + + T W; + for (;;) { + const T U = bg.template next_uniform(); + const T Z = sycl::cospi(U); + W = (T(1) + s * Z) / (s + Z); + const T Y = kappa * (s - W); + const T V = bg.template next_uniform(); + // V == 0 is fine: Y >= 0 always accepts and Y < 0 always rejects + if ((Y * (T(2) - Y) - V >= T(0)) || + (sycl::log(Y / V) + T(1) - Y >= T(0))) { + break; + } + } + + const T U = bg.template next_uniform(); + T result = sycl::acos(W); + if (U < T(0.5)) { + result = -result; + } + result += mu; + + const bool neg = (result < T(0)); + T mod = sycl::fabs(result); + mod = sycl::fmod(mod + pi, T(2) * pi) - pi; + return neg ? -mod : mod; +} } // namespace dpnp::kernels::rng diff --git a/dpnp/libtensor/extensions/rng/kernels/sample.hpp b/dpnp/libtensor/extensions/rng/kernels/sample.hpp index d48697820cc4..ab3979478c4f 100644 --- a/dpnp/libtensor/extensions/rng/kernels/sample.hpp +++ b/dpnp/libtensor/extensions/rng/kernels/sample.hpp @@ -51,7 +51,8 @@ namespace dpnp::kernels::rng // number of elements, never on the device, the layout chosen for it or how // the work-items are scheduled. Raw bits and uniform floats are therefore // the same on every device, while samplers using transcendental functions -// agree only to a few ULP. +// agree only to a few ULP, or differ where a rejection sampler then takes +// another candidate. enum class Layout { strided, diff --git a/dpnp/libtensor/extensions/rng/kernels/samplers.hpp b/dpnp/libtensor/extensions/rng/kernels/samplers.hpp index c3edfa92ffe2..abe3e67d7975 100644 --- a/dpnp/libtensor/extensions/rng/kernels/samplers.hpp +++ b/dpnp/libtensor/extensions/rng/kernels/samplers.hpp @@ -142,4 +142,388 @@ class NormalSampler : public SamplerBase } } }; + +// Log-normal: exp of a normal with mean `mean` and standard deviation `sigma` +template +class LognormalSampler : public SamplerBase +{ +private: + Param mean_; + Param sigma_; + StandardNormal normal_{}; + +public: + // one normal, half a pair of uniform values, per element + static constexpr unsigned words_per_item = uniform_words; + + LognormalSampler(const Param &mean, const Param &sigma) + : mean_(mean), sigma_(sigma) + { + } + + template + T operator()(BitGenT &bg, const IndexT i) + { + return sycl::exp(mean_[i] + sigma_[i] * normal_(bg)); + } +}; + +template +class StandardCauchySampler : public SamplerBase +{ +private: + StandardNormal normal_{}; + +public: + // two normals per element + static constexpr unsigned words_per_item = 2 * uniform_words; + + template + T operator()(BitGenT &bg, const IndexT) + { + return standard_cauchy(bg, normal_); + } +}; + +// Wald (inverse Gaussian) with mean `mean` and shape `scale` +template +class WaldSampler : public SamplerBase +{ +private: + Param mean_; + Param scale_; + StandardNormal normal_{}; + +public: + // one normal and one uniform value per element + static constexpr unsigned words_per_item = 2 * uniform_words; + + WaldSampler(const Param &mean, const Param &scale) + : mean_(mean), scale_(scale) + { + } + + template + T operator()(BitGenT &bg, const IndexT i) + { + return wald(bg, normal_, mean_[i], scale_[i]); + } +}; + +// Exponential with scale `scale` +template +class ExponentialSampler : public SamplerBase +{ +private: + Param scale_; + +public: + // one uniform value per element + static constexpr unsigned words_per_item = uniform_words; + + explicit ExponentialSampler(const Param &scale) : scale_(scale) {} + + template + T operator()(BitGenT &bg, const IndexT i) + { + return scale_[i] * standard_exponential(bg); + } +}; + +// Pareto II (Lomax) with shape `a` +template +class ParetoSampler : public SamplerBase +{ +private: + Param a_; + +public: + // one uniform value per element + static constexpr unsigned words_per_item = uniform_words; + + explicit ParetoSampler(const Param &a) : a_(a) {} + + template + T operator()(BitGenT &bg, const IndexT i) + { + return sycl::expm1(standard_exponential(bg) / a_[i]); + } +}; + +// Weibull with shape `a` +template +class WeibullSampler : public SamplerBase +{ +private: + Param a_; + +public: + // one uniform value per element + static constexpr unsigned words_per_item = uniform_words; + + explicit WeibullSampler(const Param &a) : a_(a) {} + + template + T operator()(BitGenT &bg, const IndexT i) + { + const T a = a_[i]; + const T E = standard_exponential(bg); + if (a == T(0)) { + return T(0); + } + return sycl::pow(E, T(1) / a); + } +}; + +// Power distribution with exponent `a` - 1, on [0, 1] +template +class PowerSampler : public SamplerBase +{ +private: + Param a_; + +public: + // one uniform value per element + static constexpr unsigned words_per_item = uniform_words; + + explicit PowerSampler(const Param &a) : a_(a) {} + + template + T operator()(BitGenT &bg, const IndexT i) + { + const T E = standard_exponential(bg); + return sycl::pow(-sycl::expm1(-E), T(1) / a_[i]); + } +}; + +// Rayleigh with mode `scale` +template +class RayleighSampler : public SamplerBase +{ +private: + Param scale_; + +public: + // one uniform value per element + static constexpr unsigned words_per_item = uniform_words; + + explicit RayleighSampler(const Param &scale) : scale_(scale) {} + + template + T operator()(BitGenT &bg, const IndexT i) + { + return scale_[i] * sycl::sqrt(T(2) * standard_exponential(bg)); + } +}; + +// Gamma with shape `shape` and scale `scale` +template +class GammaSampler : public SamplerBase +{ +private: + Param shape_; + Param scale_; + StandardNormal normal_{}; + +public: + GammaSampler(const Param &shape, const Param &scale) + : shape_(shape), scale_(scale) + { + } + + template + T operator()(BitGenT &bg, const IndexT i) + { + return scale_[i] * standard_gamma(bg, normal_, shape_[i]); + } +}; + +// Beta with shape parameters `a` and `b` +template +class BetaSampler : public SamplerBase +{ +private: + Param a_; + Param b_; + StandardNormal normal_{}; + +public: + BetaSampler(const Param &a, const Param &b) : a_(a), b_(b) {} + + template + T operator()(BitGenT &bg, const IndexT i) + { + return beta(bg, normal_, a_[i], b_[i]); + } +}; + +// Chi-square with `df` degrees of freedom +template +class ChisquareSampler : public SamplerBase +{ +private: + Param df_; + StandardNormal normal_{}; + +public: + explicit ChisquareSampler(const Param &df) : df_(df) {} + + template + T operator()(BitGenT &bg, const IndexT i) + { + return chisquare(bg, normal_, df_[i]); + } +}; + +// Student's t with `df` degrees of freedom +template +class StandardTSampler : public SamplerBase +{ +private: + Param df_; + StandardNormal normal_{}; + +public: + explicit StandardTSampler(const Param &df) : df_(df) {} + + template + T operator()(BitGenT &bg, const IndexT i) + { + return standard_t(bg, normal_, df_[i]); + } +}; + +// F with `dfnum` and `dfden` degrees of freedom +template +class FSampler : public SamplerBase +{ +private: + Param dfnum_; + Param dfden_; + StandardNormal normal_{}; + +public: + FSampler(const Param &dfnum, const Param &dfden) + : dfnum_(dfnum), dfden_(dfden) + { + } + + template + T operator()(BitGenT &bg, const IndexT i) + { + return f(bg, normal_, dfnum_[i], dfden_[i]); + } +}; + +// Laplace with location `loc` and scale `scale` +template +class LaplaceSampler : public SamplerBase +{ +private: + Param loc_; + Param scale_; + +public: + LaplaceSampler(const Param &loc, const Param &scale) + : loc_(loc), scale_(scale) + { + } + + template + T operator()(BitGenT &bg, const IndexT i) + { + return laplace(bg, loc_[i], scale_[i]); + } +}; + +// Gumbel with location `loc` and scale `scale` +template +class GumbelSampler : public SamplerBase +{ +private: + Param loc_; + Param scale_; + +public: + GumbelSampler(const Param &loc, const Param &scale) + : loc_(loc), scale_(scale) + { + } + + template + T operator()(BitGenT &bg, const IndexT i) + { + return gumbel(bg, loc_[i], scale_[i]); + } +}; + +// Logistic with location `loc` and scale `scale` +template +class LogisticSampler : public SamplerBase +{ +private: + Param loc_; + Param scale_; + +public: + LogisticSampler(const Param &loc, const Param &scale) + : loc_(loc), scale_(scale) + { + } + + template + T operator()(BitGenT &bg, const IndexT i) + { + return logistic(bg, loc_[i], scale_[i]); + } +}; + +// Triangular on [left, right] with mode `mode` +template +class TriangularSampler : public SamplerBase +{ +private: + Param left_; + Param mode_; + Param right_; + +public: + // one uniform value per element + static constexpr unsigned words_per_item = uniform_words; + + TriangularSampler(const Param &left, + const Param &mode, + const Param &right) + : left_(left), mode_(mode), right_(right) + { + } + + template + T operator()(BitGenT &bg, const IndexT i) + { + return triangular(bg, left_[i], mode_[i], right_[i]); + } +}; + +// von Mises with mode `mu` and concentration `kappa`, on [-pi, pi] +template +class VonmisesSampler : public SamplerBase +{ +private: + Param mu_; + Param kappa_; + StandardNormal normal_{}; + +public: + VonmisesSampler(const Param &mu, const Param &kappa) + : mu_(mu), kappa_(kappa) + { + } + + template + T operator()(BitGenT &bg, const IndexT i) + { + return vonmises(bg, normal_, mu_[i], kappa_[i]); + } +}; } // namespace dpnp::kernels::rng diff --git a/dpnp/libtensor/extensions/rng/normal.cpp b/dpnp/libtensor/extensions/rng/normal.cpp index b2660ae48ad4..df49ab1a032d 100644 --- a/dpnp/libtensor/extensions/rng/normal.cpp +++ b/dpnp/libtensor/extensions/rng/normal.cpp @@ -33,6 +33,9 @@ namespace dpnp::extensions::rng { static sample_dispatch_table_t normal_dispatch_table; +static sample_dispatch_table_t lognormal_dispatch_table; +static sample_dispatch_table_t standard_cauchy_dispatch_table; +static sample_dispatch_table_t wald_dispatch_table; void init_normal(py::module_ m) { @@ -41,5 +44,20 @@ void init_normal(py::module_ m) "Fill the result with normal samples of mean loc and standard " "deviation scale", normal_dispatch_table); + + def_sampler( + m, "_lognormal", + "Fill the result with log-normal samples whose logarithm has mean " + "mean and standard deviation sigma", + lognormal_dispatch_table); + + def_sampler( + m, "_standard_cauchy", "Fill the result with standard Cauchy samples", + standard_cauchy_dispatch_table); + + def_sampler( + m, "_wald", + "Fill the result with Wald samples of mean mean and shape scale", + wald_dispatch_table); } } // namespace dpnp::extensions::rng diff --git a/dpnp/libtensor/extensions/rng/rng_py.cpp b/dpnp/libtensor/extensions/rng/rng_py.cpp index eba9388c12a8..e7f058d9770d 100644 --- a/dpnp/libtensor/extensions/rng/rng_py.cpp +++ b/dpnp/libtensor/extensions/rng/rng_py.cpp @@ -56,4 +56,6 @@ PYBIND11_MODULE(_rng_impl, m, py::mod_gil_not_used()) rng_ns::init_uniform(m); rng_ns::init_normal(m); + rng_ns::init_exponential(m); + rng_ns::init_gamma(m); } diff --git a/dpnp/libtensor/extensions/rng/uniform.cpp b/dpnp/libtensor/extensions/rng/uniform.cpp index a9a44d92ccb4..5eea70564704 100644 --- a/dpnp/libtensor/extensions/rng/uniform.cpp +++ b/dpnp/libtensor/extensions/rng/uniform.cpp @@ -34,6 +34,11 @@ namespace dpnp::extensions::rng { static sample_dispatch_table_t uniform_dispatch_table; static sample_dispatch_table_t random_raw_dispatch_table; +static sample_dispatch_table_t laplace_dispatch_table; +static sample_dispatch_table_t gumbel_dispatch_table; +static sample_dispatch_table_t logistic_dispatch_table; +static sample_dispatch_table_t triangular_dispatch_table; +static sample_dispatch_table_t vonmises_dispatch_table; void init_uniform(py::module_ m) { @@ -46,5 +51,35 @@ void init_uniform(py::module_ m) "Fill the result with the raw 64-bit output of the engine, or with " "one 32-bit word per element", random_raw_dispatch_table); + + def_sampler( + m, "_laplace", + "Fill the result with Laplace samples of location loc and scale " + "scale", + laplace_dispatch_table); + + def_sampler( + m, "_gumbel", + "Fill the result with Gumbel samples of location loc and scale " + "scale", + gumbel_dispatch_table); + + def_sampler( + m, "_logistic", + "Fill the result with logistic samples of location loc and scale " + "scale", + logistic_dispatch_table); + + def_sampler( + m, "_triangular", + "Fill the result with triangular samples on [left, right] with mode " + "mode", + triangular_dispatch_table); + + def_sampler( + m, "_vonmises", + "Fill the result with von Mises samples of mode mu and " + "concentration kappa", + vonmises_dispatch_table); } } // namespace dpnp::extensions::rng diff --git a/dpnp/random/_bit_generator.py b/dpnp/random/_bit_generator.py index e7349c524ae6..65f54543e4e2 100644 --- a/dpnp/random/_bit_generator.py +++ b/dpnp/random/_bit_generator.py @@ -395,7 +395,8 @@ class Philox4x3210(BitGenerator): values depend on the output size: a draw is not a prefix of a larger one. For a given state, output size and data type, the raw bits and the uniform floats are the same on every device, while the samplers built on - transcendental functions, such as the normal one, agree to a few ULP. + transcendental functions agree to a few ULP, or differ where a rejection + sampler then takes another candidate. """ diff --git a/dpnp/random/_generator.py b/dpnp/random/_generator.py index 5425e4a40738..28bea1135b56 100644 --- a/dpnp/random/_generator.py +++ b/dpnp/random/_generator.py @@ -37,6 +37,7 @@ # pylint: disable=no-name-in-module # pylint: disable=protected-access +# pylint: disable=too-many-lines import itertools @@ -44,6 +45,7 @@ import dpnp import dpnp.libtensor._rng_impl as ri +import dpnp.libtensor._tensor_impl as ti import dpnp.tensor as dpt from dpnp.exceptions import ExecutionPlacementError from dpnp.tensor import validate_usm_type @@ -57,6 +59,7 @@ # numpy/random/_common.pyx _CONS_NONE = 0 _CONS_NON_NEGATIVE = 1 +_CONS_POSITIVE = 2 # Python scalars, the most common parameters, skip the NumPy checks @@ -140,6 +143,21 @@ def _as_host_float(value): return numpy.asarray(value, dtype=numpy.float64) +def _check_arrays(params, dtype=None): + """ + `params` as arrays of `dtype` to check, with the module to check them + by, which is ``None`` when some are on the device, as the check would + wait for the device. + + """ + + if any(dpnp.is_supported_array_type(p) for p in params): + return None, [None] * len(params) + for p in params: + _check_host_cast(p) + return numpy, [numpy.asarray(p, dtype) for p in params] + + def _uniform_range(low, high, dtype, overflow_msg): """ ``high - low``, raising OverflowError with `overflow_msg` unless it is @@ -194,8 +212,12 @@ def _check_constraint(value, name, cons, scalar): if cons == _CONS_NON_NEGATIVE: if numpy.any(~numpy.isnan(val) & numpy.signbit(val)): raise ValueError(f"{name} < 0") + elif cons == _CONS_POSITIVE: + if numpy.any(val <= 0): + raise ValueError(f"{name} <= 0") +# pylint: disable=too-many-public-methods class Generator: """ A container for the bit generator and the distribution samplers. @@ -441,8 +463,19 @@ def _to_kernel_param(p): p, dtype=dtype, usm_type=usm_type, sycl_queue=queue ) if _repeats_along_samples(p.shape, shape): - return dpnp.ascontiguousarray(p) - return dpnp.ascontiguousarray(dpnp.broadcast_to(p, shape)) + p = dpnp.ascontiguousarray(p) + else: + p = dpnp.ascontiguousarray(dpnp.broadcast_to(p, shape)) + if out is not None: + usm_p, usm_out = map(dpnp.get_usm_ndarray, (p, out)) + # the kernel reads element i % p.size of `p` before + # writing element i of `out`, so only an exact alias is + # safe + if ti._array_overlap( + usm_p, usm_out + ) and not ti._same_logical_tensors(usm_p, usm_out): + p = dpnp.copy(p) + return p # as in NumPy, None is NaN along with array parameters return float(_as_host_float(p)) @@ -786,6 +819,465 @@ def normal( (scale, "scale", _CONS_NON_NEGATIVE), ) + def lognormal( + self, mean=0.0, sigma=1.0, size=None, dtype=None, *, usm_type=None + ): + """ + Draw samples from a log-normal distribution. + + For full documentation refer to + :obj:`numpy.random.Generator.lognormal`. + + Limitations + ----------- + `dtype` and `usm_type` are not in NumPy's signature. + + """ + return self._cont( + ri._lognormal, + "lognormal", + size, + dtype, + usm_type, + (mean, "mean", _CONS_NONE), + (sigma, "sigma", _CONS_NON_NEGATIVE), + ) + + def standard_cauchy(self, size=None, dtype=None, *, usm_type=None): + """ + Draw samples from a standard Cauchy distribution with mode = 0. + + For full documentation refer to + :obj:`numpy.random.Generator.standard_cauchy`. + + Limitations + ----------- + `dtype` and `usm_type` are not in NumPy's signature. + + """ + return self._float_sample( + ri._standard_cauchy, (), size, dtype, usm_type, "standard_cauchy" + ) + + def wald(self, mean, scale, size=None, dtype=None, *, usm_type=None): + """ + Draw samples from a Wald, or inverse Gaussian, distribution. + + For full documentation refer to :obj:`numpy.random.Generator.wald`. + + Limitations + ----------- + `dtype` and `usm_type` are not in NumPy's signature. + + """ + return self._cont( + ri._wald, + "wald", + size, + dtype, + usm_type, + (mean, "mean", _CONS_POSITIVE), + (scale, "scale", _CONS_POSITIVE), + ) + + def standard_exponential( + self, + size=None, + dtype=None, + method="zig", + out=None, + *, + usm_type=None, + ): + """ + Draw samples from the standard exponential distribution. + + For full documentation refer to + :obj:`numpy.random.Generator.standard_exponential`. + + Limitations + ----------- + Both methods use inversion; ``"zig"`` is accepted for compatibility. + + """ + + if method not in ("zig", "inv"): + raise ValueError("method must be either 'inv' or 'zig'") + return self._float_sample( + ri._exponential, + (), + size, + dtype, + usm_type, + "standard_exponential", + out=out, + kernel_params=(1.0,), + ) + + def exponential(self, scale=1.0, size=None, dtype=None, *, usm_type=None): + """ + Draw samples from an exponential distribution. + + For full documentation refer to + :obj:`numpy.random.Generator.exponential`. + + Limitations + ----------- + `dtype` and `usm_type` are not in NumPy's signature. + + """ + return self._cont( + ri._exponential, + "exponential", + size, + dtype, + usm_type, + (scale, "scale", _CONS_NON_NEGATIVE), + ) + + def pareto(self, a, size=None, dtype=None, *, usm_type=None): + """ + Draw samples from a Pareto II (AKA Lomax) distribution with the + specified shape. + + For full documentation refer to :obj:`numpy.random.Generator.pareto`. + + Limitations + ----------- + `dtype` and `usm_type` are not in NumPy's signature. + + """ + return self._cont( + ri._pareto, + "pareto", + size, + dtype, + usm_type, + (a, "a", _CONS_POSITIVE), + ) + + def weibull(self, a, size=None, dtype=None, *, usm_type=None): + """ + Draw samples from a Weibull distribution. + + For full documentation refer to :obj:`numpy.random.Generator.weibull`. + + Limitations + ----------- + `dtype` and `usm_type` are not in NumPy's signature. + + """ + return self._cont( + ri._weibull, + "weibull", + size, + dtype, + usm_type, + (a, "a", _CONS_NON_NEGATIVE), + ) + + def power(self, a, size=None, dtype=None, *, usm_type=None): + """ + Draw samples in [0, 1] from a power distribution with positive + exponent ``a - 1``. + + For full documentation refer to :obj:`numpy.random.Generator.power`. + + Limitations + ----------- + `dtype` and `usm_type` are not in NumPy's signature. + + """ + return self._cont( + ri._power, "power", size, dtype, usm_type, (a, "a", _CONS_POSITIVE) + ) + + def rayleigh(self, scale=1.0, size=None, dtype=None, *, usm_type=None): + """ + Draw samples from a Rayleigh distribution. + + For full documentation refer to + :obj:`numpy.random.Generator.rayleigh`. + + Limitations + ----------- + `dtype` and `usm_type` are not in NumPy's signature. + + """ + return self._cont( + ri._rayleigh, + "rayleigh", + size, + dtype, + usm_type, + (scale, "scale", _CONS_NON_NEGATIVE), + ) + + def laplace( + self, loc=0.0, scale=1.0, size=None, dtype=None, *, usm_type=None + ): + """ + Draw samples from the Laplace or double exponential distribution + with specified location (or mean) and scale (decay). + + For full documentation refer to :obj:`numpy.random.Generator.laplace`. + + Limitations + ----------- + `dtype` and `usm_type` are not in NumPy's signature. + + """ + return self._cont( + ri._laplace, + "laplace", + size, + dtype, + usm_type, + (loc, "loc", _CONS_NONE), + (scale, "scale", _CONS_NON_NEGATIVE), + ) + + def gumbel( + self, loc=0.0, scale=1.0, size=None, dtype=None, *, usm_type=None + ): + """ + Draw samples from a Gumbel distribution. + + For full documentation refer to :obj:`numpy.random.Generator.gumbel`. + + Limitations + ----------- + `dtype` and `usm_type` are not in NumPy's signature. + + """ + return self._cont( + ri._gumbel, + "gumbel", + size, + dtype, + usm_type, + (loc, "loc", _CONS_NONE), + (scale, "scale", _CONS_NON_NEGATIVE), + ) + + def logistic( + self, loc=0.0, scale=1.0, size=None, dtype=None, *, usm_type=None + ): + """ + Draw samples from a logistic distribution. + + For full documentation refer to + :obj:`numpy.random.Generator.logistic`. + + Limitations + ----------- + `dtype` and `usm_type` are not in NumPy's signature. + + """ + return self._cont( + ri._logistic, + "logistic", + size, + dtype, + usm_type, + (loc, "loc", _CONS_NONE), + (scale, "scale", _CONS_NON_NEGATIVE), + ) + + def triangular( + self, left, mode, right, size=None, dtype=None, *, usm_type=None + ): + """ + Draw samples from the triangular distribution over the interval + [left, right]. + + For full documentation refer to + :obj:`numpy.random.Generator.triangular`. + + Limitations + ----------- + `dtype` and `usm_type` are not in NumPy's signature. + + """ + + params = (left, mode, right) + self._check_queues(*params) + xp, (fleft, fmode, fright) = _check_arrays(params, numpy.float64) + if xp is not None: + if xp is numpy and _is_scalar_path(*params): + for p in params: + _check_real(p) + if xp.any(fleft > fmode): + raise ValueError("left > mode") + if xp.any(fmode > fright): + raise ValueError("mode > right") + if xp.any(fleft == fright): + raise ValueError("left == right") + return self._float_sample( + ri._triangular, params, size, dtype, usm_type, "triangular" + ) + + def vonmises(self, mu, kappa, size=None, dtype=None, *, usm_type=None): + """ + Draw samples from a von Mises distribution. + + For full documentation refer to + :obj:`numpy.random.Generator.vonmises`. + + Limitations + ----------- + `dtype` and `usm_type` are not in NumPy's signature. + + """ + return self._cont( + ri._vonmises, + "vonmises", + size, + dtype, + usm_type, + (mu, "mu", _CONS_NONE), + (kappa, "kappa", _CONS_NON_NEGATIVE), + ) + + def standard_gamma( + self, shape, size=None, dtype=None, out=None, *, usm_type=None + ): + """ + Draw samples from a standard gamma distribution. + + For full documentation refer to + :obj:`numpy.random.Generator.standard_gamma`. + + Limitations + ----------- + `usm_type` is not in NumPy's signature. + + """ + + self._check_queues(shape, out) + _check_constraint( + shape, + "shape", + _CONS_NON_NEGATIVE, + _is_scalar_path(shape), + ) + return self._float_sample( + ri._gamma, + (shape,), + size, + dtype, + usm_type, + "standard_gamma", + out=out, + kernel_params=(shape, 1.0), + ) + + def gamma(self, shape, scale=1.0, size=None, dtype=None, *, usm_type=None): + """ + Draw samples from a gamma distribution. + + For full documentation refer to :obj:`numpy.random.Generator.gamma`. + + Limitations + ----------- + `dtype` and `usm_type` are not in NumPy's signature. + + """ + return self._cont( + ri._gamma, + "gamma", + size, + dtype, + usm_type, + (shape, "shape", _CONS_NON_NEGATIVE), + (scale, "scale", _CONS_NON_NEGATIVE), + ) + + def chisquare(self, df, size=None, dtype=None, *, usm_type=None): + """ + Draw samples from a chi-square distribution. + + For full documentation refer to + :obj:`numpy.random.Generator.chisquare`. + + Limitations + ----------- + `dtype` and `usm_type` are not in NumPy's signature. + + """ + return self._cont( + ri._chisquare, + "chisquare", + size, + dtype, + usm_type, + (df, "df", _CONS_POSITIVE), + ) + + def standard_t(self, df, size=None, dtype=None, *, usm_type=None): + """ + Draw samples from a standard Student's t distribution with `df` + degrees of freedom. + + For full documentation refer to + :obj:`numpy.random.Generator.standard_t`. + + Limitations + ----------- + `dtype` and `usm_type` are not in NumPy's signature. + + """ + return self._cont( + ri._standard_t, + "standard_t", + size, + dtype, + usm_type, + (df, "df", _CONS_POSITIVE), + ) + + def f(self, dfnum, dfden, size=None, dtype=None, *, usm_type=None): + """ + Draw samples from an F distribution. + + For full documentation refer to :obj:`numpy.random.Generator.f`. + + Limitations + ----------- + `dtype` and `usm_type` are not in NumPy's signature. + + """ + return self._cont( + ri._f, + "f", + size, + dtype, + usm_type, + (dfnum, "dfnum", _CONS_POSITIVE), + (dfden, "dfden", _CONS_POSITIVE), + ) + + def beta(self, a, b, size=None, dtype=None, *, usm_type=None): + """ + Draw samples from a beta distribution. + + For full documentation refer to :obj:`numpy.random.Generator.beta`. + + Limitations + ----------- + `dtype` and `usm_type` are not in NumPy's signature. + + """ + return self._cont( + ri._beta, + "beta", + size, + dtype, + usm_type, + (a, "a", _CONS_POSITIVE), + (b, "b", _CONS_POSITIVE), + ) + def default_rng(seed=None, *, device=None, sycl_queue=None): """ diff --git a/dpnp/tests/test_random_generator.py b/dpnp/tests/test_random_generator.py index 4ee24faf8b37..7d72e69d3a7d 100644 --- a/dpnp/tests/test_random_generator.py +++ b/dpnp/tests/test_random_generator.py @@ -405,6 +405,26 @@ class TestFloatMethods: ("uniform", (-1.0, 2.0)), ("standard_normal", ()), ("normal", (1.0, 2.0)), + ("lognormal", (0.0, 0.5)), + ("standard_exponential", ()), + ("exponential", (2.0,)), + ("standard_gamma", (0.5,)), + ("gamma", (3.0, 2.0)), + ("chisquare", (3.0,)), + ("beta", (0.5, 2.0)), + ("standard_cauchy", ()), + ("wald", (1.0, 2.0)), + ("pareto", (3.0,)), + ("weibull", (2.0,)), + ("power", (3.0,)), + ("rayleigh", (2.0,)), + ("laplace", (1.0, 2.0)), + ("gumbel", (1.0, 2.0)), + ("logistic", (1.0, 2.0)), + ("triangular", (0.0, 1.0, 3.0)), + ("vonmises", (0.5, 2.0)), + ("standard_t", (5.0,)), + ("f", (5.0, 7.0)), ] @pytest.mark.parametrize("dtype", float_dtypes) @@ -456,6 +476,47 @@ def test_random_range(self, dtype): ("uniform", (-1.0, 3.0), 1.0, 16 / 12), ("standard_normal", (), 0.0, 1.0), ("normal", (1.0, 2.0), 1.0, 4.0), + ( + "lognormal", + (0.0, 0.5), + numpy.exp(0.125), + (numpy.exp(0.25) - 1) * numpy.exp(0.25), + ), + ("standard_exponential", (), 1.0, 1.0), + ("exponential", (2.0,), 2.0, 4.0), + ("standard_gamma", (0.5,), 0.5, 0.5), + ("standard_gamma", (1.0,), 1.0, 1.0), + ("gamma", (3.0, 2.0), 6.0, 12.0), + ("chisquare", (3.0,), 3.0, 6.0), + ("beta", (0.5, 2.0), 0.2, 8.0 / 175), + ("beta", (0.5, 0.5), 0.5, 0.125), + ("beta", (2.0, 3.0), 0.4, 0.04), + ("wald", (1.0, 2.0), 1.0, 0.5), + ("wald", (3.0, 50.0), 3.0, 27 / 50), + ("pareto", (20.0,), 1 / 19, 20 / (19**2 * 18)), + ( + "weibull", + (2.0,), + math.gamma(1.5), + math.gamma(2.0) - math.gamma(1.5) ** 2, + ), + ("weibull", (0.0,), 0.0, 0.0), + ("power", (3.0,), 0.75, 0.0375), + ("rayleigh", (2.0,), 2 * math.sqrt(math.pi / 2), 2 * (4 - math.pi)), + ("laplace", (1.0, 2.0), 1.0, 8.0), + ( + "gumbel", + (1.0, 2.0), + 1 + 2 * 0.5772156649015329, + math.pi**2 * 4 / 6, + ), + ("logistic", (1.0, 2.0), 1.0, math.pi**2 * 4 / 3), + ("triangular", (0.0, 1.0, 3.0), 4 / 3, 7 / 18), + ("triangular", (0.0, 0.0, 1.0), 1 / 3, 1 / 18), + # uniform on the circle, whatever mu is, as in NumPy + ("vonmises", (0.5, 0.0), 0.0, math.pi**2 / 3), + ("standard_t", (10.0,), 0.0, 1.25), + ("f", (10.0, 30.0), 30 / 28, 2 * 900 * 38 / (10 * 28**2 * 26)), ], ) def test_moments(self, name, params, mean, var, dtype): @@ -468,6 +529,86 @@ def test_moments(self, name, params, mean, var, dtype): assert abs(res.mean() - mean) <= 5 * numpy.sqrt(var / n) assert abs(res.var() - var) <= 5 * var * numpy.sqrt(10 / n) + @pytest.mark.parametrize("dtype", float_dtypes) + def test_standard_cauchy(self, dtype): + res = default_rng(2).standard_cauchy(size=10**6, dtype=dtype) + q1, q2, q3 = numpy.quantile(dpnp.asnumpy(res), [0.25, 0.5, 0.75]) + assert abs(q1 + 1) < 0.01 and abs(q2) < 0.01 and abs(q3 - 1) < 0.01 + + @pytest.mark.parametrize("dtype", float_dtypes) + @pytest.mark.parametrize("kappa", [1e-9, 1e-6, 0.5, 2.0, 50.0, 1e7]) + def test_vonmises(self, kappa, dtype): + n = 10**6 + mu = 3.0 + res = default_rng(2).vonmises(mu, kappa, size=n, dtype=dtype) + res = dpnp.asnumpy(res).astype(numpy.float64) + assert ((res >= -numpy.pi) & (res <= numpy.pi)).all() + + # E[cos(x - mu)] is I1(kappa) / I0(kappa) + t = numpy.linspace(0, numpy.pi, 20001) + w = numpy.exp(kappa * (numpy.cos(t) - 1)) + expected = numpy.trapezoid(numpy.cos(t) * w, t) / numpy.trapezoid(w, t) + assert abs(numpy.cos(res - mu).mean() - expected) < 5 / numpy.sqrt(n) + # the angles are symmetric around mu + assert abs(numpy.sin(res - mu).mean()) < 5 / numpy.sqrt(n) + + @pytest.mark.parametrize("dtype", float_dtypes) + @pytest.mark.parametrize( + "name, params, lo, hi", + [ + ("pareto", (1e-3,), 0, numpy.inf), + ("weibull", (1e-3,), 0, numpy.inf), + ("power", (1e-3,), 0, 1), + ("power", (1e3,), 0, 1), + ("wald", (1e10, 1e-10), 0, numpy.inf), + ("wald", (1e-10, 1e10), 0, numpy.inf), + ("triangular", (0.0, 1.0, 1.0), 0, 1), + ("vonmises", (-3.0, 1e-3), -numpy.pi, numpy.pi), + ], + ) + def test_extreme_range(self, name, params, lo, hi, dtype): + res = getattr(default_rng(1), name)(*params, size=10**5, dtype=dtype) + res = dpnp.asnumpy(res) + assert ((res >= lo) & (res <= hi)).all() + + @pytest.mark.parametrize( + "name, params", + [ + ("wald", (1.0, 1.0)), + ("pareto", (1.0,)), + ("weibull", (1.0,)), + ("power", (1.0,)), + ("rayleigh", (1.0,)), + ("laplace", (0.0, 1.0)), + ("gumbel", (0.0, 1.0)), + ("logistic", (0.0, 1.0)), + ("vonmises", (0.0, 1.0)), + ("chisquare", (1.0,)), + ("standard_t", (1.0,)), + ("f", (1.0, 1.0)), + ("gamma", (1.0, 1.0)), + ("beta", (1.0, 1.0)), + ], + ) + def test_nan_param(self, name, params): + # NaN passes NumPy's checks and gives NaN; every parameter is tried + rng = default_rng(0) + for i in range(len(params)): + args = list(params) + args[i] = numpy.nan + res = dpnp.asnumpy(getattr(rng, name)(*args, size=100)) + assert numpy.isnan(res).all() + + @pytest.mark.parametrize("dtype", float_dtypes) + @pytest.mark.parametrize( + "a, b", [(1e-3, 1e-3), (0.01, 0.01), (0.3, 1e-4), (50.0, 0.01)] + ) + def test_beta_range(self, a, b, dtype): + # the samples underflow, which devices flushing subnormals to zero + # and with inexact division once turned into inf or 1 + ulp + res = dpnp.asnumpy(default_rng(1).beta(a, b, size=10**5, dtype=dtype)) + assert ((res >= 0) & (res <= 1)).all() + def test_array_params(self): rng = default_rng(3) loc = dpnp.arange(4.0)[:, None] * 10 @@ -475,11 +616,20 @@ def test_array_params(self): assert res.shape == (4, 10000) assert_allclose(res.mean(axis=1), [0.0, 10.0, 20.0, 30.0], atol=0.1) + # the output shape is the broadcast shape of the parameters + res = rng.gamma(dpnp.ones(3), numpy.ones((2, 1))) + assert res.shape == (2, 3) + # parameters given as lists res = rng.uniform([0.0, 10.0], [1.0, 11.0], size=(1000, 2)) res = dpnp.asnumpy(res) assert (res[:, 0] < 1).all() and (res[:, 1] >= 10).all() + def test_array_params_chisquare(self): + df = dpnp.asarray([1.0, 10.0]) + res = default_rng(4).chisquare(df, size=(10**5, 2)) + assert_allclose(dpnp.asnumpy(res.mean(axis=0)), [1.0, 10.0], rtol=0.05) + @pytest.mark.parametrize( "param_shape, expected", [ @@ -575,6 +725,13 @@ def test_size_not_broadcastable(self): "name, params, msg", [ ("normal", (0.0, -1.0), "scale < 0"), + ("lognormal", (0.0, -1.0), "sigma < 0"), + ("exponential", (-1.0,), "scale < 0"), + ("standard_gamma", (-1.0,), "shape < 0"), + ("gamma", (1.0, -1.0), "scale < 0"), + ("chisquare", (0.0,), "df <= 0"), + ("beta", (0.0, 1.0), "a <= 0"), + ("beta", (1.0, 0.0), "b <= 0"), ], ) def test_scalar_checks(self, name, params, msg): @@ -665,12 +822,42 @@ def test_usm_type_follows_params(self, usm_types, expected): # host parameters alone give a device array assert rng.normal([1.0, 2.0]).usm_type == "device" + def test_standard_exponential_method(self): + rng = default_rng(0) + rng.standard_exponential(3, method="inv") + assert_raises(ValueError, rng.standard_exponential, 3, method="x") + + def test_out_overlapping_param(self): + # a parameter overlapping `out` is read before `out` is written + dt = dpnp.default_float_type() + x = dpnp.arange(1, 10, dtype=dt) + expected = default_rng(3).standard_gamma(dpnp.copy(x[:-1])) + out = x[1:] + res = default_rng(3).standard_gamma(x[:-1], out=out) + assert res is out + assert_array_equal(out, expected) + assert x[0] == 1 + + # an exact alias needs no copy + y = dpnp.arange(1, 9, dtype=dt) + expected = default_rng(3).standard_gamma(dpnp.copy(y)) + default_rng(3).standard_gamma(y, out=y) + assert_array_equal(y, expected) + + # a smaller parameter is read by many work-items, so it is copied + z = dpnp.arange(1, 9, dtype=dt).reshape(4, 2) + expected = default_rng(3).standard_gamma(dpnp.copy(z[0]), size=(4, 2)) + default_rng(3).standard_gamma(z[0], out=z) + assert_array_equal(z, expected) + @pytest.mark.parametrize("dtype", float_dtypes) @pytest.mark.parametrize( "name, params", [ ("random", ()), ("standard_normal", ()), + ("standard_exponential", ()), + ("standard_gamma", (2.0,)), ], ) def test_out(self, name, params, dtype): @@ -742,6 +929,33 @@ def test_out_read_only(self): out=out, ) + def test_device_params_terminate(self): + # the parameters on which the rejection samplers could loop forever + # give NaN + rng = default_rng(0) + nan, inf = numpy.nan, numpy.inf + + res = rng.beta(dpnp.asarray([-inf, -1.0, 0.0, nan]), 1.0, size=(8, 4)) + assert dpnp.isnan(res).all() + + # a shape just below zero would reject nearly every draw + shape = dpnp.asarray([-1e-8, -1e-12, -1e-30, -1.0]) + res = rng.standard_gamma(shape, size=(8, 4)) + assert dpnp.isnan(res).all() + res = rng.chisquare(shape, size=(8, 4)) + assert dpnp.isnan(res).all() + res = rng.standard_gamma(shape.astype(dpnp.float32), dtype="f4") + assert dpnp.isnan(res).all() + rng.standard_t(shape) + + def test_host_params_terminate(self): + # valid parameters on which rounding in single precision made every + # draw of the rejection sampler fail + rng = default_rng(0) + kappa = [5e-5, 1e-4, 3e-4, 4e-4] + res = rng.vonmises(0.0, kappa, size=(8, 4), dtype=dpnp.float32) + assert (dpnp.abs(res) <= numpy.pi).all() + def _assert_same_error(np_call, dp_call): """Assert `dp_call` raises the same exception as `np_call`.""" @@ -768,6 +982,35 @@ class TestChecks: ("normal", (0.0, -1.0)), ("normal", (0.0, -0.0)), ("normal", (0.0, [1.0, -1.0])), + ("lognormal", (0.0, -1.0)), + ("exponential", (-1.0,)), + ("exponential", ([-1.0],)), + ("standard_gamma", (-0.0,)), + ("gamma", (1.0, -1.0)), + ("gamma", ([-1.0], 1.0)), + ("chisquare", (0.0,)), + ("chisquare", ([1.0, 0.0],)), + ("standard_t", (0.0,)), + ("f", (0.0, 1.0)), + ("f", (1.0, [0.0])), + ("beta", (0.0, 1.0)), + ("beta", (1.0, [0.0])), + ("pareto", (0.0,)), + ("power", (0.0,)), + ("weibull", (-1.0,)), + ("weibull", (-0.0,)), + ("rayleigh", (-1.0,)), + ("laplace", (0.0, -1.0)), + ("gumbel", (0.0, -1.0)), + ("logistic", (0.0, -1.0)), + ("wald", (0.0, 1.0)), + ("wald", (1.0, 0.0)), + ("wald", ([1.0], [0.0])), + ("vonmises", (0.0, -1.0)), + ("triangular", (1.0, 0.0, 2.0)), + ("triangular", (0.0, 2.0, 1.0)), + ("triangular", (1.0, 1.0, 1.0)), + ("triangular", ([0.0, 1.0], 1.0, [2.0, 1.0])), ("normal", (0.0, None)), ("uniform", (None, 1.0)), # complex and object arrays do not cast safely to float64 @@ -777,6 +1020,9 @@ class TestChecks: ("normal", ([1j, 2j],)), ("uniform", (numpy.array([1j]), 2.0)), ("uniform", (0.0, numpy.array(2j))), + ("triangular", (0.0, None, 2.0)), + ("exponential", ("x",)), + ("exponential", (1j,)), ], ) @pytest.mark.filterwarnings("ignore:overflow encountered:RuntimeWarning") @@ -792,6 +1038,9 @@ def test_same_as_numpy(self, name, args): "name, args", [ ("normal", (None, [1.0, 2.0])), + ("laplace", (0.0, [None, 1.0])), + ("gamma", (None, [1.0, 2.0])), + ("triangular", (None, [1.0, 2.0], 3.0)), ], ) def test_none_with_array_is_nan(self, name, args): @@ -808,6 +1057,7 @@ def _draw(self, device, bitgen): rng.random(1000, dtype=dpnp.float32), rng.bit_generator.random_raw(1000), rng.normal(size=1000, dtype=dpnp.float32), + rng.gamma(0.7, size=1000, dtype=dpnp.float32), ) @pytest.mark.parametrize("bitgen", [Philox4x3210]) diff --git a/dpnp/tests/test_sycl_queue.py b/dpnp/tests/test_sycl_queue.py index 5b28cedd3384..242fdb026125 100644 --- a/dpnp/tests/test_sycl_queue.py +++ b/dpnp/tests/test_sycl_queue.py @@ -943,10 +943,30 @@ def test_random_state(func, args, kwargs, device, usm_type): _generator_methods = [ + pytest.param("beta", [0.5, 2.0], {"size": (3, 4)}), + pytest.param("chisquare", [3.0], {"size": (3, 4)}), + pytest.param("exponential", [2.0], {"size": (3, 4)}), + pytest.param("f", [2.0, 3.0], {"size": (3, 4)}), + pytest.param("gamma", [2.0], {"size": (3, 4)}), + pytest.param("gumbel", [], {"size": (3, 4)}), + pytest.param("laplace", [], {"size": (3, 4)}), + pytest.param("logistic", [], {"size": (3, 4)}), + pytest.param("lognormal", [], {"size": (3, 4)}), pytest.param("normal", [], {"size": (3, 4)}), + pytest.param("pareto", [2.0], {"size": (3, 4)}), + pytest.param("power", [2.0], {"size": (3, 4)}), pytest.param("random", [], {"size": (3, 4)}), + pytest.param("rayleigh", [], {"size": (3, 4)}), + pytest.param("standard_cauchy", [], {"size": (3, 4)}), + pytest.param("standard_exponential", [], {"size": (3, 4)}), + pytest.param("standard_gamma", [2.0], {"size": (3, 4)}), pytest.param("standard_normal", [], {"size": (3, 4)}), + pytest.param("standard_t", [3.0], {"size": (3, 4)}), + pytest.param("triangular", [0.0, 1.0, 3.0], {"size": (3, 4)}), pytest.param("uniform", [], {"size": (3, 4)}), + pytest.param("vonmises", [0.0, 1.0], {"size": (3, 4)}), + pytest.param("wald", [1.0, 2.0], {"size": (3, 4)}), + pytest.param("weibull", [2.0], {"size": (3, 4)}), ] @@ -981,6 +1001,8 @@ def test_bit_generator(bit_generator, device): # queue than the generator's _diff_queue_methods = [ pytest.param("normal", ["f"]), + pytest.param("standard_gamma", ["f"]), + pytest.param("triangular", [0.0, "f", 5.0]), pytest.param("uniform", ["f", 5.0]), ] diff --git a/dpnp/tests/test_usm_type.py b/dpnp/tests/test_usm_type.py index c7e1971a6157..7f4c8ba0d2fc 100644 --- a/dpnp/tests/test_usm_type.py +++ b/dpnp/tests/test_usm_type.py @@ -1894,6 +1894,8 @@ def test_tensorsolve(self, usm_type, usm_type_other): [ pytest.param("normal", [[1.0, 2.0]], {}), pytest.param("random", [3], {}), + pytest.param("standard_gamma", [2.0], {"size": 3}), + pytest.param("triangular", [0.0, 1.0, 3.0], {"size": 3}), pytest.param("uniform", [], {"size": 3}), ], ) diff --git a/dpnp/tests/third_party/cupy/random_tests/test_generator_api.py b/dpnp/tests/third_party/cupy/random_tests/test_generator_api.py index 7b343163c871..6945c36c6a2b 100644 --- a/dpnp/tests/third_party/cupy/random_tests/test_generator_api.py +++ b/dpnp/tests/third_party/cupy/random_tests/test_generator_api.py @@ -78,7 +78,6 @@ def test_uniform_ks(self): @testing.parameterize(*common_distributions.exponential_params) @testing.with_requires("numpy>=1.17.0") @testing.fix_random() -@pytest.mark.skip("continuous distributions are not supported yet") class TestExponential(common_distributions.Exponential, GeneratorTestCase): pass @@ -102,14 +101,12 @@ class TestBinomial(common_distributions.Binomial, GeneratorTestCase): @testing.parameterize(*common_distributions.beta_params) @testing.with_requires("numpy>=1.17.0") @testing.fix_random() -@pytest.mark.skip("continuous distributions are not supported yet") class TestBeta(common_distributions.Beta, GeneratorTestCase): pass @testing.with_requires("numpy>=1.17.0") @testing.fix_random() -@pytest.mark.skip("continuous distributions are not supported yet") class TestStandardExponential( InvalidOutsMixin, common_distributions.StandardExponential, @@ -120,7 +117,6 @@ class TestStandardExponential( @testing.parameterize(*common_distributions.gamma_params) @testing.fix_random() -@pytest.mark.skip("continuous distributions are not supported yet") class TestGamma( common_distributions.Gamma, GeneratorTestCase, @@ -130,7 +126,6 @@ class TestGamma( @testing.parameterize(*common_distributions.standard_gamma_params) @testing.fix_random() -@pytest.mark.skip("continuous distributions are not supported yet") class TestStandardGamma( common_distributions.StandardGamma, GeneratorTestCase, @@ -139,7 +134,6 @@ class TestStandardGamma( @testing.fix_random() -@pytest.mark.skip("continuous distributions are not supported yet") class TestStandardGammaInvalid(InvalidOutsMixin, GeneratorTestCase): target_method = "standard_gamma" @@ -167,7 +161,6 @@ def test_invalid_dtypes(self): @testing.fix_random() -@pytest.mark.skip("continuous distributions are not supported yet") class TestStandardGammaEmpty(GeneratorTestCase): target_method = "standard_gamma" @@ -384,7 +377,6 @@ def test_hypergeometric_nbad_zero(self): @testing.parameterize(*common_distributions.power_params) @testing.fix_random() -@pytest.mark.skip("continuous distributions are not supported yet") class TestPower(common_distributions.Power, GeneratorTestCase): pass @@ -397,7 +389,10 @@ class TestPower(common_distributions.Power, GeneratorTestCase): # ) class TestRandomStateThreadSafe(unittest.TestCase): - @pytest.mark.skip("continuous distributions are not supported yet") + # upstream passes a function rather than a tuple as `args` of six threads + @pytest.mark.filterwarnings( + "ignore::pytest.PytestUnhandledThreadExceptionWarning" + ) def test_default_rng_thread_safe(self): def _f(func, args=()): # cupy.cuda.Device().use() @@ -435,14 +430,12 @@ class TestLogseries(common_distributions.Logseries, GeneratorTestCase): @testing.parameterize(*common_distributions.chisquare_params) @testing.fix_random() -@pytest.mark.skip("continuous distributions are not supported yet") class TestChisquare(common_distributions.Chisquare, GeneratorTestCase): pass @testing.parameterize(*common_distributions.f_params) @testing.fix_random() -@pytest.mark.skip("continuous distributions are not supported yet") class TestF(common_distributions.F, GeneratorTestCase): pass From 424dbbb8d73744b48f42b0ff821f20e62d8528ab Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Sat, 7 Nov 2026 12:05:35 -0800 Subject: [PATCH 02/33] Test the C-contiguous out check of the continuous samplers Also pass the dpnp array straight to assert_allclose in the chisquare test. --- dpnp/tests/test_random_generator.py | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/dpnp/tests/test_random_generator.py b/dpnp/tests/test_random_generator.py index 7d72e69d3a7d..46ba19a57c91 100644 --- a/dpnp/tests/test_random_generator.py +++ b/dpnp/tests/test_random_generator.py @@ -628,7 +628,7 @@ def test_array_params(self): def test_array_params_chisquare(self): df = dpnp.asarray([1.0, 10.0]) res = default_rng(4).chisquare(df, size=(10**5, 2)) - assert_allclose(dpnp.asnumpy(res.mean(axis=0)), [1.0, 10.0], rtol=0.05) + assert_allclose(res.mean(axis=0), [1.0, 10.0], rtol=0.05) @pytest.mark.parametrize( "param_shape, expected", @@ -918,6 +918,23 @@ def test_out_f_contiguous(self, name): assert res is usm_out assert_array_equal(usm_out, expected.T) + def test_out_c_contiguous(self): + # with array parameters, out must be C-contiguous, as in NumPy + np_rng = numpy.random.default_rng(0) + rng = default_rng(0) + dt = dpnp.default_float_type(sycl_queue=rng.sycl_queue) + for np_out, out in [ + ( + numpy.empty((3, 4), order="F"), + dpnp.empty((3, 4), dtype=dt, order="F"), + ), + (numpy.empty((3, 8))[:, ::2], dpnp.empty((3, 8), dtype=dt)[:, ::2]), + ]: + _assert_same_error( + lambda: np_rng.standard_gamma(2.0, out=np_out), + lambda: rng.standard_gamma(2.0, out=out), + ) + def test_out_read_only(self): out = dpnp.empty(3, dtype=dpnp.float32) out.flags.writable = False From 9d9722d05b2ccf1a633a722d9cf9df00d95d06d8 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Fri, 13 Nov 2026 13:09:08 -0800 Subject: [PATCH 03/33] Compute vonmises without cancellation for large kappa --- .../extensions/rng/kernels/distributions.hpp | 38 +++++++++++++++---- dpnp/tests/test_random_generator.py | 13 +++++++ 2 files changed, 43 insertions(+), 8 deletions(-) diff --git a/dpnp/libtensor/extensions/rng/kernels/distributions.hpp b/dpnp/libtensor/extensions/rng/kernels/distributions.hpp index 3f1a0af62e87..5ee238755203 100644 --- a/dpnp/libtensor/extensions/rng/kernels/distributions.hpp +++ b/dpnp/libtensor/extensions/rng/kernels/distributions.hpp @@ -357,19 +357,30 @@ T vonmises(BitGenT &bg, StandardNormal &normal, const T mu, const T kappa) return pi * (T(2) * bg.template next_uniform() - T(1)); } - T s; + // s and s - 1, which for large kappa is close to 0: W is then close to + // 1, so 1 - W, s - W and the angle are computed without cancellation + T s, sm1; if (kappa < T(1e-5)) { // as in NumPy, whose form of rho is zero in double precision until // 1.4e-8 s = T(1) / kappa + kappa; + sm1 = s - T(1); } else if (kappa <= T(1e6)) { // rho = (r - sqrt(2 r)) / (2 kappa), without the cancellation which // makes it zero in single precision for kappa below about 4e-4, // where every draw would be rejected - const T r = T(1) + sycl::sqrt(T(1) + T(4) * kappa * kappa); - const T rho = T(2) * kappa / (r + sycl::sqrt(T(2) * r)); + const T q = sycl::sqrt(T(1) + T(4) * kappa * kappa); + const T r = T(1) + q; + const T sqrt_2r = sycl::sqrt(T(2) * r); + const T rho = T(2) * kappa / (r + sqrt_2r); + // 1 - rho, with 2 kappa - q = -1 / (2 kappa + q) for large kappa + const T one_m_rho = + (rho < T(0.5)) + ? T(1) - rho + : (sqrt_2r - T(1) - T(1) / (T(2) * kappa + q)) / (T(2) * kappa); s = (T(1) + rho * rho) / (T(2) * rho); + sm1 = one_m_rho * one_m_rho / (T(2) * rho); } else { // a wrapped normal approximates the distribution for large kappa @@ -383,12 +394,17 @@ T vonmises(BitGenT &bg, StandardNormal &normal, const T mu, const T kappa) return result; } - T W; + // W = (1 + s Z) / (s + Z) for Z = cos(pi U), through 1 - W = + // (s - 1)(1 - Z) / (s + Z) and s - W = (s - 1)(s + 1) / (s + Z), with + // 1 - Z = 2 sin(pi U / 2)**2 and s + Z = s - 1 + 2 cos(pi U / 2)**2 + T one_m_W; for (;;) { const T U = bg.template next_uniform(); - const T Z = sycl::cospi(U); - W = (T(1) + s * Z) / (s + Z); - const T Y = kappa * (s - W); + const T sin_half = sycl::sinpi(U / T(2)); + const T cos_half = sycl::cospi(U / T(2)); + const T s_p_Z = sm1 + T(2) * cos_half * cos_half; + one_m_W = sm1 * T(2) * sin_half * sin_half / s_p_Z; + const T Y = kappa * sm1 * (s + T(1)) / s_p_Z; const T V = bg.template next_uniform(); // V == 0 is fine: Y >= 0 always accepts and Y < 0 always rejects if ((Y * (T(2) - Y) - V >= T(0)) || @@ -397,12 +413,18 @@ T vonmises(BitGenT &bg, StandardNormal &normal, const T mu, const T kappa) } } + // acos(W) = 2 asin(sqrt((1 - W) / 2)), accurate for W close to 1 const T U = bg.template next_uniform(); - T result = sycl::acos(W); + T result = T(2) * sycl::asin(sycl::sqrt(sycl::fmin(one_m_W / T(2), T(1)))); if (U < T(0.5)) { result = -result; } result += mu; + // adding pi to wrap would round the angle to a multiple of ulp(pi), + // which in float takes small angles to 0 + if (sycl::fabs(result) <= pi) { + return result; + } const bool neg = (result < T(0)); T mod = sycl::fabs(result); diff --git a/dpnp/tests/test_random_generator.py b/dpnp/tests/test_random_generator.py index 46ba19a57c91..b27ff1f44238 100644 --- a/dpnp/tests/test_random_generator.py +++ b/dpnp/tests/test_random_generator.py @@ -552,6 +552,19 @@ def test_vonmises(self, kappa, dtype): # the angles are symmetric around mu assert abs(numpy.sin(res - mu).mean()) < 5 / numpy.sqrt(n) + @pytest.mark.parametrize("dtype", float_dtypes) + @pytest.mark.parametrize("kappa", [1e4, 1e6]) + def test_vonmises_large_kappa(self, kappa, dtype): + # 1 - W and the angle lost most bits in single precision, which put + # a fifth of the samples exactly on mu + n = 10**5 + res = default_rng(3).vonmises(0.0, kappa, size=n, dtype=dtype) + res = dpnp.asnumpy(res).astype(numpy.float64) + assert (res == 0).mean() < 1e-4 + assert numpy.unique(numpy.abs(res)).size > 0.9 * n + # the variance of the angle is about 1 / kappa + assert abs(res.var() * kappa - 1) < 0.05 + @pytest.mark.parametrize("dtype", float_dtypes) @pytest.mark.parametrize( "name, params, lo, hi", From c25f6e407687675aa2e2f5b66ea80e392d1ec748 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Fri, 13 Nov 2026 13:10:27 -0800 Subject: [PATCH 04/33] Take the beta shortcut for tiny parameters in single precision too --- .../extensions/rng/kernels/distributions.hpp | 11 +++-- dpnp/random/_generator.py | 49 +++++++++++++++++-- dpnp/tests/test_random_generator.py | 19 +++++++ 3 files changed, 72 insertions(+), 7 deletions(-) diff --git a/dpnp/libtensor/extensions/rng/kernels/distributions.hpp b/dpnp/libtensor/extensions/rng/kernels/distributions.hpp index 5ee238755203..2b1418d74d74 100644 --- a/dpnp/libtensor/extensions/rng/kernels/distributions.hpp +++ b/dpnp/libtensor/extensions/rng/kernels/distributions.hpp @@ -190,12 +190,15 @@ T beta(BitGenT &bg, StandardNormal &normal, const T a, const T b) } if ((a <= T(1)) && (b <= T(1))) { // Below this threshold the result is 0 or 1 with overwhelming - // probability, so a single uniform draw decides which. The - // threshold underflows to zero, disabling the shortcut, in float. - constexpr T tiny_threshold = static_cast(3e-103); + // probability, so a single uniform draw decides which. NumPy's + // threshold is zero in float, where log(U) / a overflows below + // about 5e-38 and the logarithms below would give NaN. + constexpr T tiny_threshold = + std::is_same_v ? T(1e-37) : static_cast(3e-103); if (a < tiny_threshold && b < tiny_threshold) { const T U = bg.template next_uniform(); - return static_cast((a + b) * U < a); + // (a + b) * U would be subnormal, which some devices flush + return static_cast(U < a / (a + b)); } for (;;) { diff --git a/dpnp/random/_generator.py b/dpnp/random/_generator.py index 28bea1135b56..fb921a84371b 100644 --- a/dpnp/random/_generator.py +++ b/dpnp/random/_generator.py @@ -158,6 +158,21 @@ def _check_arrays(params, dtype=None): return numpy, [numpy.asarray(p, dtype) for p in params] +def _raise_to_float32_tiny(value): + """ + Raise a positive host parameter below the smallest normal ``float32`` + value to it, as one that is 0 in ``float32`` would be invalid. + + """ + + if dpnp.is_supported_array_type(value): + return value + tiny = numpy.finfo(numpy.float32).tiny + val = _as_host_float(value) + val = numpy.where((val > 0) & (val < tiny), tiny, val) + return val if val.ndim else float(val) + + def _uniform_range(low, high, dtype, overflow_msg): """ ``high - low``, raising OverflowError with `overflow_msg` unless it is @@ -525,10 +540,21 @@ def _float_sample( kernel_params=kernel_params, ) - def _cont(self, kernel, name, size, dtype, usm_type, *params, out=None): + def _cont( + self, + kernel, + name, + size, + dtype, + usm_type, + *params, + out=None, + kernel_params=None, + ): """ Draw samples of a continuous distribution after checking `params`, triples of the value, the name and the constraint of a parameter. + `kernel_params` replace the values passed to the kernel. """ @@ -538,7 +564,14 @@ def _cont(self, kernel, name, size, dtype, usm_type, *params, out=None): for value, pname, cons in params: _check_constraint(value, pname, cons, scalar) return self._float_sample( - kernel, values, size, dtype, usm_type, name, out=out + kernel, + values, + size, + dtype, + usm_type, + name, + out=out, + kernel_params=kernel_params, ) def random(self, size=None, dtype=None, out=None, *, usm_type=None): @@ -1265,9 +1298,18 @@ def beta(self, a, b, size=None, dtype=None, *, usm_type=None): Limitations ----------- - `dtype` and `usm_type` are not in NumPy's signature. + `dtype` and `usm_type` are not in NumPy's signature. In single + precision, positive `a` and `b` on the host below the smallest normal + ``float32`` value are raised to it, so when both are, 0 and 1 are + equally likely. """ + kernel_params = None + if self._float_dtype(dtype, "beta") == numpy.float32: + kernel_params = ( + _raise_to_float32_tiny(a), + _raise_to_float32_tiny(b), + ) return self._cont( ri._beta, "beta", @@ -1276,6 +1318,7 @@ def beta(self, a, b, size=None, dtype=None, *, usm_type=None): usm_type, (a, "a", _CONS_POSITIVE), (b, "b", _CONS_POSITIVE), + kernel_params=kernel_params, ) diff --git a/dpnp/tests/test_random_generator.py b/dpnp/tests/test_random_generator.py index b27ff1f44238..c62b762422f6 100644 --- a/dpnp/tests/test_random_generator.py +++ b/dpnp/tests/test_random_generator.py @@ -622,6 +622,25 @@ def test_beta_range(self, a, b, dtype): res = dpnp.asnumpy(default_rng(1).beta(a, b, size=10**5, dtype=dtype)) assert ((res >= 0) & (res <= 1)).all() + @pytest.mark.parametrize( + "a, b, mean", + [ + (1e-30, 1e-30, 0.5), + (1e-30, 3e-30, 0.25), + # below the normal range of float32, so raised to its smallest + (1e-40, 1e-40, 0.5), + (1e-50, 1e-50, 0.5), + (1e-50, 0.5, 0.0), + ], + ) + def test_beta_tiny_float32(self, a, b, mean): + # in single precision the shortcut for tiny a and b never ran, and + # the logarithms that ran instead gave NaN + res = default_rng(0).beta(a, b, size=10**5, dtype=dpnp.float32) + res = dpnp.asnumpy(res).astype(numpy.float64) + assert not numpy.isnan(res).any() + assert abs(res.mean() - mean) < 0.01 + def test_array_params(self): rng = default_rng(3) loc = dpnp.arange(4.0)[:, None] * 10 From 9523b7a074437b4713a66aaa59eaf3cc5ce6fb21 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Fri, 13 Nov 2026 13:10:38 -0800 Subject: [PATCH 05/33] Leave the int64 sentinel to the discrete distributions in the docs --- doc/reference/random.rst | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/doc/reference/random.rst b/doc/reference/random.rst index e31a51250af3..b14edab69af7 100644 --- a/doc/reference/random.rst +++ b/doc/reference/random.rst @@ -46,9 +46,8 @@ Differences from NumPy * Parameters on the host (Python scalars, lists and NumPy arrays) are checked as in NumPy. Parameters in :class:`dpnp.ndarray` are not, since that would wait for the device. - Invalid ones give undefined values, such as NaN or the smallest ``int64``, - but the kernels handle them safely: they never loop without end or access - memory out of bounds. + Invalid ones give undefined values, such as NaN, but the kernels handle + them safely: they never loop without end or access memory out of bounds. * Parameters given as lists or NumPy arrays are copied to the device first, which waits for the work already submitted to the queue. Scalars and :class:`dpnp.ndarray` parameters don't wait. From 4c9fd571b8202e1ee81cf70eacd4f593b752a0fa Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Tue, 17 Nov 2026 12:39:58 -0800 Subject: [PATCH 06/33] Document the parameters of the continuous distributions Give the Generator methods from lognormal to beta the Parameters, Returns and Examples sections that normal has, with their dtype, usm_type and out defaults. The examples check statistics of 10**5 samples, so they hold for any stream. --- dpnp/random/_generator.py | 770 +++++++++++++++++++++++++++++++++++++- 1 file changed, 762 insertions(+), 8 deletions(-) diff --git a/dpnp/random/_generator.py b/dpnp/random/_generator.py index fb921a84371b..f7efb238ac5a 100644 --- a/dpnp/random/_generator.py +++ b/dpnp/random/_generator.py @@ -861,10 +861,53 @@ def lognormal( For full documentation refer to :obj:`numpy.random.Generator.lognormal`. + Parameters + ---------- + mean : {float, array_like of floats, dpnp.ndarray, usm_ndarray}, \ + optional + The mean of the underlying normal distribution. + + Default: ``0.0``. + sigma : {float, array_like of floats, dpnp.ndarray, usm_ndarray}, \ + optional + The standard deviation of the underlying normal distribution, + non-negative. + + Default: ``1.0``. + size : {None, int, tuple of ints}, optional + Output shape. With ``None``, the broadcast shape of `mean` and + `sigma`. + + Default: ``None``. + dtype : {None, dtype}, optional + The data type of the output, :obj:`dpnp.float32` or + :obj:`dpnp.float64`. + + Default: ``None``, which means the default floating-point type of + the device. + usm_type : {None, "device", "shared", "host"}, optional + The type of SYCL USM allocation for the output array. + + Default: ``None``, which means the USM type of the array + parameters, or ``"device"`` when there are none. + + Returns + ------- + out : dpnp.ndarray + The samples. + Limitations ----------- `dtype` and `usm_type` are not in NumPy's signature. + Examples + -------- + >>> import dpnp as np + >>> rng = np.random.default_rng(42) + >>> y = np.log(rng.lognormal(0.0, 0.5, 10**5)) + >>> bool(abs(y.mean()) < 0.01), bool(abs(y.std() - 0.5) < 0.01) + (True, True) + """ return self._cont( ri._lognormal, @@ -883,10 +926,40 @@ def standard_cauchy(self, size=None, dtype=None, *, usm_type=None): For full documentation refer to :obj:`numpy.random.Generator.standard_cauchy`. + Parameters + ---------- + size : {None, int, tuple of ints}, optional + Output shape. With ``None``, a zero-dimensional array is returned. + + Default: ``None``. + dtype : {None, dtype}, optional + The data type of the output, :obj:`dpnp.float32` or + :obj:`dpnp.float64`. + + Default: ``None``, which means the default floating-point type of + the device. + usm_type : {None, "device", "shared", "host"}, optional + The type of SYCL USM allocation for the output array. + + Default: ``None``, which means ``"device"``. + + Returns + ------- + out : dpnp.ndarray + The samples. + Limitations ----------- `dtype` and `usm_type` are not in NumPy's signature. + Examples + -------- + >>> import dpnp as np + >>> rng = np.random.default_rng(42) + >>> x = rng.standard_cauchy(10**5) + >>> bool(abs(np.median(x)) < 0.05) + True + """ return self._float_sample( ri._standard_cauchy, (), size, dtype, usm_type, "standard_cauchy" @@ -898,10 +971,46 @@ def wald(self, mean, scale, size=None, dtype=None, *, usm_type=None): For full documentation refer to :obj:`numpy.random.Generator.wald`. + Parameters + ---------- + mean : {float, array_like of floats, dpnp.ndarray, usm_ndarray} + The mean of the distribution, positive. + scale : {float, array_like of floats, dpnp.ndarray, usm_ndarray} + The scale parameter of the distribution, positive. + size : {None, int, tuple of ints}, optional + Output shape. With ``None``, the broadcast shape of `mean` and + `scale`. + + Default: ``None``. + dtype : {None, dtype}, optional + The data type of the output, :obj:`dpnp.float32` or + :obj:`dpnp.float64`. + + Default: ``None``, which means the default floating-point type of + the device. + usm_type : {None, "device", "shared", "host"}, optional + The type of SYCL USM allocation for the output array. + + Default: ``None``, which means the USM type of the array + parameters, or ``"device"`` when there are none. + + Returns + ------- + out : dpnp.ndarray + The samples. + Limitations ----------- `dtype` and `usm_type` are not in NumPy's signature. + Examples + -------- + >>> import dpnp as np + >>> rng = np.random.default_rng(42) + >>> x = rng.wald(1.0, 2.0, 10**5) + >>> bool((x > 0).all()), bool(abs(x.mean() - 1) < 0.02) + (True, True) + """ return self._cont( ri._wald, @@ -928,9 +1037,52 @@ def standard_exponential( For full documentation refer to :obj:`numpy.random.Generator.standard_exponential`. + Parameters + ---------- + size : {None, int, tuple of ints}, optional + Output shape. With ``None``, a zero-dimensional array is returned. + + Default: ``None``. + dtype : {None, dtype}, optional + The data type of the output, :obj:`dpnp.float32` or + :obj:`dpnp.float64`. + + Default: ``None``, which means the default floating-point type of + the device. + method : {"zig", "inv"}, optional + The sampling method. Both draw by inversion, see Limitations. + + Default: ``"zig"``. + out : {None, dpnp.ndarray, usm_ndarray}, optional + A C- or F-contiguous array to fill, of the data type `dtype` and on + the SYCL queue of the generator. If `size` is given as well, it + must be the shape of `out`. + + Default: ``None``. + usm_type : {None, "device", "shared", "host"}, optional + The type of SYCL USM allocation for the output array. Ignored when + `out` is given. + + Default: ``None``, which means ``"device"``. + + Returns + ------- + out : dpnp.ndarray + The samples, or `out` when it is given. + Limitations ----------- - Both methods use inversion; ``"zig"`` is accepted for compatibility. + `dtype` defaults to the default floating-point type of the device, and + `usm_type` is not in NumPy's signature. Both methods use inversion; + ``"zig"`` is accepted for compatibility. + + Examples + -------- + >>> import dpnp as np + >>> rng = np.random.default_rng(42) + >>> x = rng.standard_exponential(10**5) + >>> bool((x >= 0).all()), bool(abs(x.mean() - 1) < 0.02) + (True, True) """ @@ -954,10 +1106,47 @@ def exponential(self, scale=1.0, size=None, dtype=None, *, usm_type=None): For full documentation refer to :obj:`numpy.random.Generator.exponential`. + Parameters + ---------- + scale : {float, array_like of floats, dpnp.ndarray, usm_ndarray}, \ + optional + The scale parameter of the distribution, the inverse of the rate, + non-negative. + + Default: ``1.0``. + size : {None, int, tuple of ints}, optional + Output shape. With ``None``, the shape of `scale`. + + Default: ``None``. + dtype : {None, dtype}, optional + The data type of the output, :obj:`dpnp.float32` or + :obj:`dpnp.float64`. + + Default: ``None``, which means the default floating-point type of + the device. + usm_type : {None, "device", "shared", "host"}, optional + The type of SYCL USM allocation for the output array. + + Default: ``None``, which means the USM type of the array + parameters, or ``"device"`` when there are none. + + Returns + ------- + out : dpnp.ndarray + The samples. + Limitations ----------- `dtype` and `usm_type` are not in NumPy's signature. + Examples + -------- + >>> import dpnp as np + >>> rng = np.random.default_rng(42) + >>> x = rng.exponential(2.0, 10**5) + >>> bool((x >= 0).all()), bool(abs(x.mean() - 2) < 0.04) + (True, True) + """ return self._cont( ri._exponential, @@ -975,10 +1164,43 @@ def pareto(self, a, size=None, dtype=None, *, usm_type=None): For full documentation refer to :obj:`numpy.random.Generator.pareto`. + Parameters + ---------- + a : {float, array_like of floats, dpnp.ndarray, usm_ndarray} + The shape of the distribution, positive. + size : {None, int, tuple of ints}, optional + Output shape. With ``None``, the shape of `a`. + + Default: ``None``. + dtype : {None, dtype}, optional + The data type of the output, :obj:`dpnp.float32` or + :obj:`dpnp.float64`. + + Default: ``None``, which means the default floating-point type of + the device. + usm_type : {None, "device", "shared", "host"}, optional + The type of SYCL USM allocation for the output array. + + Default: ``None``, which means the USM type of the array + parameters, or ``"device"`` when there are none. + + Returns + ------- + out : dpnp.ndarray + The samples. + Limitations ----------- `dtype` and `usm_type` are not in NumPy's signature. + Examples + -------- + >>> import dpnp as np + >>> rng = np.random.default_rng(42) + >>> x = rng.pareto(3.0, 10**5) + >>> bool((x >= 0).all()), bool(abs((x > 1).mean() - 0.125) < 0.01) + (True, True) + """ return self._cont( ri._pareto, @@ -995,10 +1217,43 @@ def weibull(self, a, size=None, dtype=None, *, usm_type=None): For full documentation refer to :obj:`numpy.random.Generator.weibull`. + Parameters + ---------- + a : {float, array_like of floats, dpnp.ndarray, usm_ndarray} + The shape of the distribution, non-negative. + size : {None, int, tuple of ints}, optional + Output shape. With ``None``, the shape of `a`. + + Default: ``None``. + dtype : {None, dtype}, optional + The data type of the output, :obj:`dpnp.float32` or + :obj:`dpnp.float64`. + + Default: ``None``, which means the default floating-point type of + the device. + usm_type : {None, "device", "shared", "host"}, optional + The type of SYCL USM allocation for the output array. + + Default: ``None``, which means the USM type of the array + parameters, or ``"device"`` when there are none. + + Returns + ------- + out : dpnp.ndarray + The samples. + Limitations ----------- `dtype` and `usm_type` are not in NumPy's signature. + Examples + -------- + >>> import dpnp as np + >>> rng = np.random.default_rng(42) + >>> x = rng.weibull(2.0, 10**5) + >>> bool((x >= 0).all()), bool(abs((x**2).mean() - 1) < 0.02) + (True, True) + """ return self._cont( ri._weibull, @@ -1016,10 +1271,45 @@ def power(self, a, size=None, dtype=None, *, usm_type=None): For full documentation refer to :obj:`numpy.random.Generator.power`. + Parameters + ---------- + a : {float, array_like of floats, dpnp.ndarray, usm_ndarray} + The parameter of the distribution, positive. + size : {None, int, tuple of ints}, optional + Output shape. With ``None``, the shape of `a`. + + Default: ``None``. + dtype : {None, dtype}, optional + The data type of the output, :obj:`dpnp.float32` or + :obj:`dpnp.float64`. + + Default: ``None``, which means the default floating-point type of + the device. + usm_type : {None, "device", "shared", "host"}, optional + The type of SYCL USM allocation for the output array. + + Default: ``None``, which means the USM type of the array + parameters, or ``"device"`` when there are none. + + Returns + ------- + out : dpnp.ndarray + The samples. + Limitations ----------- `dtype` and `usm_type` are not in NumPy's signature. + Examples + -------- + >>> import dpnp as np + >>> rng = np.random.default_rng(42) + >>> x = rng.power(3.0, 10**5) + >>> a = bool(((0 <= x) & (x <= 1)).all()) + >>> b = bool(abs(x.mean() - 0.75) < 0.005) + >>> a, b + (True, True) + """ return self._cont( ri._power, "power", size, dtype, usm_type, (a, "a", _CONS_POSITIVE) @@ -1032,10 +1322,46 @@ def rayleigh(self, scale=1.0, size=None, dtype=None, *, usm_type=None): For full documentation refer to :obj:`numpy.random.Generator.rayleigh`. + Parameters + ---------- + scale : {float, array_like of floats, dpnp.ndarray, usm_ndarray}, \ + optional + The scale of the distribution, also its mode, non-negative. + + Default: ``1.0``. + size : {None, int, tuple of ints}, optional + Output shape. With ``None``, the shape of `scale`. + + Default: ``None``. + dtype : {None, dtype}, optional + The data type of the output, :obj:`dpnp.float32` or + :obj:`dpnp.float64`. + + Default: ``None``, which means the default floating-point type of + the device. + usm_type : {None, "device", "shared", "host"}, optional + The type of SYCL USM allocation for the output array. + + Default: ``None``, which means the USM type of the array + parameters, or ``"device"`` when there are none. + + Returns + ------- + out : dpnp.ndarray + The samples. + Limitations ----------- `dtype` and `usm_type` are not in NumPy's signature. + Examples + -------- + >>> import dpnp as np + >>> rng = np.random.default_rng(42) + >>> x = rng.rayleigh(2.0, 10**5) + >>> bool((x >= 0).all()), bool(abs((x**2).mean() - 8) < 0.2) + (True, True) + """ return self._cont( ri._rayleigh, @@ -1055,10 +1381,54 @@ def laplace( For full documentation refer to :obj:`numpy.random.Generator.laplace`. + Parameters + ---------- + loc : {float, array_like of floats, dpnp.ndarray, usm_ndarray}, \ + optional + The position of the peak of the distribution. + + Default: ``0.0``. + scale : {float, array_like of floats, dpnp.ndarray, usm_ndarray}, \ + optional + The exponential decay of the distribution, non-negative. + + Default: ``1.0``. + size : {None, int, tuple of ints}, optional + Output shape. With ``None``, the broadcast shape of `loc` and + `scale`. + + Default: ``None``. + dtype : {None, dtype}, optional + The data type of the output, :obj:`dpnp.float32` or + :obj:`dpnp.float64`. + + Default: ``None``, which means the default floating-point type of + the device. + usm_type : {None, "device", "shared", "host"}, optional + The type of SYCL USM allocation for the output array. + + Default: ``None``, which means the USM type of the array + parameters, or ``"device"`` when there are none. + + Returns + ------- + out : dpnp.ndarray + The samples. + Limitations ----------- `dtype` and `usm_type` are not in NumPy's signature. + Examples + -------- + >>> import dpnp as np + >>> rng = np.random.default_rng(42) + >>> x = rng.laplace(1.0, 2.0, 10**5) + >>> a = bool(abs(x.mean() - 1) < 0.06) + >>> b = bool(abs(abs(x - 1).mean() - 2) < 0.05) + >>> a, b + (True, True) + """ return self._cont( ri._laplace, @@ -1078,10 +1448,52 @@ def gumbel( For full documentation refer to :obj:`numpy.random.Generator.gumbel`. + Parameters + ---------- + loc : {float, array_like of floats, dpnp.ndarray, usm_ndarray}, \ + optional + The location of the mode of the distribution. + + Default: ``0.0``. + scale : {float, array_like of floats, dpnp.ndarray, usm_ndarray}, \ + optional + The scale parameter of the distribution, non-negative. + + Default: ``1.0``. + size : {None, int, tuple of ints}, optional + Output shape. With ``None``, the broadcast shape of `loc` and + `scale`. + + Default: ``None``. + dtype : {None, dtype}, optional + The data type of the output, :obj:`dpnp.float32` or + :obj:`dpnp.float64`. + + Default: ``None``, which means the default floating-point type of + the device. + usm_type : {None, "device", "shared", "host"}, optional + The type of SYCL USM allocation for the output array. + + Default: ``None``, which means the USM type of the array + parameters, or ``"device"`` when there are none. + + Returns + ------- + out : dpnp.ndarray + The samples. + Limitations ----------- `dtype` and `usm_type` are not in NumPy's signature. + Examples + -------- + >>> import dpnp as np + >>> rng = np.random.default_rng(42) + >>> x = rng.gumbel(0.0, 1.0, 10**5) + >>> bool(abs(x.mean() - np.euler_gamma) < 0.03) + True + """ return self._cont( ri._gumbel, @@ -1093,19 +1505,63 @@ def gumbel( (scale, "scale", _CONS_NON_NEGATIVE), ) - def logistic( - self, loc=0.0, scale=1.0, size=None, dtype=None, *, usm_type=None - ): - """ - Draw samples from a logistic distribution. + def logistic( + self, loc=0.0, scale=1.0, size=None, dtype=None, *, usm_type=None + ): + """ + Draw samples from a logistic distribution. + + For full documentation refer to + :obj:`numpy.random.Generator.logistic`. + + Parameters + ---------- + loc : {float, array_like of floats, dpnp.ndarray, usm_ndarray}, \ + optional + The mean of the distribution. + + Default: ``0.0``. + scale : {float, array_like of floats, dpnp.ndarray, usm_ndarray}, \ + optional + The scale parameter of the distribution, non-negative. + + Default: ``1.0``. + size : {None, int, tuple of ints}, optional + Output shape. With ``None``, the broadcast shape of `loc` and + `scale`. + + Default: ``None``. + dtype : {None, dtype}, optional + The data type of the output, :obj:`dpnp.float32` or + :obj:`dpnp.float64`. + + Default: ``None``, which means the default floating-point type of + the device. + usm_type : {None, "device", "shared", "host"}, optional + The type of SYCL USM allocation for the output array. - For full documentation refer to - :obj:`numpy.random.Generator.logistic`. + Default: ``None``, which means the USM type of the array + parameters, or ``"device"`` when there are none. + + Returns + ------- + out : dpnp.ndarray + The samples. Limitations ----------- `dtype` and `usm_type` are not in NumPy's signature. + Examples + -------- + >>> import dpnp as np + >>> rng = np.random.default_rng(42) + >>> x = rng.logistic(1.0, 2.0, 10**5) + >>> a = bool(abs(x.mean() - 1) < 0.08) + >>> b = bool(abs((x < 1).mean() - 0.5) < 0.01) + >>> a, b + (True, True) + """ return self._cont( ri._logistic, @@ -1127,10 +1583,51 @@ def triangular( For full documentation refer to :obj:`numpy.random.Generator.triangular`. + Parameters + ---------- + left : {float, array_like of floats, dpnp.ndarray, usm_ndarray} + The lower limit of the distribution. + mode : {float, array_like of floats, dpnp.ndarray, usm_ndarray} + The value where the peak of the distribution occurs, with + ``left <= mode <= right``. + right : {float, array_like of floats, dpnp.ndarray, usm_ndarray} + The upper limit of the distribution, greater than `left`. + size : {None, int, tuple of ints}, optional + Output shape. With ``None``, the broadcast shape of `left`, `mode` + and `right`. + + Default: ``None``. + dtype : {None, dtype}, optional + The data type of the output, :obj:`dpnp.float32` or + :obj:`dpnp.float64`. + + Default: ``None``, which means the default floating-point type of + the device. + usm_type : {None, "device", "shared", "host"}, optional + The type of SYCL USM allocation for the output array. + + Default: ``None``, which means the USM type of the array + parameters, or ``"device"`` when there are none. + + Returns + ------- + out : dpnp.ndarray + The samples. + Limitations ----------- `dtype` and `usm_type` are not in NumPy's signature. + Examples + -------- + >>> import dpnp as np + >>> rng = np.random.default_rng(42) + >>> x = rng.triangular(-1.0, 0.0, 2.0, 10**5) + >>> a = bool(((-1 <= x) & (x <= 2)).all()) + >>> b = bool(abs(x.mean() - 1 / 3) < 0.015) + >>> a, b + (True, True) + """ params = (left, mode, right) @@ -1157,10 +1654,48 @@ def vonmises(self, mu, kappa, size=None, dtype=None, *, usm_type=None): For full documentation refer to :obj:`numpy.random.Generator.vonmises`. + Parameters + ---------- + mu : {float, array_like of floats, dpnp.ndarray, usm_ndarray} + The mode of the distribution. + kappa : {float, array_like of floats, dpnp.ndarray, usm_ndarray} + The concentration of the distribution, non-negative. + size : {None, int, tuple of ints}, optional + Output shape. With ``None``, the broadcast shape of `mu` and + `kappa`. + + Default: ``None``. + dtype : {None, dtype}, optional + The data type of the output, :obj:`dpnp.float32` or + :obj:`dpnp.float64`. + + Default: ``None``, which means the default floating-point type of + the device. + usm_type : {None, "device", "shared", "host"}, optional + The type of SYCL USM allocation for the output array. + + Default: ``None``, which means the USM type of the array + parameters, or ``"device"`` when there are none. + + Returns + ------- + out : dpnp.ndarray + The samples. + Limitations ----------- `dtype` and `usm_type` are not in NumPy's signature. + Examples + -------- + >>> import dpnp as np + >>> rng = np.random.default_rng(42) + >>> x = rng.vonmises(1.0, 4.0, 10**5) + >>> a = bool((abs(x) <= np.pi).all()) + >>> b = bool(abs(np.sin(x - 1).mean()) < 0.01) + >>> a, b + (True, True) + """ return self._cont( ri._vonmises, @@ -1181,10 +1716,51 @@ def standard_gamma( For full documentation refer to :obj:`numpy.random.Generator.standard_gamma`. + Parameters + ---------- + shape : {float, array_like of floats, dpnp.ndarray, usm_ndarray} + The shape of the distribution, non-negative. + size : {None, int, tuple of ints}, optional + Output shape. With ``None``, the shape of `shape`. + + Default: ``None``. + dtype : {None, dtype}, optional + The data type of the output, :obj:`dpnp.float32` or + :obj:`dpnp.float64`. + + Default: ``None``, which means the default floating-point type of + the device. + out : {None, dpnp.ndarray, usm_ndarray}, optional + A C-contiguous array to fill, of the data type `dtype` and on the + SYCL queue of the generator. If `size` is given as well, it must be + the shape of `out`. + + Default: ``None``. + usm_type : {None, "device", "shared", "host"}, optional + The type of SYCL USM allocation for the output array. Ignored when + `out` is given. + + Default: ``None``, which means the USM type of the array + parameters, or ``"device"`` when there are none. + + Returns + ------- + out : dpnp.ndarray + The samples, or `out` when it is given. + Limitations ----------- + `dtype` defaults to the default floating-point type of the device, and `usm_type` is not in NumPy's signature. + Examples + -------- + >>> import dpnp as np + >>> rng = np.random.default_rng(42) + >>> x = rng.standard_gamma(2.0, 10**5) + >>> bool((x >= 0).all()), bool(abs(x.mean() - 2) < 0.03) + (True, True) + """ self._check_queues(shape, out) @@ -1211,10 +1787,49 @@ def gamma(self, shape, scale=1.0, size=None, dtype=None, *, usm_type=None): For full documentation refer to :obj:`numpy.random.Generator.gamma`. + Parameters + ---------- + shape : {float, array_like of floats, dpnp.ndarray, usm_ndarray} + The shape of the distribution, non-negative. + scale : {float, array_like of floats, dpnp.ndarray, usm_ndarray}, \ + optional + The scale of the distribution, non-negative. + + Default: ``1.0``. + size : {None, int, tuple of ints}, optional + Output shape. With ``None``, the broadcast shape of `shape` and + `scale`. + + Default: ``None``. + dtype : {None, dtype}, optional + The data type of the output, :obj:`dpnp.float32` or + :obj:`dpnp.float64`. + + Default: ``None``, which means the default floating-point type of + the device. + usm_type : {None, "device", "shared", "host"}, optional + The type of SYCL USM allocation for the output array. + + Default: ``None``, which means the USM type of the array + parameters, or ``"device"`` when there are none. + + Returns + ------- + out : dpnp.ndarray + The samples. + Limitations ----------- `dtype` and `usm_type` are not in NumPy's signature. + Examples + -------- + >>> import dpnp as np + >>> rng = np.random.default_rng(42) + >>> x = rng.gamma(2.0, 3.0, 10**5) + >>> bool((x >= 0).all()), bool(abs(x.mean() - 6) < 0.1) + (True, True) + """ return self._cont( ri._gamma, @@ -1233,10 +1848,43 @@ def chisquare(self, df, size=None, dtype=None, *, usm_type=None): For full documentation refer to :obj:`numpy.random.Generator.chisquare`. + Parameters + ---------- + df : {float, array_like of floats, dpnp.ndarray, usm_ndarray} + The number of degrees of freedom, positive. + size : {None, int, tuple of ints}, optional + Output shape. With ``None``, the shape of `df`. + + Default: ``None``. + dtype : {None, dtype}, optional + The data type of the output, :obj:`dpnp.float32` or + :obj:`dpnp.float64`. + + Default: ``None``, which means the default floating-point type of + the device. + usm_type : {None, "device", "shared", "host"}, optional + The type of SYCL USM allocation for the output array. + + Default: ``None``, which means the USM type of the array + parameters, or ``"device"`` when there are none. + + Returns + ------- + out : dpnp.ndarray + The samples. + Limitations ----------- `dtype` and `usm_type` are not in NumPy's signature. + Examples + -------- + >>> import dpnp as np + >>> rng = np.random.default_rng(42) + >>> x = rng.chisquare(4.0, 10**5) + >>> bool((x >= 0).all()), bool(abs(x.mean() - 4) < 0.06) + (True, True) + """ return self._cont( ri._chisquare, @@ -1255,10 +1903,43 @@ def standard_t(self, df, size=None, dtype=None, *, usm_type=None): For full documentation refer to :obj:`numpy.random.Generator.standard_t`. + Parameters + ---------- + df : {float, array_like of floats, dpnp.ndarray, usm_ndarray} + The number of degrees of freedom, positive. + size : {None, int, tuple of ints}, optional + Output shape. With ``None``, the shape of `df`. + + Default: ``None``. + dtype : {None, dtype}, optional + The data type of the output, :obj:`dpnp.float32` or + :obj:`dpnp.float64`. + + Default: ``None``, which means the default floating-point type of + the device. + usm_type : {None, "device", "shared", "host"}, optional + The type of SYCL USM allocation for the output array. + + Default: ``None``, which means the USM type of the array + parameters, or ``"device"`` when there are none. + + Returns + ------- + out : dpnp.ndarray + The samples. + Limitations ----------- `dtype` and `usm_type` are not in NumPy's signature. + Examples + -------- + >>> import dpnp as np + >>> rng = np.random.default_rng(42) + >>> x = rng.standard_t(10.0, 10**5) + >>> bool(abs(x.mean()) < 0.025), bool(abs(x.var() - 1.25) < 0.05) + (True, True) + """ return self._cont( ri._standard_t, @@ -1275,10 +1956,46 @@ def f(self, dfnum, dfden, size=None, dtype=None, *, usm_type=None): For full documentation refer to :obj:`numpy.random.Generator.f`. + Parameters + ---------- + dfnum : {float, array_like of floats, dpnp.ndarray, usm_ndarray} + The number of degrees of freedom in the numerator, positive. + dfden : {float, array_like of floats, dpnp.ndarray, usm_ndarray} + The number of degrees of freedom in the denominator, positive. + size : {None, int, tuple of ints}, optional + Output shape. With ``None``, the broadcast shape of `dfnum` and + `dfden`. + + Default: ``None``. + dtype : {None, dtype}, optional + The data type of the output, :obj:`dpnp.float32` or + :obj:`dpnp.float64`. + + Default: ``None``, which means the default floating-point type of + the device. + usm_type : {None, "device", "shared", "host"}, optional + The type of SYCL USM allocation for the output array. + + Default: ``None``, which means the USM type of the array + parameters, or ``"device"`` when there are none. + + Returns + ------- + out : dpnp.ndarray + The samples. + Limitations ----------- `dtype` and `usm_type` are not in NumPy's signature. + Examples + -------- + >>> import dpnp as np + >>> rng = np.random.default_rng(42) + >>> x = rng.f(5.0, 10.0, 10**5) + >>> bool((x >= 0).all()), bool(abs(x.mean() - 1.25) < 0.03) + (True, True) + """ return self._cont( ri._f, @@ -1296,6 +2013,33 @@ def beta(self, a, b, size=None, dtype=None, *, usm_type=None): For full documentation refer to :obj:`numpy.random.Generator.beta`. + Parameters + ---------- + a : {float, array_like of floats, dpnp.ndarray, usm_ndarray} + The alpha parameter of the distribution, positive. + b : {float, array_like of floats, dpnp.ndarray, usm_ndarray} + The beta parameter of the distribution, positive. + size : {None, int, tuple of ints}, optional + Output shape. With ``None``, the broadcast shape of `a` and `b`. + + Default: ``None``. + dtype : {None, dtype}, optional + The data type of the output, :obj:`dpnp.float32` or + :obj:`dpnp.float64`. + + Default: ``None``, which means the default floating-point type of + the device. + usm_type : {None, "device", "shared", "host"}, optional + The type of SYCL USM allocation for the output array. + + Default: ``None``, which means the USM type of the array + parameters, or ``"device"`` when there are none. + + Returns + ------- + out : dpnp.ndarray + The samples. + Limitations ----------- `dtype` and `usm_type` are not in NumPy's signature. In single @@ -1303,6 +2047,16 @@ def beta(self, a, b, size=None, dtype=None, *, usm_type=None): ``float32`` value are raised to it, so when both are, 0 and 1 are equally likely. + Examples + -------- + >>> import dpnp as np + >>> rng = np.random.default_rng(42) + >>> x = rng.beta(2.0, 3.0, 10**5) + >>> a = bool(((0 <= x) & (x <= 1)).all()) + >>> b = bool(abs(x.mean() - 0.4) < 0.005) + >>> a, b + (True, True) + """ kernel_params = None if self._float_dtype(dtype, "beta") == numpy.float32: From 89342a9353cd450601deed75620d4dca7607d351 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Fri, 20 Nov 2026 11:07:21 -0800 Subject: [PATCH 07/33] Force inlining into the blocked lognormal, Cauchy and Wald kernels --- .../extensions/rng/kernels/samplers.hpp | 26 ++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/dpnp/libtensor/extensions/rng/kernels/samplers.hpp b/dpnp/libtensor/extensions/rng/kernels/samplers.hpp index abe3e67d7975..12f4ad5031ab 100644 --- a/dpnp/libtensor/extensions/rng/kernels/samplers.hpp +++ b/dpnp/libtensor/extensions/rng/kernels/samplers.hpp @@ -164,7 +164,14 @@ class LognormalSampler : public SamplerBase template T operator()(BitGenT &bg, const IndexT i) { - return sycl::exp(mean_[i] + sigma_[i] * normal_(bg)); + if constexpr (is_block_bitgen_v) { + // see NormalSampler + [[clang::always_inline]] return sycl::exp(mean_[i] + + sigma_[i] * normal_(bg)); + } + else { + return sycl::exp(mean_[i] + sigma_[i] * normal_(bg)); + } } }; @@ -181,7 +188,13 @@ class StandardCauchySampler : public SamplerBase template T operator()(BitGenT &bg, const IndexT) { - return standard_cauchy(bg, normal_); + if constexpr (is_block_bitgen_v) { + // see NormalSampler + [[clang::always_inline]] return standard_cauchy(bg, normal_); + } + else { + return standard_cauchy(bg, normal_); + } } }; @@ -206,7 +219,14 @@ class WaldSampler : public SamplerBase template T operator()(BitGenT &bg, const IndexT i) { - return wald(bg, normal_, mean_[i], scale_[i]); + if constexpr (is_block_bitgen_v) { + // see NormalSampler + [[clang::always_inline]] return wald(bg, normal_, mean_[i], + scale_[i]); + } + else { + return wald(bg, normal_, mean_[i], scale_[i]); + } } }; From b8809e505e3b4e48ea3decdb42f5ff736af9d418 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Fri, 20 Nov 2026 14:35:03 -0800 Subject: [PATCH 08/33] Document the ValueError of power --- dpnp/random/_generator.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/dpnp/random/_generator.py b/dpnp/random/_generator.py index f7efb238ac5a..36ed72c18a10 100644 --- a/dpnp/random/_generator.py +++ b/dpnp/random/_generator.py @@ -1296,6 +1296,11 @@ def power(self, a, size=None, dtype=None, *, usm_type=None): out : dpnp.ndarray The samples. + Raises + ------ + ValueError + If `a` <= 0, for an `a` on the host. + Limitations ----------- `dtype` and `usm_type` are not in NumPy's signature. From 31108781db73659e82227cb318f4e1c7ccc30469 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Fri, 20 Nov 2026 14:35:03 -0800 Subject: [PATCH 09/33] Document the ValueErrors of chisquare --- dpnp/random/_generator.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/dpnp/random/_generator.py b/dpnp/random/_generator.py index 36ed72c18a10..827543319a8d 100644 --- a/dpnp/random/_generator.py +++ b/dpnp/random/_generator.py @@ -1878,6 +1878,12 @@ def chisquare(self, df, size=None, dtype=None, *, usm_type=None): out : dpnp.ndarray The samples. + Raises + ------ + ValueError + When `df` <= 0, for a `df` on the host, or when an inappropriate + `size` (e.g. ``size=-1``) is given. + Limitations ----------- `dtype` and `usm_type` are not in NumPy's signature. From 3c36b497de339f87bd28e4fbc72aaae26bd7b063 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Fri, 20 Nov 2026 14:38:19 -0800 Subject: [PATCH 10/33] Skip the CuPy KS tests of the continuous distributions without fp64 --- .../cupy/random_tests/common_distributions.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/dpnp/tests/third_party/cupy/random_tests/common_distributions.py b/dpnp/tests/third_party/cupy/random_tests/common_distributions.py index c7f7f9776316..e62044636451 100644 --- a/dpnp/tests/third_party/cupy/random_tests/common_distributions.py +++ b/dpnp/tests/third_party/cupy/random_tests/common_distributions.py @@ -2,11 +2,17 @@ import unittest import numpy +import pytest import dpnp as cupy +from dpnp.tests.helper import has_support_aspect64 from dpnp.tests.third_party.cupy import testing from dpnp.tests.third_party.cupy.testing import _condition +_requires_fp64 = pytest.mark.skipif( + not has_support_aspect64(), reason="fp64 is required" +) + def two_sample_Kolmogorov_Smirnov_test(observed1, observed2): """Computes the Kolmogorov-Smirnov statistic on 2 samples @@ -158,6 +164,7 @@ def test_uniform(self): assert cupy.all(result >= cupy.asarray(low).min()) assert cupy.all(result < cupy.asarray(high).max()) + @_requires_fp64 @_condition.repeat_with_success_at_least(10, 3) def test_uniform_ks(self): if isinstance(self.low, list) or isinstance(self.high, list): @@ -187,6 +194,7 @@ def test_beta(self): b = cupy.array(self.b) self.generate(a, b, size=(3, 5)) + @_requires_fp64 @_condition.repeat_with_success_at_least(10, 3) def test_beta_ks(self): if isinstance(self.a, list) or isinstance(self.b, list): @@ -259,6 +267,7 @@ class Exponential: def test_exponential(self): self.generate(scale=self.scale, size=(3, 2)) + @_requires_fp64 @_condition.repeat_with_success_at_least(10, 3) def test_exponential_ks(self): self.check_ks(0.05)(self.scale, size=2000) @@ -305,6 +314,7 @@ def test_gamma_1(self): def test_gamma_2(self): self.generate(shape=self.shape, size=(3, 2)) + @_requires_fp64 @_condition.repeat_with_success_at_least(10, 3) def test_gamma_ks(self): self.check_ks(0.05)(self.shape, self.scale, size=2000) @@ -416,6 +426,7 @@ def test_power(self): a = cupy.array(self.a) self.generate(a=a) + @_requires_fp64 @_condition.repeat_with_success_at_least(10, 3) def test_power_ks(self): if not isinstance(self.a, float): @@ -466,6 +477,7 @@ def test_chisquare(self): df = cupy.array(self.df) self.generate(df=df) + @_requires_fp64 @_condition.repeat_with_success_at_least(10, 3) def test_chisquare_ks(self): if not isinstance(self.df, float): @@ -493,6 +505,7 @@ def test_f(self): dfden = cupy.array(self.dfden) self.generate(dfnum, dfden) + @_requires_fp64 @_condition.repeat_with_success_at_least(10, 3) def test_f_ks(self): if isinstance(self.dfnum, list) or isinstance(self.dfden, list): From a10c9cfd2cf42de5b7a2b9ffda82bb233d8b6779 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Sun, 29 Nov 2026 10:49:28 -0800 Subject: [PATCH 11/33] List the sources of the first Generator methods first in the RNG extension The device link keeps the shared engine helpers of the first source that has them, and normal.cpp's kernels then called a second copy of the oneMKL Philox internals, which the OpenCL CPU compiler handles much worse. --- dpnp/libtensor/extensions/rng/CMakeLists.txt | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/dpnp/libtensor/extensions/rng/CMakeLists.txt b/dpnp/libtensor/extensions/rng/CMakeLists.txt index 82138e03b3b2..4316000704df 100644 --- a/dpnp/libtensor/extensions/rng/CMakeLists.txt +++ b/dpnp/libtensor/extensions/rng/CMakeLists.txt @@ -29,12 +29,13 @@ set(python_module_name _rng_impl) set(_module_src - ${CMAKE_CURRENT_SOURCE_DIR}/exponential.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/gamma.cpp + # normal.cpp first: the device link takes shared engine helpers from the first source ${CMAKE_CURRENT_SOURCE_DIR}/normal.cpp ${CMAKE_CURRENT_SOURCE_DIR}/rng_py.cpp ${CMAKE_CURRENT_SOURCE_DIR}/sample.cpp ${CMAKE_CURRENT_SOURCE_DIR}/uniform.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/exponential.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/gamma.cpp ) # a launch takes one work-item per 8 elements, which can exceed INT_MAX From 99446e30a7960ecc3e183d6e1c6fc231c8e36f03 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Sun, 29 Nov 2026 10:49:49 -0800 Subject: [PATCH 12/33] Keep wald finite for a large or infinite scale 4 * scale overflowed, which made the sample inf / inf; dividing Y by 4 * scale instead gives the mean for an infinite scale, as NumPy does. --- .../extensions/rng/kernels/distributions.hpp | 12 +++++++----- dpnp/tests/test_random_generator.py | 13 +++++++++++++ 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/dpnp/libtensor/extensions/rng/kernels/distributions.hpp b/dpnp/libtensor/extensions/rng/kernels/distributions.hpp index 2b1418d74d74..b03799f4f5ce 100644 --- a/dpnp/libtensor/extensions/rng/kernels/distributions.hpp +++ b/dpnp/libtensor/extensions/rng/kernels/distributions.hpp @@ -312,16 +312,18 @@ T logistic(BitGenT &bg, const T loc, const T scale) } } -// NumPy's random_wald() takes X = mean + mean/(2*scale)*(Y - sqrt(4*scale*Y + -// Y*Y)), which cancels, and overflows in float, for large Y. This is the same -// value as mean*4*scale/(sqrt(Y) + sqrt(Y + 4*scale))**2. +// NumPy's random_wald() takes X = mean*(1 - 2/(1 + sqrt(1 + 4*scale/Y))), +// which cancels to 0 for large Y. This is the same value as +// mean/(sqrt(t) + sqrt(t + 1))**2 with t = Y/(4*scale), which doesn't +// overflow for a large scale and gives mean for an infinite one, as NumPy. template T wald(BitGenT &bg, StandardNormal &normal, const T mean, const T scale) { const T n = normal(bg); const T Y = mean * n * n; - const T s = sycl::sqrt(Y) + sycl::sqrt(Y + T(4) * scale); - const T X = mean * (T(4) * scale / (s * s)); + const T t = Y / scale * T(0.25); + const T r = sycl::sqrt(t) + sycl::sqrt(t + T(1)); + const T X = mean / (r * r); const T U = bg.template next_uniform(); if (U <= mean / (mean + X)) { return X; diff --git a/dpnp/tests/test_random_generator.py b/dpnp/tests/test_random_generator.py index c62b762422f6..7e0cceea2003 100644 --- a/dpnp/tests/test_random_generator.py +++ b/dpnp/tests/test_random_generator.py @@ -535,6 +535,19 @@ def test_standard_cauchy(self, dtype): q1, q2, q3 = numpy.quantile(dpnp.asnumpy(res), [0.25, 0.5, 0.75]) assert abs(q1 + 1) < 0.01 and abs(q2) < 0.01 and abs(q3 - 1) < 0.01 + @pytest.mark.parametrize("dtype", float_dtypes) + def test_wald_limits(self, dtype): + rng = default_rng(0) + # the limit of the distribution, as NumPy gives + res = rng.wald(1.0, numpy.inf, size=100, dtype=dtype) + assert (dpnp.asnumpy(res) == 1).all() + # 4 * scale overflowed to inf / inf + res = rng.wald(1.0, 3e38, size=10**4, dtype=dtype) + assert dpnp.isfinite(res).all() + # NumPy's form cancels to 0 here in about half of the draws + res = rng.wald(1e8, 1e-8, size=10**5, dtype=dtype) + assert (dpnp.asnumpy(res) > 0).all() + @pytest.mark.parametrize("dtype", float_dtypes) @pytest.mark.parametrize("kappa", [1e-9, 1e-6, 0.5, 2.0, 50.0, 1e7]) def test_vonmises(self, kappa, dtype): From 4b0f40139abec55d509b498f0c3c6a094c23594e Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Sun, 29 Nov 2026 10:50:10 -0800 Subject: [PATCH 13/33] Keep the float32 u1 of the normal pairs below 1 The cast rounds the top 128 32-bit words to 2**32, which made u1 exactly 1, both values of the pair 0, and standard_cauchy 0 / 0. --- .../libtensor/extensions/rng/kernels/distributions.hpp | 6 ++++-- dpnp/tests/test_random_generator.py | 10 ++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/dpnp/libtensor/extensions/rng/kernels/distributions.hpp b/dpnp/libtensor/extensions/rng/kernels/distributions.hpp index b03799f4f5ce..0f097957b293 100644 --- a/dpnp/libtensor/extensions/rng/kernels/distributions.hpp +++ b/dpnp/libtensor/extensions/rng/kernels/distributions.hpp @@ -94,11 +94,13 @@ class StandardNormal // u1 is on (0, 1], so the logarithm is always finite. In float, it // takes a whole 32-bit word, at the midpoints of 2**-32 steps, so - // that |z| reaches 6.76 rather than the 5.77 of 24 random bits. + // that |z| reaches 6.76 rather than the 5.77 of 24 random bits. The + // cast rounds the top 128 words to 2**32, so u1 is kept below 1, + // where both values of the pair would be 0. T u1; if constexpr (std::is_same_v) { const float w = static_cast(bg.next_uint32()); - u1 = (w + 0.5f) * 0x1p-32f; + u1 = sycl::fmin((w + 0.5f) * 0x1p-32f, 0x1.fffffep-1f); } else { u1 = T(1) - bg.template next_uniform(); diff --git a/dpnp/tests/test_random_generator.py b/dpnp/tests/test_random_generator.py index 7e0cceea2003..a79e2dc7577f 100644 --- a/dpnp/tests/test_random_generator.py +++ b/dpnp/tests/test_random_generator.py @@ -535,6 +535,16 @@ def test_standard_cauchy(self, dtype): q1, q2, q3 = numpy.quantile(dpnp.asnumpy(res), [0.25, 0.5, 0.75]) assert abs(q1 + 1) < 0.01 and abs(q2) < 0.01 and abs(q3 - 1) < 0.01 + def test_standard_cauchy_float32_pair(self): + # the first word rounds to 2**32 in float32, which made both normal + # values of the pair 0, and the ratio 0 / 0 + bitgen = Philox4x3210(key=0, counter=50893511 << 64) + res = Generator(bitgen).standard_cauchy(2, dtype=dpnp.float32) + assert dpnp.isfinite(res).all() + bitgen = Philox4x3210(key=0, counter=50893511 << 64) + res = Generator(bitgen).standard_normal(2, dtype=dpnp.float32) + assert (res != 0).all() + @pytest.mark.parametrize("dtype", float_dtypes) def test_wald_limits(self, dtype): rng = default_rng(0) From 0e9333c4716339690280f9614e98a90845545aa5 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Sun, 29 Nov 2026 10:50:22 -0800 Subject: [PATCH 14/33] Divide each chi-square of f by its own degrees of freedom The products with the other degrees of freedom overflowed to inf / inf in float32 from about 2e19. --- .../libtensor/extensions/rng/kernels/distributions.hpp | 6 ++++-- dpnp/tests/test_random_generator.py | 10 ++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/dpnp/libtensor/extensions/rng/kernels/distributions.hpp b/dpnp/libtensor/extensions/rng/kernels/distributions.hpp index 0f097957b293..82f34d759f1d 100644 --- a/dpnp/libtensor/extensions/rng/kernels/distributions.hpp +++ b/dpnp/libtensor/extensions/rng/kernels/distributions.hpp @@ -271,8 +271,10 @@ T standard_t(BitGenT &bg, StandardNormal &normal, const T df) template T f(BitGenT &bg, StandardNormal &normal, const T dfnum, const T dfden) { - const T num = chisquare(bg, normal, dfnum) * dfden; - return num / (chisquare(bg, normal, dfden) * dfnum); + // dividing each by its own degrees of freedom first keeps large ones + // from overflowing + const T num = chisquare(bg, normal, dfnum) / dfnum; + return num / (chisquare(bg, normal, dfden) / dfden); } template diff --git a/dpnp/tests/test_random_generator.py b/dpnp/tests/test_random_generator.py index a79e2dc7577f..1e29f08d8010 100644 --- a/dpnp/tests/test_random_generator.py +++ b/dpnp/tests/test_random_generator.py @@ -558,6 +558,16 @@ def test_wald_limits(self, dtype): res = rng.wald(1e8, 1e-8, size=10**5, dtype=dtype) assert (dpnp.asnumpy(res) > 0).all() + @pytest.mark.parametrize("dtype", float_dtypes) + @pytest.mark.parametrize("dfnum, dfden", [(2e19, 2e19), (3e38, 3e38)]) + def test_f_large_df(self, dfnum, dfden, dtype): + # the products of a chi-square and the other degrees of freedom + # overflowed to inf / inf in single precision + res = default_rng(0).f(dfnum, dfden, size=10**4, dtype=dtype) + res = dpnp.asnumpy(res) + assert numpy.isfinite(res).all() + assert abs(numpy.median(res) - 1) < 0.01 + @pytest.mark.parametrize("dtype", float_dtypes) @pytest.mark.parametrize("kappa", [1e-9, 1e-6, 0.5, 2.0, 50.0, 1e7]) def test_vonmises(self, kappa, dtype): From ec5482764d17048498945b9add04e2e206e9e695 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Sun, 29 Nov 2026 10:51:39 -0800 Subject: [PATCH 15/33] Raise tiny host parameters of f, standard_t and wald to float32 tiny As for beta, a positive host value that is 0 in float32 made every sample NaN. Also say in the Generator notes what parameters outside the float32 range give. --- dpnp/random/_generator.py | 44 ++++++++++++++++++++++++----- dpnp/tests/test_random_generator.py | 17 +++++++++++ 2 files changed, 54 insertions(+), 7 deletions(-) diff --git a/dpnp/random/_generator.py b/dpnp/random/_generator.py index 827543319a8d..81949cff728f 100644 --- a/dpnp/random/_generator.py +++ b/dpnp/random/_generator.py @@ -65,6 +65,8 @@ # Python scalars, the most common parameters, skip the NumPy checks _PY_SCALARS = (float, int, bool) +_FLOAT32_TINY = float(numpy.finfo(numpy.float32).tiny) + def _is_array(x): if type(x) in _PY_SCALARS: @@ -158,16 +160,16 @@ def _check_arrays(params, dtype=None): return numpy, [numpy.asarray(p, dtype) for p in params] -def _raise_to_float32_tiny(value): +def _raise_to_float32_tiny(value, tiny=_FLOAT32_TINY): """ - Raise a positive host parameter below the smallest normal ``float32`` - value to it, as one that is 0 in ``float32`` would be invalid. + Raise a positive host parameter below `tiny`, the smallest normal + ``float32`` value by default, to it, as one that is 0 in ``float32`` + would be invalid. """ if dpnp.is_supported_array_type(value): return value - tiny = numpy.finfo(numpy.float32).tiny val = _as_host_float(value) val = numpy.where((val > 0) & (val < tiny), tiny, val) return val if val.ndim else float(val) @@ -270,6 +272,12 @@ class Generator: first, which waits for the work already submitted to the queue. Scalars and parameters on the device don't wait. + In single precision, the parameters are rounded to ``float32``, so one + above its range is inf, and one below its smallest normal value can be + 0. The samples can then be NaN, inf or 0 where NumPy's are finite. The + positive host parameters of ``beta``, ``f``, ``standard_t`` and the + `mean` of ``wald`` are raised to the smallest normal value instead. + """ def __init__(self, bit_generator): @@ -1001,7 +1009,9 @@ def wald(self, mean, scale, size=None, dtype=None, *, usm_type=None): Limitations ----------- - `dtype` and `usm_type` are not in NumPy's signature. + `dtype` and `usm_type` are not in NumPy's signature. In single + precision, a positive `mean` on the host below the smallest normal + ``float32`` value is raised to it. Examples -------- @@ -1012,6 +1022,9 @@ def wald(self, mean, scale, size=None, dtype=None, *, usm_type=None): (True, True) """ + kernel_params = None + if self._float_dtype(dtype, "wald") == numpy.float32: + kernel_params = (_raise_to_float32_tiny(mean), scale) return self._cont( ri._wald, "wald", @@ -1020,6 +1033,7 @@ def wald(self, mean, scale, size=None, dtype=None, *, usm_type=None): usm_type, (mean, "mean", _CONS_POSITIVE), (scale, "scale", _CONS_POSITIVE), + kernel_params=kernel_params, ) def standard_exponential( @@ -1941,7 +1955,9 @@ def standard_t(self, df, size=None, dtype=None, *, usm_type=None): Limitations ----------- - `dtype` and `usm_type` are not in NumPy's signature. + `dtype` and `usm_type` are not in NumPy's signature. In single + precision, a positive `df` on the host below twice the smallest + normal ``float32`` value is raised to it. Examples -------- @@ -1952,6 +1968,10 @@ def standard_t(self, df, size=None, dtype=None, *, usm_type=None): (True, True) """ + kernel_params = None + if self._float_dtype(dtype, "standard_t") == numpy.float32: + # the kernel takes df / 2, which must not be 0 either + kernel_params = (_raise_to_float32_tiny(df, 2 * _FLOAT32_TINY),) return self._cont( ri._standard_t, "standard_t", @@ -1959,6 +1979,7 @@ def standard_t(self, df, size=None, dtype=None, *, usm_type=None): dtype, usm_type, (df, "df", _CONS_POSITIVE), + kernel_params=kernel_params, ) def f(self, dfnum, dfden, size=None, dtype=None, *, usm_type=None): @@ -1997,7 +2018,9 @@ def f(self, dfnum, dfden, size=None, dtype=None, *, usm_type=None): Limitations ----------- - `dtype` and `usm_type` are not in NumPy's signature. + `dtype` and `usm_type` are not in NumPy's signature. In single + precision, positive `dfnum` and `dfden` on the host below the + smallest normal ``float32`` value are raised to it. Examples -------- @@ -2008,6 +2031,12 @@ def f(self, dfnum, dfden, size=None, dtype=None, *, usm_type=None): (True, True) """ + kernel_params = None + if self._float_dtype(dtype, "f") == numpy.float32: + kernel_params = ( + _raise_to_float32_tiny(dfnum), + _raise_to_float32_tiny(dfden), + ) return self._cont( ri._f, "f", @@ -2016,6 +2045,7 @@ def f(self, dfnum, dfden, size=None, dtype=None, *, usm_type=None): usm_type, (dfnum, "dfnum", _CONS_POSITIVE), (dfden, "dfden", _CONS_POSITIVE), + kernel_params=kernel_params, ) def beta(self, a, b, size=None, dtype=None, *, usm_type=None): diff --git a/dpnp/tests/test_random_generator.py b/dpnp/tests/test_random_generator.py index 1e29f08d8010..d56d6b666f86 100644 --- a/dpnp/tests/test_random_generator.py +++ b/dpnp/tests/test_random_generator.py @@ -674,6 +674,23 @@ def test_beta_tiny_float32(self, a, b, mean): assert not numpy.isnan(res).any() assert abs(res.mean() - mean) < 0.01 + @pytest.mark.parametrize( + "name, params", + [ + ("f", (1e-300, 7.0)), + ("f", (5.0, 1e-300)), + ("f", (5.0, 1e-45)), + ("standard_t", (1e-300,)), + ("standard_t", (1e-45,)), + ("wald", (1e-300, 1.0)), + ], + ) + def test_tiny_params_float32(self, name, params): + # host parameters that are 0 in float32 gave NaN, as for beta + rng = default_rng(0) + res = getattr(rng, name)(*params, size=10**4, dtype=dpnp.float32) + assert not dpnp.isnan(res).any() + def test_array_params(self): rng = default_rng(3) loc = dpnp.arange(4.0)[:, None] * 10 From d4a512d377f0d6080a79ebc6b68fef81af75a146 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Sun, 29 Nov 2026 10:51:50 -0800 Subject: [PATCH 16/33] Test triangular with a parameter on the device --- dpnp/tests/test_random_generator.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/dpnp/tests/test_random_generator.py b/dpnp/tests/test_random_generator.py index d56d6b666f86..0886e8c08b8a 100644 --- a/dpnp/tests/test_random_generator.py +++ b/dpnp/tests/test_random_generator.py @@ -1047,6 +1047,16 @@ def test_device_params_terminate(self): assert dpnp.isnan(res).all() rng.standard_t(shape) + @pytest.mark.parametrize("dtype", float_dtypes) + def test_triangular_device_param(self, dtype): + left = dpnp.asarray([0.0, 1.0], dtype=dtype) + res = default_rng(0).triangular( + left, 1.0, 3.0, size=(10**4, 2), dtype=dtype + ) + assert ((res >= left) & (res <= 3.0)).all() + mean = dpnp.asnumpy(res).astype(numpy.float64).mean(axis=0) + assert_allclose(mean, [4 / 3, 5 / 3], atol=0.03) + def test_host_params_terminate(self): # valid parameters on which rounding in single precision made every # draw of the rejection sampler fail From eb5d4aac0139c54007e2b1302de89f60b62c2ca8 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Sun, 29 Nov 2026 10:51:50 -0800 Subject: [PATCH 17/33] Test float32 beta with a parameter on the device --- dpnp/tests/test_random_generator.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/dpnp/tests/test_random_generator.py b/dpnp/tests/test_random_generator.py index 0886e8c08b8a..a0213177bac3 100644 --- a/dpnp/tests/test_random_generator.py +++ b/dpnp/tests/test_random_generator.py @@ -1057,6 +1057,14 @@ def test_triangular_device_param(self, dtype): mean = dpnp.asnumpy(res).astype(numpy.float64).mean(axis=0) assert_allclose(mean, [4 / 3, 5 / 3], atol=0.03) + def test_beta_device_param_float32(self): + # only host parameters are raised to float32 tiny + a = dpnp.asarray([0.5, 2.0, 1e-30], dtype=dpnp.float32) + res = default_rng(0).beta(a, 1.0, size=(10**4, 3), dtype=dpnp.float32) + assert not dpnp.isnan(res).any() + mean = dpnp.asnumpy(res).astype(numpy.float64).mean(axis=0) + assert_allclose(mean, [1 / 3, 2 / 3, 0], atol=0.01) + def test_host_params_terminate(self): # valid parameters on which rounding in single precision made every # draw of the rejection sampler fail From a3d9ed53c099a98806248973d678fbb471d56f96 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Sun, 29 Nov 2026 10:52:22 -0800 Subject: [PATCH 18/33] Don't check the method of standard_exponential, as NumPy NumPy takes inversion for any method but "zig", and both are inversion here. --- dpnp/random/_generator.py | 5 +---- dpnp/tests/test_random_generator.py | 8 +++++--- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/dpnp/random/_generator.py b/dpnp/random/_generator.py index 81949cff728f..1d17f44b1436 100644 --- a/dpnp/random/_generator.py +++ b/dpnp/random/_generator.py @@ -1040,7 +1040,7 @@ def standard_exponential( self, size=None, dtype=None, - method="zig", + method="zig", # pylint: disable=unused-argument out=None, *, usm_type=None, @@ -1099,9 +1099,6 @@ def standard_exponential( (True, True) """ - - if method not in ("zig", "inv"): - raise ValueError("method must be either 'inv' or 'zig'") return self._float_sample( ri._exponential, (), diff --git a/dpnp/tests/test_random_generator.py b/dpnp/tests/test_random_generator.py index a0213177bac3..52c749f0fac4 100644 --- a/dpnp/tests/test_random_generator.py +++ b/dpnp/tests/test_random_generator.py @@ -904,10 +904,12 @@ def test_usm_type_follows_params(self, usm_types, expected): # host parameters alone give a device array assert rng.normal([1.0, 2.0]).usm_type == "device" - def test_standard_exponential_method(self): + @pytest.mark.parametrize("method", ["zig", "inv", "x", None]) + def test_standard_exponential_method(self, method): + # as in NumPy, method is not checked, and both draw by inversion rng = default_rng(0) - rng.standard_exponential(3, method="inv") - assert_raises(ValueError, rng.standard_exponential, 3, method="x") + res = rng.standard_exponential(3, method=method) + assert_array_equal(res, default_rng(0).standard_exponential(3)) def test_out_overlapping_param(self): # a parameter overlapping `out` is read before `out` is written From 221fd36e8102525fb0ef2ce5bd875758a03dbc6f Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Sun, 29 Nov 2026 10:52:48 -0800 Subject: [PATCH 19/33] Test the USM type of every continuous distribution --- dpnp/tests/test_usm_type.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/dpnp/tests/test_usm_type.py b/dpnp/tests/test_usm_type.py index 7f4c8ba0d2fc..3aee98312f62 100644 --- a/dpnp/tests/test_usm_type.py +++ b/dpnp/tests/test_usm_type.py @@ -1892,11 +1892,29 @@ def test_tensorsolve(self, usm_type, usm_type_other): @pytest.mark.parametrize( "func, args, kwargs", [ + pytest.param("beta", [2.0, 3.0], {"size": 3, "dtype": "f4"}), + pytest.param("chisquare", [2.0], {"size": 3}), + pytest.param("exponential", [], {"size": 3}), + pytest.param("f", [2.0, 3.0], {"size": 3}), + pytest.param("gamma", [2.0], {"size": 3}), + pytest.param("gumbel", [], {"size": 3}), + pytest.param("laplace", [], {"size": 3}), + pytest.param("logistic", [], {"size": 3}), + pytest.param("lognormal", [], {"size": 3}), pytest.param("normal", [[1.0, 2.0]], {}), + pytest.param("pareto", [2.0], {"size": 3}), + pytest.param("power", [2.0], {"size": 3}), pytest.param("random", [3], {}), + pytest.param("rayleigh", [], {"size": 3}), + pytest.param("standard_cauchy", [], {"size": 3}), + pytest.param("standard_exponential", [], {"size": 3}), pytest.param("standard_gamma", [2.0], {"size": 3}), + pytest.param("standard_t", [3.0], {"size": 3}), pytest.param("triangular", [0.0, 1.0, 3.0], {"size": 3}), pytest.param("uniform", [], {"size": 3}), + pytest.param("vonmises", [0.0, 1.0], {"size": 3}), + pytest.param("wald", [1.0, 2.0], {"size": 3}), + pytest.param("weibull", [2.0], {"size": 3}), ], ) @pytest.mark.parametrize("usm_type", list_of_usm_types) From b81d1abf6ef13e4e669bfb58a7b270831f4be7df Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Sun, 29 Nov 2026 10:54:07 -0800 Subject: [PATCH 20/33] Check pairs of host parameters of triangular with others on the device The checks were skipped as soon as one parameter was on the device, though comparing two host ones doesn't wait for the device. --- dpnp/random/_generator.py | 42 ++++++++++++++++++----------- dpnp/tests/test_random_generator.py | 18 +++++++++++++ 2 files changed, 45 insertions(+), 15 deletions(-) diff --git a/dpnp/random/_generator.py b/dpnp/random/_generator.py index 1d17f44b1436..69e01f8e114a 100644 --- a/dpnp/random/_generator.py +++ b/dpnp/random/_generator.py @@ -149,15 +149,25 @@ def _check_arrays(params, dtype=None): """ `params` as arrays of `dtype` to check, with the module to check them by, which is ``None`` when some are on the device, as the check would - wait for the device. + wait for the device. The host parameters are returned then, and + ``None`` for those on the device. """ - if any(dpnp.is_supported_array_type(p) for p in params): - return None, [None] * len(params) for p in params: - _check_host_cast(p) - return numpy, [numpy.asarray(p, dtype) for p in params] + if not dpnp.is_supported_array_type(p): + _check_host_cast(p) + host = [ + None if dpnp.is_supported_array_type(p) else numpy.asarray(p, dtype) + for p in params + ] + if any(h is None for h in host): + return None, host + return numpy, host + + +def _both_given(x, y): + return x is not None and y is not None def _raise_to_float32_tiny(value, tiny=_FLOAT32_TINY): @@ -1649,16 +1659,18 @@ def triangular( params = (left, mode, right) self._check_queues(*params) xp, (fleft, fmode, fright) = _check_arrays(params, numpy.float64) - if xp is not None: - if xp is numpy and _is_scalar_path(*params): - for p in params: - _check_real(p) - if xp.any(fleft > fmode): - raise ValueError("left > mode") - if xp.any(fmode > fright): - raise ValueError("mode > right") - if xp.any(fleft == fright): - raise ValueError("left == right") + if xp is numpy and _is_scalar_path(*params): + for p in params: + _check_real(p) + # with a parameter on the device, the comparisons of the host ones + # still run + xp = xp or numpy + if _both_given(fleft, fmode) and xp.any(fleft > fmode): + raise ValueError("left > mode") + if _both_given(fmode, fright) and xp.any(fmode > fright): + raise ValueError("mode > right") + if _both_given(fleft, fright) and xp.any(fleft == fright): + raise ValueError("left == right") return self._float_sample( ri._triangular, params, size, dtype, usm_type, "triangular" ) diff --git a/dpnp/tests/test_random_generator.py b/dpnp/tests/test_random_generator.py index 52c749f0fac4..002015dfe609 100644 --- a/dpnp/tests/test_random_generator.py +++ b/dpnp/tests/test_random_generator.py @@ -1153,6 +1153,24 @@ def test_same_as_numpy(self, name, args): lambda: getattr(rng, name)(*args), ) + @pytest.mark.parametrize( + "args, device", + [ + ((1.0, 0.0, 2.0), 2), + ((0.0, 2.0, 1.0), 0), + ((1.0, 1.0, 1.0), 1), + (([0.0, 1.0], 1.0, [2.0, 1.0]), 1), + ], + ) + def test_triangular_host_checks_with_device_param(self, args, device): + # the host parameters are compared even with one on the device + dp_args = list(args) + dp_args[device] = dpnp.asarray(args[device]) + _assert_same_error( + lambda: numpy.random.default_rng(0).triangular(*args), + lambda: default_rng(0).triangular(*dp_args), + ) + @pytest.mark.parametrize( "name, args", [ From b436291cf41b1e3ae442da6e5dab458fb45252a1 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Sun, 29 Nov 2026 10:54:18 -0800 Subject: [PATCH 21/33] Integrate with trapz in test_vonmises on NumPy 1.26 --- dpnp/tests/test_random_generator.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/dpnp/tests/test_random_generator.py b/dpnp/tests/test_random_generator.py index 002015dfe609..918d8352f157 100644 --- a/dpnp/tests/test_random_generator.py +++ b/dpnp/tests/test_random_generator.py @@ -17,7 +17,7 @@ from dpnp.random import Generator, Philox4x3210, default_rng from dpnp.random._generator import _repeats_along_samples -from .helper import get_float_dtypes, has_support_aspect64 +from .helper import get_float_dtypes, has_support_aspect64, numpy_version float_dtypes = get_float_dtypes(no_float16=True) @@ -580,7 +580,9 @@ def test_vonmises(self, kappa, dtype): # E[cos(x - mu)] is I1(kappa) / I0(kappa) t = numpy.linspace(0, numpy.pi, 20001) w = numpy.exp(kappa * (numpy.cos(t) - 1)) - expected = numpy.trapezoid(numpy.cos(t) * w, t) / numpy.trapezoid(w, t) + # trapezoid is new in NumPy 2.0 + trapz = numpy.trapz if numpy_version() < "2.0.0" else numpy.trapezoid + expected = trapz(numpy.cos(t) * w, t) / trapz(w, t) assert abs(numpy.cos(res - mu).mean() - expected) < 5 / numpy.sqrt(n) # the angles are symmetric around mu assert abs(numpy.sin(res - mu).mean()) < 5 / numpy.sqrt(n) From 0692270983ca182aa7523b69d717042f07797c05 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Sun, 29 Nov 2026 10:54:26 -0800 Subject: [PATCH 22/33] Draw standard_gamma through _cont --- dpnp/random/_generator.py | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/dpnp/random/_generator.py b/dpnp/random/_generator.py index 69e01f8e114a..17dfd5909c55 100644 --- a/dpnp/random/_generator.py +++ b/dpnp/random/_generator.py @@ -1791,20 +1791,13 @@ def standard_gamma( """ - self._check_queues(shape, out) - _check_constraint( - shape, - "shape", - _CONS_NON_NEGATIVE, - _is_scalar_path(shape), - ) - return self._float_sample( + return self._cont( ri._gamma, - (shape,), + "standard_gamma", size, dtype, usm_type, - "standard_gamma", + (shape, "shape", _CONS_NON_NEGATIVE), out=out, kernel_params=(shape, 1.0), ) From c00bd9ea750408f70f635a572204a2c5def2e086 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Sun, 29 Nov 2026 10:54:37 -0800 Subject: [PATCH 23/33] Take beta's limits for a zero uniform before the logarithms For a tiny a in float32, log(U) / a is -inf, and with V == 0 log(V) / b is too, which made the difference of the logarithms NaN. --- .../libtensor/extensions/rng/kernels/distributions.hpp | 8 ++++++++ dpnp/tests/test_random_generator.py | 10 ++++++++++ 2 files changed, 18 insertions(+) diff --git a/dpnp/libtensor/extensions/rng/kernels/distributions.hpp b/dpnp/libtensor/extensions/rng/kernels/distributions.hpp index 82f34d759f1d..7213dfc47131 100644 --- a/dpnp/libtensor/extensions/rng/kernels/distributions.hpp +++ b/dpnp/libtensor/extensions/rng/kernels/distributions.hpp @@ -220,6 +220,14 @@ T beta(BitGenT &bg, StandardNormal &normal, const T a, const T b) if ((X >= min_normal) && (Y >= min_normal)) { res = X / XpY; } + // log(U) / a can be -inf for a tiny a in float, and the + // difference of the logarithms below NaN + else if (V == T(0)) { + res = T(1); + } + else if (U == T(0)) { + res = T(0); + } else { // X or Y underflowed, so work with logarithms const T logX = sycl::log(U) / a; diff --git a/dpnp/tests/test_random_generator.py b/dpnp/tests/test_random_generator.py index 918d8352f157..13dd2d1f34cf 100644 --- a/dpnp/tests/test_random_generator.py +++ b/dpnp/tests/test_random_generator.py @@ -693,6 +693,16 @@ def test_tiny_params_float32(self, name, params): res = getattr(rng, name)(*params, size=10**4, dtype=dpnp.float32) assert not dpnp.isnan(res).any() + def test_beta_tiny_and_zero_uniform_float32(self): + # the first words give U = 0.0015 and V = 0, so log(U) / a is -inf + # for the tiny a, and so is log(V) / b + bitgen = Philox4x3210(key=0, counter=1202041481) + u = Generator(bitgen).random(2, dtype=dpnp.float32) + assert 0 < u[0] < 0.01 and u[1] == 0 + bitgen = Philox4x3210(key=0, counter=1202041481) + res = Generator(bitgen).beta(1e-40, 0.5, size=1, dtype=dpnp.float32) + assert dpnp.asnumpy(res)[0] == 1 + def test_array_params(self): rng = default_rng(3) loc = dpnp.arange(4.0)[:, None] * 10 From dfd9d4d17b524e609c45d9124824537e63e9fcff Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Wed, 2 Dec 2026 00:01:33 -0800 Subject: [PATCH 24/33] Keep the float32 u1 of the normal pairs below 1 with a select --- dpnp/libtensor/extensions/rng/kernels/distributions.hpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/dpnp/libtensor/extensions/rng/kernels/distributions.hpp b/dpnp/libtensor/extensions/rng/kernels/distributions.hpp index 7213dfc47131..127195f0b6cc 100644 --- a/dpnp/libtensor/extensions/rng/kernels/distributions.hpp +++ b/dpnp/libtensor/extensions/rng/kernels/distributions.hpp @@ -96,11 +96,12 @@ class StandardNormal // takes a whole 32-bit word, at the midpoints of 2**-32 steps, so // that |z| reaches 6.76 rather than the 5.77 of 24 random bits. The // cast rounds the top 128 words to 2**32, so u1 is kept below 1, - // where both values of the pair would be 0. + // where both values of the pair would be 0. A select rather than + // fmin, which makes the CPU compiler emit the engine rounds twice. T u1; if constexpr (std::is_same_v) { const float w = static_cast(bg.next_uint32()); - u1 = sycl::fmin((w + 0.5f) * 0x1p-32f, 0x1.fffffep-1f); + u1 = (w < 0x1p32f) ? (w + 0.5f) * 0x1p-32f : 0x1.fffffep-1f; } else { u1 = T(1) - bg.template next_uniform(); From 66ec8025f2a88168df8c751fa5db08b07b2aaf03 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Wed, 2 Dec 2026 00:01:38 -0800 Subject: [PATCH 25/33] Say why normal.cpp is the first source of the RNG extension --- dpnp/libtensor/extensions/rng/CMakeLists.txt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/dpnp/libtensor/extensions/rng/CMakeLists.txt b/dpnp/libtensor/extensions/rng/CMakeLists.txt index 4316000704df..e7fd819940d7 100644 --- a/dpnp/libtensor/extensions/rng/CMakeLists.txt +++ b/dpnp/libtensor/extensions/rng/CMakeLists.txt @@ -29,7 +29,9 @@ set(python_module_name _rng_impl) set(_module_src - # normal.cpp first: the device link takes shared engine helpers from the first source + # normal.cpp first: oneMKL's Philox helpers are static inline, and the + # device link takes the inline engine helpers from the first source, so + # later sources' kernels carry two engine copies (slow on the OpenCL CPU) ${CMAKE_CURRENT_SOURCE_DIR}/normal.cpp ${CMAKE_CURRENT_SOURCE_DIR}/rng_py.cpp ${CMAKE_CURRENT_SOURCE_DIR}/sample.cpp From de1c4e31056f9294e1eaa57655a00a7c2fc0cc3e Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Wed, 2 Dec 2026 00:02:06 -0800 Subject: [PATCH 26/33] Raise a tiny host scale of wald to float32 tiny too --- dpnp/random/_generator.py | 13 ++++++++----- dpnp/tests/test_random_generator.py | 1 + 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/dpnp/random/_generator.py b/dpnp/random/_generator.py index 17dfd5909c55..1f80ca858a3d 100644 --- a/dpnp/random/_generator.py +++ b/dpnp/random/_generator.py @@ -285,8 +285,8 @@ class Generator: In single precision, the parameters are rounded to ``float32``, so one above its range is inf, and one below its smallest normal value can be 0. The samples can then be NaN, inf or 0 where NumPy's are finite. The - positive host parameters of ``beta``, ``f``, ``standard_t`` and the - `mean` of ``wald`` are raised to the smallest normal value instead. + positive host parameters of ``beta``, ``f``, ``standard_t`` and + ``wald`` are raised to the smallest normal value instead. """ @@ -1020,8 +1020,8 @@ def wald(self, mean, scale, size=None, dtype=None, *, usm_type=None): Limitations ----------- `dtype` and `usm_type` are not in NumPy's signature. In single - precision, a positive `mean` on the host below the smallest normal - ``float32`` value is raised to it. + precision, positive `mean` and `scale` on the host below the smallest + normal ``float32`` value are raised to it. Examples -------- @@ -1034,7 +1034,10 @@ def wald(self, mean, scale, size=None, dtype=None, *, usm_type=None): """ kernel_params = None if self._float_dtype(dtype, "wald") == numpy.float32: - kernel_params = (_raise_to_float32_tiny(mean), scale) + kernel_params = ( + _raise_to_float32_tiny(mean), + _raise_to_float32_tiny(scale), + ) return self._cont( ri._wald, "wald", diff --git a/dpnp/tests/test_random_generator.py b/dpnp/tests/test_random_generator.py index 13dd2d1f34cf..2894bcb2034c 100644 --- a/dpnp/tests/test_random_generator.py +++ b/dpnp/tests/test_random_generator.py @@ -685,6 +685,7 @@ def test_beta_tiny_float32(self, a, b, mean): ("standard_t", (1e-300,)), ("standard_t", (1e-45,)), ("wald", (1e-300, 1.0)), + ("wald", (1e-300, 1e-300)), ], ) def test_tiny_params_float32(self, name, params): From c5c0b295f64542359d7c00e3e71d23b6d5e20a31 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Wed, 2 Dec 2026 00:02:11 -0800 Subject: [PATCH 27/33] Say that the df of standard_t is raised to twice float32 tiny --- dpnp/random/_generator.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/dpnp/random/_generator.py b/dpnp/random/_generator.py index 1f80ca858a3d..4c8be18895f2 100644 --- a/dpnp/random/_generator.py +++ b/dpnp/random/_generator.py @@ -285,8 +285,9 @@ class Generator: In single precision, the parameters are rounded to ``float32``, so one above its range is inf, and one below its smallest normal value can be 0. The samples can then be NaN, inf or 0 where NumPy's are finite. The - positive host parameters of ``beta``, ``f``, ``standard_t`` and - ``wald`` are raised to the smallest normal value instead. + positive host parameters of ``beta``, ``f`` and ``wald`` are raised to + the smallest normal value instead, and the `df` of ``standard_t`` to + twice it. """ From 2a973eab9168e09afb575b153ce78c594c9f03b8 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Wed, 2 Dec 2026 00:02:19 -0800 Subject: [PATCH 28/33] Take Python scalars without NumPy when raising to float32 tiny --- dpnp/random/_generator.py | 3 +++ dpnp/tests/test_random_generator.py | 2 ++ 2 files changed, 5 insertions(+) diff --git a/dpnp/random/_generator.py b/dpnp/random/_generator.py index 4c8be18895f2..6642fe7d0589 100644 --- a/dpnp/random/_generator.py +++ b/dpnp/random/_generator.py @@ -178,6 +178,9 @@ def _raise_to_float32_tiny(value, tiny=_FLOAT32_TINY): """ + if type(value) in _PY_SCALARS: + value = float(value) + return tiny if 0 < value < tiny else value if dpnp.is_supported_array_type(value): return value val = _as_host_float(value) diff --git a/dpnp/tests/test_random_generator.py b/dpnp/tests/test_random_generator.py index 2894bcb2034c..11cd540d5204 100644 --- a/dpnp/tests/test_random_generator.py +++ b/dpnp/tests/test_random_generator.py @@ -686,6 +686,8 @@ def test_beta_tiny_float32(self, a, b, mean): ("standard_t", (1e-45,)), ("wald", (1e-300, 1.0)), ("wald", (1e-300, 1e-300)), + # not Python scalars, so not on the fast path + ("wald", (numpy.float64(1e-300), [1e-300])), ], ) def test_tiny_params_float32(self, name, params): From 3be08689500bedd625cd26c12ba4cbccc207b1ab Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Wed, 2 Dec 2026 00:03:04 -0800 Subject: [PATCH 29/33] Reject left > right in triangular with the mode on the device --- dpnp/random/_generator.py | 5 +++++ dpnp/tests/test_random_generator.py | 6 ++++++ 2 files changed, 11 insertions(+) diff --git a/dpnp/random/_generator.py b/dpnp/random/_generator.py index 6642fe7d0589..83adb2d7a593 100644 --- a/dpnp/random/_generator.py +++ b/dpnp/random/_generator.py @@ -1678,6 +1678,11 @@ def triangular( raise ValueError("mode > right") if _both_given(fleft, fright) and xp.any(fleft == fright): raise ValueError("left == right") + # invalid for any mode, which NumPy reports as left > mode or + # mode > right + if fmode is None and _both_given(fleft, fright): + if xp.any(fleft > fright): + raise ValueError("left > right") return self._float_sample( ri._triangular, params, size, dtype, usm_type, "triangular" ) diff --git a/dpnp/tests/test_random_generator.py b/dpnp/tests/test_random_generator.py index 11cd540d5204..3ed03860f745 100644 --- a/dpnp/tests/test_random_generator.py +++ b/dpnp/tests/test_random_generator.py @@ -1186,6 +1186,12 @@ def test_triangular_host_checks_with_device_param(self, args, device): lambda: default_rng(0).triangular(*dp_args), ) + def test_triangular_left_above_right_device_mode(self): + # invalid for any mode, so the host values are enough to reject it + mode = dpnp.asarray(1.0) + with pytest.raises(ValueError, match="left > right"): + default_rng(0).triangular(3.0, mode, 0.0) + @pytest.mark.parametrize( "name, args", [ From cf83a34ee88d7cbea1f30b23262e0104c5bc1cd1 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Wed, 2 Dec 2026 00:03:29 -0800 Subject: [PATCH 30/33] Test float32 beta with a zero U and a tiny b --- dpnp/tests/test_random_generator.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/dpnp/tests/test_random_generator.py b/dpnp/tests/test_random_generator.py index 3ed03860f745..bfe8ca1eaf54 100644 --- a/dpnp/tests/test_random_generator.py +++ b/dpnp/tests/test_random_generator.py @@ -706,6 +706,16 @@ def test_beta_tiny_and_zero_uniform_float32(self): res = Generator(bitgen).beta(1e-40, 0.5, size=1, dtype=dpnp.float32) assert dpnp.asnumpy(res)[0] == 1 + def test_beta_tiny_and_zero_uniform_u_float32(self): + # the first words give U = 0 and V = 0.011, so log(V) / b is -inf + # for the tiny b, and so is log(U) / a + bitgen = Philox4x3210(key=0, counter=1268626110 << 64) + u = Generator(bitgen).random(2, dtype=dpnp.float32) + assert u[0] == 0 and 0 < u[1] < 0.015 + bitgen = Philox4x3210(key=0, counter=1268626110 << 64) + res = Generator(bitgen).beta(0.5, 1e-40, size=1, dtype=dpnp.float32) + assert dpnp.asnumpy(res)[0] == 0 + def test_array_params(self): rng = default_rng(3) loc = dpnp.arange(4.0)[:, None] * 10 From 7efd0c20ca3525a36d4d3e173fc22a5c821b5a93 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Wed, 2 Dec 2026 00:03:56 -0800 Subject: [PATCH 31/33] Test the edge branches of standard_gamma, beta and vonmises in both dtypes --- dpnp/tests/test_random_generator.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/dpnp/tests/test_random_generator.py b/dpnp/tests/test_random_generator.py index bfe8ca1eaf54..3e5de92daa15 100644 --- a/dpnp/tests/test_random_generator.py +++ b/dpnp/tests/test_random_generator.py @@ -647,6 +647,29 @@ def test_nan_param(self, name, params): res = dpnp.asnumpy(getattr(rng, name)(*args, size=100)) assert numpy.isnan(res).all() + @pytest.mark.parametrize("dtype", float_dtypes) + def test_edge_branches(self, dtype): + rng = default_rng(0) + res = rng.standard_gamma(0.0, size=100, dtype=dtype) + assert (dpnp.asnumpy(res) == 0).all() + a = dpnp.asarray([0.0, -1.0], dtype=dtype) + assert dpnp.isnan(rng.beta(a, 1.0, size=(8, 2), dtype=dtype)).all() + res = rng.vonmises(0.0, numpy.nan, size=100, dtype=dtype) + assert dpnp.isnan(res).all() + for mu in (numpy.pi - 1e-4, -numpy.pi + 1e-4): + res = rng.vonmises(mu, 1e7, size=10**4, dtype=dtype) + assert (numpy.abs(dpnp.asnumpy(res)) <= numpy.pi).all() + + @pytest.mark.skipif(not has_support_aspect64(), reason="fp64 is required") + def test_beta_tiny_float64(self): + # the shortcut for tiny a and b in double precision + res = default_rng(0).beta( + 1e-110, 1e-110, size=10**5, dtype=dpnp.float64 + ) + res = dpnp.asnumpy(res) + assert numpy.isin(res, (0.0, 1.0)).all() + assert abs(res.mean() - 0.5) < 0.01 + @pytest.mark.parametrize("dtype", float_dtypes) @pytest.mark.parametrize( "a, b", [(1e-3, 1e-3), (0.01, 0.01), (0.3, 1e-4), (50.0, 0.01)] From a9d4bf78225add8795ed81de0a3e67a87fc492a7 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Wed, 2 Dec 2026 00:04:11 -0800 Subject: [PATCH 32/33] Say how closely the samplers agree across devices --- doc/reference/random.rst | 6 ++++-- dpnp/libtensor/extensions/rng/kernels/sample.hpp | 7 ++++--- dpnp/random/_bit_generator.py | 8 +++++--- 3 files changed, 13 insertions(+), 8 deletions(-) diff --git a/doc/reference/random.rst b/doc/reference/random.rst index b14edab69af7..d1956f97159a 100644 --- a/doc/reference/random.rst +++ b/doc/reference/random.rst @@ -31,8 +31,10 @@ Differences from NumPy * The streams differ from NumPy's. For a given seed, output size and data type, the raw bits and the uniform floats are the same on every device. The other distributions use transcendental functions, which may round - differently on another device: their samples agree to a few ULP, or - differ when a rejection sampler then takes another candidate. + differently on another device: their samples agree to a few ULP where + the formula is well conditioned and more loosely where it isn't, and + where a rejection sampler takes another candidate on one device, some + of the later samples differ too. * The values depend on the output size: a draw is not a prefix of a larger one, and two draws of ``n`` values differ from one draw of ``2 * n``. Code splitting its draws into chunks gets other values. diff --git a/dpnp/libtensor/extensions/rng/kernels/sample.hpp b/dpnp/libtensor/extensions/rng/kernels/sample.hpp index ab3979478c4f..249086a034f1 100644 --- a/dpnp/libtensor/extensions/rng/kernels/sample.hpp +++ b/dpnp/libtensor/extensions/rng/kernels/sample.hpp @@ -50,9 +50,10 @@ namespace dpnp::kernels::rng // The words each element draws depend only on the engine state and the // number of elements, never on the device, the layout chosen for it or how // the work-items are scheduled. Raw bits and uniform floats are therefore -// the same on every device, while samplers using transcendental functions -// agree only to a few ULP, or differ where a rejection sampler then takes -// another candidate. +// the same on every device. Samplers using transcendental functions agree +// to a few ULP where their formula is well conditioned and more loosely +// where it isn't, and where a rejection sampler takes another candidate on +// one device, the later values of that work-item differ. enum class Layout { strided, diff --git a/dpnp/random/_bit_generator.py b/dpnp/random/_bit_generator.py index 65f54543e4e2..d349d6091102 100644 --- a/dpnp/random/_bit_generator.py +++ b/dpnp/random/_bit_generator.py @@ -394,9 +394,11 @@ class Philox4x3210(BitGenerator): own block. Element ``i`` comes from the block ``i % ceil(n / 8)``, so the values depend on the output size: a draw is not a prefix of a larger one. For a given state, output size and data type, the raw bits and the - uniform floats are the same on every device, while the samplers built on - transcendental functions agree to a few ULP, or differ where a rejection - sampler then takes another candidate. + uniform floats are the same on every device. The samplers built on + transcendental functions agree to a few ULP where their formula is well + conditioned and more loosely where it isn't, and where a rejection + sampler takes another candidate on one device, the later values of that + work-item differ. """ From 927cef32aab9606fe92b3aaf91abf8164a76a0f2 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Wed, 2 Dec 2026 06:58:01 -0800 Subject: [PATCH 33/33] Say how closely the samplers agree across devices in the libtensor guide --- dpnp/libtensor/AGENTS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dpnp/libtensor/AGENTS.md b/dpnp/libtensor/AGENTS.md index 788569c68007..b0febe6717f4 100644 --- a/dpnp/libtensor/AGENTS.md +++ b/dpnp/libtensor/AGENTS.md @@ -23,7 +23,7 @@ A new extension's `CMakeLists.txt` lists its sources and calls `build_dpnp_pybin - Guard double, complex and half with `dpnp::tensor::type_utils::validate_type_for_device(q)`; don't use double literals or casts in kernels that must run without fp64. - `blas`, `fft`, `lapack` and `sparse` build against either oneMKL or oneMath (`USE_ONEMATH`); `vm` has kernels only with oneMKL: with oneMath it builds empty and `_is_available()` returns `False`; `rng` uses the header-only device RNG API of oneMKL, or of oneMath with `USE_ONEMATH`, and links neither library. - Release the GIL around blocking oneMKL calls (`py::gil_scoped_release`). -- `rng` draws depend only on the engine state and the number of elements, never on the device or the layout chosen for it (`extensions/rng/kernels/sample.hpp`): raw bits and uniform floats are bit-identical across devices, samplers using transcendental functions agree to a few ULP, or differ where a rejection sampler then takes another candidate. Each engine's `items_per_work_item` (`kernels/engines.hpp`) is part of its stream definition. Parameters on the device are unchecked, so a rejection sampler returns NaN for the inputs that would make it loop forever, including values that are valid but round badly in fp32. +- `rng` draws depend only on the engine state and the number of elements, never on the device or the layout chosen for it (`extensions/rng/kernels/sample.hpp`): raw bits and uniform floats are bit-identical across devices, samplers using transcendental functions agree to a few ULP where their formula is well conditioned and more loosely where it isn't, and where a rejection sampler takes another candidate on one device, the later values of that work-item differ. Each engine's `items_per_work_item` (`kernels/engines.hpp`) is part of its stream definition. Parameters on the device are unchecked, so a rejection sampler returns NaN for the inputs that would make it loop forever, including values that are valid but round badly in fp32. - An extension whose kernels may be launched over more than `INT_MAX` work-items passes `LARGE_RANGES` to `build_dpnp_pybind11_ext`, which adds `-fno-sycl-id-queries-fit-in-int` at compile and link time (DPC++ 2026.2 and later need it at link time). `source/CMakeLists.txt` and `dpnp_backend_c` pass it to both `target_compile_options` and `target_link_options`. - clang-format 23 formats C++ (`.clang-format`: LLVM base, 4-space indent, 80 columns); gersemi formats CMake at 88 columns, except `dpnp/backend/cmake/Modules/`.