or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

array-operations.mdcuda-interface.mdcustom-kernels.mdfft-operations.mdindex.mdlinear-algebra.mdmath-functions.mdrandom-numbers.mdstatistics-sorting.md

random-numbers.mddocs/

0

# Random Numbers

1

2

GPU-accelerated random number generation compatible with numpy.random. CuPy provides both legacy RandomState interface and modern Generator API with multiple bit generators optimized for GPU architectures.

3

4

## Capabilities

5

6

### Random Generator Management

7

8

```python { .api }

9

def seed(seed=None):

10

"""

11

Seed the global random number generator.

12

13

Parameters:

14

- seed: random seed value

15

16

Returns:

17

None

18

"""

19

20

def get_random_state():

21

"""Get current random state."""

22

23

def set_random_state(state):

24

"""Set random state."""

25

26

def reset_states():

27

"""Reset all random states."""

28

29

def default_rng(seed=None):

30

"""

31

Construct new Generator with default BitGenerator (XORWOW).

32

33

Parameters:

34

- seed: seed for initialization

35

36

Returns:

37

Generator: initialized generator object

38

"""

39

40

class RandomState:

41

"""

42

Random state container (legacy interface).

43

44

Parameters:

45

- seed: random seed value

46

"""

47

def __init__(self, seed=None): ...

48

```

49

50

### Modern Generator API

51

52

```python { .api }

53

class Generator:

54

"""

55

Modern random number generator.

56

57

Parameters:

58

- bit_generator: underlying bit generator

59

"""

60

def __init__(self, bit_generator): ...

61

62

class BitGenerator:

63

"""Base class for bit generators."""

64

65

class XORWOW:

66

"""

67

XORWOW bit generator (default).

68

69

Parameters:

70

- seed: seed value

71

"""

72

def __init__(self, seed=None): ...

73

74

class MRG32k3a:

75

"""

76

MRG32k3a bit generator.

77

78

Parameters:

79

- seed: seed value

80

"""

81

def __init__(self, seed=None): ...

82

83

class Philox4x3210:

84

"""

85

Philox4x32 bit generator.

86

87

Parameters:

88

- seed: seed value

89

"""

90

def __init__(self, seed=None): ...

91

```

92

93

### Basic Random Sampling

94

95

```python { .api }

96

def random_sample(size=None):

97

"""

98

Return random floats in [0.0, 1.0).

99

100

Parameters:

101

- size: output shape

102

103

Returns:

104

cupy.ndarray: random samples

105

"""

106

107

def random(size=None):

108

"""Alias for random_sample."""

109

110

def ranf(size=None):

111

"""Alias for random_sample."""

112

113

def sample(size=None):

114

"""Alias for random_sample."""

115

116

def rand(*dn):

117

"""

118

Random values from uniform distribution over [0, 1).

119

120

Parameters:

121

- dn: dimensions of returned array

122

123

Returns:

124

cupy.ndarray: random array

125

"""

126

127

def randn(*dn):

128

"""

129

Random values from standard normal distribution.

130

131

Parameters:

132

- dn: dimensions of returned array

133

134

Returns:

135

cupy.ndarray: random array from N(0,1)

136

"""

137

138

def randint(low, high=None, size=None, dtype=int):

139

"""

140

Return random integers from low (inclusive) to high (exclusive).

141

142

Parameters:

143

- low: lowest integer to draw

144

- high: highest integer to draw

145

- size: output shape

146

- dtype: data type

147

148

Returns:

149

cupy.ndarray: random integers

150

"""

151

152

def random_integers(low, high=None, size=None):

153

"""Random integers (deprecated, use randint)."""

154

155

def choice(a, size=None, replace=True, p=None):

156

"""

157

Generate random sample from given 1-D array.

158

159

Parameters:

160

- a: 1-D array-like or int

161

- size: output shape

162

- replace: whether sample with replacement

163

- p: probabilities associated with each entry

164

165

Returns:

166

cupy.ndarray: generated random samples

167

"""

168

169

def bytes(length):

170

"""

171

Return random bytes (CPU-based).

172

173

Parameters:

174

- length: number of random bytes

175

176

Returns:

177

bytes: random bytes

178

"""

179

```

180

181

### Continuous Distributions

182

183

