CuPy: NumPy & SciPy-compatible array library for GPU-accelerated computing with Python that provides a drop-in replacement for NumPy/SciPy on NVIDIA CUDA platforms.
—
GPU-accelerated random number generation through cuRAND integration, supporting various probability distributions and random sampling operations with high performance on GPU. CuPy provides both legacy RandomState API and modern Generator API for comprehensive random number capabilities.
Control random number generation state and seeding for reproducible results.
class RandomState:
"""Container for Mersenne Twister pseudo-random number generator.
Provides legacy NumPy-compatible interface for random number generation
with GPU acceleration through cuRAND.
"""
def __init__(self, seed=None):
"""Initialize random state.
Parameters:
- seed: int, array-like, or None, random seed for initialization
"""
def get_random_state():
"""Get current global random state.
Returns:
RandomState: current global random number generator
"""
def set_random_state(rs):
"""Set global random state.
Parameters:
- rs: RandomState, random state to set as global
"""
def seed(seed=None):
"""Seed global random number generator.
Parameters:
- seed: int, array-like, or None, random seed
"""
def reset_states():
"""Reset all random states to default."""Advanced random number generation with improved statistical properties.
class Generator:
"""Random number generator using modern algorithms.
Provides improved random number generation with better statistical
properties and performance compared to legacy RandomState.
"""
class BitGenerator:
"""Base class for bit generators.
Provides low-level random bit generation for Generator classes.
"""
class XORWOW:
"""XORWOW bit generator.
High-performance pseudo-random number generator optimized for GPU.
"""
class MRG32k3a:
"""MRG32k3a bit generator.
Combined multiple recursive generator with excellent statistical properties.
"""
class Philox4x3210:
"""Philox bit generator.
Counter-based random number generator with parallel generation capability.
"""
def default_rng(seed=None):
"""Construct new Generator with default BitGenerator.
Parameters:
- seed: int, array-like, or None, random seed
Returns:
Generator: new random number generator
"""Basic random number generation functions for common use cases.
def random(size=None):
"""Random floats in half-open interval [0.0, 1.0).
Parameters:
- size: int or tuple of ints, output shape
Returns:
cupy.ndarray: array of random floats
"""
def rand(*size):
"""Random values in [0, 1) with given shape.
Parameters:
- size: int arguments, dimensions of output array
Returns:
cupy.ndarray: array of random values
"""
def randn(*size):
"""Standard normal distribution with given shape.
Parameters:
- size: int arguments, dimensions of output array
Returns:
cupy.ndarray: array of random values from N(0,1)
"""
def random_sample(size=None):
"""Random floats in [0.0, 1.0) (alias for random)."""
def ranf(size=None):
"""Random floats in [0.0, 1.0) (alias for random)."""
def sample(size=None):
"""Random floats in [0.0, 1.0) (alias for random)."""Generate random integers within specified ranges.
def randint(low, high=None, size=None, dtype='l'):
"""Random integers from low (inclusive) to high (exclusive).
Parameters:
- low: int, lowest integer to draw (inclusive)
- high: int, highest integer to draw (exclusive)
- size: int or tuple of ints, output shape
- dtype: str or dtype, data type of output
Returns:
cupy.ndarray: array of random integers
"""
def random_integers(low, high=None, size=None):
"""Random integers between low and high, inclusive.
Parameters:
- low: int, lowest integer (inclusive)
- high: int, highest integer (inclusive)
- size: int or tuple of ints, output shape
Returns:
cupy.ndarray: array of random integers
"""Random sampling from continuous probability distributions.
def normal(loc=0.0, scale=1.0, size=None):
"""Draw samples from normal (Gaussian) distribution.
Parameters:
- loc: float or array-like, mean of distribution
- scale: float or array-like, standard deviation
- size: int or tuple of ints, output shape
Returns:
cupy.ndarray: drawn samples
"""
def uniform(low=0.0, high=1.0, size=None):
"""Draw samples from uniform distribution.
Parameters:
- low: float or array-like, lower boundary
- high: float or array-like, upper boundary
- size: int or tuple of ints, output shape
Returns:
cupy.ndarray: drawn samples
"""
def exponential(scale=1.0, size=None):
"""Draw samples from exponential distribution.
Parameters:
- scale: float or array-like, scale parameter (1/rate)
- size: int or tuple of ints, output shape
Returns:
cupy.ndarray: drawn samples
"""
def gamma(shape, scale=1.0, size=None):
"""Draw samples from Gamma distribution.
Parameters:
- shape: float or array-like, shape parameter
- scale: float or array-like, scale parameter
- size: int or tuple of ints, output shape
Returns:
cupy.ndarray: drawn samples
"""
def beta(a, b, size=None):
"""Draw samples from Beta distribution.
Parameters:
- a: float or array-like, alpha parameter
- b: float or array-like, beta parameter
- size: int or tuple of ints, output shape
Returns:
cupy.ndarray: drawn samples
"""
def chisquare(df, size=None):
"""Draw samples from chi-square distribution.
Parameters:
- df: float or array-like, degrees of freedom
- size: int or tuple of ints, output shape
Returns:
cupy.ndarray: drawn samples
"""
def f(dfnum, dfden, size=None):
"""Draw samples from F distribution.
Parameters:
- dfnum: float or array-like, degrees of freedom in numerator
- dfden: float or array-like, degrees of freedom in denominator
- size: int or tuple of ints, output shape
Returns:
cupy.ndarray: drawn samples
"""
def lognormal(mean=0.0, sigma=1.0, size=None):
"""Draw samples from log-normal distribution."""
def standard_normal(size=None):
"""Draw samples from standard normal distribution N(0,1)."""
def standard_exponential(size=None):
"""Draw samples from standard exponential distribution."""
def standard_gamma(shape, size=None):
"""Draw samples from standard Gamma distribution."""
def standard_cauchy(size=None):
"""Draw samples from standard Cauchy distribution."""
def standard_t(df, size=None):
"""Draw samples from Student's t-distribution."""
def laplace(loc=0.0, scale=1.0, size=None):
"""Draw samples from Laplace distribution."""
def logistic(loc=0.0, scale=1.0, size=None):
"""Draw samples from logistic distribution."""
def gumbel(loc=0.0, scale=1.0, size=None):
"""Draw samples from Gumbel distribution."""
def weibull(a, size=None):
"""Draw samples from Weibull distribution."""
def pareto(a, size=None):
"""Draw samples from Pareto II distribution."""
def power(a, size=None):
"""Draw samples from power distribution."""
def rayleigh(scale=1.0, size=None):
"""Draw samples from Rayleigh distribution."""
def triangular(left, mode, right, size=None):
"""Draw samples from triangular distribution."""
def vonmises(mu, kappa, size=None):
"""Draw samples from von Mises distribution."""
def wald(mean, scale, size=None):
"""Draw samples from Wald distribution."""Sample from multivariate probability distributions.
def multivariate_normal(mean, cov, size=None, check_valid='warn', tol=1e-8):
"""Draw samples from multivariate normal distribution.
Parameters:
- mean: 1-D array-like, mean of distribution
- cov: 2-D array-like, covariance matrix
- size: int or tuple of ints, output shape
- check_valid: str, behavior when covariance is not valid
- tol: float, tolerance for eigenvalue check
Returns:
cupy.ndarray: drawn samples
"""
def dirichlet(alpha, size=None):
"""Draw samples from Dirichlet distribution.
Parameters:
- alpha: sequence of floats, concentration parameters
- size: int or tuple of ints, output shape
Returns:
cupy.ndarray: drawn samples
"""
def multinomial(n, pvals, size=None):
"""Draw samples from multinomial distribution.
Parameters:
- n: int, number of trials
- pvals: sequence of floats, probabilities of each outcome
- size: int or tuple of ints, output shape
Returns:
cupy.ndarray: drawn samples
"""Random sampling from discrete probability distributions.
def binomial(n, p, size=None):
"""Draw samples from binomial distribution.
Parameters:
- n: int or array-like, number of trials
- p: float or array-like, probability of success
- size: int or tuple of ints, output shape
Returns:
cupy.ndarray: drawn samples
"""
def poisson(lam=1.0, size=None):
"""Draw samples from Poisson distribution.
Parameters:
- lam: float or array-like, expected number of events
- size: int or tuple of ints, output shape
Returns:
cupy.ndarray: drawn samples
"""
def geometric(p, size=None):
"""Draw samples from geometric distribution.
Parameters:
- p: float or array-like, probability of success
- size: int or tuple of ints, output shape
Returns:
cupy.ndarray: drawn samples
"""
def negative_binomial(n, p, size=None):
"""Draw samples from negative binomial distribution."""
def hypergeometric(ngood, nbad, nsample, size=None):
"""Draw samples from hypergeometric distribution."""
def logseries(p, size=None):
"""Draw samples from logarithmic series distribution."""
def zipf(a, size=None):
"""Draw samples from Zipf distribution."""Specialized and advanced probability distributions.
def noncentral_chisquare(df, nonc, size=None):
"""Draw samples from noncentral chi-square distribution.
Parameters:
- df: float or array-like, degrees of freedom
- nonc: float or array-like, non-centrality parameter
- size: int or tuple of ints, output shape
Returns:
cupy.ndarray: drawn samples
"""
def noncentral_f(dfnum, dfden, nonc, size=None):
"""Draw samples from noncentral F distribution.
Parameters:
- dfnum: float or array-like, degrees of freedom in numerator
- dfden: float or array-like, degrees of freedom in denominator
- nonc: float or array-like, non-centrality parameter
- size: int or tuple of ints, output shape
Returns:
cupy.ndarray: drawn samples
"""Functions for shuffling and sampling from arrays.
def shuffle(x):
"""Modify sequence in-place by shuffling contents.
Parameters:
- x: array-like, sequence to shuffle
"""
def permutation(x):
"""Randomly permute sequence or return permuted range.
Parameters:
- x: int or array-like, sequence to permute or length of range
Returns:
cupy.ndarray: permuted sequence
"""
def choice(a, size=None, replace=True, p=None):
"""Generate random sample from given 1-D array.
Parameters:
- a: 1-D array-like or int, array to sample from or sample size
- size: int or tuple of ints, output shape
- replace: bool, whether sampling is with replacement
- p: 1-D array-like, probabilities associated with entries in a
Returns:
cupy.ndarray: generated random samples
"""Random functions that execute on CPU for compatibility.
def bytes(length):
"""Return random bytes (NumPy-based, runs on host).
Parameters:
- length: int, number of random bytes to generate
Returns:
bytes: random byte string
"""import cupy as cp
# Set seed for reproducibility
cp.random.seed(42)
# Generate basic random data
random_floats = cp.random.random((1000, 1000)) # Uniform [0,1)
random_ints = cp.random.randint(0, 100, size=(500, 500)) # Integers [0,100)
normal_data = cp.random.randn(10000) # Standard normal N(0,1)
# Check statistics
print(f"Mean: {cp.mean(random_floats):.4f}") # Should be ~0.5
print(f"Std: {cp.std(normal_data):.4f}") # Should be ~1.0import cupy as cp
import matplotlib.pyplot as plt
# Sample from various distributions
normal_samples = cp.random.normal(loc=5.0, scale=2.0, size=10000)
exponential_samples = cp.random.exponential(scale=2.0, size=10000)
gamma_samples = cp.random.gamma(shape=2.0, scale=1.5, size=10000)
# Generate synthetic dataset with multiple features
n_samples = 5000
features = cp.random.multivariate_normal(
mean=[0, 0, 0],
cov=[[1, 0.5, 0.2], [0.5, 1, 0.3], [0.2, 0.3, 1]],
size=n_samples
)
print(f"Feature correlation: {cp.corrcoef(features.T)}")import cupy as cp
# Create independent random states
rng1 = cp.random.RandomState(seed=123)
rng2 = cp.random.RandomState(seed=456)
# Generate different sequences
seq1 = rng1.random(10)
seq2 = rng2.random(10)
# Reset and regenerate - should be identical
rng1 = cp.random.RandomState(seed=123)
seq1_repeat = rng1.random(10)
print(f"Sequences identical: {cp.allclose(seq1, seq1_repeat)}") # True
# Use modern Generator API for better performance
gen = cp.random.default_rng(seed=789)
modern_samples = gen.random((1000, 1000))import cupy as cp
def estimate_pi_monte_carlo(n_samples):
"""Estimate π using Monte Carlo method."""
# Generate random points in unit square
x = cp.random.uniform(-1, 1, n_samples)
y = cp.random.uniform(-1, 1, n_samples)
# Count points inside unit circle
inside_circle = (x**2 + y**2) <= 1
pi_estimate = 4 * cp.mean(inside_circle)
return float(pi_estimate)
# Estimate π with increasing precision
for n in [1000, 10000, 100000, 1000000]:
pi_est = estimate_pi_monte_carlo(n)
error = abs(pi_est - cp.pi)
print(f"n={n:7d}: π ≈ {pi_est:.6f}, error = {error:.6f}")import cupy as cp
# Choice sampling with probabilities
outcomes = cp.array([1, 2, 3, 4, 5, 6]) # Dice outcomes
probabilities = cp.array([0.1, 0.1, 0.1, 0.1, 0.3, 0.3]) # Biased die
rolls = cp.random.choice(outcomes, size=10000, p=probabilities)
# Shuffle operations
deck = cp.arange(52) # Card deck
cp.random.shuffle(deck) # Shuffle in-place
random_permutation = cp.random.permutation(52) # Return new permutation
# Bootstrap sampling
original_data = cp.random.normal(10, 2, 1000)
bootstrap_samples = cp.random.choice(
original_data,
size=(1000, 1000), # 1000 bootstrap samples of size 1000
replace=True
)
bootstrap_means = cp.mean(bootstrap_samples, axis=1)
confidence_interval = cp.percentile(bootstrap_means, [2.5, 97.5])Install with Tessl CLI
npx tessl i tessl/pypi-cupy-cuda113