CuPy: NumPy & SciPy for GPU (CUDA 10.1 version)
—
GPU-based random number generation with comprehensive probability distributions. CuPy provides both legacy RandomState interface and modern Generator API with various bit generators, all accelerated on GPU for high-performance random sampling.
Modern random number generation interface with explicit state management and multiple bit generators.
def default_rng(seed=None):
"""
Construct default random number generator.
Parameters:
- seed: int, array-like, SeedSequence, BitGenerator, or Generator, optional
Returns:
cupy.random.Generator: Random number generator instance
"""
class Generator:
"""
Random number generator with explicit state management.
Modern interface for random number generation providing
better control over random state and reproducibility.
"""
def __init__(self, bit_generator):
"""
Initialize generator with bit generator.
Parameters:
- bit_generator: cupy.random.BitGenerator, source of randomness
"""
def random(self, size=None, dtype=cupy.float64, out=None):
"""
Generate random floats in [0.0, 1.0).
Parameters:
- size: int or tuple, output shape, optional
- dtype: data type, float32 or float64
- out: array, output array, optional
Returns:
cupy.ndarray: Random floats on GPU
"""
def integers(self, low, high=None, size=None, dtype=cupy.int64):
"""
Generate random integers.
Parameters:
- low: int, lower bound (inclusive) or upper bound if high is None
- high: int, upper bound (exclusive), optional
- size: int or tuple, output shape, optional
- dtype: data type, integer type
Returns:
cupy.ndarray: Random integers on GPU
"""
def normal(self, loc=0.0, scale=1.0, size=None):
"""
Generate normally distributed random numbers.
Parameters:
- loc: float or array, mean
- scale: float or array, standard deviation
- size: int or tuple, output shape, optional
Returns:
cupy.ndarray: Normal random numbers on GPU
"""
def uniform(self, low=0.0, high=1.0, size=None):
"""
Generate uniformly distributed random numbers.
Parameters:
- low: float or array, lower bound
- high: float or array, upper bound
- size: int or tuple, output shape, optional
Returns:
cupy.ndarray: Uniform random numbers on GPU
"""
class BitGenerator:
"""
Base class for bit generators.
Provides the core random bit generation functionality
used by Generator instances.
"""
def random_raw(self, size=None, output=True):
"""
Generate raw random bits.
Parameters:
- size: int or tuple, output shape, optional
- output: bool, whether to return output
Returns:
cupy.ndarray: Raw random bits
"""
class XORWOW(BitGenerator):
"""
XORWOW bit generator (default for CuPy).
Fast bit generator suitable for most applications,
optimized for GPU parallel execution.
"""
def __init__(self, seed=None):
"""
Initialize XORWOW bit generator.
Parameters:
- seed: int, array-like, or SeedSequence, optional
"""Convenient functions for common random number generation tasks.
def random(size=None):
"""
Generate random floats in [0.0, 1.0).
Parameters:
- size: int or tuple, output shape, optional
Returns:
cupy.ndarray: Random floats on GPU
"""
def rand(*size):
"""
Generate random floats in [0.0, 1.0) with specified dimensions.
Parameters:
- size: ints, dimensions
Returns:
cupy.ndarray: Random floats on GPU
"""
def randn(*size):
"""
Generate standard normal random numbers.
Parameters:
- size: ints, dimensions
Returns:
cupy.ndarray: Standard normal random numbers on GPU
"""
def randint(low, high=None, size=None, dtype=int):
"""
Generate random integers.
Parameters:
- low: int, lower bound (inclusive) or upper bound if high is None
- high: int, upper bound (exclusive), optional
- size: int or tuple, output shape, optional
- dtype: data type, integer type
Returns:
cupy.ndarray: Random integers on GPU
"""
def choice(a, size=None, replace=True, p=None):
"""
Generate random sample from array.
Parameters:
- a: int or array-like, input array or size
- size: int or tuple, output shape, optional
- replace: bool, sampling with replacement
- p: array-like, probabilities, optional
Returns:
cupy.ndarray: Random sample on GPU
"""Comprehensive set of probability distributions for statistical sampling.
def normal(loc=0.0, scale=1.0, size=None):
"""
Normal (Gaussian) distribution.
Parameters:
- loc: float or array, mean
- scale: float or array, standard deviation
- size: int or tuple, output shape, optional
Returns:
cupy.ndarray: Normal random numbers on GPU
"""
def uniform(low=0.0, high=1.0, size=None):
"""
Uniform distribution.
Parameters:
- low: float or array, lower bound
- high: float or array, upper bound
- size: int or tuple, output shape, optional
Returns:
cupy.ndarray: Uniform random numbers on GPU
"""
def exponential(scale=1.0, size=None):
"""
Exponential distribution.
Parameters:
- scale: float or array, scale parameter
- size: int or tuple, output shape, optional
Returns:
cupy.ndarray: Exponential random numbers on GPU
"""
def gamma(shape, scale=1.0, size=None):
"""
Gamma distribution.
Parameters:
- shape: float or array, shape parameter
- scale: float or array, scale parameter
- size: int or tuple, output shape, optional
Returns:
cupy.ndarray: Gamma random numbers on GPU
"""
def beta(a, b, size=None):
"""
Beta distribution.
Parameters:
- a: float or array, alpha parameter
- b: float or array, beta parameter
- size: int or tuple, output shape, optional
Returns:
cupy.ndarray: Beta random numbers on GPU
"""
def binomial(n, p, size=None):
"""
Binomial distribution.
Parameters:
- n: int or array, number of trials
- p: float or array, probability of success
- size: int or tuple, output shape, optional
Returns:
cupy.ndarray: Binomial random numbers on GPU
"""
def poisson(lam=1.0, size=None):
"""
Poisson distribution.
Parameters:
- lam: float or array, rate parameter
- size: int or tuple, output shape, optional
Returns:
cupy.ndarray: Poisson random numbers on GPU
"""
def chisquare(df, size=None):
"""
Chi-square distribution.
Parameters:
- df: float or array, degrees of freedom
- size: int or tuple, output shape, optional
Returns:
cupy.ndarray: Chi-square random numbers on GPU
"""
def laplace(loc=0.0, scale=1.0, size=None):
"""
Laplace distribution.
Parameters:
- loc: float or array, location parameter
- scale: float or array, scale parameter
- size: int or tuple, output shape, optional
Returns:
cupy.ndarray: Laplace random numbers on GPU
"""
def lognormal(mean=0.0, sigma=1.0, size=None):
"""
Log-normal distribution.
Parameters:
- mean: float or array, mean of underlying normal
- sigma: float or array, standard deviation of underlying normal
- size: int or tuple, output shape, optional
Returns:
cupy.ndarray: Log-normal random numbers on GPU
"""
def multivariate_normal(mean, cov, size=None, check_valid='warn', tol=1e-8):
"""
Multivariate normal distribution.
Parameters:
- mean: array-like, mean vector
- cov: array-like, covariance matrix
- size: int or tuple, output shape, optional
- check_valid: str, covariance validation
- tol: float, tolerance for singular values
Returns:
cupy.ndarray: Multivariate normal random vectors on GPU
"""Functions for shuffling arrays and generating permutations.
def shuffle(x):
"""
Shuffle array in-place.
Parameters:
- x: array-like, array to shuffle
"""
def permutation(x):
"""
Generate random permutation.
Parameters:
- x: int or array-like, array to permute or size
Returns:
cupy.ndarray: Random permutation on GPU
"""Legacy interface for backward compatibility with older NumPy random APIs.
class RandomState:
"""
Random state container (legacy interface).
Maintains random state for reproducible random number generation.
Provided for compatibility with older NumPy random APIs.
"""
def __init__(self, seed=None):
"""
Initialize random state.
Parameters:
- seed: int, array-like, or None, random seed
"""
def seed(self, seed=None):
"""
Reseed random number generator.
Parameters:
- seed: int, array-like, or None, random seed
"""
def get_state(self):
"""
Get current random state.
Returns:
dict: Current random state
"""
def set_state(self, state):
"""
Set random state.
Parameters:
- state: dict, random state to restore
"""
def seed(seed=None):
"""
Seed global random number generator.
Parameters:
- seed: int, array-like, or None, random seed
"""
def get_random_state():
"""
Get global random state.
Returns:
cupy.random.RandomState: Global random state
"""
def set_random_state(state):
"""
Set global random state.
Parameters:
- state: cupy.random.RandomState, random state to set
"""import cupy as cp
# Simple random arrays
random_floats = cp.random.random((1000, 1000))
random_ints = cp.random.randint(0, 100, size=(500, 500))
normal_data = cp.random.randn(10000)
# Seeded generation for reproducibility
cp.random.seed(42)
reproducible_data = cp.random.random(1000)
cp.random.seed(42) # Same seed
same_data = cp.random.random(1000)
print(cp.allclose(reproducible_data, same_data)) # True# Create generator with specific seed
rng = cp.random.default_rng(seed=12345)
# Generate various distributions
uniform_samples = rng.uniform(-1, 1, size=10000)
normal_samples = rng.normal(0, 1, size=10000)
integer_samples = rng.integers(1, 7, size=1000) # Dice rolls
# Advanced distributions
gamma_samples = rng.gamma(2.0, 1.0, size=5000)
beta_samples = rng.beta(2.0, 5.0, size=5000)
# Multiple generators with different seeds
rng1 = cp.random.default_rng(1234)
rng2 = cp.random.default_rng(5678)
data1 = rng1.normal(size=1000)
data2 = rng2.normal(size=1000)
print(f"Correlation: {cp.corrcoef(data1, data2)[0, 1]}") # Should be low# Sample from predefined array
population = cp.arange(1000)
sample = cp.random.choice(population, size=100, replace=False)
# Weighted sampling
weights = cp.exp(-cp.arange(100) / 10) # Exponential weights
weighted_sample = cp.random.choice(100, size=50, p=weights/cp.sum(weights))
# Multivariate normal sampling
mean = cp.array([0, 0])
cov = cp.array([[1, 0.5], [0.5, 1]])
mv_samples = cp.random.multivariate_normal(mean, cov, size=1000)
# Bootstrap sampling
data = cp.random.exponential(2.0, size=1000)
bootstrap_samples = cp.random.choice(data, size=(1000, 1000), replace=True)
bootstrap_means = cp.mean(bootstrap_samples, axis=1)# Monte Carlo estimation of π
def estimate_pi(n_samples):
# 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 pi_estimate
pi_est = estimate_pi(1000000)
print(f"π estimate: {pi_est}")
print(f"Error: {abs(pi_est - cp.pi)}")
# Monte Carlo integration
def monte_carlo_integrate(func, a, b, n_samples):
# Sample uniform random points
x = cp.random.uniform(a, b, n_samples)
y = func(x)
# Estimate integral
integral = (b - a) * cp.mean(y)
return integral
# Integrate x^2 from 0 to 1 (analytical result: 1/3)
integral_est = monte_carlo_integrate(lambda x: x**2, 0, 1, 100000)
print(f"Integral estimate: {integral_est}")
print(f"Analytical result: {1/3}")# Generate correlated random variables
n = 10000
x = cp.random.normal(size=n)
noise = cp.random.normal(size=n) * 0.5
y = 2 * x + 1 + noise # y = 2x + 1 + noise
correlation = cp.corrcoef(x, y)[0, 1]
print(f"Correlation coefficient: {correlation}")
# Random walk simulation
steps = cp.random.choice([-1, 1], size=10000)
walk = cp.cumsum(steps)
final_position = walk[-1]
max_excursion = cp.max(cp.abs(walk))
print(f"Final position: {final_position}")
print(f"Maximum excursion: {max_excursion}")
# Rejection sampling example
def sample_truncated_normal(mean, std, lower, upper, size):
samples = []
while len(samples) < size:
candidates = cp.random.normal(mean, std, size * 2)
valid = candidates[(candidates >= lower) & (candidates <= upper)]
samples.append(valid[:min(len(valid), size - len(samples))])
return cp.concatenate(samples)[:size]
truncated_samples = sample_truncated_normal(0, 1, -2, 2, 1000)
print(f"Sample range: [{cp.min(truncated_samples)}, {cp.max(truncated_samples)}]")import time
# Compare GPU vs CPU random generation
size = (10000, 10000)
# GPU generation
start_time = time.time()
gpu_random = cp.random.random(size)
cp.cuda.Stream.null.synchronize() # Ensure completion
gpu_time = time.time() - start_time
# CPU generation (for comparison)
import numpy as np
start_time = time.time()
cpu_random = np.random.random(size)
cpu_time = time.time() - start_time
print(f"GPU time: {gpu_time:.4f} seconds")
print(f"CPU time: {cpu_time:.4f} seconds")
print(f"Speedup: {cpu_time/gpu_time:.2f}x")Install with Tessl CLI
npx tessl i tessl/pypi-cupy-cuda101