CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pycuda

Python wrapper for Nvidia CUDA parallel computation API with object cleanup, automatic error checking, and convenient abstractions.

62

0.93x
Overview
Eval results
Files

random-numbers.mddocs/

Random Number Generation

GPU-accelerated random number generation with support for various distributions and reproducible seeding for scientific computing applications. PyCUDA provides high-performance random number generators optimized for parallel execution.

Capabilities

Basic Random Number Generation

Generate arrays of random numbers with various distributions.

def rand(shape: tuple, dtype: np.dtype = np.float32, stream: Stream = None) -> GPUArray:
    """
    Generate array of uniformly distributed random numbers in [0, 1).
    
    Parameters:
    - shape: tuple, output array shape
    - dtype: numpy.dtype, output data type (float32 or float64)
    - stream: Stream, CUDA stream (optional)
    
    Returns:
    GPUArray: array of random numbers in [0, 1)
    """

def uniform(low: float = 0.0, high: float = 1.0, size: tuple = None, 
           dtype: np.dtype = np.float32, stream: Stream = None) -> GPUArray:
    """
    Generate uniformly distributed random numbers in [low, high).
    
    Parameters:
    - low: float, lower bound (inclusive)
    - high: float, upper bound (exclusive)
    - size: tuple, output array shape
    - dtype: numpy.dtype, output data type
    - stream: Stream, CUDA stream (optional)
    
    Returns:
    GPUArray: uniformly distributed random numbers
    """

def randint(low: int, high: int = None, size: tuple = None, 
           dtype: np.dtype = np.int32, stream: Stream = None) -> GPUArray:
    """
    Generate random integers in [low, high).
    
    Parameters:
    - low: int, lower bound (inclusive) or upper bound if high=None
    - high: int, upper bound (exclusive)
    - size: tuple, output array shape
    - dtype: numpy.dtype, integer data type
    - stream: Stream, CUDA stream (optional)
    
    Returns:
    GPUArray: random integers in specified range
    """

Gaussian (Normal) Distribution

Generate normally distributed random numbers with specified mean and standard deviation.

def normal(loc: float = 0.0, scale: float = 1.0, size: tuple = None,
          dtype: np.dtype = np.float32, stream: Stream = None) -> GPUArray:
    """
    Generate normally distributed random numbers.
    
    Parameters:
    - loc: float, mean of distribution
    - scale: float, standard deviation of distribution
    - size: tuple, output array shape
    - dtype: numpy.dtype, output data type
    - stream: Stream, CUDA stream (optional)
    
    Returns:
    GPUArray: normally distributed random numbers
    """

def randn(shape: tuple, dtype: np.dtype = np.float32, stream: Stream = None) -> GPUArray:
    """
    Generate standard normal random numbers (mean=0, std=1).
    
    Parameters:
    - shape: tuple, output array shape
    - dtype: numpy.dtype, output data type
    - stream: Stream, CUDA stream (optional)
    
    Returns:
    GPUArray: standard normal random numbers
    """

def standard_normal(size: tuple = None, dtype: np.dtype = np.float32, 
                   stream: Stream = None) -> GPUArray:
    """Generate standard normal random numbers (alias for randn)."""

Exponential and Related Distributions

Generate random numbers from exponential and related probability distributions.

def exponential(scale: float = 1.0, size: tuple = None, 
               dtype: np.dtype = np.float32, stream: Stream = None) -> GPUArray:
    """
    Generate exponentially distributed random numbers.
    
    Parameters:
    - scale: float, scale parameter (1/rate)
    - size: tuple, output array shape
    - dtype: numpy.dtype, output data type  
    - stream: Stream, CUDA stream (optional)
    
    Returns:
    GPUArray: exponentially distributed random numbers
    """

def gamma(shape_param: float, scale: float = 1.0, size: tuple = None,
         dtype: np.dtype = np.float32, stream: Stream = None) -> GPUArray:
    """
    Generate gamma distributed random numbers.
    
    Parameters:
    - shape_param: float, shape parameter (alpha)
    - scale: float, scale parameter (beta)
    - size: tuple, output array shape
    - dtype: numpy.dtype, output data type
    - stream: Stream, CUDA stream (optional)
    
    Returns:
    GPUArray: gamma distributed random numbers
    """