```python { .api }

184

def normal(loc=0.0, scale=1.0, size=None):

185

"""

186

Draw samples from normal (Gaussian) distribution.

187

188

Parameters:

189

- loc: mean of distribution

190

- scale: standard deviation

191

- size: output shape

192

193

Returns:

194

cupy.ndarray: drawn samples

195

"""

196

197

def standard_normal(size=None):

198

"""Draw samples from standard normal distribution N(0,1)."""

199

200

def uniform(low=0.0, high=1.0, size=None):

201

"""Draw samples from uniform distribution."""

202

203

def exponential(scale=1.0, size=None):

204

"""Draw samples from exponential distribution."""

205

206

def gamma(shape, scale=1.0, size=None):

207

"""Draw samples from Gamma distribution."""

208

209

def standard_gamma(shape, size=None):

210

"""Draw samples from standard Gamma distribution."""

211

212

def beta(a, b, size=None):

213

"""Draw samples from Beta distribution."""

214

215

def chisquare(df, size=None):

216

"""Draw samples from chi-square distribution."""

217

218

def noncentral_chisquare(df, nonc, size=None):

219

"""Draw samples from noncentral chi-square distribution."""

220

221

def f(dfnum, dfden, size=None):

222

"""Draw samples from F distribution."""

223

224

def noncentral_f(dfnum, dfden, nonc, size=None):

225

"""Draw samples from noncentral F distribution."""

226

227

def standard_t(df, size=None):

228

"""Draw samples from standard Student's t distribution."""

229

230

def lognormal(mean=0.0, sigma=1.0, size=None):

231

"""Draw samples from log-normal distribution."""

232

233

def laplace(loc=0.0, scale=1.0, size=None):

234

"""Draw samples from Laplace distribution."""

235

236

def logistic(loc=0.0, scale=1.0, size=None):

237

"""Draw samples from logistic distribution."""

238

239

def gumbel(loc=0.0, scale=1.0, size=None):

240

"""Draw samples from Gumbel distribution."""

241

242

def standard_cauchy(size=None):

243

"""Draw samples from standard Cauchy distribution."""

244

245

def standard_exponential(size=None):

246

"""Draw samples from standard exponential distribution."""

247

248

def power(a, size=None):

249

"""Draw samples from power distribution."""

250

251

def pareto(a, size=None):

252

"""Draw samples from Pareto II distribution."""

253

254

def rayleigh(scale=1.0, size=None):

255

"""Draw samples from Rayleigh distribution."""

256

257

def triangular(left, mode, right, size=None):

258

"""Draw samples from triangular distribution."""

259

260

def vonmises(mu, kappa, size=None):

261

"""Draw samples from von Mises distribution."""

262

263

def wald(mean, scale, size=None):

264

"""Draw samples from Wald (inverse Gaussian) distribution."""

265

266

def weibull(a, size=None):

267

"""Draw samples from Weibull distribution."""

268

```

269

270

### Discrete Distributions

271

272

```python { .api }

273

def binomial(n, p, size=None):

274

"""

275

Draw samples from binomial distribution.

276

277

Parameters:

278

- n: number of trials

279

- p: probability of success

280

- size: output shape

281

282

Returns:

283

cupy.ndarray: drawn samples

284

"""

285

286

def negative_binomial(n, p, size=None):

287

"""Draw samples from negative binomial distribution."""

288

289

def poisson(lam=1.0, size=None):

290

"""Draw samples from Poisson distribution."""

291

292

def geometric(p, size=None):

293

"""Draw samples from geometric distribution."""

294

295

def hypergeometric(ngood, nbad, nsample, size=None):

296

"""Draw samples from hypergeometric distribution."""

297

298

def logseries(p, size=None):

299

"""Draw samples from logarithmic series distribution."""

300

301

def zipf(a, size=None):

302

"""Draw samples from Zipf distribution."""

303

```

304

305

### Multivariate Distributions

306

307

```python { .api }

308

def multivariate_normal(mean, cov, size=None, check_valid='warn', tol=1e-8):

309

"""

310

Draw samples from multivariate normal distribution.

311

312

Parameters:

313

- mean: mean of distribution

314

- cov: covariance matrix

315

- size: output shape

316

- check_valid: behavior when covariance is not valid

317

- tol: tolerance for checking covariance

318

319

Returns:

320

cupy.ndarray: drawn samples

321

"""

322

323

def multinomial(n, pvals, size=None):

324

"""

325

Draw samples from multinomial distribution.

326

327

Parameters:

328

- n: number of experiments

329

- pvals: probabilities of p different outcomes

330

- size: output shape

331

332

Returns:

333

cupy.ndarray: drawn samples

334

"""

335

336

def dirichlet(alpha, size=None):

337

"""

338

Draw samples from Dirichlet distribution.

339

340

Parameters:

341

- alpha: parameter of distribution

342

- size: output shape

343

344

Returns:

345

cupy.ndarray: drawn samples

346

"""

347

```

348

349

### Permutations

350

351

