"""Reimplementation of torch.randn(..., generator=torch.Generator('cpu').manual_seed(seed)) for float32. mt19937 (32-bit outputs) -> uniform floats u = (r & 0xFFFFFF) / 2^24 for every element, then Box-Muller over blocks of 16 (first 8 values pair with the next 8); if the size is not a multiple of 16 the last 16 values are redrawn and transformed again (ATen normal_fill). """ import numpy as np import torch class MT19937: def __init__(self, seed): self.mt = [0] * 624 self.mt[0] = seed & 0xFFFFFFFF for i in range(1, 624): self.mt[i] = (1812433253 * (self.mt[i - 1] ^ (self.mt[i - 1] >> 30)) + i) & 0xFFFFFFFF self.idx = 624 def next(self): if self.idx >= 624: mt = self.mt for i in range(624): y = (mt[i] & 0x80000000) | (mt[(i + 1) % 624] & 0x7FFFFFFF) mt[i] = mt[(i + 397) % 624] ^ (y >> 1) ^ (0x9908B0DF if y & 1 else 0) self.idx = 0 y = self.mt[self.idx]; self.idx += 1 y ^= y >> 11; y ^= (y << 7) & 0x9D2C5680; y ^= (y << 15) & 0xEFC60000; y ^= y >> 18 return y & 0xFFFFFFFF def randn(n, seed): g = MT19937(seed) u = lambda: np.float32((g.next() & 0xFFFFFF) / 16777216.0) d = np.array([u() for _ in range(n)], dtype=np.float32) def fill16(o): a, b = d[o:o + 8].copy(), d[o + 8:o + 16].copy() r = np.sqrt(np.float32(-2.0) * np.log(np.float32(1.0) - a)).astype(np.float32) th = (np.float32(2.0 * np.pi) * b).astype(np.float32) d[o:o + 8] = r * np.cos(th); d[o + 8:o + 16] = r * np.sin(th) for o in range(0, n - 15, 16): fill16(o) if n % 16: o = n - 16 d[o:] = [u() for _ in range(16)] fill16(o) return d if __name__ == "__main__": for shape, seed in [((1, 96, 8, 8), 11), ((1, 96, 32, 32), 7), ((1, 96, 3, 5), 1), ((1, 96, 64, 114), 4242)]: t = torch.randn(shape, generator=torch.Generator("cpu").manual_seed(seed), dtype=torch.float32).numpy().ravel() m = randn(t.size, seed) print(shape, seed, "max abs diff", float(np.abs(m - t).max()), "exact-equal fraction", float((m == t).mean()))