def weibull(shape_param: float, scale: float = 1.0, size: tuple = None,
           dtype: np.dtype = np.float32, stream: Stream = None) -> GPUArray:
    """
    Generate Weibull distributed random numbers.
    
    Parameters:
    - shape_param: float, shape parameter
    - scale: float, scale parameter
    - size: tuple, output array shape
    - dtype: numpy.dtype, output data type
    - stream: Stream, CUDA stream (optional)
    
    Returns:
    GPUArray: Weibull distributed random numbers
    """

Discrete Distributions

Generate random numbers from discrete probability distributions.

def poisson(lam: float, size: tuple = None, stream: Stream = None) -> GPUArray:
    """
    Generate Poisson distributed random integers.
    
    Parameters:
    - lam: float, expected number of events (lambda parameter)
    - size: tuple, output array shape
    - stream: Stream, CUDA stream (optional)
    
    Returns:
    GPUArray: Poisson distributed random integers
    """

def binomial(n: int, p: float, size: tuple = None, stream: Stream = None) -> GPUArray:
    """
    Generate binomial distributed random integers.
    
    Parameters:
    - n: int, number of trials
    - p: float, probability of success per trial
    - size: tuple, output array shape
    - stream: Stream, CUDA stream (optional)
    
    Returns:
    GPUArray: binomial distributed random integers
    """

def geometric(p: float, size: tuple = None, stream: Stream = None) -> GPUArray:
    """
    Generate geometric distributed random integers.
    
    Parameters:
    - p: float, probability of success
    - size: tuple, output array shape
    - stream: Stream, CUDA stream (optional)
    
    Returns:
    GPUArray: geometric distributed random integers
    """

Seeding and Reproducibility

Control random number generation for reproducible results.

def seed(seed_value: int = None) -> None:
    """
    Seed the random number generator.
    
    Parameters:
    - seed_value: int, seed value (uses current time if None)
    """

def get_state() -> dict:
    """
    Get current random number generator state.
    
    Returns:
    dict: current generator state
    """

def set_state(state: dict) -> None:
    """
    Set random number generator state.
    
    Parameters:
    - state: dict, generator state from get_state()
    """

def seed_getter_uniform(n: int) -> np.ndarray:
    """
    Generate n uniform random seeds.
    
    Parameters:
    - n: int, number of seeds to generate
    
    Returns:
    numpy.ndarray: array of random seeds
    """

def seed_getter_unique(n: int) -> np.ndarray:
    """
    Generate n unique random seeds.
    
    Parameters:
    - n: int, number of unique seeds to generate
    
    Returns:
    numpy.ndarray: array of unique random seeds
    """

Advanced Random Number Generators

Low-level access to specific random number generator algorithms.

class XORShiftGenerator:
    """XORShift random number generator for GPU."""
    
    def __init__(self, seed: int = None):
        """
        Initialize XORShift generator.
        
        Parameters:
        - seed: int, generator seed
        """
    
    def uniform(self, shape: tuple, dtype: np.dtype = np.float32) -> GPUArray:
        """Generate uniform random numbers."""
    
    def normal(self, shape: tuple, dtype: np.dtype = np.float32) -> GPUArray:
        """Generate normal random numbers."""

class MersenneTwisterGenerator:
    """Mersenne Twister random number generator for GPU."""
    
    def __init__(self, seed: int = None):
        """
        Initialize Mersenne Twister generator.
        
        Parameters:
        - seed: int, generator seed
        """
    
    def uniform(self, shape: tuple, dtype: np.dtype = np.float32) -> GPUArray:
        """Generate uniform random numbers."""
    
    def normal(self, shape: tuple, dtype: np.dtype = np.float32) -> GPUArray:
        """Generate normal random numbers."""

