trnrand 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
trnrand/__init__.py ADDED
@@ -0,0 +1,37 @@
1
+ """
2
+ trnrand — Random number generation for AWS Trainium via NKI.
3
+
4
+ Pseudo-random and quasi-random sequences for scientific computing.
5
+ Reproducible seeding, standard distributions, and low-discrepancy
6
+ sequences for quasi-Monte Carlo integration.
7
+ Part of the trnsci scientific computing suite.
8
+ """
9
+
10
+ __version__ = "0.1.0"
11
+
12
+ # Generator
13
+ from .generator import Generator, manual_seed, get_default_generator
14
+
15
+ # Distributions
16
+ from .distributions import (
17
+ uniform, normal, standard_normal, exponential,
18
+ bernoulli, randint, randperm, truncated_normal,
19
+ )
20
+
21
+ # Quasi-random sequences
22
+ from .quasi import sobol, halton, latin_hypercube
23
+
24
+ # Backend control
25
+ from .nki import HAS_NKI, set_backend, get_backend
26
+
27
+ __all__ = [
28
+ # Generator
29
+ "Generator", "manual_seed", "get_default_generator",
30
+ # Distributions
31
+ "uniform", "normal", "standard_normal", "exponential",
32
+ "bernoulli", "randint", "randperm", "truncated_normal",
33
+ # Quasi-random
34
+ "sobol", "halton", "latin_hypercube",
35
+ # Backend
36
+ "HAS_NKI", "set_backend", "get_backend",
37
+ ]
@@ -0,0 +1,135 @@
1
+ """
2
+ Random number distributions for Trainium.
3
+
4
+ Standard distributions with reproducible seeding via Generator.
5
+ All functions accept an optional Generator for deterministic streams.
6
+
7
+ For scientific computing:
8
+ - uniform/normal: Monte Carlo sampling, weight initialization
9
+ - exponential: Poisson process simulation, radioactive decay
10
+ - multinomial: importance sampling
11
+ - truncated_normal: bounded parameter initialization
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import math
17
+ import torch
18
+ from typing import Optional, Tuple, Union
19
+
20
+ from .generator import Generator, get_default_generator
21
+
22
+
23
+ def uniform(
24
+ *size: int,
25
+ low: float = 0.0,
26
+ high: float = 1.0,
27
+ dtype: torch.dtype = torch.float32,
28
+ generator: Optional[Generator] = None,
29
+ ) -> torch.Tensor:
30
+ """Uniform distribution on [low, high)."""
31
+ gen = (generator or get_default_generator()).torch_generator
32
+ return torch.empty(*size, dtype=dtype).uniform_(low, high, generator=gen)
33
+
34
+
35
+ def normal(
36
+ *size: int,
37
+ mean: float = 0.0,
38
+ std: float = 1.0,
39
+ dtype: torch.dtype = torch.float32,
40
+ generator: Optional[Generator] = None,
41
+ ) -> torch.Tensor:
42
+ """Normal (Gaussian) distribution."""
43
+ gen = (generator or get_default_generator()).torch_generator
44
+ return torch.empty(*size, dtype=dtype).normal_(mean, std, generator=gen)
45
+
46
+
47
+ def standard_normal(
48
+ *size: int,
49
+ dtype: torch.dtype = torch.float32,
50
+ generator: Optional[Generator] = None,
51
+ ) -> torch.Tensor:
52
+ """Standard normal N(0, 1)."""
53
+ return normal(*size, mean=0.0, std=1.0, dtype=dtype, generator=generator)
54
+
55
+
56
+ def exponential(
57
+ *size: int,
58
+ rate: float = 1.0,
59
+ dtype: torch.dtype = torch.float32,
60
+ generator: Optional[Generator] = None,
61
+ ) -> torch.Tensor:
62
+ """Exponential distribution with given rate (λ).
63
+
64
+ PDF: f(x) = λ exp(-λx)
65
+ Mean: 1/λ
66
+ """
67
+ gen = (generator or get_default_generator()).torch_generator
68
+ u = torch.empty(*size, dtype=dtype).uniform_(0, 1, generator=gen)
69
+ # Clamp to avoid log(0)
70
+ u = torch.clamp(u, min=1e-10)
71
+ return -torch.log(u) / rate
72
+
73
+
74
+ def bernoulli(
75
+ *size: int,
76
+ p: float = 0.5,
77
+ dtype: torch.dtype = torch.float32,
78
+ generator: Optional[Generator] = None,
79
+ ) -> torch.Tensor:
80
+ """Bernoulli distribution: 1 with probability p, 0 otherwise."""
81
+ gen = (generator or get_default_generator()).torch_generator
82
+ return torch.empty(*size, dtype=dtype).bernoulli_(p, generator=gen)
83
+
84
+
85
+ def randint(
86
+ *size: int,
87
+ low: int = 0,
88
+ high: int = 1,
89
+ dtype: torch.dtype = torch.long,
90
+ generator: Optional[Generator] = None,
91
+ ) -> torch.Tensor:
92
+ """Random integers from [low, high)."""
93
+ gen = (generator or get_default_generator()).torch_generator
94
+ return torch.randint(low, high, size, dtype=dtype, generator=gen)
95
+
96
+
97
+ def randperm(
98
+ n: int,
99
+ dtype: torch.dtype = torch.long,
100
+ generator: Optional[Generator] = None,
101
+ ) -> torch.Tensor:
102
+ """Random permutation of 0..n-1."""
103
+ gen = (generator or get_default_generator()).torch_generator
104
+ return torch.randperm(n, dtype=dtype, generator=gen)
105
+
106
+
107
+ def truncated_normal(
108
+ *size: int,
109
+ mean: float = 0.0,
110
+ std: float = 1.0,
111
+ low: float = -2.0,
112
+ high: float = 2.0,
113
+ dtype: torch.dtype = torch.float32,
114
+ generator: Optional[Generator] = None,
115
+ ) -> torch.Tensor:
116
+ """Truncated normal distribution clipped to [low, high] (in std units).
117
+
118
+ Uses rejection sampling. Useful for bounded weight initialization.
119
+ """
120
+ result = torch.empty(*size, dtype=dtype)
121
+ gen = (generator or get_default_generator()).torch_generator
122
+
123
+ # Rejection sampling
124
+ remaining = result.reshape(-1)
125
+ n_remaining = remaining.numel()
126
+ idx = 0
127
+ while idx < n_remaining:
128
+ batch_size = min(n_remaining - idx, n_remaining * 2)
129
+ samples = torch.empty(batch_size, dtype=dtype).normal_(mean, std, generator=gen)
130
+ valid = samples[(samples >= mean + low * std) & (samples <= mean + high * std)]
131
+ take = min(len(valid), n_remaining - idx)
132
+ remaining[idx:idx + take] = valid[:take]
133
+ idx += take
134
+
135
+ return result
trnrand/generator.py ADDED
@@ -0,0 +1,71 @@
1
+ """
2
+ Random number generator state management for Trainium.
3
+
4
+ Provides a Generator class that wraps torch.Generator for CPU/CUDA
5
+ and will wrap NKI-based on-device RNG for Trainium. Reproducible
6
+ seeding is critical for scientific computing — same seed, same stream,
7
+ regardless of backend.
8
+
9
+ The Philox counter-based RNG is the natural NKI target because it's
10
+ stateless (counter + key → output), embarrassingly parallel across
11
+ tiles, and used by both PyTorch and JAX as their default engine.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import torch
17
+ from typing import Optional
18
+
19
+
20
+ class Generator:
21
+ """Seeded random number generator with backend dispatch.
22
+
23
+ Wraps torch.Generator for CPU/CUDA. On NKI, would use a Philox
24
+ counter-based RNG running on the GpSimd engine.
25
+ """
26
+
27
+ def __init__(self, seed: Optional[int] = None, device: str = "cpu"):
28
+ self._device = device
29
+ self._torch_gen = torch.Generator(device=device)
30
+ if seed is not None:
31
+ self._torch_gen.manual_seed(seed)
32
+ self._seed = seed
33
+
34
+ @property
35
+ def seed(self) -> Optional[int]:
36
+ return self._seed
37
+
38
+ @property
39
+ def device(self) -> str:
40
+ return self._device
41
+
42
+ def manual_seed(self, seed: int) -> Generator:
43
+ self._seed = seed
44
+ self._torch_gen.manual_seed(seed)
45
+ return self
46
+
47
+ def get_state(self) -> torch.Tensor:
48
+ return self._torch_gen.get_state()
49
+
50
+ def set_state(self, state: torch.Tensor):
51
+ self._torch_gen.set_state(state)
52
+
53
+ @property
54
+ def torch_generator(self) -> torch.Generator:
55
+ """Access underlying torch.Generator for use with torch ops."""
56
+ return self._torch_gen
57
+
58
+
59
+ # Module-level default generator
60
+ _default_generator = Generator(seed=None)
61
+
62
+
63
+ def manual_seed(seed: int) -> Generator:
64
+ """Seed the default generator."""
65
+ global _default_generator
66
+ _default_generator = Generator(seed=seed)
67
+ return _default_generator
68
+
69
+
70
+ def get_default_generator() -> Generator:
71
+ return _default_generator
@@ -0,0 +1,5 @@
1
+ """NKI kernel dispatch for Trainium RNG acceleration."""
2
+
3
+ from .dispatch import HAS_NKI, set_backend, get_backend
4
+
5
+ __all__ = ["HAS_NKI", "set_backend", "get_backend"]
@@ -0,0 +1,224 @@
1
+ """
2
+ NKI dispatch for random number generation.
3
+
4
+ The Philox 4×32 counter-based RNG is the primary NKI target:
5
+ - Stateless: (counter, key) → deterministic output
6
+ - Parallel: each tile generates independently with disjoint counters
7
+ - Used by PyTorch (cuRAND) and JAX as default engine
8
+
9
+ On Trainium, Philox runs on the GpSimd engine (general-purpose SIMD)
10
+ since it's integer arithmetic, not matmul. The Tensor Engine isn't
11
+ useful here — RNG is compute-light, bandwidth-heavy.
12
+
13
+ For scientific workloads, on-device RNG avoids the host→device transfer
14
+ of random tensors, which can be significant for large Monte Carlo runs.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import math
20
+
21
+ import torch
22
+
23
+ try:
24
+ import neuronxcc.nki as nki
25
+ import neuronxcc.nki.language as nl
26
+ HAS_NKI = True
27
+ except ImportError:
28
+ HAS_NKI = False
29
+
30
+ TWO_PI = 2.0 * math.pi
31
+
32
+ _backend = "auto"
33
+
34
+
35
+ def set_backend(backend: str):
36
+ global _backend
37
+ assert backend in ("auto", "pytorch", "nki")
38
+ if backend == "nki" and not HAS_NKI:
39
+ raise RuntimeError("NKI backend requires neuronxcc")
40
+ _backend = backend
41
+
42
+
43
+ def get_backend() -> str:
44
+ return _backend
45
+
46
+
47
+ def _use_nki() -> bool:
48
+ if _backend == "nki":
49
+ return True
50
+ if _backend == "pytorch":
51
+ return False
52
+ return HAS_NKI
53
+
54
+
55
+ # Philox 4×32-10 constants (Salmon et al., SC'11; matches cuRAND, JAX).
56
+ PHILOX_M0 = 0xD2511F53
57
+ PHILOX_M1 = 0xCD9E8D57
58
+ PHILOX_W0 = 0x9E3779B9
59
+ PHILOX_W1 = 0xBB67AE85
60
+ PHILOX_ROUNDS = 10
61
+ UINT32_MASK = 0xFFFFFFFF
62
+
63
+
64
+ def philox4x32_reference(counter: torch.Tensor, key: torch.Tensor) -> torch.Tensor:
65
+ """CPU reference implementation of Philox 4×32-10.
66
+
67
+ Used as the conformance oracle for the NKI kernel.
68
+
69
+ Args:
70
+ counter: int64 tensor of shape (..., 4) — the 4 counter words per stream.
71
+ key: int64 tensor of shape (..., 2) — the 2 key words per stream.
72
+
73
+ Returns:
74
+ int64 tensor of shape (..., 4) holding the 4 output uint32 words
75
+ (stored in the low 32 bits of int64 for arithmetic safety).
76
+ """
77
+ assert counter.shape[-1] == 4 and key.shape[-1] == 2
78
+ c0 = counter[..., 0] & UINT32_MASK
79
+ c1 = counter[..., 1] & UINT32_MASK
80
+ c2 = counter[..., 2] & UINT32_MASK
81
+ c3 = counter[..., 3] & UINT32_MASK
82
+ k0 = key[..., 0] & UINT32_MASK
83
+ k1 = key[..., 1] & UINT32_MASK
84
+
85
+ for _ in range(PHILOX_ROUNDS):
86
+ prod0 = c0 * PHILOX_M0
87
+ prod1 = c2 * PHILOX_M1
88
+ hi0 = (prod0 >> 32) & UINT32_MASK
89
+ lo0 = prod0 & UINT32_MASK
90
+ hi1 = (prod1 >> 32) & UINT32_MASK
91
+ lo1 = prod1 & UINT32_MASK
92
+ c0, c1, c2, c3 = (
93
+ (hi1 ^ c1 ^ k0) & UINT32_MASK,
94
+ lo1 & UINT32_MASK,
95
+ (hi0 ^ c3 ^ k1) & UINT32_MASK,
96
+ lo0 & UINT32_MASK,
97
+ )
98
+ k0 = (k0 + PHILOX_W0) & UINT32_MASK
99
+ k1 = (k1 + PHILOX_W1) & UINT32_MASK
100
+
101
+ return torch.stack([c0, c1, c2, c3], dim=-1)
102
+
103
+
104
+ def box_muller_cpu(uniforms: torch.Tensor) -> torch.Tensor:
105
+ """Box-Muller transform: pairs of uniforms → standard-normal pairs.
106
+
107
+ Same algorithm as the Vector Engine kernel — kept on CPU so the
108
+ `normal_nki` path can be tested for distributional correctness without
109
+ Trainium hardware.
110
+
111
+ Args:
112
+ uniforms: even-length 1-D tensor of U(0, 1) samples.
113
+
114
+ Returns:
115
+ Tensor of the same shape, holding standard-normal samples.
116
+ """
117
+ assert uniforms.numel() % 2 == 0, "Box-Muller needs pairs"
118
+ u = uniforms.view(-1, 2)
119
+ # Clamp u1 away from 0 to avoid log(0) = -inf.
120
+ u1 = torch.clamp(u[:, 0], min=1e-10)
121
+ u2 = u[:, 1]
122
+ r = torch.sqrt(-2.0 * torch.log(u1))
123
+ theta = TWO_PI * u2
124
+ z = torch.stack([r * torch.cos(theta), r * torch.sin(theta)], dim=-1)
125
+ return z.reshape(uniforms.shape)
126
+
127
+
128
+ def philox_uniform_cpu(
129
+ n_elements: int,
130
+ seed: int,
131
+ counter_offset: int = 0,
132
+ dtype: torch.dtype = torch.float32,
133
+ ) -> torch.Tensor:
134
+ """CPU Philox uniform stream — used as fallback and as the oracle for tests.
135
+
136
+ Generates `n_elements` floats in [0, 1) by emitting `ceil(n/4)` Philox
137
+ blocks with sequential counters starting at `counter_offset`.
138
+ """
139
+ n_blocks = (n_elements + 3) // 4
140
+ counters = torch.zeros(n_blocks, 4, dtype=torch.int64)
141
+ counters[:, 0] = torch.arange(counter_offset, counter_offset + n_blocks, dtype=torch.int64)
142
+ key = torch.tensor([seed & UINT32_MASK, (seed >> 32) & UINT32_MASK], dtype=torch.int64)
143
+ key = key.expand(n_blocks, 2)
144
+ out_u32 = philox4x32_reference(counters, key).reshape(-1)[:n_elements]
145
+ # uint32 → float32 in [0, 1) via mantissa-only conversion (cuRAND convention).
146
+ return (out_u32.to(torch.float64) * (1.0 / 2**32)).to(dtype)
147
+
148
+
149
+ if HAS_NKI:
150
+
151
+ @nki.jit
152
+ def philox4x32_kernel(counter_lo_ref, key_lo_ref, key_hi_ref, out_ref):
153
+ """Philox 4×32-10 NKI kernel running on GpSimd.
154
+
155
+ Each lane processes one independent Philox stream:
156
+ - `counter_lo` (per-lane) is the 32-bit counter increment; the
157
+ remaining counter words start at zero. This is enough to give
158
+ each tile a disjoint 2^96-element stream.
159
+ - `key_lo`, `key_hi` are the two key words (broadcast across lanes).
160
+
161
+ Output: 4 uint32 words per lane, written contiguously to out_ref.
162
+
163
+ Status: scaffolded against the Philox 4×32-10 spec but not yet
164
+ validated on trn1/trn2. The CPU reference in `philox4x32_reference`
165
+ is the conformance oracle (see tests/test_nki_philox.py).
166
+ """
167
+ # Load one tile of counter_lo values (one per lane); other counter
168
+ # words start at 0 — they get written by the round function.
169
+ c0 = nl.load(counter_lo_ref)
170
+ c1 = nl.zeros_like(c0)
171
+ c2 = nl.zeros_like(c0)
172
+ c3 = nl.zeros_like(c0)
173
+ k0 = nl.load(key_lo_ref)
174
+ k1 = nl.load(key_hi_ref)
175
+
176
+ # 10 rounds of the Philox round function.
177
+ # NKI mul-hi-lo: result is i64; high 32 / low 32 isolated by shift+mask.
178
+ for _ in nl.static_range(PHILOX_ROUNDS):
179
+ prod0 = nl.multiply(c0, PHILOX_M0) # i64
180
+ prod1 = nl.multiply(c2, PHILOX_M1) # i64
181
+ hi0 = nl.bitwise_and(nl.right_shift(prod0, 32), UINT32_MASK)
182
+ lo0 = nl.bitwise_and(prod0, UINT32_MASK)
183
+ hi1 = nl.bitwise_and(nl.right_shift(prod1, 32), UINT32_MASK)
184
+ lo1 = nl.bitwise_and(prod1, UINT32_MASK)
185
+
186
+ new_c0 = nl.bitwise_xor(nl.bitwise_xor(hi1, c1), k0)
187
+ new_c1 = lo1
188
+ new_c2 = nl.bitwise_xor(nl.bitwise_xor(hi0, c3), k1)
189
+ new_c3 = lo0
190
+ c0, c1, c2, c3 = new_c0, new_c1, new_c2, new_c3
191
+
192
+ k0 = nl.bitwise_and(nl.add(k0, PHILOX_W0), UINT32_MASK)
193
+ k1 = nl.bitwise_and(nl.add(k1, PHILOX_W1), UINT32_MASK)
194
+
195
+ # Write 4 output words per lane interleaved.
196
+ nl.store(out_ref[0::4], c0)
197
+ nl.store(out_ref[1::4], c1)
198
+ nl.store(out_ref[2::4], c2)
199
+ nl.store(out_ref[3::4], c3)
200
+
201
+ @nki.jit
202
+ def box_muller_kernel(uniforms_ref, out_ref):
203
+ """Box-Muller transform on the Vector Engine: U(0,1) pairs → N(0,1) pairs.
204
+
205
+ Pairs of uniform inputs (u1, u2) → (z1, z2) with
206
+ r = sqrt(-2 ln u1), θ = 2π u2,
207
+ z1 = r cos θ, z2 = r sin θ.
208
+
209
+ Chosen over Marsaglia polar because the Vector Engine has hardware
210
+ cos/sin/log/sqrt; Marsaglia's rejection step kills SIMD throughput.
211
+
212
+ Status: scaffolded but awaits on-hardware validation per #2.
213
+ Iterate after #1 (Philox kernel) lands cleanly on trn1.
214
+ """
215
+ u1 = nl.load(uniforms_ref[0::2])
216
+ u2 = nl.load(uniforms_ref[1::2])
217
+ # Clamp u1 away from 0 to avoid log(0) = -inf.
218
+ u1_safe = nl.maximum(u1, 1e-10)
219
+ r = nl.sqrt(nl.multiply(nl.log(u1_safe), -2.0))
220
+ theta = nl.multiply(u2, TWO_PI)
221
+ z1 = nl.multiply(r, nl.cos(theta))
222
+ z2 = nl.multiply(r, nl.sin(theta))
223
+ nl.store(out_ref[0::2], z1)
224
+ nl.store(out_ref[1::2], z2)
trnrand/quasi.py ADDED
@@ -0,0 +1,115 @@
1
+ """
2
+ Quasi-random (low-discrepancy) sequences for Trainium.
3
+
4
+ Sobol and Halton sequences for quasi-Monte Carlo integration.
5
+ These provide better convergence than pseudo-random sampling for
6
+ high-dimensional integrals — O(1/N) vs O(1/√N).
7
+
8
+ Use cases:
9
+ - Numerical integration in quantum chemistry (electron integrals)
10
+ - Stochastic trace estimation (Hutchinson with QMC)
11
+ - Hyperparameter search (Sobol beats random for small budgets)
12
+ - Importance sampling with low-discrepancy proposals
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import math
18
+ import torch
19
+ from typing import Optional
20
+
21
+
22
+ def sobol(
23
+ n_points: int,
24
+ n_dims: int,
25
+ seed: Optional[int] = None,
26
+ scramble: bool = True,
27
+ dtype: torch.dtype = torch.float32,
28
+ ) -> torch.Tensor:
29
+ """Sobol quasi-random sequence.
30
+
31
+ Args:
32
+ n_points: Number of points to generate
33
+ n_dims: Dimensionality
34
+ seed: Random seed for scrambling
35
+ scramble: Apply Owen scrambling for better equidistribution
36
+
37
+ Returns:
38
+ Tensor of shape (n_points, n_dims) with values in [0, 1)
39
+ """
40
+ engine = torch.quasirandom.SobolEngine(
41
+ dimension=n_dims,
42
+ scramble=scramble,
43
+ seed=seed,
44
+ )
45
+ return engine.draw(n_points).to(dtype)
46
+
47
+
48
+ def halton(
49
+ n_points: int,
50
+ n_dims: int,
51
+ dtype: torch.dtype = torch.float32,
52
+ ) -> torch.Tensor:
53
+ """Halton quasi-random sequence.
54
+
55
+ Uses the first n_dims primes as bases.
56
+ Simpler than Sobol but degrades in high dimensions (>~20).
57
+
58
+ Args:
59
+ n_points: Number of points
60
+ n_dims: Dimensionality (recommend ≤ 20)
61
+
62
+ Returns:
63
+ Tensor of shape (n_points, n_dims) with values in (0, 1)
64
+ """
65
+ primes = _first_n_primes(n_dims)
66
+ result = torch.zeros(n_points, n_dims, dtype=dtype)
67
+ for d in range(n_dims):
68
+ result[:, d] = _halton_sequence(n_points, primes[d], dtype)
69
+ return result
70
+
71
+
72
+ def _halton_sequence(n: int, base: int, dtype: torch.dtype) -> torch.Tensor:
73
+ """Generate Halton sequence for a single base."""
74
+ result = torch.zeros(n, dtype=dtype)
75
+ for i in range(n):
76
+ f = 1.0
77
+ r = 0.0
78
+ idx = i + 1 # Skip 0
79
+ while idx > 0:
80
+ f /= base
81
+ r += f * (idx % base)
82
+ idx //= base
83
+ result[i] = r
84
+ return result
85
+
86
+
87
+ def _first_n_primes(n: int) -> list[int]:
88
+ """Return first n prime numbers."""
89
+ primes = []
90
+ candidate = 2
91
+ while len(primes) < n:
92
+ if all(candidate % p != 0 for p in primes):
93
+ primes.append(candidate)
94
+ candidate += 1
95
+ return primes
96
+
97
+
98
+ def latin_hypercube(
99
+ n_points: int,
100
+ n_dims: int,
101
+ dtype: torch.dtype = torch.float32,
102
+ generator: Optional[torch.Generator] = None,
103
+ ) -> torch.Tensor:
104
+ """Latin Hypercube Sampling.
105
+
106
+ Stratified sampling that ensures each row and column of the
107
+ hypercube contains exactly one sample. Better space-filling
108
+ than pure random for small sample sizes.
109
+ """
110
+ result = torch.zeros(n_points, n_dims, dtype=dtype)
111
+ for d in range(n_dims):
112
+ perm = torch.randperm(n_points, generator=generator)
113
+ u = torch.rand(n_points, generator=generator, dtype=dtype)
114
+ result[:, d] = (perm.to(dtype) + u) / n_points
115
+ return result
@@ -0,0 +1,122 @@
1
+ Metadata-Version: 2.4
2
+ Name: trnrand
3
+ Version: 0.1.0
4
+ Summary: Random number generation for AWS Trainium via NKI
5
+ Author-email: Scott Friedman <scttfrdmn@gmail.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/trnsci/trnrand
8
+ Project-URL: Documentation, https://trnsci.dev/trnrand/
9
+ Project-URL: Repository, https://github.com/trnsci/trnrand
10
+ Project-URL: Issues, https://github.com/trnsci/trnrand/issues
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Scientific/Engineering
15
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: torch>=2.1
20
+ Requires-Dist: numpy>=1.24
21
+ Provides-Extra: neuron
22
+ Requires-Dist: neuronxcc>=2.24; extra == "neuron"
23
+ Requires-Dist: torch-neuronx>=2.9; extra == "neuron"
24
+ Provides-Extra: dev
25
+ Requires-Dist: pytest>=7.0; extra == "dev"
26
+ Requires-Dist: pytest-benchmark>=4.0; extra == "dev"
27
+ Requires-Dist: scipy>=1.11; extra == "dev"
28
+ Requires-Dist: mkdocs>=1.5; extra == "dev"
29
+ Requires-Dist: mkdocs-material>=9.0; extra == "dev"
30
+ Dynamic: license-file
31
+
32
+ # trnrand
33
+
34
+ [![CI](https://github.com/trnsci/trnrand/actions/workflows/ci.yml/badge.svg)](https://github.com/trnsci/trnrand/actions/workflows/ci.yml)
35
+ [![PyPI](https://img.shields.io/pypi/v/trnrand)](https://pypi.org/project/trnrand/)
36
+ [![Python](https://img.shields.io/pypi/pyversions/trnrand)](https://pypi.org/project/trnrand/)
37
+ [![License](https://img.shields.io/github/license/trnsci/trnrand)](LICENSE)
38
+ [![Docs](https://img.shields.io/badge/docs-mkdocs-blue)](https://trnsci.github.io/trnrand/)
39
+
40
+ Random number generation for AWS Trainium via NKI.
41
+
42
+ Seeded pseudo-random distributions, quasi-random sequences for quasi-Monte Carlo, and on-device Philox RNG targeting the GpSimd engine.
43
+
44
+ Part of the trnsci scientific computing suite ([github.com/trnsci](https://github.com/trnsci)).
45
+
46
+ ## Install
47
+
48
+ ```bash
49
+ pip install trnrand
50
+
51
+ # With Neuron hardware support
52
+ pip install trnrand[neuron]
53
+ ```
54
+
55
+ ## Usage
56
+
57
+ ```python
58
+ import trnrand
59
+
60
+ # Seeded, reproducible generation
61
+ g = trnrand.Generator(seed=42)
62
+
63
+ # Standard distributions
64
+ x = trnrand.normal(1000, mean=0.0, std=1.0, generator=g)
65
+ u = trnrand.uniform(1000, low=-1.0, high=1.0, generator=g)
66
+ e = trnrand.exponential(1000, rate=2.0, generator=g)
67
+
68
+ # Quasi-random sequences (better convergence for MC integration)
69
+ sobol_pts = trnrand.sobol(1024, n_dims=5, seed=42)
70
+ halton_pts = trnrand.halton(1024, n_dims=3)
71
+ lhs_pts = trnrand.latin_hypercube(100, n_dims=4)
72
+
73
+ # Module-level seeding
74
+ trnrand.manual_seed(42)
75
+ x = trnrand.standard_normal(256)
76
+ ```
77
+
78
+ ## Operations
79
+
80
+ | Category | Function | Description |
81
+ |----------|----------|-------------|
82
+ | Distributions | `uniform` | U[low, high) |
83
+ | | `normal` | N(μ, σ²) |
84
+ | | `standard_normal` | N(0, 1) |
85
+ | | `exponential` | Exp(λ) |
86
+ | | `bernoulli` | Bernoulli(p) |
87
+ | | `randint` | Uniform integers [low, high) |
88
+ | | `randperm` | Random permutation |
89
+ | | `truncated_normal` | Bounded normal (rejection sampling) |
90
+ | Quasi-random | `sobol` | Sobol sequence (scrambled) |
91
+ | | `halton` | Halton sequence |
92
+ | | `latin_hypercube` | Latin Hypercube Sampling |
93
+
94
+ ## MC vs QMC Example
95
+
96
+ ```bash
97
+ python examples/mc_integration.py
98
+ ```
99
+
100
+ Compares pseudo-random vs Sobol quasi-random for estimating the volume of a 5-D hypersphere. QMC converges O(1/N) vs O(1/√N).
101
+
102
+ ## Status
103
+
104
+ - [x] Seeded Generator with state management
105
+ - [x] Standard distributions (uniform, normal, exponential, Bernoulli, etc.)
106
+ - [x] Sobol, Halton, Latin Hypercube sequences
107
+ - [x] MC vs QMC integration example
108
+ - [ ] NKI Philox kernel on GpSimd
109
+ - [ ] On-device Box-Muller (uniform → normal)
110
+ - [ ] Benchmarks vs cuRAND
111
+
112
+ ## Related Projects
113
+
114
+ | Project | What |
115
+ |---------|------|
116
+ | [trnfft](https://github.com/trnsci/trnfft) | FFT + complex ops |
117
+ | [trnblas](https://github.com/trnsci/trnblas) | BLAS operations |
118
+ | [trnsolver](https://github.com/trnsci/trnsolver) | Linear solvers |
119
+
120
+ ## License
121
+
122
+ Apache 2.0 — Copyright 2026 Scott Friedman
@@ -0,0 +1,11 @@
1
+ trnrand/__init__.py,sha256=aDhG3auvvzoTbf54WE7LrmQlmVnR--btUGO2DfG7uTk,1046
2
+ trnrand/distributions.py,sha256=5y94mDXGY_BiPpOXoWt-UIBLpZahddkg1PtYP0LE4eA,4072
3
+ trnrand/generator.py,sha256=ghxtHSrmQoECA-1lntO5UDiyD-Y28IKLVU37jYWq4lY,2012
4
+ trnrand/quasi.py,sha256=V80fkZBgEeMEUIo39tyKOwHeDPXKHNcwA3AZ9aD4YQY,3220
5
+ trnrand/nki/__init__.py,sha256=xjAwT_HOYC1_NgCwmeAMQEMFVOSKNxcLDq-5cjUQ39U,167
6
+ trnrand/nki/dispatch.py,sha256=6_YLNffct8cDrQNUCPKeYP1dmk4lLqQIlJ4x7y_Re-A,7941
7
+ trnrand-0.1.0.dist-info/licenses/LICENSE,sha256=hTt_varGm4HTIVm8GQ1pGR7jah4vW5IrddFIu94FPAE,11175
8
+ trnrand-0.1.0.dist-info/METADATA,sha256=hOfRucwRYjWM9jmY9VsQCt9RfJAvwBq9AnfggU0XrQ8,4089
9
+ trnrand-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
10
+ trnrand-0.1.0.dist-info/top_level.txt,sha256=M-7c9pzN73CKWdnPxKWLuzzLSGZmQ2XuI6NKGdVM37E,8
11
+ trnrand-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ Copyright 2026 Scott Friedman
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction,
12
+ and distribution as defined by Sections 1 through 9 of this document.
13
+
14
+ "Licensor" shall mean the copyright owner or entity authorized by
15
+ the copyright owner that is granting the License.
16
+
17
+ "Legal Entity" shall mean the union of the acting entity and all
18
+ other entities that control, are controlled by, or are under common
19
+ control with that entity. For the purposes of this definition,
20
+ "control" means (i) the power, direct or indirect, to cause the
21
+ direction or management of such entity, whether by contract or
22
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
23
+ outstanding shares, or (iii) beneficial ownership of such entity.
24
+
25
+ "You" (or "Your") shall mean an individual or Legal Entity
26
+ exercising permissions granted by this License.
27
+
28
+ "Source" form shall mean the preferred form for making modifications,
29
+ including but not limited to software source code, documentation
30
+ source, and configuration files.
31
+
32
+ "Object" form shall mean any form resulting from mechanical
33
+ transformation or translation of a Source form, including but
34
+ not limited to compiled object code, generated documentation,
35
+ and conversions to other media types.
36
+
37
+ "Work" shall mean the work of authorship, whether in Source or
38
+ Object form, made available under the License, as indicated by a
39
+ copyright notice that is included in or attached to the work
40
+ (an example is provided in the Appendix below).
41
+
42
+ "Derivative Works" shall mean any work, whether in Source or Object
43
+ form, that is based on (or derived from) the Work and for which the
44
+ editorial revisions, annotations, elaborations, or other modifications
45
+ represent, as a whole, an original work of authorship. For the purposes
46
+ of this License, Derivative Works shall not include works that remain
47
+ separable from, or merely link (or bind by name) to the interfaces of,
48
+ the Work and Derivative Works thereof.
49
+
50
+ "Contribution" shall mean any work of authorship, including
51
+ the original version of the Work and any modifications or additions
52
+ to that Work or Derivative Works thereof, that is intentionally
53
+ submitted to Licensor for inclusion in the Work by the copyright owner
54
+ or by an individual or Legal Entity authorized to submit on behalf of
55
+ the copyright owner. For the purposes of this definition, "submitted"
56
+ means any form of electronic, verbal, or written communication sent
57
+ to the Licensor or its representatives, including but not limited to
58
+ communication on electronic mailing lists, source code control systems,
59
+ and issue tracking systems that are managed by, or on behalf of, the
60
+ Licensor for the purpose of discussing and improving the Work, but
61
+ excluding communication that is conspicuously marked or otherwise
62
+ designated in writing by the copyright owner as "Not a Contribution."
63
+
64
+ "Contributor" shall mean Licensor and any individual or Legal Entity
65
+ on behalf of whom a Contribution has been received by Licensor and
66
+ subsequently incorporated within the Work.
67
+
68
+ 2. Grant of Copyright License. Subject to the terms and conditions of
69
+ this License, each Contributor hereby grants to You a perpetual,
70
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
71
+ copyright license to reproduce, prepare Derivative Works of,
72
+ publicly display, publicly perform, sublicense, and distribute the
73
+ Work and such Derivative Works in Source or Object form.
74
+
75
+ 3. Grant of Patent License. Subject to the terms and conditions of
76
+ this License, each Contributor hereby grants to You a perpetual,
77
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78
+ (except as stated in this section) patent license to make, have made,
79
+ use, offer to sell, sell, import, and otherwise transfer the Work,
80
+ where such license applies only to those patent claims licensable
81
+ by such Contributor that are necessarily infringed by their
82
+ Contribution(s) alone or by combination of their Contribution(s)
83
+ with the Work to which such Contribution(s) was submitted. If You
84
+ institute patent litigation against any entity (including a
85
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
86
+ or a Contribution incorporated within the Work constitutes direct
87
+ or contributory patent infringement, then any patent licenses
88
+ granted to You under this License for that Work shall terminate
89
+ as of the date such litigation is filed.
90
+
91
+ 4. Redistribution. You may reproduce and distribute copies of the
92
+ Work or Derivative Works thereof in any medium, with or without
93
+ modifications, and in Source or Object form, provided that You
94
+ meet the following conditions:
95
+
96
+ (a) You must give any other recipients of the Work or
97
+ Derivative Works a copy of this License; and
98
+
99
+ (b) You must cause any modified files to carry prominent notices
100
+ stating that You changed the files; and
101
+
102
+ (c) You must retain, in the Source form of any Derivative Works
103
+ that You distribute, all copyright, patent, trademark, and
104
+ attribution notices from the Source form of the Work,
105
+ excluding those notices that do not pertain to any part of
106
+ the Derivative Works; and
107
+
108
+ (d) If the Work includes a "NOTICE" text file as part of its
109
+ distribution, then any Derivative Works that You distribute must
110
+ include a readable copy of the attribution notices contained
111
+ within such NOTICE file, excluding those notices that do not
112
+ pertain to any part of the Derivative Works, in at least one
113
+ of the following places: within a NOTICE text file distributed
114
+ as part of the Derivative Works; within the Source form or
115
+ documentation, if provided along with the Derivative Works; or,
116
+ within a display generated by the Derivative Works, if and
117
+ wherever such third-party notices normally appear. The contents
118
+ of the NOTICE file are for informational purposes only and
119
+ do not modify the License. You may add Your own attribution
120
+ notices within Derivative Works that You distribute, alongside
121
+ or as an addendum to the NOTICE text from the Work, provided
122
+ that such additional attribution notices cannot be construed
123
+ as modifying the License.
124
+
125
+ You may add Your own copyright statement to Your modifications and
126
+ may provide additional or different license terms and conditions
127
+ for use, reproduction, or distribution of Your modifications, or
128
+ for any such Derivative Works as a whole, provided Your use,
129
+ reproduction, and distribution of the Work otherwise complies with
130
+ the conditions stated in this License.
131
+
132
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
133
+ any Contribution intentionally submitted for inclusion in the Work
134
+ by You to the Licensor shall be under the terms and conditions of
135
+ this License, without any additional terms or conditions.
136
+ Notwithstanding the above, nothing herein shall supersede or modify
137
+ the terms of any separate license agreement you may have executed
138
+ with Licensor regarding such Contributions.
139
+
140
+ 6. Trademarks. This License does not grant permission to use the trade
141
+ names, trademarks, service marks, or product names of the Licensor,
142
+ except as required for describing the origin of the Work and
143
+ reproducing the content of the NOTICE file.
144
+
145
+ 7. Disclaimer of Warranty. Unless required by applicable law or
146
+ agreed to in writing, Licensor provides the Work (and each
147
+ Contributor provides its Contributions) on an "AS IS" BASIS,
148
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
149
+ implied, including, without limitation, any warranties or conditions
150
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
151
+ PARTICULAR PURPOSE. You are solely responsible for determining the
152
+ appropriateness of using or redistributing the Work and assume any
153
+ risks associated with Your exercise of permissions under this License.
154
+
155
+ 8. Limitation of Liability. In no event and under no legal theory,
156
+ whether in tort (including negligence), contract, or otherwise,
157
+ unless required by applicable law (such as deliberate and grossly
158
+ negligent acts) or agreed to in writing, shall any Contributor be
159
+ liable to You for damages, including any direct, indirect, special,
160
+ incidental, or consequential damages of any character arising as a
161
+ result of this License or out of the use or inability to use the
162
+ Work (including but not limited to damages for loss of goodwill,
163
+ work stoppage, computer failure or malfunction, or any and all
164
+ other commercial damages or losses), even if such Contributor
165
+ has been advised of the possibility of such damages.
166
+
167
+ 9. Accepting Warranty or Additional Liability. While redistributing
168
+ the Work or Derivative Works thereof, You may accept support,
169
+ obligations, or other liability only on behalf of Yourself and on
170
+ Your sole responsibility, not on behalf of any other Contributor,
171
+ and only if You agree to indemnify, defend, and hold each Contributor
172
+ harmless for any liability incurred by, or claims asserted against,
173
+ such Contributor by reason of your accepting any such warranty or
174
+ additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Scott Friedman
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1 @@
1
+ trnrand