CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-cupy-cuda112

NumPy & SciPy-compatible GPU-accelerated computing library for CUDA 11.2 environments

Pending
Overview
Eval results
Files

random-generation.mddocs/

Random Number Generation

GPU-accelerated random number generation supporting multiple bit generators, probability distributions, and statistical sampling operations for simulation, machine learning, and scientific computing.

Capabilities

Random Number Generators

Core random number generation interfaces and bit generators.

class random.Generator:
    """
    Container for bit generators and methods for random number generation.
    
    Parameters:
    - bit_generator: BitGenerator, source of randomness
    """
    def __init__(self, bit_generator): ...
    def random(self, size=None, dtype=cp.float64, out=None): ...
    def integers(self, low, high=None, size=None, dtype=cp.int64, endpoint=False): ...
    def choice(self, a, size=None, replace=True, p=None, axis=0): ...
    def shuffle(self, x, axis=0): ...
    def permutation(self, x, axis=0): ...
    def beta(self, a, b, size=None, dtype=cp.float64): ...
    def binomial(self, n, p, size=None, dtype=cp.int64): ...
    def chisquare(self, df, size=None, dtype=cp.float64): ...
    def exponential(self, scale=1.0, size=None, dtype=cp.float64): ...
    def gamma(self, shape, scale=1.0, size=None, dtype=cp.float64): ...
    def geometric(self, p, size=None, dtype=cp.int64): ...
    def gumbel(self, loc=0.0, scale=1.0, size=None, dtype=cp.float64): ...
    def laplace(self, loc=0.0, scale=1.0, size=None, dtype=cp.float64): ...
    def logistic(self, loc=0.0, scale=1.0, size=None, dtype=cp.float64): ...
    def lognormal(self, mean=0.0, sigma=1.0, size=None, dtype=cp.float64): ...
    def normal(self, loc=0.0, scale=1.0, size=None, dtype=cp.float64): ...
    def pareto(self, a, size=None, dtype=cp.float64): ...
    def poisson(self, lam=1.0, size=None, dtype=cp.int64): ...
    def rayleigh(self, scale=1.0, size=None, dtype=cp.float64): ...
    def standard_cauchy(self, size=None, dtype=cp.float64): ...
    def standard_exponential(self, size=None, dtype=cp.float64): ...
    def standard_gamma(self, shape, size=None, dtype=cp.float64): ...
    def standard_normal(self, size=None, dtype=cp.float64): ...
    def standard_t(self, df, size=None, dtype=cp.float64): ...
    def triangular(self, left, mode, right, size=None, dtype=cp.float64): ...
    def uniform(self, low=0.0, high=1.0, size=None, dtype=cp.float64): ...
    def vonmises(self, mu, kappa, size=None, dtype=cp.float64): ...
    def wald(self, mean, scale, size=None, dtype=cp.float64): ...
    def weibull(self, a, size=None, dtype=cp.float64): ...

def random.default_rng(seed=None):
    """
    Construct Generator with default BitGenerator (XORWOW).
    
    Parameters:
    - seed: int, array-like, SeedSequence, BitGenerator, or Generator
    
    Returns:
    Generator, initialized generator object
    """

class random.BitGenerator:
    """
    Base class for bit generators."""
    def __init__(self): ...
    @property
    def state(self): ...
    @state.setter
    def state(self, value): ...

class random.XORWOW(BitGenerator):
    """
    XORWOW bit generator (default).
    
    Parameters:
    - seed: int, array-like, or SeedSequence
    """
    def __init__(self, seed=None): ...

class random.MRG32k3a(BitGenerator):
    """
    MRG32k3a bit generator.
    
    Parameters:
    - seed: int, array-like, or SeedSequence
    """
    def __init__(self, seed=None): ...

class random.Philox4x3210(BitGenerator):
    """
    Philox 4x32-10 bit generator.
    
    Parameters:
    - seed: int, array-like, or SeedSequence
    """
    def __init__(self, seed=None): ...

Legacy Random Interface

Legacy NumPy-compatible random number interface.

class random.RandomState:
    """
    Legacy random number generator state.
    
    Parameters:
    - seed: int, array-like, or None
    """
    def __init__(self, seed=None): ...
    def seed(self, seed=None): ...
    def get_state(self): ...
    def set_state(self, state): ...
    def rand(self, *args): ...
    def randn(self, *args): ...
    def randint(self, low, high=None, size=None, dtype=int): ...
    def random_integers(self, low, high=None, size=None): ...
    def random_sample(self, size=None): ...
    def random(self, size=None): ...
    def ranf(self, size=None): ...
    def sample(self, size=None): ...
    def choice(self, a, size=None, replace=True, p=None): ...
    def shuffle(self, x): ...
    def permutation(self, x): ...
    def beta(self, a, b, size=None): ...
    def binomial(self, n, p, size=None): ...
    def chisquare(self, df, size=None): ...
    def dirichlet(self, alpha, size=None): ...
    def exponential(self, scale=1.0, size=None): ...
    def f(self, dfnum, dfden, size=None): ...
    def gamma(self, shape, scale=1.0, size=None): ...
    def geometric(self, p, size=None): ...
    def gumbel(self, loc=0.0, scale=1.0, size=None): ...
    def hypergeometric(self, ngood, nbad, nsample, size=None): ...
    def laplace(self, loc=0.0, scale=1.0, size=None): ...
    def logistic(self, loc=0.0, scale=1.0, size=None): ...
    def lognormal(self, mean=0.0, sigma=1.0, size=None): ...
    def logseries(self, p, size=None): ...
    def multinomial(self, n, pvals, size=None): ...
    def multivariate_normal(self, mean, cov, size=None): ...
    def negative_binomial(self, n, p, size=None): ...
    def noncentral_chisquare(self, df, nonc, size=None): ...
    def noncentral_f(self, dfnum, dfden, nonc, size=None): ...
    def normal(self, loc=0.0, scale=1.0, size=None): ...
    def pareto(self, a, size=None): ...
    def poisson(self, lam=1.0, size=None): ...
    def power(self, a, size=None): ...
    def rayleigh(self, scale=1.0, size=None): ...
    def standard_cauchy(self, size=None): ...
    def standard_exponential(self, size=None): ...
    def standard_gamma(self, shape, size=None): ...
    def standard_normal(self, size=None): ...
    def standard_t(self, df, size=None): ...
    def triangular(self, left, mode, right, size=None): ...
    def uniform(self, low=0.0, high=1.0, size=None): ...
    def vonmises(self, mu, kappa, size=None): ...
    def wald(self, mean, scale, size=None): ...
    def weibull(self, a, size=None): ...
    def zipf(self, a, size=None): ...

def random.seed(seed=None):
    """
    Seed global random number generator.
    
    Parameters:
    - seed: int, array-like, or None
    """

def random.get_random_state():
    """
    Get global RandomState instance.
    
    Returns:
    RandomState, global random state
    """

def random.set_random_state(state):
    """
    Set global random state.
    
    Parameters:
    - state: RandomState, random state to set
    """

def random.reset_states():
    """Reset all random number generator states."""

Simple Random Data

Convenience functions for basic random number generation.

def random.rand(*args):
    """
    Random values in [0, 1) with given shape.
    
    Parameters:
    - args: ints, shape dimensions
    
    Returns:
    cupy.ndarray, random values
    """

def random.randn(*args):
    """
    Standard normal random values with given shape.
    
    Parameters:
    - args: ints, shape dimensions
    
    Returns:
    cupy.ndarray, normally distributed values
    """

def random.randint(low, high=None, size=None, dtype=int):
    """
    Random integers from low (inclusive) to high (exclusive).
    
    Parameters:
    - low: int or array-like, lowest value
    - high: int or array-like, highest value  
    - size: int or tuple, output shape
    - dtype: data type
    
    Returns:
    cupy.ndarray, random integers
    """

def random.random_integers(low, high=None, size=None):
    """
    Random integers from low to high, inclusive (deprecated).
    
    Parameters:
    - low: int, lowest value
    - high: int, highest value
    - size: int or tuple, output shape
    
    Returns:
    cupy.ndarray, random integers
    """

def random.random_sample(size=None):
    """
    Random floats in [0.0, 1.0) with given shape.
    
    Parameters:
    - size: int or tuple, output shape
    
    Returns:
    cupy.ndarray, random values
    """

