Skip to content

Reimplement dpnp.random.RandomState on the device RNG - #3162

Open
ndgrigorian wants to merge 19 commits into
feature/device-rng-bit-generatorsfrom
feature/device-rng-random-state
Open

ndgrigorian wants to merge 19 commits into
feature/device-rng-bit-generatorsfrom
feature/device-rng-random-state

Conversation

@ndgrigorian

@ndgrigorian ndgrigorian commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator

This PR moves dpnp.random.RandomState and the dpnp.random module functions onto the device RNG, as part of the series splitting #3147. It is stacked on #3161

RandomState now delegates to the Generator samplers, with NumPy's legacy checks and error messages. Unlike Generator, it also checks parameters on the device, as CuPy does, which waits for the device. The module functions keep one RandomState per queue: the queue given by device/sycl_queue, or else that of the first dpnp.ndarray parameter, or else the default queue

Adds

  • get_state, set_state, get_bit_generator and set_bit_generator (per queue; seed reseeds in place)
  • A bit generator as the seed of RandomState

RandomState also receives changes

  • Values now match across devices, and differ from the legacy implementation's
  • device, usm_type and sycl_queue are keyword-only
  • randn no longer takes d0=
  • uniform no longer takes an integer dtype
  • randint(dtype=int) returns int64
  • shuffle requires a dpnp.ndarray

Also enables the CuPy random_tests the 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 in skipped_tests_cuda.tbl are dropped too, but haven't been run on CUDA

The legacy Cython module is still built but no longer used; #3163 removes it

  • Have you provided a meaningful PR description?
  • Have you added a test, reproducer or referred to an issue with a reproducer?
  • Have you tested your changes locally for CPU and GPU devices?
  • Have you made sure that new changes do not introduce compiler warnings?
  • Have you checked performance impact of proposed changes?
  • Have you added documentation for your changes, if necessary?
  • Have you added your changes to the changelog?

@ndgrigorian
ndgrigorian force-pushed the feature/device-rng-bit-generators branch from b5f1504 to 3565820 Compare November 4, 2026 19:47
@ndgrigorian
ndgrigorian force-pushed the feature/device-rng-random-state branch from 315889e to 142a3d8 Compare November 4, 2026 19:47
@ndgrigorian
ndgrigorian force-pushed the feature/device-rng-bit-generators branch from 3565820 to e06fd8c Compare November 4, 2026 19:50
@ndgrigorian
ndgrigorian force-pushed the feature/device-rng-random-state branch from 142a3d8 to 160719a Compare November 4, 2026 19:50
@github-actions

github-actions Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Array API standard conformance tests for dpnp=0.22.0dev3=np2py314h8d9cdd5_126 ran successfully.
Passed: 1491
Failed: 0
Skipped: 6

@coveralls

coveralls commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator

Coverage Status

Coverage is 81.102% — feature/device-rng-random-state into feature/device-rng-bit-generators. No base build found for feature/device-rng-bit-generators.

@github-actions

github-actions Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

View rendered docs @ https://intelpython.github.io/dpnp/pull/3162/index.html

@ndgrigorian
ndgrigorian force-pushed the feature/device-rng-bit-generators branch from e06fd8c to c5182f4 Compare November 6, 2026 17:55
@ndgrigorian
ndgrigorian force-pushed the feature/device-rng-random-state branch 2 times, most recently from edee62b to 843a343 Compare November 8, 2026 21:54
@ndgrigorian
ndgrigorian force-pushed the feature/device-rng-bit-generators branch from acc7ffe to 25ebfd8 Compare November 8, 2026 21:54
Comment thread dpnp/random/dpnp_iface_random.py Resolved
Comment thread dpnp/random/dpnp_iface_random.py Resolved
Comment thread dpnp/random/dpnp_random_state.py Resolved
Comment thread dpnp/random/dpnp_random_state.py Resolved
Comment thread CHANGELOG.md Resolved
Comment thread dpnp/random/_generator.py Resolved
Comment thread dpnp/random/dpnp_random_state.py Resolved
Comment thread dpnp/random/_generator.py Resolved
Comment thread dpnp/random/_generator.py Resolved
Comment thread dpnp/random/dpnp_iface_random.py Resolved
@ndgrigorian
ndgrigorian force-pushed the feature/device-rng-bit-generators branch from 25ebfd8 to ed4d347 Compare November 13, 2026 20:06
@ndgrigorian
ndgrigorian force-pushed the feature/device-rng-random-state branch from 843a343 to 0232b4c Compare November 13, 2026 20:06
@ndgrigorian
ndgrigorian force-pushed the feature/device-rng-bit-generators branch from ed4d347 to a59e76d Compare November 13, 2026 22:41
@ndgrigorian
ndgrigorian force-pushed the feature/device-rng-random-state branch from 0232b4c to 804d1ed Compare November 13, 2026 22:41
@ndgrigorian
ndgrigorian force-pushed the feature/device-rng-bit-generators branch from a59e76d to a04ffb8 Compare November 16, 2026 15:57
@ndgrigorian
ndgrigorian force-pushed the feature/device-rng-random-state branch from 804d1ed to f2ab866 Compare November 16, 2026 15:57
Comment thread dpnp/random/dpnp_iface_random.py Resolved
Comment thread CHANGELOG.md Resolved
@ndgrigorian
ndgrigorian force-pushed the feature/device-rng-bit-generators branch from a04ffb8 to 8694043 Compare November 17, 2026 21:13
@ndgrigorian
ndgrigorian force-pushed the feature/device-rng-random-state branch from f2ab866 to 46d8cc7 Compare November 17, 2026 21:13

@vlad-perevezentsev vlad-perevezentsev left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread dpnp/random/dpnp_iface_random.py Resolved
Comment thread dpnp/random/_generator.py Resolved
Comment thread CHANGELOG.md Resolved
Comment thread doc/reference/random.rst Resolved
@ndgrigorian
ndgrigorian force-pushed the feature/device-rng-bit-generators branch from 8694043 to eef4522 Compare November 20, 2026 01:26
@ndgrigorian
ndgrigorian force-pushed the feature/device-rng-random-state branch from 46d8cc7 to 8463a23 Compare November 20, 2026 01:26
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.
@ndgrigorian
ndgrigorian force-pushed the feature/device-rng-random-state branch from d2f000b to 3194517 Compare November 23, 2026 20:18
@ndgrigorian
ndgrigorian force-pushed the feature/device-rng-bit-generators branch from eb74e82 to 05394c4 Compare November 23, 2026 20:18

@vlad-perevezentsev vlad-perevezentsev left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +830 to +838
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Comment thread dpnp/random/_generator.py
_check_constraint(
pvals, "pvals", _CONS_BOUNDED_0_1, False, device=True
)
if xp.any(pvals[..., :-1].sum(axis=-1) > 1.0 + 1e-12):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +521 to +523
if dpnp.is_supported_array_type(alpha):
# the Generator copies alpha to the host anyway
alpha = dpnp.asnumpy(alpha)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)  # host

Resolving usm_type with _usm_type_of before these conversions would keep it.

Comment thread dpnp/random/_generator.py

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 bounds

Casting device bounds to float64 when the device has fp64 would match.

Comment thread dpnp/random/_generator.py
Comment on lines +302 to +303
rng = dpnp.subtract(fhigh, flow)
rng_dtype = dpnp.subtract(fhigh.astype(dtype), flow.astype(dtype))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 >= high

Converting it as the device path does would fix it.

Comment thread dpnp/random/_generator.py
Comment on lines +3014 to +3019
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):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread doc/reference/random.rst
Comment on lines +85 to 87
``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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants