Repository navigation
Add discrete distributions to dpnp.random.Generator - #3159
ndgrigorian wants to merge 14 commits into
Conversation
9fa550e to
bb0eae2
Compare
0160558 to
adf7178
Compare
bb0eae2 to
7918e32
Compare
|
View rendered docs @ https://intelpython.github.io/dpnp/pull/3159/index.html |
|
Array API standard conformance tests for dpnp=0.22.0dev3=np2py314h8d9cdd5_79 ran successfully. |
adf7178 to
cfa00bd
Compare
6388643 to
f48c80e
Compare
df5cb09 to
7c8127b
Compare
f48c80e to
dcabbc2
Compare
7c8127b to
9ed9f9a
Compare
dcabbc2 to
bb4b69b
Compare
f4938e0 to
a64886a
Compare
78535ba to
6317de6
Compare
vlad-perevezentsev
left a comment
There was a problem hiding this comment.
I tested the new changes here on GPU and CPU, on an Alder Lake iGPU without fp64, on Windows (Arc B390) and on free-threaded Python 3.14t: everything from the previous round is fixed, and the samples are the same on all devices. One small comment below that I missed earlier.
a64886a to
ba52aac
Compare
6317de6 to
37d8b1e
Compare
Add integers and the poisson, binomial, negative_binomial, geometric, logseries, zipf and hypergeometric samplers, along with noncentral_chisquare and noncentral_f, which need poisson. The discrete samplers return int64 and compute in double precision, or in single precision on devices without fp64, where host parameters are clipped to stay inside their domain once rounded.
Also move test_usm_type_follows_bounds and test_device_integer_param_dtype into their classes: indented into a fixture and a helper, pytest never collected them.
NumPy skips the bound checks only when size is given; an empty broadcast with size=None still raises for out-of-range bounds.
d17b470 to
dcd4617
Compare
76467f9 to
2b5045e
Compare
vlad-perevezentsev
left a comment
There was a problem hiding this comment.
The last fix works, the tests pass, and the samples match the earlier runs. But float32 geometric can hang the GPU.
A few comments below:
| // rounding can stall the sum below U, until prod underflows | ||
| while ((U > sum) && (prod > T(0))) { | ||
| prod *= q; | ||
| sum += prod; | ||
| X++; | ||
| } |
There was a problem hiding this comment.
Blocking: Missed in my earlier rounds: in float32 this loop can run forever. For p = 0.4 the rounded sum stops below the largest uniform, 1 - 2**-24. Then prod * q rounds back to the smallest subnormal for q > 1/2, so prod never reaches 0. On UHD 770 and UHD 730 (no fp64) the kernel ends in DEVICE_LOST:
import dpnp
from dpnp.random import Generator, Philox4x3210
# the first word at this counter gives the largest float32 uniform (1 in 2**24 words)
Generator(Philox4x3210(key=0, counter=38471471)).geometric(0.4, size=1)
dpnp.random.default_rng(0).geometric(0.4, size=10**8)
# UHD 770/730: UR_RESULT_ERROR_DEVICE_LOST for both; OpenCL CPU on the float32 path: no result after 120 sStopping where the sum stops growing fixes it (built on both DUTs: 34 at that counter, RNG tests pass):
while (U > sum) {
prod *= q;
const T next = sum + prod;
X++;
if (next == sum) {
break;
}
sum = next;
}| return self._discrete_sample( | ||
| ri._binomial, (n, p), size, usm_type, param_types=(_int64, None) | ||
| ) |
There was a problem hiding this comment.
Missed in my earlier rounds: on the float32 path, a p close to 1 is rounded on the host before 1 - p is taken, so the number of failures is wrong. This is the mirror of the small-p case fixed here with log1p. On UHD 770 and UHD 730:
import dpnp
rng = dpnp.random.default_rng(0)
n = 3 * 10**9
print(n - rng.binomial(n, 1 - 1e-9, size=10**6).mean()) # 0.0; numpy 3.0
print(rng.negative_binomial(1e8, 1 - 1e-8, size=10**6).mean()) # 0.0; numpy 1.0
print(rng.negative_binomial(1e6, 1 - 1e-7, size=10**6).mean()) # 0.119; numpy 0.100logseries(1 - 1e-9) is off too: its 99th percentile is 2.1e7, NumPy's 1.0e9. Could the host pass 1 - p, computed in double, to these kernels?
| ${CMAKE_CURRENT_SOURCE_DIR}/binomial.cpp | ||
| ${CMAKE_CURRENT_SOURCE_DIR}/discrete.cpp |
There was a problem hiding this comment.
On the OpenCL CPU the order of these sources matters, as antonwolfy found on #3158: the device link takes the shared engine helpers from the first source. Kernel time on the i7-12700K in ms (the i5-13400 is the same):
this PR normal.cpp first helpers always_inline
normal float64, 2**24 73.6 18.8 19.1
geometric(0.1), 2**23 15.5 29.2 14.9
zipf(2), 2**23 26.2 60.0 26.6
So #3158's reorder, carried up, makes geometric and zipf 2x slower. Inlining the engine helpers (next_* and StandardNormal::operator()) is fast in every row, and the B570 and UHD 770 stay within 3%. Could #3158 take that instead?
| const T t = noncentral_chisquare<T>(bg, normal, dfnum, nonc) * dfden; | ||
| return t / (chisquare<T>(bg, normal, dfden) * dfnum); |
There was a problem hiding this comment.
Missed in my earlier rounds: this has the float32 NaN of f from antonwolfy's comment on #3158. chisquare * df overflows from df of about 2e19, and a subnormal dfden gives 0/0. On every DUT device:
import dpnp
rng = dpnp.random.default_rng(0)
x = rng.noncentral_f(2e19, 2e19, 1.0, size=10**6, dtype="f4")
print(int(dpnp.isnan(x).sum())) # 1000000; numpy: 0, median 1Dividing each one by its own df first fixes it (built on the bmg DUT: no NaN, medians as NumPy's, the RNG tests pass):
const T t = noncentral_chisquare<T>(bg, normal, dfnum, nonc) / dfnum;
return t / (chisquare<T>(bg, normal, dfden) / dfden);| pytest.param("hypergeometric", [5, 7, 4], {"size": 3}), | ||
| pytest.param("integers", [[3, 5], [7, 9]], {}), | ||
| pytest.param("normal", [[1.0, 2.0]], {}), | ||
| pytest.param("poisson", [3.0], {"size": 3}), |
There was a problem hiding this comment.
Missed in my earlier rounds: test_sycl_queue.py gets all 12 new methods, this list only 3, while dpnp/tests/AGENTS.md asks for both (as antonwolfy noted on #3158). These rows pass on the UHD 730 and the CPU:
pytest.param("binomial", [[10, 20], 0.3], {}),
pytest.param("geometric", [0.3], {"size": 3}),
pytest.param("logseries", [0.5], {"size": 3}),
pytest.param("negative_binomial", [3, 0.4], {"size": 3}),
pytest.param("noncentral_chisquare", [3.0, 1.0], {"size": 3}),
pytest.param("noncentral_f", [2.0, 3.0, 1.0], {"size": 3}),
pytest.param("zipf", [[2.0, 3.0]], {}),| The number of items drawn, at least 1 and at most | ||
| ``ngood + nbad``. |
There was a problem hiding this comment.
Nit: Missed in my earlier rounds: nsample can be 0 here and in NumPy (hypergeometric(5, 3, 0) gives 0 in both), so "at least 1" is wrong; NumPy says "nonnegative". Also, doc/reference/random.rst lists the 10**9 limit of ngood and nbad under "Differences from NumPy", but NumPy has it too, with the same error.
| # NumPy converts both parameters before checking either | ||
| n = _as_int64(n) |
There was a problem hiding this comment.
Nit: Missed in my earlier rounds: NumPy converts p before n, so with both invalid the error differs from NumPy's, unlike what the comment says:
import numpy, dpnp
for xp in (numpy, dpnp):
try:
xp.random.default_rng(0).binomial(2**63, 1j)
except Exception as e:
print(xp.__name__, type(e).__name__)
# numpy TypeError, dpnp OverflowErrorConverting p first would match it.
This PR adds
integersand the discrete distributions todpnp.random.Generator, as part of the series splitting #3147. It is stacked on #3158Adds
integers, using NumPy's bounded integer algorithm (Lemire's method)poisson,binomial(inversion and BTPE),negative_binomial,geometric,logseries,zipfandhypergeometric(HRUA)noncentral_chisquareandnoncentral_f, which needpoissonThe discrete samplers return
int64and compute in double precision, or in single precision on devices without fp64. In single precision, host parameters are clipped so that they stay inside the domain once rounded, and the large log-factorial terms of BTPE and HRUA are gathered into onelog1pso that they don't cancel.zipfusesexpm1/log1p, deliberately departing from NumPy, whose tail foraclose to 1 is too heavy above2**53(documented inrandom.rst)As in #3158, every rejection sampler returns the smallest
int64for device parameters that would make it loop foreverAlso adds
umul_hi, which replacessycl::mul_hi; DPC++ 2026.2 miscompilessycl::mul_hion Intel GPUs when one operand is a compile-time constant