Skip to content

Add discrete distributions to dpnp.random.Generator - #3159

Open
ndgrigorian wants to merge 14 commits into
feature/device-rng-continuousfrom
feature/device-rng-discrete
Open

ndgrigorian wants to merge 14 commits into
feature/device-rng-continuousfrom
feature/device-rng-discrete

Conversation

@ndgrigorian

@ndgrigorian ndgrigorian commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator

This PR adds integers and the discrete distributions to dpnp.random.Generator, as part of the series splitting #3147. It is stacked on #3158

Adds

  • integers, using NumPy's bounded integer algorithm (Lemire's method)
  • poisson, binomial (inversion and BTPE), negative_binomial, geometric, logseries, zipf and hypergeometric (HRUA)
  • 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. 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 one log1p so that they don't cancel. zipf uses expm1/log1p, deliberately departing from NumPy, whose tail for a close to 1 is too heavy above 2**53 (documented in random.rst)

As in #3158, every rejection sampler returns the smallest int64 for device parameters that would make it loop forever

Also adds umul_hi, which replaces sycl::mul_hi; DPC++ 2026.2 miscompiles sycl::mul_hi on Intel GPUs when one operand is a compile-time constant

  • 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?

@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

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

@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_79 ran successfully.
Passed: 1491
Failed: 0
Skipped: 6

@coveralls

coveralls commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator

Coverage Status

Coverage is 84.727% — feature/device-rng-discrete into feature/device-rng-continuous. No base build found for feature/device-rng-continuous.

@ndgrigorian
ndgrigorian force-pushed the feature/device-rng-continuous branch from adf7178 to cfa00bd Compare November 6, 2026 17:55
@ndgrigorian
ndgrigorian force-pushed the feature/device-rng-discrete branch 2 times, most recently from 6388643 to f48c80e Compare November 8, 2026 21:54
@ndgrigorian
ndgrigorian force-pushed the feature/device-rng-continuous branch from df5cb09 to 7c8127b Compare November 8, 2026 21:54
Comment thread dpnp/tests/test_random_generator.py Resolved
Comment thread dpnp/random/_generator.py Resolved
Comment thread dpnp/random/_generator.py Resolved
Comment thread dpnp/random/_generator.py Resolved
Comment thread dpnp/random/_generator.py Resolved
Comment thread dpnp/tests/test_random_generator.py Resolved
@ndgrigorian
ndgrigorian force-pushed the feature/device-rng-discrete branch from f48c80e to dcabbc2 Compare November 13, 2026 20:06
@ndgrigorian
ndgrigorian force-pushed the feature/device-rng-continuous branch from 7c8127b to 9ed9f9a Compare November 13, 2026 20:06
@ndgrigorian
ndgrigorian force-pushed the feature/device-rng-discrete branch from dcabbc2 to bb4b69b Compare November 13, 2026 22:41
Comment thread dpnp/random/_generator.py Resolved
@ndgrigorian
ndgrigorian force-pushed the feature/device-rng-discrete branch from f4938e0 to a64886a Compare November 17, 2026 21:13
@ndgrigorian
ndgrigorian force-pushed the feature/device-rng-continuous branch from 78535ba to 6317de6 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 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.

Comment thread dpnp/random/_generator.py Resolved
@ndgrigorian
ndgrigorian force-pushed the feature/device-rng-discrete branch from a64886a to ba52aac Compare November 20, 2026 01:26
@ndgrigorian
ndgrigorian force-pushed the feature/device-rng-continuous branch from 6317de6 to 37d8b1e Compare November 20, 2026 01:26
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.
@ndgrigorian
ndgrigorian force-pushed the feature/device-rng-continuous branch from d17b470 to dcd4617 Compare November 23, 2026 20:18
@ndgrigorian
ndgrigorian force-pushed the feature/device-rng-discrete branch from 76467f9 to 2b5045e 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 last fix works, the tests pass, and the samples match the earlier runs. But float32 geometric can hang the GPU.
A few comments below:

Comment on lines +982 to +987
// rounding can stall the sum below U, until prod underflows
while ((U > sum) && (prod > T(0))) {
prod *= q;
sum += prod;
X++;
}

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.

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 s

Stopping 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;
        }

Comment thread dpnp/random/_generator.py
Comment on lines +2458 to +2460
return self._discrete_sample(
ri._binomial, (n, p), size, usm_type, param_types=(_int64, None)
)

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 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.100

logseries(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?

Comment on lines +32 to +33
${CMAKE_CURRENT_SOURCE_DIR}/binomial.cpp
${CMAKE_CURRENT_SOURCE_DIR}/discrete.cpp

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.

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?

Comment on lines +545 to +546
const T t = noncentral_chisquare<T>(bg, normal, dfnum, nonc) * dfden;
return t / (chisquare<T>(bg, normal, dfden) * dfnum);

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: 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 1

Dividing 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);

Comment on lines +1895 to +1898
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}),

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: 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]], {}),

Comment thread dpnp/random/_generator.py
Comment on lines +2656 to +2657
The number of items drawn, at least 1 and at most
``ngood + nbad``.

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: 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.

Comment thread dpnp/random/_generator.py
Comment on lines +2454 to +2455
# NumPy converts both parameters before checking either
n = _as_int64(n)

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 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 OverflowError

Converting p first would match it.

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