def random.random(size=None):
    """
    Alias for random_sample.
    
    Parameters:
    - size: int or tuple, output shape
    
    Returns:
    cupy.ndarray, random values
    """

def random.bytes(length):
    """
    Random bytes (CPU-based, wrapper for numpy.random.bytes).
    
    Parameters:
    - length: int, number of bytes
    
    Returns:
    bytes, random byte string
    """

Probability Distributions

Statistical probability distributions for sampling.

def random.beta(a, b, size=None):
    """
    Beta distribution samples.
    
    Parameters:
    - a: float or array-like, alpha parameter
    - b: float or array-like, beta parameter
    - size: int or tuple, output shape
    
    Returns:
    cupy.ndarray, beta distributed samples
    """

def random.binomial(n, p, size=None):
    """
    Binomial distribution samples.
    
    Parameters:
    - n: int or array-like, number of trials
    - p: float or array-like, success probability
    - size: int or tuple, output shape
    
    Returns:
    cupy.ndarray, binomial distributed samples
    """

def random.chisquare(df, size=None):
    """
    Chi-square distribution samples.
    
    Parameters:
    - df: float or array-like, degrees of freedom
    - size: int or tuple, output shape
    
    Returns:
    cupy.ndarray, chi-square distributed samples
    """

def random.exponential(scale=1.0, size=None):
    """
    Exponential distribution samples.
    
    Parameters:
    - scale: float or array-like, scale parameter
    - size: int or tuple, output shape
    
    Returns:
    cupy.ndarray, exponentially distributed samples
    """

def random.gamma(shape, scale=1.0, size=None):
    """
    Gamma distribution samples.
    
    Parameters:
    - shape: float or array-like, shape parameter
    - scale: float or array-like, scale parameter  
    - size: int or tuple, output shape
    
    Returns:
    cupy.ndarray, gamma distributed samples
    """

def random.normal(loc=0.0, scale=1.0, size=None):
    """
    Normal (Gaussian) distribution samples.
    
    Parameters:
    - loc: float or array-like, mean
    - scale: float or array-like, standard deviation
    - size: int or tuple, output shape
    
    Returns:
    cupy.ndarray, normally distributed samples
    """

def random.poisson(lam=1.0, size=None):
    """
    Poisson distribution samples.
    
    Parameters:
    - lam: float or array-like, rate parameter
    - size: int or tuple, output shape
    
    Returns:
    cupy.ndarray, Poisson distributed samples
    """

def random.uniform(low=0.0, high=1.0, size=None):
    """
    Uniform distribution samples.
    
    Parameters:
    - low: float or array-like, lower bound
    - high: float or array-like, upper bound
    - size: int or tuple, output shape
    
    Returns:
    cupy.ndarray, uniformly distributed samples
    """

def random.multivariate_normal(mean, cov, size=None):
    """
    Multivariate normal distribution samples.
    
    Parameters:
    - mean: array-like, mean vector
    - cov: array-like, covariance matrix
    - size: int or tuple, output shape
    
    Returns:
    cupy.ndarray, multivariate normal samples
    """

Permutations and Sampling

Functions for permutations, shuffling, and sampling.

def random.shuffle(x):
    """
    Modify sequence in-place by shuffling its contents.
    
    Parameters:
    - x: array-like, sequence to shuffle
    """

def random.permutation(x):
    """
    Randomly permute sequence or return permuted range.
    
    Parameters:
    - x: int or array-like, sequence to permute
    
    Returns:
    cupy.ndarray, permuted sequence
    """

def random.choice(a, size=None, replace=True, p=None):
    """
    Generate random sample from given 1-D array.
    
    Parameters:
    - a: int or array-like, source array
    - size: int or tuple, output shape
    - replace: bool, sample with replacement
    - p: array-like, probabilities for each element
    
    Returns:
    cupy.ndarray, sampled values
    """

def random.multinomial(n, pvals, size=None):
    """
    Multinomial distribution samples.
    
    Parameters:
    - n: int, number of trials
    - pvals: array-like, probabilities for each outcome
    - size: int or tuple, output shape
    
    Returns:
    cupy.ndarray, multinomial samples
    """

Usage Examples

Basic Random Number Generation

import cupy as cp

# Set seed for reproducibility
cp.random.seed(42)

