Repository navigation
Reimplement dpnp.random.RandomState on the device RNG - #3162
ndgrigorian wants to merge 19 commits into
Conversation
b5f1504 to
3565820
Compare
315889e to
142a3d8
Compare
3565820 to
e06fd8c
Compare
142a3d8 to
160719a
Compare
|
Array API standard conformance tests for dpnp=0.22.0dev3=np2py314h8d9cdd5_126 ran successfully. |
|
View rendered docs @ https://intelpython.github.io/dpnp/pull/3162/index.html |
e06fd8c to
c5182f4
Compare
edee62b to
843a343
Compare
acc7ffe to
25ebfd8
Compare
25ebfd8 to
ed4d347
Compare
843a343 to
0232b4c
Compare
ed4d347 to
a59e76d
Compare
0232b4c to
804d1ed
Compare
a59e76d to
a04ffb8
Compare
804d1ed to
f2ab866
Compare
a04ffb8 to
8694043
Compare
f2ab866 to
46d8cc7
Compare
vlad-perevezentsev
left a comment
There was a problem hiding this comment.
I tested the new changes on a GPU Max and its CPU, on Python 3.14t, on an Iris Xe without fp64 and on Windows (Arc B390): both fixes work, the streams match across devices, and the tests pass. The red Linux jobs come from test_state_errors of #3161. A few comments below, the free-threading one first.
8694043 to
eef4522
Compare
46d8cc7 to
8463a23
Compare
RandomState and the module functions now delegate to the Generator samplers, keeping NumPy's legacy checks and messages, also for parameters on the device. The module keeps one RandomState per queue, and adds get_state, set_state, get_bit_generator and set_bit_generator. Enable the CuPy random tests the device RNG supports.
seed() with a SeedSequence failed after reseeding a non-Philox bit generator, as the seed was passed to SeedSequence again. The new states now spawn from the bit generator's own seed sequence, so a child it spawns also differs from them.
d2f000b to
3194517
Compare
eb74e82 to
05394c4
Compare
vlad-perevezentsev
left a comment
There was a problem hiding this comment.
The fixes of the last round work, the streams match the earlier devices, and the tests pass. Some late comments below, all small, and one follow-up on CPU speed.
| def poisson(self, lam=1.0, size=None, *, usm_type=None): | ||
| """ | ||
| Draw samples from a Poisson distribution. | ||
|
|
||
| Default: ``"device"``. | ||
| For full documentation refer to | ||
| :obj:`numpy.random.RandomState.poisson`. | ||
|
|
||
| Returns | ||
| ------- | ||
| out : dpnp.ndarray | ||
| Array of random floats of shape `size` (if ``size=None``, | ||
| zero dimension array with a single float is returned). | ||
| Output array data type is :obj:`dpnp.float64` if device supports it, | ||
| or :obj:`dpnp.float32` otherwise. | ||
| """ | ||
| return self._generator.poisson(lam, size, usm_type=usm_type) |
There was a problem hiding this comment.
Following up on #3162 (comment): on client CPUs the gap is larger, ms per call, base → PR (randint is 3-4× slower there too):
| n = 2**24 | i7-12700K | i5-13400 |
|---|---|---|
poisson(5.0, n) |
37 → 222 | 39 → 315 |
binomial(100, 0.3, n // 4) |
93 → 301 | 101 → 430 |
Generator takes the same time in both builds. Is a follow-up for the CPU kernels planned?
| _check_constraint( | ||
| pvals, "pvals", _CONS_BOUNDED_0_1, False, device=True | ||
| ) | ||
| if xp.any(pvals[..., :-1].sum(axis=-1) > 1.0 + 1e-12): |
There was a problem hiding this comment.
Missed in my earlier rounds: with the device checks of RandomState, a usm_ndarray pvals reaches pvals[..., :-1].sum(), and usm_ndarray has no sum method. Generator.multinomial takes the same array:
import dpnp
import dpnp.tensor as dpt
dpnp.random.multinomial(10, dpt.asarray([0.5, 0.5]))
# AttributeError: 'dpnp.tensor._usmarray.usm_ndarray' object has no attribute 'sum'Converting pvals with dpnp.asarray before the checks would fix it.
| if dpnp.is_supported_array_type(alpha): | ||
| # the Generator copies alpha to the host anyway | ||
| alpha = dpnp.asnumpy(alpha) |
There was a problem hiding this comment.
Missed in my earlier rounds: dirichlet copies a device alpha to the host, and multinomial replaces a 0-d device n with int(n), before Generator sees them. So the default usm_type ignores them, unlike in the other methods:
import dpnp
rs = dpnp.random.RandomState(0)
print(rs.dirichlet(dpnp.ones(3, usm_type="host")).usm_type) # device
print(rs.multinomial(dpnp.asarray(10, usm_type="host"), [0.5, 0.5]).usm_type) # device
print(rs.normal(dpnp.zeros(3, usm_type="host")).usm_type) # hostResolving usm_type with _usm_type_of before these conversions would keep it.
|
|
||
| if device and any(dpnp.is_supported_array_type(p) for p in (low, high)): | ||
| _, (flow, fhigh) = _check_arrays((low, high), True, numpy.float64) | ||
| rng = dpnp.subtract(fhigh, flow) |
There was a problem hiding this comment.
Missed in my earlier rounds: on a device with fp64, float32 bounds on the device are subtracted in float32, so a range that fits in float64 raises. The same bounds on the host give float64 values, as in NumPy:
import dpnp
low = dpnp.full(3, -3e38, dtype=dpnp.float32)
high = dpnp.full(3, 3e38, dtype=dpnp.float32)
print(dpnp.random.RandomState(0).uniform(dpnp.asnumpy(low), dpnp.asnumpy(high)).dtype) # float64
dpnp.random.RandomState(0).uniform(low, high)
# OpenCL CPU: OverflowError: Range exceeds valid boundsCasting device bounds to float64 when the device has fp64 would match.
| rng = dpnp.subtract(fhigh, flow) | ||
| rng_dtype = dpnp.subtract(fhigh.astype(dtype), flow.astype(dtype)) |
There was a problem hiding this comment.
Nit: Missed in my earlier rounds: the device checks of uniform, triangular and the p of choice skip _check_not_complex, so complex arrays don't get NumPy's 'safe' TypeError:
import dpnp
dpnp.random.RandomState(0).uniform(dpnp.asarray([1 + 0j]), 2.0)
# TypeError: ... according to the rule 'same_kind'; numpy: ... according to the rule 'safe'A complex p of choice fails in float() instead. Calling _check_not_complex there too would keep NumPy's error.
| high = high.astype(dpnp.int64, copy=False) | ||
| high = high + 1 | ||
| elif _is_array(high): | ||
| high = numpy.array(high) + 1 |
There was a problem hiding this comment.
Nit: Missed in my earlier rounds: a host array high gets + 1 in its own dtype, so a narrow type at its maximum wraps around. The device path converts to int64 first (322e566), and no test reaches this line:
import numpy, dpnp
dpnp.random.RandomState(0).random_integers(1, numpy.array([127], dtype=numpy.int8))
# ValueError: low >= highConverting it as the device path does would fix it.
| if on_host or self._check_device: | ||
| xp = numpy if on_host else dpnp | ||
| _check_constraint( | ||
| pvals, "pvals", _CONS_BOUNDED_0_1, False, device=True | ||
| ) | ||
| if xp.any(pvals[..., :-1].sum(axis=-1) > 1.0 + 1e-12): |
There was a problem hiding this comment.
Nit: Missed in my earlier rounds: NumPy checks sum(pvals[:-1]) in float64, but a float32 pvals on the device is summed in float32 here, so a sum just above 1 passes:
import numpy, dpnp
pvals = numpy.array([0.5, numpy.nextafter(numpy.float32(0.5), 1), 0], dtype=numpy.float32)
print(dpnp.random.RandomState(0).multinomial(5, dpnp.asarray(pvals))) # [1 4 0]
numpy.random.RandomState(0).multinomial(5, pvals)
# ValueError: sum(pvals[:-1].astype(np.float64)) > 1.0. ...Summing in float64 where the device has it would match NumPy.
| ``sum(colors)`` below ``10**9`` for the ``"count"`` method too. | ||
| * ``choice`` always returns a sample without replacement in random order, | ||
| so its ``shuffle`` parameter has no effect. |
There was a problem hiding this comment.
Nit: The next bullet (line 88) still says that p of choice and pvals of multinomial are only checked on the host. RandomState now checks them on the device too, so it could start with "In Generator", as the bullet on line 57 does.
This PR moves
dpnp.random.RandomStateand thedpnp.randommodule functions onto the device RNG, as part of the series splitting #3147. It is stacked on #3161RandomStatenow delegates to theGeneratorsamplers, with NumPy's legacy checks and error messages. UnlikeGenerator, it also checks parameters on the device, as CuPy does, which waits for the device. The module functions keep oneRandomStateper queue: the queue given bydevice/sycl_queue, or else that of the firstdpnp.ndarrayparameter, or else the default queueAdds
get_state,set_state,get_bit_generatorandset_bit_generator(per queue;seedreseeds in place)RandomStateRandomStatealso receives changesdevice,usm_typeandsycl_queueare keyword-onlyrandnno longer takesd0=uniformno longer takes an integer dtyperandint(dtype=int)returns int64shufflerequires adpnp.ndarrayAlso enables the CuPy
random_teststhe device RNG supports, with per-test skips for CuPy internals and the bit generators we don't provide, and drops the random entries of the skip lists. The ones inskipped_tests_cuda.tblare dropped too, but haven't been run on CUDAThe legacy Cython module is still built but no longer used; #3163 removes it