Skip to main content

trnrand

CI codecov Ruff PyPI Python License Docs

Random number generation for AWS Trainium via NKI.

Seeded pseudo-random distributions, quasi-random sequences for quasi-Monte Carlo, and on-device counter-based RNG (Threefry4x32-20, with a Philox 4x32-10 kernel alongside) on the GpSimd engine.

Part of the trnsci scientific computing suite (github.com/trnsci).

Current phase

trnrand follows the trnsci 5-phase roadmap. Active work is tracked in phase-labeled GitHub issues:

  • Phase 1 — correctness (done): Threefry, Box-Muller, Philox, Sobol and Halton NKI kernels are bit-exact against their CPU references on Trn2 (Neuron SDK 2.33, native TorchNeuron).
  • Phase 3 — perf (done): wide-tile bulk Threefry kernels (v0.8.0–v0.9.0), opt-in multi-core bulk draws with set_cores (v0.10.0), pinned host output (v0.11.0).
  • Phase 4 — multi-chip (done): counter-partitioned generators (partition_rank / partition_size); the counter reuse on P > 1 in 0.7.0–0.11.0 is fixed in v0.12.0.
  • Phase 5 — generation (open): trn2 PSUM sizing for larger batched tile generation.

(No Phase 2 for trnrand — the precision story is inherited where relevant.)

Suite-wide tracker: trnsci/trnsci#1.

Known issues in earlier releases

Silent wrong-result bugs fixed in the 2026-10-31 to 2026-11-02 releases. Details are in the CHANGELOG. "NKI" means set_backend("nki"), or "auto" on Neuron hardware.

Bug Affected versions Fixed in
Partitioned generators (P > 1) reused counters from the second draw on, so ranks returned duplicate values (key_mode="counter") or stopped concatenating to the single-chip stream (NKI) 0.7.0 – 0.11.0 0.12.0
sobol_nki past index 2^24 dropped high Gray-code bits and repeated points; it now raises 0.5.0 – 0.11.0 0.12.0
Generator.get_state() / set_state() did not restore the NKI stream 0.7.0 – 0.12.0 0.12.1
sobol / halton in float16 / bfloat16 returned 1.0, outside the documented range 0.1.0 – 0.12.1 0.13.0
exponential in float16 returned inf; bfloat16 was biased (PyTorch path) 0.1.0 – 0.12.1 0.13.0
latin_hypercube in float16 / bfloat16 put two points in one stratum 0.1.0 – 0.12.1 0.13.0
exponential_into() and GeneratorProgram.exponential() returned inf (NKI) 0.6.0 – 0.12.1 0.13.0
sobol(scramble=False, seed=s) returned shifted points (NKI) 0.5.0 – 0.12.1 0.13.0
gamma / chi_squared / beta / truncated_normal drew identical samples on every partition rank (NKI) 0.7.0 – 0.12.1 0.13.0
uniform in bfloat16 / float16 returned high, outside [low, high) (NKI) 0.5.0 – 0.12.1 0.13.0
advance_to(position()) did not resume the stream with the default key_mode="draw" (NKI); it now warns 0.7.0 – 0.12.1 0.13.0

Install

pip install trnrand

# Trn2/Trn3 with TorchNeuron (native PyTorch, Neuron SDK 2.33+)
pip install "trnrand[torchneuron]" --extra-index-url https://pip.repos.neuron.amazonaws.com

# Trn1 / PyTorch-XLA lineage
pip install "trnrand[neuron]" --extra-index-url https://pip.repos.neuron.amazonaws.com

Kernels dispatch on whichever Neuron PyTorch lineage is installed:

  • TorchNeuron (native) — Trn2/Trn3, Neuron SDK 2.33+, Python ≥ 3.12, torch 2.14, torch-neuronx 2.14.*. Each kernel is a PyTorch custom op (torch.ops.trnrand.*) on the neuron device; no torch_xla.
  • PyTorch/XLA — Trn1 (and any host on the torch-neuronx 2.9 lineage). Kernels dispatch through torch_xla, unchanged.

trnrand picks the native path when the native torch_neuronx and a neuron device are present, and the XLA path when torch_xla is installed; without nki it uses torch.Generator. Set TRNSCI_NKI_DISPATCH=native or xla (shared by all trnsci libraries) to force a path. With an editable install (pip install -e), set NKI_ENABLE_TRACE_CACHE=0: the NKI kernel cache only versions installed wheels and can serve stale kernels. See installation.

Known platform issue: NKI trace cache and kernel factories

