Repository navigation
Add continuous distributions to dpnp.random.Generator - #3158
ndgrigorian wants to merge 10 commits into
Conversation
dbdb2c8 to
3963d20
Compare
0160558 to
adf7178
Compare
3963d20 to
6c3ff46
Compare
|
Array API standard conformance tests for dpnp=0.22.0dev3=np2py314h8d9cdd5_65 ran successfully. |
9fef498 to
1bd3cee
Compare
adf7178 to
cfa00bd
Compare
|
View rendered docs @ https://intelpython.github.io/dpnp/pull/3158/index.html |
df5cb09 to
7c8127b
Compare
9f9f13e to
88c286e
Compare
|
Comments on lines outside the diff:
|
88c286e to
ef331fa
Compare
7c8127b to
9ed9f9a
Compare
78535ba to
6317de6
Compare
antonwolfy
left a comment
There was a problem hiding this comment.
Docs of the continuous distributions checked against NumPy 2.5.5: every method links to NumPy's page and states NumPy's parameter constraints. Only the two Raises sections below are missing.
vlad-perevezentsev
left a comment
There was a problem hiding this comment.
I tested the PR on Linux and Windows, on GPU and CPU, on a GPU without fp64 (Iris Xe) and with free-threaded Python 3.14t, and the samples match across them. Two comments below: the KS tests without fp64 and a race with threads. Agreed with @antonwolfy on the Raises sections.
dd59c79 to
048cdf3
Compare
6317de6 to
37d8b1e
Compare
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.
Also pass the dpnp array straight to assert_allclose in the chisquare test.
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.
d17b470 to
dcd4617
Compare
antonwolfy
left a comment
There was a problem hiding this comment.
I tested the PR on five Intel GPUs and the CPU of each host: Data Center GPU Max 1100 with a Xeon Platinum 8480+, Panther Lake-H with a Core Ultra 7 366H, Lunar Lake, Iris Xe without fp64 with a Core i7-12700H, and Arc Pro B70 with a Core i5-13400. The Max 1100 runs compute-runtime 25.18 / IGC 2.11, the others 26.40 / IGC 2.42; oneAPI 2026.2, NumPy 2.5. The rebase onto master changed none of the PR's files, so the results hold for the current head.
The samplers are right. On every device, every value of all 20 matches a NumPy port of the kernels within the few ULP the docs promise. The distributions pass goodness-of-fit tests and PractRand/TestU01, and no fuzzed parameter makes a kernel loop. A few things need a change; each has an inline comment with the measurements:
- The order of the new sources in
rng/CMakeLists.txtmakes #3157'snormalup to 6x slower on the OpenCL CPU device (kernel time; up to 4.4x end to end), with the newlognormalandstandard_cauchy. It also grows master's kernels by 133 KB. Reordering two lines fixes both. waldis NaN for an infinite or hugescale, where NumPy givesmean.- float32
standard_cauchyis NaN with probability 2**-25. - float32
f,standard_tandwaldare NaN for valid large or tiny parameters. - Test gaps: device parameters of
triangularand float32beta,test_usm_type.py, and the kernel branches below. - Two nits: the
methodcheck ofstandard_exponential, and the comment on NumPy'swald.
Tests
| Check (on the 5 GPUs and the 5 CPUs unless noted) | Result |
|---|---|
| Full dpnp test suite, 261 files, head vs master | no failure |
| RNG test files, 20 runs each | no failure |
| The 25 docstring examples (CI doesn't run them) | pass |
| Iris Xe (no fp64) | exactly the 22 _requires_fp64 KS tests skip; float64 raises ValueError in all 20 methods before the counter moves |
| Reference port: all 20 kernels in NumPy, fed by a Philox reference in work-item order, against 612 cases (20 samplers, both dtypes, parameter regimes, scalar/cyclic/full/device parameters) | every element within 4 ULP, or explained: the formula's own conditioning (cancellation, asin(sqrt(h)) near h = 1), FMA contraction, or one rejection decision that rounds the other way; 0 unexplained |
Goodness of fit: KS and AD against scipy.stats, two-sample KS against NumPy's Generator, n = 1e7 (1e8 for 18 cases on two GPUs), Holm-corrected |
0 rejections |
| PractRand on the CDF transform of the samples, to 64 GB (closed-form CDFs) or 16 GB, plus TestU01 SmallCrush, Max 1100 | all pass but float32 standard_cauchy (its NaN) |
| 5138 fuzzed calls per device: NaN, ±inf, ±0, subnormal, tiny, huge, host and device parameters | every call returns, so the "never loop" note holds; NaN only where the inline comments say |
| Blocked vs strided layout (Max 1100); oneMath v0.9 build vs oneMKL | bit-identical |
Values across devices
Raw words and uniform are bit-identical across all ten devices, as in #3157. Of the new samplers:
- the IGC 2.42 GPUs (Panther Lake-H, Lunar Lake, B70) agree bit for bit with each other;
- in float32 all five GPUs agree, the Iris Xe and the Max 1100 included;
- the four AVX2 CPUs agree bit for bit with each other.
The Max 1100's IGC 2.11 differs from the other GPUs only in float64 over wide parameter ranges (isolated elements, up to 235 ULP in pareto). The Xeon differs from the AVX2 CPUs by up to 235 ULP, and GPU from CPU by up to 11191 ULP in float64 vonmises over its full parameter range (the asin conditioning). No NaN or inf differs anywhere.
Performance
Against legacy dpnp.random (#3163 removes it, so this is the change users see): head time / legacy time, end to end, float64, scalar parameters, n = 2e7:
| Device | GPU: min - max over the samplers | its CPU: min - max | above 1.5 |
|---|---|---|---|
| Max 1100 / Xeon 8480+ | 0.002 - 0.341 | 0.020 - 0.389 | - |
| Panther Lake-H / Core Ultra 7 366H | 0.039 - 1.552 | 0.179 - 2.398 | GPU standard_cauchy 1.55; CPU beta 2.40 |
| Lunar Lake / its CPU | 0.023 - 1.146 | 0.314 - 6.517 | CPU beta 6.52, chisquare 3.70, gamma 3.38, standard_gamma 3.03, standard_cauchy 2.57, lognormal 2.31, f 2.06, gamma(0.5) 2.05 |
| B70 / Core i5-13400 | 0.003 - 0.376 | 0.210 - 2.685 | CPU beta 2.69, chisquare 1.88, standard_cauchy 1.52 |
At n = 1e3 head beats legacy everywhere: at most 0.62x. On the CPUs, standard_cauchy and lognormal above legacy are the source-order slowdown and go away with the reordering. beta, chisquare, gamma, standard_gamma and f in float64 are the samplers' own cost on the client CPUs, unchanged by it. Only for information: they are rejection loops, and legacy is oneMKL's host path. Panther Lake-H's float64 standard_cauchy (30 ms vs 19.5 ms) runs strided with NumPy's two-normal algorithm, where legacy's oneMKL cauchy inverts the CDF of one uniform.
Against NumPy (numpy.random.Generator, PCG64, single thread, on the same host): NumPy time / dpnp time, end to end with the queue wait, median over the samplers in both dtypes, scalar parameters:
| Device | n = 1e5 | n = 2e7 | slower than NumPy at 2e7 |
|---|---|---|---|
| Max 1100 | 13.6x | 121x | - |
| Panther Lake-H | 5.4x | 18.9x | - |
| Lunar Lake | 8.7x | 30.0x | - |
| B70 | 20.9x | 194x | - |
| Xeon 8480+ (112 CPUs) | 1.8x | 18.6x | - |
| Core Ultra 7 366H | 2.0x | 4.7x | - |
| Lunar Lake CPU | 2.1x | 2.1x | 10 float64 rows (beta 0.48x the lowest, and normal from the source order) and float32 beta 0.96x |
| Core i5-13400 | 2.5x | 4.4x | - |
At n = 1e3 NumPy is faster everywhere (launch latency). Every GPU beats NumPy for every sampler from n = 1e5 on. #3157's normal on the GPUs is unchanged (head/master 1.00).
Build time and footprint
Build on 112 CPUs (-j 48, 2 clean builds per tree):
- 667 s against master's 666 s; CPU time +28 s (+0.9 %); no new warning.
- The
_rng_impllink grows from 7.4 s to 30.4 s but stays off the critical path (the_tensor_impllink takes 610 s). - An edit of
samplers.hppnow costs ~40 s of rebuild instead of ~15 s.
| master | PR | change | |
|---|---|---|---|
_rng_impl*.so (Linux) |
1.40 MB | 7.04 MB | 5.0x: 202 new kernels with 4.79 MB of device images, plus 133 KB in master's kernels (the source-order comment) |
| Linux wheel (GHA artifact) | 28.46 MB | 29.43 MB | +0.98 MB (+3.4 %) |
| Windows wheel | 27.97 MB | 28.75 MB | +0.79 MB (+2.8 %) |
| Linux conda package | 17.41 MB | 17.86 MB | +0.46 MB (+2.6 %) |
import dpnp |
time within 4 ms, RSS +5-9 MiB | ||
| Device memory once every sampler has run (xe driver) | +9 MiB (Panther Lake-H), +23 MiB (B70) |
Cyclic device parameters make no full-size temporary.
Coverage
Coveralls +0.07 %. _generator.py misses lines 155 and 169 (inline comments), and a coverage build on the Max 1100 misses the same two. The binding .cpp files are at 100 %, and the GPU hits the GPU-only blocked dispatch in common.hpp. Coverage leaves out the kernel headers, so I replayed every kernel launch of the RNG tests through the reference port and counted branches. No test reaches these branches of kernels/distributions.hpp:
- the 0 of
standard_gammaforshape == 0, in both dtypes (lines 133-134); - float64
beta's shortcut fora, b < 3e-103(line 198);test_beta_tiny_float32covers float32 only; - the NaN for a device
aorb<= 0 in float32beta(187-189) and the NaNkappain float32vonmises(355-356):test_device_params_terminateandtest_nan_paramdraw in the default dtype; - the wrap of the large-
kappawrapped normal into [-pi, pi], in both dtypes (391-396).
A few rows would cover them, for instance in TestFloatMethods:
@pytest.mark.parametrize("dtype", float_dtypes)
def test_edge_branches(self, dtype):
rng = default_rng(0)
assert (dpnp.asnumpy(rng.standard_gamma(0.0, size=100, dtype=dtype)) == 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()
assert dpnp.isnan(rng.vonmises(0.0, numpy.nan, size=100, dtype=dtype)).all()
for mu in (numpy.pi - 1e-4, -numpy.pi + 1e-4):
res = dpnp.asnumpy(rng.vonmises(mu, 1e7, size=10**4, dtype=dtype))
assert (numpy.abs(res) <= numpy.pi).all()plus a float64 beta(1e-110, 1e-110) row next to test_beta_tiny_float32.
Thread race
The race of test_default_rng_thread_safe on the Max 1100 (the resolved thread) is in the runtime, not in this PR. A plain SYCL program reproduces it there:
- threads share an out-of-order queue; each submits a kernel and a host task after it (as dpnp's keep-alive does), then calls
q.wait(); - a copy after that reads unwritten data, in 440 of 5120 kernels;
- it is gone without the host task, with an in-order queue, with
ev.wait(), or with the Level Zero v2 adapter.
The v2 adapter is the default with the 26.40 driver, which likely explains why an iGPU shows nothing. Through dpnp on the Max 1100, only the long rejection samplers hit it: f, vonmises and beta, 3-33 of 12800 calls on Python 3.13 and 2-4x more on 3.14t. On opencl:cpu a non-RNG matvec hits it too. Nothing to change here.
| ${CMAKE_CURRENT_SOURCE_DIR}/exponential.cpp | ||
| ${CMAKE_CURRENT_SOURCE_DIR}/gamma.cpp |
There was a problem hiding this comment.
These two lines slow #3157's normal/standard_normal on the OpenCL CPU device, by up to 6x in float64 kernel time, and the new lognormal and standard_cauchy with them. The GPUs are not affected.
The cause is the device link:
- oneMKL's Philox internals (
philox4x32x10_impl::skip_ahead<1>,round_10) have internal linkage, so every source has its own copy. - The shared inline helpers (
UniformBits::next_uniform<double>,StandardNormal<float>::operator()) are kept from the first source that has them, nowgamma.cpp. - So the Normal kernels of
normal.cppcall two engine copies:gamma.cpp's through the helper and their own from the kernel. The OpenCL CPU compiler handles that much worse. - It is also why 14 of master's 40 kernel images grow by 9.5 KB each (+133 KB):
NormalSampler's SPIR-V goes from 4 functions to 6.
Kernel time head/master at n = 2e7 on opencl:cpu (median of 2-3 rounds; the same rows on the four GPUs measured are 0.87-1.01):
| CPU | normal float64 scalar |
cyclic | full | normal float32 scalar |
|---|---|---|---|---|
| Xeon Platinum 8480+ | 2.32 | 1.94 | 1.19 | 1.60 |
| Core Ultra 7 366H | 5.82 | 1.86 | 2.28 | 1.02 |
| Lunar Lake | 6.27 | 2.15 | 2.70 | 1.09 |
| Core i5-13400 | 5.81 | 2.37 | 2.82 | 1.18 |
End to end, float64 normal at 2e7 is 2.9-4.4x master's on the three client CPUs (1.03x on the Xeon, where allocation dominates). On the Lunar Lake CPU it is then slower than single-thread NumPy.
Listing the new sources after #3157's restores master. Master's 40 images are byte-identical again, the values stay bit-identical, the RNG tests pass on GPU and CPU, and the CPU kernels are back at master's speed:
- Xeon: float64
normal2.39 ms against master's 2.43 and head's 5.66; float32 1.32 ms against 1.31 and 2.11;lognormalandstandard_cauchyfloat64 at 0.42x and 0.35x head; - Core i5-13400: float64
normal1.46-1.48 ns per sample against master's 1.47-1.50 and head's 6.10-6.17. - Nothing gets slower: over the 568 kernel cases of every sampler, dtype, size and parameter form, the reordered build against head has a median of 1.000 on the Max 1100 (max 1.05) and 0.998 on the Xeon. The few CPU rows above 1.1 are within its per-process noise, which kernels with code identical in both builds show too.
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
)What else I tried:
- Moving
lognormal,standard_cauchyandwaldout ofnormal.cppinto a source of their own: no change. - Forcing
next_uniformandStandardNormal::operator()inline: float32 is fixed, but the cross-source call moves tonext_double(), so float64 stays slow. - Forcing every helper of the engine path inline (
UniformBits::next_float/next_double/next_uniform,BitGen::next_uint32/next_uint64,StandardNormal::operator()): the CPU is fixed whatever the link order. But it rewrites 10 of master's kernels (+90 KB), and on the Max 1100 float64gumbel,laplaceandlogisticgot 4-7 % slower at n = 2e7 and ~1.5x at n = 19997457.
| // 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 <typename T, typename BitGenT> | ||
| T wald(BitGenT &bg, StandardNormal<T> &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)); |
There was a problem hiding this comment.
wald is NaN for an infinite scale, and for a finite one large enough to make T(4) * scale overflow (float32 above ~8.5e37, float64 1.7e308). NumPy returns mean there, the limit of the distribution, and CONS_POSITIVE lets these values through in both. Here Y + T(4) * scale is inf, so 4 scale / s² is inf/inf. Measured on all five GPUs and CPUs, with host and device parameters: wald(1, inf) is NaN for every sample in both dtypes, and float32 wald(1, 3e38) too.
With t = Y / (4 scale) the same value doesn't overflow in scale, and scale = inf gives mean:
- A float32/float64 emulation against mpmath over a 305 x 305 grid of Y and scale in [1e-38, 1e38] has no NaN, max 4.4 ULP (the current form has 305 NaN in float32).
- Built on the Max 1100 and its CPU: the RNG tests pass,
wald(1, inf)is 1 for every sample, there is no NaN for a hugescale, and no zeros forwald(1e8, 1e-8). - The values stay within 8 ULP of the current form: that is the two forms' own float32 rounding. One element in 1e6 is 10 ULP off on the GPU, whose float32
sqrtisn't correctly rounded.
The comment can also say what NumPy does now. Since 2.4 it takes mean * (1 - 2/d) with d = 1 + sqrt(1 + 4*scale/Y), which still cancels to 0 for large Y: NumPy 2.5's wald(1e8, 1e-8) is exactly 0 in 47 % of the draws. So this form is the better one, and nothing tests it: with NumPy's form put back, every RNG test still passes on both devices.
| // 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 <typename T, typename BitGenT> | |
| T wald(BitGenT &bg, StandardNormal<T> &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)); | |
| // 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 <typename T, typename BitGenT> | |
| T wald(BitGenT &bg, StandardNormal<T> &normal, const T mean, const T scale) | |
| { | |
| const T n = normal(bg); | |
| const T Y = mean * n * n; | |
| 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); |
Tests for both, e.g. in TestFloatMethods:
@pytest.mark.parametrize("dtype", float_dtypes)
def test_wald_limits(self, dtype):
rng = default_rng(0)
# the limit of the distribution, as NumPy gives
assert (dpnp.asnumpy(rng.wald(1.0, numpy.inf, size=100, dtype=dtype)) == 1).all()
# NumPy's form cancels to 0 here in about half of the draws
assert (dpnp.asnumpy(rng.wald(1e8, 1e-8, size=10**5, dtype=dtype)) > 0).all()| T standard_cauchy(BitGenT &bg, StandardNormal<T> &normal) | ||
| { | ||
| const T num = normal(bg); | ||
| return num / normal(bg); | ||
| } |
There was a problem hiding this comment.
In float32 this is NaN with probability 2**-25:
StandardNormal<float>takesu1 = (float(w) + 0.5f) * 2**-32, and the cast rounds every word w >= 232 - 128 to 232.- So
u1is exactly 1, and both values of the pair are 0. numand the denominator here are the two halves of one pair, so the result is 0/0.
Repro: dpnp.random.Generator(dpnp.random.Philox4x3210(key=0, counter=50893511 << 64)).standard_cauchy(2, dtype="float32") gives [nan, 17.32] (standard_normal there gives [0., 0.]). On the Max 1100, 6.9e10 float32 draws had 2052 NaN, which is 2**-25.
Keeping u1 < 1 in StandardNormal's float branch fixes it and changes only those 128 words, e.g. u1 = sycl::fmin((w + 0.5f) * 0x1p-32f, 0x1.fffffep-1f);. It also removes float32 standard_normal's atom at exactly 0 (probability 2**-25). That line is #3157's, but this is the first sampler to divide by it.
Not a bug, only a property of taking both values from one pair: float32 standard_cauchy takes 224 values, so |x| stops at ~2.7e6, and ±inf comes with probability 2-23 (cospi(phi) == 0 at u2 = 1/4, 3/4; 8231 times in the same 6.9e10 draws).
| const T num = chisquare<T>(bg, normal, dfnum) * dfden; | ||
| return num / (chisquare<T>(bg, normal, dfden) * dfnum); |
There was a problem hiding this comment.
In float32 this is NaN for large degrees of freedom, where NumPy and float64 give a median of ~1:
chisquare(dfnum) * dfdenandchisquare(dfden) * dfnumoverflow to inf/inf from df ≈ 2e19 (f(x, x)is all NaN from 2e19 and fine at 1e19;f(5, 3e38)is 95 % NaN).- A subnormal
dfdengives 0/0 where NumPy gives inf:default_rng(0).f(5, 1e-45, size=4096, dtype="f4")has 34 NaN, the rest inf. A subnormaldfnumgives an occasional NaN:f(1e-40, 1)has 8 in 4096.
Measured on all five GPUs and CPUs. Dividing each chi-square by its own degrees of freedom first avoids both, and keeps the order of the draws (not built here):
| const T num = chisquare<T>(bg, normal, dfnum) * dfden; | |
| return num / (chisquare<T>(bg, normal, dfden) * dfnum); | |
| const T num = chisquare<T>(bg, normal, dfnum) / dfnum; | |
| return num / (chisquare<T>(bg, normal, dfden) / dfden); |
| 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. |
There was a problem hiding this comment.
In float32 the same happens to f, standard_t and wald's mean, which don't get this. A valid host value below the float32 range is 0 in the kernel, so these are all NaN, where NumPy (float64) gives finite values or ±inf:
f(1e-300, 7, dtype="f4")andf(5, 1e-300, dtype="f4");standard_t(1e-300, dtype="f4");wald(1e-300, 1, dtype="f4").
standard_t(1e-45, dtype="f4") is NaN too: df / 2 underflows to 0, where NumPy gives ±inf. Measured on all five GPUs and CPUs. Raising these parameters to float32 tiny as beta does would cover the host values; otherwise a Limitations line, as for beta.
There was a problem hiding this comment.
The same happens above the float32 range, where raising to tiny can't help. In float32, on UHD 770, Arc B570 and their CPUs: standard_t(1e39), f(1e39, 5) and wald(1e39, 1) are all NaN, gamma(1e39, 1e-30) is all inf (NumPy about 1e9), and weibull(1e-50) is all 0 (NumPy 38% inf). A Limitations line could cover both ends.
| if any(dpnp.is_supported_array_type(p) for p in params): | ||
| return None, [None] * len(params) |
There was a problem hiding this comment.
No test reaches this branch: Coveralls and a coverage build on the Max 1100 both miss line 155, and the 1641->1651 branch in triangular. test_none_with_array_is_nan uses host lists, and _diff_queue_methods raises before _check_arrays. The path itself works on all five GPUs and CPUs: a device left, cyclic and full size, stays in range with means 4/3 and 5/3. A test:
@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()| if dpnp.is_supported_array_type(value): | ||
| return value |
There was a problem hiding this comment.
No test reaches this line either: test_device_params_terminate draws beta in the default dtype, which is float64 where the device has it. A float32 draw with a device a covers it. For example, default_rng(0).beta(dpnp.asarray([0.5, 2.0, 1e-30]), 1.0, size=(10**4, 3), dtype=dpnp.float32) should have no NaN and column means near 1/3, 2/3 and 0. It does on all five GPUs and CPUs.
| if method not in ("zig", "inv"): | ||
| raise ValueError("method must be either 'inv' or 'zig'") |
There was a problem hiding this comment.
Nit, NumPy parity: NumPy 2.5 doesn't check method. Anything but "zig" takes inversion, so method="x" and method=None both run there. Since both methods are inversion here anyway, you could drop the check. Or keep it as a deliberate difference, with a Limitations line and a comment in test_standard_exponential_method, as AGENTS.md asks. Minor: NumPy checks dtype before method.
| pytest.param("standard_gamma", [2.0], {"size": 3}), | ||
| pytest.param("triangular", [0.0, 1.0, 3.0], {"size": 3}), |
There was a problem hiding this comment.
test_sycl_queue.py gets all 20 methods, this file 2, while AGENTS.md asks for both for a new public function. _sample shares the USM type logic, so the risk is low. But standard_exponential, standard_cauchy and float32 beta take their own paths, and the other rows cost a line each, e.g.:
| pytest.param("standard_gamma", [2.0], {"size": 3}), | |
| pytest.param("triangular", [0.0, 1.0, 3.0], {"size": 3}), | |
| pytest.param("standard_gamma", [2.0], {"size": 3}), | |
| pytest.param("triangular", [0.0, 1.0, 3.0], {"size": 3}), | |
| 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("pareto", [2.0], {"size": 3}), | |
| pytest.param("power", [2.0], {"size": 3}), | |
| pytest.param("rayleigh", [], {"size": 3}), | |
| pytest.param("standard_cauchy", [], {"size": 3}), | |
| pytest.param("standard_exponential", [], {"size": 3}), | |
| pytest.param("standard_t", [3.0], {"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}), |
vlad-perevezentsev
left a comment
There was a problem hiding this comment.
Agreed with @antonwolfy on all his points. A few new comments below.
|
|
||
| // F with `dfnum` and `dfden` degrees of freedom | ||
| template <typename T> | ||
| class FSampler : public SamplerBase<T, T, T> |
There was a problem hiding this comment.
Following up on #3158 (comment): yes, keeping the RNG as it is works for me. Your plain SYCL and OpenCL repros put the race in the runtime. On a UHD 770 (Level Zero v1) and an Arc B570 it doesn't show: 0 of 2560 copies for f, vonmises, beta and normal
| const T logX = sycl::log(U) / a; | ||
| const T logY = sycl::log(V) / b; | ||
| const T delta = logX - logY; |
There was a problem hiding this comment.
Missed in my earlier rounds: in float32 this is NaN with probability about 1e-9 when one parameter is tiny and the other at most 1. For a = 1e-40, raised to float32 tiny, log(U) / a is -inf for U < 0.019, and when V is exactly 0, logY is -inf too:
import dpnp
x = dpnp.random.default_rng(2).beta(1e-40, 0.5, size=2**26, dtype="float32")
print(dpnp.nonzero(dpnp.isnan(x))[0]) # [24337445] on UHD 770, UHD 730, Arc B570 and both CPUsThe B570 had 426 NaN in 4e11 draws (432 expected). Could V == 0 give 1 and U == 0 give 0 before the logarithms, as in NumPy?
| params = (left, mode, right) | ||
| self._check_queues(*params) | ||
| xp, (fleft, fmode, fright) = _check_arrays(params, numpy.float64) | ||
| if xp is not None: |
There was a problem hiding this comment.
Missed in my earlier rounds: with one parameter on the device, the host ones aren't checked either, though the Generator notes say host parameters are checked as in NumPy:
import dpnp
rng = dpnp.random.default_rng(0)
print(rng.triangular(1.0, 0.0, dpnp.asarray(2.0), 4)) # no error; NumPy: ValueError: left > modeCould each comparison run when both of its parameters are on the host?
| # 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) |
There was a problem hiding this comment.
Missed in my earlier rounds: numpy.trapezoid is new in NumPy 2.0, while dpnp still supports NumPy 1.26 (pyproject.toml), so every test_vonmises case fails there with AttributeError. TestTrapezoid in test_mathematical.py takes numpy.trapz below 2.0 with numpy_version(); the same switch would work here.
| 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), | ||
| ) |
There was a problem hiding this comment.
Nit: Missed in my earlier rounds: this repeats _cont, which takes out and kernel_params since this PR:
return self._cont(
ri._gamma, "standard_gamma", size, dtype, usm_type,
(shape, "shape", _CONS_NON_NEGATIVE),
out=out, kernel_params=(shape, 1.0),
)Then a later change to the checks in _cont reaches standard_gamma too.
This PR adds the continuous distributions to
dpnp.random.Generator, as part of the series splitting #3147. It is stacked on #3157The samplers are device ports of NumPy's algorithms:
exponential,standard_exponential,pareto,weibull,power,rayleighgamma,standard_gamma,beta,chisquare,standard_t,flognormal,standard_cauchy,wald,laplace,gumbel,logistic,triangular,vonmisesParameters on the device aren't checked, since that would wait for the device. The rejection samplers instead return NaN for parameters that would make them loop forever, including valid ones that round badly in single precision