# Basic random arrays
random_uniform = cp.random.rand(1000, 1000)
random_normal = cp.random.randn(1000, 1000)
random_integers = cp.random.randint(0, 100, size=(100, 100))

# Specific distributions
exponential_samples = cp.random.exponential(scale=2.0, size=10000)
gamma_samples = cp.random.gamma(shape=2.0, scale=1.0, size=10000)
normal_samples = cp.random.normal(loc=0.0, scale=1.0, size=10000)

Using the New Generator API

import cupy as cp

# Create generator with specific bit generator
rng = cp.random.default_rng(seed=12345)

# Generate random data
uniform_data = rng.random((1000, 1000))
integers = rng.integers(0, 100, size=1000)
normal_data = rng.normal(0, 1, size=(500, 500))

# Sample from discrete distribution
categories = rng.choice(['A', 'B', 'C', 'D'], size=1000, p=[0.1, 0.3, 0.4, 0.2])

# Different bit generators
xorwow_rng = cp.random.Generator(cp.random.XORWOW(seed=123))
philox_rng = cp.random.Generator(cp.random.Philox4x3210(seed=456))
mrg_rng = cp.random.Generator(cp.random.MRG32k3a(seed=789))

Statistical Sampling

import cupy as cp

# Monte Carlo simulation
n_samples = 1000000
rng = cp.random.default_rng(42)

# Simulate stock prices using geometric Brownian motion
dt = 1/252  # Daily time step
mu = 0.05   # Drift
sigma = 0.2 # Volatility
S0 = 100    # Initial price

# Generate random returns
random_returns = rng.normal(0, 1, size=n_samples)
price_changes = (mu - 0.5 * sigma**2) * dt + sigma * cp.sqrt(dt) * random_returns
final_prices = S0 * cp.exp(price_changes)

# Statistical analysis
mean_price = cp.mean(final_prices)
std_price = cp.std(final_prices)
percentiles = cp.percentile(final_prices, [5, 50, 95])

Permutations and Shuffling

import cupy as cp

# Create array to shuffle
data = cp.arange(100)

# In-place shuffle
cp.random.shuffle(data)

# Create permutation without modifying original
original = cp.arange(20)
permuted = cp.random.permutation(original)

# Random sampling
large_array = cp.arange(10000)
random_sample = cp.random.choice(large_array, size=100, replace=False)

# Weighted sampling
values = cp.array([1, 2, 3, 4, 5])
probabilities = cp.array([0.1, 0.2, 0.3, 0.25, 0.15])
weighted_sample = cp.random.choice(values, size=1000, p=probabilities)

Multivariate Distributions

import cupy as cp

# Multivariate normal distribution
mean_vector = cp.array([0, 0])
covariance_matrix = cp.array([[1, 0.5], [0.5, 1]])

# Generate correlated samples
mvn_samples = cp.random.multivariate_normal(
    mean_vector, covariance_matrix, size=1000
)

# Analyze correlation
correlation = cp.corrcoef(mvn_samples.T)
print("Sample correlation matrix:")
print(cp.asnumpy(correlation))

# Multinomial distribution
n_trials = 100
outcome_probs = cp.array([0.2, 0.3, 0.3, 0.2])
multinomial_samples = cp.random.multinomial(n_trials, outcome_probs, size=1000)

Performance Considerations

import cupy as cp
import time

# Compare different methods for large arrays
n = 10000000

# Method 1: Single large array generation
start = time.time()
large_array = cp.random.random(n)
time1 = time.time() - start

# Method 2: Multiple smaller arrays (less efficient)
start = time.time()
small_arrays = [cp.random.random(1000) for _ in range(n//1000)]
combined = cp.concatenate(small_arrays)
time2 = time.time() - start

print(f"Large array generation: {time1:.4f} seconds")
print(f"Small arrays generation: {time2:.4f} seconds")

# Use appropriate data types for memory efficiency
float32_array = cp.random.random(n, dtype=cp.float32)  # Half the memory
int16_array = cp.random.randint(0, 1000, size=n, dtype=cp.int16)  # Even less memory

Install with Tessl CLI

npx tessl i tessl/pypi-cupy-cuda112

docs

array-operations.md

cuda-interface.md

fft-operations.md

index.md

input-output.md

linear-algebra.md

math-operations.md

random-generation.md

scipy-extensions.md

tile.json