0
# Random Number Generation
1
2
GPU-accelerated random number generation supporting multiple probability distributions and random number generators. Provides both legacy RandomState interface and modern numpy-compatible Generator interface with high-performance GPU implementations.
3
4
## Capabilities
5
6
### Random Number Generators
7
8
Core random number generator classes and state management.
9
10
```python { .api }
11
class RandomState:
12
"""
13
Legacy random number generator for backward compatibility.
14
15
Parameters:
16
- seed: int or None, random seed
17
"""
18
def __init__(self, seed=None): ...
19
20
def seed(self, seed=None):
21
"""Initialize random number generator state."""
22
23
def get_state(self):
24
"""Return current random number generator state."""
25
26
def set_state(self, state):
27
"""Set random number generator state."""
28
29
class Generator:
30
"""
31
Modern random number generator with improved algorithms.
32
33
Parameters:
34
- bit_generator: BitGenerator instance
35
"""
36
def __init__(self, bit_generator): ...
37
38
class BitGenerator:
39
"""Base class for bit generators used by Generator."""
40
41
class XORWOW(BitGenerator):
42
"""XORWOW bit generator (CuPy default)."""
43
44
class MRG32k3a(BitGenerator):
45
"""MRG32k3a bit generator for high-quality randomness."""
46
47
class Philox4x3210(BitGenerator):
48
"""Philox 4x32x10 counter-based bit generator."""
49
50
def default_rng(seed=None):
51
"""
52
Create default random number generator.
53
54
Parameters:
55
- seed: int or None, random seed
56
57
Returns:
58
cupy.random.Generator: Random number generator instance
59
"""
60
61
def get_random_state():
62
"""Get global RandomState instance."""
63
64
def set_random_state(rs):
65
"""Set global RandomState instance."""
66
67
def seed(seed=None):
68
"""Set random seed for global RandomState."""
69
70
def reset_states():
71
"""Reset all random number generator states."""
72
```
73
74
### Simple Random Data
75
76
Basic random number generation functions.
77
78
```python { .api }
79
def random(size=None):
80
"""
81
Generate random floats in [0.0, 1.0).
82
83
Parameters:
84
- size: int or tuple, output shape
85
86
Returns:
87
cupy.ndarray: Random floats
88
"""
89
90
def rand(*args):
91
"""
92
Generate random floats in [0.0, 1.0) with given shape.
93
94
Parameters:
95
- args: ints, dimensions of output array
96
97
Returns:
98
cupy.ndarray: Random floats with shape args
99
"""
100
101
def randn(*args):
102
"""
103
Generate samples from standard normal distribution.
104
105
Parameters:
106
- args: ints, dimensions of output array
107
108
Returns:
109
cupy.ndarray: Standard normal random numbers
110
"""
111
112
def randint(low, high=None, size=None, dtype=int):
113
"""
114
Generate random integers from low (inclusive) to high (exclusive).
115
116
Parameters:
117
- low: int, lowest (signed) integer to draw, or highest if high=None
118
- high: int or None, highest (signed) integer to draw
119
- size: int or tuple, output shape
120
- dtype: data type, output data type
121
122
Returns:
123
cupy.ndarray: Random integers
124
"""
125
126
def random_sample(size=None):
127
"""Generate random floats in [0.0, 1.0) (alias for random)."""
128
129
def ranf(size=None):
130
"""Generate random floats in [0.0, 1.0) (alias for random)."""
131
132
def sample(size=None):
133
"""Generate random floats in [0.0, 1.0) (alias for random)."""
134
135
def choice(a, size=None, replace=True, p=None):
136
"""
137
Generate random sample from array.
138
139
Parameters:
140
- a: array-like or int, if int, equivalent to arange(a)
141
- size: int or tuple, output shape
142
- replace: bool, whether sampling is with replacement
143
- p: array-like, probabilities for each element (must sum to 1)
144
145
Returns:
146
cupy.ndarray: Random samples from a
147
"""
148
149
def bytes(length):
150
"""
151
Generate random bytes (NumPy wrapper).
152
153
Parameters:
154
- length: int, number of bytes
155
156
Returns:
157
bytes: Random byte string
158
"""
159
```
160
161
### Discrete Distributions
162
163
Random sampling from discrete probability distributions.
164
165
```python { .api }
166
def binomial(n, p, size=None):
167
"""
168
Draw samples from binomial distribution.
169
170
Parameters:
171
- n: int or array-like, number of trials
172
- p: float or array-like, probability of success in each trial
173
- size: int or tuple, output shape
174
175
Returns:
176
cupy.ndarray: Samples from binomial distribution
177
"""
178
179
def geometric(p, size=None):
180
"""
181
Draw samples from geometric distribution.
182
183
Parameters:
184
- p: float or array-like, probability of success
185
- size: int or tuple, output shape
186
187
Returns:
188
cupy.ndarray: Samples from geometric distribution
189
"""
190
191
def hypergeometric(ngood, nbad, nsample, size=None):
192
"""
193
Draw samples from hypergeometric distribution.
194
195
Parameters:
196
- ngood: int or array-like, number of good items
197
- nbad: int or array-like, number of bad items
198
- nsample: int or array-like, number of items sampled
199
- size: int or tuple, output shape
200
201
Returns:
202
cupy.ndarray: Samples from hypergeometric distribution
203
"""
204
205
def negative_binomial(n, p, size=None):
206
"""Draw samples from negative binomial distribution."""
207
208
def poisson(lam=1.0, size=None):
209
"""
210
Draw samples from Poisson distribution.
211
212
Parameters:
213
- lam: float or array-like, expected number of events
214
- size: int or tuple, output shape
215
216
Returns:
217
cupy.ndarray: Samples from Poisson distribution
218
"""
219
220
def power(a, size=None):
221
"""Draw samples from power distribution."""
222
223
def zipf(a, size=None):
224
"""Draw samples from Zipf distribution."""
225
226
def logseries(p, size=None):
227
"""Draw samples from logarithmic series distribution."""
228
229
def multinomial(n, pvals, size=None):
230
"""
231
Draw samples from multinomial distribution.
232
233
Parameters:
234
- n: int, number of trials
235
- pvals: sequence of floats, probabilities (must sum to 1)
236
- size: int or tuple, output shape
237
238
Returns:
239
cupy.ndarray: Samples from multinomial distribution
240
"""
241
```
242
243
### Continuous Distributions
244
245
Random sampling from continuous probability distributions.
246
247
```python { .api }
248
def normal(loc=0.0, scale=1.0, size=None):
249
"""
250
Draw samples from normal (Gaussian) distribution.
251
252
Parameters:
253
- loc: float or array-like, mean of distribution
254
- scale: float or array-like, standard deviation
255
- size: int or tuple, output shape
256
257
Returns:
258
cupy.ndarray: Samples from normal distribution
259
"""
260
261
def uniform(low=0.0, high=1.0, size=None):
262
"""
263
Draw samples from uniform distribution.
264
265
Parameters:
266
- low: float or array-like, lower boundary
267
- high: float or array-like, upper boundary
268
- size: int or tuple, output shape
269
270
Returns:
271
cupy.ndarray: Samples from uniform distribution
272
"""
273
274
def exponential(scale=1.0, size=None):
275
"""
276
Draw samples from exponential distribution.
277
278
Parameters:
279
- scale: float or array-like, scale parameter (1/rate)
280
- size: int or tuple, output shape
281
282
Returns:
283
cupy.ndarray: Samples from exponential distribution
284
"""
285
286
def gamma(shape, scale=1.0, size=None):
287
"""
288
Draw samples from gamma distribution.
289
290
Parameters:
291
- shape: float or array-like, shape parameter
292
- scale: float or array-like, scale parameter
293
- size: int or tuple, output shape
294
295
Returns:
296
cupy.ndarray: Samples from gamma distribution
297
"""
298
299
def beta(a, b, size=None):
300
"""
301
Draw samples from beta distribution.
302
303
Parameters:
304
- a: float or array-like, alpha parameter
305
- b: float or array-like, beta parameter
306
- size: int or tuple, output shape
307
308
Returns:
309
cupy.ndarray: Samples from beta distribution
310
"""
311
312
def chisquare(df, size=None):
313
"""Draw samples from chi-square distribution."""
314
315
def f(dfnum, dfden, size=None):
316
"""Draw samples from F distribution."""
317
318
def lognormal(mean=0.0, sigma=1.0, size=None):
319
"""Draw samples from log-normal distribution."""
320
321
def laplace(loc=0.0, scale=1.0, size=None):
322
"""Draw samples from Laplace distribution."""
323
324
def logistic(loc=0.0, scale=1.0, size=None):
325
"""Draw samples from logistic distribution."""
326
327
def pareto(a, size=None):
328
"""Draw samples from Pareto distribution."""
329
330
def rayleigh(scale=1.0, size=None):
331
"""Draw samples from Rayleigh distribution."""
332
333
def standard_cauchy(size=None):
334
"""Draw samples from standard Cauchy distribution."""
335
336
def standard_exponential(size=None):
337
"""Draw samples from standard exponential distribution."""
338
339
def standard_gamma(shape, size=None):
340
"""Draw samples from standard gamma distribution."""
341
342
def standard_normal(size=None):
343
"""Draw samples from standard normal distribution."""
344
345
def standard_t(df, size=None):
346
"""Draw samples from Student's t distribution."""
347
348
def triangular(left, mode, right, size=None):
349
"""
350
Draw samples from triangular distribution.
351
352
Parameters:
353
- left: float or array-like, lower limit
354
- mode: float or array-like, mode value
355
- right: float or array-like, upper limit
356
- size: int or tuple, output shape
357
358
Returns:
359
cupy.ndarray: Samples from triangular distribution
360
"""
361
362
def vonmises(mu, kappa, size=None):
363
"""Draw samples from von Mises distribution."""
364
365
def wald(mean, scale, size=None):
366
"""Draw samples from Wald (inverse Gaussian) distribution."""
367
368
def weibull(a, size=None):
369
"""Draw samples from Weibull distribution."""
370
371
def gumbel(loc=0.0, scale=1.0, size=None):
372
"""Draw samples from Gumbel distribution."""
373
374
def noncentral_chisquare(df, nonc, size=None):
375
"""Draw samples from noncentral chi-square distribution."""
376
377
def noncentral_f(dfnum, dfden, nonc, size=None):
378
"""Draw samples from noncentral F distribution."""
379
```
380
381
### Multivariate Distributions
382
383
Random sampling from multivariate probability distributions.
384
385
```python { .api }
386
def multivariate_normal(mean, cov, size=None, check_valid='warn', tol=1e-8):
387
"""
388
Draw samples from multivariate normal distribution.
389
390
Parameters:
391
- mean: array-like, mean of distribution (N,)
392
- cov: array-like, covariance matrix (N, N)
393
- size: int or tuple, output shape
394
- check_valid: {'warn', 'raise', 'ignore'}, behavior for invalid covariance
395
- tol: float, tolerance for checking covariance matrix
396
397
Returns:
398
cupy.ndarray: Samples from multivariate normal (..., N)
399
"""
400
401
def dirichlet(alpha, size=None):
402
"""
403
Draw samples from Dirichlet distribution.
404
405
Parameters:
406
- alpha: array-like, concentration parameters
407
- size: int or tuple, output shape
408
409
Returns:
410
cupy.ndarray: Samples from Dirichlet distribution
411
"""
412
```
413
414
### Permutations
415
416
Functions for shuffling and permuting arrays.
417
418
```python { .api }
419
def shuffle(x):
420
"""
421
Modify sequence by shuffling contents in-place.
422
423
Parameters:
424
- x: cupy.ndarray, array to shuffle along first axis
425
426
Returns:
427
None: Modifies x in-place
428
"""
429
430
def permutation(x):
431
"""
432
Return random permutation of sequence or range.
433
434
Parameters:
435
- x: int or array-like, if int, permutation of arange(x)
436
437
Returns:
438
cupy.ndarray: Permuted sequence
439
"""
440
```
441
442
## Usage Examples
443
444
### Basic Random Number Generation
445
446
```python
447
import cupy as cp
448
449
# Set random seed for reproducibility
450
cp.random.seed(42)
451
452
# Generate basic random arrays
453
random_floats = cp.random.random((1000, 1000))
454
random_ints = cp.random.randint(0, 100, size=(500, 500))
455
normal_data = cp.random.normal(0, 1, size=10000)
456
457
# Using the modern Generator interface
458
rng = cp.random.default_rng(seed=12345)
459
better_random = rng.random((100, 100))
460
```
461
462
### Statistical Distributions
463
464
```python
465
import cupy as cp
466
467
# Sample from various distributions
468
uniform_samples = cp.random.uniform(-1, 1, size=1000)
469
exponential_samples = cp.random.exponential(2.0, size=1000)
470
gamma_samples = cp.random.gamma(2.0, 2.0, size=1000)
471
472
# Discrete distributions
473
binomial_trials = cp.random.binomial(10, 0.3, size=1000)
474
poisson_events = cp.random.poisson(5.0, size=1000)
475
476
# Multivariate normal
477
mean = cp.array([0, 0])
478
cov = cp.array([[1, 0.5], [0.5, 1]])
479
mvn_samples = cp.random.multivariate_normal(mean, cov, size=500)
480
```
481
482
### Advanced Usage
483
484
```python
485
import cupy as cp
486
487
# Multiple random number generators
488
rng1 = cp.random.default_rng(seed=1)
489
rng2 = cp.random.default_rng(seed=2)
490
491
# Independent random streams
492
stream1_data = rng1.normal(0, 1, size=1000)
493
stream2_data = rng2.normal(0, 1, size=1000)
494
495
# Random choice with probabilities
496
categories = cp.array(['A', 'B', 'C', 'D'])
497
probabilities = cp.array([0.4, 0.3, 0.2, 0.1])
498
choices = cp.random.choice(4, size=1000, p=probabilities)
499
500
# Shuffling arrays
501
data = cp.arange(100)
502
cp.random.shuffle(data) # In-place shuffle
503
504
# Permutations
505
permuted = cp.random.permutation(100)
506
```
507
508
### Performance Considerations
509
510
```python
511
import cupy as cp
512
513
# Generate large arrays efficiently
514
large_random = cp.random.random((10000, 10000))
515
516
# Memory pool management with random generation
517
mempool = cp.get_default_memory_pool()
518
with mempool:
519
random_data = cp.random.normal(0, 1, size=(5000, 5000))
520
processed = cp.sin(random_data) + cp.cos(random_data)
521
```