class SobolGenerator:
    """Sobol quasi-random sequence generator for GPU."""
    
    def __init__(self, dimensions: int, direction_vectors: np.ndarray = None):
        """
        Initialize Sobol generator.
        
        Parameters:
        - dimensions: int, number of dimensions
        - direction_vectors: numpy.ndarray, custom direction vectors (optional)
        """
    
    def uniform(self, n_points: int) -> GPUArray:
        """
        Generate n_points from Sobol sequence.
        
        Parameters:
        - n_points: int, number of points to generate
        
        Returns:
        GPUArray: quasi-random points in [0,1)^dimensions
        """

Random Array Operations

Operations for working with existing random arrays.

def shuffle(array: GPUArray, stream: Stream = None) -> None:
    """
    Shuffle array elements in-place.
    
    Parameters:
    - array: GPUArray, array to shuffle
    - stream: Stream, CUDA stream (optional)
    """

def permutation(n: int, stream: Stream = None) -> GPUArray:
    """
    Generate random permutation of integers 0 to n-1.
    
    Parameters:
    - n: int, upper bound (exclusive)
    - stream: Stream, CUDA stream (optional)
    
    Returns:
    GPUArray: random permutation array
    """

def choice(array: GPUArray, size: int = None, replace: bool = True, 
          p: GPUArray = None, stream: Stream = None) -> GPUArray:
    """
    Generate random sample from array.
    
    Parameters:
    - array: GPUArray, source array
    - size: int, number of samples (defaults to array size)
    - replace: bool, sampling with replacement
    - p: GPUArray, sampling probabilities (optional)
    - stream: Stream, CUDA stream (optional)
    
    Returns:
    GPUArray: random sample from input array
    """

Usage Examples

Basic Random Number Generation

import pycuda.curandom as curandom
import pycuda.gpuarray as gpuarray
import numpy as np

# Generate uniform random numbers
uniform_data = curandom.rand((1000, 1000), dtype=np.float32)

# Generate normal random numbers
normal_data = curandom.randn((1000, 1000), dtype=np.float32)

# Generate random integers
random_ints = curandom.randint(0, 100, size=(500, 500))

Reproducible Random Numbers

# Set seed for reproducibility
curandom.seed(42)

# Generate reproducible random data
data1 = curandom.rand((100, 100))

# Reset to same seed
curandom.seed(42)

# Generate identical data
data2 = curandom.rand((100, 100))

# data1 and data2 are identical
assert np.allclose(data1.get(), data2.get())

Monte Carlo Simulation

# Monte Carlo estimate of pi
n_samples = 1000000

# Generate random points in unit square
x = curandom.uniform(-1.0, 1.0, size=(n_samples,))
y = curandom.uniform(-1.0, 1.0, size=(n_samples,))

# Check if points are inside unit circle
inside_circle = (x**2 + y**2) <= 1.0

# Estimate pi
pi_estimate = 4.0 * inside_circle.sum() / n_samples
print(f"Pi estimate: {pi_estimate.get()}")

Statistical Distributions

# Generate samples from various distributions
exponential_samples = curandom.exponential(scale=2.0, size=(1000,))
gamma_samples = curandom.gamma(shape_param=2.0, scale=1.5, size=(1000,))
poisson_samples = curandom.poisson(lam=3.0, size=(1000,))

# Generate correlated normal variables
n = 1000
rho = 0.7  # correlation coefficient

z1 = curandom.randn((n,))
z2 = curandom.randn((n,))

# Create correlated variables
x = z1
y = rho * z1 + np.sqrt(1 - rho**2) * z2

Custom Random Number Generators

# Use specific generator algorithm
mt_gen = curandom.MersenneTwisterGenerator(seed=123)
mt_data = mt_gen.uniform((1000, 1000))

# Quasi-random numbers for Monte Carlo
sobol_gen = curandom.SobolGenerator(dimensions=2)
sobol_points = sobol_gen.uniform(n_points=10000)  # Shape: (10000, 2)

Install with Tessl CLI

npx tessl i tessl/pypi-pycuda

docs

algorithm-kernels.md

driver-api.md

gpu-arrays.md

index.md

kernel-compilation.md

math-functions.md

opengl-integration.md

random-numbers.md

tile.json