Python interface to Intel(R) Math Kernel Library's random number generation functionality
Repo IntelPython/mkl_random, read from GitHub 32 min ago. IntelPython has not joined Take My Repo.
This release enables free-threaded (GIL-disabled) CPython builds and adds support for Python 3.15. randint and randint_untyped now accept array-like low/high bounds, as NumPy's RandomState.randint does, and sampling with array-valued distribution parameters and several randint paths is much faster. It also fixes a group of correctness bugs where mkl_random returned uninitialized memory as random values: for out-of-range brng values, for integer generation with WH, MCG31, R250 and MRG32K3A, for degenerate distribution parameters, and for very large requests. geometric now follows the NumPy convention. Several seeded streams change in this release, see Behavior Changes below. Building from source now requires a newer Cython.
๐งต Free-Threaded CPython
freethreading_compatible=True, so importing mkl_random no longer re-enables the GIL. The free-threaded configuration is built and tested in CI on 3.14tMKLRandomState serializes access to its MKL stream under its own lock, so one generator can be shared between threads. The how-to guide has a new thread-safety sectionpython-gil constraint from the conda recipes that pinned mkl_random to GIL-enabled Python 3.14 builds๐ Python 3.15 Support
๐ฒ Array-Like Bounds in randint
randint accepts broadcastable low/high arrays, as numpy.random.RandomState.randint does, drawing each element with Lemire's methodrandint_untyped reuses the randint implementation, so it gains the same array-like bounds and no longer raises OverflowError for bounds outside the C long range (e.g. 2**40 on Windows)โก Performance
normal, uniform, exponential, laplace, gumbel, logistic, rayleigh and lognormal with array-valued parameters fill the whole request with one MKL call instead of one call per elementrandint for power-of-two ranges at or above INT_MAX, for bool, int8, uint8, int16 and uint16, and for array-like boundsshuffle uses its memcpy fast path for multi-dimensional arrays whose first-axis items are contiguousWH, MCG31, R250 and MRG32K3A uses less memory and is faster๐ Correctness Fixes
brng and MKLRandomState(seed, brng=None) no longer read past the generator table and fall back to MT19937; brng=0 now selects MT19937 instead of leaving the state unseededrandint with scalar bounds above INT_MAX, tomaxint and bytes return random data for WH, MCG31, R250 and MRG32K3A, which lack viRngUniformBits supportpoisson with lam == 0 and negative_binomial with p == 1 return zeros, and geometric rejects NaN, instead of returning the untouched output bufferMKL_INT_MAX chunks, multinomial, multinormal_cholesky when the number of samples times the dimension exceeds MKL_INT_MAX, and 64-bit integers with PHILOX4X32X10 and ARS5randint no longer returns high for 64-bit dtypes when the range is at or above INT_MAXset_state and logseries๐ Other Additions
ICDF, BOXMULLER, BOXMULLER2, POISNORM and PTPE are exported from mkl_random, as the method docstrings already documentedbenchmarks/โ ๏ธ Behavior Changes
randint ranges at or above INT_MAX, for geometric, and for integer-like method ids such as np.int64(2), which now select the method they name instead of BoxMullergeometric now counts trials, as its docstring and NumPy do: the support starts at 1 and the mean is 1 / p. Samples that fit in int32 are one larger than before, and geometric(p) - 1 gives the old values. The samples are still int32, unlike NumPy's int64method values now emit a UserWarning listing the supported methods before falling back to the default methodValueErrors: negative_binomial with p == 0; NaN parameters to poisson, negative_binomial, geometric and logseries; array-valued parameters of the eight distributions above that do not broadcast to size without adding dimensions; multinormal_cholesky with an empty mean, which used to raise ZeroDivisionErroruniform with scalar bounds and size=None returns a Python float instead of a 0-d array; with array-valued bounds it may return high due to floating-point rounding๐ฆ Build Requirement Changes
Cython raised to 3.1.0 (first release providing the freethreading_compatible directive)array_like (broadcastable) low/high bounds in randint gh-168freethreading_compatible=True, so importing mkl_random no longer re-enables the GIL gh-159benchmarks/ and a benchmark optional dependency group gh-184ICDF, BOXMULLER, BOXMULLER2, POISNORM and PTPE from mkl_random, as the method docstrings already documented gh-189method values (e.g. a misspelled name, a method the function does not implement, None, bool, float) now emit a UserWarning listing the supported methods before falling back to the function's default method, instead of falling back silently gh-189normal, uniform, exponential, laplace, gumbel, logistic, rayleigh and lognormal for array-valued parameters. Seeded results change for these array paths; scalar paths are unchanged gh-171size without adding dimensions; previously accepted mismatches now raise ValueError gh-171uniform with array-valued bounds may return high due to floating-point rounding gh-171coverity/README.md documenting the known Cython-boilerplate false positives and the scan review checklist gh-164randint for power-of-two ranges at or above INT_MAX gh-172randint ranges at or above INT_MAX have changed: with a fixed seed these now produce different (but equally valid) samples gh-172randint for bool, uint8, int8, uint16 and int16; generated values are unchanged gh-172Cython requirement to 3.1.0, the first release providing the freethreading_compatible directive gh-159memcpy-based fast path of shuffle to multi-dimensional ndarray inputs whose first-axis items are contiguous, which is also much faster than the previous buffered path gh-159randint_untyped implementation, which now supports array_like (broadcastable) low/high bounds gh-176randint with array_like bounds by generating words in cache-sized chunks and by picking the Lemire rejection test by range width gh-173WH, MCG31, R250 and MRG32K3A, which lack viRngUniformBits support gh-178mklrand_py_helper.h shim with cpython.bytes cimports and dropped the no-op __future__ import, since the project requires Python 3.10+ gh-192negative_binomial now rejects p == 0, which MKL does not support, with a ValueError; the documented range of p is (0, 1] gh-195poisson, negative_binomial, geometric and logseries now reject NaN parameters with a ValueError, as NumPy does, instead of passing them to MKL gh-195geometric samples are now one larger than before for every p whose result fits in int32, so results for a fixed seed change; geometric(p) - 1 reproduces the old values for them gh-196poisson with a scalar lam == 0 returning uninitialized memory as random values, since MKL requires lam > 0. The same applied to array-valued lam with method="PTPE". Both now return zeros, as the default array path and NumPy already did gh-195negative_binomial with p == 1 returning uninitialized memory as random values, since MKL requires p < 1; it now returns zeros, as NumPy does gh-195geometric with p being NaN returning uninitialized memory as random values gh-195logseries rejecting p == 0, which NumPy documents as valid; it now returns ones, which its sampler already produced without a special case gh-195multinormal_cholesky and the other functions taking method routing integer-like ids such as np.int64(0), np.int64(2) or False to BoxMuller; NumPy integers now select the method they name gh-189multinormal_cholesky raising ZeroDivisionError for an empty mean; it now raises ValueError gh-189brng indexing brng_list past its end, which returned uninitialized memory as random values; it now warns and falls back to MT19937 gh-177brng=0 being treated as unset, which left the state unseeded gh-177MKLRandomState(seed, brng=None) reading past brng_list and returning uninitialized memory; it now uses MT19937 gh-177uniform to return a Python float for scalar bounds with size=None instead of a 0-d array gh-167randint returning high for int64, uint64 and the default int dtype when the range is at or above INT_MAX gh-172MKL_INT_MAX chunks gh-172multinomial under-filling large outputs by decrementing its chunk counter by elements instead of draws gh-172set_state, which leaked the previous MKL stream on every call gh-159logseries, which leaked a temporary buffer on every call gh-159set_state replacing the generator state before raising ValueError when the buffer does not match the algorithm name; the state is now left unchanged gh-159get_state writing past its buffer when another thread reseeded the generator with a different brng at the same time, and a deadlock when a seed value or a shuffle element called back into the same generator gh-159randint with scalar bounds above INT_MAX, tomaxint and bytes returning uninitialized data for WH, MCG31, R250 and MRG32K3A, which lack viRngUniformBits support gh-175PHILOX4X32X10 and ARS5 for requests of 2**30 elements or more gh-175randint_untyped raising OverflowError for bounds outside the C long range, e.g. 2**40 on Windows gh-176multinormal_cholesky silently returning wrong output, e.g. every sample equal to mean, when the number of samples times the dimension exceeds MKL_INT_MAX gh-187bytes docstring, which documented a str return type instead of bytes gh-192tomaxint example, which compared against the Python 2 sys.maxint gh-192random_sample, random_integers and randint docstrings and in the zipf implementation comment: the <type '...'> reprs, np.int and sys.maxint gh-192random_integers docstring, which described the result as numpy.int_ rather than a C long, documented the wrong scalar return type, and passed a float size that no longer works gh-192geometric returning the number of failures before the first success instead of the number of trials, which contradicted its own docstring and NumPy. The support now starts at 1, P(1) is p and the mean is 1 / p. The samples are still int32, unlike NumPy's int64, and overflow for very small p gh-196python-gil constraint from the conda recipes, which pinned mkl_random to GIL-enabled Python 3.14 builds gh-159Full Changelog: 1.5.0...1.6.0
This release migrates mkl_random to a modern Meson-based build system, replacing the legacy setuptools/setup.py pipeline. It also introduces a command-line interface for patching NumPy's random with MKL-accelerated implementations, and adds compatibility with NumPy 2.5.
๐๏ธ New Build System
setuptools to meson-python, removing setup.py in favor of meson.build, aligning mkl_random with the build system used by NumPy and SciPyninja/cmake are formal build requirements๐ NumPy random patching CLI
python -m mkl_random --patch install/uninstall/status for persistent NumPy random patching across all Python sessionspython -m mkl_random --with-numpy-patch <command> for one-shot execution of a command with MKL-accelerated random๐ง NumPy 2.5 compatibility
mkl_random and its test suite to work with NumPy 2.5, replacing APIs deprecated upstreampython -m mkl_random --patch <command> and python -m mkl_random --with-numpy-patch <command> gh-133numpy-base dependency and USE_NUMPY_BASE environment variable from conda recipe gh-124setuptools to meson-python, removing setup.py in favor of meson.build gh-113shape assignment with reshape, and by replacing the deprecated numpy.testing.suppress_warnings usage in tests with pytest.warns gh-137irk_rand_uint32_vec by declaring the shift variable as npy_uint32 instead of npy_int32, so 2**31 no longer overflows a signed 32-bit integer (behavior is unchanged as all downstream uses rely on modulo-2^32 arithmetic) gh-156Full Changelog: 1.4.2...1.5.0
This is a maintenance release focused on compatibility with newer NumPy and a more robust conda build. It restores a green test suite against NumPy 2.5, drops the numpy-base dependency from the conda recipe, and fixes the conda package workflow. There are no API changes โ this release is functionally identical to 1.4.1 for end users.
numpy-base dependency and USE_NUMPY_BASE environment variable from conda recipe gh-124shape assignment with reshape, and by replacing the deprecated numpy.testing.suppress_warnings usage in tests with pytest.warns gh-137Full Changelog: 1.4.1...1.4.2
This release is identical to 1.4.0 in terms of features
This release only changes package metadata to remove mkl as a runtime dependency, preventing pip check failures when mkl_random is installed in an environment.
mkl as runtime dependency to avoid possible pip check failures gh-126This release introduces NumPy compatibility through a new patching system and dedicated interface module. mkl_random can now seamlessly replace NumPy's random number generation while maintaining full API compatibility. The release includes extensive test coverage from NumPy's test suite, numerous bug fixes, and improvements to align with modern NumPy behavior. Python 3.9 support has been dropped.
๐ NumPy Patching System
numpy.random with mkl_random implementationsis_patched() function๐ฏ Strict NumPy API Interface
mkl_random.interfaces.numpy_random module provides pure NumPy-compatible APIโ Enhanced Test Coverage
numpy.random integrated to validate compatibility๐ Bug Fixes & Improvements
zipf when called with np.nan๐ฆ Flexible Build Configuration
USE_NUMPY_BASE environment variableโ ๏ธ Breaking Changes
mkl_random.RandomState deprecated - Use mkl_random.MKLRandomState instead. RandomState now delegates to the numpy_random interface for compatibility.Added mkl_random patching for NumPy, with mkl_random context manager, is_patched query, and patch_numpy_random and restore_numpy_random calls to replace numpy.random calls with calls from mkl_random.interfaces.numpy_random gh-90
Added mkl_random.interfaces with mkl_random.interfaces.numpy_random interface, which aliases mkl_random functionality to more strictly adhere to NumPy's API (i.e., drops arguments and functions which are not part of standard NumPy) gh-92
Added third-party tests from numpy.random which tests the mkl_random.interfaces.numpy_random interface gh-103
mkl_random implementations to better align with newer versions of numpy.random gh-103, gh-115USE_NUMPY_BASE environment variable gh-105zipf when called with np.nan and size-1 1D arrays being cast to scalars gh-103, gh-115mkl_random.RandomState in favor of mkl_random.MKLRandomState, delegating mkl_random.RandomState to the mkl_random.interfaces.numpy_random interface gh-92Full Changelog: v1.3.1...v1.4.0