0
# Random Number Generation
1
2
GPU-accelerated random number generation with comprehensive distribution support and modern generator APIs. CuPy provides both legacy and modern random number generation interfaces optimized for GPU execution, supporting all major statistical distributions and advanced generator management.
3
4
## Capabilities
5
6
### Generator Management
7
8
Modern generator API with pluggable bit generators and comprehensive state management for reproducible random number generation.
9
10
```python { .api }
11
def default_rng(seed=None):
12
"""
13
Construct new Generator with default BitGenerator (XORWOW).
14
15
Parameters:
16
- seed: None, int, array_like, SeedSequence, BitGenerator, or Generator
17
Seed for initializing the BitGenerator
18
19
Returns:
20
- Generator: Initialized generator object
21
"""
22
23
class Generator:
24
"""Modern random number generator with pluggable bit generators"""
25
def __init__(self, bit_generator): ...
26
def random(self, size=None, dtype=float32, out=None): ...
27
def integers(self, low, high=None, size=None, dtype=int64, endpoint=False): ...
28
def choice(self, a, size=None, replace=True, p=None, axis=0, shuffle=True): ...
29
30
class BitGenerator:
31
"""Base class for bit generators"""
32
def random_raw(self, size=None, output=True): ...
33
34
class XORWOW(BitGenerator):
35
"""XORWOW bit generator (CuPy default)"""
36
def __init__(self, seed=None): ...
37
38
class MRG32k3a(BitGenerator):
39
"""MRG32k3a bit generator for high-quality random numbers"""
40
def __init__(self, seed=None): ...
41
42
class Philox4x3210(BitGenerator):
43
"""Philox4x32-10 bit generator for parallel applications"""
44
def __init__(self, seed=None): ...
45
```
46
47
### Legacy Random State API
48
49
Compatible with NumPy's legacy random API for existing code migration.
50
51
```python { .api }
52
class RandomState:
53
"""Legacy random number generator compatible with NumPy"""
54
def __init__(self, seed=None): ...
55
def seed(self, seed=None): ...
56
def get_state(self): ...
57
def set_state(self, state): ...
58
59
def get_random_state():
60
"""Get the global RandomState instance"""
61
62
def set_random_state(rs):
63
"""Set the global RandomState instance"""
64
65
def seed(seed=None):
66
"""Seed the global random number generator"""
67
68
def reset_states():
69
"""Reset all random number generator states"""
70
```
71
72
### Simple Random Data
73
74
Basic random data generation functions for common use cases.
75
76
```python { .api }
77
def rand(*args):
78
"""
79
Random values in a given shape from uniform distribution [0, 1).
80
81
Parameters:
82
- *args: int, shape dimensions
83
84
Returns:
85
- ndarray: Random samples from uniform distribution
86
"""
87
88
def randn(*args):
89
"""
90
Random samples from standard normal distribution.
91
92
Parameters:
93
- *args: int, shape dimensions
94
95
Returns:
96
- ndarray: Random samples from N(0, 1)
97
"""
98
99
def randint(low, high=None, size=None, dtype=int):
100
"""
101
Random integers from low (inclusive) to high (exclusive).
102
103
Parameters:
104
- low: int, lowest integer to draw
105
- high: int, optional, highest integer to draw (exclusive)
106
- size: int or tuple, output shape
107
- dtype: data type, optional
108
109
Returns:
110
- ndarray: Random integers
111
"""
112
113
def random_sample(size=None):
114
"""Random floats in [0.0, 1.0)"""
115
116
def choice(a, size=None, replace=True, p=None):
117
"""
118
Generate random sample from given 1D array.
119
120
Parameters:
121
- a: 1D array-like or int, if int, equivalent to cp.arange(a)
122
- size: int or tuple, output shape
123
- replace: bool, whether sampling is with replacement
124
- p: 1D array-like, probabilities for each entry
125
126
Returns:
127
- ndarray: Generated random samples
128
"""
129
```
130
131
### Continuous Distributions
132
133
Comprehensive support for continuous probability distributions commonly used in statistics and machine learning.
134
135
```python { .api }
136
def normal(loc=0.0, scale=1.0, size=None):
137
"""
138
Draw samples from normal (Gaussian) distribution.
139
140
Parameters:
141
- loc: float, mean of distribution
142
- scale: float, standard deviation
143
- size: int or tuple, output shape
144
145
Returns:
146
- ndarray: Drawn samples
147
"""
148
149
def uniform(low=0.0, high=1.0, size=None):
150
"""
151
Draw samples from uniform distribution.
152
153
Parameters:
154
- low: float, lower boundary
155
- high: float, upper boundary
156
- size: int or tuple, output shape
157
158
Returns:
159
- ndarray: Drawn samples
160
"""
161
162
def exponential(scale=1.0, size=None):
163
"""
164
Draw samples from exponential distribution.
165
166
Parameters:
167
- scale: float, scale parameter (1/rate)
168
- size: int or tuple, output shape
169
170
Returns:
171
- ndarray: Drawn samples
172
"""
173
174
def gamma(shape, scale=1.0, size=None):
175
"""
176
Draw samples from Gamma distribution.
177
178
Parameters:
179
- shape: float, shape parameter
180
- scale: float, scale parameter
181
- size: int or tuple, output shape
182
183
Returns:
184
- ndarray: Drawn samples
185
"""
186
187
def beta(a, b, size=None):
188
"""
189
Draw samples from Beta distribution.
190
191
Parameters:
192
- a: float, alpha parameter
193
- b: float, beta parameter
194
- size: int or tuple, output shape
195
196
Returns:
197
- ndarray: Drawn samples
198
"""
199
200
def chisquare(df, size=None):
201
"""Draw samples from chi-square distribution"""
202
203
def f(dfnum, dfden, size=None):
204
"""Draw samples from F distribution"""
205
206
def laplace(loc=0.0, scale=1.0, size=None):
207
"""Draw samples from Laplace distribution"""
208
209
def logistic(loc=0.0, scale=1.0, size=None):
210
"""Draw samples from logistic distribution"""
211
212
def lognormal(mean=0.0, sigma=1.0, size=None):
213
"""Draw samples from log-normal distribution"""
214
215
def pareto(a, size=None):
216
"""Draw samples from Pareto distribution"""
217
218
def power(a, size=None):
219
"""Draw samples from power distribution"""
220
221
def rayleigh(scale=1.0, size=None):
222
"""Draw samples from Rayleigh distribution"""
223
224
def standard_cauchy(size=None):
225
"""Draw samples from standard Cauchy distribution"""
226
227
def standard_exponential(size=None):
228
"""Draw samples from standard exponential distribution"""
229
230
def standard_gamma(shape, size=None):
231
"""Draw samples from standard gamma distribution"""
232
233
def standard_normal(size=None):
234
"""Draw samples from standard normal distribution"""
235
236
def standard_t(df, size=None):
237
"""Draw samples from standard Student's t distribution"""
238
239
def triangular(left, mode, right, size=None):
240
"""Draw samples from triangular distribution"""
241
242
def vonmises(mu, kappa, size=None):
243
"""Draw samples from von Mises distribution"""
244
245
def wald(mean, scale, size=None):
246
"""Draw samples from Wald distribution"""
247
248
def weibull(a, size=None):
249
"""Draw samples from Weibull distribution"""
250
```
251
252
### Discrete Distributions
253
254
Support for discrete probability distributions for counting and categorical data.
255
256
```python { .api }
257
def binomial(n, p, size=None):
258
"""
259
Draw samples from binomial distribution.
260
261
Parameters:
262
- n: int, number of trials
263
- p: float, probability of success
264
- size: int or tuple, output shape
265
266
Returns:
267
- ndarray: Drawn samples
268
"""
269
270
def poisson(lam=1.0, size=None):
271
"""
272
Draw samples from Poisson distribution.
273
274
Parameters:
275
- lam: float, expected number of events
276
- size: int or tuple, output shape
277
278
Returns:
279
- ndarray: Drawn samples
280
"""
281
282
def geometric(p, size=None):
283
"""Draw samples from geometric distribution"""
284
285
def hypergeometric(ngood, nbad, nsample, size=None):
286
"""Draw samples from hypergeometric distribution"""
287
288
def negative_binomial(n, p, size=None):
289
"""Draw samples from negative binomial distribution"""
290
291
def zipf(a, size=None):
292
"""Draw samples from Zipf distribution"""
293
294
def logseries(p, size=None):
295
"""Draw samples from logarithmic series distribution"""
296
297
def multinomial(n, pvals, size=None):
298
"""
299
Draw samples from multinomial distribution.
300
301
Parameters:
302
- n: int, number of trials
303
- pvals: sequence of floats, probabilities of each outcome
304
- size: int or tuple, output shape
305
306
Returns:
307
- ndarray: Drawn samples
308
"""
309
```
310
311
### Multivariate Distributions
312
313
Support for multivariate probability distributions for correlated random variables.
314
315
```python { .api }
316
def multivariate_normal(mean, cov, size=None, check_valid='warn', tol=1e-8):
317
"""
318
Draw samples from multivariate normal distribution.
319
320
Parameters:
321
- mean: 1D array-like, mean of distribution
322
- cov: 2D array-like, covariance matrix
323
- size: int or tuple, output shape
324
- check_valid: {'warn', 'raise', 'ignore'}, behavior on invalid covariance
325
- tol: float, tolerance for checking covariance validity
326
327
Returns:
328
- ndarray: Drawn samples with shape (..., len(mean))
329
"""
330
331
def dirichlet(alpha, size=None):
332
"""
333
Draw samples from Dirichlet distribution.
334
335
Parameters:
336
- alpha: sequence of floats, concentration parameters
337
- size: int or tuple, output shape
338
339
Returns:
340
- ndarray: Drawn samples
341
"""
342
```
343
344
### Advanced Statistical Distributions
345
346
Specialized distributions for advanced statistical modeling and scientific applications.
347
348
```python { .api }
349
def noncentral_chisquare(df, nonc, size=None):
350
"""Draw samples from noncentral chi-square distribution"""
351
352
def noncentral_f(dfnum, dfden, nonc, size=None):
353
"""Draw samples from noncentral F distribution"""
354
355
def gumbel(loc=0.0, scale=1.0, size=None):
356
"""Draw samples from Gumbel distribution"""
357
```
358
359
### Permutations and Shuffling
360
361
Functions for generating permutations and shuffling arrays for randomization tasks.
362
363
```python { .api }
364
def shuffle(x):
365
"""
366
Modify sequence in-place by shuffling its contents.
367
368
Parameters:
369
- x: array_like, sequence to shuffle
370
371
Notes:
372
- Modifies input array in-place
373
- Multi-dimensional arrays shuffled along first axis only
374
"""
375
376
def permutation(x):
377
"""
378
Randomly permute sequence or generate permuted range.
379
380
Parameters:
381
- x: int or array_like, if int, generates permutation of range(x)
382
383
Returns:
384
- ndarray: Permuted sequence
385
"""
386
```
387
388
### Usage Examples
389
390
#### Basic Random Data Generation
391
392
```python
393
import cupy as cp
394
395
# Set seed for reproducibility
396
cp.random.seed(42)
397
398
# Generate random arrays
399
random_uniform = cp.random.rand(1000, 1000)
400
random_normal = cp.random.randn(500, 500)
401
random_integers = cp.random.randint(0, 100, size=(100,))
402
403
# Generate from specific distributions
404
normal_data = cp.random.normal(loc=5.0, scale=2.0, size=(1000,))
405
exponential_data = cp.random.exponential(scale=2.0, size=(1000,))
406
```
407
408
#### Modern Generator API
409
410
```python
411
import cupy as cp
412
413
# Create generator with specific bit generator
414
rng = cp.random.default_rng(seed=42)
415
416
# Generate random data
417
data = rng.random((1000, 1000))
418
integers = rng.integers(0, 100, size=(100,))
419
choice_data = rng.choice([1, 2, 3, 4, 5], size=50, replace=True)
420
421
# Use different bit generators for different quality/performance trade-offs
422
fast_rng = cp.random.Generator(cp.random.XORWOW(42))
423
quality_rng = cp.random.Generator(cp.random.MRG32k3a(42))
424
parallel_rng = cp.random.Generator(cp.random.Philox4x3210(42))
425
```
426
427
#### Statistical Sampling
428
429
```python
430
import cupy as cp
431
432
# Sample from various distributions for statistical modeling
433
normal_samples = cp.random.normal(0, 1, 10000)
434
gamma_samples = cp.random.gamma(2.0, 2.0, 10000)
435
beta_samples = cp.random.beta(2, 5, 10000)
436
437
# Multivariate sampling
438
mean = cp.array([0, 0])
439
cov = cp.array([[1, 0.5], [0.5, 1]])
440
mvn_samples = cp.random.multivariate_normal(mean, cov, 1000)
441
442
# Discrete distributions for count data
443
poisson_samples = cp.random.poisson(3.0, 10000)
444
binomial_samples = cp.random.binomial(10, 0.3, 10000)
445
```
446
447
## Notes
448
449
- All random number generation occurs on GPU, providing significant performance improvements for large-scale random data generation
450
- CuPy's random number generators are independent of NumPy's generators, allowing separate reproducible streams
451
- For ROCm platforms, Generator API requires ROCm ≥ 4.3
452
- Bit generators provide different trade-offs between speed, quality, and parallel generation capabilities
453
- Legacy RandomState API provided for NumPy compatibility, but modern Generator API recommended for new code