import torch_neuronx turns on the NKI trace cache, and the cache key ignores constants captured in a kernel's closure: two @nki.jit kernels built by one factory, differing only in a captured value, share one trace, and the second silently returns the first's results (aws-neuron/aws-neuron-sdk#1454). trnrand's kernels do not rely on closure constants (or on module globals that can differ between processes): every value that specialises a kernel is a kernel argument, and tests/test_trace_cache_safety.py enforces this. If you write your own NKI kernels with a factory, set NKI_ENABLE_TRACE_CACHE=0 before importing torch_neuronx.

Usage

import trnrand

# Seeded, reproducible generation
g = trnrand.Generator(seed=42)

# Standard distributions
x = trnrand.normal(1000, mean=0.0, std=1.0, generator=g)
u = trnrand.uniform(1000, low=-1.0, high=1.0, generator=g)
e = trnrand.exponential(1000, rate=2.0, generator=g)

# Quasi-random sequences (better convergence for MC integration)
sobol_pts = trnrand.sobol(1024, n_dims=5, seed=42)
halton_pts = trnrand.halton(1024, n_dims=3)
lhs_pts = trnrand.latin_hypercube(100, n_dims=4)

# Module-level seeding
trnrand.manual_seed(42)
x = trnrand.standard_normal(256)

Operations

Category Function Description
Distributions uniform U[low, high)
normal N(μ, σ²)
standard_normal N(0, 1)
exponential Exp(λ)
bernoulli Bernoulli(p)
randint Uniform integers [low, high)
randperm Random permutation
truncated_normal Bounded normal (rejection sampling)
gamma, beta, chi_squared Gamma(k, θ), Beta(α, β), χ²(df)
poisson Poisson(λ)
normal_into, uniform_into, exponential_into In-place fills of a preallocated tensor
Quasi-random sobol Sobol sequence (scrambled)
halton Halton sequence
latin_hypercube Latin Hypercube Sampling

MC vs QMC Example

python examples/mc_integration.py

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).

Status

  • Seeded Generator with state management
  • Standard distributions (uniform, normal, exponential, Bernoulli, etc.)
  • Sobol, Halton, Latin Hypercube sequences
  • MC vs QMC integration example
  • NKI Threefry and Philox kernels on GpSimd (bit-exact on Trn2)
  • On-device Box-Muller (uniform → normal)
  • Counter-partitioned multi-chip generators and multi-core bulk draws (set_cores)
  • Benchmarks vs cuRAND
Project What
trnfft FFT + complex ops
trnblas BLAS operations
trnsolver Linear solvers
trnsparse Sparse formats + SpMM
trntensor Einsum + tensor decompositions

License

Apache 2.0 — Copyright 2026 Scott Friedman

Disclaimer

trnsci is an independent open-source project. It is not sponsored by, endorsed by, or affiliated with Amazon.com, Inc., Amazon Web Services, Inc., or Annapurna Labs Ltd.

"AWS", "Amazon", "Trainium", "Inferentia", "NeuronCore", "Neuron SDK", and related identifiers are trademarks of their respective owners and are used here solely for descriptive and interoperability purposes. Use does not imply endorsement, partnership, or any other relationship.

All work, opinions, analyses, benchmark results, architectural commentary, and editorial judgments in this repository and on trnsci.dev are those of the project's contributors. They do not represent the views, positions, or commitments of Amazon, AWS, or Annapurna Labs.

Feedback directed at the Neuron SDK or Trainium hardware is good-faith ecosystem commentary from independent users. It is not privileged information, is not pre-reviewed by AWS, and should not be read as authoritative about product roadmap, behavior, or quality.

For official AWS guidance, see aws-neuron documentation and the AWS Trainium product page.

Metadata

Release files for trnrand 0.14.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for trnrand 0.14.0
File Size Uploaded Provenance Actions
trnrand-0.14.0.tar.gz 856.2 kB With provenance Details for trnrand-0.14.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for trnrand 0.14.0
File Interpreter ABI Platform Actions
trnrand-0.14.0-py3-none-any.whl Python 3 none any Details for trnrand-0.14.0-py3-none-any.whl

Total release size: 940.2 kB

Release files / trnrand-0.14.0.tar.gz

Download URL trnrand-0.14.0.tar.gz
Size 856.2 kB
Tags Source
SHA-256 checksum
How to use checksums
e3bb47f338a75c6cf65475bcd35cc33822cdfafe86f5be114880aa9bf69144fd
BLAKE2b-256 checksum
How to use checksums
faa318779e3b4c3d33a1ce6a93e83406652d1d1a7ce02b899de9be3fc302becc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 3, 2026.

Transparency log

Release files / trnrand-0.14.0-py3-none-any.whl

Download URL trnrand-0.14.0-py3-none-any.whl
Size 84.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
000020bec091855bb80b8968bca9d5881df9f33b9dce0ede95600db639e1eb00
BLAKE2b-256 checksum
How to use checksums
12d7b99de521f918a2ab226a86f59b2ec283a01c293652a583f63b01fd2482ed
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 3, 2026.

Transparency log

Security for trnrand 0.14.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

All 2 files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for trnrand-0.14.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 3, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page