or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

algorithm-kernels.mddriver-api.mdgpu-arrays.mdindex.mdkernel-compilation.mdmath-functions.mdopengl-integration.mdrandom-numbers.md

random-numbers.mddocs/

0

# Random Number Generation

1

2

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.

3

4

## Capabilities

5

6

### Basic Random Number Generation

7

8

Generate arrays of random numbers with various distributions.

9

10

```python { .api }

11

def rand(shape: tuple, dtype: np.dtype = np.float32, stream: Stream = None) -> GPUArray:

12

"""

13

Generate array of uniformly distributed random numbers in [0, 1).

14

15

Parameters:

16

- shape: tuple, output array shape

17

- dtype: numpy.dtype, output data type (float32 or float64)

18

- stream: Stream, CUDA stream (optional)

19

20

Returns:

21

GPUArray: array of random numbers in [0, 1)

22

"""

23

24

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

25

dtype: np.dtype = np.float32, stream: Stream = None) -> GPUArray:

26

"""

27

Generate uniformly distributed random numbers in [low, high).

28

29

Parameters:

30

- low: float, lower bound (inclusive)

31

- high: float, upper bound (exclusive)

32

- size: tuple, output array shape

33

- dtype: numpy.dtype, output data type

34

- stream: Stream, CUDA stream (optional)

35

36

Returns:

37

GPUArray: uniformly distributed random numbers

38

"""

39

40

def randint(low: int, high: int = None, size: tuple = None,

41

dtype: np.dtype = np.int32, stream: Stream = None) -> GPUArray:

42

"""

43

Generate random integers in [low, high).

44

45

Parameters:

46

- low: int, lower bound (inclusive) or upper bound if high=None

47

- high: int, upper bound (exclusive)

48

- size: tuple, output array shape

49

- dtype: numpy.dtype, integer data type

50

- stream: Stream, CUDA stream (optional)

51

52

Returns:

53

GPUArray: random integers in specified range

54

"""

55

```

56

57

### Gaussian (Normal) Distribution

58

59

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

60

61

```python { .api }

62

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

63

dtype: np.dtype = np.float32, stream: Stream = None) -> GPUArray:

64

"""

65

Generate normally distributed random numbers.

66

67

Parameters:

68

- loc: float, mean of distribution

69

- scale: float, standard deviation of distribution

70

- size: tuple, output array shape

71

- dtype: numpy.dtype, output data type

72

- stream: Stream, CUDA stream (optional)

73

74

Returns:

75

GPUArray: normally distributed random numbers

76

"""

77

78

def randn(shape: tuple, dtype: np.dtype = np.float32, stream: Stream = None) -> GPUArray:

79

"""

80

Generate standard normal random numbers (mean=0, std=1).

81

82

Parameters:

83

- shape: tuple, output array shape

84

- dtype: numpy.dtype, output data type

85

- stream: Stream, CUDA stream (optional)

86

87

Returns:

88

GPUArray: standard normal random numbers

89

"""

90

91

def standard_normal(size: tuple = None, dtype: np.dtype = np.float32,

92

stream: Stream = None) -> GPUArray:

93

"""Generate standard normal random numbers (alias for randn)."""

94

```

95

96

### Exponential and Related Distributions

97

98

Generate random numbers from exponential and related probability distributions.

99

100

```python { .api }

101

def exponential(scale: float = 1.0, size: tuple = None,

102

dtype: np.dtype = np.float32, stream: Stream = None) -> GPUArray:

103

"""

104

Generate exponentially distributed random numbers.

105

106

Parameters:

107

- scale: float, scale parameter (1/rate)

108

- size: tuple, output array shape

109

- dtype: numpy.dtype, output data type

110

- stream: Stream, CUDA stream (optional)

111

112

Returns:

113

GPUArray: exponentially distributed random numbers

114

"""

115

116

def gamma(shape_param: float, scale: float = 1.0, size: tuple = None,

117

dtype: np.dtype = np.float32, stream: Stream = None) -> GPUArray:

118

"""

119

Generate gamma distributed random numbers.

120

121

Parameters:

122

- shape_param: float, shape parameter (alpha)

123

- scale: float, scale parameter (beta)

124

- size: tuple, output array shape

125

- dtype: numpy.dtype, output data type

126

- stream: Stream, CUDA stream (optional)

127

128

Returns:

129

GPUArray: gamma distributed random numbers

130

"""

131

132

def weibull(shape_param: float, scale: float = 1.0, size: tuple = None,

133

dtype: np.dtype = np.float32, stream: Stream = None) -> GPUArray:

134

"""

135

Generate Weibull distributed random numbers.

136

137

Parameters:

138

- shape_param: float, shape parameter

139

- scale: float, scale parameter

140

- size: tuple, output array shape

141

- dtype: numpy.dtype, output data type

142

- stream: Stream, CUDA stream (optional)

143

144

Returns:

145

GPUArray: Weibull distributed random numbers

146

"""

147

```