```python { .api }

352

def shuffle(x):

353

"""

354

Modify array in-place by shuffling its contents.

355

356

Parameters:

357

- x: array to shuffle

358

359

Returns:

360

None

361

"""

362

363

def permutation(x):

364

"""

365

Randomly permute sequence or return permuted range.

366

367

Parameters:

368

- x: array-like or int

369

370

Returns:

371

cupy.ndarray: permuted sequence

372

"""

373

```

374

375

## Usage Examples

376

377

### Basic Random Generation

378

379

```python

380

import cupy as cp

381

382

# Set seed for reproducibility

383

cp.random.seed(42)

384

385

# Generate random numbers

386

uniform_samples = cp.random.random((5, 5))

387

normal_samples = cp.random.randn(100)

388

integers = cp.random.randint(0, 10, size=(3, 3))

389

390

# Using convenience functions

391

zeros_to_ones = cp.random.rand(1000) # Uniform [0, 1)

392

standard_normal = cp.random.randn(1000) # N(0, 1)

393

```

394

395

### Modern Generator API

396

397

```python

398

import cupy as cp

399

400

# Create generator with specific bit generator

401

rng = cp.random.default_rng(42)

402

403

# Or with specific bit generator

404

bit_gen = cp.random.XORWOW(seed=42)

405

rng = cp.random.Generator(bit_gen)

406

407

# Generate random numbers

408

samples = rng.random((5, 5))

409

normal_samples = rng.normal(0, 1, size=100)

410

integers = rng.integers(0, 10, size=(3, 3))

411

```

412

413

### Statistical Distributions

414

415

```python

416

import cupy as cp

417

418

# Normal distribution

419

normal_data = cp.random.normal(loc=10, scale=2, size=1000)

420

421

# Exponential distribution

422

exp_data = cp.random.exponential(scale=1.5, size=1000)

423

424

# Gamma distribution

425

gamma_data = cp.random.gamma(shape=2, scale=1, size=1000)

426

427

# Beta distribution

428

beta_data = cp.random.beta(a=2, b=5, size=1000)

429

430

# Discrete distributions

431

binomial_data = cp.random.binomial(n=10, p=0.3, size=1000)

432

poisson_data = cp.random.poisson(lam=3, size=1000)

433

```

434

435

### Multivariate Distributions

436

437

```python

438

import cupy as cp

439

440

# Multivariate normal

441

mean = cp.array([0, 0])

442

cov = cp.array([[1, 0.5], [0.5, 1]])

443

mv_normal = cp.random.multivariate_normal(mean, cov, size=100)

444

445

# Multinomial

446

n_trials = 20

447

probabilities = cp.array([0.2, 0.3, 0.5])

448

multinomial_samples = cp.random.multinomial(n_trials, probabilities, size=50)

449

450

# Dirichlet

451

alpha = cp.array([1, 2, 3])

452

dirichlet_samples = cp.random.dirichlet(alpha, size=100)

453

```

454

455

### Random Sampling and Choice

456

457

```python

458

import cupy as cp

459

460

# Random choice from array

461

data = cp.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

462

random_choices = cp.random.choice(data, size=5, replace=False)

463

464

# Weighted choice

465

weights = cp.array([0.1, 0.1, 0.1, 0.2, 0.2, 0.1, 0.1, 0.05, 0.025, 0.025])

466

weighted_choices = cp.random.choice(data, size=100, p=weights)

467

468

# Random permutation

469

original = cp.arange(10)

470

permuted = cp.random.permutation(original)

471

472

# Shuffle in place

473

to_shuffle = cp.arange(10)

474

cp.random.shuffle(to_shuffle)

475

```

476

477

### Random State Management

478

479

```python

480

import cupy as cp

481

482

# Save and restore state

483

state = cp.random.get_random_state()

484

sample1 = cp.random.random(5)

485

486

# Generate more samples

487

sample2 = cp.random.random(5)

488

489

# Restore state and regenerate

490

cp.random.set_random_state(state)

491

sample1_again = cp.random.random(5) # Same as sample1

492

493

# Using RandomState object

494

rs = cp.random.RandomState(42)

495

controlled_sample = rs.random(10)

496

```

497

498

### Performance Considerations

499

500

```python

501

import cupy as cp

502

import time

503

504

# Large random generation

505

size = (10000, 10000)

506

507

# Time different distributions

508

start = time.time()

509

uniform_large = cp.random.random(size)

510

uniform_time = time.time() - start

511

512

start = time.time()

513

normal_large = cp.random.normal(0, 1, size)

514

normal_time = time.time() - start

515

516

print(f"Uniform generation: {uniform_time:.4f}s")

517

print(f"Normal generation: {normal_time:.4f}s")

518

519

# Memory usage

520

memory_pool = cp.get_default_memory_pool()

521

print(f"GPU memory used: {memory_pool.used_bytes() / 1024**3:.2f} GB")

522

```