← Back to Pull requests

Refactor random generators and add MT19937 with NumPy-compatible jump #3413

Closed
KimYannn closed this pull request without merging on Oct 09, 2026 09:00 UTC
View on GitHub
KimYannn KimYannn commented on Sep 22, 2026 01:23 UTC
Author

Random generation currently combines RNG backends, buffering, and distributions in random-inl.h. This separates the reusable hwy::Generator and uniform distributions from the Xoshiro and AES-CTR backends, so additional engines can use the same sampling and fill interfaces.

  • Keep standalone composition in hwy/generator.h and provide hwy/generator-inl.h for native SIMD returns with per-target attributes. Move distributions to hwy/contrib/distributions and engines/buffering to dedicated random headers.

  • Remove the legacy random-inl.h wrapper API and Bazel :random target; migrate existing callers and update CMake, Bazel, and Meson registration. This is an include/API breaking change.

  • Add scalar MT19937 with std::mt19937 single-integer seeding, shared u32/u64 consumption, and Jump/Jumped matching native NumPy 2.5.3 state and cursor behavior for the same starting state. Keep state refill out of the hot draw path to allow inlining into bulk generation.
  • Validation:

  • 123 related CTests passed; MT19937 ASan/UBSan and Rosetta x86_64 tests each passed 13/13. Distribution/target-Generator tests passed 24/24 natively, with ASan/UBSan, and under Rosetta x86_64.

  • The complete distribution test compiles for SVE, SVE2, SVE_256, and SVE2_128 with Clang 23 at both -O0 and -O2. The previous version reproduces the CI's 16 vector-return target errors under the same options. SVE runtime testing is left to CI.

  • Direct comparison with native NumPy .jumped(): 889 scenarios and 38,542,776 matching outputs, covering cursor boundaries, repeated jumps, mixed u32/u64 consumption, and independent copies. Initial states were aligned using RandomState(seed); this does not claim NumPy SeedSequence initialization compatibility.

  • C++11 consumers compiled and ran using installed headers without linking Highway. MT19937 generation assembly was verified against the optimized pre-jump implementation.

  • Build and installation were validated with CMake; Bazel and Meson registration was checked statically.
  • Diff: 2927 lines (+2272 / -655) across 33 files Reviewer: jan-wassenberg Review duration: 24936m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.77) × (1 − Review Confidence (0.72)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.77 · 2927 lines diff across 33 files
    0.77
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.56 · 5 substantive comment(s)
    0.56
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    72%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Mass File Touch mass_file_touch
    0.080
    Ai Authored ai_authored
    0.050
    Real PR Conversation Timeline
    7 items
    jan-wassenberg jan-wassenberg commented on code on Sep 22, 2026 11:24 UTC
    Code Review
    hwy/contrib/distributions/uniform.h:1
    @@ -0,0 +1,59 @@
    +// Copyright 2026 Google LLC
    +// SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
    +//
    +// See the LICENSE file in the project root for the full license text.
    +
    +#ifndef HIGHWAY_HWY_CONTRIB_DISTRIBUTIONS_UNIFORM_H_
    +#define HIGHWAY_HWY_CONTRIB_DISTRIBUTIONS_UNIFORM_H_
    +
    +#include <stddef.h>
    +#include <stdint.h>
    +
    +#include "hwy/base.h"
    +
    +namespace hwy {
    +
    +// Uniform double samples in [0, 1), using the high 53 bits of a full-range u64
    +// bit generator. No particular PRNG, seed representation or state is required.
    +struct Uniform {
    +  static HWY_CXX14_CONSTEXPR double FromBits(uint64_t bits) noexcept {
    +    return static_cast<double>(bits >> 11) *
    +           0.00000000000000011102230246251565404236316680908203125;
    +  }
    +
    +  template <class BitGenerator>
    +  double operator()(BitGenerator& bits) const {
    +    return FromBits(bits());
    +  }
    +
    +  template <class BitGenerator>
    +  void Fill(BitGenerator& bits, double* out, size_t count) const {
    +    for (size_t i = 0; i < count; ++i) out[i] = (*this)(bits);
    +  }
    +};
    +
    +// Uniform float samples on a 23-bit grid in [-1, 1). Consumes one full-range
    +// u64 per result, using its low 23 bits as the mantissa.
    +struct NormalizedUniform {
    +  static float FromBits(uint64_t bits) noexcept {
    +    const uint32_t exponent = hwy::BitCastScalar<uint32_t>(1.0f);

    If we use 2.0f, then the range is 2-4 and we can subtract 3 to get -1..1, in 2 fewer instructions.
    Also, this adapter is scalar-only - seems vectorizing would make sense.

    jan-wassenberg jan-wassenberg commented on code on Sep 22, 2026 11:26 UTC
    Code Review
    hwy/contrib/distributions/uniform-inl.h:1
    @@ -0,0 +1,94 @@
    +// Copyright 2026 Google LLC
    +// SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
    +//
    +// See the LICENSE file in the project root for the full license text.
    +
    +#if defined(HIGHWAY_HWY_CONTRIB_DISTRIBUTIONS_UNIFORM_INL_H_) == \
    +    defined(HWY_TARGET_TOGGLE)
    +#ifdef HIGHWAY_HWY_CONTRIB_DISTRIBUTIONS_UNIFORM_INL_H_
    +#undef HIGHWAY_HWY_CONTRIB_DISTRIBUTIONS_UNIFORM_INL_H_
    +#else
    +#define HIGHWAY_HWY_CONTRIB_DISTRIBUTIONS_UNIFORM_INL_H_
    +#endif
    +
    +#include <stddef.h>
    +#include <stdint.h>
    +
    +#include "hwy/contrib/distributions/uniform.h"
    +#include "hwy/highway.h"
    +
    +HWY_BEFORE_NAMESPACE();
    +namespace hwy {
    +namespace HWY_NAMESPACE {
    +
    +#if HWY_HAVE_FLOAT64
    +namespace distribution_detail {
    +
    +template <class D>
    +HWY_INLINE Vec<Rebind<double, D>> UniformFromBits(D /*d*/, Vec<D> bits) {
    +  const Rebind<double, D> df;
    +  return Mul(ConvertTo(df, ShiftRight<11>(bits)),
    +             Set(df, hwy::Uniform::FromBits(uint64_t{1} << 11)));
    +}
    +
    +struct UniformSink {
    +  double* out;
    +
    +  template <class D>
    +  HWY_INLINE void operator()(D d, Vec<D> bits, size_t offset,
    +                             size_t valid_lanes) const {
    +    const Rebind<double, D> df;
    +    const auto samples = UniformFromBits(d, bits);
    +    if (valid_lanes == Lanes(df)) {
    +      StoreU(samples, df, out + offset);
    +    } else {
    +      StoreN(samples, df, out + offset, valid_lanes);
    +    }
    +  }
    +};
    +
    +}  // namespace distribution_detail
    +
    +// The same distribution works with scalar u64 and native SIMD backends.
    +// GenerateBlocks is an optional optimization; scalar backends need only ().
    +struct Uniform {
    +  static double FromBits(uint64_t bits) noexcept {
    +    return hwy::Uniform::FromBits(bits);
    +  }
    +
    +  static HWY_INLINE Vec<ScalableTag<double>> FromBits(

    Seems undesirable to hardcode the type. We can support any vector type, and use DFromV<V> d; then RebindToUnsigned<decltype(d)> to get the tag to pass to FromBits.

    jan-wassenberg jan-wassenberg commented on code on Sep 22, 2026 11:27 UTC
    Code Review
    hwy/contrib/random/xoshiro-inl.h:1
    @@ -0,0 +1,255 @@
    +// Copyright 2024 Google LLC
    +// SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
    +//
    +// See the LICENSE file in the project root for the full license text.
    +
    +// Vector port by Marco Barbone (m.barbone19@imperial.ac.uk) of the xoshiro256++
    +// generator. The algorithm was originally designed in 2019 by David Blackman
    +// and Sebastiano Vigna (vigna@acm.org), with the reference implementation
    +// available at https://prng.di.unimi.it/. Credit for the algorithm itself
    +// belongs to the original authors.
    +
    +#if defined(HIGHWAY_HWY_CONTRIB_RANDOM_XOSHIRO_H_) == \
    +    defined(HWY_TARGET_TOGGLE)  // NOLINT
    +#ifdef HIGHWAY_HWY_CONTRIB_RANDOM_XOSHIRO_H_
    +#undef HIGHWAY_HWY_CONTRIB_RANDOM_XOSHIRO_H_
    +#else
    +#define HIGHWAY_HWY_CONTRIB_RANDOM_XOSHIRO_H_
    +#endif
    +
    +#include <stddef.h>
    +
    +#include <array>
    +#include <cstdint>
    +
    +#include "hwy/aligned_allocator.h"
    +#include "hwy/highway.h"
    +
    +HWY_BEFORE_NAMESPACE();
    +namespace hwy {
    +namespace HWY_NAMESPACE {
    +namespace random_internal {
    +
    +constexpr std::uint64_t kJump[] = {0x180ec6d33cfd0aba, 0xd5a61266f0c9392c,
    +                                   0xa9582618e03fc9aa, 0x39abdc4529b1661c};
    +
    +constexpr std::uint64_t kLongJump[] = {0x76e15d3efefdcbbf, 0xc5004e441c522fb3,
    +                                       0x77710069854ee241, 0x39109bb02acbe635};
    +
    +class SplitMix64 {
    + public:
    +  constexpr explicit SplitMix64(const std::uint64_t state) noexcept
    +      : state_(state) {}
    +
    +  HWY_CXX14_CONSTEXPR std::uint64_t operator()() {
    +    std::uint64_t z = (state_ += 0x9e3779b97f4a7c15);
    +    z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9;
    +    z = (z ^ (z >> 27)) * 0x94d049bb133111eb;
    +    return z ^ (z >> 31);
    +  }
    +
    + private:
    +  std::uint64_t state_;
    +};
    +
    +class ScalarXoshiro {
    + public:
    +  HWY_CXX14_CONSTEXPR explicit ScalarXoshiro(const std::uint64_t seed) noexcept
    +      : state_{} {
    +    SplitMix64 splitMix64{seed};
    +    for (auto& element : state_) {
    +      element = splitMix64();
    +    }
    +  }
    +
    +  HWY_CXX14_CONSTEXPR explicit ScalarXoshiro(
    +      const std::uint64_t seed, const std::uint64_t thread_id) noexcept
    +      : ScalarXoshiro(seed) {
    +    for (auto i = UINT64_C(0); i < thread_id; ++i) {
    +      Jump();
    +    }
    +  }
    +
    +  HWY_CXX14_CONSTEXPR std::uint64_t operator()() noexcept { return Next(); }
    +
    +  HWY_CXX14_CONSTEXPR std::array<std::uint64_t, 4> GetState() const {
    +    return {state_[0], state_[1], state_[2], state_[3]};
    +  }
    +
    +  HWY_CXX17_CONSTEXPR void SetState(
    +      std::array<std::uint64_t, 4> state) noexcept {
    +    state_[0] = state[0];
    +    state_[1] = state[1];
    +    state_[2] = state[2];
    +    state_[3] = state[3];
    +  }
    +
    +  static constexpr std::uint64_t StateSize() noexcept { return 4; }
    +
    +  // Equivalent to 2^128 calls to Next(), yielding non-overlapping subsequences.
    +  HWY_CXX14_CONSTEXPR void Jump() noexcept { Jump(kJump); }
    +
    +  // Equivalent to 2^192 calls to Next(). Each resulting stream can be split
    +  // further via Jump() for parallel distributed computations.
    +  HWY_CXX14_CONSTEXPR void LongJump() noexcept { Jump(kLongJump); }
    +
    + private:
    +  std::uint64_t state_[4];
    +
    +  static constexpr std::uint64_t Rotl(const std::uint64_t x, int k) noexcept {
    +    return (x << k) | (x >> (64 - k));
    +  }
    +
    +  HWY_CXX14_CONSTEXPR std::uint64_t Next() noexcept {
    +    const std::uint64_t result = Rotl(state_[0] + state_[3], 23) + state_[0];
    +    const std::uint64_t t = state_[1] << 17;
    +
    +    state_[2] ^= state_[0];
    +    state_[3] ^= state_[1];
    +    state_[1] ^= state_[2];
    +    state_[0] ^= state_[3];
    +    state_[2] ^= t;
    +    state_[3] = Rotl(state_[3], 45);
    +
    +    return result;
    +  }
    +
    +  HWY_CXX14_CONSTEXPR void Jump(const std::uint64_t (&jumpArray)[4]) noexcept {
    +    std::uint64_t s0 = 0;
    +    std::uint64_t s1 = 0;
    +    std::uint64_t s2 = 0;
    +    std::uint64_t s3 = 0;
    +
    +    for (const std::uint64_t i : jumpArray) {
    +      for (std::uint_fast8_t b = 0; b < 64; b++) {
    +        if (i & std::uint64_t{1UL} << b) {
    +          s0 ^= state_[0];
    +          s1 ^= state_[1];
    +          s2 ^= state_[2];
    +          s3 ^= state_[3];
    +        }
    +        Next();
    +      }
    +    }
    +
    +    state_[0] = s0;
    +    state_[1] = s1;
    +    state_[2] = s2;
    +    state_[3] = s3;
    +  }
    +};
    +
    +}  // namespace random_internal
    +
    +// Parallel xoshiro256++ streams, one per SIMD lane. Thread numbers select
    +// LongJump-separated streams; adjacent lanes are separated by Jump().
    +class XoshiroBitGenerator {
    + private:
    +  using VU64 = Vec<ScalableTag<std::uint64_t>>;
    +  using StateType = AlignedNDArray<std::uint64_t, 2>;
    +
    + public:
    +  explicit XoshiroBitGenerator(const std::uint64_t seed,
    +                               const std::uint64_t threadNumber = 0)
    +      : state_{{random_internal::ScalarXoshiro::StateSize(),
    +                Lanes(ScalableTag<std::uint64_t>{})}},
    +        streams_(state_.shape().back()) {
    +    random_internal::ScalarXoshiro xoshiro{seed};
    +    for (std::uint64_t i = 0; i < threadNumber; ++i) {
    +      xoshiro.LongJump();
    +    }
    +
    +    for (size_t i = 0; i < streams_; ++i) {
    +      const auto state = xoshiro.GetState();
    +      for (size_t j = 0; j < random_internal::ScalarXoshiro::StateSize(); ++j) {
    +        state_[{j}][i] = state[j];
    +      }
    +      xoshiro.Jump();
    +    }
    +  }
    +
    +  // Native vectors must be consumed in the same target's scope.
    +  VU64 operator()() noexcept {
    +    const ScalableTag<std::uint64_t> tag;
    +    auto s0 = Load(tag, state_[{0}].data());
    +    auto s1 = Load(tag, state_[{1}].data());
    +    auto s2 = Load(tag, state_[{2}].data());
    +    auto s3 = Load(tag, state_[{3}].data());
    +    const auto result = Update(s0, s1, s2, s3);
    +    Store(s0, tag, state_[{0}].data());
    +    Store(s1, tag, state_[{1}].data());
    +    Store(s2, tag, state_[{2}].data());
    +    Store(s3, tag, state_[{3}].data());
    +    return result;
    +  }
    +
    +  // Calls consume(tag, bits, offset, valid_lanes) for each output vector,
    +  // keeping state in registers for the entire batch. A partial final vector
    +  // advances every lane; unused lanes are discarded.
    +  template <class Consumer>
    +  HWY_INLINE void GenerateBlocks(size_t count, Consumer&& consume) {
    +    const ScalableTag<std::uint64_t> tag;
    +    auto s0 = Load(tag, state_[{0}].data());
    +    auto s1 = Load(tag, state_[{1}].data());
    +    auto s2 = Load(tag, state_[{2}].data());
    +    auto s3 = Load(tag, state_[{3}].data());
    +    const size_t lanes = Lanes(tag);
    +    size_t i = 0;
    +    for (; count - i >= lanes; i += lanes) {
    +      consume(tag, Update(s0, s1, s2, s3), i, lanes);
    +    }
    +    if (i < count) {
    +      consume(tag, Update(s0, s1, s2, s3), i, count - i);
    +    }
    +    Store(s0, tag, state_[{0}].data());
    +    Store(s1, tag, state_[{1}].data());
    +    Store(s2, tag, state_[{2}].data());
    +    Store(s3, tag, state_[{3}].data());
    +  }
    +
    +  void FillBits(std::uint64_t* out, size_t count) {
    +    GenerateBlocks(count, StoreBits{out});
    +  }
    +
    +  std::uint64_t StateSize() const noexcept {
    +    return streams_ * random_internal::ScalarXoshiro::StateSize();
    +  }
    +
    +  const StateType& GetState() const { return state_; }
    +
    + private:
    +  struct StoreBits {
    +    std::uint64_t* out;
    +
    +    HWY_INLINE void operator()(ScalableTag<std::uint64_t> tag, VU64 bits,
    +                               size_t offset, size_t valid_lanes) const {
    +      if (valid_lanes == Lanes(tag)) {
    +        StoreU(bits, tag, out + offset);
    +      } else {
    +        StoreN(bits, tag, out + offset, valid_lanes);
    +      }
    +    }
    +  };
    +
    +  StateType state_;
    +  const std::uint64_t streams_;

    Makes the class noncopyable, not sure this const is worthwhile.

    jan-wassenberg jan-wassenberg commented on code on Sep 22, 2026 11:28 UTC
    Code Review
    hwy/contrib/random/cached.h:1
    @@ -0,0 +1,65 @@
    +// Copyright 2026 Google LLC
    +// SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
    +//
    +// See the LICENSE file in the project root for the full license text.
    +
    +#ifndef HIGHWAY_HWY_CONTRIB_RANDOM_CACHED_H_
    +#define HIGHWAY_HWY_CONTRIB_RANDOM_CACHED_H_
    +
    +#include <stddef.h>
    +#include <stdint.h>
    +
    +#include <array>
    +#include <limits>
    +#include <utility>
    +
    +#include "hwy/aligned_allocator.h"
    +#include "hwy/base.h"
    +
    +namespace hwy {
    +
    +// Adapts any backend with FillBits(uint64_t*, size_t) to a scalar URBG. Refills
    +// preserve the backend's batch consumption policy, including discarded lanes.
    +// Copying this adapter (when supported by BitGenerator) also copies its cache
    +// and current position. It does not expose a backend-only state snapshot.
    +template <class BitGenerator, size_t kSize = 1024>
    +class BufferedBitGenerator {
    + public:
    +  using result_type = uint64_t;
    +
    +  static constexpr result_type(min)() {
    +    return (std::numeric_limits<result_type>::min)();
    +  }
    +  static constexpr result_type(max)() {
    +    return (std::numeric_limits<result_type>::max)();
    +  }
    +
    +  explicit BufferedBitGenerator(BitGenerator bit_generator)
    +      : bit_generator_(std::move(bit_generator)), index_(0) {
    +    bit_generator_.FillBits(cache_.data(), kSize);
    +  }
    +
    +  result_type operator()() {
    +    if (HWY_UNLIKELY(index_ == kSize)) {
    +      bit_generator_.FillBits(cache_.data(), kSize);
    +      index_ = 0;
    +    }
    +    return cache_[index_++];
    +  }
    +
    +  void FillBits(uint64_t* out, size_t count) {
    +    for (size_t i = 0; i < count; ++i) out[i] = (*this)();

    Could use CopyBytes instead of a loop.

    jan-wassenberg jan-wassenberg commented on code on Sep 22, 2026 11:28 UTC
    Code Review
    hwy/contrib/random/cached.h:1
    @@ -0,0 +1,65 @@
    +// Copyright 2026 Google LLC
    +// SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
    +//
    +// See the LICENSE file in the project root for the full license text.
    +
    +#ifndef HIGHWAY_HWY_CONTRIB_RANDOM_CACHED_H_
    +#define HIGHWAY_HWY_CONTRIB_RANDOM_CACHED_H_
    +
    +#include <stddef.h>
    +#include <stdint.h>
    +
    +#include <array>
    +#include <limits>
    +#include <utility>
    +
    +#include "hwy/aligned_allocator.h"
    +#include "hwy/base.h"
    +
    +namespace hwy {
    +
    +// Adapts any backend with FillBits(uint64_t*, size_t) to a scalar URBG. Refills
    +// preserve the backend's batch consumption policy, including discarded lanes.
    +// Copying this adapter (when supported by BitGenerator) also copies its cache
    +// and current position. It does not expose a backend-only state snapshot.
    +template <class BitGenerator, size_t kSize = 1024>
    +class BufferedBitGenerator {
    + public:
    +  using result_type = uint64_t;
    +
    +  static constexpr result_type(min)() {
    +    return (std::numeric_limits<result_type>::min)();
    +  }
    +  static constexpr result_type(max)() {
    +    return (std::numeric_limits<result_type>::max)();
    +  }
    +
    +  explicit BufferedBitGenerator(BitGenerator bit_generator)
    +      : bit_generator_(std::move(bit_generator)), index_(0) {
    +    bit_generator_.FillBits(cache_.data(), kSize);
    +  }
    +
    +  result_type operator()() {
    +    if (HWY_UNLIKELY(index_ == kSize)) {
    +      bit_generator_.FillBits(cache_.data(), kSize);
    +      index_ = 0;
    +    }
    +    return cache_[index_++];
    +  }
    +
    +  void FillBits(uint64_t* out, size_t count) {
    +    for (size_t i = 0; i < count; ++i) out[i] = (*this)();
    +  }
    +
    + private:
    +  static_assert(kSize != 0 && (kSize & (kSize - 1)) == 0,

    Seems unnecessary, we're not using wraparound, right?

    jan-wassenberg jan-wassenberg requested changes on Sep 22, 2026 11:29 UTC
    Changes Requested Reviewer

    Thanks, I agree it makes sense to split AES and Xorshiro.
    This is a large change, better to discuss the design of such things first.

    As-is, this breaks a lot of (internal) dependencies, which is a non-starter. We could keep the existing header and build target, it can include the new headers, plus aliases.

    It seems dubious to add Generator to core Highway - that should reside in contrib/, and I'm not seeing a lot of value added. How about we remove it?

    Also, MT19937 is scalar and seems like a poor fit for Highway. It also has a large working set and is not a generator I'd encourage using. How about you keep the MT19937 (if you really can't/don't want to replace it with AES) in your project's source?

    distributions/ currently seems unnecessary - or do we intend to extend it? If not, probably better to stay in the same directly.

    BufferedBitGenerator: should we have lazy init in case it's unused?

    Assignees
    KimYannn KimYannn
    Labels
    risk: low confidence: 72.2% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 76.5% (HIGH) · Higher = larger blast radius
    76.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 72.2% · Lower = rushed or shallow review
    72.2%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 21.3% · Safe to merge
    21.3%
    Repository