148

149

### Discrete Distributions

150

151

Generate random numbers from discrete probability distributions.

152

153

```python { .api }

154

def poisson(lam: float, size: tuple = None, stream: Stream = None) -> GPUArray:

155

"""

156

Generate Poisson distributed random integers.

157

158

Parameters:

159

- lam: float, expected number of events (lambda parameter)

160

- size: tuple, output array shape

161

- stream: Stream, CUDA stream (optional)

162

163

Returns:

164

GPUArray: Poisson distributed random integers

165

"""

166

167

def binomial(n: int, p: float, size: tuple = None, stream: Stream = None) -> GPUArray:

168

"""

169

Generate binomial distributed random integers.

170

171

Parameters:

172

- n: int, number of trials

173

- p: float, probability of success per trial

174

- size: tuple, output array shape

175

- stream: Stream, CUDA stream (optional)

176

177

Returns:

178

GPUArray: binomial distributed random integers

179

"""

180

181

def geometric(p: float, size: tuple = None, stream: Stream = None) -> GPUArray:

182

"""

183

Generate geometric distributed random integers.

184

185

Parameters:

186

- p: float, probability of success

187

- size: tuple, output array shape

188

- stream: Stream, CUDA stream (optional)

189

190

Returns:

191

GPUArray: geometric distributed random integers

192

"""

193

```

194

195

### Seeding and Reproducibility

196

197

Control random number generation for reproducible results.

198

199

```python { .api }

200

def seed(seed_value: int = None) -> None:

201

"""

202

Seed the random number generator.

203

204

Parameters:

205

- seed_value: int, seed value (uses current time if None)

206

"""

207

208

def get_state() -> dict:

209

"""

210

Get current random number generator state.

211

212

Returns:

213

dict: current generator state

214

"""

215

216

def set_state(state: dict) -> None:

217

"""

218

Set random number generator state.

219

220

Parameters:

221

- state: dict, generator state from get_state()

222

"""

223

224

def seed_getter_uniform(n: int) -> np.ndarray:

225

"""

226

Generate n uniform random seeds.

227

228

Parameters:

229

- n: int, number of seeds to generate

230

231

Returns:

232

numpy.ndarray: array of random seeds

233

"""

234

235

def seed_getter_unique(n: int) -> np.ndarray:

236

"""

237

Generate n unique random seeds.

238

239

Parameters:

240

- n: int, number of unique seeds to generate

241

242

Returns:

243

numpy.ndarray: array of unique random seeds

244

"""

245

```

246

247

### Advanced Random Number Generators

248

249

Low-level access to specific random number generator algorithms.

250

251

```python { .api }

252

class XORShiftGenerator:

253

"""XORShift random number generator for GPU."""

254

255

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

256

"""

257

Initialize XORShift generator.

258

259

Parameters:

260

- seed: int, generator seed

261

"""

262

263

def uniform(self, shape: tuple, dtype: np.dtype = np.float32) -> GPUArray:

264

"""Generate uniform random numbers."""

265

266

def normal(self, shape: tuple, dtype: np.dtype = np.float32) -> GPUArray:

267

"""Generate normal random numbers."""

268

269

class MersenneTwisterGenerator:

270

"""Mersenne Twister random number generator for GPU."""

271

272

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

273

"""

274

Initialize Mersenne Twister generator.

275

276

Parameters:

277

- seed: int, generator seed

278

"""

279

280

def uniform(self, shape: tuple, dtype: np.dtype = np.float32) -> GPUArray:

281

"""Generate uniform random numbers."""

282

283

def normal(self, shape: tuple, dtype: np.dtype = np.float32) -> GPUArray:

284

"""Generate normal random numbers."""

285

286

class SobolGenerator:

287

"""Sobol quasi-random sequence generator for GPU."""

288

289

def __init__(self, dimensions: int, direction_vectors: np.ndarray = None):

290

"""

291

Initialize Sobol generator.

292

293

Parameters:

294

- dimensions: int, number of dimensions

295

- direction_vectors: numpy.ndarray, custom direction vectors (optional)

296

"""

297

298

def uniform(self, n_points: int) -> GPUArray:

299

"""

300

Generate n_points from Sobol sequence.

301

302

Parameters:

303

- n_points: int, number of points to generate

304

305

Returns:

306

GPUArray: quasi-random points in [0,1)^dimensions

307

"""

308

```

309

310

### Random Array Operations

311

312

Operations for working with existing random arrays.

313

314

```python { .api }

315

def shuffle(array: GPUArray, stream: Stream = None) -> None:

316

"""

317

Shuffle array elements in-place.

318

319

Parameters:

320

- array: GPUArray, array to shuffle

321

- stream: Stream, CUDA stream (optional)

322

"""

323

324

def permutation(n: int, stream: Stream = None) -> GPUArray:

325

"""

326

Generate random permutation of integers 0 to n-1.

327

328

Parameters:

329

- n: int, upper bound (exclusive)

330

- stream: Stream, CUDA stream (optional)

331

332

Returns:

333

GPUArray: random permutation array

334

"""

335

336

def choice(array: GPUArray, size: int = None, replace: bool = True,

337

p: GPUArray = None, stream: Stream = None) -> GPUArray:

338

"""

339

Generate random sample from array.

340

341

Parameters:

342

- array: GPUArray, source array

343

- size: int, number of samples (defaults to array size)

344

- replace: bool, sampling with replacement

345

- p: GPUArray, sampling probabilities (optional)

346

- stream: Stream, CUDA stream (optional)

347

348

Returns:

349

GPUArray: random sample from input array

350

"""

351

```

352

353

## Usage Examples

354

355

### Basic Random Number Generation

356

357

```python

358

import pycuda.curandom as curandom

359

import pycuda.gpuarray as gpuarray

360

import numpy as np

361

362

# Generate uniform random numbers

363

uniform_data = curandom.rand((1000, 1000), dtype=np.float32)

364

365

# Generate normal random numbers

366

normal_data = curandom.randn((1000, 1000), dtype=np.float32)

367

368

# Generate random integers

369

random_ints = curandom.randint(0, 100, size=(500, 500))

370

```

371

372

### Reproducible Random Numbers

373

374

```python

375

# Set seed for reproducibility

376

curandom.seed(42)

377

378

# Generate reproducible random data

379

data1 = curandom.rand((100, 100))

380

381

# Reset to same seed

382

curandom.seed(42)

383

384

# Generate identical data

385

data2 = curandom.rand((100, 100))

386

387

# data1 and data2 are identical

388

assert np.allclose(data1.get(), data2.get())

389

```

390

391

### Monte Carlo Simulation

392

393

```python

394

# Monte Carlo estimate of pi

395

n_samples = 1000000

396

397

# Generate random points in unit square

398

x = curandom.uniform(-1.0, 1.0, size=(n_samples,))

399

y = curandom.uniform(-1.0, 1.0, size=(n_samples,))

400

401

# Check if points are inside unit circle

402

inside_circle = (x**2 + y**2) <= 1.0

403

404

# Estimate pi

405

pi_estimate = 4.0 * inside_circle.sum() / n_samples

406

print(f"Pi estimate: {pi_estimate.get()}")

407

```

408

409

### Statistical Distributions

410

411

```python

412

# Generate samples from various distributions

413

exponential_samples = curandom.exponential(scale=2.0, size=(1000,))

414

gamma_samples = curandom.gamma(shape_param=2.0, scale=1.5, size=(1000,))

415

poisson_samples = curandom.poisson(lam=3.0, size=(1000,))

416

417

# Generate correlated normal variables

418

n = 1000

419

rho = 0.7 # correlation coefficient

420

421

z1 = curandom.randn((n,))

422

z2 = curandom.randn((n,))

423

424

# Create correlated variables

425

x = z1

426

y = rho * z1 + np.sqrt(1 - rho**2) * z2

427

```

428

429

### Custom Random Number Generators

430

431

```python

432

# Use specific generator algorithm

433

mt_gen = curandom.MersenneTwisterGenerator(seed=123)

434

mt_data = mt_gen.uniform((1000, 1000))

435

436

# Quasi-random numbers for Monte Carlo

437

sobol_gen = curandom.SobolGenerator(dimensions=2)

438

sobol_points = sobol_gen.uniform(n_points=10000) # Shape: (10000, 2)

439

```